forked from casper-network/casper-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
3493 lines (3015 loc) · 129 KB
/
mod.rs
File metadata and controls
3493 lines (3015 loc) · 129 KB
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
//! This module contains executor state of the WASM code.
mod args;
mod auction_internal;
mod externals;
mod handle_payment_internal;
mod host_function_flag;
mod mint_internal;
pub mod stack;
mod utils;
mod wasm_prep;
use std::{
cmp,
collections::{BTreeMap, BTreeSet},
convert::{TryFrom, TryInto},
iter::FromIterator,
};
use casper_wasm::elements::Module;
use casper_wasmi::{MemoryRef, Trap, TrapCode};
use tracing::error;
#[cfg(feature = "test-support")]
use casper_wasmi::RuntimeValue;
use casper_storage::{
global_state::{error::Error as GlobalStateError, state::StateReader},
system::{auction::Auction, handle_payment::HandlePayment, mint::Mint},
tracking_copy::TrackingCopyExt,
};
use casper_types::{
account::{Account, AccountHash},
addressable_entity::{
self, ActionThresholds, ActionType, AddKeyFailure, AddressableEntity,
AddressableEntityHash, AssociatedKeys, EntityKindTag, EntryPoint, EntryPointAccess,
EntryPointType, EntryPoints, MessageTopicError, MessageTopics, NamedKeys, Parameter,
RemoveKeyFailure, SetThresholdFailure, UpdateKeyFailure, Weight, DEFAULT_ENTRY_POINT_NAME,
},
bytesrepr::{self, Bytes, FromBytes, ToBytes},
contract_messages::{
Message, MessageAddr, MessagePayload, MessageTopicOperation, MessageTopicSummary,
},
contracts::ContractHash,
crypto,
system::{
self,
auction::{self, EraInfo},
handle_payment, mint, Caller, SystemEntityType, AUCTION, HANDLE_PAYMENT, MINT,
STANDARD_PAYMENT,
},
AccessRights, ApiError, BlockGlobalAddr, BlockTime, ByteCode, ByteCodeAddr, ByteCodeHash,
ByteCodeKind, CLTyped, CLValue, ContextAccessRights, EntityAddr, EntityKind, EntityVersion,
EntityVersionKey, EntityVersions, EntryPointAddr, EntryPointValue, Gas, GrantedAccess, Group,
Groups, HostFunction, HostFunctionCost, InitiatorAddr, Key, NamedArg, Package, PackageHash,
PackageStatus, Phase, PublicKey, RuntimeArgs, StoredValue, TransactionRuntime, Transfer,
TransferResult, TransferV2, TransferredTo, URef, DICTIONARY_ITEM_KEY_MAX_LENGTH, U512,
};
use crate::{
execution::ExecError, runtime::host_function_flag::HostFunctionFlag,
runtime_context::RuntimeContext,
};
pub use stack::{RuntimeStack, RuntimeStackFrame, RuntimeStackOverflow};
pub use wasm_prep::{
PreprocessingError, WasmValidationError, DEFAULT_BR_TABLE_MAX_SIZE, DEFAULT_MAX_GLOBALS,
DEFAULT_MAX_PARAMETER_COUNT, DEFAULT_MAX_TABLE_SIZE,
};
#[derive(Debug)]
enum CallContractIdentifier {
Contract {
contract_hash: AddressableEntityHash,
},
ContractPackage {
contract_package_hash: PackageHash,
version: Option<EntityVersion>,
},
}
/// Represents the runtime properties of a WASM execution.
pub struct Runtime<'a, R> {
context: RuntimeContext<'a, R>,
memory: Option<MemoryRef>,
module: Option<Module>,
host_buffer: Option<CLValue>,
stack: Option<RuntimeStack>,
host_function_flag: HostFunctionFlag,
}
impl<'a, R> Runtime<'a, R>
where
R: StateReader<Key, StoredValue, Error = GlobalStateError>,
{
/// Creates a new runtime instance.
pub(crate) fn new(context: RuntimeContext<'a, R>) -> Self {
Runtime {
context,
memory: None,
module: None,
host_buffer: None,
stack: None,
host_function_flag: HostFunctionFlag::default(),
}
}
/// Creates a new runtime instance by cloning the config, and host function flag from `self`.
fn new_invocation_runtime(
&self,
context: RuntimeContext<'a, R>,
module: Module,
memory: MemoryRef,
stack: RuntimeStack,
) -> Self {
Self::check_preconditions(&stack);
Runtime {
context,
memory: Some(memory),
module: Some(module),
host_buffer: None,
stack: Some(stack),
host_function_flag: self.host_function_flag.clone(),
}
}
/// Creates a new runtime instance with a stack from `self`.
pub(crate) fn new_with_stack(
&self,
context: RuntimeContext<'a, R>,
stack: RuntimeStack,
) -> Self {
Self::check_preconditions(&stack);
Runtime {
context,
memory: None,
module: None,
host_buffer: None,
stack: Some(stack),
host_function_flag: self.host_function_flag.clone(),
}
}
/// Preconditions that would render the system inconsistent if violated. Those are strictly
/// programming errors.
fn check_preconditions(stack: &RuntimeStack) {
if stack.is_empty() {
error!("Call stack should not be empty while creating a new Runtime instance");
debug_assert!(false);
}
if stack.first_frame().unwrap().contract_hash().is_some() {
error!("First element of the call stack should always represent a Session call");
debug_assert!(false);
}
}
/// Returns the context.
pub(crate) fn context(&self) -> &RuntimeContext<'a, R> {
&self.context
}
fn gas(&mut self, amount: Gas) -> Result<(), ExecError> {
self.context.charge_gas(amount)
}
/// Returns current gas counter.
fn gas_counter(&self) -> Gas {
self.context.gas_counter()
}
/// Sets new gas counter value.
fn set_gas_counter(&mut self, new_gas_counter: Gas) {
self.context.set_gas_counter(new_gas_counter);
}
/// Charge for a system contract call.
///
/// This method does not charge for system contract calls if the immediate caller is a system
/// contract or if we're currently within the scope of a host function call. This avoids
/// misleading gas charges if one system contract calls other system contract (e.g. auction
/// contract calls into mint to create new purses).
pub(crate) fn charge_system_contract_call<T>(&mut self, amount: T) -> Result<(), ExecError>
where
T: Into<Gas>,
{
if self.is_system_immediate_caller()? || self.host_function_flag.is_in_host_function_scope()
{
return Ok(());
}
self.context.charge_system_contract_call(amount)
}
fn checked_memory_slice<Ret>(
&self,
offset: usize,
size: usize,
func: impl FnOnce(&[u8]) -> Ret,
) -> Result<Ret, ExecError> {
// This is mostly copied from a private function `MemoryInstance::checked_memory_region`
// that calls a user defined function with a validated slice of memory. This allows
// usage patterns that does not involve copying data onto heap first i.e. deserialize
// values without copying data first, etc.
// NOTE: Depending on the VM backend used in future, this may change, as not all VMs may
// support direct memory access.
self.try_get_memory()?
.with_direct_access(|buffer| {
let end = offset.checked_add(size).ok_or_else(|| {
casper_wasmi::Error::Memory(format!(
"trying to access memory block of size {} from offset {}",
size, offset
))
})?;
if end > buffer.len() {
return Err(casper_wasmi::Error::Memory(format!(
"trying to access region [{}..{}] in memory [0..{}]",
offset,
end,
buffer.len(),
)));
}
Ok(func(&buffer[offset..end]))
})
.map_err(Into::into)
}
/// Returns bytes from the WASM memory instance.
#[inline]
fn bytes_from_mem(&self, ptr: u32, size: usize) -> Result<Vec<u8>, ExecError> {
self.checked_memory_slice(ptr as usize, size, |data| data.to_vec())
}
/// Returns a deserialized type from the WASM memory instance.
#[inline]
fn t_from_mem<T: FromBytes>(&self, ptr: u32, size: u32) -> Result<T, ExecError> {
let result = self.checked_memory_slice(ptr as usize, size as usize, |data| {
bytesrepr::deserialize_from_slice(data)
})?;
Ok(result?)
}
/// Reads key (defined as `key_ptr` and `key_size` tuple) from Wasm memory.
#[inline]
fn key_from_mem(&mut self, key_ptr: u32, key_size: u32) -> Result<Key, ExecError> {
self.t_from_mem(key_ptr, key_size)
}
/// Reads `CLValue` (defined as `cl_value_ptr` and `cl_value_size` tuple) from Wasm memory.
#[inline]
fn cl_value_from_mem(
&mut self,
cl_value_ptr: u32,
cl_value_size: u32,
) -> Result<CLValue, ExecError> {
self.t_from_mem(cl_value_ptr, cl_value_size)
}
/// Returns a deserialized string from the WASM memory instance.
#[inline]
fn string_from_mem(&self, ptr: u32, size: u32) -> Result<String, Trap> {
self.t_from_mem(ptr, size).map_err(Trap::from)
}
fn get_module_from_entry_points(
&mut self,
entry_points: &EntryPoints,
) -> Result<Vec<u8>, ExecError> {
let module = self.try_get_module()?.clone();
let entry_point_names: Vec<&str> = entry_points.keys().map(|s| s.as_str()).collect();
let module_bytes = wasm_prep::get_module_from_entry_points(entry_point_names, module)?;
Ok(module_bytes)
}
#[allow(clippy::wrong_self_convention)]
fn is_valid_uref(&self, uref_ptr: u32, uref_size: u32) -> Result<bool, Trap> {
let uref: URef = self.t_from_mem(uref_ptr, uref_size)?;
Ok(self.context.validate_uref(&uref).is_ok())
}
/// Load the uref known by the given name into the Wasm memory
fn load_key(
&mut self,
name_ptr: u32,
name_size: u32,
output_ptr: u32,
output_size: usize,
bytes_written_ptr: u32,
) -> Result<Result<(), ApiError>, Trap> {
let name = self.string_from_mem(name_ptr, name_size)?;
// Get a key and serialize it
let key = match self.context.named_keys_get(&name) {
Some(key) => key,
None => {
return Ok(Err(ApiError::MissingKey));
}
};
let key_bytes = match key.to_bytes() {
Ok(bytes) => bytes,
Err(error) => return Ok(Err(error.into())),
};
// `output_size` has to be greater or equal to the actual length of serialized Key bytes
if output_size < key_bytes.len() {
return Ok(Err(ApiError::BufferTooSmall));
}
// Set serialized Key bytes into the output buffer
if let Err(error) = self.try_get_memory()?.set(output_ptr, &key_bytes) {
return Err(ExecError::Interpreter(error.into()).into());
}
// SAFETY: For all practical purposes following conversion is assumed to be safe
let bytes_size: u32 = key_bytes
.len()
.try_into()
.expect("Keys should not serialize to many bytes");
let size_bytes = bytes_size.to_le_bytes(); // Wasm is little-endian
if let Err(error) = self.try_get_memory()?.set(bytes_written_ptr, &size_bytes) {
return Err(ExecError::Interpreter(error.into()).into());
}
Ok(Ok(()))
}
fn has_key(&mut self, name_ptr: u32, name_size: u32) -> Result<i32, Trap> {
let name = self.string_from_mem(name_ptr, name_size)?;
if self.context.named_keys_contains_key(&name) {
Ok(0)
} else {
Ok(1)
}
}
fn put_key(
&mut self,
name_ptr: u32,
name_size: u32,
key_ptr: u32,
key_size: u32,
) -> Result<(), Trap> {
let name = self.string_from_mem(name_ptr, name_size)?;
let key = self.key_from_mem(key_ptr, key_size)?;
self.context.put_key(name, key).map_err(Into::into)
}
fn remove_key(&mut self, name_ptr: u32, name_size: u32) -> Result<(), Trap> {
let name = self.string_from_mem(name_ptr, name_size)?;
self.context.remove_key(&name)?;
Ok(())
}
/// Writes runtime context's account main purse to dest_ptr in the Wasm memory.
fn get_main_purse(&mut self, dest_ptr: u32) -> Result<(), Trap> {
let purse = self.context.get_main_purse()?;
let purse_bytes = purse.into_bytes().map_err(ExecError::BytesRepr)?;
self.try_get_memory()?
.set(dest_ptr, &purse_bytes)
.map_err(|e| ExecError::Interpreter(e.into()).into())
}
/// Writes caller (deploy) account public key to dest_ptr in the Wasm
/// memory.
fn get_caller(&mut self, output_size: u32) -> Result<Result<(), ApiError>, Trap> {
if !self.can_write_to_host_buffer() {
// Exit early if the host buffer is already occupied
return Ok(Err(ApiError::HostBufferFull));
}
let value = CLValue::from_t(self.context.get_caller()).map_err(ExecError::CLValue)?;
let value_size = value.inner_bytes().len();
// Save serialized public key into host buffer
if let Err(error) = self.write_host_buffer(value) {
return Ok(Err(error));
}
// Write output
let output_size_bytes = value_size.to_le_bytes(); // Wasm is little-endian
if let Err(error) = self.try_get_memory()?.set(output_size, &output_size_bytes) {
return Err(ExecError::Interpreter(error.into()).into());
}
Ok(Ok(()))
}
/// Gets the immediate caller of the current execution
fn get_immediate_caller(&self) -> Option<&RuntimeStackFrame> {
self.stack.as_ref().and_then(|stack| stack.previous_frame())
}
/// Checks if immediate caller is of session type of the same account as the provided account
/// hash.
fn is_allowed_session_caller(&self, provided_account_hash: &AccountHash) -> bool {
if self.context.get_caller() == PublicKey::System.to_account_hash() {
return true;
}
if let Some(Caller::Initiator { account_hash }) = self.get_immediate_caller() {
return account_hash == provided_account_hash;
}
false
}
/// Writes runtime context's phase to dest_ptr in the Wasm memory.
fn get_phase(&mut self, dest_ptr: u32) -> Result<(), Trap> {
let phase = self.context.phase();
let bytes = phase.into_bytes().map_err(ExecError::BytesRepr)?;
self.try_get_memory()?
.set(dest_ptr, &bytes)
.map_err(|e| ExecError::Interpreter(e.into()).into())
}
/// Writes current blocktime to dest_ptr in Wasm memory.
fn get_blocktime(&self, dest_ptr: u32) -> Result<(), Trap> {
let blocktime = self
.context
.get_blocktime()
.into_bytes()
.map_err(ExecError::BytesRepr)?;
self.try_get_memory()?
.set(dest_ptr, &blocktime)
.map_err(|e| ExecError::Interpreter(e.into()).into())
}
/// Load the uref known by the given name into the Wasm memory
fn load_call_stack(
&mut self,
// (Output) Pointer to number of elements in the call stack.
call_stack_len_ptr: u32,
// (Output) Pointer to size in bytes of the serialized call stack.
result_size_ptr: u32,
) -> Result<Result<(), ApiError>, Trap> {
if !self.can_write_to_host_buffer() {
// Exit early if the host buffer is already occupied
return Ok(Err(ApiError::HostBufferFull));
}
let call_stack = match self.try_get_stack() {
Ok(stack) => stack.call_stack_elements(),
Err(_error) => return Ok(Err(ApiError::Unhandled)),
};
let call_stack_len: u32 = match call_stack.len().try_into() {
Ok(value) => value,
Err(_) => return Ok(Err(ApiError::OutOfMemory)),
};
let call_stack_len_bytes = call_stack_len.to_le_bytes();
if let Err(error) = self
.try_get_memory()?
.set(call_stack_len_ptr, &call_stack_len_bytes)
{
return Err(ExecError::Interpreter(error.into()).into());
}
if call_stack_len == 0 {
return Ok(Ok(()));
}
let call_stack_cl_value = CLValue::from_t(call_stack).map_err(ExecError::CLValue)?;
let call_stack_cl_value_bytes_len: u32 =
match call_stack_cl_value.inner_bytes().len().try_into() {
Ok(value) => value,
Err(_) => return Ok(Err(ApiError::OutOfMemory)),
};
if let Err(error) = self.write_host_buffer(call_stack_cl_value) {
return Ok(Err(error));
}
let call_stack_cl_value_bytes_len_bytes = call_stack_cl_value_bytes_len.to_le_bytes();
if let Err(error) = self
.try_get_memory()?
.set(result_size_ptr, &call_stack_cl_value_bytes_len_bytes)
{
return Err(ExecError::Interpreter(error.into()).into());
}
Ok(Ok(()))
}
/// Return some bytes from the memory and terminate the current `sub_call`. Note that the return
/// type is `Trap`, indicating that this function will always kill the current Wasm instance.
fn ret(&mut self, value_ptr: u32, value_size: usize) -> Trap {
self.host_buffer = None;
let mem_get =
self.checked_memory_slice(value_ptr as usize, value_size, |data| data.to_vec());
match mem_get {
Ok(buf) => {
// Set the result field in the runtime and return the proper element of the `Error`
// enum indicating that the reason for exiting the module was a call to ret.
self.host_buffer = bytesrepr::deserialize_from_slice(buf).ok();
let urefs = match &self.host_buffer {
Some(buf) => utils::extract_urefs(buf),
None => Ok(vec![]),
};
match urefs {
Ok(urefs) => {
for uref in &urefs {
if let Err(error) = self.context.validate_uref(uref) {
return Trap::from(error);
}
}
ExecError::Ret(urefs).into()
}
Err(e) => e.into(),
}
}
Err(e) => e.into(),
}
}
/// Checks if a [`Key`] is a system contract.
fn is_system_contract(&self, entity_hash: AddressableEntityHash) -> Result<bool, ExecError> {
self.context.is_system_addressable_entity(&entity_hash)
}
fn get_named_argument<T: FromBytes + CLTyped>(
args: &RuntimeArgs,
name: &str,
) -> Result<T, ExecError> {
let arg: CLValue = args
.get(name)
.cloned()
.ok_or(ExecError::Revert(ApiError::MissingArgument))?;
arg.into_t()
.map_err(|_| ExecError::Revert(ApiError::InvalidArgument))
}
fn reverter<T: Into<ApiError>>(error: T) -> ExecError {
let api_error: ApiError = error.into();
// NOTE: This is special casing needed to keep the native system contracts propagate
// GasLimit properly to the user. Once support for wasm system contract will be dropped this
// won't be necessary anymore.
match api_error {
ApiError::Mint(mint_error) if mint_error == mint::Error::GasLimit as u8 => {
ExecError::GasLimit
}
ApiError::AuctionError(auction_error)
if auction_error == auction::Error::GasLimit as u8 =>
{
ExecError::GasLimit
}
ApiError::HandlePayment(handle_payment_error)
if handle_payment_error == handle_payment::Error::GasLimit as u8 =>
{
ExecError::GasLimit
}
api_error => ExecError::Revert(api_error),
}
}
/// Calls host mint contract.
fn call_host_mint(
&mut self,
entry_point_name: &str,
runtime_args: &RuntimeArgs,
access_rights: ContextAccessRights,
stack: RuntimeStack,
) -> Result<CLValue, ExecError> {
let gas_counter = self.gas_counter();
let mint_hash = self.context.get_system_contract(MINT)?;
let mint_addr = EntityAddr::new_system(mint_hash.value());
let mint_named_keys = self
.context
.state()
.borrow_mut()
.get_named_keys(mint_addr)?;
let mut named_keys = mint_named_keys;
let runtime_context = self.context.new_from_self(
mint_addr.into(),
EntryPointType::Called,
&mut named_keys,
access_rights,
runtime_args.to_owned(),
);
let mut mint_runtime = self.new_with_stack(runtime_context, stack);
let engine_config = self.context.engine_config();
let system_config = engine_config.system_config();
let mint_costs = system_config.mint_costs();
let result = match entry_point_name {
// Type: `fn mint(amount: U512) -> Result<URef, ExecError>`
mint::METHOD_MINT => (|| {
mint_runtime.charge_system_contract_call(mint_costs.mint)?;
let amount: U512 = Self::get_named_argument(runtime_args, mint::ARG_AMOUNT)?;
let result: Result<URef, mint::Error> = mint_runtime.mint(amount);
if let Err(mint::Error::GasLimit) = result {
return Err(ExecError::GasLimit);
}
CLValue::from_t(result).map_err(Self::reverter)
})(),
mint::METHOD_REDUCE_TOTAL_SUPPLY => (|| {
mint_runtime.charge_system_contract_call(mint_costs.reduce_total_supply)?;
let amount: U512 = Self::get_named_argument(runtime_args, mint::ARG_AMOUNT)?;
let result: Result<(), mint::Error> = mint_runtime.reduce_total_supply(amount);
CLValue::from_t(result).map_err(Self::reverter)
})(),
mint::METHOD_BURN => (|| {
mint_runtime.charge_system_contract_call(mint_costs.burn)?;
let purse: URef = Self::get_named_argument(runtime_args, mint::ARG_PURSE)?;
let amount: U512 = Self::get_named_argument(runtime_args, mint::ARG_AMOUNT)?;
let result: Result<(), mint::Error> = mint_runtime.burn(purse, amount);
CLValue::from_t(result).map_err(Self::reverter)
})(),
// Type: `fn create() -> URef`
mint::METHOD_CREATE => (|| {
mint_runtime.charge_system_contract_call(mint_costs.create)?;
let uref = mint_runtime.mint(U512::zero()).map_err(Self::reverter)?;
CLValue::from_t(uref).map_err(Self::reverter)
})(),
// Type: `fn balance(purse: URef) -> Option<U512>`
mint::METHOD_BALANCE => (|| {
mint_runtime.charge_system_contract_call(mint_costs.balance)?;
let uref: URef = Self::get_named_argument(runtime_args, mint::ARG_PURSE)?;
let maybe_balance: Option<U512> =
mint_runtime.balance(uref).map_err(Self::reverter)?;
CLValue::from_t(maybe_balance).map_err(Self::reverter)
})(),
// Type: `fn transfer(maybe_to: Option<AccountHash>, source: URef, target: URef, amount:
// U512, id: Option<u64>) -> Result<(), ExecError>`
mint::METHOD_TRANSFER => (|| {
mint_runtime.charge_system_contract_call(mint_costs.transfer)?;
let maybe_to: Option<AccountHash> =
Self::get_named_argument(runtime_args, mint::ARG_TO)?;
let source: URef = Self::get_named_argument(runtime_args, mint::ARG_SOURCE)?;
let target: URef = Self::get_named_argument(runtime_args, mint::ARG_TARGET)?;
let amount: U512 = Self::get_named_argument(runtime_args, mint::ARG_AMOUNT)?;
let id: Option<u64> = Self::get_named_argument(runtime_args, mint::ARG_ID)?;
let result: Result<(), mint::Error> =
mint_runtime.transfer(maybe_to, source, target, amount, id);
CLValue::from_t(result).map_err(Self::reverter)
})(),
// Type: `fn read_base_round_reward() -> Result<U512, ExecError>`
mint::METHOD_READ_BASE_ROUND_REWARD => (|| {
mint_runtime.charge_system_contract_call(mint_costs.read_base_round_reward)?;
let result: U512 = mint_runtime
.read_base_round_reward()
.map_err(Self::reverter)?;
CLValue::from_t(result).map_err(Self::reverter)
})(),
mint::METHOD_MINT_INTO_EXISTING_PURSE => (|| {
mint_runtime.charge_system_contract_call(mint_costs.mint_into_existing_purse)?;
let amount: U512 = Self::get_named_argument(runtime_args, mint::ARG_AMOUNT)?;
let existing_purse: URef = Self::get_named_argument(runtime_args, mint::ARG_PURSE)?;
let result: Result<(), mint::Error> =
mint_runtime.mint_into_existing_purse(existing_purse, amount);
CLValue::from_t(result).map_err(Self::reverter)
})(),
_ => CLValue::from_t(()).map_err(Self::reverter),
};
// Charge just for the amount that particular entry point cost - using gas cost from the
// isolated runtime might have a recursive costs whenever system contract calls other system
// contract.
self.gas(
mint_runtime
.gas_counter()
.checked_sub(gas_counter)
.unwrap_or(gas_counter),
)?;
// Result still contains a result, but the entrypoints logic does not exit early on errors.
let ret = result?;
// Update outer spending approved limit.
self.context
.set_remaining_spending_limit(mint_runtime.context.remaining_spending_limit());
let urefs = utils::extract_urefs(&ret)?;
self.context.access_rights_extend(&urefs);
{
let transfers = self.context.transfers_mut();
*transfers = mint_runtime.context.transfers().to_owned();
}
Ok(ret)
}
/// Calls host `handle_payment` contract.
fn call_host_handle_payment(
&mut self,
entry_point_name: &str,
runtime_args: &RuntimeArgs,
access_rights: ContextAccessRights,
stack: RuntimeStack,
) -> Result<CLValue, ExecError> {
let gas_counter = self.gas_counter();
let handle_payment_hash = self.context.get_system_contract(HANDLE_PAYMENT)?;
let handle_payment_key =
Key::addressable_entity_key(EntityKindTag::System, handle_payment_hash);
let handle_payment_named_keys = self
.context
.state()
.borrow_mut()
.get_named_keys(EntityAddr::System(handle_payment_hash.value()))?;
let mut named_keys = handle_payment_named_keys;
let runtime_context = self.context.new_from_self(
handle_payment_key,
EntryPointType::Called,
&mut named_keys,
access_rights,
runtime_args.to_owned(),
);
let mut runtime = self.new_with_stack(runtime_context, stack);
let engine_config = self.context.engine_config();
let system_config = engine_config.system_config();
let handle_payment_costs = system_config.handle_payment_costs();
let result = match entry_point_name {
handle_payment::METHOD_GET_PAYMENT_PURSE => (|| {
runtime.charge_system_contract_call(handle_payment_costs.get_payment_purse)?;
let rights_controlled_purse =
runtime.get_payment_purse().map_err(Self::reverter)?;
CLValue::from_t(rights_controlled_purse).map_err(Self::reverter)
})(),
handle_payment::METHOD_SET_REFUND_PURSE => (|| {
runtime.charge_system_contract_call(handle_payment_costs.set_refund_purse)?;
let purse: URef =
Self::get_named_argument(runtime_args, handle_payment::ARG_PURSE)?;
runtime.set_refund_purse(purse).map_err(Self::reverter)?;
CLValue::from_t(()).map_err(Self::reverter)
})(),
handle_payment::METHOD_GET_REFUND_PURSE => (|| {
runtime.charge_system_contract_call(handle_payment_costs.get_refund_purse)?;
let maybe_purse = runtime.get_refund_purse().map_err(Self::reverter)?;
CLValue::from_t(maybe_purse).map_err(Self::reverter)
})(),
_ => CLValue::from_t(()).map_err(Self::reverter),
};
self.gas(
runtime
.gas_counter()
.checked_sub(gas_counter)
.unwrap_or(gas_counter),
)?;
let ret = result?;
let urefs = utils::extract_urefs(&ret)?;
self.context.access_rights_extend(&urefs);
{
let transfers = self.context.transfers_mut();
*transfers = runtime.context.transfers().to_owned();
}
Ok(ret)
}
/// Calls host auction contract.
fn call_host_auction(
&mut self,
entry_point_name: &str,
runtime_args: &RuntimeArgs,
access_rights: ContextAccessRights,
stack: RuntimeStack,
) -> Result<CLValue, ExecError> {
let gas_counter = self.gas_counter();
let auction_hash = self.context.get_system_contract(AUCTION)?;
let auction_key = Key::addressable_entity_key(EntityKindTag::System, auction_hash);
let auction_named_keys = self
.context
.state()
.borrow_mut()
.get_named_keys(EntityAddr::System(auction_hash.value()))?;
let mut named_keys = auction_named_keys;
let runtime_context = self.context.new_from_self(
auction_key,
EntryPointType::Called,
&mut named_keys,
access_rights,
runtime_args.to_owned(),
);
let mut runtime = self.new_with_stack(runtime_context, stack);
let engine_config = self.context.engine_config();
let system_config = engine_config.system_config();
let auction_costs = system_config.auction_costs();
let result = match entry_point_name {
auction::METHOD_GET_ERA_VALIDATORS => (|| {
runtime
.context
.charge_gas(auction_costs.get_era_validators.into())?;
let result = runtime.get_era_validators().map_err(Self::reverter)?;
CLValue::from_t(result).map_err(Self::reverter)
})(),
auction::METHOD_ADD_BID => (|| {
runtime.charge_system_contract_call(auction_costs.add_bid)?;
let account_hash = Self::get_named_argument(runtime_args, auction::ARG_PUBLIC_KEY)?;
let delegation_rate =
Self::get_named_argument(runtime_args, auction::ARG_DELEGATION_RATE)?;
let amount = Self::get_named_argument(runtime_args, auction::ARG_AMOUNT)?;
let inactive_validator_undelegation_delay: Option<u64> = Self::get_named_argument(
runtime_args,
auction::ARG_INACTIVE_VALIDATOR_UNDELEGATION_DELAY,
)?;
let maximum_inactive_validator_undelegation_delay = self
.context()
.engine_config()
.inactive_validator_undelegation_delay();
let result = runtime
.add_bid(
account_hash,
delegation_rate,
amount,
inactive_validator_undelegation_delay,
maximum_inactive_validator_undelegation_delay,
)
.map_err(Self::reverter)?;
CLValue::from_t(result).map_err(Self::reverter)
})(),
auction::METHOD_WITHDRAW_BID => (|| {
runtime.charge_system_contract_call(auction_costs.withdraw_bid)?;
let account_hash = Self::get_named_argument(runtime_args, auction::ARG_PUBLIC_KEY)?;
let amount = Self::get_named_argument(runtime_args, auction::ARG_AMOUNT)?;
let result = runtime
.withdraw_bid(account_hash, amount)
.map_err(Self::reverter)?;
CLValue::from_t(result).map_err(Self::reverter)
})(),
auction::METHOD_DELEGATE => (|| {
runtime.charge_system_contract_call(auction_costs.delegate)?;
let delegator = Self::get_named_argument(runtime_args, auction::ARG_DELEGATOR)?;
let validator = Self::get_named_argument(runtime_args, auction::ARG_VALIDATOR)?;
let amount = Self::get_named_argument(runtime_args, auction::ARG_AMOUNT)?;
let max_delegators_per_validator =
self.context.engine_config().max_delegators_per_validator();
let minimum_delegation_amount =
self.context.engine_config().minimum_delegation_amount();
let result = runtime
.delegate(
delegator,
validator,
amount,
max_delegators_per_validator,
minimum_delegation_amount,
)
.map_err(Self::reverter)?;
CLValue::from_t(result).map_err(Self::reverter)
})(),
auction::METHOD_UNDELEGATE => (|| {
runtime.charge_system_contract_call(auction_costs.undelegate)?;
let delegator = Self::get_named_argument(runtime_args, auction::ARG_DELEGATOR)?;
let validator = Self::get_named_argument(runtime_args, auction::ARG_VALIDATOR)?;
let amount = Self::get_named_argument(runtime_args, auction::ARG_AMOUNT)?;
let result = runtime
.undelegate(delegator, validator, amount)
.map_err(Self::reverter)?;
CLValue::from_t(result).map_err(Self::reverter)
})(),
auction::METHOD_REDELEGATE => (|| {
runtime.charge_system_contract_call(auction_costs.redelegate)?;
let delegator = Self::get_named_argument(runtime_args, auction::ARG_DELEGATOR)?;
let validator = Self::get_named_argument(runtime_args, auction::ARG_VALIDATOR)?;
let amount = Self::get_named_argument(runtime_args, auction::ARG_AMOUNT)?;
let new_validator =
Self::get_named_argument(runtime_args, auction::ARG_NEW_VALIDATOR)?;
let minimum_delegation_amount =
self.context.engine_config().minimum_delegation_amount();
let result = runtime
.redelegate(
delegator,
validator,
amount,
new_validator,
minimum_delegation_amount,
)
.map_err(Self::reverter)?;
CLValue::from_t(result).map_err(Self::reverter)
})(),
auction::METHOD_RUN_AUCTION => (|| {
runtime.charge_system_contract_call(auction_costs.run_auction)?;
let era_end_timestamp_millis =
Self::get_named_argument(runtime_args, auction::ARG_ERA_END_TIMESTAMP_MILLIS)?;
let evicted_validators =
Self::get_named_argument(runtime_args, auction::ARG_EVICTED_VALIDATORS)?;
let max_delegators_per_validator =
self.context.engine_config().max_delegators_per_validator();
let minimum_delegation_amount =
self.context.engine_config().minimum_delegation_amount();
runtime
.run_auction(
era_end_timestamp_millis,
evicted_validators,
max_delegators_per_validator,
minimum_delegation_amount,
)
.map_err(Self::reverter)?;
CLValue::from_t(()).map_err(Self::reverter)
})(),
// Type: `fn slash(validator_account_hashes: &[AccountHash]) -> Result<(), ExecError>`
auction::METHOD_SLASH => (|| {
runtime.context.charge_gas(auction_costs.slash.into())?;
let validator_public_keys =
Self::get_named_argument(runtime_args, auction::ARG_VALIDATOR_PUBLIC_KEYS)?;
runtime
.slash(validator_public_keys)
.map_err(Self::reverter)?;
CLValue::from_t(()).map_err(Self::reverter)
})(),
// Type: `fn distribute(reward_factors: BTreeMap<PublicKey, u64>) -> Result<(),
// ExecError>`
auction::METHOD_DISTRIBUTE => (|| {
runtime
.context
.charge_gas(auction_costs.distribute.into())?;
let rewards = Self::get_named_argument(runtime_args, auction::ARG_REWARDS_MAP)?;
runtime.distribute(rewards).map_err(Self::reverter)?;
CLValue::from_t(()).map_err(Self::reverter)
})(),
// Type: `fn read_era_id() -> Result<EraId, ExecError>`
auction::METHOD_READ_ERA_ID => (|| {
runtime
.context
.charge_gas(auction_costs.read_era_id.into())?;
let result = runtime.read_era_id().map_err(Self::reverter)?;
CLValue::from_t(result).map_err(Self::reverter)
})(),
auction::METHOD_ACTIVATE_BID => (|| {
runtime.charge_system_contract_call(auction_costs.activate_bid)?;
let validator = Self::get_named_argument(runtime_args, auction::ARG_VALIDATOR)?;
runtime.activate_bid(validator).map_err(Self::reverter)?;
CLValue::from_t(()).map_err(Self::reverter)
})(),
auction::METHOD_CHANGE_BID_PUBLIC_KEY => (|| {
runtime.charge_system_contract_call(auction_costs.change_bid_public_key)?;
let public_key = Self::get_named_argument(runtime_args, auction::ARG_PUBLIC_KEY)?;
let new_public_key =