Skip to content

Commit

Permalink
trie: rename trie to mpt
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrocheleau committed Oct 2, 2024
1 parent 477dc76 commit 8846388
Show file tree
Hide file tree
Showing 61 changed files with 295 additions and 258 deletions.
9 changes: 6 additions & 3 deletions packages/block/src/block/block.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ConsensusType } from '@ethereumjs/common'
import { RLP } from '@ethereumjs/rlp'
import { Trie } from '@ethereumjs/trie'
import { MerklePatriciaTrie } from '@ethereumjs/trie'
import { Blob4844Tx, Capability } from '@ethereumjs/tx'
import {
BIGINT_0,
Expand Down Expand Up @@ -226,7 +226,10 @@ export class Block {
* Generates transaction trie for validation.
*/
async genTxTrie(): Promise<Uint8Array> {
return genTransactionsTrieRoot(this.transactions, new Trie({ common: this.common }))
return genTransactionsTrieRoot(
this.transactions,
new MerklePatriciaTrie({ common: this.common }),
)
}

/**
Expand Down Expand Up @@ -471,7 +474,7 @@ export class Block {
if (this.cache.withdrawalsTrieRoot === undefined) {
this.cache.withdrawalsTrieRoot = await genWithdrawalsTrieRoot(
this.withdrawals!,
new Trie({ common: this.common }),
new MerklePatriciaTrie({ common: this.common }),
)
}
result = equalsBytes(this.cache.withdrawalsTrieRoot, this.header.withdrawalsRoot!)
Expand Down
11 changes: 7 additions & 4 deletions packages/block/src/block/constructors.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { RLP } from '@ethereumjs/rlp'
import { Trie } from '@ethereumjs/trie'
import { MerklePatriciaTrie } from '@ethereumjs/trie'
import {
type TxOptions,
createTx,
Expand Down Expand Up @@ -401,10 +401,13 @@ export async function createBlockFromExecutionPayload(
}
}

const transactionsTrie = await genTransactionsTrieRoot(txs, new Trie({ common: opts?.common }))
const transactionsTrie = await genTransactionsTrieRoot(
txs,
new MerklePatriciaTrie({ common: opts?.common }),
)
const withdrawals = withdrawalsData?.map((wData) => createWithdrawal(wData))
const withdrawalsRoot = withdrawals
? await genWithdrawalsTrieRoot(withdrawals, new Trie({ common: opts?.common }))
? await genWithdrawalsTrieRoot(withdrawals, new MerklePatriciaTrie({ common: opts?.common }))
: undefined

const hasDepositRequests = depositRequests !== undefined && depositRequests !== null
Expand Down Expand Up @@ -434,7 +437,7 @@ export async function createBlockFromExecutionPayload(
}

const requestsRoot = requests
? await genRequestsTrieRoot(requests, new Trie({ common: opts?.common }))
? await genRequestsTrieRoot(requests, new MerklePatriciaTrie({ common: opts?.common }))
: undefined

const header: HeaderData = {
Expand Down
20 changes: 13 additions & 7 deletions packages/block/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { RLP } from '@ethereumjs/rlp'
import { Trie } from '@ethereumjs/trie'
import { MerklePatriciaTrie } from '@ethereumjs/trie'
import { Blob4844Tx } from '@ethereumjs/tx'
import { BIGINT_0, BIGINT_1, TypeOutput, isHexString, toType } from '@ethereumjs/util'

Expand Down Expand Up @@ -124,8 +124,8 @@ export const fakeExponential = (factor: bigint, numerator: bigint, denominator:
* @param wts array of Withdrawal to compute the root of
* @param optional emptyTrie to use to generate the root
*/
export async function genWithdrawalsTrieRoot(wts: Withdrawal[], emptyTrie?: Trie) {
const trie = emptyTrie ?? new Trie()
export async function genWithdrawalsTrieRoot(wts: Withdrawal[], emptyTrie?: MerklePatriciaTrie) {
const trie = emptyTrie ?? new MerklePatriciaTrie()
for (const [i, wt] of wts.entries()) {
await trie.put(RLP.encode(i), RLP.encode(wt.raw()))
}
Expand All @@ -137,8 +137,11 @@ export async function genWithdrawalsTrieRoot(wts: Withdrawal[], emptyTrie?: Trie
* @param txs array of TypedTransaction to compute the root of
* @param optional emptyTrie to use to generate the root
*/
export async function genTransactionsTrieRoot(txs: TypedTransaction[], emptyTrie?: Trie) {
const trie = emptyTrie ?? new Trie()
export async function genTransactionsTrieRoot(
txs: TypedTransaction[],
emptyTrie?: MerklePatriciaTrie,
) {
const trie = emptyTrie ?? new MerklePatriciaTrie()
for (const [i, tx] of txs.entries()) {
await trie.put(RLP.encode(i), tx.serialize())
}
Expand All @@ -151,7 +154,10 @@ export async function genTransactionsTrieRoot(txs: TypedTransaction[], emptyTrie
* @param emptyTrie optional empty trie used to generate the root
* @returns a 32 byte Uint8Array representing the requests trie root
*/
export async function genRequestsTrieRoot(requests: CLRequest<CLRequestType>[], emptyTrie?: Trie) {
export async function genRequestsTrieRoot(
requests: CLRequest<CLRequestType>[],
emptyTrie?: MerklePatriciaTrie,
) {
// Requests should be sorted in monotonically ascending order based on type
// and whatever internal sorting logic is defined by each request type
if (requests.length > 1) {
Expand All @@ -160,7 +166,7 @@ export async function genRequestsTrieRoot(requests: CLRequest<CLRequestType>[],
throw new Error('requests are not sorted in ascending order')
}
}
const trie = emptyTrie ?? new Trie()
const trie = emptyTrie ?? new MerklePatriciaTrie()
for (const [i, req] of requests.entries()) {
await trie.put(RLP.encode(i), req.serialize())
}
Expand Down
2 changes: 1 addition & 1 deletion packages/client/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export interface EthereumClientOptions {
* Database to store the state.
* Should be an abstract-leveldown compliant store.
*
* Default: Database created by the Trie class
* Default: Database created by the MerklePatriciaTrie class
*/
stateDB?: AbstractLevel<string | Uint8Array, string | Uint8Array, string | Uint8Array>

Expand Down
4 changes: 2 additions & 2 deletions packages/client/src/sync/fetcher/accountfetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import type { AccountData } from '../../net/protocol/snapprotocol.js'
import type { FetcherOptions } from './fetcher.js'
import type { StorageRequest } from './storagefetcher.js'
import type { Job, SnapFetcherDoneFlags } from './types.js'
import type { Trie } from '@ethereumjs/trie'
import type { MerklePatriciaTrie } from '@ethereumjs/trie'
import type { Debugger } from 'debug'

type AccountDataResponse = AccountData[] & { completed?: boolean }
Expand Down Expand Up @@ -70,7 +70,7 @@ export type JobTask = {
export class AccountFetcher extends Fetcher<JobTask, AccountData[], AccountData> {
protected debug: Debugger
stateManager: MerkleStateManager
accountTrie: Trie
accountTrie: MerklePatriciaTrie

root: Uint8Array
highestKnownHash: Uint8Array | undefined
Expand Down
11 changes: 7 additions & 4 deletions packages/client/src/sync/fetcher/trienodefetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
BranchNode,
ExtensionNode,
LeafNode,
Trie,
MerklePatriciaTrie,
decodeNode,
mergeAndFormatKeyPaths,
pathToHexKey,
Expand Down Expand Up @@ -37,7 +37,7 @@ type TrieNodesResponse = Uint8Array[] & { completed?: boolean }
*/
export interface TrieNodeFetcherOptions extends FetcherOptions {
root: Uint8Array
accountToStorageTrie?: Map<String, Trie>
accountToStorageTrie?: Map<String, MerklePatriciaTrie>
stateManager?: MerkleStateManager

/** Destroy fetcher once all tasks are done */
Expand Down Expand Up @@ -71,7 +71,7 @@ export class TrieNodeFetcher extends Fetcher<JobTask, Uint8Array[], Uint8Array>

stateManager: MerkleStateManager
fetcherDoneFlags: SnapFetcherDoneFlags
accountTrie: Trie
accountTrie: MerklePatriciaTrie
codeDB: DB

/**
Expand Down Expand Up @@ -351,7 +351,10 @@ export class TrieNodeFetcher extends Fetcher<JobTask, Uint8Array[], Uint8Array>

// add storage data for account if it has fetched nodes
// TODO figure out what the key should be for mapping accounts to storage tries
const storageTrie = new Trie({ useKeyHashing: true, common: this.config.chainCommon })
const storageTrie = new MerklePatriciaTrie({
useKeyHashing: true,
common: this.config.chainCommon,
})
const storageTrieOps: BatchDBOp[] = []
if (pathToStorageNode !== undefined && pathToStorageNode.size > 0) {
for (const [path, data] of pathToStorageNode) {
Expand Down
4 changes: 2 additions & 2 deletions packages/client/src/util/debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { Level } from 'level';
import { Common } from '@ethereumjs/common'
import { Block } from '@ethereumjs/block'
import { VM, runBlock, createVM } from './src'
import { Trie } from '@ethereumjs/trie'
import { MerklePatriciaTrie } from '@ethereumjs/trie'
import { MerkleStateManager } from './src/state'
import { Blockchain } from '@ethereumjs/blockchain'
Expand All @@ -40,7 +40,7 @@ const main = async () => {
const block = createBlockFromRLP(hexToBytes('${bytesToHex(block.serialize())}'), { common })
const stateDB = new Level('${execution.config.getDataDirectory(DataDirectory.State)}')
const trie = new Trie({ db: stateDB, useKeyHashing: true })
const trie = new MerklePatriciaTrie({ db: stateDB, useKeyHashing: true })
const stateManager = new MerkleStateManager({ trie, common })
// Ensure we run on the right root
stateManager.setStateRoot(hexToBytes('${bytesToHex(
Expand Down
4 changes: 2 additions & 2 deletions packages/client/test/rpc/engine/withdrawals.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { genWithdrawalsTrieRoot } from '@ethereumjs/block'
import { Trie } from '@ethereumjs/trie'
import { MerklePatriciaTrie } from '@ethereumjs/trie'
import { bigIntToHex, bytesToHex, createWithdrawal, intToHex } from '@ethereumjs/util'
import { assert, it } from 'vitest'

Expand Down Expand Up @@ -105,7 +105,7 @@ for (const { name, withdrawals, withdrawalsRoot, gethBlockRlp } of testCases) {
it(name, async () => {
// check withdrawals root computation
const computedWithdrawalsRoot = bytesToHex(
await genWithdrawalsTrieRoot(withdrawals.map(createWithdrawal), new Trie()),
await genWithdrawalsTrieRoot(withdrawals.map(createWithdrawal), new MerklePatriciaTrie()),
)
assert.equal(
withdrawalsRoot,
Expand Down
16 changes: 8 additions & 8 deletions packages/statemanager/src/merkleStateManager.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Common, Mainnet } from '@ethereumjs/common'
import { RLP } from '@ethereumjs/rlp'
import { Trie } from '@ethereumjs/trie'
import { MerklePatriciaTrie } from '@ethereumjs/trie'
import {
Account,
bytesToUnprefixedHex,
Expand Down Expand Up @@ -65,8 +65,8 @@ export class MerkleStateManager implements StateManagerInterface {

originalStorageCache: OriginalStorageCache

protected _trie: Trie
protected _storageTries: { [key: string]: Trie }
protected _trie: MerklePatriciaTrie
protected _storageTries: { [key: string]: MerklePatriciaTrie }

protected readonly _prefixCodeHashes: boolean
protected readonly _prefixStorageTrieKeys: boolean
Expand Down Expand Up @@ -102,7 +102,7 @@ export class MerkleStateManager implements StateManagerInterface {

this._checkpointCount = 0

this._trie = opts.trie ?? new Trie({ useKeyHashing: true, common: this.common })
this._trie = opts.trie ?? new MerklePatriciaTrie({ useKeyHashing: true, common: this.common })
this._storageTries = {}

this.keccakFunction = opts.common?.customCrypto.keccak256 ?? keccak256
Expand Down Expand Up @@ -263,14 +263,14 @@ export class MerkleStateManager implements StateManagerInterface {
* @param rootAccount (Optional) Account object whose 'storageRoot' is to be used as
* the root of the new storageTrie returned when there is no pre-existing trie.
* If left undefined, the EMPTY_TRIE_ROOT will be used as the root instead.
* @returns storage Trie object
* @returns storage MerklePatriciaTrie object
* @private
*/
// TODO PR: have a better interface for hashed address pull?
protected _getStorageTrie(
addressOrHash: Address | { bytes: Uint8Array } | Uint8Array,
rootAccount?: Account,
): Trie {
): MerklePatriciaTrie {
// use hashed key for lookup from storage cache
const addressBytes: Uint8Array =
addressOrHash instanceof Uint8Array ? addressOrHash : this.keccakFunction(addressOrHash.bytes)
Expand All @@ -295,7 +295,7 @@ export class MerkleStateManager implements StateManagerInterface {
* cache or does a lookup.
* @private
*/
protected _getAccountTrie(): Trie {
protected _getAccountTrie(): MerklePatriciaTrie {
return this._trie
}

Expand Down Expand Up @@ -347,7 +347,7 @@ export class MerkleStateManager implements StateManagerInterface {
protected async _modifyContractStorage(
address: Address,
account: Account,
modifyTrie: (storageTrie: Trie, done: Function) => void,
modifyTrie: (storageTrie: MerklePatriciaTrie, done: Function) => void,
): Promise<void> {
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve) => {
Expand Down
6 changes: 3 additions & 3 deletions packages/statemanager/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { type PrefixedHexString } from '@ethereumjs/util'

import type { AccessWitness, Caches } from './index.js'
import type { Common } from '@ethereumjs/common'
import type { Trie } from '@ethereumjs/trie'
import type { MerklePatriciaTrie } from '@ethereumjs/trie'
import type { VerkleCrypto } from '@ethereumjs/util'
import type { VerkleTree } from '@ethereumjs/verkle'
/**
Expand Down Expand Up @@ -32,9 +32,9 @@ export interface RPCStateManagerOpts extends BaseStateManagerOpts {
*/
export interface MerkleStateManagerOpts extends BaseStateManagerOpts {
/**
* A {@link Trie} instance
* A {@link MerklePatriciaTrie} instance
*/
trie?: Trie
trie?: MerklePatriciaTrie
/**
* Option to prefix codehashes in the database. This defaults to `true`.
* If this is disabled, note that it is possible to corrupt the trie, by deploying code
Expand Down
16 changes: 8 additions & 8 deletions packages/statemanager/test/proofStateManager.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Trie, createTrie } from '@ethereumjs/trie'
import { MerklePatriciaTrie, createTrie } from '@ethereumjs/trie'
import {
Account,
Address,
Expand Down Expand Up @@ -140,7 +140,7 @@ describe('ProofStateManager', () => {
// Account: 0x68268f12253f69f66b188c95b8106b2f847859fc (this account does not exist)
// Storage slots: empty list
const address = createAddressFromString('0x68268f12253f69f66b188c95b8106b2f847859fc')
const trie = new Trie({ useKeyHashing: true })
const trie = new MerklePatriciaTrie({ useKeyHashing: true })
const stateManager = new MerkleStateManager({ trie })
// Dump all the account proof data in the DB
let stateRoot: Uint8Array | undefined
Expand All @@ -164,7 +164,7 @@ describe('ProofStateManager', () => {
// Note: the first slot has a value, but the second slot is empty
// Note: block hash 0x1d9ea6981b8093a2b63f22f74426ceb6ba1acae3fddd7831442bbeba3fa4f146
const address = createAddressFromString('0x2D80502854FC7304c3E3457084DE549f5016B73f')
const trie = new Trie({ useKeyHashing: true })
const trie = new MerklePatriciaTrie({ useKeyHashing: true })
const stateManager = new MerkleStateManager({ trie })
// Dump all the account proof data in the DB
let stateRoot: Uint8Array | undefined
Expand All @@ -177,7 +177,7 @@ describe('ProofStateManager', () => {
await trie['_db'].put(key, bufferData)
}
const storageRoot = ropstenContractWithStorageData.storageHash
const storageTrie = new Trie({ useKeyHashing: true })
const storageTrie = new MerklePatriciaTrie({ useKeyHashing: true })
const storageKeys: Uint8Array[] = []
for (const storageProofsData of ropstenContractWithStorageData.storageProof) {
storageKeys.push(hexToBytes(storageProofsData.key))
Expand All @@ -202,7 +202,7 @@ describe('ProofStateManager', () => {
// Note: the first slot has a value, but the second slot is empty
// Note: block hash 0x1d9ea6981b8093a2b63f22f74426ceb6ba1acae3fddd7831442bbeba3fa4f146
const address = createAddressFromString('0x2D80502854FC7304c3E3457084DE549f5016B73f')
const trie = new Trie({ useKeyHashing: true })
const trie = new MerklePatriciaTrie({ useKeyHashing: true })
const stateManager = new MerkleStateManager({ trie })
// Dump all the account proof data in the DB
let stateRoot: Uint8Array | undefined
Expand All @@ -215,7 +215,7 @@ describe('ProofStateManager', () => {
await trie['_db'].put(key, bufferData)
}
const storageRoot = ropstenContractWithStorageData.storageHash
const storageTrie = new Trie({ useKeyHashing: true })
const storageTrie = new MerklePatriciaTrie({ useKeyHashing: true })
const storageKeys: Uint8Array[] = []
for (const storageProofsData of ropstenContractWithStorageData.storageProof) {
storageKeys.push(hexToBytes(storageProofsData.key))
Expand Down Expand Up @@ -268,7 +268,7 @@ describe('ProofStateManager', () => {
// Note: the first slot has a value, but the second slot is empty
// Note: block hash 0x1d9ea6981b8093a2b63f22f74426ceb6ba1acae3fddd7831442bbeba3fa4f146
const address = createAddressFromString('0x68268f12253f69f66b188c95b8106b2f847859fc')
const trie = new Trie({ useKeyHashing: true })
const trie = new MerklePatriciaTrie({ useKeyHashing: true })
const stateManager = new MerkleStateManager({ trie })
// Dump all the account proof data in the DB
let stateRoot: Uint8Array | undefined
Expand All @@ -281,7 +281,7 @@ describe('ProofStateManager', () => {
await trie['_db'].put(key, bufferData)
}
const storageRoot = ropstenNonexistentAccountData.storageHash
const storageTrie = new Trie({ useKeyHashing: true })
const storageTrie = new MerklePatriciaTrie({ useKeyHashing: true })
storageTrie.root(hexToBytes(storageRoot))
const addressHex = bytesToHex(address.bytes)
stateManager['_storageTries'][addressHex] = storageTrie
Expand Down
4 changes: 2 additions & 2 deletions packages/statemanager/test/stateManager.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Trie, createTrie, createTrieFromProof } from '@ethereumjs/trie'
import { MerklePatriciaTrie, createTrie, createTrieFromProof } from '@ethereumjs/trie'
import {
Account,
KECCAK256_RLP,
Expand Down Expand Up @@ -83,7 +83,7 @@ describe('StateManager -> General', () => {
})

it(`copy()`, async () => {
const trie = new Trie({ cacheSize: 1000 })
const trie = new MerklePatriciaTrie({ cacheSize: 1000 })
let sm = new MerkleStateManager({
trie,
prefixCodeHashes: false,
Expand Down
Loading

0 comments on commit 8846388

Please sign in to comment.