diff --git a/bench/script.js b/bench/script.js new file mode 100644 index 00000000..444082d1 --- /dev/null +++ b/bench/script.js @@ -0,0 +1,43 @@ +'use strict'; + +var BN = require('bn.js'); +var bcoin = require('../').set('main'); +var constants = bcoin.constants; +var utils = bcoin.utils; +var assert = require('assert'); +var scriptTypes = constants.scriptTypes; +var opcodes = constants.opcodes; +var bench = require('./bench'); +var fs = require('fs'); +var Script = bcoin.script; + +bcoin.cache(); + +Script.prototype.fromPubkeyhashOld = function fromScripthash(hash) { + assert(Buffer.isBuffer(hash) && hash.length === 20); + this.push(opcodes.OP_DUP); + this.push(opcodes.OP_HASH160); + this.push(hash); + this.push(opcodes.OP_EQUALVERIFY); + this.push(opcodes.OP_CHECKSIG); + this.compile(); + return this; +}; + +Script.fromPubkeyhashOld = function fromScripthash(hash) { + return new Script().fromPubkeyhashOld(hash); +}; + +var hashes = []; +for (var i = 0; i < 100000; i++) + hashes.push(bcoin.crypto.randomBytes(20)); + +var end = bench('old'); +for (var i = 0; i < hashes.length; i++) + Script.fromPubkeyhashOld(hashes[i]); +end(i); + +var end = bench('hash'); +for (var i = 0; i < hashes.length; i++) + Script.fromPubkeyhash(hashes[i]); +end(i); diff --git a/lib/script/script.js b/lib/script/script.js index f91e1b41..a5729872 100644 --- a/lib/script/script.js +++ b/lib/script/script.js @@ -1611,12 +1611,23 @@ Script.fromPubkey = function fromPubkey(key) { Script.prototype.fromPubkeyhash = function fromPubkeyhash(hash) { assert(Buffer.isBuffer(hash) && hash.length === 20); - this.push(opcodes.OP_DUP); - this.push(opcodes.OP_HASH160); - this.push(hash); - this.push(opcodes.OP_EQUALVERIFY); - this.push(opcodes.OP_CHECKSIG); - this.compile(); + + this.raw = new Buffer(25); + this.raw[0] = opcodes.OP_DUP; + this.raw[1] = opcodes.OP_HASH160; + this.raw[2] = 0x14; + hash.copy(this.raw, 3); + this.raw[23] = opcodes.OP_EQUALVERIFY; + this.raw[24] = opcodes.OP_CHECKSIG; + + hash = this.raw.slice(3, 23); + + this.code.push(new Opcode(opcodes.OP_DUP)); + this.code.push(new Opcode(opcodes.OP_HASH160)); + this.code.push(new Opcode(0x14, hash)); + this.code.push(new Opcode(opcodes.OP_EQUALVERIFY)); + this.code.push(new Opcode(opcodes.OP_CHECKSIG)); + return this; }; @@ -1682,10 +1693,19 @@ Script.fromMultisig = function fromMultisig(m, n, keys) { Script.prototype.fromScripthash = function fromScripthash(hash) { assert(Buffer.isBuffer(hash) && hash.length === 20); - this.push(opcodes.OP_HASH160); - this.push(hash); - this.push(opcodes.OP_EQUAL); - this.compile(); + + this.raw = new Buffer(23); + this.raw[0] = opcodes.OP_HASH160; + this.raw[1] = 0x14; + hash.copy(this.raw, 2); + this.raw[22] = opcodes.OP_EQUAL; + + hash = this.raw.slice(2, 22); + + this.code.push(new Opcode(opcodes.OP_HASH160)); + this.code.push(new Opcode(0x14, hash)); + this.code.push(new Opcode(opcodes.OP_EQUAL)); + return this; };