-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathmod.rs
3886 lines (3593 loc) · 168 KB
/
mod.rs
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
#[macro_use]
mod macros;
use crate::{
data_stack::{DataStack, Kip10I64, OpcodeData},
ScriptSource, SpkEncoding, TxScriptEngine, TxScriptError, LOCK_TIME_THRESHOLD, MAX_TX_IN_SEQUENCE_NUM, NO_COST_OPCODE,
SEQUENCE_LOCK_TIME_DISABLED, SEQUENCE_LOCK_TIME_MASK,
};
use blake2b_simd::Params;
use kaspa_consensus_core::hashing::sighash::SigHashReusedValues;
use kaspa_consensus_core::hashing::sighash_type::SigHashType;
use kaspa_consensus_core::tx::VerifiableTransaction;
use sha2::{Digest, Sha256};
use std::{
fmt::{Debug, Formatter},
num::TryFromIntError,
};
/// First value in the range formed by the "small integer" Op# opcodes
pub const OP_SMALL_INT_MIN_VAL: u8 = 1;
/// Last value in the range formed by the "small integer" Op# opcodes
pub const OP_SMALL_INT_MAX_VAL: u8 = 16;
/// First value in the range formed by OpData# opcodes (where opcode == value)
pub const OP_DATA_MIN_VAL: u8 = self::codes::OpData1;
/// Last value in the range formed by OpData# opcodes (where opcode == value)
pub const OP_DATA_MAX_VAL: u8 = self::codes::OpData75;
/// Minus 1 value
pub const OP_1_NEGATE_VAL: u8 = 0x81;
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum OpCond {
False,
True,
Skip,
}
impl OpCond {
pub fn negate(&self) -> OpCond {
match self {
OpCond::True => OpCond::False,
OpCond::False => OpCond::True,
OpCond::Skip => OpCond::Skip,
}
}
}
type OpCodeResult = Result<(), TxScriptError>;
pub(crate) struct OpCode<const CODE: u8> {
data: Vec<u8>,
}
impl<const CODE: u8> Debug for OpCode<CODE> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "Opcode<{:#2x}>{{ data:{:?} }}", CODE, self.data)
}
}
pub trait OpCodeMetadata: Debug {
// Opcode number
fn value(&self) -> u8;
// length of data
fn len(&self) -> usize;
// Conditional should be executed also is not in branch
fn is_conditional(&self) -> bool;
// For push data- check if we can use shorter encoding
fn check_minimal_data_push(&self) -> Result<(), TxScriptError>;
fn is_disabled(&self) -> bool;
fn always_illegal(&self) -> bool;
fn is_push_opcode(&self) -> bool;
fn get_data(&self) -> &[u8];
fn is_empty(&self) -> bool {
self.len() == 0
}
}
pub trait OpCodeExecution<T: VerifiableTransaction, Reused: SigHashReusedValues> {
fn empty() -> Result<Box<dyn OpCodeImplementation<T, Reused>>, TxScriptError>
where
Self: Sized;
#[allow(clippy::new_ret_no_self)]
fn new(data: Vec<u8>) -> Result<Box<dyn OpCodeImplementation<T, Reused>>, TxScriptError>
where
Self: Sized;
fn execute(&self, vm: &mut TxScriptEngine<T, Reused>) -> OpCodeResult;
}
pub trait OpcodeSerialization {
fn serialize(&self) -> Vec<u8>;
fn deserialize<'i, I: Iterator<Item = &'i u8>, T: VerifiableTransaction, Reused: SigHashReusedValues>(
it: &mut I,
) -> Result<Box<dyn OpCodeImplementation<T, Reused>>, TxScriptError>
where
Self: Sized;
}
pub trait OpCodeImplementation<T: VerifiableTransaction, Reused: SigHashReusedValues>:
OpCodeExecution<T, Reused> + OpCodeMetadata + OpcodeSerialization
{
}
impl<const CODE: u8> OpCodeMetadata for OpCode<CODE> {
fn value(&self) -> u8 {
CODE
}
fn is_disabled(&self) -> bool {
matches!(
CODE,
codes::OpCat
| codes::OpSubStr
| codes::OpLeft
| codes::OpRight
| codes::OpInvert
| codes::OpAnd
| codes::OpOr
| codes::OpXor
| codes::Op2Mul
| codes::Op2Div
| codes::OpMul
| codes::OpDiv
| codes::OpMod
| codes::OpLShift
| codes::OpRShift
)
}
fn always_illegal(&self) -> bool {
matches!(CODE, codes::OpVerIf | codes::OpVerNotIf)
}
fn is_push_opcode(&self) -> bool {
CODE <= NO_COST_OPCODE
}
fn len(&self) -> usize {
self.data.len()
}
// TODO: add it to opcode specification
fn is_conditional(&self) -> bool {
self.value() >= 0x63 && self.value() <= 0x68
}
fn check_minimal_data_push(&self) -> Result<(), TxScriptError> {
let data_len = self.len();
let opcode = self.value();
if data_len == 0 {
if opcode != codes::OpFalse {
return Err(TxScriptError::NotMinimalData(format!(
"zero length data push is encoded with opcode {self:?} instead of OpFalse"
)));
}
} else if data_len == 1 && OP_SMALL_INT_MIN_VAL <= self.data[0] && self.data[0] <= OP_SMALL_INT_MAX_VAL {
if opcode != codes::OpTrue + self.data[0] - 1 {
return Err(TxScriptError::NotMinimalData(format!(
"zero length data push is encoded with opcode {:?} instead of Op_{}",
self, self.data[0]
)));
}
} else if data_len == 1 && self.data[0] == OP_1_NEGATE_VAL {
if opcode != codes::Op1Negate {
return Err(TxScriptError::NotMinimalData(format!(
"data push of the value -1 encoded \
with opcode {self:?} instead of OP_1NEGATE"
)));
}
} else if data_len <= OP_DATA_MAX_VAL as usize {
if opcode as usize != data_len {
return Err(TxScriptError::NotMinimalData(format!(
"data push of {data_len} bytes encoded \
with opcode {self:?} instead of OP_DATA_{data_len}"
)));
}
} else if data_len <= u8::MAX as usize {
if opcode != codes::OpPushData1 {
return Err(TxScriptError::NotMinimalData(format!(
"data push of {data_len} bytes encoded \
with opcode {self:?} instead of OP_PUSHDATA1"
)));
}
} else if data_len < u16::MAX as usize && opcode != codes::OpPushData2 {
return Err(TxScriptError::NotMinimalData(format!(
"data push of {data_len} bytes encoded \
with opcode {self:?} instead of OP_PUSHDATA2"
)));
}
Ok(())
}
fn get_data(&self) -> &[u8] {
&self.data
}
}
// Helpers for some opcodes with shared data
#[inline]
fn push_data<T: VerifiableTransaction, Reused: SigHashReusedValues>(
data: Vec<u8>,
vm: &mut TxScriptEngine<T, Reused>,
) -> OpCodeResult {
vm.dstack.push(data);
Ok(())
}
#[inline]
fn push_number<T: VerifiableTransaction, Reused: SigHashReusedValues>(
number: i64,
vm: &mut TxScriptEngine<T, Reused>,
) -> OpCodeResult {
vm.dstack.push_item(number)?;
Ok(())
}
/// This macro helps to avoid code duplication in numeric opcodes where the only difference
/// between KIP10_ENABLED and disabled states is the numeric type used (Kip10I64 vs i64).
/// KIP10I64 deserializator supports 8-byte integers
// TODO: Remove this macro after KIP-10 activation.
macro_rules! numeric_op {
($vm: expr, $pattern: pat, $count: expr, $block: expr) => {
if $vm.kip10_enabled {
let $pattern: [Kip10I64; $count] = $vm.dstack.pop_items()?;
let r = $block;
$vm.dstack.push_item(r)?;
Ok(())
} else {
let $pattern: [i64; $count] = $vm.dstack.pop_items()?;
#[allow(clippy::useless_conversion)]
let r = $block;
$vm.dstack.push_item(r)?;
Ok(())
}
};
}
/*
The following is the implementation and metadata of all opcodes. Each opcode has unique
number (and template system makes it impossible to use two opcodes), length specification,
and execution code.
The syntax is as follows:
```
opcode OpCodeName<id, length>(self, vm) {
code;
output
}
// OR
opcode OpCodeName<id, length>(self, vm) statement
// in case of an opcode alias
opcode |OpCodeAlias| OpCodeName<id, length>(self, vm) {
code;
output
}
// OR
opcode |OpCodeAlias| OpCodeName<id, length>(self, vm) statement
```
Length specification is either a number (for fixed length) or a unsigned integer type
(for var length).
The execution code is implementing OpCodeImplementation. You can access the engine using the `vm`
variable.
Implementation details in `opcodes/macros.rs`.
*/
opcode_list! {
// Data push opcodes.
opcode |Op0| OpFalse<0x00, 1>(self , vm) {
vm.dstack.push(vec![]);
Ok(())
}
opcode OpData1<0x01, 2>(self, vm) push_data(self.data.clone(), vm)
opcode OpData2<0x02, 3>(self, vm) push_data(self.data.clone(), vm)
opcode OpData3<0x03, 4>(self, vm) push_data(self.data.clone(), vm)
opcode OpData4<0x04, 5>(self, vm) push_data(self.data.clone(), vm)
opcode OpData5<0x05, 6>(self, vm) push_data(self.data.clone(), vm)
opcode OpData6<0x06, 7>(self, vm) push_data(self.data.clone(), vm)
opcode OpData7<0x07, 8>(self, vm) push_data(self.data.clone(), vm)
opcode OpData8<0x08, 9>(self, vm) push_data(self.data.clone(), vm)
opcode OpData9<0x09, 10>(self, vm) push_data(self.data.clone(), vm)
opcode OpData10<0x0a, 11>(self, vm) push_data(self.data.clone(), vm)
opcode OpData11<0x0b, 12>(self, vm) push_data(self.data.clone(), vm)
opcode OpData12<0x0c, 13>(self, vm) push_data(self.data.clone(), vm)
opcode OpData13<0x0d, 14>(self, vm) push_data(self.data.clone(), vm)
opcode OpData14<0x0e, 15>(self, vm) push_data(self.data.clone(), vm)
opcode OpData15<0x0f, 16>(self, vm) push_data(self.data.clone(), vm)
opcode OpData16<0x10, 17>(self, vm) push_data(self.data.clone(), vm)
opcode OpData17<0x11, 18>(self, vm) push_data(self.data.clone(), vm)
opcode OpData18<0x12, 19>(self, vm) push_data(self.data.clone(), vm)
opcode OpData19<0x13, 20>(self, vm) push_data(self.data.clone(), vm)
opcode OpData20<0x14, 21>(self, vm) push_data(self.data.clone(), vm)
opcode OpData21<0x15, 22>(self, vm) push_data(self.data.clone(), vm)
opcode OpData22<0x16, 23>(self, vm) push_data(self.data.clone(), vm)
opcode OpData23<0x17, 24>(self, vm) push_data(self.data.clone(), vm)
opcode OpData24<0x18, 25>(self, vm) push_data(self.data.clone(), vm)
opcode OpData25<0x19, 26>(self, vm) push_data(self.data.clone(), vm)
opcode OpData26<0x1a, 27>(self, vm) push_data(self.data.clone(), vm)
opcode OpData27<0x1b, 28>(self, vm) push_data(self.data.clone(), vm)
opcode OpData28<0x1c, 29>(self, vm) push_data(self.data.clone(), vm)
opcode OpData29<0x1d, 30>(self, vm) push_data(self.data.clone(), vm)
opcode OpData30<0x1e, 31>(self, vm) push_data(self.data.clone(), vm)
opcode OpData31<0x1f, 32>(self, vm) push_data(self.data.clone(), vm)
opcode OpData32<0x20, 33>(self, vm) push_data(self.data.clone(), vm)
opcode OpData33<0x21, 34>(self, vm) push_data(self.data.clone(), vm)
opcode OpData34<0x22, 35>(self, vm) push_data(self.data.clone(), vm)
opcode OpData35<0x23, 36>(self, vm) push_data(self.data.clone(), vm)
opcode OpData36<0x24, 37>(self, vm) push_data(self.data.clone(), vm)
opcode OpData37<0x25, 38>(self, vm) push_data(self.data.clone(), vm)
opcode OpData38<0x26, 39>(self, vm) push_data(self.data.clone(), vm)
opcode OpData39<0x27, 40>(self, vm) push_data(self.data.clone(), vm)
opcode OpData40<0x28, 41>(self, vm) push_data(self.data.clone(), vm)
opcode OpData41<0x29, 42>(self, vm) push_data(self.data.clone(), vm)
opcode OpData42<0x2a, 43>(self, vm) push_data(self.data.clone(), vm)
opcode OpData43<0x2b, 44>(self, vm) push_data(self.data.clone(), vm)
opcode OpData44<0x2c, 45>(self, vm) push_data(self.data.clone(), vm)
opcode OpData45<0x2d, 46>(self, vm) push_data(self.data.clone(), vm)
opcode OpData46<0x2e, 47>(self, vm) push_data(self.data.clone(), vm)
opcode OpData47<0x2f, 48>(self, vm) push_data(self.data.clone(), vm)
opcode OpData48<0x30, 49>(self, vm) push_data(self.data.clone(), vm)
opcode OpData49<0x31, 50>(self, vm) push_data(self.data.clone(), vm)
opcode OpData50<0x32, 51>(self, vm) push_data(self.data.clone(), vm)
opcode OpData51<0x33, 52>(self, vm) push_data(self.data.clone(), vm)
opcode OpData52<0x34, 53>(self, vm) push_data(self.data.clone(), vm)
opcode OpData53<0x35, 54>(self, vm) push_data(self.data.clone(), vm)
opcode OpData54<0x36, 55>(self, vm) push_data(self.data.clone(), vm)
opcode OpData55<0x37, 56>(self, vm) push_data(self.data.clone(), vm)
opcode OpData56<0x38, 57>(self, vm) push_data(self.data.clone(), vm)
opcode OpData57<0x39, 58>(self, vm) push_data(self.data.clone(), vm)
opcode OpData58<0x3a, 59>(self, vm) push_data(self.data.clone(), vm)
opcode OpData59<0x3b, 60>(self, vm) push_data(self.data.clone(), vm)
opcode OpData60<0x3c, 61>(self, vm) push_data(self.data.clone(), vm)
opcode OpData61<0x3d, 62>(self, vm) push_data(self.data.clone(), vm)
opcode OpData62<0x3e, 63>(self, vm) push_data(self.data.clone(), vm)
opcode OpData63<0x3f, 64>(self, vm) push_data(self.data.clone(), vm)
opcode OpData64<0x40, 65>(self, vm) push_data(self.data.clone(), vm)
opcode OpData65<0x41, 66>(self, vm) push_data(self.data.clone(), vm)
opcode OpData66<0x42, 67>(self, vm) push_data(self.data.clone(), vm)
opcode OpData67<0x43, 68>(self, vm) push_data(self.data.clone(), vm)
opcode OpData68<0x44, 69>(self, vm) push_data(self.data.clone(), vm)
opcode OpData69<0x45, 70>(self, vm) push_data(self.data.clone(), vm)
opcode OpData70<0x46, 71>(self, vm) push_data(self.data.clone(), vm)
opcode OpData71<0x47, 72>(self, vm) push_data(self.data.clone(), vm)
opcode OpData72<0x48, 73>(self, vm) push_data(self.data.clone(), vm)
opcode OpData73<0x49, 74>(self, vm) push_data(self.data.clone(), vm)
opcode OpData74<0x4a, 75>(self, vm) push_data(self.data.clone(), vm)
opcode OpData75<0x4b, 76>(self, vm) push_data(self.data.clone(), vm)
opcode OpPushData1<0x4c, u8>(self, vm) push_data(self.data.clone(), vm)
opcode OpPushData2<0x4d, u16>(self, vm) push_data(self.data.clone(), vm)
opcode OpPushData4<0x4e, u32>(self, vm) push_data(self.data.clone(), vm)
opcode Op1Negate<0x4f, 1>(self, vm) push_number(-1, vm)
opcode OpReserved<0x50, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
opcode |Op1| OpTrue<0x51, 1>(self, vm) push_number(1, vm)
opcode Op2<0x52, 1>(self, vm) push_number(2, vm)
opcode Op3<0x53, 1>(self, vm) push_number(3, vm)
opcode Op4<0x54, 1>(self, vm) push_number(4, vm)
opcode Op5<0x55, 1>(self, vm) push_number(5, vm)
opcode Op6<0x56, 1>(self, vm) push_number(6, vm)
opcode Op7<0x57, 1>(self, vm) push_number(7, vm)
opcode Op8<0x58, 1>(self, vm) push_number(8, vm)
opcode Op9<0x59, 1>(self, vm) push_number(9, vm)
opcode Op10<0x5a, 1>(self, vm) push_number(10, vm)
opcode Op11<0x5b, 1>(self, vm) push_number(11, vm)
opcode Op12<0x5c, 1>(self, vm) push_number(12, vm)
opcode Op13<0x5d, 1>(self, vm) push_number(13, vm)
opcode Op14<0x5e, 1>(self, vm) push_number(14, vm)
opcode Op15<0x5f, 1>(self, vm) push_number(15, vm)
opcode Op16<0x60, 1>(self, vm) push_number(16, vm)
// Control opcodes.
opcode OpNop<0x61, 1>(self, vm) Ok(())
opcode OpVer<0x62, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
opcode OpIf<0x63, 1>(self, vm) {
let mut cond = OpCond::Skip;
if vm.is_executing() {
// This code seems identical to pop_bool, but was written this way to preserve
// the similar flow of go-kaspad
if let Some(mut cond_buf) = vm.dstack.pop() {
if cond_buf.len() > 1 {
return Err(TxScriptError::InvalidState("expected boolean".to_string()));
}
cond = match cond_buf.pop() {
Some(stack_cond) => match stack_cond {
1 => OpCond::True,
_ => return Err(TxScriptError::InvalidState("expected boolean".to_string())),
}
None => OpCond::False,
}
} else {
return Err(TxScriptError::EmptyStack);
}
}
vm.cond_stack.push(cond);
Ok(())
}
opcode OpNotIf<0x64, 1>(self, vm) {
let mut cond = OpCond::Skip;
if vm.is_executing() {
if let Some(mut cond_buf) = vm.dstack.pop() {
if cond_buf.len() > 1 {
return Err(TxScriptError::InvalidState("expected boolean".to_string()));
}
cond = match cond_buf.pop() {
Some(stack_cond) => match stack_cond {
1 => OpCond::False,
_ => return Err(TxScriptError::InvalidState("expected boolean".to_string())),
}
None => OpCond::True,
}
} else {
return Err(TxScriptError::EmptyStack);
}
}
vm.cond_stack.push(cond);
Ok(())
}
opcode OpVerIf<0x65, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
opcode OpVerNotIf<0x66, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
opcode OpElse<0x67, 1>(self, vm) {
if let Some(cond) = vm.cond_stack.last_mut() {
*cond = cond.negate();
Ok(())
} else {
Err(TxScriptError::InvalidState("condition stack empty".to_string()))
}
}
opcode OpEndIf<0x68, 1>(self, vm) {
match vm.cond_stack.pop() {
None => Err(TxScriptError::InvalidState("condition stack empty".to_string())),
_ => Ok(())
}
}
opcode OpVerify<0x69, 1>(self, vm) {
let [result]: [bool; 1] = vm.dstack.pop_items()?;
match result {
true => Ok(()),
false => Err(TxScriptError::VerifyError)
}
}
opcode OpReturn<0x6a, 1>(self, vm) Err(TxScriptError::EarlyReturn)
// Stack opcodes.
opcode OpToAltStack<0x6b, 1>(self, vm) {
let [item] = vm.dstack.pop_raw()?;
vm.astack.push(item);
Ok(())
}
opcode OpFromAltStack<0x6c, 1>(self, vm) {
match vm.astack.pop() {
Some(last) => {
vm.dstack.push(last);
Ok(())
},
None => Err(TxScriptError::EmptyStack)
}
}
opcode Op2Drop<0x6d, 1>(self, vm) vm.dstack.drop_items::<2>()
opcode Op2Dup<0x6e, 1>(self, vm) vm.dstack.dup_items::<2>()
opcode Op3Dup<0x6f, 1>(self, vm) vm.dstack.dup_items::<3>()
opcode Op2Over<0x70, 1>(self, vm) vm.dstack.over_items::<2>()
opcode Op2Rot<0x71, 1>(self, vm) vm.dstack.rot_items::<2>()
opcode Op2Swap<0x72, 1>(self, vm) vm.dstack.swap_items::<2>()
opcode OpIfDup<0x73, 1>(self, vm) {
let [result] = vm.dstack.peek_raw()?;
if <Vec<u8> as OpcodeData<bool>>::deserialize(&result)? {
vm.dstack.push(result);
}
Ok(())
}
opcode OpDepth<0x74, 1>(self, vm) push_number(vm.dstack.len() as i64, vm)
opcode OpDrop<0x75, 1>(self, vm) vm.dstack.drop_items::<1>()
opcode OpDup<0x76, 1>(self, vm) vm.dstack.dup_items::<1>()
opcode OpNip<0x77, 1>(self, vm) {
match vm.dstack.len() >= 2 {
true => {
vm.dstack.remove(vm.dstack.len()-2);
Ok(())
}
false => Err(TxScriptError::InvalidStackOperation(2, vm.dstack.len())),
}
}
opcode OpOver<0x78, 1>(self, vm) vm.dstack.over_items::<1>()
opcode OpPick<0x79, 1>(self, vm) {
let [loc]: [i32; 1] = vm.dstack.pop_items()?;
if loc < 0 || loc as usize >= vm.dstack.len() {
return Err(TxScriptError::InvalidState("pick at an invalid location".to_string()));
}
vm.dstack.push(vm.dstack[vm.dstack.len()-(loc as usize)-1].clone());
Ok(())
}
opcode OpRoll<0x7a, 1>(self, vm) {
let [loc]: [i32; 1] = vm.dstack.pop_items()?;
if loc < 0 || loc as usize >= vm.dstack.len() {
return Err(TxScriptError::InvalidState("roll at an invalid location".to_string()));
}
let item = vm.dstack.remove(vm.dstack.len()-(loc as usize)-1);
vm.dstack.push(item);
Ok(())
}
opcode OpRot<0x7b, 1>(self, vm) vm.dstack.rot_items::<1>()
opcode OpSwap<0x7c, 1>(self, vm) vm.dstack.swap_items::<1>()
opcode OpTuck<0x7d, 1>(self, vm) {
match vm.dstack.len() >= 2 {
true => {
vm.dstack.insert(vm.dstack.len()-2, vm.dstack.last().expect("We have at least two items").clone());
Ok(())
}
false => Err(TxScriptError::InvalidStackOperation(2, vm.dstack.len()))
}
}
// Splice opcodes.
opcode OpCat<0x7e, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
opcode OpSubStr<0x7f, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
opcode OpLeft<0x80, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
opcode OpRight<0x81, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
opcode OpSize<0x82, 1>(self, vm) {
match vm.dstack.last() {
Some(last) => {
vm.dstack.push_item(i64::try_from(last.len()).map_err(|e| TxScriptError::NumberTooBig(e.to_string()))?)?;
Ok(())
},
None => Err(TxScriptError::InvalidStackOperation(1, 0))
}
}
// Bitwise logic opcodes.
opcode OpInvert<0x83, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
opcode OpAnd<0x84, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
opcode OpOr<0x85, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
opcode OpXor<0x86, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
opcode OpEqual<0x87, 1>(self, vm) {
match vm.dstack.len() >= 2 {
true => {
let pair = vm.dstack.split_off(vm.dstack.len() - 2);
match pair[0] == pair[1] {
true => vm.dstack.push(vec![1]),
false => vm.dstack.push(vec![]),
}
Ok(())
}
false => Err(TxScriptError::InvalidStackOperation(2, vm.dstack.len()))
}
}
opcode OpEqualVerify<0x88, 1>(self, vm) {
match vm.dstack.len() >= 2 {
true => {
let pair = vm.dstack.split_off(vm.dstack.len() - 2);
match pair[0] == pair[1] {
true => Ok(()),
false => Err(TxScriptError::VerifyError),
}
}
false => Err(TxScriptError::InvalidStackOperation(2, vm.dstack.len()))
}
}
opcode OpReserved1<0x89, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
opcode OpReserved2<0x8a, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
// Numeric related opcodes.
opcode Op1Add<0x8b, 1>(self, vm) {
numeric_op!(vm, [value], 1, value.checked_add(1).ok_or_else(|| TxScriptError::NumberTooBig("Result of addition exceeds 64-bit signed integer range".to_string()))?)
}
opcode Op1Sub<0x8c, 1>(self, vm) {
numeric_op!(vm, [value], 1, value.checked_sub(1).ok_or_else(|| TxScriptError::NumberTooBig("Result of subtraction exceeds 64-bit signed integer range".to_string()))?)
}
opcode Op2Mul<0x8d, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
opcode Op2Div<0x8e, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
opcode OpNegate<0x8f, 1>(self, vm) {
numeric_op!(vm, [value], 1, value.checked_neg().ok_or_else(|| TxScriptError::NumberTooBig("Negation result exceeds 64-bit signed integer range".to_string()))?)
}
opcode OpAbs<0x90, 1>(self, vm) {
numeric_op!(vm, [value], 1, value.checked_abs().ok_or_else(|| TxScriptError::NumberTooBig("Absolute value exceeds 64-bit signed integer range".to_string()))?)
}
opcode OpNot<0x91, 1>(self, vm) {
numeric_op!(vm, [m], 1, (m == 0) as i64)
}
opcode Op0NotEqual<0x92, 1>(self, vm) {
numeric_op!(vm, [m], 1, (m != 0) as i64)
}
opcode OpAdd<0x93, 1>(self, vm) {
numeric_op!(vm, [a,b], 2, a.checked_add(b.into()).ok_or_else(|| TxScriptError::NumberTooBig("Sum exceeds 64-bit signed integer range".to_string()))?)
}
opcode OpSub<0x94, 1>(self, vm) {
numeric_op!(vm, [a,b], 2, a.checked_sub(b.into()).ok_or_else(|| TxScriptError::NumberTooBig("Difference exceeds 64-bit signed integer range".to_string()))?)
}
opcode OpMul<0x95, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
opcode OpDiv<0x96, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
opcode OpMod<0x97, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
opcode OpLShift<0x98, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
opcode OpRShift<0x99, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
opcode OpBoolAnd<0x9a, 1>(self, vm) {
numeric_op!(vm, [a,b], 2, ((a != 0) && (b != 0)) as i64)
}
opcode OpBoolOr<0x9b, 1>(self, vm) {
numeric_op!(vm, [a,b], 2, ((a != 0) || (b != 0)) as i64)
}
opcode OpNumEqual<0x9c, 1>(self, vm) {
numeric_op!(vm, [a,b], 2, (a == b) as i64)
}
opcode OpNumEqualVerify<0x9d, 1>(self, vm) {
if vm.kip10_enabled {
let [a,b]: [Kip10I64; 2] = vm.dstack.pop_items()?;
match a == b {
true => Ok(()),
false => Err(TxScriptError::VerifyError)
}
} else {
let [a,b]: [i64; 2] = vm.dstack.pop_items()?;
match a == b {
true => Ok(()),
false => Err(TxScriptError::VerifyError)
}
}
}
opcode OpNumNotEqual<0x9e, 1>(self, vm) {
numeric_op!(vm, [a, b], 2, (a != b) as i64)
}
opcode OpLessThan<0x9f, 1>(self, vm) {
numeric_op!(vm, [a, b], 2, (a < b) as i64)
}
opcode OpGreaterThan<0xa0, 1>(self, vm) {
numeric_op!(vm, [a, b], 2, (a > b) as i64)
}
opcode OpLessThanOrEqual<0xa1, 1>(self, vm) {
numeric_op!(vm, [a, b], 2, (a <= b) as i64)
}
opcode OpGreaterThanOrEqual<0xa2, 1>(self, vm) {
numeric_op!(vm, [a, b], 2, (a >= b) as i64)
}
opcode OpMin<0xa3, 1>(self, vm) {
numeric_op!(vm, [a, b], 2, a.min(b))
}
opcode OpMax<0xa4, 1>(self, vm) {
numeric_op!(vm, [a, b], 2, a.max(b))
}
opcode OpWithin<0xa5, 1>(self, vm) {
numeric_op!(vm, [x,l,u], 3, (x >= l && x < u) as i64)
}
// Undefined opcodes.
opcode OpUnknown166<0xa6, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
opcode OpUnknown167<0xa7, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
// Crypto opcodes.
opcode OpSHA256<0xa8, 1>(self, vm) {
let [last] = vm.dstack.pop_raw()?;
let mut hasher = Sha256::new();
hasher.update(last);
vm.dstack.push(hasher.finalize().to_vec());
Ok(())
}
opcode OpCheckMultiSigECDSA<0xa9, 1>(self, vm) {
vm.op_check_multisig_schnorr_or_ecdsa(true)
}
opcode OpBlake2b<0xaa, 1>(self, vm) {
let [last] = vm.dstack.pop_raw()?;
//let hash = blake2b(last.as_slice());
let hash = Params::new().hash_length(32).to_state().update(&last).finalize();
vm.dstack.push(hash.as_bytes().to_vec());
Ok(())
}
opcode OpCheckSigECDSA<0xab, 1>(self, vm) {
let [mut sig, key] = vm.dstack.pop_raw()?;
// Hash type
match sig.pop() {
Some(typ) => {
let hash_type = SigHashType::from_u8(typ).map_err(|e| TxScriptError::InvalidSigHashType(typ))?;
match vm.check_ecdsa_signature(hash_type, key.as_slice(), sig.as_slice()) {
Ok(valid) => {
vm.dstack.push_item(valid)?;
Ok(())
},
Err(e) => {
Err(e)
}
}
}
None => {
vm.dstack.push_item(false)?;
Ok(())
}
}
}
opcode OpCheckSig<0xac, 1>(self, vm) {
let [mut sig, key] = vm.dstack.pop_raw()?;
// Hash type
match sig.pop() {
Some(typ) => {
let hash_type = SigHashType::from_u8(typ).map_err(|e| TxScriptError::InvalidSigHashType(typ))?;
match vm.check_schnorr_signature(hash_type, key.as_slice(), sig.as_slice()) {
Ok(valid) => {
vm.dstack.push_item(valid)?;
Ok(())
},
Err(e) => {
Err(e)
}
}
}
None => {
vm.dstack.push_item(false)?;
Ok(())
}
}
}
opcode OpCheckSigVerify<0xad, 1>(self, vm) {
// TODO: when changing impl to array based, change this too
OpCheckSig{data: self.data.clone()}.execute(vm)?;
let [valid]: [bool; 1] = vm.dstack.pop_items()?;
match valid {
true => Ok(()),
false => Err(TxScriptError::VerifyError)
}
}
opcode OpCheckMultiSig<0xae, 1>(self, vm) {
vm.op_check_multisig_schnorr_or_ecdsa(false)
}
opcode OpCheckMultiSigVerify<0xaf, 1>(self, vm) {
// TODO: when changing impl to array based, change this too
OpCheckMultiSig{data: self.data.clone()}.execute(vm)?;
let [valid]: [bool; 1] = vm.dstack.pop_items()?;
match valid {
true => Ok(()),
false => Err(TxScriptError::VerifyError)
}
}
opcode OpCheckLockTimeVerify<0xb0, 1>(self, vm) {
match vm.script_source {
ScriptSource::TxInput {input, tx, ..} => {
let [mut lock_time_bytes] = vm.dstack.pop_raw()?;
// Make sure lockTimeBytes is exactly 8 bytes.
// If more - return ErrNumberTooBig
// If less - pad with 0's
if lock_time_bytes.len() > 8 {
return Err(TxScriptError::NumberTooBig(format!("lockTime value represented as {lock_time_bytes:x?} is longer then 8 bytes")))
}
lock_time_bytes.resize(8, 0);
let stack_lock_time = u64::from_le_bytes(lock_time_bytes.try_into().expect("checked vector size"));
// The lock time field of a transaction is either a DAA score at
// which the transaction is finalized or a timestamp depending on if the
// value is before the constants.LockTimeThreshold. When it is under the
// threshold it is a DAA score.
if !(
(tx.tx().lock_time < LOCK_TIME_THRESHOLD && stack_lock_time < LOCK_TIME_THRESHOLD) ||
(tx.tx().lock_time >= LOCK_TIME_THRESHOLD && stack_lock_time >= LOCK_TIME_THRESHOLD)
){
return Err(TxScriptError::UnsatisfiedLockTime(format!("mismatched locktime types -- tx locktime {}, stack locktime {}", tx.tx().lock_time, stack_lock_time)))
}
if stack_lock_time > tx.tx().lock_time {
return Err(TxScriptError::UnsatisfiedLockTime(format!("locktime requirement not satisfied -- locktime is greater than the transaction locktime: {} > {}", stack_lock_time, tx.tx().lock_time)))
}
// The lock time feature can also be disabled, thereby bypassing
// OP_CHECKLOCKTIMEVERIFY, if every transaction input has been finalized by
// setting its sequence to the maximum value (constants.MaxTxInSequenceNum). This
// condition would result in the transaction being allowed into the blockDAG
// making the opcode ineffective.
//
// This condition is prevented by enforcing that the input being used by
// the opcode is unlocked (its sequence number is less than the max
// value). This is sufficient to prove correctness without having to
// check every input.
//
// NOTE: This implies that even if the transaction is not finalized due to
// another input being unlocked, the opcode execution will still fail when the
// input being used by the opcode is locked.
if input.sequence == MAX_TX_IN_SEQUENCE_NUM {
return Err(TxScriptError::UnsatisfiedLockTime("transaction input is finalized".to_string()));
}
Ok(())
}
_ => Err(TxScriptError::InvalidSource("LockTimeVerify only applies to transaction inputs".to_string()))
}
}
opcode OpCheckSequenceVerify<0xb1, 1>(self, vm) {
match vm.script_source {
ScriptSource::TxInput {input, tx, ..} => {
let [mut sequence_bytes] = vm.dstack.pop_raw()?;
// Make sure sequenceBytes is exactly 8 bytes.
// If more - return ErrNumberTooBig
// If less - pad with 0's
if sequence_bytes.len() > 8 {
return Err(TxScriptError::NumberTooBig(format!("sequence value represented as {sequence_bytes:x?} is longer then 8 bytes")))
}
// Don't use makeScriptNum here, since sequence is not an actual number, minimal encoding rules don't apply to it,
// and is more convenient to be represented as an unsigned int.
sequence_bytes.resize(8, 0);
let stack_sequence = u64::from_le_bytes(sequence_bytes.try_into().expect("ensured size checks"));
// To provide for future soft-fork extensibility, if the
// operand has the disabled lock-time flag set,
// CHECKSEQUENCEVERIFY behaves as a NOP.
if stack_sequence & SEQUENCE_LOCK_TIME_DISABLED != 0 {
return Ok(());
}
// Sequence numbers with their most significant bit set are not
// consensus constrained. Testing that the transaction's sequence
// number does not have this bit set prevents using this property
// to get around a CHECKSEQUENCEVERIFY check.
if input.sequence & SEQUENCE_LOCK_TIME_DISABLED != 0 {
return Err(TxScriptError::UnsatisfiedLockTime(format!("transaction sequence has sequence locktime disabled bit set: {:#x}", input.sequence)));
}
// Mask off non-consensus bits before doing comparisons.
if (stack_sequence & SEQUENCE_LOCK_TIME_MASK) > (input.sequence & SEQUENCE_LOCK_TIME_MASK) {
return Err(TxScriptError::UnsatisfiedLockTime(format!("locktime requirement not satisfied -- locktime is greater than the transaction locktime: {} > {}", stack_sequence & SEQUENCE_LOCK_TIME_MASK, input.sequence & SEQUENCE_LOCK_TIME_MASK)))
}
Ok(())
}
_ => Err(TxScriptError::InvalidSource("LockTimeVerify only applies to transaction inputs".to_string()))
}
}
// Introspection opcodes
// Transaction level opcodes (following Transaction struct field order)
opcode OpTxVersion<0xb2, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
opcode OpTxInputCount<0xb3, 1>(self, vm) {
if vm.kip10_enabled {
match vm.script_source {
ScriptSource::TxInput{tx, ..} => {
push_number(tx.inputs().len() as i64, vm)
},
_ => Err(TxScriptError::InvalidSource("OpInputCount only applies to transaction inputs".to_string()))
}
} else {
Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
}
}
opcode OpTxOutputCount<0xb4, 1>(self, vm) {
if vm.kip10_enabled {
match vm.script_source {
ScriptSource::TxInput{tx, ..} => {
push_number(tx.outputs().len() as i64, vm)
},
_ => Err(TxScriptError::InvalidSource("OpOutputCount only applies to transaction inputs".to_string()))
}
} else {
Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
}
}
opcode OpTxLockTime<0xb5, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
opcode OpTxSubnetId<0xb6, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
opcode OpTxGas<0xb7, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
opcode OpTxPayload<0xb8, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
// Input related opcodes (following TransactionInput struct field order)
opcode OpTxInputIndex<0xb9, 1>(self, vm) {
if vm.kip10_enabled {
match vm.script_source {
ScriptSource::TxInput{idx, ..} => {
push_number(idx as i64, vm)
},
_ => Err(TxScriptError::InvalidSource("OpInputIndex only applies to transaction inputs".to_string()))
}
} else {
Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
}
}
opcode OpOutpointTxId<0xba, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
opcode OpOutpointIndex<0xbb, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
opcode OpTxInputScriptSig<0xbc, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
opcode OpTxInputSeq<0xbd, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
// UTXO related opcodes (following UtxoEntry struct field order)
opcode OpTxInputAmount<0xbe, 1>(self, vm) {
if vm.kip10_enabled {
match vm.script_source {
ScriptSource::TxInput{tx, ..} => {
let [idx]: [i32; 1] = vm.dstack.pop_items()?;
let utxo = usize::try_from(idx).ok()
.and_then(|idx| tx.utxo(idx))
.ok_or_else(|| TxScriptError::InvalidInputIndex(idx, tx.inputs().len()))?;
push_number(utxo.amount.try_into().map_err(|e: TryFromIntError| TxScriptError::NumberTooBig(e.to_string()))?, vm)
},
_ => Err(TxScriptError::InvalidSource("OpInputAmount only applies to transaction inputs".to_string()))
}
} else {
Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
}
}
opcode OpTxInputSpk<0xbf, 1>(self, vm) {
if vm.kip10_enabled {
match vm.script_source {
ScriptSource::TxInput{tx, ..} => {
let [idx]: [i32; 1] = vm.dstack.pop_items()?;
let utxo = usize::try_from(idx).ok()
.and_then(|idx| tx.utxo(idx))
.ok_or_else(|| TxScriptError::InvalidInputIndex(idx, tx.inputs().len()))?;
vm.dstack.push(utxo.script_public_key.to_bytes());
Ok(())
},
_ => Err(TxScriptError::InvalidSource("OpInputSpk only applies to transaction inputs".to_string()))
}
} else {
Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
}
}
opcode OpTxInputBlockDaaScore<0xc0, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
opcode OpTxInputIsCoinbase<0xc1, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
// Output related opcodes (following TransactionOutput struct field order)
opcode OpTxOutputAmount<0xc2, 1>(self, vm) {
if vm.kip10_enabled {
match vm.script_source {
ScriptSource::TxInput{tx, ..} => {
let [idx]: [i32; 1] = vm.dstack.pop_items()?;
let output = usize::try_from(idx).ok()
.and_then(|idx| tx.outputs().get(idx))
.ok_or_else(|| TxScriptError::InvalidOutputIndex(idx, tx.inputs().len()))?;
push_number(output.value.try_into().map_err(|e: TryFromIntError| TxScriptError::NumberTooBig(e.to_string()))?, vm)
},
_ => Err(TxScriptError::InvalidSource("OpOutputAmount only applies to transaction inputs".to_string()))
}
} else {
Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
}
}
opcode OpTxOutputSpk<0xc3, 1>(self, vm) {
if vm.kip10_enabled {
match vm.script_source {
ScriptSource::TxInput{tx, ..} => {
let [idx]: [i32; 1] = vm.dstack.pop_items()?;
let output = usize::try_from(idx).ok()
.and_then(|idx| tx.outputs().get(idx))
.ok_or_else(|| TxScriptError::InvalidOutputIndex(idx, tx.inputs().len()))?;
vm.dstack.push(output.script_public_key.to_bytes());
Ok(())
},
_ => Err(TxScriptError::InvalidSource("OpOutputSpk only applies to transaction inputs".to_string()))
}
} else {
Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
}
}
// Undefined opcodes
opcode OpUnknown196<0xc4, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
opcode OpUnknown197<0xc5, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))