/
chain.rs
1019 lines (921 loc) · 35.4 KB
/
chain.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) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::verifier::{BlockVerifier, FullVerifier};
use anyhow::{bail, ensure, format_err, Result};
use consensus::Consensus;
use crypto::hash::PlainCryptoHash;
use crypto::HashValue;
use logger::prelude::*;
use sp_utils::stop_watch::{watch, CHAIN_WATCH_NAME};
use starcoin_accumulator::inmemory::InMemoryAccumulator;
use starcoin_accumulator::{
accumulator_info::AccumulatorInfo, node::AccumulatorStoreType, Accumulator, MerkleAccumulator,
};
use starcoin_chain_api::{
verify_block, ChainReader, ChainWriter, ConnectBlockError, EventWithProof, ExcludedTxns,
ExecutedBlock, MintedUncleNumber, TransactionInfoWithProof, VerifiedBlock, VerifyBlockField,
};
use starcoin_executor::VMMetrics;
use starcoin_open_block::OpenedBlock;
use starcoin_state_api::{AccountStateReader, ChainState, ChainStateReader, ChainStateWriter};
use starcoin_statedb::ChainStateDB;
use starcoin_types::block::BlockIdAndNumber;
use starcoin_types::contract_event::ContractEventInfo;
use starcoin_types::filter::Filter;
use starcoin_types::startup_info::{ChainInfo, ChainStatus};
use starcoin_types::transaction::RichTransactionInfo;
use starcoin_types::{
account_address::AccountAddress,
block::{Block, BlockHeader, BlockInfo, BlockNumber, BlockTemplate},
contract_event::ContractEvent,
error::BlockExecutorError,
transaction::{SignedUserTransaction, Transaction},
U256,
};
use starcoin_vm_types::access_path::AccessPath;
use starcoin_vm_types::account_config::genesis_address;
use starcoin_vm_types::genesis_config::ConsensusStrategy;
use starcoin_vm_types::on_chain_resource::Epoch;
use starcoin_vm_types::time::TimeService;
use std::cmp::min;
use std::iter::Extend;
use std::option::Option::{None, Some};
use std::{collections::HashMap, sync::Arc};
use storage::Store;
pub struct ChainStatusWithBlock {
pub status: ChainStatus,
pub head: Block,
}
pub struct BlockChain {
genesis_hash: HashValue,
txn_accumulator: MerkleAccumulator,
block_accumulator: MerkleAccumulator,
status: ChainStatusWithBlock,
statedb: ChainStateDB,
storage: Arc<dyn Store>,
time_service: Arc<dyn TimeService>,
uncles: HashMap<HashValue, MintedUncleNumber>,
epoch: Epoch,
vm_metrics: Option<VMMetrics>,
}
impl BlockChain {
pub fn new(
time_service: Arc<dyn TimeService>,
head_block_hash: HashValue,
storage: Arc<dyn Store>,
vm_metrics: Option<VMMetrics>,
) -> Result<Self> {
let head = storage
.get_block_by_hash(head_block_hash)?
.ok_or_else(|| format_err!("Can not find block by hash {:?}", head_block_hash))?;
Self::new_with_uncles(time_service, head, None, storage, vm_metrics)
}
fn new_with_uncles(
time_service: Arc<dyn TimeService>,
head_block: Block,
uncles: Option<HashMap<HashValue, MintedUncleNumber>>,
storage: Arc<dyn Store>,
vm_metrics: Option<VMMetrics>,
) -> Result<Self> {
let block_info = storage
.get_block_info(head_block.id())?
.ok_or_else(|| format_err!("Can not find block info by hash {:?}", head_block.id()))?;
debug!("Init chain with block_info: {:?}", block_info);
let state_root = head_block.header().state_root();
let txn_accumulator_info = block_info.get_txn_accumulator_info();
let block_accumulator_info = block_info.get_block_accumulator_info();
let chain_state = ChainStateDB::new(storage.clone().into_super_arc(), Some(state_root));
let epoch = get_epoch_from_statedb(&chain_state)?;
let genesis = storage
.get_genesis()?
.ok_or_else(|| format_err!("Can not find genesis hash in storage."))?;
watch(CHAIN_WATCH_NAME, "n1253");
let mut chain = Self {
genesis_hash: genesis,
time_service,
txn_accumulator: info_2_accumulator(
txn_accumulator_info.clone(),
AccumulatorStoreType::Transaction,
storage.as_ref(),
),
block_accumulator: info_2_accumulator(
block_accumulator_info.clone(),
AccumulatorStoreType::Block,
storage.as_ref(),
),
status: ChainStatusWithBlock {
status: ChainStatus::new(head_block.header.clone(), block_info),
head: head_block,
},
statedb: chain_state,
storage,
uncles: HashMap::new(),
epoch,
vm_metrics,
};
watch(CHAIN_WATCH_NAME, "n1251");
match uncles {
Some(data) => chain.uncles = data,
None => chain.update_uncle_cache()?,
}
watch(CHAIN_WATCH_NAME, "n1252");
Ok(chain)
}
pub fn new_with_genesis(
time_service: Arc<dyn TimeService>,
storage: Arc<dyn Store>,
genesis_epoch: Epoch,
genesis_block: Block,
) -> Result<Self> {
debug_assert!(genesis_block.header().is_genesis());
let txn_accumulator = MerkleAccumulator::new_empty(
storage.get_accumulator_store(AccumulatorStoreType::Transaction),
);
let block_accumulator = MerkleAccumulator::new_empty(
storage.get_accumulator_store(AccumulatorStoreType::Block),
);
let statedb = ChainStateDB::new(storage.clone().into_super_arc(), None);
let executed_block = Self::execute_block_and_save(
storage.as_ref(),
statedb,
txn_accumulator,
block_accumulator,
&genesis_epoch,
None,
genesis_block,
None,
)?;
Self::new(time_service, executed_block.block.id(), storage, None)
}
pub fn current_epoch_uncles_size(&self) -> u64 {
self.uncles.len() as u64
}
pub fn current_block_accumulator_info(&self) -> AccumulatorInfo {
self.block_accumulator.get_info()
}
pub fn consensus(&self) -> ConsensusStrategy {
self.epoch.strategy()
}
pub fn time_service(&self) -> Arc<dyn TimeService> {
self.time_service.clone()
}
//TODO lazy init uncles cache.
fn update_uncle_cache(&mut self) -> Result<()> {
self.uncles = self.epoch_uncles()?;
Ok(())
}
fn epoch_uncles(&self) -> Result<HashMap<HashValue, MintedUncleNumber>> {
let epoch = &self.epoch;
let mut uncles: HashMap<HashValue, MintedUncleNumber> = HashMap::new();
let head_block = self.head_block().block;
let head_number = head_block.header().number();
if head_number < epoch.start_block_number() || head_number >= epoch.end_block_number() {
return Err(format_err!(
"head block {} not in current epoch: {:?}.",
head_number,
epoch
));
}
for block_number in epoch.start_block_number()..epoch.end_block_number() {
let block_uncles = if block_number == head_number {
head_block.uncle_ids()
} else {
self.get_block_by_number(block_number)?
.ok_or_else(|| {
format_err!(
"Can not find block by number {}, head block number: {}",
block_number,
head_number
)
})?
.uncle_ids()
};
block_uncles.into_iter().for_each(|uncle_id| {
uncles.insert(uncle_id, block_number);
});
if block_number == head_number {
break;
}
}
Ok(uncles)
}
pub fn create_block_template(
&self,
author: AccountAddress,
parent_hash: Option<HashValue>,
user_txns: Vec<SignedUserTransaction>,
uncles: Vec<BlockHeader>,
block_gas_limit: Option<u64>,
) -> Result<(BlockTemplate, ExcludedTxns)> {
//FIXME create block template by parent may be use invalid chain state, such as epoch.
//So the right way should bean create a BlockChain by parent_hash, then create block template.
//the timestamp should bean a argument, if want to mock a early block.
let previous_header = match parent_hash {
Some(hash) => self
.get_header(hash)?
.ok_or_else(|| format_err!("Can find block header by {:?}", hash))?,
None => self.current_header(),
};
self.create_block_template_inner(
author,
previous_header,
user_txns,
uncles,
block_gas_limit,
)
}
fn create_block_template_inner(
&self,
author: AccountAddress,
previous_header: BlockHeader,
user_txns: Vec<SignedUserTransaction>,
uncles: Vec<BlockHeader>,
block_gas_limit: Option<u64>,
) -> Result<(BlockTemplate, ExcludedTxns)> {
let epoch = self.epoch();
let on_chain_block_gas_limit = epoch.block_gas_limit();
let final_block_gas_limit = block_gas_limit
.map(|block_gas_limit| min(block_gas_limit, on_chain_block_gas_limit))
.unwrap_or(on_chain_block_gas_limit);
let strategy = epoch.strategy();
let difficulty = strategy.calculate_next_difficulty(self)?;
let mut opened_block = OpenedBlock::new(
self.storage.clone(),
previous_header,
final_block_gas_limit,
author,
self.time_service.now_millis(),
uncles,
difficulty,
strategy,
None,
)?;
let excluded_txns = opened_block.push_txns(user_txns)?;
let template = opened_block.finalize()?;
Ok((template, excluded_txns))
}
/// Get block hash by block number, if not exist, return Error.
pub fn get_hash_by_number_ensure(&self, number: BlockNumber) -> Result<HashValue> {
self.get_hash_by_number(number)?
.ok_or_else(|| format_err!("Can not find block hash by number {}", number))
}
fn check_exist_block(&self, block_id: HashValue, block_number: BlockNumber) -> Result<bool> {
Ok(self
.get_hash_by_number(block_number)?
.filter(|hash| hash == &block_id)
.is_some())
}
// filter block by check exist
fn exist_block_filter(&self, block: Option<Block>) -> Result<Option<Block>> {
Ok(match block {
Some(block) => {
if self.check_exist_block(block.id(), block.header().number())? {
Some(block)
} else {
None
}
}
None => None,
})
}
// filter header by check exist
fn exist_header_filter(&self, header: Option<BlockHeader>) -> Result<Option<BlockHeader>> {
Ok(match header {
Some(header) => {
if self.check_exist_block(header.id(), header.number())? {
Some(header)
} else {
None
}
}
None => None,
})
}
pub fn get_storage(&self) -> Arc<dyn Store> {
self.storage.clone()
}
pub fn can_be_uncle(&self, block_header: &BlockHeader) -> Result<bool> {
FullVerifier::can_be_uncle(self, block_header)
}
pub fn verify_with_verifier<V>(&mut self, block: Block) -> Result<VerifiedBlock>
where
V: BlockVerifier,
{
V::verify_block(self, block)
}
pub fn apply_with_verifier<V>(&mut self, block: Block) -> Result<ExecutedBlock>
where
V: BlockVerifier,
{
let verified_block = self.verify_with_verifier::<V>(block)?;
watch(CHAIN_WATCH_NAME, "n1");
let executed_block = self.execute(verified_block)?;
watch(CHAIN_WATCH_NAME, "n2");
self.connect(executed_block)
}
//TODO remove this function.
pub fn update_chain_head(&mut self, block: Block) -> Result<ExecutedBlock> {
let block_info = self
.storage
.get_block_info(block.id())?
.ok_or_else(|| format_err!("Can not find block info by hash {:?}", block.id()))?;
self.connect(ExecutedBlock { block, block_info })
}
//TODO consider move this logic to BlockExecutor
fn execute_block_and_save(
storage: &dyn Store,
statedb: ChainStateDB,
txn_accumulator: MerkleAccumulator,
block_accumulator: MerkleAccumulator,
epoch: &Epoch,
parent_status: Option<ChainStatus>,
block: Block,
vm_metrics: Option<VMMetrics>,
) -> Result<ExecutedBlock> {
let header = block.header();
debug_assert!(header.is_genesis() || parent_status.is_some());
debug_assert!(!header.is_genesis() || parent_status.is_none());
let block_id = header.id();
let transactions = {
// genesis block do not generate BlockMetadata transaction.
let mut t = match &parent_status {
None => vec![],
Some(parent) => {
let block_metadata = block.to_metadata(parent.head().gas_used());
vec![Transaction::BlockMetadata(block_metadata)]
}
};
t.extend(
block
.transactions()
.iter()
.cloned()
.map(Transaction::UserTransaction),
);
t
};
watch(CHAIN_WATCH_NAME, "n21");
let executed_data = starcoin_executor::block_execute(
&statedb,
transactions.clone(),
epoch.block_gas_limit(),
vm_metrics,
)?;
watch(CHAIN_WATCH_NAME, "n22");
let state_root = executed_data.state_root;
let vec_transaction_info = &executed_data.txn_infos;
verify_block!(
VerifyBlockField::State,
state_root == header.state_root(),
"verify block:{:?} state_root fail",
block_id,
);
let block_gas_used = vec_transaction_info
.iter()
.fold(0u64, |acc, i| acc.saturating_add(i.gas_used()));
verify_block!(
VerifyBlockField::State,
block_gas_used == header.gas_used(),
"invalid block: gas_used is not match"
);
verify_block!(
VerifyBlockField::State,
vec_transaction_info.len() == transactions.len(),
"invalid txn num in the block"
);
let transaction_global_index = txn_accumulator.num_leaves();
// txn accumulator verify.
let executed_accumulator_root = {
let included_txn_info_hashes: Vec<_> =
vec_transaction_info.iter().map(|info| info.id()).collect();
txn_accumulator.append(&included_txn_info_hashes)?
};
verify_block!(
VerifyBlockField::State,
executed_accumulator_root == header.txn_accumulator_root(),
"verify block: txn accumulator root mismatch"
);
watch(CHAIN_WATCH_NAME, "n23");
statedb
.flush()
.map_err(BlockExecutorError::BlockChainStateErr)?;
// If chain state is matched, and accumulator is matched,
// then, we save flush states, and save block data.
watch(CHAIN_WATCH_NAME, "n24");
txn_accumulator
.flush()
.map_err(|_err| BlockExecutorError::BlockAccumulatorFlushErr)?;
let pre_total_difficulty = parent_status
.map(|status| status.total_difficulty())
.unwrap_or_default();
let total_difficulty = pre_total_difficulty + header.difficulty();
block_accumulator.append(&[block_id])?;
block_accumulator.flush()?;
let txn_accumulator_info: AccumulatorInfo = txn_accumulator.get_info();
let block_accumulator_info: AccumulatorInfo = block_accumulator.get_info();
let block_info = BlockInfo::new(
block_id,
total_difficulty,
txn_accumulator_info,
block_accumulator_info,
);
watch(CHAIN_WATCH_NAME, "n25");
// save block's transaction relationship and save transaction
let block_id = block.id();
let txn_infos = executed_data.txn_infos;
let txn_events = executed_data.txn_events;
debug_assert!(
txn_events.len() == txn_infos.len(),
"events' length should be equal to txn infos' length"
);
let txn_info_ids: Vec<_> = txn_infos.iter().map(|info| info.id()).collect();
for (info_id, events) in txn_info_ids.iter().zip(txn_events.into_iter()) {
storage.save_contract_events(*info_id, events)?;
}
storage.save_transaction_infos(
txn_infos
.into_iter()
.enumerate()
.map(|(transaction_index, info)| {
RichTransactionInfo::new(
block_id,
block.header().number(),
info,
transaction_index as u32,
transaction_global_index
.checked_add(transaction_index as u64)
.expect("transaction_global_index overflow."),
)
})
.collect(),
)?;
let txn_id_vec = transactions
.iter()
.map(|user_txn| user_txn.id())
.collect::<Vec<HashValue>>();
// save transactions
storage.save_transaction_batch(transactions)?;
// save block's transactions
storage.save_block_transaction_ids(block_id, txn_id_vec)?;
storage.save_block_txn_info_ids(block_id, txn_info_ids)?;
storage.commit_block(block.clone())?;
storage.save_block_info(block_info.clone())?;
watch(CHAIN_WATCH_NAME, "n26");
Ok(ExecutedBlock { block, block_info })
}
pub fn get_txn_accumulator(&self) -> &MerkleAccumulator {
&self.txn_accumulator
}
pub fn get_block_accumulator(&self) -> &MerkleAccumulator {
&self.block_accumulator
}
}
impl ChainReader for BlockChain {
fn info(&self) -> ChainInfo {
ChainInfo::new(
self.status.head.header().chain_id(),
self.genesis_hash,
self.status.status.clone(),
)
}
fn status(&self) -> ChainStatus {
self.status.status.clone()
}
fn head_block(&self) -> ExecutedBlock {
ExecutedBlock::new(self.status.head.clone(), self.status.status.info.clone())
}
fn current_header(&self) -> BlockHeader {
self.status.status.head().clone()
}
fn get_header(&self, hash: HashValue) -> Result<Option<BlockHeader>> {
self.storage
.get_block_header_by_hash(hash)
.and_then(|block_header| self.exist_header_filter(block_header))
}
fn get_header_by_number(&self, number: BlockNumber) -> Result<Option<BlockHeader>> {
self.get_hash_by_number(number)
.and_then(|block_id| match block_id {
None => Ok(None),
Some(block_id) => self.storage.get_block_header_by_hash(block_id),
})
}
fn get_block_by_number(&self, number: BlockNumber) -> Result<Option<Block>> {
self.get_hash_by_number(number)
.and_then(|block_id| match block_id {
None => Ok(None),
Some(block_id) => self.storage.get_block_by_hash(block_id),
})
}
fn get_blocks_by_number(&self, number: Option<BlockNumber>, count: u64) -> Result<Vec<Block>> {
let end_num = match number {
None => self.current_header().number(),
Some(number) => number,
};
let num_leaves = self.block_accumulator.num_leaves();
if end_num > num_leaves {
bail!("Can not find block by number {}", end_num);
}
let ids = self.get_block_ids(end_num, true, count)?;
let block_opts = self.storage.get_blocks(ids)?;
let mut blocks = vec![];
for (idx, block) in block_opts.into_iter().enumerate() {
match block {
Some(block) => blocks.push(block),
None => bail!(
"Can not find block by number {}",
end_num.saturating_sub(idx as u64)
),
}
}
Ok(blocks)
}
fn get_block(&self, hash: HashValue) -> Result<Option<Block>> {
self.storage
.get_block_by_hash(hash)
.and_then(|block| self.exist_block_filter(block))
}
fn get_hash_by_number(&self, number: BlockNumber) -> Result<Option<HashValue>> {
self.block_accumulator.get_leaf(number)
}
fn get_transaction(&self, txn_hash: HashValue) -> Result<Option<Transaction>> {
//TODO check txn should exist on current chain.
self.storage.get_transaction(txn_hash)
}
fn get_transaction_info(&self, txn_hash: HashValue) -> Result<Option<RichTransactionInfo>> {
let txn_info_ids = self
.storage
.get_transaction_info_ids_by_txn_hash(txn_hash)?;
for txn_info_id in txn_info_ids {
let txn_info = self.storage.get_transaction_info(txn_info_id)?;
if let Some(txn_info) = txn_info {
if self.exist_block(txn_info.block_id())? {
return Ok(Some(txn_info));
}
}
}
Ok(None)
}
fn get_transaction_info_by_global_index(
&self,
transaction_global_index: u64,
) -> Result<Option<RichTransactionInfo>> {
match self.txn_accumulator.get_leaf(transaction_global_index)? {
None => Ok(None),
Some(hash) => self.storage.get_transaction_info(hash),
}
}
fn chain_state_reader(&self) -> &dyn ChainStateReader {
&self.statedb
}
fn get_block_info(&self, block_id: Option<HashValue>) -> Result<Option<BlockInfo>> {
match block_id {
Some(block_id) => self.storage.get_block_info(block_id),
None => Ok(Some(self.status.status.info().clone())),
}
}
fn get_total_difficulty(&self) -> Result<U256> {
Ok(self.status.status.total_difficulty())
}
fn exist_block(&self, block_id: HashValue) -> Result<bool> {
if let Some(header) = self.storage.get_block_header_by_hash(block_id)? {
return self.check_exist_block(block_id, header.number());
}
Ok(false)
}
fn epoch(&self) -> &Epoch {
&self.epoch
}
fn get_block_ids(
&self,
start_number: BlockNumber,
reverse: bool,
max_size: u64,
) -> Result<Vec<HashValue>> {
self.block_accumulator
.get_leaves(start_number, reverse, max_size)
}
fn get_block_info_by_number(&self, number: BlockNumber) -> Result<Option<BlockInfo>> {
let block = self
.get_block_by_number(number)?
.ok_or_else(|| format_err!("Can not find block by number {}", number))?;
self.get_block_info(Some(block.id()))
}
fn time_service(&self) -> &dyn TimeService {
self.time_service.as_ref()
}
fn fork(&self, block_id: HashValue) -> Result<Self> {
ensure!(
self.exist_block(block_id)?,
"Block with id{} do not exists in current chain.",
block_id
);
let head = self
.storage
.get_block_by_hash(block_id)?
.ok_or_else(|| format_err!("Can not find block by hash {:?}", block_id))?;
// if fork block_id is at same epoch, try to reuse uncles cache.
let uncles = if head.header().number() >= self.epoch.start_block_number() {
Some(
self.uncles
.iter()
.filter(|(_uncle_id, uncle_number)| **uncle_number <= head.header().number())
.map(|(uncle_id, uncle_number)| (*uncle_id, *uncle_number))
.collect::<HashMap<HashValue, MintedUncleNumber>>(),
)
} else {
None
};
BlockChain::new_with_uncles(
self.time_service.clone(),
head,
uncles,
self.storage.clone(),
self.vm_metrics.clone(),
)
}
fn epoch_uncles(&self) -> &HashMap<HashValue, MintedUncleNumber> {
&self.uncles
}
fn find_ancestor(&self, another: &dyn ChainReader) -> Result<Option<BlockIdAndNumber>> {
let other_header_number = another.current_header().number();
let self_header_number = self.current_header().number();
let min_number = std::cmp::min(other_header_number, self_header_number);
let mut ancestor = None;
for block_number in (0..min_number).rev() {
let block_id_1 = another.get_hash_by_number(block_number)?;
let block_id_2 = self.get_hash_by_number(block_number)?;
match (block_id_1, block_id_2) {
(Some(block_id_1), Some(block_id_2)) => {
if block_id_1 == block_id_2 {
ancestor = Some(BlockIdAndNumber::new(block_id_1, block_number));
break;
}
}
(_, _) => {
continue;
}
}
}
Ok(ancestor)
}
fn verify(&self, block: Block) -> Result<VerifiedBlock> {
FullVerifier::verify_block(self, block)
}
fn execute(&self, verified_block: VerifiedBlock) -> Result<ExecutedBlock> {
Self::execute_block_and_save(
self.storage.as_ref(),
self.statedb.fork(),
self.txn_accumulator.fork(None),
self.block_accumulator.fork(None),
&self.epoch,
Some(self.status.status.clone()),
verified_block.0,
self.vm_metrics.clone(),
)
}
fn get_transaction_infos(
&self,
start_index: u64,
reverse: bool,
max_size: u64,
) -> Result<Vec<RichTransactionInfo>> {
let chain_header = self.current_header();
let hashes = self
.txn_accumulator
.get_leaves(start_index, reverse, max_size)?;
let mut infos = vec![];
let txn_infos = self.storage.get_transaction_infos(hashes.clone())?;
for (i, info) in txn_infos.into_iter().enumerate() {
match info {
Some(info) => infos.push(info),
None => bail!(
"cannot find hash({:?}) on head: {}",
hashes.get(i),
chain_header.id()
),
}
}
Ok(infos)
}
fn get_events(&self, txn_info_id: HashValue) -> Result<Option<Vec<ContractEvent>>> {
self.storage.get_contract_events(txn_info_id)
}
fn get_transaction_proof(
&self,
block_id: HashValue,
transaction_global_index: u64,
event_index: Option<u64>,
access_path: Option<AccessPath>,
) -> Result<Option<TransactionInfoWithProof>> {
let block_info = match self.get_block_info(Some(block_id))? {
Some(block_info) => block_info,
None => return Ok(None),
};
let accumulator = self
.txn_accumulator
.fork(Some(block_info.txn_accumulator_info));
let txn_proof = match accumulator.get_proof(transaction_global_index)? {
Some(proof) => proof,
None => return Ok(None),
};
//if can get proof by leaf_index, the leaf and transaction info should exist.
let txn_info_hash = self
.txn_accumulator
.get_leaf(transaction_global_index)?
.ok_or_else(|| {
format_err!(
"Can not find txn info hash by index {}",
transaction_global_index
)
})?;
let transaction_info = self
.storage
.get_transaction_info(txn_info_hash)?
.ok_or_else(|| format_err!("Can not find txn info by hash:{}", txn_info_hash))?;
let event_proof = if let Some(event_index) = event_index {
let events = self
.storage
.get_contract_events(txn_info_hash)?
.unwrap_or_default();
let event = events.get(event_index as usize).cloned().ok_or_else(|| {
format_err!("event index out of range, events len:{}", events.len())
})?;
let event_hashes: Vec<_> = events.iter().map(|e| e.crypto_hash()).collect();
let event_proof =
InMemoryAccumulator::get_proof_from_leaves(event_hashes.as_slice(), event_index)?;
Some(EventWithProof {
event,
proof: event_proof,
})
} else {
None
};
let state_proof = if let Some(access_path) = access_path {
let statedb = self
.statedb
.fork_at(transaction_info.txn_info().state_root_hash());
Some(statedb.get_with_proof(&access_path)?)
} else {
None
};
Ok(Some(TransactionInfoWithProof {
transaction_info,
proof: txn_proof,
event_proof,
state_proof,
}))
}
}
impl BlockChain {
pub fn filter_events(&self, filter: Filter) -> Result<Vec<ContractEventInfo>> {
let reverse = filter.reverse;
let chain_header = self.current_header();
let max_block_number = chain_header.number().min(filter.to_block);
// quick return.
if filter.from_block > max_block_number {
return Ok(vec![]);
}
let (mut cur_block_number, tail) = if reverse {
(max_block_number, filter.from_block)
} else {
(filter.from_block, max_block_number)
};
let mut event_with_infos = vec![];
'outer: loop {
let block = self.get_block_by_number(cur_block_number)?.ok_or_else(|| {
anyhow::anyhow!(format!(
"cannot find block({}) on main chain(head: {})",
cur_block_number,
chain_header.id()
))
})?;
let block_id = block.id();
let block_number = block.header().number();
let mut txn_info_ids = self.storage.get_block_txn_info_ids(block_id)?;
if reverse {
txn_info_ids.reverse();
}
for id in txn_info_ids.iter() {
let events = self.storage.get_contract_events(*id)?.ok_or_else(|| {
anyhow::anyhow!(format!(
"cannot find events of txn with txn_info_id {} on main chain(header: {})",
id,
chain_header.id()
))
})?;
let mut filtered_events = events
.into_iter()
.enumerate()
.filter(|(_idx, evt)| filter.matching(block_number, evt))
.peekable();
if filtered_events.peek().is_none() {
continue;
}
let txn_info = self.storage.get_transaction_info(*id)?.ok_or_else(|| {
anyhow::anyhow!(format!(
"cannot find txn info with txn_info_id {} on main chain(head: {})",
id,
chain_header.id()
))
})?;
let filtered_event_with_info =
filtered_events.map(|(idx, evt)| ContractEventInfo {
block_hash: block_id,
block_number: block.header().number(),
transaction_hash: txn_info.transaction_hash(),
transaction_index: txn_info.transaction_index,
transaction_global_index: txn_info.transaction_global_index,
event_index: idx as u32,
event: evt,
});
if reverse {
event_with_infos.extend(filtered_event_with_info.rev())
} else {
event_with_infos.extend(filtered_event_with_info);
}
if let Some(limit) = filter.limit {
if event_with_infos.len() >= limit {
break 'outer;
}
}
}
let should_break = match reverse {
true => cur_block_number <= tail,
false => cur_block_number >= tail,
};
if should_break {
break 'outer;
}
if reverse {
cur_block_number = cur_block_number.saturating_sub(1);
} else {
cur_block_number = cur_block_number.saturating_add(1);
}
}
// remove additional events in respect limit filter.
if let Some(limit) = filter.limit {
event_with_infos.truncate(limit);
}
Ok(event_with_infos)
}
}
impl ChainWriter for BlockChain {
fn can_connect(&self, executed_block: &ExecutedBlock) -> bool {
executed_block.block.header().parent_hash() == self.status.status.head().id()
}
fn connect(&mut self, executed_block: ExecutedBlock) -> Result<ExecutedBlock> {
let (block, block_info) = (executed_block.block(), executed_block.block_info());
debug_assert!(block.header().parent_hash() == self.status.status.head().id());
//TODO try reuse accumulator and state db.
let txn_accumulator_info = block_info.get_txn_accumulator_info();
let block_accumulator_info = block_info.get_block_accumulator_info();
let state_root = block.header().state_root();
self.txn_accumulator = info_2_accumulator(
txn_accumulator_info.clone(),
AccumulatorStoreType::Transaction,
self.storage.as_ref(),
);
self.block_accumulator = info_2_accumulator(
block_accumulator_info.clone(),
AccumulatorStoreType::Block,
self.storage.as_ref(),
);
self.statedb = ChainStateDB::new(self.storage.clone().into_super_arc(), Some(state_root));
self.status = ChainStatusWithBlock {
status: ChainStatus::new(block.header().clone(), block_info.clone()),
head: block.clone(),
};
if self.epoch.end_block_number() == block.header().number() {
self.epoch = get_epoch_from_statedb(&self.statedb)?;
self.update_uncle_cache()?;
} else if let Some(block_uncles) = block.uncles() {
block_uncles.iter().for_each(|uncle_header| {
self.uncles
.insert(uncle_header.id(), block.header().number());
});
}
Ok(executed_block)
}
fn apply(&mut self, block: Block) -> Result<ExecutedBlock> {
self.apply_with_verifier::<FullVerifier>(block)
}
fn chain_state(&mut self) -> &dyn ChainState {
&self.statedb
}