bsv2 2.0.13

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