-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathmod.rs
1773 lines (1588 loc) · 63.3 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
use std::cell::RefCell;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::mem::MaybeUninit;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use anyhow::anyhow;
use anyhow::Error;
use never::Never;
use semver::Version;
use wasmtime::{Memory, Trap};
use graph::blockchain::{Blockchain, HostFnCtx};
use graph::data::store;
use graph::data::subgraph::schema::SubgraphError;
use graph::data_source::{offchain, MappingTrigger, TriggerWithHandler};
use graph::prelude::*;
use graph::runtime::{
asc_get, asc_new,
gas::{self, Gas, GasCounter, SaturatingInto},
AscHeap, AscIndexId, AscType, DeterministicHostError, FromAscObj, HostExportError,
IndexForAscTypeId, ToAscObj,
};
use graph::util::mem::init_slice;
use graph::{components::subgraph::MappingError, runtime::AscPtr};
pub use into_wasm_ret::IntoWasmRet;
pub use stopwatch::TimeoutStopwatch;
use crate::asc_abi::class::*;
use crate::error::DeterminismLevel;
use crate::gas_rules::{GAS_COST_LOAD, GAS_COST_STORE};
pub use crate::host_exports;
use crate::host_exports::HostExports;
use crate::mapping::MappingContext;
use crate::mapping::ValidModule;
mod into_wasm_ret;
pub mod stopwatch;
pub const TRAP_TIMEOUT: &str = "trap: interrupt";
pub trait IntoTrap {
fn determinism_level(&self) -> DeterminismLevel;
fn into_trap(self) -> Trap;
}
/// A flexible interface for writing a type to AS memory, any pointer can be returned.
/// Use `AscPtr::erased` to convert `AscPtr<T>` into `AscPtr<()>`.
pub trait ToAscPtr {
fn to_asc_ptr<H: AscHeap>(
self,
heap: &mut H,
gas: &GasCounter,
) -> Result<AscPtr<()>, DeterministicHostError>;
}
impl ToAscPtr for offchain::TriggerData {
fn to_asc_ptr<H: AscHeap>(
self,
heap: &mut H,
gas: &GasCounter,
) -> Result<AscPtr<()>, DeterministicHostError> {
asc_new(heap, self.data.as_ref() as &[u8], gas).map(|ptr| ptr.erase())
}
}
impl<C: Blockchain> ToAscPtr for MappingTrigger<C>
where
C::MappingTrigger: ToAscPtr,
{
fn to_asc_ptr<H: AscHeap>(
self,
heap: &mut H,
gas: &GasCounter,
) -> Result<AscPtr<()>, DeterministicHostError> {
match self {
MappingTrigger::Onchain(trigger) => trigger.to_asc_ptr(heap, gas),
MappingTrigger::Offchain(trigger) => trigger.to_asc_ptr(heap, gas),
}
}
}
impl<T: ToAscPtr> ToAscPtr for TriggerWithHandler<T> {
fn to_asc_ptr<H: AscHeap>(
self,
heap: &mut H,
gas: &GasCounter,
) -> Result<AscPtr<()>, DeterministicHostError> {
self.trigger.to_asc_ptr(heap, gas)
}
}
/// Handle to a WASM instance, which is terminated if and only if this is dropped.
pub struct WasmInstance<C: Blockchain> {
pub instance: wasmtime::Instance,
// This is the only reference to `WasmInstanceContext` that's not within the instance itself, so
// we can always borrow the `RefCell` with no concern for race conditions.
//
// Also this is the only strong reference, so the instance will be dropped once this is dropped.
// The weak references are circulary held by instance itself through host exports.
pub instance_ctx: Rc<RefCell<Option<WasmInstanceContext<C>>>>,
// A reference to the gas counter used for reporting the gas used.
pub gas: GasCounter,
}
impl<C: Blockchain> Drop for WasmInstance<C> {
fn drop(&mut self) {
// Assert that the instance will be dropped.
assert_eq!(Rc::strong_count(&self.instance_ctx), 1);
}
}
impl<C: Blockchain> WasmInstance<C> {
pub fn asc_get<T, P>(&self, asc_ptr: AscPtr<P>) -> Result<T, DeterministicHostError>
where
P: AscType + AscIndexId,
T: FromAscObj<P>,
{
asc_get(self.instance_ctx().deref(), asc_ptr, &self.gas)
}
pub fn asc_new<P, T: ?Sized>(
&mut self,
rust_obj: &T,
) -> Result<AscPtr<P>, DeterministicHostError>
where
P: AscType + AscIndexId,
T: ToAscObj<P>,
{
asc_new(self.instance_ctx_mut().deref_mut(), rust_obj, &self.gas)
}
}
impl<C: Blockchain> WasmInstance<C> {
pub(crate) fn handle_json_callback(
mut self,
handler_name: &str,
value: &serde_json::Value,
user_data: &store::Value,
) -> Result<BlockState<C>, anyhow::Error> {
let gas = GasCounter::default();
let value = asc_new(self.instance_ctx_mut().deref_mut(), value, &gas)?;
let user_data = asc_new(self.instance_ctx_mut().deref_mut(), user_data, &gas)?;
self.instance_ctx_mut().ctx.state.enter_handler();
// Invoke the callback
self.instance
.get_func(handler_name)
.with_context(|| format!("function {} not found", handler_name))?
.typed()?
.call((value.wasm_ptr(), user_data.wasm_ptr()))
.with_context(|| format!("Failed to handle callback '{}'", handler_name))?;
self.instance_ctx_mut().ctx.state.exit_handler();
Ok(self.take_ctx().ctx.state)
}
pub(crate) fn handle_trigger(
mut self,
trigger: TriggerWithHandler<MappingTrigger<C>>,
) -> Result<(BlockState<C>, Gas), MappingError>
where
<C as Blockchain>::MappingTrigger: ToAscPtr,
{
let handler_name = trigger.handler_name().to_owned();
let gas = self.gas.clone();
let asc_trigger = trigger.to_asc_ptr(self.instance_ctx_mut().deref_mut(), &gas)?;
self.invoke_handler(&handler_name, asc_trigger)
}
pub fn take_ctx(&mut self) -> WasmInstanceContext<C> {
self.instance_ctx.borrow_mut().take().unwrap()
}
pub(crate) fn instance_ctx(&self) -> std::cell::Ref<'_, WasmInstanceContext<C>> {
std::cell::Ref::map(self.instance_ctx.borrow(), |i| i.as_ref().unwrap())
}
pub fn instance_ctx_mut(&self) -> std::cell::RefMut<'_, WasmInstanceContext<C>> {
std::cell::RefMut::map(self.instance_ctx.borrow_mut(), |i| i.as_mut().unwrap())
}
#[cfg(debug_assertions)]
pub fn get_func(&self, func_name: &str) -> wasmtime::Func {
self.instance.get_func(func_name).unwrap()
}
#[cfg(debug_assertions)]
pub fn gas_used(&self) -> u64 {
self.gas.get().value()
}
fn invoke_handler<T>(
&mut self,
handler: &str,
arg: AscPtr<T>,
) -> Result<(BlockState<C>, Gas), MappingError> {
let func = self
.instance
.get_func(handler)
.with_context(|| format!("function {} not found", handler))?;
let func = func
.typed()
.context("wasm function has incorrect signature")?;
// Caution: Make sure all exit paths from this function call `exit_handler`.
self.instance_ctx_mut().ctx.state.enter_handler();
// This `match` will return early if there was a non-deterministic trap.
let deterministic_error: Option<Error> = match func.call(arg.wasm_ptr()) {
Ok(()) => None,
Err(trap) if self.instance_ctx().possible_reorg => {
self.instance_ctx_mut().ctx.state.exit_handler();
return Err(MappingError::PossibleReorg(trap.into()));
}
Err(trap) if trap.to_string().contains(TRAP_TIMEOUT) => {
self.instance_ctx_mut().ctx.state.exit_handler();
return Err(MappingError::Unknown(Error::from(trap).context(format!(
"Handler '{}' hit the timeout of '{}' seconds",
handler,
self.instance_ctx().timeout.unwrap().as_secs()
))));
}
Err(trap) => {
use wasmtime::TrapCode::*;
let trap_code = trap.trap_code();
let e = Error::from(trap);
match trap_code {
Some(MemoryOutOfBounds)
| Some(HeapMisaligned)
| Some(TableOutOfBounds)
| Some(IndirectCallToNull)
| Some(BadSignature)
| Some(IntegerOverflow)
| Some(IntegerDivisionByZero)
| Some(BadConversionToInteger)
| Some(UnreachableCodeReached) => Some(e),
_ if self.instance_ctx().deterministic_host_trap => Some(e),
_ => {
self.instance_ctx_mut().ctx.state.exit_handler();
return Err(MappingError::Unknown(e));
}
}
}
};
if let Some(deterministic_error) = deterministic_error {
let message = format!("{:#}", deterministic_error).replace('\n', "\t");
// Log the error and restore the updates snapshot, effectively reverting the handler.
error!(&self.instance_ctx().ctx.logger,
"Handler skipped due to execution failure";
"handler" => handler,
"error" => &message,
);
let subgraph_error = SubgraphError {
subgraph_id: self.instance_ctx().ctx.host_exports.subgraph_id.clone(),
message,
block_ptr: Some(self.instance_ctx().ctx.block_ptr.cheap_clone()),
handler: Some(handler.to_string()),
deterministic: true,
};
self.instance_ctx_mut()
.ctx
.state
.exit_handler_and_discard_changes_due_to_error(subgraph_error);
} else {
self.instance_ctx_mut().ctx.state.exit_handler();
}
let gas = self.gas.get();
Ok((self.take_ctx().ctx.state, gas))
}
}
#[derive(Copy, Clone)]
pub struct ExperimentalFeatures {
pub allow_non_deterministic_ipfs: bool,
}
pub struct WasmInstanceContext<C: Blockchain> {
// In the future there may be multiple memories, but currently there is only one memory per
// module. And at least AS calls it "memory". There is no uninitialized memory in Wasm, memory
// is zeroed when initialized or grown.
memory: Memory,
// Function exported by the wasm module that will allocate the request number of bytes and
// return a pointer to the first byte of allocated space.
memory_allocate: wasmtime::TypedFunc<i32, i32>,
// Function wrapper for `idof<T>` from AssemblyScript
id_of_type: Option<wasmtime::TypedFunc<u32, u32>>,
pub ctx: MappingContext<C>,
pub valid_module: Arc<ValidModule>,
pub host_metrics: Arc<HostMetrics>,
pub(crate) timeout: Option<Duration>,
// Used by ipfs.map.
pub(crate) timeout_stopwatch: Arc<std::sync::Mutex<TimeoutStopwatch>>,
// First free byte in the current arena. Set on the first call to `raw_new`.
arena_start_ptr: i32,
// Number of free bytes starting from `arena_start_ptr`.
arena_free_size: i32,
// A trap ocurred due to a possible reorg detection.
pub possible_reorg: bool,
// A host export trap ocurred for a deterministic reason.
pub deterministic_host_trap: bool,
pub(crate) experimental_features: ExperimentalFeatures,
}
impl<C: Blockchain> WasmInstance<C> {
/// Instantiates the module and sets it to be interrupted after `timeout`.
pub fn from_valid_module_with_ctx(
valid_module: Arc<ValidModule>,
ctx: MappingContext<C>,
host_metrics: Arc<HostMetrics>,
timeout: Option<Duration>,
experimental_features: ExperimentalFeatures,
) -> Result<WasmInstance<C>, anyhow::Error> {
let mut linker = wasmtime::Linker::new(&wasmtime::Store::new(valid_module.module.engine()));
let host_fns = ctx.host_fns.cheap_clone();
let api_version = ctx.host_exports.api_version.clone();
// Used by exports to access the instance context. There are two ways this can be set:
// - After instantiation, if no host export is called in the start function.
// - During the start function, if it calls a host export.
// Either way, after instantiation this will have been set.
let shared_ctx: Rc<RefCell<Option<WasmInstanceContext<C>>>> = Rc::new(RefCell::new(None));
// We will move the ctx only once, to init `shared_ctx`. But we don't statically know where
// it will be moved so we need this ugly thing.
let ctx: Rc<RefCell<Option<MappingContext<C>>>> = Rc::new(RefCell::new(Some(ctx)));
// Start the timeout watchdog task.
let timeout_stopwatch = Arc::new(std::sync::Mutex::new(TimeoutStopwatch::start_new()));
if let Some(timeout) = timeout {
// This task is likely to outlive the instance, which is fine.
let interrupt_handle = linker.store().interrupt_handle().unwrap();
let timeout_stopwatch = timeout_stopwatch.clone();
graph::spawn_allow_panic(async move {
let minimum_wait = Duration::from_secs(1);
loop {
let time_left =
timeout.checked_sub(timeout_stopwatch.lock().unwrap().elapsed());
match time_left {
None => break interrupt_handle.interrupt(), // Timed out.
Some(time) if time < minimum_wait => break interrupt_handle.interrupt(),
Some(time) => tokio::time::sleep(time).await,
}
}
});
}
// Because `gas` and `deterministic_host_trap` need to be accessed from the gas
// host fn, they need to be separate from the rest of the context.
let gas = GasCounter::default();
let deterministic_host_trap = Rc::new(AtomicBool::new(false));
macro_rules! link {
($wasm_name:expr, $rust_name:ident, $($param:ident),*) => {
link!($wasm_name, $rust_name, "host_export_other", $($param),*)
};
($wasm_name:expr, $rust_name:ident, $section:expr, $($param:ident),*) => {
let modules = valid_module
.import_name_to_modules
.get($wasm_name)
.into_iter()
.flatten();
// link an import with all the modules that require it.
for module in modules {
let func_shared_ctx = Rc::downgrade(&shared_ctx);
let valid_module = valid_module.cheap_clone();
let host_metrics = host_metrics.cheap_clone();
let timeout_stopwatch = timeout_stopwatch.cheap_clone();
let ctx = ctx.cheap_clone();
let gas = gas.cheap_clone();
linker.func(
module,
$wasm_name,
move |caller: wasmtime::Caller, $($param: u32),*| {
let instance = func_shared_ctx.upgrade().unwrap();
let mut instance = instance.borrow_mut();
// Happens when calling a host fn in Wasm start.
if instance.is_none() {
*instance = Some(WasmInstanceContext::from_caller(
caller,
ctx.borrow_mut().take().unwrap(),
valid_module.cheap_clone(),
host_metrics.cheap_clone(),
timeout,
timeout_stopwatch.cheap_clone(),
experimental_features.clone()
).unwrap())
}
let instance = instance.as_mut().unwrap();
let _section = instance.host_metrics.stopwatch.start_section($section);
let result = instance.$rust_name(
&gas,
$($param.into()),*
);
match result {
Ok(result) => Ok(result.into_wasm_ret()),
Err(e) => {
match IntoTrap::determinism_level(&e) {
DeterminismLevel::Deterministic => {
instance.deterministic_host_trap = true;
},
DeterminismLevel::PossibleReorg => {
instance.possible_reorg = true;
},
DeterminismLevel::Unimplemented | DeterminismLevel::NonDeterministic => {},
}
Err(IntoTrap::into_trap(e))
}
}
}
)?;
}
};
}
// Link chain-specifc host fns.
for host_fn in host_fns.iter() {
let modules = valid_module
.import_name_to_modules
.get(host_fn.name)
.into_iter()
.flatten();
for module in modules {
let func_shared_ctx = Rc::downgrade(&shared_ctx);
let host_fn = host_fn.cheap_clone();
let gas = gas.cheap_clone();
linker.func(module, host_fn.name, move |call_ptr: u32| {
let start = Instant::now();
let instance = func_shared_ctx.upgrade().unwrap();
let mut instance = instance.borrow_mut();
let instance = match &mut *instance {
Some(instance) => instance,
// Happens when calling a host fn in Wasm start.
None => {
return Err(anyhow!(
"{} is not allowed in global variables",
host_fn.name
)
.into());
}
};
let name_for_metrics = host_fn.name.replace('.', "_");
let stopwatch = &instance.host_metrics.stopwatch;
let _section =
stopwatch.start_section(&format!("host_export_{}", name_for_metrics));
let ctx = HostFnCtx {
logger: instance.ctx.logger.cheap_clone(),
block_ptr: instance.ctx.block_ptr.cheap_clone(),
heap: instance,
gas: gas.cheap_clone(),
};
let ret = (host_fn.func)(ctx, call_ptr).map_err(|e| match e {
HostExportError::Deterministic(e) => {
instance.deterministic_host_trap = true;
e
}
HostExportError::PossibleReorg(e) => {
instance.possible_reorg = true;
e
}
HostExportError::Unknown(e) => e,
})?;
instance.host_metrics.observe_host_fn_execution_time(
start.elapsed().as_secs_f64(),
&name_for_metrics,
);
Ok(ret)
})?;
}
}
link!("ethereum.encode", ethereum_encode, params_ptr);
link!("ethereum.decode", ethereum_decode, params_ptr, data_ptr);
link!("abort", abort, message_ptr, file_name_ptr, line, column);
link!("store.get", store_get, "host_export_store_get", entity, id);
link!(
"store.set",
store_set,
"host_export_store_set",
entity,
id,
data
);
// All IPFS-related functions exported by the host WASM runtime should be listed in the
// graph::data::subgraph::features::IPFS_ON_ETHEREUM_CONTRACTS_FUNCTION_NAMES array for
// automatic feature detection to work.
//
// For reference, search this codebase for: ff652476-e6ad-40e4-85b8-e815d6c6e5e2
link!("ipfs.cat", ipfs_cat, "host_export_ipfs_cat", hash_ptr);
link!(
"ipfs.map",
ipfs_map,
"host_export_ipfs_map",
link_ptr,
callback,
user_data,
flags
);
// The previous ipfs-related functions are unconditionally linked for backward compatibility
if experimental_features.allow_non_deterministic_ipfs {
link!(
"ipfs.getBlock",
ipfs_get_block,
"host_export_ipfs_get_block",
hash_ptr
);
}
link!("store.remove", store_remove, entity_ptr, id_ptr);
link!("typeConversion.bytesToString", bytes_to_string, ptr);
link!("typeConversion.bytesToHex", bytes_to_hex, ptr);
link!("typeConversion.bigIntToString", big_int_to_string, ptr);
link!("typeConversion.bigIntToHex", big_int_to_hex, ptr);
link!("typeConversion.stringToH160", string_to_h160, ptr);
link!("typeConversion.bytesToBase58", bytes_to_base58, ptr);
link!("json.fromBytes", json_from_bytes, ptr);
link!("json.try_fromBytes", json_try_from_bytes, ptr);
link!("json.toI64", json_to_i64, ptr);
link!("json.toU64", json_to_u64, ptr);
link!("json.toF64", json_to_f64, ptr);
link!("json.toBigInt", json_to_big_int, ptr);
link!("crypto.keccak256", crypto_keccak_256, ptr);
link!("bigInt.plus", big_int_plus, x_ptr, y_ptr);
link!("bigInt.minus", big_int_minus, x_ptr, y_ptr);
link!("bigInt.times", big_int_times, x_ptr, y_ptr);
link!("bigInt.dividedBy", big_int_divided_by, x_ptr, y_ptr);
link!("bigInt.dividedByDecimal", big_int_divided_by_decimal, x, y);
link!("bigInt.mod", big_int_mod, x_ptr, y_ptr);
link!("bigInt.pow", big_int_pow, x_ptr, exp);
link!("bigInt.fromString", big_int_from_string, ptr);
link!("bigInt.bitOr", big_int_bit_or, x_ptr, y_ptr);
link!("bigInt.bitAnd", big_int_bit_and, x_ptr, y_ptr);
link!("bigInt.leftShift", big_int_left_shift, x_ptr, bits);
link!("bigInt.rightShift", big_int_right_shift, x_ptr, bits);
link!("bigDecimal.toString", big_decimal_to_string, ptr);
link!("bigDecimal.fromString", big_decimal_from_string, ptr);
link!("bigDecimal.plus", big_decimal_plus, x_ptr, y_ptr);
link!("bigDecimal.minus", big_decimal_minus, x_ptr, y_ptr);
link!("bigDecimal.times", big_decimal_times, x_ptr, y_ptr);
link!("bigDecimal.dividedBy", big_decimal_divided_by, x, y);
link!("bigDecimal.equals", big_decimal_equals, x_ptr, y_ptr);
link!("dataSource.create", data_source_create, name, params);
link!(
"dataSource.createWithContext",
data_source_create_with_context,
name,
params,
context
);
link!("dataSource.address", data_source_address,);
link!("dataSource.network", data_source_network,);
link!("dataSource.context", data_source_context,);
link!("ens.nameByHash", ens_name_by_hash, ptr);
link!("log.log", log_log, level, msg_ptr);
// `arweave and `box` functionality was removed, but apiVersion <= 0.0.4 must link it.
if api_version <= Version::new(0, 0, 4) {
link!("arweave.transactionData", arweave_transaction_data, ptr);
link!("box.profile", box_profile, ptr);
}
// link the `gas` function
// See also e3f03e62-40e4-4f8c-b4a1-d0375cca0b76
{
let gas = gas.cheap_clone();
linker.func("gas", "gas", move |gas_used: u32| -> Result<(), Trap> {
// Gas metering has a relevant execution cost cost, being called tens of thousands
// of times per handler, but it's not worth having a stopwatch section here because
// the cost of measuring would be greater than the cost of `consume_host_fn`. Last
// time this was benchmarked it took < 100ns to run.
if let Err(e) = gas.consume_host_fn(gas_used.saturating_into()) {
deterministic_host_trap.store(true, Ordering::SeqCst);
return Err(e.into_trap());
}
Ok(())
})?;
}
let instance = linker.instantiate(&valid_module.module)?;
// Usually `shared_ctx` is still `None` because no host fns were called during start.
if shared_ctx.borrow().is_none() {
*shared_ctx.borrow_mut() = Some(WasmInstanceContext::from_instance(
&instance,
ctx.borrow_mut().take().unwrap(),
valid_module,
host_metrics,
timeout,
timeout_stopwatch,
experimental_features,
)?);
}
match api_version {
version if version <= Version::new(0, 0, 4) => {}
_ => {
instance
.get_func("_start")
.context("`_start` function not found")?
.typed::<(), ()>()?
.call(())?;
}
}
Ok(WasmInstance {
instance,
instance_ctx: shared_ctx,
gas,
})
}
}
impl<C: Blockchain> AscHeap for WasmInstanceContext<C> {
fn raw_new(&mut self, bytes: &[u8], gas: &GasCounter) -> Result<u32, DeterministicHostError> {
// The cost of writing to wasm memory from the host is the same as of writing from wasm
// using load instructions.
gas.consume_host_fn(Gas::new(GAS_COST_STORE as u64 * bytes.len() as u64))?;
// We request large chunks from the AssemblyScript allocator to use as arenas that we
// manage directly.
static MIN_ARENA_SIZE: i32 = 10_000;
let size = i32::try_from(bytes.len()).unwrap();
if size > self.arena_free_size {
// Allocate a new arena. Any free space left in the previous arena is left unused. This
// causes at most half of memory to be wasted, which is acceptable.
let arena_size = size.max(MIN_ARENA_SIZE);
// Unwrap: This may panic if more memory needs to be requested from the OS and that
// fails. This error is not deterministic since it depends on the operating conditions
// of the node.
self.arena_start_ptr = self.memory_allocate.call(arena_size).unwrap();
self.arena_free_size = arena_size;
match &self.ctx.host_exports.api_version {
version if *version <= Version::new(0, 0, 4) => {}
_ => {
// This arithmetic is done because when you call AssemblyScripts's `__alloc`
// function, it isn't typed and it just returns `mmInfo` on it's header,
// differently from allocating on regular types (`__new` for example).
// `mmInfo` has size of 4, and everything allocated on AssemblyScript memory
// should have alignment of 16, this means we need to do a 12 offset on these
// big chunks of untyped allocation.
self.arena_start_ptr += 12;
self.arena_free_size -= 12;
}
};
};
let ptr = self.arena_start_ptr as usize;
// Unwrap: We have just allocated enough space for `bytes`.
self.memory.write(ptr, bytes).unwrap();
self.arena_start_ptr += size;
self.arena_free_size -= size;
Ok(ptr as u32)
}
fn read_u32(&self, offset: u32, gas: &GasCounter) -> Result<u32, DeterministicHostError> {
gas.consume_host_fn(Gas::new(GAS_COST_LOAD as u64 * 4))?;
let mut bytes = [0; 4];
self.memory.read(offset as usize, &mut bytes).map_err(|_| {
DeterministicHostError::from(anyhow!(
"Heap access out of bounds. Offset: {} Size: {}",
offset,
4
))
})?;
Ok(u32::from_le_bytes(bytes))
}
fn read<'a>(
&self,
offset: u32,
buffer: &'a mut [MaybeUninit<u8>],
gas: &GasCounter,
) -> Result<&'a mut [u8], DeterministicHostError> {
// The cost of reading wasm memory from the host is the same as of reading from wasm using
// load instructions.
gas.consume_host_fn(Gas::new(GAS_COST_LOAD as u64 * (buffer.len() as u64)))?;
let offset = offset as usize;
unsafe {
// Safety: This was copy-pasted from Memory::read, and we ensure
// nothing else is writing this memory because we don't call into
// WASM here.
let src = self
.memory
.data_unchecked()
.get(offset..)
.and_then(|s| s.get(..buffer.len()))
.ok_or(DeterministicHostError::from(anyhow!(
"Heap access out of bounds. Offset: {} Size: {}",
offset,
buffer.len()
)))?;
Ok(init_slice(src, buffer))
}
}
fn api_version(&self) -> Version {
self.ctx.host_exports.api_version.clone()
}
fn asc_type_id(
&mut self,
type_id_index: IndexForAscTypeId,
) -> Result<u32, DeterministicHostError> {
let type_id = self
.id_of_type
.as_ref()
.unwrap() // Unwrap ok because it's only called on correct apiVersion, look for AscPtr::generate_header
.call(type_id_index as u32)
.with_context(|| format!("Failed to call 'asc_type_id' with '{:?}'", type_id_index))
.map_err(DeterministicHostError::from)?;
Ok(type_id)
}
}
impl<C: Blockchain> WasmInstanceContext<C> {
pub fn from_instance(
instance: &wasmtime::Instance,
ctx: MappingContext<C>,
valid_module: Arc<ValidModule>,
host_metrics: Arc<HostMetrics>,
timeout: Option<Duration>,
timeout_stopwatch: Arc<std::sync::Mutex<TimeoutStopwatch>>,
experimental_features: ExperimentalFeatures,
) -> Result<Self, anyhow::Error> {
// Provide access to the WASM runtime linear memory
let memory = instance
.get_memory("memory")
.context("Failed to find memory export in the WASM module")?;
let memory_allocate = match &ctx.host_exports.api_version {
version if *version <= Version::new(0, 0, 4) => instance
.get_func("memory.allocate")
.context("`memory.allocate` function not found"),
_ => instance
.get_func("allocate")
.context("`allocate` function not found"),
}?
.typed()?
.clone();
let id_of_type = match &ctx.host_exports.api_version {
version if *version <= Version::new(0, 0, 4) => None,
_ => Some(
instance
.get_func("id_of_type")
.context("`id_of_type` function not found")?
.typed()?
.clone(),
),
};
Ok(WasmInstanceContext {
memory_allocate,
id_of_type,
memory,
ctx,
valid_module,
host_metrics,
timeout,
timeout_stopwatch,
arena_free_size: 0,
arena_start_ptr: 0,
possible_reorg: false,
deterministic_host_trap: false,
experimental_features,
})
}
pub fn from_caller(
caller: wasmtime::Caller,
ctx: MappingContext<C>,
valid_module: Arc<ValidModule>,
host_metrics: Arc<HostMetrics>,
timeout: Option<Duration>,
timeout_stopwatch: Arc<std::sync::Mutex<TimeoutStopwatch>>,
experimental_features: ExperimentalFeatures,
) -> Result<Self, anyhow::Error> {
let memory = caller
.get_export("memory")
.and_then(|e| e.into_memory())
.context("Failed to find memory export in the WASM module")?;
let memory_allocate = match &ctx.host_exports.api_version {
version if *version <= Version::new(0, 0, 4) => caller
.get_export("memory.allocate")
.and_then(|e| e.into_func())
.context("`memory.allocate` function not found"),
_ => caller
.get_export("allocate")
.and_then(|e| e.into_func())
.context("`allocate` function not found"),
}?
.typed()?
.clone();
let id_of_type = match &ctx.host_exports.api_version {
version if *version <= Version::new(0, 0, 4) => None,
_ => Some(
caller
.get_export("id_of_type")
.and_then(|e| e.into_func())
.context("`id_of_type` function not found")?
.typed()?
.clone(),
),
};
Ok(WasmInstanceContext {
id_of_type,
memory_allocate,
memory,
ctx,
valid_module,
host_metrics,
timeout,
timeout_stopwatch,
arena_free_size: 0,
arena_start_ptr: 0,
possible_reorg: false,
deterministic_host_trap: false,
experimental_features,
})
}
}
// Implementation of externals.
impl<C: Blockchain> WasmInstanceContext<C> {
/// function abort(message?: string | null, fileName?: string | null, lineNumber?: u32, columnNumber?: u32): void
/// Always returns a trap.
pub fn abort(
&mut self,
gas: &GasCounter,
message_ptr: AscPtr<AscString>,
file_name_ptr: AscPtr<AscString>,
line_number: u32,
column_number: u32,
) -> Result<Never, DeterministicHostError> {
let message = match message_ptr.is_null() {
false => Some(asc_get(self, message_ptr, gas)?),
true => None,
};
let file_name = match file_name_ptr.is_null() {
false => Some(asc_get(self, file_name_ptr, gas)?),
true => None,
};
let line_number = match line_number {
0 => None,
_ => Some(line_number),
};
let column_number = match column_number {
0 => None,
_ => Some(column_number),
};
self.ctx
.host_exports
.abort(message, file_name, line_number, column_number, gas)
}
/// function store.set(entity: string, id: string, data: Entity): void
pub fn store_set(
&mut self,
gas: &GasCounter,
entity_ptr: AscPtr<AscString>,
id_ptr: AscPtr<AscString>,
data_ptr: AscPtr<AscEntity>,
) -> Result<(), HostExportError> {
let stopwatch = &self.host_metrics.stopwatch;
stopwatch.start_section("host_export_store_set__wasm_instance_context_store_set");
let entity = asc_get(self, entity_ptr, gas)?;
let id = asc_get(self, id_ptr, gas)?;
let data = asc_get(self, data_ptr, gas)?;
self.ctx.host_exports.store_set(
&self.ctx.logger,
&mut self.ctx.state,
&self.ctx.proof_of_indexing,
entity,
id,
data,
stopwatch,
gas,
)?;
Ok(())
}
/// function store.remove(entity: string, id: string): void
pub fn store_remove(
&mut self,
gas: &GasCounter,
entity_ptr: AscPtr<AscString>,
id_ptr: AscPtr<AscString>,
) -> Result<(), HostExportError> {
let entity = asc_get(self, entity_ptr, gas)?;
let id = asc_get(self, id_ptr, gas)?;
self.ctx.host_exports.store_remove(
&self.ctx.logger,
&mut self.ctx.state,
&self.ctx.proof_of_indexing,
entity,
id,
gas,
)
}
/// function store.get(entity: string, id: string): Entity | null
pub fn store_get(
&mut self,
gas: &GasCounter,
entity_ptr: AscPtr<AscString>,
id_ptr: AscPtr<AscString>,
) -> Result<AscPtr<AscEntity>, HostExportError> {
let _timer = self
.host_metrics
.cheap_clone()
.time_host_fn_execution_region("store_get");
let entity_type: String = asc_get(self, entity_ptr, gas)?;
let id: String = asc_get(self, id_ptr, gas)?;
let entity_option = self.ctx.host_exports.store_get(
&mut self.ctx.state,
entity_type.clone(),
id.clone(),
gas,
)?;
let ret = match entity_option {
Some(entity) => {
let _section = self
.host_metrics
.stopwatch
.start_section("store_get_asc_new");
asc_new(self, &entity.sorted(), gas)?
}
None => match &self.ctx.debug_fork {
Some(fork) => {
let entity_option = fork.fetch(entity_type, id).map_err(|e| {
HostExportError::Unknown(anyhow!(
"store_get: failed to fetch entity from the debug fork: {}",
e
))
})?;
match entity_option {
Some(entity) => {
let _section = self