diff --git a/lib/bcoin/chaindb.js b/lib/bcoin/chaindb.js index 55fa576d..eb123e59 100644 --- a/lib/bcoin/chaindb.js +++ b/lib/bcoin/chaindb.js @@ -239,7 +239,7 @@ ChainDB.prototype._open = function open(callback) { bcoin.debug('Chain successfully loaded.'); - callback(); + self.db.checkVersion('V', 0, callback); } this.db.open(function(err) { diff --git a/lib/bcoin/lowlevelup.js b/lib/bcoin/lowlevelup.js index 1672cb09..37796b47 100644 --- a/lib/bcoin/lowlevelup.js +++ b/lib/bcoin/lowlevelup.js @@ -10,6 +10,7 @@ var utils = require('./utils'); var assert = utils.assert; var AsyncObject = require('./async'); +var VERSION_ERROR; /** * Extremely low-level version of levelup. @@ -376,6 +377,33 @@ LowlevelUp.prototype.lookup = function lookup(options, callback) { }); }; +/** + * Write and assert a version number for the database. + * @param {Number} version + * @param {Function} callback + */ + +LowlevelUp.prototype.checkVersion = function checkVersion(key, version, callback) { + var self = this; + this.get(key, function(err, data) { + if (err) + return callback(err); + + if (!data) { + data = new Buffer(4); + data.writeUInt32LE(version, 0, true); + return self.put(key, data, callback); + } + + data = data.readUInt32LE(0, true); + + if (data !== version) + return callback(new Error(VERSION_ERROR)); + + return callback(); + }); +}; + /* * Helpers */ @@ -389,6 +417,14 @@ function isNotFound(err) { || /not\s*found/i.test(err.message); } +VERSION_ERROR = 'Warning:' + + ' Your database does not match the current database version.' + + ' This is likely because the database layout or serialization' + + ' format has changed drastically. If you want to dump your' + + ' data, downgrade to your previous version first. If you do' + + ' not think you should be seeing this error, post an issue on' + + ' the repo.' + /* * Expose */ diff --git a/lib/bcoin/walletdb.js b/lib/bcoin/walletdb.js index c8beb0d3..89b9a7e5 100644 --- a/lib/bcoin/walletdb.js +++ b/lib/bcoin/walletdb.js @@ -132,7 +132,12 @@ WalletDB.prototype._open = function open(callback) { if (err) return callback(err); - self.tx._loadFilter(callback); + self.db.checkVersion('V', 0, function(err) { + if (err) + return callback(err); + + self.tx._loadFilter(callback); + }); }); };