@onekeyfe/kaspa-core-lib 1.0.0-alpha.1

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 (53) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +59 -0
  3. package/index.d.ts +410 -0
  4. package/index.js +93 -0
  5. package/lib/address.js +792 -0
  6. package/lib/block/block.js +281 -0
  7. package/lib/block/blockheader.js +296 -0
  8. package/lib/block/index.js +4 -0
  9. package/lib/block/merkleblock.js +313 -0
  10. package/lib/crypto/bn.js +218 -0
  11. package/lib/crypto/ecdsa.js +296 -0
  12. package/lib/crypto/hash.js +85 -0
  13. package/lib/crypto/point.js +166 -0
  14. package/lib/crypto/random.js +57 -0
  15. package/lib/crypto/schnorr.js +287 -0
  16. package/lib/crypto/signature.js +441 -0
  17. package/lib/encoding/base58.js +70 -0
  18. package/lib/encoding/base58check.js +95 -0
  19. package/lib/encoding/bufferreader.js +202 -0
  20. package/lib/encoding/bufferwriter.js +155 -0
  21. package/lib/encoding/varint.js +72 -0
  22. package/lib/errors/index.js +61 -0
  23. package/lib/errors/spec.js +191 -0
  24. package/lib/hdprivatekey.js +646 -0
  25. package/lib/hdpublickey.js +496 -0
  26. package/lib/networks.js +277 -0
  27. package/lib/opcode.js +261 -0
  28. package/lib/privatekey.js +431 -0
  29. package/lib/publickey.js +375 -0
  30. package/lib/script/index.js +3 -0
  31. package/lib/script/interpreter.js +2107 -0
  32. package/lib/script/script.js +1163 -0
  33. package/lib/transaction/index.js +7 -0
  34. package/lib/transaction/input/index.js +6 -0
  35. package/lib/transaction/input/input.js +375 -0
  36. package/lib/transaction/input/multisig.js +221 -0
  37. package/lib/transaction/input/multisigscripthash.js +178 -0
  38. package/lib/transaction/input/publickey.js +91 -0
  39. package/lib/transaction/input/publickeyhash.js +100 -0
  40. package/lib/transaction/output.js +188 -0
  41. package/lib/transaction/sighash.js +534 -0
  42. package/lib/transaction/signature.js +89 -0
  43. package/lib/transaction/transaction.js +1384 -0
  44. package/lib/transaction/unspentoutput.js +109 -0
  45. package/lib/unit.js +238 -0
  46. package/lib/uri.js +223 -0
  47. package/lib/util/base32.js +63 -0
  48. package/lib/util/buffer.js +162 -0
  49. package/lib/util/convertBits.js +62 -0
  50. package/lib/util/js.js +110 -0
  51. package/lib/util/log.js +10 -0
  52. package/lib/util/preconditions.js +34 -0
  53. package/package.json +62 -0
