Skip to content

Commit

Permalink
Merge 616d1c4 into b7880ea
Browse files Browse the repository at this point in the history
  • Loading branch information
olalonde committed Aug 6, 2015
2 parents b7880ea + 616d1c4 commit 8687e4d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
17 changes: 16 additions & 1 deletion lib/transaction/transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,22 @@ Object.defineProperty(Transaction.prototype, 'outputAmount', ioProperty);
* @return {Buffer}
*/
Transaction.prototype._getHash = function() {
return Hash.sha256sha256(this.toBuffer());
var buf = this.toBuffer();

// Check if we computed this hash before
if (this._hashMemo && buf.equals(this._hashMemo.buf)) {
return this._hashMemo.hash;
}

var hash = Hash.sha256sha256(buf);

// Memoize buf/hash pair
this._hashMemo = {
buf: buf,
hash: hash
};

return hash;
};

/**
Expand Down
9 changes: 9 additions & 0 deletions test/transaction/transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,15 @@ describe('Transaction', function() {
transaction.id.should.equal(tx_1_id);
});

it('transaction hash is only computed once for the same data', function() {
var transaction = new Transaction(tx_1_hex);
var hash = transaction.hash;
hash.should.equal(transaction.hash);
transaction._getHash().should.equal(transaction._hashMemo.hash);
transaction.inputs.pop();
hash.should.not.equal(transaction.hash);
});

it('serializes an empty transaction', function() {
var transaction = new Transaction();
transaction.uncheckedSerialize().should.equal(tx_empty_hex);
Expand Down

0 comments on commit 8687e4d

Please sign in to comment.