ERC2771Forwarder.test.js 22.1 KB
Newer Older
vicotor's avatar
vicotor committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
const ethSigUtil = require('eth-sig-util');
const Wallet = require('ethereumjs-wallet').default;
const { getDomain, domainType } = require('../helpers/eip712');
const { expectRevertCustomError } = require('../helpers/customError');

const { constants, expectRevert, expectEvent, time } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');

const ERC2771Forwarder = artifacts.require('ERC2771Forwarder');
const CallReceiverMockTrustingForwarder = artifacts.require('CallReceiverMockTrustingForwarder');

contract('ERC2771Forwarder', function (accounts) {
  const [, refundReceiver, another] = accounts;

  const tamperedValues = {
    from: another,
    value: web3.utils.toWei('0.5'),
    data: '0x1742',
  };

  beforeEach(async function () {
    this.forwarder = await ERC2771Forwarder.new('ERC2771Forwarder');

    this.domain = await getDomain(this.forwarder);
    this.types = {
      EIP712Domain: domainType(this.domain),
      ForwardRequest: [
        { name: 'from', type: 'address' },
        { name: 'to', type: 'address' },
        { name: 'value', type: 'uint256' },
        { name: 'gas', type: 'uint256' },
        { name: 'nonce', type: 'uint256' },
        { name: 'deadline', type: 'uint48' },
        { name: 'data', type: 'bytes' },
      ],
    };

    this.alice = Wallet.generate();
    this.alice.address = web3.utils.toChecksumAddress(this.alice.getAddressString());

    this.timestamp = await time.latest();
    this.receiver = await CallReceiverMockTrustingForwarder.new(this.forwarder.address);
    this.request = {
      from: this.alice.address,
      to: this.receiver.address,
      value: '0',
      gas: '100000',
      data: this.receiver.contract.methods.mockFunction().encodeABI(),
      deadline: this.timestamp.toNumber() + 60, // 1 minute
    };
    this.requestData = {
      ...this.request,
      nonce: (await this.forwarder.nonces(this.alice.address)).toString(),
    };

    this.forgeData = request => ({
      types: this.types,
      domain: this.domain,
      primaryType: 'ForwardRequest',
      message: { ...this.requestData, ...request },
    });
    this.sign = (privateKey, request) =>
      ethSigUtil.signTypedMessage(privateKey, {
        data: this.forgeData(request),
      });
    this.estimateRequest = request =>
      web3.eth.estimateGas({
        from: this.forwarder.address,
        to: request.to,
        data: web3.utils.encodePacked({ value: request.data, type: 'bytes' }, { value: request.from, type: 'address' }),
        value: request.value,
        gas: request.gas,
      });

    this.requestData.signature = this.sign(this.alice.getPrivateKey());
  });

  context('verify', function () {
    context('with valid signature', function () {
      it('returns true without altering the nonce', async function () {
        expect(await this.forwarder.nonces(this.requestData.from)).to.be.bignumber.equal(
          web3.utils.toBN(this.requestData.nonce),
        );
        expect(await this.forwarder.verify(this.requestData)).to.be.equal(true);
        expect(await this.forwarder.nonces(this.requestData.from)).to.be.bignumber.equal(
          web3.utils.toBN(this.requestData.nonce),
        );
      });
    });

    context('with tampered values', function () {
      for (const [key, value] of Object.entries(tamperedValues)) {
        it(`returns false with tampered ${key}`, async function () {
          expect(await this.forwarder.verify(this.forgeData({ [key]: value }).message)).to.be.equal(false);
        });
      }

      it('returns false with an untrustful to', async function () {
        expect(await this.forwarder.verify(this.forgeData({ to: another }).message)).to.be.equal(false);
      });

      it('returns false with tampered signature', async function () {
        const tamperedsign = web3.utils.hexToBytes(this.requestData.signature);
        tamperedsign[42] ^= 0xff;
        this.requestData.signature = web3.utils.bytesToHex(tamperedsign);
        expect(await this.forwarder.verify(this.requestData)).to.be.equal(false);
      });

      it('returns false with valid signature for non-current nonce', async function () {
        const req = {
          ...this.requestData,
          nonce: this.requestData.nonce + 1,
        };
        req.signature = this.sign(this.alice.getPrivateKey(), req);
        expect(await this.forwarder.verify(req)).to.be.equal(false);
      });

      it('returns false with valid signature for expired deadline', async function () {
        const req = {
          ...this.requestData,
          deadline: this.timestamp - 1,
        };
        req.signature = this.sign(this.alice.getPrivateKey(), req);
        expect(await this.forwarder.verify(req)).to.be.equal(false);
      });
    });
  });

  context('execute', function () {
    context('with valid requests', function () {
      beforeEach(async function () {
        expect(await this.forwarder.nonces(this.requestData.from)).to.be.bignumber.equal(
          web3.utils.toBN(this.requestData.nonce),
        );
      });

      it('emits an event and consumes nonce for a successful request', async function () {
        const receipt = await this.forwarder.execute(this.requestData);
        await expectEvent.inTransaction(receipt.tx, this.receiver, 'MockFunctionCalled');
        await expectEvent.inTransaction(receipt.tx, this.forwarder, 'ExecutedForwardRequest', {
          signer: this.requestData.from,
          nonce: web3.utils.toBN(this.requestData.nonce),
          success: true,
        });
        expect(await this.forwarder.nonces(this.requestData.from)).to.be.bignumber.equal(
          web3.utils.toBN(this.requestData.nonce + 1),
        );
      });

      it('reverts with an unsuccessful request', async function () {
        const req = {
          ...this.requestData,
          data: this.receiver.contract.methods.mockFunctionRevertsNoReason().encodeABI(),
        };
        req.signature = this.sign(this.alice.getPrivateKey(), req);
        await expectRevertCustomError(this.forwarder.execute(req), 'FailedInnerCall', []);
      });
    });

    context('with tampered request', function () {
      for (const [key, value] of Object.entries(tamperedValues)) {
        it(`reverts with tampered ${key}`, async function () {
          const data = this.forgeData({ [key]: value });
          await expectRevertCustomError(
            this.forwarder.execute(data.message, {
              value: key == 'value' ? value : 0, // To avoid MismatchedValue error
            }),
            'ERC2771ForwarderInvalidSigner',
            [ethSigUtil.recoverTypedSignature({ data, sig: this.requestData.signature }), data.message.from],
          );
        });
      }

      it('reverts with an untrustful to', async function () {
        const data = this.forgeData({ to: another });
        await expectRevertCustomError(this.forwarder.execute(data.message), 'ERC2771UntrustfulTarget', [
          data.message.to,
          this.forwarder.address,
        ]);
      });

      it('reverts with tampered signature', async function () {
        const tamperedSig = web3.utils.hexToBytes(this.requestData.signature);
        tamperedSig[42] ^= 0xff;
        this.requestData.signature = web3.utils.bytesToHex(tamperedSig);
        await expectRevertCustomError(this.forwarder.execute(this.requestData), 'ERC2771ForwarderInvalidSigner', [
          ethSigUtil.recoverTypedSignature({ data: this.forgeData(), sig: tamperedSig }),
          this.requestData.from,
        ]);
      });

      it('reverts with valid signature for non-current nonce', async function () {
        // Execute first a request
        await this.forwarder.execute(this.requestData);

        // And then fail due to an already used nonce
        await expectRevertCustomError(this.forwarder.execute(this.requestData), 'ERC2771ForwarderInvalidSigner', [
          ethSigUtil.recoverTypedSignature({
            data: this.forgeData({ ...this.requestData, nonce: this.requestData.nonce + 1 }),
            sig: this.requestData.signature,
          }),
          this.requestData.from,
        ]);
      });

      it('reverts with valid signature for expired deadline', async function () {
        const req = {
          ...this.requestData,
          deadline: this.timestamp - 1,
        };
        req.signature = this.sign(this.alice.getPrivateKey(), req);
        await expectRevertCustomError(this.forwarder.execute(req), 'ERC2771ForwarderExpiredRequest', [
          this.timestamp - 1,
        ]);
      });

      it('reverts with valid signature but mismatched value', async function () {
        const value = 100;
        const req = {
          ...this.requestData,
          value,
        };
        req.signature = this.sign(this.alice.getPrivateKey(), req);
        await expectRevertCustomError(this.forwarder.execute(req), 'ERC2771ForwarderMismatchedValue', [0, value]);
      });
    });

    it('bubbles out of gas', async function () {
      this.requestData.data = this.receiver.contract.methods.mockFunctionOutOfGas().encodeABI();
      this.requestData.gas = 1_000_000;
      this.requestData.signature = this.sign(this.alice.getPrivateKey());

      const gasAvailable = 100_000;
      await expectRevert.assertion(this.forwarder.execute(this.requestData, { gas: gasAvailable }));

      const { transactions } = await web3.eth.getBlock('latest');
      const { gasUsed } = await web3.eth.getTransactionReceipt(transactions[0]);

      expect(gasUsed).to.be.equal(gasAvailable);
    });

    it('bubbles out of gas forced by the relayer', async function () {
      // If there's an incentive behind executing requests, a malicious relayer could grief
      // the forwarder by executing requests and providing a top-level call gas limit that
      // is too low to successfully finish the request after the 63/64 rule.

      // We set the baseline to the gas limit consumed by a successful request if it was executed
      // normally. Note this includes the 21000 buffer that also the relayer will be charged to
      // start a request execution.
      const estimate = await this.estimateRequest(this.request);

      // Because the relayer call consumes gas until the `CALL` opcode, the gas left after failing
      // the subcall won't enough to finish the top level call (after testing), so we add a
      // moderated buffer.
      const gasAvailable = estimate + 2_000;

      // The subcall out of gas should be caught by the contract and then bubbled up consuming
      // the available gas with an `invalid` opcode.
      await expectRevert.outOfGas(this.forwarder.execute(this.requestData, { gas: gasAvailable }));

      const { transactions } = await web3.eth.getBlock('latest');
      const { gasUsed } = await web3.eth.getTransactionReceipt(transactions[0]);

      // We assert that indeed the gas was totally consumed.
      expect(gasUsed).to.be.equal(gasAvailable);
    });
  });

  context('executeBatch', function () {
    const batchValue = requestDatas => requestDatas.reduce((value, request) => value + Number(request.value), 0);

    beforeEach(async function () {
      this.bob = Wallet.generate();
      this.bob.address = web3.utils.toChecksumAddress(this.bob.getAddressString());

      this.eve = Wallet.generate();
      this.eve.address = web3.utils.toChecksumAddress(this.eve.getAddressString());

      this.signers = [this.alice, this.bob, this.eve];

      this.requestDatas = await Promise.all(
        this.signers.map(async ({ address }) => ({
          ...this.requestData,
          from: address,
          nonce: (await this.forwarder.nonces(address)).toString(),
          value: web3.utils.toWei('10', 'gwei'),
        })),
      );

      this.requestDatas = this.requestDatas.map((requestData, i) => ({
        ...requestData,
        signature: this.sign(this.signers[i].getPrivateKey(), requestData),
      }));

      this.msgValue = batchValue(this.requestDatas);

      this.gasUntil = async reqIdx => {
        const gas = 0;
        const estimations = await Promise.all(
          new Array(reqIdx + 1).fill().map((_, idx) => this.estimateRequest(this.requestDatas[idx])),
        );
        return estimations.reduce((acc, estimation) => acc + estimation, gas);
      };
    });

    context('with valid requests', function () {
      beforeEach(async function () {
        for (const request of this.requestDatas) {
          expect(await this.forwarder.verify(request)).to.be.equal(true);
        }

        this.receipt = await this.forwarder.executeBatch(this.requestDatas, another, { value: this.msgValue });
      });

      it('emits events', async function () {
        for (const request of this.requestDatas) {
          await expectEvent.inTransaction(this.receipt.tx, this.receiver, 'MockFunctionCalled');
          await expectEvent.inTransaction(this.receipt.tx, this.forwarder, 'ExecutedForwardRequest', {
            signer: request.from,
            nonce: web3.utils.toBN(request.nonce),
            success: true,
          });
        }
      });

      it('increase nonces', async function () {
        for (const request of this.requestDatas) {
          expect(await this.forwarder.nonces(request.from)).to.be.bignumber.eq(web3.utils.toBN(request.nonce + 1));
        }
      });
    });

    context('with tampered requests', function () {
      beforeEach(async function () {
        this.idx = 1; // Tampered idx
      });

      it('reverts with mismatched value', async function () {
        this.requestDatas[this.idx].value = 100;
        this.requestDatas[this.idx].signature = this.sign(
          this.signers[this.idx].getPrivateKey(),
          this.requestDatas[this.idx],
        );
        await expectRevertCustomError(
          this.forwarder.executeBatch(this.requestDatas, another, { value: this.msgValue }),
          'ERC2771ForwarderMismatchedValue',
          [batchValue(this.requestDatas), this.msgValue],
        );
      });

      context('when the refund receiver is the zero address', function () {
        beforeEach(function () {
          this.refundReceiver = constants.ZERO_ADDRESS;
        });

        for (const [key, value] of Object.entries(tamperedValues)) {
          it(`reverts with at least one tampered request ${key}`, async function () {
            const data = this.forgeData({ ...this.requestDatas[this.idx], [key]: value });

            this.requestDatas[this.idx] = data.message;

            await expectRevertCustomError(
              this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { value: this.msgValue }),
              'ERC2771ForwarderInvalidSigner',
              [
                ethSigUtil.recoverTypedSignature({ data, sig: this.requestDatas[this.idx].signature }),
                data.message.from,
              ],
            );
          });
        }

        it('reverts with at least one untrustful to', async function () {
          const data = this.forgeData({ ...this.requestDatas[this.idx], to: another });

          this.requestDatas[this.idx] = data.message;

          await expectRevertCustomError(
            this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { value: this.msgValue }),
            'ERC2771UntrustfulTarget',
            [this.requestDatas[this.idx].to, this.forwarder.address],
          );
        });

        it('reverts with at least one tampered request signature', async function () {
          const tamperedSig = web3.utils.hexToBytes(this.requestDatas[this.idx].signature);
          tamperedSig[42] ^= 0xff;

          this.requestDatas[this.idx].signature = web3.utils.bytesToHex(tamperedSig);

          await expectRevertCustomError(
            this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { value: this.msgValue }),
            'ERC2771ForwarderInvalidSigner',
            [
              ethSigUtil.recoverTypedSignature({
                data: this.forgeData(this.requestDatas[this.idx]),
                sig: this.requestDatas[this.idx].signature,
              }),
              this.requestDatas[this.idx].from,
            ],
          );
        });

        it('reverts with at least one valid signature for non-current nonce', async function () {
          // Execute first a request
          await this.forwarder.execute(this.requestDatas[this.idx], { value: this.requestDatas[this.idx].value });

          // And then fail due to an already used nonce
          await expectRevertCustomError(
            this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { value: this.msgValue }),
            'ERC2771ForwarderInvalidSigner',
            [
              ethSigUtil.recoverTypedSignature({
                data: this.forgeData({ ...this.requestDatas[this.idx], nonce: this.requestDatas[this.idx].nonce + 1 }),
                sig: this.requestDatas[this.idx].signature,
              }),
              this.requestDatas[this.idx].from,
            ],
          );
        });

        it('reverts with at least one valid signature for expired deadline', async function () {
          this.requestDatas[this.idx].deadline = this.timestamp.toNumber() - 1;
          this.requestDatas[this.idx].signature = this.sign(
            this.signers[this.idx].getPrivateKey(),
            this.requestDatas[this.idx],
          );
          await expectRevertCustomError(
            this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { value: this.msgValue }),
            'ERC2771ForwarderExpiredRequest',
            [this.timestamp.toNumber() - 1],
          );
        });
      });

      context('when the refund receiver is a known address', function () {
        beforeEach(async function () {
          this.refundReceiver = refundReceiver;
          this.initialRefundReceiverBalance = web3.utils.toBN(await web3.eth.getBalance(this.refundReceiver));
          this.initialTamperedRequestNonce = await this.forwarder.nonces(this.requestDatas[this.idx].from);
        });

        for (const [key, value] of Object.entries(tamperedValues)) {
          it(`ignores a request with tampered ${key} and refunds its value`, async function () {
            const data = this.forgeData({ ...this.requestDatas[this.idx], [key]: value });

            this.requestDatas[this.idx] = data.message;

            const receipt = await this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, {
              value: batchValue(this.requestDatas),
            });
            expect(receipt.logs.filter(({ event }) => event === 'ExecutedForwardRequest').length).to.be.equal(2);
          });
        }

        it('ignores a request with a valid signature for non-current nonce', async function () {
          // Execute first a request
          await this.forwarder.execute(this.requestDatas[this.idx], { value: this.requestDatas[this.idx].value });
          this.initialTamperedRequestNonce++; // Should be already incremented by the individual `execute`

          // And then ignore the same request in a batch due to an already used nonce
          const receipt = await this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, {
            value: this.msgValue,
          });
          expect(receipt.logs.filter(({ event }) => event === 'ExecutedForwardRequest').length).to.be.equal(2);
        });

        it('ignores a request with a valid signature for expired deadline', async function () {
          this.requestDatas[this.idx].deadline = this.timestamp.toNumber() - 1;
          this.requestDatas[this.idx].signature = this.sign(
            this.signers[this.idx].getPrivateKey(),
            this.requestDatas[this.idx],
          );

          const receipt = await this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, {
            value: this.msgValue,
          });
          expect(receipt.logs.filter(({ event }) => event === 'ExecutedForwardRequest').length).to.be.equal(2);
        });

        afterEach(async function () {
          // The invalid request value was refunded
          expect(await web3.eth.getBalance(this.refundReceiver)).to.be.bignumber.equal(
            this.initialRefundReceiverBalance.add(web3.utils.toBN(this.requestDatas[this.idx].value)),
          );

          // The invalid request from's nonce was not incremented
          expect(await this.forwarder.nonces(this.requestDatas[this.idx].from)).to.be.bignumber.eq(
            web3.utils.toBN(this.initialTamperedRequestNonce),
          );
        });
      });

      it('bubbles out of gas', async function () {
        this.requestDatas[this.idx].data = this.receiver.contract.methods.mockFunctionOutOfGas().encodeABI();
        this.requestDatas[this.idx].gas = 1_000_000;
        this.requestDatas[this.idx].signature = this.sign(
          this.signers[this.idx].getPrivateKey(),
          this.requestDatas[this.idx],
        );

        const gasAvailable = 300_000;
        await expectRevert.assertion(
          this.forwarder.executeBatch(this.requestDatas, constants.ZERO_ADDRESS, {
            gas: gasAvailable,
            value: this.requestDatas.reduce((acc, { value }) => acc + Number(value), 0),
          }),
        );

        const { transactions } = await web3.eth.getBlock('latest');
        const { gasUsed } = await web3.eth.getTransactionReceipt(transactions[0]);

        expect(gasUsed).to.be.equal(gasAvailable);
      });

      it('bubbles out of gas forced by the relayer', async function () {
        // Similarly to the single execute, a malicious relayer could grief requests.

        // We estimate until the selected request as if they were executed normally
        const estimate = await this.gasUntil(this.requestDatas, this.idx);

        // We add a Buffer to account for all the gas that's used before the selected call.
        // Note is slightly bigger because the selected request is not the index 0 and it affects
        // the buffer needed.
        const gasAvailable = estimate + 10_000;

        // The subcall out of gas should be caught by the contract and then bubbled up consuming
        // the available gas with an `invalid` opcode.
        await expectRevert.outOfGas(
          this.forwarder.executeBatch(this.requestDatas, constants.ZERO_ADDRESS, { gas: gasAvailable }),
        );

        const { transactions } = await web3.eth.getBlock('latest');
        const { gasUsed } = await web3.eth.getTransactionReceipt(transactions[0]);

        // We assert that indeed the gas was totally consumed.
        expect(gasUsed).to.be.equal(gasAvailable);
      });
    });
  });
});