-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcompute_raft.rs
More file actions
1967 lines (1758 loc) · 72.1 KB
/
Copy pathcompute_raft.rs
File metadata and controls
1967 lines (1758 loc) · 72.1 KB
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
use crate::active_raft::ActiveRaft;
use crate::block_pipeline::{
MiningPipelineInfo, MiningPipelineInfoImport, MiningPipelineItem, MiningPipelinePhaseChange,
MiningPipelineStatus, Participants, PipelineEventInfo,
};
use crate::configurations::{ComputeNodeConfig, UnicornFixedInfo};
use crate::constants::{BLOCK_SIZE_IN_TX, DB_PATH, TX_POOL_LIMIT};
use crate::db_utils::{self, SimpleDb, SimpleDbError, SimpleDbSpec};
use crate::interfaces::{BlockStoredInfo, UtxoSet, WinningPoWInfo};
use crate::raft::{RaftCommit, RaftCommitData, RaftData, RaftMessageWrapper};
use crate::raft_util::{RaftContextKey, RaftInFlightProposals};
use crate::tracked_utxo::TrackedUtxoSet;
use crate::unicorn::{UnicornFixedParam, UnicornInfo};
use crate::utils::{
calculate_reward, create_socket_addr_for_list, get_total_coinbase_tokens,
make_utxo_set_from_seed, BackupCheck, UtxoReAlignCheck,
};
use a_block_chain::crypto::sha3_256;
use a_block_chain::primitives::asset::TokenAmount;
use a_block_chain::primitives::block::Block;
use a_block_chain::primitives::transaction::Transaction;
use a_block_chain::utils::transaction_utils::get_inputs_previous_out_point;
use bincode::{deserialize, serialize};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::fmt;
use std::future::Future;
use std::net::SocketAddr;
use std::time::Duration;
use tokio::time::{self, Instant};
use tracing::{debug, error, trace, warn};
pub const DB_SPEC: SimpleDbSpec = SimpleDbSpec {
db_path: DB_PATH,
suffix: ".compute_raft",
columns: &[],
};
// A coordinated command sent through the RAFT to all peers
#[derive(Default, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Serialize, Deserialize)]
pub enum CoordinatedCommand {
PauseNodes {
b_num: u64,
},
#[default]
ResumeNodes,
ApplySharedConfig,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct MinerWhitelist {
pub active: bool,
pub miner_api_keys: Option<HashSet<String>>,
pub miner_addresses: Option<HashSet<SocketAddr>>,
}
/// Item serialized into RaftData and process by Raft.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[allow(clippy::large_enum_variant)]
pub enum ComputeRaftItem {
FirstBlock(BTreeMap<String, Transaction>),
Block(BlockStoredInfo),
Transactions(BTreeMap<String, Transaction>),
DruidTransactions(Vec<BTreeMap<String, Transaction>>),
PipelineItem(MiningPipelineItem, u64),
CoordinatedCmd(CoordinatedCommand),
}
/// Commited item to process.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum CommittedItem {
FirstBlock,
Block,
BlockShutdown,
StartPhasePowIntake,
StartPhaseHalted,
ResetPipeline,
Transactions,
Snapshot,
CoordinatedCmd(CoordinatedCommand),
}
impl From<MiningPipelinePhaseChange> for CommittedItem {
fn from(other: MiningPipelinePhaseChange) -> Self {
use MiningPipelinePhaseChange::*;
match other {
StartPhasePowIntake => CommittedItem::StartPhasePowIntake,
StartPhaseHalted => CommittedItem::StartPhaseHalted,
Reset => CommittedItem::ResetPipeline,
}
}
}
/// Accumulated previous block info
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum AccumulatingBlockStoredInfo {
/// Accumulating first block utxo_set
FirstBlock(BTreeMap<String, Transaction>),
/// Accumulating other blocks BlockStoredInfo
Block(BlockStoredInfo),
}
/// Accumulated previous block info
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum SpecialHandling {
/// Shutting down on this block.
Shutdown,
/// Waiting for first block after an upgrade.
FirstUpgradeBlock,
}
/// Initial proposal state: Need both miner ready and block info ready
#[allow(clippy::large_enum_variant)]
#[allow(clippy::enum_variant_names)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InitialProposal {
PendingAll,
PendingAuthorized,
PendingItem {
item: ComputeRaftItem,
dedup_b_num: Option<u64>,
},
}
/// All fields that are consensused between the RAFT group.
/// These fields need to be written and read from a committed log event.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ComputeConsensused {
/// Sufficient majority
unanimous_majority: usize,
/// Sufficient majority
sufficient_majority: usize,
/// Number of miners
partition_full_size: usize,
/// Committed transaction pool.
tx_pool: BTreeMap<String, Transaction>,
/// Committed DRUID transactions.
tx_druid_pool: Vec<BTreeMap<String, Transaction>>,
/// Header to use for next block if ready to generate.
tx_current_block_previous_hash: Option<String>,
/// The very first block to consensus.
initial_utxo_txs: Option<BTreeMap<String, Transaction>>,
/// UTXO set containing the valid transaction to use as previous input hashes.
utxo_set: TrackedUtxoSet,
/// Accumulating block:
/// Requires majority of compute node votes for normal blocks.
/// Requires unanimous vote for first block.
current_block_stored_info: BTreeMap<Vec<u8>, (AccumulatingBlockStoredInfo, BTreeSet<u64>)>,
/// Coordinated commands sent through RAFT
/// Requires unanimous vote
current_raft_coordinated_cmd_stored_info: BTreeMap<CoordinatedCommand, BTreeSet<u64>>,
/// The last commited raft index.
last_committed_raft_idx_and_term: (u64, u64),
/// The current circulation of tokens
current_circulation: TokenAmount,
/// The block pipeline
block_pipeline: MiningPipelineInfo,
/// The last mining rewards.
last_mining_transaction_hashes: Vec<String>,
/// Special handling for processing blocks.
special_handling: Option<SpecialHandling>,
/// Whitelisted miner nodes.
miner_whitelist: MinerWhitelist,
}
/// Consensused info to apply on start up after upgrade.
pub struct ComputeConsensusedImport {
pub unanimous_majority: usize,
pub sufficient_majority: usize,
pub partition_full_size: usize,
pub unicorn_fixed_param: UnicornFixedParam,
pub tx_current_block_num: Option<u64>,
pub current_block: Option<Block>,
pub utxo_set: UtxoSet,
pub last_committed_raft_idx_and_term: (u64, u64),
pub current_circulation: TokenAmount,
pub special_handling: Option<SpecialHandling>,
pub miner_whitelist: MinerWhitelist,
}
/// Consensused Compute fields and consensus management.
pub struct ComputeRaft {
/// True if first peer (leader).
first_raft_peer: bool,
/// The raft instance to interact with.
raft_active: ActiveRaft,
/// Consensused fields.
consensused: ComputeConsensused,
/// Whether consensused received initial snapshot
consensused_snapshot_applied: bool,
/// Initial item to propose when ready.
local_initial_proposal: Option<InitialProposal>,
/// Local transaction pool.
local_tx_pool: BTreeMap<String, Transaction>,
/// Local DRUID transaction pool.
local_tx_druid_pool: Vec<BTreeMap<String, Transaction>>,
/// Ordered transaction hashes from the last commit.
local_tx_hash_last_commited: Vec<String>,
/// Min duration between each transaction poposal.
propose_transactions_timeout_duration: Duration,
/// Timeout expiration time for transactimining_pipeline_statusons poposal.
propose_transactions_timeout_at: Instant,
/// Min duration between each event in the mining pipeline.
propose_mining_event_timeout_duration: Duration,
/// Timeout expiration time for mining event poposal.
propose_mining_event_timeout_at: Instant,
/// Proposed items in flight.
proposed_in_flight: RaftInFlightProposals,
/// Proposed transaction in flight length.
proposed_tx_pool_len: usize,
/// Maximum transaction in flight length.
proposed_tx_pool_len_max: usize,
/// Maximum transaction consensused and in flight for proposing more.
proposed_and_consensused_tx_pool_len_max: usize,
/// No longer process commits after shutdown reached
shutdown_no_commit_process: bool,
/// Check for backup needed
backup_check: BackupCheck,
/// Check UTXO set alignment if needed
utxo_re_align_check: UtxoReAlignCheck,
}
impl fmt::Debug for ComputeRaft {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ComputeRaft()")
}
}
impl ComputeRaft {
/// Create a ComputeRaft, need to spawn the raft loop to use raft.
///
/// ### Arguments
///
/// * `config` - Configuration option for a computer node.
/// * `raft_db` - Override raft db to use.
pub async fn new(config: &ComputeNodeConfig, raft_db: Option<SimpleDb>) -> Self {
let use_raft = config.compute_raft != 0;
if config.backup_restore.unwrap_or(false) {
db_utils::restore_file_backup(config.compute_db_mode, &DB_SPEC, None).unwrap();
}
let raw_node_ips = config
.compute_nodes
.clone()
.into_iter()
.map(|v| v.address.clone())
.collect::<Vec<String>>();
let raft_active = ActiveRaft::new(
config.compute_node_idx,
&create_socket_addr_for_list(&raw_node_ips).await.unwrap_or_default(),
use_raft,
Duration::from_millis(config.compute_raft_tick_timeout as u64),
db_utils::new_db(config.compute_db_mode, &DB_SPEC, raft_db, None),
);
let propose_transactions_timeout_duration =
Duration::from_millis(config.compute_transaction_timeout as u64);
let propose_transactions_timeout_at = Instant::now();
let propose_mining_event_timeout_duration =
Duration::from_millis(config.compute_mining_event_timeout as u64);
let propose_mining_event_timeout_at = Instant::now();
let utxo_set =
make_utxo_set_from_seed(&config.compute_seed_utxo, &config.compute_genesis_tx_in);
let first_raft_peer = config.compute_node_idx == 0 || !raft_active.use_raft();
let peers_len = raft_active.peers_len();
let consensused = ComputeConsensused::default()
.with_peers_len(peers_len)
.with_partition_full_size(config.compute_partition_full_size)
.with_unicorn_fixed_param(config.compute_unicorn_fixed_param.clone())
.init_block_pipeline_status();
let local_initial_proposal = Some(InitialProposal::PendingItem {
item: ComputeRaftItem::FirstBlock(utxo_set),
dedup_b_num: None,
});
let backup_check = BackupCheck::new(config.backup_block_modulo);
let utxo_re_align_check = UtxoReAlignCheck::new(config.utxo_re_align_block_modulo);
Self {
first_raft_peer,
raft_active,
consensused,
consensused_snapshot_applied: !use_raft,
local_initial_proposal,
local_tx_pool: Default::default(),
local_tx_druid_pool: Default::default(),
local_tx_hash_last_commited: Default::default(),
propose_transactions_timeout_duration,
propose_transactions_timeout_at,
propose_mining_event_timeout_duration,
propose_mining_event_timeout_at,
proposed_in_flight: Default::default(),
proposed_tx_pool_len: 0,
proposed_tx_pool_len_max: BLOCK_SIZE_IN_TX / peers_len,
proposed_and_consensused_tx_pool_len_max: BLOCK_SIZE_IN_TX * 2,
shutdown_no_commit_process: false,
backup_check,
utxo_re_align_check,
}
}
/// Determine whether the compute node has whitelisting active.
pub fn get_compute_whitelisting_active(&self) -> bool {
self.consensused.miner_whitelist.active
}
/// Return full settings for miner whitelisting
pub fn get_compute_miner_whitelist(&self) -> MinerWhitelist {
self.consensused.miner_whitelist.clone()
}
/// Get the full mining partition size
pub fn get_compute_partition_full_size(&self) -> usize {
self.consensused.partition_full_size
}
/// Get the compute nodes whitelist miner API keys
pub fn get_compute_miner_whitelist_api_keys(&self) -> Option<HashSet<String>> {
self.consensused.miner_whitelist.miner_api_keys.clone()
}
/// Get the compute nodes whitelist miner API keys
pub fn get_compute_miner_whitelist_addresses(&self) -> Option<HashSet<SocketAddr>> {
self.consensused.miner_whitelist.miner_addresses.clone()
}
/// Get the compute mining event timeout in MS
pub fn get_compute_mining_event_timeout(&self) -> usize {
self.propose_mining_event_timeout_duration.as_millis() as usize
}
/// Update the mining event timeout duration
pub fn update_mining_event_timeout_duration(&mut self, ms: usize) {
self.propose_mining_event_timeout_duration = Duration::from_millis(ms as u64);
}
/// Update the partition full size
pub fn update_partition_full_size(&mut self, partition_full_size: usize) {
self.consensused
.update_partition_full_size(partition_full_size);
}
/// Update the miner whitelisting state
pub fn update_compute_miner_whitelist_active(&mut self, active: bool) {
self.consensused.update_miner_whitelist_active(active);
}
/// Update the miner API keys
pub fn update_compute_miner_whitelist_api_keys(
&mut self,
miner_whitelist_api_keys: Option<HashSet<String>>,
) {
self.consensused
.update_miner_whitelist_api_keys(miner_whitelist_api_keys);
}
/// Update the miner API keys
pub fn update_compute_miner_whitelist_addresses(
&mut self,
miner_whitelist_addresses: Option<HashSet<SocketAddr>>,
) {
self.consensused
.update_miner_whitelist_addresses(miner_whitelist_addresses);
}
/// Set the key run for all proposals (load from db before first proposal).
pub fn set_key_run(&mut self, key_run: u64) {
self.proposed_in_flight.set_key_run(key_run)
}
/// Mark the initial proposal as done (first block after start or upgrade).
pub fn set_initial_proposal_done(&mut self) {
self.local_initial_proposal = None;
}
/// All the peers to connect to when using raft.
pub fn raft_peer_to_connect(&self) -> impl Iterator<Item = &SocketAddr> {
self.raft_active.raft_peer_to_connect()
}
/// All the peers expected to be connected when raft is running.
pub fn raft_peer_addrs(&self) -> impl Iterator<Item = &SocketAddr> {
self.raft_active.raft_peer_addrs()
}
/// Blocks & waits for a next event from a peer.
pub fn raft_loop(&self) -> impl Future<Output = ()> {
self.raft_active.raft_loop()
}
/// Signal to the raft loop to complete
pub async fn close_raft_loop(&mut self) {
self.raft_active.close_raft_loop().await
}
/// Extract persistent storage of a closed raft
pub async fn take_closed_persistent_store(&mut self) -> SimpleDb {
self.raft_active.take_closed_persistent_store().await
}
/// Extract persistent storage
pub async fn backup_persistent_store(&self) -> Result<(), SimpleDbError> {
self.raft_active.backup_persistent_store().await
}
/// Check if we are waiting for initial state
pub fn need_initial_state(&self) -> bool {
!self.consensused_snapshot_applied
}
/// Blocks & waits for a next commit from a peer.
pub async fn next_commit(&self) -> Option<RaftCommit> {
self.raft_active.next_commit().await
}
/// Process result from next_commit.
/// Return Some CommittedItem if block to mine is ready to generate. Returns 'not implemented' if not implemented
/// ### Arguments
/// * 'raft_commit' - a RaftCommit struct from the raft.rs class to be proposed to commit.
pub async fn received_commit(&mut self, raft_commit: RaftCommit) -> Option<CommittedItem> {
self.consensused.last_committed_raft_idx_and_term = (raft_commit.index, raft_commit.term);
match raft_commit.data {
RaftCommitData::Proposed(data, context) => {
self.received_commit_proposal(data, context).await
}
RaftCommitData::Snapshot(data) => self.apply_snapshot(data),
RaftCommitData::NewLeader => {
self.proposed_in_flight
.re_propose_all_items(&mut self.raft_active)
.await;
None
}
}
}
/// Apply snapshot
fn apply_snapshot(&mut self, consensused_ser: RaftData) -> Option<CommittedItem> {
self.consensused_snapshot_applied = true;
if consensused_ser.is_empty() {
// Empty initial snapshot
self.set_next_propose_transactions_timeout_at();
self.set_next_propose_mining_event_timeout_at();
None
} else {
// Non empty snapshot
warn!("apply_snapshot called self.consensused updated");
self.consensused = deserialize(&consensused_ser).unwrap();
self.set_ignore_dedeup_b_num_less_than_current();
self.set_next_propose_transactions_timeout_at();
self.set_next_propose_mining_event_timeout_at();
if let Some(proposal) = &mut self.local_initial_proposal {
*proposal = InitialProposal::PendingAll;
}
debug!(
"apply_snapshot called self.consensused updated: tx_current_block_num({:?})",
self.consensused.block_pipeline.current_block_num()
);
Some(CommittedItem::Snapshot)
}
}
/// Process data in RaftData.
/// Return Some CommitedItem if block to mine is ready to generate or none if there is a deserialize error.
///
/// ### Arguments
///
/// * `raft_data` - Data for the commit
/// * `raft_ctx` - Context for the commit
async fn received_commit_proposal(
&mut self,
raft_data: RaftData,
raft_ctx: RaftData,
) -> Option<CommittedItem> {
let (key, item, removed) = self
.proposed_in_flight
.received_commit_proposal(&raft_data, &raft_ctx)
.await?;
if removed {
if let ComputeRaftItem::Transactions(ref txs) = &item {
self.proposed_tx_pool_len -= txs.len();
}
}
trace!("received_commit_proposal {:?} -> {:?}", key, item);
match item {
ComputeRaftItem::FirstBlock(uxto_set) => {
if !self.consensused.is_first_block() {
error!("Proposed FirstBlock after startup {:?}", key);
return None;
}
self.consensused.append_first_block_info(key, uxto_set);
if self.consensused.has_different_block_stored_info() {
error!("Proposed uxtosets are different {:?}", key);
}
if self.consensused.has_block_stored_info_ready() {
// First block complete:
self.consensused.apply_ready_block_stored_info();
self.consensused.generate_first_block().await;
self.consensused.start_items_intake();
self.set_next_propose_mining_event_timeout_at();
self.event_processed_generate_snapshot();
return Some(CommittedItem::FirstBlock);
}
}
ComputeRaftItem::Transactions(mut txs) => {
self.local_tx_hash_last_commited = txs.keys().cloned().collect();
self.consensused.tx_pool.append(&mut txs);
return Some(CommittedItem::Transactions);
}
ComputeRaftItem::DruidTransactions(mut txs) => {
self.consensused.tx_druid_pool.append(&mut txs);
return Some(CommittedItem::Transactions);
}
ComputeRaftItem::Block(info) => {
let b_num = info.block_num;
if !self.consensused.is_current_block(info.block_num) {
trace!("Ignore invalid or outdated block stored info {:?}", key);
return None;
}
self.consensused.append_block_stored_info(key, info);
if self.consensused.has_different_block_stored_info() {
warn!("Proposed previous blocks are different {:?}", key);
}
if self.consensused.has_block_stored_info_ready() {
// New block:
// Must not populate further tx_pool & tx_druid_pool
// before generating block.
self.consensused.apply_ready_block_stored_info();
if self.is_shutdown_on_commit() {
self.event_processed_re_align_utxo_set(b_num);
self.event_processed_generate_snapshot();
return Some(CommittedItem::BlockShutdown);
} else {
self.consensused.generate_block().await;
self.consensused.start_items_intake();
self.set_next_propose_mining_event_timeout_at();
self.event_processed_re_align_utxo_set(b_num);
self.event_processed_generate_snapshot();
return Some(CommittedItem::Block);
}
}
}
ComputeRaftItem::PipelineItem(mining_pipeline_item, b_num) => {
if !self.consensused.is_current_block(b_num) {
trace!("Ignore outdated item {:?}", key);
return None;
}
match self
.consensused
.handle_mining_pipeline_item(mining_pipeline_item, key)
.await
{
Some(v @ MiningPipelinePhaseChange::StartPhasePowIntake)
| Some(v @ MiningPipelinePhaseChange::StartPhaseHalted) => {
self.set_next_propose_mining_event_timeout_at();
return Some(v.into());
}
Some(v @ MiningPipelinePhaseChange::Reset) => {
let proposed_block_pipeline_keys =
self.consensused.block_pipeline.get_proposed_keys();
self.proposed_in_flight
.remove_all_keys(proposed_block_pipeline_keys);
self.consensused.block_pipeline.clear_proposed_keys();
return Some(v.into());
}
None => return None,
}
}
ComputeRaftItem::CoordinatedCmd(cmd) => {
self.consensused
.append_current_coordinated_raft_cmd_stored_info(key, cmd);
if self
.consensused
.has_different_coordinated_raft_cmd_stored_info()
{
warn!("Proposed coordinated commands are different {:?}", key);
}
if self.consensused.has_coordinated_raft_cmd_info_ready() {
let coordinated_command = self.consensused.take_ready_coordinated_raft_cmd();
return Some(CommittedItem::CoordinatedCmd(coordinated_command));
}
}
}
None
}
/// Blocks & waits for a new mining pipeline event.
pub async fn timeout_propose_mining_event(&self) {
time::sleep_until(self.propose_mining_event_timeout_at).await;
}
/// Get the mining pipeline status
pub fn get_mining_pipeline_status(&self) -> &MiningPipelineStatus {
self.consensused.block_pipeline.get_mining_pipeline_status()
}
/// Process block generation in single step (Test only)
pub fn test_skip_block_gen(&mut self, block: Block, block_tx: BTreeMap<String, Transaction>) {
self.consensused.set_committed_mining_block(block, block_tx);
self.consensused.start_items_intake();
}
/// Process all the mining phase in a single step (Test only)
pub fn test_skip_mining(&mut self, winning_pow: (SocketAddr, WinningPoWInfo), seed: Vec<u8>) {
self.consensused
.block_pipeline
.test_skip_mining(winning_pow, seed)
}
/// Blocks & waits for a next message to dispatch from a peer.
/// Message needs to be sent to given peer address.
pub async fn next_msg(&self) -> Option<(SocketAddr, RaftMessageWrapper)> {
self.raft_active.next_msg().await
}
/// Process a raft message: send to spawned raft loop.
/// ### Arguments
/// * `msg` - holds the recieved message in a RaftMessageWrapper.
pub async fn received_message(&mut self, msg: RaftMessageWrapper) {
self.raft_active.received_message(msg).await
}
/// Blocks & waits for a timeout to propose transactions.
pub async fn timeout_propose_transactions(&self) {
time::sleep_until(self.propose_transactions_timeout_at).await;
}
/// Propose initial item
pub async fn propose_initial_item(&mut self) {
self.local_initial_proposal = match self.local_initial_proposal.take() {
Some(InitialProposal::PendingAll) => Some(InitialProposal::PendingAuthorized),
Some(InitialProposal::PendingItem { item, dedup_b_num }) => {
if let Some(b_num) = dedup_b_num {
self.propose_item_dedup(&item, b_num).await.unwrap();
} else {
self.propose_item(&item).await;
}
None
}
Some(InitialProposal::PendingAuthorized) | None => {
panic!("propose_initial_item called again")
}
};
}
/// Process as received block info necessary for new block to be generated.
pub async fn propose_block_with_last_info(&mut self, block: BlockStoredInfo) -> bool {
let b_num = block.block_num;
let item = ComputeRaftItem::Block(block);
match self.local_initial_proposal {
None | Some(InitialProposal::PendingAuthorized) => {
self.local_initial_proposal = None;
self.propose_item_dedup(&item, b_num).await.is_some()
}
Some(InitialProposal::PendingAll) | Some(InitialProposal::PendingItem { .. }) => {
let dedup_b_num = Some(b_num);
let proposal = Some(InitialProposal::PendingItem { item, dedup_b_num });
let old = std::mem::replace(&mut self.local_initial_proposal, proposal);
old != self.local_initial_proposal
}
}
}
///Returns the clock time after the proposed block time out
fn set_next_propose_transactions_timeout_at(&mut self) {
self.propose_transactions_timeout_at =
Instant::now() + self.propose_transactions_timeout_duration
}
///Returns the clock time after the proposed mining time out
fn set_next_propose_mining_event_timeout_at(&mut self) {
self.propose_mining_event_timeout_at =
Instant::now() + self.propose_mining_event_timeout_duration
}
/// Propose a new mining event if relecant
/// Restart timeout, for re-proposal.
pub async fn propose_mining_event_at_timeout(&mut self) -> bool {
self.set_next_propose_mining_event_timeout_at();
if let Some(item) = self.consensused.block_pipeline.mining_event_at_timeout() {
debug!("propose_mining_event_at_timeout: {:?}", item);
self.propose_mining_pipeline_item(item).await
} else {
false
}
}
/// Propose a new mining pipeline item
pub async fn propose_mining_pipeline_item(&mut self, item: MiningPipelineItem) -> bool {
if let Some(block) = self.get_mining_block() {
let b_num = block.header.b_num;
let item = ComputeRaftItem::PipelineItem(item, b_num);
if let Some(key) = self.propose_item_dedup(&item, b_num).await {
self.consensused.block_pipeline.add_proposed_key(key);
return true;
}
false
} else {
false
}
}
/// Clear block pipeline proposed keys
pub fn clear_block_pipeline_proposed_keys(&mut self) {
self.consensused.block_pipeline.clear_proposed_keys();
}
/// Flush disconnected miners from compute node
pub fn flush_stale_miners(&mut self, unsent_miners: &[SocketAddr]) {
self.consensused
.block_pipeline
.cleanup_participant_intake(unsent_miners);
self.consensused
.block_pipeline
.cleanup_participants_mining(unsent_miners);
}
/// Propose to pause nodes
///
/// NOTE: Requires a unanimous majority vote
pub async fn propose_pause_nodes(&mut self, b_num: u64) {
self.propose_item(&ComputeRaftItem::CoordinatedCmd(
CoordinatedCommand::PauseNodes { b_num },
))
.await;
}
/// Propose to resume nodes
///
/// NOTE: Requires a unanimous majority vote
pub async fn propose_resume_nodes(&mut self) {
self.propose_item(&ComputeRaftItem::CoordinatedCmd(
CoordinatedCommand::ResumeNodes,
))
.await;
}
/// Propose to apply a shared config
///
/// NOTE: Requires a unanimous majority vote
pub async fn propose_apply_shared_config(&mut self) {
self.propose_item(&ComputeRaftItem::CoordinatedCmd(
CoordinatedCommand::ApplySharedConfig,
))
.await;
}
/// Process as a result of timeout_propose_transactions.
/// Reset timeout, and propose local transactions if available.
pub async fn propose_local_transactions_at_timeout(&mut self) {
self.set_next_propose_transactions_timeout_at();
let max_add = self
.proposed_and_consensused_tx_pool_len_max
.saturating_sub(self.proposed_and_consensused_tx_pool_len());
let max_propose_len = std::cmp::min(max_add, self.proposed_tx_pool_len_max);
let txs = take_first_n(max_propose_len, &mut self.local_tx_pool);
if !txs.is_empty() {
self.proposed_tx_pool_len += txs.len();
self.propose_item(&ComputeRaftItem::Transactions(txs)).await;
}
}
/// Process as a result of timeout_propose_transactions.
/// Propose druid transactions if available.
pub async fn propose_local_druid_transactions(&mut self) {
let txs = std::mem::take(&mut self.local_tx_druid_pool);
if !txs.is_empty() {
self.propose_item(&ComputeRaftItem::DruidTransactions(txs))
.await;
}
}
/// Re-propose uncommited items relevant for current block.
pub async fn re_propose_uncommitted_current_b_num(&mut self) {
if let Some(tx_current_block_num) = self.consensused.block_pipeline.current_block_num() {
self.proposed_in_flight
.re_propose_uncommitted_current_b_num(&mut self.raft_active, tx_current_block_num)
.await;
}
}
/// Propose an item to raft if use_raft, or commit it otherwise.
/// Deduplicate entries.
///
/// ### Arguments
///
/// * `item` - The item to be proposed to a raft.
/// * `b_num` - Block number associated with this item.
async fn propose_item_dedup(
&mut self,
item: &ComputeRaftItem,
b_num: u64,
) -> Option<RaftContextKey> {
self.proposed_in_flight
.propose_item(&mut self.raft_active, item, Some(b_num))
.await
}
/// Propose an item to raft if use_raft, or commit it otherwise.
///
/// ### Arguments
///
/// * `item` - The item to be proposed to a raft.
async fn propose_item(&mut self, item: &ComputeRaftItem) -> RaftContextKey {
self.proposed_in_flight
.propose_item(&mut self.raft_active, item, None)
.await
.unwrap()
}
/// Get the UNICORN value for the current mining round
pub fn get_current_unicorn(&self) -> &UnicornInfo {
self.consensused.get_current_unicorn()
}
/// Get iterator for the participating miners for the current mining round
pub fn get_mining_participants_iter(&self) -> impl Iterator<Item = SocketAddr> + '_ {
self.get_mining_participants().iter().copied()
}
/// Get the participating miners for the current mining round
pub fn get_mining_participants(&self) -> &Participants {
let proposer_id = self.raft_active.peer_id();
self.consensused.get_mining_participants(proposer_id)
}
/// Get the winning miner and PoW entry for the current mining round
pub fn get_winning_miner(&self) -> &Option<(SocketAddr, WinningPoWInfo)> {
self.consensused.get_winning_miner()
}
/// The current tx_pool that will be used to generate next block
/// Returns a BTreeMap reference which contains a String and a Transaction.
pub fn get_committed_tx_pool(&self) -> &BTreeMap<String, Transaction> {
&self.consensused.tx_pool
}
/// The current tx_druid_pool that will be used to generate next block
/// Returns a Vec<BTreeMap> reference which contains a String and a Transaction.
pub fn get_committed_tx_druid_pool(&self) -> &Vec<BTreeMap<String, Transaction>> {
&self.consensused.tx_druid_pool
}
/// Gets the current number of tokens in circulation
pub fn get_current_circulation(&self) -> &TokenAmount {
&self.consensused.current_circulation
}
/// Gets the current reward for a given block
pub fn get_current_reward(&self) -> &TokenAmount {
self.consensused.block_pipeline.get_current_reward()
}
/// Whether adding these will grow our pool within the limit. Returns a bool.
pub fn tx_pool_can_accept(&self, extra_len: usize) -> bool {
self.combined_tx_pool_len() + extra_len <= TX_POOL_LIMIT
}
/// Get the local DRUID pool transactions
pub fn get_local_tx_druid_pool(&self) -> &Vec<BTreeMap<String, Transaction>> {
&self.local_tx_druid_pool
}
/// Current tx_pool lenght handled by this node.
fn combined_tx_pool_len(&self) -> usize {
self.local_tx_pool.len() + self.proposed_and_consensused_tx_pool_len()
}
/// Current proposed tx_pool lenght handled by this node.
fn proposed_and_consensused_tx_pool_len(&self) -> usize {
self.proposed_tx_pool_len + self.consensused.tx_pool.len()
}
/// Append new transaction to our local pool from which to propose
/// consensused transactions.
/// ### Arguments
/// * 'transactions' - a mutable BTreeMap that has a String and a Transaction parameters
pub fn append_to_tx_pool(&mut self, mut transactions: BTreeMap<String, Transaction>) {
self.local_tx_pool.append(&mut transactions);
}
/// Append new transaction to our local pool from which to propose
/// consensused transactions.
pub fn append_to_tx_druid_pool(&mut self, transactions: BTreeMap<String, Transaction>) {
self.local_tx_druid_pool.push(transactions);
}
/// Current block to mine or being mined.
pub fn get_mining_block(&self) -> &Option<Block> {
self.consensused.get_mining_block()
}
/// Current block number
pub fn get_current_block_num(&self) -> u64 {
if let Some(block) = self.consensused.get_mining_block() {
block.header.b_num
} else {
0
}
}
/// Current utxo_set returned as `UtxoSet` including block being mined
pub fn get_committed_utxo_set(&self) -> &UtxoSet {
self.consensused.get_committed_utxo_set()
}
/// Current utxo_set returned as `TrackedUtxoSet`
pub fn get_committed_utxo_tracked_set(&self) -> &TrackedUtxoSet {
self.consensused.get_committed_utxo_tracked_set()
}
/// Get a clone of `pk_cache` element of `TrackedUtxoSet`
///
/// ## NOTE
///
/// Only used during tests
#[cfg(test)]
pub fn get_committed_utxo_tracked_pk_cache(
&self,
) -> std::collections::HashMap<String, BTreeSet<a_block_chain::primitives::transaction::OutPoint>>
{
self.consensused.utxo_set.get_pk_cache()
}
/// Remove an entry from `pk_cache` element of `TrackedUtxoSet` ONLY
///
/// ## Arguments
///
/// * `entry` - entry to remove
///
/// ## NOTE
///
/// Only used during tests
#[cfg(test)]
pub fn committed_utxo_remove_pk_cache(&mut self, entry: &str) {
self.consensused.utxo_set.remove_pk_cache_entry(entry)
}
/// Take mining block when mining is completed, use to populate mined block.
pub fn take_mining_block(&mut self) -> Option<(Block, BTreeMap<String, Transaction>)> {
self.consensused.take_mining_block()
}
/// Take all the transactions hashes last commited
pub fn take_local_tx_hash_last_commited(&mut self) -> Vec<String> {
std::mem::take(&mut self.local_tx_hash_last_commited)
}
/// Re-align tracked UTXO set with base UTXO set if needed
///
/// ## Arguments
/// * `b_num` - block number
pub fn event_processed_re_align_utxo_set(&mut self, b_num: u64) {
if self.need_utxo_re_alignment(b_num) {
self.consensused.re_align_utxo_set();
}
}
/// Generate a snapshot, needs to happen at the end of the event processing.
pub fn event_processed_generate_snapshot(&mut self) {
self.set_ignore_dedeup_b_num_less_than_current();
let consensused_ser = serialize(&self.consensused).unwrap();
let (snapshot_idx, term) = self.consensused.last_committed_raft_idx_and_term;
debug!("generate_snapshot: (idx: {}, term: {})", snapshot_idx, term);
let backup = self.need_backup();
self.raft_active
.create_snapshot(snapshot_idx, consensused_ser, backup);
if self.is_shutdown_on_commit() {
self.shutdown_no_commit_process = true;
}
}
/// Ignore processing raft item out of date.
fn set_ignore_dedeup_b_num_less_than_current(&mut self) {
self.proposed_in_flight.ignore_dedeup_b_num_less_than(
self.consensused.block_pipeline.current_block_num().unwrap(),
);
}
/// Find transactions for the current block.
/// ### Arguments
///