tx-pool: ignore and remove stale transactions

This commit is contained in:
Fedor Indutny 2014-05-10 19:47:30 +04:00
parent d49b04158f
commit 4b6eeeea66
2 changed files with 19 additions and 4 deletions

View File

@ -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)

View File

@ -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;
};