diff --git a/lib/blockchain/chaindb.js b/lib/blockchain/chaindb.js index a361df4b..aa6845e4 100644 --- a/lib/blockchain/chaindb.js +++ b/lib/blockchain/chaindb.js @@ -11,6 +11,7 @@ const assert = require('bsert'); const bdb = require('bdb'); const bio = require('bufio'); const LRU = require('blru'); +const {resolve} = require('path'); const {BufferMap, BufferSet} = require('buffer-map'); const Amount = require('../btc/amount'); const Network = require('../protocol/network'); @@ -24,6 +25,7 @@ const Address = require('../primitives/address'); const ChainEntry = require('./chainentry'); const TXMeta = require('../primitives/txmeta'); const CoinEntry = require('../coins/coinentry'); +const FileBlockStore = require('../blockstore/file'); /** * ChainDB @@ -46,6 +48,9 @@ class ChainDB { this.state = new ChainState(); this.pending = null; this.current = null; + this.blockStore = new FileBlockStore({ + location: resolve(options.location, '../blocks') + }); this.cacheHash = new LRU(this.options.entryCache, null, BufferMap); this.cacheHeight = new LRU(this.options.entryCache); @@ -60,7 +65,8 @@ class ChainDB { this.logger.info('Opening ChainDB...'); await this.db.open(); - await this.db.verify(layout.V.encode(), 'chain', 4); + await this.db.verify(layout.V.encode(), 'chain', 5); + await this.blockStore.open(); const state = await this.getState(); @@ -101,7 +107,8 @@ class ChainDB { * @returns {Promise} */ - close() { + async close() { + await this.blockStore.close(); return this.db.close(); } @@ -768,8 +775,8 @@ class ChainDB { if (!hash) throw new Error(`Cannot find hash for ${i}.`); - b.del(layout.b.encode(hash)); b.del(layout.u.encode(hash)); + await this.blockStore.prune(hash); } try { @@ -1052,7 +1059,7 @@ class ChainDB { if (!hash) return null; - return this.db.get(layout.b.encode(hash)); + return this.blockStore.read(hash); } /** @@ -1639,7 +1646,7 @@ class ChainDB { this.del(layout.p.encode(tip.hash)); this.del(layout.h.encode(tip.hash)); this.del(layout.e.encode(tip.hash)); - this.del(layout.b.encode(tip.hash)); + await this.blockStore.prune(tip.hash); // Queue up hash to be removed // on successful write. @@ -1667,7 +1674,7 @@ class ChainDB { // Write actual block data (this may be // better suited to flat files in the future). - this.put(layout.b.encode(hash), block.toRaw()); + await this.blockStore.write(hash, block.toRaw()); if (!view) return; @@ -1691,7 +1698,7 @@ class ChainDB { if (!block) throw new Error('Block not found.'); - this.del(layout.b.encode(block.hash())); + await this.blockStore.prune(block.hash()); return this.disconnectBlock(entry, block); } @@ -1851,8 +1858,8 @@ class ChainDB { if (!hash) return; - this.del(layout.b.encode(hash)); this.del(layout.u.encode(hash)); + await this.blockStore.prune(hash); } /**