ERC2771Forwarder.test.js 22 KB

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