@@ -0,0 +1,2107 @@
1
+ 'use strict';
2
+
3
+ var _ = require('lodash');
4
+
5
+ var Script = require('./script');
6
+ var Opcode = require('../opcode');
7
+ var BN = require('../crypto/bn');
8
+ var Hash = require('../crypto/hash');
9
+ var Signature = require('../crypto/signature');
10
+ var PublicKey = require('../publickey');
11
+ var ECDSA = require('../crypto/ecdsa');
12
+ var Schnorr = require('../crypto/schnorr');
13
+
14
+
15
+
16
+ /**
17
+ * Bitcoin transactions contain scripts. Each input has a script called the
18
+ * scriptSig, and each output has a script called the scriptPubkey. To validate
19
+ * an input, the input's script is concatenated with the referenced output script,
20
+ * and the result is executed. If at the end of execution the stack contains a
21
+ * "true" value, then the transaction is valid.
22
+ *
23
+ * The primary way to use this class is via the verify function.
24
+ * e.g., Interpreter().verify( ... );
25
+ */
26
+ var Interpreter = function Interpreter(obj) {
27
+ if (!(this instanceof Interpreter)) {
28
+ return new Interpreter(obj);
29
+ }
30
+ if (obj) {
31
+ this.initialize();
32
+ this.set(obj);
33
+ } else {
34
+ this.initialize();
35
+ }
36
+ };
37
+
38
+ /**
39
+ * Verifies a Script by executing it and returns true if it is valid.
40
+ * This function needs to be provided with the scriptSig and the scriptPubkey
41
+ * separately.
42
+ * @param {Script} scriptSig - the script's first part (corresponding to the tx input)
43
+ * @param {Script} scriptPubkey - the script's last part (corresponding to the tx output)
44
+ * @param {Transaction=} tx - the Transaction containing the scriptSig in one input (used
45
+ * to check signature validity for some opcodes like OP_CHECKSIG)
46
+ * @param {number} nin - index of the transaction input containing the scriptSig verified.
47
+ * @param {number} flags - evaluation flags. See Interpreter.SCRIPT_* constants
48
+ * @param {number} satoshisBN - amount in satoshis of the input to be verified (when FORKID signhash is used)
49
+ *
50
+ * Translated from bitcoind's VerifyScript
51
+ */
52
+ Interpreter.prototype.verify = function(scriptSig, scriptPubkey, tx, nin, flags, satoshisBN) {
53
+ var Transaction = require('../transaction');
54
+
55
+ if (_.isUndefined(tx)) {
56
+ tx = new Transaction();
57
+ }
58
+ if (_.isUndefined(nin)) {
59
+ nin = 0;
60
+ }
61
+ if (_.isUndefined(flags)) {
62
+ flags = 0;
63
+ }
64
+
65
+ // If FORKID is enabled, we also ensure strict encoding.
66
+ if (flags & Interpreter.SCRIPT_ENABLE_SIGHASH_FORKID) {
67
+ flags |= Interpreter.SCRIPT_VERIFY_STRICTENC;
68
+
69
+ // If FORKID is enabled, we need the input amount.
70
+ if (!satoshisBN) {
71
+ throw new Error('internal error - need satoshisBN to verify FORKID transactions');
72
+ }
73
+ }
74
+
75
+ this.set({
76
+ script: scriptSig,
77
+ tx: tx,
78
+ nin: nin,
79
+ flags: flags,
80
+ satoshisBN: satoshisBN,
81
+ });
82
+ var stackCopy;
83
+
84
+ if ((flags & Interpreter.SCRIPT_VERIFY_SIGPUSHONLY) !== 0 && !scriptSig.isPushOnly()) {
85
+ this.errstr = 'SCRIPT_ERR_SIG_PUSHONLY';
86
+ return false;
87
+ }
88
+
89
+ // evaluate scriptSig
90
+ if (!this.evaluate()) {
91
+ return false;
92
+ }
93
+
94
+ if (flags & Interpreter.SCRIPT_VERIFY_P2SH) {
95
+ stackCopy = this.stack.slice();
96
+ }
97
+
98
+ var stack = this.stack;
99
+ this.initialize();
100
+ this.set({
101
+ script: scriptPubkey,
102
+ stack: stack,
103
+ tx: tx,
104
+ nin: nin,
105
+ flags: flags,
106
+ satoshisBN: satoshisBN,
107
+ });
108
+
109
+ // evaluate scriptPubkey
110
+ if (!this.evaluate()) {
111
+ return false;
112
+ }
113
+
114
+ if (this.stack.length === 0) {
115
+ this.errstr = 'SCRIPT_ERR_EVAL_FALSE_NO_RESULT';
116
+ return false;
117
+ }
118
+
119
+ var buf = this.stack[this.stack.length - 1];
120
+ if (!Interpreter.castToBool(buf)) {
121
+ this.errstr = 'SCRIPT_ERR_EVAL_FALSE_IN_STACK';
122
+ return false;
123
+ }
124
+
125
+ // Additional validation for spend-to-script-hash transactions:
126
+ if ((flags & Interpreter.SCRIPT_VERIFY_P2SH) && scriptPubkey.isScriptHashOut()) {
127
+ // scriptSig must be literals-only or validation fails
128
+ if (!scriptSig.isPushOnly()) {
129
+ this.errstr = 'SCRIPT_ERR_SIG_PUSHONLY';
130
+ return false;
131
+ }
132
+
133
+ // stackCopy cannot be empty here, because if it was the
134
+ // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
135
+ // an empty stack and the EvalScript above would return false.
136
+ if (stackCopy.length === 0) {
137
+ throw new Error('internal error - stack copy empty');
138
+ }
139
+
140
+ var redeemScriptSerialized = stackCopy[stackCopy.length - 1];
141
+ var redeemScript = Script.fromBuffer(redeemScriptSerialized);
142
+ stackCopy.pop();
143
+
144
+ this.initialize();
145
+ this.set({
146
+ script: redeemScript,
147
+ stack: stackCopy,
148
+ tx: tx,
149
+ nin: nin,
150
+ flags: flags,
151
+ satoshisBN: satoshisBN,
152
+ });
153
+
154
+ // evaluate redeemScript
155
+ if (!this.evaluate()) {
156
+ return false;
157
+ }
158
+
159
+ if (stackCopy.length === 0) {
160
+ this.errstr = 'SCRIPT_ERR_EVAL_FALSE_NO_P2SH_STACK';
161
+ return false;
162
+ }
163
+
164
+ if (!Interpreter.castToBool(stackCopy[stackCopy.length - 1])) {
165
+ this.errstr = 'SCRIPT_ERR_EVAL_FALSE_IN_P2SH_STACK';
166
+ return false;
167
+ }
168
+ }
169
+
170
+ // The CLEANSTACK check is only performed after potential P2SH evaluation,
171
+ // as the non-P2SH evaluation of a P2SH script will obviously not result in
172
+ // a clean stack (the P2SH inputs remain). The same holds for witness
173
+ // evaluation.
174
+ if ((flags & Interpreter.SCRIPT_VERIFY_CLEANSTACK) != 0) {
175
+ // Disallow CLEANSTACK without P2SH, as otherwise a switch
176
+ // CLEANSTACK->P2SH+CLEANSTACK would be possible, which is not a
177
+ // softfork (and P2SH should be one).
178
+ if ((flags & Interpreter.SCRIPT_VERIFY_P2SH) == 0) {
179
+ throw new Error('internal error - CLEANSTACK without P2SH');
180
+ }
181
+
182
+ if (stackCopy.length != 1) {
183
+ this.errstr = 'SCRIPT_ERR_CLEANSTACK';
184
+ return false;
185
+ }
186
+ }
187
+
188
+ return true;
189
+ };
190
+
191
+ module.exports = Interpreter;
192
+
193
+ Interpreter.prototype.initialize = function(obj) {
194
+ this.stack = [];
195
+ this.altstack = [];
196
+ this.pc = 0;
197
+ this.pbegincodehash = 0;
198
+ this.nOpCount = 0;
199
+ this.vfExec = [];
200
+ this.errstr = '';
201
+ this.flags = 0;
202
+ };
203
+
204
+ Interpreter.prototype.set = function(obj) {
205
+ this.script = obj.script || this.script;
206
+ this.tx = obj.tx || this.tx;
207
+ this.nin = typeof obj.nin !== 'undefined' ? obj.nin : this.nin;
208
+ this.satoshisBN = obj.satoshisBN || this.satoshisBN;
209
+ this.stack = obj.stack || this.stack;
210
+ this.altstack = obj.altack || this.altstack;
211
+ this.pc = typeof obj.pc !== 'undefined' ? obj.pc : this.pc;
212
+ this.pbegincodehash = typeof obj.pbegincodehash !== 'undefined' ? obj.pbegincodehash : this.pbegincodehash;
213
+ this.nOpCount = typeof obj.nOpCount !== 'undefined' ? obj.nOpCount : this.nOpCount;
214
+ this.vfExec = obj.vfExec || this.vfExec;
215
+ this.errstr = obj.errstr || this.errstr;
216
+ this.flags = typeof obj.flags !== 'undefined' ? obj.flags : this.flags;
217
+ };
218
+
219
+ Interpreter.true = Buffer.from([1]);
220
+ Interpreter.false = Buffer.from([]);
221
+
222
+ Interpreter.MAX_SCRIPT_ELEMENT_SIZE = 520;
223
+ Interpreter.MAXIMUM_ELEMENT_SIZE = 4;
224
+
225
+ Interpreter.LOCKTIME_THRESHOLD = 500000000;
226
+ Interpreter.LOCKTIME_THRESHOLD_BN = new BN(Interpreter.LOCKTIME_THRESHOLD);
227
+
228
+ // flags taken from bitcoind
229
+ // bitcoind commit: b5d1b1092998bc95313856d535c632ea5a8f9104
230
+ Interpreter.SCRIPT_VERIFY_NONE = 0;
231
+
232
+ // Evaluate P2SH subscripts (softfork safe, BIP16).
233
+ Interpreter.SCRIPT_VERIFY_P2SH = (1 << 0);
234
+
235
+ // Passing a non-strict-DER signature or one with undefined hashtype to a checksig operation causes script failure.
236
+ // Passing a pubkey that is not (0x04 + 64 bytes) or (0x02 or 0x03 + 32 bytes) to checksig causes that pubkey to be
237
+ // skipped (not softfork safe: this flag can widen the validity of OP_CHECKSIG OP_NOT).
238
+ Interpreter.SCRIPT_VERIFY_STRICTENC = (1 << 1);
239
+
240
+ // Passing a non-strict-DER signature to a checksig operation causes script failure (softfork safe, BIP62 rule 1)
241
+ Interpreter.SCRIPT_VERIFY_DERSIG = (1 << 2);
242
+
243
+ // Passing a non-strict-DER signature or one with S > order/2 to a checksig operation causes script failure
244
+ // (softfork safe, BIP62 rule 5).
245
+ Interpreter.SCRIPT_VERIFY_LOW_S = (1 << 3);
246
+
247
+ // verify dummy stack item consumed by CHECKMULTISIG is of zero-length (softfork safe, BIP62 rule 7).
248
+ Interpreter.SCRIPT_VERIFY_NULLDUMMY = (1 << 4);
249
+
250
+ // Using a non-push operator in the scriptSig causes script failure (softfork safe, BIP62 rule 2).
251
+ Interpreter.SCRIPT_VERIFY_SIGPUSHONLY = (1 << 5);
252
+
253
+ // Require minimal encodings for all push operations (OP_0... OP_16, OP_1NEGATE where possible, direct
254
+ // pushes up to 75 bytes, OP_PUSHDATA up to 255 bytes, OP_PUSHDATA2 for anything larger). Evaluating
255
+ // any other push causes the script to fail (BIP62 rule 3).
256
+ // In addition, whenever a stack element is interpreted as a number, it must be of minimal length (BIP62 rule 4).
257
+ // (softfork safe)
258
+ Interpreter.SCRIPT_VERIFY_MINIMALDATA = (1 << 6);
259
+
260
+ // Discourage use of NOPs reserved for upgrades (NOP1-10)
261
+ //
262
+ // Provided so that nodes can avoid accepting or mining transactions
263
+ // containing executed NOP's whose meaning may change after a soft-fork,
264
+ // thus rendering the script invalid; with this flag set executing
265
+ // discouraged NOPs fails the script. This verification flag will never be
266
+ // a mandatory flag applied to scripts in a block. NOPs that are not
267
+ // executed, e.g. within an unexecuted IF ENDIF block, are *not* rejected.
268
+ Interpreter.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS = (1 << 7);
269
+
270
+
271
+ // Require that only a single stack element remains after evaluation. This
272
+ // changes the success criterion from "At least one stack element must
273
+ // remain, and when interpreted as a boolean, it must be true" to "Exactly
274
+ // one stack element must remain, and when interpreted as a boolean, it must // be true".
275
+ // (softfork safe, BIP62 rule 6)
276
+ // Note: CLEANSTACK should never be used without P2SH or WITNESS.
277
+ Interpreter.SCRIPT_VERIFY_CLEANSTACK = (1 << 8),
278
+
279
+ // CLTV See BIP65 for details.
280
+ Interpreter.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY = (1 << 9);
281
+
282
+ // support CHECKSEQUENCEVERIFY opcode
283
+ //
284
+ // See BIP112 for details
285
+ Interpreter.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY = (1 << 10);
286
+
287
+ // Segwit script only: Require the argument of OP_IF/NOTIF to be exactly
288
+ // 0x01 or empty vector
289
+ //
290
+ Interpreter.SCRIPT_VERIFY_MINIMALIF = (1 << 13);
291
+
292
+ // Signature(s) must be empty vector if an CHECK(MULTI)SIG operation failed
293
+ //
294
+ Interpreter.SCRIPT_VERIFY_NULLFAIL = (1 << 14);
295
+
296
+ // Public keys in scripts must be compressed
297
+ Interpreter.SCRIPT_VERIFY_COMPRESSED_PUBKEYTYPE = (1 << 15);
298
+
299
+ // Do we accept signature using SIGHASH_FORKID
300
+ //
301
+ Interpreter.SCRIPT_ENABLE_SIGHASH_FORKID = (1 << 16);
302
+
303
+ // Do we accept activate replay protection using a different fork id.
304
+ //
305
+ Interpreter.SCRIPT_ENABLE_REPLAY_PROTECTION = (1 << 17);
306
+
307
+ // Enable new opcodes.
308
+ //
309
+ Interpreter.SCRIPT_ENABLE_CHECKDATASIG = (1 << 18),
310
+
311
+
312
+ // The exception to CLEANSTACK and P2SH for the recovery of coins sent
313
+ // to p2sh segwit addresses is not allowed.
314
+
315
+ Interpreter.SCRIPT_DISALLOW_SEGWIT_RECOVERY = (1 << 20)
316
+
317
+
318
+ // Whether to allow new OP_CHECKMULTISIG logic to trigger. (new multisig
319
+ // logic verifies faster, and only allows Schnorr signatures)
320
+ Interpreter.SCRIPT_ENABLE_SCHNORR_MULTISIG = (1 << 21),
321
+
322
+
323
+ /* Below flags apply in the context of BIP 68*/
324
+ /**
325
+ * If this flag set, CTxIn::nSequence is NOT interpreted as a relative
326
+ * lock-time.
327
+ */
328
+ Interpreter.SEQUENCE_LOCKTIME_DISABLE_FLAG = (1 << 31);
329
+
330
+ /**
331
+ * If CTxIn::nSequence encodes a relative lock-time and this flag is set,
332
+ * the relative lock-time has units of 512 seconds, otherwise it specifies
333
+ * blocks with a granularity of 1.
334
+ */
335
+ Interpreter.SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);
336
+
337
+ /**
338
+ * If CTxIn::nSequence encodes a relative lock-time, this mask is applied to
339
+ * extract that lock-time from the sequence field.
340
+ */
341
+ Interpreter.SEQUENCE_LOCKTIME_MASK = 0x0000ffff;
342
+
343
+
344
+ Interpreter.castToBool = function(buf) {
345
+ for (var i = 0; i < buf.length; i++) {
346
+ if (buf[i] !== 0) {
347
+ // can be negative zero
348
+ if (i === buf.length - 1 && buf[i] === 0x80) {
349
+ return false;
350
+ }
351
+ return true;
352
+ }
353
+ }
354
+ return false;
355
+ };
356
+
357
+ Interpreter.isSchnorrSig = function(buf) {
358
+ return (buf.length === 64 || buf.length === 65) && (buf[0] !== 0x30);
359
+ }
360
+
361
+ /**
362
+ * Translated from bitcoind's CheckSignatureEncoding
363
+ */
364
+ Interpreter.prototype.checkRawSignatureEncoding = function(buf) {
365
+ var sig;
366
+
367
+ //TODO update interpreter.js and necessary functions to match bitcoin-abc interpreter.cpp
368
+ if(Interpreter.isSchnorrSig(buf)) {
369
+ return true;
370
+ }
371
+
372
+
373
+ if ((this.flags & (Interpreter.SCRIPT_VERIFY_DERSIG | Interpreter.SCRIPT_VERIFY_LOW_S | Interpreter.SCRIPT_VERIFY_STRICTENC)) !== 0 && !Signature.isDER(buf)) {
374
+ this.errstr = 'SCRIPT_ERR_SIG_DER_INVALID_FORMAT';
375
+ return false;
376
+ } else if ((this.flags & Interpreter.SCRIPT_VERIFY_LOW_S) !== 0) {
377
+ sig = Signature.fromTxFormat(buf);
378
+ if (!sig.hasLowS()) {
379
+ this.errstr = 'SCRIPT_ERR_SIG_DER_HIGH_S';
380
+ return false;
381
+ }
382
+ }
383
+
384
+ return true;
385
+ };
386
+
387
+
388
+ // Back compat
389
+ Interpreter.prototype.checkSignatureEncoding =
390
+ Interpreter.prototype.checkTxSignatureEncoding = function(buf) {
391
+
392
+ // Empty signature. Not strictly DER encoded, but allowed to provide a
393
+ // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
394
+ if (buf.length == 0) {
395
+ return true;
396
+ }
397
+
398
+ if (!this.checkRawSignatureEncoding(buf.slice(0,buf.length-1))) {
399
+ return false;
400
+ }
401
+
402
+ if ((this.flags & Interpreter.SCRIPT_VERIFY_STRICTENC) !== 0) {
403
+ var sig = Signature.fromTxFormat(buf);
404
+ if (!sig.hasDefinedHashtype()) {
405
+ this.errstr = 'SCRIPT_ERR_SIG_HASHTYPE';
406
+ return false;
407
+ }
408
+ if (!(this.flags & Interpreter.SCRIPT_ENABLE_SIGHASH_FORKID) &&
409
+ (sig.nhashtype & Signature.SIGHASH_FORKID)) {
410
+ this.errstr = 'SCRIPT_ERR_ILLEGAL_FORKID';
411
+ return false;
412
+ }
413
+
414
+ if ( (this.flags & Interpreter.SCRIPT_ENABLE_SIGHASH_FORKID) &&
415
+ !(sig.nhashtype & Signature.SIGHASH_FORKID)) {
416
+ this.errstr = 'SCRIPT_ERR_MUST_USE_FORKID';
417
+ return false;
418
+ }
419
+ }
420
+
421
+ return true;
422
+ };
423
+
424
+ Interpreter.prototype.checkDataSignatureEncoding = function(buf) {
425
+ // Empty signature. Not strictly DER encoded, but allowed to provide a
426
+ // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
427
+ if (buf.length == 0) {
428
+ return true;
429
+ }
430
+
431
+ return this.checkRawSignatureEncoding(buf);
432
+ };
433
+
434
+
435
+
436
+
437
+ /**
438
+ * Translated from bitcoind's CheckPubKeyEncoding
439
+ */
440
+ Interpreter.prototype.checkPubkeyEncoding = function(buf) {
441
+ if ((this.flags & Interpreter.SCRIPT_VERIFY_STRICTENC) !== 0 && !(PublicKey.isValid(buf) || IsCompressedOrUncompressedPubkey(buf))) {
442
+ this.errstr = 'SCRIPT_ERR_PUBKEYTYPE';
443
+ return false;
444
+ }
445
+ return true;
446
+ };
447
+
448
+ function IsCompressedOrUncompressedPubkey(bufPubkey) {
449
+ switch(bufPubkey.length) {
450
+ case 33:
451
+ return bufPubkey[0] === 0x02 || bufPubkey[0] === 0x03;
452
+ case 64:
453
+ return bufPubkey[0] === 0x04;
454
+ default:
455
+ return false;
456
+ }
457
+ }
458
+
459
+
460
+
461
+ /**
462
+ *
463
+ * Check the buffer is minimally encoded (see https://github.com/bitcoincashorg/spec/blob/master/may-2018-reenabled-opcodes.md#op_bin2num)
464
+ *
465
+ *
466
+ */
467
+
468
+ Interpreter._isMinimallyEncoded = function(buf, nMaxNumSize) {
469
+ nMaxNumSize = nMaxNumSize || Interpreter.MAXIMUM_ELEMENT_SIZE;
470
+ if (buf.length > nMaxNumSize ) {
471
+ return false;
472
+ }
473
+
474
+ if (buf.length > 0) {
475
+ // Check that the number is encoded with the minimum possible number
476
+ // of bytes.
477
+ //
478
+ // If the most-significant-byte - excluding the sign bit - is zero
479
+ // then we're not minimal. Note how this test also rejects the
480
+ // negative-zero encoding, 0x80.
481
+ if ((buf[buf.length-1] & 0x7f) == 0) {
482
+ // One exception: if there's more than one byte and the most
483
+ // significant bit of the second-most-significant-byte is set it
484
+ // would conflict with the sign bit. An example of this case is
485
+ // +-255, which encode to 0xff00 and 0xff80 respectively.
486
+ // (big-endian).
487
+ if (buf.length <= 1 || (buf[buf.length - 2] & 0x80) == 0) {
488
+ return false;
489
+ }
490
+ }
491
+ }
492
+ return true;
493
+ };
494
+
495
+ /**
496
+ *
497
+ * minimally encode the buffer content
498
+ *
499
+ * @param {number} nMaxNumSize (max allowed size)
500
+ */
501
+ Interpreter._minimallyEncode = function(buf) {
502
+ if (buf.length == 0) {
503
+ return buf;
504
+ }
505
+
506
+ // If the last byte is not 0x00 or 0x80, we are minimally encoded.
507
+ var last = buf[buf.length - 1];
508
+ if (last & 0x7f) {
509
+ return buf;
510
+ }
511
+
512
+ // If the script is one byte long, then we have a zero, which encodes as an
513
+ // empty array.
514
+ if (buf.length == 1) {
515
+ return Buffer.from('');
516
+ }
517
+
518
+ // If the next byte has it sign bit set, then we are minimaly encoded.
519
+ if (buf[buf.length - 2] & 0x80) {
520
+ return buf;
521
+ }
522
+
523
+ // We are not minimally encoded, we need to figure out how much to trim.
524
+ for (var i = buf.length - 1; i > 0; i--) {
525
+ // We found a non zero byte, time to encode.
526
+ if (buf[i - 1] != 0) {
527
+ if (buf[i - 1] & 0x80) {
528
+ // We found a byte with it sign bit set so we need one more
529
+ // byte.
530
+ buf[i++] = last;
531
+ } else {
532
+ // the sign bit is clear, we can use it.
533
+ buf[i - 1] |= last;
534
+ }
535
+
536
+ return buf.slice(0,i);
537
+ }
538
+ }
539
+
540
+ // If we the whole thing is zeros, then we have a zero.
541
+ return Buffer.from('');
542
+ }
543
+
544
+
545
+
546
+ /**
547
+ * Based on bitcoind's EvalScript function, with the inner loop moved to
548
+ * Interpreter.prototype.step()
549
+ * bitcoind commit: b5d1b1092998bc95313856d535c632ea5a8f9104
550
+ */
551
+ Interpreter.prototype.evaluate = function() {
552
+ if (this.script.toBuffer().length > 10000) {
553
+ this.errstr = 'SCRIPT_ERR_SCRIPT_SIZE';
554
+ return false;
555
+ }
556
+
557
+ try {
558
+ while (this.pc < this.script.chunks.length) {
559
+ var fSuccess = this.step();
560
+ if (!fSuccess) {
561
+ return false;
562
+ }
563
+ }
564
+
565
+ // Size limits
566
+ if (this.stack.length + this.altstack.length > 1000) {
567
+ this.errstr = 'SCRIPT_ERR_STACK_SIZE';
568
+ return false;
569
+ }
570
+ } catch (e) {
571
+ this.errstr = 'SCRIPT_ERR_UNKNOWN_ERROR: ' + e;
572
+ return false;
573
+ }
574
+
575
+ if (this.vfExec.length > 0) {
576
+ this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL';
577
+ return false;
578
+ }
579
+
580
+ return true;
581
+ };
582
+
583
+ /**
584
+ * Checks a locktime parameter with the transaction's locktime.
585
+ * There are two times of nLockTime: lock-by-blockheight and lock-by-blocktime,
586
+ * distinguished by whether nLockTime < LOCKTIME_THRESHOLD = 500000000
587
+ *
588
+ * See the corresponding code on bitcoin core:
589
+ * https://github.com/bitcoin/bitcoin/blob/ffd75adce01a78b3461b3ff05bcc2b530a9ce994/src/script/interpreter.cpp#L1129
590
+ *
591
+ * @param {BN} nLockTime the locktime read from the script
592
+ * @return {boolean} true if the transaction's locktime is less than or equal to
593
+ * the transaction's locktime
594
+ */
595
+ Interpreter.prototype.checkLockTime = function(nLockTime) {
596
+
597
+ // We want to compare apples to apples, so fail the script
598
+ // unless the type of nLockTime being tested is the same as
599
+ // the nLockTime in the transaction.
600
+ if (!(
601
+ (this.tx.nLockTime < Interpreter.LOCKTIME_THRESHOLD && nLockTime.lt(Interpreter.LOCKTIME_THRESHOLD_BN)) ||
602
+ (this.tx.nLockTime >= Interpreter.LOCKTIME_THRESHOLD && nLockTime.gte(Interpreter.LOCKTIME_THRESHOLD_BN))
603
+ )) {
604
+ return false;
605
+ }
606
+
607
+ // Now that we know we're comparing apples-to-apples, the
608
+ // comparison is a simple numeric one.
609
+ if (nLockTime.gt(new BN(this.tx.nLockTime))) {
610
+ return false;
611
+ }
612
+
613
+ // Finally the nLockTime feature can be disabled and thus
614
+ // CHECKLOCKTIMEVERIFY bypassed if every txin has been
615
+ // finalized by setting nSequence to maxint. The
616
+ // transaction would be allowed into the blockchain, making
617
+ // the opcode ineffective.
618
+ //
619
+ // Testing if this vin is not final is sufficient to
620
+ // prevent this condition. Alternatively we could test all
621
+ // inputs, but testing just this input minimizes the data
622
+ // required to prove correct CHECKLOCKTIMEVERIFY execution.
623
+ if (!this.tx.inputs[this.nin].isFinal()) {
624
+ return false;
625
+ }
626
+
627
+ return true;
628
+ }
629
+
630
+
631
+ /**
632
+ * Checks a sequence parameter with the transaction's sequence.
633
+ * @param {BN} nSequence the sequence read from the script
634
+ * @return {boolean} true if the transaction's sequence is less than or equal to
635
+ * the transaction's sequence
636
+ */
637
+ Interpreter.prototype.checkSequence = function(nSequence) {
638
+
639
+ // Relative lock times are supported by comparing the passed in operand to
640
+ // the sequence number of the input.
641
+ var txToSequence = this.tx.inputs[this.nin].sequenceNumber;
642
+
643
+ // Fail if the transaction's version number is not set high enough to
644
+ // trigger BIP 68 rules.
645
+ if (this.tx.version < 2) {
646
+ return false;
647
+ }
648
+
649
+ // Sequence numbers with their most significant bit set are not consensus
650
+ // constrained. Testing that the transaction's sequence number do not have
651
+ // this bit set prevents using this property to get around a
652
+ // CHECKSEQUENCEVERIFY check.
653
+ if (txToSequence & SEQUENCE_LOCKTIME_DISABLE_FLAG) {
654
+ return false;
655
+ }
656
+
657
+ // Mask off any bits that do not have consensus-enforced meaning before
658
+ // doing the integer comparisons
659
+ var nLockTimeMask =
660
+ Interpreter.SEQUENCE_LOCKTIME_TYPE_FLAG | Interpreter.SEQUENCE_LOCKTIME_MASK;
661
+ var txToSequenceMasked = new BN(txToSequence & nLockTimeMask);
662
+ var nSequenceMasked = nSequence.and(nLockTimeMask);
663
+
664
+ // There are two kinds of nSequence: lock-by-blockheight and
665
+ // lock-by-blocktime, distinguished by whether nSequenceMasked <
666
+ // CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
667
+ //
668
+ // We want to compare apples to apples, so fail the script unless the type
669
+ // of nSequenceMasked being tested is the same as the nSequenceMasked in the
670
+ // transaction.
671
+ var SEQUENCE_LOCKTIME_TYPE_FLAG_BN = new BN(Interpreter.SEQUENCE_LOCKTIME_TYPE_FLAG);
672
+
673
+ if (!((txToSequenceMasked.lt(SEQUENCE_LOCKTIME_TYPE_FLAG_BN) &&
674
+ nSequenceMasked.lt(SEQUENCE_LOCKTIME_TYPE_FLAG_BN)) ||
675
+ (txToSequenceMasked.gte(SEQUENCE_LOCKTIME_TYPE_FLAG_BN) &&
676
+ nSequenceMasked.gte(SEQUENCE_LOCKTIME_TYPE_FLAG_BN)))) {
677
+ return false;
678
+ }
679
+
680
+ // Now that we know we're comparing apples-to-apples, the comparison is a
681
+ // simple numeric one.
682
+ if (nSequenceMasked.gt(txToSequenceMasked)) {
683
+ return false;
684
+ }
685
+ return true;
686
+ }
687
+
688
+ /**
689
+ * Implemented from bitcoin-abc
690
+ * https://github.com/Bitcoin-ABC/bitcoin-abc/blob/f8cbc0e2b439aa4030430a7b1ecbdafede0dd072/src/script/bitfield.cpp
691
+ * @param {*} dummy
692
+ * @param {*} size
693
+ */
694
+ function DecodeBitfield(dummy, size) {
695
+ if (size > 32) {
696
+ this.errstr = "INVALID_BITFIELD_SIZE";
697
+ return {result: false};
698
+ }
699
+
700
+ let bitfieldSize = Math.floor((size + 7) / 8);
701
+ let dummyBitlength = dummy.length;
702
+ if (dummyBitlength !== bitfieldSize) {
703
+ this.errstr = "INVALID_BITFIELD_SIZE";
704
+ return {result: false};
705
+ }
706
+
707
+ let bitfield = 0;
708
+ let dummyAs32Bit = Uint32Array.from(dummy);
709
+ // let one = new Uint8Array([1]);
710
+ // let oneAs64Bit = BigUint64Array.from(one);
711
+
712
+ for (let i = 0; i < bitfieldSize; i++) {
713
+ bitfield = bitfield | (dummyAs32Bit[i] << (8*i));
714
+ }
715
+
716
+ let mask = (0x01 << size) - 1
717
+ if((bitfield & mask) != bitfield) {
718
+ this.errstr = "INVALID_BIT_RANGE";
719
+ return {result: false};
720
+ }
721
+
722
+ return {result: true, bitfield: bitfield};
723
+ }
724
+
725
+ /**
726
+ * countBits
727
+ * Implemented from https://github.com/Bitcoin-ABC/bitcoin-abc/blob/f8cbc0e2b439aa4030430a7b1ecbdafede0dd072/src/util/bitmanip.h
728
+ * @param {*} v
729
+ */
730
+
731
+ function countBits(v) {
732
+ /**
733
+ * Computes the number of bits set in each group of 8bits then uses a
734
+ * multiplication to sum all of them in the 8 most significant bits and
735
+ * return these.
736
+ * More detailed explanation can be found at
737
+ * https://www.playingwithpointers.com/blog/swar.html
738
+ */
739
+ v = v - (((v) >> 1) & 0x55555555);
740
+ v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
741
+ return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
742
+ }
743
+
744
+ /**
745
+ * Based on the inner loop of bitcoind's EvalScript function
746
+ * bitcoind commit: b5d1b1092998bc95313856d535c632ea5a8f9104
747
+ */
748
+ Interpreter.prototype.step = function() {
749
+ var self = this;
750
+
751
+ function stacktop(i) {
752
+ return self.stack[self.stack.length+i];
753
+ }
754
+
755
+ function isOpcodeDisabled(opcode) {
756
+ switch (opcode) {
757
+ case Opcode.OP_INVERT:
758
+ case Opcode.OP_2MUL:
759
+ case Opcode.OP_2DIV:
760
+ case Opcode.OP_MUL:
761
+ case Opcode.OP_LSHIFT:
762
+ case Opcode.OP_RSHIFT:
763
+
764
+
765
+
766
+ // Disabled opcodes.
767
+ return true;
768
+
769
+ case Opcode.OP_DIV:
770
+ case Opcode.OP_MOD:
771
+ case Opcode.OP_SPLIT:
772
+ case Opcode.OP_CAT:
773
+ case Opcode.OP_AND:
774
+ case Opcode.OP_OR:
775
+ case Opcode.OP_XOR:
776
+ case Opcode.OP_BIN2NUM:
777
+ case Opcode.OP_NUM2BIN:
778
+ // Opcodes that have been reenabled and do not need any flag as for Nov 14,2018
779
+ return false;
780
+
781
+ default:
782
+ break;
783
+ }
784
+
785
+ return false;
786
+ }
787
+
788
+ var fRequireMinimal = (this.flags & Interpreter.SCRIPT_VERIFY_MINIMALDATA) !== 0;
789
+
790
+ //bool fExec = !count(vfExec.begin(), vfExec.end(), false);
791
+ var fExec = (this.vfExec.indexOf(false) === -1);
792
+ var buf, buf1, buf2, spliced, n, x1, x2, bn, bn1, bn2, bufSig, bufPubkey, bufMessage, subscript;
793
+ var sig, pubkey;
794
+ var fValue, fSuccess;
795
+
796
+ // Read instruction
797
+ var chunk = this.script.chunks[this.pc];
798
+ this.pc++;
799
+ var opcodenum = chunk.opcodenum;
800
+ if (_.isUndefined(opcodenum)) {
801
+ this.errstr = 'SCRIPT_ERR_UNDEFINED_OPCODE';
802
+ return false;
803
+ }
804
+ if (chunk.buf && chunk.buf.length > Interpreter.MAX_SCRIPT_ELEMENT_SIZE) {
805
+ this.errstr = 'SCRIPT_ERR_PUSH_SIZE';
806
+ return false;
807
+ }
808
+
809
+ // Note how Opcode.OP_RESERVED does not count towards the opcode limit.
810
+ if (opcodenum > Opcode.OP_16 && ++(this.nOpCount) > 201) {
811
+ this.errstr = 'SCRIPT_ERR_OP_COUNT';
812
+ return false;
813
+ }
814
+
815
+ if (isOpcodeDisabled(opcodenum)) {
816
+ this.errstr = 'SCRIPT_ERR_DISABLED_OPCODE';
817
+ return false;
818
+ }
819
+
820
+ if (fExec && 0 <= opcodenum && opcodenum <= Opcode.OP_PUSHDATA4) {
821
+ if (fRequireMinimal && !this.script.checkMinimalPush(this.pc - 1)) {
822
+ this.errstr = 'SCRIPT_ERR_MINIMALDATA';
823
+ return false;
824
+ }
825
+ if (!chunk.buf) {
826
+ this.stack.push(Interpreter.false);
827
+ } else if (chunk.len !== chunk.buf.length) {
828
+ throw new Error('Length of push value not equal to length of data');
829
+ } else {
830
+ this.stack.push(chunk.buf);
831
+ }
832
+ } else if (fExec || (Opcode.OP_IF <= opcodenum && opcodenum <= Opcode.OP_ENDIF)) {
833
+ switch (opcodenum) {
834
+ // Push value
835
+ case Opcode.OP_1NEGATE:
836
+ case Opcode.OP_1:
837
+ case Opcode.OP_2:
838
+ case Opcode.OP_3:
839
+ case Opcode.OP_4:
840
+ case Opcode.OP_5:
841
+ case Opcode.OP_6:
842
+ case Opcode.OP_7:
843
+ case Opcode.OP_8:
844
+ case Opcode.OP_9:
845
+ case Opcode.OP_10:
846
+ case Opcode.OP_11:
847
+ case Opcode.OP_12:
848
+ case Opcode.OP_13:
849
+ case Opcode.OP_14:
850
+ case Opcode.OP_15:
851
+ case Opcode.OP_16:
852
+ {
853
+ // ( -- value)
854
+ // ScriptNum bn((int)opcode - (int)(Opcode.OP_1 - 1));
855
+ n = opcodenum - (Opcode.OP_1 - 1);
856
+ buf = new BN(n).toScriptNumBuffer();
857
+ this.stack.push(buf);
858
+ // The result of these opcodes should always be the minimal way to push the data
859
+ // they push, so no need for a CheckMinimalPush here.
860
+ }
861
+ break;
862
+
863
+
864
+ //
865
+ // Control
866
+ //
867
+ case Opcode.OP_NOP:
868
+ break;
869
+
870
+ case Opcode.OP_NOP2:
871
+ case Opcode.OP_CHECKLOCKTIMEVERIFY:
872
+
873
+ if (!(this.flags & Interpreter.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
874
+ // not enabled; treat as a NOP2
875
+ if (this.flags & Interpreter.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
876
+ this.errstr = 'SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS';
877
+ return false;
878
+ }
879
+ break;
880
+ }
881
+
882
+ if (this.stack.length < 1) {
883
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
884
+ return false;
885
+ }
886
+
887
+ // Note that elsewhere numeric opcodes are limited to
888
+ // operands in the range -2**31+1 to 2**31-1, however it is
889
+ // legal for opcodes to produce results exceeding that
890
+ // range. This limitation is implemented by CScriptNum's
891
+ // default 4-byte limit.
892
+ //
893
+ // If we kept to that limit we'd have a year 2038 problem,
894
+ // even though the nLockTime field in transactions
895
+ // themselves is uint32 which only becomes meaningless
896
+ // after the year 2106.
897
+ //
898
+ // Thus as a special case we tell CScriptNum to accept up
899
+ // to 5-byte bignums, which are good until 2**39-1, well
900
+ // beyond the 2**32-1 limit of the nLockTime field itself.
901
+ var nLockTime = BN.fromScriptNumBuffer(this.stack[this.stack.length - 1], fRequireMinimal, 5);
902
+
903
+ // In the rare event that the argument may be < 0 due tod
904
+ // some arithmetic being done first, you can always use
905
+ // 0 MAX CHECKLOCKTIMEVERIFY.
906
+ if (nLockTime.lt(new BN(0))) {
907
+ this.errstr = 'SCRIPT_ERR_NEGATIVE_LOCKTIME';
908
+ return false;
909
+ }
910
+
911
+ // Actually compare the specified lock time with the transaction.
912
+ if (!this.checkLockTime(nLockTime)) {
913
+ this.errstr = 'SCRIPT_ERR_UNSATISFIED_LOCKTIME';
914
+ return false;
915
+ }
916
+ break;
917
+
918
+ case Opcode.OP_NOP3:
919
+ case Opcode.OP_CHECKSEQUENCEVERIFY:
920
+
921
+ if (!(this.flags & Interpreter.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
922
+ // not enabled; treat as a NOP3
923
+ if (this.flags & Interpreter.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
924
+ this.errstr = 'SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS';
925
+ return false;
926
+ }
927
+ break;
928
+ }
929
+
930
+ if (this.stack.length < 1) {
931
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
932
+ return false;
933
+ }
934
+
935
+
936
+ // nSequence, like nLockTime, is a 32-bit unsigned
937
+ // integer field. See the comment in CHECKLOCKTIMEVERIFY
938
+ // regarding 5-byte numeric operands.
939
+
940
+ var nSequence = BN.fromScriptNumBuffer(stacktop(-1), fRequireMinimal, 5);
941
+
942
+
943
+ // In the rare event that the argument may be < 0 due to
944
+ // some arithmetic being done first, you can always use
945
+ // 0 MAX CHECKSEQUENCEVERIFY.
946
+ if (nSequence.lt(new BN(0))) {
947
+ this.errstr = 'SCRIPT_ERR_NEGATIVE_LOCKTIME';
948
+ return false;
949
+ }
950
+
951
+ // To provide for future soft-fork extensibility, if the
952
+ // operand has the disabled lock-time flag set,
953
+ // CHECKSEQUENCEVERIFY behaves as a NOP.
954
+ if ((nSequence &
955
+ Interpreter.SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0) {
956
+ break;
957
+ }
958
+
959
+ // Actually compare the specified lock time with the transaction.
960
+ if (!this.checkSequence(nSequence)) {
961
+ this.errstr = 'SCRIPT_ERR_UNSATISFIED_LOCKTIME';
962
+ return false;
963
+ }
964
+ break;
965
+
966
+
967
+
968
+ case Opcode.OP_NOP1:
969
+ case Opcode.OP_NOP4:
970
+ case Opcode.OP_NOP5:
971
+ case Opcode.OP_NOP6:
972
+ case Opcode.OP_NOP7:
973
+ case Opcode.OP_NOP8:
974
+ case Opcode.OP_NOP9:
975
+ case Opcode.OP_NOP10:
976
+ {
977
+ if (this.flags & Interpreter.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
978
+ this.errstr = 'SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS';
979
+ return false;
980
+ }
981
+ }
982
+ break;
983
+
984
+ case Opcode.OP_IF:
985
+ case Opcode.OP_NOTIF:
986
+ {
987
+ // <expression> if [statements] [else [statements]] endif
988
+ // bool fValue = false;
989
+ fValue = false;
990
+ if (fExec) {
991
+ if (this.stack.length < 1) {
992
+ this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL';
993
+ return false;
994
+ }
995
+ buf = stacktop(-1);
996
+
997
+ if (this.flags & Interpreter.SCRIPT_VERIFY_MINIMALIF) {
998
+ if (buf.length > 1) {
999
+ this.errstr = 'SCRIPT_ERR_MINIMALIF';
1000
+ return false;
1001
+ }
1002
+ if (buf.length == 1 && buf[0]!=1) {
1003
+ this.errstr = 'SCRIPT_ERR_MINIMALIF';
1004
+ return false;
1005
+ }
1006
+ }
1007
+ fValue = Interpreter.castToBool(buf);
1008
+ if (opcodenum === Opcode.OP_NOTIF) {
1009
+ fValue = !fValue;
1010
+ }
1011
+ this.stack.pop();
1012
+ }
1013
+ this.vfExec.push(fValue);
1014
+ }
1015
+ break;
1016
+
1017
+ case Opcode.OP_ELSE:
1018
+ {
1019
+ if (this.vfExec.length === 0) {
1020
+ this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL';
1021
+ return false;
1022
+ }
1023
+ this.vfExec[this.vfExec.length - 1] = !this.vfExec[this.vfExec.length - 1];
1024
+ }
1025
+ break;
1026
+
1027
+ case Opcode.OP_ENDIF:
1028
+ {
1029
+ if (this.vfExec.length === 0) {
1030
+ this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL';
1031
+ return false;
1032
+ }
1033
+ this.vfExec.pop();
1034
+ }
1035
+ break;
1036
+
1037
+ case Opcode.OP_VERIFY:
1038
+ {
1039
+ // (true -- ) or
1040
+ // (false -- false) and return
1041
+ if (this.stack.length < 1) {
1042
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1043
+ return false;
1044
+ }
1045
+ buf = stacktop(-1);
1046
+ fValue = Interpreter.castToBool(buf);
1047
+ if (fValue) {
1048
+ this.stack.pop();
1049
+ } else {
1050
+ this.errstr = 'SCRIPT_ERR_VERIFY';
1051
+ return false;
1052
+ }
1053
+ }
1054
+ break;
1055
+
1056
+ case Opcode.OP_RETURN:
1057
+ {
1058
+ this.errstr = 'SCRIPT_ERR_OP_RETURN';
1059
+ return false;
1060
+ }
1061
+ break;
1062
+
1063
+
1064
+ //
1065
+ // Stack ops
1066
+ //
1067
+ case Opcode.OP_TOALTSTACK:
1068
+ {
1069
+ if (this.stack.length < 1) {
1070
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1071
+ return false;
1072
+ }
1073
+ this.altstack.push(this.stack.pop());
1074
+ }
1075
+ break;
1076
+
1077
+ case Opcode.OP_FROMALTSTACK:
1078
+ {
1079
+ if (this.altstack.length < 1) {
1080
+ this.errstr = 'SCRIPT_ERR_INVALID_ALTSTACK_OPERATION';
1081
+ return false;
1082
+ }
1083
+ this.stack.push(this.altstack.pop());
1084
+ }
1085
+ break;
1086
+
1087
+ case Opcode.OP_2DROP:
1088
+ {
1089
+ // (x1 x2 -- )
1090
+ if (this.stack.length < 2) {
1091
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1092
+ return false;
1093
+ }
1094
+ this.stack.pop();
1095
+ this.stack.pop();
1096
+ }
1097
+ break;
1098
+
1099
+ case Opcode.OP_2DUP:
1100
+ {
1101
+ // (x1 x2 -- x1 x2 x1 x2)
1102
+ if (this.stack.length < 2) {
1103
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1104
+ return false;
1105
+ }
1106
+ buf1 = stacktop(-2);
1107
+ buf2 = stacktop(-1);
1108
+ this.stack.push(buf1);
1109
+ this.stack.push(buf2);
1110
+ }
1111
+ break;
1112
+
1113
+ case Opcode.OP_3DUP:
1114
+ {
1115
+ // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
1116
+ if (this.stack.length < 3) {
1117
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1118
+ return false;
1119
+ }
1120
+ buf1 = stacktop(-3);
1121
+ buf2 = stacktop(-2);
1122
+ var buf3 = stacktop(-1);
1123
+ this.stack.push(buf1);
1124
+ this.stack.push(buf2);
1125
+ this.stack.push(buf3);
1126
+ }
1127
+ break;
1128
+
1129
+ case Opcode.OP_2OVER:
1130
+ {
1131
+ // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
1132
+ if (this.stack.length < 4) {
1133
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1134
+ return false;
1135
+ }
1136
+ buf1 = stacktop(-4);
1137
+ buf2 = stacktop(-3);
1138
+ this.stack.push(buf1);
1139
+ this.stack.push(buf2);
1140
+ }
1141
+ break;
1142
+
1143
+ case Opcode.OP_2ROT:
1144
+ {
1145
+ // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
1146
+ if (this.stack.length < 6) {
1147
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1148
+ return false;
1149
+ }
1150
+ spliced = this.stack.splice(this.stack.length - 6, 2);
1151
+ this.stack.push(spliced[0]);
1152
+ this.stack.push(spliced[1]);
1153
+ }
1154
+ break;
1155
+
1156
+ case Opcode.OP_2SWAP:
1157
+ {
1158
+ // (x1 x2 x3 x4 -- x3 x4 x1 x2)
1159
+ if (this.stack.length < 4) {
1160
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1161
+ return false;
1162
+ }
1163
+ spliced = this.stack.splice(this.stack.length - 4, 2);
1164
+ this.stack.push(spliced[0]);
1165
+ this.stack.push(spliced[1]);
1166
+ }
1167
+ break;
1168
+
1169
+ case Opcode.OP_IFDUP:
1170
+ {
1171
+ // (x - 0 | x x)
1172
+ if (this.stack.length < 1) {
1173
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1174
+ return false;
1175
+ }
1176
+ buf = stacktop(-1);
1177
+ fValue = Interpreter.castToBool(buf);
1178
+ if (fValue) {
1179
+ this.stack.push(buf);
1180
+ }
1181
+ }
1182
+ break;
1183
+
1184
+ case Opcode.OP_DEPTH:
1185
+ {
1186
+ // -- stacksize
1187
+ buf = new BN(this.stack.length).toScriptNumBuffer();
1188
+ this.stack.push(buf);
1189
+ }
1190
+ break;
1191
+
1192
+ case Opcode.OP_DROP:
1193
+ {
1194
+ // (x -- )
1195
+ if (this.stack.length < 1) {
1196
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1197
+ return false;
1198
+ }
1199
+ this.stack.pop();
1200
+ }
1201
+ break;
1202
+
1203
+ case Opcode.OP_DUP:
1204
+ {
1205
+ // (x -- x x)
1206
+ if (this.stack.length < 1) {
1207
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1208
+ return false;
1209
+ }
1210
+ this.stack.push(stacktop(-1));
1211
+ }
1212
+ break;
1213
+
1214
+ case Opcode.OP_NIP:
1215
+ {
1216
+ // (x1 x2 -- x2)
1217
+ if (this.stack.length < 2) {
1218
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1219
+ return false;
1220
+ }
1221
+ this.stack.splice(this.stack.length - 2, 1);
1222
+ }
1223
+ break;
1224
+
1225
+ case Opcode.OP_OVER:
1226
+ {
1227
+ // (x1 x2 -- x1 x2 x1)
1228
+ if (this.stack.length < 2) {
1229
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1230
+ return false;
1231
+ }
1232
+ this.stack.push(stacktop(-2));
1233
+ }
1234
+ break;
1235
+
1236
+ case Opcode.OP_PICK:
1237
+ case Opcode.OP_ROLL:
1238
+ {
1239
+ // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
1240
+ // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
1241
+ if (this.stack.length < 2) {
1242
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1243
+ return false;
1244
+ }
1245
+ buf = stacktop(-1);
1246
+ bn = BN.fromScriptNumBuffer(buf, fRequireMinimal);
1247
+ n = bn.toNumber();
1248
+ this.stack.pop();
1249
+ if (n < 0 || n >= this.stack.length) {
1250
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1251
+ return false;
1252
+ }
1253
+ buf = stacktop(-n-1);
1254
+ if (opcodenum === Opcode.OP_ROLL) {
1255
+ this.stack.splice(this.stack.length - n - 1, 1);
1256
+ }
1257
+ this.stack.push(buf);
1258
+ }
1259
+ break;
1260
+
1261
+ case Opcode.OP_ROT:
1262
+ {
1263
+ // (x1 x2 x3 -- x2 x3 x1)
1264
+ // x2 x1 x3 after first swap
1265
+ // x2 x3 x1 after second swap
1266
+ if (this.stack.length < 3) {
1267
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1268
+ return false;
1269
+ }
1270
+ x1 = stacktop(-3);
1271
+ x2 = stacktop(-2);
1272
+ var x3 = stacktop(-1);
1273
+ this.stack[this.stack.length - 3] = x2;
1274
+ this.stack[this.stack.length - 2] = x3;
1275
+ this.stack[this.stack.length - 1] = x1;
1276
+ }
1277
+ break;
1278
+
1279
+ case Opcode.OP_SWAP:
1280
+ {
1281
+ // (x1 x2 -- x2 x1)
1282
+ if (this.stack.length < 2) {
1283
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1284
+ return false;
1285
+ }
1286
+ x1 = stacktop(-2);
1287
+ x2 = stacktop(-1);
1288
+ this.stack[this.stack.length - 2] = x2;
1289
+ this.stack[this.stack.length - 1] = x1;
1290
+ }
1291
+ break;
1292
+
1293
+ case Opcode.OP_TUCK:
1294
+ {
1295
+ // (x1 x2 -- x2 x1 x2)
1296
+ if (this.stack.length < 2) {
1297
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1298
+ return false;
1299
+ }
1300
+ this.stack.splice(this.stack.length - 2, 0, stacktop(-1));
1301
+ }
1302
+ break;
1303
+
1304
+
1305
+ case Opcode.OP_SIZE:
1306
+ {
1307
+ // (in -- in size)
1308
+ if (this.stack.length < 1) {
1309
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1310
+ return false;
1311
+ }
1312
+ bn = new BN(stacktop(-1).length);
1313
+ this.stack.push(bn.toScriptNumBuffer());
1314
+ }
1315
+ break;
1316
+
1317
+ //
1318
+ // Bitwise logic
1319
+ //
1320
+ case Opcode.OP_AND:
1321
+ case Opcode.OP_OR:
1322
+ case Opcode.OP_XOR:
1323
+ {
1324
+ // (x1 x2 - out)
1325
+ if (this.stack.length < 2) {
1326
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1327
+ return false;
1328
+ }
1329
+ buf1 = stacktop(-2);
1330
+ buf2 = stacktop(-1);
1331
+
1332
+ // Inputs must be the same size
1333
+ if (buf1.length !== buf2.length) {
1334
+ this.errstr = 'SCRIPT_ERR_INVALID_OPERAND_SIZE';
1335
+ return false;
1336
+ }
1337
+
1338
+ // To avoid allocating, we modify vch1 in place.
1339
+ switch (opcodenum) {
1340
+ case Opcode.OP_AND:
1341
+ for (var i = 0; i < buf1.length; i++) {
1342
+ buf1[i] &= buf2[i];
1343
+ }
1344
+ break;
1345
+ case Opcode.OP_OR:
1346
+ for (var i = 0; i < buf1.length; i++) {
1347
+ buf1[i] |= buf2[i];
1348
+ }
1349
+ break;
1350
+ case Opcode.OP_XOR:
1351
+ for (var i = 0; i < buf1.length; i++) {
1352
+ buf1[i] ^= buf2[i];
1353
+ }
1354
+ break;
1355
+ default:
1356
+ break;
1357
+ }
1358
+
1359
+ // And pop vch2.
1360
+ this.stack.pop()
1361
+ }
1362
+ break;
1363
+
1364
+ case Opcode.OP_EQUAL:
1365
+ case Opcode.OP_EQUALVERIFY:
1366
+ //case Opcode.OP_NOTEQUAL: // use Opcode.OP_NUMNOTEQUAL
1367
+ {
1368
+ // (x1 x2 - bool)
1369
+ if (this.stack.length < 2) {
1370
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1371
+ return false;
1372
+ }
1373
+ buf1 = stacktop(-2);
1374
+ buf2 = stacktop(-1);
1375
+ var fEqual = buf1.toString('hex') === buf2.toString('hex');
1376
+ this.stack.pop();
1377
+ this.stack.pop();
1378
+ this.stack.push(fEqual ? Interpreter.true : Interpreter.false);
1379
+ if (opcodenum === Opcode.OP_EQUALVERIFY) {
1380
+ if (fEqual) {
1381
+ this.stack.pop();
1382
+ } else {
1383
+ this.errstr = 'SCRIPT_ERR_EQUALVERIFY';
1384
+ return false;
1385
+ }
1386
+ }
1387
+ }
1388
+ break;
1389
+
1390
+
1391
+ //
1392
+ // Numeric
1393
+ //
1394
+ case Opcode.OP_1ADD:
1395
+ case Opcode.OP_1SUB:
1396
+ case Opcode.OP_NEGATE:
1397
+ case Opcode.OP_ABS:
1398
+ case Opcode.OP_NOT:
1399
+ case Opcode.OP_0NOTEQUAL:
1400
+ {
1401
+ // (in -- out)
1402
+ if (this.stack.length < 1) {
1403
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1404
+ return false;
1405
+ }
1406
+ buf = stacktop(-1);
1407
+ bn = BN.fromScriptNumBuffer(buf, fRequireMinimal);
1408
+ switch (opcodenum) {
1409
+ case Opcode.OP_1ADD:
1410
+ bn = bn.add(BN.One);
1411
+ break;
1412
+ case Opcode.OP_1SUB:
1413
+ bn = bn.sub(BN.One);
1414
+ break;
1415
+ case Opcode.OP_NEGATE:
1416
+ bn = bn.neg();
1417
+ break;
1418
+ case Opcode.OP_ABS:
1419
+ if (bn.cmp(BN.Zero) < 0) {
1420
+ bn = bn.neg();
1421
+ }
1422
+ break;
1423
+ case Opcode.OP_NOT:
1424
+ bn = new BN((bn.cmp(BN.Zero) === 0) + 0);
1425
+ break;
1426
+ case Opcode.OP_0NOTEQUAL:
1427
+ bn = new BN((bn.cmp(BN.Zero) !== 0) + 0);
1428
+ break;
1429
+ //default: assert(!'invalid opcode'); break; // TODO: does this ever occur?
1430
+ }
1431
+ this.stack.pop();
1432
+ this.stack.push(bn.toScriptNumBuffer());
1433
+ }
1434
+ break;
1435
+
1436
+ case Opcode.OP_ADD:
1437
+ case Opcode.OP_SUB:
1438
+ case Opcode.OP_MOD:
1439
+ case Opcode.OP_DIV:
1440
+ case Opcode.OP_BOOLAND:
1441
+ case Opcode.OP_BOOLOR:
1442
+ case Opcode.OP_NUMEQUAL:
1443
+ case Opcode.OP_NUMEQUALVERIFY:
1444
+ case Opcode.OP_NUMNOTEQUAL:
1445
+ case Opcode.OP_LESSTHAN:
1446
+ case Opcode.OP_GREATERTHAN:
1447
+ case Opcode.OP_LESSTHANOREQUAL:
1448
+ case Opcode.OP_GREATERTHANOREQUAL:
1449
+ case Opcode.OP_MIN:
1450
+ case Opcode.OP_MAX:
1451
+ {
1452
+ // (x1 x2 -- out)
1453
+ if (this.stack.length < 2) {
1454
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1455
+ return false;
1456
+ }
1457
+ bn1 = BN.fromScriptNumBuffer(stacktop(-2), fRequireMinimal);
1458
+ bn2 = BN.fromScriptNumBuffer(stacktop(-1), fRequireMinimal);
1459
+ bn = new BN(0);
1460
+
1461
+ switch (opcodenum) {
1462
+ case Opcode.OP_ADD:
1463
+ bn = bn1.add(bn2);
1464
+ break;
1465
+
1466
+ case Opcode.OP_SUB:
1467
+ bn = bn1.sub(bn2);
1468
+ break;
1469
+
1470
+ case Opcode.OP_DIV:
1471
+ // denominator must not be 0
1472
+ if (bn2 == 0) {
1473
+ this.errstr = 'SCRIPT_ERR_DIV_BY_ZERO';
1474
+ return false;
1475
+ }
1476
+ bn = bn1.div(bn2);
1477
+ break;
1478
+
1479
+ case Opcode.OP_MOD:
1480
+ // divisor must not be 0
1481
+ if (bn2 == 0) {
1482
+ this.errstr = 'SCRIPT_ERR_DIV_BY_ZERO';
1483
+ return false;
1484
+ }
1485
+ bn = bn1.mod(bn2);
1486
+ break;
1487
+
1488
+ case Opcode.OP_BOOLAND:
1489
+ bn = new BN(((bn1.cmp(BN.Zero) !== 0) && (bn2.cmp(BN.Zero) !== 0)) + 0);
1490
+ break;
1491
+ // case Opcode.OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
1492
+ case Opcode.OP_BOOLOR:
1493
+ bn = new BN(((bn1.cmp(BN.Zero) !== 0) || (bn2.cmp(BN.Zero) !== 0)) + 0);
1494
+ break;
1495
+ // case Opcode.OP_NUMEQUAL: bn = (bn1 == bn2); break;
1496
+ case Opcode.OP_NUMEQUAL:
1497
+ bn = new BN((bn1.cmp(bn2) === 0) + 0);
1498
+ break;
1499
+ // case Opcode.OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
1500
+ case Opcode.OP_NUMEQUALVERIFY:
1501
+ bn = new BN((bn1.cmp(bn2) === 0) + 0);
1502
+ break;
1503
+ // case Opcode.OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
1504
+ case Opcode.OP_NUMNOTEQUAL:
1505
+ bn = new BN((bn1.cmp(bn2) !== 0) + 0);
1506
+ break;
1507
+ // case Opcode.OP_LESSTHAN: bn = (bn1 < bn2); break;
1508
+ case Opcode.OP_LESSTHAN:
1509
+ bn = new BN((bn1.cmp(bn2) < 0) + 0);
1510
+ break;
1511
+ // case Opcode.OP_GREATERTHAN: bn = (bn1 > bn2); break;
1512
+ case Opcode.OP_GREATERTHAN:
1513
+ bn = new BN((bn1.cmp(bn2) > 0) + 0);
1514
+ break;
1515
+ // case Opcode.OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
1516
+ case Opcode.OP_LESSTHANOREQUAL:
1517
+ bn = new BN((bn1.cmp(bn2) <= 0) + 0);
1518
+ break;
1519
+ // case Opcode.OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
1520
+ case Opcode.OP_GREATERTHANOREQUAL:
1521
+ bn = new BN((bn1.cmp(bn2) >= 0) + 0);
1522
+ break;
1523
+ case Opcode.OP_MIN:
1524
+ bn = (bn1.cmp(bn2) < 0 ? bn1 : bn2);
1525
+ break;
1526
+ case Opcode.OP_MAX:
1527
+ bn = (bn1.cmp(bn2) > 0 ? bn1 : bn2);
1528
+ break;
1529
+ // default: assert(!'invalid opcode'); break; //TODO: does this ever occur?
1530
+ }
1531
+ this.stack.pop();
1532
+ this.stack.pop();
1533
+ this.stack.push(bn.toScriptNumBuffer());
1534
+
1535
+ if (opcodenum === Opcode.OP_NUMEQUALVERIFY) {
1536
+ // if (CastToBool(stacktop(-1)))
1537
+ if (Interpreter.castToBool(stacktop(-1))) {
1538
+ this.stack.pop();
1539
+ } else {
1540
+ this.errstr = 'SCRIPT_ERR_NUMEQUALVERIFY';
1541
+ return false;
1542
+ }
1543
+ }
1544
+ }
1545
+ break;
1546
+
1547
+ case Opcode.OP_WITHIN:
1548
+ {
1549
+ // (x min max -- out)
1550
+ if (this.stack.length < 3) {
1551
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1552
+ return false;
1553
+ }
1554
+ bn1 = BN.fromScriptNumBuffer(stacktop(-3), fRequireMinimal);
1555
+ bn2 = BN.fromScriptNumBuffer(stacktop(-2), fRequireMinimal);
1556
+ var bn3 = BN.fromScriptNumBuffer(stacktop(-1), fRequireMinimal);
1557
+ //bool fValue = (bn2 <= bn1 && bn1 < bn3);
1558
+ fValue = (bn2.cmp(bn1) <= 0) && (bn1.cmp(bn3) < 0);
1559
+ this.stack.pop();
1560
+ this.stack.pop();
1561
+ this.stack.pop();
1562
+ this.stack.push(fValue ? Interpreter.true : Interpreter.false);
1563
+ }
1564
+ break;
1565
+
1566
+
1567
+ //
1568
+ // Crypto
1569
+ //
1570
+ case Opcode.OP_RIPEMD160:
1571
+ case Opcode.OP_SHA1:
1572
+ case Opcode.OP_SHA256:
1573
+ case Opcode.OP_HASH160:
1574
+ case Opcode.OP_HASH256:
1575
+ {
1576
+ // (in -- hash)
1577
+ if (this.stack.length < 1) {
1578
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1579
+ return false;
1580
+ }
1581
+ buf = stacktop(-1);
1582
+ //valtype vchHash((opcode == Opcode.OP_RIPEMD160 ||
1583
+ // opcode == Opcode.OP_SHA1 || opcode == Opcode.OP_HASH160) ? 20 : 32);
1584
+ var bufHash;
1585
+ if (opcodenum === Opcode.OP_RIPEMD160) {
1586
+ bufHash = Hash.ripemd160(buf);
1587
+ } else if (opcodenum === Opcode.OP_SHA1) {
1588
+ bufHash = Hash.sha1(buf);
1589
+ } else if (opcodenum === Opcode.OP_SHA256) {
1590
+ bufHash = Hash.sha256(buf);
1591
+ } else if (opcodenum === Opcode.OP_HASH160) {
1592
+ bufHash = Hash.sha256ripemd160(buf);
1593
+ } else if (opcodenum === Opcode.OP_HASH256) {
1594
+ bufHash = Hash.sha256sha256(buf);
1595
+ }
1596
+ this.stack.pop();
1597
+ this.stack.push(bufHash);
1598
+ }
1599
+ break;
1600
+
1601
+ case Opcode.OP_CODESEPARATOR:
1602
+ {
1603
+ // Hash starts after the code separator
1604
+ this.pbegincodehash = this.pc;
1605
+ }
1606
+ break;
1607
+
1608
+ case Opcode.OP_CHECKSIG:
1609
+ case Opcode.OP_CHECKSIGVERIFY:
1610
+ {
1611
+ // (sig pubkey -- bool)
1612
+ if (this.stack.length < 2) {
1613
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1614
+ return false;
1615
+ }
1616
+
1617
+ bufSig = stacktop(-2);
1618
+ bufPubkey = stacktop(-1);
1619
+
1620
+ if (!this.checkTxSignatureEncoding(bufSig) || !this.checkPubkeyEncoding(bufPubkey)) {
1621
+ return false;
1622
+ }
1623
+
1624
+ // Subset of script starting at the most recent codeseparator
1625
+ // CScript scriptCode(pbegincodehash, pend);
1626
+ subscript = new Script().set({
1627
+ chunks: this.script.chunks.slice(this.pbegincodehash)
1628
+ });
1629
+
1630
+ // Drop the signature, since there's no way for a signature to sign itself
1631
+ var tmpScript = new Script().add(bufSig);
1632
+ subscript.findAndDelete(tmpScript);
1633
+
1634
+ try {
1635
+ sig = Signature.fromTxFormat(bufSig);
1636
+ pubkey = PublicKey.fromBuffer(bufPubkey, false);
1637
+
1638
+ if(!sig.isSchnorr) {
1639
+ fSuccess = this.tx.verifySignature(sig, pubkey, this.nin, subscript, this.satoshisBN, this.flags);
1640
+ } else {
1641
+ fSuccess = this.tx.verifySignature(sig, pubkey, this.nin, subscript, this.satoshisBN, this.flags, "schnorr");
1642
+ }
1643
+ } catch (e) {
1644
+ //invalid sig or pubkey
1645
+ fSuccess = false;
1646
+ }
1647
+
1648
+ if (!fSuccess && (this.flags & Interpreter.SCRIPT_VERIFY_NULLFAIL) &&
1649
+ bufSig.length) {
1650
+ this.errstr = 'SCRIPT_ERR_NULLFAIL';
1651
+ return false;
1652
+ }
1653
+
1654
+ this.stack.pop();
1655
+ this.stack.pop();
1656
+
1657
+ // stack.push_back(fSuccess ? vchTrue : vchFalse);
1658
+ this.stack.push(fSuccess ? Interpreter.true : Interpreter.false);
1659
+ if (opcodenum === Opcode.OP_CHECKSIGVERIFY) {
1660
+ if (fSuccess) {
1661
+ this.stack.pop();
1662
+ } else {
1663
+ this.errstr = 'SCRIPT_ERR_CHECKSIGVERIFY';
1664
+ return false;
1665
+ }
1666
+ }
1667
+ }
1668
+ break;
1669
+
1670
+ case Opcode.OP_CHECKDATASIG:
1671
+ case Opcode.OP_CHECKDATASIGVERIFY:
1672
+ {
1673
+
1674
+
1675
+ // (sig message pubkey -- bool)
1676
+ if (this.stack.length < 3) {
1677
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1678
+ return false;
1679
+ }
1680
+
1681
+ bufSig = stacktop(-3);
1682
+ bufMessage = stacktop(-2);
1683
+ bufPubkey = stacktop(-1);
1684
+
1685
+ if (!this.checkDataSignatureEncoding(bufSig) || !this.checkPubkeyEncoding(bufPubkey)) {
1686
+ return false;
1687
+ }
1688
+
1689
+ fSuccess = false;
1690
+
1691
+
1692
+ try {
1693
+ sig = Signature.fromDataFormat(bufSig);
1694
+ pubkey = PublicKey.fromBuffer(bufPubkey, false);
1695
+ bufHash = Hash.sha256(bufMessage);
1696
+ if (!sig.isSchnorr) {
1697
+ fSuccess = ECDSA.verify(bufHash, sig, pubkey, 'big');
1698
+ } else {
1699
+ fSuccess = Schnorr.verify(bufHash, sig, pubkey, 'big');
1700
+ }
1701
+ } catch (e) {
1702
+ //invalid sig or pubkey
1703
+ fSuccess = false;
1704
+ }
1705
+
1706
+ if (!fSuccess && (this.flags & Interpreter.SCRIPT_VERIFY_NULLFAIL) &&
1707
+ bufSig.length) {
1708
+ this.errstr = 'SCRIPT_ERR_NULLFAIL';
1709
+ return false;
1710
+ }
1711
+
1712
+ this.stack.pop();
1713
+ this.stack.pop();
1714
+ this.stack.pop();
1715
+
1716
+ this.stack.push(fSuccess ? Interpreter.true : Interpreter.false);
1717
+ if (opcodenum === Opcode.OP_CHECKDATASIGVERIFY) {
1718
+ if (fSuccess) {
1719
+ this.stack.pop();
1720
+ } else {
1721
+ this.errstr = 'SCRIPT_ERR_CHECKDATASIGVERIFY';
1722
+ return false;
1723
+ }
1724
+ }
1725
+
1726
+ }
1727
+ break;
1728
+
1729
+ case Opcode.OP_REVERSEBYTES:
1730
+ {
1731
+ if (this.stack.length < 1) {
1732
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1733
+ return false;
1734
+ }
1735
+
1736
+ buf1 = stacktop(-1);
1737
+ var reversedBuf = Buffer.from(buf1).reverse();
1738
+ this.stack.pop();
1739
+ this.stack.push(reversedBuf);
1740
+ }
1741
+ break;
1742
+
1743
+ case Opcode.OP_CHECKMULTISIG:
1744
+ case Opcode.OP_CHECKMULTISIGVERIFY:
1745
+ {
1746
+ // ([dummy] [sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1747
+
1748
+ var i = 1;
1749
+ let idxTopKey = i + 1;
1750
+ if (this.stack.length < i) {
1751
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1752
+ return false;
1753
+ }
1754
+
1755
+ var nKeysCount = BN.fromScriptNumBuffer(stacktop(-i), fRequireMinimal).toNumber();
1756
+ var idxSigCount = idxTopKey + nKeysCount;
1757
+ if (nKeysCount < 0 || nKeysCount > 20) {
1758
+ this.errstr = 'SCRIPT_ERR_PUBKEY_COUNT';
1759
+ return false;
1760
+ }
1761
+ this.nOpCount += nKeysCount;
1762
+ if (this.nOpCount > 201) {
1763
+ this.errstr = 'SCRIPT_ERR_OP_COUNT';
1764
+ return false;
1765
+ }
1766
+
1767
+ // todo map interpreter.cpp variables with interpreter.js variables for future readability, maintainability
1768
+ // ikey maps to idxTopKey in interpreter.cpp (MULTISIG case)
1769
+ var ikey = ++i; // top pubkey
1770
+ var idxTopSig = idxSigCount + 1;
1771
+
1772
+ // i maps to idxSigCount in interpreter.cpp (MULTISIG case) (stack depth of nSigsCount)
1773
+ i += nKeysCount;
1774
+
1775
+ // ikey2 is the position of last non-signature item in
1776
+ // the stack. Top stack item = 1. With
1777
+ // SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if
1778
+ // operation fails.
1779
+ var ikey2 = nKeysCount + 2; // ?dummy variable
1780
+
1781
+ if (this.stack.length < i) {
1782
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1783
+ return false;
1784
+ }
1785
+
1786
+ var nSigsCount = BN.fromScriptNumBuffer(stacktop(-idxSigCount), fRequireMinimal).toNumber();
1787
+ var idxDummy = idxTopSig + nSigsCount;
1788
+
1789
+ if (nSigsCount < 0 || nSigsCount > nKeysCount) {
1790
+ this.errstr = 'SCRIPT_ERR_SIG_COUNT';
1791
+ return false;
1792
+ }
1793
+ // int isig = ++i;
1794
+ var isig = ++i;
1795
+ i += nSigsCount;
1796
+ if (this.stack.length < idxDummy) {
1797
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1798
+ return false;
1799
+ }
1800
+
1801
+
1802
+ // Subset of script starting at the most recent codeseparator
1803
+ subscript = new Script().set({
1804
+ chunks: this.script.chunks.slice(this.pbegincodehash)
1805
+ });
1806
+
1807
+ fSuccess = true;
1808
+
1809
+ if((this.flags & Interpreter.SCRIPT_ENABLE_SCHNORR_MULTISIG) && stacktop(-idxDummy).length !== 0) {
1810
+ // SCHNORR MULTISIG
1811
+
1812
+ let dummy = stacktop(-idxDummy);
1813
+
1814
+ let bitfieldObj = DecodeBitfield(dummy, nKeysCount);
1815
+
1816
+ if(!bitfieldObj["result"]) {
1817
+ fSuccess = false;
1818
+ }
1819
+
1820
+ let nSigs8bit = new Uint8Array([nSigsCount]);
1821
+ let nSigs32 = Uint32Array.from(nSigs8bit);
1822
+
1823
+ if (countBits(bitfieldObj["bitfield"]) !== nSigs32[0]) {
1824
+ this.errstr = "INVALID_BIT_COUNT";
1825
+ fSuccess = false;
1826
+ }
1827
+
1828
+ var bottomKey = idxTopKey + nKeysCount - 1;
1829
+ var bottomSig = idxTopSig + nSigsCount - 1;
1830
+
1831
+ let iKey = 0;
1832
+ for(let iSig = 0; iSig < nSigsCount;
1833
+ iSig++, iKey++) {
1834
+ if((bitfieldObj["bitfield"] >> iKey) === 0) {
1835
+ this.errstr = "INVALID_BIT_RANGE";
1836
+ fSuccess = false;
1837
+ }
1838
+
1839
+ while(((bitfieldObj["bitfield"] >> iKey) & 0x01) == 0) {
1840
+ if(iKey >= nKeysCount) {
1841
+ this.errstr = "wrong";
1842
+ fSuccess = false;
1843
+ break;
1844
+ }
1845
+ iKey++;
1846
+ }
1847
+
1848
+ // this is a sanity check and should be
1849
+ // unreachable
1850
+ if(iKey >= nKeysCount) {
1851
+ this.errstr = "PUBKEY_COUNT";
1852
+ fSuccess = false;
1853
+ }
1854
+
1855
+ // Check the signature
1856
+ let bufsig = stacktop(-bottomSig + iSig)
1857
+ let bufPubkey = stacktop(-bottomKey + iKey)
1858
+
1859
+ // Note that only pubkeys associated with a
1860
+ // signature are check for validity
1861
+
1862
+ if(!this.checkRawSignatureEncoding(bufsig) || !this.checkPubkeyEncoding(bufPubkey)) {
1863
+ fSuccess = false;
1864
+ }
1865
+
1866
+ let sig = Signature.fromTxFormat(bufsig);
1867
+ let pubkey = PublicKey.fromBuffer(bufPubkey, false);
1868
+ let fOk = this.tx.verifySignature(sig, pubkey, this.nin, subscript, this.satoshisBN, this.flags, "schnorr");
1869
+
1870
+ if(!fOk) {
1871
+ this.errstr = "SIG_NULLFAIL"
1872
+ fSuccess = false;
1873
+ }
1874
+ }
1875
+
1876
+ if ((bitfieldObj["bitfield"] >> iKey) != 0) {
1877
+ // This is a sanity check and should be
1878
+ // unreachable.
1879
+ this.errstr = "INVALID_BIT_COUNT"
1880
+ fSuccess = false;
1881
+ }
1882
+ }
1883
+ else {
1884
+ // Drop the signatures, since there's no way for a signature to sign itself
1885
+ for (var k = 0; k < nSigsCount; k++) {
1886
+ bufSig = stacktop(-isig-k);
1887
+ subscript.findAndDelete(new Script().add(bufSig));
1888
+ }
1889
+
1890
+ while (fSuccess && nSigsCount > 0) {
1891
+
1892
+ // valtype& vchSig = stacktop(-isig);
1893
+ bufSig = stacktop(-isig);
1894
+ // valtype& vchPubKey = stacktop(-ikey);
1895
+ bufPubkey = stacktop(-ikey);
1896
+
1897
+ if (!this.checkTxSignatureEncoding(bufSig) || !this.checkPubkeyEncoding(bufPubkey)) {
1898
+ return false;
1899
+ }
1900
+
1901
+ var fOk;
1902
+ try {
1903
+ sig = Signature.fromTxFormat(bufSig);
1904
+ pubkey = PublicKey.fromBuffer(bufPubkey, false);
1905
+ fOk = this.tx.verifySignature(sig, pubkey, this.nin, subscript, this.satoshisBN, this.flags);
1906
+ } catch (e) {
1907
+ //invalid sig or pubkey
1908
+ fOk = false;
1909
+ }
1910
+
1911
+ if (fOk) {
1912
+ isig++;
1913
+ nSigsCount--;
1914
+ }
1915
+ ikey++;
1916
+ nKeysCount--;
1917
+
1918
+ // If there are more signatures left than keys left,
1919
+ // then too many signatures have failed
1920
+ if (nSigsCount > nKeysCount) {
1921
+ fSuccess = false;
1922
+ }
1923
+ }
1924
+ }
1925
+
1926
+ // Clean up stack of actual arguments
1927
+ while (i-- > 1) {
1928
+ if (!fSuccess && (this.flags & Interpreter.SCRIPT_VERIFY_NULLFAIL) &&
1929
+ !ikey2 && stacktop(-1).length) {
1930
+
1931
+ this.errstr = 'SCRIPT_ERR_NULLFAIL';
1932
+ return false;
1933
+ }
1934
+
1935
+ if (ikey2 > 0) {
1936
+ ikey2--;
1937
+ }
1938
+
1939
+ this.stack.pop();
1940
+ }
1941
+
1942
+ // A bug causes CHECKMULTISIG to consume one extra argument
1943
+ // whose contents were not checked in any way.
1944
+ //
1945
+ // Unfortunately this is a potential source of mutability,
1946
+ // so optionally verify it is exactly equal to zero prior
1947
+ // to removing it from the stack.
1948
+ if (this.stack.length < 1) {
1949
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1950
+ return false;
1951
+ }
1952
+ if ((this.flags & Interpreter.SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).length) {
1953
+ this.errstr = 'SCRIPT_ERR_SIG_NULLDUMMY';
1954
+ return false;
1955
+ }
1956
+ this.stack.pop();
1957
+
1958
+ this.stack.push(fSuccess ? Interpreter.true : Interpreter.false);
1959
+
1960
+ if (opcodenum === Opcode.OP_CHECKMULTISIGVERIFY) {
1961
+ if (fSuccess) {
1962
+ this.stack.pop();
1963
+ } else {
1964
+ this.errstr = 'SCRIPT_ERR_CHECKMULTISIGVERIFY';
1965
+ return false;
1966
+ }
1967
+ }
1968
+ }
1969
+ break;
1970
+
1971
+ //
1972
+ // Byte string operations
1973
+ //
1974
+ case Opcode.OP_CAT: {
1975
+
1976
+ if (this.stack.length < 2) {
1977
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1978
+ return false;
1979
+ }
1980
+
1981
+ buf1 = stacktop(-2);
1982
+ buf2 = stacktop(-1);
1983
+ if (buf1.length + buf2.length > Interpreter.MAX_SCRIPT_ELEMENT_SIZE) {
1984
+ this.errstr = 'SCRIPT_ERR_PUSH_SIZE';
1985
+ return false;
1986
+ }
1987
+ this.stack[this.stack.length - 2] = Buffer.concat([buf1,buf2]);
1988
+ this.stack.pop();
1989
+ }
1990
+ break;
1991
+
1992
+ case Opcode.OP_SPLIT: {
1993
+ if (this.stack.length < 2) {
1994
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
1995
+ return false;
1996
+ }
1997
+ buf1 = stacktop(-2);
1998
+
1999
+ // Make sure the split point is apropriate.
2000
+ var position = BN.fromScriptNumBuffer(stacktop(-1), fRequireMinimal).toNumber();
2001
+ if (position < 0 || position > buf1.length) {
2002
+ this.errstr = 'SCRIPT_ERR_INVALID_SPLIT_RANGE';
2003
+ return false;
2004
+ }
2005
+
2006
+ // Prepare the results in their own buffer as `data`
2007
+ // will be invalidated.
2008
+ // Copy buffer data, to slice it before
2009
+ var n1 = Buffer.from(buf1);
2010
+
2011
+ // Replace existing stack values by the new values.
2012
+ this.stack[this.stack.length - 2] = n1.slice(0, position);
2013
+ this.stack[this.stack.length - 1] = n1.slice(position);
2014
+ }
2015
+ break;
2016
+
2017
+ //
2018
+ // Conversion operations
2019
+ //
2020
+ case Opcode.OP_NUM2BIN: {
2021
+
2022
+ // (in -- out)
2023
+ if (this.stack.length < 2) {
2024
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
2025
+ return false;
2026
+ }
2027
+
2028
+ var size = BN.fromScriptNumBuffer(stacktop(-1), fRequireMinimal).toNumber();
2029
+ if (size > Interpreter.MAX_SCRIPT_ELEMENT_SIZE) {
2030
+ this.errstr = 'SCRIPT_ERR_PUSH_SIZE';
2031
+ return false;
2032
+ }
2033
+
2034
+ this.stack.pop();
2035
+ var rawnum = stacktop(-1);
2036
+
2037
+ // Try to see if we can fit that number in the number of
2038
+ // byte requested.
2039
+ rawnum=Interpreter._minimallyEncode(rawnum);
2040
+
2041
+ if (rawnum.length > size) {
2042
+ // We definitively cannot.
2043
+ this.errstr = 'SCRIPT_ERR_IMPOSSIBLE_ENCODING';
2044
+ return false;
2045
+ }
2046
+
2047
+ // We already have an element of the right size, we
2048
+ // don't need to do anything.
2049
+ if (rawnum.length == size) {
2050
+ this.stack[this.stack.length-1] = rawnum;
2051
+ break;
2052
+ }
2053
+
2054
+ var signbit = 0x00;
2055
+ if (rawnum.length > 0) {
2056
+ signbit = rawnum[rawnum.length - 1] & 0x80;
2057
+ rawnum[rawnum.length - 1] &= 0x7f;
2058
+ }
2059
+
2060
+ var num = Buffer.alloc(size);
2061
+ rawnum.copy(num,0);
2062
+
2063
+ var l = rawnum.length - 1;
2064
+ while (l++ < size - 2) {
2065
+ num[l]=0x00;
2066
+ }
2067
+
2068
+ num[l]=signbit;
2069
+
2070
+ this.stack[this.stack.length-1] = num;
2071
+ }
2072
+ break;
2073
+
2074
+
2075
+
2076
+ case Opcode.OP_BIN2NUM: {
2077
+ // (in -- out)
2078
+ if (this.stack.length < 1) {
2079
+ this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
2080
+ return false;
2081
+ }
2082
+
2083
+ buf1 = stacktop(-1);
2084
+ buf2 = Interpreter._minimallyEncode(buf1);
2085
+
2086
+ this.stack[this.stack.length - 1] = buf2;
2087
+
2088
+ // The resulting number must be a valid number.
2089
+ if (!Interpreter._isMinimallyEncoded(buf2)) {
2090
+ this.errstr = 'SCRIPT_ERR_INVALID_NUMBER_RANGE';
2091
+ return false;
2092
+ }
2093
+ }
2094
+ break;
2095
+
2096
+
2097
+
2098
+
2099
+ default:
2100
+ this.errstr = 'SCRIPT_ERR_BAD_OPCODE';
2101
+ return false;
2102
+ }
2103
+ }
2104
+
2105
+ return true;
2106
+ };
2107
+