diff --git a/lib/primitives/abstractblock.js b/lib/primitives/abstractblock.js index dade5bef..e0ecfc06 100644 --- a/lib/primitives/abstractblock.js +++ b/lib/primitives/abstractblock.js @@ -58,6 +58,7 @@ function AbstractBlock(options) { this._valid = null; this._hash = null; + this._hhash = null; this._size = null; this._witnessSize = null; @@ -140,6 +141,7 @@ AbstractBlock.prototype.parseJSON = function parseJSON(json) { AbstractBlock.prototype.hash = function hash(enc) { var hash = this._hash; + var hex; if (!hash) { hash = crypto.hash256(this.abbr()); @@ -147,7 +149,17 @@ AbstractBlock.prototype.hash = function hash(enc) { this._hash = hash; } - return enc === 'hex' ? hash.toString('hex') : hash; + if (enc === 'hex') { + hex = this._hhash; + if (!hex) { + hex = hash.toString('hex'); + if (!this.mutable) + this._hhash = hex; + } + hash = hex; + } + + return hash; }; /** diff --git a/lib/primitives/tx.js b/lib/primitives/tx.js index f1e8589b..a7cd7e83 100644 --- a/lib/primitives/tx.js +++ b/lib/primitives/tx.js @@ -86,6 +86,7 @@ function TX(options) { this.mutable = false; this._hash = null; + this._hhash = null; this._whash = null; this._raw = null; @@ -219,6 +220,7 @@ TX.prototype.unsetBlock = function unsetBlock() { TX.prototype.hash = function _hash(enc) { var hash = this._hash; + var hex; if (!hash) { hash = crypto.hash256(this.toNormal()); @@ -226,7 +228,17 @@ TX.prototype.hash = function _hash(enc) { this._hash = hash; } - return enc === 'hex' ? hash.toString('hex') : hash; + if (enc === 'hex') { + hex = this._hhash; + if (!hex) { + hex = hash.toString('hex'); + if (!this.mutable) + this._hhash = hex; + } + hash = hex; + } + + return hash; }; /** diff --git a/test/script-test.js b/test/script-test.js index 3b49dd20..82df00fb 100644 --- a/test/script-test.js +++ b/test/script-test.js @@ -348,6 +348,8 @@ describe('Script', function() { tx._witnessSize = -1; tx._lastWitnessSize = 0; tx._hash = null; + tx._hhash = null; + tx._whash = null; tx._inputValue = -1; tx._outputValue = -1; tx._hashPrevouts = null; diff --git a/test/tx-test.js b/test/tx-test.js index 6f2911a1..6cd589c0 100644 --- a/test/tx-test.js +++ b/test/tx-test.js @@ -47,6 +47,8 @@ function clearCache(tx, nocache) { tx._witnessSize = -1; tx._lastWitnessSize = 0; tx._hash = null; + tx._hhash = null; + tx._whash = null; tx._inputValue = -1; tx._outputValue = -1; tx._hashPrevouts = null;