-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathdatastore.rs
More file actions
1597 lines (1415 loc) · 56.4 KB
/
datastore.rs
File metadata and controls
1597 lines (1415 loc) · 56.4 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 std::cell::RefCell;
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use std::rc::Rc;
use std::vec;
use clarity::types::chainstate::{
BlockHeaderHash, BurnchainHeaderHash, ConsensusHash, SortitionId, StacksAddress, StacksBlockId,
TrieHash, VRFSeed,
};
use clarity::types::StacksEpochId;
use clarity::util::hash::Sha512Trunc256Sum;
use clarity::vm::analysis::{AnalysisDatabase, ContractAnalysis};
use clarity::vm::ast::build_ast;
use clarity::vm::contracts::Contract as ContractContextResponse;
use clarity::vm::database::clarity_db::ContractDataVarName;
use clarity::vm::database::clarity_store::ContractCommitment;
use clarity::vm::database::{
BurnStateDB, ClarityBackingStore, ClarityDatabase, ClaritySerializable, HeadersDB, StoreType,
};
use clarity::vm::errors::{VmExecutionError, VmInternalError};
use clarity::vm::{ContractContext, StacksEpoch};
use clarity_types::types::{
PrincipalData, QualifiedContractIdentifier, StandardPrincipalData, TupleData,
};
use pox_locking::handle_contract_call_special_cases;
use sha2::{Digest, Sha512_256};
use super::interpreter::BLOCK_LIMIT_MAINNET;
use super::remote_data::fs::{get_file_from_cache, write_file_to_cache};
use super::remote_data::{epoch_for_height, Block, HttpClient, Sortition};
use super::settings::RemoteNetworkInfo;
use crate::repl::remote_data::context;
// todo: export it from clarity
const CLARITY_STORAGE_BLOCK_TIME_KEY: &str = "_stx-data::clarity_storage::block_time";
const SECONDS_BETWEEN_BURN_BLOCKS: u64 = 600;
const SECONDS_BETWEEN_STACKS_BLOCKS: u64 = 10;
fn epoch_to_peer_version(epoch: StacksEpochId) -> u8 {
use clarity::consts::*;
match epoch {
StacksEpochId::Epoch10 => PEER_VERSION_EPOCH_1_0,
StacksEpochId::Epoch20 => PEER_VERSION_EPOCH_2_0,
StacksEpochId::Epoch2_05 => PEER_VERSION_EPOCH_2_05,
StacksEpochId::Epoch21 => PEER_VERSION_EPOCH_2_1,
StacksEpochId::Epoch22 => PEER_VERSION_EPOCH_2_2,
StacksEpochId::Epoch23 => PEER_VERSION_EPOCH_2_3,
StacksEpochId::Epoch24 => PEER_VERSION_EPOCH_2_4,
StacksEpochId::Epoch25 => PEER_VERSION_EPOCH_2_5,
StacksEpochId::Epoch30 => PEER_VERSION_EPOCH_3_0,
StacksEpochId::Epoch31 => PEER_VERSION_EPOCH_3_1,
StacksEpochId::Epoch32 => PEER_VERSION_EPOCH_3_2,
StacksEpochId::Epoch33 => PEER_VERSION_EPOCH_3_3,
StacksEpochId::Epoch34 => PEER_VERSION_EPOCH_3_4,
}
}
/// This stores all of the data for the Clarity VM, especially MARF values
/// It also includes the data needed for mainnet execution simulation (HTTP Client, FS Cache)
pub struct ClarityDatastore {
open_chain_tip: StacksBlockId,
current_chain_tip: Rc<RefCell<StacksBlockId>>,
store: HashMap<String, BTreeMap<u32, String>>,
metadata: HashMap<(String, String), String>,
height_at_chain_tip: HashMap<StacksBlockId, u32>,
chain_tip_at_height: HashMap<u32, StacksBlockId>,
remote_network_info: Option<RemoteNetworkInfo>,
remote_block_info_cache: Rc<RefCell<HashMap<StacksBlockId, Block>>>,
remote_sortition_cache: Rc<RefCell<HashMap<BurnchainHeaderHash, Sortition>>>,
fs_cache_location: PathBuf,
local_accounts: Vec<StandardPrincipalData>,
client: HttpClient,
}
impl Clone for ClarityDatastore {
fn clone(&self) -> Self {
// for performance optimization, a simnet session can be stored and cached
// when cloning the session (and the datastore), we do not want to keep the
// current_chain_tip RefCell value, but rather sync it with the open_chain_tip
*self.current_chain_tip.borrow_mut() = self.open_chain_tip.clone();
Self {
open_chain_tip: self.open_chain_tip.clone(),
current_chain_tip: Rc::clone(&self.current_chain_tip),
store: self.store.clone(),
metadata: self.metadata.clone(),
height_at_chain_tip: self.height_at_chain_tip.clone(),
chain_tip_at_height: self.chain_tip_at_height.clone(),
remote_network_info: self.remote_network_info.clone(),
remote_block_info_cache: Rc::clone(&self.remote_block_info_cache),
remote_sortition_cache: Rc::clone(&self.remote_sortition_cache),
fs_cache_location: self.fs_cache_location.clone(),
local_accounts: self.local_accounts.clone(),
client: self.client.clone(),
}
}
}
struct BurnBlockHashes {
header_hash: BurnchainHeaderHash,
consensus_hash: ConsensusHash,
vrf_seed: VRFSeed,
sortition_id: SortitionId,
}
#[derive(Clone, Debug)]
struct BurnBlockInfo {
consensus_hash: ConsensusHash,
vrf_seed: VRFSeed,
sortition_id: SortitionId,
burn_block_time: u64,
burn_chain_height: u32,
}
#[derive(Clone, Debug)]
pub struct StacksBlockInfo {
block_header_hash: BlockHeaderHash,
burn_block_header_hash: BurnchainHeaderHash,
stacks_block_time: u64,
}
#[derive(Clone, Debug)]
pub struct StacksConstants {
pub burn_start_height: u32,
pub pox_prepare_length: u32,
pub pox_reward_cycle_length: u32,
pub pox_rejection_fraction: u64,
}
impl Default for StacksConstants {
fn default() -> Self {
StacksConstants {
burn_start_height: 0,
pox_prepare_length: 50,
pox_reward_cycle_length: 1050,
pox_rejection_fraction: 0,
}
}
}
/// Store the Stacks and Burn blocks info
#[derive(Clone, Debug)]
pub struct Datastore {
genesis_id: StacksBlockId,
burn_chain_tip: BurnchainHeaderHash,
burn_chain_height: u32,
tenure_height: u32,
current_chain_tip: Rc<RefCell<StacksBlockId>>,
remote_block_info_cache: Rc<RefCell<HashMap<StacksBlockId, Block>>>,
remote_sortition_cache: Rc<RefCell<HashMap<BurnchainHeaderHash, Sortition>>>,
burn_blocks: HashMap<BurnchainHeaderHash, BurnBlockInfo>,
stacks_chain_height: u32,
stacks_blocks: HashMap<StacksBlockId, StacksBlockInfo>,
sortition_lookup: HashMap<SortitionId, BurnchainHeaderHash>,
tenure_height_at_stacks_height: HashMap<u32, u32>,
stacks_height_at_tenure_height: HashMap<u32, u32>,
consensus_hash_lookup: HashMap<ConsensusHash, SortitionId>,
current_epoch: StacksEpochId,
current_epoch_start_height: u32,
constants: StacksConstants,
remote_network_info: Option<RemoteNetworkInfo>,
initial_burn_height: u32,
client: HttpClient,
}
fn height_to_hashed_bytes(height: u32) -> [u8; 32] {
let input_bytes = height.to_be_bytes();
let mut hasher = Sha512_256::new();
hasher.update(input_bytes);
let hash = Sha512Trunc256Sum::from_hasher(hasher);
hash.0
}
impl BurnBlockHashes {
fn from_height(height: u32) -> Self {
let bytes = height_to_hashed_bytes(height);
let header_hash = {
let mut buffer = bytes;
buffer[0] = 2;
BurnchainHeaderHash::from_bytes(&buffer[0..32]).unwrap()
};
let consensus_hash = {
let mut buffer = bytes;
buffer[0] = 3;
ConsensusHash::from_bytes(&buffer[0..20]).unwrap()
};
let vrf_seed = {
let mut buffer = bytes;
buffer[0] = 4;
VRFSeed(buffer)
};
Self {
header_hash,
consensus_hash,
vrf_seed,
sortition_id: SortitionId(bytes),
}
}
}
impl ClarityDatastore {
pub fn new(remote_network_info: Option<RemoteNetworkInfo>, client: HttpClient) -> Self {
if let Some(remote_network_info) = remote_network_info {
return Self::new_with_remote_data(remote_network_info, client);
}
let height = 0;
let id = StacksBlockId(height_to_hashed_bytes(height));
let fs_cache_location = remote_network_info
.and_then(|r| r.cache_location)
.unwrap_or(PathBuf::from("./.cache"))
.join("datastore");
Self {
open_chain_tip: id.clone(),
current_chain_tip: Rc::new(RefCell::new(id.clone())),
store: HashMap::new(),
metadata: HashMap::new(),
height_at_chain_tip: HashMap::from([(id.clone(), height)]),
chain_tip_at_height: HashMap::from([(height, id.clone())]),
remote_network_info: None,
remote_block_info_cache: Rc::new(RefCell::new(HashMap::new())),
remote_sortition_cache: Rc::new(RefCell::new(HashMap::new())),
fs_cache_location,
local_accounts: Vec::new(),
client,
}
}
fn new_with_remote_data(remote_network_info: RemoteNetworkInfo, client: HttpClient) -> Self {
let height = remote_network_info.initial_height;
let path = format!("/extended/v2/blocks/{height}");
let block = client.fetch_block(&path);
let sortition = client.fetch_sortition(block.burn_block_height);
let block_cache = HashMap::from([(block.index_block_hash.clone(), block.clone())]);
let sortition_cache = HashMap::from([(block.burn_block_hash, sortition)]);
let fs_cache_location = remote_network_info
.cache_location
.as_ref()
.unwrap_or(&PathBuf::from("./.cache"))
.join("datastore");
let id = block.index_block_hash;
Self {
open_chain_tip: id.clone(),
current_chain_tip: Rc::new(RefCell::new(id.clone())),
store: HashMap::new(),
metadata: HashMap::new(),
height_at_chain_tip: HashMap::from([(id.clone(), height)]),
chain_tip_at_height: HashMap::from([(height, id.clone())]),
remote_network_info: Some(remote_network_info),
remote_block_info_cache: Rc::new(RefCell::new(block_cache)),
remote_sortition_cache: Rc::new(RefCell::new(sortition_cache)),
fs_cache_location,
local_accounts: Vec::new(),
client,
}
}
pub fn as_analysis_db(&mut self) -> AnalysisDatabase<'_> {
AnalysisDatabase::new(self)
}
/// begin, commit, rollback a save point identified by key
/// this is used to clean up any data from aborted blocks
/// (NOT aborted transactions that is handled by the clarity vm directly).
/// The block header hash is used for identifying savepoints.
/// this _cannot_ be used to rollback to arbitrary prior block hash, because that
/// blockhash would already have committed and no longer exist in the save point stack.
/// this is a "lower-level" rollback than the roll backs performed in
/// ClarityDatabase or AnalysisDatabase -- this is done at the backing store level.
pub fn begin(&mut self, _current: &StacksBlockId, _next: &StacksBlockId) {
// self.marf.begin(current, next)
// .expect(&format!("ERROR: Failed to begin new MARF block {} - {})", current, next));
// self.chain_tip = self.marf.get_open_chain_tip()
// .expect("ERROR: Failed to get open MARF")
// .clone();
// self.side_store.begin(&self.chain_tip);
}
pub fn rollback(&mut self) {
// self.marf.drop_current();
// self.side_store.rollback(&self.chain_tip);
// self.chain_tip = StacksBlockId::sentinel();
}
// This is used by miners
// so that the block validation and processing logic doesn't
// reprocess the same data as if it were already loaded
pub fn commit_mined_block(&mut self, _will_move_to: &StacksBlockId) {
// rollback the side_store
// the side_store shouldn't commit data for blocks that won't be
// included in the processed chainstate (like a block constructed during mining)
// _if_ for some reason, we do want to be able to access that mined chain state in the future,
// we should probably commit the data to a different table which does not have uniqueness constraints.
// self.side_store.rollback(&self.chain_tip);
// self.marf.commit_mined(will_move_to)
// .expect("ERROR: Failed to commit MARF block");
}
pub fn commit_to(&mut self, _final_bhh: &StacksBlockId) {
// println!("commit_to({})", final_bhh);
// self.side_store.commit_metadata_to(&self.chain_tip, final_bhh);
// self.side_store.commit(&self.chain_tip);
// self.marf.commit_to(final_bhh)
// .expect("ERROR: Failed to commit MARF block");
}
pub fn save_local_account(&mut self, local_accounts: Vec<StandardPrincipalData>) {
self.local_accounts = local_accounts;
}
fn is_key_from_local_account(&mut self, key: &str) -> bool {
let parts: Vec<&str> = key.split("::").collect();
if let Ok(principal) = PrincipalData::parse(parts[1]) {
let standard_principal = match principal {
PrincipalData::Contract(contract) => contract.issuer,
PrincipalData::Standard(standard) => standard,
};
return self.local_accounts.contains(&standard_principal);
}
false
}
fn put(&mut self, key: &str, value: &str) {
let height = self.get_current_block_height();
self.store
.entry(key.to_string())
.or_default()
.insert(height, value.to_string());
}
fn fetch_block(&mut self, url: &str) -> Block {
let block = self.client.fetch_block(url);
self.remote_block_info_cache
.borrow_mut()
.insert(block.index_block_hash.clone(), block.clone());
self.height_at_chain_tip
.insert(block.index_block_hash.clone(), block.height);
self.chain_tip_at_height
.insert(block.height, block.index_block_hash.clone());
if self
.remote_sortition_cache
.borrow()
.get(&block.burn_block_hash)
.is_none()
{
let sortition = self.client.fetch_sortition(block.burn_block_height);
self.remote_sortition_cache
.borrow_mut()
.insert(block.burn_block_hash.clone(), sortition);
}
block
}
fn get_remote_block_info_from_height(&mut self, height: u32) -> Block {
if let Some(hash) = self.chain_tip_at_height.get(&height) {
return self.get_remote_block_info_from_hash(&hash.clone());
}
self.fetch_block(&format!("/extended/v2/blocks/{height}"))
}
fn get_remote_block_info_from_hash(&mut self, hash: &StacksBlockId) -> Block {
if let Some(cached) = self.remote_block_info_cache.borrow().get(hash) {
return cached.clone();
}
self.fetch_block(&format!("/extended/v2/blocks/{hash}"))
}
fn get_remote_chaintip(&mut self) -> String {
let initial_height = self.remote_network_info.as_ref().unwrap().initial_height;
let height = self.get_current_block_height().min(initial_height);
let block_info = self.get_remote_block_info_from_height(height);
block_info.index_block_hash.to_string()
}
fn fetch_clarity_marf_value(&mut self, key: &str) -> Result<Option<String>, VmExecutionError> {
let key_hash = TrieHash::from_key(key);
let tip = self.get_remote_chaintip();
let url = format!("/v2/clarity/marf/{key_hash}?tip={tip}&proof=false");
self.client.fetch_clarity_data(&url)
}
fn populate_context_functions(
&mut self,
contract_id: &QualifiedContractIdentifier,
context_str: Option<String>,
) -> Result<ContractContext, VmExecutionError> {
let contract_src_key = ClarityDatabase::make_metadata_key(
StoreType::Contract,
ContractDataVarName::ContractSrc.as_str(),
);
let contract_src =
self.get_metadata(contract_id, &contract_src_key)?
.ok_or(VmInternalError::Expect(format!(
"No contract source found for contract: {contract_id}",
)))?;
let mut contract_context = context_str
.ok_or(VmInternalError::Expect(format!(
"No contract context found for contract: {contract_id}",
)))
.and_then(|s| {
serde_json::from_str::<ContractContextResponse>(&s).map_err(|e| {
VmInternalError::Expect(format!("Failed to parse contract context: {e}"))
})
})?
.contract_context;
contract_context.functions.clear();
let analysis = self
.get_metadata(contract_id, AnalysisDatabase::storage_key())?
.ok_or(VmInternalError::Expect(format!(
"No analysis metadata found for contract: {contract_id}",
)))
.and_then(|s| {
serde_json::from_str::<ContractAnalysis>(&s).map_err(|e| {
VmInternalError::Expect(format!("Failed to parse analysis metadata: {e}"))
})
})?;
let contract_ast = build_ast(
contract_id,
&contract_src,
&mut (),
analysis.clarity_version,
analysis.epoch,
)
.map_err(|e| VmInternalError::Expect(e.to_string()))?;
context::set_functions_in_contract_context(
&contract_ast.expressions,
&mut contract_context,
&analysis.epoch,
)
.map_err(|e| VmInternalError::Expect(e.to_string()))?;
Ok(contract_context)
}
fn fetch_clarity_metadata(
&mut self,
contract_id: &QualifiedContractIdentifier,
key: &str,
) -> Result<Option<String>, VmExecutionError> {
let addr = contract_id.issuer.to_string();
let contract = contract_id.name.to_string();
let tip = self.get_remote_chaintip();
let cache_file_path = PathBuf::from(format!(
"{}_{}_{}_{}",
addr,
contract,
key.replace(":", "_"),
tip
))
.with_extension("json");
if let Some(cached) = get_file_from_cache(&self.fs_cache_location, &cache_file_path) {
return Ok(Some(cached));
}
let url = format!("/v2/clarity/metadata/{addr}/{contract}/{key}?tip={tip}");
let raw_response = self.client.fetch_clarity_data(&url)?;
let contract_context_key = ClarityDatabase::make_metadata_key(
StoreType::Contract,
ContractDataVarName::Contract.as_str(),
);
let response = if key == contract_context_key {
// the `vm-metadata::9::contract`, returns the contracts Context, including the contract AST.
// since node don't have the `clarity-vm/developer-mode` cargo feature enabled,
// the AST doesn't contain the spans, which are useful for most debugging purposes.
// The solution is to fetch the source code of the contract, and parse it locally,
let contract_context = self.populate_context_functions(contract_id, raw_response)?;
let contract_context_response = ContractContextResponse { contract_context };
Some(
serde_json::to_string(&contract_context_response).map_err(|e| {
VmInternalError::Expect(format!("Failed to serialize contract context: {e}"))
})?,
)
} else {
raw_response
};
if let Some(content) = &response {
write_file_to_cache(
&self.fs_cache_location,
&cache_file_path,
content.as_bytes(),
);
}
Ok(response)
}
}
impl ClarityBackingStore for ClarityDatastore {
fn put_all_data(&mut self, items: Vec<(String, String)>) -> Result<(), VmExecutionError> {
for (key, value) in items {
self.put(&key, &value);
}
Ok(())
}
/// fetch K-V out of the committed datastore
fn get_data(&mut self, key: &str) -> Result<Option<String>, VmExecutionError> {
let current_height = self.get_current_block_height();
let fetch_remote_data =
self.remote_network_info.is_some() && !self.is_key_from_local_account(key);
let values_map = self.store.get(key);
if fetch_remote_data {
// if the value for the exact current_chain_tip is present, return it
if let Some(data) = values_map.and_then(|data| data.get(¤t_height)) {
return Ok(Some(data.clone()));
}
let initial_height = self.remote_network_info.as_ref().unwrap().initial_height;
if current_height > initial_height {
if let Some((_, value)) = values_map.and_then(|data| {
data.iter()
.rev()
.find(|(height, _)| height > &&initial_height && height <= &¤t_height)
}) {
return Ok(Some(value.clone()));
}
}
let data = self.fetch_clarity_marf_value(key);
if let Ok(Some(value)) = &data {
self.put(key, value);
}
return data;
}
Ok(values_map.and_then(|data| {
data.iter()
.rev()
.find(|(height, _)| height <= &¤t_height)
.map(|(_, value)| value.clone())
}))
}
fn get_data_from_path(&mut self, _hash: &TrieHash) -> Result<Option<String>, VmExecutionError> {
unreachable!()
}
fn get_data_with_proof(
&mut self,
_key: &str,
) -> Result<Option<(String, Vec<u8>)>, VmExecutionError> {
Ok(None)
}
fn get_data_with_proof_from_path(
&mut self,
_hash: &TrieHash,
) -> Result<Option<(String, Vec<u8>)>, VmExecutionError> {
unreachable!()
}
fn has_entry(&mut self, key: &str) -> Result<bool, VmExecutionError> {
Ok(self.get_data(key)?.is_some())
}
/// change the current MARF context to service reads from a different chain_tip
/// used to implement time-shifted evaluation.
/// returns the previous block header hash on success
fn set_block_hash(&mut self, bhh: StacksBlockId) -> Result<StacksBlockId, VmExecutionError> {
let prior_tip = self.open_chain_tip.clone();
if self.remote_network_info.is_some() {
#[allow(clippy::map_entry)]
if !self.height_at_chain_tip.contains_key(&bhh) {
let block_info = self.get_remote_block_info_from_hash(&bhh);
self.height_at_chain_tip
.insert(bhh.clone(), block_info.height);
self.chain_tip_at_height
.insert(block_info.height, bhh.clone());
}
}
*self.current_chain_tip.borrow_mut() = bhh;
Ok(prior_tip)
}
fn get_block_at_height(&mut self, height: u32) -> Option<StacksBlockId> {
if let Some(remote_network_info) = &self.remote_network_info {
if height <= remote_network_info.initial_height {
let block_info = self.get_remote_block_info_from_height(height);
return Some(block_info.index_block_hash);
}
}
self.chain_tip_at_height.get(&height).cloned()
}
/// this function returns the current block height, as viewed by this marfed-kv structure,
/// i.e., it changes on time-shifted evaluation. the open_chain_tip functions always
/// return data about the chain tip that is currently open for writing.
fn get_current_block_height(&mut self) -> u32 {
let current_chain_tip = self.current_chain_tip.borrow().clone();
if let Some(&height) = self.height_at_chain_tip.get(¤t_chain_tip) {
return height;
}
if let Some(initial_height) = self.remote_network_info.as_ref().map(|d| d.initial_height) {
let block_info = self.get_remote_block_info_from_hash(¤t_chain_tip);
if block_info.height <= initial_height {
return block_info.height;
}
}
u32::MAX
}
fn get_open_chain_tip_height(&mut self) -> u32 {
self.height_at_chain_tip
.get(&self.open_chain_tip)
.copied()
.unwrap_or(u32::MAX)
}
fn get_open_chain_tip(&mut self) -> StacksBlockId {
self.open_chain_tip.clone()
}
fn insert_metadata(
&mut self,
contract: &QualifiedContractIdentifier,
key: &str,
value: &str,
) -> Result<(), VmExecutionError> {
self.metadata
.insert((contract.to_string(), key.to_string()), value.to_string());
Ok(())
}
fn get_metadata(
&mut self,
contract: &QualifiedContractIdentifier,
key: &str,
) -> Result<Option<String>, VmExecutionError> {
let metadata = self.metadata.get(&(contract.to_string(), key.to_string()));
if metadata.is_some() {
return Ok(metadata.cloned());
}
if self.remote_network_info.is_some() && !self.local_accounts.contains(&contract.issuer) {
let data = self.fetch_clarity_metadata(contract, key);
if let Ok(Some(value)) = &data {
self.insert_metadata(contract, key, value)?;
}
return data;
}
Ok(None)
}
fn get_contract_hash(
&mut self,
_contract: &QualifiedContractIdentifier,
) -> Result<(StacksBlockId, Sha512Trunc256Sum), VmExecutionError> {
panic!("Datastore cannot get_contract_hash")
}
fn get_metadata_manual(
&mut self,
_at_height: u32,
_contract: &QualifiedContractIdentifier,
_key: &str,
) -> Result<Option<String>, VmExecutionError> {
panic!("Datastore cannot get_metadata_manual")
}
fn get_cc_special_cases_handler(&self) -> Option<clarity::vm::database::SpecialCaseHandler> {
Some(&handle_contract_call_special_cases)
}
fn make_contract_commitment(&mut self, contract_hash: Sha512Trunc256Sum) -> String {
ContractCommitment {
hash: contract_hash,
block_height: self.get_open_chain_tip_height(),
}
.serialize()
}
#[cfg(not(target_arch = "wasm32"))]
fn get_side_store(&mut self) -> &rusqlite::Connection {
panic!("Datastore cannot get_side_store")
}
}
impl Datastore {
pub fn new(
clarity_datastore: &ClarityDatastore,
constants: StacksConstants,
client: HttpClient,
) -> Self {
if clarity_datastore.remote_network_info.is_some() {
return Self::new_with_remote_data(clarity_datastore, constants, client);
}
let stacks_chain_height = 0;
let burn_chain_height = 0;
let bytes = height_to_hashed_bytes(stacks_chain_height);
let id = StacksBlockId(bytes);
let genesis_time = chrono::Utc::now().timestamp() as u64;
let burn_block_hashes = BurnBlockHashes::from_height(burn_chain_height);
let burn_block_header_hash = burn_block_hashes.header_hash.clone();
let burn_block = BurnBlockInfo {
consensus_hash: burn_block_hashes.consensus_hash,
vrf_seed: burn_block_hashes.vrf_seed,
sortition_id: burn_block_hashes.sortition_id,
burn_block_time: genesis_time,
burn_chain_height,
};
let stacks_block = StacksBlockInfo {
block_header_hash: BlockHeaderHash(bytes),
burn_block_header_hash: burn_block_hashes.header_hash.clone(),
stacks_block_time: genesis_time + SECONDS_BETWEEN_STACKS_BLOCKS,
};
let sortition_lookup = HashMap::from([(
burn_block.sortition_id.clone(),
burn_block_header_hash.clone(),
)]);
let consensus_hash_lookup = HashMap::from([(
burn_block.consensus_hash.clone(),
burn_block.sortition_id.clone(),
)]);
let tenure_height_at_stacks_height = HashMap::from([(0, 0)]);
let stacks_height_at_tenure_height = HashMap::from([(0, 0)]);
let burn_blocks = HashMap::from([(burn_block_header_hash.clone(), burn_block.clone())]);
let stacks_blocks = HashMap::from([(id.clone(), stacks_block)]);
Datastore {
genesis_id: id,
burn_chain_tip: burn_block_header_hash,
burn_chain_height,
tenure_height: 0,
current_chain_tip: Rc::clone(&clarity_datastore.current_chain_tip),
remote_block_info_cache: Rc::clone(&clarity_datastore.remote_block_info_cache),
remote_sortition_cache: Rc::clone(&clarity_datastore.remote_sortition_cache),
burn_blocks,
stacks_chain_height,
stacks_blocks,
sortition_lookup,
consensus_hash_lookup,
tenure_height_at_stacks_height,
stacks_height_at_tenure_height,
current_epoch: StacksEpochId::Epoch2_05,
current_epoch_start_height: stacks_chain_height,
constants,
remote_network_info: None,
initial_burn_height: 0,
client,
}
}
fn new_with_remote_data(
clarity_datastore: &ClarityDatastore,
constants: StacksConstants,
client: HttpClient,
) -> Self {
let current_chain_tip = clarity_datastore.current_chain_tip.borrow();
let stacks_chain_height = clarity_datastore
.height_at_chain_tip
.get(¤t_chain_tip)
.unwrap();
let block = {
let cache = clarity_datastore.remote_block_info_cache.borrow();
cache.get(¤t_chain_tip).unwrap().clone()
};
let sortition = {
let cache = clarity_datastore.remote_sortition_cache.borrow();
cache.get(&block.burn_block_hash).unwrap().clone()
};
let is_mainnet = clarity_datastore
.remote_network_info
.as_ref()
.unwrap()
.is_mainnet;
let burn_chain_height = block.burn_block_height;
let id = block.index_block_hash.clone();
let burn_block_header_hash = block.burn_block_hash.clone();
let block_header_hash = block.hash;
let sortition_id = sortition.sortition_id.clone();
let consensus_hash = sortition.consensus_hash;
let vrf_seed = sortition.vrf_seed.unwrap_or_else(|| {
let bytes = height_to_hashed_bytes(burn_chain_height);
VRFSeed(bytes)
});
let burn_block = BurnBlockInfo {
consensus_hash,
vrf_seed,
sortition_id: sortition_id.clone(),
burn_block_time: block.burn_block_time,
burn_chain_height,
};
let stacks_block = StacksBlockInfo {
block_header_hash,
burn_block_header_hash: burn_block_header_hash.clone(),
stacks_block_time: block.block_time,
};
let sortition_lookup =
HashMap::from([(sortition_id.clone(), burn_block_header_hash.clone())]);
let consensus_hash_lookup =
HashMap::from([(burn_block.consensus_hash.clone(), sortition_id)]);
let tenure_height_at_stacks_height =
HashMap::from([(*stacks_chain_height, block.tenure_height)]);
let stacks_height_at_tenure_height =
HashMap::from([(block.tenure_height, *stacks_chain_height)]);
let burn_blocks = HashMap::from([(burn_block_header_hash.clone(), burn_block)]);
let stacks_blocks = HashMap::from([(id.clone(), stacks_block)]);
Datastore {
genesis_id: id,
burn_chain_tip: burn_block_header_hash,
burn_chain_height,
tenure_height: block.tenure_height,
current_chain_tip: Rc::clone(&clarity_datastore.current_chain_tip),
remote_block_info_cache: Rc::clone(&clarity_datastore.remote_block_info_cache),
remote_sortition_cache: Rc::clone(&clarity_datastore.remote_sortition_cache),
burn_blocks,
stacks_chain_height: *stacks_chain_height,
stacks_blocks,
sortition_lookup,
consensus_hash_lookup,
tenure_height_at_stacks_height,
stacks_height_at_tenure_height,
current_epoch: epoch_for_height(is_mainnet, *stacks_chain_height),
current_epoch_start_height: *stacks_chain_height,
constants,
remote_network_info: clarity_datastore.remote_network_info.clone(),
initial_burn_height: burn_chain_height,
client,
}
}
pub fn get_current_epoch(&self) -> StacksEpochId {
self.current_epoch
}
pub fn get_current_stacks_block_height(&self) -> u32 {
self.stacks_chain_height
}
pub fn get_current_burn_block_height(&self) -> u32 {
self.burn_chain_height
}
fn get_tenure_for_burn_block_height(&self, height: u32) -> u32 {
*self
.tenure_height_at_stacks_height
.get(&height)
.unwrap_or(&0)
}
pub fn get_current_tenure(&self) -> u32 {
self.get_tenure_for_burn_block_height(self.stacks_chain_height)
}
fn build_next_stacks_block(&self, clarity_datastore: &ClarityDatastore) -> StacksBlockInfo {
let stacks_block_height = self.stacks_chain_height;
let previous_stacks_block = self
.stacks_blocks
.get(&clarity_datastore.open_chain_tip)
.expect("current chain tip missing in stacks block table");
let last_burn_block = self
.burn_blocks
.get(&self.burn_chain_tip)
.expect("burn block missing in burn block table");
let last_block_time = std::cmp::max(
previous_stacks_block.stacks_block_time,
last_burn_block.burn_block_time,
);
let block_header_hash = {
let mut buffer = height_to_hashed_bytes(stacks_block_height);
buffer[0] = 1;
BlockHeaderHash(buffer)
};
let stacks_block_time: u64 = last_block_time + SECONDS_BETWEEN_STACKS_BLOCKS;
StacksBlockInfo {
block_header_hash,
burn_block_header_hash: self.burn_chain_tip.clone(),
stacks_block_time,
}
}
pub fn advance_burn_chain_tip(
&mut self,
clarity_datastore: &mut ClarityDatastore,
count: u32,
) -> u32 {
for _ in 1..=count {
let next_burn_block_time = {
let last_stacks_block = self
.stacks_blocks
.get(&clarity_datastore.open_chain_tip)
.unwrap_or_else(|| {
panic!(
"current chain tip missing in stacks_blocks table: {}",
clarity_datastore.open_chain_tip
)
});
let last_burn_block =
self.burn_blocks
.get(&self.burn_chain_tip)
.unwrap_or_else(|| {
panic!(
"burn block missing in burn_blocks table: {}",
self.burn_chain_tip
)
});
let mut next_burn_block_time =
last_burn_block.burn_block_time + SECONDS_BETWEEN_BURN_BLOCKS;
if last_stacks_block.stacks_block_time > next_burn_block_time {
next_burn_block_time =
last_stacks_block.stacks_block_time + SECONDS_BETWEEN_STACKS_BLOCKS;
}
next_burn_block_time
};
let previous_height = self.burn_chain_height;
let next_height = previous_height + 1;
let burn_block_hashes = BurnBlockHashes::from_height(next_height);
let burn_block_header_hash = burn_block_hashes.header_hash.clone();
let burn_block = BurnBlockInfo {
consensus_hash: burn_block_hashes.consensus_hash,
vrf_seed: burn_block_hashes.vrf_seed,
sortition_id: burn_block_hashes.sortition_id,
burn_block_time: next_burn_block_time,
burn_chain_height: next_height,
};
self.consensus_hash_lookup.insert(
burn_block.consensus_hash.clone(),
burn_block.sortition_id.clone(),
);
self.sortition_lookup.insert(
burn_block.sortition_id.clone(),
burn_block_header_hash.clone(),
);
self.burn_chain_tip = burn_block_header_hash.clone();
self.burn_blocks
.insert(burn_block_header_hash, burn_block.clone());
self.burn_chain_height = next_height;
self.tenure_height += 1;
self.advance_stacks_chain_tip(clarity_datastore, 1);
self.stacks_height_at_tenure_height
.insert(self.tenure_height, self.stacks_chain_height);
}
self.burn_chain_height
}
pub fn advance_stacks_chain_tip(
&mut self,
clarity_datastore: &mut ClarityDatastore,
count: u32,
) -> u32 {
for _ in 1..=count {
self.stacks_chain_height += 1;
let bytes = height_to_hashed_bytes(self.stacks_chain_height);
let id = StacksBlockId(bytes);
let block_info = self.build_next_stacks_block(clarity_datastore);
if self.current_epoch.uses_marfed_block_time() {
clarity_datastore
.put_all_data(vec![(
CLARITY_STORAGE_BLOCK_TIME_KEY.to_string(),
format!("{}", block_info.stacks_block_time),
)])
.expect("failed to update vm-epoch::block-height");
}
self.stacks_blocks.insert(id.clone(), block_info);