ERC2771Forwarder.test.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. const ethSigUtil = require('eth-sig-util');
  2. const Wallet = require('ethereumjs-wallet').default;
  3. const { getDomain, domainType } = require('../helpers/eip712');
  4. const { expectRevertCustomError } = require('../helpers/customError');
  5. const { constants, expectRevert, expectEvent, time } = require('@openzeppelin/test-helpers');
  6. const { expect } = require('chai');
  7. const ERC2771Forwarder = artifacts.require('ERC2771Forwarder');
  8. const CallReceiverMockTrustingForwarder = artifacts.require('CallReceiverMockTrustingForwarder');
  9. contract('ERC2771Forwarder', function (accounts) {
  10. const [, refundReceiver, another] = accounts;
  11. const tamperedValues = {
  12. from: another,
  13. value: web3.utils.toWei('0.5'),
  14. data: '0x1742',
  15. };
  16. beforeEach(async function () {
  17. this.forwarder = await ERC2771Forwarder.new('ERC2771Forwarder');
  18. this.domain = await getDomain(this.forwarder);
  19. this.types = {
  20. EIP712Domain: domainType(this.domain),
  21. ForwardRequest: [
  22. { name: 'from', type: 'address' },
  23. { name: 'to', type: 'address' },
  24. { name: 'value', type: 'uint256' },
  25. { name: 'gas', type: 'uint256' },
  26. { name: 'nonce', type: 'uint256' },
  27. { name: 'deadline', type: 'uint48' },
  28. { name: 'data', type: 'bytes' },
  29. ],
  30. };
  31. this.alice = Wallet.generate();
  32. this.alice.address = web3.utils.toChecksumAddress(this.alice.getAddressString());
  33. this.timestamp = await time.latest();
  34. this.receiver = await CallReceiverMockTrustingForwarder.new(this.forwarder.address);
  35. this.request = {
  36. from: this.alice.address,
  37. to: this.receiver.address,
  38. value: '0',
  39. gas: '100000',
  40. data: this.receiver.contract.methods.mockFunction().encodeABI(),
  41. deadline: this.timestamp.toNumber() + 60, // 1 minute
  42. };
  43. this.requestData = {
  44. ...this.request,
  45. nonce: (await this.forwarder.nonces(this.alice.address)).toString(),
  46. };
  47. this.forgeData = request => ({
  48. types: this.types,
  49. domain: this.domain,
  50. primaryType: 'ForwardRequest',
  51. message: { ...this.requestData, ...request },
  52. });
  53. this.sign = (privateKey, request) =>
  54. ethSigUtil.signTypedMessage(privateKey, {
  55. data: this.forgeData(request),
  56. });
  57. this.estimateRequest = request =>
  58. web3.eth.estimateGas({
  59. from: this.forwarder.address,
  60. to: request.to,
  61. data: web3.utils.encodePacked({ value: request.data, type: 'bytes' }, { value: request.from, type: 'address' }),
  62. value: request.value,
  63. gas: request.gas,
  64. });
  65. this.requestData.signature = this.sign(this.alice.getPrivateKey());
  66. });
  67. context('verify', function () {
  68. context('with valid signature', function () {
  69. it('returns true without altering the nonce', async function () {
  70. expect(await this.forwarder.nonces(this.requestData.from)).to.be.bignumber.equal(
  71. web3.utils.toBN(this.requestData.nonce),
  72. );
  73. expect(await this.forwarder.verify(this.requestData)).to.be.equal(true);
  74. expect(await this.forwarder.nonces(this.requestData.from)).to.be.bignumber.equal(
  75. web3.utils.toBN(this.requestData.nonce),
  76. );
  77. });
  78. });
  79. context('with tampered values', function () {
  80. for (const [key, value] of Object.entries(tamperedValues)) {
  81. it(`returns false with tampered ${key}`, async function () {
  82. expect(await this.forwarder.verify(this.forgeData({ [key]: value }).message)).to.be.equal(false);
  83. });
  84. }
  85. it('returns false with an untrustful to', async function () {
  86. expect(await this.forwarder.verify(this.forgeData({ to: another }).message)).to.be.equal(false);
  87. });
  88. it('returns false with tampered signature', async function () {
  89. const tamperedsign = web3.utils.hexToBytes(this.requestData.signature);
  90. tamperedsign[42] ^= 0xff;
  91. this.requestData.signature = web3.utils.bytesToHex(tamperedsign);
  92. expect(await this.forwarder.verify(this.requestData)).to.be.equal(false);
  93. });
  94. it('returns false with valid signature for non-current nonce', async function () {
  95. const req = {
  96. ...this.requestData,
  97. nonce: this.requestData.nonce + 1,
  98. };
  99. req.signature = this.sign(this.alice.getPrivateKey(), req);
  100. expect(await this.forwarder.verify(req)).to.be.equal(false);
  101. });
  102. it('returns false with valid signature for expired deadline', async function () {
  103. const req = {
  104. ...this.requestData,
  105. deadline: this.timestamp - 1,
  106. };
  107. req.signature = this.sign(this.alice.getPrivateKey(), req);
  108. expect(await this.forwarder.verify(req)).to.be.equal(false);
  109. });
  110. });
  111. });
  112. context('execute', function () {
  113. context('with valid requests', function () {
  114. beforeEach(async function () {
  115. expect(await this.forwarder.nonces(this.requestData.from)).to.be.bignumber.equal(
  116. web3.utils.toBN(this.requestData.nonce),
  117. );
  118. });
  119. it('emits an event and consumes nonce for a successful request', async function () {
  120. const receipt = await this.forwarder.execute(this.requestData);
  121. await expectEvent.inTransaction(receipt.tx, this.receiver, 'MockFunctionCalled');
  122. await expectEvent.inTransaction(receipt.tx, this.forwarder, 'ExecutedForwardRequest', {
  123. signer: this.requestData.from,
  124. nonce: web3.utils.toBN(this.requestData.nonce),
  125. success: true,
  126. });
  127. expect(await this.forwarder.nonces(this.requestData.from)).to.be.bignumber.equal(
  128. web3.utils.toBN(this.requestData.nonce + 1),
  129. );
  130. });
  131. it('reverts with an unsuccessful request', async function () {
  132. const req = {
  133. ...this.requestData,
  134. data: this.receiver.contract.methods.mockFunctionRevertsNoReason().encodeABI(),
  135. };
  136. req.signature = this.sign(this.alice.getPrivateKey(), req);
  137. await expectRevertCustomError(this.forwarder.execute(req), 'FailedInnerCall', []);
  138. });
  139. });
  140. context('with tampered request', function () {
  141. for (const [key, value] of Object.entries(tamperedValues)) {
  142. it(`reverts with tampered ${key}`, async function () {
  143. const data = this.forgeData({ [key]: value });
  144. await expectRevertCustomError(
  145. this.forwarder.execute(data.message, {
  146. value: key == 'value' ? value : 0, // To avoid MismatchedValue error
  147. }),
  148. 'ERC2771ForwarderInvalidSigner',
  149. [ethSigUtil.recoverTypedSignature({ data, sig: this.requestData.signature }), data.message.from],
  150. );
  151. });
  152. }
  153. it('reverts with an untrustful to', async function () {
  154. const data = this.forgeData({ to: another });
  155. await expectRevertCustomError(this.forwarder.execute(data.message), 'ERC2771UntrustfulTarget', [
  156. data.message.to,
  157. this.forwarder.address,
  158. ]);
  159. });
  160. it('reverts with tampered signature', async function () {
  161. const tamperedSig = web3.utils.hexToBytes(this.requestData.signature);
  162. tamperedSig[42] ^= 0xff;
  163. this.requestData.signature = web3.utils.bytesToHex(tamperedSig);
  164. await expectRevertCustomError(this.forwarder.execute(this.requestData), 'ERC2771ForwarderInvalidSigner', [
  165. ethSigUtil.recoverTypedSignature({ data: this.forgeData(), sig: tamperedSig }),
  166. this.requestData.from,
  167. ]);
  168. });
  169. it('reverts with valid signature for non-current nonce', async function () {
  170. // Execute first a request
  171. await this.forwarder.execute(this.requestData);
  172. // And then fail due to an already used nonce
  173. await expectRevertCustomError(this.forwarder.execute(this.requestData), 'ERC2771ForwarderInvalidSigner', [
  174. ethSigUtil.recoverTypedSignature({
  175. data: this.forgeData({ ...this.requestData, nonce: this.requestData.nonce + 1 }),
  176. sig: this.requestData.signature,
  177. }),
  178. this.requestData.from,
  179. ]);
  180. });
  181. it('reverts with valid signature for expired deadline', async function () {
  182. const req = {
  183. ...this.requestData,
  184. deadline: this.timestamp - 1,
  185. };
  186. req.signature = this.sign(this.alice.getPrivateKey(), req);
  187. await expectRevertCustomError(this.forwarder.execute(req), 'ERC2771ForwarderExpiredRequest', [
  188. this.timestamp - 1,
  189. ]);
  190. });
  191. it('reverts with valid signature but mismatched value', async function () {
  192. const value = 100;
  193. const req = {
  194. ...this.requestData,
  195. value,
  196. };
  197. req.signature = this.sign(this.alice.getPrivateKey(), req);
  198. await expectRevertCustomError(this.forwarder.execute(req), 'ERC2771ForwarderMismatchedValue', [0, value]);
  199. });
  200. });
  201. it('bubbles out of gas', async function () {
  202. this.requestData.data = this.receiver.contract.methods.mockFunctionOutOfGas().encodeABI();
  203. this.requestData.gas = 1_000_000;
  204. this.requestData.signature = this.sign(this.alice.getPrivateKey());
  205. const gasAvailable = 100_000;
  206. await expectRevert.assertion(this.forwarder.execute(this.requestData, { gas: gasAvailable }));
  207. const { transactions } = await web3.eth.getBlock('latest');
  208. const { gasUsed } = await web3.eth.getTransactionReceipt(transactions[0]);
  209. expect(gasUsed).to.be.equal(gasAvailable);
  210. });
  211. it('bubbles out of gas forced by the relayer', async function () {
  212. // If there's an incentive behind executing requests, a malicious relayer could grief
  213. // the forwarder by executing requests and providing a top-level call gas limit that
  214. // is too low to successfully finish the request after the 63/64 rule.
  215. // We set the baseline to the gas limit consumed by a successful request if it was executed
  216. // normally. Note this includes the 21000 buffer that also the relayer will be charged to
  217. // start a request execution.
  218. const estimate = await this.estimateRequest(this.request);
  219. // Because the relayer call consumes gas until the `CALL` opcode, the gas left after failing
  220. // the subcall won't enough to finish the top level call (after testing), so we add a
  221. // moderated buffer.
  222. const gasAvailable = estimate + 2_000;
  223. // The subcall out of gas should be caught by the contract and then bubbled up consuming
  224. // the available gas with an `invalid` opcode.
  225. await expectRevert.outOfGas(this.forwarder.execute(this.requestData, { gas: gasAvailable }));
  226. const { transactions } = await web3.eth.getBlock('latest');
  227. const { gasUsed } = await web3.eth.getTransactionReceipt(transactions[0]);
  228. // We assert that indeed the gas was totally consumed.
  229. expect(gasUsed).to.be.equal(gasAvailable);
  230. });
  231. });
  232. context('executeBatch', function () {
  233. const batchValue = requestDatas => requestDatas.reduce((value, request) => value + Number(request.value), 0);
  234. beforeEach(async function () {
  235. this.bob = Wallet.generate();
  236. this.bob.address = web3.utils.toChecksumAddress(this.bob.getAddressString());
  237. this.eve = Wallet.generate();
  238. this.eve.address = web3.utils.toChecksumAddress(this.eve.getAddressString());
  239. this.signers = [this.alice, this.bob, this.eve];
  240. this.requestDatas = await Promise.all(
  241. this.signers.map(async ({ address }) => ({
  242. ...this.requestData,
  243. from: address,
  244. nonce: (await this.forwarder.nonces(address)).toString(),
  245. value: web3.utils.toWei('10', 'gwei'),
  246. })),
  247. );
  248. this.requestDatas = this.requestDatas.map((requestData, i) => ({
  249. ...requestData,
  250. signature: this.sign(this.signers[i].getPrivateKey(), requestData),
  251. }));
  252. this.msgValue = batchValue(this.requestDatas);
  253. this.gasUntil = async reqIdx => {
  254. const gas = 0;
  255. const estimations = await Promise.all(
  256. new Array(reqIdx + 1).fill().map((_, idx) => this.estimateRequest(this.requestDatas[idx])),
  257. );
  258. return estimations.reduce((acc, estimation) => acc + estimation, gas);
  259. };
  260. });
  261. context('with valid requests', function () {
  262. beforeEach(async function () {
  263. for (const request of this.requestDatas) {
  264. expect(await this.forwarder.verify(request)).to.be.equal(true);
  265. }
  266. this.receipt = await this.forwarder.executeBatch(this.requestDatas, another, { value: this.msgValue });
  267. });
  268. it('emits events', async function () {
  269. for (const request of this.requestDatas) {
  270. await expectEvent.inTransaction(this.receipt.tx, this.receiver, 'MockFunctionCalled');
  271. await expectEvent.inTransaction(this.receipt.tx, this.forwarder, 'ExecutedForwardRequest', {
  272. signer: request.from,
  273. nonce: web3.utils.toBN(request.nonce),
  274. success: true,
  275. });
  276. }
  277. });
  278. it('increase nonces', async function () {
  279. for (const request of this.requestDatas) {
  280. expect(await this.forwarder.nonces(request.from)).to.be.bignumber.eq(web3.utils.toBN(request.nonce + 1));
  281. }
  282. });
  283. });
  284. context('with tampered requests', function () {
  285. beforeEach(async function () {
  286. this.idx = 1; // Tampered idx
  287. });
  288. it('reverts with mismatched value', async function () {
  289. this.requestDatas[this.idx].value = 100;
  290. this.requestDatas[this.idx].signature = this.sign(
  291. this.signers[this.idx].getPrivateKey(),
  292. this.requestDatas[this.idx],
  293. );
  294. await expectRevertCustomError(
  295. this.forwarder.executeBatch(this.requestDatas, another, { value: this.msgValue }),
  296. 'ERC2771ForwarderMismatchedValue',
  297. [batchValue(this.requestDatas), this.msgValue],
  298. );
  299. });
  300. context('when the refund receiver is the zero address', function () {
  301. beforeEach(function () {
  302. this.refundReceiver = constants.ZERO_ADDRESS;
  303. });
  304. for (const [key, value] of Object.entries(tamperedValues)) {
  305. it(`reverts with at least one tampered request ${key}`, async function () {
  306. const data = this.forgeData({ ...this.requestDatas[this.idx], [key]: value });
  307. this.requestDatas[this.idx] = data.message;
  308. await expectRevertCustomError(
  309. this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { value: this.msgValue }),
  310. 'ERC2771ForwarderInvalidSigner',
  311. [
  312. ethSigUtil.recoverTypedSignature({ data, sig: this.requestDatas[this.idx].signature }),
  313. data.message.from,
  314. ],
  315. );
  316. });
  317. }
  318. it('reverts with at least one untrustful to', async function () {
  319. const data = this.forgeData({ ...this.requestDatas[this.idx], to: another });
  320. this.requestDatas[this.idx] = data.message;
  321. await expectRevertCustomError(
  322. this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { value: this.msgValue }),
  323. 'ERC2771UntrustfulTarget',
  324. [this.requestDatas[this.idx].to, this.forwarder.address],
  325. );
  326. });
  327. it('reverts with at least one tampered request signature', async function () {
  328. const tamperedSig = web3.utils.hexToBytes(this.requestDatas[this.idx].signature);
  329. tamperedSig[42] ^= 0xff;
  330. this.requestDatas[this.idx].signature = web3.utils.bytesToHex(tamperedSig);
  331. await expectRevertCustomError(
  332. this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { value: this.msgValue }),
  333. 'ERC2771ForwarderInvalidSigner',
  334. [
  335. ethSigUtil.recoverTypedSignature({
  336. data: this.forgeData(this.requestDatas[this.idx]),
  337. sig: this.requestDatas[this.idx].signature,
  338. }),
  339. this.requestDatas[this.idx].from,
  340. ],
  341. );
  342. });
  343. it('reverts with at least one valid signature for non-current nonce', async function () {
  344. // Execute first a request
  345. await this.forwarder.execute(this.requestDatas[this.idx], { value: this.requestDatas[this.idx].value });
  346. // And then fail due to an already used nonce
  347. await expectRevertCustomError(
  348. this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { value: this.msgValue }),
  349. 'ERC2771ForwarderInvalidSigner',
  350. [
  351. ethSigUtil.recoverTypedSignature({
  352. data: this.forgeData({ ...this.requestDatas[this.idx], nonce: this.requestDatas[this.idx].nonce + 1 }),
  353. sig: this.requestDatas[this.idx].signature,
  354. }),
  355. this.requestDatas[this.idx].from,
  356. ],
  357. );
  358. });
  359. it('reverts with at least one valid signature for expired deadline', async function () {
  360. this.requestDatas[this.idx].deadline = this.timestamp.toNumber() - 1;
  361. this.requestDatas[this.idx].signature = this.sign(
  362. this.signers[this.idx].getPrivateKey(),
  363. this.requestDatas[this.idx],
  364. );
  365. await expectRevertCustomError(
  366. this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { value: this.msgValue }),
  367. 'ERC2771ForwarderExpiredRequest',
  368. [this.timestamp.toNumber() - 1],
  369. );
  370. });
  371. });
  372. context('when the refund receiver is a known address', function () {
  373. beforeEach(async function () {
  374. this.refundReceiver = refundReceiver;
  375. this.initialRefundReceiverBalance = web3.utils.toBN(await web3.eth.getBalance(this.refundReceiver));
  376. this.initialTamperedRequestNonce = await this.forwarder.nonces(this.requestDatas[this.idx].from);
  377. });
  378. for (const [key, value] of Object.entries(tamperedValues)) {
  379. it(`ignores a request with tampered ${key} and refunds its value`, async function () {
  380. const data = this.forgeData({ ...this.requestDatas[this.idx], [key]: value });
  381. this.requestDatas[this.idx] = data.message;
  382. const receipt = await this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, {
  383. value: batchValue(this.requestDatas),
  384. });
  385. expect(receipt.logs.filter(({ event }) => event === 'ExecutedForwardRequest').length).to.be.equal(2);
  386. });
  387. }
  388. it('ignores a request with a valid signature for non-current nonce', async function () {
  389. // Execute first a request
  390. await this.forwarder.execute(this.requestDatas[this.idx], { value: this.requestDatas[this.idx].value });
  391. this.initialTamperedRequestNonce++; // Should be already incremented by the individual `execute`
  392. // And then ignore the same request in a batch due to an already used nonce
  393. const receipt = await this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, {
  394. value: this.msgValue,
  395. });
  396. expect(receipt.logs.filter(({ event }) => event === 'ExecutedForwardRequest').length).to.be.equal(2);
  397. });
  398. it('ignores a request with a valid signature for expired deadline', async function () {
  399. this.requestDatas[this.idx].deadline = this.timestamp.toNumber() - 1;
  400. this.requestDatas[this.idx].signature = this.sign(
  401. this.signers[this.idx].getPrivateKey(),
  402. this.requestDatas[this.idx],
  403. );
  404. const receipt = await this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, {
  405. value: this.msgValue,
  406. });
  407. expect(receipt.logs.filter(({ event }) => event === 'ExecutedForwardRequest').length).to.be.equal(2);
  408. });
  409. afterEach(async function () {
  410. // The invalid request value was refunded
  411. expect(await web3.eth.getBalance(this.refundReceiver)).to.be.bignumber.equal(
  412. this.initialRefundReceiverBalance.add(web3.utils.toBN(this.requestDatas[this.idx].value)),
  413. );
  414. // The invalid request from's nonce was not incremented
  415. expect(await this.forwarder.nonces(this.requestDatas[this.idx].from)).to.be.bignumber.eq(
  416. web3.utils.toBN(this.initialTamperedRequestNonce),
  417. );
  418. });
  419. });
  420. it('bubbles out of gas', async function () {
  421. this.requestDatas[this.idx].data = this.receiver.contract.methods.mockFunctionOutOfGas().encodeABI();
  422. this.requestDatas[this.idx].gas = 1_000_000;
  423. this.requestDatas[this.idx].signature = this.sign(
  424. this.signers[this.idx].getPrivateKey(),
  425. this.requestDatas[this.idx],
  426. );
  427. const gasAvailable = 300_000;
  428. await expectRevert.assertion(
  429. this.forwarder.executeBatch(this.requestDatas, constants.ZERO_ADDRESS, {
  430. gas: gasAvailable,
  431. value: this.requestDatas.reduce((acc, { value }) => acc + Number(value), 0),
  432. }),
  433. );
  434. const { transactions } = await web3.eth.getBlock('latest');
  435. const { gasUsed } = await web3.eth.getTransactionReceipt(transactions[0]);
  436. expect(gasUsed).to.be.equal(gasAvailable);
  437. });
  438. it('bubbles out of gas forced by the relayer', async function () {
  439. // Similarly to the single execute, a malicious relayer could grief requests.
  440. // We estimate until the selected request as if they were executed normally
  441. const estimate = await this.gasUntil(this.requestDatas, this.idx);
  442. // We add a Buffer to account for all the gas that's used before the selected call.
  443. // Note is slightly bigger because the selected request is not the index 0 and it affects
  444. // the buffer needed.
  445. const gasAvailable = estimate + 10_000;
  446. // The subcall out of gas should be caught by the contract and then bubbled up consuming
  447. // the available gas with an `invalid` opcode.
  448. await expectRevert.outOfGas(
  449. this.forwarder.executeBatch(this.requestDatas, constants.ZERO_ADDRESS, { gas: gasAvailable }),
  450. );
  451. const { transactions } = await web3.eth.getBlock('latest');
  452. const { gasUsed } = await web3.eth.getTransactionReceipt(transactions[0]);
  453. // We assert that indeed the gas was totally consumed.
  454. expect(gasUsed).to.be.equal(gasAvailable);
  455. });
  456. });
  457. });
  458. });