Source: script/script.js

  1. /*!
  2. * script.js - script interpreter for bcoin
  3. * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
  4. * Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
  5. * https://github.com/bcoin-org/bcoin
  6. */
  7. 'use strict';
  8. const assert = require('bsert');
  9. const bio = require('bufio');
  10. const ripemd160 = require('bcrypto/lib/ripemd160');
  11. const sha1 = require('bcrypto/lib/sha1');
  12. const sha256 = require('bcrypto/lib/sha256');
  13. const hash160 = require('bcrypto/lib/hash160');
  14. const hash256 = require('bcrypto/lib/hash256');
  15. const secp256k1 = require('bcrypto/lib/secp256k1');
  16. const consensus = require('../protocol/consensus');
  17. const policy = require('../protocol/policy');
  18. const Program = require('./program');
  19. const Opcode = require('./opcode');
  20. const Stack = require('./stack');
  21. const ScriptError = require('./scripterror');
  22. const ScriptNum = require('./scriptnum');
  23. const common = require('./common');
  24. const Address = require('../primitives/address');
  25. const opcodes = common.opcodes;
  26. const scriptTypes = common.types;
  27. const {encoding} = bio;
  28. const {inspectSymbol} = require('../utils');
  29. /*
  30. * Constants
  31. */
  32. const EMPTY_BUFFER = Buffer.alloc(0);
  33. /**
  34. * Script
  35. * Represents a input or output script.
  36. * @alias module:script.Script
  37. * @property {Array} code - Parsed script code.
  38. * @property {Buffer?} raw - Serialized script.
  39. * @property {Number} length - Number of parsed opcodes.
  40. */
  41. class Script {
  42. /**
  43. * Create a script.
  44. * @constructor
  45. * @param {Buffer|Array|Object} code
  46. */
  47. constructor(options) {
  48. this.raw = EMPTY_BUFFER;
  49. this.code = [];
  50. if (options)
  51. this.fromOptions(options);
  52. }
  53. /**
  54. * Get length.
  55. * @returns {Number}
  56. */
  57. get length() {
  58. return this.code.length;
  59. }
  60. /**
  61. * Set length.
  62. * @param {Number} value
  63. */
  64. set length(value) {
  65. this.code.length = value;
  66. }
  67. /**
  68. * Inject properties from options object.
  69. * @private
  70. * @param {Object} options
  71. */
  72. fromOptions(options) {
  73. assert(options, 'Script data is required.');
  74. if (Buffer.isBuffer(options))
  75. return this.fromRaw(options);
  76. if (Array.isArray(options))
  77. return this.fromArray(options);
  78. if (options.raw) {
  79. if (!options.code)
  80. return this.fromRaw(options.raw);
  81. assert(Buffer.isBuffer(options.raw), 'Raw must be a Buffer.');
  82. this.raw = options.raw;
  83. }
  84. if (options.code) {
  85. if (!options.raw)
  86. return this.fromArray(options.code);
  87. assert(Array.isArray(options.code), 'Code must be an array.');
  88. this.code = options.code;
  89. }
  90. return this;
  91. }
  92. /**
  93. * Insantiate script from options object.
  94. * @param {Object} options
  95. * @returns {Script}
  96. */
  97. static fromOptions(options) {
  98. return new this().fromOptions(options);
  99. }
  100. /**
  101. * Instantiate a value-only iterator.
  102. * @returns {ScriptIterator}
  103. */
  104. values() {
  105. return this.code.values();
  106. }
  107. /**
  108. * Instantiate a key and value iterator.
  109. * @returns {ScriptIterator}
  110. */
  111. entries() {
  112. return this.code.entries();
  113. }
  114. /**
  115. * Instantiate a value-only iterator.
  116. * @returns {ScriptIterator}
  117. */
  118. [Symbol.iterator]() {
  119. return this.code[Symbol.iterator]();
  120. }
  121. /**
  122. * Convert the script to an array of
  123. * Buffers (pushdatas) and Numbers
  124. * (opcodes).
  125. * @returns {Array}
  126. */
  127. toArray() {
  128. return this.code.slice();
  129. }
  130. /**
  131. * Inject properties from an array of
  132. * of buffers and numbers.
  133. * @private
  134. * @param {Array} code
  135. * @returns {Script}
  136. */
  137. fromArray(code) {
  138. assert(Array.isArray(code));
  139. this.clear();
  140. for (const op of code)
  141. this.push(op);
  142. return this.compile();
  143. }
  144. /**
  145. * Instantiate script from an array
  146. * of buffers and numbers.
  147. * @param {Array} code
  148. * @returns {Script}
  149. */
  150. static fromArray(code) {
  151. return new this().fromArray(code);
  152. }
  153. /**
  154. * Convert script to stack items.
  155. * @returns {Buffer[]}
  156. */
  157. toItems() {
  158. const items = [];
  159. for (const op of this.code) {
  160. const data = op.toPush();
  161. if (!data)
  162. throw new Error('Non-push opcode in script.');
  163. items.push(data);
  164. }
  165. return items;
  166. }
  167. /**
  168. * Inject data from stack items.
  169. * @private
  170. * @param {Buffer[]} items
  171. * @returns {Script}
  172. */
  173. fromItems(items) {
  174. assert(Array.isArray(items));
  175. this.clear();
  176. for (const item of items)
  177. this.pushData(item);
  178. return this.compile();
  179. }
  180. /**
  181. * Instantiate script from stack items.
  182. * @param {Buffer[]} items
  183. * @returns {Script}
  184. */
  185. static fromItems(items) {
  186. return new this().fromItems(items);
  187. }
  188. /**
  189. * Convert script to stack.
  190. * @returns {Stack}
  191. */
  192. toStack() {
  193. return new Stack(this.toItems());
  194. }
  195. /**
  196. * Inject data from stack.
  197. * @private
  198. * @param {Stack} stack
  199. * @returns {Script}
  200. */
  201. fromStack(stack) {
  202. return this.fromItems(stack.items);
  203. }
  204. /**
  205. * Instantiate script from stack.
  206. * @param {Stack} stack
  207. * @returns {Script}
  208. */
  209. static fromStack(stack) {
  210. return new this().fromStack(stack);
  211. }
  212. /**
  213. * Clone the script.
  214. * @returns {Script} Cloned script.
  215. */
  216. clone() {
  217. return new this.constructor().inject(this);
  218. }
  219. /**
  220. * Inject properties from script.
  221. * Used for cloning.
  222. * @private
  223. * @param {Script} script
  224. * @returns {Script}
  225. */
  226. inject(script) {
  227. this.raw = script.raw;
  228. this.code = script.code.slice();
  229. return this;
  230. }
  231. /**
  232. * Test equality against script.
  233. * @param {Script} script
  234. * @returns {Boolean}
  235. */
  236. equals(script) {
  237. assert(Script.isScript(script));
  238. return this.raw.equals(script.raw);
  239. }
  240. /**
  241. * Compare against another script.
  242. * @param {Script} script
  243. * @returns {Number}
  244. */
  245. compare(script) {
  246. assert(Script.isScript(script));
  247. return this.raw.compare(script.raw);
  248. }
  249. /**
  250. * Clear the script.
  251. * @returns {Script}
  252. */
  253. clear() {
  254. this.raw = EMPTY_BUFFER;
  255. this.code.length = 0;
  256. return this;
  257. }
  258. /**
  259. * Inspect the script.
  260. * @returns {String} Human-readable script code.
  261. */
  262. [inspectSymbol]() {
  263. return `<Script: ${this.toString()}>`;
  264. }
  265. /**
  266. * Convert the script to a bitcoind test string.
  267. * @returns {String} Human-readable script code.
  268. */
  269. toString() {
  270. const out = [];
  271. for (const op of this.code)
  272. out.push(op.toFormat());
  273. return out.join(' ');
  274. }
  275. /**
  276. * Format the script as bitcoind asm.
  277. * @param {Boolean?} decode - Attempt to decode hash types.
  278. * @returns {String} Human-readable script.
  279. */
  280. toASM(decode) {
  281. if (this.isNulldata())
  282. decode = false;
  283. const out = [];
  284. for (const op of this.code)
  285. out.push(op.toASM(decode));
  286. return out.join(' ');
  287. }
  288. /**
  289. * Re-encode the script internally. Useful if you
  290. * changed something manually in the `code` array.
  291. * @returns {Script}
  292. */
  293. compile() {
  294. if (this.code.length === 0)
  295. return this.clear();
  296. let size = 0;
  297. for (const op of this.code)
  298. size += op.getSize();
  299. const bw = bio.write(size);
  300. for (const op of this.code)
  301. op.toWriter(bw);
  302. this.raw = bw.render();
  303. return this;
  304. }
  305. /**
  306. * Write the script to a buffer writer.
  307. * @param {BufferWriter} bw
  308. */
  309. toWriter(bw) {
  310. bw.writeVarBytes(this.raw);
  311. return bw;
  312. }
  313. /**
  314. * Encode the script to a Buffer. See {@link Script#encode}.
  315. * @param {String} enc - Encoding, either `'hex'` or `null`.
  316. * @returns {Buffer|String} Serialized script.
  317. */
  318. toRaw() {
  319. return this.raw;
  320. }
  321. /**
  322. * Convert script to a hex string.
  323. * @returns {String}
  324. */
  325. toJSON() {
  326. return this.toRaw().toString('hex');
  327. }
  328. /**
  329. * Inject properties from json object.
  330. * @private
  331. * @param {String} json
  332. */
  333. fromJSON(json) {
  334. assert(typeof json === 'string', 'Code must be a string.');
  335. return this.fromRaw(Buffer.from(json, 'hex'));
  336. }
  337. /**
  338. * Instantiate script from a hex string.
  339. * @params {String} json
  340. * @returns {Script}
  341. */
  342. static fromJSON(json) {
  343. return new this().fromJSON(json);
  344. }
  345. /**
  346. * Get the script's "subscript" starting at a separator.
  347. * @param {Number} index - The last separator to sign/verify beyond.
  348. * @returns {Script} Subscript.
  349. */
  350. getSubscript(index) {
  351. if (index === 0)
  352. return this.clone();
  353. const script = new Script();
  354. for (let i = index; i < this.code.length; i++) {
  355. const op = this.code[i];
  356. if (op.value === -1)
  357. break;
  358. script.code.push(op);
  359. }
  360. return script.compile();
  361. }
  362. /**
  363. * Get the script's "subscript" starting at a separator.
  364. * Remove all OP_CODESEPARATORs if present. This bizarre
  365. * behavior is necessary for signing and verification when
  366. * code separators are present.
  367. * @returns {Script} Subscript.
  368. */
  369. removeSeparators() {
  370. let found = false;
  371. // Optimizing for the common case:
  372. // Check for any separators first.
  373. for (const op of this.code) {
  374. if (op.value === -1)
  375. break;
  376. if (op.value === opcodes.OP_CODESEPARATOR) {
  377. found = true;
  378. break;
  379. }
  380. }
  381. if (!found)
  382. return this;
  383. // Uncommon case: someone actually
  384. // has a code separator. Go through
  385. // and remove them all.
  386. const script = new Script();
  387. for (const op of this.code) {
  388. if (op.value === -1)
  389. break;
  390. if (op.value !== opcodes.OP_CODESEPARATOR)
  391. script.code.push(op);
  392. }
  393. return script.compile();
  394. }
  395. /**
  396. * Execute and interpret the script.
  397. * @param {Stack} stack - Script execution stack.
  398. * @param {Number?} flags - Script standard flags.
  399. * @param {TX?} tx - Transaction being verified.
  400. * @param {Number?} index - Index of input being verified.
  401. * @param {Amount?} value - Previous output value.
  402. * @param {Number?} version - Signature hash version (0=legacy, 1=segwit).
  403. * @throws {ScriptError} Will be thrown on VERIFY failures.
  404. */
  405. execute(stack, flags, tx, index, value, version) {
  406. if (flags == null)
  407. flags = Script.flags.STANDARD_VERIFY_FLAGS;
  408. if (version == null)
  409. version = 0;
  410. if (this.raw.length > consensus.MAX_SCRIPT_SIZE)
  411. throw new ScriptError('SCRIPT_SIZE');
  412. const state = [];
  413. const alt = [];
  414. let lastSep = 0;
  415. let opCount = 0;
  416. let negate = 0;
  417. let minimal = false;
  418. if (flags & Script.flags.VERIFY_MINIMALDATA)
  419. minimal = true;
  420. for (let ip = 0; ip < this.code.length; ip++) {
  421. const op = this.code[ip];
  422. if (op.value === -1)
  423. throw new ScriptError('BAD_OPCODE', op, ip);
  424. if (op.data && op.data.length > consensus.MAX_SCRIPT_PUSH)
  425. throw new ScriptError('PUSH_SIZE', op, ip);
  426. if (op.value > opcodes.OP_16 && ++opCount > consensus.MAX_SCRIPT_OPS)
  427. throw new ScriptError('OP_COUNT', op, ip);
  428. if (op.isDisabled())
  429. throw new ScriptError('DISABLED_OPCODE', op, ip);
  430. if (op.value === opcodes.OP_CODESEPARATOR && version === 0 &&
  431. (flags & Script.flags.VERIFY_CONST_SCRIPTCODE))
  432. throw new ScriptError('OP_CODESEPARATOR', op, ip);
  433. if (negate && !op.isBranch()) {
  434. if (stack.length + alt.length > consensus.MAX_SCRIPT_STACK)
  435. throw new ScriptError('STACK_SIZE', op, ip);
  436. continue;
  437. }
  438. if (op.data) {
  439. if (minimal && !op.isMinimal())
  440. throw new ScriptError('MINIMALDATA', op, ip);
  441. stack.push(op.data);
  442. if (stack.length + alt.length > consensus.MAX_SCRIPT_STACK)
  443. throw new ScriptError('STACK_SIZE', op, ip);
  444. continue;
  445. }
  446. switch (op.value) {
  447. case opcodes.OP_0: {
  448. stack.pushInt(0);
  449. break;
  450. }
  451. case opcodes.OP_1NEGATE: {
  452. stack.pushInt(-1);
  453. break;
  454. }
  455. case opcodes.OP_1:
  456. case opcodes.OP_2:
  457. case opcodes.OP_3:
  458. case opcodes.OP_4:
  459. case opcodes.OP_5:
  460. case opcodes.OP_6:
  461. case opcodes.OP_7:
  462. case opcodes.OP_8:
  463. case opcodes.OP_9:
  464. case opcodes.OP_10:
  465. case opcodes.OP_11:
  466. case opcodes.OP_12:
  467. case opcodes.OP_13:
  468. case opcodes.OP_14:
  469. case opcodes.OP_15:
  470. case opcodes.OP_16: {
  471. stack.pushInt(op.value - 0x50);
  472. break;
  473. }
  474. case opcodes.OP_NOP: {
  475. break;
  476. }
  477. case opcodes.OP_CHECKLOCKTIMEVERIFY: {
  478. // OP_CHECKLOCKTIMEVERIFY = OP_NOP2
  479. if (!(flags & Script.flags.VERIFY_CHECKLOCKTIMEVERIFY))
  480. break;
  481. if (!tx)
  482. throw new ScriptError('UNKNOWN_ERROR', 'No TX passed in.');
  483. if (stack.length === 0)
  484. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  485. const num = stack.getNum(-1, minimal, 5);
  486. if (num.isNeg())
  487. throw new ScriptError('NEGATIVE_LOCKTIME', op, ip);
  488. const locktime = num.toDouble();
  489. if (!tx.verifyLocktime(index, locktime))
  490. throw new ScriptError('UNSATISFIED_LOCKTIME', op, ip);
  491. break;
  492. }
  493. case opcodes.OP_CHECKSEQUENCEVERIFY: {
  494. // OP_CHECKSEQUENCEVERIFY = OP_NOP3
  495. if (!(flags & Script.flags.VERIFY_CHECKSEQUENCEVERIFY))
  496. break;
  497. if (!tx)
  498. throw new ScriptError('UNKNOWN_ERROR', 'No TX passed in.');
  499. if (stack.length === 0)
  500. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  501. const num = stack.getNum(-1, minimal, 5);
  502. if (num.isNeg())
  503. throw new ScriptError('NEGATIVE_LOCKTIME', op, ip);
  504. const locktime = num.toDouble();
  505. if (!tx.verifySequence(index, locktime))
  506. throw new ScriptError('UNSATISFIED_LOCKTIME', op, ip);
  507. break;
  508. }
  509. case opcodes.OP_NOP1:
  510. case opcodes.OP_NOP4:
  511. case opcodes.OP_NOP5:
  512. case opcodes.OP_NOP6:
  513. case opcodes.OP_NOP7:
  514. case opcodes.OP_NOP8:
  515. case opcodes.OP_NOP9:
  516. case opcodes.OP_NOP10: {
  517. if (flags & Script.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
  518. throw new ScriptError('DISCOURAGE_UPGRADABLE_NOPS', op, ip);
  519. break;
  520. }
  521. case opcodes.OP_IF:
  522. case opcodes.OP_NOTIF: {
  523. let val = false;
  524. if (!negate) {
  525. if (stack.length < 1)
  526. throw new ScriptError('UNBALANCED_CONDITIONAL', op, ip);
  527. if (version === 1 && (flags & Script.flags.VERIFY_MINIMALIF)) {
  528. const item = stack.get(-1);
  529. if (item.length > 1)
  530. throw new ScriptError('MINIMALIF');
  531. if (item.length === 1 && item[0] !== 1)
  532. throw new ScriptError('MINIMALIF');
  533. }
  534. val = stack.getBool(-1);
  535. if (op.value === opcodes.OP_NOTIF)
  536. val = !val;
  537. stack.pop();
  538. }
  539. state.push(val);
  540. if (!val)
  541. negate += 1;
  542. break;
  543. }
  544. case opcodes.OP_ELSE: {
  545. if (state.length === 0)
  546. throw new ScriptError('UNBALANCED_CONDITIONAL', op, ip);
  547. state[state.length - 1] = !state[state.length - 1];
  548. if (!state[state.length - 1])
  549. negate += 1;
  550. else
  551. negate -= 1;
  552. break;
  553. }
  554. case opcodes.OP_ENDIF: {
  555. if (state.length === 0)
  556. throw new ScriptError('UNBALANCED_CONDITIONAL', op, ip);
  557. if (!state.pop())
  558. negate -= 1;
  559. break;
  560. }
  561. case opcodes.OP_VERIFY: {
  562. if (stack.length === 0)
  563. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  564. if (!stack.getBool(-1))
  565. throw new ScriptError('VERIFY', op, ip);
  566. stack.pop();
  567. break;
  568. }
  569. case opcodes.OP_RETURN: {
  570. throw new ScriptError('OP_RETURN', op, ip);
  571. }
  572. case opcodes.OP_TOALTSTACK: {
  573. if (stack.length === 0)
  574. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  575. alt.push(stack.pop());
  576. break;
  577. }
  578. case opcodes.OP_FROMALTSTACK: {
  579. if (alt.length === 0)
  580. throw new ScriptError('INVALID_ALTSTACK_OPERATION', op, ip);
  581. stack.push(alt.pop());
  582. break;
  583. }
  584. case opcodes.OP_2DROP: {
  585. if (stack.length < 2)
  586. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  587. stack.pop();
  588. stack.pop();
  589. break;
  590. }
  591. case opcodes.OP_2DUP: {
  592. if (stack.length < 2)
  593. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  594. const v1 = stack.get(-2);
  595. const v2 = stack.get(-1);
  596. stack.push(v1);
  597. stack.push(v2);
  598. break;
  599. }
  600. case opcodes.OP_3DUP: {
  601. if (stack.length < 3)
  602. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  603. const v1 = stack.get(-3);
  604. const v2 = stack.get(-2);
  605. const v3 = stack.get(-1);
  606. stack.push(v1);
  607. stack.push(v2);
  608. stack.push(v3);
  609. break;
  610. }
  611. case opcodes.OP_2OVER: {
  612. if (stack.length < 4)
  613. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  614. const v1 = stack.get(-4);
  615. const v2 = stack.get(-3);
  616. stack.push(v1);
  617. stack.push(v2);
  618. break;
  619. }
  620. case opcodes.OP_2ROT: {
  621. if (stack.length < 6)
  622. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  623. const v1 = stack.get(-6);
  624. const v2 = stack.get(-5);
  625. stack.erase(-6, -4);
  626. stack.push(v1);
  627. stack.push(v2);
  628. break;
  629. }
  630. case opcodes.OP_2SWAP: {
  631. if (stack.length < 4)
  632. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  633. stack.swap(-4, -2);
  634. stack.swap(-3, -1);
  635. break;
  636. }
  637. case opcodes.OP_IFDUP: {
  638. if (stack.length === 0)
  639. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  640. if (stack.getBool(-1)) {
  641. const val = stack.get(-1);
  642. stack.push(val);
  643. }
  644. break;
  645. }
  646. case opcodes.OP_DEPTH: {
  647. stack.pushInt(stack.length);
  648. break;
  649. }
  650. case opcodes.OP_DROP: {
  651. if (stack.length === 0)
  652. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  653. stack.pop();
  654. break;
  655. }
  656. case opcodes.OP_DUP: {
  657. if (stack.length === 0)
  658. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  659. stack.push(stack.get(-1));
  660. break;
  661. }
  662. case opcodes.OP_NIP: {
  663. if (stack.length < 2)
  664. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  665. stack.remove(-2);
  666. break;
  667. }
  668. case opcodes.OP_OVER: {
  669. if (stack.length < 2)
  670. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  671. stack.push(stack.get(-2));
  672. break;
  673. }
  674. case opcodes.OP_PICK:
  675. case opcodes.OP_ROLL: {
  676. if (stack.length < 2)
  677. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  678. const num = stack.getInt(-1, minimal, 4);
  679. stack.pop();
  680. if (num < 0 || num >= stack.length)
  681. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  682. const val = stack.get(-num - 1);
  683. if (op.value === opcodes.OP_ROLL)
  684. stack.remove(-num - 1);
  685. stack.push(val);
  686. break;
  687. }
  688. case opcodes.OP_ROT: {
  689. if (stack.length < 3)
  690. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  691. stack.swap(-3, -2);
  692. stack.swap(-2, -1);
  693. break;
  694. }
  695. case opcodes.OP_SWAP: {
  696. if (stack.length < 2)
  697. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  698. stack.swap(-2, -1);
  699. break;
  700. }
  701. case opcodes.OP_TUCK: {
  702. if (stack.length < 2)
  703. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  704. stack.insert(-2, stack.get(-1));
  705. break;
  706. }
  707. case opcodes.OP_SIZE: {
  708. if (stack.length < 1)
  709. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  710. stack.pushInt(stack.get(-1).length);
  711. break;
  712. }
  713. case opcodes.OP_EQUAL:
  714. case opcodes.OP_EQUALVERIFY: {
  715. if (stack.length < 2)
  716. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  717. const v1 = stack.get(-2);
  718. const v2 = stack.get(-1);
  719. const res = v1.equals(v2);
  720. stack.pop();
  721. stack.pop();
  722. stack.pushBool(res);
  723. if (op.value === opcodes.OP_EQUALVERIFY) {
  724. if (!res)
  725. throw new ScriptError('EQUALVERIFY', op, ip);
  726. stack.pop();
  727. }
  728. break;
  729. }
  730. case opcodes.OP_1ADD:
  731. case opcodes.OP_1SUB:
  732. case opcodes.OP_NEGATE:
  733. case opcodes.OP_ABS:
  734. case opcodes.OP_NOT:
  735. case opcodes.OP_0NOTEQUAL: {
  736. if (stack.length < 1)
  737. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  738. let num = stack.getNum(-1, minimal, 4);
  739. let cmp;
  740. switch (op.value) {
  741. case opcodes.OP_1ADD:
  742. num.iaddn(1);
  743. break;
  744. case opcodes.OP_1SUB:
  745. num.isubn(1);
  746. break;
  747. case opcodes.OP_NEGATE:
  748. num.ineg();
  749. break;
  750. case opcodes.OP_ABS:
  751. num.iabs();
  752. break;
  753. case opcodes.OP_NOT:
  754. cmp = num.isZero();
  755. num = ScriptNum.fromBool(cmp);
  756. break;
  757. case opcodes.OP_0NOTEQUAL:
  758. cmp = !num.isZero();
  759. num = ScriptNum.fromBool(cmp);
  760. break;
  761. default:
  762. assert(false, 'Fatal script error.');
  763. break;
  764. }
  765. stack.pop();
  766. stack.pushNum(num);
  767. break;
  768. }
  769. case opcodes.OP_ADD:
  770. case opcodes.OP_SUB:
  771. case opcodes.OP_BOOLAND:
  772. case opcodes.OP_BOOLOR:
  773. case opcodes.OP_NUMEQUAL:
  774. case opcodes.OP_NUMEQUALVERIFY:
  775. case opcodes.OP_NUMNOTEQUAL:
  776. case opcodes.OP_LESSTHAN:
  777. case opcodes.OP_GREATERTHAN:
  778. case opcodes.OP_LESSTHANOREQUAL:
  779. case opcodes.OP_GREATERTHANOREQUAL:
  780. case opcodes.OP_MIN:
  781. case opcodes.OP_MAX: {
  782. if (stack.length < 2)
  783. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  784. const n1 = stack.getNum(-2, minimal, 4);
  785. const n2 = stack.getNum(-1, minimal, 4);
  786. let num, cmp;
  787. switch (op.value) {
  788. case opcodes.OP_ADD:
  789. num = n1.iadd(n2);
  790. break;
  791. case opcodes.OP_SUB:
  792. num = n1.isub(n2);
  793. break;
  794. case opcodes.OP_BOOLAND:
  795. cmp = n1.toBool() && n2.toBool();
  796. num = ScriptNum.fromBool(cmp);
  797. break;
  798. case opcodes.OP_BOOLOR:
  799. cmp = n1.toBool() || n2.toBool();
  800. num = ScriptNum.fromBool(cmp);
  801. break;
  802. case opcodes.OP_NUMEQUAL:
  803. cmp = n1.eq(n2);
  804. num = ScriptNum.fromBool(cmp);
  805. break;
  806. case opcodes.OP_NUMEQUALVERIFY:
  807. cmp = n1.eq(n2);
  808. num = ScriptNum.fromBool(cmp);
  809. break;
  810. case opcodes.OP_NUMNOTEQUAL:
  811. cmp = !n1.eq(n2);
  812. num = ScriptNum.fromBool(cmp);
  813. break;
  814. case opcodes.OP_LESSTHAN:
  815. cmp = n1.lt(n2);
  816. num = ScriptNum.fromBool(cmp);
  817. break;
  818. case opcodes.OP_GREATERTHAN:
  819. cmp = n1.gt(n2);
  820. num = ScriptNum.fromBool(cmp);
  821. break;
  822. case opcodes.OP_LESSTHANOREQUAL:
  823. cmp = n1.lte(n2);
  824. num = ScriptNum.fromBool(cmp);
  825. break;
  826. case opcodes.OP_GREATERTHANOREQUAL:
  827. cmp = n1.gte(n2);
  828. num = ScriptNum.fromBool(cmp);
  829. break;
  830. case opcodes.OP_MIN:
  831. num = ScriptNum.min(n1, n2);
  832. break;
  833. case opcodes.OP_MAX:
  834. num = ScriptNum.max(n1, n2);
  835. break;
  836. default:
  837. assert(false, 'Fatal script error.');
  838. break;
  839. }
  840. stack.pop();
  841. stack.pop();
  842. stack.pushNum(num);
  843. if (op.value === opcodes.OP_NUMEQUALVERIFY) {
  844. if (!stack.getBool(-1))
  845. throw new ScriptError('NUMEQUALVERIFY', op, ip);
  846. stack.pop();
  847. }
  848. break;
  849. }
  850. case opcodes.OP_WITHIN: {
  851. if (stack.length < 3)
  852. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  853. const n1 = stack.getNum(-3, minimal, 4);
  854. const n2 = stack.getNum(-2, minimal, 4);
  855. const n3 = stack.getNum(-1, minimal, 4);
  856. const val = n2.lte(n1) && n1.lt(n3);
  857. stack.pop();
  858. stack.pop();
  859. stack.pop();
  860. stack.pushBool(val);
  861. break;
  862. }
  863. case opcodes.OP_RIPEMD160: {
  864. if (stack.length === 0)
  865. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  866. stack.push(ripemd160.digest(stack.pop()));
  867. break;
  868. }
  869. case opcodes.OP_SHA1: {
  870. if (stack.length === 0)
  871. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  872. stack.push(sha1.digest(stack.pop()));
  873. break;
  874. }
  875. case opcodes.OP_SHA256: {
  876. if (stack.length === 0)
  877. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  878. stack.push(sha256.digest(stack.pop()));
  879. break;
  880. }
  881. case opcodes.OP_HASH160: {
  882. if (stack.length === 0)
  883. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  884. stack.push(hash160.digest(stack.pop()));
  885. break;
  886. }
  887. case opcodes.OP_HASH256: {
  888. if (stack.length === 0)
  889. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  890. stack.push(hash256.digest(stack.pop()));
  891. break;
  892. }
  893. case opcodes.OP_CODESEPARATOR: {
  894. lastSep = ip + 1;
  895. break;
  896. }
  897. case opcodes.OP_CHECKSIG:
  898. case opcodes.OP_CHECKSIGVERIFY: {
  899. if (!tx)
  900. throw new ScriptError('UNKNOWN_ERROR', 'No TX passed in.');
  901. if (stack.length < 2)
  902. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  903. const sig = stack.get(-2);
  904. const key = stack.get(-1);
  905. const subscript = this.getSubscript(lastSep);
  906. if (version === 0) {
  907. const found = subscript.findAndDelete(sig);
  908. if (found > 0 && (flags & Script.flags.VERIFY_CONST_SCRIPTCODE))
  909. throw new ScriptError('SIG_FINDANDDELETE', op, ip);
  910. }
  911. validateSignature(sig, flags);
  912. validateKey(key, flags, version);
  913. let res = false;
  914. if (sig.length > 0) {
  915. const type = sig[sig.length - 1];
  916. const hash = tx.signatureHash(
  917. index,
  918. subscript,
  919. value,
  920. type,
  921. version
  922. );
  923. res = checksig(hash, sig, key);
  924. }
  925. if (!res && (flags & Script.flags.VERIFY_NULLFAIL)) {
  926. if (sig.length !== 0)
  927. throw new ScriptError('NULLFAIL', op, ip);
  928. }
  929. stack.pop();
  930. stack.pop();
  931. stack.pushBool(res);
  932. if (op.value === opcodes.OP_CHECKSIGVERIFY) {
  933. if (!res)
  934. throw new ScriptError('CHECKSIGVERIFY', op, ip);
  935. stack.pop();
  936. }
  937. break;
  938. }
  939. case opcodes.OP_CHECKMULTISIG:
  940. case opcodes.OP_CHECKMULTISIGVERIFY: {
  941. if (!tx)
  942. throw new ScriptError('UNKNOWN_ERROR', 'No TX passed in.');
  943. let i = 1;
  944. if (stack.length < i)
  945. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  946. let n = stack.getInt(-i, minimal, 4);
  947. let okey = n + 2;
  948. let ikey, isig;
  949. if (n < 0 || n > consensus.MAX_MULTISIG_PUBKEYS)
  950. throw new ScriptError('PUBKEY_COUNT', op, ip);
  951. opCount += n;
  952. if (opCount > consensus.MAX_SCRIPT_OPS)
  953. throw new ScriptError('OP_COUNT', op, ip);
  954. i += 1;
  955. ikey = i;
  956. i += n;
  957. if (stack.length < i)
  958. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  959. let m = stack.getInt(-i, minimal, 4);
  960. if (m < 0 || m > n)
  961. throw new ScriptError('SIG_COUNT', op, ip);
  962. i += 1;
  963. isig = i;
  964. i += m;
  965. if (stack.length < i)
  966. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  967. const subscript = this.getSubscript(lastSep);
  968. for (let j = 0; j < m; j++) {
  969. const sig = stack.get(-isig - j);
  970. if (version === 0) {
  971. const found = subscript.findAndDelete(sig);
  972. if (found > 0 && (flags & Script.flags.VERIFY_CONST_SCRIPTCODE))
  973. throw new ScriptError('SIG_FINDANDDELETE', op, ip);
  974. }
  975. }
  976. let res = true;
  977. while (res && m > 0) {
  978. const sig = stack.get(-isig);
  979. const key = stack.get(-ikey);
  980. validateSignature(sig, flags);
  981. validateKey(key, flags, version);
  982. if (sig.length > 0) {
  983. const type = sig[sig.length - 1];
  984. const hash = tx.signatureHash(
  985. index,
  986. subscript,
  987. value,
  988. type,
  989. version
  990. );
  991. if (checksig(hash, sig, key)) {
  992. isig += 1;
  993. m -= 1;
  994. }
  995. }
  996. ikey += 1;
  997. n -= 1;
  998. if (m > n)
  999. res = false;
  1000. }
  1001. while (i > 1) {
  1002. if (!res && (flags & Script.flags.VERIFY_NULLFAIL)) {
  1003. if (okey === 0 && stack.get(-1).length !== 0)
  1004. throw new ScriptError('NULLFAIL', op, ip);
  1005. }
  1006. if (okey > 0)
  1007. okey -= 1;
  1008. stack.pop();
  1009. i -= 1;
  1010. }
  1011. if (stack.length < 1)
  1012. throw new ScriptError('INVALID_STACK_OPERATION', op, ip);
  1013. if (flags & Script.flags.VERIFY_NULLDUMMY) {
  1014. if (stack.get(-1).length !== 0)
  1015. throw new ScriptError('SIG_NULLDUMMY', op, ip);
  1016. }
  1017. stack.pop();
  1018. stack.pushBool(res);
  1019. if (op.value === opcodes.OP_CHECKMULTISIGVERIFY) {
  1020. if (!res)
  1021. throw new ScriptError('CHECKMULTISIGVERIFY', op, ip);
  1022. stack.pop();
  1023. }
  1024. break;
  1025. }
  1026. default: {
  1027. throw new ScriptError('BAD_OPCODE', op, ip);
  1028. }
  1029. }
  1030. if (stack.length + alt.length > consensus.MAX_SCRIPT_STACK)
  1031. throw new ScriptError('STACK_SIZE', op, ip);
  1032. }
  1033. if (state.length !== 0)
  1034. throw new ScriptError('UNBALANCED_CONDITIONAL');
  1035. }
  1036. /**
  1037. * Remove all matched data elements from
  1038. * a script's code (used to remove signatures
  1039. * before verification). Note that this
  1040. * compares and removes data on the _byte level_.
  1041. * It also reserializes the data to a single
  1042. * script with minimaldata encoding beforehand.
  1043. * A signature will _not_ be removed if it is
  1044. * not minimaldata.
  1045. * @see https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2014-November/006878.html
  1046. * @see https://test.webbtc.com/tx/19aa42fee0fa57c45d3b16488198b27caaacc4ff5794510d0c17f173f05587ff
  1047. * @param {Buffer} data - Data element to match against.
  1048. * @returns {Number} Total.
  1049. */
  1050. findAndDelete(data) {
  1051. const target = Opcode.fromPush(data);
  1052. if (this.raw.length < target.getSize())
  1053. return 0;
  1054. let found = false;
  1055. for (const op of this.code) {
  1056. if (op.value === -1)
  1057. break;
  1058. if (op.equals(target)) {
  1059. found = true;
  1060. break;
  1061. }
  1062. }
  1063. if (!found)
  1064. return 0;
  1065. const code = [];
  1066. let total = 0;
  1067. for (const op of this.code) {
  1068. if (op.value === -1)
  1069. break;
  1070. if (op.equals(target)) {
  1071. total += 1;
  1072. continue;
  1073. }
  1074. code.push(op);
  1075. }
  1076. this.code = code;
  1077. this.compile();
  1078. return total;
  1079. }
  1080. /**
  1081. * Find a data element in a script.
  1082. * @param {Buffer} data - Data element to match against.
  1083. * @returns {Number} Index (`-1` if not present).
  1084. */
  1085. indexOf(data) {
  1086. for (let i = 0; i < this.code.length; i++) {
  1087. const op = this.code[i];
  1088. if (op.value === -1)
  1089. break;
  1090. if (!op.data)
  1091. continue;
  1092. if (op.data.equals(data))
  1093. return i;
  1094. }
  1095. return -1;
  1096. }
  1097. /**
  1098. * Test a script to see if it is likely
  1099. * to be script code (no weird opcodes).
  1100. * @returns {Boolean}
  1101. */
  1102. isCode() {
  1103. for (const op of this.code) {
  1104. if (op.value === -1)
  1105. return false;
  1106. if (op.isDisabled())
  1107. return false;
  1108. switch (op.value) {
  1109. case opcodes.OP_RESERVED:
  1110. case opcodes.OP_NOP:
  1111. case opcodes.OP_VER:
  1112. case opcodes.OP_VERIF:
  1113. case opcodes.OP_VERNOTIF:
  1114. case opcodes.OP_RESERVED1:
  1115. case opcodes.OP_RESERVED2:
  1116. case opcodes.OP_NOP1:
  1117. return false;
  1118. }
  1119. if (op.value > opcodes.OP_CHECKSEQUENCEVERIFY)
  1120. return false;
  1121. }
  1122. return true;
  1123. }
  1124. /**
  1125. * Inject properties from a pay-to-pubkey script.
  1126. * @private
  1127. * @param {Buffer} key
  1128. */
  1129. fromPubkey(key) {
  1130. assert(Buffer.isBuffer(key) && (key.length === 33 || key.length === 65));
  1131. this.raw = Buffer.allocUnsafe(1 + key.length + 1);
  1132. this.raw[0] = key.length;
  1133. key.copy(this.raw, 1);
  1134. this.raw[1 + key.length] = opcodes.OP_CHECKSIG;
  1135. key = this.raw.slice(1, 1 + key.length);
  1136. this.code.length = 0;
  1137. this.code.push(Opcode.fromPush(key));
  1138. this.code.push(Opcode.fromOp(opcodes.OP_CHECKSIG));
  1139. return this;
  1140. }
  1141. /**
  1142. * Create a pay-to-pubkey script.
  1143. * @param {Buffer} key
  1144. * @returns {Script}
  1145. */
  1146. static fromPubkey(key) {
  1147. return new this().fromPubkey(key);
  1148. }
  1149. /**
  1150. * Inject properties from a pay-to-pubkeyhash script.
  1151. * @private
  1152. * @param {Buffer} hash
  1153. */
  1154. fromPubkeyhash(hash) {
  1155. assert(Buffer.isBuffer(hash) && hash.length === 20);
  1156. this.raw = Buffer.allocUnsafe(25);
  1157. this.raw[0] = opcodes.OP_DUP;
  1158. this.raw[1] = opcodes.OP_HASH160;
  1159. this.raw[2] = 0x14;
  1160. hash.copy(this.raw, 3);
  1161. this.raw[23] = opcodes.OP_EQUALVERIFY;
  1162. this.raw[24] = opcodes.OP_CHECKSIG;
  1163. hash = this.raw.slice(3, 23);
  1164. this.code.length = 0;
  1165. this.code.push(Opcode.fromOp(opcodes.OP_DUP));
  1166. this.code.push(Opcode.fromOp(opcodes.OP_HASH160));
  1167. this.code.push(Opcode.fromPush(hash));
  1168. this.code.push(Opcode.fromOp(opcodes.OP_EQUALVERIFY));
  1169. this.code.push(Opcode.fromOp(opcodes.OP_CHECKSIG));
  1170. return this;
  1171. }
  1172. /**
  1173. * Create a pay-to-pubkeyhash script.
  1174. * @param {Buffer} hash
  1175. * @returns {Script}
  1176. */
  1177. static fromPubkeyhash(hash) {
  1178. return new this().fromPubkeyhash(hash);
  1179. }
  1180. /**
  1181. * Inject properties from pay-to-multisig script.
  1182. * @private
  1183. * @param {Number} m
  1184. * @param {Number} n
  1185. * @param {Buffer[]} keys
  1186. */
  1187. fromMultisig(m, n, keys) {
  1188. assert((m & 0xff) === m && (n & 0xff) === n);
  1189. assert(Array.isArray(keys));
  1190. assert(keys.length === n, '`n` keys are required for multisig.');
  1191. assert(m >= 1 && m <= n);
  1192. assert(n >= 1 && n <= 15);
  1193. this.clear();
  1194. this.pushSmall(m);
  1195. for (const key of sortKeys(keys))
  1196. this.pushData(key);
  1197. this.pushSmall(n);
  1198. this.pushOp(opcodes.OP_CHECKMULTISIG);
  1199. return this.compile();
  1200. }
  1201. /**
  1202. * Create a pay-to-multisig script.
  1203. * @param {Number} m
  1204. * @param {Number} n
  1205. * @param {Buffer[]} keys
  1206. * @returns {Script}
  1207. */
  1208. static fromMultisig(m, n, keys) {
  1209. return new this().fromMultisig(m, n, keys);
  1210. }
  1211. /**
  1212. * Inject properties from a pay-to-scripthash script.
  1213. * @private
  1214. * @param {Buffer} hash
  1215. */
  1216. fromScripthash(hash) {
  1217. assert(Buffer.isBuffer(hash) && hash.length === 20);
  1218. this.raw = Buffer.allocUnsafe(23);
  1219. this.raw[0] = opcodes.OP_HASH160;
  1220. this.raw[1] = 0x14;
  1221. hash.copy(this.raw, 2);
  1222. this.raw[22] = opcodes.OP_EQUAL;
  1223. hash = this.raw.slice(2, 22);
  1224. this.code.length = 0;
  1225. this.code.push(Opcode.fromOp(opcodes.OP_HASH160));
  1226. this.code.push(Opcode.fromPush(hash));
  1227. this.code.push(Opcode.fromOp(opcodes.OP_EQUAL));
  1228. return this;
  1229. }
  1230. /**
  1231. * Create a pay-to-scripthash script.
  1232. * @param {Buffer} hash
  1233. * @returns {Script}
  1234. */
  1235. static fromScripthash(hash) {
  1236. return new this().fromScripthash(hash);
  1237. }
  1238. /**
  1239. * Inject properties from a nulldata/opreturn script.
  1240. * @private
  1241. * @param {Buffer} flags
  1242. */
  1243. fromNulldata(flags) {
  1244. assert(Buffer.isBuffer(flags));
  1245. assert(flags.length <= policy.MAX_OP_RETURN, 'Nulldata too large.');
  1246. this.clear();
  1247. this.pushOp(opcodes.OP_RETURN);
  1248. this.pushData(flags);
  1249. return this.compile();
  1250. }
  1251. /**
  1252. * Create a nulldata/opreturn script.
  1253. * @param {Buffer} flags
  1254. * @returns {Script}
  1255. */
  1256. static fromNulldata(flags) {
  1257. return new this().fromNulldata(flags);
  1258. }
  1259. /**
  1260. * Inject properties from a witness program.
  1261. * @private
  1262. * @param {Number} version
  1263. * @param {Buffer} data
  1264. */
  1265. fromProgram(version, data) {
  1266. assert((version & 0xff) === version && version >= 0 && version <= 16);
  1267. assert(Buffer.isBuffer(data) && data.length >= 2 && data.length <= 40);
  1268. this.raw = Buffer.allocUnsafe(2 + data.length);
  1269. this.raw[0] = version === 0 ? 0 : version + 0x50;
  1270. this.raw[1] = data.length;
  1271. data.copy(this.raw, 2);
  1272. data = this.raw.slice(2, 2 + data.length);
  1273. this.code.length = 0;
  1274. this.code.push(Opcode.fromSmall(version));
  1275. this.code.push(Opcode.fromPush(data));
  1276. return this;
  1277. }
  1278. /**
  1279. * Create a witness program.
  1280. * @param {Number} version
  1281. * @param {Buffer} data
  1282. * @returns {Script}
  1283. */
  1284. static fromProgram(version, data) {
  1285. return new this().fromProgram(version, data);
  1286. }
  1287. /**
  1288. * Inject properties from an address.
  1289. * @private
  1290. * @param {Address|AddressString} address
  1291. */
  1292. fromAddress(address) {
  1293. if (typeof address === 'string')
  1294. address = Address.fromString(address);
  1295. assert(address instanceof Address, 'Not an address.');
  1296. if (address.isPubkeyhash())
  1297. return this.fromPubkeyhash(address.hash);
  1298. if (address.isScripthash())
  1299. return this.fromScripthash(address.hash);
  1300. if (address.isProgram())
  1301. return this.fromProgram(address.version, address.hash);
  1302. throw new Error('Unknown address type.');
  1303. }
  1304. /**
  1305. * Create an output script from an address.
  1306. * @param {Address|AddressString} address
  1307. * @returns {Script}
  1308. */
  1309. static fromAddress(address) {
  1310. return new this().fromAddress(address);
  1311. }
  1312. /**
  1313. * Inject properties from a witness block commitment.
  1314. * @private
  1315. * @param {Buffer} hash
  1316. * @param {String|Buffer} flags
  1317. */
  1318. fromCommitment(hash, flags) {
  1319. const bw = bio.write(36);
  1320. bw.writeU32BE(0xaa21a9ed);
  1321. bw.writeHash(hash);
  1322. this.clear();
  1323. this.pushOp(opcodes.OP_RETURN);
  1324. this.pushData(bw.render());
  1325. if (flags)
  1326. this.pushData(flags);
  1327. return this.compile();
  1328. }
  1329. /**
  1330. * Create a witness block commitment.
  1331. * @param {Buffer} hash
  1332. * @param {String|Buffer} flags
  1333. * @returns {Script}
  1334. */
  1335. static fromCommitment(hash, flags) {
  1336. return new this().fromCommitment(hash, flags);
  1337. }
  1338. /**
  1339. * Grab and deserialize the redeem script.
  1340. * @returns {Script|null} Redeem script.
  1341. */
  1342. getRedeem() {
  1343. let data = null;
  1344. for (const op of this.code) {
  1345. if (op.value === -1)
  1346. return null;
  1347. if (op.value > opcodes.OP_16)
  1348. return null;
  1349. data = op.data;
  1350. }
  1351. if (!data)
  1352. return null;
  1353. return Script.fromRaw(data);
  1354. }
  1355. /**
  1356. * Get the standard script type.
  1357. * @returns {ScriptType}
  1358. */
  1359. getType() {
  1360. if (this.isPubkey())
  1361. return scriptTypes.PUBKEY;
  1362. if (this.isPubkeyhash())
  1363. return scriptTypes.PUBKEYHASH;
  1364. if (this.isScripthash())
  1365. return scriptTypes.SCRIPTHASH;
  1366. if (this.isWitnessPubkeyhash())
  1367. return scriptTypes.WITNESSPUBKEYHASH;
  1368. if (this.isWitnessScripthash())
  1369. return scriptTypes.WITNESSSCRIPTHASH;
  1370. if (this.isMultisig())
  1371. return scriptTypes.MULTISIG;
  1372. if (this.isNulldata())
  1373. return scriptTypes.NULLDATA;
  1374. return scriptTypes.NONSTANDARD;
  1375. }
  1376. /**
  1377. * Test whether a script is of an unknown/non-standard type.
  1378. * @returns {Boolean}
  1379. */
  1380. isUnknown() {
  1381. return this.getType() === scriptTypes.NONSTANDARD;
  1382. }
  1383. /**
  1384. * Test whether the script is standard by policy standards.
  1385. * @returns {Boolean}
  1386. */
  1387. isStandard() {
  1388. const [m, n] = this.getMultisig();
  1389. if (m !== -1) {
  1390. if (n < 1 || n > 3)
  1391. return false;
  1392. if (m < 1 || m > n)
  1393. return false;
  1394. return true;
  1395. }
  1396. if (this.isNulldata())
  1397. return this.raw.length <= policy.MAX_OP_RETURN_BYTES;
  1398. return this.getType() !== scriptTypes.NONSTANDARD;
  1399. }
  1400. /**
  1401. * Calculate the size of the script
  1402. * excluding the varint size bytes.
  1403. * @returns {Number}
  1404. */
  1405. getSize() {
  1406. return this.raw.length;
  1407. }
  1408. /**
  1409. * Calculate the size of the script
  1410. * including the varint size bytes.
  1411. * @returns {Number}
  1412. */
  1413. getVarSize() {
  1414. return encoding.sizeVarBytes(this.raw);
  1415. }
  1416. /**
  1417. * "Guess" the address of the input script.
  1418. * This method is not 100% reliable.
  1419. * @returns {Address|null}
  1420. */
  1421. getInputAddress() {
  1422. return Address.fromInputScript(this);
  1423. }
  1424. /**
  1425. * Get the address of the script if present. Note that
  1426. * pubkey and multisig scripts will be treated as though
  1427. * they are pubkeyhash and scripthashes respectively.
  1428. * @returns {Address|null}
  1429. */
  1430. getAddress() {
  1431. return Address.fromScript(this);
  1432. }
  1433. /**
  1434. * Get the hash160 of the raw script.
  1435. * @param {String?} enc
  1436. * @returns {Hash}
  1437. */
  1438. hash160(enc) {
  1439. let hash = hash160.digest(this.toRaw());
  1440. if (enc === 'hex')
  1441. hash = hash.toString('hex');
  1442. return hash;
  1443. }
  1444. /**
  1445. * Get the sha256 of the raw script.
  1446. * @param {String?} enc
  1447. * @returns {Hash}
  1448. */
  1449. sha256(enc) {
  1450. let hash = sha256.digest(this.toRaw());
  1451. if (enc === 'hex')
  1452. hash = hash.toString('hex');
  1453. return hash;
  1454. }
  1455. /**
  1456. * Test whether the output script is pay-to-pubkey.
  1457. * @param {Boolean} [minimal=false] - Minimaldata only.
  1458. * @returns {Boolean}
  1459. */
  1460. isPubkey(minimal) {
  1461. if (minimal) {
  1462. return this.raw.length >= 35
  1463. && (this.raw[0] === 33 || this.raw[0] === 65)
  1464. && this.raw[0] + 2 === this.raw.length
  1465. && this.raw[this.raw.length - 1] === opcodes.OP_CHECKSIG;
  1466. }
  1467. if (this.code.length !== 2)
  1468. return false;
  1469. const size = this.getLength(0);
  1470. return (size === 33 || size === 65)
  1471. && this.getOp(1) === opcodes.OP_CHECKSIG;
  1472. }
  1473. /**
  1474. * Get P2PK key if present.
  1475. * @param {Boolean} [minimal=false] - Minimaldata only.
  1476. * @returns {Buffer|null}
  1477. */
  1478. getPubkey(minimal) {
  1479. if (!this.isPubkey(minimal))
  1480. return null;
  1481. if (minimal)
  1482. return this.raw.slice(1, 1 + this.raw[0]);
  1483. return this.getData(0);
  1484. }
  1485. /**
  1486. * Test whether the output script is pay-to-pubkeyhash.
  1487. * @param {Boolean} [minimal=false] - Minimaldata only.
  1488. * @returns {Boolean}
  1489. */
  1490. isPubkeyhash(minimal) {
  1491. if (minimal || this.raw.length === 25) {
  1492. return this.raw.length === 25
  1493. && this.raw[0] === opcodes.OP_DUP
  1494. && this.raw[1] === opcodes.OP_HASH160
  1495. && this.raw[2] === 0x14
  1496. && this.raw[23] === opcodes.OP_EQUALVERIFY
  1497. && this.raw[24] === opcodes.OP_CHECKSIG;
  1498. }
  1499. if (this.code.length !== 5)
  1500. return false;
  1501. return this.getOp(0) === opcodes.OP_DUP
  1502. && this.getOp(1) === opcodes.OP_HASH160
  1503. && this.getLength(2) === 20
  1504. && this.getOp(3) === opcodes.OP_EQUALVERIFY
  1505. && this.getOp(4) === opcodes.OP_CHECKSIG;
  1506. }
  1507. /**
  1508. * Get P2PKH hash if present.
  1509. * @param {Boolean} [minimal=false] - Minimaldata only.
  1510. * @returns {Buffer|null}
  1511. */
  1512. getPubkeyhash(minimal) {
  1513. if (!this.isPubkeyhash(minimal))
  1514. return null;
  1515. if (minimal)
  1516. return this.raw.slice(3, 23);
  1517. return this.getData(2);
  1518. }
  1519. /**
  1520. * Test whether the output script is pay-to-multisig.
  1521. * @param {Boolean} [minimal=false] - Minimaldata only.
  1522. * @returns {Boolean}
  1523. */
  1524. isMultisig(minimal) {
  1525. if (this.code.length < 4 || this.code.length > 19)
  1526. return false;
  1527. if (this.getOp(-1) !== opcodes.OP_CHECKMULTISIG)
  1528. return false;
  1529. const m = this.getSmall(0);
  1530. if (m < 1)
  1531. return false;
  1532. const n = this.getSmall(-2);
  1533. if (n < 1 || m > n)
  1534. return false;
  1535. if (this.code.length !== n + 3)
  1536. return false;
  1537. for (let i = 1; i < n + 1; i++) {
  1538. const op = this.code[i];
  1539. const size = op.toLength();
  1540. if (size !== 33 && size !== 65)
  1541. return false;
  1542. if (minimal && !op.isMinimal())
  1543. return false;
  1544. }
  1545. return true;
  1546. }
  1547. /**
  1548. * Get multisig m and n values if present.
  1549. * @param {Boolean} [minimal=false] - Minimaldata only.
  1550. * @returns {Array} [m, n]
  1551. */
  1552. getMultisig(minimal) {
  1553. if (!this.isMultisig(minimal))
  1554. return [-1, -1];
  1555. return [this.getSmall(0), this.getSmall(-2)];
  1556. }
  1557. /**
  1558. * Test whether the output script is pay-to-scripthash. Note that
  1559. * bitcoin itself requires scripthashes to be in strict minimaldata
  1560. * encoding. Using `OP_HASH160 OP_PUSHDATA1 [hash] OP_EQUAL` will
  1561. * _not_ be recognized as a scripthash.
  1562. * @returns {Boolean}
  1563. */
  1564. isScripthash() {
  1565. return this.raw.length === 23
  1566. && this.raw[0] === opcodes.OP_HASH160
  1567. && this.raw[1] === 0x14
  1568. && this.raw[22] === opcodes.OP_EQUAL;
  1569. }
  1570. /**
  1571. * Get P2SH hash if present.
  1572. * @returns {Buffer|null}
  1573. */
  1574. getScripthash() {
  1575. if (!this.isScripthash())
  1576. return null;
  1577. return this.getData(1);
  1578. }
  1579. /**
  1580. * Test whether the output script is nulldata/opreturn.
  1581. * @param {Boolean} [minimal=false] - Minimaldata only.
  1582. * @returns {Boolean}
  1583. */
  1584. isNulldata(minimal) {
  1585. if (this.code.length === 0)
  1586. return false;
  1587. if (this.getOp(0) !== opcodes.OP_RETURN)
  1588. return false;
  1589. if (this.code.length === 1)
  1590. return true;
  1591. if (minimal) {
  1592. if (this.raw.length > policy.MAX_OP_RETURN_BYTES)
  1593. return false;
  1594. }
  1595. for (let i = 1; i < this.code.length; i++) {
  1596. const op = this.code[i];
  1597. if (op.value === -1)
  1598. return false;
  1599. if (op.value > opcodes.OP_16)
  1600. return false;
  1601. if (minimal && !op.isMinimal())
  1602. return false;
  1603. }
  1604. return true;
  1605. }
  1606. /**
  1607. * Get OP_RETURN data if present.
  1608. * @param {Boolean} [minimal=false] - Minimaldata only.
  1609. * @returns {Buffer|null}
  1610. */
  1611. getNulldata(minimal) {
  1612. if (!this.isNulldata(minimal))
  1613. return null;
  1614. for (let i = 1; i < this.code.length; i++) {
  1615. const op = this.code[i];
  1616. const data = op.toPush();
  1617. if (data)
  1618. return data;
  1619. }
  1620. return EMPTY_BUFFER;
  1621. }
  1622. /**
  1623. * Test whether the output script is a segregated witness
  1624. * commitment.
  1625. * @returns {Boolean}
  1626. */
  1627. isCommitment() {
  1628. return this.raw.length >= 38
  1629. && this.raw[0] === opcodes.OP_RETURN
  1630. && this.raw[1] === 0x24
  1631. && this.raw.readUInt32BE(2, true) === 0xaa21a9ed;
  1632. }
  1633. /**
  1634. * Get the commitment hash if present.
  1635. * @returns {Buffer|null}
  1636. */
  1637. getCommitment() {
  1638. if (!this.isCommitment())
  1639. return null;
  1640. return this.raw.slice(6, 38);
  1641. }
  1642. /**
  1643. * Test whether the output script is a witness program.
  1644. * Note that this will return true even for malformed
  1645. * witness v0 programs.
  1646. * @return {Boolean}
  1647. */
  1648. isProgram() {
  1649. if (this.raw.length < 4 || this.raw.length > 42)
  1650. return false;
  1651. if (this.raw[0] !== opcodes.OP_0
  1652. && (this.raw[0] < opcodes.OP_1 || this.raw[0] > opcodes.OP_16)) {
  1653. return false;
  1654. }
  1655. if (this.raw[1] + 2 !== this.raw.length)
  1656. return false;
  1657. return true;
  1658. }
  1659. /**
  1660. * Get the witness program if present.
  1661. * @returns {Program|null}
  1662. */
  1663. getProgram() {
  1664. if (!this.isProgram())
  1665. return null;
  1666. const version = this.getSmall(0);
  1667. const data = this.getData(1);
  1668. return new Program(version, data);
  1669. }
  1670. /**
  1671. * Get the script to the equivalent witness
  1672. * program (mimics bitcoind's scriptForWitness).
  1673. * @returns {Script|null}
  1674. */
  1675. forWitness() {
  1676. if (this.isProgram())
  1677. return this.clone();
  1678. const pk = this.getPubkey();
  1679. if (pk) {
  1680. const hash = hash160.digest(pk);
  1681. return Script.fromProgram(0, hash);
  1682. }
  1683. const pkh = this.getPubkeyhash();
  1684. if (pkh)
  1685. return Script.fromProgram(0, pkh);
  1686. return Script.fromProgram(0, this.sha256());
  1687. }
  1688. /**
  1689. * Test whether the output script is
  1690. * a pay-to-witness-pubkeyhash program.
  1691. * @returns {Boolean}
  1692. */
  1693. isWitnessPubkeyhash() {
  1694. return this.raw.length === 22
  1695. && this.raw[0] === opcodes.OP_0
  1696. && this.raw[1] === 0x14;
  1697. }
  1698. /**
  1699. * Get P2WPKH hash if present.
  1700. * @returns {Buffer|null}
  1701. */
  1702. getWitnessPubkeyhash() {
  1703. if (!this.isWitnessPubkeyhash())
  1704. return null;
  1705. return this.getData(1);
  1706. }
  1707. /**
  1708. * Test whether the output script is
  1709. * a pay-to-witness-scripthash program.
  1710. * @returns {Boolean}
  1711. */
  1712. isWitnessScripthash() {
  1713. return this.raw.length === 34
  1714. && this.raw[0] === opcodes.OP_0
  1715. && this.raw[1] === 0x20;
  1716. }
  1717. /**
  1718. * Get P2WSH hash if present.
  1719. * @returns {Buffer|null}
  1720. */
  1721. getWitnessScripthash() {
  1722. if (!this.isWitnessScripthash())
  1723. return null;
  1724. return this.getData(1);
  1725. }
  1726. /**
  1727. * Test whether the output script is unspendable.
  1728. * @returns {Boolean}
  1729. */
  1730. isUnspendable() {
  1731. if (this.raw.length > consensus.MAX_SCRIPT_SIZE)
  1732. return true;
  1733. return this.raw.length > 0 && this.raw[0] === opcodes.OP_RETURN;
  1734. }
  1735. /**
  1736. * "Guess" the type of the input script.
  1737. * This method is not 100% reliable.
  1738. * @returns {ScriptType}
  1739. */
  1740. getInputType() {
  1741. if (this.isPubkeyInput())
  1742. return scriptTypes.PUBKEY;
  1743. if (this.isPubkeyhashInput())
  1744. return scriptTypes.PUBKEYHASH;
  1745. if (this.isScripthashInput())
  1746. return scriptTypes.SCRIPTHASH;
  1747. if (this.isMultisigInput())
  1748. return scriptTypes.MULTISIG;
  1749. return scriptTypes.NONSTANDARD;
  1750. }
  1751. /**
  1752. * "Guess" whether the input script is an unknown/non-standard type.
  1753. * This method is not 100% reliable.
  1754. * @returns {Boolean}
  1755. */
  1756. isUnknownInput() {
  1757. return this.getInputType() === scriptTypes.NONSTANDARD;
  1758. }
  1759. /**
  1760. * "Guess" whether the input script is pay-to-pubkey.
  1761. * This method is not 100% reliable.
  1762. * @returns {Boolean}
  1763. */
  1764. isPubkeyInput() {
  1765. if (this.code.length !== 1)
  1766. return false;
  1767. const size = this.getLength(0);
  1768. return size >= 9 && size <= 73;
  1769. }
  1770. /**
  1771. * Get P2PK signature if present.
  1772. * @returns {Buffer|null}
  1773. */
  1774. getPubkeyInput() {
  1775. if (!this.isPubkeyInput())
  1776. return null;
  1777. return this.getData(0);
  1778. }
  1779. /**
  1780. * "Guess" whether the input script is pay-to-pubkeyhash.
  1781. * This method is not 100% reliable.
  1782. * @returns {Boolean}
  1783. */
  1784. isPubkeyhashInput() {
  1785. if (this.code.length !== 2)
  1786. return false;
  1787. const sig = this.getLength(0);
  1788. const key = this.getLength(1);
  1789. return sig >= 9 && sig <= 73
  1790. && (key === 33 || key === 65);
  1791. }
  1792. /**
  1793. * Get P2PKH signature and key if present.
  1794. * @returns {Array} [sig, key]
  1795. */
  1796. getPubkeyhashInput() {
  1797. if (!this.isPubkeyhashInput())
  1798. return [null, null];
  1799. return [this.getData(0), this.getData(1)];
  1800. }
  1801. /**
  1802. * "Guess" whether the input script is pay-to-multisig.
  1803. * This method is not 100% reliable.
  1804. * @returns {Boolean}
  1805. */
  1806. isMultisigInput() {
  1807. if (this.code.length < 2)
  1808. return false;
  1809. if (this.getOp(0) !== opcodes.OP_0)
  1810. return false;
  1811. if (this.getOp(1) > opcodes.OP_PUSHDATA4)
  1812. return false;
  1813. // We need to rule out scripthash
  1814. // because it may look like multisig.
  1815. if (this.isScripthashInput())
  1816. return false;
  1817. for (let i = 1; i < this.code.length; i++) {
  1818. const size = this.getLength(i);
  1819. if (size < 9 || size > 73)
  1820. return false;
  1821. }
  1822. return true;
  1823. }
  1824. /**
  1825. * Get multisig signatures if present.
  1826. * @returns {Buffer[]|null}
  1827. */
  1828. getMultisigInput() {
  1829. if (!this.isMultisigInput())
  1830. return null;
  1831. const sigs = [];
  1832. for (let i = 1; i < this.code.length; i++)
  1833. sigs.push(this.getData(i));
  1834. return sigs;
  1835. }
  1836. /**
  1837. * "Guess" whether the input script is pay-to-scripthash.
  1838. * This method is not 100% reliable.
  1839. * @returns {Boolean}
  1840. */
  1841. isScripthashInput() {
  1842. if (this.code.length < 1)
  1843. return false;
  1844. // Grab the raw redeem script.
  1845. const raw = this.getData(-1);
  1846. // Last data element should be an array
  1847. // for the redeem script.
  1848. if (!raw)
  1849. return false;
  1850. // Testing for scripthash inputs requires
  1851. // some evil magic to work. We do it by
  1852. // ruling things _out_. This test will not
  1853. // be correct 100% of the time. We rule
  1854. // out that the last data element is: a
  1855. // null dummy, a valid signature, a valid
  1856. // key, and we ensure that it is at least
  1857. // a script that does not use undefined
  1858. // opcodes.
  1859. if (raw.length === 0)
  1860. return false;
  1861. if (common.isSignatureEncoding(raw))
  1862. return false;
  1863. if (common.isKeyEncoding(raw))
  1864. return false;
  1865. const redeem = Script.fromRaw(raw);
  1866. if (!redeem.isCode())
  1867. return false;
  1868. if (redeem.isUnspendable())
  1869. return false;
  1870. if (!this.isPushOnly())
  1871. return false;
  1872. return true;
  1873. }
  1874. /**
  1875. * Get P2SH redeem script if present.
  1876. * @returns {Buffer|null}
  1877. */
  1878. getScripthashInput() {
  1879. if (!this.isScripthashInput())
  1880. return null;
  1881. return this.getData(-1);
  1882. }
  1883. /**
  1884. * Get coinbase height.
  1885. * @returns {Number} `-1` if not present.
  1886. */
  1887. getCoinbaseHeight() {
  1888. return Script.getCoinbaseHeight(this.raw);
  1889. }
  1890. /**
  1891. * Get coinbase height.
  1892. * @param {Buffer} raw - Raw script.
  1893. * @returns {Number} `-1` if not present.
  1894. */
  1895. static getCoinbaseHeight(raw) {
  1896. if (raw.length === 0)
  1897. return -1;
  1898. if (raw[0] >= opcodes.OP_1 && raw[0] <= opcodes.OP_16)
  1899. return raw[0] - 0x50;
  1900. if (raw[0] > 0x06)
  1901. return -1;
  1902. const op = Opcode.fromRaw(raw);
  1903. const num = op.toNum();
  1904. if (!num)
  1905. return 1;
  1906. if (num.isNeg())
  1907. return -1;
  1908. if (!op.equals(Opcode.fromNum(num)))
  1909. return -1;
  1910. return num.toDouble();
  1911. }
  1912. /**
  1913. * Test the script against a bloom filter.
  1914. * @param {Bloom} filter
  1915. * @returns {Boolean}
  1916. */
  1917. test(filter) {
  1918. for (const op of this.code) {
  1919. if (op.value === -1)
  1920. break;
  1921. if (!op.data || op.data.length === 0)
  1922. continue;
  1923. if (filter.test(op.data))
  1924. return true;
  1925. }
  1926. return false;
  1927. }
  1928. /**
  1929. * Test the script to see if it contains only push ops.
  1930. * Push ops are: OP_1NEGATE, OP_0-OP_16 and all PUSHDATAs.
  1931. * @returns {Boolean}
  1932. */
  1933. isPushOnly() {
  1934. for (const op of this.code) {
  1935. if (op.value === -1)
  1936. return false;
  1937. if (op.value > opcodes.OP_16)
  1938. return false;
  1939. }
  1940. return true;
  1941. }
  1942. /**
  1943. * Count the sigops in the script.
  1944. * @param {Boolean} accurate - Whether to enable accurate counting. This will
  1945. * take into account the `n` value for OP_CHECKMULTISIG(VERIFY).
  1946. * @returns {Number} sigop count
  1947. */
  1948. getSigops(accurate) {
  1949. let total = 0;
  1950. let lastOp = -1;
  1951. for (const op of this.code) {
  1952. if (op.value === -1)
  1953. break;
  1954. switch (op.value) {
  1955. case opcodes.OP_CHECKSIG:
  1956. case opcodes.OP_CHECKSIGVERIFY:
  1957. total += 1;
  1958. break;
  1959. case opcodes.OP_CHECKMULTISIG:
  1960. case opcodes.OP_CHECKMULTISIGVERIFY:
  1961. if (accurate && lastOp >= opcodes.OP_1 && lastOp <= opcodes.OP_16)
  1962. total += lastOp - 0x50;
  1963. else
  1964. total += consensus.MAX_MULTISIG_PUBKEYS;
  1965. break;
  1966. }
  1967. lastOp = op.value;
  1968. }
  1969. return total;
  1970. }
  1971. /**
  1972. * Count the sigops in the script, taking into account redeem scripts.
  1973. * @param {Script} input - Input script, needed for access to redeem script.
  1974. * @returns {Number} sigop count
  1975. */
  1976. getScripthashSigops(input) {
  1977. if (!this.isScripthash())
  1978. return this.getSigops(true);
  1979. const redeem = input.getRedeem();
  1980. if (!redeem)
  1981. return 0;
  1982. return redeem.getSigops(true);
  1983. }
  1984. /**
  1985. * Count the sigops in a script, taking into account witness programs.
  1986. * @param {Script} input
  1987. * @param {Witness} witness
  1988. * @returns {Number} sigop count
  1989. */
  1990. getWitnessSigops(input, witness) {
  1991. let program = this.getProgram();
  1992. if (!program) {
  1993. if (this.isScripthash()) {
  1994. const redeem = input.getRedeem();
  1995. if (redeem)
  1996. program = redeem.getProgram();
  1997. }
  1998. }
  1999. if (!program)
  2000. return 0;
  2001. if (program.version === 0) {
  2002. if (program.data.length === 20)
  2003. return 1;
  2004. if (program.data.length === 32 && witness.items.length > 0) {
  2005. const redeem = witness.getRedeem();
  2006. return redeem.getSigops(true);
  2007. }
  2008. }
  2009. return 0;
  2010. }
  2011. /*
  2012. * Mutation
  2013. */
  2014. get(index) {
  2015. if (index < 0)
  2016. index += this.code.length;
  2017. if (index < 0 || index >= this.code.length)
  2018. return null;
  2019. return this.code[index];
  2020. }
  2021. pop() {
  2022. const op = this.code.pop();
  2023. return op || null;
  2024. }
  2025. shift() {
  2026. const op = this.code.shift();
  2027. return op || null;
  2028. }
  2029. remove(index) {
  2030. if (index < 0)
  2031. index += this.code.length;
  2032. if (index < 0 || index >= this.code.length)
  2033. return null;
  2034. const items = this.code.splice(index, 1);
  2035. if (items.length === 0)
  2036. return null;
  2037. return items[0];
  2038. }
  2039. set(index, op) {
  2040. if (index < 0)
  2041. index += this.code.length;
  2042. assert(Opcode.isOpcode(op));
  2043. assert(index >= 0 && index <= this.code.length);
  2044. this.code[index] = op;
  2045. return this;
  2046. }
  2047. push(op) {
  2048. assert(Opcode.isOpcode(op));
  2049. this.code.push(op);
  2050. return this;
  2051. }
  2052. unshift(op) {
  2053. assert(Opcode.isOpcode(op));
  2054. this.code.unshift(op);
  2055. return this;
  2056. }
  2057. insert(index, op) {
  2058. if (index < 0)
  2059. index += this.code.length;
  2060. assert(Opcode.isOpcode(op));
  2061. assert(index >= 0 && index <= this.code.length);
  2062. this.code.splice(index, 0, op);
  2063. return this;
  2064. }
  2065. /*
  2066. * Op
  2067. */
  2068. getOp(index) {
  2069. const op = this.get(index);
  2070. return op ? op.value : -1;
  2071. }
  2072. popOp() {
  2073. const op = this.pop();
  2074. return op ? op.value : -1;
  2075. }
  2076. shiftOp() {
  2077. const op = this.shift();
  2078. return op ? op.value : -1;
  2079. }
  2080. removeOp(index) {
  2081. const op = this.remove(index);
  2082. return op ? op.value : -1;
  2083. }
  2084. setOp(index, value) {
  2085. return this.set(index, Opcode.fromOp(value));
  2086. }
  2087. pushOp(value) {
  2088. return this.push(Opcode.fromOp(value));
  2089. }
  2090. unshiftOp(value) {
  2091. return this.unshift(Opcode.fromOp(value));
  2092. }
  2093. insertOp(index, value) {
  2094. return this.insert(index, Opcode.fromOp(value));
  2095. }
  2096. /*
  2097. * Data
  2098. */
  2099. getData(index) {
  2100. const op = this.get(index);
  2101. return op ? op.data : null;
  2102. }
  2103. popData() {
  2104. const op = this.pop();
  2105. return op ? op.data : null;
  2106. }
  2107. shiftData() {
  2108. const op = this.shift();
  2109. return op ? op.data : null;
  2110. }
  2111. removeData(index) {
  2112. const op = this.remove(index);
  2113. return op ? op.data : null;
  2114. }
  2115. setData(index, data) {
  2116. return this.set(index, Opcode.fromData(data));
  2117. }
  2118. pushData(data) {
  2119. return this.push(Opcode.fromData(data));
  2120. }
  2121. unshiftData(data) {
  2122. return this.unshift(Opcode.fromData(data));
  2123. }
  2124. insertData(index, data) {
  2125. return this.insert(index, Opcode.fromData(data));
  2126. }
  2127. /*
  2128. * Length
  2129. */
  2130. getLength(index) {
  2131. const op = this.get(index);
  2132. return op ? op.toLength() : -1;
  2133. }
  2134. /*
  2135. * Push
  2136. */
  2137. getPush(index) {
  2138. const op = this.get(index);
  2139. return op ? op.toPush() : null;
  2140. }
  2141. popPush() {
  2142. const op = this.pop();
  2143. return op ? op.toPush() : null;
  2144. }
  2145. shiftPush() {
  2146. const op = this.shift();
  2147. return op ? op.toPush() : null;
  2148. }
  2149. removePush(index) {
  2150. const op = this.remove(index);
  2151. return op ? op.toPush() : null;
  2152. }
  2153. setPush(index, data) {
  2154. return this.set(index, Opcode.fromPush(data));
  2155. }
  2156. pushPush(data) {
  2157. return this.push(Opcode.fromPush(data));
  2158. }
  2159. unshiftPush(data) {
  2160. return this.unshift(Opcode.fromPush(data));
  2161. }
  2162. insertPush(index, data) {
  2163. return this.insert(index, Opcode.fromPush(data));
  2164. }
  2165. /*
  2166. * String
  2167. */
  2168. getString(index, enc) {
  2169. const op = this.get(index);
  2170. return op ? op.toString(enc) : null;
  2171. }
  2172. popString(enc) {
  2173. const op = this.pop();
  2174. return op ? op.toString(enc) : null;
  2175. }
  2176. shiftString(enc) {
  2177. const op = this.shift();
  2178. return op ? op.toString(enc) : null;
  2179. }
  2180. removeString(index, enc) {
  2181. const op = this.remove(index);
  2182. return op ? op.toString(enc) : null;
  2183. }
  2184. setString(index, str, enc) {
  2185. return this.set(index, Opcode.fromString(str, enc));
  2186. }
  2187. pushString(str, enc) {
  2188. return this.push(Opcode.fromString(str, enc));
  2189. }
  2190. unshiftString(str, enc) {
  2191. return this.unshift(Opcode.fromString(str, enc));
  2192. }
  2193. insertString(index, str, enc) {
  2194. return this.insert(index, Opcode.fromString(str, enc));
  2195. }
  2196. /*
  2197. * Small
  2198. */
  2199. getSmall(index) {
  2200. const op = this.get(index);
  2201. return op ? op.toSmall() : -1;
  2202. }
  2203. popSmall() {
  2204. const op = this.pop();
  2205. return op ? op.toSmall() : -1;
  2206. }
  2207. shiftSmall() {
  2208. const op = this.shift();
  2209. return op ? op.toSmall() : -1;
  2210. }
  2211. removeSmall(index) {
  2212. const op = this.remove(index);
  2213. return op ? op.toSmall() : -1;
  2214. }
  2215. setSmall(index, num) {
  2216. return this.set(index, Opcode.fromSmall(num));
  2217. }
  2218. pushSmall(num) {
  2219. return this.push(Opcode.fromSmall(num));
  2220. }
  2221. unshiftSmall(num) {
  2222. return this.unshift(Opcode.fromSmall(num));
  2223. }
  2224. insertSmall(index, num) {
  2225. return this.insert(index, Opcode.fromSmall(num));
  2226. }
  2227. /*
  2228. * Num
  2229. */
  2230. getNum(index, minimal, limit) {
  2231. const op = this.get(index);
  2232. return op ? op.toNum(minimal, limit) : null;
  2233. }
  2234. popNum(minimal, limit) {
  2235. const op = this.pop();
  2236. return op ? op.toNum(minimal, limit) : null;
  2237. }
  2238. shiftNum(minimal, limit) {
  2239. const op = this.shift();
  2240. return op ? op.toNum(minimal, limit) : null;
  2241. }
  2242. removeNum(index, minimal, limit) {
  2243. const op = this.remove(index);
  2244. return op ? op.toNum(minimal, limit) : null;
  2245. }
  2246. setNum(index, num) {
  2247. return this.set(index, Opcode.fromNum(num));
  2248. }
  2249. pushNum(num) {
  2250. return this.push(Opcode.fromNum(num));
  2251. }
  2252. unshiftNum(num) {
  2253. return this.unshift(Opcode.fromNum(num));
  2254. }
  2255. insertNum(index, num) {
  2256. return this.insert(index, Opcode.fromNum(num));
  2257. }
  2258. /*
  2259. * Int
  2260. */
  2261. getInt(index, minimal, limit) {
  2262. const op = this.get(index);
  2263. return op ? op.toInt(minimal, limit) : -1;
  2264. }
  2265. popInt(minimal, limit) {
  2266. const op = this.pop();
  2267. return op ? op.toInt(minimal, limit) : -1;
  2268. }
  2269. shiftInt(minimal, limit) {
  2270. const op = this.shift();
  2271. return op ? op.toInt(minimal, limit) : -1;
  2272. }
  2273. removeInt(index, minimal, limit) {
  2274. const op = this.remove(index);
  2275. return op ? op.toInt(minimal, limit) : -1;
  2276. }
  2277. setInt(index, num) {
  2278. return this.set(index, Opcode.fromInt(num));
  2279. }
  2280. pushInt(num) {
  2281. return this.push(Opcode.fromInt(num));
  2282. }
  2283. unshiftInt(num) {
  2284. return this.unshift(Opcode.fromInt(num));
  2285. }
  2286. insertInt(index, num) {
  2287. return this.insert(index, Opcode.fromInt(num));
  2288. }
  2289. /*
  2290. * Bool
  2291. */
  2292. getBool(index) {
  2293. const op = this.get(index);
  2294. return op ? op.toBool() : false;
  2295. }
  2296. popBool() {
  2297. const op = this.pop();
  2298. return op ? op.toBool() : false;
  2299. }
  2300. shiftBool() {
  2301. const op = this.shift();
  2302. return op ? op.toBool() : false;
  2303. }
  2304. removeBool(index) {
  2305. const op = this.remove(index);
  2306. return op ? op.toBool() : false;
  2307. }
  2308. setBool(index, value) {
  2309. return this.set(index, Opcode.fromBool(value));
  2310. }
  2311. pushBool(value) {
  2312. return this.push(Opcode.fromBool(value));
  2313. }
  2314. unshiftBool(value) {
  2315. return this.unshift(Opcode.fromBool(value));
  2316. }
  2317. insertBool(index, value) {
  2318. return this.insert(index, Opcode.fromBool(value));
  2319. }
  2320. /*
  2321. * Symbol
  2322. */
  2323. getSym(index) {
  2324. const op = this.get(index);
  2325. return op ? op.toSymbol() : null;
  2326. }
  2327. popSym() {
  2328. const op = this.pop();
  2329. return op ? op.toSymbol() : null;
  2330. }
  2331. shiftSym() {
  2332. const op = this.shift();
  2333. return op ? op.toSymbol() : null;
  2334. }
  2335. removeSym(index) {
  2336. const op = this.remove(index);
  2337. return op ? op.toSymbol() : null;
  2338. }
  2339. setSym(index, symbol) {
  2340. return this.set(index, Opcode.fromSymbol(symbol));
  2341. }
  2342. pushSym(symbol) {
  2343. return this.push(Opcode.fromSymbol(symbol));
  2344. }
  2345. unshiftSym(symbol) {
  2346. return this.unshift(Opcode.fromSymbol(symbol));
  2347. }
  2348. insertSym(index, symbol) {
  2349. return this.insert(index, Opcode.fromSymbol(symbol));
  2350. }
  2351. /**
  2352. * Inject properties from bitcoind test string.
  2353. * @private
  2354. * @param {String} items - Script string.
  2355. * @throws Parse error.
  2356. */
  2357. fromString(code) {
  2358. assert(typeof code === 'string');
  2359. code = code.trim();
  2360. if (code.length === 0)
  2361. return this;
  2362. const items = code.split(/\s+/);
  2363. const bw = bio.write();
  2364. for (const item of items) {
  2365. let symbol = item;
  2366. if (symbol.charCodeAt(0) & 32)
  2367. symbol = symbol.toUpperCase();
  2368. if (!/^OP_/.test(symbol))
  2369. symbol = `OP_${symbol}`;
  2370. const value = opcodes[symbol];
  2371. if (value == null) {
  2372. if (item[0] === '\'') {
  2373. assert(item[item.length - 1] === '\'', 'Invalid string.');
  2374. const str = item.slice(1, -1);
  2375. const op = Opcode.fromString(str);
  2376. bw.writeBytes(op.toRaw());
  2377. continue;
  2378. }
  2379. if (/^-?\d+$/.test(item)) {
  2380. const num = ScriptNum.fromString(item, 10);
  2381. const op = Opcode.fromNum(num);
  2382. bw.writeBytes(op.toRaw());
  2383. continue;
  2384. }
  2385. assert(item.indexOf('0x') === 0, 'Unknown opcode.');
  2386. const hex = item.substring(2);
  2387. const data = Buffer.from(hex, 'hex');
  2388. assert(data.length === hex.length / 2, 'Invalid hex string.');
  2389. bw.writeBytes(data);
  2390. continue;
  2391. }
  2392. bw.writeU8(value);
  2393. }
  2394. return this.fromRaw(bw.render());
  2395. }
  2396. /**
  2397. * Parse a bitcoind test script
  2398. * string into a script object.
  2399. * @param {String} items - Script string.
  2400. * @returns {Script}
  2401. * @throws Parse error.
  2402. */
  2403. static fromString(code) {
  2404. return new this().fromString(code);
  2405. }
  2406. /**
  2407. * Verify an input and output script, and a witness if present.
  2408. * @param {Script} input
  2409. * @param {Witness} witness
  2410. * @param {Script} output
  2411. * @param {TX} tx
  2412. * @param {Number} index
  2413. * @param {Amount} value
  2414. * @param {VerifyFlags} flags
  2415. * @throws {ScriptError}
  2416. */
  2417. static verify(input, witness, output, tx, index, value, flags) {
  2418. if (flags == null)
  2419. flags = Script.flags.STANDARD_VERIFY_FLAGS;
  2420. if (flags & Script.flags.VERIFY_SIGPUSHONLY) {
  2421. if (!input.isPushOnly())
  2422. throw new ScriptError('SIG_PUSHONLY');
  2423. }
  2424. // Setup a stack.
  2425. let stack = new Stack();
  2426. // Execute the input script
  2427. input.execute(stack, flags, tx, index, value, 0);
  2428. // Copy the stack for P2SH
  2429. let copy;
  2430. if (flags & Script.flags.VERIFY_P2SH)
  2431. copy = stack.clone();
  2432. // Execute the previous output script.
  2433. output.execute(stack, flags, tx, index, value, 0);
  2434. // Verify the stack values.
  2435. if (stack.length === 0 || !stack.getBool(-1))
  2436. throw new ScriptError('EVAL_FALSE');
  2437. let hadWitness = false;
  2438. if ((flags & Script.flags.VERIFY_WITNESS) && output.isProgram()) {
  2439. hadWitness = true;
  2440. // Input script must be empty.
  2441. if (input.raw.length !== 0)
  2442. throw new ScriptError('WITNESS_MALLEATED');
  2443. // Verify the program in the output script.
  2444. Script.verifyProgram(witness, output, flags, tx, index, value);
  2445. // Force a cleanstack
  2446. stack.length = 1;
  2447. }
  2448. // If the script is P2SH, execute the real output script
  2449. if ((flags & Script.flags.VERIFY_P2SH) && output.isScripthash()) {
  2450. // P2SH can only have push ops in the scriptSig
  2451. if (!input.isPushOnly())
  2452. throw new ScriptError('SIG_PUSHONLY');
  2453. // Reset the stack
  2454. stack = copy;
  2455. // Stack should not be empty at this point
  2456. if (stack.length === 0)
  2457. throw new ScriptError('EVAL_FALSE');
  2458. // Grab the real redeem script
  2459. const raw = stack.pop();
  2460. const redeem = Script.fromRaw(raw);
  2461. // Execute the redeem script.
  2462. redeem.execute(stack, flags, tx, index, value, 0);
  2463. // Verify the the stack values.
  2464. if (stack.length === 0 || !stack.getBool(-1))
  2465. throw new ScriptError('EVAL_FALSE');
  2466. if ((flags & Script.flags.VERIFY_WITNESS) && redeem.isProgram()) {
  2467. hadWitness = true;
  2468. // Input script must be exactly one push of the redeem script.
  2469. if (!input.raw.equals(Opcode.fromPush(raw).toRaw()))
  2470. throw new ScriptError('WITNESS_MALLEATED_P2SH');
  2471. // Verify the program in the redeem script.
  2472. Script.verifyProgram(witness, redeem, flags, tx, index, value);
  2473. // Force a cleanstack.
  2474. stack.length = 1;
  2475. }
  2476. }
  2477. // Ensure there is nothing left on the stack.
  2478. if (flags & Script.flags.VERIFY_CLEANSTACK) {
  2479. assert((flags & Script.flags.VERIFY_P2SH) !== 0);
  2480. if (stack.length !== 1)
  2481. throw new ScriptError('CLEANSTACK');
  2482. }
  2483. // If we had a witness but no witness program, fail.
  2484. if (flags & Script.flags.VERIFY_WITNESS) {
  2485. assert((flags & Script.flags.VERIFY_P2SH) !== 0);
  2486. if (!hadWitness && witness.items.length > 0)
  2487. throw new ScriptError('WITNESS_UNEXPECTED');
  2488. }
  2489. }
  2490. /**
  2491. * Verify a witness program. This runs after regular script
  2492. * execution if a witness program is present. It will convert
  2493. * the witness to a stack and execute the program.
  2494. * @param {Witness} witness
  2495. * @param {Script} output
  2496. * @param {VerifyFlags} flags
  2497. * @param {TX} tx
  2498. * @param {Number} index
  2499. * @param {Amount} value
  2500. * @throws {ScriptError}
  2501. */
  2502. static verifyProgram(witness, output, flags, tx, index, value) {
  2503. const program = output.getProgram();
  2504. assert(program, 'verifyProgram called on non-witness-program.');
  2505. assert((flags & Script.flags.VERIFY_WITNESS) !== 0);
  2506. const stack = witness.toStack();
  2507. let redeem;
  2508. if (program.version === 0) {
  2509. if (program.data.length === 32) {
  2510. if (stack.length === 0)
  2511. throw new ScriptError('WITNESS_PROGRAM_WITNESS_EMPTY');
  2512. const witnessScript = stack.pop();
  2513. if (!sha256.digest(witnessScript).equals(program.data))
  2514. throw new ScriptError('WITNESS_PROGRAM_MISMATCH');
  2515. redeem = Script.fromRaw(witnessScript);
  2516. } else if (program.data.length === 20) {
  2517. if (stack.length !== 2)
  2518. throw new ScriptError('WITNESS_PROGRAM_MISMATCH');
  2519. redeem = Script.fromPubkeyhash(program.data);
  2520. } else {
  2521. // Failure on version=0 (bad program data length).
  2522. throw new ScriptError('WITNESS_PROGRAM_WRONG_LENGTH');
  2523. }
  2524. } else {
  2525. // Anyone can spend (we can return true here
  2526. // if we want to always relay these transactions).
  2527. // Otherwise, if we want to act like an "old"
  2528. // implementation and only accept them in blocks,
  2529. // we can use the regular output script which will
  2530. // succeed in a block, but fail in the mempool
  2531. // due to VERIFY_CLEANSTACK.
  2532. if (flags & Script.flags.VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)
  2533. throw new ScriptError('DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM');
  2534. return;
  2535. }
  2536. // Witnesses still have push limits.
  2537. for (let j = 0; j < stack.length; j++) {
  2538. if (stack.get(j).length > consensus.MAX_SCRIPT_PUSH)
  2539. throw new ScriptError('PUSH_SIZE');
  2540. }
  2541. // Verify the redeem script.
  2542. redeem.execute(stack, flags, tx, index, value, 1);
  2543. // Verify the stack values.
  2544. if (stack.length !== 1)
  2545. throw new ScriptError('CLEANSTACK');
  2546. if (!stack.getBool(-1))
  2547. throw new ScriptError('EVAL_FALSE');
  2548. }
  2549. /**
  2550. * Inject properties from buffer reader.
  2551. * @private
  2552. * @param {BufferReader} br
  2553. */
  2554. fromReader(br) {
  2555. return this.fromRaw(br.readVarBytes());
  2556. }
  2557. /**
  2558. * Inject properties from serialized data.
  2559. * @private
  2560. * @param {Buffer}
  2561. */
  2562. fromRaw(data) {
  2563. const br = bio.read(data);
  2564. this.raw = data;
  2565. while (br.left())
  2566. this.code.push(Opcode.fromReader(br));
  2567. return this;
  2568. }
  2569. /**
  2570. * Create a script from buffer reader.
  2571. * @param {BufferReader} br
  2572. * @param {String?} enc - Either `"hex"` or `null`.
  2573. * @returns {Script}
  2574. */
  2575. static fromReader(br) {
  2576. return new this().fromReader(br);
  2577. }
  2578. /**
  2579. * Create a script from a serialized buffer.
  2580. * @param {Buffer|String} data - Serialized script.
  2581. * @param {String?} enc - Either `"hex"` or `null`.
  2582. * @returns {Script}
  2583. */
  2584. static fromRaw(data, enc) {
  2585. if (typeof data === 'string')
  2586. data = Buffer.from(data, enc);
  2587. return new this().fromRaw(data);
  2588. }
  2589. /**
  2590. * Test whether an object a Script.
  2591. * @param {Object} obj
  2592. * @returns {Boolean}
  2593. */
  2594. static isScript(obj) {
  2595. return obj instanceof Script;
  2596. }
  2597. }
  2598. /**
  2599. * Script opcodes.
  2600. * @enum {Number}
  2601. * @default
  2602. */
  2603. Script.opcodes = common.opcodes;
  2604. /**
  2605. * Opcodes by value.
  2606. * @const {RevMap}
  2607. */
  2608. Script.opcodesByVal = common.opcodesByVal;
  2609. /**
  2610. * Script and locktime flags. See {@link VerifyFlags}.
  2611. * @enum {Number}
  2612. */
  2613. Script.flags = common.flags;
  2614. /**
  2615. * Sighash Types.
  2616. * @enum {SighashType}
  2617. * @default
  2618. */
  2619. Script.hashType = common.hashType;
  2620. /**
  2621. * Sighash types by value.
  2622. * @const {RevMap}
  2623. */
  2624. Script.hashTypeByVal = common.hashTypeByVal;
  2625. /**
  2626. * Output script types.
  2627. * @enum {Number}
  2628. */
  2629. Script.types = common.types;
  2630. /**
  2631. * Output script types by value.
  2632. * @const {RevMap}
  2633. */
  2634. Script.typesByVal = common.typesByVal;
  2635. /*
  2636. * Helpers
  2637. */
  2638. function sortKeys(keys) {
  2639. return keys.slice().sort((a, b) => {
  2640. return a.compare(b);
  2641. });
  2642. }
  2643. /**
  2644. * Test whether the data element is a valid key if VERIFY_STRICTENC is enabled.
  2645. * @param {Buffer} key
  2646. * @param {VerifyFlags?} flags
  2647. * @returns {Boolean}
  2648. * @throws {ScriptError}
  2649. */
  2650. function validateKey(key, flags, version) {
  2651. assert(Buffer.isBuffer(key));
  2652. assert(typeof flags === 'number');
  2653. assert(typeof version === 'number');
  2654. if (flags & Script.flags.VERIFY_STRICTENC) {
  2655. if (!common.isKeyEncoding(key))
  2656. throw new ScriptError('PUBKEYTYPE');
  2657. }
  2658. if (version === 1) {
  2659. if (flags & Script.flags.VERIFY_WITNESS_PUBKEYTYPE) {
  2660. if (!common.isCompressedEncoding(key))
  2661. throw new ScriptError('WITNESS_PUBKEYTYPE');
  2662. }
  2663. }
  2664. return true;
  2665. }
  2666. /**
  2667. * Test whether the data element is a valid signature based
  2668. * on the encoding, S value, and sighash type. Requires
  2669. * VERIFY_DERSIG|VERIFY_LOW_S|VERIFY_STRICTENC, VERIFY_LOW_S
  2670. * and VERIFY_STRING_ENC to be enabled respectively. Note that
  2671. * this will allow zero-length signatures.
  2672. * @param {Buffer} sig
  2673. * @param {VerifyFlags?} flags
  2674. * @returns {Boolean}
  2675. * @throws {ScriptError}
  2676. */
  2677. function validateSignature(sig, flags) {
  2678. assert(Buffer.isBuffer(sig));
  2679. assert(typeof flags === 'number');
  2680. // Allow empty sigs
  2681. if (sig.length === 0)
  2682. return true;
  2683. if ((flags & Script.flags.VERIFY_DERSIG)
  2684. || (flags & Script.flags.VERIFY_LOW_S)
  2685. || (flags & Script.flags.VERIFY_STRICTENC)) {
  2686. if (!common.isSignatureEncoding(sig))
  2687. throw new ScriptError('SIG_DER');
  2688. }
  2689. if (flags & Script.flags.VERIFY_LOW_S) {
  2690. if (!common.isLowDER(sig))
  2691. throw new ScriptError('SIG_HIGH_S');
  2692. }
  2693. if (flags & Script.flags.VERIFY_STRICTENC) {
  2694. if (!common.isHashType(sig))
  2695. throw new ScriptError('SIG_HASHTYPE');
  2696. }
  2697. return true;
  2698. }
  2699. /**
  2700. * Verify a signature, taking into account sighash type.
  2701. * @param {Buffer} msg - Signature hash.
  2702. * @param {Buffer} sig
  2703. * @param {Buffer} key
  2704. * @returns {Boolean}
  2705. */
  2706. function checksig(msg, sig, key) {
  2707. return secp256k1.verifyDER(msg, sig.slice(0, -1), key);
  2708. }
  2709. /*
  2710. * Expose
  2711. */
  2712. module.exports = Script;