This repository has been archived by the owner on Oct 14, 2022. It is now read-only.
/
chain.rs
7664 lines (6925 loc) · 282 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 2018 The Purple Library Authors
This file is part of the Purple Library.
The Purple Library is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The Purple Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the Purple Library. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::block::Block;
use crate::types::*;
use bin_tools::*;
use crypto::Hash;
use elastic_array::ElasticArray128;
use hashbrown::{HashMap, HashSet};
use hashdb::HashDB;
use lazy_static::*;
use lru::LruCache;
use parking_lot::{Mutex, RwLock};
use persistence::PersistentDb;
use std::collections::VecDeque;
use std::hash::Hash as HashTrait;
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq)]
pub enum ChainErr {
/// The block already exists in the chain.
AlreadyInChain,
/// The parent of the given block is invalid
InvalidParent,
/// The given block does not have a parent hash
NoParentHash,
/// Bad block height
BadHeight,
/// The block with the given hash is not written in the ledger
NoSuchBlock,
/// The orphan pool is full.
TooManyOrphans,
/// The append condition returned false
BadAppendCondition,
/// Could not find a matching checkpoint
NoCheckpointFound,
}
lazy_static! {
/// Canonical tip block key
static ref TIP_KEY: Hash = { crypto::hash_slice(b"canonical_tip") };
/// The key of the root block
static ref ROOT_KEY: Hash = { crypto::hash_slice(b"root_block") };
/// The key to the canonical height of the chain
static ref CANONICAL_HEIGHT_KEY: Hash = { crypto::hash_slice(b"canonical_height") };
}
#[derive(Clone)]
/// Thread-safe reference to a chain and its block cache.
pub struct ChainRef<B: Block> {
/// Atomic reference to the chain.
pub chain: Arc<RwLock<Chain<B>>>,
/// Block lookup cache.
block_cache: Arc<Mutex<LruCache<Hash, Arc<B>>>>,
}
impl<B: Block> ChainRef<B> {
pub fn new(chain: Arc<RwLock<Chain<B>>>) -> ChainRef<B> {
ChainRef {
chain,
block_cache: Arc::new(Mutex::new(LruCache::new(B::BLOCK_CACHE_SIZE))),
}
}
/// Attempts to fetch a block by its hash from the cache
/// and if it doesn't succeed it then attempts to retrieve
/// it from the database.
pub fn query(&self, hash: &Hash) -> Option<Arc<B>> {
let cache_result = {
let mut cache = self.block_cache.lock();
if let Some(result) = cache.get(hash) {
Some(result.clone())
} else {
None
}
};
if let Some(result) = cache_result {
Some(result)
} else {
let chain_result = {
let chain = self.chain.read();
if let Some(result) = chain.query(hash) {
Some(result)
} else {
None
}
};
if let Some(result) = chain_result {
let mut cache = self.block_cache.lock();
if cache.get(hash).is_none() {
// Cache result and then return it
cache.put(hash.clone(), result.clone());
}
Some(result)
} else {
None
}
}
}
}
#[derive(Debug)]
/// Generic chain
pub struct Chain<B: Block> {
/// Reference to the database storing the chain.
db: PersistentDb,
/// The current height of the chain.
height: u64,
/// The tip block of the canonical chain.
canonical_tip: Arc<B>,
/// The state associated with the canonical tip
canonical_tip_state: UnflushedChainState<B::ChainState>,
/// The block from which the canonical chain and
/// all current forks descend.
root_block: Arc<B>,
/// The root state from which all other states descend.
root_state: FlushedChainState<B::ChainState>,
/// Memory pool of blocks that are not in the canonical chain.
orphan_pool: HashMap<Hash, Arc<B>>,
/// The biggest height of all orphans
max_orphan_height: Option<u64>,
/// Height of the last state that has a checkpoint
last_checkpoint_height: Option<u64>,
/// Earliest height to have a checkpoint
earliest_checkpoint_height: Option<u64>,
/// Mapping between heights and their sets of
/// orphans mapped to their inverse height.
heights_mapping: HashMap<u64, HashMap<Hash, u64>>,
/// Mapping between heights and associated
/// checkpointed state. Note that this only
/// stores the states of the canonical chain.
///
/// TODO: Checkpoint states on non-canonical chains as well
///
/// TODO: Flush chain states when we are certain that their
/// blocks are mostly certain to stay in the canonical chain (
/// and otherwise any change would trigger a re-sync).
heights_state_mapping: HashMap<u64, UnflushedChainState<B::ChainState>>,
/// Mapping between orphans and their orphan types/validation statuses.
validations_mapping: HashMap<Hash, OrphanType>,
/// Mapping between disconnected chains heads and tips.
disconnected_heads_mapping: HashMap<Hash, HashSet<Hash>>,
/// Mapping between disconnected heads and the largest
/// height of any associated tip along with its hash.
disconnected_heads_heights: HashMap<Hash, (u64, Hash)>,
/// Mapping between disconnected chains tips and heads.
disconnected_tips_mapping: HashMap<Hash, Hash>,
/// Set containing tips of valid chains that descend
/// from the canonical chain.
valid_tips: HashSet<Hash>,
/// Validation states associated with the valid tips
valid_tips_states: HashMap<Hash, UnflushedChainState<B::ChainState>>,
/// Whether the chain is in archival mode or not
archival_mode: bool,
}
impl<B: Block> Chain<B> {
pub fn new(mut db_ref: PersistentDb, root_state: B::ChainState, archival_mode: bool) -> Chain<B> {
let tip_db_res = db_ref.get(&TIP_KEY);
let found_tip = tip_db_res.is_some();
let canonical_tip = match tip_db_res {
Some(tip) => {
let mut buf = [0; 32];
buf.copy_from_slice(&tip);
let block_bytes = db_ref.get(&Hash(buf)).unwrap();
B::from_bytes(&block_bytes).unwrap()
}
None => B::genesis(),
};
let root_state = FlushedChainState::new(root_state);
let root_db_res = db_ref.get(&ROOT_KEY);
let root_block = match root_db_res {
Some(tip) => {
let mut buf = [0; 32];
buf.copy_from_slice(&tip);
let block_bytes = db_ref.get(&Hash(buf)).unwrap();
B::from_bytes(&block_bytes).unwrap()
}
None => B::genesis(),
};
let mut heights_state_mapping = HashMap::with_capacity(B::MAX_CHECKPOINTS);
let mut earliest_checkpoint_height = None;
let mut last_checkpoint_height = None;
let canonical_tip_state = if canonical_tip.is_genesis() {
root_state.clone().modify()
} else {
// Calculate canonical tip state by gathering
// all blocks from the tip to the root and
// then applying each block to the state.
//
// We checkpoint states along the way if we can.
let mut blocks = vec![canonical_tip.clone()];
let mut state = root_state.clone().modify();
let mut block_hash = canonical_tip.parent_hash().unwrap();
// Gather blocks
loop {
if block_hash == root_block.block_hash().unwrap() {
break;
}
let block_res = db_ref.get(&block_hash).unwrap();
let block = B::from_bytes(&block_res).unwrap();
block_hash = block.parent_hash().unwrap();
blocks.push(block);
}
// Apply each block to the state
while let Some(block) = blocks.pop() {
let s = B::append_condition(block.clone(), state.inner()).unwrap();
let s = UnflushedChainState::new(s);
// Perform checkpoint
{
let height = block.height();
let last_checkpoint = last_checkpoint_height.unwrap_or(0);
// Checkpoint state if we have reached the quota
if height - last_checkpoint == B::CHECKPOINT_INTERVAL as u64 {
if let None = earliest_checkpoint_height {
earliest_checkpoint_height = Some(height);
}
last_checkpoint_height = Some(height);
heights_state_mapping.insert(height, s.clone());
}
}
state = s;
}
state
};
let height = match db_ref.get(&CANONICAL_HEIGHT_KEY) {
Some(height) => decode_be_u64!(&height).unwrap(),
None => {
if !found_tip {
// Set 0 height
db_ref.emplace(
CANONICAL_HEIGHT_KEY.clone(),
ElasticArray128::<u8>::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]),
);
}
0
}
};
Chain {
canonical_tip,
canonical_tip_state,
root_block,
root_state,
earliest_checkpoint_height,
last_checkpoint_height,
heights_state_mapping,
orphan_pool: HashMap::with_capacity(B::MAX_ORPHANS),
heights_mapping: HashMap::with_capacity(B::MAX_ORPHANS),
validations_mapping: HashMap::with_capacity(B::MAX_ORPHANS),
disconnected_heads_mapping: HashMap::with_capacity(B::MAX_ORPHANS),
disconnected_heads_heights: HashMap::with_capacity(B::MAX_ORPHANS),
disconnected_tips_mapping: HashMap::with_capacity(B::MAX_ORPHANS),
valid_tips: HashSet::with_capacity(B::MAX_ORPHANS),
valid_tips_states: HashMap::with_capacity(B::MAX_ORPHANS),
max_orphan_height: None,
archival_mode,
height,
db: db_ref,
}
}
/// Rewinds the canonical chain to the block with the given hash.
///
/// Returns `Err(ChainErr::NoSuchBlock)` if there is no block with
/// the given hash in the canonical chain.
pub fn rewind(&mut self, block_hash: &Hash) -> Result<(), ChainErr> {
let genesis = B::genesis();
let new_tip = if *block_hash == genesis.block_hash().unwrap() {
genesis
} else if let Some(new_tip) = self.db.get(block_hash) {
B::from_bytes(&new_tip).unwrap()
} else {
return Err(ChainErr::NoSuchBlock);
};
// TODO: Rewind states
let canonical_state = self.canonical_tip_state.clone();
let mut current = self.canonical_tip.clone();
let mut inverse_height = 1;
// Remove canonical tip from the chain
// and mark it as a valid chain tip.
self.db.remove(¤t.block_hash().unwrap());
// Remove current height entry
let current_height_key = crypto::hash_slice(&encode_be_u64!(current.height()));
self.db.remove(¤t_height_key);
// Add the old tip to the orphan pool
self.orphan_pool
.insert(current.block_hash().unwrap(), current.clone());
// Mark old tip as a valid chain tip
self.validations_mapping.insert(current.block_hash().unwrap(), OrphanType::ValidChainTip);
self.valid_tips.insert(current.block_hash().unwrap());
self.valid_tips_states.insert(current.block_hash().unwrap(), canonical_state);
let cur_height = current.height();
// Insert to heights mapping
if let Some(entries) = self.heights_mapping.get_mut(&cur_height) {
entries.insert(current.block_hash().unwrap(), 0);
} else {
let mut hm = HashMap::new();
hm.insert(current.block_hash().unwrap(), 0);
self.heights_mapping.insert(cur_height, hm);
}
// Try to update the maximum orphan height with
// the previous canonical tip's height.
self.update_max_orphan_height(current.height());
// Traverse parents and remove them until we
// reach the block with the given hash.
loop {
let parent_hash = current.parent_hash().unwrap();
if parent_hash == *block_hash {
break;
} else {
let parent = B::from_bytes(&self.db.get(&parent_hash).unwrap()).unwrap();
let cur_height = parent.height();
// Remove parent from db
self.db.remove(&parent_hash);
// Remove current height entry
let current_height_key = crypto::hash_slice(&encode_be_u64!(cur_height));
self.db.remove(¤t_height_key);
// Add the parent to the orphan pool
self.orphan_pool
.insert(parent.block_hash().unwrap(), parent.clone());
// Mark parent as belonging to a valid chain
self.validations_mapping.insert(
parent.block_hash().unwrap(),
OrphanType::BelongsToValidChain,
);
// Insert to heights mapping
if let Some(entries) = self.heights_mapping.get_mut(&cur_height) {
entries.insert(parent.block_hash().unwrap(), inverse_height);
} else {
let mut hm = HashMap::new();
hm.insert(parent.block_hash().unwrap(), inverse_height);
self.heights_mapping.insert(cur_height, hm);
}
// Update max orphan height
self.update_max_orphan_height(parent.height());
current = parent;
inverse_height += 1;
}
}
let state = self.search_fetch_next_state(new_tip.height());
self.height = new_tip.height();
self.write_canonical_height(new_tip.height());
self.canonical_tip_state = state;
self.canonical_tip = new_tip;
// Flush changes
self.db.flush();
Ok(())
}
fn update_max_orphan_height(&mut self, new_height: u64) {
if self.max_orphan_height.is_none() {
self.max_orphan_height = Some(new_height);
} else {
let cur_height = self.max_orphan_height.unwrap();
if new_height > cur_height {
self.max_orphan_height = Some(new_height);
}
}
}
fn write_block(&mut self, block: Arc<B>) {
let block_hash = block.block_hash().unwrap();
//println!("DEBUG WRITING BLOCK: {:?}", block_hash);
assert!(self.disconnected_heads_mapping.get(&block_hash).is_none());
assert!(self.disconnected_tips_mapping.get(&block_hash).is_none());
// We can only write a block whose parent
// hash is the hash of the current canonical
// tip block.
assert_eq!(
block.parent_hash().unwrap(),
self.canonical_tip.block_hash().unwrap()
);
// Place block in the ledger
self.db.emplace(
block_hash.clone(),
ElasticArray128::<u8>::from_slice(&block.to_bytes()),
);
// Set new tip block
self.canonical_tip = block.clone();
let mut height = decode_be_u64!(self.db.get(&CANONICAL_HEIGHT_KEY).unwrap()).unwrap();
// Increment height
height += 1;
// Set new height
self.height = height;
let encoded_height = encode_be_u64!(height);
// Write new height
self.write_canonical_height(height);
// Write block height
let block_height_key = Self::compute_height_key(&block_hash);
self.db.emplace(
block_height_key,
ElasticArray128::<u8>::from_slice(&encoded_height),
);
// Write height mapping
self.db.emplace(
crypto::hash_slice(&encoded_height),
ElasticArray128::<u8>::from_slice(&block_hash.0)
);
self.orphan_pool.remove(&block_hash);
self.validations_mapping.remove(&block_hash);
// Remove from height mappings
if let Some(orphans) = self.heights_mapping.get_mut(&block.height()) {
orphans.remove(&block_hash);
}
// Remove from valid tips
self.valid_tips.remove(&block_hash);
self.valid_tips_states.remove(&block_hash);
// Update max orphan height if this is the case
if let Some(max_height) = self.max_orphan_height {
if block.height() == max_height {
// Traverse heights backwards until we have
// an entry. We then set that as the new max orphan height.
let mut current = max_height - 1;
loop {
if current == 0 {
self.max_orphan_height = None;
break;
}
if self.heights_mapping.get(¤t).is_some() {
self.max_orphan_height = Some(current);
break;
}
current -= 1;
}
}
}
self.db.flush();
// Execute after write callback
if let Some(mut cb) = B::after_write() {
cb(block);
}
}
fn write_canonical_height(&mut self, height: u64) {
let encoded_height = encode_be_u64!(height);
self.db.emplace(
CANONICAL_HEIGHT_KEY.clone(),
ElasticArray128::<u8>::from_slice(&encoded_height),
);
}
fn write_orphan(&mut self, orphan: Arc<B>, orphan_type: OrphanType, inverse_height: u64) {
let orphan_hash = orphan.block_hash().unwrap();
let height = orphan.height();
if let OrphanType::ValidChainTip = orphan_type {
self.valid_tips.insert(orphan.block_hash().unwrap());
}
// Write height mapping
if let Some(height_entry) = self.heights_mapping.get_mut(&height) {
if height_entry.get(&orphan_hash).is_none() {
height_entry.insert(orphan_hash.clone(), inverse_height);
}
} else {
let mut map = HashMap::new();
map.insert(orphan_hash.clone(), inverse_height);
self.heights_mapping.insert(height, map);
}
// Write to orphan pool
self.orphan_pool.insert(orphan_hash.clone(), orphan.clone());
// Set max orphan height if this is the case
self.update_max_orphan_height(height);
// Write to validations mappings
self.validations_mapping.insert(orphan_hash, orphan_type);
}
fn compute_height_key(hash: &Hash) -> Hash {
let block_height_key = format!("{}.height", hex::encode(hash.to_vec()));
crypto::hash_slice(block_height_key.as_bytes())
}
/// Attempts to attach orphans to the canonical chain
/// starting with the given height.
fn process_orphans(&mut self, start_height: u64) {
if let Some(max_orphan_height) = self.max_orphan_height {
let mut h = start_height;
let mut done = false;
let mut prev_valid_tips = HashSet::new();
loop {
if h > max_orphan_height {
break;
}
if let Some(orphans) = self.heights_mapping.get(&h) {
if orphans.len() == 1 {
// HACK: Maybe we can find a better/faster way to get the only item of a set?
let (orphan_hash, _) = orphans.iter().find(|_| true).unwrap();
let orphan = self.orphan_pool.get(orphan_hash).unwrap().clone();
let block_hash = orphan.block_hash().unwrap();
// If the orphan directly follows the canonical
// tip, write it to the chain.
if orphan.parent_hash().unwrap() == self.canonical_tip.block_hash().unwrap()
{
// Verify append condition
let append_condition = match B::append_condition(orphan.clone(), self.canonical_tip_state.clone().inner()) {
// Set new tip state if the append can proceed
Ok(new_tip_state) => Some(new_tip_state),
_ => None
};
if !done {
// Verify append condition
if let Some(new_tip_state) = append_condition {
let new_tip_state = UnflushedChainState::new(new_tip_state);
self.make_valid_tips(&block_hash, new_tip_state.clone());
self.write_block(orphan.clone());
// Perform checkpoint
{
let height = self.height;
let last_checkpoint_height = self.last_checkpoint_height.unwrap_or(0);
// Checkpoint state if we have reached the quota
if height - last_checkpoint_height == B::CHECKPOINT_INTERVAL as u64 {
if let None = self.earliest_checkpoint_height {
self.earliest_checkpoint_height = Some(height);
}
self.last_checkpoint_height = Some(height);
self.heights_state_mapping.insert(height, new_tip_state.clone());
}
}
self.canonical_tip_state = new_tip_state;
} else {
done = true;
}
} else {
break;
}
} else {
break;
}
} else if orphans.is_empty() {
if prev_valid_tips.is_empty() {
break;
} else {
// Mark processing as done but continue so we can
// update the current valid chains.
if !done {
done = true;
} else {
break;
}
}
} else {
let mut new_prev_valid_tips = prev_valid_tips.clone();
let mut obsolete = HashSet::new();
let mut buf: Vec<(Hash, u64, B::ChainState)> = Vec::with_capacity(orphans.len());
for (o, i_h) in orphans.iter() {
// Filter out orphans that do not follow
// the canonical tip.
let orphan = self.orphan_pool.get(o).unwrap();
let orphan_parent = orphan.parent_hash().unwrap();
let canonical_tip = self.canonical_tip.block_hash().unwrap();
if orphan_parent == canonical_tip {
let new_state = {
match B::append_condition(orphan.clone(), self.canonical_tip_state.clone().inner()) {
// Set new tip state if the append can proceed
Ok(new_tip_state) => Some(new_tip_state),
_ => None
}
};
if let Some(new_state) = new_state {
buf.push((o.clone(), i_h.clone(), new_state));
} else {
// TODO: Maybe cleanup here? Issue #109
}
} else if prev_valid_tips.contains(&orphan_parent) {
let append_condition = {
let parent_state = self.valid_tips_states.get(&orphan_parent).unwrap();
match B::append_condition(orphan.clone(), parent_state.clone().inner()) {
// Set new tip state if the append can proceed
Ok(new_tip_state) => Some(new_tip_state),
_ => None
}
};
if let Some(new_tip_state) = append_condition {
// Mark old tip as belonging to valid chain
let parent_status =
self.validations_mapping.get_mut(&orphan_parent).unwrap();
*parent_status = OrphanType::BelongsToValidChain;
// Mark new tip
let status = self.validations_mapping.get_mut(&o).unwrap();
*status = OrphanType::ValidChainTip;
obsolete.insert(orphan_parent.clone());
self.valid_tips_states.insert(o.clone(), UnflushedChainState::new(new_tip_state));
// Add to valid tips sets
self.valid_tips.insert(o.clone());
new_prev_valid_tips.remove(&orphan_parent);
new_prev_valid_tips.insert(o.clone());
} else {
// TODO: Maybe cleanup here? Issue #109
}
} else {
}
}
// Remove obsolete tips
for b in obsolete.iter() {
self.valid_tips.remove(&b);
self.valid_tips_states.remove(&b);
}
prev_valid_tips = new_prev_valid_tips;
if buf.is_empty() {
if prev_valid_tips.is_empty() {
break;
} else {
// Mark processing as done but continue so we can
// update tips information.
if !done {
done = true;
continue;
} else {
break;
}
}
}
// Write the orphan with the greatest inverse height
buf.sort_unstable_by(|(_, a, _), (_, b, _)| a.cmp(&b));
if !done {
if let Some((to_write, _, state)) = buf.pop() {
let to_write = self.orphan_pool.get(&to_write).unwrap().clone();
let block_hash = to_write.block_hash().unwrap();
let height = to_write.height();
let last_checkpoint_height = self.last_checkpoint_height.unwrap_or(0);
let state = UnflushedChainState::new(state);
// Checkpoint state if we have reached the quota
if height - last_checkpoint_height == B::CHECKPOINT_INTERVAL as u64 {
if let None = self.earliest_checkpoint_height {
self.earliest_checkpoint_height = Some(height);
}
self.last_checkpoint_height = Some(height);
self.heights_state_mapping.insert(height, state.clone());
}
self.make_valid_tips(&block_hash, state.clone());
self.canonical_tip_state = state;
self.write_block(to_write.clone());
}
}
// Place remaining tips in valid tips set
// and mark them as valid chain tips.
for (o, _, state) in buf {
let status = self.validations_mapping.get_mut(&o).unwrap();
*status = OrphanType::ValidChainTip;
prev_valid_tips.insert(o);
self.valid_tips.insert(o.clone());
self.valid_tips_states.insert(o.clone(), UnflushedChainState::new(state));
}
}
}
h += 1;
}
}
}
/// Attempts to switch the canonical chain to the valid chain
/// which has the given canidate tip. Do nothing if this is not
/// possible.
fn attempt_switch(&mut self, candidate_tip: Arc<B>) {
let candidate_hash = candidate_tip.block_hash().unwrap();
assert!(self.valid_tips.contains(&candidate_hash));
assert!(self.disconnected_heads_mapping.get(&candidate_hash).is_none());
assert!(self.disconnected_tips_mapping.get(&candidate_hash).is_none());
if candidate_tip.height() > self.height + B::SWITCH_OFFSET as u64 {
let mut to_write: VecDeque<Arc<B>> = VecDeque::new();
to_write.push_front(candidate_tip.clone());
// Find the horizon block i.e. the common
// ancestor of both the candidate tip and
// the canonical tip.
let horizon = {
let mut current = candidate_tip.parent_hash().unwrap();
// Traverse parents until we find a canonical block
loop {
if self.db.get(¤t).is_some() {
break;
}
let cur = self.orphan_pool.get(¤t).unwrap();
to_write.push_front(cur.clone());
current = cur.parent_hash().unwrap();
}
current
};
// Rewind to horizon
self.rewind(&horizon).unwrap();
// Set the canonical tip state as the one belonging to the new tip
let state = self.valid_tips_states.remove(&candidate_hash).unwrap();
self.canonical_tip_state = state;
// Write the blocks from the candidate chain
for block in to_write {
let block_hash = block.block_hash().unwrap();
// Don't write the horizon
if block_hash == horizon {
continue;
}
self.disconnected_heads_mapping.remove(&block_hash);
self.disconnected_tips_mapping.remove(&block_hash);
self.disconnected_heads_heights.remove(&block_hash);
self.write_block(block);
}
}
}
/// Attempts to attach a disconnected chain tip to other
/// disconnected chains. Returns the final status of the tip.
fn attempt_attach(&mut self, tip_hash: &Hash, initial_status: OrphanType) -> OrphanType {
let mut status = initial_status;
let mut to_attach = Vec::with_capacity(B::MAX_ORPHANS);
let our_head_hash = self.disconnected_tips_mapping.get(tip_hash).unwrap();
// Find a matching disconnected chain head
for (head_hash, _) in self.disconnected_heads_mapping.iter() {
// Skip our tip
if head_hash == our_head_hash || head_hash == tip_hash {
continue;
}
let head = self.orphan_pool.get(head_hash).unwrap();
// Attach chain to our tip
if head.parent_hash().unwrap() == *tip_hash {
to_attach.push(head_hash.clone());
status = OrphanType::BelongsToDisconnected;
}
}
let cur_head = self
.disconnected_tips_mapping
.get(tip_hash)
.unwrap()
.clone();
// Attach heads
for head in to_attach.iter() {
let tips = self.disconnected_heads_mapping.remove(head).unwrap();
self.disconnected_heads_heights.remove(head).unwrap();
let cur_tips =
if let Some(cur_tips) = self.disconnected_heads_mapping.get_mut(&cur_head) {
cur_tips
} else {
self.disconnected_heads_mapping
.insert(cur_head.clone(), HashSet::new());
self.disconnected_heads_mapping.get_mut(&cur_head).unwrap()
};
let mut to_traverse = Vec::with_capacity(tips.len());
// Clear our the head from tips set if it exists
cur_tips.remove(&cur_head);
self.disconnected_tips_mapping.remove(&cur_head);
// Merge tips
for tip_hash in tips.iter() {
let tip = self.orphan_pool.get(tip_hash).unwrap();
let (largest_height, _) = self.disconnected_heads_heights.get(&cur_head).unwrap();
if let Some(head_mapping) = self.disconnected_tips_mapping.get_mut(tip_hash) {
*head_mapping = cur_head.clone();
} else {
self.disconnected_tips_mapping
.insert(tip_hash.clone(), cur_head.clone());
}
// Update heights entry if new tip height is larger
if tip.height() > *largest_height {
self.disconnected_heads_heights
.insert(cur_head.clone(), (tip.height(), tip.block_hash().unwrap()));
}
to_traverse.push(tip.clone());
cur_tips.insert(tip_hash.clone());
}
// Update inverse heights starting from pushed tips
for tip in to_traverse {
self.traverse_inverse(tip, 0, false);
}
}
status
}
/// Attempts to attach a canonical chain tip to other
/// disconnected chains. Returns the final status of the
/// old tip, its inverse height and the new tip.
fn attempt_attach_valid(
&mut self,
tip: &mut Arc<B>,
tip_state: UnflushedChainState<B::ChainState>,
inverse_height: &mut u64,
status: &mut OrphanType,
) {
let block_hash = tip.block_hash().unwrap();
assert!(self.valid_tips.contains(&block_hash));
assert!(self.disconnected_heads_mapping.get(&block_hash).is_none());
assert!(self.disconnected_tips_mapping.get(&block_hash).is_none());
// Init validations mappings for tip
if self.validations_mapping.get(&block_hash).is_none() {
self.validations_mapping.insert(block_hash.clone(), status.clone());
}
let tip_clone = tip.clone();
let iterable = self
.disconnected_heads_heights
.iter()
.filter(|(h, (_, largest_tip))| {
let tips = self.disconnected_heads_mapping.get(h).unwrap();
assert!(tips.contains(&largest_tip));
let head = self.orphan_pool.get(h).unwrap();
let parent_hash = head.parent_hash().unwrap();
parent_hash == tip_clone.block_hash().unwrap()
});
let mut to_write: Vec<(Hash, Arc<B>, u64, B::ChainState)> = Vec::new();
// For each matching head, make the descending
// branches, valid chains.
for (head_hash, (largest_height, largest_tip)) in iterable {
let head = self.orphan_pool.get(head_hash).unwrap();
let tip_state = B::append_condition(head.clone(), tip_state.clone().inner());
if let Ok(tip_state) = tip_state {
let largest_tip = self.orphan_pool.get(&largest_tip).unwrap().clone();
let tip_height = tip.height();
let inverse_h = largest_height - tip_height;
to_write.push((head_hash.clone(), largest_tip, inverse_h, tip_state));
} else {
// TODO: Maybe cleanup here? Issue #109
}
}
for (head_hash, new_tip, inverse_h, tip_state) in to_write {
*status = OrphanType::BelongsToValidChain;
if inverse_h > *inverse_height {
*inverse_height = inverse_h;
*tip = new_tip;
}
// Remove old tip if we found a match
self.valid_tips.remove(&block_hash);
self.valid_tips_states.remove(&block_hash);
let old_tip_status = self.validations_mapping.get_mut(&block_hash).unwrap();
*old_tip_status = OrphanType::BelongsToValidChain;
self.make_valid_tips(&head_hash.clone(), UnflushedChainState::new(tip_state));
}
// Update inverse heights
self.traverse_inverse(tip.clone(), 0, true);
}
/// Recursively changes the validation status of the tips