itns-sidechain/lib/script/script.js

3623 lines
86 KiB
JavaScript
Raw Normal View History

/*!
2016-03-14 20:43:32 -07:00
* script.js - script interpreter for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License)
2016-04-06 18:20:03 -07:00
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
2016-06-09 16:18:50 -07:00
* https://github.com/bcoin-org/bcoin
2016-03-14 20:43:32 -07:00
*/
2016-06-13 01:06:01 -07:00
'use strict';
2016-08-23 22:43:20 -07:00
var bcoin = require('../env');
2016-03-14 20:43:32 -07:00
var bn = require('bn.js');
2016-08-24 01:32:56 -07:00
var constants = bcoin.constants;
2016-08-23 22:43:20 -07:00
var utils = require('../utils/utils');
2016-03-15 04:57:11 -07:00
var assert = utils.assert;
2016-08-23 22:43:20 -07:00
var BufferWriter = require('../utils/writer');
var BufferReader = require('../utils/reader');
2016-03-28 19:42:05 -07:00
var opcodes = constants.opcodes;
2016-03-29 13:15:43 -07:00
var STACK_TRUE = new Buffer([1]);
var STACK_FALSE = new Buffer([]);
2016-04-18 17:02:33 -07:00
var STACK_NEGATE = new Buffer([0x81]);
2016-04-29 17:45:13 -07:00
var ScriptError = bcoin.errors.ScriptError;
2016-07-02 04:53:42 -07:00
var scriptTypes = constants.scriptTypes;
2016-08-24 04:08:40 -07:00
var Program = require('./program');
var Opcode = require('./opcode');
var Stack = require('./stack');
2016-03-24 13:28:24 -07:00
2016-03-14 20:43:32 -07:00
/**
* Represents a input or output script.
* @exports Script
* @constructor
* @param {Buffer|Array|Object|NakedScript} code - Array
* of script code or a serialized script Buffer.
2016-06-20 01:09:27 -07:00
* @property {Array} code - Parsed script code.
2016-04-17 19:34:03 -07:00
* @property {Buffer?} raw - Serialized script.
* @property {Script?} redeem - Redeem script.
2016-06-20 01:09:27 -07:00
* @property {Number} length - Number of parsed opcodes.
2016-03-14 20:43:32 -07:00
*/
2016-06-18 17:42:49 -07:00
function Script(options) {
2016-03-14 20:43:32 -07:00
if (!(this instanceof Script))
2016-06-18 17:42:49 -07:00
return new Script(options);
2016-03-14 20:43:32 -07:00
2016-06-17 01:34:59 -07:00
this.raw = STACK_FALSE;
this.code = [];
2016-04-17 19:34:03 -07:00
2016-06-18 17:42:49 -07:00
if (options)
this.fromOptions(options);
2016-06-17 01:34:59 -07:00
}
2016-04-17 19:34:03 -07:00
2016-06-20 03:16:23 -07:00
Script.prototype.__defineGetter__('length', function() {
return this.code.length;
});
Script.prototype.__defineSetter__('length', function(length) {
return this.code.length = length;
});
2016-06-20 01:09:27 -07:00
/**
* Inject properties from options object.
* @private
* @param {Object} options
*/
2016-06-17 01:34:59 -07:00
Script.prototype.fromOptions = function fromOptions(options) {
2016-07-01 06:03:48 -07:00
assert(options, 'Script data is required.');
2016-06-17 01:34:59 -07:00
2016-07-01 06:03:48 -07:00
if (Buffer.isBuffer(options))
return this.fromRaw(options);
2016-06-17 01:34:59 -07:00
2016-07-01 06:03:48 -07:00
if (Array.isArray(options))
return this.fromArray(options);
2016-06-17 01:34:59 -07:00
2016-07-01 06:03:48 -07:00
if (options.raw) {
if (!options.code)
return this.fromRaw(options.raw);
assert(Buffer.isBuffer(options.raw));
this.raw = options.raw;
}
2016-06-13 21:25:42 -07:00
2016-07-01 06:03:48 -07:00
if (options.code) {
if (!options.raw)
return this.fromArray(options.code);
assert(Array.isArray(options.code));
this.code = options.code;
}
2016-06-17 01:34:59 -07:00
return this;
};
2016-06-20 01:09:27 -07:00
/**
* Insantiate script from options object.
* @param {Object} options
* @returns {Script}
*/
2016-06-18 17:42:49 -07:00
Script.fromOptions = function fromOptions(options) {
return new Script().fromOptions(options);
2016-06-17 01:34:59 -07:00
};
2016-03-14 20:43:32 -07:00
2016-06-14 16:26:26 -07:00
/**
* Convert the script to an array of
* Buffers (pushdatas) and Numbers
* (opcodes).
* @returns {Array}
*/
2016-06-13 21:25:42 -07:00
Script.prototype.toArray = function toArray() {
var code = [];
var i, op;
for (i = 0; i < this.code.length; i++) {
op = this.code[i];
code.push(op.data || op.value);
}
return code;
};
2016-07-01 05:42:04 -07:00
/**
* Inject properties from an array of
* of buffers and numbers.
* @private
*/
Script.prototype.fromArray = function fromArray(code) {
assert(Array.isArray(code));
this.code = Script.parseArray(code);
this.raw = Script.encode(this.code);
return this;
};
2016-06-14 16:26:26 -07:00
/**
* Instantiate script from an array
* of buffers and numbers.
* @returns {Script}
*/
2016-06-13 21:25:42 -07:00
Script.fromArray = function fromArray(code) {
2016-07-01 05:42:04 -07:00
return new Script().fromArray(code);
2016-06-13 21:25:42 -07:00
};
/**
* Clone the script.
* @returns {Script} Cloned script.
*/
2016-06-13 21:25:42 -07:00
Script.prototype.clone = function clone() {
return new Script(this.raw);
2016-03-14 20:43:32 -07:00
};
/**
* Inspect the script.
* @returns {String} Human-readable script code.
*/
2016-03-14 20:43:32 -07:00
Script.prototype.inspect = function inspect() {
return '<Script: ' + this.toString() + '>';
};
/**
* Convert the script to a bitcoind test string.
* @returns {String} Human-readable script code.
*/
Script.prototype.toString = function toString() {
2016-03-14 20:43:32 -07:00
return Script.format(this.code);
};
2016-04-29 21:45:18 -07:00
/**
* Format the script as bitcoind asm.
* @param {Boolean?} decode - Attempt to decode hash types.
* @returns {String} Human-readable script.
*/
Script.prototype.toASM = function toASM(decode) {
return Script.formatASM(this.code, decode);
};
2016-06-14 16:26:26 -07:00
/**
* Re-encode the script internally. Useful if you
* changed something manually in the `code` array.
*/
Script.prototype.compile = function compile() {
2016-06-13 21:25:42 -07:00
this.raw = Script.encode(this.code);
};
2016-04-19 11:39:55 -07:00
/**
* Encode the script to a Buffer. See {@link Script#encode}.
* @param {String} enc - Encoding, either `'hex'` or `null`.
* @returns {Buffer|String} Serialized script.
*/
2016-06-17 01:34:59 -07:00
Script.prototype.toRaw = function toRaw(writer) {
if (writer) {
writer.writeVarBytes(this.raw);
return writer;
}
return this.raw;
2016-04-19 11:39:55 -07:00
};
2016-06-20 01:09:27 -07:00
/**
* Convert script to a hex string.
* @returns {String}
*/
2016-06-17 02:26:48 -07:00
Script.prototype.toJSON = function toJSON() {
return this.toRaw().toString('hex');
};
2016-06-27 17:32:23 -07:00
/**
* Inject properties from json object.
* @private
* @param {String} json
*/
Script.prototype.fromJSON = function fromJSON(json) {
assert(typeof json === 'string');
return this.fromRaw(new Buffer(json, 'hex'));
};
2016-06-20 01:09:27 -07:00
/**
* Instantiate script from a hex string.
* @params {String} json
* @returns {Script}
*/
2016-06-17 02:26:48 -07:00
Script.fromJSON = function fromJSON(json) {
2016-06-27 17:32:23 -07:00
return new Script().fromJSON(json);
2016-06-17 02:26:48 -07:00
};
/**
* Get the script's "subscript" starting at a separator.
* @param {Number?} lastSep - The last separator to sign/verify beyond.
* @returns {Script} Subscript.
*/
2016-03-14 20:43:32 -07:00
Script.prototype.getSubscript = function getSubscript(lastSep) {
2016-04-15 06:44:34 -07:00
var code = [];
2016-06-13 21:25:42 -07:00
var i, op;
2016-03-14 20:43:32 -07:00
2016-06-13 21:25:42 -07:00
if (lastSep === 0)
return this.clone();
2016-03-14 20:43:32 -07:00
2016-04-27 20:06:55 -07:00
for (i = lastSep; i < this.code.length; i++) {
2016-06-13 21:25:42 -07:00
op = this.code[i];
if (op.value === -1)
2016-04-21 10:24:09 -07:00
break;
2016-06-13 21:25:42 -07:00
code.push(op);
2016-04-27 20:06:55 -07:00
}
2016-06-13 22:39:05 -07:00
return new Script(code);
2016-04-27 20:06:55 -07:00
};
/**
* Get the script's "subscript" starting at a separator.
* Remove all OP_CODESEPARATORs if present. This bizarre
* behavior is necessary for signing and verification when
* code separators are present.
* @returns {Script} Subscript.
*/
Script.prototype.removeSeparators = function removeSeparators() {
var code = [];
2016-06-13 21:25:42 -07:00
var i, op;
2016-04-27 20:06:55 -07:00
for (i = 0; i < this.code.length; i++) {
2016-06-13 21:25:42 -07:00
op = this.code[i];
if (op.value === -1)
2016-04-27 20:50:04 -07:00
break;
2016-06-13 21:25:42 -07:00
if (op.value !== opcodes.OP_CODESEPARATOR)
code.push(op);
2016-03-14 20:43:32 -07:00
}
2016-06-13 21:25:42 -07:00
if (code.length === this.code.length)
return this.clone();
2016-03-14 20:43:32 -07:00
2016-06-13 22:39:05 -07:00
return new Script(code);
2016-03-14 20:43:32 -07:00
};
/**
* Execute and interpret the script.
* @param {Stack} stack - Script execution stack.
* @param {Number?} flags - Script standard flags.
* @param {TX?} tx - Transaction being verified.
* @param {Number?} index - Index of input being verified.
* @param {Number?} version - Signature hash version (0=legacy, 1=segwit).
* @throws {ScriptError} Will be thrown on VERIFY failures, among other things.
* @returns {Boolean} Whether the execution was successful.
*/
2016-04-19 22:44:54 -07:00
Script.prototype.execute = function execute(stack, flags, tx, index, version) {
2016-03-14 20:43:32 -07:00
var ip = 0;
2016-04-27 20:06:55 -07:00
var lastSep = 0;
2016-04-17 06:39:31 -07:00
var opCount = 0;
2016-06-12 14:27:29 -07:00
var alt = [];
var state = [];
var negate = 0;
2016-06-16 02:51:50 -07:00
var op, code, data, val, v1, v2, v3;
2016-03-14 20:43:32 -07:00
var n, n1, n2, n3;
2016-04-04 02:53:55 -07:00
var res, key, sig, type, subscript, hash;
2016-05-25 01:06:41 -07:00
var i, j, m, ikey, isig;
2016-04-18 19:19:06 -07:00
var locktime;
2016-03-14 20:43:32 -07:00
if (flags == null)
flags = constants.flags.STANDARD_VERIFY_FLAGS;
2016-04-17 08:45:22 -07:00
if (this.getSize() > constants.script.MAX_SIZE)
2016-04-19 22:44:54 -07:00
throw new ScriptError('SCRIPT_SIZE');
2016-03-14 20:43:32 -07:00
2016-04-17 06:39:31 -07:00
for (ip = 0; ip < this.code.length; ip++) {
2016-06-16 02:51:50 -07:00
code = this.code[ip];
op = code.value;
data = code.data;
2016-03-14 20:43:32 -07:00
2016-06-16 02:51:50 -07:00
if (op === -1)
2016-04-20 09:20:45 -07:00
throw new ScriptError('BAD_OPCODE', op, ip);
2016-06-16 02:51:50 -07:00
if (data) {
if (data.length > constants.script.MAX_PUSH)
2016-04-19 21:43:40 -07:00
throw new ScriptError('PUSH_SIZE', op, ip);
2016-04-17 06:39:31 -07:00
// Note that minimaldata is not checked
// on unexecuted branches of code.
2016-06-12 14:27:29 -07:00
if (negate === 0) {
2016-06-16 02:51:50 -07:00
if (!Script.isMinimal(data, op, flags))
2016-04-19 21:43:40 -07:00
throw new ScriptError('MINIMALDATA', op, ip);
2016-06-16 02:51:50 -07:00
stack.push(data);
2016-04-17 06:39:31 -07:00
}
2016-03-14 20:43:32 -07:00
continue;
}
2016-04-17 08:45:22 -07:00
if (op > opcodes.OP_16 && ++opCount > constants.script.MAX_OPS)
2016-04-19 21:43:40 -07:00
throw new ScriptError('OP_COUNT', op, ip);
2016-04-17 06:39:31 -07:00
// It's very important to make a distiction
// here: these opcodes will fail _even if they
// are in unexecuted branches of code_. Whereas
// a totally unknown opcode is fine as long as it
// is unexecuted.
2016-06-16 02:23:36 -07:00
switch (op) {
case opcodes.OP_CAT:
case opcodes.OP_SUBSTR:
case opcodes.OP_LEFT:
case opcodes.OP_RIGHT:
case opcodes.OP_INVERT:
case opcodes.OP_AND:
case opcodes.OP_OR:
case opcodes.OP_XOR:
case opcodes.OP_2MUL:
case opcodes.OP_2DIV:
case opcodes.OP_MUL:
case opcodes.OP_DIV:
case opcodes.OP_MOD:
case opcodes.OP_LSHIFT:
case opcodes.OP_RSHIFT:
throw new ScriptError('DISABLED_OPCODE', op, ip);
2016-04-17 06:39:31 -07:00
}
if (op >= opcodes.OP_IF && op <= opcodes.OP_ENDIF) {
switch (op) {
case opcodes.OP_IF:
case opcodes.OP_NOTIF: {
2016-06-16 02:27:35 -07:00
val = false;
2016-06-12 14:27:29 -07:00
if (negate === 0) {
2016-04-17 06:39:31 -07:00
if (stack.length < 1)
2016-04-19 21:43:40 -07:00
throw new ScriptError('UNBALANCED_CONDITIONAL', op, ip);
2016-04-17 06:39:31 -07:00
val = Script.bool(stack.pop());
if (op === opcodes.OP_NOTIF)
val = !val;
}
2016-06-16 02:27:35 -07:00
state.push(val);
if (!val)
negate++;
2016-04-17 06:39:31 -07:00
break;
}
case opcodes.OP_ELSE: {
2016-06-12 14:27:29 -07:00
if (state.length === 0)
2016-04-19 21:43:40 -07:00
throw new ScriptError('UNBALANCED_CONDITIONAL', op, ip);
2016-06-16 02:25:42 -07:00
state[state.length - 1] = !state[state.length - 1];
if (!state[state.length - 1])
2016-06-12 14:27:29 -07:00
negate++;
2016-04-17 06:39:31 -07:00
else
2016-06-12 14:27:29 -07:00
negate--;
2016-04-17 06:39:31 -07:00
break;
}
case opcodes.OP_ENDIF: {
2016-06-12 14:27:29 -07:00
if (state.length === 0)
2016-04-19 21:43:40 -07:00
throw new ScriptError('UNBALANCED_CONDITIONAL', op, ip);
2016-06-16 02:25:42 -07:00
if (!state.pop())
2016-06-12 14:27:29 -07:00
negate--;
2016-04-17 06:39:31 -07:00
break;
}
case opcodes.OP_VERIF:
case opcodes.OP_VERNOTIF: {
2016-04-19 21:43:40 -07:00
throw new ScriptError('BAD_OPCODE', op, ip);
2016-04-17 06:39:31 -07:00
}
default: {
2016-06-16 02:27:35 -07:00
assert(false, 'Fatal script error.');
2016-04-17 06:39:31 -07:00
}
}
continue;
}
2016-06-12 14:27:29 -07:00
if (negate !== 0)
2016-04-17 06:39:31 -07:00
continue;
2016-04-19 21:43:40 -07:00
switch (op) {
case opcodes.OP_0: {
stack.push(STACK_FALSE);
break;
}
case opcodes.OP_1NEGATE: {
stack.push(STACK_NEGATE);
break;
}
case opcodes.OP_1:
case opcodes.OP_2:
case opcodes.OP_3:
case opcodes.OP_4:
case opcodes.OP_5:
case opcodes.OP_6:
case opcodes.OP_7:
case opcodes.OP_8:
case opcodes.OP_9:
case opcodes.OP_10:
case opcodes.OP_11:
case opcodes.OP_12:
case opcodes.OP_13:
case opcodes.OP_14:
case opcodes.OP_15:
case opcodes.OP_16: {
stack.push(new Buffer([op - 0x50]));
break;
}
case opcodes.OP_NOP: {
break;
}
case opcodes.OP_CHECKLOCKTIMEVERIFY: {
// OP_CHECKLOCKTIMEVERIFY = OP_NOP2
if (!(flags & constants.flags.VERIFY_CHECKLOCKTIMEVERIFY)) {
if (flags & constants.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
throw new ScriptError('DISCOURAGE_UPGRADABLE_NOPS', op, ip);
break;
}
2016-03-14 20:43:32 -07:00
2016-04-19 21:43:40 -07:00
if (!tx)
2016-04-19 22:44:54 -07:00
throw new ScriptError('UNKNOWN_ERROR', 'No TX passed in.');
2016-03-14 20:43:32 -07:00
2016-04-19 21:43:40 -07:00
if (stack.length === 0)
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
locktime = Script.num(stack.top(-1), flags, 5);
if (locktime.cmpn(0) < 0)
throw new ScriptError('NEGATIVE_LOCKTIME', op, ip);
2016-06-20 03:21:53 -07:00
locktime = locktime.toNumber();
2016-04-19 21:43:40 -07:00
if (!Script.checkLocktime(locktime, tx, index))
throw new ScriptError('UNSATISFIED_LOCKTIME', op, ip);
2016-04-19 01:30:12 -07:00
break;
2016-04-19 21:43:40 -07:00
}
case opcodes.OP_CHECKSEQUENCEVERIFY: {
// OP_CHECKSEQUENCEVERIFY = OP_NOP3
if (!(flags & constants.flags.VERIFY_CHECKSEQUENCEVERIFY)) {
if (flags & constants.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
throw new ScriptError('DISCOURAGE_UPGRADABLE_NOPS', op, ip);
break;
}
if (!tx)
2016-04-19 22:44:54 -07:00
throw new ScriptError('UNKNOWN_ERROR', 'No TX passed in.');
2016-04-19 21:43:40 -07:00
if (stack.length === 0)
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
locktime = Script.num(stack.top(-1), flags, 5);
if (locktime.cmpn(0) < 0)
throw new ScriptError('NEGATIVE_LOCKTIME', op, ip);
2016-06-20 03:21:53 -07:00
locktime = locktime.toNumber();
2016-04-19 21:43:40 -07:00
if ((locktime & constants.sequence.DISABLE_FLAG) !== 0)
break;
if (!Script.checkSequence(locktime, tx, index))
throw new ScriptError('UNSATISFIED_LOCKTIME', op, ip);
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_NOP1:
case opcodes.OP_NOP4:
case opcodes.OP_NOP5:
case opcodes.OP_NOP6:
case opcodes.OP_NOP7:
case opcodes.OP_NOP8:
case opcodes.OP_NOP9:
case opcodes.OP_NOP10: {
2016-03-14 20:43:32 -07:00
if (flags & constants.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
2016-04-19 21:43:40 -07:00
throw new ScriptError('DISCOURAGE_UPGRADABLE_NOPS', op, ip);
2016-03-14 20:43:32 -07:00
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_VERIFY: {
2016-03-14 20:43:32 -07:00
if (stack.length === 0)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-03-14 20:43:32 -07:00
if (!Script.bool(stack.pop()))
2016-04-19 21:43:40 -07:00
throw new ScriptError('VERIFY', op, ip);
2016-03-14 20:43:32 -07:00
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_RETURN: {
2016-04-19 21:43:40 -07:00
throw new ScriptError('OP_RETURN', op, ip);
2016-03-14 20:43:32 -07:00
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_TOALTSTACK: {
2016-06-12 14:27:29 -07:00
stack.toalt(alt);
2016-03-14 20:43:32 -07:00
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_FROMALTSTACK: {
2016-06-12 14:27:29 -07:00
stack.fromalt(alt);
2016-03-14 20:43:32 -07:00
break;
}
2016-04-19 21:43:40 -07:00
case opcodes.OP_2DROP: {
stack.drop2();
break;
}
case opcodes.OP_2DUP: {
stack.dup2();
break;
}
case opcodes.OP_3DUP: {
stack.dup3();
break;
}
case opcodes.OP_2OVER: {
stack.over2();
break;
}
case opcodes.OP_2ROT: {
stack.rot2();
break;
}
case opcodes.OP_2SWAP: {
stack.swap2();
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_IFDUP: {
2016-03-14 20:43:32 -07:00
stack.ifdup();
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_DEPTH: {
2016-03-14 20:43:32 -07:00
stack.depth();
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_DROP: {
2016-03-14 20:43:32 -07:00
stack.drop();
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_DUP: {
2016-03-14 20:43:32 -07:00
stack.dup();
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_NIP: {
2016-03-14 20:43:32 -07:00
stack.nip();
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_OVER: {
2016-03-14 20:43:32 -07:00
stack.over();
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_PICK: {
2016-03-15 04:23:23 -07:00
stack.pick(flags);
2016-03-14 20:43:32 -07:00
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_ROLL: {
2016-03-15 04:23:23 -07:00
stack.roll(flags);
2016-03-14 20:43:32 -07:00
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_ROT: {
2016-03-14 20:43:32 -07:00
stack.rot();
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_SWAP: {
2016-03-14 20:43:32 -07:00
stack.swap();
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_TUCK: {
2016-03-14 20:43:32 -07:00
stack.tuck();
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_SIZE: {
2016-03-14 20:43:32 -07:00
stack.size();
break;
}
2016-04-19 21:43:40 -07:00
case opcodes.OP_EQUAL:
case opcodes.OP_EQUALVERIFY: {
if (stack.length < 2)
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-04-30 16:20:40 -07:00
res = utils.equal(stack.pop(), stack.pop());
2016-04-19 21:43:40 -07:00
if (op === opcodes.OP_EQUALVERIFY) {
if (!res)
2016-04-19 22:44:54 -07:00
throw new ScriptError('EQUALVERIFY', op, ip);
2016-04-19 21:43:40 -07:00
} else {
stack.push(res ? STACK_TRUE : STACK_FALSE);
}
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_1ADD:
case opcodes.OP_1SUB:
2016-04-17 06:39:31 -07:00
case opcodes.OP_2MUL:
case opcodes.OP_2DIV:
2016-03-28 19:42:05 -07:00
case opcodes.OP_NEGATE:
case opcodes.OP_ABS:
case opcodes.OP_NOT:
case opcodes.OP_0NOTEQUAL: {
2016-03-14 20:43:32 -07:00
if (stack.length < 1)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-03-14 20:43:32 -07:00
n = Script.num(stack.pop(), flags);
switch (op) {
2016-03-28 19:42:05 -07:00
case opcodes.OP_1ADD:
2016-04-18 17:02:33 -07:00
n.iaddn(1);
2016-03-14 20:43:32 -07:00
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_1SUB:
2016-04-18 17:02:33 -07:00
n.isubn(1);
2016-03-14 20:43:32 -07:00
break;
2016-04-17 06:39:31 -07:00
case opcodes.OP_2MUL:
n.iushln(1);
break;
case opcodes.OP_2DIV:
n.iushrn(1);
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_NEGATE:
2016-04-17 06:39:31 -07:00
n.ineg();
2016-03-14 20:43:32 -07:00
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_ABS:
2016-03-14 20:43:32 -07:00
if (n.cmpn(0) < 0)
2016-03-29 13:15:43 -07:00
n.ineg();
2016-03-14 20:43:32 -07:00
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_NOT:
2016-03-14 20:43:32 -07:00
n = n.cmpn(0) === 0;
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_0NOTEQUAL:
2016-03-14 20:43:32 -07:00
n = n.cmpn(0) !== 0;
break;
default:
2016-06-16 02:27:35 -07:00
assert(false, 'Fatal script error.');
2016-03-14 20:43:32 -07:00
}
if (typeof n === 'boolean')
2016-04-04 02:53:55 -07:00
n = new bn(n ? 1 : 0);
2016-03-14 20:43:32 -07:00
stack.push(Script.array(n));
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_ADD:
case opcodes.OP_SUB:
2016-04-17 06:39:31 -07:00
case opcodes.OP_MUL:
case opcodes.OP_DIV:
case opcodes.OP_MOD:
case opcodes.OP_LSHIFT:
case opcodes.OP_RSHIFT:
2016-03-28 19:42:05 -07:00
case opcodes.OP_BOOLAND:
case opcodes.OP_BOOLOR:
case opcodes.OP_NUMEQUAL:
case opcodes.OP_NUMEQUALVERIFY:
case opcodes.OP_NUMNOTEQUAL:
case opcodes.OP_LESSTHAN:
case opcodes.OP_GREATERTHAN:
case opcodes.OP_LESSTHANOREQUAL:
case opcodes.OP_GREATERTHANOREQUAL:
case opcodes.OP_MIN:
2016-04-19 21:43:40 -07:00
case opcodes.OP_MAX: {
2016-03-14 20:43:32 -07:00
switch (op) {
2016-03-28 19:42:05 -07:00
case opcodes.OP_ADD:
case opcodes.OP_SUB:
2016-04-17 06:39:31 -07:00
case opcodes.OP_MUL:
case opcodes.OP_DIV:
case opcodes.OP_MOD:
case opcodes.OP_LSHIFT:
case opcodes.OP_RSHIFT:
2016-03-28 19:42:05 -07:00
case opcodes.OP_BOOLAND:
case opcodes.OP_BOOLOR:
case opcodes.OP_NUMEQUAL:
case opcodes.OP_NUMEQUALVERIFY:
case opcodes.OP_NUMNOTEQUAL:
case opcodes.OP_LESSTHAN:
case opcodes.OP_GREATERTHAN:
case opcodes.OP_LESSTHANOREQUAL:
case opcodes.OP_GREATERTHANOREQUAL:
case opcodes.OP_MIN:
case opcodes.OP_MAX:
2016-03-14 20:43:32 -07:00
if (stack.length < 2)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-03-14 20:43:32 -07:00
n2 = Script.num(stack.pop(), flags);
n1 = Script.num(stack.pop(), flags);
2016-04-04 02:53:55 -07:00
n = new bn(0);
2016-03-14 20:43:32 -07:00
switch (op) {
2016-03-28 19:42:05 -07:00
case opcodes.OP_ADD:
2016-03-14 20:43:32 -07:00
n = n1.add(n2);
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_SUB:
2016-03-14 20:43:32 -07:00
n = n1.sub(n2);
break;
2016-04-17 06:39:31 -07:00
case opcodes.OP_MUL:
n = n1.mul(n2);
break;
case opcodes.OP_DIV:
n = n1.div(n2);
break;
case opcodes.OP_MOD:
n = n1.mod(n2);
break;
case opcodes.OP_LSHIFT:
if (n2.cmpn(0) < 0 || n2.cmpn(2048) > 0)
2016-04-19 22:44:54 -07:00
throw new ScriptError('UNKNOWN_ERROR', 'Bad shift.');
2016-04-17 06:39:31 -07:00
n = n1.ushln(n2.toNumber());
break;
case opcodes.OP_RSHIFT:
if (n2.cmpn(0) < 0 || n2.cmpn(2048) > 0)
2016-04-19 22:44:54 -07:00
throw new ScriptError('UNKNOWN_ERROR', 'Bad shift.');
2016-04-17 06:39:31 -07:00
n = n1.ushrn(n2.toNumber());
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_BOOLAND:
2016-03-14 20:43:32 -07:00
n = n1.cmpn(0) !== 0 && n2.cmpn(0) !== 0;
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_BOOLOR:
2016-03-14 20:43:32 -07:00
n = n1.cmpn(0) !== 0 || n2.cmpn(0) !== 0;
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_NUMEQUAL:
2016-03-14 20:43:32 -07:00
n = n1.cmp(n2) === 0;
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_NUMEQUALVERIFY:
2016-03-14 20:43:32 -07:00
n = n1.cmp(n2) === 0;
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_NUMNOTEQUAL:
2016-03-14 20:43:32 -07:00
n = n1.cmp(n2) !== 0;
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_LESSTHAN:
2016-03-14 20:43:32 -07:00
n = n1.cmp(n2) < 0;
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_GREATERTHAN:
2016-03-14 20:43:32 -07:00
n = n1.cmp(n2) > 0;
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_LESSTHANOREQUAL:
2016-03-14 20:43:32 -07:00
n = n1.cmp(n2) <= 0;
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_GREATERTHANOREQUAL:
2016-03-14 20:43:32 -07:00
n = n1.cmp(n2) >= 0;
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_MIN:
2016-03-14 20:43:32 -07:00
n = n1.cmp(n2) < 0 ? n1 : n2;
break;
2016-03-28 19:42:05 -07:00
case opcodes.OP_MAX:
2016-03-14 20:43:32 -07:00
n = n1.cmp(n2) > 0 ? n1 : n2;
break;
default:
2016-06-16 02:27:35 -07:00
assert(false, 'Fatal script error.');
2016-03-14 20:43:32 -07:00
}
if (typeof n === 'boolean')
2016-04-04 02:53:55 -07:00
n = new bn(n ? 1 : 0);
2016-03-28 19:42:05 -07:00
if (op === opcodes.OP_NUMEQUALVERIFY) {
2016-04-18 17:02:33 -07:00
if (!Script.bool(n))
2016-04-19 21:43:40 -07:00
throw new ScriptError('NUMEQUALVERIFY', op, ip);
2016-03-14 20:43:32 -07:00
} else {
stack.push(Script.array(n));
}
break;
}
break;
}
2016-04-19 21:43:40 -07:00
case opcodes.OP_WITHIN: {
if (stack.length < 3)
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
n3 = Script.num(stack.pop(), flags);
n2 = Script.num(stack.pop(), flags);
n1 = Script.num(stack.pop(), flags);
val = n2.cmp(n1) <= 0 && n1.cmp(n3) < 0;
stack.push(val ? STACK_TRUE : STACK_FALSE);
2016-03-14 20:43:32 -07:00
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_RIPEMD160: {
2016-03-14 20:43:32 -07:00
if (stack.length === 0)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-03-14 20:43:32 -07:00
stack.push(utils.ripemd160(stack.pop()));
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_SHA1: {
2016-03-14 20:43:32 -07:00
if (stack.length === 0)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-03-14 20:43:32 -07:00
stack.push(utils.sha1(stack.pop()));
break;
}
2016-03-28 19:42:05 -07:00
case opcodes.OP_SHA256: {
2016-03-14 20:43:32 -07:00
if (stack.length === 0)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-03-14 20:43:32 -07:00
stack.push(utils.sha256(stack.pop()));
break;
}
2016-06-16 02:38:27 -07:00
case opcodes.OP_HASH160: {
2016-03-14 20:43:32 -07:00
if (stack.length === 0)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-06-18 20:59:34 -07:00
stack.push(utils.hash160(stack.pop()));
2016-03-14 20:43:32 -07:00
break;
}
2016-06-16 02:38:27 -07:00
case opcodes.OP_HASH256: {
2016-03-14 20:43:32 -07:00
if (stack.length === 0)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-06-18 20:59:34 -07:00
stack.push(utils.hash256(stack.pop()));
2016-03-14 20:43:32 -07:00
break;
}
2016-04-19 21:43:40 -07:00
case opcodes.OP_CODESEPARATOR: {
lastSep = ip;
2016-03-14 20:43:32 -07:00
break;
}
2016-06-16 02:38:27 -07:00
case opcodes.OP_CHECKSIG:
case opcodes.OP_CHECKSIGVERIFY: {
2016-03-27 18:54:13 -07:00
if (!tx)
2016-04-19 22:44:54 -07:00
throw new ScriptError('UNKNOWN_ERROR', 'No TX passed in.');
2016-03-27 18:54:13 -07:00
if (stack.length < 2)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-03-14 20:43:32 -07:00
key = stack.pop();
sig = stack.pop();
2016-04-18 19:19:06 -07:00
subscript = this.getSubscript(lastSep);
if (version === 0)
subscript.removeData(sig);
2016-04-18 19:19:06 -07:00
2016-04-19 22:44:54 -07:00
Script.validateSignature(sig, flags);
Script.validateKey(key, flags);
2016-03-14 20:43:32 -07:00
type = sig[sig.length - 1];
hash = tx.signatureHash(index, subscript, type, version);
res = Script.checksig(hash, sig, key, flags);
2016-03-28 19:42:05 -07:00
if (op === opcodes.OP_CHECKSIGVERIFY) {
2016-03-14 20:43:32 -07:00
if (!res)
2016-04-19 21:43:40 -07:00
throw new ScriptError('CHECKSIGVERIFY', op, ip);
2016-03-14 20:43:32 -07:00
} else {
2016-03-29 13:15:43 -07:00
stack.push(res ? STACK_TRUE : STACK_FALSE);
2016-03-14 20:43:32 -07:00
}
break;
}
2016-06-16 02:38:27 -07:00
case opcodes.OP_CHECKMULTISIG:
case opcodes.OP_CHECKMULTISIGVERIFY: {
2016-03-27 18:54:13 -07:00
if (!tx)
2016-04-19 22:44:54 -07:00
throw new ScriptError('UNKNOWN_ERROR', 'No TX passed in.');
2016-03-27 18:54:13 -07:00
2016-04-18 19:19:06 -07:00
i = 1;
if (stack.length < i)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-03-14 20:43:32 -07:00
2016-04-18 19:19:06 -07:00
n = Script.num(stack.top(-i), flags).toNumber();
2016-03-14 20:43:32 -07:00
2016-04-18 19:19:06 -07:00
if (!(n >= 0 && n <= constants.script.MAX_MULTISIG_PUBKEYS))
2016-04-19 21:43:40 -07:00
throw new ScriptError('PUBKEY_COUNT', op, ip);
2016-03-14 20:43:32 -07:00
2016-04-18 19:19:06 -07:00
opCount += n;
2016-03-14 20:43:32 -07:00
2016-04-18 19:19:06 -07:00
if (opCount > constants.script.MAX_OPS)
2016-04-19 21:43:40 -07:00
throw new ScriptError('OP_COUNT', op, ip);
2016-03-14 20:43:32 -07:00
2016-04-18 19:19:06 -07:00
i++;
ikey = i;
i += n;
2016-03-14 20:43:32 -07:00
2016-04-18 19:19:06 -07:00
if (stack.length < i)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-03-14 20:43:32 -07:00
2016-04-18 19:19:06 -07:00
m = Script.num(stack.top(-i), flags).toNumber();
2016-03-14 20:43:32 -07:00
2016-04-18 19:19:06 -07:00
if (!(m >= 0 && m <= n))
2016-04-19 21:43:40 -07:00
throw new ScriptError('SIG_COUNT', op, ip);
2016-03-14 20:43:32 -07:00
2016-04-18 19:19:06 -07:00
i++;
isig = i;
i += m;
if (stack.length < i)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-03-14 20:43:32 -07:00
subscript = this.getSubscript(lastSep);
2016-04-18 19:19:06 -07:00
for (j = 0; j < m; j++) {
sig = stack.top(-isig - j);
2016-04-17 19:34:03 -07:00
if (version === 0)
subscript.removeData(sig);
2016-03-14 20:43:32 -07:00
}
2016-04-18 19:19:06 -07:00
res = true;
while (res && m > 0) {
sig = stack.top(-isig);
key = stack.top(-ikey);
2016-03-14 20:43:32 -07:00
2016-04-19 22:44:54 -07:00
Script.validateSignature(sig, flags);
Script.validateKey(key, flags);
2016-03-14 20:43:32 -07:00
2016-04-18 19:19:06 -07:00
type = sig[sig.length - 1];
2016-03-14 20:43:32 -07:00
hash = tx.signatureHash(index, subscript, type, version);
2016-04-18 19:19:06 -07:00
if (Script.checksig(hash, sig, key, flags)) {
isig++;
m--;
}
ikey++;
n--;
2016-03-14 20:43:32 -07:00
2016-04-18 19:19:06 -07:00
if (m > n)
res = false;
2016-03-14 20:43:32 -07:00
}
2016-04-18 19:19:06 -07:00
while (i-- > 1)
stack.pop();
2016-03-14 20:43:32 -07:00
if (stack.length < 1)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-03-14 20:43:32 -07:00
if (flags & constants.flags.VERIFY_NULLDUMMY) {
2016-04-18 19:19:06 -07:00
if (!Script.isDummy(stack.top(-1)))
2016-04-19 22:44:54 -07:00
throw new ScriptError('SIG_NULLDUMMY', op, ip);
2016-03-14 20:43:32 -07:00
}
2016-04-18 19:19:06 -07:00
stack.pop();
2016-03-14 20:43:32 -07:00
2016-03-28 19:42:05 -07:00
if (op === opcodes.OP_CHECKMULTISIGVERIFY) {
2016-03-14 20:43:32 -07:00
if (!res)
2016-04-19 21:43:40 -07:00
throw new ScriptError('CHECKMULTISIGVERIFY', op, ip);
2016-03-14 20:43:32 -07:00
} else {
2016-03-29 13:15:43 -07:00
stack.push(res ? STACK_TRUE : STACK_FALSE);
2016-03-14 20:43:32 -07:00
}
break;
}
2016-04-17 06:39:31 -07:00
case opcodes.OP_CAT: {
if (stack.length < 2)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-04-17 06:39:31 -07:00
v2 = stack.pop();
v1 = stack.pop();
stack.push(Buffer.concat([v1, v2]));
2016-04-17 08:45:22 -07:00
if (stack.top(-1).length > constants.script.MAX_PUSH)
2016-04-19 21:43:40 -07:00
throw new ScriptError('PUSH_SIZE', op, ip);
2016-04-17 06:39:31 -07:00
break;
}
case opcodes.OP_SUBSTR: {
if (stack.length < 3)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-04-17 08:45:37 -07:00
v3 = Script.num(stack.pop(), flags).toNumber(); // end
2016-04-17 06:39:31 -07:00
v2 = Script.num(stack.pop(), flags).toNumber(); // begin
2016-04-17 08:45:37 -07:00
v1 = stack.pop(); // string
if (v2 < 0 || v3 < v2)
2016-04-19 22:44:54 -07:00
throw new ScriptError('UNKNOWN_ERROR', 'String out of range.');
2016-04-17 08:45:37 -07:00
if (v2 > v1.length)
v2 = v1.length;
if (v3 > v1.length)
v3 = v1.length;
stack.push(v1.slice(v2, v3));
2016-04-17 06:39:31 -07:00
break;
}
case opcodes.OP_LEFT:
case opcodes.OP_RIGHT: {
if (stack.length < 2)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-04-17 08:45:37 -07:00
v2 = Script.num(stack.pop(), flags).toNumber(); // size
v1 = stack.pop(); // string
if (v2 < 0)
2016-04-19 22:44:54 -07:00
throw new ScriptError('UNKNOWN_ERROR', 'String size out of range.');
2016-04-17 08:45:37 -07:00
if (v2 > v1.length)
v2 = v1.length;
2016-04-17 06:39:31 -07:00
if (op === opcodes.OP_LEFT)
2016-04-17 08:45:37 -07:00
v1 = v1.slice(0, v2);
2016-04-17 06:39:31 -07:00
else
2016-04-17 08:45:37 -07:00
v1 = v1.slice(v1.length - v2);
stack.push(v1);
2016-04-17 06:39:31 -07:00
break;
}
case opcodes.OP_INVERT: {
if (stack.length < 1)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-05-19 16:47:41 -07:00
val = utils.copy(stack.pop());
2016-04-17 06:39:31 -07:00
for (i = 0; i < val.length; i++)
2016-04-17 08:45:37 -07:00
val[i] = ~val[i] & 0xff;
2016-04-17 06:39:31 -07:00
stack.push(val);
break;
}
case opcodes.OP_AND:
case opcodes.OP_OR:
case opcodes.OP_XOR: {
if (stack.length < 2)
2016-04-19 21:43:40 -07:00
throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
2016-04-17 06:39:31 -07:00
v2 = stack.pop();
2016-05-19 16:47:41 -07:00
v1 = utils.copy(stack.pop());
2016-04-17 06:39:31 -07:00
if (v1.length < v2.length) {
v3 = new Buffer(v2.length - v1.length);
v3.fill(0);
v1 = Buffer.concat([v1, v3]);
}
if (v2.length < v1.length) {
v3 = new Buffer(v1.length - v2.length);
v3.fill(0);
v2 = Buffer.concat([v2, v3]);
}
if (op === opcodes.OP_AND) {
for (i = 0; i < v1.length; i++)
v1[i] &= v2[i];
} else if (op === opcodes.OP_OR) {
for (i = 0; i < v1.length; i++)
v1[i] |= v2[i];
} else if (op === opcodes.OP_XOR) {
for (i = 0; i < v1.length; i++)
v1[i] ^= v2[i];
}
stack.push(v1);
break;
}
2016-03-14 20:43:32 -07:00
default: {
2016-04-19 21:43:40 -07:00
throw new ScriptError('BAD_OPCODE', op, ip);
2016-03-14 20:43:32 -07:00
}
}
}
2016-06-12 14:27:29 -07:00
if (stack.getSize(alt) > constants.script.MAX_STACK)
2016-04-19 21:43:40 -07:00
throw new ScriptError('STACK_SIZE', op, ip);
2016-03-14 20:43:32 -07:00
2016-06-12 14:27:29 -07:00
if (state.length !== 0)
2016-04-19 21:43:40 -07:00
throw new ScriptError('UNBALANCED_CONDITIONAL', op, ip);
2016-04-17 06:39:31 -07:00
2016-03-14 20:43:32 -07:00
return true;
};
/**
* Verify the nLockTime of a transaction.
* @param {Number} locktime - Locktime to verify against (max=u32).
* @param {TX} tx - Transaction to verify.
* @param {Number} index - Index of input being verified (for IsFinal).
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.checkLocktime = function checkLocktime(locktime, tx, i) {
2016-04-17 08:45:22 -07:00
var threshold = constants.LOCKTIME_THRESHOLD;
2016-03-14 20:43:32 -07:00
if (!(
(tx.locktime < threshold && locktime < threshold)
|| (tx.locktime >= threshold && locktime >= threshold)
)) {
return false;
}
if (locktime > tx.locktime)
return false;
2016-03-15 04:23:23 -07:00
if (tx.inputs[i].sequence === 0xffffffff)
2016-03-14 20:43:32 -07:00
return false;
return true;
};
/**
* Verify the nSequence locktime of a transaction.
* @param {Number} sequence - Locktime to verify against (max=u32).
* @param {TX} tx - Transaction to verify.
* @param {Number} index - Index of input being verified.
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.checkSequence = function checkSequence(sequence, tx, i) {
var txSequence = tx.inputs[i].sequence;
var locktimeMask, txSequenceMasked, sequenceMasked;
2016-03-31 02:08:08 -07:00
if (tx.version < 2)
2016-03-14 20:43:32 -07:00
return false;
2016-04-17 08:45:22 -07:00
if (txSequence & constants.sequence.DISABLE_FLAG)
2016-03-14 20:43:32 -07:00
return false;
2016-04-17 08:45:22 -07:00
locktimeMask = constants.sequence.TYPE_FLAG
| constants.sequence.MASK;
2016-03-14 20:43:32 -07:00
txSequenceMasked = txSequence & locktimeMask;
sequenceMasked = sequence & locktimeMask;
if (!(
2016-04-17 08:45:22 -07:00
(txSequenceMasked < constants.sequence.TYPE_FLAG
&& sequenceMasked < constants.sequence.TYPE_FLAG)
|| (txSequenceMasked >= constants.sequence.TYPE_FLAG
&& sequenceMasked >= constants.sequence.TYPE_FLAG)
2016-03-14 20:43:32 -07:00
)) {
return false;
}
if (sequenceMasked > txSequenceMasked)
return false;
return true;
};
/**
* Cast a big number or Buffer to a bool.
* @see CastToBool
* @param {BN|Buffer} value
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.bool = function bool(value) {
var i;
2016-03-24 13:28:24 -07:00
if (bn.isBN(value))
2016-03-14 20:43:32 -07:00
return value.cmpn(0) !== 0;
assert(Buffer.isBuffer(value));
for (i = 0; i < value.length; i++) {
if (value[i] !== 0) {
// Cannot be negative zero
if (i === value.length - 1 && value[i] === 0x80)
return false;
return true;
}
}
return false;
};
/**
* Create a CScriptNum.
* @param {Buffer} value
* @param {Number?} flags - Script standard flags.
* @param {Number?} size - Max size in bytes.
2016-04-15 08:01:03 -07:00
* @returns {BN}
* @throws {ScriptError}
*/
2016-03-14 20:43:32 -07:00
Script.num = function num(value, flags, size) {
2016-05-25 01:06:41 -07:00
var result;
2016-04-18 17:02:33 -07:00
2016-03-14 20:43:32 -07:00
assert(Buffer.isBuffer(value));
if (flags == null)
flags = constants.flags.STANDARD_VERIFY_FLAGS;
if (size == null)
size = 4;
if (value.length > size)
2016-04-19 22:44:54 -07:00
throw new ScriptError('UNKNOWN_ERROR', 'Script number overflow.');
2016-03-14 20:43:32 -07:00
if ((flags & constants.flags.VERIFY_MINIMALDATA) && value.length > 0) {
// If the low bits on the last byte are unset,
// fail if the value's second to last byte does
// not have the high bit set. A number can't
// justify having the last byte's low bits unset
// unless they ran out of space for the sign bit
// in the second to last bit. We also fail on [0]
// to avoid negative zero (also avoids positive
// zero).
if (!(value[value.length - 1] & 0x7f)) {
2016-04-19 22:44:54 -07:00
if (value.length === 1 || !(value[value.length - 2] & 0x80)) {
throw new ScriptError(
'UNKNOWN_ERROR',
'Non-minimally encoded Script number.');
}
2016-03-14 20:43:32 -07:00
}
}
2016-04-18 17:02:33 -07:00
if (value.length === 0)
return new bn(0);
result = new bn(value, 'le');
// If the input vector's most significant byte is
// 0x80, remove it from the result's msb and return
// a negative.
2016-05-15 22:33:20 -07:00
// Equivalent to:
// -(result & ~(0x80 << (8 * (value.length - 1))))
if (value[value.length - 1] & 0x80)
2016-05-15 22:18:33 -07:00
result.setn((value.length * 8) - 1, 0).ineg();
2016-03-14 20:43:32 -07:00
2016-04-18 17:02:33 -07:00
return result;
2016-03-14 20:43:32 -07:00
};
/**
* Create a script array. Will convert Numbers and big
* numbers to a little-endian buffer while taking into
* account negative zero, minimaldata, etc.
* @example
* assert.deepEqual(Script.array(0), new Buffer([]));
2016-05-19 11:56:11 -07:00
* assert.deepEqual(Script.array(0xffee), new Buffer([0xee, 0xff, 0x00]));
* assert.deepEqual(Script.array(new bn(0xffee)), new Buffer([0xee, 0xff, 0x00]));
* assert.deepEqual(Script.array(new bn(0x1e).ineg()), new Buffer([0x9e]));
* @param {Buffer|Number|BN} value
* @returns {Buffer}
*/
2016-03-14 20:43:32 -07:00
Script.array = function(value) {
2016-04-18 17:02:33 -07:00
var neg, result;
2016-03-14 20:43:32 -07:00
if (Buffer.isBuffer(value))
return value;
2016-04-30 16:20:40 -07:00
if (utils.isNumber(value))
2016-04-03 05:47:06 -07:00
value = new bn(value);
2016-03-14 20:43:32 -07:00
2016-03-24 13:28:24 -07:00
assert(bn.isBN(value));
2016-03-14 20:43:32 -07:00
if (value.cmpn(0) === 0)
2016-03-29 13:15:43 -07:00
return STACK_FALSE;
2016-03-14 20:43:32 -07:00
2016-04-18 17:02:33 -07:00
// If the most significant byte is >= 0x80
// and the value is positive, push a new
// zero-byte to make the significant
// byte < 0x80 again.
// If the most significant byte is >= 0x80
// and the value is negative, push a new
// 0x80 byte that will be popped off when
// converting to an integral.
// If the most significant byte is < 0x80
// and the value is negative, add 0x80 to
// it, since it will be subtracted and
// interpreted as a negative when
// converting to an integral.
neg = value.cmpn(0) < 0;
result = value.toArray('le');
2016-05-15 22:18:33 -07:00
2016-04-18 17:02:33 -07:00
if (result[result.length - 1] & 0x80)
result.push(neg ? 0x80 : 0);
else if (neg)
result[result.length - 1] |= 0x80;
return new Buffer(result);
2016-03-14 20:43:32 -07:00
};
/**
* Remove all matched data elements from
* a script's code (used to remove signatures
2016-04-18 21:37:27 -07:00
* before verification). Note that this
* compares and removes data on the _byte level_.
* It also reserializes the data to a single
* script with minimaldata encoding beforehand.
* A signature will _not_ be removed if it is
* not minimaldata.
* @see https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2014-November/006878.html
* @see https://test.webbtc.com/tx/19aa42fee0fa57c45d3b16488198b27caaacc4ff5794510d0c17f173f05587ff
* @param {Buffer} data - Data element to match against.
2016-04-17 19:34:03 -07:00
* @returns {Number} Total.
*/
Script.prototype.removeData = function removeData(data) {
2016-05-04 01:06:34 -07:00
var index = [];
var i, op;
// We need to go forward first. We can't go
// backwards (this is consensus code and we
// need to be aware of bad pushes).
for (i = 0; i < this.code.length; i++) {
op = this.code[i];
2016-06-13 21:25:42 -07:00
if (op.value === -1)
2016-05-04 01:06:34 -07:00
break;
2016-06-13 21:25:42 -07:00
if (!op.data)
2016-05-04 01:06:34 -07:00
continue;
2016-06-14 19:06:17 -07:00
if (!Script.isMinimal(op.data, op.value))
2016-05-04 01:06:34 -07:00
continue;
2016-06-13 21:25:42 -07:00
if (utils.equal(op.data, data))
2016-05-04 01:06:34 -07:00
index.push(i);
}
if (index.length === 0)
return 0;
// Go backwards and splice out the data.
for (i = index.length - 1; i >= 0; i--)
this.code.splice(index[i], 1);
2016-06-13 21:25:42 -07:00
this.raw = Script.encode(this.code);
2016-05-04 01:06:34 -07:00
return index.length;
};
2016-05-15 23:51:18 -07:00
/**
2016-06-13 21:25:42 -07:00
* Find a data element in a script.
* @param {Buffer} data - Data element to match against.
* @returns {Number} Index (`-1` if not present).
2016-05-15 23:51:18 -07:00
*/
2016-06-13 21:25:42 -07:00
Script.prototype.indexOf = function indexOf(data) {
var i, op;
2016-05-15 23:51:18 -07:00
2016-06-13 21:25:42 -07:00
for (i = 0; i < this.code.length; i++) {
op = this.code[i];
2016-05-15 23:51:18 -07:00
2016-06-13 21:25:42 -07:00
if (op.value === -1)
2016-05-15 23:51:18 -07:00
break;
2016-06-13 21:25:42 -07:00
if (!op.data)
continue;
2016-05-15 23:51:18 -07:00
2016-06-13 21:25:42 -07:00
if (utils.equal(op.data, data))
return i;
2016-05-15 23:51:18 -07:00
}
2016-06-13 21:25:42 -07:00
return -1;
2016-04-17 19:34:03 -07:00
};
/**
* Check to see if a pushdata Buffer abides by minimaldata.
2016-06-16 02:03:17 -07:00
* @param {Buffer} data
* @param {Number} opcode
* @param {Number?} flags
* @returns {Boolean}
*/
2016-06-14 19:06:17 -07:00
Script.isMinimal = function isMinimal(data, opcode, flags) {
2016-03-14 20:43:32 -07:00
if (flags == null)
flags = constants.flags.STANDARD_VERIFY_FLAGS;
if (!(flags & constants.flags.VERIFY_MINIMALDATA))
return true;
2016-06-13 21:25:42 -07:00
if (!data)
2016-03-14 20:43:32 -07:00
return true;
2016-06-13 21:25:42 -07:00
if (data.length === 0)
return opcode === opcodes.OP_0;
2016-04-21 10:24:09 -07:00
2016-06-13 21:25:42 -07:00
if (data.length === 1 && data[0] >= 1 && data[0] <= 16)
2016-03-14 20:43:32 -07:00
return false;
2016-06-13 21:25:42 -07:00
if (data.length === 1 && data[0] === 0x81)
2016-03-14 20:43:32 -07:00
return false;
2016-06-13 21:25:42 -07:00
if (data.length <= 75)
return opcode === data.length;
2016-03-14 20:43:32 -07:00
2016-06-13 21:25:42 -07:00
if (data.length <= 255)
return opcode === opcodes.OP_PUSHDATA1;
2016-03-14 20:43:32 -07:00
2016-06-13 21:25:42 -07:00
if (data.length <= 65535)
return opcode === opcodes.OP_PUSHDATA2;
2016-03-14 20:43:32 -07:00
return true;
};
/**
2016-06-20 01:09:27 -07:00
* Test a buffer to see if it is valid
* script code (no non-existent opcodes).
2016-04-20 13:14:38 -07:00
* @param {Buffer} raw
* @returns {Boolean}
*/
2016-04-20 13:14:38 -07:00
Script.isCode = function isCode(raw) {
2016-03-29 20:46:09 -07:00
var i, op, code;
2016-03-14 20:43:32 -07:00
2016-04-20 13:14:38 -07:00
if (!raw)
2016-03-14 20:43:32 -07:00
return false;
2016-04-20 13:14:38 -07:00
if (!Buffer.isBuffer(raw))
2016-03-14 20:43:32 -07:00
return false;
2016-04-20 13:14:38 -07:00
code = Script.decode(raw);
2016-03-14 20:43:32 -07:00
2016-03-29 20:46:09 -07:00
for (i = 0; i < code.length; i++) {
op = code[i];
2016-06-14 16:26:26 -07:00
2016-06-13 21:25:42 -07:00
if (op.data)
2016-03-14 20:43:32 -07:00
continue;
2016-06-14 16:26:26 -07:00
2016-06-13 21:25:42 -07:00
if (op.value === -1)
2016-04-20 09:01:10 -07:00
return false;
2016-06-14 16:26:26 -07:00
2016-07-16 12:17:08 -07:00
if (op.value > opcodes.OP_NOP10)
2016-03-14 20:43:32 -07:00
return false;
}
return true;
};
2016-07-01 05:42:04 -07:00
/**
* Inject properties from a pay-to-pubkey script.
* @private
* @param {Buffer} key
*/
Script.prototype.fromPubkey = function fromPubkey(key) {
assert(Buffer.isBuffer(key) && key.length >= 33);
2016-07-01 14:46:16 -07:00
this.push(key);
this.push(opcodes.OP_CHECKSIG);
this.compile();
return this;
2016-07-01 05:42:04 -07:00
};
/**
* Create a pay-to-pubkey script.
* @param {Buffer} key
* @returns {Script}
*/
2016-06-18 20:59:34 -07:00
Script.fromPubkey = function fromPubkey(key) {
2016-07-01 05:42:04 -07:00
return new Script().fromPubkey(key);
2016-03-14 20:43:32 -07:00
};
/**
2016-07-01 05:42:04 -07:00
* Inject properties from a pay-to-pubkeyhash script.
* @private
* @param {Buffer} hash
*/
2016-07-01 05:42:04 -07:00
Script.prototype.fromPubkeyhash = function fromPubkeyhash(hash) {
2016-06-20 16:49:09 -07:00
assert(Buffer.isBuffer(hash) && hash.length === 20);
2016-07-01 14:46:16 -07:00
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;
2016-03-14 20:43:32 -07:00
};
/**
2016-07-01 05:42:04 -07:00
* Create a pay-to-pubkeyhash script.
* @param {Buffer} hash
* @returns {Script}
*/
Script.fromPubkeyhash = function fromPubkeyhash(hash) {
return new Script().fromPubkeyhash(hash);
};
/**
* Inject properties from pay-to-multisig script.
* @private
* @param {Number} m
* @param {Number} n
2016-06-20 01:09:27 -07:00
* @param {Buffer[]} keys
*/
2016-07-01 05:42:04 -07:00
Script.prototype.fromMultisig = function fromMultisig(m, n, keys) {
2016-03-29 20:46:09 -07:00
var i;
2016-03-14 20:43:32 -07:00
2016-06-20 16:49:09 -07:00
assert(utils.isNumber(m) && utils.isNumber(n));
assert(Array.isArray(keys));
2016-03-29 20:46:09 -07:00
assert(keys.length === n, '`n` keys are required for multisig.');
2016-03-14 20:43:32 -07:00
assert(m >= 1 && m <= n);
assert(n >= 1 && n <= 15);
2016-03-29 20:46:09 -07:00
keys = utils.sortKeys(keys);
2016-07-01 18:28:22 -07:00
this.push(Opcode.fromSmall(m));
2016-03-29 20:46:09 -07:00
for (i = 0; i < keys.length; i++)
2016-07-01 14:46:16 -07:00
this.push(keys[i]);
2016-03-29 20:46:09 -07:00
2016-07-01 18:28:22 -07:00
this.push(Opcode.fromSmall(n));
2016-07-01 14:46:16 -07:00
this.push(opcodes.OP_CHECKMULTISIG);
2016-07-01 14:48:23 -07:00
2016-07-01 14:46:16 -07:00
this.compile();
2016-03-29 20:46:09 -07:00
2016-07-01 14:46:16 -07:00
return this;
2016-03-14 20:43:32 -07:00
};
/**
2016-07-01 05:42:04 -07:00
* Create a pay-to-multisig script.
* @param {Number} m
* @param {Number} n
* @param {Buffer[]} keys
* @returns {Script}
*/
2016-07-01 05:42:04 -07:00
Script.fromMultisig = function fromMultisig(m, n, keys) {
return new Script().fromMultisig(m, n, keys);
};
/**
* Inject properties from a pay-to-scripthash script.
* @private
* @param {Buffer} hash
*/
Script.prototype.fromScripthash = function fromScripthash(hash) {
2016-06-20 16:49:09 -07:00
assert(Buffer.isBuffer(hash) && hash.length === 20);
2016-07-01 14:46:16 -07:00
this.push(opcodes.OP_HASH160);
this.push(hash);
this.push(opcodes.OP_EQUAL);
this.compile();
return this;
2016-03-14 20:43:32 -07:00
};
/**
2016-07-01 05:42:04 -07:00
* Create a pay-to-scripthash script.
* @param {Buffer} hash
* @returns {Script}
*/
2016-07-01 05:42:04 -07:00
Script.fromScripthash = function fromScripthash(hash) {
return new Script().fromScripthash(hash);
};
/**
* Inject properties from a nulldata/opreturn script.
* @private
* @param {Buffer} flags
*/
Script.prototype.fromNulldata = function fromNulldata(flags) {
assert(Buffer.isBuffer(flags));
2016-04-17 08:45:22 -07:00
assert(flags.length <= constants.script.MAX_OP_RETURN, 'Nulldata too large.');
2016-07-01 14:46:16 -07:00
this.push(opcodes.OP_RETURN);
this.push(flags);
this.compile();
return this;
2016-03-14 20:43:32 -07:00
};
2016-07-01 05:42:04 -07:00
/**
* Create a nulldata/opreturn script.
* @param {Buffer} flags
* @returns {Script}
*/
Script.fromNulldata = function fromNulldata(flags) {
return new Script().fromNulldata(flags);
};
/**
* Inject properties from a witness program.
* @private
* @param {Number} version
* @param {Buffer} data
*/
Script.prototype.fromProgram = function fromProgram(version, data) {
assert(utils.isNumber(version) && version >= 0 && version <= 16);
assert(Buffer.isBuffer(data) && data.length >= 2 && data.length <= 40);
2016-07-01 18:28:22 -07:00
this.push(Opcode.fromSmall(version));
2016-07-01 14:46:16 -07:00
this.push(data);
this.compile();
return this;
2016-07-01 05:42:04 -07:00
};
/**
* Create a witness program.
* @param {Number} version
* @param {Buffer} data
* @returns {Script}
*/
2016-06-18 20:59:34 -07:00
Script.fromProgram = function fromProgram(version, data) {
2016-07-01 05:42:04 -07:00
return new Script().fromProgram(version, data);
2016-03-29 20:46:09 -07:00
};
2016-06-18 20:59:34 -07:00
/**
2016-07-01 05:42:04 -07:00
* Inject properties from an address.
* @private
2016-06-18 20:59:34 -07:00
* @param {Address|Base58Address} address
*/
2016-07-01 05:42:04 -07:00
Script.prototype.fromAddress = function fromAddress(address) {
2016-06-18 20:59:34 -07:00
if (typeof address === 'string')
address = bcoin.address.fromBase58(address);
2016-06-24 12:54:49 -07:00
if (!address)
throw new Error('Unknown address type.');
2016-07-02 04:53:42 -07:00
if (address.type === scriptTypes.PUBKEYHASH)
2016-07-01 05:42:04 -07:00
return this.fromPubkeyhash(address.hash);
2016-06-18 20:59:34 -07:00
2016-07-02 04:53:42 -07:00
if (address.type === scriptTypes.SCRIPTHASH)
2016-07-01 05:42:04 -07:00
return this.fromScripthash(address.hash);
2016-06-18 20:59:34 -07:00
if (address.version !== -1)
2016-07-01 05:42:04 -07:00
return this.fromProgram(address.version, address.hash);
2016-06-18 20:59:34 -07:00
2016-06-24 12:54:49 -07:00
assert(false, 'Bad address type.');
2016-06-18 20:59:34 -07:00
};
/**
2016-07-01 05:42:04 -07:00
* Create an output script from an address.
* @param {Address|Base58Address} address
* @returns {Script}
*/
Script.fromAddress = function fromAddress(address) {
return new Script().fromAddress(address);
};
/**
* Inject properties from a witness block commitment.
* @private
* @param {Buffer} hash
2016-06-14 18:13:51 -07:00
* @param {String|Buffer} flags
*/
2016-07-01 05:42:04 -07:00
Script.prototype.fromCommitment = function fromCommitment(hash, flags) {
2016-07-01 14:48:23 -07:00
var p = new BufferWriter();
2016-04-27 14:44:58 -07:00
p.writeU32BE(0xaa21a9ed);
p.writeHash(hash);
2016-05-23 01:04:55 -07:00
2016-07-01 14:46:16 -07:00
this.push(opcodes.OP_RETURN);
this.push(p.render());
2016-07-01 06:19:57 -07:00
if (flags)
2016-07-01 14:46:16 -07:00
this.push(flags);
2016-07-01 06:19:57 -07:00
2016-07-01 14:46:16 -07:00
this.compile();
return this;
2016-03-31 02:08:08 -07:00
};
2016-07-01 05:42:04 -07:00
/**
* Create a witness block commitment.
* @param {Buffer} hash
* @param {String|Buffer} flags
* @returns {Script}
*/
Script.fromCommitment = function fromCommitment(hash, flags) {
return new Script().fromCommitment(hash, flags);
};
/**
* Grab and deserialize the redeem script.
* @returns {Script|null} Redeem script.
*/
2016-03-14 20:43:32 -07:00
Script.prototype.getRedeem = function getRedeem() {
2016-06-13 21:25:42 -07:00
var redeem;
2016-04-17 19:34:03 -07:00
2016-07-01 02:31:27 -07:00
if (!this.isPushOnly())
return;
2016-07-01 02:31:27 -07:00
redeem = this.code[this.code.length - 1];
2016-03-14 20:43:32 -07:00
2016-07-01 02:31:27 -07:00
if (!redeem || !redeem.data)
return;
2016-03-14 20:43:32 -07:00
2016-07-01 02:31:27 -07:00
return new Script(redeem.data);
2016-03-14 20:43:32 -07:00
};
/**
* Get the standard script type.
2016-07-02 04:53:42 -07:00
* @returns {ScriptType}
*/
2016-03-14 20:43:32 -07:00
Script.prototype.getType = function getType() {
2016-07-02 04:53:42 -07:00
if (this.isPubkey())
return scriptTypes.PUBKEY;
if (this.isPubkeyhash())
return scriptTypes.PUBKEYHASH;
if (this.isScripthash())
return scriptTypes.SCRIPTHASH;
2016-03-14 20:43:32 -07:00
2016-07-02 04:53:42 -07:00
if (this.isWitnessPubkeyhash())
return scriptTypes.WITNESSPUBKEYHASH;
if (this.isWitnessScripthash())
return scriptTypes.WITNESSSCRIPTHASH;
if (this.isWitnessMasthash())
return scriptTypes.WITNESSMASTHASH;
if (this.isMultisig())
return scriptTypes.MULTISIG;
if (this.isNulldata())
return scriptTypes.NULLDATA;
return scriptTypes.NONSTANDARD;
2016-03-14 20:43:32 -07:00
};
/**
* Test whether a script is of an unknown/non-standard type.
* @returns {Boolean}
*/
2016-04-02 14:27:11 -07:00
Script.prototype.isUnknown = function isUnknown() {
2016-07-02 04:53:42 -07:00
return this.getType() === scriptTypes.NONSTANDARD;
2016-03-30 04:13:26 -07:00
};
/**
* Test whether the script is standard by policy standards.
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.prototype.isStandard = function isStandard() {
var type = this.getType();
var m, n;
2016-07-02 04:53:42 -07:00
if (type === scriptTypes.MULTISIG) {
2016-06-14 18:13:51 -07:00
m = Script.getSmall(this.raw[0]);
n = Script.getSmall(this.raw[this.raw.length - 2]);
2016-03-14 20:43:32 -07:00
if (n < 1 || n > 3)
return false;
if (m < 1 || m > n)
return false;
2016-07-02 04:53:42 -07:00
return true;
2016-03-14 20:43:32 -07:00
}
2016-07-02 04:53:42 -07:00
if (type === scriptTypes.NULLDATA) {
if (this.raw.length > constants.script.MAX_OP_RETURN_BYTES)
return false;
return true;
}
return type !== scriptTypes.NONSTANDARD;
2016-03-14 20:43:32 -07:00
};
/**
2016-04-17 19:34:03 -07:00
* Calculate size of script excluding the varint size bytes.
* @returns {Number}
*/
2016-03-14 20:43:32 -07:00
Script.prototype.getSize = function getSize() {
2016-06-13 21:25:42 -07:00
return this.raw.length;
2016-03-14 20:43:32 -07:00
};
/**
* "Guess" the address of the input script.
* This method is not 100% reliable.
2016-07-01 19:21:20 -07:00
* @returns {Address|null}
*/
2016-05-13 12:01:06 -07:00
Script.prototype.getInputAddress = function getInputAddress() {
2016-05-13 13:33:18 -07:00
return bcoin.address.fromInputScript(this);
2016-03-14 20:43:32 -07:00
};
/**
* Get the address of the script if present. Note that
* pubkey and multisig scripts will be treated as though
* they are pubkeyhash and scripthashes respectively.
2016-07-01 19:21:20 -07:00
* @returns {Address|null}
*/
2016-05-13 12:01:06 -07:00
Script.prototype.getAddress = function getAddress() {
2016-05-13 13:33:18 -07:00
return bcoin.address.fromScript(this);
2016-03-26 03:49:45 -07:00
};
2016-08-18 18:27:17 -07:00
/**
* Get the hash160 of the raw script.
* @param {Buffer}
*/
Script.prototype.hash160 = function hash160(enc) {
var hash = utils.hash160(this.toRaw());
if (enc === 'hex')
hash = hash.toString('hex');
return hash;
};
/**
* Get the sha256 of the raw script.
* @param {Buffer}
*/
Script.prototype.sha256 = function sha256(enc) {
var hash = utils.sha256(this.toRaw());
if (enc === 'hex')
hash = hash.toString('hex');
return hash;
};
/**
* Test whether the output script is pay-to-pubkey.
2016-07-01 15:09:33 -07:00
* @param {Boolean} [minimal=false] - Minimaldata only.
* @returns {Boolean}
*/
2016-07-01 15:09:33 -07:00
Script.prototype.isPubkey = function isPubkey(minimal) {
if (minimal) {
2016-07-01 21:02:50 -07:00
return this.raw.length >= 35
&& this.raw[0] >= 33 && this.raw[0] <= 65
2016-07-01 15:09:33 -07:00
&& this.raw[0] + 2 === this.raw.length
&& this.raw[this.raw.length - 1] === opcodes.OP_CHECKSIG;
2016-06-13 21:25:42 -07:00
}
2016-07-01 15:09:33 -07:00
return this.code.length === 2
&& Script.isKey(this.code[0].data)
&& this.code[1].value === opcodes.OP_CHECKSIG;
2016-03-14 20:43:32 -07:00
};
/**
* Test whether the output script is pay-to-pubkeyhash.
2016-07-01 15:09:33 -07:00
* @param {Boolean} [minimal=false] - Minimaldata only.
* @returns {Boolean}
*/
2016-07-01 15:09:33 -07:00
Script.prototype.isPubkeyhash = function isPubkeyhash(minimal) {
2016-07-01 18:28:22 -07:00
if (minimal) {
2016-07-01 15:09:33 -07:00
return this.raw.length === 25
&& this.raw[0] === opcodes.OP_DUP
&& this.raw[1] === opcodes.OP_HASH160
&& this.raw[2] === 0x14
&& this.raw[23] === opcodes.OP_EQUALVERIFY
&& this.raw[24] === opcodes.OP_CHECKSIG;
2016-06-13 21:25:42 -07:00
}
2016-07-01 15:09:33 -07:00
return this.code.length === 5
&& this.code[0].value === opcodes.OP_DUP
&& this.code[1].value === opcodes.OP_HASH160
&& Script.isHash(this.code[2].data)
&& this.code[3].value === opcodes.OP_EQUALVERIFY
&& this.code[4].value === opcodes.OP_CHECKSIG;
2016-03-14 20:43:32 -07:00
};
/**
* Test whether the output script is pay-to-multisig.
2016-07-01 15:09:33 -07:00
* @param {Boolean} [minimal=false] - Minimaldata only.
* @returns {Boolean}
*/
2016-07-01 15:09:33 -07:00
Script.prototype.isMultisig = function isMultisig(minimal) {
var m, n, i, op;
2016-03-14 20:43:32 -07:00
2016-06-13 21:25:42 -07:00
if (this.raw.length < 41)
2016-03-14 20:43:32 -07:00
return false;
2016-06-13 21:25:42 -07:00
if (this.raw[this.raw.length - 1] !== opcodes.OP_CHECKMULTISIG)
2016-03-14 20:43:32 -07:00
return false;
2016-06-13 21:25:42 -07:00
n = Script.getSmall(this.raw[this.raw.length - 2]);
2016-03-14 20:43:32 -07:00
2016-04-18 19:19:06 -07:00
if (n < 1)
return false;
2016-06-13 21:25:42 -07:00
m = Script.getSmall(this.raw[0]);
2016-03-14 20:43:32 -07:00
if (!(m >= 1 && m <= n))
return false;
if (n + 3 !== this.code.length)
return false;
for (i = 1; i < n + 1; i++) {
2016-07-01 15:09:33 -07:00
op = this.code[i];
if (!Script.isKey(op.data))
2016-03-14 20:43:32 -07:00
return false;
2016-07-01 15:09:33 -07:00
if (minimal) {
if (!Script.isMinimal(op.data, op.value))
return false;
}
2016-03-14 20:43:32 -07:00
}
return true;
};
/**
* Test whether the output script is pay-to-scripthash. Note that
* bitcoin itself requires scripthashes to be in strict minimaldata
* encoding. Using `OP_HASH160 OP_PUSHDATA1 [hash] OP_EQUAL` will
* _not_ be recognized as a scripthash.
* @returns {Boolean}
*/
2016-04-04 02:53:55 -07:00
Script.prototype.isScripthash = function isScripthash() {
2016-06-13 21:25:42 -07:00
return this.raw.length === 23
&& this.raw[0] === opcodes.OP_HASH160
&& this.raw[1] === 0x14
&& this.raw[22] === opcodes.OP_EQUAL;
2016-03-14 20:43:32 -07:00
};
/**
2016-06-14 16:26:26 -07:00
* Test whether the output script is nulldata/opreturn.
2016-07-01 15:09:33 -07:00
* @param {Boolean} [minimal=false] - Minimaldata only.
* @returns {Boolean}
*/
2016-07-01 15:09:33 -07:00
Script.prototype.isNulldata = function isNulldata(minimal) {
2016-04-17 19:34:03 -07:00
var i, op;
2016-06-13 21:25:42 -07:00
if (this.raw.length === 0)
2016-04-17 19:34:03 -07:00
return false;
2016-06-13 21:25:42 -07:00
if (this.raw[0] !== opcodes.OP_RETURN)
2016-04-17 19:34:03 -07:00
return false;
2016-06-20 01:09:27 -07:00
if (this.raw.length === 1)
return true;
2016-07-01 15:09:33 -07:00
if (minimal) {
2016-07-02 04:53:42 -07:00
if (this.raw.length > constants.script.MAX_OP_RETURN_BYTES)
return false;
2016-07-01 15:09:33 -07:00
if (this.raw.length === 2)
return Script.getSmall(this.raw[1]) !== -1;
if (this.raw[1] >= 0x01 && this.raw[1] <= 0x4b)
return this.raw[1] + 2 === this.raw.length;
2016-06-13 21:25:42 -07:00
2016-07-01 15:09:33 -07:00
if (this.raw[1] === opcodes.OP_PUSHDATA1)
return this.raw[2] > 75 && this.raw[2] + 3 === this.raw.length;
2016-06-20 01:09:27 -07:00
2016-07-01 15:09:33 -07:00
return false;
}
2016-06-13 21:25:42 -07:00
2016-07-01 15:09:33 -07:00
for (i = 1; i < this.code.length; i++) {
op = this.code[i];
2016-07-02 04:53:42 -07:00
2016-07-01 15:09:33 -07:00
if (op.data)
continue;
2016-07-02 04:53:42 -07:00
2016-07-01 15:09:33 -07:00
if (op.value === -1)
return false;
2016-07-02 04:53:42 -07:00
2016-07-01 15:09:33 -07:00
if (op.value > opcodes.OP_16)
return false;
}
2016-04-17 19:34:03 -07:00
2016-07-01 15:09:33 -07:00
return true;
2016-03-14 20:43:32 -07:00
};
/**
* Test whether the output script is a segregated witness
2016-07-14 14:01:33 -07:00
* commitment.
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.prototype.isCommitment = function isCommitment() {
2016-06-20 01:09:27 -07:00
return this.raw.length >= 38
&& this.raw[0] === opcodes.OP_RETURN
&& this.raw[1] === 0x24
&& this.raw.readUInt32BE(2, true) === 0xaa21a9ed;
2016-03-14 20:43:32 -07:00
};
/**
* Get the commitment hash if present.
* @returns {Buffer|null}
*/
2016-03-14 20:43:32 -07:00
Script.prototype.getCommitmentHash = function getCommitmentHash() {
if (!this.isCommitment())
return;
2016-06-13 21:25:42 -07:00
return this.raw.slice(6, 38);
2016-03-14 20:43:32 -07:00
};
/**
* Test whether the output script is a witness program.
* Note that this will return true even for malformed
* witness v0 programs.
* @return {Boolean}
*/
2016-06-18 20:59:34 -07:00
Script.prototype.isProgram = function isProgram() {
2016-06-13 21:25:42 -07:00
if (!(this.raw.length >= 4 && this.raw.length <= 42))
2016-03-14 20:43:32 -07:00
return false;
2016-06-13 21:25:42 -07:00
if (this.raw[0] !== opcodes.OP_0
&& !(this.raw[0] >= opcodes.OP_1 && this.raw[0] <= opcodes.OP_16)) {
2016-03-14 20:43:32 -07:00
return false;
2016-06-13 21:25:42 -07:00
}
2016-03-14 20:43:32 -07:00
2016-06-13 21:25:42 -07:00
if (this.raw[1] + 2 !== this.raw.length)
2016-03-14 20:43:32 -07:00
return false;
2016-06-13 21:25:42 -07:00
return true;
2016-03-14 20:43:32 -07:00
};
/**
* Get the witness program if present.
* @returns {Program|null}
*/
2016-06-17 06:32:00 -07:00
Script.prototype.toProgram = function toProgram() {
2016-06-17 21:23:05 -07:00
var version, data;
2016-03-14 20:43:32 -07:00
2016-06-18 20:59:34 -07:00
if (!this.isProgram())
2016-03-14 20:43:32 -07:00
return;
2016-06-13 21:25:42 -07:00
version = Script.getSmall(this.raw[0]);
data = this.raw.slice(2);
2016-03-14 20:43:32 -07:00
2016-06-17 06:32:00 -07:00
return new Program(version, data);
2016-03-14 20:43:32 -07:00
};
2016-08-18 20:03:58 -07:00
/**
* Get the script to the equivalent witness
* program (mimics bitcoind's scriptForWitness).
* @returns {Program|null}
*/
Script.prototype.forWitness = function() {
var hash;
if (this.isProgram())
return this;
if (this.isPubkey()) {
hash = utils.hash160(this.get(0));
return Script.fromProgram(0, hash);
}
if (this.isPubkeyhash())
return Script.fromProgram(0, this.get(2));
return Script.fromProgram(0, this.sha256());
};
/**
2016-06-29 04:51:00 -07:00
* Test whether the output script is
* a pay-to-witness-pubkeyhash program.
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.prototype.isWitnessPubkeyhash = function isWitnessPubkeyhash() {
2016-06-14 16:26:26 -07:00
return this.raw.length === 22
&& this.raw[0] === opcodes.OP_0
&& this.raw[1] === 0x14;
2016-03-14 20:43:32 -07:00
};
/**
2016-06-29 04:51:00 -07:00
* Test whether the output script is
* a pay-to-witness-scripthash program.
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.prototype.isWitnessScripthash = function isWitnessScripthash() {
2016-06-14 16:26:26 -07:00
return this.raw.length === 34
&& this.raw[0] === opcodes.OP_0
&& this.raw[1] === 0x20;
2016-03-14 20:43:32 -07:00
};
2016-06-29 04:51:00 -07:00
/**
* Test whether the output script
* is a pay-to-mast program.
* @returns {Boolean}
*/
2016-07-02 04:53:42 -07:00
Script.prototype.isWitnessMasthash = function isWitnessMasthash() {
2016-06-29 04:51:00 -07:00
return this.raw.length === 34
&& this.raw[0] === opcodes.OP_1
&& this.raw[1] === 0x20;
};
2016-04-29 21:45:18 -07:00
/**
* Test whether the output script is unspendable.
* @returns {Boolean}
*/
Script.prototype.isUnspendable = function isUnspendable() {
2016-06-13 21:25:42 -07:00
return this.raw.length > 0 && this.raw[0] === opcodes.OP_RETURN;
2016-04-29 21:45:18 -07:00
};
/**
* "Guess" the type of the input script.
* This method is not 100% reliable.
2016-07-02 04:53:42 -07:00
* @returns {ScriptType}
*/
2016-04-04 02:53:55 -07:00
Script.prototype.getInputType = function getInputType() {
2016-07-02 04:53:42 -07:00
if (this.isPubkeyInput())
return scriptTypes.PUBKEY;
if (this.isPubkeyhashInput())
return scriptTypes.PUBKEYHASH;
if (this.isScripthashInput())
return scriptTypes.SCRIPTHASH;
if (this.isMultisigInput())
return scriptTypes.MULTISIG;
return scriptTypes.NONSTANDARD;
2016-03-14 20:43:32 -07:00
};
/**
2016-04-17 03:30:27 -07:00
* "Guess" whether the input script is an unknown/non-standard type.
* This method is not 100% reliable.
* @returns {Boolean}
*/
2016-04-04 02:53:55 -07:00
Script.prototype.isUnknownInput = function isUnknownInput() {
2016-07-02 04:53:42 -07:00
return this.getInputType() === scriptTypes.NONSTANDARD;
2016-03-30 04:13:26 -07:00
};
/**
* "Guess" whether the input script is pay-to-pubkey.
* This method is not 100% reliable.
* @returns {Boolean}
*/
2016-04-04 02:53:55 -07:00
Script.prototype.isPubkeyInput = function isPubkeyInput() {
2016-06-16 01:13:06 -07:00
if (this.raw.length < 10)
2016-06-13 21:25:42 -07:00
return false;
2016-06-20 01:09:27 -07:00
2016-06-13 21:25:42 -07:00
if (this.raw.length > 78)
return false;
2016-06-20 01:09:27 -07:00
2016-06-13 21:25:42 -07:00
if (this.raw[0] > opcodes.OP_PUSHDATA4)
return false;
2016-06-20 01:09:27 -07:00
2016-06-13 21:25:42 -07:00
return this.code.length === 1 && Script.isSignature(this.code[0].data);
2016-03-14 20:43:32 -07:00
};
/**
* "Guess" whether the input script is pay-to-pubkeyhash.
* This method is not 100% reliable.
* @returns {Boolean}
*/
2016-04-04 02:53:55 -07:00
Script.prototype.isPubkeyhashInput = function isPubkeyhashInput() {
2016-06-16 01:13:06 -07:00
if (this.raw.length < 44)
2016-06-13 21:25:42 -07:00
return false;
2016-06-20 01:09:27 -07:00
2016-06-13 21:25:42 -07:00
if (this.raw.length > 148)
return false;
2016-06-20 01:09:27 -07:00
2016-06-13 21:25:42 -07:00
if (this.raw[0] > opcodes.OP_PUSHDATA4)
return false;
2016-06-20 01:09:27 -07:00
2016-06-13 21:25:42 -07:00
return this.code.length === 2
&& Script.isSignature(this.code[0].data)
&& Script.isKey(this.code[1].data);
2016-03-14 20:43:32 -07:00
};
/**
* "Guess" whether the input script is pay-to-multisig.
* This method is not 100% reliable.
* @returns {Boolean}
*/
2016-04-04 02:53:55 -07:00
Script.prototype.isMultisigInput = function isMultisigInput() {
2016-03-14 20:43:32 -07:00
var i;
2016-06-16 01:13:06 -07:00
if (this.raw.length < 20)
2016-06-13 21:25:42 -07:00
return false;
if (this.raw[0] !== opcodes.OP_0)
return false;
if (this.raw[1] > opcodes.OP_PUSHDATA4)
return false;
2016-04-04 02:53:55 -07:00
// We need to rule out scripthash
// because it may look like multisig.
2016-06-13 21:25:42 -07:00
if (this.isScripthashInput())
2016-03-14 20:43:32 -07:00
return false;
2016-06-13 21:25:42 -07:00
if (this.code.length < 3)
2016-03-14 20:43:32 -07:00
return false;
2016-06-13 21:25:42 -07:00
for (i = 1; i < this.code.length; i++) {
if (!Script.isSignature(this.code[i].data))
2016-03-14 20:43:32 -07:00
return false;
}
return true;
};
/**
* "Guess" whether the input script is pay-to-scripthash.
* This method is not 100% reliable.
* @returns {Boolean}
*/
2016-04-04 02:53:55 -07:00
Script.prototype.isScripthashInput = function isScripthashInput() {
2016-07-01 21:02:50 -07:00
var op;
2016-03-14 20:43:32 -07:00
2016-06-13 21:25:42 -07:00
if (this.raw.length < 2)
return false;
2016-03-14 20:43:32 -07:00
// Grab the raw redeem script.
2016-07-01 21:02:50 -07:00
op = this.code[this.code.length - 1];
2016-03-14 20:43:32 -07:00
// Last data element should be an array
// for the redeem script.
2016-07-01 21:02:50 -07:00
if (!op.data)
2016-03-14 20:43:32 -07:00
return false;
// Testing for scripthash inputs requires
// some evil magic to work. We do it by
// ruling things _out_. This test will not
// be correct 100% of the time. We rule
// out that the last data element is: a
// null dummy, a valid signature, a valid
// key, and we ensure that it is at least
// a script that does not use undefined
// opcodes.
2016-07-01 21:02:50 -07:00
if (Script.isDummy(op.data))
2016-03-14 20:43:32 -07:00
return false;
2016-07-01 21:02:50 -07:00
if (Script.isSignatureEncoding(op.data))
2016-03-14 20:43:32 -07:00
return false;
2016-07-01 21:02:50 -07:00
if (Script.isKeyEncoding(op.data))
2016-03-14 20:43:32 -07:00
return false;
2016-07-01 21:02:50 -07:00
if (!Script.isCode(op.data))
2016-03-14 20:43:32 -07:00
return false;
return true;
};
2016-04-17 19:34:03 -07:00
/**
* Get coinbase height.
* @returns {Number} `-1` if not present.
*/
Script.prototype.getCoinbaseHeight = function getCoinbaseHeight() {
2016-06-13 21:25:42 -07:00
return Script.getCoinbaseHeight(this.raw);
2016-04-17 19:34:03 -07:00
};
/**
* Get coinbase height.
2016-06-14 16:26:26 -07:00
* @param {Buffer} raw - Raw script.
2016-04-17 19:34:03 -07:00
* @returns {Number} `-1` if not present.
*/
2016-06-13 21:25:42 -07:00
Script.getCoinbaseHeight = function getCoinbaseHeight(raw) {
2016-06-14 19:06:17 -07:00
var flags = constants.flags.STANDARD_VERIFY_FLAGS;
var data, height, op;
2016-04-17 21:11:52 -07:00
2016-06-13 21:25:42 -07:00
if (raw.length === 0)
2016-04-17 19:34:03 -07:00
return -1;
2016-06-14 19:06:17 -07:00
// Small ints are allowed.
2016-06-13 21:25:42 -07:00
height = Script.getSmall(raw[0]);
2016-04-17 21:11:52 -07:00
2016-06-14 18:13:51 -07:00
if (height !== -1)
2016-06-13 21:25:42 -07:00
return height;
2016-04-17 19:34:03 -07:00
2016-06-14 19:06:17 -07:00
// No more than 6 bytes (we can't
// handle 7 byte JS numbers and
// height 281 trillion is far away).
if (raw[0] > 0x06)
2016-04-17 19:34:03 -07:00
return -1;
2016-06-14 19:06:17 -07:00
// No bad pushes allowed.
if (raw.length < 1 + raw[0])
return -1;
data = raw.slice(1, 1 + raw[0]);
// Deserialize the height.
try {
height = Script.num(data, flags, 6);
} catch (e) {
return -1;
}
// Reserialize the height.
op = Opcode.fromNumber(height);
// Should have been OP_0-OP_16.
if (!op.data)
return -1;
// Ensure the miner serialized the
// number in the most minimal fashion.
if (!utils.equal(data, op.data))
return -1;
return height.toNumber();
2016-04-17 19:34:03 -07:00
};
/**
* Get info about a coinbase script.
* @returns {Object} Object containing `height`,
2016-07-01 21:02:50 -07:00
* `nonce`, `flags`, and `text`.
*/
2016-05-06 15:33:19 -07:00
Script.prototype.getCoinbaseFlags = function getCoinbaseFlags() {
2016-06-14 16:26:26 -07:00
var height = this.getCoinbaseHeight();
2016-07-01 21:02:50 -07:00
var index = 0;
var nonce, flags, text;
2016-03-14 20:43:32 -07:00
2016-06-14 16:26:26 -07:00
if (height !== -1)
2016-05-06 15:33:19 -07:00
index++;
2016-03-14 20:43:32 -07:00
2016-07-01 21:02:50 -07:00
nonce = this.getNumber(1);
2016-06-20 01:09:27 -07:00
2016-07-01 21:02:50 -07:00
if (nonce)
nonce = nonce.toNumber();
2016-06-14 16:26:26 -07:00
else
2016-07-01 21:02:50 -07:00
nonce = -1;
2016-06-14 16:26:26 -07:00
flags = Script.encode(this.code.slice(index));
text = flags.toString('utf8');
text = text.replace(/[\u0000-\u0019\u007f-\u00ff]/g, '');
return {
height: height,
2016-07-01 21:02:50 -07:00
nonce: nonce,
2016-06-14 16:26:26 -07:00
flags: flags,
text: text
};
};
/**
* Test the script against a bloom filter.
* @param {Bloom} filter
* @returns {Boolean}
*/
Script.prototype.test = function test(filter) {
var i, op;
for (i = 0; i < this.code.length; i++) {
op = this.code[i];
if (op.value === -1)
break;
if (!op.data || op.data.length === 0)
continue;
if (filter.test(op.data))
return true;
2016-05-06 15:33:19 -07:00
}
2016-03-25 02:07:47 -07:00
2016-06-14 16:26:26 -07:00
return false;
};
2016-06-14 18:13:51 -07:00
/**
* Unshift an item onto the `code` array.
* @param {Number|String|BN|Buffer} data
* @returns {Number} Length.
*/
2016-06-14 16:26:26 -07:00
Script.prototype.unshift = function unshift(data) {
return this.code.unshift(Opcode.from(data));
};
2016-06-14 18:13:51 -07:00
/**
* Push an item onto the `code` array.
* @param {Number|String|BN|Buffer} data
* @returns {Number} Length.
*/
2016-06-14 16:26:26 -07:00
Script.prototype.push = function push(data) {
return this.code.push(Opcode.from(data));
};
2016-06-14 18:13:51 -07:00
/**
* Shift an item off of the `code` array.
* @returns {Buffer|Number}
*/
2016-06-14 16:26:26 -07:00
Script.prototype.shift = function shift() {
var op = this.code.shift();
if (!op)
return;
return op.data || op.value;
};
2016-06-14 18:13:51 -07:00
/**
* Pop an item off of the `code` array.
* @returns {Buffer|Number}
*/
2016-06-14 16:26:26 -07:00
Script.prototype.pop = function push(data) {
var op = this.code.pop();
if (!op)
return;
return op.data || op.value;
};
2016-06-14 18:13:51 -07:00
/**
* Remove an item from the `code` array.
* @param {Number} index
* @returns {Buffer|Number}
*/
2016-06-14 16:26:26 -07:00
Script.prototype.remove = function remove(i) {
var op = this.code.splice(i, 1)[0];
if (!op)
return;
return op.data || op.value;
};
2016-03-25 02:07:47 -07:00
2016-06-14 18:13:51 -07:00
/**
* Insert an item into the `code` array.
* @param {Number} index
* @param {Number|String|BN|Buffer} data
*/
2016-06-14 16:26:26 -07:00
Script.prototype.insert = function insert(i, data) {
assert(i <= this.code.length, 'Index out of bounds.');
this.code.splice(i, 0, Opcode.from(data))[0];
};
2016-03-14 20:43:32 -07:00
2016-06-14 18:13:51 -07:00
/**
* Get an item from the `code` array.
* @param {Number} index
* @returns {Buffer|Number}
*/
2016-06-14 16:26:26 -07:00
Script.prototype.get = function get(i) {
var op = this.code[i];
if (!op)
return;
return op.data || op.value;
2016-03-14 20:43:32 -07:00
};
2016-06-14 18:13:51 -07:00
/**
* Get a small integer from an opcode (OP_0-OP_16).
* @param {Number} index
* @returns {Number}
*/
Script.prototype.getSmall = function getSmall(i) {
var op = this.code[i];
if (!op)
return -1;
return Script.getSmall(op.value);
};
/**
* Get a number from the `code` array (5-byte limit).
* @params {Number} index
* @returns {BN}
*/
2016-06-14 16:26:26 -07:00
Script.prototype.getNumber = function getNumber(i) {
2016-06-14 18:13:51 -07:00
var small = this.getSmall(i);
2016-06-14 16:26:26 -07:00
var op = this.code[i];
2016-06-14 18:13:51 -07:00
if (small !== -1)
return new bn(small);
2016-06-14 16:26:26 -07:00
if (!op || !op.data || op.data.length > 5)
return;
2016-06-14 18:13:51 -07:00
2016-06-14 16:26:26 -07:00
return Script.num(op.data, constants.flags.VERIFY_NONE, 5);
};
2016-06-14 18:13:51 -07:00
/**
* Get a string from the `code` array (utf8).
* @params {Number} index
* @returns {String}
*/
2016-06-14 16:26:26 -07:00
Script.prototype.getString = function getString(i) {
var op = this.code[i];
if (!op || !op.data)
return;
return op.data.toString('utf8');
};
2016-07-01 05:42:04 -07:00
/**
* Clear the script code.
*/
Script.prototype.clear = function clear() {
this.code.length = 0;
};
2016-06-14 18:13:51 -07:00
/**
* Set an item in the `code` array.
* @param {Number} index
* @param {Buffer|Number|String|BN} data
*/
2016-06-14 16:26:26 -07:00
Script.prototype.set = function set(i, data) {
assert(i <= this.code.length, 'Index out of bounds.');
this.code[i] = Opcode.from(data);
};
/**
* Test whether the data element is a ripemd160 hash.
* @param {Buffer?} hash
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.isHash = function isHash(hash) {
2016-04-20 09:17:58 -07:00
return Buffer.isBuffer(hash) && hash.length === 20;
2016-03-14 20:43:32 -07:00
};
/**
* Test whether the data element is a public key. Note that
* this does not verify the format of the key, only the length.
* @param {Buffer?} key
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.isKey = function isKey(key) {
2016-04-20 09:17:58 -07:00
return Buffer.isBuffer(key) && key.length >= 33 && key.length <= 65;
2016-03-14 20:43:32 -07:00
};
/**
* Test whether the data element is a signature. Note that
* this does not verify the format of the signature, only the length.
* @param {Buffer?} sig
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.isSignature = function isSignature(sig) {
2016-04-20 09:17:58 -07:00
return Buffer.isBuffer(sig) && sig.length >= 9 && sig.length <= 73;
2016-03-14 20:43:32 -07:00
};
/**
* Test whether the data element is a null dummy (a zero-length array).
* @param {Buffer?} data
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.isDummy = function isDummy(data) {
2016-04-20 09:17:58 -07:00
return Buffer.isBuffer(data) && data.length === 0;
2016-03-14 20:43:32 -07:00
};
/**
* Test whether the data element is a valid key if VERIFY_STRICTENC is enabled.
* @param {Buffer} key
2016-04-15 07:32:44 -07:00
* @param {VerifyFlags?} flags
* @returns {Boolean}
2016-04-19 22:44:54 -07:00
* @throws {ScriptError}
*/
2016-04-19 22:44:54 -07:00
Script.validateKey = function validateKey(key, flags) {
2016-03-14 20:43:32 -07:00
if (flags == null)
flags = constants.flags.STANDARD_VERIFY_FLAGS;
2016-04-20 09:17:58 -07:00
if (!Buffer.isBuffer(key))
2016-04-19 22:44:54 -07:00
throw new ScriptError('BAD_OPCODE');
2016-03-14 20:43:32 -07:00
if (flags & constants.flags.VERIFY_STRICTENC) {
2016-04-19 22:44:54 -07:00
if (!Script.isKeyEncoding(key))
throw new ScriptError('PUBKEYTYPE');
2016-03-14 20:43:32 -07:00
}
return true;
};
/**
* Test whether the data element is a valid key.
* @param {Buffer} key
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.isKeyEncoding = function isKeyEncoding(key) {
2016-04-20 09:17:58 -07:00
if (!Buffer.isBuffer(key))
2016-03-14 20:43:32 -07:00
return false;
if (key.length < 33)
return false;
if (key[0] === 0x04) {
if (key.length !== 65)
return false;
} else if (key[0] === 0x02 || key[0] === 0x03) {
if (key.length !== 33)
return false;
} else {
return false;
}
return true;
};
/**
* Test whether the data element is a valid signature based
* on the encoding, S value, and sighash type. Requires
* VERIFY_DERSIG|VERIFY_LOW_S|VERIFY_STRICTENC, VERIFY_LOW_S
* and VERIFY_STRING_ENC to be enabled respectively. Note that
* this will allow zero-length signatures.
* @param {Buffer} sig
2016-04-15 07:32:44 -07:00
* @param {VerifyFlags?} flags
* @returns {Boolean}
2016-04-19 22:44:54 -07:00
* @throws {ScriptError}
*/
2016-04-19 22:44:54 -07:00
Script.validateSignature = function validateSignature(sig, flags) {
2016-03-14 20:43:32 -07:00
if (flags == null)
flags = constants.flags.STANDARD_VERIFY_FLAGS;
2016-04-20 09:17:58 -07:00
if (!Buffer.isBuffer(sig))
2016-04-19 22:44:54 -07:00
throw new ScriptError('BAD_OPCODE');
2016-03-14 20:43:32 -07:00
// Allow empty sigs
if (sig.length === 0)
return true;
if ((flags & constants.flags.VERIFY_DERSIG)
|| (flags & constants.flags.VERIFY_LOW_S)
|| (flags & constants.flags.VERIFY_STRICTENC)) {
2016-04-19 22:44:54 -07:00
if (!Script.isSignatureEncoding(sig))
throw new ScriptError('SIG_DER');
2016-03-14 20:43:32 -07:00
}
if (flags & constants.flags.VERIFY_LOW_S) {
2016-04-19 22:44:54 -07:00
if (!Script.isLowDER(sig))
throw new ScriptError('SIG_HIGH_S');
2016-03-14 20:43:32 -07:00
}
if (flags & constants.flags.VERIFY_STRICTENC) {
2016-04-19 22:44:54 -07:00
if (!Script.isHashType(sig))
throw new ScriptError('SIG_HASHTYPE');
2016-03-14 20:43:32 -07:00
}
return true;
};
/**
* Test a signature to see if it abides by BIP66.
* @see https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki
* @param {Buffer} sig
* @returns {Boolean}
2016-03-14 20:43:32 -07:00
*/
2016-03-14 20:43:32 -07:00
Script.isSignatureEncoding = function isSignatureEncoding(sig) {
var lenR, lenS;
2016-04-20 09:17:58 -07:00
if (!Buffer.isBuffer(sig))
2016-03-14 20:43:32 -07:00
return false;
// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
// * total-length: 1-byte length descriptor of everything that follows,
// excluding the sighash byte.
// * R-length: 1-byte length descriptor of the R value that follows.
// * R: arbitrary-length big-endian encoded R value. It must use the shortest
// possible encoding for a positive integers (which means no null bytes at
// the start, except a single one when the next byte has its highest bit set).
// * S-length: 1-byte length descriptor of the S value that follows.
// * S: arbitrary-length big-endian encoded S value. The same rules apply.
// * sighash: 1-byte value indicating what data is hashed (not part of the DER
// signature)
// Minimum and maximum size constraints.
if (sig.length < 9)
return false;
if (sig.length > 73)
return false;
// A signature is of type 0x30 (compound).
if (sig[0] !== 0x30)
return false;
// Make sure the length covers the entire signature.
if (sig[1] !== sig.length - 3)
return false;
// Extract the length of the R element.
lenR = sig[3];
// Make sure the length of the S element is still inside the signature.
if (5 + lenR >= sig.length)
return false;
// Extract the length of the S element.
lenS = sig[5 + lenR];
// Verify that the length of the signature matches the sum of the length
// of the elements.
if (lenR + lenS + 7 !== sig.length)
return false;
// Check whether the R element is an integer.
if (sig[2] !== 0x02)
return false;
// Zero-length integers are not allowed for R.
if (lenR === 0)
return false;
// Negative numbers are not allowed for R.
if (sig[4] & 0x80)
return false;
// Null bytes at the start of R are not allowed, unless R would
// otherwise be interpreted as a negative number.
if (lenR > 1 && (sig[4] === 0x00) && !(sig[5] & 0x80))
return false;
// Check whether the S element is an integer.
if (sig[lenR + 4] !== 0x02)
return false;
// Zero-length integers are not allowed for S.
if (lenS === 0)
return false;
// Negative numbers are not allowed for S.
if (sig[lenR + 6] & 0x80)
return false;
// Null bytes at the start of S are not allowed, unless S would otherwise be
// interpreted as a negative number.
if (lenS > 1 && (sig[lenR + 6] === 0x00) && !(sig[lenR + 7] & 0x80))
return false;
return true;
};
/**
* Test a signature to see whether it contains a valid sighash type.
* @param {Buffer} sig
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.isHashType = function isHashType(sig) {
2016-03-15 04:23:23 -07:00
var type;
2016-04-20 09:17:58 -07:00
if (!Buffer.isBuffer(sig))
2016-03-14 20:43:32 -07:00
return false;
if (sig.length === 0)
return false;
2016-04-17 08:45:22 -07:00
type = sig[sig.length - 1] & ~constants.hashType.ANYONECANPAY;
2016-03-14 20:43:32 -07:00
if (!(type >= constants.hashType.ALL && type <= constants.hashType.SINGLE))
2016-03-14 20:43:32 -07:00
return false;
return true;
};
/**
* Test a signature to see whether it contains a low S value.
* @param {Buffer} sig
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.isLowDER = function isLowDER(sig) {
if (!sig.s) {
2016-04-20 09:17:58 -07:00
if (!Buffer.isBuffer(sig))
2016-03-14 20:43:32 -07:00
return false;
if (!Script.isSignatureEncoding(sig))
return false;
sig = sig.slice(0, -1);
}
return bcoin.ec.isLowS(sig);
};
/**
* Format script code into a human readable-string.
* @param {Array} code
* @returns {String} Human-readable string.
*/
2016-03-14 20:43:32 -07:00
Script.format = function format(code) {
2016-06-14 16:26:26 -07:00
var out = [];
var i, op, data, value, size;
for (i = 0; i < code.length; i++) {
op = code[i];
data = op.data;
value = op.value;
2016-06-13 21:25:42 -07:00
if (data) {
size = data.length.toString(16);
2016-04-21 23:11:14 -07:00
while (size.length % 2 !== 0)
2016-04-20 14:12:40 -07:00
size = '0' + size;
2016-06-13 21:25:42 -07:00
if (!constants.opcodesByVal[value]) {
value = value.toString(16);
if (value.length < 2)
value = '0' + value;
2016-06-14 16:26:26 -07:00
value = '0x' + value + ' 0x' + data.toString('hex');
out.push(value);
continue;
2016-04-20 14:12:40 -07:00
}
2016-06-13 21:25:42 -07:00
value = constants.opcodesByVal[value];
2016-06-14 16:26:26 -07:00
value = value + ' 0x' + size + ' 0x' + data.toString('hex');
out.push(value);
continue;
2016-03-14 20:43:32 -07:00
}
2016-06-13 21:25:42 -07:00
assert(typeof value === 'number');
2016-03-29 13:15:43 -07:00
2016-06-14 16:26:26 -07:00
if (constants.opcodesByVal[value]) {
value = constants.opcodesByVal[value];
out.push(value);
continue;
}
2016-03-14 20:43:32 -07:00
2016-06-13 21:25:42 -07:00
value = value.toString(16);
2016-03-29 13:15:43 -07:00
2016-06-13 21:25:42 -07:00
if (value.length < 2)
value = '0' + value;
2016-06-14 16:26:26 -07:00
value = '0x' + value;
out.push(value);
}
return out.join(' ');
2016-03-14 20:43:32 -07:00
};
2016-04-29 21:45:18 -07:00
/**
* Format script code into bitcoind asm format.
* @param {Array} code
* @param {Boolean?} decode - Attempt to decode hash types.
* @returns {String} Human-readable string.
*/
Script.formatASM = function formatASM(code, decode) {
var out = [];
2016-06-13 21:25:42 -07:00
var i, op, type, symbol, data, value;
2016-04-29 21:45:18 -07:00
for (i = 0; i < code.length; i++) {
op = code[i];
2016-06-13 21:25:42 -07:00
data = op.data;
value = op.value;
2016-04-29 21:45:18 -07:00
2016-06-13 21:25:42 -07:00
if (value === -1) {
2016-04-29 21:45:18 -07:00
out.push('[error]');
break;
}
2016-06-13 21:25:42 -07:00
if (data) {
if (data.length <= 4) {
data = Script.num(data, constants.flags.VERIFY_NONE);
out.push(data.toString(10));
2016-04-29 21:45:18 -07:00
continue;
}
if (decode && code[0] !== opcodes.OP_RETURN) {
symbol = '';
2016-06-13 21:25:42 -07:00
if (Script.isSignatureEncoding(data)) {
type = data[data.length - 1];
2016-04-29 21:45:18 -07:00
symbol = constants.hashTypeByVal[type & 0x1f] || '';
if (symbol) {
if (type & constants.hashType.ANYONECANPAY)
symbol += '|ANYONECANPAY';
symbol = '[' + symbol + ']';
}
2016-06-13 21:25:42 -07:00
data = data.slice(0, -1);
2016-04-29 21:45:18 -07:00
}
2016-06-13 21:25:42 -07:00
out.push(data.toString('hex') + symbol);
2016-04-29 21:45:18 -07:00
continue;
}
2016-06-13 21:25:42 -07:00
out.push(data.toString('hex'));
2016-04-29 21:45:18 -07:00
continue;
}
2016-06-13 21:25:42 -07:00
value = constants.opcodesByVal[value] || 'OP_UNKNOWN';
2016-04-29 21:45:18 -07:00
2016-06-13 21:25:42 -07:00
out.push(value);
2016-04-29 21:45:18 -07:00
}
return out.join(' ');
};
/**
* Test the script to see if it contains only push ops.
* Push ops are: OP_1NEGATE, OP_0-OP_16 and all PUSHDATAs.
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.prototype.isPushOnly = function isPushOnly() {
var i, op;
2016-06-14 16:26:26 -07:00
2016-03-14 20:43:32 -07:00
for (i = 0; i < this.code.length; i++) {
op = this.code[i];
2016-06-14 16:26:26 -07:00
2016-06-13 21:25:42 -07:00
if (op.data)
2016-03-14 20:43:32 -07:00
continue;
2016-06-14 16:26:26 -07:00
2016-06-17 01:34:59 -07:00
if (op.value === -1)
2016-04-20 09:01:10 -07:00
return false;
2016-06-14 16:26:26 -07:00
2016-06-13 21:25:42 -07:00
if (op.value > opcodes.OP_16)
2016-04-21 10:24:09 -07:00
return false;
2016-03-14 20:43:32 -07:00
}
2016-06-14 16:26:26 -07:00
2016-03-14 20:43:32 -07:00
return true;
};
/**
* Count the sigops in the script.
* @param {Boolean} accurate - Whether to enable accurate counting. This will
* take into account the `n` value for OP_CHECKMULTISIG(VERIFY).
* @returns {Number} sigop count
*/
2016-03-14 20:43:32 -07:00
Script.prototype.getSigops = function getSigops(accurate) {
var total = 0;
var lastOp = -1;
2016-03-25 02:07:47 -07:00
var i, op;
2016-03-14 20:43:32 -07:00
for (i = 0; i < this.code.length; i++) {
op = this.code[i];
2016-06-13 21:25:42 -07:00
if (op.data)
2016-03-14 20:43:32 -07:00
continue;
2016-06-13 21:25:42 -07:00
if (op.value === -1)
2016-04-20 13:14:38 -07:00
break;
2016-03-14 20:43:32 -07:00
2016-06-14 16:26:26 -07:00
switch (op.value) {
case opcodes.OP_CHECKSIG:
case opcodes.OP_CHECKSIGVERIFY:
total++;
break;
case opcodes.OP_CHECKMULTISIG:
case opcodes.OP_CHECKMULTISIGVERIFY:
if (accurate && lastOp >= opcodes.OP_1 && lastOp <= opcodes.OP_16)
total += lastOp - 0x50;
else
total += constants.script.MAX_MULTISIG_PUBKEYS;
break;
2016-03-14 20:43:32 -07:00
}
2016-06-14 16:26:26 -07:00
lastOp = op.value;
2016-03-14 20:43:32 -07:00
}
return total;
};
2016-04-27 14:44:58 -07:00
/**
* Count the sigops in the script, taking into account redeem scripts.
* @param {Script} input - Input script, needed for access to redeem script.
* @returns {Number} sigop count
*/
Script.prototype.getScripthashSigops = function getScripthashSigops(input) {
var i, op, redeem;
if (!this.isScripthash())
return this.getSigops(true);
for (i = 0; i < input.code.length; i++) {
op = input.code[i];
2016-06-14 16:26:26 -07:00
2016-06-13 21:25:42 -07:00
if (op.data)
2016-04-27 14:44:58 -07:00
continue;
2016-06-14 16:26:26 -07:00
2016-06-13 21:25:42 -07:00
if (op.value === -1)
2016-04-27 14:44:58 -07:00
return 0;
2016-06-14 16:26:26 -07:00
2016-06-13 21:25:42 -07:00
if (op.value > opcodes.OP_16)
2016-04-27 14:44:58 -07:00
return 0;
}
2016-06-13 21:25:42 -07:00
if (!op.data)
2016-04-27 14:44:58 -07:00
return 0;
2016-06-13 21:25:42 -07:00
redeem = new Script(op.data);
2016-04-27 14:44:58 -07:00
return redeem.getSigops(true);
};
/**
* Count the sigops for a program.
* @param {Program} program
* @param {Witness} witness
* @param {VerifyFlags} flags
* @returns {Number} sigop count
*/
Script.witnessSigops = function witnessSigops(program, witness, flags) {
2016-05-25 01:06:41 -07:00
var redeem;
2016-04-27 14:44:58 -07:00
if (flags == null)
flags = constants.flags.STANDARD_VERIFY_FLAGS;
if (program.version === 0) {
if (program.data.length === 20)
return 1;
if (program.data.length === 32 && witness.items.length > 0) {
redeem = witness.getRedeem();
return redeem.getSigops(true);
}
}
return 0;
};
/**
* Count the sigops in a script, taking into account witness programs.
* @param {Script} input
* @param {Script} output
* @param {Witness} witness
* @param {VerifyFlags} flags
* @returns {Number} sigop count
*/
Script.getWitnessSigops = function getWitnessSigops(input, output, witness, flags) {
var redeem;
if (flags == null)
flags = constants.flags.STANDARD_VERIFY_FLAGS;
if ((flags & constants.flags.VERIFY_WITNESS) === 0)
return 0;
assert((flags & constants.flags.VERIFY_P2SH) !== 0);
2016-06-18 20:59:34 -07:00
if (output.isProgram())
2016-06-17 06:32:00 -07:00
return Script.witnessSigops(output.toProgram(), witness, flags);
2016-04-27 14:44:58 -07:00
// This is a unique situation in terms of consensus
// rules. We can just grab the redeem script without
// "parsing" (i.e. checking for pushdata parse errors)
// the script. This is because isPushOnly is called
// which checks for parse errors and will return
// false if one is found. Even the bitcoind code
// does not check the return value of GetOp.
if (output.isScripthash() && input.isPushOnly()) {
redeem = input.getRedeem();
2016-06-18 20:59:34 -07:00
if (redeem && redeem.isProgram())
2016-06-17 06:32:00 -07:00
return Script.witnessSigops(redeem.toProgram(), witness, flags);
2016-04-27 14:44:58 -07:00
}
return 0;
};
2016-04-19 01:30:12 -07:00
/**
2016-07-01 06:19:57 -07:00
* Inject properties from bitcoind test string.
* @private
2016-04-19 01:30:12 -07:00
* @param {String} items - Script string.
* @throws Parse error.
*/
2016-07-01 06:19:57 -07:00
Script.prototype.fromString = function fromString(code) {
2016-04-19 01:30:12 -07:00
var i, op, symbol, p;
2016-07-01 06:19:57 -07:00
assert(typeof code === 'string');
2016-04-19 01:30:12 -07:00
code = code.trim();
if (code.length === 0)
2016-07-01 06:19:57 -07:00
return this;
2016-04-19 01:30:12 -07:00
code = code.split(/\s+/);
2016-07-01 06:19:57 -07:00
2016-04-19 01:30:12 -07:00
p = new BufferWriter();
for (i = 0; i < code.length; i++) {
op = code[i];
2016-04-19 03:05:35 -07:00
symbol = op.toUpperCase();
2016-04-30 21:08:32 -07:00
if (symbol.indexOf('OP_') !== 0)
2016-04-19 03:05:35 -07:00
symbol = 'OP_' + symbol;
2016-04-19 01:30:12 -07:00
if (opcodes[symbol] == null) {
2016-04-30 21:08:32 -07:00
if (op[0] === '\'') {
2016-05-18 02:06:03 -07:00
assert(op[op.length - 1] === '\'', 'Unknown opcode.');
2016-04-19 01:30:12 -07:00
op = op.slice(1, -1);
2016-06-16 02:03:17 -07:00
op = Opcode.fromString(op);
p.writeBytes(op.toRaw());
2016-04-19 01:30:12 -07:00
continue;
}
if (/^-?\d+$/.test(op)) {
op = new bn(op, 10);
2016-06-16 02:03:17 -07:00
op = Opcode.fromNumber(op);
p.writeBytes(op.toRaw());
2016-04-19 01:30:12 -07:00
continue;
}
2016-05-18 02:06:03 -07:00
assert(op.indexOf('0x') === 0, 'Unknown opcode.');
2016-04-30 21:08:32 -07:00
op = op.substring(2);
2016-04-19 01:30:12 -07:00
assert(utils.isHex(op), 'Unknown opcode.');
op = new Buffer(op, 'hex');
p.writeBytes(op);
continue;
}
p.writeU8(opcodes[symbol]);
}
2016-07-01 06:19:57 -07:00
return this.fromRaw(p.render());
};
/**
* Parse a bitcoind test script
* string into a script object.
* @param {String} items - Script string.
* @returns {Script}
* @throws Parse error.
*/
Script.fromString = function fromString(code) {
return new Script().fromString(code);
2016-04-19 01:30:12 -07:00
};
/**
* Get a small integer from an opcode (OP_0-OP_16).
* @param {Number} index
* @returns {Number}
*/
2016-03-28 18:37:38 -07:00
Script.getSmall = function getSmall(op) {
if (typeof op !== 'number')
2016-06-14 18:13:51 -07:00
return -1;
2016-03-28 18:37:38 -07:00
2016-03-28 19:42:05 -07:00
if (op === opcodes.OP_0)
2016-03-28 18:37:38 -07:00
return 0;
2016-03-28 19:42:05 -07:00
if (op >= opcodes.OP_1 && op <= opcodes.OP_16)
2016-03-28 18:37:38 -07:00
return op - 0x50;
2016-06-13 21:25:42 -07:00
return -1;
2016-03-28 18:37:38 -07:00
};
/**
* Verify an input and output script, and a witness if present.
* @param {Script} input
* @param {Witness} witness
* @param {Script} output
* @param {TX} tx
* @param {Number} i
2016-04-15 07:32:44 -07:00
* @param {VerifyFlags} flags
* @returns {Boolean}
2016-04-19 22:44:54 -07:00
* @throws {ScriptError}
*/
2016-03-14 20:43:32 -07:00
Script.verify = function verify(input, witness, output, tx, i, flags) {
2016-04-19 22:44:54 -07:00
var copy, raw, redeem, hadWitness;
2016-03-14 20:43:32 -07:00
var stack = new Stack();
if (flags == null)
flags = constants.flags.STANDARD_VERIFY_FLAGS;
if (flags & constants.flags.VERIFY_SIGPUSHONLY) {
if (!input.isPushOnly())
2016-04-19 22:44:54 -07:00
throw new ScriptError('SIG_PUSHONLY');
2016-03-14 20:43:32 -07:00
}
// Execute the input script
2016-04-19 22:44:54 -07:00
input.execute(stack, flags, tx, i, 0);
2016-03-14 20:43:32 -07:00
// Copy the stack for P2SH
if (flags & constants.flags.VERIFY_P2SH)
copy = stack.clone();
2016-07-02 04:53:42 -07:00
// Execute the previous output script.
2016-04-19 22:44:54 -07:00
output.execute(stack, flags, tx, i, 0);
2016-03-14 20:43:32 -07:00
2016-07-02 04:53:42 -07:00
// Verify the stack values.
2016-04-19 22:44:54 -07:00
if (stack.length === 0 || !Script.bool(stack.pop()))
throw new ScriptError('EVAL_FALSE');
2016-03-14 20:43:32 -07:00
2016-06-18 20:59:34 -07:00
if ((flags & constants.flags.VERIFY_WITNESS) && output.isProgram()) {
2016-03-14 20:43:32 -07:00
hadWitness = true;
// Input script must be empty.
2016-06-13 21:25:42 -07:00
if (input.raw.length !== 0)
2016-04-19 22:44:54 -07:00
throw new ScriptError('WITNESS_MALLEATED');
2016-03-14 20:43:32 -07:00
2016-07-02 04:53:42 -07:00
// Verify the program in the output script.
2016-04-19 22:44:54 -07:00
Script.verifyProgram(witness, output, flags, tx, i);
2016-03-14 20:43:32 -07:00
// Force a cleanstack
stack.length = 0;
}
// If the script is P2SH, execute the real output script
if ((flags & constants.flags.VERIFY_P2SH) && output.isScripthash()) {
// P2SH can only have push ops in the scriptSig
if (!input.isPushOnly())
2016-04-19 22:44:54 -07:00
throw new ScriptError('SIG_PUSHONLY');
2016-03-14 20:43:32 -07:00
// Reset the stack
stack = copy;
// Stack should not be empty at this point
if (stack.length === 0)
2016-04-19 22:44:54 -07:00
throw new ScriptError('EVAL_FALSE');
2016-03-14 20:43:32 -07:00
// Grab the real redeem script
raw = stack.pop();
redeem = new Script(raw);
2016-07-02 04:53:42 -07:00
// Execute the redeem script.
2016-04-19 22:44:54 -07:00
redeem.execute(stack, flags, tx, i, 0);
2016-03-14 20:43:32 -07:00
2016-07-02 04:53:42 -07:00
// Verify the the stack values.
2016-04-19 22:44:54 -07:00
if (stack.length === 0 || !Script.bool(stack.pop()))
throw new ScriptError('EVAL_FALSE');
2016-03-14 20:43:32 -07:00
2016-06-18 20:59:34 -07:00
if ((flags & constants.flags.VERIFY_WITNESS) && redeem.isProgram()) {
2016-03-14 20:43:32 -07:00
hadWitness = true;
// Input script must be exactly one push of the redeem script.
2016-06-16 02:03:17 -07:00
if (!utils.equal(input.raw, Opcode.fromPush(raw).toRaw()))
2016-05-06 16:32:50 -07:00
throw new ScriptError('WITNESS_MALLEATED_P2SH');
2016-03-14 20:43:32 -07:00
2016-07-02 04:53:42 -07:00
// Verify the program in the redeem script.
2016-04-19 22:44:54 -07:00
Script.verifyProgram(witness, redeem, flags, tx, i);
2016-03-14 20:43:32 -07:00
2016-07-02 04:53:42 -07:00
// Force a cleanstack.
2016-03-14 20:43:32 -07:00
stack.length = 0;
}
}
2016-07-02 04:53:42 -07:00
// Ensure there is nothing left on the stack.
2016-03-14 20:43:32 -07:00
if (flags & constants.flags.VERIFY_CLEANSTACK) {
assert((flags & constants.flags.VERIFY_P2SH) !== 0);
// assert((flags & constants.flags.VERIFY_WITNESS) !== 0);
if (stack.length !== 0)
2016-04-19 22:44:54 -07:00
throw new ScriptError('CLEANSTACK');
2016-03-14 20:43:32 -07:00
}
// If we had a witness but no witness program, fail.
if (flags & constants.flags.VERIFY_WITNESS) {
assert((flags & constants.flags.VERIFY_P2SH) !== 0);
2016-04-27 14:44:58 -07:00
if (!hadWitness && witness.items.length > 0)
2016-04-19 22:44:54 -07:00
throw new ScriptError('WITNESS_UNEXPECTED');
2016-03-14 20:43:32 -07:00
}
return true;
};
/**
* Verify a witness program. This runs after regular script
* execution if a witness program is present. It will convert
* the witness to a stack and execute the program.
* @param {Witness} witness
* @param {Script} output
2016-04-15 07:32:44 -07:00
* @param {VerifyFlags} flags
* @param {TX} tx
* @param {Number} i
2016-04-19 22:44:54 -07:00
* @throws {ScriptError}
*/
2016-03-27 18:54:13 -07:00
Script.verifyProgram = function verifyProgram(witness, output, flags, tx, i) {
2016-06-17 06:32:00 -07:00
var program = output.toProgram();
2016-04-19 22:44:54 -07:00
var stack = witness.toStack();
var witnessScript, redeem, j;
2016-06-27 07:10:26 -07:00
var hash, pathdata, depth, path, posdata, pos, root;
2016-03-14 20:43:32 -07:00
2016-04-19 22:44:54 -07:00
assert(program, 'verifyProgram called on non-witness-program.');
2016-03-14 20:43:32 -07:00
assert((flags & constants.flags.VERIFY_WITNESS) !== 0);
2016-04-19 22:44:54 -07:00
if (program.version === 0) {
if (program.data.length === 32) {
if (stack.length === 0)
throw new ScriptError('WITNESS_PROGRAM_WITNESS_EMPTY');
2016-03-14 20:43:32 -07:00
2016-04-19 22:44:54 -07:00
witnessScript = stack.pop();
2016-03-14 20:43:32 -07:00
2016-04-30 16:20:40 -07:00
if (!utils.equal(utils.sha256(witnessScript), program.data))
2016-04-19 22:44:54 -07:00
throw new ScriptError('WITNESS_PROGRAM_MISMATCH');
redeem = new Script(witnessScript);
} else if (program.data.length === 20) {
if (stack.length !== 2)
throw new ScriptError('WITNESS_PROGRAM_MISMATCH');
2016-06-18 20:59:34 -07:00
redeem = Script.fromPubkeyhash(program.data);
2016-04-19 22:44:54 -07:00
} else {
2016-07-02 04:53:42 -07:00
// Failure on version=0 (bad program data length).
2016-04-19 22:44:54 -07:00
throw new ScriptError('WITNESS_PROGRAM_WRONG_LENGTH');
}
2016-06-24 10:15:34 -07:00
} else if ((flags & constants.flags.VERIFY_MAST) && program.version === 1) {
if (program.data.length !== 32)
throw new ScriptError('WITNESS_PROGRAM_WRONG_LENGTH');
if (stack.length < 3)
throw new ScriptError('WITNESS_PROGRAM_MISMATCH');
witnessScript = stack.pop();
redeem = new Script(witnessScript);
hash = utils.hash256(witnessScript);
pathdata = stack.pop();
if (pathdata.length & 0x1f)
throw new ScriptError('WITNESS_PROGRAM_MISMATCH');
depth = pathdata.length >>> 5;
if (depth > 32)
throw new ScriptError('WITNESS_PROGRAM_MISMATCH');
path = [];
for (j = 0; j < depth; j++)
path.push(pathdata.slice(j * 32, j * 32 + 32));
posdata = stack.pop();
if (posdata.length > 4)
throw new ScriptError('WITNESS_PROGRAM_MISMATCH');
pos = 0;
if (posdata.length > 0) {
if (posdata[posdata.length - 1] === 0x00)
throw new ScriptError('WITNESS_PROGRAM_MISMATCH');
for (j = 0; j < posdata.length; j++)
pos |= posdata[i] << 8 * j;
if (pos < 0)
pos += 0x100000000;
}
if (depth < 32) {
if (pos >= ((1 << depth) >>> 0))
throw new ScriptError('WITNESS_PROGRAM_MISMATCH');
}
root = utils.checkMerkleBranch(hash, path, pos);
if (!utils.equal(root, program.data))
throw new ScriptError('WITNESS_PROGRAM_MISMATCH');
2016-04-19 22:44:54 -07:00
} else {
2016-03-14 20:43:32 -07:00
// Anyone can spend (we can return true here
// if we want to always relay these transactions).
// Otherwise, if we want to act like an "old"
// implementation and only accept them in blocks,
// we can use the regalar output script which will
// succeed in a block, but fail in the mempool
// due to VERIFY_CLEANSTACK.
if (flags & constants.flags.VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)
2016-04-19 22:44:54 -07:00
throw new ScriptError('DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM');
2016-03-14 20:43:32 -07:00
return true;
}
2016-07-02 04:53:42 -07:00
// Witnesses still have push limits.
2016-03-14 20:43:32 -07:00
for (j = 0; j < stack.length; j++) {
2016-04-19 03:05:35 -07:00
if (stack.get(j).length > constants.script.MAX_PUSH)
2016-04-19 22:44:54 -07:00
throw new ScriptError('PUSH_SIZE');
2016-03-14 20:43:32 -07:00
}
2016-07-02 04:53:42 -07:00
// Verify the redeem script.
2016-04-19 22:44:54 -07:00
redeem.execute(stack, flags, tx, i, 1);
2016-03-14 20:43:32 -07:00
2016-07-02 04:53:42 -07:00
// Verify the stack values.
2016-05-06 22:48:51 -07:00
if (stack.length !== 1 || !Script.bool(stack.pop()))
2016-04-19 22:44:54 -07:00
throw new ScriptError('EVAL_FALSE');
2016-03-14 20:43:32 -07:00
return true;
};
/**
* Verify a signature, taking into account sighash type
* and whether the signature is historical.
* @param {Buffer} msg - Signature hash.
* @param {Buffer} sig
* @param {Buffer} key
2016-04-15 07:32:44 -07:00
* @param {VerifyFlags?} flags - If none of VERIFY_DERSIG,
* VERIFY_LOW_S, or VERIFY_STRICTENC are enabled, the signature
* is treated as historical, allowing odd signature lengths
* and high S values.
* @returns {Boolean}
*/
2016-03-14 20:43:32 -07:00
Script.checksig = function checksig(msg, sig, key, flags) {
var historical = false;
var high = false;
2016-03-14 20:43:32 -07:00
if (flags == null)
flags = constants.flags.STANDARD_VERIFY_FLAGS;
if (!Buffer.isBuffer(sig))
return false;
// Attempt to normalize the signature
// length before passing to elliptic.
// Note: We only do this for historical data!
// https://github.com/indutny/elliptic/issues/78
if (!((flags & constants.flags.VERIFY_DERSIG)
|| (flags & constants.flags.VERIFY_LOW_S)
|| (flags & constants.flags.VERIFY_STRICTENC))) {
historical = true;
}
if (!(flags & constants.flags.VERIFY_LOW_S))
high = true;
2016-07-04 05:36:06 -07:00
if (bcoin.sigcache)
return bcoin.sigcache.verify(msg, sig.slice(0, -1), key, historical, high);
return bcoin.ec.verify(msg, sig.slice(0, -1), key, historical, high);
2016-03-14 20:43:32 -07:00
};
/**
* Sign a message, appending the sighash type.
* @param {Buffer} msg - Signature hash.
* @param {Buffer} key - Public key.
* @param {Number} type - Sighash type.
* @returns {Buffer} signature
*/
2016-03-14 20:43:32 -07:00
Script.sign = function sign(msg, key, type) {
var sig = bcoin.ec.sign(msg, key);
2016-04-30 21:08:32 -07:00
var p = new BufferWriter();
2016-03-14 20:43:32 -07:00
// Add the sighash type as a single byte
// to the signature.
2016-04-30 21:08:32 -07:00
p.writeBytes(sig);
p.writeU8(type);
return p.render();
2016-03-14 20:43:32 -07:00
};
/**
2016-06-20 01:09:27 -07:00
* Inject properties from serialized data.
* @private
* @param {Buffer}
*/
2016-06-17 01:34:59 -07:00
Script.prototype.fromRaw = function fromRaw(data) {
if (data instanceof bcoin.reader)
data = data.readVarBytes();
2016-04-19 11:39:55 -07:00
2016-06-17 01:34:59 -07:00
this.raw = data;
this.code = Script.decode(data);
2016-04-19 11:39:55 -07:00
2016-06-17 01:34:59 -07:00
return this;
};
2016-04-19 11:39:55 -07:00
2016-06-20 01:09:27 -07:00
/**
* Create a script from a serialized buffer.
* @param {Buffer|String} data - Serialized script.
* @param {String?} enc - Either `"hex"` or `null`.
* @returns {Script}
*/
2016-04-19 11:39:55 -07:00
Script.fromRaw = function fromRaw(data, enc) {
2016-06-17 01:34:59 -07:00
if (typeof data === 'string')
data = new Buffer(data, enc);
return new Script().fromRaw(data);
2016-03-31 02:55:19 -07:00
};
/**
* Decode a serialized script into script code.
* Note that the serialized script must _not_
2016-06-14 16:26:26 -07:00
* include the varint size before it. Parse
* errors will output an opcode with a value
* of -1.
2016-04-20 13:14:38 -07:00
*
* @param {Buffer} raw - Serialized script.
2016-06-14 16:26:26 -07:00
* @returns {Opcode[]} Script code.
*/
2016-04-20 13:14:38 -07:00
Script.decode = function decode(raw) {
var p = new BufferReader(raw, true);
2016-04-20 09:01:10 -07:00
var code = [];
2016-04-20 13:14:38 -07:00
var op, size, data;
2016-04-20 09:01:10 -07:00
2016-04-20 13:14:38 -07:00
assert(Buffer.isBuffer(raw));
2016-04-20 09:01:10 -07:00
while (p.left()) {
op = p.readU8();
if (op >= 0x01 && op <= 0x4b) {
2016-04-20 09:17:58 -07:00
if (p.left() < op) {
2016-06-13 21:25:42 -07:00
code.push(new Opcode(-1));
2016-06-20 03:16:50 -07:00
break;
2016-04-20 09:17:58 -07:00
}
data = p.readBytes(op);
2016-06-13 21:25:42 -07:00
code.push(new Opcode(op, data));
2016-04-20 09:01:10 -07:00
} else if (op === opcodes.OP_PUSHDATA1) {
if (p.left() < 1) {
2016-06-13 21:25:42 -07:00
code.push(new Opcode(-1));
2016-06-20 03:16:50 -07:00
break;
2016-04-20 09:01:10 -07:00
}
size = p.readU8();
if (p.left() < size) {
2016-06-13 21:25:42 -07:00
code.push(new Opcode(-1));
2016-06-20 03:16:50 -07:00
break;
2016-04-20 09:01:10 -07:00
}
2016-04-20 09:17:58 -07:00
data = p.readBytes(size);
2016-06-13 21:25:42 -07:00
code.push(new Opcode(op, data));
2016-04-20 09:01:10 -07:00
} else if (op === opcodes.OP_PUSHDATA2) {
if (p.left() < 2) {
2016-06-13 21:25:42 -07:00
code.push(new Opcode(-1));
2016-06-20 03:16:50 -07:00
break;
2016-04-20 09:01:10 -07:00
}
size = p.readU16();
if (p.left() < size) {
2016-06-13 21:25:42 -07:00
code.push(new Opcode(-1));
2016-06-20 03:16:50 -07:00
break;
2016-04-20 09:01:10 -07:00
}
2016-04-20 09:17:58 -07:00
data = p.readBytes(size);
2016-06-13 21:25:42 -07:00
code.push(new Opcode(op, data));
2016-04-20 09:01:10 -07:00
} else if (op === opcodes.OP_PUSHDATA4) {
if (p.left() < 4) {
2016-06-13 21:25:42 -07:00
code.push(new Opcode(-1));
2016-06-20 03:16:50 -07:00
break;
2016-04-20 09:01:10 -07:00
}
size = p.readU32();
if (p.left() < size) {
2016-06-13 21:25:42 -07:00
code.push(new Opcode(-1));
2016-06-20 03:16:50 -07:00
break;
2016-04-20 09:01:10 -07:00
}
2016-04-20 09:17:58 -07:00
data = p.readBytes(size);
2016-06-13 21:25:42 -07:00
code.push(new Opcode(op, data));
2016-04-20 09:01:10 -07:00
} else {
2016-06-13 21:25:42 -07:00
code.push(new Opcode(op));
2016-04-20 09:01:10 -07:00
}
}
return code;
};
/**
* Encode and serialize script code. This will _not_
2016-06-14 16:26:26 -07:00
* include the varint size at the start.
* @param {Array} code - Script code.
* @returns {Buffer} Serialized script.
*/
2016-04-17 19:34:03 -07:00
Script.encode = function encode(code, writer) {
var p = new BufferWriter(writer);
2016-06-13 21:25:42 -07:00
var i, op;
2016-07-01 02:56:13 -07:00
assert(Array.isArray(code));
2016-06-13 21:25:42 -07:00
for (i = 0; i < code.length; i++) {
op = code[i];
2016-06-14 16:26:26 -07:00
if (op.value === -1)
throw new Error('Cannot reserialize a parse error.');
2016-06-13 21:25:42 -07:00
if (op.data) {
if (op.value <= 0x4b) {
p.writeU8(op.data.length);
p.writeBytes(op.data);
} else if (op.value === opcodes.OP_PUSHDATA1) {
p.writeU8(opcodes.OP_PUSHDATA1);
p.writeU8(op.data.length);
p.writeBytes(op.data);
} else if (op.value === opcodes.OP_PUSHDATA2) {
p.writeU8(opcodes.OP_PUSHDATA2);
p.writeU16(op.data.length);
p.writeBytes(op.data);
} else if (op.value === opcodes.OP_PUSHDATA4) {
p.writeU8(opcodes.OP_PUSHDATA4);
p.writeU32(op.data.length);
p.writeBytes(op.data);
} else {
2016-06-14 16:26:26 -07:00
throw new Error('Unknown pushdata opcode.');
2016-06-13 21:25:42 -07:00
}
continue;
}
2016-06-14 16:26:26 -07:00
2016-06-13 21:25:42 -07:00
p.writeU8(op.value);
}
if (!writer)
p = p.render();
return p;
};
2016-06-14 16:26:26 -07:00
/**
* Convert an array of Buffers and
* Numbers into an array of Opcodes.
* @param {Array} code
* @returns {Opcode[]}
*/
Script.parseArray = function parseArray(code) {
2016-06-13 22:39:05 -07:00
var out = [];
2016-06-13 21:25:42 -07:00
var i, op;
2016-03-14 20:43:32 -07:00
2016-07-01 02:56:13 -07:00
assert(Array.isArray(code));
2016-07-01 06:03:48 -07:00
if (code.length === 0)
return code;
2016-06-13 22:39:05 -07:00
if (code[0] instanceof Opcode)
return code;
2016-03-14 20:43:32 -07:00
for (i = 0; i < code.length; i++) {
2016-03-15 02:59:09 -07:00
op = code[i];
if (Buffer.isBuffer(op)) {
2016-06-14 16:26:26 -07:00
out.push(Opcode.fromData(op));
2016-03-14 20:43:32 -07:00
continue;
}
2016-03-28 16:50:59 -07:00
assert(typeof op === 'number');
2016-06-13 22:39:05 -07:00
out.push(new Opcode(op));
2016-03-14 20:43:32 -07:00
}
2016-06-13 22:39:05 -07:00
return out;
2016-03-14 20:43:32 -07:00
};
2016-06-14 16:26:26 -07:00
/**
* Calculate the size (including
* the opcode) of a pushdata.
* @param {Number} num - Pushdata data length.
* @returns {Number} size
*/
Script.sizePush = function sizePush(num) {
if (num <= 0x4b)
return 1;
if (num <= 0xff)
return 2;
2016-04-20 13:08:42 -07:00
2016-06-14 16:26:26 -07:00
if (num <= 0xffff)
return 3;
2016-06-13 21:25:42 -07:00
2016-06-14 16:26:26 -07:00
return 5;
2016-06-13 21:25:42 -07:00
};
2016-06-14 16:26:26 -07:00
/**
* Test whether an object a Script.
* @param {Object} obj
* @returns {Boolean}
*/
2016-06-13 21:25:42 -07:00
2016-06-14 16:26:26 -07:00
Script.isScript = function isScript(obj) {
return obj
&& Buffer.isBuffer(obj.raw)
&& typeof obj.getSubscript === 'function';
};
2016-06-13 21:25:42 -07:00
2016-05-15 18:07:06 -07:00
/*
* Expose
*/
exports = Script;
2016-05-15 21:55:17 -07:00
exports.opcodes = constants.opcodes;
exports.opcodesByVal = constants.opcodesByVal;
2016-07-02 04:53:42 -07:00
exports.types = scriptTypes;
exports.typesByVal = constants.scriptTypesByVal;
2016-07-02 00:19:44 -07:00
exports.flags = constants.flags;
2016-05-15 21:55:17 -07:00
2016-05-15 18:07:06 -07:00
module.exports = exports;