/
block_state.rs
1152 lines (1002 loc) · 73.3 KB
/
block_state.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) SimpleStaking and Tezedge Contributors
// SPDX-License-Identifier: MIT
use std::cmp;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, RwLock};
use rand::prelude::ThreadRng;
use rand::Rng;
use slog::Logger;
use crypto::hash::{BlockHash, ChainId, HashType, ProtocolHash};
use crypto::seeded_step::{Seed, Step};
use storage::{BlockHeaderWithHash, BlockMetaStorage, BlockMetaStorageReader, BlockStorage, BlockStorageReader, ChainMetaStorage, IteratorMode, StorageError};
use storage::block_meta_storage::Meta;
use storage::chain_meta_storage::ChainMetaStorageReader;
use storage::persistent::PersistentStorage;
use tezos_messages::Head;
use tezos_messages::p2p::encoding::block_header::{BlockHeader, Level};
use tezos_messages::p2p::encoding::current_branch::{CurrentBranchMessage, HISTORY_MAX_SIZE};
use tezos_messages::p2p::encoding::prelude::CurrentHeadMessage;
use tezos_wrapper::service::{ProtocolController, ProtocolServiceError};
use crate::collections::{BlockData, UniqueBlockData};
use crate::shell_channel::{BlockApplied, CurrentMempoolState};
use crate::validation;
pub enum BlockAcceptanceResult {
AcceptBlock,
IgnoreBlock,
UnknownBranch,
MutlipassValidationError(ProtocolServiceError),
}
/// Holds state of all known blocks
pub struct BlockchainState {
/// persistent block storage
block_storage: BlockStorage,
///persistent block metadata storage
block_meta_storage: BlockMetaStorage,
///persistent chain metadata storage
chain_meta_storage: ChainMetaStorage,
/// Current missing blocks.
/// This represents a set of missing block we will try to retrieve in the future.
/// Before we try to fetch missing block it is removed from this queue.
/// Block is then sent to [`chain_manager`](crate::chain_manager::ChainManager) actor whose responsibility is to
/// retrieve the block data. If the block data cannot be fetched it's the responsibility
/// of the [`chain_manager`](crate::chain_manager::ChainManager) to return the block to this queue.
missing_blocks: UniqueBlockData<MissingBlock>,
chain_id: ChainId,
}
impl BlockchainState {
pub fn new(persistent_storage: &PersistentStorage, chain_id: ChainId) -> Self {
BlockchainState {
block_storage: BlockStorage::new(persistent_storage),
block_meta_storage: BlockMetaStorage::new(persistent_storage),
chain_meta_storage: ChainMetaStorage::new(persistent_storage),
missing_blocks: UniqueBlockData::new(),
chain_id,
}
}
/// Validate if we can accept branch
pub fn can_accept_branch(&self, branch: &CurrentBranchMessage, current_head: &Option<Head>) -> bool {
// validate chain which we operate on
if self.get_chain_id() != branch.chain_id() {
// return Ok(BlockAcceptanceResult::IgnoreBlock);
return false;
}
if branch.current_branch().current_head().level() <= 0 {
return false;
}
if let Some(current_head) = current_head.as_ref() {
// (only_if_fitness_increases) we can accept branch if increases fitness
if validation::is_fitness_increases(current_head, branch.current_branch().current_head().fitness()) {
return true;
}
false
} else {
true
}
}
/// Validate if we can accept head
pub fn can_accept_head(&self,
head: &CurrentHeadMessage,
current_head: &Option<Head>,
api: &ProtocolController,
) -> Result<BlockAcceptanceResult, failure::Error> {
// validate chain which we operate on
if self.get_chain_id() != head.chain_id() {
return Ok(BlockAcceptanceResult::IgnoreBlock);
}
let validated_header: &BlockHeader = head.current_block_header();
if validated_header.level() <= 0 {
return Ok(BlockAcceptanceResult::IgnoreBlock);
}
// we need our current head at first
if let Some(current_head) = current_head.as_ref() {
// (future block)
if validation::is_future_block(&validated_header)? {
return Ok(BlockAcceptanceResult::IgnoreBlock);
}
// (only_if_fitness_increases) we can accept head if increases fitness
if !validation::is_fitness_increases(current_head, validated_header.fitness()) {
return Ok(BlockAcceptanceResult::IgnoreBlock);
}
// lets try to find protocol for validated_block
let (protocol_hash, predecessor_header, missing_predecessor) = self.resolve_protocol(validated_header, ¤t_head)?;
// if missing predecessor
if missing_predecessor {
return Ok(BlockAcceptanceResult::UnknownBranch);
}
// if we have protocol lets validate
if let Some(protocol_hash) = protocol_hash {
// lets check strict multipass validation
match validation::check_multipass_validation(
head.chain_id(),
protocol_hash,
&validated_header,
predecessor_header,
api,
) {
Some(error) => {
Ok(BlockAcceptanceResult::MutlipassValidationError(error))
}
None => Ok(BlockAcceptanceResult::AcceptBlock)
}
} else {
// if not, we cannot trigger validation, so we just ignore head
Ok(BlockAcceptanceResult::IgnoreBlock)
}
} else {
Ok(BlockAcceptanceResult::IgnoreBlock)
}
}
/// Returns triplet:
/// 1. protocol_hash
/// 2. applied_predecessor (only if is already applied)
/// 3. (bool) missing_predecessor,
fn resolve_protocol(&self, validated_header: &BlockHeader, current_head: &Head) -> Result<(Option<ProtocolHash>, Option<BlockHeaderWithHash>, bool), failure::Error> {
// TODO: TE-238 - store proto_level and protocol_hash and map - optimization - detect change protocol event
let (protocol_hash, predecessor_header, missing_predecessor) = match self.block_meta_storage.get(validated_header.predecessor())? {
Some(predecessor_meta) => {
match predecessor_meta.is_applied() {
true => {
// if predecessor is applied, than we have exact protocol
match self.block_storage.get_with_json_data(validated_header.predecessor())? {
Some((predecessor_header, predecessor_data)) => {
// get next_protocol from predecessor
let metadata: HashMap<String, serde_json::Value> = serde_json::from_str(&predecessor_data.block_header_proto_metadata_json())?;
let protocol_hash = metadata
.get("next_protocol")
.map(|value| value.as_str());
if let Some(Some(protocol_hash)) = protocol_hash {
// return next_protocol and header
(
Some(HashType::ProtocolHash.string_to_bytes(protocol_hash)?),
Some(predecessor_header),
false,
)
} else {
return Err(
failure::format_err!(
"Missing `next_protocol` attribute for applied predecessor: {}!",
HashType::BlockHash.bytes_to_string(validated_header.predecessor())
)
);
}
}
None => {
return Err(
failure::format_err!(
"Missing data for applied predecessor: {}!",
HashType::BlockHash.bytes_to_string(validated_header.predecessor())
)
);
}
}
}
false => {
// if we dont have applied predecessor, we dont know protocol_hash
(None, None, false)
}
}
}
None => {
// if we dont have predecessor stored
(None, None, true)
}
};
if protocol_hash.is_some() {
// if we have protocol by predecessor
Ok((protocol_hash, predecessor_header, missing_predecessor))
} else {
// check protocol by current head for the same proto_level
// if predecessor is applied, than we have exact protocol
match self.block_storage.get_with_json_data(current_head.block_hash())? {
Some((current_head_header, current_head_header_data)) => {
if current_head_header.header.proto() == validated_header.proto() {
// get protocol from predecessor
let metadata: HashMap<String, serde_json::Value> = serde_json::from_str(¤t_head_header_data.block_header_proto_metadata_json())?;
let protocol_hash = metadata
.get("protocol")
.map(|value| value.as_str());
if let Some(Some(protocol_hash)) = protocol_hash {
// return protocol
Ok(
(
Some(HashType::ProtocolHash.string_to_bytes(protocol_hash)?),
predecessor_header,
missing_predecessor
)
)
} else {
return Err(
failure::format_err!(
"Missing `next_protocol` attribute for applied predecessor: {}!",
HashType::BlockHash.bytes_to_string(validated_header.predecessor())
)
);
}
} else {
Ok((None, predecessor_header, missing_predecessor))
}
}
None => {
return Err(
failure::format_err!(
"Missing data for applied current_head: {}!",
HashType::BlockHash.bytes_to_string(current_head.block_hash())
)
);
}
}
}
}
/// Returns true, if [block] can be applied
pub fn can_apply_block<'b, OP>(&self, (block, block_metadata): (&'b BlockHash, &'b Meta), operations_complete: OP) -> Result<bool, StorageError>
where OP: Fn(&'b BlockHash) -> Result<bool, StorageError> /* func returns true, if operations are completed */
{
let block_predecessor = block_metadata.predecessor();
// check if block is already applied, dont need to apply second time
if block_metadata.is_applied() {
return Ok(false);
}
// we need to have predecessor (every block has)
if block_predecessor.is_none() {
return Ok(false);
}
// if operations are not complete, we cannot apply block
if !operations_complete(block)? {
return Ok(false);
}
// check if predecesor is applied
if let Some(predecessor) = block_predecessor {
if let Some(predecessor_meta) = self.block_meta_storage.get(predecessor)? {
return Ok(predecessor_meta.is_applied());
}
}
Ok(false)
}
/// Resolves missing blocks and schedules them for download from network
pub fn schedule_branch_bootstrap(&mut self, block_header: &BlockHeaderWithHash, history: &Vec<BlockHash>) -> Result<(), StorageError> {
let block_level = block_header.header.level();
let block_hash = block_header.hash.clone();
// at first schedule history - we try to prioritize download from the beginning, so the history is reversed here
self.push_missing_history(
history.iter().cloned().rev().collect(),
block_level,
)?;
// schedule predecessor (if not present in history)
if !history.contains(block_header.header.predecessor()) {
self.push_missing_block(
MissingBlock::with_level_guess(
block_header.header.predecessor().clone(),
std::cmp::max(1, block_level - 1),
)
)?;
}
// schedule also current_head
self.push_missing_block(
MissingBlock::with_level(
block_hash.clone(),
block_level,
)
)?;
Ok(())
}
/// Resolve if new applied block can be set as new current head.
/// Original algorithm is in [chain_validator][on_request], where just fitness is checked.
/// Returns:
/// - None, if head was not updated, means was ignored
/// - Some(new_head, head_result)
pub fn try_update_new_current_head(&self, potential_new_head: &BlockApplied, current_head: &Option<Head>, mempool_state: &Option<Arc<RwLock<CurrentMempoolState>>>) -> Result<Option<(Head, HeadResult)>, StorageError> {
if let Some(current_head) = current_head {
// get fitness from mempool, if not, than use current_head.fitness
let current_context_fitness = match mempool_state {
Some(state) => {
let mempool_state = state.read().unwrap();
match mempool_state.fitness.as_ref() {
Some(fitness) => fitness.clone(),
None => current_head.fitness().to_vec()
}
}
None => current_head.fitness().to_vec()
};
// need to check against current_head, if not accepted, just ignore potential head
if !validation::can_update_current_head(potential_new_head.header(), ¤t_head, ¤t_context_fitness) {
// just ignore
return Ok(None);
}
}
// we need to check, if previous head is predecessor of new_head (for later use)
let head_result = match ¤t_head {
Some(previos_head) => if previos_head.block_hash().eq(potential_new_head.header().header.predecessor()) {
HeadResult::HeadIncrement
} else {
// if previous head is not predecesor of new head, means it could be new branch
HeadResult::BranchSwitch
}
None => HeadResult::HeadIncrement,
};
// this will be new head
let head = Head::new(
potential_new_head.header().hash.clone(),
potential_new_head.header().header.level(),
potential_new_head.header().header.fitness().clone(),
);
// set new head to db
self.chain_meta_storage.set_current_head(&self.chain_id, head.clone())?;
Ok(Some((head, head_result)))
}
pub fn process_block_header(&mut self, block_header: &BlockHeaderWithHash, log: &Logger) -> Result<(Meta, bool), StorageError> {
// check if we already have seen predecessor
self.push_missing_block(
MissingBlock::with_level_guess(
block_header.header.predecessor().clone(),
block_header.header.level() - 1,
)
)?;
// store block
let is_new_block = self.block_storage.put_block_header(block_header)?;
// update meta
let metadata = self.block_meta_storage.put_block_header(block_header, &self.chain_id, &log)?;
Ok((metadata, is_new_block))
}
#[inline]
pub fn drain_missing_blocks(&mut self, n: usize, level_max: i32) -> Vec<MissingBlock> {
(0..cmp::min(self.missing_blocks.len(), n))
.filter_map(|_| {
if self.missing_blocks.peek().filter(|block| block.fits_to_max(level_max)).is_some() {
self.missing_blocks.pop()
} else {
None
}
})
.collect()
}
#[inline]
pub fn push_missing_block(&mut self, missing_block: MissingBlock) -> Result<(), StorageError> {
if !self.block_storage.contains(&missing_block.block_hash)? {
self.missing_blocks.push(missing_block);
}
Ok(())
}
#[inline]
fn push_missing_history(&mut self, history: Vec<BlockHash>, level: Level) -> Result<(), StorageError> {
let mut rng = rand::thread_rng();
let history_max_parts = if history.len() < usize::from(HISTORY_MAX_SIZE) {
history.len() as u8
} else {
HISTORY_MAX_SIZE
};
history.iter().enumerate()
.map(|(idx, history_block_hash)| {
self.push_missing_block(
MissingBlock::with_level_guess(
history_block_hash.clone(),
Self::guess_level(&mut rng, level, history_max_parts, idx),
)
)
})
.collect::<Result<Vec<_>, _>>()?;
Ok(())
}
#[inline]
pub fn has_missing_blocks(&self) -> bool {
!self.missing_blocks.is_empty()
}
#[inline]
pub fn missing_blocks_count(&self) -> usize {
self.missing_blocks.len()
}
pub fn hydrate(&mut self) -> Result<(), StorageError> {
for (key, value) in self.block_meta_storage.iter(IteratorMode::Start)? {
let (block_hash, meta) = (key?, value?);
if meta.predecessor().is_none() && (meta.chain_id() == &self.chain_id) {
self.missing_blocks.push(
MissingBlock::with_level(
block_hash,
meta.level(),
)
);
}
}
Ok(())
}
#[inline]
pub fn get_chain_id(&self) -> &ChainId {
&self.chain_id
}
pub fn get_history(&self, head: &BlockHash, seed: &Seed) -> Result<Vec<BlockHash>, StorageError> {
Self::compute_history(
&self.block_meta_storage,
self.chain_meta_storage.get_caboose(&self.chain_id)?,
head,
HISTORY_MAX_SIZE,
seed,
)
}
/// Resulted history is sorted: "from oldest block to newest"
fn compute_history(block_meta_storage: &BlockMetaStorage, caboose: Option<Head>, head: &BlockHash, max_size: u8, seed: &Seed) -> Result<Vec<BlockHash>, StorageError> {
if max_size == 0 {
return Ok(vec![]);
}
// init steping
let mut step = Step::init(seed, &head);
// iterate and get history records
let mut counter = max_size;
let mut current_block_hash = head.clone();
let mut history = Vec::with_capacity(max_size as usize);
while counter > 0 {
// evaluate next step, means we want predecessor at this distance
let distance = step.next();
// need to find predecesor at requested distance
match block_meta_storage.find_block_at_distance(current_block_hash, distance)? {
Some(predecessor) => {
// add to history
history.push(predecessor.clone());
// decrement counter and continue
counter -= 1;
current_block_hash = predecessor;
}
None => {
// close history with caboose, if predecessor was not found in this run
if let Some(caboose) = caboose {
if let Some(last) = history.last() {
if !last.eq(caboose.block_hash()) {
history.push(caboose.into());
}
} else {
history.push(caboose.into());
}
}
break;
}
}
}
Ok(history)
}
fn guess_level(rng: &mut ThreadRng, level: Level, parts: u8, index: usize) -> i32 {
// e.g. we have: level 100 a 5 record in history, so split is 20, never <= 0
let split = level / i32::from(parts);
// corner case for 1 level;
let split = cmp::max(1, split);
// we try to guess level, because in history there is no level
if index == 0 {
// first block in history is always genesis
0
} else {
// e.g. next block: idx * split, e.g. for index in history: 1 and split, we guess level is in range (0 * 20 - 1 * 20) -> (0, 20)
let start_level = ((index as i32 - 1) * split) + 1;
let end_level = (index as i32) * split;
// corner case for 1 level
let start_level = cmp::min(start_level, level);
let end_level = cmp::min(end_level, level);
if start_level == end_level {
start_level
} else {
rng.gen_range(start_level, end_level)
}
}
}
}
#[derive(Clone, Debug)]
pub struct MissingBlock {
pub block_hash: BlockHash,
// if level is known, we use level
level: Option<i32>,
// if level is unknow, we 'guess' level
level_guess: Option<i32>,
}
impl BlockData for MissingBlock {
#[inline]
fn block_hash(&self) -> &BlockHash {
&self.block_hash
}
}
impl MissingBlock {
pub fn with_level(block_hash: BlockHash, level: i32) -> Self {
MissingBlock {
block_hash,
level: Some(level),
level_guess: None,
}
}
pub fn with_level_guess(block_hash: BlockHash, level_guess: i32) -> Self {
MissingBlock {
block_hash,
level: None,
level_guess: Some(level_guess),
}
}
fn fits_to_max(&self, level_max: i32) -> bool {
if let Some(level) = self.level {
return level <= level_max;
}
if let Some(level_guess) = self.level_guess {
return level_guess <= level_max;
}
// if both are None
true
}
}
impl PartialEq for MissingBlock {
fn eq(&self, other: &Self) -> bool {
self.block_hash == other.block_hash
}
}
impl Eq for MissingBlock {}
impl PartialOrd for MissingBlock {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for MissingBlock {
fn cmp(&self, other: &Self) -> Ordering {
let self_potential_level = match self.level {
Some(level) => level,
None => match self.level_guess {
Some(level) => level,
None => 0
}
};
let other_potential_level = match other.level {
Some(level) => level,
None => match other.level_guess {
Some(level) => level,
None => 0
}
};
// reverse, because we want lower level at begining
self_potential_level.cmp(&other_potential_level).reverse()
}
}
pub enum HeadResult {
BranchSwitch,
HeadIncrement,
}
impl fmt::Display for HeadResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
HeadResult::BranchSwitch => write!(f, "BranchSwitch"),
HeadResult::HeadIncrement => write!(f, "HeadIncrement"),
}
}
}
#[cfg(test)]
mod tests {
use slog::{Drain, Level, Logger};
use crypto::hash::chain_id_from_block_hash;
use storage::tests_common::TmpStorage;
use super::*;
#[test]
fn test_missing_blocks_has_correct_ordering() {
let mut heap = UniqueBlockData::new();
// simulate header and predecesor
heap.push(MissingBlock::with_level(vec![0, 0, 0, 1], 10));
heap.push(MissingBlock::with_level(vec![0, 0, 0, 2], 9));
// simulate history
heap.push(MissingBlock::with_level_guess(vec![0, 0, 0, 3], 4));
heap.push(MissingBlock::with_level_guess(vec![0, 0, 0, 7], 0));
heap.push(MissingBlock::with_level_guess(vec![0, 0, 0, 5], 2));
heap.push(MissingBlock::with_level_guess(vec![0, 0, 0, 6], 1));
heap.push(MissingBlock::with_level_guess(vec![0, 0, 0, 4], 3));
// pop all from heap
let ordered_hashes = (0..heap.len())
.map(|_| heap.pop().unwrap())
.map(|i| i.block_hash)
.collect::<Vec<BlockHash>>();
// from level: 0, 1, 2, 3, 4, 9, 10
let expected_order = vec![
vec![0, 0, 0, 7],
vec![0, 0, 0, 6],
vec![0, 0, 0, 5],
vec![0, 0, 0, 4],
vec![0, 0, 0, 3],
vec![0, 0, 0, 2],
vec![0, 0, 0, 1],
];
assert_eq!(expected_order, ordered_hashes)
}
#[test]
fn test_guess_level() {
let mut rng = rand::thread_rng();
// for block 0 in history (always 0)
for _ in 0..100 {
let level = BlockchainState::guess_level(&mut rng, 100, 5, 0);
assert_eq!(level, 0);
}
// for block 1 in history [1, 20)
for _ in 0..100 {
let level = BlockchainState::guess_level(&mut rng, 100, 5, 1);
assert!(level >= 1 && level < 20);
}
// for block 2 in history [20, 40)
for _ in 0..100 {
let level = BlockchainState::guess_level(&mut rng, 100, 5, 2);
assert!(level >= 20 && level < 40);
}
// for block 3 in history [40, 60)
for _ in 0..100 {
let level = BlockchainState::guess_level(&mut rng, 100, 5, 3);
assert!(level >= 40 && level < 60);
}
// for block 4 in history [60, 80)
for _ in 0..100 {
let level = BlockchainState::guess_level(&mut rng, 100, 5, 4);
assert!(level >= 60 && level < 80);
}
// for block 5 in history [80, 100)
for _ in 0..100 {
let level = BlockchainState::guess_level(&mut rng, 100, 5, 5);
assert!(level >= 80 && level < 100);
}
// for block 0 in history [0, 1)
for _ in 0..100 {
let level = BlockchainState::guess_level(&mut rng, 1, 1, 0);
assert!(level >= 0 && level < 1);
}
// corner case (for level 1 if there are two elements)
// for block 0 in history [0, 1)
for _ in 0..100 {
let level = BlockchainState::guess_level(&mut rng, 1, 2, 0);
assert!(level >= 0 && level < 1);
}
// corner case (for level 1 if there are two elements)
// for block 1 in history [1, 2)
for _ in 0..100 {
let level = BlockchainState::guess_level(&mut rng, 1, 2, 1);
assert!(level >= 1 && level < 2);
}
// corner cases
for _ in 0..100 {
let level = BlockchainState::guess_level(&mut rng, 1, 3, 0);
assert!(level >= 0 && level < 1);
let level = BlockchainState::guess_level(&mut rng, 1, 3, 1);
assert!(level >= 1 && level < 2);
let level = BlockchainState::guess_level(&mut rng, 1, 3, 2);
assert!(level >= 1 && level < 2);
}
}
/// This test is rewritten according to [test_state.ml -> test_locator]
#[test]
fn test_history_and_compute_locator() -> Result<(), failure::Error> {
let log = create_logger(Level::Debug);
let storage = TmpStorage::create_to_out_dir("__test_history")?;
let block_meta_storage = BlockMetaStorage::new(storage.storage());
let block_storage = BlockStorage::new(storage.storage());
/*
* Genesis - A1 - A2 - A3 - A4 - A5 - A6 - A7 - A8
* \
* B1 - B2 - B3 - B4 - B5 - B6 - B7 - B8
*/
let blocksdb = data::init_blocks();
// init with genesis
let (genesis_hash, genesis_header) = (blocksdb.block_hash("Genesis"), blocksdb.header("Genesis"));
let chain_id = chain_id_from_block_hash(&genesis_hash);
block_storage.put_block_header(&genesis_header)?;
block_meta_storage.put(&genesis_hash, &Meta::genesis_meta(&genesis_hash, &chain_id, true))?;
// store branch1 - root genesis
data::store_branch(&vec!["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8"],
&chain_id, &blocksdb, &block_storage, &block_meta_storage, &log);
// store branch2 - root A3
data::store_branch(&vec!["B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8"],
&chain_id, &blocksdb, &block_storage, &block_meta_storage, &log);
// store branch3 - root A3 (C0, C1, C2 ... C62)
let c_branch = {
let mut b = Vec::with_capacity(10_000);
for i in 0..63 {
b.push(format!("C{}", i));
}
b
};
data::store_branch(&c_branch.iter().map(|s| s.as_str()).collect::<Vec<&str>>(),
&chain_id, &blocksdb, &block_storage, &block_meta_storage, &log);
// check if reorg stored - A3 - should also contains successor A4 and B1 and C0
let reorg_block_meta = block_meta_storage.get(&blocksdb.block_hash("A3"))?.unwrap();
assert!(reorg_block_meta.successors().contains(&blocksdb.block_hash("A4")));
assert!(reorg_block_meta.successors().contains(&blocksdb.block_hash("B1")));
assert!(reorg_block_meta.successors().contains(&blocksdb.block_hash("C0")));
// calculates and checks
let caboose = Some(Head::new(blocksdb.block_hash("Genesis"), Meta::GENESIS_LEVEL, vec![]));
data::assert_history(
&["A7", "A6", "A5", "A4", "A3", "A2"],
&blocksdb,
BlockchainState::compute_history(
&block_meta_storage,
caboose.clone(),
&blocksdb.block_hash("A8"),
6,
&Seed::new(&data::generate_key_string('s'), &data::generate_key_string('r')),
)?,
);
data::assert_history(
&["B7", "B6", "B5", "B4", "B3", "B2", "B1", "A3"],
&blocksdb,
BlockchainState::compute_history(
&block_meta_storage,
caboose.clone(),
&blocksdb.block_hash("B8"),
8,
&Seed::new(&data::generate_key_string('s'), &data::generate_key_string('r')),
)?,
);
data::assert_history(
&["B7", "B6", "B5", "B4"],
&blocksdb,
BlockchainState::compute_history(
&block_meta_storage,
caboose.clone(),
&blocksdb.block_hash("B8"),
4,
&Seed::new(&data::generate_key_string('s'), &data::generate_key_string('r')),
)?,
);
data::assert_history(
&[],
&blocksdb,
BlockchainState::compute_history(
&block_meta_storage,
caboose.clone(),
&blocksdb.block_hash("A5"),
0,
&Seed::new(&data::generate_key_string('s'), &data::generate_key_string('r')),
)?,
);
data::assert_history(
&["A4", "A3", "A2", "A1", "Genesis"],
&blocksdb,
BlockchainState::compute_history(
&block_meta_storage,
caboose.clone(),
&blocksdb.block_hash("A5"),
100,
&Seed::new(&data::generate_key_string('s'), &data::generate_key_string('r')),
)?,
);
data::assert_history(
&["C61", "C60", "C59", "C58", "C57", "C56", "C55", "C54", "C53", "C52", "C51", "C49", "C46", "C44", "C43", "C42", "C41", "C40", "C39", "C37", "C34", "C29", "C26", "C20", "C15", "C13", "C9", "C7", "C3"],
&blocksdb,
BlockchainState::compute_history(
&block_meta_storage,
caboose,
&blocksdb.block_hash("C62"),
29,
&Seed::new(&data::generate_key_string('s'), &data::generate_key_string('r')),
)?,
);
Ok(())
}
fn create_logger(level: Level) -> Logger {
let drain = slog_async::Async::new(
slog_term::FullFormat::new(
slog_term::TermDecorator::new().build()
).build().fuse()
).build().filter_level(level).fuse();
Logger::root(drain, slog::o!())
}
mod data {
use std::collections::HashMap;
use itertools::Itertools;
use slog::Logger;
use crypto::hash::{BlockHash, CryptoboxPublicKeyHash, HashType};
use storage::{BlockHeaderWithHash, BlockMetaStorage, BlockStorage, BlockStorageReader};
use tezos_messages::p2p::binary_message::BinaryMessage;
use tezos_messages::p2p::encoding::block_header::BlockHeader;
macro_rules! init_block {
($blocks:ident, $name:expr, $block_hash_expected:expr, $block_header_hex_data:expr) => {
init_block!($blocks, $name, $block_hash_expected, $block_hash_expected, $block_header_hex_data);
};
($blocks:ident, $name:expr, $block_hash:expr, $block_hash_expected:expr, $block_header_hex_data:expr) => {
let block_hash = HashType::BlockHash.string_to_bytes($block_hash).expect("Failed to create block hash");
let block_hash_expected = HashType::BlockHash.string_to_bytes($block_hash_expected).expect("Failed to create block hash");
$blocks.insert(
$name,
(
block_hash.clone(),
BlockHeaderWithHash::new(
BlockHeader::from_bytes(
hex::decode($block_header_hex_data).expect("Failed to decode hex data")
).expect("Failed to decode block header")
).expect("Failed to create block header with hash")
),
);
let (hash, header) = $blocks.get($name).unwrap();
assert_eq!(block_hash, *hash);
assert_eq!(block_hash_expected, *header.hash);
}
}
pub struct BlocksDb {
blocks: HashMap<&'static str, (BlockHash, BlockHeaderWithHash)>,
}
impl BlocksDb {
pub fn block_hash(&self, name: &str) -> BlockHash {
let (hash, _) = self.blocks.get(name).unwrap();
hash.clone()
}
pub fn name(&self, block_hash: &BlockHash) -> String {
self.blocks
.iter()
.find(|(_, (bh, _))| bh.eq(block_hash))
.map(|(k, _)| k.to_string())
.unwrap()
}
pub fn header(&self, name: &str) -> BlockHeaderWithHash {
let (_, header) = self.blocks.get(name).unwrap();
header.clone()
}
}
/// These block where dump from [test_state.ml -> build_valid_chain]
pub(crate) fn init_blocks() -> BlocksDb {
let mut blocks = HashMap::new();
// Genesis - BLockGenesisGenesisGenesisGenesisGenesisGeneskvg68z -> BLqDCPdEsAv9giMTD5Uv7Z8HVF3mJAfZw3iH1XvR9p2B8uSsgdn
// {"level":0,"proto":0,"predecessor":"BLockGenesisGenesisGenesisGenesisGenesisGeneskvg68z","timestamp":"1970-01-01T00:00:00Z","validation_pass":0,"operations_hash":"LLoZS2LW3rEi7KYU4ouBQtorua37aWWCtpDmv1n2x3xoKi6sVXLWp","fitness":[],"context":"CoVea41f9dPhkymYEfPsXV5FmyzDb91iz1Grk6zasb31zv9nEZjN","protocol_data":""}
init_block!(blocks, "Genesis", "BLockGenesisGenesisGenesisGenesisGenesisGeneskvg68z", "BLqDCPdEsAv9giMTD5Uv7Z8HVF3mJAfZw3iH1XvR9p2B8uSsgdn", "00000000008fcf233671b6a04fcf679d2a381c2544ea6c1ea29ba6157776ed8424418da9c10000000000000000000e5751c026e543b2e8ab2eb06099daa1d1e5df47778f7787faab45cdf12fe3a800000000844a8057887e732f873636fae3ef3dd0674646b6c3b27182034e41cd01ce2de1");
// A1
// {"level":1,"proto":0,"predecessor":"BLockGenesisGenesisGenesisGenesisGenesisGeneskvg68z","timestamp":"1970-01-01T00:00:06Z","validation_pass":1,"operations_hash":"LLoaE6dT25pScPXK1u6udM3qTyJF1XX4C9zhbDB8iRFvMrDJCxpeV","fitness":["0000000000000001"],"context":"CoVTPCEqHAJQ1knCdXo7BUZjWkYHKqudzct4YjwK2qMxpy9f9smh","protocol_data":"000000024131"}
init_block!(blocks, "A1", "BMPpsdYyqRPUx4bPM187UguF29NUAxNhh5tXXrSNMbb6UKZf2iM", "00000001008fcf233671b6a04fcf679d2a381c2544ea6c1ea29ba6157776ed8424418da9c100000000000000060176f52f440c8e4ab99a2a4ef76474c4bcf4ee09238150ed77fd73fb3be1fe4af30000000c0000000800000000000000016ae39b9a0de0eff1d52ae16a9282747edf61f89e4bc72b943221ca94fd3b9b48000000024131");
// A2
// {"level":2,"proto":0,"predecessor":"BMPpsdYyqRPUx4bPM187UguF29NUAxNhh5tXXrSNMbb6UKZf2iM","timestamp":"1970-01-01T00:00:16Z","validation_pass":1,"operations_hash":"LLoZPCKN1ZAUGopsojjhxEHMegPKYtLL6MXsR9vmUEtB6f8vsBW3m","fitness":["0000000000000002"],"context":"CoVG7LmDBWkBCJuNSnyrQtt9maotfYRjQTtgEiq8VV9xVSCFnpvF","protocol_data":"000000024132"}
init_block!(blocks, "A2", "BLq4AAun3eFcHWA8BJZgnUy6DEkSRZde69MziAh2ct4wCE1weCY", "0000000200dd7c2bbc9594cd39fe49f29637f6bff5ca9d50f11dd341508bfacf714b7e28e300000000000000100107eb8155a0827d5ef666e43b15acdea8adb58e3817aa6ca7ac4a9c55eb41ebd20000000c000000080000000000000002514aa7bfad26b4289f9225f722803ad5d62294c931e8ccd8d237ea7e87afb236000000024132");
// A3
// {"level":3,"proto":0,"predecessor":"BLq4AAun3eFcHWA8BJZgnUy6DEkSRZde69MziAh2ct4wCE1weCY","timestamp":"1970-01-01T00:00:24Z","validation_pass":1,"operations_hash":"LLobEmNi6YBNnkPhA96raqZgXxpzdUtTrchWEiN5xERnja9DYVXoF","fitness":["0000000000000003"],"context":"CoWUk7yRZFKZXqXbkBdbabNdaWAxkdBcZvr6gK2iSdZSNgdzEWnu","protocol_data":"000000024133"}
init_block!(blocks, "A3", "BLMw95k8rwLf2aZmGiRh9jFMuKGgQXipKUMHk4WLE8YM4Z2WJ86", "000000030093131926e0640848ba856c0dd8efd864f7d9a0b5c263a5e03f869f5dc598943b000000000000001801fc2bb2c1c5997df6928a6dc2099f44125464dd8dc38fcf24b67db2a79fc82c0f0000000c000000080000000000000003f1acd04bbdb7838be6b8f74d74963cbb6b89633114e986ae1674eb80f0a6420c000000024133");
// A4
// {"level":4,"proto":0,"predecessor":"BLMw95k8rwLf2aZmGiRh9jFMuKGgQXipKUMHk4WLE8YM4Z2WJ86","timestamp":"1970-01-01T00:00:26Z","validation_pass":1,"operations_hash":"LLoazNce1rhdo8XCbVxfCzcHkUMXMwjHd66Pr4P56qygx2WPrQsN6","fitness":["0000000000000004"],"context":"CoUmdAefV4kn2Z9G7qHypqedCbTrSfJGaeTrAYvAZ9LEJH2ycqNa","protocol_data":"000000024134"}
init_block!(blocks, "A4", "BME4s6XySdprEvUwyG9A5YvcgsDnKzBKKSVQ6UoZ6mk3rBR7jNt", "0000000400557e36cf1cae93bda2831222102b7c4ce19a131c3d3d01aec176a7b00d1ee98a000000000000001a01db7daffe2c9e790d589a6b3ce96dc49efbb10fbb50f1e636707f751a5ae1f30b0000000c000000080000000000000004109c7826a2c620d2c5cac965b853a9bc98d6385ace6601a3a1515d518143f9af000000024134");
// A5
// {"level":5,"proto":0,"predecessor":"BME4s6XySdprEvUwyG9A5YvcgsDnKzBKKSVQ6UoZ6mk3rBR7jNt","timestamp":"1970-01-01T00:00:34Z","validation_pass":1,"operations_hash":"LLoaWkxXDhZFViUeF3UaSKuLUJbs9Mxx9QtAVXFfhWFSbsarJdR6B","fitness":["0000000000000005"],"context":"CoVNuije97tRC5t9nT8Wf79f8n4JLravT3tKdTu8u6SSWoo7ETBM","protocol_data":"000000024135"}
init_block!(blocks, "A5", "BKjP9MgvzqEDCdXaVvy2Yt5C52UtpUa9puUQ6konopdi9UKFFWp", "0000000500c7539814cb12b4fc92c3768ad7dc7322e6abeb3b9b563b556ecb69d341b260040000000000000022019cc9c998792c4ef6eb7c797cc8aa6c3dddd360d611746a3e827fc1dbecb5fe850000000c00000008000000000000000560bb24813522ffed0aabe1b776e9a2317639e4c57cf51ceb4145d8d75976447f000000024135");
// A6
// {"level":6,"proto":0,"predecessor":"BKjP9MgvzqEDCdXaVvy2Yt5C52UtpUa9puUQ6konopdi9UKFFWp","timestamp":"1970-01-01T00:00:35Z","validation_pass":1,"operations_hash":"LLoaKzR9mfrjup9r9onHtTdemXuiUxEtE4UTFGyRKTUxnQrD1Dkg4","fitness":["0000000000000006"],"context":"CoVSgGeehEaqSrikvKReCXwvxGxKc3Y1jpNjoN9YGUB1RjdGbhqf","protocol_data":"000000024136"}
init_block!(blocks, "A6", "BKm9XUEw7yWXEF8ERb9QQXncRe44smMJy8hgkpE57Pv2U6mLNtn", "0000000600027f8016df677b17a3b62d9f4e34ce9544289554a546ce5d1db87cbe2a4f927b00000000000000230184569a705486fd7bb7231ae792a28a499d94be7240d69671a5bc72ad1d1b65b60000000c00000008000000000000000669497732182ffb3e538a9e25c1443b7d1a989daae42e435edcd3ff3ef2ef7d12000000024136");
// A7
// {"level":7,"proto":0,"predecessor":"BKm9XUEw7yWXEF8ERb9QQXncRe44smMJy8hgkpE57Pv2U6mLNtn","timestamp":"1970-01-01T00:00:39Z","validation_pass":1,"operations_hash":"LLoaB9R6FQkYCnaj9DLLntenyvzHhan4HdGyvk2y4Yy1NCNfQkd8K","fitness":["0000000000000007"],"context":"CoUnTVf8rkYTb82tVQDbB4amRcJcM8BQY5Yb7o3NcqejK3iPPW8G","protocol_data":"000000024137"}
init_block!(blocks, "A7", "BLdUbYSyRkYiaYJ2N5GX9UHR8eHeaYyTGXoDRCx9BA9dQMvGvEo", "0000000700068192385150f050be916e7c5e3f07170485e496f9863b6f3fb6d18b6bd0c637000000000000002701704147069176a05aab67929dd7bb6c6dca3473aa9a908deb1e0ea4d74c75c0930000000c0000000800000000000000071280d005273dcf3f67d043b6b5f539d2f74dd73e6f0eb4a5d660f2275fb67912000000024137");
// A8
// {"level":8,"proto":0,"predecessor":"BLdUbYSyRkYiaYJ2N5GX9UHR8eHeaYyTGXoDRCx9BA9dQMvGvEo","timestamp":"1970-01-01T00:00:45Z","validation_pass":1,"operations_hash":"LLoZjnGfgrcCz7MGQhtjGv1UprjcCnyMFB4wAbzTQGfegXmBrL4ze","fitness":["0000000000000008"],"context":"CoWKW6oSENmEMm1KRkKUcKu6t2Z7EbxxpMPPLjf7QPsX1FU5rtyX","protocol_data":"000000024138"}
init_block!(blocks, "A8", "BKjtHh7SVHFMncnvYdxo1MZ78vHRC26CCEb8BYgGPgYhm98J5cY", "000000080078c8a8ead1a1d3552d63ce5ab671e67e14e07838ad02cc862f4d1cacc24f0060000000000000002d0136a960337b7cdd7dac3ff954699a6ce4e8447d1bc491a4d16af21b181dcf8a9d0000000c000000080000000000000008dcb0c9d7bd04a8039cb9e81141377dea11c93d44fbde0ee5f004a8ef2aeb8ded000000024138");
// B1
// {"level":4,"proto":0,"predecessor":"BLMw95k8rwLf2aZmGiRh9jFMuKGgQXipKUMHk4WLE8YM4Z2WJ86","timestamp":"1970-01-01T00:00:32Z","validation_pass":1,"operations_hash":"LLoaHSv7gZeFvmDtRHx3Mz4gdzFsKZ2sKsF9aSGagaU5Hyev3sMxL","fitness":["0000000000000004"],"context":"CoWHe9YkhrSXASSmysMv2yTpA9kmxPzCUBft8j4K3ua5QmshywVt","protocol_data":"000000024231"}
init_block!(blocks, "B1", "BLnnrZmgGM7266JbFTByPPjEMhY4yLmZq7jswsCEEAG49JQRafJ", "0000000400557e36cf1cae93bda2831222102b7c4ce19a131c3d3d01aec176a7b00d1ee98a0000000000000020017e9057f774f7dcc849651ee2ca66ace961921b4ad93bf8f559e34cf638da40440000000c000000080000000000000004d876e18398aa6f0299e7920079c545fcec9dad9dbee54392ccd856b4857d795a000000024231");
// B2
// {"level":5,"proto":0,"predecessor":"BLnnrZmgGM7266JbFTByPPjEMhY4yLmZq7jswsCEEAG49JQRafJ","timestamp":"1970-01-01T00:00:41Z","validation_pass":1,"operations_hash":"LLoapJhxXKpPX27pkThLv51MSdWuBJS73Az1wWQkNTg4KuBjwTCW2","fitness":["0000000000000005"],"context":"CoV7HqdQrymGjWgxHjPBEHRePHn2uxgcnmVNKZMdwBBmhtPgoPhZ","protocol_data":"000000024232"}
init_block!(blocks, "B2", "BKrKqDUnsoMVS872iYPBrpxGZGNDUgSJgpuo4X3g37vpqoG81Gg", "00000005008def2aa446ea14813fb3f83455d383a1d97a8d59befe548f4e809d1e4688599f000000000000002901c4a1b9a56fa0b7bda340ddbbebc341d30d4c98afa6c9916377642e3cbd517af80000000c0000000800000000000000053d44598b2ef87707a51d4fb2ba6004210368a13f996f26db874a3f0eaf72d2a2000000024232");
// B3
// {"level":6,"proto":0,"predecessor":"BKrKqDUnsoMVS872iYPBrpxGZGNDUgSJgpuo4X3g37vpqoG81Gg","timestamp":"1970-01-01T00:00:47Z","validation_pass":1,"operations_hash":"LLoax8ixMAWcMacdW4HqgAyeXVByykoYLYzN2yBftEnee436DwMcD","fitness":["0000000000000006"],"context":"CoUySwpvuRn5wLAvuJgJvRykeiYcYwgyb8kqXnPEsr1k1gTHgii1","protocol_data":"000000024233"}
init_block!(blocks, "B3", "BLFc7roUTEU9kxnvoenJuFQiaybNpeCLet5MrySYKC5ByGGeuzq", "00000006001243413091fd56379c270ab1713bb64d664be7344b8c36f2163d543c425889d2000000000000002f01d667e952c00d8f3f3c91a9ab64e71420e1a754816cf48d06403b0d41a44c4f350000000c0000000800000000000000062b756284973374c23d90c25ff741c68946f0c3762f77fbb0b3dc72b5a59e5a6d000000024233");
// B4
// {"level":7,"proto":0,"predecessor":"BLFc7roUTEU9kxnvoenJuFQiaybNpeCLet5MrySYKC5ByGGeuzq","timestamp":"1970-01-01T00:00:49Z","validation_pass":1,"operations_hash":"LLoZwmsD4hAdfdsVHcxEdA7gP8Xfoua4oCnndodosMtysTpv31wXo","fitness":["0000000000000007"],"context":"CoVTTtAGew3XLidqRcsJC9RvyAEH4quMq3i77636k3Gsq7za5Cxs","protocol_data":"000000024234"}
init_block!(blocks, "B4", "BLdkVcEw2Sb1RhtoQwEUirbHZLU9yMWDrPTiBfbNGB2ky5v9Yek", "0000000700471fe862a4e8f980072e68a4587072d3b5e058434cfdc3bb8aff406179703aa600000000000000310151e4ac8c070ea450cf258b0b222fb557779d268f86a2f021fed622f6b2128aa30000000c0000000800000000000000076b12981ebf5ce0b849bfa6ed9ad019bd7167399ee724a3b3cb7136c442eb6e30000000024234");