Browse Source

initialize transaction

In order to add convenience methods to a transaction, such as pushing new
inputs and outputs, we need to first have the notion of an initialized
transaction, which is actually not blank. An initialized transaction just has
default values for everything, such as no inputs and no outputs, and default
version and nlocktime.
patch-2
Ryan X. Charles 10 years ago
parent
commit
c07d509623
  1. 15
      lib/transaction.js
  2. 24
      test/transaction.js

15
lib/transaction.js

@ -9,6 +9,7 @@ var Transaction = function Transaction(version, txinsvi, txins, txoutsvi, txouts
if (!(this instanceof Transaction))
return new Transaction(version, txinsvi, txins, txoutsvi, txouts, nlocktime);
if (typeof version === 'number') {
this.initialize();
this.set({
version: version,
txinsvi: txinsvi,
@ -18,14 +19,28 @@ var Transaction = function Transaction(version, txinsvi, txins, txoutsvi, txouts
nlocktime: nlocktime
});
} else if (Buffer.isBuffer(version)) {
//not necessary to initialize, since everything should be overwritten
var txbuf = version;
this.fromBuffer(txbuf);
} else if (version) {
this.initialize();
var obj = version;
this.set(obj);
} else {
this.initialize();
}
};
Transaction.prototype.initialize = function() {
this.version = 1;
this.txinsvi = Varint(0);
this.txins = [];
this.txoutsvi = Varint(0);
this.txouts = [];
this.nlocktime = 0xffffffff;
return this;
};
Transaction.prototype.set = function(obj) {
this.version = typeof obj.version !== 'undefined' ? obj.version : this.version;
this.txinsvi = obj.txinsvi || this.txinsvi;

24
test/transaction.js

@ -30,7 +30,31 @@ describe('Transaction', function() {
should.exist(tx);
tx = Transaction();
should.exist(tx);
Transaction(txbuf).toBuffer().toString('hex').should.equal(txhex);
//should set known defaults
tx.version.should.equal(1);
tx.txinsvi.toNumber().should.equal(0);
tx.txins.length.should.equal(0);
tx.txoutsvi.toNumber().should.equal(0);
tx.txouts.length.should.equal(0);
tx.nlocktime.should.equal(0xffffffff);
});
describe('#initialize', function() {
it('should set these known defaults', function() {
var tx = new Transaction();
tx.initialize();
tx.version.should.equal(1);
tx.txinsvi.toNumber().should.equal(0);
tx.txins.length.should.equal(0);
tx.txoutsvi.toNumber().should.equal(0);
tx.txouts.length.should.equal(0);
tx.nlocktime.should.equal(0xffffffff);
});
});
describe('#set', function() {

Loading…
Cancel
Save