diff --git a/package-lock.json b/package-lock.json index efe96a9f05..2cc6aea911 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14309,6 +14309,18 @@ "semver": "bin/semver.js" } }, + "node_modules/split": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/split/-/split-1.0.1.tgz", + "integrity": "sha512-mTyOoPbrivtXnwnIxZRFYRrPNtEFKlpB2fvjSnCQUiAA6qAZzqwna5envK4uk6OIeP17CsdF3rSBGYVBsU0Tkg==", + "dev": true, + "dependencies": { + "through": "2" + }, + "engines": { + "node": "*" + } + }, "node_modules/split2": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", @@ -16842,7 +16854,8 @@ "minimist": "^1.2.5", "node-dir": "^0.1.17", "rollup-plugin-visualizer": "^5.12.0", - "solc": "^0.8.1" + "solc": "^0.8.1", + "split": "^1.0.1" }, "engines": { "node": ">=18" diff --git a/packages/block/examples/simple.ts b/packages/block/examples/simple.ts index c94aaa3f72..c03ee2b3a0 100644 --- a/packages/block/examples/simple.ts +++ b/packages/block/examples/simple.ts @@ -1,4 +1,4 @@ -import { createHeader } from '@ethereumjs/block' +import { createBlockHeader } from '@ethereumjs/block' import { bytesToHex } from '@ethereumjs/util' import type { HeaderData } from '@ethereumjs/block' @@ -9,5 +9,5 @@ const headerData: HeaderData = { gasLimit: 8000000, timestamp: 1562422144, } -const header = createHeader(headerData) +const header = createBlockHeader(headerData) console.log(`Created block header with hash=${bytesToHex(header.hash())}`) diff --git a/packages/block/src/constructors.ts b/packages/block/src/constructors.ts index 0ebe25e67a..c6a413cb6e 100644 --- a/packages/block/src/constructors.ts +++ b/packages/block/src/constructors.ts @@ -62,7 +62,7 @@ import type { * @param headerData * @param opts */ -export function createHeader(headerData: HeaderData = {}, opts: BlockOptions = {}) { +export function createBlockHeader(headerData: HeaderData = {}, opts: BlockOptions = {}) { return new BlockHeader(headerData, opts) } @@ -72,11 +72,14 @@ export function createHeader(headerData: HeaderData = {}, opts: BlockOptions = { * @param values * @param opts */ -export function createHeaderFromValuesArray(values: BlockHeaderBytes, opts: BlockOptions = {}) { +export function createBlockHeaderFromValuesArray( + values: BlockHeaderBytes, + opts: BlockOptions = {}, +) { const headerData = valuesArrayToHeaderData(values) const { number, baseFeePerGas, excessBlobGas, blobGasUsed, parentBeaconBlockRoot, requestsRoot } = headerData - const header = createHeader(headerData, opts) + const header = createBlockHeader(headerData, opts) if (header.common.isActivatedEIP(1559) && baseFeePerGas === undefined) { const eip1559ActivationBlock = bigIntToBytes(header.common.eipBlock(1559)!) if ( @@ -109,12 +112,15 @@ export function createHeaderFromValuesArray(values: BlockHeaderBytes, opts: Bloc * @param serializedHeaderData * @param opts */ -export function createHeaderFromRLP(serializedHeaderData: Uint8Array, opts: BlockOptions = {}) { +export function createBlockHeaderFromRLP( + serializedHeaderData: Uint8Array, + opts: BlockOptions = {}, +) { const values = RLP.decode(serializedHeaderData) if (!Array.isArray(values)) { throw new Error('Invalid serialized header input. Must be array') } - return createHeaderFromValuesArray(values as Uint8Array[], opts) + return createBlockHeaderFromValuesArray(values as Uint8Array[], opts) } /** @@ -133,7 +139,7 @@ export function createBlock(blockData: BlockData = {}, opts?: BlockOptions) { requests: clRequests, } = blockData - const header = createHeader(headerData, opts) + const header = createBlockHeader(headerData, opts) // parse transactions const transactions = [] @@ -160,7 +166,7 @@ export function createBlock(blockData: BlockData = {}, opts?: BlockOptions) { uncleOpts.setHardfork = true } for (const uhData of uhsData ?? []) { - const uh = createHeader(uhData, uncleOpts) + const uh = createBlockHeader(uhData, uncleOpts) uncleHeaders.push(uh) } @@ -194,7 +200,7 @@ export function createBlockFromValuesArray(values: BlockBytes, opts?: BlockOptio // First try to load header so that we can use its common (in case of setHardfork being activated) // to correctly make checks on the hardforks const [headerData, txsData, uhsData, ...valuesTail] = values - const header = createHeaderFromValuesArray(headerData, opts) + const header = createBlockHeaderFromValuesArray(headerData, opts) // conditional assignment of rest of values and splicing them out from the valuesTail const withdrawalBytes = header.common.isActivatedEIP(4895) @@ -259,7 +265,7 @@ export function createBlockFromValuesArray(values: BlockBytes, opts?: BlockOptio uncleOpts.setHardfork = true } for (const uncleHeaderData of uhsData ?? []) { - uncleHeaders.push(createHeaderFromValuesArray(uncleHeaderData, uncleOpts)) + uncleHeaders.push(createBlockHeaderFromValuesArray(uncleHeaderData, uncleOpts)) } const withdrawals = (withdrawalBytes as WithdrawalBytes[]) diff --git a/packages/block/src/header.ts b/packages/block/src/header.ts index 06cdb01c4f..88830ab200 100644 --- a/packages/block/src/header.ts +++ b/packages/block/src/header.ts @@ -92,7 +92,7 @@ export class BlockHeader { * This constructor takes the values, validates them, assigns them and freezes the object. * * @deprecated Use the public static factory methods to assist in creating a Header object from - * varying data types. For a default empty header, use {@link createHeader}. + * varying data types. For a default empty header, use {@link createBlockHeader}. * */ constructor(headerData: HeaderData, opts: BlockOptions = {}) { diff --git a/packages/block/test/clique.spec.ts b/packages/block/test/clique.spec.ts index 787a605cba..e7af1e298a 100644 --- a/packages/block/test/clique.spec.ts +++ b/packages/block/test/clique.spec.ts @@ -2,13 +2,13 @@ import { Common, Goerli, Hardfork } from '@ethereumjs/common' import { Address, createZeroAddress, hexToBytes } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' -import { createHeader } from '../src/constructors.js' +import { createBlockHeader } from '../src/constructors.js' describe('[Header]: Clique PoA Functionality', () => { const common = new Common({ chain: Goerli, hardfork: Hardfork.Chainstart }) it('Header Data', () => { - let header = createHeader({ number: 1 }) + let header = createBlockHeader({ number: 1 }) assert.throws( () => { header.cliqueIsEpochTransition() @@ -18,13 +18,13 @@ describe('[Header]: Clique PoA Functionality', () => { 'cliqueIsEpochTransition() -> should throw on PoW networks', ) - header = createHeader({ extraData: new Uint8Array(97) }, { common }) + header = createBlockHeader({ extraData: new Uint8Array(97) }, { common }) assert.ok( header.cliqueIsEpochTransition(), 'cliqueIsEpochTransition() -> should indicate an epoch transition for the genesis block', ) - header = createHeader({ number: 1, extraData: new Uint8Array(97) }, { common }) + header = createBlockHeader({ number: 1, extraData: new Uint8Array(97) }, { common }) assert.notOk( header.cliqueIsEpochTransition(), 'cliqueIsEpochTransition() -> should correctly identify a non-epoch block', @@ -48,7 +48,7 @@ describe('[Header]: Clique PoA Functionality', () => { 'cliqueEpochTransitionSigners() -> should throw on non-epch block', ) - header = createHeader({ number: 60000, extraData: new Uint8Array(137) }, { common }) + header = createBlockHeader({ number: 60000, extraData: new Uint8Array(137) }, { common }) assert.ok( header.cliqueIsEpochTransition(), 'cliqueIsEpochTransition() -> should correctly identify an epoch block', @@ -89,7 +89,7 @@ describe('[Header]: Clique PoA Functionality', () => { it('Signing', () => { const cliqueSigner = A.privateKey - let header = createHeader( + let header = createBlockHeader( { number: 1, extraData: new Uint8Array(97) }, { common, freeze: false, cliqueSigner }, ) @@ -98,7 +98,7 @@ describe('[Header]: Clique PoA Functionality', () => { assert.ok(header.cliqueVerifySignature([A.address]), 'should verify signature') assert.ok(header.cliqueSigner().equals(A.address), 'should recover the correct signer address') - header = createHeader({ extraData: new Uint8Array(97) }, { common }) + header = createBlockHeader({ extraData: new Uint8Array(97) }, { common }) assert.ok( header.cliqueSigner().equals(createZeroAddress()), 'should return zero address on default block', diff --git a/packages/block/test/eip1559block.spec.ts b/packages/block/test/eip1559block.spec.ts index 4120836dd2..b01ccbeb29 100644 --- a/packages/block/test/eip1559block.spec.ts +++ b/packages/block/test/eip1559block.spec.ts @@ -3,7 +3,7 @@ import { create1559FeeMarketTx } from '@ethereumjs/tx' import { hexToBytes } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' -import { createBlock, createHeader } from '../src/constructors.js' +import { createBlock, createBlockHeader } from '../src/constructors.js' // Test data from Besu (retrieved via Discord) // Older version at https://github.com/abdelhamidbakhta/besu/blob/bf54b6c0b40d3015fc85ff9b078fbc26592d80c0/ethereum/core/src/test/resources/org/hyperledger/besu/ethereum/core/fees/basefee-test.json import { paramsBlock } from '../src/params.js' @@ -36,7 +36,7 @@ describe('EIP1559 tests', () => { const common = new Common({ chain: Mainnet, hardfork: Hardfork.Istanbul }) assert.throws( () => { - createHeader( + createBlockHeader( { number: BigInt(1), parentHash: genesis.hash(), @@ -57,7 +57,7 @@ describe('EIP1559 tests', () => { it('Header -> genericFormatValidation checks', async () => { try { - createHeader( + createBlockHeader( { number: BigInt(1), parentHash: genesis.hash(), @@ -81,7 +81,7 @@ describe('EIP1559 tests', () => { } try { - const header = createHeader( + const header = createBlockHeader( { number: BigInt(1), parentHash: genesis.hash(), @@ -127,7 +127,7 @@ describe('EIP1559 tests', () => { it('Header -> validate()', async () => { try { - createHeader( + createBlockHeader( { baseFeePerGas: BigInt(1000), number: BigInt(1), @@ -182,7 +182,7 @@ describe('EIP1559 tests', () => { it('Header -> validate() -> gas usage', async () => { try { - createHeader( + createBlockHeader( { number: BigInt(1), parentHash: genesis.hash(), @@ -205,7 +205,7 @@ describe('EIP1559 tests', () => { }) it('Header -> validate() -> gas usage', async () => { - createHeader( + createBlockHeader( { number: BigInt(1), parentHash: genesis.hash(), @@ -241,7 +241,7 @@ describe('EIP1559 tests', () => { it('Header -> validate() -> gasLimit -> success cases', async () => { let parentGasLimit = genesis.header.gasLimit * BigInt(2) - createHeader( + createBlockHeader( { number: BigInt(1), parentHash: genesis.hash(), @@ -257,7 +257,7 @@ describe('EIP1559 tests', () => { assert.ok(true, 'should not throw if gas limit is between bounds (HF transition block)') - createHeader( + createBlockHeader( { number: BigInt(1), parentHash: genesis.hash(), @@ -274,7 +274,7 @@ describe('EIP1559 tests', () => { assert.ok(true, 'should not throw if gas limit is between bounds (HF transition block)') parentGasLimit = block1.header.gasLimit - createHeader( + createBlockHeader( { number: BigInt(2), parentHash: block1.hash(), @@ -290,7 +290,7 @@ describe('EIP1559 tests', () => { assert.ok(true, 'should not throw if gas limit is between bounds (post-HF transition block)') - createHeader( + createBlockHeader( { number: BigInt(2), parentHash: block1.hash(), @@ -309,7 +309,7 @@ describe('EIP1559 tests', () => { it('Header -> validateGasLimit() -> error cases', async () => { let parentGasLimit = genesis.header.gasLimit * BigInt(2) - let header = createHeader( + let header = createBlockHeader( { number: BigInt(1), parentHash: genesis.hash(), @@ -333,7 +333,7 @@ describe('EIP1559 tests', () => { } parentGasLimit = block1.header.gasLimit - header = createHeader( + header = createBlockHeader( { number: BigInt(2), parentHash: block1.hash(), @@ -359,7 +359,7 @@ describe('EIP1559 tests', () => { it('Header -> validateGasLimit() -> error cases', async () => { let parentGasLimit = genesis.header.gasLimit * BigInt(2) - let header = createHeader( + let header = createBlockHeader( { number: BigInt(1), parentHash: genesis.hash(), @@ -383,7 +383,7 @@ describe('EIP1559 tests', () => { } parentGasLimit = block1.header.gasLimit - header = createHeader( + header = createBlockHeader( { number: BigInt(2), parentHash: block1.hash(), @@ -452,7 +452,7 @@ describe('EIP1559 tests', () => { it('Header -> calcNextBaseFee()', () => { for (let index = 0; index < eip1559BaseFee.length; index++) { const item = eip1559BaseFee[index] - const result = createHeader( + const result = createBlockHeader( { baseFeePerGas: BigInt(item.parentBaseFee), gasUsed: BigInt(item.parentGasUsed), @@ -466,7 +466,7 @@ describe('EIP1559 tests', () => { }) it('Header -> toJSON()', () => { - const header = createHeader( + const header = createBlockHeader( { number: BigInt(3), parentHash: genesis.hash(), diff --git a/packages/block/test/eip4788block.spec.ts b/packages/block/test/eip4788block.spec.ts index a2352b5128..bb4bf0f0e4 100644 --- a/packages/block/test/eip4788block.spec.ts +++ b/packages/block/test/eip4788block.spec.ts @@ -2,7 +2,7 @@ import { Common, Hardfork, Mainnet } from '@ethereumjs/common' import { bytesToHex, zeros } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' -import { createBlock, createHeader } from '../src/constructors.js' +import { createBlock, createBlockHeader } from '../src/constructors.js' describe('EIP4788 header tests', () => { it('should work', () => { @@ -11,7 +11,7 @@ describe('EIP4788 header tests', () => { assert.throws( () => { - createHeader( + createBlockHeader( { parentBeaconBlockRoot: zeros(32), }, @@ -27,7 +27,7 @@ describe('EIP4788 header tests', () => { assert.throws( () => { - createHeader( + createBlockHeader( { blobGasUsed: 1n, }, @@ -41,7 +41,7 @@ describe('EIP4788 header tests', () => { 'should throw when setting blobGasUsed with EIP4844 not being activated', ) assert.doesNotThrow(() => { - createHeader( + createBlockHeader( { excessBlobGas: 0n, blobGasUsed: 0n, @@ -56,7 +56,7 @@ describe('EIP4788 header tests', () => { const block = createBlock( { - header: createHeader({}, { common }), + header: createBlockHeader({}, { common }), }, { common, skipConsensusFormatValidation: true }, ) diff --git a/packages/block/test/eip4844block.spec.ts b/packages/block/test/eip4844block.spec.ts index 4f91927f8f..d3c5c6542b 100644 --- a/packages/block/test/eip4844block.spec.ts +++ b/packages/block/test/eip4844block.spec.ts @@ -9,7 +9,7 @@ import { import { loadKZG } from 'kzg-wasm' import { assert, beforeAll, describe, it } from 'vitest' -import { createBlock, createHeader } from '../src/constructors.js' +import { createBlock, createBlockHeader } from '../src/constructors.js' import { fakeExponential, getNumBlobs } from '../src/helpers.js' import { paramsBlock } from '../src/params.js' @@ -36,7 +36,7 @@ describe('EIP4844 header tests', () => { assert.throws( () => { - createHeader( + createBlockHeader( { excessBlobGas: 1n, }, @@ -52,7 +52,7 @@ describe('EIP4844 header tests', () => { assert.throws( () => { - createHeader( + createBlockHeader( { blobGasUsed: 1n, }, @@ -66,7 +66,7 @@ describe('EIP4844 header tests', () => { 'should throw when setting blobGasUsed with EIP4844 not being activated', ) - const excessBlobGas = createHeader( + const excessBlobGas = createBlockHeader( {}, { common, skipConsensusFormatValidation: true }, ).excessBlobGas @@ -76,7 +76,7 @@ describe('EIP4844 header tests', () => { 'instantiates block with reasonable default excess blob gas value when not provided', ) assert.doesNotThrow(() => { - createHeader( + createBlockHeader( { excessBlobGas: 0n, }, @@ -89,7 +89,7 @@ describe('EIP4844 header tests', () => { const block = createBlock( { - header: createHeader({}, { common, skipConsensusFormatValidation: true }), + header: createBlockHeader({}, { common, skipConsensusFormatValidation: true }), }, { common, skipConsensusFormatValidation: true }, ) @@ -111,7 +111,10 @@ describe('blob gas tests', () => { blobGasPerBlob = common.param('blobGasPerBlob') }) it('should work', () => { - const preShardingHeader = createHeader({}) + const preShardingHeader = createBlockHeader( + {}, + { common: new Common({ chain: Mainnet, hardfork: Hardfork.Shanghai }) }, + ) let excessBlobGas = preShardingHeader.calcNextExcessBlobGas() assert.equal( @@ -127,7 +130,7 @@ describe('blob gas tests', () => { 'calcDataFee throws when header has no excessBlobGas field', ) - const lowGasHeader = createHeader( + const lowGasHeader = createBlockHeader( { number: 1, excessBlobGas: 5000 }, { common, skipConsensusFormatValidation: true }, ) @@ -136,7 +139,7 @@ describe('blob gas tests', () => { let blobGasPrice = lowGasHeader.getBlobGasPrice() assert.equal(excessBlobGas, 0n, 'excess blob gas should be 0 for small parent header blob gas') assert.equal(blobGasPrice, 1n, 'blob gas price should be 1n when low or no excess blob gas') - const highGasHeader = createHeader( + const highGasHeader = createBlockHeader( { number: 1, excessBlobGas: 6291456, blobGasUsed: BigInt(6) * blobGasPerBlob }, { common, skipConsensusFormatValidation: true }, ) @@ -196,7 +199,7 @@ describe('transaction validation tests', () => { { common }, ).sign(randomBytes(32)) - const parentHeader = createHeader( + const parentHeader = createBlockHeader( { number: 1n, excessBlobGas: 4194304, blobGasUsed: 0 }, { common, skipConsensusFormatValidation: true }, ) @@ -206,7 +209,7 @@ describe('transaction validation tests', () => { function getBlock(transactions: TypedTransaction[]) { const blobs = getNumBlobs(transactions) - const blockHeader = createHeader( + const blockHeader = createBlockHeader( { number: 2n, parentHash: parentHeader.hash(), diff --git a/packages/block/test/eip4895block.spec.ts b/packages/block/test/eip4895block.spec.ts index 9738a38ca3..60aa4b4cd8 100644 --- a/packages/block/test/eip4895block.spec.ts +++ b/packages/block/test/eip4895block.spec.ts @@ -13,7 +13,7 @@ import { assert, describe, it } from 'vitest' import { createBlock, createBlockFromRLPSerializedBlock, - createHeader, + createBlockHeader, } from '../src/constructors.js' import { genWithdrawalsTrieRoot } from '../src/helpers.js' @@ -59,7 +59,7 @@ describe('EIP4895 tests', () => { const earlyCommon = new Common({ chain: Mainnet, hardfork: Hardfork.Istanbul }) assert.throws( () => { - createHeader( + createBlockHeader( { withdrawalsRoot: zeros(32), }, @@ -73,7 +73,7 @@ describe('EIP4895 tests', () => { 'should throw when setting withdrawalsRoot with EIP4895 not being activated', ) assert.doesNotThrow(() => { - createHeader( + createBlockHeader( {}, { common, @@ -81,7 +81,7 @@ describe('EIP4895 tests', () => { ) }, 'should not throw when withdrawalsRoot is undefined with EIP4895 being activated') assert.doesNotThrow(() => { - createHeader( + createBlockHeader( { withdrawalsRoot: zeros(32), }, @@ -144,7 +144,7 @@ describe('EIP4895 tests', () => { await block.withdrawalsTrieIsValid(), 'should invalidate the empty withdrawals root', ) - const validHeader = createHeader( + const validHeader = createBlockHeader( { withdrawalsRoot: KECCAK256_RLP, }, diff --git a/packages/block/test/eip7685block.spec.ts b/packages/block/test/eip7685block.spec.ts index 92083d7588..14aa9759e1 100644 --- a/packages/block/test/eip7685block.spec.ts +++ b/packages/block/test/eip7685block.spec.ts @@ -12,7 +12,7 @@ import { createBlock, createBlockFromRPC, createBlockFromValuesArray, - createHeader, + createBlockHeader, } from '../src/constructors.js' import { genRequestsTrieRoot } from '../src/helpers.js' import { Block } from '../src/index.js' @@ -111,9 +111,12 @@ describe('7685 tests', () => { describe('fromValuesArray tests', () => { it('should construct a block with empty requests root', () => { - const block = createBlockFromValuesArray([createHeader({}, { common }).raw(), [], [], [], []], { - common, - }) + const block = createBlockFromValuesArray( + [createBlockHeader({}, { common }).raw(), [], [], [], []], + { + common, + }, + ) assert.deepEqual(block.header.requestsRoot, KECCAK256_RLP) }) it('should construct a block with a valid requests array', async () => { @@ -125,7 +128,7 @@ describe('fromValuesArray tests', () => { const serializedRequests = [request1.serialize(), request2.serialize(), request3.serialize()] const block = createBlockFromValuesArray( - [createHeader({ requestsRoot }, { common }).raw(), [], [], [], serializedRequests], + [createBlockHeader({ requestsRoot }, { common }).raw(), [], [], [], serializedRequests], { common, }, @@ -145,7 +148,7 @@ describe('fromRPC tests', () => { const serializedRequests = [request1.serialize(), request2.serialize(), request3.serialize()] const block = createBlockFromValuesArray( - [createHeader({ requestsRoot }, { common }).raw(), [], [], [], serializedRequests], + [createBlockHeader({ requestsRoot }, { common }).raw(), [], [], [], serializedRequests], { common, }, diff --git a/packages/block/test/from-beacon-payload.spec.ts b/packages/block/test/from-beacon-payload.spec.ts index f60df7d846..1851897b14 100644 --- a/packages/block/test/from-beacon-payload.spec.ts +++ b/packages/block/test/from-beacon-payload.spec.ts @@ -3,7 +3,7 @@ import { loadKZG } from 'kzg-wasm' import { assert, beforeAll, describe, it } from 'vitest' import * as shardingJson from '../../client/test/sim/configs/4844-devnet.json' -import { createBlockFromBeaconPayloadJson, createHeader } from '../src/constructors.js' +import { createBlockFromBeaconPayloadJson, createBlockHeader } from '../src/constructors.js' import * as payloadKaustinen from './testdata/payload-kaustinen.json' import * as payload87335 from './testdata/payload-slot-87335.json' @@ -34,7 +34,7 @@ describe('[fromExecutionPayloadJson]: 4844 devnet 5', () => { const block = await createBlockFromBeaconPayloadJson(payload as BeaconPayloadJson, { common, }) - const parentHeader = createHeader( + const parentHeader = createBlockHeader( { excessBlobGas: BigInt(0), blobGasUsed: block.header.excessBlobGas! + BigInt(393216) }, { common }, ) @@ -73,7 +73,7 @@ describe('[fromExecutionPayloadJson]: 4844 devnet 5', () => { } as BeaconPayloadJson, { common }, ) - const parentHeader = createHeader({ excessBlobGas: BigInt(0) }, { common }) + const parentHeader = createBlockHeader({ excessBlobGas: BigInt(0) }, { common }) block.validateBlobTransactions(parentHeader) assert.fail(`should have failed constructing the block`) } catch (e) { diff --git a/packages/block/test/header.spec.ts b/packages/block/test/header.spec.ts index 914aa5fa19..ec658db5a0 100644 --- a/packages/block/test/header.spec.ts +++ b/packages/block/test/header.spec.ts @@ -15,9 +15,9 @@ import { assert, describe, it } from 'vitest' import { createBlock, createBlockFromRLPSerializedBlock, - createHeader, - createHeaderFromRLP, - createHeaderFromValuesArray, + createBlockHeader, + createBlockHeaderFromRLP, + createBlockHeaderFromValuesArray, } from '../src/constructors.js' import { Block } from '../src/index.js' @@ -49,7 +49,7 @@ describe('[Block]: Header functions', () => { assert.ok(equalsBytes(header.nonce, zeros(8))) } - const header = createHeader() + const header = createBlockHeader() compareDefaultHeader(header) const block = new Block() @@ -58,7 +58,7 @@ describe('[Block]: Header functions', () => { it('Initialization -> fromHeaderData()', () => { const common = new Common({ chain: Mainnet, hardfork: Hardfork.Chainstart }) - let header = createHeader(undefined, { common }) + let header = createBlockHeader(undefined, { common }) assert.ok(bytesToHex(header.hash()), 'genesis block should initialize') assert.equal( header.common.hardfork(), @@ -73,15 +73,15 @@ describe('[Block]: Header functions', () => { 'should stay on correct HF if outer common HF changes', ) - header = createHeader({}, { common }) + header = createBlockHeader({}, { common }) assert.ok(bytesToHex(header.hash()), 'default block should initialize') // test default freeze values // also test if the options are carried over to the constructor - header = createHeader({}) + header = createBlockHeader({}) assert.ok(Object.isFrozen(header), 'block should be frozen by default') - header = createHeader({}, { freeze: false }) + header = createBlockHeader({}, { freeze: false }) assert.ok( !Object.isFrozen(header), 'block should not be frozen when freeze deactivated in options', @@ -90,15 +90,15 @@ describe('[Block]: Header functions', () => { it('Initialization -> fromRLPSerializedHeader()', () => { const common = new Common({ chain: Mainnet, hardfork: Hardfork.London }) - let header = createHeader({}, { common, freeze: false }) + let header = createBlockHeader({}, { common, freeze: false }) const rlpHeader = header.serialize() - header = createHeaderFromRLP(rlpHeader, { + header = createBlockHeaderFromRLP(rlpHeader, { common, }) assert.ok(Object.isFrozen(header), 'block should be frozen by default') - header = createHeaderFromRLP(rlpHeader, { + header = createBlockHeaderFromRLP(rlpHeader, { common, freeze: false, }) @@ -107,7 +107,7 @@ describe('[Block]: Header functions', () => { 'block should not be frozen when freeze deactivated in options', ) - header = createHeaderFromRLP( + header = createBlockHeaderFromRLP( hexToBytes( '0xf90214a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a0d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000850400000000808213888080a011bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82faa00000000000000000000000000000000000000000000000000000000000000000880000000000000042', ), @@ -122,7 +122,7 @@ describe('[Block]: Header functions', () => { it('Initialization -> fromRLPSerializedHeader() -> error cases', () => { try { - createHeaderFromRLP(RLP.encode('a')) + createBlockHeaderFromRLP(RLP.encode('a')) } catch (e: any) { const expectedError = 'Invalid serialized header input. Must be array' assert.ok(e.message.includes(expectedError), 'should throw with header as rlp encoded string') @@ -146,10 +146,10 @@ describe('[Block]: Header functions', () => { headerArray[13] = zeros(32) // mixHash headerArray[14] = zeros(8) // nonce - let header = createHeaderFromValuesArray(headerArray, { common }) + let header = createBlockHeaderFromValuesArray(headerArray, { common }) assert.ok(Object.isFrozen(header), 'block should be frozen by default') - header = createHeaderFromValuesArray(headerArray, { common, freeze: false }) + header = createBlockHeaderFromValuesArray(headerArray, { common, freeze: false }) assert.ok( !Object.isFrozen(header), 'block should not be frozen when freeze deactivated in options', @@ -169,14 +169,14 @@ describe('[Block]: Header functions', () => { headerArray[14] = zeros(8) // nonce headerArray[15] = zeros(4) // bad data try { - createHeaderFromValuesArray(headerArray) + createBlockHeaderFromValuesArray(headerArray) } catch (e: any) { const expectedError = 'invalid header. More values than expected were received' assert.ok(e.message.includes(expectedError), 'should throw on more values than expected') } try { - createHeaderFromValuesArray(headerArray.slice(0, 5)) + createBlockHeaderFromValuesArray(headerArray.slice(0, 5)) } catch (e: any) { const expectedError = 'invalid header. Less values than expected were received' assert.ok(e.message.includes(expectedError), 'should throw on less values than expected') @@ -185,7 +185,7 @@ describe('[Block]: Header functions', () => { it('Initialization -> Clique Blocks', () => { const common = new Common({ chain: Goerli, hardfork: Hardfork.Chainstart }) - const header = createHeader({ extraData: new Uint8Array(97) }, { common }) + const header = createBlockHeader({ extraData: new Uint8Array(97) }, { common }) assert.ok(bytesToHex(header.hash()), 'default block should initialize') }) @@ -206,7 +206,7 @@ describe('[Block]: Header functions', () => { let extraData = new Uint8Array(32) try { - createHeader({ ...data, extraData }, opts) + createBlockHeader({ ...data, extraData }, opts) assert.ok(true, testCase) } catch (error: any) { assert.fail(testCase) @@ -217,7 +217,7 @@ describe('[Block]: Header functions', () => { extraData = new Uint8Array(12) try { - createHeader({ ...data, extraData }, opts) + createBlockHeader({ ...data, extraData }, opts) assert.ok(testCase) } catch (error: any) { assert.fail(testCase) @@ -228,7 +228,7 @@ describe('[Block]: Header functions', () => { extraData = new Uint8Array(42) try { - createHeader({ ...data, extraData }, opts) + createBlockHeader({ ...data, extraData }, opts) assert.fail(testCase) } catch (error: any) { assert.ok((error.message as string).includes('invalid amount of extra data'), testCase) @@ -248,7 +248,7 @@ describe('[Block]: Header functions', () => { 'clique block should validate with valid number of bytes in extraData: 32 byte vanity + 65 byte seal' extraData = concatBytes(new Uint8Array(32), new Uint8Array(65)) try { - createHeader({ ...data, extraData }, opts) + createBlockHeader({ ...data, extraData }, opts) assert.ok(true, testCase) } catch (error: any) { assert.fail(testCase) @@ -258,7 +258,7 @@ describe('[Block]: Header functions', () => { testCase = 'clique block should throw on invalid extraData length' extraData = new Uint8Array(32) try { - createHeader({ ...data, extraData }, opts) + createBlockHeader({ ...data, extraData }, opts) assert.fail(testCase) } catch (error: any) { assert.ok( @@ -279,7 +279,7 @@ describe('[Block]: Header functions', () => { ) const epoch = BigInt((common.consensusConfig() as CliqueConfig).epoch) try { - createHeader({ ...data, number: epoch, extraData }, opts) + createBlockHeader({ ...data, number: epoch, extraData }, opts) assert.fail(testCase) } catch (error: any) { assert.ok( @@ -296,7 +296,7 @@ describe('[Block]: Header functions', () => { const extraData = concatBytes(new Uint8Array(1)) try { - createHeader({ extraData }, { common, skipConsensusFormatValidation: true }) + createBlockHeader({ extraData }, { common, skipConsensusFormatValidation: true }) assert.ok( true, 'should instantiate header with invalid extraData when skipConsensusFormatValidation === true', @@ -310,26 +310,26 @@ describe('[Block]: Header functions', () => { const badHash = new Uint8Array(31) assert.throws( - () => createHeader({ parentHash: badHash }), + () => createBlockHeader({ parentHash: badHash }), 'parentHash must be 32 bytes', undefined, 'throws on invalid parent hash length', ) assert.throws( - () => createHeader({ stateRoot: badHash }), + () => createBlockHeader({ stateRoot: badHash }), 'stateRoot must be 32 bytes', undefined, 'throws on invalid state root hash length', ) assert.throws( - () => createHeader({ transactionsTrie: badHash }), + () => createBlockHeader({ transactionsTrie: badHash }), 'transactionsTrie must be 32 bytes', undefined, 'throws on invalid transactionsTrie root hash length', ) assert.throws( - () => createHeader({ nonce: new Uint8Array(5) }), + () => createBlockHeader({ nonce: new Uint8Array(5) }), 'nonce must be 8 bytes', undefined, 'contains nonce length error message', @@ -354,7 +354,7 @@ describe('[Block]: Header functions', () => { headerData.difficulty = BigInt(2) let testCase = 'should throw on lower than period timestamp diffs' - let header = createHeader(headerData, { common }) + let header = createBlockHeader(headerData, { common }) try { await header.validate(blockchain) assert.fail(testCase) @@ -364,7 +364,7 @@ describe('[Block]: Header functions', () => { testCase = 'should not throw on timestamp diff equal to period' headerData.timestamp = BigInt(1422494864) - header = createHeader(headerData, { common }) + header = createBlockHeader(headerData, { common }) try { await header.validate(blockchain) assert.ok(true, testCase) @@ -375,7 +375,7 @@ describe('[Block]: Header functions', () => { testCase = 'should throw on non-zero beneficiary (coinbase) for epoch transition block' headerData.number = common.consensusConfig().epoch headerData.coinbase = createAddressFromString('0x091dcd914fCEB1d47423e532955d1E62d1b2dAEf') - header = createHeader(headerData, { common }) + header = createBlockHeader(headerData, { common }) try { await header.validate(blockchain) assert.fail('should throw') @@ -391,7 +391,7 @@ describe('[Block]: Header functions', () => { testCase = 'should throw on non-zero mixHash' headerData.mixHash = new Uint8Array(32).fill(1) - header = createHeader(headerData, { common }) + header = createBlockHeader(headerData, { common }) try { await header.validate(blockchain) assert.fail('should throw') @@ -406,7 +406,7 @@ describe('[Block]: Header functions', () => { testCase = 'should throw on invalid clique difficulty' headerData.difficulty = BigInt(3) - header = createHeader(headerData, { common }) + header = createBlockHeader(headerData, { common }) try { header.validateCliqueDifficulty(blockchain) assert.fail(testCase) @@ -427,7 +427,7 @@ describe('[Block]: Header functions', () => { const poaBlock = createBlockFromRLPSerializedBlock(genesisRlp, { common, cliqueSigner }) await poaBlockchain.putBlock(poaBlock) - header = createHeader(headerData, { common, cliqueSigner }) + header = createBlockHeader(headerData, { common, cliqueSigner }) try { const res = header.validateCliqueDifficulty(poaBlockchain) assert.equal(res, true, testCase) @@ -438,7 +438,7 @@ describe('[Block]: Header functions', () => { testCase = 'validateCliqueDifficulty() should return false with INTURN difficulty and one signer' headerData.difficulty = BigInt(1) - header = createHeader(headerData, { common, cliqueSigner }) + header = createBlockHeader(headerData, { common, cliqueSigner }) try { const res = header.validateCliqueDifficulty(poaBlockchain) assert.equal(res, false, testCase) @@ -467,16 +467,16 @@ describe('[Block]: Header functions', () => { }) it('should test isGenesis()', () => { - const header1 = createHeader({ number: 1 }) + const header1 = createBlockHeader({ number: 1 }) assert.equal(header1.isGenesis(), false) - const header2 = createHeader() + const header2 = createBlockHeader() assert.equal(header2.isGenesis(), true) }) it('should test hash() function', () => { let common = new Common({ chain: Mainnet, hardfork: Hardfork.Chainstart }) - let header = createHeader((blocksMainnet as any).default[0]['header'], { common }) + let header = createBlockHeader((blocksMainnet as any).default[0]['header'], { common }) assert.equal( bytesToHex(header.hash()), '0x88e96d4537bea4d9c05d12549907b32561d3bf31f45aae734cdc119f13406cb6', @@ -484,7 +484,7 @@ describe('[Block]: Header functions', () => { ) common = new Common({ chain: Goerli, hardfork: Hardfork.Chainstart }) - header = createHeader((blocksGoerli as any).default[0]['header'], { common }) + header = createBlockHeader((blocksGoerli as any).default[0]['header'], { common }) assert.equal( bytesToHex(header.hash()), '0x8f5bab218b6bb34476f51ca588e9f4553a3a7ce5e13a66c660a5283e97e9a85a', @@ -494,7 +494,7 @@ describe('[Block]: Header functions', () => { it('should be able to initialize shanghai header with correct hardfork defaults', () => { const common = new Common({ chain: Mainnet, hardfork: Hardfork.Shanghai }) - const header = createHeader({}, { common }) + const header = createBlockHeader({}, { common }) assert.equal(header.common.hardfork(), Hardfork.Shanghai, 'hardfork should be set to shanghai') assert.equal(header.baseFeePerGas, BigInt(7), 'baseFeePerGas should be set to minimum default') assert.deepEqual( diff --git a/packages/block/test/mergeBlock.spec.ts b/packages/block/test/mergeBlock.spec.ts index b1415ae05b..638a0d2995 100644 --- a/packages/block/test/mergeBlock.spec.ts +++ b/packages/block/test/mergeBlock.spec.ts @@ -10,7 +10,7 @@ import { import { assert, describe, it } from 'vitest' import { Block } from '../src/block.js' -import { createBlock, createHeader } from '../src/constructors.js' +import { createBlock, createBlockHeader } from '../src/constructors.js' import type { BlockHeader } from '../src/header.js' @@ -39,7 +39,7 @@ function validateMergeHeader(header: BlockHeader) { describe('[Header]: Casper PoS / The Merge Functionality', () => { it('should construct default blocks with post-merge PoS constants fields', () => { - const header = createHeader({}, { common }) + const header = createBlockHeader({}, { common }) validateMergeHeader(header) const block = new Block(undefined, undefined, undefined, undefined, { common }, undefined) @@ -52,7 +52,7 @@ describe('[Header]: Casper PoS / The Merge Functionality', () => { const headerData = { uncleHash: hexToBytes('0x123abc'), } - createHeader(headerData, { common }) + createBlockHeader(headerData, { common }) assert.fail('should throw') } catch (e: any) { assert.ok(true, 'should throw on wrong uncleHash') @@ -63,7 +63,7 @@ describe('[Header]: Casper PoS / The Merge Functionality', () => { difficulty: BigInt(123456), number: 1n, } - createHeader(headerData, { common }) + createBlockHeader(headerData, { common }) assert.fail('should throw') } catch (e: any) { assert.ok(true, 'should throw on wrong difficulty') @@ -74,7 +74,7 @@ describe('[Header]: Casper PoS / The Merge Functionality', () => { extraData: new Uint8Array(33).fill(1), number: 1n, } - createHeader(headerData, { common }) + createBlockHeader(headerData, { common }) assert.fail('should throw') } catch (e: any) { assert.ok(true, 'should throw on invalid extraData length') @@ -84,7 +84,7 @@ describe('[Header]: Casper PoS / The Merge Functionality', () => { const headerData = { mixHash: new Uint8Array(30).fill(1), } - createHeader(headerData, { common }) + createBlockHeader(headerData, { common }) assert.fail('should throw') } catch (e: any) { assert.ok(true, 'should throw on invalid mixHash length') @@ -95,7 +95,7 @@ describe('[Header]: Casper PoS / The Merge Functionality', () => { nonce: new Uint8Array(8).fill(1), number: 1n, } - createHeader(headerData, { common }) + createBlockHeader(headerData, { common }) assert.fail('should throw') } catch (e: any) { assert.ok(true, 'should throw on wrong nonce') @@ -104,7 +104,7 @@ describe('[Header]: Casper PoS / The Merge Functionality', () => { it('test that a PoS block with uncles cannot be produced', () => { try { - new Block(undefined, undefined, [createHeader(undefined, { common })], undefined, { + new Block(undefined, undefined, [createBlockHeader(undefined, { common })], undefined, { common, }) assert.fail('should have thrown') diff --git a/packages/blockchain/src/db/manager.ts b/packages/blockchain/src/db/manager.ts index 0b0d5f1eb8..c0864c1cd0 100644 --- a/packages/blockchain/src/db/manager.ts +++ b/packages/blockchain/src/db/manager.ts @@ -1,4 +1,4 @@ -import { createBlockFromValuesArray, createHeaderFromValuesArray } from '@ethereumjs/block' +import { createBlockFromValuesArray, createBlockHeaderFromValuesArray } from '@ethereumjs/block' import { RLP } from '@ethereumjs/rlp' import { KECCAK256_RLP, @@ -160,7 +160,7 @@ export class DBManager { const headerValues = RLP.decode(encodedHeader) const opts: BlockOptions = { common: this.common, setHardfork: true } - return createHeaderFromValuesArray(headerValues as Uint8Array[], opts) + return createBlockHeaderFromValuesArray(headerValues as Uint8Array[], opts) } /** diff --git a/packages/blockchain/test/blockValidation.spec.ts b/packages/blockchain/test/blockValidation.spec.ts index b80a8246f1..0a9a57732e 100644 --- a/packages/blockchain/test/blockValidation.spec.ts +++ b/packages/blockchain/test/blockValidation.spec.ts @@ -1,4 +1,4 @@ -import { createBlock, createHeader } from '@ethereumjs/block' +import { createBlock, createBlockHeader } from '@ethereumjs/block' import { Common, ConsensusAlgorithm, Hardfork, Mainnet } from '@ethereumjs/common' import { Ethash } from '@ethereumjs/ethash' import { RLP } from '@ethereumjs/rlp' @@ -224,7 +224,7 @@ describe('[Blockchain]: Block validation tests', () => { return BigInt(0) } - const header = createHeader( + const header = createBlockHeader( { number: BigInt(1), parentHash: genesis.hash(), @@ -242,7 +242,7 @@ describe('[Blockchain]: Block validation tests', () => { const block = createBlock({ header }, { common }) await blockchain.putBlock(block) try { - const header = createHeader( + const header = createBlockHeader( { number: BigInt(2), parentHash: block.hash(), @@ -348,7 +348,7 @@ describe('[Blockchain]: Block validation tests', () => { const uncleHeaderData = unclePreFork.header.toJSON() uncleHeaderData.extraData = '0xffff' - const uncleHeader = createHeader(uncleHeaderData, { + const uncleHeader = createBlockHeader(uncleHeaderData, { common: new Common({ chain: Mainnet, hardfork: Hardfork.Berlin }), }) diff --git a/packages/blockchain/test/index.spec.ts b/packages/blockchain/test/index.spec.ts index b02343f9fb..f195591334 100644 --- a/packages/blockchain/test/index.spec.ts +++ b/packages/blockchain/test/index.spec.ts @@ -1,8 +1,8 @@ import { createBlock, createBlockFromRLPSerializedBlock, - createHeader, - createHeaderFromValuesArray, + createBlockHeader, + createBlockHeaderFromValuesArray, } from '@ethereumjs/block' import { Common, Goerli, Hardfork, Holesky, Mainnet, Sepolia } from '@ethereumjs/common' import { MapDB, bytesToHex, equalsBytes, hexToBytes, utf8ToBytes } from '@ethereumjs/util' @@ -439,7 +439,7 @@ describe('blockchain test', () => { gasLimit: 8000000, timestamp: BigInt(blocks[14].header.timestamp) + BigInt(1), } - const forkHeader = createHeader(headerData, { + const forkHeader = createBlockHeader(headerData, { common, calcDifficultyFromHeader: blocks[14].header, }) @@ -464,7 +464,7 @@ describe('blockchain test', () => { //eslint-disable-next-line timestamp: BigInt(blocks[14].header.timestamp) + BigInt(1), } - const forkHeader = createHeader(headerData, { + const forkHeader = createBlockHeader(headerData, { common, calcDifficultyFromHeader: blocks[14].header, }) @@ -531,7 +531,7 @@ describe('blockchain test', () => { const block2HeaderValuesArray = blocks[2].header.raw() block2HeaderValuesArray[1] = new Uint8Array(32) - const block2Header = createHeaderFromValuesArray(block2HeaderValuesArray, { + const block2Header = createBlockHeaderFromValuesArray(block2HeaderValuesArray, { common: blocks[2].common, }) await blockchain.putHeader(block2Header) @@ -629,7 +629,7 @@ describe('blockchain test', () => { gasLimit, timestamp: genesisBlock.header.timestamp + BigInt(1), } - const header = createHeader(headerData, { + const header = createBlockHeader(headerData, { calcDifficultyFromHeader: genesisBlock.header, common, }) @@ -679,7 +679,7 @@ describe('blockchain test', () => { gasLimit, } opts.calcDifficultyFromHeader = genesisBlock.header - const header1 = createHeader(headerData1, opts) + const header1 = createBlockHeader(headerData1, opts) const headers = [header1] const headerData2 = { @@ -689,7 +689,7 @@ describe('blockchain test', () => { gasLimit, } opts.calcDifficultyFromHeader = block.header - const header2 = createHeader(headerData2, opts) + const header2 = createBlockHeader(headerData2, opts) headers.push(header2) await blockchain.putHeaders(headers) diff --git a/packages/blockchain/test/util.ts b/packages/blockchain/test/util.ts index f32df97bb7..abb88488c5 100644 --- a/packages/blockchain/test/util.ts +++ b/packages/blockchain/test/util.ts @@ -1,4 +1,4 @@ -import { Block, createBlock, createHeader } from '@ethereumjs/block' +import { Block, createBlock, createBlockHeader } from '@ethereumjs/block' import { Common, Hardfork, Mainnet } from '@ethereumjs/common' import { RLP } from '@ethereumjs/rlp' import { @@ -83,14 +83,14 @@ export const generateConsecutiveBlock = ( difficultyChangeFactor = 1 } const common = new Common({ chain: Mainnet, hardfork: Hardfork.MuirGlacier }) - const tmpHeader = createHeader( + const tmpHeader = createBlockHeader( { number: parentBlock.header.number + BigInt(1), timestamp: parentBlock.header.timestamp + BigInt(10 + -difficultyChangeFactor * 9), }, { common }, ) - const header = createHeader( + const header = createBlockHeader( { number: parentBlock.header.number + BigInt(1), parentHash: parentBlock.hash(), diff --git a/packages/client/src/blockchain/chain.ts b/packages/client/src/blockchain/chain.ts index cbc7ff253b..b3280f44b9 100644 --- a/packages/client/src/blockchain/chain.ts +++ b/packages/client/src/blockchain/chain.ts @@ -1,4 +1,4 @@ -import { createBlockFromValuesArray, createHeaderFromValuesArray } from '@ethereumjs/block' +import { createBlockFromValuesArray, createBlockHeaderFromValuesArray } from '@ethereumjs/block' import { CliqueConsensus, createBlockchain } from '@ethereumjs/blockchain' import { ConsensusAlgorithm, Hardfork } from '@ethereumjs/common' import { BIGINT_0, equalsBytes } from '@ethereumjs/util' @@ -468,7 +468,7 @@ export class Chain { } break } - const header = createHeaderFromValuesArray(h.raw(), { + const header = createBlockHeaderFromValuesArray(h.raw(), { common: this.config.chainCommon, setHardfork: true, }) diff --git a/packages/client/src/execution/vmexecution.ts b/packages/client/src/execution/vmexecution.ts index 0ddbe76e6c..8b45786f67 100644 --- a/packages/client/src/execution/vmexecution.ts +++ b/packages/client/src/execution/vmexecution.ts @@ -4,14 +4,10 @@ import { DBSetHashToNumber, DBSetTD, } from '@ethereumjs/blockchain' -import { ConsensusType, Hardfork } from '@ethereumjs/common' +import { CacheType, ConsensusType, Hardfork } from '@ethereumjs/common' import { MCLBLS } from '@ethereumjs/evm' import { getGenesis } from '@ethereumjs/genesis' -import { - CacheType, - DefaultStateManager, - StatelessVerkleStateManager, -} from '@ethereumjs/statemanager' +import { DefaultStateManager, StatelessVerkleStateManager } from '@ethereumjs/statemanager' import { createTrie } from '@ethereumjs/trie' import { BIGINT_0, diff --git a/packages/client/src/miner/miner.ts b/packages/client/src/miner/miner.ts index d337edf29b..d4acf00e96 100644 --- a/packages/client/src/miner/miner.ts +++ b/packages/client/src/miner/miner.ts @@ -1,4 +1,4 @@ -import { type BlockHeader, createHeader } from '@ethereumjs/block' +import { type BlockHeader, createBlockHeader } from '@ethereumjs/block' import { ConsensusType, Hardfork } from '@ethereumjs/common' import { Ethash } from '@ethereumjs/ethash' import { BIGINT_0, BIGINT_1, BIGINT_2, bytesToHex, equalsBytes } from '@ethereumjs/util' @@ -208,7 +208,10 @@ export class Miner { if (this.config.chainCommon.consensusType() === ConsensusType.ProofOfAuthority) { // Abort if we have too recently signed const cliqueSigner = this.config.accounts[0][1] - const header = createHeader({ number }, { common: this.config.chainCommon, cliqueSigner }) + const header = createBlockHeader( + { number }, + { common: this.config.chainCommon, cliqueSigner }, + ) if ( (this.service.chain.blockchain as any).consensus.cliqueCheckRecentlySigned(header) === true ) { diff --git a/packages/client/src/net/protocol/ethprotocol.ts b/packages/client/src/net/protocol/ethprotocol.ts index d5b2c96144..1dd3539313 100644 --- a/packages/client/src/net/protocol/ethprotocol.ts +++ b/packages/client/src/net/protocol/ethprotocol.ts @@ -1,4 +1,4 @@ -import { createBlockFromValuesArray, createHeaderFromValuesArray } from '@ethereumjs/block' +import { createBlockFromValuesArray, createBlockHeaderFromValuesArray } from '@ethereumjs/block' import { RLP } from '@ethereumjs/rlp' import { BlobEIP4844Transaction, @@ -168,7 +168,7 @@ export class EthProtocol extends Protocol { bytesToBigInt(reqId), headers.map((h) => { const common = this.config.chainCommon - const header = createHeaderFromValuesArray(h, { common, setHardfork: true }) + const header = createBlockHeaderFromValuesArray(h, { common, setHardfork: true }) return header }), ], diff --git a/packages/client/src/net/protocol/lesprotocol.ts b/packages/client/src/net/protocol/lesprotocol.ts index 82d8d753d3..b906eaf48c 100644 --- a/packages/client/src/net/protocol/lesprotocol.ts +++ b/packages/client/src/net/protocol/lesprotocol.ts @@ -1,4 +1,4 @@ -import { createHeaderFromValuesArray } from '@ethereumjs/block' +import { createBlockHeaderFromValuesArray } from '@ethereumjs/block' import { BIGINT_0, bigIntToUnpaddedBytes, @@ -109,7 +109,7 @@ export class LesProtocol extends Protocol { reqId: bytesToBigInt(reqId), bv: bytesToBigInt(bv), headers: headers.map((h: BlockHeaderBytes) => - createHeaderFromValuesArray(h, { + createBlockHeaderFromValuesArray(h, { setHardfork: true, common: this.config.chainCommon, // eslint-disable-line no-invalid-this }), diff --git a/packages/client/src/rpc/modules/eth.ts b/packages/client/src/rpc/modules/eth.ts index 36da556bd4..6cdb852b77 100644 --- a/packages/client/src/rpc/modules/eth.ts +++ b/packages/client/src/rpc/modules/eth.ts @@ -45,8 +45,8 @@ import type { EthProtocol } from '../../net/protocol/index.js' import type { FullEthereumService, Service } from '../../service/index.js' import type { RpcTx } from '../types.js' import type { Block, JsonRpcBlock } from '@ethereumjs/block' +import type { Proof } from '@ethereumjs/common' import type { Log } from '@ethereumjs/evm' -import type { Proof } from '@ethereumjs/statemanager' import type { FeeMarketEIP1559Transaction, LegacyTransaction, diff --git a/packages/client/test/execution/vmexecution.spec.ts b/packages/client/test/execution/vmexecution.spec.ts index bdbdc726e6..2d604d1906 100644 --- a/packages/client/test/execution/vmexecution.spec.ts +++ b/packages/client/test/execution/vmexecution.spec.ts @@ -197,7 +197,9 @@ describe('[VMExecution]', () => { engine: true, }) - const block = await createBlockFromExecutionPayload(shanghaiPayload as ExecutionPayload) + const block = await createBlockFromExecutionPayload(shanghaiPayload as ExecutionPayload, { + common: new Common({ chain: Mainnet, hardfork: Hardfork.Shanghai }), + }) const oldHead = await blockchain.getIteratorHead() const parentStateRoot = oldHead.header.stateRoot diff --git a/packages/client/test/miner/miner.spec.ts b/packages/client/test/miner/miner.spec.ts index 43dc616903..dea370b039 100644 --- a/packages/client/test/miner/miner.spec.ts +++ b/packages/client/test/miner/miner.spec.ts @@ -1,4 +1,4 @@ -import { BlockHeader, createBlock, createHeader } from '@ethereumjs/block' +import { BlockHeader, createBlock, createBlockHeader } from '@ethereumjs/block' import { Common, Goerli, @@ -53,7 +53,7 @@ class FakeChain { update() {} get headers() { return { - latest: createHeader(), + latest: createBlockHeader(), height: BigInt(0), } } @@ -64,10 +64,10 @@ class FakeChain { } } getBlock() { - return createHeader() + return createBlockHeader() } getCanonicalHeadHeader() { - return createHeader() + return createBlockHeader() } blockchain: any = { putBlock: async () => {}, diff --git a/packages/client/test/miner/pendingBlock.spec.ts b/packages/client/test/miner/pendingBlock.spec.ts index b46783883b..4a009e9465 100644 --- a/packages/client/test/miner/pendingBlock.spec.ts +++ b/packages/client/test/miner/pendingBlock.spec.ts @@ -1,4 +1,4 @@ -import { Block, BlockHeader, createHeader } from '@ethereumjs/block' +import { Block, BlockHeader, createBlockHeader } from '@ethereumjs/block' import { Common, Goerli, Hardfork, Mainnet, createCommonFromGethGenesis } from '@ethereumjs/common' import { DefaultStateManager } from '@ethereumjs/statemanager' import { create1559FeeMarketTx, create4844BlobTx, createLegacyTx } from '@ethereumjs/tx' @@ -70,7 +70,7 @@ const setup = () => { const service: any = { chain: { headers: { height: BigInt(0) }, - getCanonicalHeadHeader: () => createHeader({}, { common }), + getCanonicalHeadHeader: () => createBlockHeader({}, { common }), }, execution: { vm: { diff --git a/packages/client/test/rpc/debug/getRawBlock.spec.ts b/packages/client/test/rpc/debug/getRawBlock.spec.ts index 9b5f51788a..f15680c255 100644 --- a/packages/client/test/rpc/debug/getRawBlock.spec.ts +++ b/packages/client/test/rpc/debug/getRawBlock.spec.ts @@ -1,4 +1,4 @@ -import { createBlock, createHeader } from '@ethereumjs/block' +import { createBlock, createBlockHeader } from '@ethereumjs/block' import { Mainnet, createCustomCommon } from '@ethereumjs/common' import { create4844BlobTx, createLegacyTx } from '@ethereumjs/tx' import { bytesToHex, createZeroAddress, hexToBytes } from '@ethereumjs/util' @@ -28,7 +28,7 @@ const block = { header: { number: BigInt(1), hash: () => blockHash, - serialize: () => createHeader({ number: 1 }).serialize(), + serialize: () => createBlockHeader({ number: 1 }).serialize(), }, toJSON: () => ({ ...createBlock({ header: { number: 1 } }).toJSON(), diff --git a/packages/client/test/rpc/debug/getRawHeader.spec.ts b/packages/client/test/rpc/debug/getRawHeader.spec.ts index f920f3d0a3..f125998cee 100644 --- a/packages/client/test/rpc/debug/getRawHeader.spec.ts +++ b/packages/client/test/rpc/debug/getRawHeader.spec.ts @@ -1,4 +1,4 @@ -import { createBlock, createHeader } from '@ethereumjs/block' +import { createBlock, createBlockHeader } from '@ethereumjs/block' import { Mainnet, createCustomCommon } from '@ethereumjs/common' import { create4844BlobTx, createLegacyTx } from '@ethereumjs/tx' import { bytesToHex, createZeroAddress, hexToBytes } from '@ethereumjs/util' @@ -28,7 +28,7 @@ const block = { header: { number: BigInt(1), hash: () => blockHash, - serialize: () => createHeader({ number: 1 }).serialize(), + serialize: () => createBlockHeader({ number: 1 }).serialize(), }, toJSON: () => ({ ...createBlock({ header: { number: 1 } }).toJSON(), @@ -46,7 +46,7 @@ const genesisBlock = { hash: () => genesisBlockHash, header: { number: BigInt(0), - serialize: () => createHeader({ number: 0 }).serialize(), + serialize: () => createBlockHeader({ number: 0 }).serialize(), }, toJSON: () => ({ ...createBlock({ header: { number: 0 } }).toJSON(), transactions }), serialize: () => createBlock({ header: { number: 0 }, transactions }).serialize(), diff --git a/packages/client/test/rpc/engine/getPayloadBodiesByHashV1.spec.ts b/packages/client/test/rpc/engine/getPayloadBodiesByHashV1.spec.ts index 9fffa532d2..06fdc93a21 100644 --- a/packages/client/test/rpc/engine/getPayloadBodiesByHashV1.spec.ts +++ b/packages/client/test/rpc/engine/getPayloadBodiesByHashV1.spec.ts @@ -1,4 +1,4 @@ -import { createBlock, createHeader } from '@ethereumjs/block' +import { createBlock, createBlockHeader } from '@ethereumjs/block' import { Hardfork } from '@ethereumjs/common' import { DefaultStateManager } from '@ethereumjs/statemanager' import { createTxFromTxData } from '@ethereumjs/tx' @@ -75,7 +75,7 @@ describe(method, () => { const block = createBlock( { transactions: [tx], - header: createHeader( + header: createBlockHeader( { parentHash: chain.genesis.hash(), number: 1n }, { common, skipConsensusFormatValidation: true }, ), @@ -85,7 +85,7 @@ describe(method, () => { const block2 = createBlock( { transactions: [tx2], - header: createHeader( + header: createBlockHeader( { parentHash: block.hash(), number: 2n }, { common, skipConsensusFormatValidation: true }, ), @@ -161,7 +161,7 @@ describe(method, () => { const block = createBlock( { transactions: [tx], - header: createHeader( + header: createBlockHeader( { parentHash: chain.genesis.hash(), number: 1n }, { common, skipConsensusFormatValidation: true }, ), @@ -171,7 +171,7 @@ describe(method, () => { const block2 = createBlock( { transactions: [tx2], - header: createHeader( + header: createBlockHeader( { parentHash: block.hash(), number: 2n }, { common, skipConsensusFormatValidation: true }, ), diff --git a/packages/client/test/rpc/engine/getPayloadBodiesByRangeV1.spec.ts b/packages/client/test/rpc/engine/getPayloadBodiesByRangeV1.spec.ts index 3918c355ab..5719f74e02 100644 --- a/packages/client/test/rpc/engine/getPayloadBodiesByRangeV1.spec.ts +++ b/packages/client/test/rpc/engine/getPayloadBodiesByRangeV1.spec.ts @@ -1,4 +1,4 @@ -import { createBlock, createHeader } from '@ethereumjs/block' +import { createBlock, createBlockHeader } from '@ethereumjs/block' import { Hardfork } from '@ethereumjs/common' import { DefaultStateManager } from '@ethereumjs/statemanager' import { createTxFromTxData } from '@ethereumjs/tx' @@ -71,7 +71,7 @@ describe(method, () => { const block = createBlock( { transactions: [tx], - header: createHeader( + header: createBlockHeader( { parentHash: chain.genesis.hash(), number: 1n }, { common, skipConsensusFormatValidation: true }, ), @@ -81,7 +81,7 @@ describe(method, () => { const block2 = createBlock( { transactions: [tx2], - header: createHeader( + header: createBlockHeader( { parentHash: block.hash(), number: 2n }, { common, skipConsensusFormatValidation: true }, ), @@ -153,7 +153,7 @@ describe(method, () => { const block = createBlock( { transactions: [tx], - header: createHeader( + header: createBlockHeader( { parentHash: chain.genesis.hash(), number: 1n }, { common, skipConsensusFormatValidation: true }, ), @@ -163,7 +163,7 @@ describe(method, () => { const block2 = createBlock( { transactions: [tx2], - header: createHeader( + header: createBlockHeader( { parentHash: block.hash(), number: 2n }, { common, skipConsensusFormatValidation: true }, ), diff --git a/packages/client/test/rpc/eth/estimateGas.spec.ts b/packages/client/test/rpc/eth/estimateGas.spec.ts index 5e3ea04e59..b4a3b8ccb4 100644 --- a/packages/client/test/rpc/eth/estimateGas.spec.ts +++ b/packages/client/test/rpc/eth/estimateGas.spec.ts @@ -1,4 +1,4 @@ -import { createBlock, createHeader } from '@ethereumjs/block' +import { createBlock, createBlockHeader } from '@ethereumjs/block' import { createBlockchain } from '@ethereumjs/blockchain' import { createCommonFromGethGenesis } from '@ethereumjs/common' import { getGenesis } from '@ethereumjs/genesis' @@ -131,7 +131,7 @@ describe( const headBlock = await service.chain.getCanonicalHeadBlock() const londonBlock = createBlock( { - header: createHeader( + header: createBlockHeader( { baseFeePerGas: 1000000000n, number: 2n, diff --git a/packages/client/test/rpc/helpers.ts b/packages/client/test/rpc/helpers.ts index 453f7c3aca..0118bd5aa2 100644 --- a/packages/client/test/rpc/helpers.ts +++ b/packages/client/test/rpc/helpers.ts @@ -1,4 +1,4 @@ -import { createHeader } from '@ethereumjs/block' +import { createBlockHeader } from '@ethereumjs/block' import { createBlockchain } from '@ethereumjs/blockchain' import { Common, @@ -128,7 +128,7 @@ export async function createClient(clientOpts: Partial = {}) { chain.getTd = async (_hash: Uint8Array, _num: bigint) => BigInt(1000) if ((chain as any)._headers !== undefined) { - ;(chain as any)._headers.latest = createHeader( + ;(chain as any)._headers.latest = createBlockHeader( { withdrawalsRoot: common.isActivatedEIP(4895) ? KECCAK256_RLP : undefined }, { common }, ) diff --git a/packages/client/test/rpc/txpool/content.spec.ts b/packages/client/test/rpc/txpool/content.spec.ts index a45512fff2..2473a8fd02 100644 --- a/packages/client/test/rpc/txpool/content.spec.ts +++ b/packages/client/test/rpc/txpool/content.spec.ts @@ -1,4 +1,4 @@ -import { createBlock, createHeader } from '@ethereumjs/block' +import { createBlock, createBlockHeader } from '@ethereumjs/block' import { createBlockchain } from '@ethereumjs/blockchain' import { Common, Hardfork, Mainnet } from '@ethereumjs/common' import { getGenesis } from '@ethereumjs/genesis' @@ -53,7 +53,7 @@ describe(method, () => { const headBlock = await service.chain.getCanonicalHeadBlock() const londonBlock = createBlock( { - header: createHeader( + header: createBlockHeader( { baseFeePerGas: 1000000000n, number: 2n, diff --git a/packages/client/test/sync/fetcher/blockfetcher.spec.ts b/packages/client/test/sync/fetcher/blockfetcher.spec.ts index 830ccdf24e..15c04cd7f1 100644 --- a/packages/client/test/sync/fetcher/blockfetcher.spec.ts +++ b/packages/client/test/sync/fetcher/blockfetcher.spec.ts @@ -1,4 +1,4 @@ -import { createHeader } from '@ethereumjs/block' +import { createBlockHeader } from '@ethereumjs/block' import { Hardfork } from '@ethereumjs/common' import { KECCAK256_RLP } from '@ethereumjs/util' import { assert, describe, it, vi } from 'vitest' @@ -207,7 +207,7 @@ describe('[BlockFetcher]', async () => { count: BigInt(0), }) - const shanghaiHeader = createHeader( + const shanghaiHeader = createBlockHeader( { number: 1, withdrawalsRoot: KECCAK256_RLP }, { common: config.chainCommon, setHardfork: true }, ) diff --git a/packages/client/test/sync/lightsync.spec.ts b/packages/client/test/sync/lightsync.spec.ts index 93a7dde658..e8d718e1fb 100644 --- a/packages/client/test/sync/lightsync.spec.ts +++ b/packages/client/test/sync/lightsync.spec.ts @@ -1,4 +1,4 @@ -import { createHeader } from '@ethereumjs/block' +import { createBlockHeader } from '@ethereumjs/block' import * as td from 'testdouble' import { assert, describe, it, vi } from 'vitest' @@ -182,7 +182,7 @@ describe('import headers', () => { } as any) td.when(HeaderFetcher.prototype.fetch()).thenResolve(true) td.when(HeaderFetcher.prototype.fetch()).thenDo(() => - config.events.emit(Event.SYNC_FETCHED_HEADERS, [createHeader({})]), + config.events.emit(Event.SYNC_FETCHED_HEADERS, [createBlockHeader({})]), ) config.logger.on('data', async (data) => { if ((data.message as string).includes('Imported headers count=1')) { diff --git a/packages/client/test/sync/snapsync.spec.ts b/packages/client/test/sync/snapsync.spec.ts index dec6bc67e8..1f5683ca31 100644 --- a/packages/client/test/sync/snapsync.spec.ts +++ b/packages/client/test/sync/snapsync.spec.ts @@ -1,4 +1,4 @@ -import { createHeader } from '@ethereumjs/block' +import { createBlockHeader } from '@ethereumjs/block' import { assert, describe, it, vi } from 'vitest' import { Chain } from '../../src/blockchain/index.js' @@ -72,8 +72,12 @@ describe('[SnapSynchronizer]', async () => { chain, } as any) ;(sync as any).chain = { blocks: { height: 1 } } - const getBlockHeaders1 = vi.fn().mockReturnValue([BigInt(1), [createHeader({ number: 1 })]]) - const getBlockHeaders2 = vi.fn().mockReturnValue([BigInt(2), [createHeader({ number: 2 })]]) + const getBlockHeaders1 = vi + .fn() + .mockReturnValue([BigInt(1), [createBlockHeader({ number: 1 })]]) + const getBlockHeaders2 = vi + .fn() + .mockReturnValue([BigInt(2), [createBlockHeader({ number: 2 })]]) const peers = [ { snap: {}, diff --git a/packages/common/src/chains.ts b/packages/common/src/chains.ts index ccbc87718e..b463c81d1b 100644 --- a/packages/common/src/chains.ts +++ b/packages/common/src/chains.ts @@ -3,7 +3,7 @@ import type { ChainConfig } from './types.js' export const Mainnet: ChainConfig = { name: 'mainnet', chainId: 1, - defaultHardfork: 'shanghai', + defaultHardfork: 'cancun', consensus: { type: 'pow', algorithm: 'ethash', @@ -156,7 +156,7 @@ export const Mainnet: ChainConfig = { export const Goerli: ChainConfig = { name: 'goerli', chainId: 5, - defaultHardfork: 'shanghai', + defaultHardfork: 'cancun', consensus: { type: 'poa', algorithm: 'clique', @@ -317,7 +317,7 @@ export const Goerli: ChainConfig = { export const Sepolia: ChainConfig = { name: 'sepolia', chainId: 11155111, - defaultHardfork: 'shanghai', + defaultHardfork: 'cancun', consensus: { type: 'pow', algorithm: 'ethash', diff --git a/packages/common/src/common.ts b/packages/common/src/common.ts index 28022d4f01..2a19008654 100644 --- a/packages/common/src/common.ts +++ b/packages/common/src/common.ts @@ -61,7 +61,7 @@ export class Common { this.events = new EventEmitter() this._chainParams = opts.chain - this.DEFAULT_HARDFORK = this._chainParams.defaultHardfork ?? Hardfork.Shanghai + this.DEFAULT_HARDFORK = this._chainParams.defaultHardfork ?? Hardfork.Cancun // Assign hardfork changes in the sequence of the applied hardforks this.HARDFORK_CHANGES = this.hardforks().map((hf) => [ hf.name, diff --git a/packages/common/src/constructors.ts b/packages/common/src/constructors.ts index f5fb13ee0d..cf6e51e70c 100644 --- a/packages/common/src/constructors.ts +++ b/packages/common/src/constructors.ts @@ -35,7 +35,7 @@ export function createCustomCommon( /** * Static method to load and set common from a geth genesis json * @param genesisJson json of geth configuration - * @param { Mainnet, eips, genesisHash, hardfork, mergeForkIdPostMerge } to further configure the common instance + * @param opts additional {@link GethConfigOpts} for configuring common * @returns Common */ export function createCommonFromGethGenesis( diff --git a/packages/common/src/interfaces.ts b/packages/common/src/interfaces.ts index 1768e417b1..29c7b259df 100644 --- a/packages/common/src/interfaces.ts +++ b/packages/common/src/interfaces.ts @@ -209,4 +209,35 @@ export interface StateManagerInterface { */ clearCaches(): void shallowCopy(downlevelCaches?: boolean): StateManagerInterface + + /* + * Cache properties + */ + _accountCache?: Cache + _storageCache?: Cache + _codeCache?: Cache + + _accountCacheSettings?: CacheSettings + _storageCacheSettings?: CacheSettings + _codeCacheSettings?: CacheSettings +} + +/** + * Cache related + */ +export enum CacheType { + LRU = 'lru', + ORDERED_MAP = 'ordered_map', +} + +export type CacheSettings = { + deactivate: boolean + type: CacheType + size: number +} + +interface Cache { + checkpoint(): void + commit(): void + revert(): void } diff --git a/packages/common/src/utils.ts b/packages/common/src/utils.ts index 55796081eb..090591a69a 100644 --- a/packages/common/src/utils.ts +++ b/packages/common/src/utils.ts @@ -85,7 +85,8 @@ function parseGethParams(json: any) { // so the Merge/Paris hardfork block must be 0 if ( config.terminalTotalDifficulty !== undefined && - (config.terminalTotalDifficulty > 0 || config.terminalTotalDifficultyPassed === false) + (BigInt(difficulty) < BigInt(config.terminalTotalDifficulty) || + config.terminalTotalDifficultyPassed === false) ) { throw new Error('nonzero terminal total difficulty is not supported') } diff --git a/packages/common/test/chains.spec.ts b/packages/common/test/chains.spec.ts index 3cc5c21d79..a96ca4e951 100644 --- a/packages/common/test/chains.spec.ts +++ b/packages/common/test/chains.spec.ts @@ -15,7 +15,7 @@ describe('[Common/Chains]: Initialization / Chain params', () => { const c = new Common({ chain: Mainnet }) assert.equal(c.chainName(), 'mainnet', 'should initialize with chain name') assert.equal(c.chainId(), BigInt(1), 'should return correct chain Id') - assert.equal(c.hardfork(), Hardfork.Shanghai, 'should set hardfork to current default hardfork') + assert.equal(c.hardfork(), Hardfork.Cancun, 'should set hardfork to current default hardfork') assert.equal( c.hardfork(), c.DEFAULT_HARDFORK, diff --git a/packages/common/test/customChains.spec.ts b/packages/common/test/customChains.spec.ts index 0f903c8b44..02c3cacd0f 100644 --- a/packages/common/test/customChains.spec.ts +++ b/packages/common/test/customChains.spec.ts @@ -87,9 +87,9 @@ describe('[Common]: Custom chains', () => { }, Mainnet, ) - // Note: default HF of Common is currently Shanghai + // Note: default HF of Common is currently Cancun // Did not pass any "hardfork" param - assert.equal(c.hardfork(), Hardfork.Shanghai) + assert.equal(c.hardfork(), Hardfork.Cancun) c.setHardforkBy({ blockNumber: 0, }) diff --git a/packages/devp2p/examples/peer-communication-les.ts b/packages/devp2p/examples/peer-communication-les.ts index 3584428e8a..1b40d26149 100644 --- a/packages/devp2p/examples/peer-communication-les.ts +++ b/packages/devp2p/examples/peer-communication-les.ts @@ -1,4 +1,4 @@ -import { createBlockFromValuesArray, createHeaderFromValuesArray } from '@ethereumjs/block' +import { createBlockFromValuesArray, createBlockHeaderFromValuesArray } from '@ethereumjs/block' import { Common, Hardfork, Mainnet } from '@ethereumjs/common' import * as devp2p from '@ethereumjs/devp2p' import { bytesToHex, bytesToInt, hexToBytes, intToBytes, randomBytes } from '@ethereumjs/util' @@ -109,7 +109,7 @@ rlpx.events.on('peer:added', (peer) => { ) break } - const header = createHeaderFromValuesArray(payload[2][0], { common }) + const header = createBlockHeaderFromValuesArray(payload[2][0], { common }) setTimeout(() => { les.sendMessage(devp2p.LES.MESSAGE_CODES.GET_BLOCK_BODIES, [ diff --git a/packages/devp2p/examples/peer-communication.ts b/packages/devp2p/examples/peer-communication.ts index a74fb50f26..a3600b15c4 100644 --- a/packages/devp2p/examples/peer-communication.ts +++ b/packages/devp2p/examples/peer-communication.ts @@ -174,7 +174,7 @@ rlpx.events.on('peer:added', (peer) => { } const expectedHash = CHECK_BLOCK - const header = createHeaderFromValuesArray(payload[1][0], { common }) + const header = createBlockHeaderFromValuesArray(payload[1][0], { common }) if (bytesToUnprefixedHex(header.hash()) === expectedHash) { console.log(`${addr} verified to be on the same side of the ${CHECK_BLOCK_TITLE}`) clearTimeout(forkDrop) @@ -189,7 +189,7 @@ rlpx.events.on('peer:added', (peer) => { } let isValidPayload = false - const header = createHeaderFromValuesArray(payload[1][0], { common }) + const header = createBlockHeaderFromValuesArray(payload[1][0], { common }) while (requests.headers.length > 0) { const blockHash = requests.headers.shift() if (equalsBytes(header.hash(), blockHash)) { diff --git a/packages/devp2p/src/rlpx/ecies.ts b/packages/devp2p/src/rlpx/ecies.ts index 4eaa7455d5..fd59b7af8e 100644 --- a/packages/devp2p/src/rlpx/ecies.ts +++ b/packages/devp2p/src/rlpx/ecies.ts @@ -356,7 +356,7 @@ export class ECIES { this.parseAckPlain(data.subarray(2), data.subarray(0, 2)) } - createHeader(size: number): Uint8Array | undefined { + createBlockHeader(size: number): Uint8Array | undefined { const bufSize = zfill(intToBytes(size), 3) const headerData = RLP.encode([0, 0]) // [capability-id, context-id] (currently unused in spec) let header = concatBytes(bufSize, headerData) diff --git a/packages/devp2p/src/rlpx/peer.ts b/packages/devp2p/src/rlpx/peer.ts index 228cc13bd3..65111987d1 100644 --- a/packages/devp2p/src/rlpx/peer.ts +++ b/packages/devp2p/src/rlpx/peer.ts @@ -200,7 +200,7 @@ export class Peer { if (this._closed) return false const msg = concatBytes(RLP.encode(code), data) - const header = this._eciesSession.createHeader(msg.length) + const header = this._eciesSession.createBlockHeader(msg.length) if (!header || this._socket.destroyed) return this._socket.write(header) diff --git a/packages/devp2p/test/rlpx-ecies.spec.ts b/packages/devp2p/test/rlpx-ecies.spec.ts index 4e857a477f..72d9e6c2de 100644 --- a/packages/devp2p/test/rlpx-ecies.spec.ts +++ b/packages/devp2p/test/rlpx-ecies.spec.ts @@ -84,8 +84,8 @@ it( const body = getRandomBytesSync(600) - const header = t.context.b.parseHeader(t.context.a.createHeader(body.length) as Uint8Array) - assert.equal(header, body.length, 'createHeader -> parseHeader should lead to same') + const header = t.context.b.parseHeader(t.context.a.createBlockHeader(body.length) as Uint8Array) + assert.equal(header, body.length, 'createBlockHeader -> parseHeader should lead to same') const parsedBody = t.context.b.parseBody(t.context.a.createBody(body) as Uint8Array) assert.deepEqual(parsedBody, body, 'createBody -> parseBody should lead to same') diff --git a/packages/ethash/src/index.ts b/packages/ethash/src/index.ts index dd3b148fca..41c3739e70 100644 --- a/packages/ethash/src/index.ts +++ b/packages/ethash/src/index.ts @@ -1,4 +1,4 @@ -import { Block, BlockHeader, createBlock, createHeader } from '@ethereumjs/block' +import { Block, BlockHeader, createBlock, createBlockHeader } from '@ethereumjs/block' import { RLP } from '@ethereumjs/rlp' import { BIGINT_0, @@ -101,7 +101,7 @@ export class Miner { const data = this.blockHeader.toJSON() data.mixHash = solution.mixHash data.nonce = solution.nonce - return createHeader(data, { common: this.blockHeader.common }) + return createBlockHeader(data, { common: this.blockHeader.common }) } } } diff --git a/packages/ethash/test/ethash.spec.ts b/packages/ethash/test/ethash.spec.ts index ff28017c86..d22e26823c 100644 --- a/packages/ethash/test/ethash.spec.ts +++ b/packages/ethash/test/ethash.spec.ts @@ -1,4 +1,4 @@ -import { createHeaderFromRLP } from '@ethereumjs/block' +import { createBlockHeaderFromRLP } from '@ethereumjs/block' import { Common, Hardfork, Mainnet } from '@ethereumjs/common' import { bytesToHex, hexToBytes } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' @@ -16,7 +16,7 @@ describe('POW tests', () => { it('should work', async () => { for (const key of tests) { const test = powTests[key] - const header = createHeaderFromRLP(hexToBytes(`0x${test.header}`), { common }) + const header = createBlockHeaderFromRLP(hexToBytes(`0x${test.header}`), { common }) const headerHash = ethash.headerHash(header.raw()) assert.equal(bytesToHex(headerHash), '0x' + test.header_hash, 'generate header hash') diff --git a/packages/evm/package.json b/packages/evm/package.json index bdd1015585..b136324d2d 100644 --- a/packages/evm/package.json +++ b/packages/evm/package.json @@ -60,10 +60,10 @@ "@ethereumjs/statemanager": "^2.3.0", "@ethereumjs/tx": "^5.3.0", "@ethereumjs/util": "^9.0.3", + "@noble/curves": "^1.4.2", "@types/debug": "^4.1.9", "debug": "^4.3.3", "ethereum-cryptography": "^2.2.1", - "@noble/curves": "^1.4.2", "rustbn-wasm": "^0.4.0" }, "devDependencies": { @@ -81,7 +81,8 @@ "minimist": "^1.2.5", "node-dir": "^0.1.17", "rollup-plugin-visualizer": "^5.12.0", - "solc": "^0.8.1" + "solc": "^0.8.1", + "split": "^1.0.1" }, "engines": { "node": ">=18" diff --git a/packages/evm/scripts/eofContainerValidator.ts b/packages/evm/scripts/eofContainerValidator.ts new file mode 100644 index 0000000000..a1265db084 --- /dev/null +++ b/packages/evm/scripts/eofContainerValidator.ts @@ -0,0 +1,36 @@ +import { Common, Hardfork, Mainnet } from '@ethereumjs/common' +import { unprefixedHexToBytes } from '@ethereumjs/util' +import split from 'split' + +import { createEVM, validateEOF } from '../src/index.js' + +/** + * This script reads hex strings (either prefixed or non-prefixed with 0x) from stdin + * It tries to validate the EOF container, if it is valid, it will print "OK" + * If there is a validation error, it will print "err: " + * If the input is emtpy, the program will exit + */ + +const common = new Common({ chain: Mainnet }) +common.setHardfork(Hardfork.Prague) +common.setEIPs([663, 3540, 3670, 4200, 4750, 5450, 6206, 7069, 7480, 7620, 7692, 7698]) +const evm = await createEVM({ common }) + +function processLine(line) { + if (line.length === 0) { + process.exit() + } + let trimmed = line + if (line.startsWith('0x')) { + trimmed = line.slice(2) + } + const bytes = unprefixedHexToBytes(trimmed) + try { + validateEOF(bytes, evm) + console.log('OK') + } catch (e: any) { + console.log('err: ' + e.message) + } +} + +process.stdin.pipe(split()).on('data', processLine) diff --git a/packages/evm/src/index.ts b/packages/evm/src/index.ts index dc79d5c626..94ab69aff6 100644 --- a/packages/evm/src/index.ts +++ b/packages/evm/src/index.ts @@ -1,3 +1,4 @@ +import { EOFContainer, validateEOF } from './eof/container.js' import { EVM } from './evm.js' import { ERROR as EVMErrorMessage, EvmError } from './exceptions.js' import { Message } from './message.js' @@ -36,6 +37,7 @@ export type { } export { + EOFContainer, EVM, EvmError, EVMErrorMessage, @@ -44,6 +46,7 @@ export { MCLBLS, Message, NobleBLS, + validateEOF, } export * from './constructors.js' diff --git a/packages/statemanager/src/cache/account.ts b/packages/statemanager/src/cache/account.ts index 216abeb54d..eedb7ef5c5 100644 --- a/packages/statemanager/src/cache/account.ts +++ b/packages/statemanager/src/cache/account.ts @@ -1,10 +1,10 @@ +import { CacheType } from '@ethereumjs/common' import { bytesToUnprefixedHex } from '@ethereumjs/util' import { OrderedMap } from '@js-sdsl/ordered-map' import debugDefault from 'debug' import { LRUCache } from 'lru-cache' import { Cache } from './cache.js' -import { CacheType } from './types.js' import type { CacheOpts } from './types.js' import type { Account, Address } from '@ethereumjs/util' diff --git a/packages/statemanager/src/cache/code.ts b/packages/statemanager/src/cache/code.ts index 3aaeb25db8..61a957de62 100644 --- a/packages/statemanager/src/cache/code.ts +++ b/packages/statemanager/src/cache/code.ts @@ -1,10 +1,10 @@ +import { CacheType } from '@ethereumjs/common' import { bytesToUnprefixedHex } from '@ethereumjs/util' import { OrderedMap } from '@js-sdsl/ordered-map' import debugDefault from 'debug' import { LRUCache } from 'lru-cache' import { Cache } from './cache.js' -import { CacheType } from './types.js' import type { CacheOpts } from './types.js' import type { Address } from '@ethereumjs/util' diff --git a/packages/statemanager/src/cache/storage.ts b/packages/statemanager/src/cache/storage.ts index 345e74ad3b..6c9c153e14 100644 --- a/packages/statemanager/src/cache/storage.ts +++ b/packages/statemanager/src/cache/storage.ts @@ -1,10 +1,10 @@ +import { CacheType } from '@ethereumjs/common' import { bytesToUnprefixedHex, hexToBytes } from '@ethereumjs/util' import { OrderedMap } from '@js-sdsl/ordered-map' import debugDefault from 'debug' import { LRUCache } from 'lru-cache' import { Cache } from './cache.js' -import { CacheType } from './types.js' import type { CacheOpts } from './types.js' import type { Address } from '@ethereumjs/util' diff --git a/packages/statemanager/src/cache/types.ts b/packages/statemanager/src/cache/types.ts index 0e5b3d40f6..7f283d7c65 100644 --- a/packages/statemanager/src/cache/types.ts +++ b/packages/statemanager/src/cache/types.ts @@ -1,7 +1,4 @@ -export enum CacheType { - LRU = 'lru', - ORDERED_MAP = 'ordered_map', -} +import type { CacheType } from '@ethereumjs/common' export interface CacheOpts { size: number diff --git a/packages/statemanager/src/capabilities.ts b/packages/statemanager/src/capabilities.ts new file mode 100644 index 0000000000..9b48cd0468 --- /dev/null +++ b/packages/statemanager/src/capabilities.ts @@ -0,0 +1,88 @@ +import { type AccountFields, CacheType, type StateManagerInterface } from '@ethereumjs/common' +import { Account } from '@ethereumjs/util' + +import { AccountCache, CodeCache, OriginalStorageCache, StorageCache } from './cache/index.js' + +import type { CacheStateManagerOpts } from './types.js' +import type { Address } from '@ethereumjs/util' + +export function checkpointCaches(stateManager: StateManagerInterface): void { + stateManager._accountCache?.checkpoint() + stateManager._storageCache?.checkpoint() + stateManager._codeCache?.checkpoint() +} + +export function commitCaches(stateManager: StateManagerInterface): void { + stateManager._accountCache?.commit() + stateManager._storageCache?.commit() + stateManager._codeCache?.commit() +} + +export function initializeCaches( + stateManager: StateManagerInterface, + options: CacheStateManagerOpts, +): void { + stateManager.originalStorageCache = new OriginalStorageCache( + stateManager.getStorage.bind(stateManager), + ) + + stateManager._accountCacheSettings = { + deactivate: options.accountCacheOpts?.deactivate ?? false, + type: options.accountCacheOpts?.type ?? CacheType.ORDERED_MAP, + size: options.accountCacheOpts?.size ?? 100000, + } + + if (stateManager._accountCacheSettings.deactivate === false) { + stateManager._accountCache = new AccountCache({ + size: stateManager._accountCacheSettings.size, + type: stateManager._accountCacheSettings.type, + }) + } + + stateManager._storageCacheSettings = { + deactivate: options.storageCacheOpts?.deactivate ?? false, + type: options.storageCacheOpts?.type ?? CacheType.ORDERED_MAP, + size: options.storageCacheOpts?.size ?? 20000, + } + + if (stateManager._storageCacheSettings.deactivate === false) { + stateManager._storageCache = new StorageCache({ + size: stateManager._storageCacheSettings.size, + type: stateManager._storageCacheSettings.type, + }) + } + + stateManager._codeCacheSettings = { + deactivate: + (options.codeCacheOpts?.deactivate === true || options.codeCacheOpts?.size === 0) ?? false, + type: options.codeCacheOpts?.type ?? CacheType.ORDERED_MAP, + size: options.codeCacheOpts?.size ?? 20000, + } + + if (stateManager._codeCacheSettings.deactivate === false) { + stateManager._codeCache = new CodeCache({ + size: stateManager._codeCacheSettings.size, + type: stateManager._codeCacheSettings.type, + }) + } +} + +export async function modifyAccountFields( + stateManager: StateManagerInterface, + address: Address, + accountFields: AccountFields, +): Promise { + const account = (await stateManager.getAccount(address)) ?? new Account() + + account.nonce = accountFields.nonce ?? account.nonce + account.balance = accountFields.balance ?? account.balance + account.storageRoot = accountFields.storageRoot ?? account.storageRoot + account.codeHash = accountFields.codeHash ?? account.codeHash + await stateManager.putAccount(address, account) +} + +export function revertCaches(stateManager: StateManagerInterface): void { + stateManager._accountCache?.revert() + stateManager._storageCache?.revert() + stateManager._codeCache?.revert() +} diff --git a/packages/statemanager/src/rpcStateManager.ts b/packages/statemanager/src/rpcStateManager.ts index 198dd25a94..2c6016aac4 100644 --- a/packages/statemanager/src/rpcStateManager.ts +++ b/packages/statemanager/src/rpcStateManager.ts @@ -1,4 +1,4 @@ -import { Common, Mainnet } from '@ethereumjs/common' +import { CacheType, Common, Mainnet } from '@ethereumjs/common' import { RLP } from '@ethereumjs/rlp' import { verifyTrieProof } from '@ethereumjs/trie' import { @@ -16,10 +16,11 @@ import { import debugDefault from 'debug' import { keccak256 } from 'ethereum-cryptography/keccak.js' -import { AccountCache, CacheType, OriginalStorageCache, StorageCache } from './cache/index.js' +import { AccountCache, OriginalStorageCache, StorageCache } from './cache/index.js' +import * as Capabilities from './capabilities.js' -import type { Proof, RPCStateManagerOpts } from './index.js' -import type { AccountFields, StateManagerInterface, StorageDump } from '@ethereumjs/common' +import type { RPCStateManagerOpts } from './index.js' +import type { AccountFields, Proof, StateManagerInterface, StorageDump } from '@ethereumjs/common' import type { Address, PrefixedHexString } from '@ethereumjs/util' import type { Debugger } from 'debug' @@ -27,12 +28,14 @@ const KECCAK256_RLP_EMPTY_ACCOUNT = RLP.encode(new Account().serialize()).slice( export class RPCStateManager implements StateManagerInterface { protected _provider: string - protected _contractCache: Map - protected _storageCache: StorageCache protected _blockTag: string - protected _accountCache: AccountCache + + _accountCache: AccountCache + _storageCache: StorageCache + _contractCache: Map + originalStorageCache: OriginalStorageCache - protected _debug: Debugger + _debug: Debugger protected DEBUG: boolean private keccakFunction: Function public readonly common: Common @@ -317,15 +320,7 @@ export class RPCStateManager implements StateManagerInterface { ), ) } - let account = await this.getAccount(address) - if (!account) { - account = new Account() - } - account.nonce = accountFields.nonce ?? account.nonce - account.balance = accountFields.balance ?? account.balance - account.storageRoot = accountFields.storageRoot ?? account.storageRoot - account.codeHash = accountFields.codeHash ?? account.codeHash - await this.putAccount(address, account) + await Capabilities.modifyAccountFields(this, address, accountFields) } /** diff --git a/packages/statemanager/src/simpleStateManager.ts b/packages/statemanager/src/simpleStateManager.ts index 8c58c616ba..58d6977a96 100644 --- a/packages/statemanager/src/simpleStateManager.ts +++ b/packages/statemanager/src/simpleStateManager.ts @@ -2,6 +2,7 @@ import { Account, bytesToHex } from '@ethereumjs/util' import { keccak256 } from 'ethereum-cryptography/keccak.js' import { OriginalStorageCache } from './cache/originalStorageCache.js' +import * as Capabilities from './capabilities.js' import type { SimpleStateManagerOpts } from './index.js' import type { AccountFields, Common, StateManagerInterface } from '@ethereumjs/common' @@ -78,15 +79,7 @@ export class SimpleStateManager implements StateManagerInterface { } async modifyAccountFields(address: Address, accountFields: AccountFields): Promise { - let account = await this.getAccount(address) - if (!account) { - account = new Account() - } - account.nonce = accountFields.nonce ?? account.nonce - account.balance = accountFields.balance ?? account.balance - account.storageRoot = accountFields.storageRoot ?? account.storageRoot - account.codeHash = accountFields.codeHash ?? account.codeHash - await this.putAccount(address, account) + await Capabilities.modifyAccountFields(this, address, accountFields) } async getCode(address: Address): Promise { diff --git a/packages/statemanager/src/stateManager.ts b/packages/statemanager/src/stateManager.ts index 9e05681adb..7daf7e1917 100644 --- a/packages/statemanager/src/stateManager.ts +++ b/packages/statemanager/src/stateManager.ts @@ -1,10 +1,10 @@ -import { Common, Mainnet } from '@ethereumjs/common' +import { CacheType, Common, Mainnet } from '@ethereumjs/common' import { RLP } from '@ethereumjs/rlp' import { Trie, - createProof, + createMerkleProof, createTrieFromProof, - updateFromProof, + updateTrieFromMerkleProof, verifyTrieProof, } from '@ethereumjs/trie' import { @@ -31,22 +31,17 @@ import { import debugDefault from 'debug' import { keccak256 } from 'ethereum-cryptography/keccak.js' -import { - AccountCache, - CacheType, - CodeCache, - OriginalStorageCache, - StorageCache, -} from './cache/index.js' +import * as Capabilities from './capabilities.js' import { CODEHASH_PREFIX, type CacheSettings, type DefaultStateManagerOpts } from './index.js' -import type { StorageProof } from './index.js' +import type { AccountCache, CodeCache, OriginalStorageCache, StorageCache } from './cache/index.js' import type { AccountFields, Proof, StateManagerInterface, StorageDump, + StorageProof, StorageRange, } from '@ethereumjs/common' import type { Address, DB, PrefixedHexString } from '@ethereumjs/util' @@ -69,20 +64,21 @@ import type { Debugger } from 'debug' */ export class DefaultStateManager implements StateManagerInterface { protected _debug: Debugger - protected _accountCache?: AccountCache - protected _storageCache?: StorageCache - protected _codeCache?: CodeCache - - originalStorageCache: OriginalStorageCache + _accountCache?: AccountCache + _storageCache?: StorageCache + _codeCache?: CodeCache protected _trie: Trie protected _storageTries: { [key: string]: Trie } protected readonly _prefixCodeHashes: boolean protected readonly _prefixStorageTrieKeys: boolean - protected readonly _accountCacheSettings: CacheSettings - protected readonly _storageCacheSettings: CacheSettings - protected readonly _codeCacheSettings: CacheSettings + + // Non-null assertion necessary to inform TypeScript that these properties are set in the constructor through a helper function + originalStorageCache!: OriginalStorageCache + readonly _accountCacheSettings!: CacheSettings + readonly _storageCacheSettings!: CacheSettings + readonly _codeCacheSettings!: CacheSettings public readonly common: Common @@ -120,48 +116,10 @@ export class DefaultStateManager implements StateManagerInterface { this.keccakFunction = opts.common?.customCrypto.keccak256 ?? keccak256 - this.originalStorageCache = new OriginalStorageCache(this.getStorage.bind(this)) - this._prefixCodeHashes = opts.prefixCodeHashes ?? true this._prefixStorageTrieKeys = opts.prefixStorageTrieKeys ?? false - this._accountCacheSettings = { - deactivate: - (opts.accountCacheOpts?.deactivate === true || opts.accountCacheOpts?.size === 0) ?? false, - type: opts.accountCacheOpts?.type ?? CacheType.ORDERED_MAP, - size: opts.accountCacheOpts?.size ?? 100000, - } - if (!this._accountCacheSettings.deactivate) { - this._accountCache = new AccountCache({ - size: this._accountCacheSettings.size, - type: this._accountCacheSettings.type, - }) - } - - this._storageCacheSettings = { - deactivate: - (opts.storageCacheOpts?.deactivate === true || opts.storageCacheOpts?.size === 0) ?? false, - type: opts.storageCacheOpts?.type ?? CacheType.ORDERED_MAP, - size: opts.storageCacheOpts?.size ?? 20000, - } - if (!this._storageCacheSettings.deactivate) { - this._storageCache = new StorageCache({ - size: this._storageCacheSettings.size, - type: this._storageCacheSettings.type, - }) - } - this._codeCacheSettings = { - deactivate: - (opts.codeCacheOpts?.deactivate === true || opts.codeCacheOpts?.size === 0) ?? false, - type: opts.codeCacheOpts?.type ?? CacheType.ORDERED_MAP, - size: opts.codeCacheOpts?.size ?? 20000, - } - if (!this._codeCacheSettings.deactivate) { - this._codeCache = new CodeCache({ - size: this._codeCacheSettings.size, - type: this._codeCacheSettings.type, - }) - } + Capabilities.initializeCaches(this, opts) } /** @@ -224,15 +182,7 @@ export class DefaultStateManager implements StateManagerInterface { * @param accountFields - Object containing account fields and values to modify */ async modifyAccountFields(address: Address, accountFields: AccountFields): Promise { - let account = await this.getAccount(address) - if (!account) { - account = new Account() - } - account.nonce = accountFields.nonce ?? account.nonce - account.balance = accountFields.balance ?? account.balance - account.storageRoot = accountFields.storageRoot ?? account.storageRoot - account.codeHash = accountFields.codeHash ?? account.codeHash - await this.putAccount(address, account) + await Capabilities.modifyAccountFields(this, address, accountFields) } /** @@ -512,9 +462,7 @@ export class DefaultStateManager implements StateManagerInterface { */ async checkpoint(): Promise { this._trie.checkpoint() - this._storageCache?.checkpoint() - this._accountCache?.checkpoint() - this._codeCache?.checkpoint() + Capabilities.checkpointCaches(this) this._checkpointCount++ } @@ -525,9 +473,7 @@ export class DefaultStateManager implements StateManagerInterface { async commit(): Promise { // setup trie checkpointing await this._trie.commit() - this._storageCache?.commit() - this._accountCache?.commit() - this._codeCache?.commit() + Capabilities.commitCaches(this) this._checkpointCount-- if (this._checkpointCount === 0) { @@ -547,9 +493,7 @@ export class DefaultStateManager implements StateManagerInterface { async revert(): Promise { // setup trie checkpointing await this._trie.revert() - this._storageCache?.revert() - this._accountCache?.revert() - this._codeCache?.revert() + Capabilities.revertCaches(this) this._storageTries = {} @@ -635,19 +579,21 @@ export class DefaultStateManager implements StateManagerInterface { codeHash: KECCAK256_NULL_S, nonce: '0x0', storageHash: KECCAK256_RLP_S, - accountProof: (await createProof(this._trie, address.bytes)).map((p) => bytesToHex(p)), + accountProof: (await createMerkleProof(this._trie, address.bytes)).map((p) => + bytesToHex(p), + ), storageProof: [], } return returnValue } - const accountProof: PrefixedHexString[] = (await createProof(this._trie, address.bytes)).map( - (p) => bytesToHex(p), - ) + const accountProof: PrefixedHexString[] = ( + await createMerkleProof(this._trie, address.bytes) + ).map((p) => bytesToHex(p)) const storageProof: StorageProof[] = [] const storageTrie = this._getStorageTrie(address, account) for (const storageKey of storageSlots) { - const proof = (await createProof(storageTrie, storageKey)).map((p) => bytesToHex(p)) + const proof = (await createMerkleProof(storageTrie, storageKey)).map((p) => bytesToHex(p)) const value = bytesToHex(await this.getStorage(address, storageKey)) const proofItem: StorageProof = { key: bytesToHex(storageKey), @@ -723,7 +669,7 @@ export class DefaultStateManager implements StateManagerInterface { const trie = this._getStorageTrie(address) trie.root(hexToBytes(storageHash)) for (let i = 0; i < storageProof.length; i++) { - await updateFromProof( + await updateTrieFromMerkleProof( trie, storageProof[i].proof.map((e) => hexToBytes(e)), safe, @@ -740,7 +686,7 @@ export class DefaultStateManager implements StateManagerInterface { async addProofData(proof: Proof | Proof[], safe: boolean = false) { if (Array.isArray(proof)) { for (let i = 0; i < proof.length; i++) { - await updateFromProof( + await updateTrieFromMerkleProof( this._trie, proof[i].accountProof.map((e) => hexToBytes(e)), safe, diff --git a/packages/statemanager/src/statelessVerkleStateManager.ts b/packages/statemanager/src/statelessVerkleStateManager.ts index 4fc1d33211..cc9b93d15f 100644 --- a/packages/statemanager/src/statelessVerkleStateManager.ts +++ b/packages/statemanager/src/statelessVerkleStateManager.ts @@ -25,16 +25,16 @@ import debugDefault from 'debug' import { keccak256 } from 'ethereum-cryptography/keccak.js' import { AccessWitness, AccessedStateType, decodeValue } from './accessWitness.js' +import * as Capabilities from './capabilities.js' + import { - AccountCache, - CacheType, - CodeCache, - OriginalStorageCache, - StorageCache, -} from './cache/index.js' + type CacheSettings, + type StatelessVerkleStateManagerOpts, + type VerkleState, +} from './index.js' import type { AccessedStateWithAddress } from './accessWitness.js' -import type { CacheSettings, StatelessVerkleStateManagerOpts, VerkleState } from './index.js' +import type { AccountCache, CodeCache, OriginalStorageCache, StorageCache } from './cache/index.js' import type { DefaultStateManager } from './stateManager.js' import type { AccountFields, Proof, StateManagerInterface } from '@ethereumjs/common' import type { @@ -72,12 +72,13 @@ export class StatelessVerkleStateManager implements StateManagerInterface { _codeCache?: CodeCache _cachedStateRoot?: Uint8Array - originalStorageCache: OriginalStorageCache - verkleCrypto: VerkleCrypto - protected readonly _accountCacheSettings: CacheSettings - protected readonly _storageCacheSettings: CacheSettings - protected readonly _codeCacheSettings: CacheSettings + + // Non-null assertion necessary to inform TypeScript that these properties are set in the constructor through a helper function + originalStorageCache!: OriginalStorageCache + readonly _accountCacheSettings!: CacheSettings + readonly _storageCacheSettings!: CacheSettings + readonly _codeCacheSettings!: CacheSettings /** * StateManager is run in DEBUG mode (default: false) @@ -112,47 +113,7 @@ export class StatelessVerkleStateManager implements StateManagerInterface { * Instantiate the StateManager interface. */ constructor(opts: StatelessVerkleStateManagerOpts) { - this.originalStorageCache = new OriginalStorageCache(this.getStorage.bind(this)) - - this._accountCacheSettings = { - deactivate: opts.accountCacheOpts?.deactivate ?? false, - type: opts.accountCacheOpts?.type ?? CacheType.ORDERED_MAP, - size: opts.accountCacheOpts?.size ?? 100000, - } - - if (!this._accountCacheSettings.deactivate) { - this._accountCache = new AccountCache({ - size: this._accountCacheSettings.size, - type: this._accountCacheSettings.type, - }) - } - - this._storageCacheSettings = { - deactivate: opts.storageCacheOpts?.deactivate ?? false, - type: opts.storageCacheOpts?.type ?? CacheType.ORDERED_MAP, - size: opts.storageCacheOpts?.size ?? 20000, - } - - if (!this._storageCacheSettings.deactivate) { - this._storageCache = new StorageCache({ - size: this._storageCacheSettings.size, - type: this._storageCacheSettings.type, - }) - } - - this._codeCacheSettings = { - deactivate: - (opts.codeCacheOpts?.deactivate === true || opts.codeCacheOpts?.size === 0) ?? false, - type: opts.codeCacheOpts?.type ?? CacheType.ORDERED_MAP, - size: opts.codeCacheOpts?.size ?? 20000, - } - - if (!this._codeCacheSettings.deactivate) { - this._codeCache = new CodeCache({ - size: this._codeCacheSettings.size, - type: this._codeCacheSettings.type, - }) - } + Capabilities.initializeCaches(this, opts) this._cachedStateRoot = opts.initialStateRoot @@ -571,16 +532,7 @@ export class StatelessVerkleStateManager implements StateManagerInterface { } async modifyAccountFields(address: Address, accountFields: AccountFields): Promise { - let account = await this.getAccount(address) - if (!account) { - account = new Account() - } - - account._nonce = accountFields.nonce ?? account._nonce - account._balance = accountFields.balance ?? account._balance - account._storageRoot = accountFields.storageRoot ?? account._storageRoot - account._codeHash = accountFields.codeHash ?? account._codeHash - await this.putAccount(address, account) + await Capabilities.modifyAccountFields(this, address, accountFields) } getProof(_: Address, __: Uint8Array[] = []): Promise { @@ -781,9 +733,7 @@ export class StatelessVerkleStateManager implements StateManagerInterface { */ async checkpoint(): Promise { this._checkpoints.push(this._state) - this._accountCache?.checkpoint() - this._storageCache?.checkpoint() - this._codeCache?.checkpoint() + Capabilities.checkpointCaches(this) } /** @@ -792,9 +742,7 @@ export class StatelessVerkleStateManager implements StateManagerInterface { */ async commit(): Promise { this._checkpoints.pop() - this._accountCache!.commit() - this._storageCache?.commit() - this._codeCache?.commit() + Capabilities.commitCaches(this) } // TODO @@ -809,9 +757,7 @@ export class StatelessVerkleStateManager implements StateManagerInterface { async revert(): Promise { // setup trie checkpointing this._checkpoints.pop() - this._accountCache?.revert() - this._storageCache?.revert() - this._codeCache?.revert() + Capabilities.revertCaches(this) } /** diff --git a/packages/statemanager/src/types.ts b/packages/statemanager/src/types.ts index da35fe4a85..340a21eb3c 100644 --- a/packages/statemanager/src/types.ts +++ b/packages/statemanager/src/types.ts @@ -1,8 +1,7 @@ import { type PrefixedHexString, utf8ToBytes } from '@ethereumjs/util' -import type { CacheType } from './cache/index.js' import type { AccessWitness } from './index.js' -import type { Common } from '@ethereumjs/common' +import type { CacheType, Common } from '@ethereumjs/common' import type { Trie } from '@ethereumjs/trie' import type { VerkleCrypto } from '@ethereumjs/util' @@ -62,7 +61,7 @@ interface BaseStateManagerOpts { /** * Cache state manager options (not to be used directly) */ -interface CacheStateManagerOpts { +export interface CacheStateManagerOpts { accountCacheOpts?: CacheOptions storageCacheOpts?: CacheOptions codeCacheOpts?: CacheOptions @@ -137,19 +136,3 @@ export interface EncodedVerkleProof { * misbehaviour in the underlying trie library. */ export const CODEHASH_PREFIX = utf8ToBytes('c') - -export type StorageProof = { - key: PrefixedHexString - proof: PrefixedHexString[] - value: PrefixedHexString -} - -export type Proof = { - address: PrefixedHexString - balance: PrefixedHexString - codeHash: PrefixedHexString - nonce: PrefixedHexString - storageHash: PrefixedHexString - accountProof: PrefixedHexString[] - storageProof: StorageProof[] -} diff --git a/packages/statemanager/test/cache/account.spec.ts b/packages/statemanager/test/cache/account.spec.ts index 533f62d095..4c69073eb8 100644 --- a/packages/statemanager/test/cache/account.spec.ts +++ b/packages/statemanager/test/cache/account.spec.ts @@ -1,7 +1,8 @@ +import { CacheType } from '@ethereumjs/common' import { Account, Address, equalsBytes, hexToBytes } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' -import { AccountCache, CacheType } from '../../src/cache/index.js' +import { AccountCache } from '../../src/cache/index.js' import { createAccountWithDefaults } from '../util.js' describe('Account Cache: initialization', () => { diff --git a/packages/statemanager/test/cache/code.spec.ts b/packages/statemanager/test/cache/code.spec.ts index 2bbe3eaea7..cc1aac0b40 100644 --- a/packages/statemanager/test/cache/code.spec.ts +++ b/packages/statemanager/test/cache/code.spec.ts @@ -1,7 +1,8 @@ +import { CacheType } from '@ethereumjs/common' import { Address, equalsBytes, hexToBytes } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' -import { CacheType, CodeCache } from '../../src/cache/index.js' +import { CodeCache } from '../../src/cache/index.js' describe('Code Cache: initialization', () => { for (const type of [CacheType.LRU, CacheType.ORDERED_MAP]) { diff --git a/packages/statemanager/test/cache/storage.spec.ts b/packages/statemanager/test/cache/storage.spec.ts index 3fcb30d5f6..dbd9914767 100644 --- a/packages/statemanager/test/cache/storage.spec.ts +++ b/packages/statemanager/test/cache/storage.spec.ts @@ -1,7 +1,8 @@ +import { CacheType } from '@ethereumjs/common' import { Address, equalsBytes, hexToBytes } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' -import { CacheType, StorageCache } from '../../src/cache/index.js' +import { StorageCache } from '../../src/cache/index.js' describe('Storage Cache: initialization', () => { for (const type of [CacheType.LRU, CacheType.ORDERED_MAP]) { diff --git a/packages/statemanager/test/stateManager.spec.ts b/packages/statemanager/test/stateManager.spec.ts index 1744973e3b..6aca9047bb 100644 --- a/packages/statemanager/test/stateManager.spec.ts +++ b/packages/statemanager/test/stateManager.spec.ts @@ -1,3 +1,4 @@ +import { CacheType } from '@ethereumjs/common' import { Trie, createTrie, createTrieFromProof } from '@ethereumjs/trie' import { Account, @@ -14,7 +15,7 @@ import { } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' -import { CacheType, DefaultStateManager } from '../src/index.js' +import { DefaultStateManager } from '../src/index.js' import type { PrefixedHexString } from '@ethereumjs/util' diff --git a/packages/statemanager/test/statelessVerkleStateManager.spec.ts b/packages/statemanager/test/statelessVerkleStateManager.spec.ts index 489d594616..310fcebd7b 100644 --- a/packages/statemanager/test/statelessVerkleStateManager.spec.ts +++ b/packages/statemanager/test/statelessVerkleStateManager.spec.ts @@ -1,5 +1,5 @@ import { createBlock } from '@ethereumjs/block' -import { createCommonFromGethGenesis } from '@ethereumjs/common' +import { CacheType, createCommonFromGethGenesis } from '@ethereumjs/common' import { createTxFromSerializedData } from '@ethereumjs/tx' import { Address, @@ -16,7 +16,7 @@ import { import { loadVerkleCrypto } from 'verkle-cryptography-wasm' import { assert, beforeAll, describe, it, test } from 'vitest' -import { CacheType, StatelessVerkleStateManager } from '../src/index.js' +import { StatelessVerkleStateManager } from '../src/index.js' import * as testnetVerkleKaustinen from './testdata/testnetVerkleKaustinen.json' import * as verkleBlockJSON from './testdata/verkleKaustinen6Block72.json' diff --git a/packages/trie/examples/createFromProof.ts b/packages/trie/examples/createFromProof.ts index e1f08dbfa4..1b8ac8e5fa 100644 --- a/packages/trie/examples/createFromProof.ts +++ b/packages/trie/examples/createFromProof.ts @@ -1,4 +1,9 @@ -import { Trie, createProof, createTrieFromProof, updateFromProof } from '@ethereumjs/trie' +import { + Trie, + createMerkleProof, + createTrieFromProof, + updateTrieFromMerkleProof, +} from '@ethereumjs/trie' import { bytesToUtf8, utf8ToBytes } from '@ethereumjs/util' async function main() { @@ -9,12 +14,12 @@ async function main() { await someOtherTrie.put(k1, utf8ToBytes('valueOne')) await someOtherTrie.put(k2, utf8ToBytes('valueTwo')) - const proof = await createProof(someOtherTrie, k1) + const proof = await createMerkleProof(someOtherTrie, k1) const trie = await createTrieFromProof(proof, { useKeyHashing: true }) - const otherProof = await createProof(someOtherTrie, k2) + const otherProof = await createMerkleProof(someOtherTrie, k2) - // To add more proofs to the trie, use `updateFromProof` - await updateFromProof(trie, otherProof) + // To add more proofs to the trie, use `updateTrieFromMerkleProof` + await updateTrieFromMerkleProof(trie, otherProof) const value = await trie.get(k1) console.log(bytesToUtf8(value!)) // valueOne diff --git a/packages/trie/examples/logDemo.ts b/packages/trie/examples/logDemo.ts index 0875a22c3a..2356ab047e 100644 --- a/packages/trie/examples/logDemo.ts +++ b/packages/trie/examples/logDemo.ts @@ -1,7 +1,7 @@ /** * Run with DEBUG=ethjs,trie:* to see debug log ouput */ -import { Trie, createProof, verifyProof } from '@ethereumjs/trie' +import { Trie, createMerkleProof, verifyMerkleProof } from '@ethereumjs/trie' import { utf8ToBytes } from '@ethereumjs/util' const trie_entries: [string, string | null][] = [ @@ -22,8 +22,8 @@ const main = async () => { for (const [key, value] of trie_entries) { await trie.put(utf8ToBytes(key), value === null ? Uint8Array.from([]) : utf8ToBytes(value)) } - const proof = await createProof(trie, utf8ToBytes('doge')) - const valid = await verifyProof(trie, trie.root(), utf8ToBytes('doge'), proof) + const proof = await createMerkleProof(trie, utf8ToBytes('doge')) + const valid = await verifyMerkleProof(trie, trie.root(), utf8ToBytes('doge'), proof) console.log('valid', valid) } diff --git a/packages/trie/examples/proofs.ts b/packages/trie/examples/proofs.ts index c2a14f38b1..73a3efcb88 100644 --- a/packages/trie/examples/proofs.ts +++ b/packages/trie/examples/proofs.ts @@ -1,4 +1,4 @@ -import { Trie, createProof, verifyProof } from '@ethereumjs/trie' +import { Trie, createMerkleProof, verifyMerkleProof } from '@ethereumjs/trie' import { bytesToUtf8, utf8ToBytes } from '@ethereumjs/util' const trie = new Trie() @@ -11,24 +11,24 @@ async function main() { // proof-of-inclusion await trie.put(k1, v1) - let proof = await createProof(trie, k1) - let value = await verifyProof(trie, trie.root(), k1, proof) + let proof = await createMerkleProof(trie, k1) + let value = await verifyMerkleProof(trie, trie.root(), k1, proof) console.log(value ? bytesToUtf8(value) : 'not found') // 'one' // proof-of-exclusion await trie.put(k1, v1) await trie.put(k2, v2) - proof = await createProof(trie, utf8ToBytes('key3')) - value = await verifyProof(trie, trie.root(), utf8ToBytes('key3'), proof) + proof = await createMerkleProof(trie, utf8ToBytes('key3')) + value = await verifyMerkleProof(trie, trie.root(), utf8ToBytes('key3'), proof) console.log(value ? bytesToUtf8(value) : 'null') // null // invalid proof await trie.put(k1, v1) await trie.put(k2, v2) - proof = await createProof(trie, k2) + proof = await createMerkleProof(trie, k2) proof[0].reverse() try { - const _value = await verifyProof(trie, trie.root(), k2, proof) // results in error + const _value = await verifyMerkleProof(trie, trie.root(), k2, proof) // results in error } catch (err) { console.log(err) } diff --git a/packages/trie/src/constructors.ts b/packages/trie/src/constructors.ts index 0d5844bbd1..04b727d77e 100644 --- a/packages/trie/src/constructors.ts +++ b/packages/trie/src/constructors.ts @@ -7,7 +7,7 @@ import { import { keccak256 } from 'ethereum-cryptography/keccak' import { concatBytes } from 'ethereum-cryptography/utils' -import { ROOT_DB_KEY, Trie, updateFromProof } from './index.js' +import { ROOT_DB_KEY, Trie, updateTrieFromMerkleProof } from './index.js' import type { Proof, TrieOpts } from './index.js' @@ -63,7 +63,7 @@ export async function createTrie(opts?: TrieOpts) { export async function createTrieFromProof(proof: Proof, trieOpts?: TrieOpts) { const shouldVerifyRoot = trieOpts?.root !== undefined const trie = new Trie(trieOpts) - const root = await updateFromProof(trie, proof, shouldVerifyRoot) + const root = await updateTrieFromMerkleProof(trie, proof, shouldVerifyRoot) trie.root(root) await trie.persistRoot() return trie diff --git a/packages/trie/src/proof/index.ts b/packages/trie/src/proof/index.ts index c7ec4ac5cc..c3462c9318 100644 --- a/packages/trie/src/proof/index.ts +++ b/packages/trie/src/proof/index.ts @@ -71,7 +71,7 @@ export function verifyTrieRangeProof( * serialized branch, extension, and/or leaf nodes. * @param key key to create a proof for */ -export async function createProof(trie: Trie, key: Uint8Array): Promise { +export async function createMerkleProof(trie: Trie, key: Uint8Array): Promise { trie['DEBUG'] && trie['debug'](`Creating Proof for Key: ${bytesToHex(key)}`, ['CREATE_PROOF']) const { stack } = await trie.findPath(trie['appliedKey'](key)) const p = stack.map((stackElem) => { @@ -89,7 +89,11 @@ export async function createProof(trie: Trie, key: Uint8Array): Promise { * @param shouldVerifyRoot - defaults to false. If `true`, verifies that the root key of the proof matches the trie root and throws if not (i.e invalid proof). * @returns The root of the proof */ -export async function updateFromProof(trie: Trie, proof: Proof, shouldVerifyRoot: boolean = false) { +export async function updateTrieFromMerkleProof( + trie: Trie, + proof: Proof, + shouldVerifyRoot: boolean = false, +) { trie['DEBUG'] && trie['debug'](`Saving (${proof.length}) proof nodes in DB`, ['FROM_PROOF']) const opStack = proof.map((nodeValue) => { let key = Uint8Array.from(trie['hash'](nodeValue)) @@ -124,7 +128,7 @@ export async function updateFromProof(trie: Trie, proof: Proof, shouldVerifyRoot * @throws If proof is found to be invalid. * @returns The value from the key, or null if valid proof of non-existence. */ -export async function verifyProof( +export async function verifyMerkleProof( trie: Trie, rootHash: Uint8Array, key: Uint8Array, @@ -144,7 +148,7 @@ export async function verifyProof( common: trie['_opts'].common, }) try { - await updateFromProof(proofTrie, proof, true) + await updateTrieFromMerkleProof(proofTrie, proof, true) } catch (e: any) { throw new Error('Invalid proof nodes given') } diff --git a/packages/trie/src/proof/range.ts b/packages/trie/src/proof/range.ts index 3c5e9f5566..ff8f62b201 100644 --- a/packages/trie/src/proof/range.ts +++ b/packages/trie/src/proof/range.ts @@ -317,7 +317,7 @@ async function unsetInternal(trie: Trie, left: Nibbles, right: Nibbles): Promise * @throws If proof is found to be invalid. * @returns The value from the key, or null if valid proof of non-existence. */ -async function verifyProof( +async function verifyMerkleProof( rootHash: Uint8Array, key: Uint8Array, proof: Uint8Array[], @@ -450,7 +450,7 @@ export async function verifyRangeProof( if (proof !== null && firstKey !== null && lastKey === null) { // Zero element proof if (keys.length === 0) { - const { trie, value } = await verifyProof( + const { trie, value } = await verifyMerkleProof( rootHash, nibblesTypeToPackedBytes(firstKey), proof, @@ -473,7 +473,7 @@ export async function verifyRangeProof( // One element proof if (keys.length === 1 && nibblesCompare(firstKey, lastKey) === 0) { - const { trie, value } = await verifyProof( + const { trie, value } = await verifyMerkleProof( rootHash, nibblesTypeToPackedBytes(firstKey), proof, diff --git a/packages/trie/src/trie.ts b/packages/trie/src/trie.ts index 6f32b8ec62..c64609007c 100644 --- a/packages/trie/src/trie.ts +++ b/packages/trie/src/trie.ts @@ -513,7 +513,7 @@ export class Trie { const value = (await this._db.get(key)) ?? null if (value === null) { - // Dev note: this error message text is used for error checking in `checkRoot`, `verifyProof`, and `findPath` + // Dev note: this error message text is used for error checking in `checkRoot`, `verifyMerkleProof`, and `findPath` throw new Error('Missing node in DB') } diff --git a/packages/trie/test/proof.spec.ts b/packages/trie/test/proof.spec.ts index 56d22c195e..ae972ac733 100644 --- a/packages/trie/test/proof.spec.ts +++ b/packages/trie/test/proof.spec.ts @@ -4,9 +4,9 @@ import { assert, describe, it } from 'vitest' import { Trie, - createProof, + createMerkleProof, createTrieFromProof, - updateFromProof, + updateTrieFromMerkleProof, verifyTrieProof, } from '../src/index.js' @@ -18,27 +18,27 @@ describe('simple merkle proofs generation and verification', () => { await trie.put(utf8ToBytes('key2bb'), utf8ToBytes('aval2')) await trie.put(utf8ToBytes('key3cc'), utf8ToBytes('aval3')) - let proof = await createProof(trie, utf8ToBytes('key2bb')) + let proof = await createMerkleProof(trie, utf8ToBytes('key2bb')) let val = await verifyTrieProof(utf8ToBytes('key2bb'), proof) assert.equal(bytesToUtf8(val!), 'aval2') - proof = await createProof(trie, utf8ToBytes('key1aa')) + proof = await createMerkleProof(trie, utf8ToBytes('key1aa')) val = await verifyTrieProof(utf8ToBytes('key1aa'), proof) assert.equal(bytesToUtf8(val!), '0123456789012345678901234567890123456789xx') - proof = await createProof(trie, utf8ToBytes('key2bb')) + proof = await createMerkleProof(trie, utf8ToBytes('key2bb')) val = await verifyTrieProof(utf8ToBytes('key2'), proof) // In this case, the proof _happens_ to contain enough nodes to prove `key2` because // traversing into `key22` would touch all the same nodes as traversing into `key2` assert.equal(val, null, 'Expected value at a random key to be null') let myKey = utf8ToBytes('anyrandomkey') - proof = await createProof(trie, myKey) + proof = await createMerkleProof(trie, myKey) val = await verifyTrieProof(myKey, proof) assert.equal(val, null, 'Expected value to be null') myKey = utf8ToBytes('anothergarbagekey') // should generate a valid proof of null - proof = await createProof(trie, myKey) + proof = await createMerkleProof(trie, myKey) proof.push(utf8ToBytes('123456')) // extra nodes are just ignored val = await verifyTrieProof(myKey, proof) assert.equal(val, null, 'Expected value to be null') @@ -46,7 +46,7 @@ describe('simple merkle proofs generation and verification', () => { await trie.put(utf8ToBytes('another'), utf8ToBytes('3498h4riuhgwe')) // to fail our proof we can request a proof for one key - proof = await createProof(trie, utf8ToBytes('another')) + proof = await createMerkleProof(trie, utf8ToBytes('another')) // and try to use that proof on another key try { await verifyTrieProof(utf8ToBytes('key1aa'), proof) @@ -56,7 +56,7 @@ describe('simple merkle proofs generation and verification', () => { } // we can also corrupt a valid proof - proof = await createProof(trie, utf8ToBytes('key2bb')) + proof = await createMerkleProof(trie, utf8ToBytes('key2bb')) proof[0].reverse() try { await verifyTrieProof(utf8ToBytes('key2bb'), proof) @@ -68,7 +68,7 @@ describe('simple merkle proofs generation and verification', () => { // test an invalid exclusion proof by creating // a valid exclusion proof then making it non-null myKey = utf8ToBytes('anyrandomkey') - proof = await createProof(trie, myKey) + proof = await createMerkleProof(trie, myKey) val = await verifyTrieProof(myKey, proof) assert.equal(val, null, 'Expected value to be null') // now make the key non-null so the exclusion proof becomes invalid @@ -86,7 +86,7 @@ describe('simple merkle proofs generation and verification', () => { await trie.put(utf8ToBytes('key1aa'), utf8ToBytes('0123456789012345678901234567890123456789xx')) - const proof = await createProof(trie, utf8ToBytes('key1aa')) + const proof = await createMerkleProof(trie, utf8ToBytes('key1aa')) const val = await verifyTrieProof(utf8ToBytes('key1aa'), proof) assert.equal(bytesToUtf8(val!), '0123456789012345678901234567890123456789xx') }) @@ -96,7 +96,7 @@ describe('simple merkle proofs generation and verification', () => { await trie.put(utf8ToBytes('key1aa'), utf8ToBytes('01234')) - const proof = await createProof(trie, utf8ToBytes('key1aa')) + const proof = await createMerkleProof(trie, utf8ToBytes('key1aa')) const val = await verifyTrieProof(utf8ToBytes('key1aa'), proof) assert.equal(bytesToUtf8(val!), '01234') }) @@ -117,15 +117,15 @@ describe('simple merkle proofs generation and verification', () => { await trie.put(utf8ToBytes('key3cc'), utf8ToBytes('aval3')) await trie.put(utf8ToBytes('key3'), utf8ToBytes('1234567890123456789012345678901')) - let proof = await createProof(trie, utf8ToBytes('key1')) + let proof = await createMerkleProof(trie, utf8ToBytes('key1')) let val = await verifyTrieProof(utf8ToBytes('key1'), proof) assert.equal(bytesToUtf8(val!), '0123456789012345678901234567890123456789Very_Long') - proof = await createProof(trie, utf8ToBytes('key2')) + proof = await createMerkleProof(trie, utf8ToBytes('key2')) val = await verifyTrieProof(utf8ToBytes('key2'), proof) assert.equal(bytesToUtf8(val!), 'short') - proof = await createProof(trie, utf8ToBytes('key3')) + proof = await createMerkleProof(trie, utf8ToBytes('key3')) val = await verifyTrieProof(utf8ToBytes('key3'), proof) assert.equal(bytesToUtf8(val!), '1234567890123456789012345678901') }) @@ -137,15 +137,15 @@ describe('simple merkle proofs generation and verification', () => { await trie.put(utf8ToBytes('b'), utf8ToBytes('b')) await trie.put(utf8ToBytes('c'), utf8ToBytes('c')) - let proof = await createProof(trie, utf8ToBytes('a')) + let proof = await createMerkleProof(trie, utf8ToBytes('a')) let val = await verifyTrieProof(utf8ToBytes('a'), proof) assert.equal(bytesToUtf8(val!), 'a') - proof = await createProof(trie, utf8ToBytes('b')) + proof = await createMerkleProof(trie, utf8ToBytes('b')) val = await verifyTrieProof(utf8ToBytes('b'), proof) assert.equal(bytesToUtf8(val!), 'b') - proof = await createProof(trie, utf8ToBytes('c')) + proof = await createMerkleProof(trie, utf8ToBytes('c')) val = await verifyTrieProof(utf8ToBytes('c'), proof) assert.equal(bytesToUtf8(val!), 'c') }) @@ -165,7 +165,7 @@ describe('simple merkle proofs generation and verification', () => { await trie.put(key, encodedValue) await trie.put(key2, encodedValue2) await trie.put(key3, encodedValue3) - const proof = await createProof(trie, key) + const proof = await createMerkleProof(trie, key) const newTrie = await createTrieFromProof(proof, { useKeyHashing: true }) const trieValue = await newTrie.get(key) @@ -173,8 +173,8 @@ describe('simple merkle proofs generation and verification', () => { assert.ok(equalsBytes(trieValue!, encodedValue), 'trie value sucessfully copied') assert.ok(equalsBytes(trie.root(), newTrie.root()), 'root set correctly') - const proof2 = await createProof(trie, key2) - await updateFromProof(newTrie, proof2) + const proof2 = await createMerkleProof(trie, key2) + await updateTrieFromMerkleProof(newTrie, proof2) const trieValue2 = await newTrie.get(key2) assert.ok(equalsBytes(trieValue2!, encodedValue2), 'trie value succesfully updated') @@ -188,16 +188,16 @@ describe('simple merkle proofs generation and verification', () => { const safeValue = RLP.encode(new Uint8Array([1337])) await safeTrie.put(safeKey, safeValue) - const safeProof = await createProof(safeTrie, safeKey) + const safeProof = await createMerkleProof(safeTrie, safeKey) try { - await updateFromProof(newTrie, safeProof, true) + await updateTrieFromMerkleProof(newTrie, safeProof, true) assert.fail('cannot reach this') } catch (e) { assert.ok(true, 'throws on unmatching proof') } - await updateFromProof(newTrie, safeProof) + await updateTrieFromMerkleProof(newTrie, safeProof) assert.ok(equalsBytes(trie.root(), newTrie.root()), 'root set correctly') const newSafeValue = await newTrie.get(safeKey) diff --git a/packages/trie/test/proof/range.spec.ts b/packages/trie/test/proof/range.spec.ts index 2ca66baefa..4fa8eaa74c 100644 --- a/packages/trie/test/proof/range.spec.ts +++ b/packages/trie/test/proof/range.spec.ts @@ -9,7 +9,7 @@ import { } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' -import { Trie, createProof, verifyTrieRangeProof } from '../../src/index.js' +import { Trie, createMerkleProof, verifyTrieRangeProof } from '../../src/index.js' import type { DB } from '@ethereumjs/util' @@ -94,7 +94,7 @@ async function verify( endKey, keys ?? targetRange.map(([key]) => key), vals ?? targetRange.map(([, val]) => val), - [...(await createProof(trie, startKey)), ...(await createProof(trie, endKey))], + [...(await createMerkleProof(trie, startKey)), ...(await createMerkleProof(trie, endKey))], ) } @@ -474,7 +474,7 @@ describe('simple merkle range proofs generation and verification', () => { let bloatedProof: Uint8Array[] = [] for (let i = 0; i < TRIE_SIZE; i++) { - bloatedProof = bloatedProof.concat(await createProof(trie, entries[i][0])) + bloatedProof = bloatedProof.concat(await createMerkleProof(trie, entries[i][0])) } assert.equal(await verify(trie, entries, 0, entries.length - 1), false) diff --git a/packages/trie/test/trie/secure.spec.ts b/packages/trie/test/trie/secure.spec.ts index a13171adb4..eade5ecabe 100644 --- a/packages/trie/test/trie/secure.spec.ts +++ b/packages/trie/test/trie/secure.spec.ts @@ -10,7 +10,7 @@ import { keccak256 } from 'ethereum-cryptography/keccak.js' import { sha256 } from 'ethereum-cryptography/sha256.js' import { assert, describe, it } from 'vitest' -import { ROOT_DB_KEY, Trie, createProof, verifyTrieProof } from '../../src/index.js' +import { ROOT_DB_KEY, Trie, createMerkleProof, verifyTrieProof } from '../../src/index.js' import secureTrieTests from '../fixtures/trietest_secureTrie.json' describe('SecureTrie', () => { @@ -52,7 +52,7 @@ describe('SecureTrie proof', () => { const trie = new Trie({ useKeyHashing: true, db: new MapDB() }) await trie.put(utf8ToBytes('key1aa'), utf8ToBytes('01234')) - const proof = await createProof(trie, utf8ToBytes('key1aa')) + const proof = await createMerkleProof(trie, utf8ToBytes('key1aa')) const val = await verifyTrieProof(utf8ToBytes('key1aa'), proof, { useKeyHashing: true, }) diff --git a/packages/trie/test/util/asyncWalk.spec.ts b/packages/trie/test/util/asyncWalk.spec.ts index 0adf4e2d09..7b875625bf 100644 --- a/packages/trie/test/util/asyncWalk.spec.ts +++ b/packages/trie/test/util/asyncWalk.spec.ts @@ -4,7 +4,7 @@ import { assert, describe, it } from 'vitest' import { LeafNode, Trie, - createProof, + createMerkleProof, createTrieFromProof, verifyTrieProof, } from '../../src/index.js' @@ -84,7 +84,7 @@ describe('walk a sparse trie', async () => { }) // Generate a proof for inputs[0] const proofKey = inputs[0][0] - const proof = await createProof(trie, proofKey) + const proof = await createMerkleProof(trie, proofKey) assert.ok(await verifyTrieProof(proofKey, proof)) // Build a sparse trie from the proof diff --git a/packages/trie/test/util/log.spec.ts b/packages/trie/test/util/log.spec.ts index b4f79826d1..be4e7157b4 100644 --- a/packages/trie/test/util/log.spec.ts +++ b/packages/trie/test/util/log.spec.ts @@ -1,7 +1,7 @@ import { utf8ToBytes } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' -import { createProof, createTrieFromProof, verifyProof } from '../../src/index.js' +import { createMerkleProof, createTrieFromProof, verifyMerkleProof } from '../../src/index.js' import { Trie } from '../../src/trie.js' describe('Run Trie script with DEBUG enabled', async () => { @@ -20,8 +20,8 @@ describe('Run Trie script with DEBUG enabled', async () => { await trie.put(utf8ToBytes(key), value === null ? Uint8Array.from([]) : utf8ToBytes(value)) } - const proof = await createProof(trie, utf8ToBytes('doge')) - const valid = await verifyProof(trie, trie.root(), utf8ToBytes('doge'), proof) + const proof = await createMerkleProof(trie, utf8ToBytes('doge')) + const valid = await verifyMerkleProof(trie, trie.root(), utf8ToBytes('doge'), proof) it('should be valid', async () => { assert.deepEqual(valid, utf8ToBytes('coin')) diff --git a/packages/verkle/src/verkleTree.ts b/packages/verkle/src/verkleTree.ts index c1839b966a..186999852b 100644 --- a/packages/verkle/src/verkleTree.ts +++ b/packages/verkle/src/verkleTree.ts @@ -529,10 +529,10 @@ export class VerkleTree { } /** - * Creates a proof from a tree and key that can be verified using {@link VerkleTree.verifyProof}. + * Creates a proof from a tree and key that can be verified using {@link VerkleTree.verifyVerkleProof}. * @param key */ - async createProof(_key: Uint8Array): Promise { + async createVerkleProof(_key: Uint8Array): Promise { throw new Error('Not implemented') } @@ -544,7 +544,7 @@ export class VerkleTree { * @throws If proof is found to be invalid. * @returns The value from the key, or null if valid proof of non-existence. */ - async verifyProof( + async verifyVerkleProof( _rootHash: Uint8Array, _key: Uint8Array, _proof: Proof, diff --git a/packages/vm/test/api/EIPs/eip-4788-beaconroot.spec.ts b/packages/vm/test/api/EIPs/eip-4788-beaconroot.spec.ts index 56416ed043..9b784b8c2b 100644 --- a/packages/vm/test/api/EIPs/eip-4788-beaconroot.spec.ts +++ b/packages/vm/test/api/EIPs/eip-4788-beaconroot.spec.ts @@ -9,7 +9,7 @@ * - Input length < 32 bytes (reverts) */ -import { createBlock, createHeader } from '@ethereumjs/block' +import { createBlock, createBlockHeader } from '@ethereumjs/block' import { Common, Hardfork, Mainnet } from '@ethereumjs/common' import { type TransactionType, type TxData, createTxFromTxData } from '@ethereumjs/tx' import { @@ -56,7 +56,7 @@ function beaconrootBlock( } const root = setLengthLeft(bigIntToBytes(blockroot), 32) - const header = createHeader( + const header = createBlockHeader( { parentBeaconBlockRoot: root, timestamp, diff --git a/packages/vm/test/api/index.spec.ts b/packages/vm/test/api/index.spec.ts index 6da787071a..dcd8e2f107 100644 --- a/packages/vm/test/api/index.spec.ts +++ b/packages/vm/test/api/index.spec.ts @@ -35,7 +35,7 @@ describe('VM -> basic instantiation / boolean switches', () => { KECCAK256_RLP, 'it has default trie', ) - assert.equal(vm.common.hardfork(), Hardfork.Shanghai, 'it has correct default HF') + assert.equal(vm.common.hardfork(), Hardfork.Cancun, 'it has correct default HF') }) it('should be able to activate precompiles', async () => { diff --git a/packages/vm/test/api/runTx.spec.ts b/packages/vm/test/api/runTx.spec.ts index 93ba381dff..c6e1c2d3df 100644 --- a/packages/vm/test/api/runTx.spec.ts +++ b/packages/vm/test/api/runTx.spec.ts @@ -1,4 +1,4 @@ -import { createBlock, createHeader } from '@ethereumjs/block' +import { createBlock, createBlockHeader } from '@ethereumjs/block' import { Blockchain, createBlockchain } from '@ethereumjs/blockchain' import { Common, Goerli, Hardfork, Mainnet, createCommonFromGethGenesis } from '@ethereumjs/common' import { @@ -874,7 +874,7 @@ describe('EIP 4844 transaction tests', () => { Blockchain.prototype.getBlock = async () => { return createBlock( { - header: createHeader( + header: createBlockHeader( { excessBlobGas: 0n, number: 1, @@ -902,7 +902,7 @@ describe('EIP 4844 transaction tests', () => { const block = createBlock( { - header: createHeader( + header: createBlockHeader( { excessBlobGas: 1n, number: 2, diff --git a/packages/vm/test/util.ts b/packages/vm/test/util.ts index 3ba0d34876..ae078319f2 100644 --- a/packages/vm/test/util.ts +++ b/packages/vm/test/util.ts @@ -1,4 +1,4 @@ -import { Block, createHeader } from '@ethereumjs/block' +import { Block, createBlockHeader } from '@ethereumjs/block' import { Common, Hardfork, Mainnet, createCustomCommon } from '@ethereumjs/common' import { RLP } from '@ethereumjs/rlp' import { @@ -326,7 +326,7 @@ export function makeBlockHeader(data: any, opts?: BlockOptions) { if (opts?.common && opts.common.gteHardfork('london')) { headerData['baseFeePerGas'] = currentBaseFee if (currentBaseFee === undefined) { - const parentBlockHeader = createHeader( + const parentBlockHeader = createBlockHeader( { gasLimit: parentGasLimit, gasUsed: parentGasUsed, @@ -344,7 +344,7 @@ export function makeBlockHeader(data: any, opts?: BlockOptions) { if (opts?.common && opts.common.gteHardfork('cancun')) { headerData['excessBlobGas'] = currentExcessBlobGas } - return createHeader(headerData, opts) + return createBlockHeader(headerData, opts) } /**