diff --git a/lib/blockchain/chaindb.js b/lib/blockchain/chaindb.js index eef121c4..f24e6f97 100644 --- a/lib/blockchain/chaindb.js +++ b/lib/blockchain/chaindb.js @@ -762,7 +762,6 @@ class ChainDB { const start = pruneAfter + 1; const end = height - keepBlocks; - const b = this.db.batch(); for (let i = start; i <= end; i++) { const hash = await this.getHash(i); @@ -780,16 +779,12 @@ class ChainDB { const flags = ChainFlags.fromOptions(options); assert(flags.prune); - b.put(layout.O.encode(), flags.toRaw()); - - await b.write(); + await this.db.put(layout.O.encode(), flags.toRaw()); } catch (e) { options.prune = false; throw e; } - await this.db.compactRange(); - return true; } @@ -1466,6 +1461,10 @@ class ChainDB { await this.commit(); + // Remove undo data _after_ successful commit. + if (this.blocks) + await this.blocks.pruneUndo(entry.hash); + return view; } @@ -1582,6 +1581,12 @@ class ChainDB { await this.commit(); + // Remove block and undo data _after_ successful commit. + if (this.blocks) { + await this.blocks.pruneUndo(tip.hash); + await this.blocks.prune(tip.hash); + } + // Update caches _after_ successful commit. this.cacheHeight.remove(tip.height); this.cacheHash.remove(tip.hash); @@ -1605,15 +1610,23 @@ class ChainDB { // one giant atomic write! this.start(); + let hashes = []; + try { for (const tip of tips) - await this._removeChain(tip); + hashes = hashes.concat(await this._removeChain(tip)); } catch (e) { this.drop(); throw e; } await this.commit(); + + // SPV doesn't store blocks. + if (this.blocks) { + for (const hash of hashes) + await this.blocks.prune(hash); + } } /** @@ -1631,6 +1644,8 @@ class ChainDB { this.logger.debug('Removing alternate chain: %h.', tip.hash); + const hashes = []; + for (;;) { if (await this.isMainChain(tip)) break; @@ -1641,7 +1656,10 @@ class ChainDB { this.del(layout.p.encode(tip.hash)); this.del(layout.h.encode(tip.hash)); this.del(layout.e.encode(tip.hash)); - await this.blocks.prune(tip.hash); + + // Queue block to be pruned on + // successful write. + hashes.push(tip.hash); // Queue up hash to be removed // on successful write. @@ -1650,6 +1668,8 @@ class ChainDB { tip = await this.getPrevious(tip); assert(tip); } + + return hashes; } /** @@ -1692,8 +1712,6 @@ class ChainDB { if (!block) throw new Error('Block not found.'); - await this.blocks.prune(block.hash()); - return this.disconnectBlock(entry, block); } @@ -1821,9 +1839,6 @@ class ChainDB { // Commit new coin state. this.saveView(view); - // Remove undo coins. - await this.blocks.pruneUndo(hash); - return view; }