scirs2_metrics/optimization/distributed_advanced/consensus/
proof_of_stake.rs1use crate::error::{MetricsError, Result};
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct ProofOfStakeConsensus {
12 node_id: String,
13 stake: u64,
14 validators: HashMap<String, u64>,
15 current_epoch: u64,
16}
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct Validator {
20 id: String,
21 stake: u64,
22 is_active: bool,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize, Default)]
27pub struct PoSState {
28 pub current_epoch: u64,
29 pub validators: HashMap<String, Validator>,
30 pub finalized_blocks: Vec<String>,
31 pub pending_transactions: Vec<String>,
32}
33
34impl ProofOfStakeConsensus {
35 pub fn new(node_id: String, initial_stake: u64) -> Self {
36 let mut validators = HashMap::new();
37 validators.insert(node_id.clone(), initial_stake);
38
39 Self {
40 node_id,
41 stake: initial_stake,
42 validators,
43 current_epoch: 0,
44 }
45 }
46
47 pub fn add_validator(&mut self, validator_id: String, stake: u64) -> Result<()> {
48 self.validators.insert(validator_id, stake);
49 Ok(())
50 }
51
52 pub fn select_validator(&self) -> Result<String> {
53 let total_stake: u64 = self.validators.values().sum();
54 if total_stake == 0 {
55 return Err(MetricsError::InvalidOperation(
56 "No validators with stake".into(),
57 ));
58 }
59
60 let mut max_stake = 0;
62 let mut selected = self.node_id.clone();
63
64 for (id, &stake) in &self.validators {
65 if stake > max_stake {
66 max_stake = stake;
67 selected = id.clone();
68 }
69 }
70
71 Ok(selected)
72 }
73
74 pub fn validate_block(&self, validator_id: &str) -> Result<bool> {
75 match self.validators.get(validator_id) {
76 Some(&stake) => Ok(stake > 0),
77 None => Ok(false),
78 }
79 }
80
81 pub fn next_epoch(&mut self) {
82 self.current_epoch += 1;
83 }
84}