handle double spends

This commit is contained in:
Matias Alejo Garcia 2014-02-10 17:12:40 -03:00
parent 8b892edfbc
commit a920abdcd9
1 changed files with 56 additions and 26 deletions

View File

@ -70,8 +70,29 @@ function spec(b) {
});
};
TransactionDb.prototype.fromTxId = function(txid, cb) {
TransactionDb.prototype._addSpendInfo = function(r, txid, index) {
if (r.spendTxId) {
if (!r.multipleSpendAttempts) {
r.multipleSpendAttempts = [{
txid: r.spendTxId,
index: r.index,
}];
}
r.multipleSpendAttempts.push({
txid: txid,
index: parseInt(index),
});
}
else {
r.spendTxId = txid;
r.spendIndex = parseInt(index);
}
};
// This is not used now
TransactionDb.prototype.fromTxId = function(txid, cb) {
var self = this;
var k = OUTS_PREFIX + txid;
var ret=[];
var idx={};
@ -93,6 +114,7 @@ function spec(b) {
return cb(err);
})
.on('end', function () {
var k = SPEND_PREFIX + txid;
db.createReadStream({start: k, end: k + '~'})
.on('data', function (data) {
@ -102,15 +124,7 @@ function spec(b) {
assert(typeof j !== 'undefined','Spent could not be stored: tx ' + txid +
'spend in TX:' + k[2] + ',' + k[3]+ ' j:' + j);
/// TODO Handle multiple addresses here!
if (ret[j].spendTxId) {
// double spend!
assert(0);
}
else {
ret[j].spendTxId = k[4];
ret[j].spendIndex = parseInt(k[5]);
}
self._addSpendInfo(ret[j], k[4], k[5]);
})
.on('error', function (err) {
return cb(err);
@ -135,7 +149,7 @@ function spec(b) {
if (err || !addr || !valueSat ) {
console.log('Could not get TXouts in %s,%d from %s ', i.txid, i.vout, info.txid);
incompleteInputs = 1;
return c_in(); // error not scaled
return c_in(); // error not scalated
}
i.addr = addr;
i.valueSat = valueSat;
@ -202,12 +216,37 @@ function spec(b) {
o.isConfirmed = is;
if (!o.spendTxId) return cb();
self.isConfirmed(o.spendTxId, function(err,is) {
if (err) return cb(err);
if (o.multipleSpendAttempts) {
o.spendIsConfirmed = is;
return cb();
});
var isConfirmed = 0;
var txid, index;
async.each(o.multipleSpendAttempts,
function (oi) {
self.isConfirmed(oi.spendTxId, function(err,is) {
if (err) return cb(err);
isConfirmed = 1;
txid = oi.spendTxId;
index = oi.index;
return cb();
});
},
function (err) {
// write the spended TXid into main register
if (isConfirmed) {
o.spendTxId = txid;
o.index = index;
o.spendIsConfirmed = 1;
}
return cb(err);
});
}
else {
self.isConfirmed(o.spendTxId, function(err,is) {
if (err) return cb(err);
o.spendIsConfirmed = is;
return cb();
});
}
});
};
@ -238,16 +277,7 @@ function spec(b) {
db.createReadStream({start: k, end: k + '~'})
.on('data', function (data) {
var k = data.key.split('-');
var v = data.value;
if (o.spendTxId) {
// double spend!
assert(0);
}
else {
o.spendTxId = k[4];
o.spendIndex = parseInt(k[5]);
o.spendTs = parseInt(v);
}
self._addSpendInfo(o, k[4], k[5]);
})
.on('error', function (err) {
return e_c(err);