-
Notifications
You must be signed in to change notification settings - Fork 653
/
logic.rs
2468 lines (2301 loc) · 100 KB
/
logic.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 crate::context::VMContext;
use crate::dependencies::{External, MemoryLike};
use crate::gas_counter::GasCounter;
use crate::types::{PromiseIndex, PromiseResult, ReceiptIndex, ReturnData};
use crate::utils::split_method_names;
use crate::ValuePtr;
use byteorder::ByteOrder;
use near_primitives::checked_feature;
use near_primitives::version::is_implicit_account_creation_enabled;
use near_primitives_core::config::ExtCosts::*;
use near_primitives_core::config::{ActionCosts, ExtCosts, VMConfig};
use near_primitives_core::profile::ProfileData;
use near_primitives_core::runtime::fees::{
transfer_exec_fee, transfer_send_fee, RuntimeFeesConfig,
};
use near_primitives_core::types::{
AccountId, Balance, EpochHeight, Gas, ProtocolVersion, StorageUsage,
};
use near_runtime_utils::is_account_id_64_len_hex;
use near_vm_errors::InconsistentStateError;
use near_vm_errors::{HostError, VMLogicError};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::mem::size_of;
pub type Result<T> = ::std::result::Result<T, VMLogicError>;
const LEGACY_DEFAULT_PROTOCOL_VERSION: ProtocolVersion = 34;
pub struct VMLogic<'a> {
/// Provides access to the components outside the Wasm runtime for operations on the trie and
/// receipts creation.
ext: &'a mut dyn External,
/// Part of Context API and Economics API that was extracted from the receipt.
context: VMContext,
/// Parameters of Wasm and economic parameters.
config: &'a VMConfig,
/// Fees for creating (async) actions on runtime.
fees_config: &'a RuntimeFeesConfig,
/// If this method execution is invoked directly as a callback by one or more contract calls the
/// results of the methods that made the callback are stored in this collection.
promise_results: &'a [PromiseResult],
/// Pointer to the guest memory.
memory: &'a mut dyn MemoryLike,
/// Keeping track of the current account balance, which can decrease when we create promises
/// and attach balance to them.
current_account_balance: Balance,
/// Current amount of locked tokens, does not automatically change when staking transaction is
/// issued.
current_account_locked_balance: Balance,
/// Storage usage of the current account at the moment
current_storage_usage: StorageUsage,
gas_counter: GasCounter,
/// What method returns.
return_data: ReturnData,
/// Logs written by the runtime.
logs: Vec<String>,
/// Registers can be used by the guest to store blobs of data without moving them across
/// host-guest boundary.
registers: HashMap<u64, Vec<u8>>,
/// The DAG of promises, indexed by promise id.
promises: Vec<Promise>,
/// Record the accounts towards which the receipts are directed.
receipt_to_account: HashMap<ReceiptIndex, AccountId>,
/// Tracks the total log length. The sum of length of all logs.
total_log_length: u64,
/// Current protocol version that is used for the function call.
current_protocol_version: ProtocolVersion,
}
/// Promises API allows to create a DAG-structure that defines dependencies between smart contract
/// calls. A single promise can be created with zero or several dependencies on other promises.
/// * If a promise was created from a receipt (using `promise_create` or `promise_then`) it's a
/// `Receipt`;
/// * If a promise was created by merging several promises (using `promise_and`) then
/// it's a `NotReceipt`, but has receipts of all promises it depends on.
#[derive(Debug)]
enum Promise {
Receipt(ReceiptIndex),
NotReceipt(Vec<ReceiptIndex>),
}
macro_rules! memory_get {
($_type:ty, $name:ident) => {
fn $name(&mut self, offset: u64) -> Result<$_type> {
let mut array = [0u8; size_of::<$_type>()];
self.memory_get_into(offset, &mut array)?;
Ok(<$_type>::from_le_bytes(array))
}
};
}
macro_rules! memory_set {
($_type:ty, $name:ident) => {
fn $name(&mut self, offset: u64, value: $_type) -> Result<()> {
self.memory_set_slice(offset, &value.to_le_bytes())
}
};
}
impl<'a> VMLogic<'a> {
pub fn new_with_protocol_version(
ext: &'a mut dyn External,
context: VMContext,
config: &'a VMConfig,
fees_config: &'a RuntimeFeesConfig,
promise_results: &'a [PromiseResult],
memory: &'a mut dyn MemoryLike,
profile: ProfileData,
current_protocol_version: ProtocolVersion,
) -> Self {
ext.reset_touched_nodes_counter();
// Overflow should be checked before calling VMLogic.
let current_account_balance = context.account_balance + context.attached_deposit;
let current_storage_usage = context.storage_usage;
let max_gas_burnt = if context.is_view {
config.limit_config.max_gas_burnt_view
} else {
config.limit_config.max_gas_burnt
};
let current_account_locked_balance = context.account_locked_balance;
let gas_counter = GasCounter::new(
config.ext_costs.clone(),
max_gas_burnt,
context.prepaid_gas,
context.is_view,
profile,
);
Self {
ext,
context,
config,
fees_config,
promise_results,
memory,
current_account_balance,
current_account_locked_balance,
current_storage_usage,
gas_counter,
return_data: ReturnData::None,
logs: vec![],
registers: HashMap::new(),
promises: vec![],
receipt_to_account: HashMap::new(),
total_log_length: 0,
current_protocol_version,
}
}
/// Legacy initialization method that doesn't pass the protocol version and uses the last
/// protocol version before the change was introduced.
pub fn new(
ext: &'a mut dyn External,
context: VMContext,
config: &'a VMConfig,
fees_config: &'a RuntimeFeesConfig,
promise_results: &'a [PromiseResult],
memory: &'a mut dyn MemoryLike,
profile: ProfileData,
) -> Self {
Self::new_with_protocol_version(
ext,
context,
config,
fees_config,
promise_results,
memory,
profile,
LEGACY_DEFAULT_PROTOCOL_VERSION,
)
}
// ###########################
// # Memory helper functions #
// ###########################
fn try_fit_mem(&mut self, offset: u64, len: u64) -> Result<()> {
if self.memory.fits_memory(offset, len) {
Ok(())
} else {
Err(HostError::MemoryAccessViolation.into())
}
}
fn memory_get_into(&mut self, offset: u64, buf: &mut [u8]) -> Result<()> {
self.gas_counter.pay_base(read_memory_base)?;
self.gas_counter.pay_per_byte(read_memory_byte, buf.len() as _)?;
self.try_fit_mem(offset, buf.len() as _)?;
self.memory.read_memory(offset, buf);
Ok(())
}
fn memory_get_vec(&mut self, offset: u64, len: u64) -> Result<Vec<u8>> {
self.gas_counter.pay_base(read_memory_base)?;
self.gas_counter.pay_per_byte(read_memory_byte, len)?;
self.try_fit_mem(offset, len)?;
let mut buf = vec![0; len as usize];
self.memory.read_memory(offset, &mut buf);
Ok(buf)
}
memory_get!(u128, memory_get_u128);
memory_get!(u32, memory_get_u32);
memory_get!(u16, memory_get_u16);
memory_get!(u8, memory_get_u8);
/// Reads an array of `u64` elements.
fn memory_get_vec_u64(&mut self, offset: u64, num_elements: u64) -> Result<Vec<u64>> {
let memory_len = num_elements
.checked_mul(size_of::<u64>() as u64)
.ok_or(HostError::MemoryAccessViolation)?;
let data = self.memory_get_vec(offset, memory_len)?;
let mut res = vec![0u64; num_elements as usize];
byteorder::LittleEndian::read_u64_into(&data, &mut res);
Ok(res)
}
fn get_vec_from_memory_or_register(&mut self, offset: u64, len: u64) -> Result<Vec<u8>> {
if len != std::u64::MAX {
self.memory_get_vec(offset, len)
} else {
self.internal_read_register(offset)
}
}
fn memory_set_slice(&mut self, offset: u64, buf: &[u8]) -> Result<()> {
self.gas_counter.pay_base(write_memory_base)?;
self.gas_counter.pay_per_byte(write_memory_byte, buf.len() as _)?;
self.try_fit_mem(offset, buf.len() as _)?;
self.memory.write_memory(offset, buf);
Ok(())
}
memory_set!(u128, memory_set_u128);
// #################
// # Registers API #
// #################
fn internal_read_register(&mut self, register_id: u64) -> Result<Vec<u8>> {
if let Some(data) = self.registers.get(®ister_id) {
self.gas_counter.pay_base(read_register_base)?;
self.gas_counter.pay_per_byte(read_register_byte, data.len() as _)?;
Ok(data.clone())
} else {
Err(HostError::InvalidRegisterId { register_id }.into())
}
}
fn internal_write_register(&mut self, register_id: u64, data: Vec<u8>) -> Result<()> {
self.gas_counter.pay_base(write_register_base)?;
self.gas_counter.pay_per_byte(write_register_byte, data.len() as u64)?;
if data.len() as u64 > self.config.limit_config.max_register_size
|| self.registers.len() as u64 >= self.config.limit_config.max_number_registers
{
return Err(HostError::MemoryAccessViolation.into());
}
self.registers.insert(register_id, data);
// Calculate the new memory usage.
let usage: usize =
self.registers.values().map(|v| size_of::<u64>() + v.len() * size_of::<u8>()).sum();
if usage as u64 > self.config.limit_config.registers_memory_limit {
Err(HostError::MemoryAccessViolation.into())
} else {
Ok(())
}
}
/// Convenience function for testing.
pub fn wrapped_internal_write_register(&mut self, register_id: u64, data: &[u8]) -> Result<()> {
self.internal_write_register(register_id, data.to_vec())
}
/// Writes the entire content from the register `register_id` into the memory of the guest starting with `ptr`.
///
/// # Arguments
///
/// * `register_id` -- a register id from where to read the data;
/// * `ptr` -- location on guest memory where to copy the data.
///
/// # Errors
///
/// * If the content extends outside the memory allocated to the guest. In Wasmer, it returns `MemoryAccessViolation` error message;
/// * If `register_id` is pointing to unused register returns `InvalidRegisterId` error message.
///
/// # Undefined Behavior
///
/// If the content of register extends outside the preallocated memory on the host side, or the pointer points to a
/// wrong location this function will overwrite memory that it is not supposed to overwrite causing an undefined behavior.
///
/// # Cost
///
/// `base + read_register_base + read_register_byte * num_bytes + write_memory_base + write_memory_byte * num_bytes`
pub fn read_register(&mut self, register_id: u64, ptr: u64) -> Result<()> {
self.gas_counter.pay_base(base)?;
let data = self.internal_read_register(register_id)?;
self.memory_set_slice(ptr, &data)
}
/// Returns the size of the blob stored in the given register.
/// * If register is used, then returns the size, which can potentially be zero;
/// * If register is not used, returns `u64::MAX`
///
/// # Arguments
///
/// * `register_id` -- a register id from where to read the data;
///
/// # Cost
///
/// `base`
pub fn register_len(&mut self, register_id: u64) -> Result<u64> {
self.gas_counter.pay_base(base)?;
Ok(self.registers.get(®ister_id).map(|r| r.len() as _).unwrap_or(std::u64::MAX))
}
/// Copies `data` from the guest memory into the register. If register is unused will initialize
/// it. If register has larger capacity than needed for `data` will not re-allocate it. The
/// register will lose the pre-existing data if any.
///
/// # Arguments
///
/// * `register_id` -- a register id where to write the data;
/// * `data_len` -- length of the data in bytes;
/// * `data_ptr` -- pointer in the guest memory where to read the data from.
///
/// # Cost
///
/// `base + read_memory_base + read_memory_bytes * num_bytes + write_register_base + write_register_bytes * num_bytes`
pub fn write_register(&mut self, register_id: u64, data_len: u64, data_ptr: u64) -> Result<()> {
self.gas_counter.pay_base(base)?;
let data = self.memory_get_vec(data_ptr, data_len)?;
self.internal_write_register(register_id, data)
}
// ###################################
// # String reading helper functions #
// ###################################
/// Helper function to read and return utf8-encoding string.
/// If `len == u64::MAX` then treats the string as null-terminated with character `'\0'`.
///
/// # Errors
///
/// * If string extends outside the memory of the guest with `MemoryAccessViolation`;
/// * If string is not UTF-8 returns `BadUtf8`.
/// * If number of bytes read + `total_log_length` exceeds the `max_total_log_length` returns
/// `TotalLogLengthExceeded`.
///
/// # Cost
///
/// For not nul-terminated string:
/// `read_memory_base + read_memory_byte * num_bytes + utf8_decoding_base + utf8_decoding_byte * num_bytes`
///
/// For nul-terminated string:
/// `(read_memory_base + read_memory_byte) * num_bytes + utf8_decoding_base + utf8_decoding_byte * num_bytes`
fn get_utf8_string(&mut self, len: u64, ptr: u64) -> Result<String> {
self.gas_counter.pay_base(utf8_decoding_base)?;
let mut buf;
let max_len =
self.config.limit_config.max_total_log_length.saturating_sub(self.total_log_length);
if len != std::u64::MAX {
if len > max_len {
return Err(HostError::TotalLogLengthExceeded {
length: self.total_log_length.saturating_add(len),
limit: self.config.limit_config.max_total_log_length,
}
.into());
}
buf = self.memory_get_vec(ptr, len)?;
} else {
buf = vec![];
for i in 0..=max_len {
// self.try_fit_mem will check for u64 overflow on the first iteration (i == 0)
let el = self.memory_get_u8(ptr + i)?;
if el == 0 {
break;
}
if i == max_len {
return Err(HostError::TotalLogLengthExceeded {
length: self.total_log_length.saturating_add(max_len).saturating_add(1),
limit: self.config.limit_config.max_total_log_length,
}
.into());
}
buf.push(el);
}
}
self.gas_counter.pay_per_byte(utf8_decoding_byte, buf.len() as _)?;
String::from_utf8(buf).map_err(|_| HostError::BadUTF8.into())
}
/// Helper function to read UTF-16 formatted string from guest memory.
/// # Errors
///
/// * If string extends outside the memory of the guest with `MemoryAccessViolation`;
/// * If string is not UTF-16 returns `BadUtf16`.
/// * If number of bytes read + `total_log_length` exceeds the `max_total_log_length` returns
/// `TotalLogLengthExceeded`.
///
/// # Cost
///
/// For not nul-terminated string:
/// `read_memory_base + read_memory_byte * num_bytes + utf16_decoding_base + utf16_decoding_byte * num_bytes`
///
/// For nul-terminated string:
/// `read_memory_base * num_bytes / 2 + read_memory_byte * num_bytes + utf16_decoding_base + utf16_decoding_byte * num_bytes`
fn get_utf16_string(&mut self, len: u64, ptr: u64) -> Result<String> {
self.gas_counter.pay_base(utf16_decoding_base)?;
let mut u16_buffer;
let max_len =
self.config.limit_config.max_total_log_length.saturating_sub(self.total_log_length);
if len != std::u64::MAX {
let input = self.memory_get_vec(ptr, len)?;
if len % 2 != 0 {
return Err(HostError::BadUTF16.into());
}
if len > max_len {
return Err(HostError::TotalLogLengthExceeded {
length: self.total_log_length.saturating_add(len),
limit: self.config.limit_config.max_total_log_length,
}
.into());
}
u16_buffer = vec![0u16; len as usize / 2];
byteorder::LittleEndian::read_u16_into(&input, &mut u16_buffer);
} else {
u16_buffer = vec![];
let limit = max_len / size_of::<u16>() as u64;
// Takes 2 bytes each iter
for i in 0..=limit {
// self.try_fit_mem will check for u64 overflow on the first iteration (i == 0)
let start = ptr + i * size_of::<u16>() as u64;
let el = self.memory_get_u16(start)?;
if el == 0 {
break;
}
if i == limit {
return Err(HostError::TotalLogLengthExceeded {
length: self
.total_log_length
.saturating_add(i * size_of::<u16>() as u64)
.saturating_add(size_of::<u16>() as u64),
limit: self.config.limit_config.max_total_log_length,
}
.into());
}
u16_buffer.push(el);
}
}
self.gas_counter
.pay_per_byte(utf16_decoding_byte, u16_buffer.len() as u64 * size_of::<u16>() as u64)?;
String::from_utf16(&u16_buffer).map_err(|_| HostError::BadUTF16.into())
}
// ####################################################
// # Helper functions to prevent code duplication API #
// ####################################################
/// Checks that the current log number didn't reach the limit yet, so we can add a new message.
fn check_can_add_a_log_message(&self) -> Result<()> {
if self.logs.len() as u64 >= self.config.limit_config.max_number_logs {
Err(HostError::NumberOfLogsExceeded { limit: self.config.limit_config.max_number_logs }
.into())
} else {
Ok(())
}
}
/// Adds a given promise to the vector of promises and returns a new promise index.
/// Throws `NumberPromisesExceeded` if the total number of promises exceeded the limit.
fn checked_push_promise(&mut self, promise: Promise) -> Result<PromiseIndex> {
let new_promise_idx = self.promises.len() as PromiseIndex;
self.promises.push(promise);
if self.promises.len() as u64
> self.config.limit_config.max_promises_per_function_call_action
{
Err(HostError::NumberPromisesExceeded {
number_of_promises: self.promises.len() as u64,
limit: self.config.limit_config.max_promises_per_function_call_action,
}
.into())
} else {
Ok(new_promise_idx)
}
}
fn checked_push_log(&mut self, message: String) -> Result<()> {
// The size of logged data can't be too large. No overflow.
self.total_log_length += message.len() as u64;
if self.total_log_length > self.config.limit_config.max_total_log_length {
return Err(HostError::TotalLogLengthExceeded {
length: self.total_log_length,
limit: self.config.limit_config.max_total_log_length,
}
.into());
}
self.logs.push(message);
Ok(())
}
// ###############
// # Context API #
// ###############
/// Saves the account id of the current contract that we execute into the register.
///
/// # Errors
///
/// If the registers exceed the memory limit returns `MemoryAccessViolation`.
///
/// # Cost
///
/// `base + write_register_base + write_register_byte * num_bytes`
pub fn current_account_id(&mut self, register_id: u64) -> Result<()> {
self.gas_counter.pay_base(base)?;
self.internal_write_register(
register_id,
self.context.current_account_id.as_bytes().to_vec(),
)
}
/// All contract calls are a result of some transaction that was signed by some account using
/// some access key and submitted into a memory pool (either through the wallet using RPC or by
/// a node itself). This function returns the id of that account. Saves the bytes of the signer
/// account id into the register.
///
/// # Errors
///
/// * If the registers exceed the memory limit returns `MemoryAccessViolation`.
/// * If called as view function returns `ProhibitedInView`.
///
/// # Cost
///
/// `base + write_register_base + write_register_byte * num_bytes`
pub fn signer_account_id(&mut self, register_id: u64) -> Result<()> {
self.gas_counter.pay_base(base)?;
if self.context.is_view {
return Err(HostError::ProhibitedInView {
method_name: "signer_account_id".to_string(),
}
.into());
}
self.internal_write_register(
register_id,
self.context.signer_account_id.as_bytes().to_vec(),
)
}
/// Saves the public key fo the access key that was used by the signer into the register. In
/// rare situations smart contract might want to know the exact access key that was used to send
/// the original transaction, e.g. to increase the allowance or manipulate with the public key.
///
/// # Errors
///
/// * If the registers exceed the memory limit returns `MemoryAccessViolation`.
/// * If called as view function returns `ProhibitedInView`.
///
/// # Cost
///
/// `base + write_register_base + write_register_byte * num_bytes`
pub fn signer_account_pk(&mut self, register_id: u64) -> Result<()> {
self.gas_counter.pay_base(base)?;
if self.context.is_view {
return Err(HostError::ProhibitedInView {
method_name: "signer_account_pk".to_string(),
}
.into());
}
self.internal_write_register(register_id, self.context.signer_account_pk.clone())
}
/// All contract calls are a result of a receipt, this receipt might be created by a transaction
/// that does function invocation on the contract or another contract as a result of
/// cross-contract call. Saves the bytes of the predecessor account id into the register.
///
/// # Errors
///
/// * If the registers exceed the memory limit returns `MemoryAccessViolation`.
/// * If called as view function returns `ProhibitedInView`.
///
/// # Cost
///
/// `base + write_register_base + write_register_byte * num_bytes`
pub fn predecessor_account_id(&mut self, register_id: u64) -> Result<()> {
self.gas_counter.pay_base(base)?;
if self.context.is_view {
return Err(HostError::ProhibitedInView {
method_name: "predecessor_account_id".to_string(),
}
.into());
}
self.internal_write_register(
register_id,
self.context.predecessor_account_id.as_bytes().to_vec(),
)
}
/// Reads input to the contract call into the register. Input is expected to be in JSON-format.
/// If input is provided saves the bytes (potentially zero) of input into register. If input is
/// not provided writes 0 bytes into the register.
///
/// # Cost
///
/// `base + write_register_base + write_register_byte * num_bytes`
pub fn input(&mut self, register_id: u64) -> Result<()> {
self.gas_counter.pay_base(base)?;
self.internal_write_register(register_id, self.context.input.clone())
}
/// Returns the current block height.
///
/// # Cost
///
/// `base`
// TODO #1903 rename to `block_height`
pub fn block_index(&mut self) -> Result<u64> {
self.gas_counter.pay_base(base)?;
Ok(self.context.block_index)
}
/// Returns the current block timestamp (number of non-leap-nanoseconds since January 1, 1970 0:00:00 UTC).
///
/// # Cost
///
/// `base`
pub fn block_timestamp(&mut self) -> Result<u64> {
self.gas_counter.pay_base(base)?;
Ok(self.context.block_timestamp)
}
/// Returns the current epoch height.
///
/// # Cost
///
/// `base`
pub fn epoch_height(&mut self) -> Result<EpochHeight> {
self.gas_counter.pay_base(base)?;
Ok(self.context.epoch_height)
}
/// Get the stake of an account, if the account is currently a validator. Otherwise returns 0.
/// writes the value into the` u128` variable pointed by `stake_ptr`.
///
/// # Cost
///
/// `base + memory_write_base + memory_write_size * 16 + utf8_decoding_base + utf8_decoding_byte * account_id_len + validator_stake_base`.
pub fn validator_stake(
&mut self,
account_id_len: u64,
account_id_ptr: u64,
stake_ptr: u64,
) -> Result<()> {
self.gas_counter.pay_base(base)?;
let account_id = self.read_and_parse_account_id(account_id_ptr, account_id_len)?;
self.gas_counter.pay_base(validator_stake_base)?;
let balance = self.ext.validator_stake(&account_id)?.unwrap_or_default();
self.memory_set_u128(stake_ptr, balance)
}
/// Get the total validator stake of the current epoch.
/// Write the u128 value into `stake_ptr`.
/// writes the value into the` u128` variable pointed by `stake_ptr`.
///
/// # Cost
///
/// `base + memory_write_base + memory_write_size * 16 + validator_total_stake_base`
pub fn validator_total_stake(&mut self, stake_ptr: u64) -> Result<()> {
self.gas_counter.pay_base(base)?;
self.gas_counter.pay_base(validator_total_stake_base)?;
let total_stake = self.ext.validator_total_stake()?;
self.memory_set_u128(stake_ptr, total_stake)
}
/// Returns the number of bytes used by the contract if it was saved to the trie as of the
/// invocation. This includes:
/// * The data written with storage_* functions during current and previous execution;
/// * The bytes needed to store the access keys of the given account.
/// * The contract code size
/// * A small fixed overhead for account metadata.
///
/// # Cost
///
/// `base`
pub fn storage_usage(&mut self) -> Result<StorageUsage> {
self.gas_counter.pay_base(base)?;
Ok(self.current_storage_usage)
}
// #################
// # Economics API #
// #################
/// The current balance of the given account. This includes the attached_deposit that was
/// attached to the transaction.
///
/// # Cost
///
/// `base + memory_write_base + memory_write_size * 16`
pub fn account_balance(&mut self, balance_ptr: u64) -> Result<()> {
self.gas_counter.pay_base(base)?;
self.memory_set_u128(balance_ptr, self.current_account_balance)
}
/// The current amount of tokens locked due to staking.
///
/// # Cost
///
/// `base + memory_write_base + memory_write_size * 16`
pub fn account_locked_balance(&mut self, balance_ptr: u64) -> Result<()> {
self.gas_counter.pay_base(base)?;
self.memory_set_u128(balance_ptr, self.current_account_locked_balance)
}
/// The balance that was attached to the call that will be immediately deposited before the
/// contract execution starts.
///
/// # Errors
///
/// If called as view function returns `ProhibitedInView``.
///
/// # Cost
///
/// `base + memory_write_base + memory_write_size * 16`
pub fn attached_deposit(&mut self, balance_ptr: u64) -> Result<()> {
self.gas_counter.pay_base(base)?;
if self.context.is_view {
return Err(HostError::ProhibitedInView {
method_name: "attached_deposit".to_string(),
}
.into());
}
self.memory_set_u128(balance_ptr, self.context.attached_deposit)
}
/// The amount of gas attached to the call that can be used to pay for the gas fees.
///
/// # Errors
///
/// If called as view function returns `ProhibitedInView`.
///
/// # Cost
///
/// `base`
pub fn prepaid_gas(&mut self) -> Result<Gas> {
self.gas_counter.pay_base(base)?;
if self.context.is_view {
return Err(
HostError::ProhibitedInView { method_name: "prepaid_gas".to_string() }.into()
);
}
Ok(self.context.prepaid_gas)
}
/// The gas that was already burnt during the contract execution (cannot exceed `prepaid_gas`)
///
/// # Errors
///
/// If called as view function returns `ProhibitedInView`.
///
/// # Cost
///
/// `base`
pub fn used_gas(&mut self) -> Result<Gas> {
self.gas_counter.pay_base(base)?;
if self.context.is_view {
return Err(HostError::ProhibitedInView { method_name: "used_gas".to_string() }.into());
}
Ok(self.gas_counter.used_gas())
}
// ############
// # Math API #
// ############
/// Compute multiexp on alt_bn128 curve.
/// See more detailed description at `alt_bn128::alt_bn128_g1_multiexp`.
///
/// # Errors
///
/// If `value_len + value_ptr` points outside the memory or the registers use more memory than
/// the limit with `MemoryAccessViolation`.
///
/// AltBn128SerializationError, AltBn128DeserializationError
///
/// # Cost
///
/// `base + write_register_base + write_register_byte * num_bytes + alt_bn128_g1_multiexp_base +
/// alt_bn128_g1_multiexp_byte * num_bytes + alt_bn128_g1_multiexp_sublinear *
/// alt_bn128_g1_multiexp_sublinear_complexity_estimate(num_bytes, (alt_bn128_g1_multiexp_base *
/// alt_bn128_g1_multiexp_byte * num_bytes) / alt_bn128_g1_multiexp_sublinear)`
#[cfg(feature = "protocol_feature_alt_bn128")]
pub fn alt_bn128_g1_multiexp(
&mut self,
value_len: u64,
value_ptr: u64,
register_id: u64,
) -> Result<()> {
self.gas_counter.pay_base(alt_bn128_g1_multiexp_base)?;
let value_buf = self.get_vec_from_memory_or_register(value_ptr, value_len)?;
let len = value_buf.len() as u64;
self.gas_counter.pay_per_byte(alt_bn128_g1_multiexp_byte, len)?;
let discount = (alt_bn128_g1_multiexp_base as u64
+ alt_bn128_g1_multiexp_byte as u64 * len)
/ alt_bn128_g1_multiexp_sublinear as u64;
let sublinear_complexity =
crate::alt_bn128::alt_bn128_g1_multiexp_sublinear_complexity_estimate(len, discount);
self.gas_counter.pay_per_byte(alt_bn128_g1_multiexp_sublinear, sublinear_complexity)?;
let res = crate::alt_bn128::alt_bn128_g1_multiexp(&value_buf)?;
self.internal_write_register(register_id, res)
}
/// Compute signed sum on alt_bn128 for g1 group.
/// See more detailed description at `alt_bn128::alt_bn128_g1_sum`.
///
/// # Errors
///
/// If `value_len + value_ptr` points outside the memory or the registers use more memory than
/// the limit with `MemoryAccessViolation`.
///
/// AltBn128SerializationError, AltBn128DeserializationError
///
/// # Cost
///
/// `base + write_register_base + write_register_byte * num_bytes + alt_bn128_g1_sum_base + alt_bn128_g1_sum_byte * num_bytes`
#[cfg(feature = "protocol_feature_alt_bn128")]
pub fn alt_bn128_g1_sum(
&mut self,
value_len: u64,
value_ptr: u64,
register_id: u64,
) -> Result<()> {
self.gas_counter.pay_base(alt_bn128_g1_sum_base)?;
let value_buf = self.get_vec_from_memory_or_register(value_ptr, value_len)?;
self.gas_counter.pay_per_byte(alt_bn128_g1_sum_byte, value_buf.len() as u64)?;
let res = crate::alt_bn128::alt_bn128_g1_sum(&value_buf)?;
self.internal_write_register(register_id, res)
}
/// Compute pairing check on alt_bn128 curve.
/// See more detailed description at `alt_bn128::alt_bn128_pairing_check`.
///
/// # Errors
///
/// If `value_len + value_ptr` points outside the memory or the registers use more memory than
/// the limit with `MemoryAccessViolation`.
///
/// AltBn128SerializationError, AltBn128DeserializationError
///
/// # Cost
///
/// `base + write_register_base + write_register_byte * num_bytes + alt_bn128_pairing_base + alt_bn128_pairing_byte * num_bytes`
#[cfg(feature = "protocol_feature_alt_bn128")]
pub fn alt_bn128_pairing_check(&mut self, value_len: u64, value_ptr: u64) -> Result<u64> {
self.gas_counter.pay_base(alt_bn128_pairing_check_base)?;
let value_buf = self.get_vec_from_memory_or_register(value_ptr, value_len)?;
self.gas_counter.pay_per_byte(alt_bn128_pairing_check_byte, value_buf.len() as u64)?;
Ok(crate::alt_bn128::alt_bn128_pairing_check(&value_buf)? as u64)
}
/// Writes random seed into the register.
///
/// # Errors
///
/// If the size of the registers exceed the set limit `MemoryAccessViolation`.
///
/// # Cost
///
/// `base + write_register_base + write_register_byte * num_bytes`.
pub fn random_seed(&mut self, register_id: u64) -> Result<()> {
self.gas_counter.pay_base(base)?;
self.internal_write_register(register_id, self.context.random_seed.clone())
}
/// Hashes the given value using sha256 and returns it into `register_id`.
///
/// # Errors
///
/// If `value_len + value_ptr` points outside the memory or the registers use more memory than
/// the limit with `MemoryAccessViolation`.
///
/// # Cost
///
/// `base + write_register_base + write_register_byte * num_bytes + sha256_base + sha256_byte * num_bytes`
pub fn sha256(&mut self, value_len: u64, value_ptr: u64, register_id: u64) -> Result<()> {
self.gas_counter.pay_base(sha256_base)?;
let value = self.get_vec_from_memory_or_register(value_ptr, value_len)?;
self.gas_counter.pay_per_byte(sha256_byte, value.len() as u64)?;
use sha2::Digest;
let value_hash = sha2::Sha256::digest(&value);
self.internal_write_register(register_id, value_hash.as_slice().to_vec())
}
/// Hashes the given value using keccak256 and returns it into `register_id`.
///
/// # Errors
///
/// If `value_len + value_ptr` points outside the memory or the registers use more memory than
/// the limit with `MemoryAccessViolation`.
///
/// # Cost
///
/// `base + write_register_base + write_register_byte * num_bytes + keccak256_base + keccak256_byte * num_bytes`
pub fn keccak256(&mut self, value_len: u64, value_ptr: u64, register_id: u64) -> Result<()> {
self.gas_counter.pay_base(keccak256_base)?;
let value = self.get_vec_from_memory_or_register(value_ptr, value_len)?;
self.gas_counter.pay_per_byte(keccak256_byte, value.len() as u64)?;
use sha3::Digest;
let value_hash = sha3::Keccak256::digest(&value);
self.internal_write_register(register_id, value_hash.as_slice().to_vec())
}
/// Hashes the given value using keccak512 and returns it into `register_id`.
///
/// # Errors
///
/// If `value_len + value_ptr` points outside the memory or the registers use more memory than
/// the limit with `MemoryAccessViolation`.
///
/// # Cost
///
/// `base + write_register_base + write_register_byte * num_bytes + keccak512_base + keccak512_byte * num_bytes`
pub fn keccak512(&mut self, value_len: u64, value_ptr: u64, register_id: u64) -> Result<()> {
self.gas_counter.pay_base(keccak512_base)?;
let value = self.get_vec_from_memory_or_register(value_ptr, value_len)?;
self.gas_counter.pay_per_byte(keccak512_byte, value.len() as u64)?;
use sha3::Digest;
let value_hash = sha3::Keccak512::digest(&value);
self.internal_write_register(register_id, value_hash.as_slice().to_vec())
}
/// Called by gas metering injected into Wasm. Counts both towards `burnt_gas` and `used_gas`.
///
/// # Errors
///
/// * If passed gas amount somehow overflows internal gas counters returns `IntegerOverflow`;
/// * If we exceed usage limit imposed on burnt gas returns `GasLimitExceeded`;
/// * If we exceed the `prepaid_gas` then returns `GasExceeded`.
pub fn gas(&mut self, gas_amount: u32) -> Result<()> {
let value = Gas::from(gas_amount) * Gas::from(self.config.regular_op_cost);
self.gas_counter.pay_wasm_gas(value)
}
// ################
// # Promises API #
// ################
/// A helper function to pay gas fee for creating a new receipt without actions.
/// # Args:
/// * `sir`: whether contract call is addressed to itself;
/// * `data_dependencies`: other contracts that this execution will be waiting on (or rather
/// their data receipts), where bool indicates whether this is sender=receiver communication.
///
/// # Cost
///
/// This is a convenience function that encapsulates several costs:
/// `burnt_gas := dispatch cost of the receipt + base dispatch cost cost of the data receipt`
/// `used_gas := burnt_gas + exec cost of the receipt + base exec cost cost of the data receipt`
/// Notice that we prepay all base cost upon the creation of the data dependency, we are going to
/// pay for the content transmitted through the dependency upon the actual creation of the
/// DataReceipt.
fn pay_gas_for_new_receipt(&mut self, sir: bool, data_dependencies: &[bool]) -> Result<()> {
let fees_config_cfg = &self.fees_config;
let mut burn_gas = fees_config_cfg.action_receipt_creation_config.send_fee(sir);
let mut use_gas = fees_config_cfg.action_receipt_creation_config.exec_fee();
for dep in data_dependencies {
// Both creation and execution for data receipts are considered burnt gas.
burn_gas = burn_gas
.checked_add(fees_config_cfg.data_receipt_creation_config.base_cost.send_fee(*dep))
.ok_or(HostError::IntegerOverflow)?
.checked_add(fees_config_cfg.data_receipt_creation_config.base_cost.exec_fee())
.ok_or(HostError::IntegerOverflow)?;
}
use_gas = use_gas.checked_add(burn_gas).ok_or(HostError::IntegerOverflow)?;
self.gas_counter.pay_action_accumulated(burn_gas, use_gas, ActionCosts::new_receipt)
}
/// A helper function to subtract balance on transfer or attached deposit for promises.