-
Notifications
You must be signed in to change notification settings - Fork 106
/
cache.rs
1078 lines (974 loc) · 33.8 KB
/
cache.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::collections::BTreeSet;
use std::convert::TryInto;
use std::panic::{catch_unwind, AssertUnwindSafe};
use cosmwasm_std::Checksum;
use cosmwasm_vm::Cache;
use serde::Serialize;
use crate::api::GoApi;
use crate::args::{CACHE_ARG, CHECKSUM_ARG, CONFIG_ARG, WASM_ARG};
use crate::error::{handle_c_error_binary, handle_c_error_default, handle_c_error_ptr, Error};
use crate::handle_vm_panic::handle_vm_panic;
use crate::memory::{ByteSliceView, UnmanagedVector};
use crate::querier::GoQuerier;
use crate::storage::GoStorage;
#[repr(C)]
pub struct cache_t {}
pub fn to_cache(ptr: *mut cache_t) -> Option<&'static mut Cache<GoApi, GoStorage, GoQuerier>> {
if ptr.is_null() {
None
} else {
let c = unsafe { &mut *(ptr as *mut Cache<GoApi, GoStorage, GoQuerier>) };
Some(c)
}
}
#[no_mangle]
pub extern "C" fn init_cache(
config: ByteSliceView,
error_msg: Option<&mut UnmanagedVector>,
) -> *mut cache_t {
let r = catch_unwind(|| do_init_cache(config)).unwrap_or_else(|err| {
handle_vm_panic("do_init_cache", err);
Err(Error::panic())
});
handle_c_error_ptr(r, error_msg) as *mut cache_t
}
fn do_init_cache(config: ByteSliceView) -> Result<*mut Cache<GoApi, GoStorage, GoQuerier>, Error> {
let config =
serde_json::from_slice(config.read().ok_or_else(|| Error::unset_arg(CONFIG_ARG))?)?;
// parse the supported capabilities
let cache = unsafe { Cache::new_with_config(config) }?;
let out = Box::new(cache);
Ok(Box::into_raw(out))
}
#[no_mangle]
pub extern "C" fn store_code(
cache: *mut cache_t,
wasm: ByteSliceView,
checked: bool,
persist: bool,
error_msg: Option<&mut UnmanagedVector>,
) -> UnmanagedVector {
let r = match to_cache(cache) {
Some(c) => catch_unwind(AssertUnwindSafe(move || {
do_store_code(c, wasm, checked, persist)
}))
.unwrap_or_else(|err| {
handle_vm_panic("do_store_code", err);
Err(Error::panic())
}),
None => Err(Error::unset_arg(CACHE_ARG)),
};
let checksum = handle_c_error_binary(r, error_msg);
UnmanagedVector::new(Some(checksum))
}
fn do_store_code(
cache: &mut Cache<GoApi, GoStorage, GoQuerier>,
wasm: ByteSliceView,
checked: bool,
persist: bool,
) -> Result<Checksum, Error> {
let wasm = wasm.read().ok_or_else(|| Error::unset_arg(WASM_ARG))?;
Ok(cache.store_code(wasm, checked, persist)?)
}
#[no_mangle]
pub extern "C" fn remove_wasm(
cache: *mut cache_t,
checksum: ByteSliceView,
error_msg: Option<&mut UnmanagedVector>,
) {
let r = match to_cache(cache) {
Some(c) => catch_unwind(AssertUnwindSafe(move || do_remove_wasm(c, checksum)))
.unwrap_or_else(|err| {
handle_vm_panic("do_remove_wasm", err);
Err(Error::panic())
}),
None => Err(Error::unset_arg(CACHE_ARG)),
};
handle_c_error_default(r, error_msg)
}
fn do_remove_wasm(
cache: &mut Cache<GoApi, GoStorage, GoQuerier>,
checksum: ByteSliceView,
) -> Result<(), Error> {
let checksum: Checksum = checksum
.read()
.ok_or_else(|| Error::unset_arg(CHECKSUM_ARG))?
.try_into()?;
cache.remove_wasm(&checksum)?;
Ok(())
}
#[no_mangle]
pub extern "C" fn load_wasm(
cache: *mut cache_t,
checksum: ByteSliceView,
error_msg: Option<&mut UnmanagedVector>,
) -> UnmanagedVector {
let r = match to_cache(cache) {
Some(c) => catch_unwind(AssertUnwindSafe(move || do_load_wasm(c, checksum)))
.unwrap_or_else(|err| {
handle_vm_panic("do_load_wasm", err);
Err(Error::panic())
}),
None => Err(Error::unset_arg(CACHE_ARG)),
};
let data = handle_c_error_binary(r, error_msg);
UnmanagedVector::new(Some(data))
}
fn do_load_wasm(
cache: &mut Cache<GoApi, GoStorage, GoQuerier>,
checksum: ByteSliceView,
) -> Result<Vec<u8>, Error> {
let checksum: Checksum = checksum
.read()
.ok_or_else(|| Error::unset_arg(CHECKSUM_ARG))?
.try_into()?;
let wasm = cache.load_wasm(&checksum)?;
Ok(wasm)
}
#[no_mangle]
pub extern "C" fn pin(
cache: *mut cache_t,
checksum: ByteSliceView,
error_msg: Option<&mut UnmanagedVector>,
) {
let r = match to_cache(cache) {
Some(c) => {
catch_unwind(AssertUnwindSafe(move || do_pin(c, checksum))).unwrap_or_else(|err| {
handle_vm_panic("do_pin", err);
Err(Error::panic())
})
}
None => Err(Error::unset_arg(CACHE_ARG)),
};
handle_c_error_default(r, error_msg)
}
fn do_pin(
cache: &mut Cache<GoApi, GoStorage, GoQuerier>,
checksum: ByteSliceView,
) -> Result<(), Error> {
let checksum: Checksum = checksum
.read()
.ok_or_else(|| Error::unset_arg(CHECKSUM_ARG))?
.try_into()?;
cache.pin(&checksum)?;
Ok(())
}
#[no_mangle]
pub extern "C" fn unpin(
cache: *mut cache_t,
checksum: ByteSliceView,
error_msg: Option<&mut UnmanagedVector>,
) {
let r = match to_cache(cache) {
Some(c) => {
catch_unwind(AssertUnwindSafe(move || do_unpin(c, checksum))).unwrap_or_else(|err| {
handle_vm_panic("do_unpin", err);
Err(Error::panic())
})
}
None => Err(Error::unset_arg(CACHE_ARG)),
};
handle_c_error_default(r, error_msg)
}
fn do_unpin(
cache: &mut Cache<GoApi, GoStorage, GoQuerier>,
checksum: ByteSliceView,
) -> Result<(), Error> {
let checksum: Checksum = checksum
.read()
.ok_or_else(|| Error::unset_arg(CHECKSUM_ARG))?
.try_into()?;
cache.unpin(&checksum)?;
Ok(())
}
/// The result type of the FFI function analyze_code.
///
/// Please note that the unmanaged vector in `required_capabilities`
/// has to be destroyed exactly once. When calling `analyze_code`
/// from Go this is done via `C.destroy_unmanaged_vector`.
#[repr(C)]
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)]
pub struct AnalysisReport {
/// `true` if and only if all required ibc exports exist as exported functions.
/// This does not guarantee they are functional or even have the correct signatures.
pub has_ibc_entry_points: bool,
/// A UTF-8 encoded comma separated list of all entrypoints that
/// are exported by the contract.
pub entrypoints: UnmanagedVector,
/// An UTF-8 encoded comma separated list of required capabilities.
/// This is never None/nil.
pub required_capabilities: UnmanagedVector,
/// The migrate version of the contract.
/// This is None if the contract does not have a migrate version and the `migrate` entrypoint
/// needs to be called for every migration (if present).
/// If it is `Some(version)`, it only needs to be called if the `version` increased.
pub contract_migrate_version: OptionalU64,
}
impl From<cosmwasm_vm::AnalysisReport> for AnalysisReport {
fn from(report: cosmwasm_vm::AnalysisReport) -> Self {
let cosmwasm_vm::AnalysisReport {
has_ibc_entry_points,
required_capabilities,
entrypoints,
contract_migrate_version,
..
} = report;
let required_capabilities_utf8 = set_to_csv(required_capabilities).into_bytes();
let entrypoints = set_to_csv(entrypoints).into_bytes();
AnalysisReport {
has_ibc_entry_points,
required_capabilities: UnmanagedVector::new(Some(required_capabilities_utf8)),
entrypoints: UnmanagedVector::new(Some(entrypoints)),
contract_migrate_version: contract_migrate_version.into(),
}
}
}
/// A version of `Option<u64>` that can be used safely in FFI.
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct OptionalU64 {
is_some: bool,
value: u64,
}
impl From<Option<u64>> for OptionalU64 {
fn from(opt: Option<u64>) -> Self {
match opt {
None => OptionalU64 {
is_some: false,
value: 0, // value is ignored
},
Some(value) => OptionalU64 {
is_some: true,
value,
},
}
}
}
/// Takes a set of string-like elements and returns a comma-separated list.
/// Since no escaping or quoting is applied to the elements, the caller needs to ensure
/// only simple alphanumeric values are used.
///
/// The order of the output elements is determined by the iteration order of the provided set.
fn set_to_csv(set: BTreeSet<impl AsRef<str>>) -> String {
let list: Vec<&str> = set.iter().map(|e| e.as_ref()).collect();
list.join(",")
}
#[no_mangle]
pub extern "C" fn analyze_code(
cache: *mut cache_t,
checksum: ByteSliceView,
error_msg: Option<&mut UnmanagedVector>,
) -> AnalysisReport {
let r = match to_cache(cache) {
Some(c) => catch_unwind(AssertUnwindSafe(move || do_analyze_code(c, checksum)))
.unwrap_or_else(|err| {
handle_vm_panic("do_analyze_code", err);
Err(Error::panic())
}),
None => Err(Error::unset_arg(CACHE_ARG)),
};
handle_c_error_default(r, error_msg)
}
fn do_analyze_code(
cache: &mut Cache<GoApi, GoStorage, GoQuerier>,
checksum: ByteSliceView,
) -> Result<AnalysisReport, Error> {
let checksum: Checksum = checksum
.read()
.ok_or_else(|| Error::unset_arg(CHECKSUM_ARG))?
.try_into()?;
let report = cache.analyze(&checksum)?;
Ok(report.into())
}
#[repr(C)]
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)]
pub struct Metrics {
pub hits_pinned_memory_cache: u32,
pub hits_memory_cache: u32,
pub hits_fs_cache: u32,
pub misses: u32,
pub elements_pinned_memory_cache: u64,
pub elements_memory_cache: u64,
pub size_pinned_memory_cache: u64,
pub size_memory_cache: u64,
}
impl From<cosmwasm_vm::Metrics> for Metrics {
fn from(report: cosmwasm_vm::Metrics) -> Self {
let cosmwasm_vm::Metrics {
stats:
cosmwasm_vm::Stats {
hits_pinned_memory_cache,
hits_memory_cache,
hits_fs_cache,
misses,
},
elements_pinned_memory_cache,
elements_memory_cache,
size_pinned_memory_cache,
size_memory_cache,
} = report;
Metrics {
hits_pinned_memory_cache,
hits_memory_cache,
hits_fs_cache,
misses,
elements_pinned_memory_cache: elements_pinned_memory_cache
.try_into()
.expect("usize is larger than 64 bit? Really?"),
elements_memory_cache: elements_memory_cache
.try_into()
.expect("usize is larger than 64 bit? Really?"),
size_pinned_memory_cache: size_pinned_memory_cache
.try_into()
.expect("usize is larger than 64 bit? Really?"),
size_memory_cache: size_memory_cache
.try_into()
.expect("usize is larger than 64 bit? Really?"),
}
}
}
#[no_mangle]
pub extern "C" fn get_metrics(
cache: *mut cache_t,
error_msg: Option<&mut UnmanagedVector>,
) -> Metrics {
let r = match to_cache(cache) {
Some(c) => {
catch_unwind(AssertUnwindSafe(move || do_get_metrics(c))).unwrap_or_else(|err| {
handle_vm_panic("do_get_metrics", err);
Err(Error::panic())
})
}
None => Err(Error::unset_arg(CACHE_ARG)),
};
handle_c_error_default(r, error_msg)
}
#[allow(clippy::unnecessary_wraps)] // Keep unused Result for consistent boilerplate for all fn do_*
fn do_get_metrics(cache: &mut Cache<GoApi, GoStorage, GoQuerier>) -> Result<Metrics, Error> {
Ok(cache.metrics().into())
}
#[derive(Serialize)]
struct PerModuleMetrics {
hits: u32,
size: usize,
}
impl From<cosmwasm_vm::PerModuleMetrics> for PerModuleMetrics {
fn from(value: cosmwasm_vm::PerModuleMetrics) -> Self {
Self {
hits: value.hits,
size: value.size,
}
}
}
#[derive(Serialize)]
struct PinnedMetrics {
// TODO: Remove the array usage as soon as `Checksum` has a stable wire format in msgpack
per_module: Vec<([u8; 32], PerModuleMetrics)>,
}
impl From<cosmwasm_vm::PinnedMetrics> for PinnedMetrics {
fn from(value: cosmwasm_vm::PinnedMetrics) -> Self {
Self {
per_module: value
.per_module
.into_iter()
.map(|(checksum, metrics)| (*checksum.as_ref(), metrics.into()))
.collect(),
}
}
}
#[no_mangle]
pub extern "C" fn get_pinned_metrics(
cache: *mut cache_t,
error_msg: Option<&mut UnmanagedVector>,
) -> UnmanagedVector {
let r = match to_cache(cache) {
Some(c) => {
catch_unwind(AssertUnwindSafe(move || do_get_pinned_metrics(c))).unwrap_or_else(|err| {
handle_vm_panic("do_get_pinned_metrics", err);
Err(Error::panic())
})
}
None => Err(Error::unset_arg(CACHE_ARG)),
};
handle_c_error_default(r, error_msg)
}
fn do_get_pinned_metrics(
cache: &mut Cache<GoApi, GoStorage, GoQuerier>,
) -> Result<UnmanagedVector, Error> {
let pinned_metrics = PinnedMetrics::from(cache.pinned_metrics());
let edgerunner = rmp_serde::to_vec(&pinned_metrics)?;
Ok(UnmanagedVector::new(Some(edgerunner)))
}
/// frees a cache reference
///
/// # Safety
///
/// This must be called exactly once for any `*cache_t` returned by `init_cache`
/// and cannot be called on any other pointer.
#[no_mangle]
pub extern "C" fn release_cache(cache: *mut cache_t) {
if !cache.is_null() {
// this will free cache when it goes out of scope
let _ = unsafe { Box::from_raw(cache as *mut Cache<GoApi, GoStorage, GoQuerier>) };
}
}
#[cfg(test)]
mod tests {
use crate::assert_approx_eq;
use super::*;
use cosmwasm_vm::{CacheOptions, Config, Size};
use std::{cmp::Ordering, collections::HashSet, iter::FromIterator, path::PathBuf};
use tempfile::TempDir;
static HACKATOM: &[u8] = include_bytes!("../../testdata/hackatom.wasm");
static IBC_REFLECT: &[u8] = include_bytes!("../../testdata/ibc_reflect.wasm");
#[test]
fn init_cache_and_release_cache_work() {
let dir: String = TempDir::new().unwrap().path().to_str().unwrap().to_owned();
let capabilities = "staking".to_string();
let mut error_msg = UnmanagedVector::default();
let config = Config::new(CacheOptions::new(
dir,
[capabilities],
Size::mebi(512),
Size::mebi(32),
));
let config = serde_json::to_vec(&config).unwrap();
let cache_ptr = init_cache(ByteSliceView::new(config.as_slice()), Some(&mut error_msg));
assert!(error_msg.is_none());
let _ = error_msg.consume();
release_cache(cache_ptr);
}
#[test]
fn init_cache_writes_error() {
let dir: String = String::from("broken\0dir"); // null bytes are valid UTF8 but not allowed in FS paths
let capabilities = "staking".to_string();
let mut error_msg = UnmanagedVector::default();
let config = Config::new(CacheOptions::new(
dir,
[capabilities],
Size::mebi(512),
Size::mebi(32),
));
let config = serde_json::to_vec(&config).unwrap();
let cache_ptr = init_cache(ByteSliceView::new(config.as_slice()), Some(&mut error_msg));
assert!(cache_ptr.is_null());
assert!(error_msg.is_some());
let msg = String::from_utf8(error_msg.consume().unwrap()).unwrap();
assert_eq!(
msg,
"Error calling the VM: Cache error: Error creating state directory"
);
}
#[test]
fn save_wasm_works() {
let dir: String = TempDir::new().unwrap().path().to_str().unwrap().to_owned();
let capabilities = "staking".to_string();
let mut error_msg = UnmanagedVector::default();
let config = Config::new(CacheOptions::new(
dir,
[capabilities],
Size::mebi(512),
Size::mebi(32),
));
let config = serde_json::to_vec(&config).unwrap();
let cache_ptr = init_cache(ByteSliceView::new(config.as_slice()), Some(&mut error_msg));
assert!(error_msg.is_none());
let _ = error_msg.consume();
let mut error_msg = UnmanagedVector::default();
store_code(
cache_ptr,
ByteSliceView::new(HACKATOM),
false,
true,
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
release_cache(cache_ptr);
}
#[test]
fn remove_wasm_works() {
let dir: String = TempDir::new().unwrap().path().to_str().unwrap().to_owned();
let capabilities = "staking".to_string();
let mut error_msg = UnmanagedVector::default();
let config = Config::new(CacheOptions::new(
dir,
[capabilities],
Size::mebi(512),
Size::mebi(32),
));
let config = serde_json::to_vec(&config).unwrap();
let cache_ptr = init_cache(ByteSliceView::new(config.as_slice()), Some(&mut error_msg));
assert!(error_msg.is_none());
let _ = error_msg.consume();
let mut error_msg = UnmanagedVector::default();
let checksum = store_code(
cache_ptr,
ByteSliceView::new(HACKATOM),
false,
true,
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
let checksum = checksum.consume().unwrap_or_default();
// Removing once works
let mut error_msg = UnmanagedVector::default();
remove_wasm(
cache_ptr,
ByteSliceView::new(&checksum),
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
// Removing again fails
let mut error_msg = UnmanagedVector::default();
remove_wasm(
cache_ptr,
ByteSliceView::new(&checksum),
Some(&mut error_msg),
);
let error_msg = error_msg
.consume()
.map(|e| String::from_utf8_lossy(&e).into_owned());
assert_eq!(
error_msg.unwrap(),
"Error calling the VM: Cache error: Wasm file does not exist"
);
release_cache(cache_ptr);
}
#[test]
fn load_wasm_works() {
let dir: String = TempDir::new().unwrap().path().to_str().unwrap().to_owned();
let capabilities = "staking".to_string();
let mut error_msg = UnmanagedVector::default();
let config = Config::new(CacheOptions::new(
dir,
[capabilities],
Size::mebi(512),
Size::mebi(32),
));
let config = serde_json::to_vec(&config).unwrap();
let cache_ptr = init_cache(ByteSliceView::new(config.as_slice()), Some(&mut error_msg));
assert!(error_msg.is_none());
let _ = error_msg.consume();
let mut error_msg = UnmanagedVector::default();
let checksum = store_code(
cache_ptr,
ByteSliceView::new(HACKATOM),
false,
true,
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
let checksum = checksum.consume().unwrap_or_default();
let mut error_msg = UnmanagedVector::default();
let wasm = load_wasm(
cache_ptr,
ByteSliceView::new(&checksum),
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
let wasm = wasm.consume().unwrap_or_default();
assert_eq!(wasm, HACKATOM);
release_cache(cache_ptr);
}
#[test]
fn pin_works() {
let dir: String = TempDir::new().unwrap().path().to_str().unwrap().to_owned();
let capabilities = "staking".to_string();
let mut error_msg = UnmanagedVector::default();
let config = Config::new(CacheOptions::new(
dir,
[capabilities],
Size::mebi(512),
Size::mebi(32),
));
let config = serde_json::to_vec(&config).unwrap();
let cache_ptr = init_cache(ByteSliceView::new(config.as_slice()), Some(&mut error_msg));
assert!(error_msg.is_none());
let _ = error_msg.consume();
let mut error_msg = UnmanagedVector::default();
let checksum = store_code(
cache_ptr,
ByteSliceView::new(HACKATOM),
false,
true,
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
let checksum = checksum.consume().unwrap_or_default();
let mut error_msg = UnmanagedVector::default();
pin(
cache_ptr,
ByteSliceView::new(&checksum),
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
// pinning again has no effect
let mut error_msg = UnmanagedVector::default();
pin(
cache_ptr,
ByteSliceView::new(&checksum),
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
release_cache(cache_ptr);
}
#[test]
fn unpin_works() {
let dir: String = TempDir::new().unwrap().path().to_str().unwrap().to_owned();
let capabilities = "staking".to_string();
let mut error_msg = UnmanagedVector::default();
let config = Config::new(CacheOptions::new(
dir,
[capabilities],
Size::mebi(512),
Size::mebi(32),
));
let config = serde_json::to_vec(&config).unwrap();
let cache_ptr = init_cache(ByteSliceView::new(config.as_slice()), Some(&mut error_msg));
assert!(error_msg.is_none());
let _ = error_msg.consume();
let mut error_msg = UnmanagedVector::default();
let checksum = store_code(
cache_ptr,
ByteSliceView::new(HACKATOM),
false,
true,
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
let checksum = checksum.consume().unwrap_or_default();
let mut error_msg = UnmanagedVector::default();
pin(
cache_ptr,
ByteSliceView::new(&checksum),
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
let mut error_msg = UnmanagedVector::default();
unpin(
cache_ptr,
ByteSliceView::new(&checksum),
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
// Unpinning again has no effect
let mut error_msg = UnmanagedVector::default();
unpin(
cache_ptr,
ByteSliceView::new(&checksum),
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
release_cache(cache_ptr);
}
#[test]
fn analyze_code_works() {
let dir: String = TempDir::new().unwrap().path().to_str().unwrap().to_owned();
let capabilities = ["staking", "stargate", "iterator"].map(|c| c.to_string());
let mut error_msg = UnmanagedVector::default();
let config = Config::new(CacheOptions::new(
dir,
capabilities,
Size::mebi(512),
Size::mebi(32),
));
let config = serde_json::to_vec(&config).unwrap();
let cache_ptr = init_cache(ByteSliceView::new(config.as_slice()), Some(&mut error_msg));
assert!(error_msg.is_none());
let _ = error_msg.consume();
let mut error_msg = UnmanagedVector::default();
let checksum_hackatom = store_code(
cache_ptr,
ByteSliceView::new(HACKATOM),
false,
true,
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
let checksum_hackatom = checksum_hackatom.consume().unwrap_or_default();
let mut error_msg = UnmanagedVector::default();
let checksum_ibc_reflect = store_code(
cache_ptr,
ByteSliceView::new(IBC_REFLECT),
false,
true,
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
let checksum_ibc_reflect = checksum_ibc_reflect.consume().unwrap_or_default();
let mut error_msg = UnmanagedVector::default();
let hackatom_report = analyze_code(
cache_ptr,
ByteSliceView::new(&checksum_hackatom),
Some(&mut error_msg),
);
let _ = error_msg.consume();
assert!(!hackatom_report.has_ibc_entry_points);
assert_eq!(
hackatom_report.required_capabilities.consume().unwrap(),
b""
);
assert!(hackatom_report.contract_migrate_version.is_some);
assert_eq!(hackatom_report.contract_migrate_version.value, 42);
let mut error_msg: UnmanagedVector = UnmanagedVector::default();
let ibc_reflect_report = analyze_code(
cache_ptr,
ByteSliceView::new(&checksum_ibc_reflect),
Some(&mut error_msg),
);
let _ = error_msg.consume();
assert!(ibc_reflect_report.has_ibc_entry_points);
let required_capabilities =
String::from_utf8_lossy(&ibc_reflect_report.required_capabilities.consume().unwrap())
.to_string();
assert_eq!(required_capabilities, "iterator,stargate");
release_cache(cache_ptr);
}
#[test]
fn set_to_csv_works() {
assert_eq!(set_to_csv(BTreeSet::<String>::new()), "");
assert_eq!(
set_to_csv(BTreeSet::from_iter(vec!["foo".to_string()])),
"foo",
);
assert_eq!(
set_to_csv(BTreeSet::from_iter(vec![
"foo".to_string(),
"bar".to_string(),
"baz".to_string(),
])),
"bar,baz,foo",
);
assert_eq!(
set_to_csv(BTreeSet::from_iter(vec![
"a".to_string(),
"aa".to_string(),
"b".to_string(),
"c".to_string(),
"A".to_string(),
"AA".to_string(),
"B".to_string(),
"C".to_string(),
])),
"A,AA,B,C,a,aa,b,c",
);
// str
assert_eq!(
set_to_csv(BTreeSet::from_iter(vec![
"a", "aa", "b", "c", "A", "AA", "B", "C",
])),
"A,AA,B,C,a,aa,b,c",
);
// custom type with numeric ordering
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
enum Number {
One = 1,
Two = 2,
Three = 3,
Eleven = 11,
Twelve = 12,
Zero = 0,
MinusOne = -1,
}
impl AsRef<str> for Number {
fn as_ref(&self) -> &str {
use Number::*;
match self {
One => "1",
Two => "2",
Three => "3",
Eleven => "11",
Twelve => "12",
Zero => "0",
MinusOne => "-1",
}
}
}
assert_eq!(
set_to_csv(BTreeSet::from_iter([
Number::One,
Number::Two,
Number::Three,
Number::Eleven,
Number::Twelve,
Number::Zero,
Number::MinusOne,
])),
"-1,0,1,2,3,11,12",
);
// custom type with lexicographical ordering
#[derive(PartialEq, Eq)]
enum Color {
Red,
Green,
Blue,
Yellow,
}
impl AsRef<str> for Color {
fn as_ref(&self) -> &str {
use Color::*;
match self {
Red => "red",
Green => "green",
Blue => "blue",
Yellow => "yellow",
}
}
}
impl Ord for Color {
fn cmp(&self, other: &Self) -> Ordering {
// sort by name
self.as_ref().cmp(other.as_ref())
}
}
impl PartialOrd for Color {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
assert_eq!(
set_to_csv(BTreeSet::from_iter([
Color::Red,
Color::Green,
Color::Blue,
Color::Yellow,
])),
"blue,green,red,yellow",
);
}
#[test]
fn get_metrics_works() {
let dir: String = TempDir::new().unwrap().path().to_str().unwrap().to_owned();
let capabilities = "staking".to_string();
// Init cache
let mut error_msg = UnmanagedVector::default();
let config = Config::new(CacheOptions::new(
dir,
[capabilities],
Size::mebi(512),
Size::mebi(32),
));
let config = serde_json::to_vec(&config).unwrap();
let cache_ptr = init_cache(ByteSliceView::new(config.as_slice()), Some(&mut error_msg));
assert!(error_msg.is_none());
let _ = error_msg.consume();
// Get metrics 1
let mut error_msg = UnmanagedVector::default();
let metrics = get_metrics(cache_ptr, Some(&mut error_msg));
let _ = error_msg.consume();
assert_eq!(metrics, Metrics::default());
// Save wasm
let mut error_msg = UnmanagedVector::default();
let checksum_hackatom = store_code(
cache_ptr,
ByteSliceView::new(HACKATOM),
false,
true,
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
let checksum = checksum_hackatom.consume().unwrap_or_default();
// Get metrics 2
let mut error_msg = UnmanagedVector::default();
let metrics = get_metrics(cache_ptr, Some(&mut error_msg));
let _ = error_msg.consume();
assert_eq!(metrics, Metrics::default());
// Pin
let mut error_msg = UnmanagedVector::default();
pin(
cache_ptr,
ByteSliceView::new(&checksum),
Some(&mut error_msg),
);
assert!(error_msg.is_none());
let _ = error_msg.consume();
// Get metrics 3
let mut error_msg = UnmanagedVector::default();
let metrics = get_metrics(cache_ptr, Some(&mut error_msg));
let _ = error_msg.consume();
let Metrics {