-
Notifications
You must be signed in to change notification settings - Fork 647
/
contexts.rs
2194 lines (1949 loc) · 72.2 KB
/
contexts.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
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::mem::replace;
//use hashbrown::{HashMap, HashSet};
use serde::Serialize;
use serde_json::json;
use stacks_common::consts::CHAIN_ID_TESTNET;
use stacks_common::types::chainstate::StacksBlockId;
use stacks_common::types::{StacksEpochId, StacksHashMap as HashMap, StacksHashSet as HashSet};
use super::EvalHook;
use crate::vm::ast::{ASTRules, ContractAST};
use crate::vm::callables::{DefinedFunction, FunctionIdentifier};
use crate::vm::contracts::Contract;
use crate::vm::costs::cost_functions::ClarityCostFunction;
use crate::vm::costs::{
cost_functions, runtime_cost, ClarityCostFunctionReference, CostErrors, CostTracker,
ExecutionCost, LimitedCostTracker,
};
use crate::vm::database::{
ClarityDatabase, DataMapMetadata, DataVariableMetadata, FungibleTokenMetadata,
NonFungibleTokenMetadata,
};
use crate::vm::errors::{
CheckErrors, InterpreterError, InterpreterResult as Result, RuntimeErrorType,
};
use crate::vm::events::*;
use crate::vm::representations::{ClarityName, ContractName, SymbolicExpression};
use crate::vm::types::signatures::FunctionSignature;
use crate::vm::types::{
AssetIdentifier, BuffData, CallableData, OptionalData, PrincipalData,
QualifiedContractIdentifier, TraitIdentifier, TypeSignature, Value,
};
use crate::vm::version::ClarityVersion;
use crate::vm::{ast, eval, is_reserved, stx_transfer_consolidated};
pub const MAX_CONTEXT_DEPTH: u16 = 256;
// TODO:
// hide the environment's instance variables.
// we don't want many of these changing after instantiation.
/// Environments pack a reference to the global context (which is basically the db),
/// the current contract context, a call stack, the current sender, caller, and
/// sponsor (if one exists).
/// Essentially, the point of the Environment struct is to prevent all the eval functions
/// from including all of these items in their method signatures individually. Because
/// these different contexts can be mixed and matched (i.e., in a contract-call, you change
/// contract context), a single "invocation" will end up creating multiple environment
/// objects as context changes occur.
pub struct Environment<'a, 'b, 'hooks> {
pub global_context: &'a mut GlobalContext<'b, 'hooks>,
pub contract_context: &'a ContractContext,
pub call_stack: &'a mut CallStack,
pub sender: Option<PrincipalData>,
pub caller: Option<PrincipalData>,
pub sponsor: Option<PrincipalData>,
}
pub struct OwnedEnvironment<'a, 'hooks> {
context: GlobalContext<'a, 'hooks>,
call_stack: CallStack,
}
#[derive(Debug, PartialEq, Eq)]
pub enum AssetMapEntry {
STX(u128),
Burn(u128),
Token(u128),
Asset(Vec<Value>),
}
/**
The AssetMap is used to track which assets have been transfered from whom
during the execution of a transaction.
*/
#[derive(Debug, Clone)]
pub struct AssetMap {
stx_map: HashMap<PrincipalData, u128>,
burn_map: HashMap<PrincipalData, u128>,
token_map: HashMap<PrincipalData, HashMap<AssetIdentifier, u128>>,
asset_map: HashMap<PrincipalData, HashMap<AssetIdentifier, Vec<Value>>>,
}
impl AssetMap {
pub fn to_json(&self) -> serde_json::Value {
let stx: serde_json::map::Map<_, _> = self
.stx_map
.iter()
.map(|(principal, amount)| {
(
format!("{}", principal),
serde_json::value::Value::String(format!("{}", amount)),
)
})
.collect();
let burns: serde_json::map::Map<_, _> = self
.burn_map
.iter()
.map(|(principal, amount)| {
(
format!("{}", principal),
serde_json::value::Value::String(format!("{}", amount)),
)
})
.collect();
let tokens: serde_json::map::Map<_, _> = self
.token_map
.iter()
.map(|(principal, token_map)| {
let token_json: serde_json::map::Map<_, _> = token_map
.iter()
.map(|(asset_id, amount)| {
(
format!("{}", asset_id),
serde_json::value::Value::String(format!("{}", amount)),
)
})
.collect();
(
format!("{}", principal),
serde_json::value::Value::Object(token_json),
)
})
.collect();
let assets: serde_json::map::Map<_, _> = self
.asset_map
.iter()
.map(|(principal, nft_map)| {
let nft_json: serde_json::map::Map<_, _> = nft_map
.iter()
.map(|(asset_id, nft_values)| {
let nft_array = nft_values
.iter()
.map(|nft_value| {
serde_json::value::Value::String(format!("{}", nft_value))
})
.collect();
(
format!("{}", asset_id),
serde_json::value::Value::Array(nft_array),
)
})
.collect();
(
format!("{}", principal),
serde_json::value::Value::Object(nft_json),
)
})
.collect();
json!({
"stx": stx,
"burns": burns,
"tokens": tokens,
"assets": assets
})
}
}
#[derive(Debug, Clone)]
pub struct EventBatch {
pub events: Vec<StacksTransactionEvent>,
}
/** GlobalContext represents the outermost context for a single transaction's
execution. It tracks an asset changes that occurred during the
processing of the transaction, whether or not the current context is read_only,
and is responsible for committing/rolling-back transactions as they error or
abort.
*/
pub struct GlobalContext<'a, 'hooks> {
asset_maps: Vec<AssetMap>,
pub event_batches: Vec<EventBatch>,
pub database: ClarityDatabase<'a>,
read_only: Vec<bool>,
pub cost_track: LimitedCostTracker,
pub mainnet: bool,
/// This is the epoch of the the block that this transaction is executing within.
pub epoch_id: StacksEpochId,
/// This is the chain ID of the transaction
pub chain_id: u32,
pub eval_hooks: Option<Vec<&'hooks mut dyn EvalHook>>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "testing", derive(fake::Dummy))]
pub struct ContractContext {
pub contract_identifier: QualifiedContractIdentifier,
pub variables: HashMap<ClarityName, Value>,
pub functions: HashMap<ClarityName, DefinedFunction>,
pub defined_traits: HashMap<ClarityName, BTreeMap<ClarityName, FunctionSignature>>,
pub implemented_traits: HashSet<TraitIdentifier>,
// tracks the names of NFTs, FTs, Maps, and Data Vars.
// used for ensuring that they never are defined twice.
pub persisted_names: HashSet<ClarityName>,
// track metadata for contract defined storage
pub meta_data_map: HashMap<ClarityName, DataMapMetadata>,
pub meta_data_var: HashMap<ClarityName, DataVariableMetadata>,
pub meta_nft: HashMap<ClarityName, NonFungibleTokenMetadata>,
pub meta_ft: HashMap<ClarityName, FungibleTokenMetadata>,
pub data_size: u64,
/// track the clarity version of the contract
clarity_version: ClarityVersion,
}
pub struct LocalContext<'a> {
pub function_context: Option<&'a LocalContext<'a>>,
pub parent: Option<&'a LocalContext<'a>>,
pub variables: HashMap<ClarityName, Value>,
pub callable_contracts: HashMap<ClarityName, CallableData>,
depth: u16,
}
pub struct CallStack {
stack: Vec<FunctionIdentifier>,
set: HashSet<FunctionIdentifier>,
apply_depth: usize,
}
pub type StackTrace = Vec<FunctionIdentifier>;
pub const TRANSIENT_CONTRACT_NAME: &str = "__transient";
impl AssetMap {
pub fn new() -> AssetMap {
AssetMap {
stx_map: HashMap::new(),
burn_map: HashMap::new(),
token_map: HashMap::new(),
asset_map: HashMap::new(),
}
}
// This will get the next amount for a (principal, stx) entry in the stx table.
fn get_next_stx_amount(&self, principal: &PrincipalData, amount: u128) -> Result<u128> {
let current_amount = self.stx_map.get(principal).unwrap_or(&0);
current_amount
.checked_add(amount)
.ok_or(RuntimeErrorType::ArithmeticOverflow.into())
}
// This will get the next amount for a (principal, stx) entry in the burn table.
fn get_next_stx_burn_amount(&self, principal: &PrincipalData, amount: u128) -> Result<u128> {
let current_amount = self.burn_map.get(principal).unwrap_or(&0);
current_amount
.checked_add(amount)
.ok_or(RuntimeErrorType::ArithmeticOverflow.into())
}
// This will get the next amount for a (principal, asset) entry in the asset table.
fn get_next_amount(
&self,
principal: &PrincipalData,
asset: &AssetIdentifier,
amount: u128,
) -> Result<u128> {
let current_amount = match self.token_map.get(principal) {
Some(principal_map) => *principal_map.get(asset).unwrap_or(&0),
None => 0,
};
current_amount
.checked_add(amount)
.ok_or(RuntimeErrorType::ArithmeticOverflow.into())
}
pub fn add_stx_transfer(&mut self, principal: &PrincipalData, amount: u128) -> Result<()> {
let next_amount = self.get_next_stx_amount(principal, amount)?;
self.stx_map.insert(principal.clone(), next_amount);
Ok(())
}
pub fn add_stx_burn(&mut self, principal: &PrincipalData, amount: u128) -> Result<()> {
let next_amount = self.get_next_stx_burn_amount(principal, amount)?;
self.burn_map.insert(principal.clone(), next_amount);
Ok(())
}
pub fn add_asset_transfer(
&mut self,
principal: &PrincipalData,
asset: AssetIdentifier,
transfered: Value,
) {
let principal_map = self
.asset_map
.entry(principal.clone())
.or_insert_with(|| HashMap::new());
if let Some(map_entry) = principal_map.get_mut(&asset) {
map_entry.push(transfered);
} else {
principal_map.insert(asset, vec![transfered]);
}
}
pub fn add_token_transfer(
&mut self,
principal: &PrincipalData,
asset: AssetIdentifier,
amount: u128,
) -> Result<()> {
let next_amount = self.get_next_amount(principal, &asset, amount)?;
let principal_map = self
.token_map
.entry(principal.clone())
.or_insert_with(|| HashMap::new());
principal_map.insert(asset, next_amount);
Ok(())
}
// This will add any asset transfer data from other to self,
// aborting _all_ changes in the event of an error, leaving self unchanged
pub fn commit_other(&mut self, mut other: AssetMap) -> Result<()> {
let mut to_add = Vec::new();
let mut stx_to_add = Vec::with_capacity(other.stx_map.len());
let mut stx_burn_to_add = Vec::with_capacity(other.burn_map.len());
for (principal, mut principal_map) in other.token_map.drain() {
for (asset, amount) in principal_map.drain() {
let next_amount = self.get_next_amount(&principal, &asset, amount)?;
to_add.push((principal.clone(), asset, next_amount));
}
}
for (principal, stx_amount) in other.stx_map.drain() {
let next_amount = self.get_next_stx_amount(&principal, stx_amount)?;
stx_to_add.push((principal.clone(), next_amount));
}
for (principal, stx_burn_amount) in other.burn_map.drain() {
let next_amount = self.get_next_stx_burn_amount(&principal, stx_burn_amount)?;
stx_burn_to_add.push((principal.clone(), next_amount));
}
// After this point, this function will not fail.
for (principal, mut principal_map) in other.asset_map.drain() {
for (asset, mut transfers) in principal_map.drain() {
let landing_map = self
.asset_map
.entry(principal.clone())
.or_insert_with(|| HashMap::new());
if let Some(landing_vec) = landing_map.get_mut(&asset) {
landing_vec.append(&mut transfers);
} else {
landing_map.insert(asset, transfers);
}
}
}
for (principal, stx_amount) in stx_to_add.into_iter() {
self.stx_map.insert(principal, stx_amount);
}
for (principal, stx_burn_amount) in stx_burn_to_add.into_iter() {
self.burn_map.insert(principal, stx_burn_amount);
}
for (principal, asset, amount) in to_add.into_iter() {
let principal_map = self
.token_map
.entry(principal)
.or_insert_with(|| HashMap::new());
principal_map.insert(asset, amount);
}
Ok(())
}
pub fn to_table(mut self) -> HashMap<PrincipalData, HashMap<AssetIdentifier, AssetMapEntry>> {
let mut map = HashMap::new();
for (principal, mut principal_map) in self.token_map.drain() {
let mut output_map = HashMap::new();
for (asset, amount) in principal_map.drain() {
output_map.insert(asset, AssetMapEntry::Token(amount));
}
map.insert(principal, output_map);
}
for (principal, stx_amount) in self.stx_map.drain() {
let output_map = map
.entry(principal.clone())
.or_insert_with(|| HashMap::new());
output_map.insert(
AssetIdentifier::STX(),
AssetMapEntry::STX(stx_amount as u128),
);
}
for (principal, stx_burned_amount) in self.burn_map.drain() {
let output_map = map
.entry(principal.clone())
.or_insert_with(|| HashMap::new());
output_map.insert(
AssetIdentifier::STX_burned(),
AssetMapEntry::Burn(stx_burned_amount as u128),
);
}
for (principal, mut principal_map) in self.asset_map.drain() {
let output_map = map
.entry(principal.clone())
.or_insert_with(|| HashMap::new());
for (asset, transfers) in principal_map.drain() {
output_map.insert(asset, AssetMapEntry::Asset(transfers));
}
}
return map;
}
pub fn get_stx(&self, principal: &PrincipalData) -> Option<u128> {
match self.stx_map.get(principal) {
Some(value) => Some(*value),
None => None,
}
}
pub fn get_stx_burned(&self, principal: &PrincipalData) -> Option<u128> {
match self.burn_map.get(principal) {
Some(value) => Some(*value),
None => None,
}
}
pub fn get_stx_burned_total(&self) -> Result<u128> {
let mut total: u128 = 0;
for principal in self.burn_map.keys() {
total = total
.checked_add(*self.burn_map.get(principal).unwrap_or(&0u128))
.ok_or_else(|| InterpreterError::Expect("BURN OVERFLOW".into()))?;
}
Ok(total)
}
pub fn get_fungible_tokens(
&self,
principal: &PrincipalData,
asset_identifier: &AssetIdentifier,
) -> Option<u128> {
match self.token_map.get(principal) {
Some(ref assets) => match assets.get(asset_identifier) {
Some(value) => Some(*value),
None => None,
},
None => None,
}
}
pub fn get_nonfungible_tokens(
&self,
principal: &PrincipalData,
asset_identifier: &AssetIdentifier,
) -> Option<&Vec<Value>> {
match self.asset_map.get(principal) {
Some(ref assets) => match assets.get(asset_identifier) {
Some(values) => Some(values),
None => None,
},
None => None,
}
}
}
impl fmt::Display for AssetMap {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[")?;
for (principal, principal_map) in self.token_map.iter() {
for (asset, amount) in principal_map.iter() {
write!(f, "{} spent {} {}\n", principal, amount, asset)?;
}
}
for (principal, principal_map) in self.asset_map.iter() {
for (asset, transfer) in principal_map.iter() {
write!(f, "{} transfered [", principal)?;
for t in transfer {
write!(f, "{}, ", t)?;
}
write!(f, "] {}\n", asset)?;
}
}
for (principal, stx_amount) in self.stx_map.iter() {
write!(f, "{} spent {} microSTX\n", principal, stx_amount)?;
}
for (principal, stx_burn_amount) in self.burn_map.iter() {
write!(f, "{} burned {} microSTX\n", principal, stx_burn_amount)?;
}
write!(f, "]")
}
}
impl EventBatch {
pub fn new() -> EventBatch {
EventBatch { events: vec![] }
}
}
impl<'a, 'hooks> OwnedEnvironment<'a, 'hooks> {
#[cfg(any(test, feature = "testing"))]
pub fn new(database: ClarityDatabase<'a>, epoch: StacksEpochId) -> OwnedEnvironment<'a, '_> {
OwnedEnvironment {
context: GlobalContext::new(
false,
CHAIN_ID_TESTNET,
database,
LimitedCostTracker::new_free(),
epoch,
),
call_stack: CallStack::new(),
}
}
#[cfg(any(test, feature = "testing"))]
pub fn new_toplevel(mut database: ClarityDatabase<'a>) -> OwnedEnvironment<'a, '_> {
database.begin();
let epoch = database.get_clarity_epoch_version().unwrap();
let version = ClarityVersion::default_for_epoch(epoch);
database.roll_back().unwrap();
debug!(
"Begin OwnedEnvironment(epoch = {}, version = {})",
&epoch, &version
);
OwnedEnvironment {
context: GlobalContext::new(
false,
CHAIN_ID_TESTNET,
database,
LimitedCostTracker::new_free(),
epoch,
),
call_stack: CallStack::new(),
}
}
#[cfg(any(test, feature = "testing"))]
pub fn new_max_limit(
mut database: ClarityDatabase<'a>,
epoch: StacksEpochId,
use_mainnet: bool,
) -> OwnedEnvironment<'a, '_> {
use crate::vm::tests::test_only_mainnet_to_chain_id;
let cost_track = LimitedCostTracker::new_max_limit(&mut database, epoch, use_mainnet)
.expect("FAIL: problem instantiating cost tracking");
let chain_id = test_only_mainnet_to_chain_id(use_mainnet);
OwnedEnvironment {
context: GlobalContext::new(use_mainnet, chain_id, database, cost_track, epoch),
call_stack: CallStack::new(),
}
}
pub fn new_free(
mainnet: bool,
chain_id: u32,
database: ClarityDatabase<'a>,
epoch_id: StacksEpochId,
) -> OwnedEnvironment<'a, '_> {
OwnedEnvironment {
context: GlobalContext::new(
mainnet,
chain_id,
database,
LimitedCostTracker::new_free(),
epoch_id,
),
call_stack: CallStack::new(),
}
}
pub fn new_cost_limited(
mainnet: bool,
chain_id: u32,
database: ClarityDatabase<'a>,
cost_tracker: LimitedCostTracker,
epoch_id: StacksEpochId,
) -> OwnedEnvironment<'a, '_> {
OwnedEnvironment {
context: GlobalContext::new(mainnet, chain_id, database, cost_tracker, epoch_id),
call_stack: CallStack::new(),
}
}
pub fn get_exec_environment<'b>(
&'b mut self,
sender: Option<PrincipalData>,
sponsor: Option<PrincipalData>,
context: &'b ContractContext,
) -> Environment<'b, 'a, 'hooks> {
Environment::new(
&mut self.context,
context,
&mut self.call_stack,
sender.clone(),
sender,
sponsor,
)
}
pub fn execute_in_env<F, A, E>(
&mut self,
sender: PrincipalData,
sponsor: Option<PrincipalData>,
initial_context: Option<ContractContext>,
f: F,
) -> std::result::Result<(A, AssetMap, Vec<StacksTransactionEvent>), E>
where
E: From<crate::vm::errors::Error>,
F: FnOnce(&mut Environment) -> std::result::Result<A, E>,
{
assert!(self.context.is_top_level());
self.begin();
let result = {
let mut initial_context = initial_context.unwrap_or(ContractContext::new(
QualifiedContractIdentifier::transient(),
ClarityVersion::Clarity1,
));
let mut exec_env =
self.get_exec_environment(Some(sender), sponsor, &mut initial_context);
f(&mut exec_env)
};
match result {
Ok(return_value) => {
let (asset_map, event_batch) = self.commit()?;
Ok((return_value, asset_map, event_batch.events))
}
Err(e) => {
self.context.roll_back()?;
Err(e)
}
}
}
/// Initialize a contract with the "default" contract context (i.e. clarity1, transient ID).
/// No longer appropriate outside of testing, now that there are multiple clarity versions.
#[cfg(any(test, feature = "testing"))]
pub fn initialize_contract(
&mut self,
contract_identifier: QualifiedContractIdentifier,
contract_content: &str,
sponsor: Option<PrincipalData>,
ast_rules: ASTRules,
) -> Result<((), AssetMap, Vec<StacksTransactionEvent>)> {
self.execute_in_env(
contract_identifier.issuer.clone().into(),
sponsor,
None,
|exec_env| {
exec_env.initialize_contract(contract_identifier, contract_content, ast_rules)
},
)
}
pub fn initialize_versioned_contract(
&mut self,
contract_identifier: QualifiedContractIdentifier,
version: ClarityVersion,
contract_content: &str,
sponsor: Option<PrincipalData>,
ast_rules: ASTRules,
) -> Result<((), AssetMap, Vec<StacksTransactionEvent>)> {
self.execute_in_env(
contract_identifier.issuer.clone().into(),
sponsor,
Some(ContractContext::new(
QualifiedContractIdentifier::transient(),
version,
)),
|exec_env| {
exec_env.initialize_contract(contract_identifier, contract_content, ast_rules)
},
)
}
pub fn initialize_contract_from_ast(
&mut self,
contract_identifier: QualifiedContractIdentifier,
clarity_version: ClarityVersion,
contract_content: &ContractAST,
contract_string: &str,
sponsor: Option<PrincipalData>,
) -> Result<((), AssetMap, Vec<StacksTransactionEvent>)> {
self.execute_in_env(
contract_identifier.issuer.clone().into(),
sponsor,
Some(ContractContext::new(
QualifiedContractIdentifier::transient(),
clarity_version,
)),
|exec_env| {
exec_env.initialize_contract_from_ast(
contract_identifier,
clarity_version,
contract_content,
contract_string,
)
},
)
}
pub fn execute_transaction(
&mut self,
sender: PrincipalData,
sponsor: Option<PrincipalData>,
contract_identifier: QualifiedContractIdentifier,
tx_name: &str,
args: &[SymbolicExpression],
) -> Result<(Value, AssetMap, Vec<StacksTransactionEvent>)> {
self.execute_in_env(sender, sponsor, None, |exec_env| {
exec_env.execute_contract(&contract_identifier, tx_name, args, false)
})
}
pub fn stx_transfer(
&mut self,
from: &PrincipalData,
to: &PrincipalData,
amount: u128,
memo: &BuffData,
) -> Result<(Value, AssetMap, Vec<StacksTransactionEvent>)> {
self.execute_in_env(from.clone(), None, None, |exec_env| {
exec_env.stx_transfer(from, to, amount, memo)
})
}
#[cfg(any(test, feature = "testing"))]
pub fn stx_faucet(&mut self, recipient: &PrincipalData, amount: u128) {
self.execute_in_env::<_, _, crate::vm::errors::Error>(
recipient.clone(),
None,
None,
|env| {
let mut snapshot = env
.global_context
.database
.get_stx_balance_snapshot(&recipient)
.unwrap();
snapshot.credit(amount).unwrap();
snapshot.save().unwrap();
env.global_context
.database
.increment_ustx_liquid_supply(amount)
.unwrap();
let res: std::result::Result<(), crate::vm::errors::Error> = Ok(());
res
},
)
.unwrap();
}
#[cfg(any(test, feature = "testing"))]
pub fn eval_raw(
&mut self,
program: &str,
) -> Result<(Value, AssetMap, Vec<StacksTransactionEvent>)> {
self.execute_in_env(
QualifiedContractIdentifier::transient().issuer.into(),
None,
None,
|exec_env| exec_env.eval_raw(program),
)
}
pub fn eval_read_only_with_rules(
&mut self,
contract: &QualifiedContractIdentifier,
program: &str,
ast_rules: ast::ASTRules,
) -> Result<(Value, AssetMap, Vec<StacksTransactionEvent>)> {
self.execute_in_env(
QualifiedContractIdentifier::transient().issuer.into(),
None,
None,
|exec_env| exec_env.eval_read_only_with_rules(contract, program, ast_rules),
)
}
#[cfg(any(test, feature = "testing"))]
pub fn eval_read_only(
&mut self,
contract: &QualifiedContractIdentifier,
program: &str,
) -> Result<(Value, AssetMap, Vec<StacksTransactionEvent>)> {
self.eval_read_only_with_rules(contract, program, ast::ASTRules::Typical)
}
pub fn begin(&mut self) {
self.context.begin();
}
pub fn commit(&mut self) -> Result<(AssetMap, EventBatch)> {
let (asset_map, event_batch) = self.context.commit()?;
let asset_map = asset_map.ok_or(InterpreterError::FailedToConstructAssetTable)?;
let event_batch = event_batch.ok_or(InterpreterError::FailedToConstructEventBatch)?;
Ok((asset_map, event_batch))
}
pub fn get_cost_total(&self) -> ExecutionCost {
self.context.cost_track.get_total()
}
/// Destroys this environment, returning ownership of its database reference.
/// If the context wasn't top-level (i.e., it had uncommitted data), return None,
/// because the database is not guaranteed to be in a sane state.
pub fn destruct(self) -> Option<(ClarityDatabase<'a>, LimitedCostTracker)> {
self.context.destruct()
}
pub fn add_eval_hook(&mut self, hook: &'hooks mut dyn EvalHook) {
if let Some(mut hooks) = self.context.eval_hooks.take() {
hooks.push(hook);
self.context.eval_hooks = Some(hooks);
} else {
self.context.eval_hooks = Some(vec![hook]);
}
}
}
impl CostTracker for Environment<'_, '_, '_> {
fn compute_cost(
&mut self,
cost_function: ClarityCostFunction,
input: &[u64],
) -> std::result::Result<ExecutionCost, CostErrors> {
self.global_context
.cost_track
.compute_cost(cost_function, input)
}
fn add_cost(&mut self, cost: ExecutionCost) -> std::result::Result<(), CostErrors> {
self.global_context.cost_track.add_cost(cost)
}
fn add_memory(&mut self, memory: u64) -> std::result::Result<(), CostErrors> {
self.global_context.cost_track.add_memory(memory)
}
fn drop_memory(&mut self, memory: u64) -> std::result::Result<(), CostErrors> {
self.global_context.cost_track.drop_memory(memory)
}
fn reset_memory(&mut self) {
self.global_context.cost_track.reset_memory()
}
fn short_circuit_contract_call(
&mut self,
contract: &QualifiedContractIdentifier,
function: &ClarityName,
input: &[u64],
) -> std::result::Result<bool, CostErrors> {
self.global_context
.cost_track
.short_circuit_contract_call(contract, function, input)
}
}
impl CostTracker for GlobalContext<'_, '_> {
fn compute_cost(
&mut self,
cost_function: ClarityCostFunction,
input: &[u64],
) -> std::result::Result<ExecutionCost, CostErrors> {
self.cost_track.compute_cost(cost_function, input)
}
fn add_cost(&mut self, cost: ExecutionCost) -> std::result::Result<(), CostErrors> {
self.cost_track.add_cost(cost)
}
fn add_memory(&mut self, memory: u64) -> std::result::Result<(), CostErrors> {
self.cost_track.add_memory(memory)
}
fn drop_memory(&mut self, memory: u64) -> std::result::Result<(), CostErrors> {
self.cost_track.drop_memory(memory)
}
fn reset_memory(&mut self) {
self.cost_track.reset_memory()
}
fn short_circuit_contract_call(
&mut self,
contract: &QualifiedContractIdentifier,
function: &ClarityName,
input: &[u64],
) -> std::result::Result<bool, CostErrors> {
self.cost_track
.short_circuit_contract_call(contract, function, input)
}
}
impl<'a, 'b, 'hooks> Environment<'a, 'b, 'hooks> {
/// Returns an Environment value & checks the types of the contract sender, caller, and sponsor
///
/// # Panics
/// Panics if the Value types for sender (Principal), caller (Principal), or sponsor
/// (Optional Principal) are incorrect.
pub fn new(
global_context: &'a mut GlobalContext<'b, 'hooks>,
contract_context: &'a ContractContext,
call_stack: &'a mut CallStack,
sender: Option<PrincipalData>,
caller: Option<PrincipalData>,
sponsor: Option<PrincipalData>,
) -> Environment<'a, 'b, 'hooks> {
Environment {
global_context,
contract_context,
call_stack,
sender,
caller,
sponsor,
}
}
/// Leaving sponsor value as is for this new context (as opposed to setting it to None)
pub fn nest_as_principal<'c>(
&'c mut self,
sender: PrincipalData,
) -> Environment<'c, 'b, 'hooks> {
Environment::new(
self.global_context,
self.contract_context,
self.call_stack,
Some(sender.clone()),
Some(sender),
self.sponsor.clone(),
)
}
pub fn nest_with_caller<'c>(
&'c mut self,
caller: PrincipalData,
) -> Environment<'c, 'b, 'hooks> {
Environment::new(
self.global_context,
self.contract_context,
self.call_stack,
self.sender.clone(),
Some(caller),
self.sponsor.clone(),
)
}
pub fn eval_read_only_with_rules(
&mut self,
contract_identifier: &QualifiedContractIdentifier,
program: &str,
rules: ast::ASTRules,
) -> Result<Value> {
let clarity_version = self.contract_context.clarity_version.clone();
let parsed = ast::build_ast_with_rules(
contract_identifier,
program,
self,
clarity_version,
self.global_context.epoch_id,
rules,
)?
.expressions;
if parsed.len() < 1 {
return Err(RuntimeErrorType::ParseError(
"Expected a program of at least length 1".to_string(),
)
.into());
}
self.global_context.begin();
let contract = self
.global_context
.database