Skip to content

Commit

Permalink
Process blocks in turn
Browse files Browse the repository at this point in the history
  • Loading branch information
dgca committed Sep 8, 2023
1 parent b39304e commit 8e4c14c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
5 changes: 3 additions & 2 deletions example/src/Client/utils/BlockCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,9 @@ export class BlockCache {
return Number(key);
}

public getBlockBySequence(sequence: number): Promise<LightBlock> {
return this.db.get(this.encodeKey(sequence));
public async getBlockBySequence(sequence: number): Promise<LightBlock> {
const blockData = await this.db.get(this.encodeKey(sequence));
return LightBlock.decode(blockData);
}

public async handleReorg(lastValidBlock: LightBlock) {
Expand Down
14 changes: 8 additions & 6 deletions example/src/Client/utils/BlockProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,10 @@ export class BlockProcessor {

try {
await new Promise((res) => {
stream.on("data", (block: LightBlock) => {
this._processBlock(block);
stream.on("data", async (block: LightBlock) => {
stream.pause();
await this._processBlock(block);
stream.resume();
blocksProcessed++;

logThrottled(
Expand Down Expand Up @@ -156,7 +158,7 @@ export class BlockProcessor {
return;
}

this.blockCache.cacheBlock(block);
await this.blockCache.cacheBlock(block);

const notes: Buffer[] = [];

Expand All @@ -175,13 +177,13 @@ export class BlockProcessor {
return false;
}

const prevBlock = await this.blockCache.getBlockBySequence(
const prevCachedBlock = await this.blockCache.getBlockBySequence(
block.sequence - 1,
);

// If the incoming block's previous block hash matches the previous block's hash,
// there is no reorg.
if (block.previousBlockHash === prevBlock.hash) {
// there is no reorg. Note that Buffer.compare returns 0 if the two buffers are equal.
if (block.previousBlockHash.compare(prevCachedBlock.hash) === 0) {
return false;
}

Expand Down

0 comments on commit 8e4c14c

Please sign in to comment.