Skip to content

Commit f16177e

Browse files
blockchain: add setHead method
blockchain: add maxBlocks parameter to iterator
1 parent 0067d72 commit f16177e

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

packages/blockchain/src/index.ts

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -736,15 +736,16 @@ export default class Blockchain implements BlockchainInterface {
736736
*
737737
* @param name - Name of the state root head
738738
* @param onBlock - Function called on each block with params (block, reorg)
739+
* @param maxBlocks - How many blocks to run. By default, run all blocks in the canonical chain.
739740
*/
740-
async iterator(name: string, onBlock: OnBlock) {
741-
return this._iterator(name, onBlock)
741+
async iterator(name: string, onBlock: OnBlock, maxBlocks?: number) {
742+
return this._iterator(name, onBlock, maxBlocks)
742743
}
743744

744745
/**
745746
* @hidden
746747
*/
747-
private async _iterator(name: string, onBlock: OnBlock) {
748+
private async _iterator(name: string, onBlock: OnBlock, maxBlocks?: number) {
748749
await this.initAndLock<void>(async () => {
749750
const blockHash = this._heads[name] || this._genesis
750751
let lastBlock: Block | undefined
@@ -755,6 +756,7 @@ export default class Blockchain implements BlockchainInterface {
755756

756757
const number = await this.dbManager.hashToNumber(blockHash)
757758
const blockNumber = number.addn(1)
759+
let blocksRanCounter = 0
758760

759761
// eslint-disable-next-line no-constant-condition
760762
while (true) {
@@ -770,6 +772,10 @@ export default class Blockchain implements BlockchainInterface {
770772
lastBlock = block
771773
await onBlock(block, reorg)
772774
blockNumber.iaddn(1)
775+
blocksRanCounter++
776+
if (maxBlocks && blocksRanCounter == maxBlocks) {
777+
break
778+
}
773779
} catch (error) {
774780
if (error.type !== 'NotFoundError') {
775781
throw error
@@ -782,6 +788,20 @@ export default class Blockchain implements BlockchainInterface {
782788
})
783789
}
784790

791+
/**
792+
* Set header hash of a certain `tag`.
793+
* When calling the iterator, the iterator will start running the first child block after the header hash currenntly stored.
794+
* @param tag - The tag to save the headHash to
795+
* @param headHash - The head hash to save
796+
*/
797+
798+
async setHead(tag: string, headHash: Buffer) {
799+
await this.initAndLock<void>(async () => {
800+
this._heads[tag] = headHash
801+
await this._saveHeads()
802+
})
803+
}
804+
785805
/* Methods regarding re-org operations */
786806

787807
/**

0 commit comments

Comments
 (0)