From e8a70f9d7b382be31effb7f52896c14bce2f8180 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Wed, 2 Mar 2016 03:03:14 -0800 Subject: [PATCH] check for double-spends in txdb. --- lib/bcoin/txdb.js | 51 +++++++++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/lib/bcoin/txdb.js b/lib/bcoin/txdb.js index 66e0ffaa..51fa0660 100644 --- a/lib/bcoin/txdb.js +++ b/lib/bcoin/txdb.js @@ -237,8 +237,6 @@ TXPool.prototype._add = function add(tx, callback, force) { return next(); } - // TODO: Check for double-spend by doing self.getTX(input.prevout.hash) - // Only add orphans if this input is ours. self._hasAddress(input.getAddress(), function(err, result) { if (err) @@ -247,31 +245,40 @@ TXPool.prototype._add = function add(tx, callback, force) { if (!result) return next(); - // Add orphan, if no parent transaction is yet known - self.db.get(p + 'o/' + key, function(err, orphans) { - if (err && err.type !== 'NotFoundError') + self.getTX(input.prevout.hash, function(err, result) { + if (err) return done(err); - if (orphans) { - try { - orphans = JSON.parse(orphans.toString('utf8')); - } catch (e) { - return done(e); + // Are we double-spending? + if (result) + return done(new Error('Transaction is double-spending.')); + + // Add orphan, if no parent transaction is yet known + self.db.get(p + 'o/' + key, function(err, orphans) { + if (err && err.type !== 'NotFoundError') + return done(err); + + if (orphans) { + try { + orphans = JSON.parse(orphans.toString('utf8')); + } catch (e) { + return done(e); + } + } else { + orphans = []; } - } else { - orphans = []; - } - orphans.push({ - tx: tx.toExtended(true).toString('hex'), - index: i + orphans.push({ + tx: tx.toExtended(true).toString('hex'), + index: i + }); + + orphans = new Buffer(JSON.stringify(orphans), 'utf8'); + + batch.put(p + 'o/' + key, orphans); + + return next(); }); - - orphans = new Buffer(JSON.stringify(orphans), 'utf8'); - - batch.put(p + 'o/' + key, orphans); - - return next(); }); }); });