Skip to content

Commit

Permalink
chain: emit reset for spv reorg.
Browse files Browse the repository at this point in the history
  • Loading branch information
nodech committed May 13, 2022
1 parent 51f2262 commit 219d611
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
2 changes: 1 addition & 1 deletion lib/blockchain/chain.js
Original file line number Diff line number Diff line change
Expand Up @@ -1652,7 +1652,7 @@ class Chain extends AsyncEmitter {
// to the fork block, causing
// us to redownload the blocks
// on the new main chain.
await this._reset(fork.hash, true);
await this._reset(fork.hash);

// Emit disconnection events now that
// the chain has successfully reset.
Expand Down
13 changes: 10 additions & 3 deletions test/chain-reorg-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,21 +160,25 @@ for (const type of ['full', 'spv']) {
assert(!await chain.isMainChain(tip2));
assert(await testChain.isMainChain(tip1));
assert(!await testChain.isMainChain(tip2));
assert.strictEqual(tip1.height, 11 + i);
}
});

if (type === 'spv') {
it('should reorg to alternative chain and back (spv)', async () => {
const reorgs = [];
let resets = 0;

const handleReorg = (tip, competitor) => {
reorgs.push({
competitor,
tip
});
};
const handleReset = () => resets++;

testChain.on('reorganize', handleReorg);
testChain.on('reset', handleReset);

// Replay main chain to the SPV node.
const replayChain = async (fork) => {
Expand Down Expand Up @@ -208,6 +212,7 @@ for (const type of ['full', 'spv']) {
assert(await chain.isMainChain(tip2));
}

// sync chain with spv.
await replayChain(fork);
assert.bufferEqual(testChain.tip.hash, tip2.hash);

Expand All @@ -226,19 +231,19 @@ for (const type of ['full', 'spv']) {

assert(await chain.add(blk));

// i = 1 will give use new best chain tip and tip1 will become best.
tip1 = await chain.getEntry(hash);
// last one.
assert(tip1);
assert.strictEqual(await testChain.getEntry(hash), null);
}

// Replay current best chain. This should
// cause SPV to reset chain to the fork.
// above reset will catch it and replay again.
await replayChain(fork);

assert.bufferEqual(testChain.tip.hash, fork.hash);

// Now we need to replay network once again,
// Now we need to replay blocks once again,
// because above replay caused it to reorg and reset.
await replayChain(fork);
assert.bufferEqual(testChain.tip.hash, tip1.hash);
Expand All @@ -265,8 +270,10 @@ for (const type of ['full', 'spv']) {

assert.bufferEqual(testChain.tip.hash, tip1.hash);
assert.strictEqual(reorgs.length, 2);
assert.strictEqual(resets, 2);

testChain.removeListener('reorganize', handleReorg);
testChain.removeListener('reset', handleReset);
});
}

Expand Down

0 comments on commit 219d611

Please sign in to comment.