@@ -736,15 +736,16 @@ export default class Blockchain implements BlockchainInterface {
736
736
*
737
737
* @param name - Name of the state root head
738
738
* @param onBlock - Function called on each block with params (block, reorg)
739
+ * @param maxBlocks - How many blocks to run. By default, run all unprocessed blocks in the canonical chain.
739
740
*/
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 )
742
743
}
743
744
744
745
/**
745
746
* @hidden
746
747
*/
747
- private async _iterator ( name : string , onBlock : OnBlock ) {
748
+ private async _iterator ( name : string , onBlock : OnBlock , maxBlocks ?: number ) {
748
749
await this . initAndLock < void > ( async ( ) => {
749
750
const blockHash = this . _heads [ name ] || this . _genesis
750
751
let lastBlock : Block | undefined
@@ -753,11 +754,15 @@ export default class Blockchain implements BlockchainInterface {
753
754
return
754
755
}
755
756
757
+ if ( maxBlocks && maxBlocks < 0 ) {
758
+ throw 'If maxBlocks is provided, it has to be a non-negative number'
759
+ }
760
+
756
761
const number = await this . dbManager . hashToNumber ( blockHash )
757
762
const blockNumber = number . addn ( 1 )
763
+ let blocksRanCounter = 0
758
764
759
- // eslint-disable-next-line no-constant-condition
760
- while ( true ) {
765
+ while ( maxBlocks !== blocksRanCounter ) {
761
766
try {
762
767
const block = await this . _getBlock ( blockNumber )
763
768
@@ -770,6 +775,7 @@ export default class Blockchain implements BlockchainInterface {
770
775
lastBlock = block
771
776
await onBlock ( block , reorg )
772
777
blockNumber . iaddn ( 1 )
778
+ blocksRanCounter ++
773
779
} catch ( error ) {
774
780
if ( error . type !== 'NotFoundError' ) {
775
781
throw error
@@ -782,6 +788,19 @@ export default class Blockchain implements BlockchainInterface {
782
788
} )
783
789
}
784
790
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
+ async setHead ( tag : string , headHash : Buffer ) {
798
+ await this . initAndLock < void > ( async ( ) => {
799
+ this . _heads [ tag ] = headHash
800
+ await this . _saveHeads ( )
801
+ } )
802
+ }
803
+
785
804
/* Methods regarding re-org operations */
786
805
787
806
/**
0 commit comments