Skip to content

Commit

Permalink
vm: only create tries when necessary
Browse files Browse the repository at this point in the history
  • Loading branch information
jochem-brouwer committed Oct 27, 2023
1 parent 8cff6f8 commit e3bdb7c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
4 changes: 4 additions & 0 deletions packages/vm/src/buildBlock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
BIGINT_1,
BIGINT_2,
GWEI_TO_WEI,
KECCAK256_RLP,
TypeOutput,
Withdrawal,
toBytes,
Expand Down Expand Up @@ -150,6 +151,9 @@ export class BlockBuilder {
* Calculates and returns the receiptTrie for the block.
*/
public async receiptTrie() {
if (this.transactionResults.length === 0) {
return KECCAK256_RLP
}
const receiptTrie = new Trie()
for (const [i, txResult] of this.transactionResults.entries()) {
const tx = this.transactions[i]
Expand Down
17 changes: 14 additions & 3 deletions packages/vm/src/runBlock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
BIGINT_0,
BIGINT_8,
GWEI_TO_WEI,
KECCAK256_RLP,
bigIntToBytes,
bytesToHex,
concatBytes,
Expand Down Expand Up @@ -390,7 +391,12 @@ async function applyTransactions(this: VM, block: Block, opts: RunBlockOpts) {
const bloom = new Bloom()
// the total amount of gas used processing these transactions
let gasUsed = BIGINT_0
const receiptTrie = new Trie()

let receiptTrie: Trie | undefined = undefined
if (block.transactions.length !== 0) {
receiptTrie = new Trie()
}

const receipts = []
const txResults = []

Expand Down Expand Up @@ -440,7 +446,7 @@ async function applyTransactions(this: VM, block: Block, opts: RunBlockOpts) {
// Add receipt to trie to later calculate receipt root
receipts.push(txRes.receipt)
const encodedReceipt = encodeReceipt(txRes.receipt, tx.type)
await receiptTrie.put(RLP.encode(txIdx), encodedReceipt)
await receiptTrie!.put(RLP.encode(txIdx), encodedReceipt)
}

if (enableProfiler) {
Expand All @@ -450,10 +456,12 @@ async function applyTransactions(this: VM, block: Block, opts: RunBlockOpts) {
console.timeEnd(entireBlockLabel)
}

const receiptsRoot = receiptTrie !== undefined ? receiptTrie.root() : KECCAK256_RLP

return {
bloom,
gasUsed,
receiptsRoot: receiptTrie.root(),
receiptsRoot,
receipts,
results: txResults,
}
Expand Down Expand Up @@ -590,6 +598,9 @@ async function _applyDAOHardfork(evm: EVMInterface) {
}

async function _genTxTrie(block: Block) {
if (block.transactions.length === 0) {
return KECCAK256_RLP
}
const trie = new Trie()
for (const [i, tx] of block.transactions.entries()) {
await trie.put(RLP.encode(i), tx.serialize())
Expand Down

0 comments on commit e3bdb7c

Please sign in to comment.