bsv2 2.0.23 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/{.babelrc.test → .babel.test} +1 -1
  2. package/.husky/pre-commit +1 -1
  3. package/.mocharc.yml +1 -1
  4. package/.travis.yml +1 -1
  5. package/babel.config.cjs +44 -0
  6. package/benchmark.js +10 -18
  7. package/bin/bsv.js +1 -1
  8. package/bin/network.js +2 -1
  9. package/dist/bsv2.mjs +36061 -4
  10. package/dist/bsv2.umd.js +28 -0
  11. package/doc/assets/anchor.js +350 -0
  12. package/doc/assets/bass-addons.css +12 -0
  13. package/doc/assets/bass.css +544 -0
  14. package/doc/assets/fonts/EOT/SourceCodePro-Bold.eot +0 -0
  15. package/doc/assets/fonts/EOT/SourceCodePro-Regular.eot +0 -0
  16. package/doc/assets/fonts/LICENSE.txt +93 -0
  17. package/doc/assets/fonts/OTF/SourceCodePro-Bold.otf +0 -0
  18. package/doc/assets/fonts/OTF/SourceCodePro-Regular.otf +0 -0
  19. package/doc/assets/fonts/TTF/SourceCodePro-Bold.ttf +0 -0
  20. package/doc/assets/fonts/TTF/SourceCodePro-Regular.ttf +0 -0
  21. package/doc/assets/fonts/WOFF/OTF/SourceCodePro-Bold.otf.woff +0 -0
  22. package/doc/assets/fonts/WOFF/OTF/SourceCodePro-Regular.otf.woff +0 -0
  23. package/doc/assets/fonts/WOFF/TTF/SourceCodePro-Bold.ttf.woff +0 -0
  24. package/doc/assets/fonts/WOFF/TTF/SourceCodePro-Regular.ttf.woff +0 -0
  25. package/doc/assets/fonts/WOFF2/OTF/SourceCodePro-Bold.otf.woff2 +0 -0
  26. package/doc/assets/fonts/WOFF2/OTF/SourceCodePro-Regular.otf.woff2 +0 -0
  27. package/doc/assets/fonts/WOFF2/TTF/SourceCodePro-Bold.ttf.woff2 +0 -0
  28. package/doc/assets/fonts/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2 +0 -0
  29. package/doc/assets/fonts/source-code-pro.css +23 -0
  30. package/doc/assets/github.css +123 -0
  31. package/doc/assets/site.js +168 -0
  32. package/doc/assets/split.css +15 -0
  33. package/doc/assets/split.js +782 -0
  34. package/doc/assets/style.css +147 -0
  35. package/doc/index.html +9461 -0
  36. package/entry.js +2 -3
  37. package/eslint.config.mjs +8 -0
  38. package/index.js +1 -5
  39. package/{karma.conf.js → karma.conf.ts} +2 -3
  40. package/lib/ach.js +5 -5
  41. package/lib/address.js +11 -9
  42. package/lib/aescbc.js +3 -3
  43. package/lib/bip-39.js +12 -11
  44. package/lib/block.js +2 -2
  45. package/lib/bn.js +12 -17
  46. package/lib/bsm.js +1 -1
  47. package/lib/config.js +1 -1
  48. package/lib/constants.js +1 -1
  49. package/lib/ecdsa.js +24 -23
  50. package/lib/interp.js +190 -26
  51. package/lib/merkle.js +1 -1
  52. package/lib/op-code.js +137 -135
  53. package/lib/priv-key.js +1 -1
  54. package/lib/script.js +44 -42
  55. package/lib/sig.js +12 -12
  56. package/lib/struct.js +9 -6
  57. package/lib/tx.js +8 -7
  58. package/load-babel.js +3 -1
  59. package/mtest/test.html +6 -4
  60. package/mtest/test.js +1 -1
  61. package/out/Sig.html +541 -0
  62. package/out/bip-32.js.html +523 -0
  63. package/out/bip-39.js.html +336 -0
  64. package/out/block.js.html +183 -0
  65. package/out/bn.js.html +512 -0
  66. package/out/ecdsa.js.html +546 -0
  67. package/out/fonts/OpenSans-Bold-webfont.eot +0 -0
  68. package/out/fonts/OpenSans-Bold-webfont.svg +1830 -0
  69. package/out/fonts/OpenSans-Bold-webfont.woff +0 -0
  70. package/out/fonts/OpenSans-BoldItalic-webfont.eot +0 -0
  71. package/out/fonts/OpenSans-BoldItalic-webfont.svg +1830 -0
  72. package/out/fonts/OpenSans-BoldItalic-webfont.woff +0 -0
  73. package/out/fonts/OpenSans-Italic-webfont.eot +0 -0
  74. package/out/fonts/OpenSans-Italic-webfont.svg +1830 -0
  75. package/out/fonts/OpenSans-Italic-webfont.woff +0 -0
  76. package/out/fonts/OpenSans-Light-webfont.eot +0 -0
  77. package/out/fonts/OpenSans-Light-webfont.svg +1831 -0
  78. package/out/fonts/OpenSans-Light-webfont.woff +0 -0
  79. package/out/fonts/OpenSans-LightItalic-webfont.eot +0 -0
  80. package/out/fonts/OpenSans-LightItalic-webfont.svg +1835 -0
  81. package/out/fonts/OpenSans-LightItalic-webfont.woff +0 -0
  82. package/out/fonts/OpenSans-Regular-webfont.eot +0 -0
  83. package/out/fonts/OpenSans-Regular-webfont.svg +1831 -0
  84. package/out/fonts/OpenSans-Regular-webfont.woff +0 -0
  85. package/out/global.html +220 -0
  86. package/out/index.html +128 -0
  87. package/out/interp.js.html +2064 -0
  88. package/out/merkle.js.html +143 -0
  89. package/out/msg.js.html +235 -0
  90. package/out/priv-key.js.html +208 -0
  91. package/out/pub-key.js.html +281 -0
  92. package/out/script.js.html +876 -0
  93. package/out/scripts/linenumber.js +25 -0
  94. package/out/scripts/prettify/Apache-License-2.0.txt +202 -0
  95. package/out/scripts/prettify/lang-css.js +2 -0
  96. package/out/scripts/prettify/prettify.js +28 -0
  97. package/out/sig-operations.js.html +171 -0
  98. package/out/sig.js.html +450 -0
  99. package/out/struct.js.html +440 -0
  100. package/out/styles/jsdoc-default.css +358 -0
  101. package/out/styles/prettify-jsdoc.css +111 -0
  102. package/out/styles/prettify-tomorrow.css +132 -0
  103. package/out/tx-builder.js.html +644 -0
  104. package/out/tx-in.js.html +223 -0
  105. package/out/tx-verifier.js.html +260 -0
  106. package/out/tx.js.html +481 -0
  107. package/package.json +34 -39
  108. package/vite.config.js +36 -0
  109. package/dist/bsv2.bundle.js +0 -8
  110. package/dist/bsv2.cjs.js +0 -2
  111. package/dist/bsv2.cjs.js.LICENSE.txt +0 -1
  112. package/dist/bsv2.module.js +0 -2
  113. /package/{webpack.config.js → mtest/webpack.config.js} +0 -0
