Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Verify raw tx format when send raw transaction #1076

Merged
merged 2 commits into from
Jun 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 8 additions & 42 deletions web3/packages/api-server/src/convert-tx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,15 @@ import { Uint64 } from "./base/types/uint";
import { AutoCreateAccountCacheValue } from "./cache/types";
import { TransactionCallObject } from "./methods/types";
import { isGaslessTransaction } from "./gasless/utils";
import {
PolyjuiceTransaction,
decodeEthRawTx,
encodePolyjuiceTransaction,
toRlpNumber,
} from "./rlp";

export const DEPLOY_TO_ADDRESS = "0x";

export interface PolyjuiceTransaction {
nonce: HexNumber;
gasPrice: HexNumber;
gasLimit: HexNumber;
to: HexString;
value: HexNumber;
data: HexString;
v: HexNumber;
r: HexString;
s: HexString;
}

// execute raw transaction
export async function ethCallTxToGodwokenRawTx(
tx: Required<TransactionCallObject>,
Expand Down Expand Up @@ -246,14 +240,9 @@ export async function ethRawTxToGwTx(
* Convert ETH raw transaction to PolyjuiceTransaction
*/
export function ethRawTxToPolyTx(ethRawTx: HexString): PolyjuiceTransaction {
const result: Buffer[] = rlp.decode(ethRawTx) as Buffer[];
if (result.length !== 9) {
throw new Error("decode eth raw transaction data error");
}

// todo: r might be "0x" which cause inconvenient for down-stream
const resultHex = result.map((r) => "0x" + Buffer.from(r).toString("hex"));
const [nonce, gasPrice, gasLimit, to, value, data, v, r, s] = resultHex;
const resultHex = decodeEthRawTx(ethRawTx);
const { nonce, gasPrice, gasLimit, to, value, data, v, r, s } = resultHex;

// r & s is integer in RLP, convert to 32-byte hex string (add leading zeros)
const rWithLeadingZeros: HexString = "0x" + r.slice(2).padStart(64, "0");
Expand Down Expand Up @@ -327,29 +316,6 @@ function calcMessage(tx: PolyjuiceTransaction): HexString {
return message;
}

function toRlpNumber(num: HexNumber): bigint {
return num === "0x" ? 0n : BigInt(num);
}

function encodePolyjuiceTransaction(tx: PolyjuiceTransaction) {
const { nonce, gasPrice, gasLimit, to, value, data, v, r, s } = tx;

const beforeEncode = [
toRlpNumber(nonce),
toRlpNumber(gasPrice),
toRlpNumber(gasLimit),
to,
toRlpNumber(value),
data,
toRlpNumber(v),
toRlpNumber(r),
toRlpNumber(s),
];

const result = rlp.encode(beforeEncode);
return "0x" + result.toString("hex");
}

/**
* Convert Polyjuice transaction to Godwoken transaction
*/
Expand Down
4 changes: 2 additions & 2 deletions web3/packages/api-server/src/methods/modules/eth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ import {
getSignature,
polyTxToGwTx,
polyjuiceRawTransactionToApiTransaction,
PolyjuiceTransaction,
ethCallTxToGodwokenRawTx,
} from "../../convert-tx";
import { PolyjuiceTransaction } from "../../rlp";
import { ethAddressToAccountId, EthRegistryAddress } from "../../base/address";
import { keccakFromString } from "ethereumjs-util";
import { DataCacheConstructor, RedisDataCache } from "../../cache/data";
Expand Down Expand Up @@ -212,7 +212,7 @@ export class Eth {
this.sendRawTransaction = middleware(
this.sendRawTransaction.bind(this),
1,
[validators.hexString]
[validators.rawTransaction]
);

//
Expand Down
6 changes: 2 additions & 4 deletions web3/packages/api-server/src/methods/modules/gw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,8 @@ import {
import { InvalidParamsError } from "../error";
import { gwConfig, readonlyPriceOracle } from "../../base";
import { META_CONTRACT_ID } from "../constant";
import {
PolyjuiceTransaction,
recoverEthAddressFromPolyjuiceTx,
} from "../../convert-tx";
import { PolyjuiceTransaction } from "../../rlp";
import { recoverEthAddressFromPolyjuiceTx } from "../../convert-tx";
import { isGaslessTransaction } from "../../gasless/utils";

export class Gw {
Expand Down
57 changes: 57 additions & 0 deletions web3/packages/api-server/src/methods/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ import { GodwokenClient } from "@godwoken-web3/godwoken";
import { EthRegistryAddress } from "../base/address";
import { decodeGaslessPayload } from "../gasless/payload";
import { gwConfig } from "../base";
import {
decodeEthRawTx,
encodePolyjuiceTransaction,
PolyjuiceTransaction,
} from "../rlp";

/**
* middleware for parameters validation
Expand Down Expand Up @@ -137,6 +142,10 @@ export const validators = {
newFilterParams(params: any[], index: number) {
return verifyNewFilterObj(params[index], index);
},

rawTransaction(params: any[], index: number) {
return verifySendRawTransaction(params[index], index);
},
};

//****** standalone verify function ********/
Expand Down Expand Up @@ -808,6 +817,54 @@ export function verifyGaslessTransaction(
}
}

type KeyOfPolyjuiceTransaction = keyof PolyjuiceTransaction;
export function verifySendRawTransaction(rawTx: HexString, index: number) {
const verifyHexStringResult = verifyHexString(rawTx, index);
if (verifyHexStringResult != null) {
return verifyHexStringResult;
}

const numberTypes: KeyOfPolyjuiceTransaction[] = [
"nonce",
"gasPrice",
"gasLimit",
"value",
"v",
"r",
"s",
];

let polyTx: PolyjuiceTransaction;
try {
polyTx = decodeEthRawTx(rawTx);
} catch (err) {
logger.debug(`verify raw transaction:`, err);
return invalidParamsError(index, `rlp: invalid format`);
}

for (const t of numberTypes) {
const v = polyTx[t];
if (v.startsWith("0x00")) {
const msg = `rlp: non-canonical integer (leading zero bytes) for ${t}, receive: ${v}`;
logger.debug(msg);
return invalidParamsError(index, msg);
}
}

let encoded: HexString;
try {
encoded = encodePolyjuiceTransaction(polyTx);
} catch (err) {
logger.debug(`verify raw transaction:`, err);
return invalidParamsError(index, `rlp: invalid format`);
}
if (encoded !== rawTx) {
return invalidParamsError(index, `rlp: invalid format`);
}

return undefined;
}

//******* end of standalone verify function ********/

// some utils function
Expand Down
59 changes: 59 additions & 0 deletions web3/packages/api-server/src/rlp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { HexNumber, HexString } from "@ckb-lumos/base";
import { rlp } from "ethereumjs-util";

export interface PolyjuiceTransaction {
nonce: HexNumber;
gasPrice: HexNumber;
gasLimit: HexNumber;
to: HexString;
value: HexNumber;
data: HexString;
v: HexNumber;
r: HexString;
s: HexString;
}

export function toRlpNumber(num: HexNumber): bigint {
return num === "0x" ? 0n : BigInt(num);
}

export function decodeEthRawTx(ethRawTx: HexString): PolyjuiceTransaction {
const result: Buffer[] = rlp.decode(ethRawTx) as Buffer[];
if (result.length !== 9) {
throw new Error("decode eth raw transaction data error");
}

// todo: r might be "0x" which cause inconvenient for down-stream
const resultHex = result.map((r) => "0x" + Buffer.from(r).toString("hex"));
const [nonce, gasPrice, gasLimit, to, value, data, v, r, s] = resultHex;
return {
nonce,
gasPrice,
gasLimit,
to,
value,
data,
v,
r,
s,
};
}

export function encodePolyjuiceTransaction(tx: PolyjuiceTransaction) {
const { nonce, gasPrice, gasLimit, to, value, data, v, r, s } = tx;

const beforeEncode = [
toRlpNumber(nonce),
toRlpNumber(gasPrice),
toRlpNumber(gasLimit),
to,
toRlpNumber(value),
data,
toRlpNumber(v),
toRlpNumber(r),
toRlpNumber(s),
];

const result = rlp.encode(beforeEncode);
return "0x" + result.toString("hex");
}
45 changes: 45 additions & 0 deletions web3/packages/api-server/tests/methods/validators.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import test from "ava";

import { validators } from "../../src/methods/validator";
import { InvalidParamsError } from "../../src/methods/error";

test("validators.rawTransaction's s with leading zeros", (t) => {
const originRawTx =
"0xf8680485174876e8008302f1c8940000000000000000000000000000000000000000808083022df4a0aa4567c44b378929018ebd3100716f288dd17f616ff9418d7ef0341f3aef4ca0a00013d2f7290ba5aff8911b28871c8e6b624117a711dea4f1484e0dc9d587d60a";

const params = [originRawTx];

const result = validators.rawTransaction(params, 0);

t.true(result instanceof InvalidParamsError);
t.is(
result?.message,
"invalid argument 0: rlp: non-canonical integer (leading zero bytes) for s, receive: 0x0013d2f7290ba5aff8911b28871c8e6b624117a711dea4f1484e0dc9d587d60a"
);
});

test("validators.rawTranaction's r with leading zeros", (t) => {
const originRawTx =
"0xf8680485174876e8008302f45b940000000000000000000000000000000000000000808083022df4a000330af14634c7d18125258707de6b115ff990743d5c5fac35089e54ea4dfd60a01a9186f9b620063219709aadb6857f88702aa03d94850199c80d39ec090897a2";

const params = [originRawTx];

const result = validators.rawTransaction(params, 0);

t.true(result instanceof InvalidParamsError);
t.is(
result?.message,
"invalid argument 0: rlp: non-canonical integer (leading zero bytes) for r, receive: 0x00330af14634c7d18125258707de6b115ff990743d5c5fac35089e54ea4dfd60"
);
});

test("validators.rawTransaction valid", (t) => {
const originRawTx =
"0xf8670485174876e8008302f45b940000000000000000000000000000000000000000808083022df49f330af14634c7d18125258707de6b115ff990743d5c5fac35089e54ea4dfd60a01a9186f9b620063219709aadb6857f88702aa03d94850199c80d39ec090897a2";

const params = [originRawTx];

const result = validators.rawTransaction(params, 0);

t.is(result, undefined);
});