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

monorepo: PrefixedHexString related type fixes #3357

Merged
merged 18 commits into from
Apr 22, 2024
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
1 change: 0 additions & 1 deletion packages/block/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,6 @@ export interface JsonRpcBlock {
executionWitness?: VerkleExecutionWitness | null // If Verkle is enabled for this block
}

// Note: all these strings are 0x-prefixed
export type WithdrawalV1 = {
index: PrefixedHexString // Quantity, 8 Bytes
validatorIndex: PrefixedHexString // Quantity, 8 bytes
Expand Down
2 changes: 1 addition & 1 deletion packages/block/test/eip1559block.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ describe('EIP1559 tests', () => {
maxPriorityFeePerGas: BigInt(0),
},
{ common }
).sign(hexToBytes('0x' + '46'.repeat(32)))
).sign(hexToBytes(`0x${'46'.repeat(32)}`))
const block = Block.fromBlockData(
{
header: {
Expand Down
6 changes: 3 additions & 3 deletions packages/block/test/eip4895block.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ common.hardforkBlock = function (hardfork: string | undefined) {
describe('EIP4895 tests', () => {
it('should correctly generate withdrawalsRoot', async () => {
// get withdwalsArray
const gethBlockBytesArray = RLP.decode(hexToBytes('0x' + gethWithdrawals8BlockRlp))
const gethBlockBytesArray = RLP.decode(hexToBytes(`0x${gethWithdrawals8BlockRlp}`))
const withdrawals = (gethBlockBytesArray[3] as WithdrawalBytes[]).map((wa) =>
Withdrawal.fromValuesArray(wa)
)
Expand Down Expand Up @@ -160,7 +160,7 @@ describe('EIP4895 tests', () => {
const withdrawal = <WithdrawalData>{
index: BigInt(0),
validatorIndex: BigInt(0),
address: new Address(hexToBytes('0x' + '20'.repeat(20))),
address: new Address(hexToBytes(`0x${'20'.repeat(20)}`)),
amount: BigInt(1000),
}

Expand All @@ -185,7 +185,7 @@ describe('EIP4895 tests', () => {
const withdrawal2 = <WithdrawalData>{
index: BigInt(1),
validatorIndex: BigInt(11),
address: new Address(hexToBytes('0x' + '30'.repeat(20))),
address: new Address(hexToBytes(`0x${'30'.repeat(20)}`)),
amount: BigInt(2000),
}

Expand Down
17 changes: 12 additions & 5 deletions packages/block/test/from-beacon-payload.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import * as payload87335 from './testdata/payload-slot-87335.json'
import * as payload87475 from './testdata/payload-slot-87475.json'
import * as testnetVerkleKaustinen from './testdata/testnetVerkleKaustinen.json'

import type { BeaconPayloadJson, VerkleExecutionWitness } from '../src/index.js'

describe('[fromExecutionPayloadJson]: 4844 devnet 5', () => {
let common: Common
beforeAll(async () => {
Expand All @@ -27,7 +29,7 @@ describe('[fromExecutionPayloadJson]: 4844 devnet 5', () => {
it('reconstruct cancun block with blob txs', async () => {
for (const payload of [payload87335, payload87475]) {
try {
const block = await Block.fromBeaconPayloadJson(payload, { common })
const block = await Block.fromBeaconPayloadJson(payload as BeaconPayloadJson, { common })
const parentHeader = BlockHeader.fromHeaderData(
{ excessBlobGas: BigInt(0), blobGasUsed: block.header.excessBlobGas! + BigInt(393216) },
{ common }
Expand All @@ -44,7 +46,10 @@ describe('[fromExecutionPayloadJson]: 4844 devnet 5', () => {
try {
// construct a payload with differing block hash
await Block.fromBeaconPayloadJson(
{ ...payload87335, block_hash: payload87475.block_hash },
{
...payload87335,
block_hash: payload87475.block_hash,
} as BeaconPayloadJson,
{ common }
)
assert.fail(`should have failed constructing the block`)
Expand All @@ -61,7 +66,7 @@ describe('[fromExecutionPayloadJson]: 4844 devnet 5', () => {
{
...payload87475,
block_hash: '0x573714bdd0ca5e47bc32008751c4fc74237f8cb354fbc1475c1d0ece38236ea4',
},
} as BeaconPayloadJson,
{ common }
)
const parentHeader = BlockHeader.fromHeaderData({ excessBlobGas: BigInt(0) }, { common })
Expand All @@ -84,12 +89,14 @@ describe('[fromExecutionPayloadJson]: kaustinen', () => {
})
it('reconstruct kaustinen block', async () => {
assert.ok(common.isActivatedEIP(6800), 'verkle eip should be activated')
const block = await Block.fromBeaconPayloadJson(payloadKaustinen, { common })
const block = await Block.fromBeaconPayloadJson(payloadKaustinen as BeaconPayloadJson, {
common,
})
// the witness object in payload has camel casing for now
// the current block hash doesn't include witness data so deep match is required
assert.deepEqual(
block.executionWitness,
payloadKaustinen.execution_witness,
payloadKaustinen.execution_witness as VerkleExecutionWitness,
'execution witness should match'
)
})
Expand Down
44 changes: 25 additions & 19 deletions packages/block/test/from-rpc.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,22 @@ import * as uncleBlockData from './testdata/testdata-from-rpc-with-uncles_uncle-
import * as blockDataWithWithdrawals from './testdata/testdata-from-rpc-with-withdrawals.json'
import * as blockData from './testdata/testdata-from-rpc.json'

import type { JsonRpcBlock } from '../src/index.js'
import type { LegacyTransaction } from '@ethereumjs/tx'
import type { PrefixedHexString } from '@ethereumjs/util'

describe('[fromRPC]: block #2924874', () => {
const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Istanbul })

it('should create a block with transactions with valid signatures', () => {
const block = blockFromRpc(blockData, [], { common })
const block = blockFromRpc(blockData as JsonRpcBlock, [], { common })
const allValid = block.transactions.every((tx) => tx.verifySignature())
assert.equal(allValid, true, 'all transaction signatures are valid')
})

it('should create a block header with the correct hash', () => {
const block = blockHeaderFromRpc(blockData, { common })
const hash = hexToBytes(blockData.hash)
const block = blockHeaderFromRpc(blockData as JsonRpcBlock, { common })
const hash = hexToBytes(blockData.hash as PrefixedHexString)
assert.ok(equalsBytes(block.hash(), hash))
})
})
Expand All @@ -44,7 +46,7 @@ describe('[fromRPC]:', () => {
const blockDataTransactionValueAsInteger = blockData
blockDataTransactionValueAsInteger.transactions[0].value = valueAsIntegerString
const blockFromTransactionValueAsInteger = blockFromRpc(
blockDataTransactionValueAsInteger,
blockDataTransactionValueAsInteger as JsonRpcBlock,
undefined,
{ common }
)
Expand All @@ -60,7 +62,7 @@ describe('[fromRPC]:', () => {
const blockDataTransactionGasPriceAsInteger = blockData
blockDataTransactionGasPriceAsInteger.transactions[0].gasPrice = gasPriceAsIntegerString
const blockFromTransactionGasPriceAsInteger = blockFromRpc(
blockDataTransactionGasPriceAsInteger,
blockDataTransactionGasPriceAsInteger as JsonRpcBlock,
undefined,
{ common }
)
Expand All @@ -74,9 +76,13 @@ describe('[fromRPC]:', () => {

it('should create a block given json data that includes a difficulty parameter of type integer string', () => {
const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.London })
const blockDifficultyAsInteger = blockFromRpc(blockDataDifficultyAsInteger, undefined, {
common,
})
const blockDifficultyAsInteger = blockFromRpc(
blockDataDifficultyAsInteger as JsonRpcBlock,
undefined,
{
common,
}
)
assert.equal(
blockDifficultyAsInteger.header.difficulty.toString(),
blockDataDifficultyAsInteger.difficulty
Expand All @@ -85,7 +91,7 @@ describe('[fromRPC]:', () => {

it('should create a block from london hardfork', () => {
const common = new Common({ chain: Chain.Goerli, hardfork: Hardfork.London })
const block = blockFromRpc(testDataFromRpcGoerliLondon, [], { common })
const block = blockFromRpc(testDataFromRpcGoerliLondon as JsonRpcBlock, [], { common })
assert.equal(
`0x${block.header.baseFeePerGas?.toString(16)}`,
testDataFromRpcGoerliLondon.baseFeePerGas
Expand All @@ -95,19 +101,19 @@ describe('[fromRPC]:', () => {

it('should create a block with uncles', () => {
const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Istanbul })
const block = blockFromRpc(blockDataWithUncles, [uncleBlockData], { common })
const block = blockFromRpc(blockDataWithUncles as JsonRpcBlock, [uncleBlockData], { common })
assert.ok(block.uncleHashIsValid())
})

it('should create a block with EIP-4896 withdrawals', () => {
const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Shanghai })
const block = blockFromRpc(blockDataWithWithdrawals, [], { common })
const block = blockFromRpc(blockDataWithWithdrawals as JsonRpcBlock, [], { common })
assert.ok(block.withdrawalsTrieIsValid())
})

it('should create a block header with the correct hash when EIP-4896 withdrawals are present', () => {
const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Shanghai })
const block = blockHeaderFromRpc(blockDataWithWithdrawals, { common })
const block = blockHeaderFromRpc(blockDataWithWithdrawals as JsonRpcBlock, { common })
const hash = blockDataWithWithdrawals.hash
assert.equal(bytesToHex(block.hash()), hash)
})
Expand All @@ -116,25 +122,25 @@ describe('[fromRPC]:', () => {
describe('[fromRPC] - Alchemy/Infura API block responses', () => {
it('should create pre merge block from Alchemy API response to eth_getBlockByHash', () => {
const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.London })
const block = blockFromRpc(alchemy14151203, [], { common })
const block = blockFromRpc(alchemy14151203 as JsonRpcBlock, [], { common })
assert.equal(bytesToHex(block.hash()), alchemy14151203.hash)
})

it('should create pre and post merge blocks from Infura API responses to eth_getBlockByHash and eth_getBlockByNumber', () => {
const common = new Common({ chain: Chain.Mainnet })
let block = blockFromRpc(infura2000004woTxs, [], { common, setHardfork: true })
let block = blockFromRpc(infura2000004woTxs as JsonRpcBlock, [], { common, setHardfork: true })
assert.equal(
bytesToHex(block.hash()),
infura2000004woTxs.hash,
'created premerge block w/o txns'
)
block = blockFromRpc(infura2000004wTxs, [], { common, setHardfork: true })
block = blockFromRpc(infura2000004wTxs as JsonRpcBlock, [], { common, setHardfork: true })
assert.equal(
bytesToHex(block.hash()),
infura2000004wTxs.hash,
'created premerge block with txns'
)
block = blockFromRpc(infura15571241woTxs, [], {
block = blockFromRpc(infura15571241woTxs as JsonRpcBlock, [], {
common,
setHardfork: 58750000000000000000000n,
})
Expand All @@ -144,7 +150,7 @@ describe('[fromRPC] - Alchemy/Infura API block responses', () => {
'created post merge block without txns'
)

block = blockFromRpc(infura15571241wTxs, [], {
block = blockFromRpc(infura15571241wTxs as JsonRpcBlock, [], {
common,
setHardfork: 58750000000000000000000n,
})
Expand All @@ -157,8 +163,8 @@ describe('[fromRPC] - Alchemy/Infura API block responses', () => {

it('should correctly parse a cancun block over rpc', () => {
const common = new Common({ chain: Chain.Goerli, hardfork: Hardfork.Cancun })
const block = blockHeaderFromRpc(infuraGoerliBlock10536893, { common })
const hash = hexToBytes(infuraGoerliBlock10536893.hash)
const block = blockHeaderFromRpc(infuraGoerliBlock10536893 as JsonRpcBlock, { common })
const hash = hexToBytes(infuraGoerliBlock10536893.hash as PrefixedHexString)
assert.ok(equalsBytes(block.hash(), hash))
})
})
Expand Down
12 changes: 7 additions & 5 deletions packages/block/test/header.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
concatBytes,
equalsBytes,
hexToBytes,
toBytes,
zeros,
} from '@ethereumjs/util'
import { assert, describe, it } from 'vitest'
Expand All @@ -21,6 +20,7 @@ import * as blocksGoerli from './testdata/blocks_goerli.json'
import * as blocksMainnet from './testdata/blocks_mainnet.json'

import type { CliqueConfig } from '@ethereumjs/common'
import type { PrefixedHexString } from '@ethereumjs/util'

describe('[Block]: Header functions', () => {
it('should create with default constructor', () => {
Expand Down Expand Up @@ -457,12 +457,14 @@ describe('[Block]: Header functions', () => {
const bcBlockGasLimitTestData = testData.tests.BlockGasLimit2p63m1

for (const key of Object.keys(bcBlockGasLimitTestData)) {
const genesisRlp = toBytes(
bcBlockGasLimitTestData[key as keyof typeof bcBlockGasLimitTestData].genesisRLP
const genesisRlp = hexToBytes(
bcBlockGasLimitTestData[key as keyof typeof bcBlockGasLimitTestData]
.genesisRLP as PrefixedHexString
)
const parentBlock = Block.fromRLPSerializedBlock(genesisRlp, { common })
const blockRlp = toBytes(
bcBlockGasLimitTestData[key as keyof typeof bcBlockGasLimitTestData].blocks[0].rlp
const blockRlp = hexToBytes(
bcBlockGasLimitTestData[key as keyof typeof bcBlockGasLimitTestData].blocks[0]
.rlp as PrefixedHexString
)
const block = Block.fromRLPSerializedBlock(blockRlp, { common })
assert.doesNotThrow(() => block.validateGasLimit(parentBlock))
Expand Down
9 changes: 5 additions & 4 deletions packages/blockchain/test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import blocksData from './testdata/blocks_mainnet.json'
import * as testDataPreLondon from './testdata/testdata_pre-london.json'
import { createTestDB, generateBlockchain, generateBlocks, isConsecutive } from './util.js'

import type { BlockOptions } from '@ethereumjs/block'
import type { BlockData, BlockOptions } from '@ethereumjs/block'
import type { PrefixedHexString } from '@ethereumjs/util'

describe('blockchain test', () => {
it('should not crash on getting head of a blockchain without a genesis', async () => {
Expand Down Expand Up @@ -54,7 +55,7 @@ describe('blockchain test', () => {

it('should initialize correctly with Blockchain.fromBlocksData()', async () => {
const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Chainstart })
const blockchain = await Blockchain.fromBlocksData(blocksData, {
const blockchain = await Blockchain.fromBlocksData(blocksData as BlockData[], {
validateBlocks: true,
validateConsensus: false,
common,
Expand Down Expand Up @@ -573,15 +574,15 @@ describe('blockchain test', () => {

it('should add block with body', async () => {
const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Istanbul })
const genesisRlp = hexToBytes(testDataPreLondon.genesisRLP)
const genesisRlp = hexToBytes(testDataPreLondon.genesisRLP as PrefixedHexString)
const genesisBlock = Block.fromRLPSerializedBlock(genesisRlp, { common })
const blockchain = await Blockchain.create({
validateBlocks: true,
validateConsensus: false,
genesisBlock,
})

const blockRlp = hexToBytes(testDataPreLondon.blocks[0].rlp)
const blockRlp = hexToBytes(testDataPreLondon.blocks[0].rlp as PrefixedHexString)
const block = Block.fromRLPSerializedBlock(blockRlp, { common })
await blockchain.putBlock(block)
})
Expand Down
4 changes: 2 additions & 2 deletions packages/client/bin/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ const args: ClientOpts = yargs
.option('verkleGenesisStateRoot', {
describe: 'State root of the verkle genesis genesis (experimental)',
string: true,
coerce: (customGenesisStateRoot: string) => hexToBytes(customGenesisStateRoot),
coerce: (customGenesisStateRoot: PrefixedHexString) => hexToBytes(customGenesisStateRoot),
})
.option('gethGenesis', {
describe: 'Import a geth genesis file for running a custom network',
Expand Down Expand Up @@ -816,7 +816,7 @@ async function inputAccounts() {
}
} else {
const acc = readFileSync(path.resolve(args.unlock!), 'utf-8').replace(/(\r\n|\n|\r)/gm, '')
const privKey = hexToBytes('0x' + acc) // See docs: acc has to be non-zero prefixed in the file
const privKey = hexToBytes(`0x${acc}`) // See docs: acc has to be non-zero prefixed in the file
const derivedAddress = Address.fromPrivateKey(privKey)
accounts.push([derivedAddress, privKey])
}
Expand Down
2 changes: 1 addition & 1 deletion packages/client/bin/startRpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ function parseJwtSecret(config: Config, jwtFilePath?: string): Uint8Array {
if (jwtSecretHex === undefined || jwtSecretHex.length !== 64) {
throw Error('Need a valid 256 bit hex encoded secret')
}
jwtSecret = hexToBytes('0x' + jwtSecretHex)
jwtSecret = hexToBytes(`0x${jwtSecretHex}`)
} else {
const folderExists = existsSync(config.datadir)
if (!folderExists) {
Expand Down
3 changes: 2 additions & 1 deletion packages/client/src/execution/vmexecution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { ReceiptsManager } from './receipt'

import type { ExecutionOptions } from './execution'
import type { Block } from '@ethereumjs/block'
import type { PrefixedHexString } from '@ethereumjs/util'
import type { RunBlockOpts, TxReceipt } from '@ethereumjs/vm'

export enum ExecStatus {
Expand Down Expand Up @@ -474,7 +475,7 @@ export class VMExecution extends Execution {
return true
}

async savePreimages(preimages: Map<string, Uint8Array>) {
async savePreimages(preimages: Map<PrefixedHexString, Uint8Array>) {
if (this.preimagesManager !== undefined) {
for (const [key, preimage] of preimages) {
await this.preimagesManager.savePreimage(hexToBytes(key), preimage)
Expand Down
Loading
Loading