Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve register block #360

Merged
merged 1 commit into from
Aug 2, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions packages/chopsticks/src/blockchain/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,17 +87,26 @@ export class Blockchain {
this.offchainWorker = new OffchainWorker()
}

if (maxMemoryBlockCount < 1) {
throw new Error('MaxMemoryBlockCount value must be equalOrGreater than 1.')
}

this.#maxMemoryBlockCount = maxMemoryBlockCount
}

#registerBlock(block: Block) {
// if exceed max memory block count, delete the oldest block
if (this.#blocksByNumber.size === this.#maxMemoryBlockCount) {
const firstKey = this.#blocksByNumber.keys().next().value
this.#blocksByNumber.delete(firstKey)
}
this.#blocksByNumber.set(block.number, block)
this.#blocksByHash[block.hash] = block

// if exceed max memory block count, delete the earliest block
if (this.#blocksByNumber.size > this.#maxMemoryBlockCount) {
const earliestBlockNumber = Math.min(...this.#blocksByNumber.keys())
const earliestBlock = this.#blocksByNumber.get(earliestBlockNumber)
this.#blocksByNumber.delete(earliestBlockNumber)
if (earliestBlock) {
delete this.#blocksByHash[earliestBlock.hash]
}
}
}

get head(): Block {
Expand Down Expand Up @@ -173,6 +182,7 @@ export class Blockchain {
'setHead',
)
this.#head = block
// TODO: unregister blocks from current head to new head
this.#registerBlock(block)
await this.headState.setHead(block)

Expand Down