-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathplutus.rs
2602 lines (2355 loc) · 115 KB
/
plutus.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
use std::hash::Hash;
use super::*;
use std::io::{BufRead, Seek, Write};
use linked_hash_map::LinkedHashMap;
use core::hash::Hasher;
// This library was code-generated using an experimental CDDL to rust tool:
// https://github.com/Emurgo/cddl-codegen
use cbor_event::{
self,
de::Deserializer,
se::{Serialize, Serializer},
};
use schemars::JsonSchema;
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct PlutusScript {
bytes: Vec<u8>,
language: LanguageKind,
}
to_from_bytes!(PlutusScript);
#[wasm_bindgen]
impl PlutusScript {
/**
* Creates a new Plutus script from the RAW bytes of the compiled script.
* This does NOT include any CBOR encoding around these bytes (e.g. from "cborBytes" in cardano-cli)
* If you creating this from those you should use PlutusScript::from_bytes() instead.
*/
pub fn new(bytes: Vec<u8>) -> PlutusScript {
Self::new_with_version(bytes, &Language::new_plutus_v1())
}
/**
* Creates a new Plutus script from the RAW bytes of the compiled script.
* This does NOT include any CBOR encoding around these bytes (e.g. from "cborBytes" in cardano-cli)
* If you creating this from those you should use PlutusScript::from_bytes() instead.
*/
pub fn new_v2(bytes: Vec<u8>) -> PlutusScript {
Self::new_with_version(bytes, &Language::new_plutus_v2())
}
/**
* Creates a new Plutus script from the RAW bytes of the compiled script.
* This does NOT include any CBOR encoding around these bytes (e.g. from "cborBytes" in cardano-cli)
* If you creating this from those you should use PlutusScript::from_bytes() instead.
*/
pub fn new_with_version(bytes: Vec<u8>, language: &Language) -> PlutusScript {
Self {
bytes,
language: language.0.clone(),
}
}
/**
* The raw bytes of this compiled Plutus script.
* If you need "cborBytes" for cardano-cli use PlutusScript::to_bytes() instead.
*/
pub fn bytes(&self) -> Vec<u8> {
self.bytes.clone()
}
/// Same as `.from_bytes` but will consider the script as requiring the Plutus Language V2
pub fn from_bytes_v2(bytes: Vec<u8>) -> Result<PlutusScript, JsError> {
Self::from_bytes_with_version(bytes, &Language::new_plutus_v2())
}
/// Same as `.from_bytes` but will consider the script as requiring the specified language version
pub fn from_bytes_with_version(
bytes: Vec<u8>,
language: &Language,
) -> Result<PlutusScript, JsError> {
Ok(Self::new_with_version(
Self::from_bytes(bytes)?.bytes,
language,
))
}
/// Same as .from_hex but will consider the script as requiring the specified language version
pub fn from_hex_with_version(
hex_str: &str,
language: &Language,
) -> Result<PlutusScript, JsError> {
Ok(Self::new_with_version(
Self::from_hex(hex_str)?.bytes,
language,
))
}
pub fn hash(&self) -> ScriptHash {
let mut bytes = Vec::with_capacity(self.bytes.len() + 1);
// https://github.com/input-output-hk/cardano-ledger/blob/master/eras/babbage/test-suite/cddl-files/babbage.cddl#L413
bytes.extend_from_slice(&vec![self.script_namespace() as u8]);
bytes.extend_from_slice(&self.bytes);
ScriptHash::from(blake2b224(bytes.as_ref()))
}
pub fn language_version(&self) -> Language {
Language(self.language.clone())
}
pub(crate) fn script_namespace(&self) -> ScriptHashNamespace {
match self.language {
LanguageKind::PlutusV1 => ScriptHashNamespace::PlutusScript,
LanguageKind::PlutusV2 => ScriptHashNamespace::PlutusScriptV2,
}
}
pub(crate) fn clone_as_version(&self, language: &Language) -> PlutusScript {
Self::new_with_version(self.bytes.clone(), language)
}
}
impl serde::Serialize for PlutusScript {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&hex::encode(&self.bytes))
}
}
impl<'de> serde::de::Deserialize<'de> for PlutusScript {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let s = <String as serde::de::Deserialize>::deserialize(deserializer)?;
hex::decode(&s)
.map(|bytes| PlutusScript::new(bytes))
.map_err(|_err| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Str(&s),
&"PlutusScript as hex string e.g. F8AB28C2 (without CBOR bytes tag)",
)
})
}
}
impl JsonSchema for PlutusScript {
fn schema_name() -> String {
String::from("PlutusScript")
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
String::json_schema(gen)
}
fn is_referenceable() -> bool {
String::is_referenceable()
}
}
#[wasm_bindgen]
#[derive(
Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize, JsonSchema,
)]
pub struct PlutusScripts(pub(crate) Vec<PlutusScript>);
impl_to_from!(PlutusScripts);
#[wasm_bindgen]
impl PlutusScripts {
pub fn new() -> Self {
Self(Vec::new())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn get(&self, index: usize) -> PlutusScript {
self.0[index].clone()
}
pub fn add(&mut self, elem: &PlutusScript) {
self.0.push(elem.clone());
}
pub(crate) fn by_version(&self, language: &Language) -> PlutusScripts {
PlutusScripts(
self.0
.iter()
.filter(|s| s.language_version().eq(language))
.map(|s| s.clone())
.collect(),
)
}
pub(crate) fn has_version(&self, language: &Language) -> bool {
self.0.iter().any(|s| s.language_version().eq(language))
}
pub(crate) fn merge(&self, other: &PlutusScripts) -> PlutusScripts {
let mut res = self.clone();
for s in &other.0 {
res.add(s);
}
res
}
pub(crate) fn map_as_version(&self, language: &Language) -> PlutusScripts {
let mut res = PlutusScripts::new();
for s in &self.0 {
res.add(&s.clone_as_version(language));
}
res
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
pub struct ConstrPlutusData {
alternative: BigNum,
data: PlutusList,
}
to_from_bytes!(ConstrPlutusData);
#[wasm_bindgen]
impl ConstrPlutusData {
pub fn alternative(&self) -> BigNum {
self.alternative.clone()
}
pub fn data(&self) -> PlutusList {
self.data.clone()
}
pub fn new(alternative: &BigNum, data: &PlutusList) -> Self {
Self {
alternative: alternative.clone(),
data: data.clone(),
}
}
}
impl ConstrPlutusData {
// see: https://github.com/input-output-hk/plutus/blob/1f31e640e8a258185db01fa899da63f9018c0e85/plutus-core/plutus-core/src/PlutusCore/Data.hs#L61
// We don't directly serialize the alternative in the tag, instead the scheme is:
// - Alternatives 0-6 -> tags 121-127, followed by the arguments in a list
// - Alternatives 7-127 -> tags 1280-1400, followed by the arguments in a list
// - Any alternatives, including those that don't fit in the above -> tag 102 followed by a list containing
// an unsigned integer for the actual alternative, and then the arguments in a (nested!) list.
const GENERAL_FORM_TAG: u64 = 102;
// None -> needs general tag serialization, not compact
fn alternative_to_compact_cbor_tag(alt: u64) -> Option<u64> {
if alt <= 6 {
Some(121 + alt)
} else if alt >= 7 && alt <= 127 {
Some(1280 - 7 + alt)
} else {
None
}
}
// None -> General tag(=102) OR Invalid CBOR tag for this scheme
fn compact_cbor_tag_to_alternative(cbor_tag: u64) -> Option<u64> {
if cbor_tag >= 121 && cbor_tag <= 127 {
Some(cbor_tag - 121)
} else if cbor_tag >= 1280 && cbor_tag <= 1400 {
Some(cbor_tag - 1280 + 7)
} else {
None
}
}
}
#[wasm_bindgen]
#[derive(
Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize, JsonSchema,
)]
pub struct CostModel(Vec<Int>);
impl_to_from!(CostModel);
#[wasm_bindgen]
impl CostModel {
/// Creates a new CostModels instance of an unrestricted length
pub fn new() -> Self {
Self(Vec::new())
}
/// Sets the cost at the specified index to the specified value.
/// In case the operation index is larger than the previous largest used index,
/// it will fill any inbetween indexes with zeroes
pub fn set(&mut self, operation: usize, cost: &Int) -> Result<Int, JsError> {
let len = self.0.len();
let idx = operation.clone();
if idx >= len {
for _ in 0..(idx - len + 1) {
self.0.push(Int::new_i32(0));
}
}
let old = self.0[idx].clone();
self.0[idx] = cost.clone();
Ok(old)
}
pub fn get(&self, operation: usize) -> Result<Int, JsError> {
let max = self.0.len();
if operation >= max {
return Err(JsError::from_str(&format!(
"CostModel operation {} out of bounds. Max is {}",
operation, max
)));
}
Ok(self.0[operation].clone())
}
pub fn len(&self) -> usize {
self.0.len()
}
}
impl From<Vec<i128>> for CostModel {
fn from(values: Vec<i128>) -> Self {
CostModel(values.iter().map(|x| Int(*x)).collect())
}
}
#[wasm_bindgen]
#[derive(
Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize, JsonSchema,
)]
pub struct Costmdls(std::collections::BTreeMap<Language, CostModel>);
impl_to_from!(Costmdls);
#[wasm_bindgen]
impl Costmdls {
pub fn new() -> Self {
Self(std::collections::BTreeMap::new())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn insert(&mut self, key: &Language, value: &CostModel) -> Option<CostModel> {
self.0.insert(key.clone(), value.clone())
}
pub fn get(&self, key: &Language) -> Option<CostModel> {
self.0.get(key).map(|v| v.clone())
}
pub fn keys(&self) -> Languages {
Languages(self.0.iter().map(|(k, _v)| k.clone()).collect::<Vec<_>>())
}
pub(crate) fn language_views_encoding(&self) -> Vec<u8> {
let mut serializer = Serializer::new_vec();
fn key_len(l: &Language) -> usize {
if l.kind() == LanguageKind::PlutusV1 {
let mut serializer = Serializer::new_vec();
serializer.write_bytes(l.to_bytes()).unwrap();
return serializer.finalize().len();
}
l.to_bytes().len()
}
let mut keys: Vec<Language> = self.0.iter().map(|(k, _v)| k.clone()).collect();
// keys must be in canonical ordering first
keys.sort_by(|lhs, rhs| match key_len(lhs).cmp(&key_len(rhs)) {
std::cmp::Ordering::Equal => lhs.cmp(&rhs),
len_order => len_order,
});
serializer
.write_map(cbor_event::Len::Len(self.0.len() as u64))
.unwrap();
for key in keys.iter() {
if key.kind() == LanguageKind::PlutusV1 {
serializer.write_bytes(key.to_bytes()).unwrap();
let cost_model = self.0.get(&key).unwrap();
// Due to a bug in the cardano-node input-output-hk/cardano-ledger-specs/issues/2512
// we must use indefinite length serialization in this inner bytestring to match it
let mut cost_model_serializer = Serializer::new_vec();
cost_model_serializer
.write_array(cbor_event::Len::Indefinite)
.unwrap();
for cost in &cost_model.0 {
cost.serialize(&mut cost_model_serializer).unwrap();
}
cost_model_serializer
.write_special(cbor_event::Special::Break)
.unwrap();
serializer
.write_bytes(cost_model_serializer.finalize())
.unwrap();
} else {
serializer.serialize(key).unwrap();
serializer.serialize(self.0.get(&key).unwrap()).unwrap();
}
}
serializer.finalize()
}
pub fn retain_language_versions(&self, languages: &Languages) -> Costmdls {
let mut result = Costmdls::new();
for lang in &languages.0 {
match self.get(&lang) {
Some(costmodel) => { result.insert(&lang, &costmodel); },
_ => {}
}
}
result
}
}
#[wasm_bindgen]
#[derive(
Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize, JsonSchema,
)]
pub struct ExUnitPrices {
mem_price: SubCoin,
step_price: SubCoin,
}
impl_to_from!(ExUnitPrices);
#[wasm_bindgen]
impl ExUnitPrices {
pub fn mem_price(&self) -> SubCoin {
self.mem_price.clone()
}
pub fn step_price(&self) -> SubCoin {
self.step_price.clone()
}
pub fn new(mem_price: &SubCoin, step_price: &SubCoin) -> Self {
Self {
mem_price: mem_price.clone(),
step_price: step_price.clone(),
}
}
}
#[wasm_bindgen]
#[derive(
Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize, JsonSchema,
)]
pub struct ExUnits {
mem: BigNum,
steps: BigNum,
}
impl_to_from!(ExUnits);
#[wasm_bindgen]
impl ExUnits {
pub fn mem(&self) -> BigNum {
self.mem.clone()
}
pub fn steps(&self) -> BigNum {
self.steps.clone()
}
pub fn new(mem: &BigNum, steps: &BigNum) -> Self {
Self {
mem: mem.clone(),
steps: steps.clone(),
}
}
}
#[wasm_bindgen]
#[derive(
Clone,
Copy,
Debug,
Eq,
Ord,
PartialEq,
PartialOrd,
serde::Serialize,
serde::Deserialize,
JsonSchema,
)]
pub enum LanguageKind {
PlutusV1 = 0,
PlutusV2 = 1,
}
impl LanguageKind {
fn from_u64(x: u64) -> Option<LanguageKind> {
match x {
0 => Some(LanguageKind::PlutusV1),
1 => Some(LanguageKind::PlutusV2),
_ => None,
}
}
}
#[wasm_bindgen]
#[derive(
Clone,
Copy,
Debug,
Eq,
Ord,
PartialEq,
PartialOrd,
serde::Serialize,
serde::Deserialize,
JsonSchema,
)]
pub struct Language(LanguageKind);
impl_to_from!(Language);
#[wasm_bindgen]
impl Language {
pub fn new_plutus_v1() -> Self {
Self(LanguageKind::PlutusV1)
}
pub fn new_plutus_v2() -> Self {
Self(LanguageKind::PlutusV2)
}
pub fn kind(&self) -> LanguageKind {
self.0.clone()
}
}
#[wasm_bindgen]
#[derive(
Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize, JsonSchema,
)]
pub struct Languages(pub(crate) Vec<Language>);
#[wasm_bindgen]
impl Languages {
pub fn new() -> Self {
Self(Vec::new())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn get(&self, index: usize) -> Language {
self.0[index]
}
pub fn add(&mut self, elem: Language) {
self.0.push(elem);
}
pub fn list() -> Languages {
Languages(vec![Language::new_plutus_v1(), Language::new_plutus_v2()])
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
pub struct PlutusMap(LinkedHashMap<PlutusData, PlutusData>);
to_from_bytes!(PlutusMap);
#[wasm_bindgen]
impl PlutusMap {
pub fn new() -> Self {
Self(LinkedHashMap::new())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn insert(&mut self, key: &PlutusData, value: &PlutusData) -> Option<PlutusData> {
self.0.insert(key.clone(), value.clone())
}
pub fn get(&self, key: &PlutusData) -> Option<PlutusData> {
self.0.get(key).map(|v| v.clone())
}
pub fn keys(&self) -> PlutusList {
PlutusList {
elems: self.0.iter().map(|(k, _v)| k.clone()).collect::<Vec<_>>(),
definite_encoding: None,
}
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum PlutusDataKind {
ConstrPlutusData,
Map,
List,
Integer,
Bytes,
}
#[derive(
Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
pub enum PlutusDataEnum {
ConstrPlutusData(ConstrPlutusData),
Map(PlutusMap),
List(PlutusList),
Integer(BigInt),
Bytes(Vec<u8>),
}
#[wasm_bindgen]
#[derive(Clone, Debug, Ord, PartialOrd)]
pub struct PlutusData {
datum: PlutusDataEnum,
// We should always preserve the original datums when deserialized as this is NOT canonicized
// before computing datum hashes. So this field stores the original bytes to re-use.
original_bytes: Option<Vec<u8>>,
}
impl std::cmp::PartialEq<Self> for PlutusData {
fn eq(&self, other: &Self) -> bool {
self.datum.eq(&other.datum)
}
}
impl Hash for PlutusData {
fn hash<H: Hasher>(&self, state: &mut H) {
self.datum.hash(state)
}
}
impl std::cmp::Eq for PlutusData {}
to_from_bytes!(PlutusData);
#[wasm_bindgen]
impl PlutusData {
pub fn new_constr_plutus_data(constr_plutus_data: &ConstrPlutusData) -> Self {
Self {
datum: PlutusDataEnum::ConstrPlutusData(constr_plutus_data.clone()),
original_bytes: None,
}
}
/// Same as `.new_constr_plutus_data` but creates constr with empty data list
pub fn new_empty_constr_plutus_data(alternative: &BigNum) -> Self {
Self::new_constr_plutus_data(&ConstrPlutusData::new(alternative, &PlutusList::new()))
}
pub fn new_single_value_constr_plutus_data(alternative: &BigNum, plutus_data: &PlutusData) -> Self {
let mut list = PlutusList::new();
list.add(plutus_data);
Self::new_constr_plutus_data(&ConstrPlutusData::new(alternative, &list))
}
pub fn new_map(map: &PlutusMap) -> Self {
Self {
datum: PlutusDataEnum::Map(map.clone()),
original_bytes: None,
}
}
pub fn new_list(list: &PlutusList) -> Self {
Self {
datum: PlutusDataEnum::List(list.clone()),
original_bytes: None,
}
}
pub fn new_integer(integer: &BigInt) -> Self {
Self {
datum: PlutusDataEnum::Integer(integer.clone()),
original_bytes: None,
}
}
pub fn new_bytes(bytes: Vec<u8>) -> Self {
Self {
datum: PlutusDataEnum::Bytes(bytes),
original_bytes: None,
}
}
pub fn kind(&self) -> PlutusDataKind {
match &self.datum {
PlutusDataEnum::ConstrPlutusData(_) => PlutusDataKind::ConstrPlutusData,
PlutusDataEnum::Map(_) => PlutusDataKind::Map,
PlutusDataEnum::List(_) => PlutusDataKind::List,
PlutusDataEnum::Integer(_) => PlutusDataKind::Integer,
PlutusDataEnum::Bytes(_) => PlutusDataKind::Bytes,
}
}
pub fn as_constr_plutus_data(&self) -> Option<ConstrPlutusData> {
match &self.datum {
PlutusDataEnum::ConstrPlutusData(x) => Some(x.clone()),
_ => None,
}
}
pub fn as_map(&self) -> Option<PlutusMap> {
match &self.datum {
PlutusDataEnum::Map(x) => Some(x.clone()),
_ => None,
}
}
pub fn as_list(&self) -> Option<PlutusList> {
match &self.datum {
PlutusDataEnum::List(x) => Some(x.clone()),
_ => None,
}
}
pub fn as_integer(&self) -> Option<BigInt> {
match &self.datum {
PlutusDataEnum::Integer(x) => Some(x.clone()),
_ => None,
}
}
pub fn as_bytes(&self) -> Option<Vec<u8>> {
match &self.datum {
PlutusDataEnum::Bytes(x) => Some(x.clone()),
_ => None,
}
}
pub fn to_json(&self, schema: PlutusDatumSchema) -> Result<String, JsError> {
decode_plutus_datum_to_json_str(self, schema)
}
pub fn from_json(json: &str, schema: PlutusDatumSchema) -> Result<PlutusData, JsError> {
encode_json_str_to_plutus_datum(json, schema)
}
pub fn from_address(address: &Address) -> Result<PlutusData, JsError> {
let payment_cred = match &address.0 {
AddrType::Base(addr) => Ok(addr.payment_cred()),
AddrType::Enterprise(addr) => Ok(addr.payment_cred()),
AddrType::Ptr(addr) => Ok(addr.payment_cred()),
AddrType::Reward(addr) => Ok(addr.payment_cred()),
AddrType::Byron(_) =>
Err(JsError::from_str("Cannot convert Byron address to PlutusData")),
}?;
let staking_data = match &address.0 {
AddrType::Base(addr) => {
let staking_bytes_data =
PlutusData::from_stake_credential(&addr.stake_cred())?;
Some(PlutusData::new_single_value_constr_plutus_data(
&BigNum::from(0u32),
&staking_bytes_data,
))
}
_ => None,
};
let pointer_data = match &address.0 {
AddrType::Ptr(addr) =>
Some(PlutusData::from_pointer(&addr.stake_pointer())?),
_ => None,
};
let payment_data = PlutusData::from_stake_credential(&payment_cred)?;
let staking_optional_data = match (staking_data, pointer_data) {
(Some(_), Some(_)) =>
Err(JsError::from_str("Address can't have both staking and pointer data")),
(Some(staking_data), None) => Ok(Some(staking_data)),
(None, Some(pointer_data)) => Ok(Some(pointer_data)),
(None, None) => Ok(None)
}?;
let mut data_list = PlutusList::new();
data_list.add(&payment_data);
if let Some(staking_optional_data) = staking_optional_data {
data_list.add(
&PlutusData::new_single_value_constr_plutus_data(
&BigNum::from(0u32), &staking_optional_data));
} else {
data_list.add(&PlutusData::new_empty_constr_plutus_data(
&BigNum::from(1u32)));
}
Ok(PlutusData::new_constr_plutus_data(&ConstrPlutusData::new(
&BigNum::from(0u32),
&data_list,
)))
}
fn from_stake_credential(stake_credential: &StakeCredential) -> Result<PlutusData, JsError> {
let (bytes_plutus_data, index) = match &stake_credential.0 {
StakeCredType::Key(key_hash) =>
(PlutusData::new_bytes(key_hash.to_bytes().to_vec()), BigNum::from(0u32)),
StakeCredType::Script(script_hash) =>
(PlutusData::new_bytes(script_hash.to_bytes().to_vec()), BigNum::from(1u32)),
};
Ok(PlutusData::new_single_value_constr_plutus_data(&index, &bytes_plutus_data))
}
fn from_pointer(pointer: &Pointer) -> Result<PlutusData, JsError> {
let mut data_list = PlutusList::new();
data_list.add(&PlutusData::new_integer(&pointer.slot_bignum().into()));
data_list.add(&PlutusData::new_integer(&pointer.tx_index_bignum().into()));
data_list.add(&PlutusData::new_integer(&pointer.cert_index_bignum().into()));
Ok(PlutusData::new_constr_plutus_data(
&ConstrPlutusData::new(&BigNum::from(1u32), &data_list)))
}
}
//TODO: replace this by cardano-node schemas
impl JsonSchema for PlutusData {
fn is_referenceable() -> bool {
String::is_referenceable()
}
fn schema_name() -> String {
String::from("PlutusData")
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
String::json_schema(gen)
}
}
//TODO: need to figure out what schema to use here
impl serde::Serialize for PlutusData {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: serde::Serializer {
let json = decode_plutus_datum_to_json_str(
self,
PlutusDatumSchema::DetailedSchema)
.map_err(|ser_err| serde::ser::Error::custom(&format!("Serialization error: {:?}", ser_err)))?;
serializer.serialize_str(&json)
}
}
impl <'de> serde::de::Deserialize<'de> for PlutusData {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where
D: serde::de::Deserializer<'de> {
let datum_json = <String as serde::Deserialize>::deserialize(deserializer)?;
encode_json_str_to_plutus_datum(&datum_json, PlutusDatumSchema::DetailedSchema)
.map_err(|ser_err| serde::de::Error::custom(&format!("Deserialization error: {:?}", ser_err)))
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Ord, PartialOrd, Hash, serde::Serialize, serde::Deserialize, JsonSchema)]
pub struct PlutusList {
elems: Vec<PlutusData>,
// We should always preserve the original datums when deserialized as this is NOT canonicized
// before computing datum hashes. This field will default to cardano-cli behavior if None
// and will re-use the provided one if deserialized, unless the list is modified.
pub(crate) definite_encoding: Option<bool>,
}
impl<'a> IntoIterator for &'a PlutusList {
type Item = &'a PlutusData;
type IntoIter = std::slice::Iter<'a, PlutusData>;
fn into_iter(self) -> std::slice::Iter<'a, PlutusData> {
self.elems.iter()
}
}
impl std::cmp::PartialEq<Self> for PlutusList {
fn eq(&self, other: &Self) -> bool {
self.elems.eq(&other.elems)
}
}
impl std::cmp::Eq for PlutusList {}
to_from_bytes!(PlutusList);
#[wasm_bindgen]
impl PlutusList {
pub fn new() -> Self {
Self {
elems: Vec::new(),
definite_encoding: None,
}
}
pub fn len(&self) -> usize {
self.elems.len()
}
pub fn get(&self, index: usize) -> PlutusData {
self.elems[index].clone()
}
pub fn add(&mut self, elem: &PlutusData) {
self.elems.push(elem.clone());
self.definite_encoding = None;
}
}
impl From<Vec<PlutusData>> for PlutusList {
fn from(elems: Vec<PlutusData>) -> Self {
Self {
elems,
definite_encoding: None,
}
}
}
#[wasm_bindgen]
#[derive(
Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize, JsonSchema,
)]
pub struct Redeemer {
tag: RedeemerTag,
index: BigNum,
data: PlutusData,
ex_units: ExUnits,
}
impl_to_from!(Redeemer);
#[wasm_bindgen]
impl Redeemer {
pub fn tag(&self) -> RedeemerTag {
self.tag.clone()
}
pub fn index(&self) -> BigNum {
self.index.clone()
}
pub fn data(&self) -> PlutusData {
self.data.clone()
}
pub fn ex_units(&self) -> ExUnits {
self.ex_units.clone()
}
pub fn new(tag: &RedeemerTag, index: &BigNum, data: &PlutusData, ex_units: &ExUnits) -> Self {
Self {
tag: tag.clone(),
index: index.clone(),
data: data.clone(),
ex_units: ex_units.clone(),
}
}
#[allow(dead_code)]
pub(crate) fn clone_with_index(&self, index: &BigNum) -> Self {
Self {
tag: self.tag.clone(),
index: index.clone(),
data: self.data.clone(),
ex_units: self.ex_units.clone(),
}
}
pub(crate) fn clone_with_index_and_tag(&self, index: &BigNum, tag: &RedeemerTag) -> Self {
Self {
tag: tag.clone(),
index: index.clone(),
data: self.data.clone(),
ex_units: self.ex_units.clone(),
}
}
}
#[wasm_bindgen]
#[derive(
Copy,
Clone,
Debug,
Hash,
Eq,
Ord,
PartialEq,
PartialOrd,
serde::Serialize,
serde::Deserialize,
JsonSchema,
)]
pub enum RedeemerTagKind {
Spend,
Mint,
Cert,
Reward,
}
#[wasm_bindgen]
#[derive(
Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize, JsonSchema,
)]
pub struct RedeemerTag(RedeemerTagKind);
impl_to_from!(RedeemerTag);