Skip to content

Commit 3594f8d

Browse files
authored
util: prefixed hex string type improvements (#3995)
* chore: revert startsWith0x * util: fix hexToBytes in usage * util: remoe redundant byte checking * chore: more type adjustments * format: linting * monorepo: more type issues * util: undo remove undefined * chore: more type fixes * client: remove typecasting * client: simplify typecasting * common: remove typecasting * chore: remove unused import * chore: address review comments * chore: remove unused var * chore: strictEqual
1 parent f5e4537 commit 3594f8d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+176
-489
lines changed

packages/binarytree/test/node/internalNode.spec.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,16 @@ import { equalsBytes, hexToBytes } from '@ethereumjs/util'
22
import { assert, describe, it } from 'vitest'
33

44
import { BinaryNodeType, InternalBinaryNode, decodeBinaryNode } from '../../src/index.ts'
5-
import {} from '../../src/types.ts'
65

76
describe('InternalBinaryNode', () => {
87
it('should round-trip encode and decode an internal node', () => {
98
// Create dummy child pointers:
109
const leftCanonicalChild = {
11-
hash: hexToBytes('0x' + '11'.repeat(32)),
10+
hash: hexToBytes(`0x${'11'.repeat(32)}`),
1211
path: [0, 1, 1, 0, 1, 0],
1312
}
1413
const rightCanonicalChild = {
15-
hash: hexToBytes('0x' + '22'.repeat(32)),
14+
hash: hexToBytes(`0x${'22'.repeat(32)}`),
1615
path: [1, 1, 0, 0],
1716
}
1817
const node = InternalBinaryNode.create([leftCanonicalChild, rightCanonicalChild])

packages/binarytree/test/node/stemNode.spec.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@ import { StemBinaryNode } from '../../src/node/stemNode.ts'
77
describe('StemBinaryNode', () => {
88
it('should round-trip encode and decode a stem node', () => {
99
// Create a 31-byte stem (for example, all 0x01 bytes)
10-
const stem = hexToBytes('0x' + '01'.repeat(31))
10+
const stem = hexToBytes(`0x${'01'.repeat(31)}`)
1111

1212
// Create an array of 256 possible values (initially all null)
1313
const values: (Uint8Array | null)[] = new Array(256).fill(null)
1414
// Set a few non-null values at specific indices
15-
const value3 = hexToBytes('0x' + '02'.repeat(32))
16-
const value100 = hexToBytes('0x' + '03'.repeat(32))
17-
const value255 = hexToBytes('0x' + '04'.repeat(32))
15+
const value3 = hexToBytes(`0x${'02'.repeat(32)}`)
16+
const value100 = hexToBytes(`0x${'03'.repeat(32)}`)
17+
const value255 = hexToBytes(`0x${'04'.repeat(32)}`)
1818
values[3] = value3
1919
values[100] = value100
2020
values[255] = value255

packages/block/src/block/constructors.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ import {
3131
executionPayloadFromBeaconPayload,
3232
} from '../index.ts'
3333

34-
import type { EthersProvider, PrefixedHexString, WithdrawalBytes } from '@ethereumjs/util'
34+
import type { EthersProvider, WithdrawalBytes } from '@ethereumjs/util'
3535
import type { BeaconPayloadJSON } from '../from-beacon-payload.ts'
3636
import type {
3737
BlockBytes,
@@ -339,7 +339,7 @@ export async function createBlockFromExecutionPayload(
339339
const txs = []
340340
for (const [index, serializedTx] of transactions.entries()) {
341341
try {
342-
const tx = createTxFromRLP(hexToBytes(serializedTx as PrefixedHexString), {
342+
const tx = createTxFromRLP(hexToBytes(serializedTx), {
343343
common: opts?.common,
344344
})
345345
txs.push(tx)
@@ -377,7 +377,7 @@ export async function createBlockFromExecutionPayload(
377377
throw Error('Missing executionWitness for EIP-6800 activated executionPayload')
378378
}
379379
// Verify blockHash matches payload
380-
if (!equalsBytes(block.hash(), hexToBytes(payload.blockHash as PrefixedHexString))) {
380+
if (!equalsBytes(block.hash(), hexToBytes(payload.blockHash))) {
381381
const validationError = `Invalid blockHash, expected: ${
382382
payload.blockHash
383383
}, received: ${bytesToHex(block.hash())}`

packages/block/test/block.spec.ts

Lines changed: 15 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@ import { Common, Hardfork, Mainnet, createCustomCommon } from '@ethereumjs/commo
22
import { RLP } from '@ethereumjs/rlp'
33
import {
44
goerliChainConfig,
5-
preLondonTestDataBlocks1,
6-
preLondonTestDataBlocks2,
5+
preLondonTestDataBlocks1RLP,
6+
preLondonTestDataBlocks2RLP,
77
testnetMergeChainConfig,
88
} from '@ethereumjs/testdata'
99
import { createLegacyTx } from '@ethereumjs/tx'
10-
import { KECCAK256_RLP_ARRAY, bytesToHex, equalsBytes, hexToBytes, toBytes } from '@ethereumjs/util'
10+
import { KECCAK256_RLP_ARRAY, bytesToHex, equalsBytes, hexToBytes } from '@ethereumjs/util'
1111
import { assert, describe, it } from 'vitest'
1212

1313
import { genTransactionsTrieRoot } from '../src/helpers.ts'
@@ -25,7 +25,7 @@ import {
2525
import { genesisHashesTestData } from './testdata/genesisHashesTest.ts'
2626
import { testdataFromRPCGoerliData } from './testdata/testdata-from-rpc-goerli.ts'
2727

28-
import type { NestedUint8Array, PrefixedHexString } from '@ethereumjs/util'
28+
import type { NestedUint8Array } from '@ethereumjs/util'
2929

3030
describe('[Block]: block functions', () => {
3131
it('should test block initialization', () => {
@@ -137,7 +137,7 @@ describe('[Block]: block functions', () => {
137137

138138
it('should test block validation on pow chain', async () => {
139139
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Istanbul })
140-
const blockRlp = hexToBytes(preLondonTestDataBlocks1.blocks[0].rlp as PrefixedHexString)
140+
const blockRlp = hexToBytes(preLondonTestDataBlocks1RLP.blockRLP)
141141
try {
142142
createBlockFromRLP(blockRlp, { common })
143143
assert.isTrue(true, 'should pass')
@@ -163,7 +163,7 @@ describe('[Block]: block functions', () => {
163163
}
164164

165165
it('should test transaction validation - invalid tx trie', async () => {
166-
const blockRlp = hexToBytes(preLondonTestDataBlocks1.blocks[0].rlp as PrefixedHexString)
166+
const blockRlp = hexToBytes(preLondonTestDataBlocks1RLP.blockRLP)
167167
const common = new Common({ chain: Mainnet, hardfork: Hardfork.London })
168168
const block = createBlockFromRLP(blockRlp, { common, freeze: false })
169169
await testTransactionValidation(block)
@@ -205,7 +205,7 @@ describe('[Block]: block functions', () => {
205205

206206
it('should test transaction validation with legacy tx in london', async () => {
207207
const common = new Common({ chain: Mainnet, hardfork: Hardfork.London })
208-
const blockRlp = hexToBytes(preLondonTestDataBlocks1.blocks[0].rlp as PrefixedHexString)
208+
const blockRlp = hexToBytes(preLondonTestDataBlocks1RLP.blockRLP)
209209
const block = createBlockFromRLP(blockRlp, { common, freeze: false })
210210
await testTransactionValidation(block)
211211
// @ts-expect-error -- Assigning to read-only property
@@ -219,7 +219,7 @@ describe('[Block]: block functions', () => {
219219

220220
it('should test uncles hash validation', async () => {
221221
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Istanbul })
222-
const blockRlp = hexToBytes(preLondonTestDataBlocks2.blocks[2].rlp as PrefixedHexString)
222+
const blockRlp = hexToBytes(preLondonTestDataBlocks2RLP.block2RLP)
223223
const block = createBlockFromRLP(blockRlp, { common, freeze: false })
224224
assert.equal(block.uncleHashIsValid(), true)
225225
// @ts-expect-error -- Assigning to read-only property
@@ -356,31 +356,23 @@ describe('[Block]: block functions', () => {
356356

357357
it('should return the same block data from raw()', () => {
358358
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Istanbul })
359-
const block = createBlockFromRLP(
360-
toBytes(preLondonTestDataBlocks2.blocks[2].rlp as PrefixedHexString),
361-
{
362-
common,
363-
},
364-
)
359+
const block = createBlockFromRLP(hexToBytes(preLondonTestDataBlocks2RLP.block2RLP), {
360+
common,
361+
})
365362
const createBlockFromRaw = createBlockFromBytesArray(block.raw(), { common })
366363
assert.isTrue(equalsBytes(block.hash(), createBlockFromRaw.hash()))
367364
})
368365

369366
it('should test toJSON', () => {
370367
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Istanbul })
371-
const block = createBlockFromRLP(
372-
toBytes(preLondonTestDataBlocks2.blocks[2].rlp as PrefixedHexString),
373-
{
374-
common,
375-
},
376-
)
368+
const block = createBlockFromRLP(hexToBytes(preLondonTestDataBlocks2RLP.block2RLP), {
369+
common,
370+
})
377371
assert.equal(typeof block.toJSON(), 'object')
378372
})
379373

380374
it('DAO hardfork', () => {
381-
const blockData = RLP.decode(
382-
preLondonTestDataBlocks2.blocks[0].rlp as PrefixedHexString,
383-
) as NestedUint8Array
375+
const blockData = RLP.decode(preLondonTestDataBlocks2RLP.block0RLP) as NestedUint8Array
384376
// Set block number from test block to mainnet DAO fork block 1920000
385377
blockData[0][8] = hexToBytes('0x1D4C00')
386378

packages/blockchain/test/index.spec.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
createBlockHeaderFromBytesArray,
66
} from '@ethereumjs/block'
77
import { Common, Hardfork, Holesky, Mainnet, Sepolia } from '@ethereumjs/common'
8-
import { goerliChainConfig, mainnetBlocks, preLondonTestDataBlocks1 } from '@ethereumjs/testdata'
8+
import { goerliChainConfig, mainnetBlocks, preLondonTestDataBlocks1RLP } from '@ethereumjs/testdata'
99
import { MapDB, bytesToHex, equalsBytes, hexToBytes, utf8ToBytes } from '@ethereumjs/util'
1010
import { assert, describe, it } from 'vitest'
1111

@@ -14,7 +14,6 @@ import { Blockchain, createBlockchain, createBlockchainFromBlocksData } from '..
1414
import { createTestDB, generateBlockchain, generateBlocks, isConsecutive } from './util.ts'
1515

1616
import type { Block, BlockOptions } from '@ethereumjs/block'
17-
import type { PrefixedHexString } from '@ethereumjs/util'
1817

1918
describe('blockchain test', () => {
2019
it('should not crash on getting head of a blockchain without a genesis', async () => {
@@ -581,15 +580,15 @@ describe('blockchain test', () => {
581580

582581
it('should add block with body', async () => {
583582
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Istanbul })
584-
const genesisRlp = hexToBytes(preLondonTestDataBlocks1.genesisRLP as PrefixedHexString)
583+
const genesisRlp = hexToBytes(preLondonTestDataBlocks1RLP.genesisRLP)
585584
const genesisBlock = createBlockFromRLP(genesisRlp, { common })
586585
const blockchain = await createBlockchain({
587586
validateBlocks: true,
588587
validateConsensus: false,
589588
genesisBlock,
590589
})
591590

592-
const blockRlp = hexToBytes(preLondonTestDataBlocks1.blocks[0].rlp as PrefixedHexString)
591+
const blockRlp = hexToBytes(preLondonTestDataBlocks1RLP.blockRLP)
593592
const block = createBlockFromRLP(blockRlp, { common })
594593
await blockchain.putBlock(block)
595594
})

packages/client/bin/utils.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ import { Event } from '../src/types.ts'
5252
import { parseMultiaddrs } from '../src/util/index.ts'
5353
import { setupMetrics } from '../src/util/metrics.ts'
5454

55-
import type { CustomCrypto, GenesisState } from '@ethereumjs/common'
55+
import type { CustomCrypto, GenesisState, GethGenesis } from '@ethereumjs/common'
5656
import type { Address, PrefixedHexString } from '@ethereumjs/util'
5757
import type { Logger } from '../src/logging.ts'
5858
import type { ClientOpts } from '../src/types.ts'
@@ -495,7 +495,7 @@ async function setupDevnet(prefundAddress: Address, args: ClientOpts) {
495495
epoch: 30000,
496496
},
497497
}
498-
const defaultChainData = {
498+
const defaultChainData: GethGenesis = {
499499
config: {
500500
chainId: 123456,
501501
homesteadBlock: 0,
@@ -521,6 +521,7 @@ async function setupDevnet(prefundAddress: Address, args: ClientOpts) {
521521
gasUsed: '0x0',
522522
parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000',
523523
baseFeePerGas: 7,
524+
alloc: {},
524525
}
525526
const extraData =
526527
args.dev === 'pow' ? '0x' + '0'.repeat(32) : '0x' + '0'.repeat(64) + addr + '0'.repeat(130)

packages/client/src/sync/fetcher/trienodefetcher.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ export class TrieNodeFetcher extends Fetcher<JobTask, Uint8Array[], Uint8Array>
347347
// add account node data to account trie
348348
const node = decodeMPTNode(nodeData)
349349
if (node instanceof LeafMPTNode) {
350-
const key = bytesToUnprefixedHex(pathToHexKey(path, node.key(), 'keybyte'))
350+
const key = bytesToHex(pathToHexKey(path, node.key(), 'keybyte'))
351351
ops.push({
352352
type: 'put',
353353
key: hexToBytes(key),
@@ -365,9 +365,7 @@ export class TrieNodeFetcher extends Fetcher<JobTask, Uint8Array[], Uint8Array>
365365
for (const [path, data] of pathToStorageNode) {
366366
const storageNode = decodeMPTNode(data)
367367
if (storageNode instanceof LeafMPTNode) {
368-
const storageKey = bytesToUnprefixedHex(
369-
pathToHexKey(path, storageNode.key(), 'keybyte'),
370-
)
368+
const storageKey = bytesToHex(pathToHexKey(path, storageNode.key(), 'keybyte'))
371369
storageTrieOps.push({
372370
type: 'put',
373371
key: hexToBytes(storageKey),

packages/client/src/util/vkt.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,11 @@ export async function generateVKTStateRoot(genesisState: GenesisState, common: C
1616
const state = new StatefulVerkleStateManager({ common })
1717
await state['_trie'].createRootNode()
1818
await state.checkpoint()
19-
for (const addressStr of Object.keys(genesisState)) {
19+
for (const addressStr of Object.keys(genesisState) as PrefixedHexString[]) {
2020
const addrState = genesisState[addressStr]
21-
let nonce, balance, code
21+
let nonce: PrefixedHexString | undefined
22+
let balance: PrefixedHexString | bigint
23+
let code: PrefixedHexString | undefined
2224
let storage: StoragePair[] | undefined
2325
if (Array.isArray(addrState)) {
2426
;[balance, code, storage, nonce] = addrState
@@ -51,8 +53,8 @@ export async function generateVKTStateRoot(genesisState: GenesisState, common: C
5153

5254
// Put account data
5355
const account = createPartialAccount({
54-
nonce: nonce as PrefixedHexString,
55-
balance: balance as PrefixedHexString,
56+
nonce,
57+
balance,
5658
codeHash,
5759
codeSize: codeBuf.byteLength,
5860
})

packages/client/test/integration/miner.spec.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
import { Hardfork, createCommonFromGethGenesis, parseGethGenesisState } from '@ethereumjs/common'
1+
import {
2+
type GethGenesis,
3+
Hardfork,
4+
createCommonFromGethGenesis,
5+
parseGethGenesisState,
6+
} from '@ethereumjs/common'
27
import { Address, bytesToHex, concatBytes, hexToBytes } from '@ethereumjs/util'
38
import { assert, describe, it } from 'vitest'
49

@@ -12,7 +17,7 @@ import type { EthereumClient } from '../../src/index.ts'
1217

1318
async function setupDevnet(prefundAddress: Address) {
1419
const addr = prefundAddress.toString().slice(2)
15-
const defaultChainData = {
20+
const defaultChainData: GethGenesis = {
1621
config: {
1722
chainId: 123456,
1823
homesteadBlock: 0,
@@ -37,6 +42,7 @@ async function setupDevnet(prefundAddress: Address) {
3742
gasUsed: '0x0',
3843
parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000',
3944
baseFeePerGas: 7,
45+
alloc: {},
4046
}
4147
const extraData = concatBytes(new Uint8Array(32), prefundAddress.toBytes(), new Uint8Array(65))
4248

packages/client/test/integration/pow.spec.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import { rmSync } from 'fs'
2-
import { Hardfork, createCommonFromGethGenesis, parseGethGenesisState } from '@ethereumjs/common'
2+
import {
3+
type GethGenesis,
4+
Hardfork,
5+
createCommonFromGethGenesis,
6+
parseGethGenesisState,
7+
} from '@ethereumjs/common'
38
import { assert, describe, it } from 'vitest'
49

510
import { Config } from '../../src/index.ts'
@@ -18,7 +23,7 @@ async function setupPowDevnet(prefundAddress: Address, cleanStart: boolean) {
1823
const addr = prefundAddress.toString().slice(2)
1924
const consensusConfig = { ethash: true }
2025

21-
const defaultChainData = {
26+
const defaultChainData: GethGenesis = {
2227
config: {
2328
chainId: 123456,
2429
homesteadBlock: 0,
@@ -44,9 +49,10 @@ async function setupPowDevnet(prefundAddress: Address, cleanStart: boolean) {
4449
gasUsed: '0x0',
4550
parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000',
4651
baseFeePerGas: 7,
52+
alloc: {},
4753
}
48-
const extraData = '0x' + '0'.repeat(32)
49-
const chainData = {
54+
const extraData = `0x${'0'.repeat(32)}`
55+
const chainData: GethGenesis = {
5056
...defaultChainData,
5157
extraData,
5258
alloc: { [addr]: { balance: '0x10000000000000000000' } },

0 commit comments

Comments
 (0)