-
Notifications
You must be signed in to change notification settings - Fork 299
/
interpreter.cpp
2111 lines (1870 loc) · 83.3 KB
/
interpreter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Copyright (c) 2018-2019 Bitcoin Association
// Distributed under the Open BSV software license, see the accompanying file LICENSE.
#include "interpreter.h"
#include "script_flags.h"
#include "crypto/ripemd160.h"
#include "crypto/sha1.h"
#include "crypto/sha256.h"
#include "primitives/transaction.h"
#include "pubkey.h"
#include "script/int_serialization.h"
#include "script/script.h"
#include "script/script_num.h"
#include "taskcancellation.h"
#include "uint256.h"
#include "consensus/consensus.h"
#include "script_config.h"
namespace {
inline bool set_success(ScriptError *ret) {
if (ret) {
*ret = SCRIPT_ERR_OK;
}
return true;
}
inline bool set_error(ScriptError *ret, const ScriptError serror) {
if (ret) {
*ret = serror;
}
return false;
}
} // namespace
inline uint8_t make_rshift_mask(size_t n) {
static uint8_t mask[] = {0xFF, 0xFE, 0xFC, 0xF8, 0xF0, 0xE0, 0xC0, 0x80};
return mask[n];
}
inline uint8_t make_lshift_mask(size_t n) {
static uint8_t mask[] = {0xFF, 0x7F, 0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x01};
return mask[n];
}
// shift x right by n bits, implements OP_RSHIFT
static valtype RShift(const valtype &x, int n) {
valtype::size_type bit_shift = n % 8;
valtype::size_type byte_shift = n / 8;
uint8_t mask = make_rshift_mask(bit_shift);
uint8_t overflow_mask = ~mask;
valtype result(x.size(), 0x00);
for (valtype::size_type i = 0; i < x.size(); i++) {
valtype::size_type k = i + byte_shift;
if (k < x.size()) {
uint8_t val = (x[i] & mask);
val >>= bit_shift;
result[k] |= val;
}
if (k + 1 < x.size()) {
uint8_t carryval = (x[i] & overflow_mask);
carryval <<= 8 - bit_shift;
result[k + 1] |= carryval;
}
}
return result;
}
// shift x left by n bits, implements OP_LSHIFT
static valtype LShift(const valtype &x, int n) {
valtype::size_type bit_shift = n % 8;
valtype::size_type byte_shift = n / 8;
uint8_t mask = make_lshift_mask(bit_shift);
uint8_t overflow_mask = ~mask;
valtype result(x.size(), 0x00);
for (valtype::size_type index = x.size(); index > 0; index--) {
valtype::size_type i = index - 1;
// make sure that k is always >= 0
if (byte_shift <= i)
{
valtype::size_type k = i - byte_shift;
uint8_t val = (x[i] & mask);
val <<= bit_shift;
result[k] |= val;
if (k >= 1) {
uint8_t carryval = (x[i] & overflow_mask);
carryval >>= 8 - bit_shift;
result[k - 1] |= carryval;
}
}
}
return result;
}
bool CastToBool(const valtype &vch) {
for (size_t i = 0; i < vch.size(); i++) {
if (vch[i] != 0) {
// Can be negative zero
if (i == vch.size() - 1 && vch[i] == 0x80) {
return false;
}
return true;
}
}
return false;
}
static bool IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
if (vchPubKey.size() < 33) {
// Non-canonical public key: too short
return false;
}
if (vchPubKey[0] == 0x04) {
if (vchPubKey.size() != 65) {
// Non-canonical public key: invalid length for uncompressed key
return false;
}
} else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
if (vchPubKey.size() != 33) {
// Non-canonical public key: invalid length for compressed key
return false;
}
} else {
// Non-canonical public key: neither compressed nor uncompressed
return false;
}
return true;
}
static bool IsCompressedPubKey(const valtype &vchPubKey) {
if (vchPubKey.size() != 33) {
// Non-canonical public key: invalid length for compressed key
return false;
}
if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
// Non-canonical public key: invalid prefix for compressed key
return false;
}
return true;
}
/**
* A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len
* S> <S> <hashtype>, where R and S are not negative (their first byte has its
* highest bit not set), and not excessively padded (do not start with a 0 byte,
* unless an otherwise negative number follows, in which case a single 0 byte is
* necessary and even required).
*
* See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
*
* This function is consensus-critical since BIP66.
*/
static bool IsValidSignatureEncoding(const std::vector<uint8_t> &sig) {
// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
// [sighash]
// * total-length: 1-byte length descriptor of everything that follows,
// excluding the sighash byte.
// * R-length: 1-byte length descriptor of the R value that follows.
// * R: arbitrary-length big-endian encoded R value. It must use the
// shortest possible encoding for a positive integers (which means no null
// bytes at the start, except a single one when the next byte has its
// highest bit set).
// * S-length: 1-byte length descriptor of the S value that follows.
// * S: arbitrary-length big-endian encoded S value. The same rules apply.
// * sighash: 1-byte value indicating what data is hashed (not part of the
// DER signature)
// Minimum and maximum size constraints.
if (sig.size() < 9) return false;
if (sig.size() > 73) return false;
// A signature is of type 0x30 (compound).
if (sig[0] != 0x30) return false;
// Make sure the length covers the entire signature.
if (sig[1] != sig.size() - 3) return false;
// Extract the length of the R element.
unsigned int lenR = sig[3];
// Make sure the length of the S element is still inside the signature.
if (5 + lenR >= sig.size()) return false;
// Extract the length of the S element.
unsigned int lenS = sig[5 + lenR];
// Verify that the length of the signature matches the sum of the length
// of the elements.
if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
// Check whether the R element is an integer.
if (sig[2] != 0x02) return false;
// Zero-length integers are not allowed for R.
if (lenR == 0) return false;
// Negative numbers are not allowed for R.
if (sig[4] & 0x80) return false;
// Null bytes at the start of R are not allowed, unless R would otherwise be
// interpreted as a negative number.
if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
// Check whether the S element is an integer.
if (sig[lenR + 4] != 0x02) return false;
// Zero-length integers are not allowed for S.
if (lenS == 0) return false;
// Negative numbers are not allowed for S.
if (sig[lenR + 6] & 0x80) return false;
// Null bytes at the start of S are not allowed, unless S would otherwise be
// interpreted as a negative number.
if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) {
return false;
}
return true;
}
static bool IsLowDERSignature(const valtype &vchSig, ScriptError *serror) {
if (!IsValidSignatureEncoding(vchSig)) {
return set_error(serror, SCRIPT_ERR_SIG_DER);
}
std::vector<uint8_t> vchSigCopy(vchSig.begin(),
vchSig.begin() + vchSig.size() - 1);
if (!CPubKey::CheckLowS(vchSigCopy)) {
return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
}
return true;
}
static SigHashType GetHashType(const valtype &vchSig) {
if (vchSig.size() == 0) {
return SigHashType(0);
}
return SigHashType(vchSig[vchSig.size() - 1]);
}
static void CleanupScriptCode(CScript &scriptCode,
const std::vector<uint8_t> &vchSig,
uint32_t flags) {
// Drop the signature in scripts when SIGHASH_FORKID is not used.
SigHashType sigHashType = GetHashType(vchSig);
if (!(flags & SCRIPT_ENABLE_SIGHASH_FORKID) || !sigHashType.hasForkId()) {
scriptCode.FindAndDelete(CScript(vchSig));
}
}
bool CheckSignatureEncoding(const std::vector<uint8_t> &vchSig, uint32_t flags,
ScriptError *serror) {
// Empty signature. Not strictly DER encoded, but allowed to provide a
// compact way to provide an invalid signature for use with CHECK(MULTI)SIG
if (vchSig.size() == 0) {
return true;
}
if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S |
SCRIPT_VERIFY_STRICTENC)) != 0 &&
!IsValidSignatureEncoding(vchSig)) {
return set_error(serror, SCRIPT_ERR_SIG_DER);
}
if ((flags & SCRIPT_VERIFY_LOW_S) != 0 &&
!IsLowDERSignature(vchSig, serror)) {
// serror is set
return false;
}
if ((flags & SCRIPT_VERIFY_STRICTENC) != 0) {
if (!GetHashType(vchSig).isDefined()) {
return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
}
bool usesForkId = GetHashType(vchSig).hasForkId();
bool forkIdEnabled = flags & SCRIPT_ENABLE_SIGHASH_FORKID;
if (!forkIdEnabled && usesForkId) {
return set_error(serror, SCRIPT_ERR_ILLEGAL_FORKID);
}
if (forkIdEnabled && !usesForkId) {
return set_error(serror, SCRIPT_ERR_MUST_USE_FORKID);
}
}
return true;
}
static bool CheckPubKeyEncoding(const valtype &vchPubKey, uint32_t flags,
ScriptError *serror) {
if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 &&
!IsCompressedOrUncompressedPubKey(vchPubKey)) {
return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
}
// Only compressed keys are accepted when
// SCRIPT_VERIFY_COMPRESSED_PUBKEYTYPE is enabled.
if (flags & SCRIPT_VERIFY_COMPRESSED_PUBKEYTYPE &&
!IsCompressedPubKey(vchPubKey)) {
return set_error(serror, SCRIPT_ERR_NONCOMPRESSED_PUBKEY);
}
return true;
}
static bool CheckMinimalPush(const valtype &data, opcodetype opcode) {
if (data.size() == 0) {
// Could have used OP_0.
return opcode == OP_0;
}
if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
// Could have used OP_1 .. OP_16.
return opcode == OP_1 + (data[0] - 1);
}
if (data.size() == 1 && data[0] == 0x81) {
// Could have used OP_1NEGATE.
return opcode == OP_1NEGATE;
}
if (data.size() <= 75) {
// Could have used a direct push (opcode indicating number of bytes
// pushed + those bytes).
return opcode == data.size();
}
if (data.size() <= 255) {
// Could have used OP_PUSHDATA.
return opcode == OP_PUSHDATA1;
}
if (data.size() <= 65535) {
// Could have used OP_PUSHDATA2.
return opcode == OP_PUSHDATA2;
}
return true;
}
static bool IsOpcodeDisabled(opcodetype opcode) {
switch (opcode) {
case OP_2MUL:
case OP_2DIV:
// Disabled opcodes.
return true;
default:
break;
}
return false;
}
static bool IsInvalidBranchingOpcode(opcodetype opcode) {
return opcode == OP_VERNOTIF || opcode == OP_VERIF;
}
inline bool IsValidMaxOpsPerScript(uint64_t nOpCount,
const CScriptConfig &config,
bool isGenesisEnabled, bool consensus)
{
return (nOpCount <= config.GetMaxOpsPerScript(isGenesisEnabled, consensus));
}
std::optional<bool> EvalScript(
const CScriptConfig& config,
bool consensus,
const task::CCancellationToken& token,
LimitedStack& stack,
const CScript& script,
uint32_t flags,
const BaseSignatureChecker& checker,
ScriptError* serror)
{
static const CScriptNum bnZero(0);
static const CScriptNum bnOne(1);
static const valtype vchFalse(0);
static const valtype vchTrue(1, 1);
CScript::const_iterator pc = script.begin();
CScript::const_iterator pend = script.end();
CScript::const_iterator pbegincodehash = script.begin();
opcodetype opcode;
valtype vchPushValue;
std::vector<bool> vfExec;
std::vector<bool> vfElse;
// altstack shares memory with stack
LimitedStack altstack {stack.makeChildStack()};
set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
const bool utxo_after_genesis{(flags & SCRIPT_UTXO_AFTER_GENESIS) != 0};
const uint64_t maxScriptNumLength = config.GetMaxScriptNumLength(utxo_after_genesis, consensus);
if(script.size() > config.GetMaxScriptSize(utxo_after_genesis, consensus))
{
return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
}
uint64_t nOpCount = 0;
const bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
// if OP_RETURN is found in executed branches after genesis is activated,
// we still have to check if the rest of the script is valid
bool nonTopLevelReturnAfterGenesis = false;
try {
while (pc < pend) {
if (token.IsCanceled())
{
return {};
}
//
// Read instruction
//
if (!script.GetOp(pc, opcode, vchPushValue)) {
return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
}
if (!utxo_after_genesis && (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS))
{
return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
}
// Do not execute instructions if Genesis OP_RETURN was found in executed branches.
bool fExec = !count(vfExec.begin(), vfExec.end(), false) && (!nonTopLevelReturnAfterGenesis || opcode == OP_RETURN);
//
// Check opcode limits.
//
// Push values are not taken into consideration.
// Note how OP_RESERVED does not count towards the opcode limit.
if ((opcode > OP_16) && !IsValidMaxOpsPerScript(++nOpCount, config, utxo_after_genesis, consensus)) {
return set_error(serror, SCRIPT_ERR_OP_COUNT);
}
// Some opcodes are disabled.
if (IsOpcodeDisabled(opcode) && (!utxo_after_genesis || fExec )) {
return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE);
}
if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
if (fRequireMinimal &&
!CheckMinimalPush(vchPushValue, opcode)) {
return set_error(serror, SCRIPT_ERR_MINIMALDATA);
}
stack.push_back(vchPushValue);
} else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF)) {
switch (opcode) {
//
// Push value
//
case OP_1NEGATE:
case OP_1:
case OP_2:
case OP_3:
case OP_4:
case OP_5:
case OP_6:
case OP_7:
case OP_8:
case OP_9:
case OP_10:
case OP_11:
case OP_12:
case OP_13:
case OP_14:
case OP_15:
case OP_16: {
// ( -- value)
CScriptNum bn((int)opcode - (int)(OP_1 - 1));
stack.push_back(bn.getvch());
// The result of these opcodes should always be the
// minimal way to push the data they push, so no need
// for a CheckMinimalPush here.
} break;
//
// Control
//
case OP_NOP:
break;
case OP_CHECKLOCKTIMEVERIFY: {
if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY) || utxo_after_genesis) {
// not enabled; treat as a NOP2
if (flags &
SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
return set_error(
serror,
SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
}
break;
}
if (stack.size() < 1) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
// Note that elsewhere numeric opcodes are limited to
// operands in the range -2**31+1 to 2**31-1, however it
// is legal for opcodes to produce results exceeding
// that range. This limitation is implemented by
// CScriptNum's default 4-byte limit.
//
// If we kept to that limit we'd have a year 2038
// problem, even though the nLockTime field in
// transactions themselves is uint32 which only becomes
// meaningless after the year 2106.
//
// Thus as a special case we tell CScriptNum to accept
// up to 5-byte bignums, which are good until 2**39-1,
// well beyond the 2**32-1 limit of the nLockTime field
// itself.
const CScriptNum nLockTime(stack.stacktop(-1).GetElement(),
fRequireMinimal, 5);
// In the rare event that the argument may be < 0 due to
// some arithmetic being done first, you can always use
// 0 MAX CHECKLOCKTIMEVERIFY.
if (nLockTime < 0) {
return set_error(serror,
SCRIPT_ERR_NEGATIVE_LOCKTIME);
}
// Actually compare the specified lock time with the
// transaction.
if (!checker.CheckLockTime(nLockTime)) {
return set_error(serror,
SCRIPT_ERR_UNSATISFIED_LOCKTIME);
}
break;
}
case OP_CHECKSEQUENCEVERIFY: {
if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY) || utxo_after_genesis) {
// not enabled; treat as a NOP3
if (flags &
SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
return set_error(
serror,
SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
}
break;
}
if (stack.size() < 1) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
// nSequence, like nLockTime, is a 32-bit unsigned
// integer field. See the comment in CHECKLOCKTIMEVERIFY
// regarding 5-byte numeric operands.
const CScriptNum nSequence(stack.stacktop(-1).GetElement(),
fRequireMinimal, 5);
// In the rare event that the argument may be < 0 due to
// some arithmetic being done first, you can always use
// 0 MAX CHECKSEQUENCEVERIFY.
if (nSequence < 0) {
return set_error(serror,
SCRIPT_ERR_NEGATIVE_LOCKTIME);
}
// To provide for future soft-fork extensibility, if the
// operand has the disabled lock-time flag set,
// CHECKSEQUENCEVERIFY behaves as a NOP.
if ((nSequence &
CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != bnZero) {
break;
}
// Compare the specified sequence number with the input.
if (!checker.CheckSequence(nSequence)) {
return set_error(serror,
SCRIPT_ERR_UNSATISFIED_LOCKTIME);
}
break;
}
case OP_NOP1:
case OP_NOP4:
case OP_NOP5:
case OP_NOP6:
case OP_NOP7:
case OP_NOP8:
case OP_NOP9:
case OP_NOP10: {
if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
return set_error(
serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
}
} break;
case OP_IF:
case OP_NOTIF: {
// <expression> if [statements] [else [statements]]
// endif
bool fValue = false;
if (fExec) {
if (stack.size() < 1) {
return set_error(
serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
}
LimitedVector &vch = stack.stacktop(-1);
if (flags & SCRIPT_VERIFY_MINIMALIF) {
if (vch.size() > 1) {
return set_error(serror,
SCRIPT_ERR_MINIMALIF);
}
if (vch.size() == 1 && vch[0] != 1) {
return set_error(serror,
SCRIPT_ERR_MINIMALIF);
}
}
fValue = CastToBool(vch.GetElement());
if (opcode == OP_NOTIF) {
fValue = !fValue;
}
stack.pop_back();
}
vfExec.push_back(fValue);
vfElse.push_back(false);
} break;
case OP_ELSE: {
// Only one ELSE is allowed in IF after genesis.
if (vfExec.empty() || (vfElse.back() && utxo_after_genesis)) {
return set_error(serror,
SCRIPT_ERR_UNBALANCED_CONDITIONAL);
}
vfExec.back() = !vfExec.back();
vfElse.back() = true;
} break;
case OP_ENDIF: {
if (vfExec.empty()) {
return set_error(serror,
SCRIPT_ERR_UNBALANCED_CONDITIONAL);
}
vfExec.pop_back();
vfElse.pop_back();
} break;
case OP_VERIFY: {
// (true -- ) or
// (false -- false) and return
if (stack.size() < 1) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
bool fValue = CastToBool(stack.stacktop(-1).GetElement());
if (fValue) {
stack.pop_back();
} else {
return set_error(serror, SCRIPT_ERR_VERIFY);
}
} break;
case OP_RETURN: {
if (utxo_after_genesis) {
if (vfExec.empty()) {
// Terminate the execution as successful. The remaining of the script does not affect the validity (even in
// presence of unbalanced IFs, invalid opcodes etc)
return set_success(serror);
}
// op_return encountered inside if statement after genesis --> check for invalid grammar
nonTopLevelReturnAfterGenesis = true;
} else {
// Pre-Genesis OP_RETURN marks script as invalid
return set_error(serror, SCRIPT_ERR_OP_RETURN);
}
} break;
//
// Stack ops
//
case OP_TOALTSTACK: {
if (stack.size() < 1) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
altstack.moveTopToStack(stack);
} break;
case OP_FROMALTSTACK: {
if (altstack.size() < 1) {
return set_error(
serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
}
stack.moveTopToStack(altstack);
} break;
case OP_2DROP: {
// (x1 x2 -- )
if (stack.size() < 2) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
stack.pop_back();
stack.pop_back();
} break;
case OP_2DUP: {
// (x1 x2 -- x1 x2 x1 x2)
if (stack.size() < 2) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
LimitedVector vch1 = stack.stacktop(-2);
LimitedVector vch2 = stack.stacktop(-1);
stack.push_back(vch1);
stack.push_back(vch2);
} break;
case OP_3DUP: {
// (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
if (stack.size() < 3) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
LimitedVector vch1 = stack.stacktop(-3);
LimitedVector vch2 = stack.stacktop(-2);
LimitedVector vch3 = stack.stacktop(-1);
stack.push_back(vch1);
stack.push_back(vch2);
stack.push_back(vch3);
} break;
case OP_2OVER: {
// (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
if (stack.size() < 4) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
LimitedVector vch1 = stack.stacktop(-4);
LimitedVector vch2 = stack.stacktop(-3);
stack.push_back(vch1);
stack.push_back(vch2);
} break;
case OP_2ROT: {
// (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
if (stack.size() < 6) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
LimitedVector vch1 = stack.stacktop(-6);
LimitedVector vch2 = stack.stacktop(-5);
stack.erase(- 6, - 4);
stack.push_back(vch1);
stack.push_back(vch2);
} break;
case OP_2SWAP: {
// (x1 x2 x3 x4 -- x3 x4 x1 x2)
if (stack.size() < 4) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
stack.swapElements(stack.size() - 4, stack.size() - 2);
stack.swapElements(stack.size() - 3, stack.size() - 1);
} break;
case OP_IFDUP: {
// (x - 0 | x x)
if (stack.size() < 1) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
LimitedVector vch = stack.stacktop(-1);
if (CastToBool(vch.GetElement())) {
stack.push_back(vch);
}
} break;
case OP_DEPTH: {
// -- stacksize
const CScriptNum bn(bsv::bint{stack.size()});
stack.push_back(bn.getvch());
} break;
case OP_DROP: {
// (x -- )
if (stack.size() < 1) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
stack.pop_back();
} break;
case OP_DUP: {
// (x -- x x)
if (stack.size() < 1) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
LimitedVector vch = stack.stacktop(-1);
stack.push_back(vch);
} break;
case OP_NIP: {
// (x1 x2 -- x2)
if (stack.size() < 2) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
stack.erase(-2);
} break;
case OP_OVER: {
// (x1 x2 -- x1 x2 x1)
if (stack.size() < 2) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
LimitedVector vch = stack.stacktop(-2);
stack.push_back(vch);
} break;
case OP_PICK:
case OP_ROLL: {
// (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
// (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
if (stack.size() < 2) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
const auto& top{stack.stacktop(-1).GetElement()};
const CScriptNum sn{
top, fRequireMinimal,
maxScriptNumLength,
utxo_after_genesis};
stack.pop_back();
if(sn < 0 || sn >= stack.size())
{
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
const auto n{sn.to_size_t_limited()};
LimitedVector vch = stack.stacktop(-n - 1);
if (opcode == OP_ROLL) {
stack.erase(- n - 1);
}
stack.push_back(vch);
} break;
case OP_ROT: {
// (x1 x2 x3 -- x2 x3 x1)
// x2 x1 x3 after first swap
// x2 x3 x1 after second swap
if (stack.size() < 3) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
stack.swapElements(stack.size() - 3, stack.size() - 2);
stack.swapElements(stack.size() - 2, stack.size() - 1);
} break;
case OP_SWAP: {
// (x1 x2 -- x2 x1)
if (stack.size() < 2) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
stack.swapElements(stack.size() - 2, stack.size() - 1);
} break;
case OP_TUCK: {
// (x1 x2 -- x2 x1 x2)
if (stack.size() < 2) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
LimitedVector vch = stack.stacktop(-1);
stack.insert(-2, vch);
} break;
case OP_SIZE: {
// (in -- in size)
if (stack.size() < 1) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
CScriptNum bn(bsv::bint{stack.stacktop(-1).size()});
stack.push_back(bn.getvch());
} break;
//
// Bitwise logic
//
case OP_AND:
case OP_OR:
case OP_XOR: {
// (x1 x2 - out)
if (stack.size() < 2) {
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
LimitedVector &vch1 = stack.stacktop(-2);
LimitedVector &vch2 = stack.stacktop(-1);
// Inputs must be the same size
if (vch1.size() != vch2.size()) {
return set_error(serror,
SCRIPT_ERR_INVALID_OPERAND_SIZE);
}
// To avoid allocating, we modify vch1 in place.
switch (opcode) {
case OP_AND:
for (size_t i = 0; i < vch1.size(); ++i) {
vch1[i] &= vch2[i];
}
break;
case OP_OR:
for (size_t i = 0; i < vch1.size(); ++i) {
vch1[i] |= vch2[i];
}
break;
case OP_XOR:
for (size_t i = 0; i < vch1.size(); ++i) {
vch1[i] ^= vch2[i];
}
break;
default:
break;
}
// And pop vch2.
stack.pop_back();
} break;
case OP_INVERT: {
// (x -- out)
if (stack.size() < 1) {
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
LimitedVector &vch1 = stack.stacktop(-1);
// To avoid allocating, we modify vch1 in place
for(size_t i=0; i<vch1.size(); i++)
{
vch1[i] = ~vch1[i];
}
} break;
case OP_LSHIFT:
{
// (x n -- out)
if(stack.size() < 2)
{
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
const LimitedVector vch1 = stack.stacktop(-2);
const auto& top{stack.stacktop(-1).GetElement()};
CScriptNum n{top, fRequireMinimal, maxScriptNumLength,
utxo_after_genesis};
if(n < 0)
{
return set_error(serror,
SCRIPT_ERR_INVALID_NUMBER_RANGE);
}
stack.pop_back();
stack.pop_back();
auto values{vch1.GetElement()};
do
{
values = LShift(values, n.getint());
n -= utxo_after_genesis
? CScriptNum{bsv::bint{INT32_MAX}}
: CScriptNum{INT32_MAX};
} while(n > 0);
stack.push_back(values);
}
break;
case OP_RSHIFT:
{
// (x n -- out)
if(stack.size() < 2)
{
return set_error(
serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
}
const LimitedVector vch1 = stack.stacktop(-2);
const auto& top{stack.stacktop(-1).GetElement()};
CScriptNum n{top, fRequireMinimal, maxScriptNumLength,
utxo_after_genesis};