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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
use std::collections::{VecDeque, HashSet};
use std::fmt;
use linked_hash_map::LinkedHashMap;
use chain::{BlockHeader, Transaction, IndexedBlockHeader, IndexedBlock, IndexedTransaction};
use storage;
use miner::{MemoryPoolOrderingStrategy, MemoryPoolInformation};
use network::ConsensusParams;
use primitives::bytes::Bytes;
use primitives::hash::H256;
use utils::{BestHeadersChain, BestHeadersChainInformation, HashQueueChain, HashPosition};
use types::{BlockHeight, StorageRef, MemoryPoolRef};
const VERIFYING_QUEUE: usize = 0;
const REQUESTED_QUEUE: usize = 1;
const SCHEDULED_QUEUE: usize = 2;
const NUMBER_OF_QUEUES: usize = 3;
#[derive(Default, PartialEq)]
pub struct BlockInsertionResult {
pub canonized_blocks_hashes: Vec<H256>,
pub transactions_to_reverify: Vec<IndexedTransaction>,
}
impl fmt::Debug for BlockInsertionResult {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("BlockInsertionResult")
.field("canonized_blocks_hashes", &self.canonized_blocks_hashes.iter().map(H256::reversed).collect::<Vec<_>>())
.field("transactions_to_reverify", &self.transactions_to_reverify)
.finish()
}
}
impl BlockInsertionResult {
#[cfg(test)]
pub fn with_canonized_blocks(canonized_blocks_hashes: Vec<H256>) -> Self {
BlockInsertionResult {
canonized_blocks_hashes: canonized_blocks_hashes,
transactions_to_reverify: Vec::new(),
}
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum BlockState {
Unknown,
Scheduled,
Requested,
Verifying,
Stored,
DeadEnd,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum TransactionState {
Unknown,
Verifying,
InMemory,
Stored,
}
pub struct Information {
pub scheduled: BlockHeight,
pub requested: BlockHeight,
pub verifying: BlockHeight,
pub stored: BlockHeight,
pub transactions: MemoryPoolInformation,
pub headers: BestHeadersChainInformation,
}
pub struct Chain {
genesis_block_hash: H256,
best_storage_block: storage::BestBlock,
storage: StorageRef,
hash_chain: HashQueueChain,
headers_chain: BestHeadersChain,
verifying_transactions: LinkedHashMap<H256, IndexedTransaction>,
memory_pool: MemoryPoolRef,
dead_end_blocks: HashSet<H256>,
is_segwit_possible: bool,
}
impl BlockState {
pub fn from_queue_index(queue_index: usize) -> BlockState {
match queue_index {
SCHEDULED_QUEUE => BlockState::Scheduled,
REQUESTED_QUEUE => BlockState::Requested,
VERIFYING_QUEUE => BlockState::Verifying,
_ => panic!("Unsupported queue_index: {}", queue_index),
}
}
pub fn to_queue_index(&self) -> usize {
match *self {
BlockState::Scheduled => SCHEDULED_QUEUE,
BlockState::Requested => REQUESTED_QUEUE,
BlockState::Verifying => VERIFYING_QUEUE,
_ => panic!("Unsupported queue: {:?}", self),
}
}
}
impl Chain {
pub fn new(storage: StorageRef, consensus: ConsensusParams, memory_pool: MemoryPoolRef) -> Self {
let genesis_block_hash = storage.block_hash(0)
.expect("storage with genesis block is required");
let best_storage_block = storage.best_block();
let best_storage_block_hash = best_storage_block.hash.clone();
let is_segwit_possible = consensus.is_segwit_possible();
Chain {
genesis_block_hash: genesis_block_hash,
best_storage_block: best_storage_block,
storage: storage,
hash_chain: HashQueueChain::with_number_of_queues(NUMBER_OF_QUEUES),
headers_chain: BestHeadersChain::new(best_storage_block_hash),
verifying_transactions: LinkedHashMap::new(),
memory_pool: memory_pool,
dead_end_blocks: HashSet::new(),
is_segwit_possible,
}
}
pub fn information(&self) -> Information {
Information {
scheduled: self.hash_chain.len_of(SCHEDULED_QUEUE),
requested: self.hash_chain.len_of(REQUESTED_QUEUE),
verifying: self.hash_chain.len_of(VERIFYING_QUEUE),
stored: self.best_storage_block.number + 1,
transactions: self.memory_pool.read().information(),
headers: self.headers_chain.information(),
}
}
pub fn storage(&self) -> StorageRef {
self.storage.clone()
}
pub fn memory_pool(&self) -> MemoryPoolRef {
self.memory_pool.clone()
}
pub fn is_segwit_possible(&self) -> bool {
self.is_segwit_possible
}
pub fn length_of_blocks_state(&self, state: BlockState) -> BlockHeight {
match state {
BlockState::Stored => self.best_storage_block.number + 1,
_ => self.hash_chain.len_of(state.to_queue_index()),
}
}
pub fn best_n_of_blocks_state(&self, state: BlockState, n: BlockHeight) -> Vec<H256> {
match state {
BlockState::Scheduled | BlockState::Requested | BlockState::Verifying => self.hash_chain.front_n_at(state.to_queue_index(), n),
_ => unreachable!("must be checked by caller"),
}
}
pub fn best_block(&self) -> storage::BestBlock {
match self.hash_chain.back() {
Some(hash) => storage::BestBlock {
number: self.best_storage_block.number + self.hash_chain.len(),
hash: hash.clone(),
},
None => self.best_storage_block.clone(),
}
}
pub fn best_storage_block(&self) -> storage::BestBlock {
self.best_storage_block.clone()
}
pub fn best_block_header(&self) -> storage::BestBlock {
let headers_chain_information = self.headers_chain.information();
if headers_chain_information.best == 0 {
return self.best_storage_block()
}
storage::BestBlock {
number: self.best_storage_block.number + headers_chain_information.best,
hash: self.headers_chain.at(headers_chain_information.best - 1)
.expect("got this index above; qed")
.hash,
}
}
pub fn block_hash(&self, number: BlockHeight) -> Option<H256> {
if number <= self.best_storage_block.number {
self.storage.block_hash(number)
} else {
self.hash_chain.at(number - self.best_storage_block.number)
}
}
pub fn block_number(&self, hash: &H256) -> Option<BlockHeight> {
if let Some(number) = self.storage.block_number(hash) {
return Some(number);
}
self.headers_chain.height(hash).map(|p| self.best_storage_block.number + p + 1)
}
pub fn block_header_by_number(&self, number: BlockHeight) -> Option<IndexedBlockHeader> {
if number <= self.best_storage_block.number {
self.storage.block_header(storage::BlockRef::Number(number)).map(Into::into)
} else {
self.headers_chain.at(number - self.best_storage_block.number)
}
}
pub fn block_header_by_hash(&self, hash: &H256) -> Option<IndexedBlockHeader> {
if let Some(block) = self.storage.block(storage::BlockRef::Hash(hash.clone())) {
return Some(block.block_header.into());
}
self.headers_chain.by_hash(hash)
}
pub fn block_state(&self, hash: &H256) -> BlockState {
match self.hash_chain.contains_in(hash) {
Some(queue_index) => BlockState::from_queue_index(queue_index),
None => if self.storage.contains_block(storage::BlockRef::Hash(hash.clone())) {
BlockState::Stored
} else if self.dead_end_blocks.contains(hash) {
BlockState::DeadEnd
} else {
BlockState::Unknown
},
}
}
pub fn block_locator_hashes(&self) -> Vec<H256> {
let mut block_locator_hashes: Vec<H256> = Vec::new();
let (local_index, step) = self.block_locator_hashes_for_queue(&mut block_locator_hashes);
let storage_index = if self.best_storage_block.number < local_index { 0 } else { self.best_storage_block.number - local_index };
self.block_locator_hashes_for_storage(storage_index, step, &mut block_locator_hashes);
block_locator_hashes
}
pub fn schedule_blocks_headers(&mut self, headers: Vec<IndexedBlockHeader>) {
self.hash_chain.push_back_n_at(SCHEDULED_QUEUE, headers.iter().map(|h| h.hash.clone()).collect());
self.headers_chain.insert_n(headers);
}
pub fn request_blocks_hashes(&mut self, n: BlockHeight) -> Vec<H256> {
let scheduled = self.hash_chain.pop_front_n_at(SCHEDULED_QUEUE, n);
self.hash_chain.push_back_n_at(REQUESTED_QUEUE, scheduled.clone());
scheduled
}
pub fn verify_block(&mut self, header: IndexedBlockHeader) {
self.hash_chain.push_back_at(VERIFYING_QUEUE, header.hash.clone());
self.headers_chain.insert(header);
}
pub fn verify_blocks(&mut self, blocks: Vec<IndexedBlockHeader>) {
for block in blocks {
self.verify_block(block);
}
}
#[cfg(test)]
pub fn verify_blocks_hashes(&mut self, n: BlockHeight) -> Vec<H256> {
let requested = self.hash_chain.pop_front_n_at(REQUESTED_QUEUE, n);
self.hash_chain.push_back_n_at(VERIFYING_QUEUE, requested.clone());
requested
}
pub fn mark_dead_end_block(&mut self, hash: &H256) {
self.dead_end_blocks.insert(hash.clone());
}
pub fn insert_best_block(&mut self, block: IndexedBlock) -> Result<BlockInsertionResult, storage::Error> {
assert_eq!(Some(self.storage.best_block().hash), self.storage.block_hash(self.storage.best_block().number));
let block_origin = self.storage.block_origin(&block.header)?;
trace!(target: "sync", "insert_best_block {:?} origin: {:?}", block.hash().reversed(), block_origin);
match block_origin {
storage::BlockOrigin::KnownBlock => {
unreachable!();
},
storage::BlockOrigin::CanonChain { .. } => {
self.storage.insert(block.clone())?;
self.storage.canonize(block.hash())?;
self.best_storage_block = self.storage.as_store().best_block();
self.headers_chain.block_inserted_to_storage(block.hash(), &self.best_storage_block.hash);
assert_eq!(self.best_storage_block.hash, block.hash().clone());
let mut memory_pool = self.memory_pool.write();
for tx in &block.transactions {
memory_pool.remove_by_hash(&tx.hash);
self.verifying_transactions.remove(&tx.hash);
for tx_input in &tx.raw.inputs {
memory_pool.remove_by_prevout(&tx_input.previous_output);
}
}
Ok(BlockInsertionResult {
canonized_blocks_hashes: vec![block.hash().clone()],
transactions_to_reverify: Vec::new(),
})
},
storage::BlockOrigin::SideChainBecomingCanonChain(origin) => {
let fork = self.storage.fork(origin.clone())?;
fork.store().insert(block.clone())?;
fork.store().canonize(block.hash())?;
self.storage.switch_to_fork(fork)?;
self.best_storage_block = self.storage.best_block();
self.headers_chain.block_inserted_to_storage(block.hash(), &self.best_storage_block.hash);
let this_block_transactions_hashes = block.transactions.iter().map(|tx| tx.hash.clone()).collect::<Vec<_>>();
let mut canonized_blocks_hashes = origin.canonized_route.clone();
let new_main_blocks_transactions_hashes = origin.canonized_route.into_iter()
.flat_map(|block_hash| self.storage.block_transaction_hashes(block_hash.into()))
.collect::<Vec<_>>();
let mut memory_pool = self.memory_pool.write();
for transaction_accepted in this_block_transactions_hashes.into_iter().chain(new_main_blocks_transactions_hashes.into_iter()) {
memory_pool.remove_by_hash(&transaction_accepted);
self.verifying_transactions.remove(&transaction_accepted);
}
let old_main_blocks_transactions = origin.decanonized_route.into_iter()
.flat_map(|block_hash| self.storage.indexed_block_transactions(block_hash.into()))
.collect::<Vec<_>>();
trace!(target: "sync", "insert_best_block, old_main_blocks_transactions: {:?}",
old_main_blocks_transactions.iter().map(|tx| tx.hash.reversed()).collect::<Vec<H256>>());
let memory_pool_transactions_count = memory_pool.information().transactions_count;
let memory_pool_transactions: Vec<IndexedTransaction> = memory_pool
.remove_n_with_strategy(memory_pool_transactions_count, MemoryPoolOrderingStrategy::ByTimestamp)
.into_iter()
.map(|t| t.into())
.collect();
let verifying_transactions: Vec<IndexedTransaction> = self.verifying_transactions
.iter()
.map(|(_, t)| t.clone())
.collect();
self.verifying_transactions.clear();
canonized_blocks_hashes.push(block.hash().clone());
let result = BlockInsertionResult {
canonized_blocks_hashes: canonized_blocks_hashes,
transactions_to_reverify: old_main_blocks_transactions.into_iter()
.chain(memory_pool_transactions.into_iter())
.chain(verifying_transactions.into_iter())
.collect(),
};
trace!(target: "sync", "result: {:?}", result);
Ok(result)
},
storage::BlockOrigin::SideChain(_origin) => {
let block_hash = block.hash().clone();
self.storage.insert(block)?;
self.headers_chain.block_inserted_to_storage(&block_hash, &self.best_storage_block.hash);
Ok(BlockInsertionResult::default())
},
}
}
pub fn forget_block(&mut self, hash: &H256) -> HashPosition {
self.headers_chain.remove(hash);
self.forget_block_leave_header(hash)
}
pub fn forget_blocks(&mut self, hashes: &[H256]) {
for hash in hashes {
self.forget_block(hash);
}
}
pub fn forget_block_leave_header(&mut self, hash: &H256) -> HashPosition {
match self.hash_chain.remove_at(VERIFYING_QUEUE, hash) {
HashPosition::Missing => match self.hash_chain.remove_at(REQUESTED_QUEUE, hash) {
HashPosition::Missing => self.hash_chain.remove_at(SCHEDULED_QUEUE, hash),
position => position,
},
position => position,
}
}
pub fn forget_blocks_leave_header(&mut self, hashes: &[H256]) {
for hash in hashes {
self.forget_block_leave_header(hash);
}
}
#[cfg(test)]
pub fn forget_block_with_state(&mut self, hash: &H256, state: BlockState) -> HashPosition {
self.headers_chain.remove(hash);
self.forget_block_with_state_leave_header(hash, state)
}
pub fn forget_block_with_state_leave_header(&mut self, hash: &H256, state: BlockState) -> HashPosition {
self.hash_chain.remove_at(state.to_queue_index(), hash)
}
pub fn forget_block_with_children(&mut self, hash: &H256) {
let mut removal_stack: VecDeque<H256> = VecDeque::new();
let mut removal_queue: VecDeque<H256> = VecDeque::new();
removal_queue.push_back(hash.clone());
while let Some(hash) = removal_queue.pop_front() {
removal_queue.extend(self.headers_chain.children(&hash));
removal_stack.push_back(hash);
}
while let Some(hash) = removal_stack.pop_back() {
self.forget_block(&hash);
}
}
pub fn forget_all_blocks_with_state(&mut self, state: BlockState) {
let hashes = self.hash_chain.remove_all_at(state.to_queue_index());
self.headers_chain.remove_n(hashes);
}
pub fn transaction_state(&self, hash: &H256) -> TransactionState {
if self.verifying_transactions.contains_key(hash) {
return TransactionState::Verifying;
}
if self.storage.contains_transaction(hash) {
return TransactionState::Stored;
}
if self.memory_pool.read().contains(hash) {
return TransactionState::InMemory;
}
TransactionState::Unknown
}
pub fn transactions_hashes_with_state(&self, state: TransactionState) -> Vec<H256> {
match state {
TransactionState::InMemory => self.memory_pool.read().get_transactions_ids(),
TransactionState::Verifying => self.verifying_transactions.keys().cloned().collect(),
_ => panic!("wrong argument"),
}
}
pub fn verify_transaction(&mut self, tx: IndexedTransaction) {
self.verifying_transactions.insert(tx.hash.clone(), tx);
}
pub fn forget_verifying_transaction(&mut self, hash: &H256) -> bool {
self.verifying_transactions.remove(hash).is_some()
}
pub fn forget_verifying_transaction_with_children(&mut self, hash: &H256) {
self.forget_verifying_transaction(hash);
let mut queue: VecDeque<H256> = VecDeque::new();
queue.push_back(hash.clone());
while let Some(hash) = queue.pop_front() {
let all_keys: Vec<_> = self.verifying_transactions.keys().cloned().collect();
for h in all_keys {
let remove_verifying_transaction = {
if let Some(entry) = self.verifying_transactions.get(&h) {
if entry.raw.inputs.iter().any(|i| i.previous_output.hash == hash) {
queue.push_back(h.clone());
true
} else {
false
}
} else {
unreachable!()
}
};
if remove_verifying_transaction {
self.verifying_transactions.remove(&h);
}
}
}
}
pub fn transaction_by_hash(&self, hash: &H256) -> Option<IndexedTransaction> {
self.verifying_transactions.get(hash).cloned()
.or_else(|| self.memory_pool.read().read_by_hash(hash).cloned().map(|t| t.into()))
}
pub fn insert_verified_transaction(&mut self, transaction: IndexedTransaction) {
let mut memory_pool = self.memory_pool.write();
for input in &transaction.raw.inputs {
memory_pool.remove_by_prevout(&input.previous_output);
}
memory_pool.insert_verified(transaction);
}
fn block_locator_hashes_for_queue(&self, hashes: &mut Vec<H256>) -> (BlockHeight, BlockHeight) {
let queue_len = self.hash_chain.len();
if queue_len == 0 {
return (0, 1);
}
let mut index = queue_len - 1;
let mut step = 1u32;
loop {
let block_hash = self.hash_chain[index].clone();
hashes.push(block_hash);
if hashes.len() >= 10 {
step <<= 1;
}
if index < step {
return (step - index - 1, step);
}
index -= step;
}
}
fn block_locator_hashes_for_storage(&self, mut index: BlockHeight, mut step: BlockHeight, hashes: &mut Vec<H256>) {
loop {
let block_hash = self.storage.block_hash(index)
.expect("private function; index calculated in `block_locator_hashes`; qed");
hashes.push(block_hash);
if hashes.len() >= 10 {
step <<= 1;
}
if index < step {
if index != 0 {
hashes.push(self.genesis_block_hash.clone())
}
break;
}
index -= step;
}
}
}
impl storage::TransactionProvider for Chain {
fn transaction_bytes(&self, hash: &H256) -> Option<Bytes> {
self.memory_pool.read().transaction_bytes(hash)
.or_else(|| self.storage.transaction_bytes(hash))
}
fn transaction(&self, hash: &H256) -> Option<Transaction> {
self.memory_pool.read().transaction(hash)
.or_else(|| self.storage.transaction(hash))
}
}
impl storage::BlockHeaderProvider for Chain {
fn block_header_bytes(&self, block_ref: storage::BlockRef) -> Option<Bytes> {
use ser::serialize;
self.block_header(block_ref).map(|h| serialize(&h))
}
fn block_header(&self, block_ref: storage::BlockRef) -> Option<BlockHeader> {
match block_ref {
storage::BlockRef::Hash(hash) => self.block_header_by_hash(&hash).map(|h| h.raw),
storage::BlockRef::Number(n) => self.block_header_by_number(n).map(|h| h.raw),
}
}
}
impl fmt::Debug for Information {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[sch:{} -> req:{} -> vfy:{} -> stored: {}]", self.scheduled, self.requested, self.verifying, self.stored)
}
}
impl fmt::Debug for Chain {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "chain: ["));
{
let mut num = self.best_storage_block.number;
try!(writeln!(f, "\tworse(stored): {} {:?}", 0, self.storage.block_hash(0)));
try!(writeln!(f, "\tbest(stored): {} {:?}", num, self.storage.block_hash(num)));
let queues = vec![
("verifying", VERIFYING_QUEUE),
("requested", REQUESTED_QUEUE),
("scheduled", SCHEDULED_QUEUE),
];
for (state, queue) in queues {
let queue_len = self.hash_chain.len_of(queue);
if queue_len != 0 {
try!(writeln!(f, "\tworse({}): {} {:?}", state, num + 1, self.hash_chain.front_at(queue)));
num += queue_len;
if let Some(pre_best) = self.hash_chain.pre_back_at(queue) {
try!(writeln!(f, "\tpre-best({}): {} {:?}", state, num - 1, pre_best));
}
try!(writeln!(f, "\tbest({}): {} {:?}", state, num, self.hash_chain.back_at(queue)));
}
}
}
writeln!(f, "]")
}
}
#[cfg(test)]
mod tests {
extern crate test_data;
use std::sync::Arc;
use parking_lot::RwLock;
use chain::{Transaction, IndexedBlockHeader};
use db::BlockChainDatabase;
use miner::MemoryPool;
use network::{Network, ConsensusParams, ConsensusFork};
use primitives::hash::H256;
use super::{Chain, BlockState, TransactionState, BlockInsertionResult};
use utils::HashPosition;
#[test]
fn chain_empty() {
let db = Arc::new(BlockChainDatabase::init_test_chain(vec![test_data::genesis().into()]));
let db_best_block = db.best_block();
let chain = Chain::new(db.clone(), ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore), Arc::new(RwLock::new(MemoryPool::new())));
assert_eq!(chain.information().scheduled, 0);
assert_eq!(chain.information().requested, 0);
assert_eq!(chain.information().verifying, 0);
assert_eq!(chain.information().stored, 1);
assert_eq!(chain.length_of_blocks_state(BlockState::Scheduled), 0);
assert_eq!(chain.length_of_blocks_state(BlockState::Requested), 0);
assert_eq!(chain.length_of_blocks_state(BlockState::Verifying), 0);
assert_eq!(chain.length_of_blocks_state(BlockState::Stored), 1);
assert_eq!(&chain.best_block(), &db_best_block);
assert_eq!(chain.block_state(&db_best_block.hash), BlockState::Stored);
assert_eq!(chain.block_state(&H256::from(0)), BlockState::Unknown);
}
#[test]
fn chain_block_path() {
let db = Arc::new(BlockChainDatabase::init_test_chain(vec![test_data::genesis().into()]));
let mut chain = Chain::new(db.clone(), ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore), Arc::new(RwLock::new(MemoryPool::new())));
let blocks = test_data::build_n_empty_blocks_from_genesis(6, 0);
let headers: Vec<IndexedBlockHeader> = blocks.into_iter().map(|b| b.block_header.into()).collect();
let hashes: Vec<_> = headers.iter().map(|h| h.hash.clone()).collect();
chain.schedule_blocks_headers(headers.clone());
assert!(chain.information().scheduled == 6 && chain.information().requested == 0
&& chain.information().verifying == 0 && chain.information().stored == 1);
chain.request_blocks_hashes(2);
assert!(chain.information().scheduled == 4 && chain.information().requested == 2
&& chain.information().verifying == 0 && chain.information().stored == 1);
chain.request_blocks_hashes(0);
assert!(chain.information().scheduled == 4 && chain.information().requested == 2
&& chain.information().verifying == 0 && chain.information().stored == 1);
chain.request_blocks_hashes(1);
assert!(chain.information().scheduled == 3 && chain.information().requested == 3
&& chain.information().verifying == 0 && chain.information().stored == 1);
assert_eq!(chain.forget_block_with_state(&hashes[0], BlockState::Scheduled), HashPosition::Missing);
assert!(chain.information().scheduled == 3 && chain.information().requested == 3
&& chain.information().verifying == 0 && chain.information().stored == 1);
assert_eq!(chain.forget_block_with_state(&hashes[1], BlockState::Requested), HashPosition::Inside(1));
assert_eq!(chain.forget_block_with_state(&hashes[0], BlockState::Requested), HashPosition::Front);
assert!(chain.information().scheduled == 3 && chain.information().requested == 1
&& chain.information().verifying == 0 && chain.information().stored == 1);
chain.verify_block(headers[0].clone().into());
chain.verify_block(headers[1].clone().into());
assert!(chain.information().scheduled == 3 && chain.information().requested == 1
&& chain.information().verifying == 2 && chain.information().stored == 1);
assert_eq!(chain.forget_block_with_state(&hashes[0], BlockState::Verifying), HashPosition::Front);
assert!(chain.information().scheduled == 3 && chain.information().requested == 1
&& chain.information().verifying == 1 && chain.information().stored == 1);
chain.insert_best_block(test_data::block_h1().into()).expect("Db error");
assert!(chain.information().scheduled == 3 && chain.information().requested == 1
&& chain.information().verifying == 1 && chain.information().stored == 2);
assert_eq!(db.best_block().number, 1);
}
#[test]
fn chain_block_locator_hashes() {
let db = Arc::new(BlockChainDatabase::init_test_chain(vec![test_data::genesis().into()]));
let mut chain = Chain::new(db, ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore), Arc::new(RwLock::new(MemoryPool::new())));
let genesis_hash = chain.best_block().hash;
assert_eq!(chain.block_locator_hashes(), vec![genesis_hash.clone()]);
let block1 = test_data::block_h1();
let block1_hash = block1.hash();
chain.insert_best_block(block1.into()).expect("Error inserting new block");
assert_eq!(chain.block_locator_hashes(), vec![block1_hash.clone(), genesis_hash.clone()]);
let block2 = test_data::block_h2();
let block2_hash = block2.hash();
chain.insert_best_block(block2.into()).expect("Error inserting new block");
assert_eq!(chain.block_locator_hashes(), vec![block2_hash.clone(), block1_hash.clone(), genesis_hash.clone()]);
let blocks0 = test_data::build_n_empty_blocks_from_genesis(11, 0);
let headers0: Vec<IndexedBlockHeader> = blocks0.into_iter().map(|b| b.block_header.into()).collect();
let hashes0: Vec<_> = headers0.iter().map(|h| h.hash.clone()).collect();
chain.schedule_blocks_headers(headers0.clone());
chain.request_blocks_hashes(10);
chain.verify_blocks_hashes(10);
assert_eq!(chain.block_locator_hashes(), vec![
hashes0[10].clone(),
hashes0[9].clone(),
hashes0[8].clone(),
hashes0[7].clone(),
hashes0[6].clone(),
hashes0[5].clone(),
hashes0[4].clone(),
hashes0[3].clone(),
hashes0[2].clone(),
hashes0[1].clone(),
block2_hash.clone(),
genesis_hash.clone(),
]);
let blocks1 = test_data::build_n_empty_blocks_from(6, 0, &headers0[10].raw);
let headers1: Vec<IndexedBlockHeader> = blocks1.into_iter().map(|b| b.block_header.into()).collect();
let hashes1: Vec<_> = headers1.iter().map(|h| h.hash.clone()).collect();
chain.schedule_blocks_headers(headers1.clone());
chain.request_blocks_hashes(10);
assert_eq!(chain.block_locator_hashes(), vec![
hashes1[5].clone(),
hashes1[4].clone(),
hashes1[3].clone(),
hashes1[2].clone(),
hashes1[1].clone(),
hashes1[0].clone(),
hashes0[10].clone(),
hashes0[9].clone(),
hashes0[8].clone(),
hashes0[7].clone(),
hashes0[5].clone(),
hashes0[1].clone(),
genesis_hash.clone(),
]);
let blocks2 = test_data::build_n_empty_blocks_from(3, 0, &headers1[5].raw);
let headers2: Vec<IndexedBlockHeader> = blocks2.into_iter().map(|b| b.block_header.into()).collect();
let hashes2: Vec<_> = headers2.iter().map(|h| h.hash.clone()).collect();
chain.schedule_blocks_headers(headers2);
assert_eq!(chain.block_locator_hashes(), vec![
hashes2[2].clone(),
hashes2[1].clone(),
hashes2[0].clone(),
hashes1[5].clone(),
hashes1[4].clone(),
hashes1[3].clone(),
hashes1[2].clone(),
hashes1[1].clone(),
hashes1[0].clone(),
hashes0[10].clone(),
hashes0[8].clone(),
hashes0[4].clone(),
genesis_hash.clone(),
]);
}
#[test]
fn chain_transaction_state() {
let db = Arc::new(BlockChainDatabase::init_test_chain(vec![test_data::genesis().into()]));
let mut chain = Chain::new(db, ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore), Arc::new(RwLock::new(MemoryPool::new())));
let genesis_block = test_data::genesis();
let block1 = test_data::block_h1();
let tx1: Transaction = test_data::TransactionBuilder::with_version(1).into();
let tx2: Transaction = test_data::TransactionBuilder::with_version(2).into();
let tx1_hash = tx1.hash();
let tx2_hash = tx2.hash();
chain.verify_transaction(tx1.into());
chain.insert_verified_transaction(tx2.into());
assert_eq!(chain.transaction_state(&genesis_block.transactions[0].hash()), TransactionState::Stored);
assert_eq!(chain.transaction_state(&block1.transactions[0].hash()), TransactionState::Unknown);
assert_eq!(chain.transaction_state(&tx1_hash), TransactionState::Verifying);
assert_eq!(chain.transaction_state(&tx2_hash), TransactionState::InMemory);
}
#[test]
fn chain_block_transaction_is_removed_from_on_block_insert() {
let b0 = test_data::block_builder().header().build()
.transaction().coinbase()
.output().value(10).build()
.build()
.build();
let b1 = test_data::block_builder().header().parent(b0.hash()).build()
.transaction().coinbase()
.output().value(10).build()
.build()
.transaction()
.input().hash(b0.transactions[0].hash()).index(0).build()
.build()
.build();
let tx1 = b1.transactions[0].clone();
let tx1_hash = tx1.hash();
let tx2 = b1.transactions[1].clone();
let tx2_hash = tx2.hash();
let db = Arc::new(BlockChainDatabase::init_test_chain(vec![b0.into()]));
let mut chain = Chain::new(db, ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore), Arc::new(RwLock::new(MemoryPool::new())));
chain.verify_transaction(tx1.into());
chain.insert_verified_transaction(tx2.into());
assert_eq!(chain.information().transactions.transactions_count, 1);
chain.insert_best_block(b1.into()).expect("block accepted");
assert_eq!(chain.information().transactions.transactions_count, 0);
assert!(!chain.forget_verifying_transaction(&tx1_hash));
assert!(!chain.forget_verifying_transaction(&tx2_hash));
}
#[test]
fn chain_forget_verifying_transaction_with_children() {
let test_chain = &mut test_data::ChainBuilder::new();
test_data::TransactionBuilder::with_output(100).store(test_chain)
.into_input(0).add_output(200).store(test_chain)
.into_input(0).add_output(300).store(test_chain)
.set_default_input(0).set_output(400).store(test_chain);
let db = Arc::new(BlockChainDatabase::init_test_chain(vec![test_data::genesis().into()]));
let mut chain = Chain::new(db, ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore), Arc::new(RwLock::new(MemoryPool::new())));
chain.verify_transaction(test_chain.at(0).into());
chain.verify_transaction(test_chain.at(1).into());
chain.verify_transaction(test_chain.at(2).into());
chain.verify_transaction(test_chain.at(3).into());
chain.forget_verifying_transaction_with_children(&test_chain.at(0).hash());
assert!(!chain.forget_verifying_transaction(&test_chain.at(0).hash()));
assert!(!chain.forget_verifying_transaction(&test_chain.at(1).hash()));
assert!(!chain.forget_verifying_transaction(&test_chain.at(2).hash()));
assert!(chain.forget_verifying_transaction(&test_chain.at(3).hash()));
}
#[test]
fn chain_transactions_hashes_with_state() {
let test_chain = &mut test_data::ChainBuilder::new();
test_data::TransactionBuilder::with_output(100).store(test_chain)
.into_input(0).add_output(200).store(test_chain)
.into_input(0).add_output(300).store(test_chain)
.set_default_input(0).set_output(400).store(test_chain);
let db = Arc::new(BlockChainDatabase::init_test_chain(vec![test_data::genesis().into()]));
let mut chain = Chain::new(db, ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore), Arc::new(RwLock::new(MemoryPool::new())));
chain.insert_verified_transaction(test_chain.at(0).into());
chain.insert_verified_transaction(test_chain.at(1).into());
chain.insert_verified_transaction(test_chain.at(2).into());
chain.insert_verified_transaction(test_chain.at(3).into());
let chain_transactions = chain.transactions_hashes_with_state(TransactionState::InMemory);
assert!(chain_transactions.contains(&test_chain.at(0).hash()));
assert!(chain_transactions.contains(&test_chain.at(1).hash()));
assert!(chain_transactions.contains(&test_chain.at(2).hash()));
assert!(chain_transactions.contains(&test_chain.at(3).hash()));
}
#[test]
fn memory_pool_transactions_are_reverified_after_reorganization() {
let b0 = test_data::block_builder().header().build().build();
let b1 = test_data::block_builder().header().nonce(1).parent(b0.hash()).build().build();
let b2 = test_data::block_builder().header().nonce(2).parent(b0.hash()).build().build();
let b3 = test_data::block_builder().header().parent(b2.hash()).build().build();
let tx1: Transaction = test_data::TransactionBuilder::with_version(1).into();
let tx1_hash = tx1.hash();
let tx2: Transaction = test_data::TransactionBuilder::with_version(2).into();
let tx2_hash = tx2.hash();
let db = Arc::new(BlockChainDatabase::init_test_chain(vec![b0.into()]));
let mut chain = Chain::new(db, ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore), Arc::new(RwLock::new(MemoryPool::new())));
chain.verify_transaction(tx1.into());
chain.insert_verified_transaction(tx2.into());
let result = chain.insert_best_block(b1.into()).expect("no error");
assert_eq!(result.transactions_to_reverify.len(), 0);
let result = chain.insert_best_block(b2.into()).expect("no error");
assert_eq!(result.transactions_to_reverify.len(), 0);
let result = chain.insert_best_block(b3.into()).expect("no error");
assert_eq!(result.transactions_to_reverify.len(), 2);
assert!(result.transactions_to_reverify.iter().any(|ref tx| &tx.hash == &tx1_hash));
assert!(result.transactions_to_reverify.iter().any(|ref tx| &tx.hash == &tx2_hash));
}
#[test]
fn fork_chain_block_transaction_is_removed_from_on_block_insert() {
let genesis = test_data::genesis();
let b0 = test_data::block_builder().header().parent(genesis.hash()).build().build();
let b1 = test_data::block_builder().header().nonce(1).parent(b0.hash()).build()
.transaction().output().value(10).build().build()
.build();
let b2 = test_data::block_builder().header().parent(b1.hash()).build()
.transaction().output().value(20).build().build()
.build();
let b3 = test_data::block_builder().header().nonce(2).parent(b0.hash()).build()
.transaction().output().value(30).build().build()
.build();
let b4 = test_data::block_builder().header().parent(b3.hash()).build()
.transaction().output().value(40).build().build()
.build();
let b5 = test_data::block_builder().header().parent(b4.hash()).build()
.transaction().output().value(50).build().build()
.build();
let tx1 = b1.transactions[0].clone();
let tx1_hash = tx1.hash();
let tx2 = b2.transactions[0].clone();
let tx2_hash = tx2.hash();
let tx3 = b3.transactions[0].clone();
let tx4 = b4.transactions[0].clone();
let tx5 = b5.transactions[0].clone();
let db = Arc::new(BlockChainDatabase::init_test_chain(vec![genesis.into()]));
let mut chain = Chain::new(db, ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore), Arc::new(RwLock::new(MemoryPool::new())));
chain.insert_verified_transaction(tx3.into());
chain.insert_verified_transaction(tx4.into());
chain.insert_verified_transaction(tx5.into());
assert_eq!(chain.insert_best_block(b0.clone().into()).expect("block accepted"), BlockInsertionResult::with_canonized_blocks(vec![b0.hash()]));
assert_eq!(chain.information().transactions.transactions_count, 3);
assert_eq!(chain.insert_best_block(b1.clone().into()).expect("block accepted"), BlockInsertionResult::with_canonized_blocks(vec![b1.hash()]));
assert_eq!(chain.information().transactions.transactions_count, 3);
assert_eq!(chain.insert_best_block(b2.clone().into()).expect("block accepted"), BlockInsertionResult::with_canonized_blocks(vec![b2.hash()]));
assert_eq!(chain.information().transactions.transactions_count, 3);
assert_eq!(chain.insert_best_block(b3.clone().into()).expect("block accepted"), BlockInsertionResult::default());
assert_eq!(chain.information().transactions.transactions_count, 3);
assert_eq!(chain.insert_best_block(b4.clone().into()).expect("block accepted"), BlockInsertionResult::default());
assert_eq!(chain.information().transactions.transactions_count, 3);
let insert_result = chain.insert_best_block(b5.clone().into()).expect("block accepted");
let transactions_to_reverify_hashes: Vec<_> = insert_result
.transactions_to_reverify
.into_iter()
.map(|tx| tx.hash)
.collect();
assert_eq!(transactions_to_reverify_hashes, vec![tx1_hash, tx2_hash]);
assert_eq!(insert_result.canonized_blocks_hashes, vec![b3.hash(), b4.hash(), b5.hash()]);
assert_eq!(chain.information().transactions.transactions_count, 0);
}
#[test]
fn double_spend_transaction_is_removed_from_memory_pool_when_output_is_spent_in_block_transaction() {
let genesis = test_data::genesis();
let tx0 = genesis.transactions[0].clone();
let b0 = test_data::block_builder().header().nonce(1).parent(genesis.hash()).build()
.transaction()
.lock_time(1)
.input().hash(tx0.hash()).index(0).build()
.build()
.build();
let tx2: Transaction = test_data::TransactionBuilder::with_output(20).add_input(&tx0, 0).into();
let tx3: Transaction = test_data::TransactionBuilder::with_output(20).add_input(&tx0, 1).into();
let db = Arc::new(BlockChainDatabase::init_test_chain(vec![test_data::genesis().into()]));
let mut chain = Chain::new(db, ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore), Arc::new(RwLock::new(MemoryPool::new())));
chain.insert_verified_transaction(tx2.clone().into());
chain.insert_verified_transaction(tx3.clone().into());
chain.insert_best_block(b0.into()).expect("no error");
assert_eq!(chain.information().transactions.transactions_count, 1);
}
#[test]
fn update_memory_pool_transaction() {
use self::test_data::{ChainBuilder, TransactionBuilder};
let data_chain = &mut ChainBuilder::new();
TransactionBuilder::with_output(10).add_output(10).add_output(10).store(data_chain)
.reset().set_input(&data_chain.at(0), 0).add_output(20).lock().store(data_chain)
.reset().set_input(&data_chain.at(0), 0).add_output(30).store(data_chain);
let db = Arc::new(BlockChainDatabase::init_test_chain(vec![test_data::genesis().into()]));
let mut chain = Chain::new(db, ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore), Arc::new(RwLock::new(MemoryPool::new())));
chain.insert_verified_transaction(data_chain.at(1).into());
assert_eq!(chain.information().transactions.transactions_count, 1);
chain.insert_verified_transaction(data_chain.at(2).into());
assert_eq!(chain.information().transactions.transactions_count, 1);
}
}