-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathimpls.rs
More file actions
2462 lines (2274 loc) · 93.2 KB
/
Copy pathimpls.rs
File metadata and controls
2462 lines (2274 loc) · 93.2 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
use crate::{
constants,
invocation::{ChangeSet, EntrypointInvocationHandler, TestConfigurationError},
types::*,
CONTRACT_MODULE_OUTPUT_PATH_ENV_VAR,
};
use anyhow::anyhow;
use concordium_rust_sdk::{
self as sdk, base,
base::{
base::{AccountThreshold, Energy, InsufficientEnergy},
constants::MAX_WASM_MODULE_SIZE,
contracts_common::{
self, AccountAddress, AccountBalance, Address, Amount, ChainMetadata, ContractAddress,
Deserial, Duration, ExchangeRate, ExchangeRates, ModuleReference, OwnedPolicy,
ParseResult, SlotTime, Timestamp,
},
hashes::BlockHash,
smart_contracts::{ContractEvent, ModuleSource, WasmModule, WasmVersion},
transactions::{
self, cost, AccountAccessStructure, InitContractPayload, UpdateContractPayload,
},
},
smart_contracts::engine::{
v0,
v1::{self, DebugTracker, InvalidReturnCodeError, InvokeResponse},
wasm,
wasm::validate::ValidationConfig,
DebugInfo, InterpreterEnergy,
},
v2::Endpoint,
};
use num_bigint::BigUint;
use num_integer::Integer;
use sdk::{
smart_contracts::engine::wasm::CostConfigurationV1,
types::smart_contracts::InvokeContractResult,
};
use std::{
collections::{BTreeMap, BTreeSet},
env,
future::Future,
path::Path,
sync::Arc,
};
use tokio::{runtime, time::timeout};
/// The timeout duration set for queries with an external node.
const EXTERNAL_NODE_QUERY_TIMEOUT: tokio::time::Duration = tokio::time::Duration::from_secs(10);
/// The timeout duration set for connecting to an external node.
const EXTERNAL_NODE_CONNECT_TIMEOUT: tokio::time::Duration = tokio::time::Duration::from_secs(3);
impl Default for Chain {
fn default() -> Self { Self::new() }
}
impl ChainParameters {
/// Create a new [`ChainParameters`](Self) where
/// - `block_time` defaults to `0`,
/// - `micro_ccd_per_euro` defaults to `50000 / 1`
/// - `euro_per_energy` defaults to `1 / 50000`.
///
/// With these exchange rates, one energy costs one microCCD.
pub fn new() -> Self {
Self::new_with_time_and_rates(
Timestamp::from_timestamp_millis(0),
ExchangeRate::new_unchecked(50000, 1),
ExchangeRate::new_unchecked(1, 50000),
)
.expect("Parameters are in range.")
}
/// Create a new [`ChainParameters`](Self) with a specified `block_time`
/// where
/// - `micro_ccd_per_euro` defaults to `50000 / 1`
/// - `euro_per_energy` defaults to `1 / 50000`.
pub fn new_with_time(block_time: SlotTime) -> Self {
Self {
block_time,
..Self::new()
}
}
/// Create a new [`ChainParameters`](Self) where all the configurable
/// parameters are provided.
///
/// Returns an error if the exchange rates provided makes one energy cost
/// more than `u64::MAX / 100_000_000_000`.
pub fn new_with_time_and_rates(
block_time: SlotTime,
micro_ccd_per_euro: ExchangeRate,
euro_per_energy: ExchangeRate,
) -> Result<Self, ExchangeRateError> {
// Ensure the exchange rates are within a valid range.
check_exchange_rates(euro_per_energy, micro_ccd_per_euro)?;
Ok(Self {
block_time,
micro_ccd_per_euro,
euro_per_energy,
})
}
/// Helper function for converting [`Energy`] to [`Amount`] using the two
/// [`ExchangeRate`]s `euro_per_energy` and `micro_ccd_per_euro`.
pub fn calculate_energy_cost(&self, energy: Energy) -> Amount {
energy_to_amount(energy, self.euro_per_energy, self.micro_ccd_per_euro)
}
}
impl ChainBuilder {
/// Create a new [`ChainBuilder`] for constructing the [`Chain`].
///
/// Can also be created via the [`Chain::builder`] method.
///
/// To complete the building process, use [`ChainBuilder::build`], see the
/// example below.
///
/// # Example
/// ```
/// # use concordium_smart_contract_testing::*;
///
/// let chain = ChainBuilder::new()
/// // Use zero or more builder methods, for example:
/// .micro_ccd_per_euro(ExchangeRate::new_unchecked(50000, 1))
/// .block_time(Timestamp::from_timestamp_millis(123))
/// // Then build:
/// .build()
/// .unwrap();
/// ```
pub fn new() -> Self {
Self {
external_node_endpoint: None,
external_query_block: None,
micro_ccd_per_euro: None,
micro_ccd_per_euro_from_external: false,
euro_per_energy: None,
euro_per_energy_from_external: false,
block_time: None,
block_time_from_external: false,
}
}
/// Configure a connection to an external Concordium node.
///
/// The connection can be used for getting the current exchange rates
/// between CCD, Euro and Energy.
///
/// # Example
///
/// ```no_run
/// # use concordium_smart_contract_testing::*;
/// let chain = Chain::builder()
/// .external_node_connection(Endpoint::from_static("http://node.testnet.concordium.com:20000"))
/// .build()
/// .unwrap();
/// ```
pub fn external_node_connection(mut self, endpoint: impl Into<Endpoint>) -> Self {
self.external_node_endpoint = Some(endpoint.into());
self
}
/// Configure the block to be used for all external queries.
///
/// If this is not set, then the last final block will be queried during
/// [`ChainBuilder::build`] and saved, so it can be used for future queries.
///
/// This can only be used in combination with
/// [`external_node_connection`][Self::external_node_connection].
///
/// To view the configured block, see [`Chain::external_query_block`].
///
/// # Example
///
/// ```no_run
/// # use concordium_smart_contract_testing::*;
/// let chain = Chain::builder()
/// .external_node_connection(Endpoint::from_static("http://node.testnet.concordium.com:20000"))
/// .external_query_block(
/// "95ff82f26892a2327c3e7ac582224a54d75c367341fbff209bce552d81349eb0".parse().unwrap(),
/// )
/// .build()
/// .unwrap();
/// ```
pub fn external_query_block(mut self, query_block: BlockHash) -> Self {
self.external_query_block = Some(query_block);
self
}
/// Configure the 'microCCD per euro' exchange rate.
///
/// By default the rate is `50000 / 1`.
///
/// This cannot be used together with
/// [`ChainBuilder::micro_ccd_per_euro_from_external`].
///
/// # Example
/// ```
/// # use concordium_smart_contract_testing::*;
/// let chain = ChainBuilder::new()
/// .micro_ccd_per_euro(ExchangeRate::new_unchecked(50000, 1))
/// .build()
/// .unwrap();
/// ```
pub fn micro_ccd_per_euro(mut self, exchange_rate: ExchangeRate) -> Self {
self.micro_ccd_per_euro = Some(exchange_rate);
self
}
/// Configure the 'euro per energy' exchange rate.
///
/// By default the rate is `1 / 50000`.
///
/// This cannot be used together with
/// [`ChainBuilder::euro_per_energy_from_external`].
///
/// # Example
/// ```
/// # use concordium_smart_contract_testing::*;
/// let chain =
/// ChainBuilder::new().euro_per_energy(ExchangeRate::new_unchecked(1, 50000)).build().unwrap();
/// ```
pub fn euro_per_energy(mut self, exchange_rate: ExchangeRate) -> Self {
self.euro_per_energy = Some(exchange_rate);
self
}
/// Configure the exchange rate between microCCD and euro using the external
/// node connection.
///
/// This can only be used in combination with
/// [`external_node_connection`][Self::external_node_connection], and it
/// cannot be used together with
/// [`micro_ccd_per_euro`][Self::micro_ccd_per_euro].
///
/// # Example
/// ```no_run
/// # use concordium_smart_contract_testing::*;
/// let chain = ChainBuilder::new()
/// .external_node_connection(Endpoint::from_static("http://node.testnet.concordium.com:20000"))
/// .micro_ccd_per_euro_from_external()
/// .build()
/// .unwrap();
/// ```
pub fn micro_ccd_per_euro_from_external(mut self) -> Self {
self.micro_ccd_per_euro_from_external = true;
self
}
/// Configure the exchange rate between euro and energy using the external
/// node connection.
///
/// This can only be used in combination with
/// [`external_node_connection`][Self::external_node_connection], and it
/// cannot be used together with
/// [`euro_per_energy`][Self::euro_per_energy].
///
/// # Example
/// ```no_run
/// # use concordium_smart_contract_testing::*;
/// let chain = ChainBuilder::new()
/// .external_node_connection(Endpoint::from_static("http://node.testnet.concordium.com:20000"))
/// .euro_per_energy_from_external()
/// .build()
/// .unwrap();
/// ```
pub fn euro_per_energy_from_external(mut self) -> Self {
self.euro_per_energy_from_external = true;
self
}
/// Configure the block time.
///
/// By default the block time is `0`.
///
/// This cannot be used in combination with
/// [`ChainBuilder::block_time_from_external`].
///
/// # Example
/// ```
/// # use concordium_smart_contract_testing::*;
/// let chain = ChainBuilder::new()
/// .block_time(Timestamp::from_timestamp_millis(1687440701000))
/// .build()
/// .unwrap();
/// ```
pub fn block_time(mut self, block_time: Timestamp) -> Self {
self.block_time = Some(block_time);
self
}
/// Configure the block time using the external node connection.
///
/// This can only be used in combination with
/// [`external_node_connection`][Self::external_node_connection], and it
/// cannot be used together with
/// [`block_time`][Self::block_time].
///
/// # Example
/// ```no_run
/// # use concordium_smart_contract_testing::*;
/// let chain = ChainBuilder::new()
/// .external_node_connection(Endpoint::from_static("http://node.testnet.concordium.com:20000"))
/// .block_time_from_external()
/// .build()
/// .unwrap();
/// ```
pub fn block_time_from_external(mut self) -> Self {
self.block_time_from_external = true;
self
}
/// Build the [`Chain`] with the configured options.
///
/// # Example
/// ```
/// # use concordium_smart_contract_testing::*;
///
/// let chain = Chain::builder()
/// // Use zero or more builder methods, for example:
/// .euro_per_energy(ExchangeRate::new_unchecked(1, 50000))
/// .micro_ccd_per_euro(ExchangeRate::new_unchecked(50000, 1))
/// // Then build:
/// .build()
/// .unwrap();
/// ```
pub fn build(self) -> Result<Chain, ChainBuilderError> {
// Create the chain with default parameters.
let mut chain = Chain::new();
// Setup the external node connection if provided. This also forwards and sets
// the external query block.
if let Some(endpoint) = self.external_node_endpoint {
chain.setup_external_node_connection(endpoint, self.external_query_block)?;
}
// Check for conflicting exchange rate configurations.
if self.micro_ccd_per_euro.is_some() && self.micro_ccd_per_euro_from_external {
return Err(ChainBuilderError::ConflictingMicroCCDPerEuro);
}
if self.euro_per_energy.is_some() && self.euro_per_energy_from_external {
return Err(ChainBuilderError::ConflictingEuroPerEnergy);
}
// Set the exchange rates via an external query.
if self.micro_ccd_per_euro_from_external || self.euro_per_energy_from_external {
let exchange_rates = chain.get_exchange_rates_via_external_node()?;
if self.micro_ccd_per_euro_from_external {
chain.parameters.micro_ccd_per_euro = exchange_rates.micro_ccd_per_euro;
}
if self.euro_per_energy_from_external {
chain.parameters.euro_per_energy = exchange_rates.euro_per_energy;
}
}
// Set the exchange rates directly.
if let Some(micro_ccd_per_euro) = self.micro_ccd_per_euro {
chain.parameters.micro_ccd_per_euro = micro_ccd_per_euro;
}
if let Some(euro_per_energy) = self.euro_per_energy {
chain.parameters.euro_per_energy = euro_per_energy;
}
// Check the exchange rates and return early if they are invalid.
check_exchange_rates(
chain.parameters.euro_per_energy,
chain.parameters.micro_ccd_per_euro,
)?;
match (self.block_time, self.block_time_from_external) {
(Some(_), true) => return Err(ChainBuilderError::ConflictingBlockTime),
(Some(block_time), false) => {
chain.parameters.block_time = block_time;
}
(None, true) => {
chain.set_block_time_via_external_node()?;
}
(None, false) => (),
}
// Replace the default block time if provided.
if let Some(block_time) = self.block_time {
chain.parameters.block_time = block_time;
}
Ok(chain)
}
}
impl Default for ChainBuilder {
fn default() -> Self { Self::new() }
}
// Exit early with an out of energy error.
macro_rules! exit_ooe {
($charge:expr, $trace:expr) => {
if let Err(InsufficientEnergy) = $charge {
return Err(ContractInitErrorKind::OutOfEnergy {
debug_trace: $trace,
});
}
};
}
impl Chain {
/// Get a [`ChainBuilder`] for constructing a new [`Chain`] with a builder
/// pattern.
///
/// See the [`ChainBuilder`] for more details.
pub fn builder() -> ChainBuilder { ChainBuilder::new() }
/// Create a new [`Chain`](Self) where all the configurable parameters are
/// provided.
///
/// Returns an error if the exchange rates provided makes one energy cost
/// more than `u64::MAX / 100_000_000_000`.
///
/// *For more configuration options and flexibility, use the builder
/// pattern. See [`Chain::builder`].*
pub fn new_with_time_and_rates(
block_time: SlotTime,
micro_ccd_per_euro: ExchangeRate,
euro_per_energy: ExchangeRate,
) -> Result<Self, ExchangeRateError> {
Ok(Self {
parameters: ChainParameters::new_with_time_and_rates(
block_time,
micro_ccd_per_euro,
euro_per_energy,
)?,
accounts: BTreeMap::new(),
modules: BTreeMap::new(),
contracts: BTreeMap::new(),
next_contract_index: 0,
external_node_connection: None,
})
}
/// Create a new [`Chain`](Self) with a specified `block_time` where
/// - `micro_ccd_per_euro` defaults to `50000 / 1`
/// - `euro_per_energy` defaults to `1 / 50000`.
///
/// *For more configuration options and flexibility, use the builder
/// pattern. See [`Chain::builder`].*
pub fn new_with_time(block_time: SlotTime) -> Self {
Self {
parameters: ChainParameters::new_with_time(block_time),
..Self::new()
}
}
/// Create a new [`Chain`](Self) where
/// - `block_time` defaults to `0`,
/// - `micro_ccd_per_euro` defaults to `50000 / 1`
/// - `euro_per_energy` defaults to `1 / 50000`.
///
/// With these exchange rates, one energy costs one microCCD.
///
/// *For more configuration options and flexibility, use the builder
/// pattern. See [`Chain::builder`].*
pub fn new() -> Self {
Self::new_with_time_and_rates(
Timestamp::from_timestamp_millis(0),
ExchangeRate::new_unchecked(50000, 1),
ExchangeRate::new_unchecked(1, 50000),
)
.expect("Rates known to be within range.")
}
/// Helper function for converting [`Energy`] to [`Amount`] using the two
/// [`ExchangeRate`]s `euro_per_energy` and `micro_ccd_per_euro`.
pub fn calculate_energy_cost(&self, energy: Energy) -> Amount {
self.parameters.calculate_energy_cost(energy)
}
/// Get the state of the contract if it exists in the [`Chain`](Self).
pub fn get_contract(&self, address: ContractAddress) -> Option<&Contract> {
self.contracts.get(&address)
}
/// Get the the module if it exists in the [`Chain`](Self).
pub fn get_module(&self, module: ModuleReference) -> Option<&ContractModule> {
self.modules.get(&module)
}
/// Get the state of the account if it exists in the [`Chain`](Self).
/// Account addresses that are aliases will return the same account.
pub fn get_account(&self, address: AccountAddress) -> Option<&Account> {
self.accounts.get(&address.into())
}
/// Deploy a smart contract module using the same validation rules as
/// enforced by the node.
///
/// The `WasmModule` can be loaded from disk with either
/// [`module_load_v1`] or [`module_load_v1_raw`].
///
/// Parameters:
/// - `signer`: the signer with a number of keys, which affects the cost.
/// - `sender`: the sender account.
/// - `module`: the v1 wasm module.
pub fn module_deploy_v1(
&mut self,
signer: Signer,
sender: AccountAddress,
wasm_module: WasmModule,
) -> Result<ModuleDeploySuccess, ModuleDeployError> {
self.module_deploy_v1_debug(signer, sender, wasm_module, false)
}
/// Like [`module_deploy_v1`](Self::module_deploy_v1)
/// except that optionally debugging output may be allowed in the module.
pub fn module_deploy_v1_debug(
&mut self,
signer: Signer,
sender: AccountAddress,
wasm_module: WasmModule,
enable_debug: bool,
) -> Result<ModuleDeploySuccess, ModuleDeployError> {
// For maintainers:
//
// This function does not correspond exactly to what happens in the node.
// There a user is also expected to give a max energy bound and the failures are
// slightly different. There it is possible to fail with "out of energy"
// error whereas here we only fail with "insufficient funds" if the user does
// not have enough CCD to pay.
//
// If users use our tools to deploy modules the costs are calculated for them so
// that deployment should never fail with out of energy. Not requiring energy
// provides a more ergonomic experience.
let Ok(sender_account) = self.accounts.get_mut(&sender.into()).ok_or(AccountDoesNotExist {
address: sender,
}) else {
// Ensure sender account exists.
return Err(ModuleDeployError {
kind: ModuleDeployErrorKind::SenderDoesNotExist(AccountDoesNotExist {
address: sender,
}),
energy_used: 0.into(),
transaction_fee: Amount::zero(),
});
};
// Only v1 modules are supported in this testing library.
// This error case does not exist in the node, so we don't need to match a
// specific cost. We charge 0 for it.
if wasm_module.version != WasmVersion::V1 {
return Err(ModuleDeployError {
kind: ModuleDeployErrorKind::UnsupportedModuleVersion(
wasm_module.version,
),
energy_used: 0.into(),
transaction_fee: Amount::zero(),
});
}
let parameters = &self.parameters;
let check_header_energy = {
// +1 for the tag, +8 for size and version
let payload_size = 1
+ 8
+ wasm_module.source.size()
+ transactions::construct::TRANSACTION_HEADER_SIZE;
cost::base_cost(payload_size, signer.num_keys)
};
// Calculate the deploy module cost.
let deploy_module_energy = cost::deploy_module(wasm_module.source.size());
let energy_used = check_header_energy + deploy_module_energy;
let transaction_fee = parameters.calculate_energy_cost(energy_used);
// Check if the account has sufficient balance to cover the transaction fee.
// This fee corresponds to the energy_reserved that our tools calculate when
// sending the transaction to the node. The account is not charged in the node
// unless it has sufficient balance to pay for the full deployment (and thus all
// the energy).
if sender_account.balance.available() < transaction_fee {
return Err(ModuleDeployError {
kind: ModuleDeployErrorKind::InsufficientFunds,
energy_used: 0.into(),
transaction_fee: Amount::zero(),
});
};
// Charge the account.
sender_account.balance.total -= transaction_fee;
// Construct the artifact.
let artifact = match wasm::utils::instantiate_with_metering::<v1::ProcessedImports>(
ValidationConfig::V1,
CostConfigurationV1,
&v1::ConcordiumAllowedImports {
support_upgrade: true,
enable_debug,
},
wasm_module.source.as_ref(),
) {
Ok(artifact) => artifact,
Err(err) => {
return Err(ModuleDeployError {
kind: ModuleInvalidError(err).into(),
energy_used,
transaction_fee,
})
}
};
let module_reference: ModuleReference = wasm_module.get_module_ref();
// Ensure module hasn't been deployed before.
if self.modules.contains_key(&module_reference) {
return Err(ModuleDeployError {
kind: ModuleDeployErrorKind::DuplicateModule(module_reference),
energy_used,
transaction_fee,
});
}
self.modules.insert(module_reference, ContractModule {
// we follow protocol 6 semantics, and don't count the custom section size towards
// module size.
size: wasm_module.source.size().saturating_sub(artifact.custom_sections_size),
artifact: Arc::new(artifact.artifact),
});
Ok(ModuleDeploySuccess {
module_reference,
energy_used,
transaction_fee,
})
}
/// Initialize a contract.
///
/// **Parameters:**
/// - `signer`: the signer with a number of keys, which affects the cost.
/// - `sender`: The account paying for the transaction. Will also become
/// the owner of the contract created.
/// - `energy_reserved`: Amount of energy reserved for executing the init
/// method.
/// - `payload`:
/// - `amount`: The initial balance of the contract. Subtracted from the
/// `sender` account.
/// - `mod_ref`: The reference to the a module that has already been
/// deployed.
/// - `init_name`: Name of the contract to initialize.
/// - `param`: Parameter provided to the init method.
pub fn contract_init(
&mut self,
signer: Signer,
sender: AccountAddress,
energy_reserved: Energy,
payload: InitContractPayload,
) -> Result<ContractInitSuccess, ContractInitError> {
let mut remaining_energy = energy_reserved;
if !self.account_exists(sender) {
return Err(self.convert_to_init_error(
ContractInitErrorKind::SenderDoesNotExist(AccountDoesNotExist {
address: sender,
}),
energy_reserved,
remaining_energy,
));
}
let res = self.contract_init_worker(
signer,
sender,
energy_reserved,
payload,
&mut remaining_energy,
);
let (res, transaction_fee) = match res {
Ok(s) => {
let transaction_fee = s.transaction_fee;
(Ok(s), transaction_fee)
}
Err(e) => {
let err = self.convert_to_init_error(e, energy_reserved, remaining_energy);
let transaction_fee = err.transaction_fee;
(Err(err), transaction_fee)
}
};
// Charge the account.
self.account_mut(sender).expect("existence already checked").balance.total -=
transaction_fee;
res
}
/// Helper method for initializing contracts, which does most of the actual
/// work.
///
/// The main reason for splitting init in two is to have this method return
/// early if it runs out of energy. `contract_init` will then always
/// ensure to charge the account for the energy used.
fn contract_init_worker(
&mut self,
signer: Signer,
sender: AccountAddress,
energy_reserved: Energy,
payload: InitContractPayload,
remaining_energy: &mut Energy,
) -> Result<ContractInitSuccess, ContractInitErrorKind> {
// Get the account and check that it has sufficient balance to pay for the
// reserved_energy and amount.
let account_info = self.account(sender)?;
let energy_reserved_cost = self.parameters.calculate_energy_cost(energy_reserved);
// Check that the account can pay for the reserved energy.
if account_info.balance.available() < energy_reserved_cost {
return Err(ContractInitErrorKind::InsufficientFunds);
}
// Compute the base cost for checking the transaction header.
let check_header_cost = {
// 1 byte for the tag.
let transaction_size =
transactions::construct::TRANSACTION_HEADER_SIZE + 1 + payload.size() as u64;
transactions::cost::base_cost(transaction_size, signer.num_keys)
};
// Charge the header cost.
exit_ooe!(remaining_energy.tick_energy(check_header_cost), DebugTracker::empty_trace());
// Ensure that the parameter has a valid size.
if payload.param.as_ref().len() > contracts_common::constants::MAX_PARAMETER_LEN {
return Err(ContractInitErrorKind::ParameterTooLarge);
}
// Charge the base cost for initializing a contract.
exit_ooe!(
remaining_energy.tick_energy(constants::INITIALIZE_CONTRACT_INSTANCE_BASE_COST),
DebugTracker::empty_trace()
);
// Check that the account also has enough funds to pay for the amount (in
// addition to the reserved energy).
if account_info.balance.available() < energy_reserved_cost + payload.amount {
return Err(ContractInitErrorKind::AmountTooLarge);
}
// Lookup module.
let module = self.contract_module(payload.mod_ref)?;
let lookup_cost = lookup_module_cost(&module);
// Charge the cost for looking up the module.
exit_ooe!(remaining_energy.tick_energy(lookup_cost), DebugTracker::empty_trace());
// Ensure the module contains the provided init name.
let init_name = payload.init_name.as_contract_name().get_chain_name();
if !module.artifact.export.contains_key(init_name) {
return Err(ContractInitErrorKind::ContractNotPresentInModule {
name: payload.init_name,
});
}
// Sender policies have a very bespoke serialization in
// order to allow skipping portions of them in smart contracts.
let sender_policies = {
let mut out = Vec::new();
account_info
.policy
.serial_for_smart_contract(&mut out)
.expect("Writing to a vector should succeed.");
out
};
// Construct the context.
let init_ctx = v0::InitContext {
metadata: ChainMetadata {
slot_time: self.parameters.block_time,
},
init_origin: sender,
sender_policies,
};
// Initialize contract
// We create an empty loader as no caching is used in this testing library
// presently, so the loader is not used.
let mut loader = v1::trie::Loader::new(&[][..]);
let energy_given_to_interpreter =
InterpreterEnergy::new(to_interpreter_energy(*remaining_energy));
let res = v1::invoke_init::<_, _, DebugTracker>(
module.artifact,
init_ctx,
v1::InitInvocation {
amount: payload.amount,
init_name,
parameter: payload.param.as_ref(),
energy: energy_given_to_interpreter,
},
false, // We only support protocol P5 and up, so no limiting.
loader,
);
// Handle the result
match res {
Ok(v1::InitResult::Success {
logs,
return_value: _, /* Ignore return value for now, since our tools do not support
* it for inits, currently. */
remaining_energy: remaining_interpreter_energy,
mut state,
trace,
}) => {
let contract_address = self.create_contract_address();
let mut collector = v1::trie::SizeCollector::default();
let persisted_state = state.freeze(&mut loader, &mut collector);
// Perform the subtraction in the more finegrained (*1000) `InterpreterEnergy`,
// and *then* convert to `Energy`. This is how it is done in the node, and if we
// swap the operations, it can result in a small discrepancy due to rounding.
let energy_used_in_interpreter = from_interpreter_energy(
&energy_given_to_interpreter.saturating_sub(&remaining_interpreter_energy),
);
exit_ooe!(remaining_energy.tick_energy(energy_used_in_interpreter), trace);
// Charge one energy per stored state byte.
let energy_for_state_storage = Energy::from(collector.collect());
exit_ooe!(remaining_energy.tick_energy(energy_for_state_storage), trace);
// Charge the constant cost for initializing a contract.
exit_ooe!(
remaining_energy
.tick_energy(constants::INITIALIZE_CONTRACT_INSTANCE_CREATE_COST),
trace
);
let contract = Contract {
module_reference: payload.mod_ref,
contract_name: payload.init_name,
state: persisted_state,
owner: sender,
self_balance: payload.amount,
address: contract_address,
};
// Save the contract.
self.contracts.insert(contract_address, contract);
// Subtract the amount from the invoker.
self.account_mut(sender).expect("Account known to exist").balance.total -=
payload.amount;
let energy_used = energy_reserved - *remaining_energy;
let transaction_fee = self.parameters.calculate_energy_cost(energy_used);
Ok(ContractInitSuccess {
contract_address,
events: contract_events_from_logs(logs),
energy_used,
transaction_fee,
debug_trace: trace,
})
}
Ok(v1::InitResult::Reject {
reason,
return_value,
remaining_energy: remaining_interpreter_energy,
trace,
}) => {
let energy_used_in_interpreter = from_interpreter_energy(
&energy_given_to_interpreter.saturating_sub(&remaining_interpreter_energy),
);
exit_ooe!(remaining_energy.tick_energy(energy_used_in_interpreter), trace);
Err(ContractInitErrorKind::ExecutionError {
error: InitExecutionError::Reject {
reason,
return_value,
},
debug_trace: trace,
})
}
Ok(v1::InitResult::Trap {
error,
remaining_energy: remaining_interpreter_energy,
trace,
}) => {
let energy_used_in_interpreter = from_interpreter_energy(
&energy_given_to_interpreter.saturating_sub(&remaining_interpreter_energy),
);
exit_ooe!(remaining_energy.tick_energy(energy_used_in_interpreter), trace);
Err(ContractInitErrorKind::ExecutionError {
error: InitExecutionError::Trap {
error: error.into(),
},
debug_trace: trace,
})
}
Ok(v1::InitResult::OutOfEnergy {
trace,
}) => {
*remaining_energy = Energy::from(0);
Err(ContractInitErrorKind::ExecutionError {
error: InitExecutionError::OutOfEnergy,
debug_trace: trace,
})
}
Err(InvalidReturnCodeError {
value,
debug_trace,
}) => Err(ContractInitErrorKind::ExecutionError {
error: InitExecutionError::Trap {
error: anyhow::anyhow!("Invalid return value received: {value:?}").into(),
},
debug_trace,
}),
}
}
/// Helper method that handles contract invocation.
///
/// *Preconditions:*
/// - `invoker` exists.
/// - `sender` exists.
/// - `invoker` has sufficient balance to pay for `energy_reserved`.
fn contract_invocation_worker(
&self,
invoker: AccountAddress,
sender: Address,
energy_reserved: Energy,
amount_reserved_for_energy: Amount,
payload: UpdateContractPayload,
remaining_energy: &mut Energy,
) -> Result<(InvokeResponse, ChangeSet, Vec<DebugTraceElement>, Energy), ContractInvokeError>
{
// Check if the contract to invoke exists.
if !self.contract_exists(payload.address) {
return Err(self.convert_to_invoke_error(
ContractDoesNotExist {
address: payload.address,
}
.into(),
Vec::new(),
energy_reserved,
*remaining_energy,
0.into(),
));
}
// Ensure that the parameter has a valid size.
if payload.message.as_ref().len() > contracts_common::constants::MAX_PARAMETER_LEN {
return Err(self.convert_to_invoke_error(
ContractInvokeErrorKind::ParameterTooLarge,
Vec::new(),
energy_reserved,
*remaining_energy,
0.into(),
));
}
// Check that the invoker has sufficient funds to pay for amount (in addition to
// the energy reserved, which is already checked).
if self
.account(invoker)
.expect("Precondition violation: must already exist")
.balance
.available()
< amount_reserved_for_energy + payload.amount
{
return Err(self.convert_to_invoke_error(
ContractInvokeErrorKind::AmountTooLarge,
Vec::new(),
energy_reserved,
*remaining_energy,
0.into(),
));
}
let mut contract_invocation = EntrypointInvocationHandler {
changeset: ChangeSet::new(),
remaining_energy,
energy_reserved,
chain: self,
reserved_amount: amount_reserved_for_energy,
invoker,
// Starts at 1 since 0 is the "initial state" of all contracts in the current
// transaction.
next_contract_modification_index: 1,
module_load_energy: 0.into(),
};
let module_load_energy = contract_invocation.module_load_energy;
let res = contract_invocation.invoke_entrypoint(invoker, sender, payload);
match res {
Ok((result, trace_elements)) => Ok((
result,
contract_invocation.changeset,
trace_elements,
contract_invocation.module_load_energy,
)),
Err(err) => Err(self.convert_to_invoke_error(
err.into(),
Vec::new(),
energy_reserved,
*remaining_energy,
module_load_energy,
)),
}