ERC2771Forwarder.test.js 21 KB

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