-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathconsensus_integration.rs
More file actions
1775 lines (1514 loc) · 72.7 KB
/
consensus_integration.rs
File metadata and controls
1775 lines (1514 loc) · 72.7 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
//! Consensus integration for ZHTP blockchain
//!
//! Provides full integration with lib-consensus package including validator management,
//! block production, consensus events, DAO governance, and reward distribution.
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use tokio::sync::{RwLock, mpsc};
use tracing::{info, warn, error, debug};
use lib_consensus::{
ConsensusEngine, ConsensusConfig, ConsensusEvent, ValidatorStatus,
DaoEngine, DaoProposalType, DaoVoteChoice,
RewardCalculator, RewardRound,
ConsensusProposal, ConsensusVote, VoteType, ConsensusStep,
ConsensusType, ConsensusProof, NoOpBroadcaster,
DifficultyConfig, DifficultyManager,
};
use lib_crypto::{Hash, hash_blake3, KeyPair};
use lib_identity::IdentityId;
use crate::{
Blockchain, Block, BlockHeader, Transaction, TransactionType, TransactionOutput,
types::{Hash as BlockchainHash, Difficulty},
mempool::Mempool,
utils::time::current_timestamp,
transaction::IdentityTransactionData,
};
/// Validator keypair for cryptographic operations
#[derive(Debug, Clone)]
pub struct ValidatorKeypair {
pub public_key: lib_crypto::PublicKey,
pub private_key: lib_crypto::PrivateKey,
}
/// Detailed information about a validator
#[derive(Debug, Clone)]
pub struct ValidatorInfo {
/// Validator's identity
pub identity: IdentityId,
/// Current validator status
pub status: ValidatorStatus,
/// Amount of ZHTP staked
pub stake_amount: u64,
/// Reputation score (0-100)
pub reputation_score: u8,
/// Height of last active participation
pub last_active_height: u64,
/// Total number of blocks produced
pub total_blocks_produced: u64,
/// Number of times slashed for misbehavior
pub slashing_count: u32,
}
/// Blockchain consensus coordinator
///
/// This struct bridges the blockchain with the consensus engine, handling
/// all consensus-related operations including block production, validation,
/// DAO governance, and reward distribution.
pub struct BlockchainConsensusCoordinator {
/// Core consensus engine from lib-consensus
consensus_engine: Arc<RwLock<ConsensusEngine>>,
/// Blockchain state reference
blockchain: Arc<RwLock<Blockchain>>,
/// Transaction mempool
mempool: Arc<RwLock<Mempool>>,
/// Local validator identity (if this node is a validator)
local_validator_id: Option<IdentityId>,
/// Event channel for consensus events
event_sender: mpsc::UnboundedSender<ConsensusEvent>,
event_receiver: Arc<RwLock<mpsc::UnboundedReceiver<ConsensusEvent>>>,
/// Block production state
is_producing_blocks: bool,
/// Current consensus round cache
current_round_cache: Arc<RwLock<Option<lib_consensus::ConsensusRound>>>,
/// Pending consensus proposals
pending_proposals: Arc<RwLock<VecDeque<ConsensusProposal>>>,
/// Active consensus votes
active_votes: Arc<RwLock<HashMap<Hash, Vec<ConsensusVote>>>>,
/// Difficulty manager (owns difficulty adjustment policy)
difficulty_manager: Arc<RwLock<DifficultyManager>>,
}
// Manual Debug implementation because ConsensusEngine doesn't derive Debug
impl std::fmt::Debug for BlockchainConsensusCoordinator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BlockchainConsensusCoordinator")
.field("local_validator_id", &self.local_validator_id)
.field("is_producing_blocks", &self.is_producing_blocks)
.field("consensus_engine", &"<ConsensusEngine>")
.field("blockchain", &"<Blockchain>")
.field("mempool", &"<Mempool>")
.finish()
}
}
impl BlockchainConsensusCoordinator {
/// Create a new blockchain consensus coordinator
pub async fn new(
blockchain: Arc<RwLock<Blockchain>>,
mempool: Arc<RwLock<Mempool>>,
consensus_config: ConsensusConfig,
) -> Result<Self> {
let consensus_engine = Arc::new(RwLock::new(
ConsensusEngine::new(consensus_config, Arc::new(NoOpBroadcaster))?
));
let (event_sender, event_receiver) = mpsc::unbounded_channel();
// Initialize difficulty manager with default configuration
let difficulty_manager = Arc::new(RwLock::new(DifficultyManager::default()));
Ok(Self {
consensus_engine,
blockchain,
mempool,
local_validator_id: None,
event_sender,
event_receiver: Arc::new(RwLock::new(event_receiver)),
is_producing_blocks: false,
current_round_cache: Arc::new(RwLock::new(None)),
pending_proposals: Arc::new(RwLock::new(VecDeque::new())),
active_votes: Arc::new(RwLock::new(HashMap::new())),
difficulty_manager,
})
}
/// Create a new blockchain consensus coordinator with custom difficulty configuration
pub async fn new_with_difficulty_config(
blockchain: Arc<RwLock<Blockchain>>,
mempool: Arc<RwLock<Mempool>>,
consensus_config: ConsensusConfig,
difficulty_config: DifficultyConfig,
) -> Result<Self> {
let consensus_engine = Arc::new(RwLock::new(
ConsensusEngine::new(consensus_config, Arc::new(NoOpBroadcaster))?
));
let (event_sender, event_receiver) = mpsc::unbounded_channel();
// Initialize difficulty manager with provided configuration
let difficulty_manager = Arc::new(RwLock::new(DifficultyManager::new(difficulty_config)));
Ok(Self {
consensus_engine,
blockchain,
mempool,
local_validator_id: None,
event_sender,
event_receiver: Arc::new(RwLock::new(event_receiver)),
is_producing_blocks: false,
current_round_cache: Arc::new(RwLock::new(None)),
pending_proposals: Arc::new(RwLock::new(VecDeque::new())),
active_votes: Arc::new(RwLock::new(HashMap::new())),
difficulty_manager,
})
}
/// Register this node as a validator
pub async fn register_as_validator(
&mut self,
identity: IdentityId,
stake_amount: u64,
storage_capacity: u64,
consensus_keypair: &KeyPair,
commission_rate: u8,
) -> Result<()> {
let mut consensus_engine = self.consensus_engine.write().await;
// Register with the consensus engine
consensus_engine.register_validator(
identity.clone(),
stake_amount,
storage_capacity,
consensus_keypair.public_key.dilithium_pk.clone(),
commission_rate,
false, // Not genesis validator
).await.map_err(|e| anyhow::anyhow!("Consensus registration failed: {}", e))?;
// Store local validator identity
self.local_validator_id = Some(identity.clone());
// Create validator registration transaction
let mut blockchain = self.blockchain.write().await;
let registration_tx = self.create_validator_registration_transaction(
&identity,
stake_amount,
storage_capacity,
consensus_keypair,
commission_rate,
).await?;
// Add to pending transactions
blockchain.add_pending_transaction(registration_tx)?;
info!("Registered as validator: {:?} with {} ZHTP stake", identity, stake_amount);
Ok(())
}
/// Start the consensus coordinator event loop
pub async fn start_consensus_coordinator(&mut self) -> Result<()> {
info!(" Starting blockchain consensus coordinator");
self.is_producing_blocks = true;
// Start consensus event processing loop
let coordinator_clone = self.clone_for_background();
tokio::spawn(async move {
coordinator_clone.consensus_event_loop().await;
});
// Start block production if this node is a validator
if self.local_validator_id.is_some() {
let coordinator_clone = self.clone_for_background();
tokio::spawn(async move {
coordinator_clone.block_production_loop().await;
});
}
// Start DAO governance processing
let coordinator_clone = self.clone_for_background();
tokio::spawn(async move {
coordinator_clone.dao_governance_loop().await;
});
// Start reward distribution processing
let coordinator_clone = self.clone_for_background();
tokio::spawn(async move {
coordinator_clone.reward_distribution_loop().await;
});
info!("Blockchain consensus coordinator started successfully");
Ok(())
}
/// Create a clone suitable for background tasks
fn clone_for_background(&self) -> BlockchainConsensusCoordinator {
BlockchainConsensusCoordinator {
consensus_engine: self.consensus_engine.clone(),
blockchain: self.blockchain.clone(),
mempool: self.mempool.clone(),
local_validator_id: self.local_validator_id.clone(),
event_sender: self.event_sender.clone(),
event_receiver: self.event_receiver.clone(),
is_producing_blocks: self.is_producing_blocks,
current_round_cache: self.current_round_cache.clone(),
pending_proposals: self.pending_proposals.clone(),
active_votes: self.active_votes.clone(),
difficulty_manager: self.difficulty_manager.clone(),
}
}
/// Get the difficulty manager
pub fn difficulty_manager(&self) -> &Arc<RwLock<DifficultyManager>> {
&self.difficulty_manager
}
/// Get the current difficulty configuration
pub async fn get_difficulty_config(&self) -> DifficultyConfig {
let manager = self.difficulty_manager.read().await;
manager.config().clone()
}
/// Calculate new difficulty using the consensus-owned algorithm
///
/// This is the entry point for blockchain difficulty adjustment.
/// The blockchain calls this method and the consensus engine owns the algorithm.
pub async fn calculate_difficulty_adjustment(
&self,
height: u64,
current_difficulty: u32,
interval_start_time: u64,
interval_end_time: u64,
) -> Result<Option<u32>> {
let manager = self.difficulty_manager.read().await;
manager
.adjust_difficulty(height, current_difficulty, interval_start_time, interval_end_time)
.map_err(|e| anyhow!("Difficulty adjustment failed: {}", e))
}
/// Check if difficulty should be adjusted at the given height
pub async fn should_adjust_difficulty(&self, height: u64) -> bool {
let manager = self.difficulty_manager.read().await;
manager.should_adjust(height)
}
/// Get the initial difficulty value from consensus policy
pub async fn get_initial_difficulty(&self) -> u32 {
let manager = self.difficulty_manager.read().await;
manager.initial_difficulty()
}
/// Get the difficulty adjustment interval from consensus policy
pub async fn get_difficulty_adjustment_interval(&self) -> u64 {
let manager = self.difficulty_manager.read().await;
manager.adjustment_interval()
}
/// Apply DAO governance updates to difficulty parameters
pub async fn apply_difficulty_governance_update(
&self,
initial_difficulty: Option<u32>,
adjustment_interval: Option<u64>,
target_timespan: Option<u64>,
) -> Result<()> {
let mut manager = self.difficulty_manager.write().await;
manager
.apply_governance_update(initial_difficulty, adjustment_interval, target_timespan)
.map_err(|e| anyhow!("Failed to apply difficulty governance update: {}", e))
}
/// Main consensus event processing loop
async fn consensus_event_loop(&self) {
info!(" Starting consensus event processing loop");
loop {
if let Ok(mut receiver) = self.event_receiver.try_write() {
if let Some(event) = receiver.recv().await {
if let Err(e) = self.handle_consensus_event(event).await {
error!("Error handling consensus event: {}", e);
}
}
}
// Brief pause to prevent busy waiting
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
}
}
/// Handle individual consensus events
async fn handle_consensus_event(&self, event: ConsensusEvent) -> Result<()> {
debug!(" Processing consensus event: {:?}", event);
match event {
ConsensusEvent::StartRound { height, trigger } => {
self.handle_start_round(height, trigger).await?;
}
ConsensusEvent::NewBlock { height, previous_hash } => {
self.handle_new_block(height, previous_hash).await?;
}
ConsensusEvent::ProposalReceived { proposal } => {
self.handle_proposal_received(proposal).await?;
}
ConsensusEvent::VoteReceived { vote } => {
self.handle_vote_received(vote).await?;
}
ConsensusEvent::RoundCompleted { height } => {
self.handle_round_completed(height).await?;
}
ConsensusEvent::ValidatorRegistered { identity } => {
info!("Validator registered: {:?}", identity);
}
ConsensusEvent::DaoError { error } => {
warn!("DAO error: {}", error);
}
ConsensusEvent::ByzantineFault { error } => {
warn!(" Byzantine fault detected: {}", error);
}
ConsensusEvent::RewardError { error } => {
warn!(" Reward error: {}", error);
}
_ => {
debug!("Unhandled consensus event: {:?}", event);
}
}
Ok(())
}
/// Handle start round event
async fn handle_start_round(&self, height: u64, trigger: String) -> Result<()> {
info!(" Starting consensus round {} (trigger: {})", height, trigger);
// Update current round cache
{
let consensus_engine = self.consensus_engine.read().await;
let current_round = consensus_engine.current_round().clone();
*self.current_round_cache.write().await = Some(current_round);
}
// Trigger consensus engine event handling
let mut consensus_engine = self.consensus_engine.write().await;
let events = consensus_engine.handle_consensus_event(
ConsensusEvent::StartRound { height, trigger }
).await?;
// Process resulting events
for event in events {
if let Err(e) = self.event_sender.send(event) {
warn!("Failed to send consensus event: {}", e);
}
}
Ok(())
}
/// Handle new block event
async fn handle_new_block(&self, height: u64, previous_hash: Hash) -> Result<()> {
info!(" Processing new block at height {}", height);
// Convert Hash types
// Convert consensus hash to blockchain hash
let mut hash_bytes = [0u8; 32];
let prev_bytes = previous_hash.as_bytes();
hash_bytes[..prev_bytes.len().min(32)].copy_from_slice(&prev_bytes[..prev_bytes.len().min(32)]);
let blockchain_previous_hash = BlockchainHash::from(hash_bytes);
// Verify block can be added to blockchain
let blockchain = self.blockchain.read().await;
if let Some(latest_block) = blockchain.latest_block() {
// Validate that the previous hash matches the latest block
if latest_block.header.hash() != blockchain_previous_hash {
return Err(anyhow!("Previous hash mismatch: expected {}, got {}",
latest_block.header.hash(), blockchain_previous_hash));
}
if latest_block.height() + 1 != height {
return Err(anyhow::anyhow!(
"Block height mismatch: expected {}, got {}",
latest_block.height() + 1,
height
));
}
}
drop(blockchain);
// Process through consensus engine
let mut consensus_engine = self.consensus_engine.write().await;
let events = consensus_engine.handle_consensus_event(
ConsensusEvent::NewBlock { height, previous_hash }
).await?;
// Forward resulting events
for event in events {
if let Err(e) = self.event_sender.send(event) {
warn!("Failed to send consensus event: {}", e);
}
}
Ok(())
}
/// Handle proposal received event
async fn handle_proposal_received(&self, proposal: ConsensusProposal) -> Result<()> {
info!("Received consensus proposal: {:?}", proposal.id);
// Store proposal
self.pending_proposals.write().await.push_back(proposal.clone());
// Convert consensus proposal to blockchain block
let block = self.consensus_proposal_to_block(&proposal).await?;
// Validate block against blockchain rules
let blockchain = self.blockchain.read().await;
let previous_block = blockchain.latest_block();
if !blockchain.verify_block(&block, previous_block)? {
return Err(anyhow::anyhow!("Block verification failed for proposal"));
}
drop(blockchain);
// If we're a validator, cast our vote
if let Some(ref _validator_id) = self.local_validator_id {
self.cast_consensus_vote(&proposal.id, VoteType::PreVote).await?;
}
Ok(())
}
/// Handle vote received event
async fn handle_vote_received(&self, vote: ConsensusVote) -> Result<()> {
debug!(" Received consensus vote: {:?} on proposal {:?}", vote.vote_type, vote.proposal_id);
// Store vote
let proposal_id = vote.proposal_id.clone();
self.active_votes.write().await
.entry(proposal_id)
.or_insert_with(Vec::new)
.push(vote);
Ok(())
}
/// Handle round completed event
async fn handle_round_completed(&self, height: u64) -> Result<()> {
info!("Consensus round completed at height {}", height);
// Find the winning proposal
if let Some(winning_proposal) = self.determine_winning_proposal(height).await? {
// Extract actual transactions from the proposal
let transactions = self.extract_transactions_from_proposal(&winning_proposal).await?;
let block = self.consensus_proposal_to_block_with_transactions(&winning_proposal, transactions).await?;
// Only generate proof if we were the block proposer (otherwise we're just accepting someone else's block)
let mut blockchain = self.blockchain.write().await;
let was_proposer = self.local_validator_id.as_ref()
.map(|id| id == &winning_proposal.proposer)
.unwrap_or(false);
if was_proposer {
// We proposed this block - generate proof
info!("We were the proposer - generating recursive proof for block at height {}", height);
blockchain.add_block_with_proof(block).await?;
} else {
// Another validator proposed this block - just accept it (already has proof)
info!("Accepting block from proposer {} at height {}", hex::encode(winning_proposal.proposer.as_bytes()), height);
blockchain.add_block(block)?;
}
// Remove processed transactions from mempool
let mut mempool = self.mempool.write().await;
let tx_hashes: Vec<_> = winning_proposal.block_data
.chunks(32)
.map(|chunk| {
let mut hash_bytes = [0u8; 32];
hash_bytes.copy_from_slice(chunk);
BlockchainHash::from(hash_bytes)
})
.collect();
mempool.remove_transactions(&tx_hashes);
info!(" Added new block to blockchain at height {} with {} transactions",
height, tx_hashes.len());
}
// Clear processed proposals and votes
self.pending_proposals.write().await.clear();
self.active_votes.write().await.clear();
Ok(())
}
/// Convert consensus proposal to blockchain block with specific transactions
async fn consensus_proposal_to_block_with_transactions(&self, proposal: &ConsensusProposal, transactions: Vec<Transaction>) -> Result<Block> {
// Create block header
let blockchain = self.blockchain.read().await;
let previous_block = blockchain.latest_block();
let height = proposal.height;
// Validate that the proposal height is consistent with blockchain state
if let Some(ref prev_block) = previous_block {
if height != prev_block.header.height + 1 {
return Err(anyhow!("Invalid height: expected {}, got {}", prev_block.header.height + 1, height));
}
debug!("Validated block height against previous block: {}", prev_block.header.height);
}
let mut hash_bytes = [0u8; 32];
let prop_bytes = proposal.previous_hash.as_bytes();
hash_bytes[..prop_bytes.len().min(32)].copy_from_slice(&prop_bytes[..prop_bytes.len().min(32)]);
let previous_hash = BlockchainHash::from(hash_bytes);
let timestamp = proposal.timestamp;
// Validate proposal timestamp
if let Err(e) = validate_consensus_timestamp(timestamp) {
warn!("Invalid proposal timestamp: {}", e);
return Err(anyhow!("Proposal timestamp validation failed: {}", e));
}
debug!("Proposal timestamp validated: {}", timestamp);
// Calculate merkle root from actual transactions
let merkle_root = crate::transaction::hashing::calculate_transaction_merkle_root(&transactions);
// Set difficulty (in production this would be calculated based on network state)
let difficulty = Difficulty::from_bits(crate::INITIAL_DIFFICULTY);
let header = BlockHeader::new(
1, // version
previous_hash,
merkle_root,
timestamp,
difficulty,
height,
transactions.len() as u32,
0, // block_size - will be calculated
difficulty, // cumulative_difficulty
);
let block = Block::new(header, transactions);
Ok(block)
}
/// Block production loop for validators
async fn block_production_loop(&self) {
info!("⛏️ Starting block production loop");
while self.is_producing_blocks {
if let Err(e) = self.attempt_block_production().await {
error!("Block production error: {}", e);
}
// Wait for next block time (configurable, default 10 seconds)
tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;
}
}
/// Attempt to produce a new block
async fn attempt_block_production(&self) -> Result<()> {
let validator_id = match &self.local_validator_id {
Some(id) => id,
None => return Ok(()), // Not a validator, skip block production
};
let blockchain = self.blockchain.read().await;
let current_height = blockchain.get_height() + 1;
let previous_hash = blockchain.latest_block()
.map(|b| b.hash())
.unwrap_or_default();
drop(blockchain);
// Check if we should be the proposer for this round
let consensus_engine = self.consensus_engine.read().await;
let validator_manager = consensus_engine.validator_manager();
if let Some(proposer) = validator_manager.select_proposer(current_height, 0) {
if &proposer.identity == validator_id {
// We are the proposer, create a consensus proposal with transaction data
let consensus_proposal = self.create_consensus_proposal(current_height, previous_hash).await?;
// Send the proposal through consensus engine
let proposal_event = ConsensusEvent::ProposalReceived { proposal: consensus_proposal };
if let Err(e) = self.event_sender.send(proposal_event) {
warn!("Failed to send consensus proposal event: {}", e);
}
}
}
Ok(())
}
/// Create a consensus proposal with transaction data
async fn create_consensus_proposal(&self, height: u64, previous_hash: BlockchainHash) -> Result<ConsensusProposal> {
// Select transactions from mempool
let mempool = self.mempool.read().await;
let selected_transactions = mempool.get_transactions_for_block(
crate::MAX_TRANSACTIONS_PER_BLOCK,
crate::MAX_BLOCK_SIZE,
);
drop(mempool);
// Serialize transaction hashes into block_data
let mut block_data = Vec::new();
for transaction in &selected_transactions {
let tx_hash = transaction.hash();
block_data.extend_from_slice(tx_hash.as_bytes());
}
// Convert blockchain hash to consensus hash
let consensus_previous_hash = Hash::from_bytes(previous_hash.as_bytes());
// Generate proposal ID
let mut proposal_data = Vec::new();
proposal_data.extend_from_slice(&height.to_le_bytes());
proposal_data.extend_from_slice(consensus_previous_hash.as_bytes());
proposal_data.extend_from_slice(&block_data);
let consensus_timestamp = get_current_unix_timestamp().unwrap_or(0);
proposal_data.extend_from_slice(&consensus_timestamp.to_le_bytes());
let proposal_id = Hash::from_bytes(&hash_blake3(&proposal_data));
let proposal = ConsensusProposal {
id: proposal_id.clone(),
height,
proposer: self.local_validator_id.clone().unwrap_or_else(|| Hash::from_bytes(&[0u8; 32])),
previous_hash: consensus_previous_hash,
block_data,
timestamp: consensus_timestamp,
signature: lib_crypto::Signature {
signature: vec![0u8; 64], // Would be properly signed in production
public_key: lib_crypto::PublicKey::new(vec![0u8; 32]),
algorithm: lib_crypto::SignatureAlgorithm::Dilithium2,
timestamp: current_timestamp(),
},
consensus_proof: ConsensusProof {
consensus_type: ConsensusType::Hybrid, // Default to hybrid consensus
stake_proof: None,
storage_proof: None,
work_proof: None,
zk_did_proof: None,
timestamp: current_timestamp(),
},
};
info!("Created consensus proposal {} at height {} with {} transactions",
hex::encode(proposal_id.as_bytes()), height, selected_transactions.len());
Ok(proposal)
}
/// DAO governance processing loop
async fn dao_governance_loop(&self) {
info!(" Starting DAO governance processing loop");
loop {
if let Err(e) = self.process_dao_governance().await {
error!("DAO governance processing error: {}", e);
}
// Process DAO governance every 30 seconds
tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
}
}
/// Process DAO governance operations
async fn process_dao_governance(&self) -> Result<()> {
let mut consensus_engine = self.consensus_engine.write().await;
let dao_engine = consensus_engine.dao_engine_mut();
// Process expired proposals
dao_engine.process_expired_proposals().await?;
// Check for new governance transactions in mempool
let mempool = self.mempool.read().await;
let pending_transactions = mempool.get_all_transactions();
for transaction in pending_transactions {
if self.is_dao_transaction(transaction) {
self.process_dao_transaction(transaction, dao_engine).await?;
}
}
Ok(())
}
/// Reward distribution processing loop
async fn reward_distribution_loop(&self) {
info!("Starting reward distribution processing loop");
loop {
if let Err(e) = self.process_reward_distribution().await {
error!("Reward distribution error: {}", e);
}
// Process rewards every minute
tokio::time::sleep(tokio::time::Duration::from_secs(60)).await;
}
}
/// Process reward distribution
async fn process_reward_distribution(&self) -> Result<()> {
let blockchain = self.blockchain.read().await;
let current_height = blockchain.get_height();
drop(blockchain);
let consensus_engine = self.consensus_engine.read().await;
let validator_manager = consensus_engine.validator_manager();
// Create a temporary reward calculator for this operation
let mut reward_calculator = RewardCalculator::new();
// Calculate rewards for the current round
let reward_round = reward_calculator.calculate_round_rewards(validator_manager, current_height)?;
// Create reward transactions
let reward_transactions = self.create_reward_transactions(&reward_round).await?;
// Add reward transactions to blockchain
drop(consensus_engine);
let mut blockchain = self.blockchain.write().await;
for tx in reward_transactions {
blockchain.add_system_transaction(tx)?;
}
info!(" Distributed {} ZHTP in rewards to {} validators",
reward_round.total_rewards, reward_round.validator_rewards.len());
Ok(())
}
/// Create UBI distribution transactions through consensus
pub async fn create_ubi_distributions(
&self,
citizens: &[(IdentityId, u64)],
system_keypair: &KeyPair,
) -> Result<Vec<BlockchainHash>> {
info!("Creating UBI distributions for {} citizens", citizens.len());
// Simple treasury balance validation to avoid consensus engine deadlock
// Use conservative estimate based on initial treasury setup
let estimated_treasury_available = 200000u64; // Conservative estimate
let total_ubi: u64 = citizens.iter().map(|(_, amount)| *amount).sum();
if total_ubi > estimated_treasury_available {
return Err(anyhow::anyhow!("UBI distribution amount {} exceeds estimated treasury capacity {}",
total_ubi, estimated_treasury_available));
}
info!("Treasury validation passed: {} ZHTP needed, estimated {} ZHTP available",
total_ubi, estimated_treasury_available);
// Create UBI transactions for each citizen
let mut ubi_tx_hashes = Vec::new();
for (citizen_id, amount) in citizens {
// Create transfer transaction for UBI payment
let ubi_transaction = Transaction::new(
vec![], // No inputs - treasury funding
vec![TransactionOutput {
commitment: BlockchainHash::from_slice(&citizen_id.as_bytes()[..32]),
note: BlockchainHash::from_slice(b"UBI_PAYMENT_________________"),
recipient: crate::integration::crypto_integration::PublicKey::new(
citizen_id.as_bytes().to_vec()
),
}],
10, // UBI transaction fee
crate::integration::crypto_integration::Signature {
signature: vec![0u8; 64], // System signature
public_key: crate::integration::crypto_integration::PublicKey::new(
system_keypair.public_key.dilithium_pk.clone()
),
algorithm: crate::integration::crypto_integration::SignatureAlgorithm::Dilithium2,
timestamp: current_timestamp(),
},
format!("UBI_DISTRIBUTION:citizen:{}:amount:{}",
hex::encode(citizen_id.as_bytes()), amount).into_bytes(),
);
let tx_hash = ubi_transaction.hash();
// For demo purposes, we'll simulate successful transaction creation
// In production, this would integrate with the actual economic transaction system
info!("Created UBI payment transaction of {} ZHTP for citizen {} (Demo: Transaction hash: {})",
amount, hex::encode(&citizen_id.as_bytes()[..8]), hex::encode(tx_hash.as_bytes()));
// Since we can't access blockchain due to consensus locks, we'll record the transaction
// In production, this would be handled by a separate economic transaction processor
ubi_tx_hashes.push(tx_hash);
}
info!("Created {} UBI distribution transactions totaling {} ZHTP",
ubi_tx_hashes.len(), total_ubi);
Ok(ubi_tx_hashes)
} /// Create welfare funding transactions through consensus
pub async fn create_welfare_funding(
&self,
services: &[(String, [u8; 32], u64)], // (service_name, address, amount)
system_keypair: &KeyPair,
) -> Result<Vec<BlockchainHash>> {
info!("🏥 Creating welfare funding for {} services", services.len());
// Simple treasury balance validation to avoid consensus engine deadlock
// Use conservative estimate based on initial treasury setup
let estimated_treasury_available = 200000u64; // Conservative estimate
let total_welfare: u64 = services.iter().map(|(_, _, amount)| *amount).sum();
if total_welfare > estimated_treasury_available {
return Err(anyhow::anyhow!("Welfare funding amount {} exceeds estimated treasury capacity {}",
total_welfare, estimated_treasury_available));
}
info!("Treasury validation passed: {} ZHTP needed, estimated {} ZHTP available",
total_welfare, estimated_treasury_available);
// Create welfare funding transactions
let mut welfare_tx_hashes = Vec::new();
for (service_name, service_address, amount) in services {
// Create transfer transaction for welfare funding
let welfare_transaction = Transaction::new(
vec![], // No inputs - treasury funding
vec![TransactionOutput {
commitment: BlockchainHash::from_slice(service_address),
note: BlockchainHash::from_slice(b"WELFARE_FUNDING_____________"),
recipient: crate::integration::crypto_integration::PublicKey::new(
service_address.to_vec()
),
}],
25, // Welfare transaction fee
crate::integration::crypto_integration::Signature {
signature: vec![0u8; 64], // System signature
public_key: crate::integration::crypto_integration::PublicKey::new(
system_keypair.public_key.dilithium_pk.clone()
),
algorithm: crate::integration::crypto_integration::SignatureAlgorithm::Dilithium2,
timestamp: current_timestamp(),
},
format!("WELFARE_FUNDING:service:{}:amount:{}",
service_name, amount).into_bytes(),
);
let tx_hash = welfare_transaction.hash();
// For demo purposes, we'll simulate successful transaction creation
// In production, this would integrate with the actual economic transaction system
info!("Created welfare funding transaction of {} ZHTP for service {} (Demo: Transaction hash: {})",
amount, service_name, hex::encode(tx_hash.as_bytes()));
// Since we can't access blockchain due to consensus locks, we'll record the transaction
// In production, this would be handled by a separate economic transaction processor
welfare_tx_hashes.push(tx_hash);
}
info!("Created {} welfare funding transactions totaling {} ZHTP",
welfare_tx_hashes.len(), total_welfare);
Ok(welfare_tx_hashes)
}
/// Cast a consensus vote
async fn cast_consensus_vote(&self, proposal_id: &Hash, vote_type: VoteType) -> Result<()> {
let validator_id = self.local_validator_id.as_ref()
.ok_or_else(|| anyhow::anyhow!("Not a validator"))?;
let mut consensus_engine = self.consensus_engine.write().await;
// Log the validator casting the vote
debug!("Validator {} casting vote {:?} for proposal {}",
validator_id, vote_type, proposal_id);
let vote = ConsensusVote {
id: lib_crypto::Hash::from_bytes(&[0u8; 32]),
voter: self.local_validator_id.clone().unwrap_or_else(|| lib_crypto::Hash::from_bytes(&[0u8; 32])),
proposal_id: proposal_id.clone(),
vote_type: vote_type.clone(),
height: 0, // Would be set properly in implementation
round: 0,
timestamp: current_timestamp(),
signature: self.create_vote_signature(proposal_id, &vote_type).await?,
};
let vote_event = ConsensusEvent::VoteReceived { vote };
consensus_engine.handle_consensus_event(vote_event).await
.map_err(|e| anyhow::anyhow!("Failed to cast vote: {}", e))?;
Ok(())
}
/// Convert consensus proposal to blockchain block
async fn consensus_proposal_to_block(&self, proposal: &ConsensusProposal) -> Result<Block> {
// Get transactions from mempool based on proposal data
let transactions = self.extract_transactions_from_proposal(proposal).await?;
// Create block header
let blockchain = self.blockchain.read().await;
let previous_block = blockchain.latest_block();
// Determine height based on previous block
let height = if let Some(ref prev_block) = previous_block {
prev_block.header.height + 1
} else {
proposal.height // Genesis block case
};
let mut hash_bytes = [0u8; 32];
let prop_bytes = proposal.previous_hash.as_bytes();
hash_bytes[..prop_bytes.len().min(32)].copy_from_slice(&prop_bytes[..prop_bytes.len().min(32)]);
let previous_hash = BlockchainHash::from(hash_bytes);
let timestamp = proposal.timestamp;
// Calculate merkle root
let merkle_root = crate::transaction::hashing::calculate_transaction_merkle_root(&transactions);
// Set difficulty (in production this would be calculated based on network state)
let difficulty = Difficulty::from_bits(crate::INITIAL_DIFFICULTY);
let header = BlockHeader::new(
1, // version
previous_hash,
merkle_root,
timestamp,
difficulty,
height,
transactions.len() as u32,
0, // block_size - will be calculated
difficulty, // cumulative_difficulty
);
let block = Block::new(header, transactions);
Ok(block)
}
/// Extract transactions from consensus proposal
async fn extract_transactions_from_proposal(&self, proposal: &ConsensusProposal) -> Result<Vec<Transaction>> {
let mut transactions = Vec::new();
let mempool = self.mempool.read().await;
// Parse block_data to extract transaction hashes
// The block_data should contain serialized transaction hashes (32 bytes each)
if proposal.block_data.len() % 32 != 0 {
return Err(anyhow::anyhow!("Invalid block_data: length must be multiple of 32 bytes"));
}
let transaction_count = proposal.block_data.len() / 32;
debug!("Extracting {} transactions from consensus proposal", transaction_count);
for i in 0..transaction_count {
let start_idx = i * 32;
let end_idx = start_idx + 32;
// Extract transaction hash from proposal
let mut tx_hash_bytes = [0u8; 32];
tx_hash_bytes.copy_from_slice(&proposal.block_data[start_idx..end_idx]);
let tx_hash = BlockchainHash::from(tx_hash_bytes);
// Look up transaction in mempool
if let Some(transaction) = mempool.get_transaction(&tx_hash) {
transactions.push(transaction.clone());
debug!("Found transaction in mempool: {}", hex::encode(tx_hash.as_bytes()));
} else {