-
Notifications
You must be signed in to change notification settings - Fork 712
/
Copy pathblock_graph.rs
4288 lines (3988 loc) · 175 KB
/
block_graph.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) 2021 MASSA LABS <[email protected]>
//! All information concerning blocks, the block graph and cliques is managed here.
use super::settings::ConsensusConfig;
use crate::error::ConsensusError;
use crate::{
ledger::{Ledger, LedgerChanges, LedgerSubset, OperationLedgerInterface},
pos::{OperationRollInterface, ProofOfStake, RollCounts, RollUpdate, RollUpdates},
};
use massa_hash::hash::Hash;
use massa_models::api::EndorsementInfo;
use massa_models::clique::Clique;
use massa_models::ledger::LedgerChange;
use massa_models::prehash::{BuildMap, Map, Set};
use massa_models::{
array_from_slice, u8_from_slice, with_serialization_context, Address, Block, BlockHeader,
BlockHeaderContent, BlockId, DeserializeCompact, DeserializeVarInt, Endorsement, EndorsementId,
ModelsError, Operation, OperationId, OperationSearchResult, OperationSearchResultBlockStatus,
OperationSearchResultStatus, SerializeCompact, SerializeVarInt, Slot, ADDRESS_SIZE_BYTES,
BLOCK_ID_SIZE_BYTES,
};
use massa_signature::{derive_public_key, PublicKey};
use serde::{Deserialize, Serialize};
use std::mem;
use std::{collections::HashSet, convert::TryInto, usize};
use std::{
collections::{hash_map, BTreeSet, VecDeque},
convert::TryFrom,
};
use tracing::{debug, error, info, warn};
#[derive(Debug, Clone)]
enum HeaderOrBlock {
Header(BlockHeader),
Block(
Block,
Map<OperationId, (usize, u64)>,
Map<EndorsementId, u32>,
),
}
impl HeaderOrBlock {
/// Gets slot for that header or block
pub fn get_slot(&self) -> Slot {
match self {
HeaderOrBlock::Header(header) => header.content.slot,
HeaderOrBlock::Block(block, ..) => block.header.content.slot,
}
}
}
/// Aggregated changes made during a block's execution
#[derive(Debug, Clone)]
pub struct BlockStateAccumulator {
/// Addresses impacted by ledger updates
pub loaded_ledger_addrs: Set<Address>,
/// Subset of the ledger. Contains only data in the thread of the given block
pub ledger_thread_subset: LedgerSubset,
/// Cumulative changes made during that block execution
pub ledger_changes: LedgerChanges,
/// Addresses impacted by roll updates
pub loaded_roll_addrs: Set<Address>,
/// Current roll counts for these addresses
pub roll_counts: RollCounts,
/// Roll updates that happened during that block execution
pub roll_updates: RollUpdates,
/// Roll updates that happened during current cycle
pub cycle_roll_updates: RollUpdates,
/// Cycle of the parent in the same thread
pub same_thread_parent_cycle: u64,
/// Address of the parent in the same thread
pub same_thread_parent_creator: Address,
/// Addresses of that block endorsers
pub endorsers_addresses: Vec<Address>,
}
/// Block that was checked as final, with some useful precomputed data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActiveBlock {
/// The creator's address
pub creator_address: Address,
/// The block itself, as it was created
pub block: Block,
/// one (block id, period) per thread ( if not genesis )
pub parents: Vec<(BlockId, u64)>,
/// one HashMap<Block id, period> per thread (blocks that need to be kept)
/// Children reference that block as a parent
pub children: Vec<Map<BlockId, u64>>,
/// dependencies required for validity check
pub dependencies: Set<BlockId>,
/// Blocks id that have this block as an ancestor
pub descendants: Set<BlockId>,
/// ie has its fitness reached the given threshold
pub is_final: bool,
/// Changes caused by this block
pub block_ledger_changes: LedgerChanges,
/// index in the block, end of validity period
pub operation_set: Map<OperationId, (usize, u64)>,
/// IDs of the endorsements to index in block
pub endorsement_ids: Map<EndorsementId, u32>,
/// Maps addresses to operations id they are involved in
pub addresses_to_operations: Map<Address, Set<OperationId>>,
/// Maps addresses to endorsements id they are involved in
pub addresses_to_endorsements: Map<Address, Set<EndorsementId>>,
/// Address -> RollUpdate
pub roll_updates: RollUpdates,
/// list of (period, address, did_create) for all block/endorsement creation events
pub production_events: Vec<(u64, Address, bool)>,
}
impl ActiveBlock {
/// Computes the fitness of the block
fn fitness(&self) -> u64 {
1 + self.block.header.content.endorsements.len() as u64
}
}
/// Exportable version of ActiveBlock
/// Fields that can be easily recomputed were left out
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportActiveBlock {
/// The block itself, as it was created
pub block: Block,
/// one (block id, period) per thread ( if not genesis )
pub parents: Vec<(BlockId, u64)>,
/// one HashMap<Block id, period> per thread (blocks that need to be kept)
/// Children reference that block as a parent
pub children: Vec<Map<BlockId, u64>>,
/// dependencies required for validity check
pub dependencies: Set<BlockId>,
/// ie has its fitness reached the given threshold
pub is_final: bool,
/// Changes caused by this block
pub block_ledger_changes: LedgerChanges,
/// Address -> RollUpdate
pub roll_updates: RollUpdates,
/// list of (period, address, did_create) for all block/endorsement creation events
pub production_events: Vec<(u64, Address, bool)>,
}
impl From<&ActiveBlock> for ExportActiveBlock {
fn from(a_block: &ActiveBlock) -> Self {
ExportActiveBlock {
block: a_block.block.clone(),
parents: a_block.parents.clone(),
children: a_block.children.clone(),
dependencies: a_block.dependencies.clone(),
is_final: a_block.is_final,
block_ledger_changes: a_block.block_ledger_changes.clone(),
roll_updates: a_block.roll_updates.clone(),
production_events: a_block.production_events.clone(),
}
}
}
impl TryFrom<ExportActiveBlock> for ActiveBlock {
fn try_from(a_block: ExportActiveBlock) -> Result<ActiveBlock, ConsensusError> {
let operation_set = a_block
.block
.operations
.iter()
.enumerate()
.map(|(idx, op)| match op.get_operation_id() {
Ok(id) => Ok((id, (idx, op.content.expire_period))),
Err(e) => Err(e),
})
.collect::<Result<_, _>>()?;
let endorsement_ids = a_block
.block
.header
.content
.endorsements
.iter()
.map(|endo| Ok((endo.compute_endorsement_id()?, endo.content.index)))
.collect::<Result<_, ConsensusError>>()?;
let addresses_to_operations = a_block.block.involved_addresses(&operation_set)?;
let addresses_to_endorsements =
a_block.block.addresses_to_endorsements(&endorsement_ids)?;
Ok(ActiveBlock {
creator_address: Address::from_public_key(&a_block.block.header.content.creator),
block: a_block.block,
parents: a_block.parents,
children: a_block.children,
dependencies: a_block.dependencies,
descendants: Default::default(), // will be computed once the full graph is available
is_final: a_block.is_final,
block_ledger_changes: a_block.block_ledger_changes,
operation_set,
endorsement_ids,
addresses_to_operations,
roll_updates: a_block.roll_updates,
production_events: a_block.production_events,
addresses_to_endorsements,
})
}
type Error = ConsensusError;
}
impl SerializeCompact for ExportActiveBlock {
fn to_bytes_compact(&self) -> Result<Vec<u8>, massa_models::ModelsError> {
let mut res: Vec<u8> = Vec::new();
// is_final
if self.is_final {
res.push(1);
} else {
res.push(0);
}
// block
res.extend(self.block.to_bytes_compact()?);
// parents (note: there should be none if slot period=0)
if self.parents.is_empty() {
res.push(0);
} else {
res.push(1);
}
for (hash, period) in self.parents.iter() {
res.extend(&hash.to_bytes());
res.extend(period.to_varint_bytes());
}
// children
let children_count: u32 = self.children.len().try_into().map_err(|err| {
ModelsError::SerializeError(format!("too many children in ActiveBlock: {}", err))
})?;
res.extend(children_count.to_varint_bytes());
for map in self.children.iter() {
let map_count: u32 = map.len().try_into().map_err(|err| {
ModelsError::SerializeError(format!(
"too many entry in children map in ActiveBlock: {}",
err
))
})?;
res.extend(map_count.to_varint_bytes());
for (hash, period) in map {
res.extend(&hash.to_bytes());
res.extend(period.to_varint_bytes());
}
}
// dependencies
let dependencies_count: u32 = self.dependencies.len().try_into().map_err(|err| {
ModelsError::SerializeError(format!("too many dependencies in ActiveBlock: {}", err))
})?;
res.extend(dependencies_count.to_varint_bytes());
for dep in self.dependencies.iter() {
res.extend(&dep.to_bytes());
}
// block_ledger_change
let block_ledger_change_count: u32 =
self.block_ledger_changes
.0
.len()
.try_into()
.map_err(|err| {
ModelsError::SerializeError(format!(
"too many block_ledger_change in ActiveBlock: {}",
err
))
})?;
res.extend(block_ledger_change_count.to_varint_bytes());
for (addr, change) in self.block_ledger_changes.0.iter() {
res.extend(&addr.to_bytes());
res.extend(change.to_bytes_compact()?);
}
// roll updates
let roll_updates_count: u32 = self.roll_updates.0.len().try_into().map_err(|err| {
ModelsError::SerializeError(format!("too many roll updates in ActiveBlock: {}", err))
})?;
res.extend(roll_updates_count.to_varint_bytes());
for (addr, roll_update) in self.roll_updates.0.iter() {
res.extend(addr.to_bytes());
res.extend(roll_update.to_bytes_compact()?);
}
// creation events
let production_events_count: u32 =
self.production_events.len().try_into().map_err(|err| {
ModelsError::SerializeError(format!(
"too many creation events in ActiveBlock: {}",
err
))
})?;
res.extend(production_events_count.to_varint_bytes());
for (period, addr, has_created) in self.production_events.iter() {
res.extend(period.to_varint_bytes());
res.extend(addr.to_bytes());
res.push(if *has_created { 1u8 } else { 0u8 });
}
Ok(res)
}
}
impl DeserializeCompact for ExportActiveBlock {
fn from_bytes_compact(buffer: &[u8]) -> Result<(Self, usize), massa_models::ModelsError> {
let mut cursor = 0usize;
let (parent_count, max_bootstrap_children, max_bootstrap_deps, max_bootstrap_pos_entries) =
with_serialization_context(|context| {
(
context.parent_count,
context.max_bootstrap_children,
context.max_bootstrap_deps,
context.max_bootstrap_pos_entries,
)
});
// is_final
let is_final_u8 = u8_from_slice(buffer)?;
cursor += 1;
let is_final = is_final_u8 != 0;
// block
let (block, delta) = Block::from_bytes_compact(&buffer[cursor..])?;
cursor += delta;
// parents
let has_parents = u8_from_slice(&buffer[cursor..])?;
cursor += 1;
let parents = if has_parents == 1 {
let mut parents: Vec<(BlockId, u64)> = Vec::with_capacity(parent_count as usize);
for _ in 0..parent_count {
let parent_h = BlockId::from_bytes(&array_from_slice(&buffer[cursor..])?)?;
cursor += BLOCK_ID_SIZE_BYTES;
let (period, delta) = u64::from_varint_bytes(&buffer[cursor..])?;
cursor += delta;
parents.push((parent_h, period));
}
parents
} else if has_parents == 0 {
Vec::new()
} else {
return Err(ModelsError::SerializeError(
"ActiveBlock from_bytes_compact bad has parents flags.".into(),
));
};
// children
let (children_count, delta) = u32::from_varint_bytes(&buffer[cursor..])?;
let parent_count_u32: u32 = parent_count.into();
if children_count > parent_count_u32 {
return Err(ModelsError::DeserializeError(
"too many threads with children to deserialize".to_string(),
));
}
cursor += delta;
let mut children: Vec<Map<BlockId, u64>> = Vec::with_capacity(children_count as usize);
for _ in 0..(children_count as usize) {
let (map_count, delta) = u32::from_varint_bytes(&buffer[cursor..])?;
if map_count > max_bootstrap_children {
return Err(ModelsError::DeserializeError(
"too many children to deserialize".to_string(),
));
}
cursor += delta;
let mut map: Map<BlockId, u64> =
Map::with_capacity_and_hasher(map_count as usize, BuildMap::default());
for _ in 0..(map_count as usize) {
let hash = BlockId::from_bytes(&array_from_slice(&buffer[cursor..])?)?;
cursor += BLOCK_ID_SIZE_BYTES;
let (period, delta) = u64::from_varint_bytes(&buffer[cursor..])?;
cursor += delta;
map.insert(hash, period);
}
children.push(map);
}
// dependencies
let (dependencies_count, delta) = u32::from_varint_bytes(&buffer[cursor..])?;
if dependencies_count > max_bootstrap_deps {
return Err(ModelsError::DeserializeError(
"too many dependencies to deserialize".to_string(),
));
}
cursor += delta;
let mut dependencies = Set::<BlockId>::with_capacity_and_hasher(
dependencies_count as usize,
BuildMap::default(),
);
for _ in 0..(dependencies_count as usize) {
let dep = BlockId::from_bytes(&array_from_slice(&buffer[cursor..])?)?;
cursor += BLOCK_ID_SIZE_BYTES;
dependencies.insert(dep);
}
// block_ledger_changes
let (block_ledger_change_count, delta) = u32::from_varint_bytes(&buffer[cursor..])?;
// TODO: count check ... see #1200
cursor += delta;
let mut block_ledger_changes = LedgerChanges(Map::with_capacity_and_hasher(
block_ledger_change_count as usize,
BuildMap::default(),
));
for _ in 0..block_ledger_change_count {
let address = Address::from_bytes(&array_from_slice(&buffer[cursor..])?)?;
cursor += ADDRESS_SIZE_BYTES;
let (change, delta) = LedgerChange::from_bytes_compact(&buffer[cursor..])?;
cursor += delta;
block_ledger_changes.0.insert(address, change);
}
// roll_updates
let (roll_updates_count, delta) = u32::from_varint_bytes(&buffer[cursor..])?;
if roll_updates_count > max_bootstrap_pos_entries {
return Err(ModelsError::DeserializeError(
"too many roll updates to deserialize".to_string(),
));
}
cursor += delta;
let mut roll_updates = RollUpdates(Map::with_capacity_and_hasher(
roll_updates_count as usize,
BuildMap::default(),
));
for _ in 0..roll_updates_count {
let address = Address::from_bytes(&array_from_slice(&buffer[cursor..])?)?;
cursor += ADDRESS_SIZE_BYTES;
let (roll_update, delta) = RollUpdate::from_bytes_compact(&buffer[cursor..])?;
cursor += delta;
roll_updates.0.insert(address, roll_update);
}
// production_events
let (production_events_count, delta) = u32::from_varint_bytes(&buffer[cursor..])?;
// TODO: count check ... see #1200
cursor += delta;
let mut production_events: Vec<(u64, Address, bool)> =
Vec::with_capacity(production_events_count as usize);
for _ in 0..production_events_count {
let (period, delta) = u64::from_varint_bytes(&buffer[cursor..])?;
cursor += delta;
let address = Address::from_bytes(&array_from_slice(&buffer[cursor..])?)?;
cursor += ADDRESS_SIZE_BYTES;
let has_created = match u8_from_slice(&buffer[cursor..])? {
0u8 => false,
1u8 => true,
_ => {
return Err(ModelsError::SerializeError(
"could not deserialize active_block.production_events.has_created".into(),
))
}
};
cursor += 1;
production_events.push((period, address, has_created));
}
Ok((
ExportActiveBlock {
is_final,
block,
parents,
children,
dependencies,
block_ledger_changes,
roll_updates,
production_events,
},
cursor,
))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum DiscardReason {
/// Block is invalid, either structurally, or because of some incompatibility. The String contains the reason for info or debugging.
Invalid(String),
/// Block is incompatible with a final block.
Stale,
/// Block has enough fitness.
Final,
}
/// Enum used in blockgraph's state machine
#[derive(Debug, Clone)]
enum BlockStatus {
/// The block/header has reached consensus but no consensus-level check has been performed.
/// It will be processed during the next iteration
Incoming(HeaderOrBlock),
/// The block/header's slot is too much in the future.
/// It will be processed at the block/header slot
WaitingForSlot(HeaderOrBlock),
/// The block references an unknown Block id
WaitingForDependencies {
/// Given header/block
header_or_block: HeaderOrBlock,
/// includes self if it's only a header
unsatisfied_dependencies: Set<BlockId>,
/// Used to limit and sort the number of blocks/headers wainting for dependencies
sequence_number: u64,
},
/// The block was checked and incluced in the blockgraph
Active(Box<ActiveBlock>),
/// The block was discarded and is kept to avoid reprocessing it
Discarded {
/// Just the header of that block
header: BlockHeader,
/// why it was discarded
reason: DiscardReason,
/// Used to limit and sort the number of blocks/headers wainting for dependencies
sequence_number: u64,
},
}
/// Block status in the graph that can be exported.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ExportBlockStatus {
Incoming,
WaitingForSlot,
WaitingForDependencies,
Active(Block),
Final(Block),
Discarded(DiscardReason),
}
impl<'a> From<&'a BlockStatus> for ExportBlockStatus {
fn from(block: &BlockStatus) -> Self {
match block {
BlockStatus::Incoming(_) => ExportBlockStatus::Incoming,
BlockStatus::WaitingForSlot(_) => ExportBlockStatus::WaitingForSlot,
BlockStatus::WaitingForDependencies { .. } => ExportBlockStatus::WaitingForDependencies,
BlockStatus::Active(active_block) => {
if active_block.is_final {
ExportBlockStatus::Final(active_block.block.clone())
} else {
ExportBlockStatus::Active(active_block.block.clone())
}
}
BlockStatus::Discarded { reason, .. } => ExportBlockStatus::Discarded(reason.clone()),
}
}
}
/// The block version that can be exported.
/// Note that the detailed list of operation is not exported
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportCompiledBlock {
/// Header of the corresponding block.
pub header: BlockHeader,
/// For (i, set) in children,
/// set contains the headers' hashes
/// of blocks referencing exported block as a parent,
/// in thread i.
pub children: Vec<Set<BlockId>>,
/// Active or final
pub is_final: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum Status {
Active,
Final,
}
impl<'a> BlockGraphExport {
/// Conversion from blockgraph.
pub fn extract_from(
block_graph: &'a BlockGraph,
slot_start: Option<Slot>,
slot_end: Option<Slot>,
) -> Self {
let mut export = BlockGraphExport {
genesis_blocks: block_graph.genesis_hashes.clone(),
active_blocks: Map::with_capacity_and_hasher(
block_graph.block_statuses.len(),
BuildMap::default(),
),
discarded_blocks: Map::with_capacity_and_hasher(
block_graph.block_statuses.len(),
BuildMap::default(),
),
best_parents: block_graph.best_parents.clone(),
latest_final_blocks_periods: block_graph.latest_final_blocks_periods.clone(),
gi_head: block_graph.gi_head.clone(),
max_cliques: block_graph.max_cliques.clone(),
};
let filter = |s| {
if let Some(s_start) = slot_start {
if s < s_start {
return false;
}
}
if let Some(s_end) = slot_end {
if s >= s_end {
return false;
}
}
true
};
for (hash, block) in block_graph.block_statuses.iter() {
match block {
BlockStatus::Discarded { header, reason, .. } => {
if filter(header.content.slot) {
export
.discarded_blocks
.insert(*hash, (reason.clone(), header.clone()));
}
}
BlockStatus::Active(a_block) => {
if filter(a_block.block.header.content.slot) {
export.active_blocks.insert(
*hash,
ExportCompiledBlock {
header: a_block.block.header.clone(),
children: a_block
.children
.iter()
.map(|thread| thread.keys().copied().collect::<Set<BlockId>>())
.collect(),
is_final: a_block.is_final,
},
);
}
}
_ => continue,
}
}
export
}
}
#[derive(Debug, Clone)]
pub struct BlockGraphExport {
/// Genesis blocks.
pub genesis_blocks: Vec<BlockId>,
/// Map of active blocks, were blocks are in their exported version.
pub active_blocks: Map<BlockId, ExportCompiledBlock>,
/// Finite cache of discarded blocks, in exported version.
pub discarded_blocks: Map<BlockId, (DiscardReason, BlockHeader)>,
/// Best parents hashe in each thread.
pub best_parents: Vec<(BlockId, u64)>,
/// Latest final period and block hash in each thread.
pub latest_final_blocks_periods: Vec<(BlockId, u64)>,
/// Head of the incompatibility graph.
pub gi_head: Map<BlockId, Set<BlockId>>,
/// List of maximal cliques of compatible blocks.
pub max_cliques: Vec<Clique>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct LedgerDataExport {
/// Candidate data
pub candidate_data: LedgerSubset,
/// Final data
pub final_data: LedgerSubset,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BootstrapableGraph {
/// Map of active blocks, were blocks are in their exported version.
pub active_blocks: Map<BlockId, ExportActiveBlock>,
/// Best parents hashe in each thread.
pub best_parents: Vec<(BlockId, u64)>,
/// Latest final period and block hash in each thread.
pub latest_final_blocks_periods: Vec<(BlockId, u64)>,
/// Head of the incompatibility graph.
pub gi_head: Map<BlockId, Set<BlockId>>,
/// List of maximal cliques of compatible blocks.
pub max_cliques: Vec<Clique>,
/// Ledger at last final blocks
pub ledger: LedgerSubset,
}
impl SerializeCompact for BootstrapableGraph {
fn to_bytes_compact(&self) -> Result<Vec<u8>, massa_models::ModelsError> {
let mut res: Vec<u8> = Vec::new();
let (max_bootstrap_blocks, max_bootstrap_cliques) = with_serialization_context(|context| {
(context.max_bootstrap_blocks, context.max_bootstrap_cliques)
});
// active_blocks
let blocks_count: u32 = self.active_blocks.len().try_into().map_err(|err| {
ModelsError::SerializeError(format!(
"too many active blocks in BootstrapableGraph: {}",
err
))
})?;
if blocks_count > max_bootstrap_blocks {
return Err(ModelsError::SerializeError(format!("too many blocks in active_blocks for serialization context in BootstrapableGraph: {}", blocks_count)));
}
res.extend(blocks_count.to_varint_bytes());
for (hash, block) in self.active_blocks.iter() {
res.extend(&hash.to_bytes());
res.extend(block.to_bytes_compact()?);
}
// best_parents
for (parent_h, parent_period) in self.best_parents.iter() {
res.extend(&parent_h.to_bytes());
res.extend(&parent_period.to_varint_bytes());
}
// latest_final_blocks_periods
for (hash, period) in self.latest_final_blocks_periods.iter() {
res.extend(&hash.to_bytes());
res.extend(period.to_varint_bytes());
}
// gi_head
let gi_head_count: u32 = self.gi_head.len().try_into().map_err(|err| {
ModelsError::SerializeError(format!("too many gi_head in BootstrapableGraph: {}", err))
})?;
res.extend(gi_head_count.to_varint_bytes());
for (gihash, set) in self.gi_head.iter() {
res.extend(&gihash.to_bytes());
let set_count: u32 = set.len().try_into().map_err(|err| {
ModelsError::SerializeError(format!(
"too many entry in gi_head set in BootstrapableGraph: {}",
err
))
})?;
res.extend(set_count.to_varint_bytes());
for hash in set {
res.extend(&hash.to_bytes());
}
}
// max_cliques
let max_cliques_count: u32 = self.max_cliques.len().try_into().map_err(|err| {
ModelsError::SerializeError(format!(
"too many max_cliques in BootstrapableGraph (format): {}",
err
))
})?;
if max_cliques_count > max_bootstrap_cliques {
return Err(ModelsError::SerializeError(format!(
"too many max_cliques for serialization context in BootstrapableGraph: {}",
max_cliques_count
)));
}
res.extend(max_cliques_count.to_varint_bytes());
for e_clique in self.max_cliques.iter() {
res.extend(e_clique.to_bytes_compact()?);
}
// ledger
res.extend(self.ledger.to_bytes_compact()?);
Ok(res)
}
}
impl DeserializeCompact for BootstrapableGraph {
fn from_bytes_compact(buffer: &[u8]) -> Result<(Self, usize), massa_models::ModelsError> {
let mut cursor = 0usize;
let (max_bootstrap_blocks, parent_count, max_bootstrap_cliques) =
with_serialization_context(|context| {
(
context.max_bootstrap_blocks,
context.parent_count,
context.max_bootstrap_cliques,
)
});
// active_blocks
let (active_blocks_count, delta) = u32::from_varint_bytes(&buffer[cursor..])?;
if active_blocks_count > max_bootstrap_blocks {
return Err(ModelsError::DeserializeError(format!("too many blocks in active_blocks for deserialization context in BootstrapableGraph: {}", active_blocks_count)));
}
cursor += delta;
let mut active_blocks =
Map::with_capacity_and_hasher(active_blocks_count as usize, BuildMap::default());
for _ in 0..(active_blocks_count as usize) {
let hash = BlockId::from_bytes(&array_from_slice(&buffer[cursor..])?)?;
cursor += BLOCK_ID_SIZE_BYTES;
let (block, delta) = ExportActiveBlock::from_bytes_compact(&buffer[cursor..])?;
cursor += delta;
active_blocks.insert(hash, block);
}
// best_parents
let mut best_parents: Vec<(BlockId, u64)> = Vec::with_capacity(parent_count as usize);
for _ in 0..parent_count {
let parent_h = BlockId::from_bytes(&array_from_slice(&buffer[cursor..])?)?;
cursor += BLOCK_ID_SIZE_BYTES;
let (parent_period, delta) = u64::from_varint_bytes(&buffer[cursor..])?;
cursor += delta;
best_parents.push((parent_h, parent_period));
}
// latest_final_blocks_periods
let mut latest_final_blocks_periods: Vec<(BlockId, u64)> =
Vec::with_capacity(parent_count as usize);
for _ in 0..parent_count {
let hash = BlockId::from_bytes(&array_from_slice(&buffer[cursor..])?)?;
cursor += BLOCK_ID_SIZE_BYTES;
let (period, delta) = u64::from_varint_bytes(&buffer[cursor..])?;
cursor += delta;
latest_final_blocks_periods.push((hash, period));
}
// gi_head
let (gi_head_count, delta) = u32::from_varint_bytes(&buffer[cursor..])?;
if gi_head_count > max_bootstrap_blocks {
return Err(ModelsError::DeserializeError(format!(
"too many blocks in gi_head for deserialization context in BootstrapableGraph: {}",
gi_head_count
)));
}
cursor += delta;
let mut gi_head =
Map::with_capacity_and_hasher(gi_head_count as usize, BuildMap::default());
for _ in 0..(gi_head_count as usize) {
let gihash = BlockId::from_bytes(&array_from_slice(&buffer[cursor..])?)?;
cursor += BLOCK_ID_SIZE_BYTES;
let (set_count, delta) = u32::from_varint_bytes(&buffer[cursor..])?;
if set_count > max_bootstrap_blocks {
return Err(ModelsError::DeserializeError(format!("too many blocks in a set in gi_head for deserialization context in BootstrapableGraph: {}", set_count)));
}
cursor += delta;
let mut set =
Set::<BlockId>::with_capacity_and_hasher(set_count as usize, BuildMap::default());
for _ in 0..(set_count as usize) {
let hash = BlockId::from_bytes(&array_from_slice(&buffer[cursor..])?)?;
cursor += BLOCK_ID_SIZE_BYTES;
set.insert(hash);
}
gi_head.insert(gihash, set);
}
// max_cliques
let (max_cliques_count, delta) = u32::from_varint_bytes(&buffer[cursor..])?;
if max_cliques_count > max_bootstrap_cliques {
return Err(ModelsError::DeserializeError(format!(
"too many for deserialization context in BootstrapableGraph: {}",
max_cliques_count
)));
}
cursor += delta;
let mut max_cliques: Vec<Clique> = Vec::with_capacity(max_cliques_count as usize);
for _ in 0..max_cliques_count {
let (c, delta) = Clique::from_bytes_compact(&buffer[cursor..])?;
cursor += delta;
max_cliques.push(c);
}
// ledger
let (ledger, delta) = LedgerSubset::from_bytes_compact(&buffer[cursor..])?;
cursor += delta;
Ok((
BootstrapableGraph {
active_blocks,
best_parents,
latest_final_blocks_periods,
gi_head,
max_cliques,
ledger,
},
cursor,
))
}
}
pub struct BlockGraph {
/// Consensus related config
cfg: ConsensusConfig,
/// Block ids of genesis blocks
genesis_hashes: Vec<BlockId>,
/// Used to limit the number of waiting and discarded blocks
sequence_counter: u64,
/// Every block we know about
block_statuses: Map<BlockId, BlockStatus>,
/// Ids of incomming blocks/headers
incoming_index: Set<BlockId>,
/// ids of waiting for slot blocks/headers
waiting_for_slot_index: Set<BlockId>,
/// ids of waiting for dependencies blocks/headers
waiting_for_dependencies_index: Set<BlockId>,
/// ids of active blocks
active_index: Set<BlockId>,
/// ids of discarded blocks
discarded_index: Set<BlockId>,
/// One (block id, period) per thread
latest_final_blocks_periods: Vec<(BlockId, u64)>,
/// One (block id, period) per thread TODO not sure I understand the difference with latest_final_blocks_periods
best_parents: Vec<(BlockId, u64)>,
/// Incompatibility graph: maps a block id to the block ids it is incompatible with
/// One entry per Active Block
pub(crate) gi_head: Map<BlockId, Set<BlockId>>,
/// All the cliques
max_cliques: Vec<Clique>,
/// Blocks that need to be propagated
to_propagate: Map<BlockId, (Block, Set<OperationId>, Vec<EndorsementId>)>,
/// List of block ids we think are attack attempts
attack_attempts: Vec<BlockId>,
/// Newly final blocks
new_final_blocks: Set<BlockId>,
/// Newly stale block mapped to creator and slot
new_stale_blocks: Map<BlockId, (PublicKey, Slot)>,
/// ledger
ledger: Ledger,
}
/// Possible output of a header check
#[derive(Debug)]
enum HeaderCheckOutcome {
/// it's ok and here are some useful values
Proceed {
/// one (parent block id, parent's period) per thread
parents_hash_period: Vec<(BlockId, u64)>,
/// blocks that header depends on
dependencies: Set<BlockId>,
/// blocks that header is incompatible with
incompatibilities: Set<BlockId>,
/// number of incompatibilities that are inherited from the parents
inherited_incompatibilities_count: usize,
/// list of (period, address, did_create) for all block/endorsement creation events
production_events: Vec<(u64, Address, bool)>,
},
/// there is something wrong with that header
Discard(DiscardReason),
/// it must wait for its slot to be fully processed
WaitForSlot,
/// it must wait for these block ids to be fully processed
WaitForDependencies(Set<BlockId>),
}
/// Possible outcomes of endorsements check
#[derive(Debug)]
enum EndorsementsCheckOutcome {
/// Everything is ok
Proceed,
/// There is something wrong with that endorsement
Discard(DiscardReason),
/// It must wait for its slot to be fully processed
WaitForSlot,
}
/// Possible outcome of block check
#[derive(Debug)]
enum BlockCheckOutcome {
/// Everything is ok
Proceed {
/// one (parent block id, parent's period) per thread
parents_hash_period: Vec<(BlockId, u64)>,
/// blocks that block depends on
dependencies: Set<BlockId>,
/// blocks that block is incompatible with
incompatibilities: Set<BlockId>,
/// number of incompatibilities that are inherited from the parents
inherited_incompatibilities_count: usize,
/// changes caused by that block on the ledger
block_ledger_changes: LedgerChanges,
/// changes caused by that block on rolls
roll_updates: RollUpdates,
/// list of (period, address, did_create) for all block/endorsement creation events
production_events: Vec<(u64, Address, bool)>,
},
/// There is something wrong with that block
Discard(DiscardReason),
/// It must wait for its slot to be fully processed
WaitForSlot,
/// it must wait for these block ids to be fully processed
WaitForDependencies(Set<BlockId>),
}
/// Possible outcome of a block's operations check.
#[derive(Debug)]
enum BlockOperationsCheckOutcome {
/// Everything is ok
Proceed {
/// blocks that block depends on
dependencies: Set<BlockId>,
/// changes caused by that block on the ledger
block_ledger_changes: LedgerChanges,
/// changes caused by that block on rolls
roll_updates: RollUpdates,
},
/// There is something wrong with that batch of operation
Discard(DiscardReason),
/// it must wait for these block ids to be fully processed
WaitForDependencies(Set<BlockId>),
}
/// Read the initial ledger.
async fn read_genesis_ledger(cfg: &ConsensusConfig) -> Result<Ledger, ConsensusError> {
// load ledger from file
let ledger = serde_json::from_str::<LedgerSubset>(
&tokio::fs::read_to_string(&cfg.initial_ledger_path).await?,
)?;
Ledger::new(cfg.clone(), Some(ledger))
}
/// Creates genesis block in given thread.
///
/// # Arguments
/// * cfg: consensus configuration
/// * serialization_context: ref to a SerializationContext instance
/// * thread_number: thread in wich we want a genesis block
pub(crate) fn create_genesis_block(