From 4b6eeeea6673a5d56ba519516637891b3d380deb Mon Sep 17 00:00:00 2001 From: Fedor Indutny Date: Sat, 10 May 2014 19:47:30 +0400 Subject: [PATCH] tx-pool: ignore and remove stale transactions --- lib/bcoin/tx-pool.js | 11 ++++++++++- lib/bcoin/tx.js | 12 +++++++++--- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/lib/bcoin/tx-pool.js b/lib/bcoin/tx-pool.js index df894b4b..112ecb4c 100644 --- a/lib/bcoin/tx-pool.js +++ b/lib/bcoin/tx-pool.js @@ -48,6 +48,12 @@ TXPool.prototype._init = function init() { TXPool.prototype.add = function add(tx, noWrite) { var hash = tx.hash('hex'); + // Ignore stale pending transactions + if (tx.ps + 2 * 24 * 3600 < +new Date / 1000) { + this._removeTX(orphan.tx); + return; + } + // Do not add TX two times if (this._all[hash]) { // Transaction was confirmed, update it in storage @@ -135,7 +141,7 @@ TXPool.prototype.add = function add(tx, noWrite) { if (updated) this.emit('update', this._lastTs); - if (!noWrite && this._storage) + if (!noWrite) this._storeTX(hash, tx); this.emit('tx', tx); @@ -144,6 +150,9 @@ TXPool.prototype.add = function add(tx, noWrite) { }; TXPool.prototype._storeTX = function _storeTX(hash, tx) { + if (!this._storage) + return; + var self = this; this._storage.put(this._prefix + hash, tx.toJSON(), function(err) { if (err) diff --git a/lib/bcoin/tx.js b/lib/bcoin/tx.js index 51129c2b..c3db4e1b 100644 --- a/lib/bcoin/tx.js +++ b/lib/bcoin/tx.js @@ -35,6 +35,9 @@ function TX(data, block) { if (!data.ts && block && block.hasTX(this.hash('hex'))) this.ts = block.ts; + + // ps = Pending Since + this.ps = this.ts === 0 ? +new Date / 1000 : 0; } module.exports = TX; @@ -246,19 +249,22 @@ TX.prototype.inputAddrs = function inputAddrs() { TX.prototype.toJSON = function toJSON() { // Compact representation - var ts = new Array(4); + var ts = new Array(8); bcoin.utils.writeU32(ts, this.ts, 0); + bcoin.utils.writeU32(ts, this.ps, 4); return utils.toHex(this.render().concat(ts)); }; TX.fromJSON = function fromJSON(json) { // Compact representation var data = utils.toArray(json, 'hex'); - var tx = data.slice(0, -4); - var ts = bcoin.utils.readU32(data, data.length - 4); + var tx = data.slice(0, -8); + var ts = bcoin.utils.readU32(data, data.length - 8); + var ps = bcoin.utils.readU32(data, data.length - 4); tx = new TX(new bcoin.protocol.parser().parseTX(tx)); tx.ts = ts; + tx.ps = ps; return tx; };