-
Notifications
You must be signed in to change notification settings - Fork 665
/
Copy pathlogic.rs
3115 lines (2903 loc) · 125 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 super::context::VMContext;
use super::dependencies::{External, MemSlice, MemoryLike};
use super::errors::{FunctionCallError, InconsistentStateError};
use super::gas_counter::{FastGasCounter, GasCounter};
use super::types::{PromiseIndex, PromiseResult, ReceiptIndex, ReturnData};
use super::utils::split_method_names;
use super::ValuePtr;
use super::{HostError, VMLogicError};
use crate::ProfileDataV3;
use near_crypto::Secp256K1Signature;
use near_parameters::vm::{Config, StorageGetMode};
use near_parameters::{
transfer_exec_fee, transfer_send_fee, ActionCosts, ExtCosts, RuntimeFeesConfig,
};
use near_primitives_core::config::ViewConfig;
use near_primitives_core::hash::CryptoHash;
use near_primitives_core::types::{
AccountId, Balance, Compute, EpochHeight, Gas, GasWeight, StorageUsage,
};
use std::mem::size_of;
use ExtCosts::*;
pub type Result<T, E = VMLogicError> = ::std::result::Result<T, E>;
#[cfg(feature = "io_trace")]
fn base64(s: &[u8]) -> String {
use base64::Engine;
base64::engine::general_purpose::STANDARD.encode(s)
}
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: &'a VMContext,
/// All gas and economic parameters required during contract execution.
pub(crate) config: &'a Config,
/// 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: super::vmstate::Memory<'a>,
/// 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: super::vmstate::Registers,
/// The DAG of promises, indexed by promise id.
promises: Vec<Promise>,
/// Tracks the total log length. The sum of length of all logs.
total_log_length: u64,
/// Stores the amount of stack space remaining
remaining_stack: u64,
}
/// 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>),
}
/// Helper for calling `super::vmstate::get_memory_or_register`.
///
/// super::vmstate::get_memory_or_register has a whole lot of wordy arguments
/// which are always the same when invoked inside of one of VMLogic method.
/// This macro helps with that invocation.
macro_rules! get_memory_or_register {
($logic:expr, $offset:expr, $len:expr) => {
super::vmstate::get_memory_or_register(
&mut $logic.gas_counter,
&$logic.memory,
&$logic.registers,
$offset,
$len,
)
};
}
/// A wrapper for reading public key.
///
/// This exists for historical reasons because we must maintain when errors are
/// returned. In the old days, between reading the public key and decoding it
/// we could return unrelated error. Because of that we cannot change the code
/// to return deserialisation errors immediately after reading the public key.
///
/// This struct abstracts away the fact that we’re deserialising the key
/// immediately. Decoding errors are detected as soon as this object is created
/// but they are communicated to the user only once they call [`Self::decode`].
///
/// Why not just keep the old ways without this noise? By doing deserialisation
/// immediately we’re copying the data onto the stack without having to allocate
/// a temporary vector.
struct PublicKeyBuffer(Result<near_crypto::PublicKey, ()>);
impl PublicKeyBuffer {
fn new(data: &[u8]) -> Self {
Self(borsh::BorshDeserialize::try_from_slice(data).map_err(|_| ()))
}
fn decode(self) -> Result<near_crypto::PublicKey> {
self.0.map_err(|_| HostError::InvalidPublicKey.into())
}
}
impl<'a> VMLogic<'a> {
pub fn new(
ext: &'a mut dyn External,
context: &'a VMContext,
config: &'a Config,
fees_config: &'a RuntimeFeesConfig,
promise_results: &'a [PromiseResult],
memory: &'a mut dyn MemoryLike,
) -> Self {
// 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 = match context.view_config {
Some(ViewConfig { max_gas_burnt: max_gas_burnt_view }) => max_gas_burnt_view,
None => 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,
config.regular_op_cost,
context.prepaid_gas,
context.is_view(),
);
Self {
ext,
context,
config,
fees_config,
promise_results,
memory: super::vmstate::Memory::new(memory),
current_account_balance,
current_account_locked_balance,
current_storage_usage,
gas_counter,
return_data: ReturnData::None,
logs: vec![],
registers: Default::default(),
promises: vec![],
total_log_length: 0,
remaining_stack: u64::from(config.limit_config.max_stack_height),
}
}
/// Returns reference to logs that have been created so far.
pub fn logs(&self) -> &[String] {
&self.logs
}
#[cfg(test)]
pub(super) fn gas_counter(&self) -> &GasCounter {
&self.gas_counter
}
#[cfg(test)]
pub(super) fn config(&self) -> &Config {
&self.config
}
#[cfg(test)]
pub(super) fn memory(&mut self) -> &mut super::vmstate::Memory<'a> {
&mut self.memory
}
#[cfg(test)]
pub(super) fn registers(&mut self) -> &mut super::vmstate::Registers {
&mut self.registers
}
// #########################
// # Finite-wasm internals #
// #########################
pub fn finite_wasm_gas(&mut self, gas: u64) -> Result<()> {
self.gas(gas)
}
pub fn finite_wasm_stack(&mut self, operand_size: u64, frame_size: u64) -> Result<()> {
self.remaining_stack =
match self.remaining_stack.checked_sub(operand_size.saturating_add(frame_size)) {
Some(s) => s,
None => return Err(VMLogicError::HostError(HostError::MemoryAccessViolation)),
};
self.gas(((frame_size + 7) / 8) * u64::from(self.config.regular_op_cost))?;
Ok(())
}
pub fn finite_wasm_unstack(&mut self, operand_size: u64, frame_size: u64) -> Result<()> {
self.remaining_stack = self
.remaining_stack
.checked_add(operand_size.saturating_add(frame_size))
.expect("remaining stack integer overflow");
Ok(())
}
// #################
// # Registers API #
// #################
/// Convenience function for testing.
#[cfg(test)]
pub fn wrapped_internal_write_register(&mut self, register_id: u64, data: &[u8]) -> Result<()> {
self.registers.set(&mut self.gas_counter, &self.config.limit_config, register_id, data)
}
/// 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.registers.get(&mut self.gas_counter, register_id)?;
self.memory.set(&mut self.gas_counter, 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_len(register_id).unwrap_or(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.view(&mut self.gas_counter, MemSlice { ptr: data_ptr, len: data_len })?;
self.registers.set(&mut self.gas_counter, &self.config.limit_config, 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 != u64::MAX {
if len > max_len {
return self.total_log_length_exceeded(len);
}
buf = self.memory.view(&mut self.gas_counter, MemSlice { ptr, len })?.into_owned();
} else {
buf = vec![];
for i in 0..=max_len {
// self.memory_get_u8 will check for u64 overflow on the first iteration (i == 0)
let el = self.memory.get_u8(&mut self.gas_counter, ptr + i)?;
if el == 0 {
break;
}
if i == max_len {
return self.total_log_length_exceeded(max_len.saturating_add(1));
}
buf.push(el);
}
}
self.gas_counter.pay_per(utf8_decoding_byte, buf.len() as _)?;
String::from_utf8(buf).map_err(|_| HostError::BadUTF8.into())
}
/// Helper function to get utf8 string, for sandbox debug log. The difference with `get_utf8_string`:
/// * It's only available on sandbox node
/// * The cost is 0
/// * It's up to the caller to set correct len
#[cfg(feature = "sandbox")]
fn sandbox_get_utf8_string(&mut self, len: u64, ptr: u64) -> Result<String> {
let buf = self.memory.view_for_free(MemSlice { ptr, len })?.into_owned();
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, mut len: u64, ptr: u64) -> Result<String> {
self.gas_counter.pay_base(utf16_decoding_base)?;
let max_len =
self.config.limit_config.max_total_log_length.saturating_sub(self.total_log_length);
let mem_view = if len == u64::MAX {
len = self.get_nul_terminated_utf16_len(ptr, max_len)?;
self.memory.view_for_free(MemSlice { ptr, len })
} else {
self.memory.view(&mut self.gas_counter, MemSlice { ptr, len })
}?;
let input = stdx::as_chunks_exact(&mem_view).map_err(|_| HostError::BadUTF16)?;
if len > max_len {
return self.total_log_length_exceeded(len);
}
self.gas_counter.pay_per(utf16_decoding_byte, len)?;
char::decode_utf16(input.into_iter().copied().map(u16::from_le_bytes))
.collect::<Result<String, _>>()
.map_err(|_| HostError::BadUTF16.into())
}
/// Helper function to get length of NUL-terminated UTF-16 formatted string
/// in guest memory.
///
/// In other words, counts how many bytes are there to first pair of NUL
/// bytes.
fn get_nul_terminated_utf16_len(&mut self, ptr: u64, max_len: u64) -> Result<u64> {
let mut len = 0;
loop {
if self.memory.get_u16(&mut self.gas_counter, ptr.saturating_add(len))? == 0 {
return Ok(len);
}
len = match len.checked_add(2) {
Some(len) if len <= max_len => len,
Some(len) => return self.total_log_length_exceeded(len),
None => return self.total_log_length_exceeded(u64::MAX),
};
}
}
// ####################################################
// # 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 self.total_log_length_exceeded(0);
}
self.logs.push(message);
Ok(())
}
fn total_log_length_exceeded<T>(&self, add_len: u64) -> Result<T> {
Err(HostError::TotalLogLengthExceeded {
length: self.total_log_length.saturating_add(add_len),
limit: self.config.limit_config.max_total_log_length,
}
.into())
}
fn get_public_key(&mut self, ptr: u64, len: u64) -> Result<PublicKeyBuffer> {
Ok(PublicKeyBuffer::new(&get_memory_or_register!(self, ptr, len)?))
}
// ###############
// # 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.registers.set(
&mut self.gas_counter,
&self.config.limit_config,
register_id,
self.context.current_account_id.as_bytes(),
)
}
/// 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.registers.set(
&mut self.gas_counter,
&self.config.limit_config,
register_id,
self.context.signer_account_id.as_bytes(),
)
}
/// 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.registers.set(
&mut self.gas_counter,
&self.config.limit_config,
register_id,
self.context.signer_account_pk.as_slice(),
)
}
/// 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.registers.set(
&mut self.gas_counter,
&self.config.limit_config,
register_id,
self.context.predecessor_account_id.as_bytes(),
)
}
/// 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.registers.set(
&mut self.gas_counter,
&self.config.limit_config,
register_id,
self.context.input.as_slice(),
)
}
/// Returns the current block height.
///
/// It’s only due to historical reasons, this host function is called
/// `block_index` rather than `block_height`.
///
/// # Cost
///
/// `base`
pub fn block_index(&mut self) -> Result<u64> {
self.gas_counter.pay_base(base)?;
Ok(self.context.block_height)
}
/// 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(&mut self.gas_counter, 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(&mut self.gas_counter, 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(&mut self.gas_counter, 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(
&mut self.gas_counter,
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)?;
self.memory.set_u128(&mut self.gas_counter, 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 #
// ############
/// Computes multiexp on alt_bn128 curve using Pippenger's algorithm \sum_i
/// mul_i g_{1 i} should be equal result.
///
/// # Arguments
///
/// * `value` - sequence of (g1:G1, fr:Fr), where
/// G1 is point (x:Fq, y:Fq) on alt_bn128,
/// alt_bn128 is Y^2 = X^3 + 3 curve over Fq.
///
/// `value` is encoded as packed, little-endian
/// `[((u256, u256), u256)]` slice.
///
/// # Errors
///
/// If `value_len + value_ptr` points outside the memory or the registers
/// use more memory than the limit, the function returns
/// `MemoryAccessViolation`.
///
/// If point coordinates are not on curve, point is not in the subgroup,
/// scalar is not in the field or `value.len()%96!=0`, the function returns
/// `AltBn128InvalidInput`.
///
/// # Cost
///
/// `base + write_register_base + write_register_byte * num_bytes +
/// alt_bn128_g1_multiexp_base +
/// alt_bn128_g1_multiexp_element * num_elements`
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 data = get_memory_or_register!(self, value_ptr, value_len)?;
let elements = super::alt_bn128::split_elements(&data)?;
self.gas_counter.pay_per(alt_bn128_g1_multiexp_element, elements.len() as u64)?;
let res = super::alt_bn128::g1_multiexp(elements)?;
self.registers.set(&mut self.gas_counter, &self.config.limit_config, register_id, res)
}
/// Computes sum for signed g1 group elements on alt_bn128 curve \sum_i
/// (-1)^{sign_i} g_{1 i} should be equal result.
///
/// # Arguments
///
/// * `value` - sequence of (sign:bool, g1:G1), where
/// G1 is point (x:Fq, y:Fq) on alt_bn128,
/// alt_bn128 is Y^2 = X^3 + 3 curve over Fq.
///
/// `value` is encoded as packed, little-endian
/// `[(u8, (u256, u256))]` slice. `0u8` is positive sign,
/// `1u8` -- negative.
///
/// # Errors
///
/// If `value_len + value_ptr` points outside the memory or the registers
/// use more memory than the limit, the function returns `MemoryAccessViolation`.
///
/// If point coordinates are not on curve, point is not in the subgroup,
/// scalar is not in the field, sign is not 0 or 1, or `value.len()%65!=0`,
/// the function returns `AltBn128InvalidInput`.
///
/// # Cost
///
/// `base + write_register_base + write_register_byte * num_bytes +
/// alt_bn128_g1_sum_base + alt_bn128_g1_sum_element * num_elements`
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 data = get_memory_or_register!(self, value_ptr, value_len)?;
let elements = super::alt_bn128::split_elements(&data)?;
self.gas_counter.pay_per(alt_bn128_g1_sum_element, elements.len() as u64)?;
let res = super::alt_bn128::g1_sum(elements)?;
self.registers.set(&mut self.gas_counter, &self.config.limit_config, register_id, res)
}
/// Computes pairing check on alt_bn128 curve.
/// \sum_i e(g_{1 i}, g_{2 i}) should be equal one (in additive notation), e(g1, g2) is Ate pairing
///
/// # Arguments
///
/// * `value` - sequence of (g1:G1, g2:G2), where
/// G2 is Fr-ordered subgroup point (x:Fq2, y:Fq2) on alt_bn128 twist,
/// alt_bn128 twist is Y^2 = X^3 + 3/(i+9) curve over Fq2
/// Fq2 is complex field element (re: Fq, im: Fq)
/// G1 is point (x:Fq, y:Fq) on alt_bn128,
/// alt_bn128 is Y^2 = X^3 + 3 curve over Fq
///
/// `value` is encoded a as packed, little-endian
/// `[((u256, u256), ((u256, u256), (u256, u256)))]` slice.
///
/// # Errors
///
/// If `value_len + value_ptr` points outside the memory or the registers use more memory than
/// the function returns `MemoryAccessViolation`.
///
/// If point coordinates are not on curve, point is not in the subgroup, scalar
/// is not in the field or data are wrong serialized, for example,
/// `value.len()%192!=0`, the function returns `AltBn128InvalidInput`.
///
/// # Cost
///
/// `base + write_register_base + write_register_byte * num_bytes + alt_bn128_pairing_base + alt_bn128_pairing_element * num_elements`
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 data = get_memory_or_register!(self, value_ptr, value_len)?;
let elements = super::alt_bn128::split_elements(&data)?;
self.gas_counter.pay_per(alt_bn128_pairing_check_element, elements.len() as u64)?;
let res = super::alt_bn128::pairing_check(elements)?;
Ok(res 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.registers.set(
&mut self.gas_counter,
&self.config.limit_config,
register_id,
self.context.random_seed.as_slice(),
)
}
/// 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 = get_memory_or_register!(self, value_ptr, value_len)?;
self.gas_counter.pay_per(sha256_byte, value.len() as u64)?;
use sha2::Digest;
let value_hash = sha2::Sha256::digest(&value);
self.registers.set(
&mut self.gas_counter,
&self.config.limit_config,
register_id,
value_hash.as_slice(),
)
}
/// 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 = get_memory_or_register!(self, value_ptr, value_len)?;
self.gas_counter.pay_per(keccak256_byte, value.len() as u64)?;
use sha3::Digest;
let value_hash = sha3::Keccak256::digest(&value);
self.registers.set(
&mut self.gas_counter,
&self.config.limit_config,
register_id,
value_hash.as_slice(),
)
}
/// 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 = get_memory_or_register!(self, value_ptr, value_len)?;
self.gas_counter.pay_per(keccak512_byte, value.len() as u64)?;
use sha3::Digest;
let value_hash = sha3::Keccak512::digest(&value);
self.registers.set(
&mut self.gas_counter,
&self.config.limit_config,
register_id,
value_hash.as_slice(),
)
}
/// Hashes the given value using RIPEMD-160 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
///
/// Where `message_blocks` is `(value_len + 9).div_ceil(64)`.
///
/// `base + write_register_base + write_register_byte * num_bytes + ripemd160_base + ripemd160_block * message_blocks`
pub fn ripemd160(&mut self, value_len: u64, value_ptr: u64, register_id: u64) -> Result<()> {
self.gas_counter.pay_base(ripemd160_base)?;
let value = get_memory_or_register!(self, value_ptr, value_len)?;
let message_blocks = value
.len()