@@ -0,0 +1,2064 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>JSDoc: Source: interp.js</title>
6
+
7
+ <script src="scripts/prettify/prettify.js"> </script>
8
+ <script src="scripts/prettify/lang-css.js"> </script>
9
+ <!--[if lt IE 9]>
10
+ <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
11
+ <![endif]-->
12
+ <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
13
+ <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
14
+ </head>
15
+
16
+ <body>
17
+
18
+ <div id="main">
19
+
20
+ <h1 class="page-title">Source: interp.js</h1>
21
+
22
+
23
+
24
+
25
+
26
+
27
+ <section>
28
+ <article>
29
+ <pre class="prettyprint source linenums"><code>/**
30
+ * Script Interpreter
31
+ * ==================
32
+ *
33
+ * Bitcoin transactions contain scripts. Each input has a script called the
34
+ * scriptSig, and each output has a script called the scriptPubKey. To validate
35
+ * an input, the ScriptSig is executed, then with the same stack, the
36
+ * scriptPubKey from the output corresponding to that input is run. The primary
37
+ * way to use this class is via the verify function:
38
+ *
39
+ * new Interp().verify( ... )
40
+ *
41
+ * In some ways, the script interpreter is one of the most poorly architected
42
+ * components of Yours Bitcoin because of the giant switch statement in step(). But
43
+ * that is deliberately so to make it similar to bitcoin core, and thus easier
44
+ * to audit.
45
+ */
46
+ 'use strict'
47
+
48
+ import { Br } from './br'
49
+ import { Bn } from './bn'
50
+ import { Bw } from './bw'
51
+ import { cmp } from './cmp'
52
+ import { Hash } from './hash'
53
+ import { OpCode } from './op-code'
54
+ import { PubKey } from './pub-key'
55
+ import { Script } from './script'
56
+ import { Sig } from './sig'
57
+ import { Struct } from './struct'
58
+ import { Tx } from './tx'
59
+ import { TxIn } from './tx-in'
60
+ import { Ecdsa } from './ecdsa'
61
+
62
+
63
+ const minimallyEncode = (buf) => {
64
+ if (buf.length === 0) {
65
+ return buf
66
+ }
67
+
68
+ // If the last byte is not 0x00 or 0x80, we are minimally encoded.
69
+ const last = buf[buf.length - 1]
70
+ if ((last &amp; 0x7f) !== 0) {
71
+ return buf
72
+ }
73
+
74
+ // If the script is one byte long, then we have a zero, which encodes as an
75
+ // empty array.
76
+ if (buf.length === 1) {
77
+ return []
78
+ }
79
+
80
+ // If the next byte has it sign bit set, then we are minimaly encoded.
81
+ if ((buf[buf.length - 2] &amp; 0x80) !== 0) {
82
+ return buf
83
+ }
84
+
85
+ // We are not minimally encoded, we need to figure out how much to trim.
86
+ for (let i = buf.length - 1; i > 0; i--) {
87
+ // We found a non zero byte, time to encode.
88
+ if (buf[i - 1] !== 0) {
89
+ if ((buf[i - 1] &amp; 0x80) !== 0) {
90
+ // We found a byte with it sign bit set so we need one more
91
+ // byte.
92
+ buf[i] = last
93
+ return buf.slice(0, i + 1)
94
+ } else {
95
+ // the sign bit is clear, we can use it.
96
+ buf[i - 1] |= last
97
+ return buf.slice(0, i)
98
+ }
99
+ }
100
+ }
101
+
102
+ // If we found the whole thing is zeros, then we have a zero.
103
+ return []
104
+ }
105
+
106
+ class Interp extends Struct {
107
+ constructor (
108
+ script,
109
+ tx,
110
+ nIn,
111
+ stack = [],
112
+ altStack = [],
113
+ pc = 0,
114
+ pBeginCodeHash = 0,
115
+ nOpCount = 0,
116
+ ifStack = [],
117
+ errStr = '',
118
+ flags = Interp.defaultFlags,
119
+ valueBn = new Bn(0)
120
+ ) {
121
+ super({
122
+ script,
123
+ tx,
124
+ nIn,
125
+ stack,
126
+ altStack,
127
+ pc,
128
+ pBeginCodeHash,
129
+ nOpCount,
130
+ ifStack,
131
+ errStr,
132
+ flags,
133
+ valueBn
134
+ })
135
+ }
136
+
137
+ initialize () {
138
+ this.script = new Script()
139
+ this.stack = []
140
+ this.altStack = []
141
+ this.pc = 0
142
+ this.pBeginCodeHash = 0
143
+ this.nOpCount = 0
144
+ this.ifStack = []
145
+ this.errStr = ''
146
+ this.flags = Interp.defaultFlags
147
+ this.scriptLimit = 10000000
148
+ this.stackLimit = 10000000
149
+ return this
150
+ }
151
+
152
+ fromJSON (json) {
153
+ this.fromJSONNoTx(json)
154
+ this.tx = json.tx ? new Tx().fromJSON(json.tx) : undefined
155
+ return this
156
+ }
157
+ /**
158
+ * Convert JSON containing everything but the tx to an interp object.
159
+ */
160
+ fromJSONNoTx (json) {
161
+ this.fromObject({
162
+ script:
163
+ json.script !== undefined
164
+ ? new Script().fromJSON(json.script)
165
+ : undefined,
166
+ nIn: json.nIn
167
+ })
168
+ this.stack = []
169
+ json.stack.forEach(
170
+ function (hex) {
171
+ this.stack.push(Buffer.from(hex, 'hex'))
172
+ }.bind(this)
173
+ )
174
+ this.altStack = []
175
+ json.altStack.forEach(
176
+ function (hex) {
177
+ this.altStack.push(Buffer.from(hex, 'hex'))
178
+ }.bind(this)
179
+ )
180
+ this.fromObject({
181
+ pc: json.pc,
182
+ pBeginCodeHash: json.pBeginCodeHash,
183
+ nOpCount: json.nOpCount,
184
+ ifStack: json.ifStack,
185
+ errStr: json.errStr,
186
+ flags: json.flags
187
+ })
188
+ return this
189
+ }
190
+
191
+ fromBr (br) {
192
+ let jsonNoTxBufLEn = br.readVarIntNum()
193
+ let jsonNoTxBuf = br.read(jsonNoTxBufLEn)
194
+ this.fromJSONNoTx(JSON.parse(jsonNoTxBuf.toString()))
195
+ let txbuflen = br.readVarIntNum()
196
+ if (txbuflen > 0) {
197
+ let txbuf = br.read(txbuflen)
198
+ this.tx = new Tx().fromFastBuffer(txbuf)
199
+ }
200
+ return this
201
+ }
202
+
203
+ toJSON () {
204
+ let json = this.toJSONNoTx()
205
+ json.tx = this.tx ? this.tx.toJSON() : undefined
206
+ return json
207
+ }
208
+
209
+ /**
210
+ * Convert everything but the tx to JSON.
211
+ */
212
+ toJSONNoTx () {
213
+ let stack = []
214
+ this.stack.forEach(function (buf) {
215
+ stack.push(buf.toString('hex'))
216
+ })
217
+ let altStack = []
218
+ this.altStack.forEach(function (buf) {
219
+ altStack.push(buf.toString('hex'))
220
+ })
221
+ return {
222
+ script: this.script ? this.script.toJSON() : undefined,
223
+ nIn: this.nIn,
224
+ stack: stack,
225
+ altStack: altStack,
226
+ pc: this.pc,
227
+ pBeginCodeHash: this.pBeginCodeHash,
228
+ nOpCount: this.nOpCount,
229
+ ifStack: this.ifStack,
230
+ errStr: this.errStr,
231
+ flags: this.flags,
232
+ preImage: this?.preImage ? this.preImage.toString("hex"):"",
233
+ hashBuf: this?.hashBuf ? this.hashBuf.toString("hex"):""
234
+ }
235
+ }
236
+
237
+ toBw (bw) {
238
+ if (!bw) {
239
+ bw = new Bw()
240
+ }
241
+ let jsonNoTxBuf = Buffer.from(JSON.stringify(this.toJSONNoTx()))
242
+ bw.writeVarIntNum(jsonNoTxBuf.length)
243
+ bw.write(jsonNoTxBuf)
244
+ if (this.tx) {
245
+ let txbuf = this.tx.toFastBuffer()
246
+ bw.writeVarIntNum(txbuf.length)
247
+ bw.write(txbuf)
248
+ } else {
249
+ bw.writeVarIntNum(0)
250
+ }
251
+ return bw
252
+ }
253
+
254
+ /**
255
+ * In order to make auduting the script interpreter easier, we use the same
256
+ * constants as bitcoin core, including the flags, which customize the
257
+ * operation of the interpreter.
258
+ */
259
+ static getFlags (flagstr) {
260
+ let flags = 0
261
+ if (flagstr.indexOf('NONE') !== -1) {
262
+ flags = flags | Interp.SCRIPT_VERIFY_NONE
263
+ }
264
+ if (flagstr.indexOf('P2SH') !== -1) {
265
+ flags = flags | Interp.SCRIPT_VERIFY_P2SH
266
+ }
267
+ if (flagstr.indexOf('STRICTENC') !== -1) {
268
+ flags = flags | Interp.SCRIPT_VERIFY_STRICTENC
269
+ }
270
+ if (flagstr.indexOf('DERSIG') !== -1) {
271
+ flags = flags | Interp.SCRIPT_VERIFY_DERSIG
272
+ }
273
+ if (flagstr.indexOf('LOW_S') !== -1) {
274
+ flags = flags | Interp.SCRIPT_VERIFY_LOW_S
275
+ }
276
+ if (flagstr.indexOf('NULLDUMMY') !== -1) {
277
+ flags = flags | Interp.SCRIPT_VERIFY_NULLDUMMY
278
+ }
279
+ if (flagstr.indexOf('SIGPUSHONLY') !== -1) {
280
+ flags = flags | Interp.SCRIPT_VERIFY_SIGPUSHONLY
281
+ }
282
+ if (flagstr.indexOf('MINIMALDATA') !== -1) {
283
+ flags = flags | Interp.SCRIPT_VERIFY_MINIMALDATA
284
+ }
285
+ if (flagstr.indexOf('DISCOURAGE_UPGRADABLE_NOPS') !== -1) {
286
+ flags = flags | Interp.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS
287
+ }
288
+ if (flagstr.indexOf('CLEANSTACK') !== -1) {
289
+ flags = flags | Interp.SCRIPT_VERIFY_CLEANSTACK
290
+ }
291
+ if (flagstr.indexOf('CHECKLOCKTIMEVERIFY') !== -1) {
292
+ flags = flags | Interp.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
293
+ }
294
+ if (flagstr.indexOf('CHECKSEQUENCEVERIFY') !== -1) {
295
+ flags = flags | Interp.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
296
+ }
297
+ if (flagstr.indexOf('SIGHASH_FORKID') !== -1) {
298
+ flags = flags | Interp.SCRIPT_ENABLE_SIGHASH_FORKID
299
+ }
300
+ return flags
301
+ }
302
+
303
+ static castToBool (buf) {
304
+ for (let i = 0; i &lt; buf.length; i++) {
305
+ if (buf[i] !== 0) {
306
+ // can be negative zero
307
+ if (i === buf.length - 1 &amp;&amp; buf[i] === 0x80) {
308
+ return false
309
+ }
310
+ return true
311
+ }
312
+ }
313
+ return false
314
+ }
315
+
316
+ /**
317
+ * Translated from bitcoin core's CheckSigEncoding
318
+ */
319
+ checkSigEncoding (buf) {
320
+ // Empty signature. Not strictly DER encoded, but allowed to provide a
321
+ // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
322
+ if (buf.length === 0) {
323
+ return true
324
+ }
325
+ if (
326
+ (this.flags &amp;
327
+ (Interp.SCRIPT_VERIFY_DERSIG |
328
+ Interp.SCRIPT_VERIFY_LOW_S |
329
+ Interp.SCRIPT_VERIFY_STRICTENC)) !==
330
+ 0 &amp;&amp;
331
+ !Sig.IsTxDer(buf)
332
+ ) {
333
+ this.errStr = 'SCRIPT_ERR_SIG_DER'
334
+ return false
335
+ } else if ((this.flags &amp; Interp.SCRIPT_VERIFY_LOW_S) !== 0) {
336
+ let sig = new Sig().fromTxFormat(buf)
337
+ if (!sig.hasLowS()) {
338
+ this.errStr = 'SCRIPT_ERR_SIG_DER'
339
+ return false
340
+ }
341
+ } else if ((this.flags &amp; Interp.SCRIPT_VERIFY_STRICTENC) !== 0) {
342
+ let sig = new Sig().fromTxFormat(buf)
343
+ if (!sig.hasDefinedHashType()) {
344
+ this.errStr = 'SCRIPT_ERR_SIG_HASHTYPE'
345
+ return false
346
+ }
347
+ }
348
+ return true
349
+ }
350
+
351
+ /**
352
+ * Translated from bitcoin core's CheckPubKeyEncoding
353
+ */
354
+ checkPubKeyEncoding (buf) {
355
+ if (
356
+ (this.flags &amp; Interp.SCRIPT_VERIFY_STRICTENC) !== 0 &amp;&amp;
357
+ !PubKey.isCompressedOrUncompressed(buf)
358
+ ) {
359
+ this.errStr = 'SCRIPT_ERR_PUBKEYTYPE'
360
+ return false
361
+ }
362
+ return true
363
+ }
364
+
365
+ /**
366
+ * Translated from bitcoin core's CheckLockTime
367
+ */
368
+ checkLockTime (nLockTime) {
369
+ // There are two kinds of nLockTime: lock-by-blockheight
370
+ // and lock-by-blocktime, distinguished by whether
371
+ // nLockTime &lt; LOCKTIME_THRESHOLD.
372
+ //
373
+ // We want to compare apples to apples, so fail the script
374
+ // unless the type of nLockTime being tested is the same as
375
+ // the nLockTime in the transaction.
376
+ if (
377
+ !(
378
+ (this.tx.nLockTime &lt; Interp.LOCKTIME_THRESHOLD &amp;&amp;
379
+ nLockTime &lt; Interp.LOCKTIME_THRESHOLD) ||
380
+ (this.tx.nLockTime >= Interp.LOCKTIME_THRESHOLD &amp;&amp;
381
+ nLockTime >= Interp.LOCKTIME_THRESHOLD)
382
+ )
383
+ ) {
384
+ return false
385
+ }
386
+
387
+ // Now that we know we're comparing apples-to-apples, the
388
+ // comparison is a simple numeric one.
389
+ if (nLockTime > this.tx.nLockTime) {
390
+ return false
391
+ }
392
+
393
+ // Finally the nLockTime feature can be disabled and thus
394
+ // CHECKLOCKTIMEVERIFY bypassed if every txIn has been
395
+ // finalized by setting nSequence to maxint. The
396
+ // transaction would be allowed into the blockchain, making
397
+ // the opCode ineffective.
398
+ //
399
+ // Testing if this vin is not final is sufficient to
400
+ // prevent this condition. Alternatively we could test all
401
+ // inputs, but testing just this input minimizes the data
402
+ // required to prove correct CHECKLOCKTIMEVERIFY execution.
403
+ if (TxIn.SEQUENCE_FINAL === this.tx.txIns[this.nIn].nSequence) {
404
+ return false
405
+ }
406
+
407
+ return true
408
+ }
409
+
410
+ /**
411
+ * Translated from bitcoin core's CheckSequence.
412
+ */
413
+ checkSequence (nSequence) {
414
+ // Relative lock times are supported by comparing the passed
415
+ // in operand to the sequence number of the input.
416
+ let txToSequence = this.tx.txIns[this.nIn].nSequence
417
+
418
+ // Fail if the transaction's version number is not set high
419
+ // enough to trigger Bip 68 rules.
420
+ if (this.tx.versionBytesNum &lt; 2) {
421
+ return false
422
+ }
423
+
424
+ // Sequence numbers with their most significant bit set are not
425
+ // consensus constrained. Testing that the transaction's sequence
426
+ // number do not have this bit set prevents using this property
427
+ // to get around a CHECKSEQUENCEVERIFY check.
428
+ if (txToSequence &amp; TxIn.SEQUENCE_LOCKTIME_DISABLE_FLAG) {
429
+ return false
430
+ }
431
+
432
+ // Mask off any bits that do not have consensus-enforced meaning
433
+ // before doing the integer comparisons
434
+ let nLockTimeMask =
435
+ TxIn.SEQUENCE_LOCKTIME_TYPE_FLAG | TxIn.SEQUENCE_LOCKTIME_MASK
436
+ let txToSequenceMasked = txToSequence &amp; nLockTimeMask
437
+ let nSequenceMasked = nSequence &amp; nLockTimeMask
438
+
439
+ // There are two kinds of nSequence: lock-by-blockheight
440
+ // and lock-by-blocktime, distinguished by whether
441
+ // nSequenceMasked &lt; CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
442
+ //
443
+ // We want to compare apples to apples, so fail the script
444
+ // unless the type of nSequenceMasked being tested is the same as
445
+ // the nSequenceMasked in the transaction.
446
+ if (
447
+ !(
448
+ (txToSequenceMasked &lt; TxIn.SEQUENCE_LOCKTIME_TYPE_FLAG &amp;&amp;
449
+ nSequenceMasked &lt; TxIn.SEQUENCE_LOCKTIME_TYPE_FLAG) ||
450
+ (txToSequenceMasked >= TxIn.SEQUENCE_LOCKTIME_TYPE_FLAG &amp;&amp;
451
+ nSequenceMasked >= TxIn.SEQUENCE_LOCKTIME_TYPE_FLAG)
452
+ )
453
+ ) {
454
+ return false
455
+ }
456
+
457
+ // Now that we know we're comparing apples-to-apples, the
458
+ // comparison is a simple numeric one.
459
+ if (nSequenceMasked > txToSequenceMasked) {
460
+ return false
461
+ }
462
+
463
+ return true
464
+ }
465
+
466
+ /**
467
+ * Based on bitcoin core's EvalScript function, with the inner loop moved to
468
+ * Interp.prototype.step()
469
+ * bitcoin core commit: b5d1b1092998bc95313856d535c632ea5a8f9104
470
+ */
471
+ * eval () {
472
+ if (this.script.toBuffer().length > this.scriptLimit) {
473
+ this.errStr = 'SCRIPT_ERR_SCRIPT_SIZE'
474
+ yield false
475
+ }
476
+
477
+ try {
478
+ while (this.pc &lt; this.script.chunks.length) {
479
+ let fSuccess = this.step()
480
+ if (!fSuccess) {
481
+ yield false
482
+ } else {
483
+ yield fSuccess
484
+ }
485
+ }
486
+
487
+ // Size limits
488
+ if (this.stack.length + this.altStack.length > this.stackLimit) {
489
+ this.errStr = 'SCRIPT_ERR_STACK_SIZE'
490
+ yield false
491
+ }
492
+ } catch (e) {
493
+ this.errStr = 'SCRIPT_ERR_UNKNOWN_ERROR: ' + e
494
+ yield false
495
+ }
496
+
497
+ if (this.ifStack.length > 0) {
498
+ this.errStr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL'
499
+ yield false
500
+ }
501
+
502
+ yield true
503
+ }
504
+
505
+ /**
506
+ * Based on the inner loop of bitcoin core's EvalScript function
507
+ */
508
+ step () {
509
+ let fRequireMinimal =
510
+ (this.flags &amp; Interp.SCRIPT_VERIFY_MINIMALDATA) !== 0
511
+
512
+ // bool fExec = !count(ifStack.begin(), ifStack.end(), false)
513
+ let fExec = !(this.ifStack.indexOf(false) + 1)
514
+
515
+ //
516
+ // Read instruction
517
+ //
518
+ let chunk = this.script.chunks[this.pc]
519
+ this.pc++
520
+ let opCodeNum = chunk.opCodeNum
521
+ if (opCodeNum === undefined) {
522
+ this.errStr = 'SCRIPT_ERR_BAD_OPCODE'
523
+ return false
524
+ }
525
+ if (chunk.buf &amp;&amp; chunk.buf.length > Interp.MAX_SCRIPT_ELEMENT_SIZE) {
526
+ this.errStr = 'SCRIPT_ERR_PUSH_SIZE'
527
+ return false
528
+ }
529
+
530
+ // Note how OpCode.OP_RESERVED does not count towards the opCode limit.
531
+ if (opCodeNum > OpCode.OP_16 &amp;&amp; ++this.nOpCount > 201) {
532
+ this.errStr = 'SCRIPT_ERR_OP_COUNT'
533
+ return false
534
+ }
535
+
536
+ if (
537
+ opCodeNum === OpCode.OP_2MUL ||
538
+ opCodeNum === OpCode.OP_2DIV
539
+ ) {
540
+ this.errStr = 'SCRIPT_ERR_DISABLED_OPCODE'
541
+ return false
542
+ }
543
+
544
+ if (fExec &amp;&amp; opCodeNum >= 0 &amp;&amp; opCodeNum &lt;= OpCode.OP_PUSHDATA4) {
545
+ if (fRequireMinimal &amp;&amp; !this.script.checkMinimalPush(this.pc - 1)) {
546
+ this.errStr = 'SCRIPT_ERR_MINIMALDATA'
547
+ return false
548
+ }
549
+ if (!chunk.buf) {
550
+ this.stack.push(Interp.false)
551
+ } else if (chunk.len !== chunk.buf.length) {
552
+ throw new Error('LEngth of push value not equal to length of data')
553
+ } else {
554
+ this.stack.push(chunk.buf)
555
+ }
556
+ } else if (
557
+ fExec ||
558
+ (OpCode.OP_IF &lt;= opCodeNum &amp;&amp; opCodeNum &lt;= OpCode.OP_ENDIF)
559
+ ) {
560
+ switch (opCodeNum) {
561
+ //
562
+ // Push value
563
+ //
564
+ case OpCode.OP_1NEGATE:
565
+ case OpCode.OP_1:
566
+ case OpCode.OP_2:
567
+ case OpCode.OP_3:
568
+ case OpCode.OP_4:
569
+ case OpCode.OP_5:
570
+ case OpCode.OP_6:
571
+ case OpCode.OP_7:
572
+ case OpCode.OP_8:
573
+ case OpCode.OP_9:
574
+ case OpCode.OP_10:
575
+ case OpCode.OP_11:
576
+ case OpCode.OP_12:
577
+ case OpCode.OP_13:
578
+ case OpCode.OP_14:
579
+ case OpCode.OP_15:
580
+ case OpCode.OP_16:
581
+ {
582
+ // ( -- value)
583
+ // ScriptNum bn((int)opCode - (int)(OpCode.OP_1 - 1))
584
+ let n = opCodeNum - (OpCode.OP_1 - 1)
585
+ let buf = new Bn(n).toScriptNumBuffer()
586
+ this.stack.push(buf)
587
+ // The result of these opCodes should always be the minimal way to push the data
588
+ // they push, so no need for a CheckMinimalPush here.
589
+ }
590
+ break
591
+
592
+ //
593
+ // Control
594
+ //
595
+ case OpCode.OP_NOP:
596
+ break
597
+
598
+ case OpCode.OP_CHECKLOCKTIMEVERIFY:
599
+ {
600
+ if (!(this.flags &amp; Interp.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
601
+ // not enabled; treat as a NOP2
602
+ if (
603
+ this.flags &amp; Interp.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS
604
+ ) {
605
+ this.errStr = 'SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS'
606
+ return false
607
+ }
608
+ break
609
+ }
610
+
611
+ if (this.stack.length &lt; 1) {
612
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
613
+ return false
614
+ }
615
+
616
+ // Note that elsewhere numeric opCodes are limited to
617
+ // operands in the range -2**31+1 to 2**31-1, however it is
618
+ // legal for opCodes to produce results exceeding that
619
+ // range. This limitation is implemented by CScriptNum's
620
+ // default 4-byte limit.
621
+ //
622
+ // If we kept to that limit we'd have a year 2038 problem,
623
+ // even though the nLockTime field in transactions
624
+ // themselves is uint32 which only becomes meaningless
625
+ // after the year 2106.
626
+ //
627
+ // Thus as a special case we tell CScriptNum to accept up
628
+ // to 5-byte bignums, which are good until 2**39-1, well
629
+ // beyond the 2**32-1 limit of the nLockTime field itself.
630
+ let nLockTimebuf = this.stack[this.stack.length - 1]
631
+ let nLockTimebn = new Bn().fromScriptNumBuffer(
632
+ nLockTimebuf,
633
+ fRequireMinimal,
634
+ 5
635
+ )
636
+ let nLockTime = nLockTimebn.toNumber()
637
+
638
+ // In the rare event that the argument may be &lt; 0 due to
639
+ // some arithmetic being done first, you can always use
640
+ // 0 MAX CHECKLOCKTIMEVERIFY.
641
+ if (nLockTime &lt; 0) {
642
+ this.errStr = 'SCRIPT_ERR_NEGATIVE_LOCKTIME'
643
+ return false
644
+ }
645
+
646
+ // Actually compare the specified lock time with the transaction.
647
+ if (!this.checkLockTime(nLockTime)) {
648
+ this.errStr = 'SCRIPT_ERR_UNSATISFIED_LOCKTIME'
649
+ return false
650
+ }
651
+ }
652
+ break
653
+
654
+ case OpCode.OP_CHECKSEQUENCEVERIFY:
655
+ {
656
+ if (!(this.flags &amp; Interp.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
657
+ // not enabled; treat as a NOP3
658
+ if (
659
+ this.flags &amp; Interp.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS
660
+ ) {
661
+ this.errStr = 'SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS'
662
+ return false
663
+ }
664
+ break
665
+ }
666
+
667
+ if (this.stack.length &lt; 1) {
668
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
669
+ return false
670
+ }
671
+
672
+ // nSequence, like nLockTime, is a 32-bit unsigned integer
673
+ // field. See the comment in CHECKLOCKTIMEVERIFY regarding
674
+ // 5-byte numeric operands.
675
+ let nSequencebuf = this.stack[this.stack.length - 1]
676
+ let nSequencebn = new Bn().fromScriptNumBuffer(
677
+ nSequencebuf,
678
+ fRequireMinimal,
679
+ 5
680
+ )
681
+ let nSequence = nSequencebn.toNumber()
682
+
683
+ // In the rare event that the argument may be &lt; 0 due to
684
+ // some arithmetic being done first, you can always use
685
+ // 0 MAX CHECKSEQUENCEVERIFY.
686
+ if (nSequence &lt; 0) {
687
+ this.errStr = 'SCRIPT_ERR_NEGATIVE_LOCKTIME'
688
+ return false
689
+ }
690
+
691
+ // To provide for future soft-fork extensibility, if the
692
+ // operand has the disabled lock-time flag set,
693
+ // CHECKSEQUENCEVERIFY behaves as a NOP.
694
+ if ((nSequence &amp; TxIn.SEQUENCE_LOCKTIME_DISABLE_FLAG) !== 0) {
695
+ break
696
+ }
697
+
698
+ // Compare the specified sequence number with the input.
699
+ if (!this.checkSequence(nSequence)) {
700
+ this.errStr = 'SCRIPT_ERR_UNSATISFIED_LOCKTIME'
701
+ return false
702
+ }
703
+ }
704
+ break
705
+
706
+ case OpCode.OP_NOP1:
707
+ case OpCode.OP_NOP3:
708
+ case OpCode.OP_NOP4:
709
+ case OpCode.OP_NOP5:
710
+ case OpCode.OP_NOP6:
711
+ case OpCode.OP_NOP7:
712
+ case OpCode.OP_NOP8:
713
+ case OpCode.OP_NOP9:
714
+ case OpCode.OP_NOP10:
715
+ if (this.flags &amp; Interp.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
716
+ this.errStr = 'SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS'
717
+ return false
718
+ }
719
+ break
720
+
721
+ case OpCode.OP_IF:
722
+ case OpCode.OP_NOTIF:
723
+ {
724
+ // &lt;expression> if [statements] [else [statements]] endif
725
+ // bool fValue = false
726
+ let fValue = false
727
+ if (fExec) {
728
+ if (this.stack.length &lt; 1) {
729
+ this.errStr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL'
730
+ return false
731
+ }
732
+ let buf = this.stack.pop()
733
+ fValue = Interp.castToBool(buf)
734
+ if (opCodeNum === OpCode.OP_NOTIF) {
735
+ fValue = !fValue
736
+ }
737
+ }
738
+ this.ifStack.push(fValue)
739
+ }
740
+ break
741
+
742
+ case OpCode.OP_ELSE:
743
+ if (this.ifStack.length === 0) {
744
+ this.errStr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL'
745
+ return false
746
+ }
747
+ this.ifStack[this.ifStack.length - 1] = !this.ifStack[
748
+ this.ifStack.length - 1
749
+ ]
750
+ break
751
+
752
+ case OpCode.OP_ENDIF:
753
+ if (this.ifStack.length === 0) {
754
+ this.errStr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL'
755
+ return false
756
+ }
757
+ this.ifStack.pop()
758
+ break
759
+
760
+ case OpCode.OP_VERIFY:
761
+ {
762
+ // (true -- ) or
763
+ // (false -- false) and return
764
+ if (this.stack.length &lt; 1) {
765
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
766
+ return false
767
+ }
768
+ let buf = this.stack[this.stack.length - 1]
769
+ let fValue = Interp.castToBool(buf)
770
+ if (fValue) {
771
+ this.stack.pop()
772
+ } else {
773
+ this.errStr = 'SCRIPT_ERR_VERIFY'
774
+ return false
775
+ }
776
+ }
777
+ break
778
+
779
+ case OpCode.OP_RETURN: {
780
+ this.errStr = 'SCRIPT_ERR_OP_RETURN'
781
+ return false
782
+ }
783
+ // unreachable code: break
784
+
785
+ //
786
+ // Stack ops
787
+ //
788
+ case OpCode.OP_TOALTSTACK:
789
+ if (this.stack.length &lt; 1) {
790
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
791
+ return false
792
+ }
793
+ this.altStack.push(this.stack.pop())
794
+ break
795
+
796
+ case OpCode.OP_FROMALTSTACK:
797
+ if (this.altStack.length &lt; 1) {
798
+ this.errStr = 'SCRIPT_ERR_INVALID_ALTSTACK_OPERATION'
799
+ return false
800
+ }
801
+ this.stack.push(this.altStack.pop())
802
+ break
803
+
804
+ case OpCode.OP_2DROP:
805
+ // (x1 x2 -- )
806
+ if (this.stack.length &lt; 2) {
807
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
808
+ return false
809
+ }
810
+ this.stack.pop()
811
+ this.stack.pop()
812
+ break
813
+
814
+ case OpCode.OP_2DUP:
815
+ {
816
+ // (x1 x2 -- x1 x2 x1 x2)
817
+ if (this.stack.length &lt; 2) {
818
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
819
+ return false
820
+ }
821
+ let buf1 = this.stack[this.stack.length - 2]
822
+ let buf2 = this.stack[this.stack.length - 1]
823
+ this.stack.push(buf1)
824
+ this.stack.push(buf2)
825
+ }
826
+ break
827
+
828
+ case OpCode.OP_3DUP:
829
+ {
830
+ // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
831
+ if (this.stack.length &lt; 3) {
832
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
833
+ return false
834
+ }
835
+ let buf1 = this.stack[this.stack.length - 3]
836
+ let buf2 = this.stack[this.stack.length - 2]
837
+ let buf3 = this.stack[this.stack.length - 1]
838
+ this.stack.push(buf1)
839
+ this.stack.push(buf2)
840
+ this.stack.push(buf3)
841
+ }
842
+ break
843
+
844
+ case OpCode.OP_2OVER:
845
+ {
846
+ // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
847
+ if (this.stack.length &lt; 4) {
848
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
849
+ return false
850
+ }
851
+ let buf1 = this.stack[this.stack.length - 4]
852
+ let buf2 = this.stack[this.stack.length - 3]
853
+ this.stack.push(buf1)
854
+ this.stack.push(buf2)
855
+ }
856
+ break
857
+
858
+ case OpCode.OP_2ROT:
859
+ {
860
+ // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
861
+ if (this.stack.length &lt; 6) {
862
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
863
+ return false
864
+ }
865
+ let spliced = this.stack.splice(this.stack.length - 6, 2)
866
+ this.stack.push(spliced[0])
867
+ this.stack.push(spliced[1])
868
+ }
869
+ break
870
+
871
+ case OpCode.OP_2SWAP:
872
+ {
873
+ // (x1 x2 x3 x4 -- x3 x4 x1 x2)
874
+ if (this.stack.length &lt; 4) {
875
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
876
+ return false
877
+ }
878
+ let spliced = this.stack.splice(this.stack.length - 4, 2)
879
+ this.stack.push(spliced[0])
880
+ this.stack.push(spliced[1])
881
+ }
882
+ break
883
+
884
+ case OpCode.OP_IFDUP:
885
+ {
886
+ // (x - 0 | x x)
887
+ if (this.stack.length &lt; 1) {
888
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
889
+ return false
890
+ }
891
+ let buf = this.stack[this.stack.length - 1]
892
+ let fValue = Interp.castToBool(buf)
893
+ if (fValue) {
894
+ this.stack.push(buf)
895
+ }
896
+ }
897
+ break
898
+
899
+ case OpCode.OP_DEPTH:
900
+ {
901
+ // -- stacksize
902
+ let buf = new Bn(this.stack.length).toScriptNumBuffer()
903
+ this.stack.push(buf)
904
+ }
905
+ break
906
+
907
+ case OpCode.OP_DROP:
908
+ // (x -- )
909
+ if (this.stack.length &lt; 1) {
910
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
911
+ return false
912
+ }
913
+ this.stack.pop()
914
+ break
915
+
916
+ case OpCode.OP_DUP:
917
+ // (x -- x x)
918
+ if (this.stack.length &lt; 1) {
919
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
920
+ return false
921
+ }
922
+ this.stack.push(this.stack[this.stack.length - 1])
923
+ break
924
+
925
+ case OpCode.OP_NIP:
926
+ // (x1 x2 -- x2)
927
+ if (this.stack.length &lt; 2) {
928
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
929
+ return false
930
+ }
931
+ this.stack.splice(this.stack.length - 2, 1)
932
+ break
933
+
934
+ case OpCode.OP_OVER:
935
+ // (x1 x2 -- x1 x2 x1)
936
+ if (this.stack.length &lt; 2) {
937
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
938
+ return false
939
+ }
940
+ this.stack.push(this.stack[this.stack.length - 2])
941
+ break
942
+
943
+ case OpCode.OP_PICK:
944
+ case OpCode.OP_ROLL:
945
+ {
946
+ // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
947
+ // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
948
+ if (this.stack.length &lt; 2) {
949
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
950
+ return false
951
+ }
952
+ let buf = this.stack[this.stack.length - 1]
953
+ let bn = new Bn().fromScriptNumBuffer(buf, fRequireMinimal, Interp.DEFAULT_SCRIPT_NUM_LENGTH_POLICY_AFTER_GENESIS)
954
+ let n = bn.toNumber()
955
+ this.stack.pop()
956
+ if (n &lt; 0 || n >= this.stack.length) {
957
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
958
+ return false
959
+ }
960
+ buf = this.stack[this.stack.length - n - 1]
961
+ if (opCodeNum === OpCode.OP_ROLL) {
962
+ this.stack.splice(this.stack.length - n - 1, 1)
963
+ }
964
+ this.stack.push(buf)
965
+ }
966
+ break
967
+
968
+ case OpCode.OP_ROT:
969
+ {
970
+ // (x1 x2 x3 -- x2 x3 x1)
971
+ // x2 x1 x3 after first swap
972
+ // x2 x3 x1 after second swap
973
+ if (this.stack.length &lt; 3) {
974
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
975
+ return false
976
+ }
977
+ let x1 = this.stack[this.stack.length - 3]
978
+ let x2 = this.stack[this.stack.length - 2]
979
+ let x3 = this.stack[this.stack.length - 1]
980
+ this.stack[this.stack.length - 3] = x2
981
+ this.stack[this.stack.length - 2] = x3
982
+ this.stack[this.stack.length - 1] = x1
983
+ }
984
+ break
985
+
986
+ case OpCode.OP_SWAP:
987
+ {
988
+ // (x1 x2 -- x2 x1)
989
+ if (this.stack.length &lt; 2) {
990
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
991
+ return false
992
+ }
993
+ let x1 = this.stack[this.stack.length - 2]
994
+ let x2 = this.stack[this.stack.length - 1]
995
+ this.stack[this.stack.length - 2] = x2
996
+ this.stack[this.stack.length - 1] = x1
997
+ }
998
+ break
999
+
1000
+ case OpCode.OP_TUCK:
1001
+ // (x1 x2 -- x2 x1 x2)
1002
+ if (this.stack.length &lt; 2) {
1003
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1004
+ return false
1005
+ }
1006
+ this.stack.splice(
1007
+ this.stack.length - 2,
1008
+ 0,
1009
+ this.stack[this.stack.length - 1]
1010
+ )
1011
+ break
1012
+
1013
+ case OpCode.OP_SIZE:
1014
+ {
1015
+ // (in -- in size)
1016
+ if (this.stack.length &lt; 1) {
1017
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1018
+ return false
1019
+ }
1020
+ let bn = new Bn(this.stack[this.stack.length - 1].length)
1021
+ this.stack.push(bn.toScriptNumBuffer())
1022
+ }
1023
+ break
1024
+
1025
+ //
1026
+ // Bitwise logic
1027
+ //
1028
+ case OpCode.OP_OR:
1029
+ case OpCode.OP_AND:
1030
+ case OpCode.OP_XOR:
1031
+ // (x1 x2 -- out)
1032
+ if (this.stack.length &lt; 2) {
1033
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1034
+ return false
1035
+ }
1036
+ let buf1 = this.stack[this.stack.length - 2]
1037
+ let buf2 = this.stack[this.stack.length - 1]
1038
+
1039
+ if (buf1.length != buf2.length) {
1040
+ this.errStr = 'SCRIPT_ERR_INVALID_OPERAND_SIZE'
1041
+ return false
1042
+ }
1043
+
1044
+ switch (opCodeNum) {
1045
+ case OpCode.OP_AND:
1046
+ for(let i = 0; i &lt; buf1.length; i++) {
1047
+ buf1[i] &amp;= buf2[i]
1048
+ }
1049
+ break
1050
+ case OpCode.OP_OR:
1051
+ for(let i = 0; i &lt; buf1.length; i++) {
1052
+ buf1[i] |= buf2[i]
1053
+ }
1054
+ break
1055
+ case OpCode.OP_XOR:
1056
+ for(let i = 0; i &lt; buf1.length; i++) {
1057
+ buf1[i] ^= buf2[i]
1058
+ }
1059
+ break
1060
+ }
1061
+
1062
+ // pop out buf2
1063
+ this.stack.pop();
1064
+ break
1065
+ case OpCode.OP_INVERT:
1066
+ // (x -- out)
1067
+ if (this.stack.length &lt; 1) {
1068
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1069
+ return false
1070
+ }
1071
+ let buf = this.stack[this.stack.length - 1]
1072
+ for(let i = 0; i &lt; buf.length; i++) {
1073
+ buf[i] = ~buf[i]
1074
+ }
1075
+ break
1076
+ case OpCode.OP_LSHIFT:
1077
+ case OpCode.OP_RSHIFT:
1078
+ // (x n -- out)
1079
+ {
1080
+ if (this.stack.length &lt; 2) {
1081
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1082
+ return false
1083
+ }
1084
+
1085
+ let buf1 = this.stack[this.stack.length - 2]
1086
+ let value = new Bn(buf1)
1087
+ let n = new Bn().fromScriptNumBuffer(
1088
+ this.stack[this.stack.length - 1],
1089
+ fRequireMinimal,
1090
+ Interp.DEFAULT_SCRIPT_NUM_LENGTH_POLICY_AFTER_GENESIS
1091
+ ).toNumber()
1092
+ if(n &lt; 0) {
1093
+ this.errStr = 'SCRIPT_ERR_INVALID_NUMBER_RANGE'
1094
+ return false
1095
+ }
1096
+
1097
+ this.stack.pop()
1098
+ this.stack.pop()
1099
+
1100
+ switch(opCodeNum) {
1101
+ case OpCode.OP_LSHIFT:
1102
+ value = value.ushln(n)
1103
+ break
1104
+ case OpCode.OP_RSHIFT:
1105
+ value = value.ushrn(n)
1106
+ break
1107
+ }
1108
+
1109
+ let buf2 = value.toBuffer().slice(-buf1.length)
1110
+ if(buf2.length &lt; buf1.length) {
1111
+ buf2 = Buffer.concat([Buffer.alloc(buf1.length - buf2.length), buf2])
1112
+ }
1113
+
1114
+ this.stack.push(buf2)
1115
+ break
1116
+ }
1117
+ case OpCode.OP_EQUAL:
1118
+ case OpCode.OP_EQUALVERIFY:
1119
+ // case OpCode.OP_NOTEQUAL: // use OpCode.OP_NUMNOTEQUAL
1120
+ {
1121
+ // (x1 x2 - bool)
1122
+ if (this.stack.length &lt; 2) {
1123
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1124
+ return false
1125
+ }
1126
+ let buf1 = this.stack[this.stack.length - 2]
1127
+ let buf2 = this.stack[this.stack.length - 1]
1128
+ let fEqual = cmp(buf1, buf2)
1129
+ // OpCode.OP_NOTEQUAL is disabled because it would be too easy to say
1130
+ // something like n != 1 and have some wiseguy pass in 1 with extra
1131
+ // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
1132
+ // if (opCode == OpCode.OP_NOTEQUAL)
1133
+ // fEqual = !fEqual
1134
+ this.stack.pop()
1135
+ this.stack.pop()
1136
+ this.stack.push(fEqual ? Interp.true : Interp.false)
1137
+ if (opCodeNum === OpCode.OP_EQUALVERIFY) {
1138
+ if (fEqual) {
1139
+ this.stack.pop()
1140
+ } else {
1141
+ this.errStr = 'SCRIPT_ERR_EQUALVERIFY'
1142
+ return false
1143
+ }
1144
+ }
1145
+ }
1146
+ break
1147
+
1148
+ //
1149
+ // Numeric
1150
+ //
1151
+ case OpCode.OP_1ADD:
1152
+ case OpCode.OP_1SUB:
1153
+ case OpCode.OP_NEGATE:
1154
+ case OpCode.OP_ABS:
1155
+ case OpCode.OP_NOT:
1156
+ case OpCode.OP_0NOTEQUAL:
1157
+ {
1158
+ // (in -- out)
1159
+ if (this.stack.length &lt; 1) {
1160
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1161
+ return false
1162
+ }
1163
+ let buf = this.stack[this.stack.length - 1]
1164
+ let bn = new Bn().fromScriptNumBuffer(buf, fRequireMinimal, Interp.DEFAULT_SCRIPT_NUM_LENGTH_POLICY_AFTER_GENESIS)
1165
+ switch (opCodeNum) {
1166
+ case OpCode.OP_1ADD:
1167
+ bn = bn.add(1)
1168
+ break
1169
+ case OpCode.OP_1SUB:
1170
+ bn = bn.sub(1)
1171
+ break
1172
+ case OpCode.OP_NEGATE:
1173
+ bn = bn.neg()
1174
+ break
1175
+ case OpCode.OP_ABS:
1176
+ if (bn.lt(0)) bn = bn.neg()
1177
+ break
1178
+ case OpCode.OP_NOT:
1179
+ bn = new Bn(bn.eq(0) + 0)
1180
+ break
1181
+ case OpCode.OP_0NOTEQUAL:
1182
+ bn = new Bn(bn.neq(0) + 0)
1183
+ break
1184
+ // default: assert(!"invalid opCode"); break; // TODO: does this ever occur?
1185
+ }
1186
+ this.stack.pop()
1187
+ this.stack.push(bn.toScriptNumBuffer())
1188
+ }
1189
+ break
1190
+
1191
+ case OpCode.OP_ADD:
1192
+ case OpCode.OP_SUB:
1193
+ case OpCode.OP_MUL:
1194
+ case OpCode.OP_DIV:
1195
+ case OpCode.OP_MOD:
1196
+ case OpCode.OP_BOOLAND:
1197
+ case OpCode.OP_BOOLOR:
1198
+ case OpCode.OP_NUMEQUAL:
1199
+ case OpCode.OP_NUMEQUALVERIFY:
1200
+ case OpCode.OP_NUMNOTEQUAL:
1201
+ case OpCode.OP_LESSTHAN:
1202
+ case OpCode.OP_GREATERTHAN:
1203
+ case OpCode.OP_LESSTHANOREQUAL:
1204
+ case OpCode.OP_GREATERTHANOREQUAL:
1205
+ case OpCode.OP_MIN:
1206
+ case OpCode.OP_MAX:
1207
+ {
1208
+ // (x1 x2 -- out)
1209
+ if (this.stack.length &lt; 2) {
1210
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1211
+ return false
1212
+ }
1213
+ let bn1 = new Bn().fromScriptNumBuffer(
1214
+ this.stack[this.stack.length - 2],
1215
+ fRequireMinimal,
1216
+ Interp.DEFAULT_SCRIPT_NUM_LENGTH_POLICY_AFTER_GENESIS
1217
+ )
1218
+ let bn2 = new Bn().fromScriptNumBuffer(
1219
+ this.stack[this.stack.length - 1],
1220
+ fRequireMinimal,
1221
+ Interp.DEFAULT_SCRIPT_NUM_LENGTH_POLICY_AFTER_GENESIS
1222
+ )
1223
+ let bn = new Bn(0)
1224
+
1225
+ switch (opCodeNum) {
1226
+ case OpCode.OP_ADD:
1227
+ bn = bn1.add(bn2)
1228
+ break
1229
+
1230
+ case OpCode.OP_SUB:
1231
+ bn = bn1.sub(bn2)
1232
+ break
1233
+
1234
+ case OpCode.OP_MUL:
1235
+ bn = bn1.mul(bn2)
1236
+ break
1237
+
1238
+ case OpCode.OP_DIV:
1239
+ if (bn2 == 0) {
1240
+ this.errStr = "SCRIPT_ERR_DIV_BY_ZERO"
1241
+ return false
1242
+ }
1243
+ bn = bn1.div(bn2)
1244
+ break
1245
+
1246
+ case OpCode.OP_MOD:
1247
+ if (bn2 == 0) {
1248
+ this.errStr = "SCRIPT_ERR_DIV_BY_ZERO"
1249
+ return false
1250
+ }
1251
+ bn = bn1.mod(bn2)
1252
+ break
1253
+
1254
+ // case OpCode.OP_BOOLAND: bn = (bn1 != bnZero &amp;&amp; bn2 != bnZero); break
1255
+ case OpCode.OP_BOOLAND:
1256
+ bn = new Bn((bn1.neq(0) &amp;&amp; bn2.neq(0)) + 0)
1257
+ break
1258
+ // case OpCode.OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break
1259
+ case OpCode.OP_BOOLOR:
1260
+ bn = new Bn((bn1.neq(0) || bn2.neq(0)) + 0)
1261
+ break
1262
+ // case OpCode.OP_NUMEQUAL: bn = (bn1 == bn2); break
1263
+ case OpCode.OP_NUMEQUAL:
1264
+ bn = new Bn(bn1.eq(bn2) + 0)
1265
+ break
1266
+ // case OpCode.OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break
1267
+ case OpCode.OP_NUMEQUALVERIFY:
1268
+ bn = new Bn(bn1.eq(bn2) + 0)
1269
+ break
1270
+ // case OpCode.OP_NUMNOTEQUAL: bn = (bn1 != bn2); break
1271
+ case OpCode.OP_NUMNOTEQUAL:
1272
+ bn = new Bn(bn1.neq(bn2) + 0)
1273
+ break
1274
+ // case OpCode.OP_LESSTHAN: bn = (bn1 &lt; bn2); break
1275
+ case OpCode.OP_LESSTHAN:
1276
+ bn = new Bn(bn1.lt(bn2) + 0)
1277
+ break
1278
+ // case OpCode.OP_GREATERTHAN: bn = (bn1 > bn2); break
1279
+ case OpCode.OP_GREATERTHAN:
1280
+ bn = new Bn(bn1.gt(bn2) + 0)
1281
+ break
1282
+ // case OpCode.OP_LESSTHANOREQUAL: bn = (bn1 &lt;= bn2); break
1283
+ case OpCode.OP_LESSTHANOREQUAL:
1284
+ bn = new Bn(bn1.leq(bn2) + 0)
1285
+ break
1286
+ // case OpCode.OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break
1287
+ case OpCode.OP_GREATERTHANOREQUAL:
1288
+ bn = new Bn(bn1.geq(bn2) + 0)
1289
+ break
1290
+ case OpCode.OP_MIN:
1291
+ bn = bn1.lt(bn2) ? bn1 : bn2
1292
+ break
1293
+ case OpCode.OP_MAX:
1294
+ bn = bn1.gt(bn2) ? bn1 : bn2
1295
+ break
1296
+ // default: assert(!"invalid opCode"); break; //TODO: does this ever occur?
1297
+ }
1298
+ this.stack.pop()
1299
+ this.stack.pop()
1300
+ this.stack.push(bn.toScriptNumBuffer())
1301
+
1302
+ if (opCodeNum === OpCode.OP_NUMEQUALVERIFY) {
1303
+ // if (CastToBool(stacktop(-1)))
1304
+ if (Interp.castToBool(this.stack[this.stack.length - 1])) {
1305
+ this.stack.pop()
1306
+ } else {
1307
+ this.errStr = 'SCRIPT_ERR_NUMEQUALVERIFY'
1308
+ return false
1309
+ }
1310
+ }
1311
+ }
1312
+ break
1313
+
1314
+ case OpCode.OP_WITHIN:
1315
+ {
1316
+ // (x min max -- out)
1317
+ if (this.stack.length &lt; 3) {
1318
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1319
+ return false
1320
+ }
1321
+ let bn1 = new Bn().fromScriptNumBuffer(
1322
+ this.stack[this.stack.length - 3],
1323
+ fRequireMinimal,
1324
+ Interp.DEFAULT_SCRIPT_NUM_LENGTH_POLICY_AFTER_GENESIS
1325
+ )
1326
+ let bn2 = new Bn().fromScriptNumBuffer(
1327
+ this.stack[this.stack.length - 2],
1328
+ fRequireMinimal,
1329
+ Interp.DEFAULT_SCRIPT_NUM_LENGTH_POLICY_AFTER_GENESIS
1330
+
1331
+ )
1332
+ let bn3 = new Bn().fromScriptNumBuffer(
1333
+ this.stack[this.stack.length - 1],
1334
+ fRequireMinimal,
1335
+ Interp.DEFAULT_SCRIPT_NUM_LENGTH_POLICY_AFTER_GENESIS
1336
+ )
1337
+ // bool fValue = (bn2 &lt;= bn1 &amp;&amp; bn1 &lt; bn3)
1338
+ let fValue = bn2.leq(bn1) &amp;&amp; bn1.lt(bn3)
1339
+ this.stack.pop()
1340
+ this.stack.pop()
1341
+ this.stack.pop()
1342
+ this.stack.push(fValue ? Interp.true : Interp.false)
1343
+ }
1344
+ break
1345
+
1346
+ //
1347
+ // Crypto
1348
+ //
1349
+ case OpCode.OP_RIPEMD160:
1350
+ case OpCode.OP_SHA1:
1351
+ case OpCode.OP_SHA256:
1352
+ case OpCode.OP_HASH160:
1353
+ case OpCode.OP_HASH256:
1354
+ {
1355
+ // (in -- hash)
1356
+ if (this.stack.length &lt; 1) {
1357
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1358
+ return false
1359
+ }
1360
+ let buf = this.stack[this.stack.length - 1]
1361
+ // valtype vchnew Hash((opCode == OpCode.OP_RIPEMD160 || opCode == OpCode.OP_SHA1 || opCode == OpCode.OP_HASH160) ? 20 : 32)
1362
+ let bufHash
1363
+ if (opCodeNum === OpCode.OP_RIPEMD160) {
1364
+ bufHash = Hash.ripemd160(buf)
1365
+ } else if (opCodeNum === OpCode.OP_SHA1) {
1366
+ bufHash = Hash.sha1(buf)
1367
+ } else if (opCodeNum === OpCode.OP_SHA256) {
1368
+ bufHash = Hash.sha256(buf)
1369
+ } else if (opCodeNum === OpCode.OP_HASH160) {
1370
+ bufHash = Hash.sha256Ripemd160(buf)
1371
+ } else if (opCodeNum === OpCode.OP_HASH256) {
1372
+ bufHash = Hash.sha256Sha256(buf)
1373
+ }
1374
+ this.stack.pop()
1375
+ this.stack.push(bufHash)
1376
+ }
1377
+ break
1378
+
1379
+ case OpCode.OP_CODESEPARATOR:
1380
+ // Hash starts after the code separator
1381
+ this.pBeginCodeHash = this.pc
1382
+ break
1383
+
1384
+ case OpCode.OP_CHECKSIG:
1385
+ case OpCode.OP_CHECKSIGVERIFY:
1386
+ {
1387
+ // (sig pubKey -- bool)
1388
+ if (this.stack.length &lt; 2) {
1389
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1390
+ return false
1391
+ }
1392
+
1393
+ let bufSig = this.stack[this.stack.length - 2]
1394
+ let bufPubKey = this.stack[this.stack.length - 1]
1395
+ if (
1396
+ !this.checkSigEncoding(bufSig) ||
1397
+ !this.checkPubKeyEncoding(bufPubKey)
1398
+ ) {
1399
+ // serror is set
1400
+ return false
1401
+ }
1402
+
1403
+ // Subset of script starting at the most recent codeseparator
1404
+ // CScript scriptCode(pBeginCodeHash, pend)
1405
+ let subScript = new Script().fromObject({
1406
+ chunks: this.script.chunks.slice(this.pBeginCodeHash)
1407
+ })
1408
+ // https://github.com/Bitcoin-UAHF/spec/blob/master/replay-protected-sighash.md
1409
+ let nHashType =
1410
+ bufSig.length > 0 ? bufSig.readUInt8(bufSig.length - 1) : 0
1411
+ if (nHashType &amp; Sig.SIGHASH_FORKID) {
1412
+ if (!(this.flags &amp; Interp.SCRIPT_ENABLE_SIGHASH_FORKID)) {
1413
+ this.errStr = 'SCRIPT_ERR_ILLEGAL_FORKID'
1414
+ return false
1415
+ }
1416
+ } else {
1417
+ subScript.findAndDelete(new Script().writeBuffer(bufSig))
1418
+ }
1419
+
1420
+ let fSuccess
1421
+ try {
1422
+ let sig = new Sig().fromTxFormat(bufSig)
1423
+ let pubKey = new PubKey().fromBuffer(bufPubKey, false)
1424
+
1425
+
1426
+ this.nHashType = sig.nHashType
1427
+
1428
+ if (typeof this.nIn === "undefined"){
1429
+ console.log("Missing tx input nIn")
1430
+ }
1431
+ if (typeof this.tx === "undefined"){
1432
+ this.tx = new Tx()
1433
+ }
1434
+
1435
+ //subScript is usually the redeemScript
1436
+
1437
+ try{
1438
+
1439
+
1440
+ this.preImage = this.tx.sighashPreimage (sig.nHashType, this.nIn, subScript, this.valueBn, Tx.SCRIPT_ENABLE_SIGHASH_FORKID )
1441
+ //this.hashBuf = this.tx.sighash(sig.nHashType, this.nIn, subScript, this.valueBn, Tx.SCRIPT_ENABLE_SIGHASH_FORKID)
1442
+
1443
+ if (this.preImage.compare(Buffer.from('0000000000000000000000000000000000000000000000000000000000000001', 'hex')) === 0) {
1444
+ this.hashBuf = this.preImage
1445
+ }else{
1446
+ this.hashBuf = new Br(Hash.sha256Sha256(this.preImage)).readReverse()
1447
+ }
1448
+ this.verify = Ecdsa.verify( this.hashBuf, sig, pubKey, 'little', true)
1449
+
1450
+ }catch(e){
1451
+ console.log("ERROR: ",e.message)
1452
+ }
1453
+ fSuccess = this.tx.verify(
1454
+ sig,
1455
+ pubKey,
1456
+ this.nIn,
1457
+ subScript,
1458
+ Boolean(this.flags &amp; Interp.SCRIPT_VERIFY_LOW_S),
1459
+ this.valueBn,
1460
+ Tx.SCRIPT_ENABLE_SIGHASH_FORKID
1461
+ )
1462
+
1463
+ } catch (e) {
1464
+ // invalid sig or pubKey
1465
+ fSuccess = false
1466
+ }
1467
+
1468
+ this.stack.pop()
1469
+ this.stack.pop()
1470
+ // stack.push_back(fSuccess ? vchTrue : vchFalse)
1471
+ this.stack.push(fSuccess ? Interp.true : Interp.false)
1472
+ if (opCodeNum === OpCode.OP_CHECKSIGVERIFY) {
1473
+ if (fSuccess) {
1474
+ this.stack.pop()
1475
+ } else {
1476
+ this.errStr = 'SCRIPT_ERR_CHECKSIGVERIFY'
1477
+ return false
1478
+ }
1479
+ }
1480
+ }
1481
+ break
1482
+
1483
+ case OpCode.OP_CHECKMULTISIG:
1484
+ case OpCode.OP_CHECKMULTISIGVERIFY:
1485
+ {
1486
+ // ([sig ...] num_of_signatures [pubKey ...] num_of_pubKeys -- bool)
1487
+
1488
+ let i = 1
1489
+ if (this.stack.length &lt; i) {
1490
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1491
+ return false
1492
+ }
1493
+
1494
+ let nKeysCount = new Bn()
1495
+ .fromScriptNumBuffer(
1496
+ this.stack[this.stack.length - i],
1497
+ fRequireMinimal
1498
+ )
1499
+ .toNumber()
1500
+ if (nKeysCount &lt; 0 || nKeysCount > 20) {
1501
+ this.errStr = 'SCRIPT_ERR_PUBKEY_COUNT'
1502
+ return false
1503
+ }
1504
+ this.nOpCount += nKeysCount
1505
+ if (this.nOpCount > 201) {
1506
+ this.errStr = 'SCRIPT_ERR_OP_COUNT'
1507
+ return false
1508
+ }
1509
+ // int ikey = ++i
1510
+ let ikey = ++i
1511
+ i += nKeysCount
1512
+ if (this.stack.length &lt; i) {
1513
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1514
+ return false
1515
+ }
1516
+
1517
+ let nSigsCount = new Bn()
1518
+ .fromScriptNumBuffer(
1519
+ this.stack[this.stack.length - i],
1520
+ fRequireMinimal
1521
+ )
1522
+ .toNumber()
1523
+ if (nSigsCount &lt; 0 || nSigsCount > nKeysCount) {
1524
+ this.errStr = 'SCRIPT_ERR_SIG_COUNT'
1525
+ return false
1526
+ }
1527
+ // int isig = ++i
1528
+ let isig = ++i
1529
+ i += nSigsCount
1530
+ if (this.stack.length &lt; i) {
1531
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1532
+ return false
1533
+ }
1534
+
1535
+ // Subset of script starting at the most recent codeseparator
1536
+ let subScript = new Script().fromObject({
1537
+ chunks: this.script.chunks.slice(this.pBeginCodeHash)
1538
+ })
1539
+
1540
+ for (let k = 0; k &lt; nSigsCount; k++) {
1541
+ let bufSig = this.stack[this.stack.length - isig - k]
1542
+
1543
+ // https://github.com/Bitcoin-UAHF/spec/blob/master/replay-protected-sighash.md
1544
+ let nHashType =
1545
+ bufSig.length > 0 ? bufSig.readUInt8(bufSig.length - 1) : 0
1546
+ if (nHashType &amp; Sig.SIGHASH_FORKID) {
1547
+ if (!(this.flags &amp; Interp.SCRIPT_ENABLE_SIGHASH_FORKID)) {
1548
+ this.errStr = 'SCRIPT_ERR_ILLEGAL_FORKID'
1549
+ return false
1550
+ }
1551
+ } else {
1552
+ // Drop the signature, since there's no way for a signature to sign itself
1553
+ subScript.findAndDelete(new Script().writeBuffer(bufSig))
1554
+ }
1555
+ }
1556
+
1557
+ let fSuccess = true
1558
+ while (fSuccess &amp;&amp; nSigsCount > 0) {
1559
+ // valtype&amp; vchSig = stacktop(-isig)
1560
+ let bufSig = this.stack[this.stack.length - isig]
1561
+ // valtype&amp; vchPubKey = stacktop(-ikey)
1562
+ let bufPubKey = this.stack[this.stack.length - ikey]
1563
+
1564
+ if (
1565
+ !this.checkSigEncoding(bufSig) ||
1566
+ !this.checkPubKeyEncoding(bufPubKey)
1567
+ ) {
1568
+ // serror is set
1569
+ return false
1570
+ }
1571
+
1572
+ let fOk
1573
+ try {
1574
+ let sig = new Sig().fromTxFormat(bufSig)
1575
+ let pubKey = new PubKey().fromBuffer(bufPubKey, false)
1576
+ fOk = this.tx.verify(
1577
+ sig,
1578
+ pubKey,
1579
+ this.nIn,
1580
+ subScript,
1581
+ Boolean(this.flags &amp; Interp.SCRIPT_VERIFY_LOW_S),
1582
+ this.valueBn,
1583
+ this.flags
1584
+ )
1585
+ } catch (e) {
1586
+ // invalid sig or pubKey
1587
+ fOk = false
1588
+ }
1589
+
1590
+ if (fOk) {
1591
+ isig++
1592
+ nSigsCount--
1593
+ }
1594
+ ikey++
1595
+ nKeysCount--
1596
+
1597
+ // If there are more signatures left than keys left,
1598
+ // then too many signatures have failed
1599
+ if (nSigsCount > nKeysCount) {
1600
+ fSuccess = false
1601
+ }
1602
+ }
1603
+
1604
+ // Clean up stack of actual arguments
1605
+ while (i-- > 1) {
1606
+ this.stack.pop()
1607
+ }
1608
+
1609
+ // A bug causes CHECKMULTISIG to consume one extra argument
1610
+ // whose contents were not checked in any way.
1611
+ //
1612
+ // Unfortunately this is a potential source of mutability,
1613
+ // so optionally verify it is exactly equal to zero prior
1614
+ // to removing it from the stack.
1615
+ if (this.stack.length &lt; 1) {
1616
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1617
+ return false
1618
+ }
1619
+ if (
1620
+ this.flags &amp; Interp.SCRIPT_VERIFY_NULLDUMMY &amp;&amp;
1621
+ this.stack[this.stack.length - 1].length
1622
+ ) {
1623
+ this.errStr = 'SCRIPT_ERR_SIG_NULLDUMMY'
1624
+ return false
1625
+ }
1626
+ this.stack.pop()
1627
+
1628
+ // stack.push_back(fSuccess ? vchTrue : vchFalse)
1629
+ this.stack.push(fSuccess ? Interp.true : Interp.false)
1630
+
1631
+ if (opCodeNum === OpCode.OP_CHECKMULTISIGVERIFY) {
1632
+ if (fSuccess) {
1633
+ this.stack.pop()
1634
+ } else {
1635
+ this.errStr = 'SCRIPT_ERR_CHECKMULTISIGVERIFY'
1636
+ return false
1637
+ }
1638
+ }
1639
+ }
1640
+ break
1641
+
1642
+ //
1643
+ // Byte string operations
1644
+ //
1645
+ case OpCode.OP_CAT:
1646
+ if (this.stack.length &lt; 2) {
1647
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1648
+ return false
1649
+ }
1650
+
1651
+ let vch1 = this.stack[this.stack.length - 2]
1652
+ let vch2 = this.stack[this.stack.length - 1]
1653
+
1654
+ this.stack[this.stack.length - 2] = Buffer.concat([vch1, vch2])
1655
+ this.stack.pop()
1656
+ break
1657
+
1658
+ case OpCode.OP_SPLIT:
1659
+ if (this.stack.length &lt; 2) {
1660
+ this.errStr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'
1661
+ return false
1662
+ }
1663
+
1664
+ let data = this.stack[this.stack.length - 2]
1665
+ let position = new Bn().fromScriptNumBuffer(
1666
+ this.stack[this.stack.length - 1],
1667
+ fRequireMinimal
1668
+ )
1669
+
1670
+ if(position.lt(0) || position.gt(data.length)) {
1671
+ this.errStr = 'SCRIPT_ERR_INVALID_SPLIT_RANGE'
1672
+ return false
1673
+ }
1674
+
1675
+ let n1 = data.slice(0, position)
1676
+ let n2 = data.slice(position)
1677
+
1678
+ this.stack.pop()
1679
+ this.stack.pop()
1680
+
1681
+ this.stack.push(n1)
1682
+ this.stack.push(n2)
1683
+
1684
+ break
1685
+ // input: a b
1686
+ // output: out
1687
+ // Converts numeric value a into byte sequence of length b.
1688
+ case OpCode.OP_NUM2BIN:
1689
+ if (this.stack.length &lt; 2) {
1690
+ this.errStr = 'OP_NUM2BIN requires at least two items to be on the stack.'
1691
+ }
1692
+
1693
+ let size = new Bn().fromScriptNumBuffer(
1694
+ this.stack[this.stack.length - 1],
1695
+ fRequireMinimal,
1696
+ Interp.DEFAULT_SCRIPT_NUM_LENGTH_POLICY_AFTER_GENESIS
1697
+ ).toNumber()
1698
+ if (size > Interp.MAX_SCRIPT_ELEMENT_SIZE) {
1699
+ this.errStr=`It's not currently possible to push data larger than ${Interp.MAX_SCRIPT_ELEMENT_SIZE} bytes.`
1700
+ }
1701
+
1702
+ this.stack.pop()
1703
+ let rawnum = this.stack[this.stack.length - 1]
1704
+ // Try to see if we can fit that number in the number of
1705
+ // byte requested.
1706
+ rawnum = minimallyEncode(rawnum)
1707
+
1708
+ if (rawnum.length > size) {
1709
+ this.errStr='OP_NUM2BIN requires that the size expressed in the top stack item is large enough to hold the value expressed in the second-from-top stack item.'
1710
+ }
1711
+
1712
+ // We already have an element of the right size, we
1713
+ // don't need to do anything.
1714
+ if (rawnum.length === size) {
1715
+ this.stack[this.stack.length - 1] = rawnum
1716
+ break
1717
+ }
1718
+
1719
+ let signbit = 0x00
1720
+ if (rawnum.length > 0) {
1721
+ signbit = rawnum[rawnum.length - 1] &amp; 0x80
1722
+ rawnum[rawnum.length - 1] &amp;= 0x7f
1723
+ }
1724
+
1725
+ let num = new Array(size)
1726
+ num.fill(0)
1727
+ let n
1728
+ for (n = 0; n &lt; size; n++) {
1729
+ num[n] = rawnum[n]
1730
+ }
1731
+ n = rawnum.length - 1
1732
+ while (n++ &lt; size - 2) {
1733
+ num[n] = 0x00
1734
+ }
1735
+
1736
+ num[n] = signbit
1737
+
1738
+ this.stack[this.stack.length - 1] = Buffer.from(new Uint8Array(num).buffer, "binary")
1739
+ break
1740
+
1741
+
1742
+ // input: x
1743
+ // output: out
1744
+ // Converts byte sequence x into a numeric value.
1745
+ case OpCode.OP_BIN2NUM:
1746
+ if (this.stack.length &lt; 1) {
1747
+ this.errStr='OP_BIN2NUM requires at least one item to be on the stack.'
1748
+ }
1749
+ let tmp1 = this.stack[this.stack.length - 1]
1750
+
1751
+ let tmp2 = minimallyEncode(tmp1)
1752
+ // The resulting number must be a valid number.
1753
+ this.stack[this.stack.length - 1] = new Bn().fromScriptNumBuffer(tmp2, fRequireMinimal, Interp.DEFAULT_SCRIPT_NUM_LENGTH_POLICY_AFTER_GENESIS)
1754
+
1755
+ break
1756
+ default:
1757
+ this.errStr = 'SCRIPT_ERR_BAD_OPCODE'
1758
+ return false
1759
+ }
1760
+ }
1761
+
1762
+ return true
1763
+ }
1764
+
1765
+ /**
1766
+ * This function has the same interface as bitcoin core's VerifyScript and is
1767
+ * the function you want to use to know if a particular input in a
1768
+ * transaction is valid or not. It simply iterates over the results generated
1769
+ * by the results method.
1770
+ */
1771
+ verify (scriptSig, scriptPubKey, tx, nIn, flags, valueBn) {
1772
+ let results = this.results(
1773
+ scriptSig,
1774
+ scriptPubKey,
1775
+ tx,
1776
+ nIn,
1777
+ flags,
1778
+ valueBn
1779
+ )
1780
+ for (let success of results) {
1781
+ if (!success) {
1782
+ return false
1783
+ }
1784
+ }
1785
+ return true
1786
+ }
1787
+
1788
+ /**
1789
+ * Gives you the results of the execution each operation of the scripSig and
1790
+ * scriptPubKey corresponding to a particular input (nIn) for the concerned
1791
+ * transaction (tx). Each result can be either true or false. If true, then
1792
+ * the operation did not invalidate the transaction. If false, then the
1793
+ * operation has invalidated the script, and the transaction is not valid.
1794
+ * flags is a number that can pass in some special flags, such as whether or
1795
+ * not to execute the redeemScript in a p2sh transaction.
1796
+ *
1797
+ * This method is translated from bitcoin core's VerifyScript. This function
1798
+ * is a generator, thus you can and need to iterate through it. To
1799
+ * automatically return true or false, use the verify method.
1800
+ */
1801
+ * results (scriptSig, scriptPubKey, tx, nIn, flags, valueBn) {
1802
+ let stackCopy
1803
+
1804
+ this.fromObject({
1805
+ script: scriptSig,
1806
+ tx: tx,
1807
+ nIn: nIn,
1808
+ flags: flags,
1809
+ valueBn: valueBn
1810
+ })
1811
+
1812
+ if (
1813
+ (flags &amp; Interp.SCRIPT_VERIFY_SIGPUSHONLY) !== 0 &amp;&amp;
1814
+ !scriptSig.isPushOnly()
1815
+ ) {
1816
+ this.errStr = this.errStr || 'SCRIPT_ERR_SIG_PUSHONLY'
1817
+ yield false
1818
+ }
1819
+
1820
+ yield * this.eval()
1821
+
1822
+ if (flags &amp; Interp.SCRIPT_VERIFY_P2SH) {
1823
+ stackCopy = this.stack.slice()
1824
+ }
1825
+
1826
+ let stack = this.stack
1827
+ this.initialize()
1828
+ this.fromObject({
1829
+ script: scriptPubKey,
1830
+ stack: stack,
1831
+ tx: tx,
1832
+ nIn: nIn,
1833
+ flags: flags,
1834
+ valueBn: valueBn
1835
+ })
1836
+
1837
+ yield * this.eval()
1838
+
1839
+ if (this.stack.length === 0) {
1840
+ this.errStr = this.errStr || 'SCRIPT_ERR_EVAL_FALSE'
1841
+ yield false
1842
+ }
1843
+
1844
+ let buf = this.stack[this.stack.length - 1]
1845
+ if (!Interp.castToBool(buf)) {
1846
+ this.errStr = this.errStr || 'SCRIPT_ERR_EVAL_FALSE'
1847
+ yield false
1848
+ }
1849
+
1850
+ // Additional validation for spend-to-script-hash transactions:
1851
+ if (flags &amp; Interp.SCRIPT_VERIFY_P2SH &amp;&amp; scriptPubKey.isScriptHashOut()) {
1852
+ // scriptSig must be literals-only or validation fails
1853
+ if (!scriptSig.isPushOnly()) {
1854
+ this.errStr = this.errStr || 'SCRIPT_ERR_SIG_PUSHONLY'
1855
+ yield false
1856
+ }
1857
+
1858
+ // Restore stack.
1859
+ let tmp = stack
1860
+ stack = stackCopy
1861
+ stackCopy = tmp
1862
+
1863
+ // stack cannot be empty here, because if it was the
1864
+ // P2SH HASH &lt;> EQUAL scriptPubKey would be evaluated with
1865
+ // an empty stack and the EvalScript above would yield false.
1866
+ if (stack.length === 0) {
1867
+ throw new Error('internal error - stack copy empty')
1868
+ }
1869
+
1870
+ let pubKeySerialized = stack[stack.length - 1]
1871
+ let scriptPubKey2 = new Script().fromBuffer(pubKeySerialized)
1872
+ stack.pop()
1873
+
1874
+ this.initialize()
1875
+ this.fromObject({
1876
+ script: scriptPubKey2,
1877
+ stack: stack,
1878
+ tx: tx,
1879
+ nIn: nIn,
1880
+ flags: flags,
1881
+ valueBn: valueBn
1882
+ })
1883
+
1884
+ yield * this.eval()
1885
+
1886
+ if (stack.length === 0) {
1887
+ this.errStr = this.errStr || 'SCRIPT_ERR_EVAL_FALSE'
1888
+ yield false
1889
+ }
1890
+
1891
+ if (!Interp.castToBool(stack[stack.length - 1])) {
1892
+ this.errStr = this.errStr || 'SCRIPT_ERR_EVAL_FALSE'
1893
+ yield false
1894
+ } else {
1895
+ yield true
1896
+ }
1897
+ }
1898
+
1899
+ // The CLEANSTACK check is only performed after potential P2SH evaluation,
1900
+ // as the non-P2SH evaluation of a P2SH script will obviously not result in
1901
+ // a clean stack (the P2SH inputs remain).
1902
+ if ((flags &amp; Interp.SCRIPT_VERIFY_CLEANSTACK) !== 0) {
1903
+ // Disallow CLEANSTACK without P2SH, as otherwise a switch
1904
+ // CLEANSTACK->P2SH+CLEANSTACK would be possible, which is not a softfork
1905
+ // (and P2SH should be one).
1906
+ if (!(flags &amp; Interp.SCRIPT_VERIFY_P2SH)) {
1907
+ throw new Error('cannot use CLEANSTACK without P2SH')
1908
+ }
1909
+ if (stack.length !== 1) {
1910
+ this.errStr = this.errStr || 'SCRIPT_ERR_CLEANSTACK'
1911
+ yield false
1912
+ }
1913
+ }
1914
+
1915
+ yield true
1916
+ }
1917
+
1918
+ /**
1919
+ * If the script has failed, this methods returns valuable debug
1920
+ * information about exactly where the script failed. It is a
1921
+ * JSON-compatible object so it can be easily stringified. pc refers to the
1922
+ * currently executing opcode.
1923
+ */
1924
+ getDebugObject () {
1925
+ let pc = this.pc - 1 // pc is incremented immediately after getting
1926
+ return {
1927
+ errStr: this.errStr,
1928
+ scriptStr: this.script ? this.script.toString() : 'no script found',
1929
+ pc: pc,
1930
+ stack: this.stack.map(buf => buf.toString('hex')),
1931
+ altStack: this.altStack.map(buf => buf.toString('hex')),
1932
+ opCodeStr: this.script
1933
+ ? OpCode.fromNumber(this.script.chunks[pc].opCodeNum).toString()
1934
+ : 'no script found'
1935
+ }
1936
+ }
1937
+
1938
+ getDebugString () {
1939
+ return JSON.stringify(this.getDebugObject(), null, 2)
1940
+ }
1941
+ }
1942
+
1943
+ Interp.true = Buffer.from([1])
1944
+ Interp.false = Buffer.from([])
1945
+ // TODO: https://github.com/bitcoin-sv/bitcoin-sv/blob/b489c32ef55d428c5c3825d5526de018031a20af/src/policy/policy.h
1946
+ /** Maximum stack memory usage (used instead of MAX_SCRIPT_ELEMENT_SIZE and MAX_STACK_ELEMENTS) after Genesis. **/
1947
+
1948
+ Interp.MAX_SCRIPT_ELEMENT_SIZE = 500*1000
1949
+ Interp.DEFAULT_SCRIPT_NUM_LENGTH_POLICY_AFTER_GENESIS = 10*1000 // 10KB
1950
+
1951
+ Interp.LOCKTIME_THRESHOLD = 500000000 // Tue Nov 5 00:53:20 1985 UTC
1952
+
1953
+ // flags taken from bitcoin core
1954
+ // bitcoin core commit: b5d1b1092998bc95313856d535c632ea5a8f9104
1955
+ Interp.SCRIPT_VERIFY_NONE = 0
1956
+
1957
+ // Evaluate P2SH subScripts (softfork safe, Bip16).
1958
+ Interp.SCRIPT_VERIFY_P2SH = 1 &lt;&lt; 0
1959
+
1960
+ // Passing a non-strict-DER signature or one with undefined hashtype to a checksig operation causes script failure.
1961
+ // Passing a pubKey that is not (0x04 + 64 bytes) or (0x02 or 0x03 + 32 bytes) to checksig causes that pubKey to be
1962
+ // skipped (not softfork safe: this flag can widen the validity of OP_CHECKSIG OP_NOT).
1963
+ Interp.SCRIPT_VERIFY_STRICTENC = 1 &lt;&lt; 1
1964
+
1965
+ // Passing a non-strict-DER signature to a checksig operation causes script failure (softfork safe, Bip62 rule 1)
1966
+ Interp.SCRIPT_VERIFY_DERSIG = 1 &lt;&lt; 2
1967
+
1968
+ // Passing a non-strict-DER signature or one with S > order/2 to a checksig operation causes script failure
1969
+ // (softfork safe, Bip62 rule 5).
1970
+ Interp.SCRIPT_VERIFY_LOW_S = 1 &lt;&lt; 3
1971
+
1972
+ // verify dummy stack item consumed by CHECKMULTISIG is of zero-length (softfork safe, Bip62 rule 7).
1973
+ Interp.SCRIPT_VERIFY_NULLDUMMY = 1 &lt;&lt; 4
1974
+
1975
+ // Using a non-push operator in the scriptSig causes script failure (softfork safe, Bip62 rule 2).
1976
+ Interp.SCRIPT_VERIFY_SIGPUSHONLY = 1 &lt;&lt; 5
1977
+
1978
+ // Require minimal encodings for all push operations (OP_0... OP_16, OP_1NEGATE where possible, direct
1979
+ // pushes up to 75 bytes, OP_PUSHDATA up to 255 bytes, OP_PUSHDATA2 for anything larger). Evaluating
1980
+ // any other push causes the script to fail (Bip62 rule 3).
1981
+ // In addition, whenever a stack element is interpreted as a number, it must be of minimal length (Bip62 rule 4).
1982
+ // (softfork safe)
1983
+ Interp.SCRIPT_VERIFY_MINIMALDATA = 1 &lt;&lt; 6
1984
+
1985
+ // Discourage use of NOPs reserved for upgrades (NOP1-10)
1986
+ //
1987
+ // Provided so that nodes can avoid accepting or mining transactions
1988
+ // containing executed NOP's whose meaning may change after a soft-fork,
1989
+ // thus rendering the script invalid; with this flag set executing
1990
+ // discouraged NOPs fails the script. This verification flag will never be
1991
+ // a mandatory flag applied to scripts in a block. NOPs that are not
1992
+ // executed, e.g. within an unexecuted IF ENDIF block, are *not* rejected.
1993
+ Interp.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS = 1 &lt;&lt; 7
1994
+
1995
+ // Require that only a single stack element remains after evaluation. This
1996
+ // changes the success criterion from "At least one stack element must
1997
+ // remain, and when interpreted as a boolean, it must be true" to "Exactly
1998
+ // one stack element must remain, and when interpreted as a boolean, it must
1999
+ // be true". (softfork safe, Bip62 rule 6)
2000
+ // Note: CLEANSTACK should never be used without P2SH.
2001
+ Interp.SCRIPT_VERIFY_CLEANSTACK = 1 &lt;&lt; 8
2002
+
2003
+ // Verify CHECKLOCKTIMEVERIFY
2004
+ //
2005
+ // See Bip65 for details.
2006
+ Interp.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY = 1 &lt;&lt; 9
2007
+
2008
+ // support CHECKSEQUENCEVERIFY opCode
2009
+ //
2010
+ // See Bip112 for details
2011
+ Interp.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY = 1 &lt;&lt; 10
2012
+
2013
+ // used for UAHF
2014
+ // https://github.com/Bitcoin-UAHF/spec/blob/master/replay-protected-sighash.md
2015
+ Interp.SCRIPT_ENABLE_SIGHASH_FORKID = 1 &lt;&lt; 16
2016
+
2017
+ // These are the things we wish to verify by default. At the time of writing,
2018
+ // P2SH and CHECKLOCKTIMEVERIFY are both active, but CHECKSEQUENCEVERIFY is
2019
+ // not.
2020
+
2021
+
2022
+ // https://github.com/bitcoin-sv/bitcoin-sv/blob/86eb5e8bdf5573c3cd844a1d81bd4fb151b909e0/src/policy/policy.h#L176
2023
+ // https://github.com/bitcoin-sv/bitcoin-sv/blob/86eb5e8bdf5573c3cd844a1d81bd4fb151b909e0/src/script/standard.h#L41
2024
+ Interp.defaultFlags = Interp.SCRIPT_VERIFY_P2SH |
2025
+ Interp.SCRIPT_VERIFY_STRICTENC |
2026
+ Interp.SCRIPT_ENABLE_SIGHASH_FORKID |
2027
+ Interp.SCRIPT_VERIFY_LOW_S |
2028
+ Interp.SCRIPT_VERIFY_NULLDUMMY |
2029
+ Interp.SCRIPT_VERIFY_DERSIG |
2030
+ Interp.SCRIPT_VERIFY_MINIMALDATA |
2031
+ Interp.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS |
2032
+ Interp.SCRIPT_VERIFY_CLEANSTACK |
2033
+ Interp.SCRIPT_VERIFY_SIGPUSHONLY |
2034
+ Interp.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY |
2035
+ Interp.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
2036
+
2037
+
2038
+ // Interp.SCRIPT_VERIFY_P2SH | Interp.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
2039
+ // Interp.defaultFlags = Interp.SCRIPT_VERIFY_P2SH |
2040
+
2041
+ export { Interp }
2042
+ </code></pre>
2043
+ </article>
2044
+ </section>
2045
+
2046
+
2047
+
2048
+
2049
+ </div>
2050
+
2051
+ <nav>
2052
+ <h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="Sig.html">Sig</a></li></ul><h3>Global</h3><ul><li><a href="global.html#decorate">decorate</a></li></ul>
2053
+ </nav>
2054
+
2055
+ <br class="clear">
2056
+
2057
+ <footer>
2058
+ Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 4.0.4</a> on Fri Feb 28 2025 03:51:24 GMT+0100 (hora estándar de Europa central)
2059
+ </footer>
2060
+
2061
+ <script> prettyPrint(); </script>
2062
+ <script src="scripts/linenumber.js"> </script>
2063
+ </body>
2064
+ </html>