This repository has been archived by the owner on Nov 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathmavm.rs
1698 lines (1590 loc) · 57.3 KB
/
mavm.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
/*
* Copyright 2020, Offchain Labs, Inc. All rights reserved.
*/
use crate::compile::{DebugInfo, FrameSize, FuncProperties, SlotNum, TypeTree};
use crate::console::Color;
use crate::stringtable::StringId;
use crate::uint256::Uint256;
use crate::upload::CodeUploader;
use ethers_core::utils::keccak256;
use serde::de::Visitor;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use serde_repr::{Deserialize_repr, Serialize_repr};
use std::hash::{Hash, Hasher};
use std::{collections::HashMap, fmt, sync::Arc};
/// A label who's value is the same across ArbOS versions
pub type LabelId = u64;
#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy, Serialize, Deserialize)]
pub enum Label {
Func(LabelId), // A function uniquely identified by module & name
Closure(LabelId), // A closure uniquely identified by module & name
Anon(LabelId), // An anonymous label identified by func/closure + count
Evm(usize), // program counter in EVM contract
}
impl Label {
pub fn get_id(&self) -> LabelId {
match self {
Label::Func(id) | Label::Closure(id) | Label::Anon(id) => *id,
Label::Evm(n) => panic!("no unique id for evm label {}", n),
}
}
pub fn avm_hash(&self) -> Value {
match self {
Label::Func(id) | Label::Closure(id) => Value::avm_hash2(
&Value::Int(Uint256::from_usize(4)),
&Value::Int(Uint256::from_u64(*id)),
),
Label::Anon(n) => Value::avm_hash2(
&Value::Int(Uint256::from_usize(5)),
&Value::Int(Uint256::from_usize(*n as usize)),
),
Label::Evm(_) => {
panic!("tried to avm_hash an EVM label");
}
}
}
pub fn pretty_print(&self, highlight: &str) -> String {
Value::Label(*self).pretty_print(highlight)
}
}
impl fmt::Display for Label {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Label::Func(sid) => write!(f, "function_{}", sid),
Label::Closure(sid) => write!(f, "closure_{}", sid),
Label::Anon(n) => write!(f, "label_{}", n),
Label::Evm(pc) => write!(f, "EvmPC({})", pc),
}
}
}
#[derive(Default)]
pub struct LabelGenerator {
current: LabelId,
}
impl LabelGenerator {
/// Creates a new label generator that will hand out labels starting at some value.
/// In practice, this means giving the generator a unique func id, so that local labels
/// are always unique regardless of the function they are in.
pub fn new(current: LabelId) -> Self {
LabelGenerator { current }
}
/// Hands out a new label, advancing the generator
pub fn next(&mut self) -> Label {
let next = Label::Anon(self.current);
self.current += 1;
next
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Instruction<T = Opcode> {
pub opcode: T,
pub immediate: Option<Value>,
#[serde(default)]
pub debug_info: DebugInfo,
}
impl From<Instruction<AVMOpcode>> for Instruction {
fn from(from: Instruction<AVMOpcode>) -> Self {
let Instruction {
opcode,
immediate,
debug_info,
} = from;
Self {
opcode: opcode.into(),
immediate,
debug_info,
}
}
}
impl From<AVMOpcode> for Instruction<AVMOpcode> {
fn from(opcode: AVMOpcode) -> Self {
Self::from_opcode(opcode, DebugInfo::default())
}
}
impl From<Opcode> for Instruction {
fn from(opcode: Opcode) -> Self {
Self::from_opcode(opcode, DebugInfo::default())
}
}
impl<T> Instruction<T> {
pub fn new(opcode: T, immediate: Option<Value>, debug_info: DebugInfo) -> Self {
Instruction {
opcode,
immediate,
debug_info,
}
}
pub fn from_opcode(opcode: T, debug_info: DebugInfo) -> Self {
Instruction::new(opcode, None, debug_info)
}
pub fn from_opcode_imm(opcode: T, immediate: Value, debug_info: DebugInfo) -> Self {
Instruction::new(opcode, Some(immediate), debug_info)
}
pub fn replace_labels(self, label_map: &HashMap<Label, CodePt>) -> Result<Self, Label> {
match self.immediate {
Some(val) => Ok(Instruction::from_opcode_imm(
self.opcode,
val.replace_labels(label_map)?,
self.debug_info,
)),
None => Ok(self),
}
}
}
impl Instruction<AVMOpcode> {
pub fn _upload(&self, u: &mut CodeUploader) {
u.push_byte(self.opcode.to_number());
if let Some(val) = &self.immediate {
u.push_byte(1u8);
val.upload(u);
} else {
u.push_byte(0u8);
}
}
pub fn pretty_print(&self, highlight: &str) -> String {
let label_color = Color::PINK;
let op = Opcode::AVMOpcode(self.opcode).pretty_print(label_color);
match &self.immediate {
Some(value) => format!("{} {}", op, value.pretty_print(highlight)),
None => op,
}
}
}
impl Instruction {
pub fn is_view(&self, type_tree: &TypeTree) -> bool {
self.opcode.is_view(type_tree)
}
pub fn is_write(&self, type_tree: &TypeTree) -> bool {
self.opcode.is_write(type_tree)
}
pub fn get_label(&self) -> Option<Label> {
match &self.opcode {
Opcode::Label(label) => Some(*label),
_ => None,
}
}
pub fn get_uniques(&self) -> Vec<LabelId> {
let mut uniques = vec![];
if let Opcode::Label(Label::Func(id) | Label::Closure(id)) = self.opcode {
uniques.push(id);
}
if let Some(value) = &self.immediate {
uniques.extend(value.get_uniques());
}
uniques
}
pub fn pretty_print(&self, highlight: &str) -> String {
let label_color = Color::PINK;
let text = match &self.immediate {
Some(value) => format!(
"{} {}",
self.opcode.pretty_print(label_color),
value.pretty_print(highlight)
),
None => format!("{}", self.opcode.pretty_print(label_color)),
};
match self.debug_info.attributes.color_group {
1 => Color::orange(text),
_ => text,
}
}
}
impl<T> fmt::Display for Instruction<T>
where
T: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.immediate {
Some(value) => match value {
Value::Tuple(_) => write!(f, "[{}]\n {}", value, self.opcode),
_ => write!(f, "{} {}", self.opcode, value),
},
None => write!(f, "{}", self.opcode),
}
}
}
#[macro_export]
macro_rules! opcode {
($opcode:ident) => {
Instruction::from(Opcode::AVMOpcode(AVMOpcode::$opcode))
};
($opcode:ident, $immediate:expr) => {
Instruction::from_opcode_imm(
Opcode::AVMOpcode(AVMOpcode::$opcode),
$immediate,
DebugInfo::default(),
)
};
(@$($opcode:tt)+) => {
Instruction::from_opcode(Opcode::$($opcode)+, DebugInfo::default())
};
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum CodePt {
Internal(usize),
External(usize), // slot in imported funcs list
InSegment(usize, usize), // in code segment, at offset
Null, // initial value of the Error Codepoint register
}
impl CodePt {
pub fn new_internal(pc: usize) -> Self {
CodePt::Internal(pc)
}
pub fn new_in_segment(seg_num: usize, offset: usize) -> Self {
CodePt::InSegment(seg_num, offset)
}
pub fn upload(&self, u: &mut CodeUploader) {
match self {
CodePt::Internal(pc) => {
u.push_byte(1);
u.push_bytes(&Uint256::from_usize(u._translate_pc(*pc)).rlp_encode());
}
_ => {
panic!("Tried to upload bad codepoint");
}
}
}
pub fn incr(&self) -> Option<Self> {
match self {
CodePt::Internal(pc) => Some(CodePt::Internal(pc + 1)),
CodePt::InSegment(seg, offset) => {
if *offset == 0 {
None
} else {
Some(CodePt::InSegment(*seg, offset - 1))
}
}
CodePt::External(_) => None,
CodePt::Null => None,
}
}
pub fn avm_hash(&self) -> Value {
match self {
CodePt::Internal(sz) => Value::avm_hash2(
&Value::Int(Uint256::from_usize(3)),
&Value::Int(Uint256::from_usize(*sz)),
),
CodePt::External(_) => {
Value::Int(Uint256::zero()) // never gets called when it matters
}
CodePt::InSegment(_, _) => {
Value::Int(Uint256::zero()) // never gets called when it matters
}
CodePt::Null => Value::Int(Uint256::zero()),
}
}
}
impl fmt::Display for CodePt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CodePt::Internal(pc) => write!(f, "Internal({})", pc),
CodePt::External(idx) => write!(f, "External({})", idx),
CodePt::InSegment(seg, offset) => write!(f, "(segment {}, offset {})", seg, offset),
CodePt::Null => write!(f, "Null"),
}
}
}
#[derive(Debug, Clone, Eq)]
pub struct Buffer {
root: Arc<BufferNode>,
size: u128,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BufferNode {
Leaf(Vec<u8>),
Internal(BufferInternal),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BufferInternal {
height: usize,
capacity: u128,
left: Arc<BufferNode>,
right: Arc<BufferNode>,
hash_val: Uint256,
}
impl Buffer {
pub fn new_empty() -> Self {
Buffer {
root: Arc::new(BufferNode::new_empty()),
size: 0,
}
}
pub fn from_bytes(contents: Vec<u8>) -> Self {
let mut ret = Buffer::new_empty();
for i in 0..contents.len() {
ret = ret.set_byte(i as u128, contents[i]);
}
ret
}
pub fn as_bytes(&self, nbytes: usize) -> Vec<u8> {
// TODO: make this more efficient
let mut ret = vec![];
for i in 0..nbytes {
ret.push(self.read_byte(i as u128));
}
ret
}
pub fn max_size(&self) -> u128 {
self.size
}
fn avm_hash(&self) -> Uint256 {
self.root.hash()
}
pub fn hex_encode(&self) -> String {
self.root.hex_encode(self.size as usize)
}
pub fn read_byte(&self, offset: u128) -> u8 {
if offset >= self.size {
0u8
} else {
self.root.read_byte(offset)
}
}
pub fn set_byte(&self, offset: u128, val: u8) -> Self {
Buffer {
root: Arc::new(self.root.set_byte(offset, val)),
size: if offset >= self.size {
offset + 1
} else {
self.size
},
}
}
}
impl Hash for Buffer {
fn hash<H: Hasher>(&self, state: &mut H) {
self.root.hash().hash(state);
}
}
impl PartialEq for Buffer {
fn eq(&self, other: &Buffer) -> bool {
self.avm_hash() == other.avm_hash()
}
}
struct BufferVisitor;
impl<'de> Visitor<'de> for BufferVisitor {
type Value = Buffer;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Expected hex string")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Buffer::from_bytes(hex::decode(v).map_err(|_| {
E::custom("Could not buffer as hex string".to_string())
})?))
}
}
impl Serialize for Buffer {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where
S: Serializer,
{
serializer.serialize_str(&*format!(
"{}",
hex::encode(self.as_bytes(self.size as usize))
))
}
}
impl<'de> Deserialize<'de> for Buffer {
fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(BufferVisitor)
}
}
impl BufferNode {
pub fn new_empty() -> Self {
BufferNode::Leaf(vec![0u8; 32])
}
pub fn _leaf_from_bytes(v: &[u8]) -> Self {
assert!(v.len() <= 32);
let mut buf = vec![0u8; 32];
for i in 0..v.len() {
buf[i] = v[i]
}
BufferNode::Leaf(buf)
}
fn _minimal_internal_from_bytes(v: &[u8]) -> Self {
assert!(v.len() > 32);
let (height, size) = _levels_needed(v.len() as u128);
BufferNode::_internal_from_bytes(height, size, v)
}
fn _internal_from_bytes(height: usize, capacity: u128, v: &[u8]) -> Self {
if height == 1 {
BufferNode::_leaf_from_bytes(v)
} else if v.len() == 0 {
BufferNode::new_empty_internal(height, capacity)
} else if v.len() as u128 <= capacity / 2 {
let left = Arc::new(BufferNode::_internal_from_bytes(
height - 1,
capacity / 2,
v,
));
let right = Arc::new(BufferNode::new_empty_internal(height - 1, capacity / 2));
BufferNode::Internal(BufferInternal {
height,
capacity,
left: left.clone(),
right: right.clone(),
hash_val: {
let mut b = left.hash().to_bytes_be();
b.extend(right.hash().to_bytes_be());
Uint256::from_bytes(&keccak256(&b))
},
})
} else {
let mid = (capacity / 2) as usize;
let left = Arc::new(BufferNode::_internal_from_bytes(
height - 1,
capacity / 2,
&v[0..mid],
));
let right = Arc::new(BufferNode::_internal_from_bytes(
height - 1,
capacity / 2,
&v[mid..],
));
BufferNode::Internal(BufferInternal {
height,
capacity,
left: left.clone(),
right: right.clone(),
hash_val: {
let mut b = left.hash().to_bytes_be();
b.extend(right.hash().to_bytes_be());
Uint256::from_bytes(&keccak256(&b))
},
})
}
}
fn new_empty_internal(height: usize, capacity: u128) -> Self {
let child = Arc::new(if height == 1 {
BufferNode::new_empty()
} else {
BufferNode::new_empty_internal(height - 1, capacity / 2)
});
BufferNode::Internal(BufferInternal {
height,
capacity,
left: child.clone(),
right: child.clone(),
hash_val: {
let a = child.hash().to_bytes_be();
let mut b = a.clone();
b.extend(a);
Uint256::from_bytes(&keccak256(&b))
},
})
}
fn hash(&self) -> Uint256 {
match self {
BufferNode::Leaf(b) => Uint256::from_bytes(&keccak256(&b[..])),
BufferNode::Internal(x) => x.hash_val.clone(),
}
}
fn hex_encode(&self, size: usize) -> String {
match self {
BufferNode::Leaf(b) => hex::encode(b)[0..(2 * size)].to_string(),
BufferNode::Internal(node) => node.hex_encode(size),
}
}
fn read_byte(&self, offset: u128) -> u8 {
match self {
BufferNode::Leaf(b) => b[offset as usize],
BufferNode::Internal(node) => node.read_byte(offset),
}
}
fn set_byte(&self, offset: u128, val: u8) -> Self {
match self {
BufferNode::Leaf(b) => {
if (offset < 32) {
let mut bb = b.clone();
bb[offset as usize] = val;
BufferNode::Leaf(bb)
} else {
BufferNode::Internal(
BufferInternal::grow_from_leaf(self.clone()).set_byte(offset, val),
)
}
}
BufferNode::Internal(node) => BufferNode::Internal(node.set_byte(offset, val)),
}
}
}
impl BufferInternal {
fn new(height: usize, capacity: u128, left: BufferNode, right: BufferNode) -> Self {
BufferInternal {
height,
capacity,
left: Arc::new(left.clone()),
right: Arc::new(right.clone()),
hash_val: {
let mut b = left.hash().to_bytes_be();
b.extend(right.hash().to_bytes_be());
Uint256::from_bytes(&keccak256(&b))
},
}
}
fn grow(&self) -> Self {
BufferInternal::new(
self.height + 1,
self.capacity * 2,
BufferNode::Internal(self.clone()),
BufferNode::new_empty_internal(self.height, self.capacity),
)
}
fn grow_from_leaf(leaf: BufferNode) -> Self {
BufferInternal::new(2, 2 * 32, leaf, BufferNode::new_empty())
}
fn hex_encode(&self, size: usize) -> String {
let half_capacity = (self.capacity / 2) as usize;
if size == 0 {
"".to_string()
} else if size <= half_capacity {
self.left.hex_encode(size)
} else {
let mut left_str = self.left.hex_encode(half_capacity);
let right_str = self.right.hex_encode(size - half_capacity);
left_str.push_str(&right_str);
left_str
}
}
fn read_byte(&self, offset: u128) -> u8 {
if offset < self.capacity / 2 {
self.left.read_byte(offset)
} else {
self.right.read_byte(offset - self.capacity / 2)
}
}
fn set_byte(&self, offset: u128, val: u8) -> BufferInternal {
if offset < self.capacity / 2 {
BufferInternal::new(
self.height,
self.capacity,
self.left.set_byte(offset, val),
(*self.right).clone(),
)
} else if offset < self.capacity {
BufferInternal::new(
self.height,
self.capacity,
(*self.left).clone(),
self.right.set_byte(offset - self.capacity / 2, val),
)
} else {
self.grow().set_byte(offset, val)
}
}
}
fn _levels_needed(x: u128) -> (usize, u128) {
let mut height = 1;
let mut size = 32u128;
while (size < x) {
height = height + 1;
size = size * 2;
}
(height, size)
}
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub enum Value {
Int(Uint256),
Tuple(Arc<Vec<Value>>),
CodePoint(CodePt),
Label(Label),
Buffer(Buffer),
}
impl Value {
/// Returns a value containing no data, a zero sized tuple.
pub fn none() -> Self {
Value::Tuple(Arc::new(vec![]))
}
/// Creates a single tuple `Value` from a `Vec<Value>`
pub fn new_tuple(v: Vec<Value>) -> Self {
Value::Tuple(Arc::new(v))
}
pub fn new_buffer(v: Vec<u8>) -> Self {
Value::Buffer(Buffer::from_bytes(v))
}
pub fn copy_buffer(v: Buffer) -> Self {
Value::Buffer(v)
}
pub fn upload(&self, u: &mut CodeUploader) {
match self {
Value::Int(ui) => {
u.push_byte(0u8); // type code for uint
u.push_bytes(&ui.rlp_encode());
}
Value::Tuple(tup) => {
u.push_byte((10 + tup.len()) as u8);
for subval in &**tup {
subval.upload(u);
}
}
Value::CodePoint(cp) => {
cp.upload(u);
}
Value::Buffer(buf) => {
if buf.size == 0 {
u.push_byte(2u8);
} else {
u.push_byte(3u8);
let size = buf.max_size() as usize;
u.push_bytes(&Uint256::from_usize(size).rlp_encode());
u.push_bytes(&buf.as_bytes(size));
}
}
_ => {
println!("unable to upload value: {}", self);
panic!();
} // other types should never be encountered here
}
}
pub fn is_none(&self) -> bool {
self == &Value::none()
}
pub fn type_insn_result(&self) -> usize {
match self {
Value::Int(_) => 0,
Value::CodePoint(_) => 1,
Value::Tuple(_) => 3,
Value::Buffer(_) => 4,
Value::Label(_) => {
panic!("tried to run type instruction on a label");
}
}
}
pub fn replace_labels(self, label_map: &HashMap<Label, CodePt>) -> Result<Self, Label> {
match self {
Value::Int(_) => Ok(self),
Value::CodePoint(_) => Ok(self),
Value::Buffer(_) => Ok(self),
Value::Label(label) => {
let maybe_pc = label_map.get(&label);
match maybe_pc {
Some(pc) => Ok(Value::CodePoint(*pc)),
None => Err(label),
}
}
Value::Tuple(tup) => {
let mut new_vec = Vec::new();
for v in tup.iter() {
let val = v.clone();
new_vec.push(val.replace_labels(label_map)?);
}
Ok(Value::new_tuple(new_vec))
}
}
}
pub fn replace_last_none(&self, val: &Value) -> Self {
if self.is_none() {
return val.clone();
}
if let Value::Tuple(tup) = self {
let tlen = tup.len();
let mut mut_tup = tup.clone();
let new_tup = Arc::<Vec<Value>>::make_mut(&mut mut_tup);
new_tup[tlen - 1] = new_tup[tlen - 1].replace_last_none(val);
Value::new_tuple(new_tup.to_vec())
} else {
panic!();
}
}
pub fn avm_hash(&self) -> Value {
//BUGBUG: should do same hash as AVM
match self {
Value::Int(ui) => Value::Int(ui.avm_hash()),
Value::Buffer(buf) => Value::Int(buf.avm_hash()),
Value::Tuple(v) => {
// According to the C++ emulator, the AVM hash of a tuple is
// H(3 || H(uint8(tlen) || A(tuple[0]) || ... || A(tuple[tlen-1])) || uint256(recursiveSize))
// where A is an AVM hash & H is keccack
let total_size = 1 + v.len(); // we assume tuples only contain ints for now
let outer_size = v.len() as u8;
let mut all_bytes = vec![3u8];
let mut content_bytes = vec![outer_size];
for val in v.to_vec() {
if let Value::Int(ui) = val.avm_hash() {
let child_hash = Uint256::avm_hash(&ui);
content_bytes.extend(child_hash.to_bytes_be());
} else {
panic!("Invalid value type from hash");
}
}
let content_hash = keccak256(&content_bytes);
all_bytes.extend(content_hash);
all_bytes.extend(Uint256::from_usize(total_size).to_bytes_be());
let hash = Uint256::from_bytes(&keccak256(&all_bytes));
Value::Int(hash)
}
Value::CodePoint(cp) => Value::avm_hash2(&Value::Int(Uint256::one()), &cp.avm_hash()),
Value::Label(label) => {
Value::avm_hash2(&Value::Int(Uint256::from_usize(2)), &label.avm_hash())
}
}
}
pub fn avm_hash2(v1: &Self, v2: &Self) -> Value {
if let Value::Int(ui) = v1 {
if let Value::Int(ui2) = v2 {
let mut buf = ui.to_bytes_be();
buf.extend(ui2.to_bytes_be());
Value::Int(Uint256::from_bytes(&keccak256(&buf)))
} else {
panic!();
}
} else {
panic!();
}
}
pub fn get_uniques(&self) -> Vec<LabelId> {
let mut uniques = vec![];
match self {
Value::Label(Label::Func(id) | Label::Closure(id)) => uniques.push(*id),
Value::Tuple(tup) => {
for child in &**tup {
uniques.extend(child.get_uniques());
}
}
_ => {}
}
uniques
}
/// Surgically replace value potentially nested within a tuple with others.
/// |with| should return true when a value is to be replaced.
/// |when| makes the value substitution.
/// The application order allows a substituted value to itself be replaced.
pub fn replace<With, When>(self, with: &mut With, when: &mut When) -> Self
where
With: FnMut(Value) -> Value,
When: FnMut(&Value) -> bool,
{
let mut current = match when(&self) {
true => with(self),
false => self,
};
if let Value::Tuple(ref mut contents) = current {
let items = contents
.to_vec()
.into_iter()
.map(|val| val.replace(with, when))
.collect();
*contents = Arc::new(items);
}
current
}
/// Surgically replace types potentially nested within others.
/// |via| makes the type substitution.
pub fn replace2<Via>(&mut self, via: &mut Via)
where
Via: FnMut(&mut Self),
{
match self {
Self::Tuple(ref mut contents) => {
let mut nested = contents.to_vec();
nested.iter_mut().for_each(|val| val.replace2(via));
*contents = Arc::new(nested);
}
_ => {}
}
via(self);
}
pub fn pretty_print(&self, highlight: &str) -> String {
match self {
Value::Int(i) => Color::color(highlight, i),
Value::CodePoint(pc) => match pc {
CodePt::Null => Color::maroon("Err"),
_ => Color::color(highlight, pc),
},
Value::Label(label) => match label {
Label::Func(id) => Color::color(highlight, format!("func_{}", id % 256)),
Label::Closure(id) => Color::color(highlight, format!("λ_{}", id % 256)),
Label::Anon(id) => Color::color(highlight, format!("label_{}", id % 256)),
_ => Color::color(highlight, label),
},
Value::Buffer(buf) => {
let text = String::from_utf8_lossy(&hex::decode(buf.hex_encode()).unwrap())
.chars()
.filter(|c| !c.is_ascii_control())
.take(100)
.collect::<String>();
Color::lavender(format!("\"{}\"", text))
}
Value::Tuple(tup) => match tup.is_empty() {
true => Color::grey("_"),
false => {
let mut s = Color::color(highlight, "(");
for (i, value) in tup.iter().enumerate() {
let child = value.pretty_print(highlight);
match i == 0 {
true => {
s = format!("{}{}", s, child);
}
false => {
s = format!("{}{}{}", s, Color::grey(", "), child);
}
}
}
format!("{}{}", s, Color::color(highlight, ")"))
}
},
}
}
}
impl Default for Value {
fn default() -> Self {
return Value::none();
}
}
impl From<usize> for Value {
fn from(v: usize) -> Self {
Self::Int(Uint256::from_usize(v))
}
}
impl From<u8> for Value {
fn from(v: u8) -> Self {
Self::Int(Uint256::from_usize(v.into()))
}
}
impl From<i32> for Value {
fn from(v: i32) -> Self {
match v < 0 {
true => panic!("tried to make mavm::Value from {}", v),
false => Self::Int(Uint256::from_usize(v as usize)),
}
}
}
impl From<u64> for Value {
fn from(v: u64) -> Self {
Self::Int(Uint256::from_u64(v))
}
}
impl From<&str> for Value {
fn from(v: &str) -> Self {
Self::Buffer(Buffer::from_bytes(v.as_bytes().to_vec()))
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Value::Int(i) => i.fmt(f),
Value::Buffer(buf) => write!(f, "Buffer({})", buf.hex_encode()),
Value::CodePoint(pc) => write!(f, "CodePoint({})", pc),
Value::Label(label) => write!(f, "Label({})", label),
Value::Tuple(tup) => {
if tup.is_empty() {
write!(f, "_")
} else {
let mut s = "Tuple(".to_owned();
for (i, v) in tup.iter().enumerate() {
if i == 0 {
s = format!("{}{}", s, v);
} else {
s = format!("{}, {}", s, v);
}
}
write!(f, "{})", s)
}
}
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Eq, PartialEq, Hash)]
pub enum Opcode {
MakeFrame(FrameSize, bool, bool), // make a func frame: space, returns, prebuilt
GetLocal(SlotNum), // get a local variable within a func frame
SetLocal(SlotNum), // set a local variable within a func frame
MoveLocal(SlotNum, SlotNum), // move into arg1 arg2 within a func frame
DropLocal(SlotNum), // annotate a point after which the local is never used again
ReserveCapture(SlotNum, StringId), // annotate where a capture should be placed within a func frame
Capture(LabelId, StringId), // annotate which value to retrieve for closure packing
MakeClosure(LabelId), // create a callable closure frame
FuncCall(FuncProperties), // make a function call: nargs, nouts, and view/write-props
TupleGet(usize, usize), // args are offset and size for the anysize_tuple
TupleSet(usize, usize), // args are offset and size for the anysize_tuple
GetGlobalVar(usize), // gets a global variable at a global index