summaryrefslogtreecommitdiffstats
path: root/consensus/src/validator.rs
blob: b5c3a70f9b9ca8f9c9cd6b1f3eb58799f18317fb (plain) (blame)
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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Validator tier based on stake amount
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ValidatorTier {
    /// Micro validator: 10 ONC minimum stake
    /// Perfect for Raspberry Pi Zero, old hardware
    Micro,

    /// Light validator: 100 ONC minimum stake
    /// Raspberry Pi 4, basic VPS
    Light,

    /// Standard validator: 1000 ONC minimum stake
    /// Desktop PC, decent VPS
    Standard,

    /// Power validator: 10000 ONC minimum stake
    /// Dedicated server, 24/7 operation
    Power,
}

impl ValidatorTier {
    /// Get minimum stake required for this tier
    pub fn min_stake(&self) -> u64 {
        match self {
            Self::Micro => 10,
            Self::Light => 100,
            Self::Standard => 1000,
            Self::Power => 10000,
        }
    }

    /// Get expected monthly return for this tier (approximate)
    pub fn expected_monthly_return(&self) -> f64 {
        match self {
            Self::Micro => 0.1,
            Self::Light => 1.0,
            Self::Standard => 10.0,
            Self::Power => 100.0,
        }
    }

    /// Determine tier from stake amount
    pub fn from_stake(stake: u64) -> Self {
        if stake >= 10000 {
            Self::Power
        } else if stake >= 1000 {
            Self::Standard
        } else if stake >= 100 {
            Self::Light
        } else {
            Self::Micro
        }
    }

    /// Get stake weight multiplier for this tier
    pub fn stake_multiplier(&self) -> f64 {
        match self {
            Self::Micro => 1.0,
            Self::Light => 1.1,    // 10% bonus
            Self::Standard => 1.2, // 20% bonus
            Self::Power => 1.3,    // 30% bonus
        }
    }
}

/// A validator in the OnionCoin network
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Validator {
    /// Validator's public key (also .onion identity)
    pub pubkey: [u8; 32],

    /// Staked amount
    pub stake: u64,

    /// Validator tier
    pub tier: ValidatorTier,

    /// When the stake was created (Unix timestamp)
    pub stake_time: i64,

    /// Lock period end time (Unix timestamp)
    pub unlock_time: i64,

    /// Onion address of the validator node
    pub onion_address: String,

    /// Is currently active?
    pub active: bool,

    /// Total blocks validated
    pub blocks_validated: u64,

    /// Total rewards earned
    pub total_rewards: u64,
}

impl Validator {
    /// Minimum lock period for stake (30 days)
    pub const LOCK_PERIOD_DAYS: i64 = 30;

    /// Create a new validator
    pub fn new(
        pubkey: [u8; 32],
        stake: u64,
        onion_address: String,
        current_time: i64,
    ) -> Result<Self, ValidatorError> {
        // Check minimum stake
        if stake < ValidatorTier::Micro.min_stake() {
            return Err(ValidatorError::InsufficientStake {
                provided: stake,
                minimum: ValidatorTier::Micro.min_stake(),
            });
        }

        let tier = ValidatorTier::from_stake(stake);
        let unlock_time = current_time + (Self::LOCK_PERIOD_DAYS * 24 * 3600);

        Ok(Self {
            pubkey,
            stake,
            tier,
            stake_time: current_time,
            unlock_time,
            onion_address,
            active: true,
            blocks_validated: 0,
            total_rewards: 0,
        })
    }

    /// Check if stake is locked
    pub fn is_locked(&self, current_time: i64) -> bool {
        current_time < self.unlock_time
    }

    /// Add stake to existing validator
    pub fn add_stake(&mut self, amount: u64, current_time: i64) {
        self.stake += amount;
        self.tier = ValidatorTier::from_stake(self.stake);

        // Extend lock period
        self.unlock_time = current_time + (Self::LOCK_PERIOD_DAYS * 24 * 3600);
    }

    /// Remove stake (only if unlocked)
    pub fn remove_stake(
        &mut self,
        amount: u64,
        current_time: i64,
    ) -> Result<(), ValidatorError> {
        if self.is_locked(current_time) {
            return Err(ValidatorError::StakeLocked {
                unlock_time: self.unlock_time,
            });
        }

        if amount > self.stake {
            return Err(ValidatorError::InsufficientStake {
                provided: self.stake,
                minimum: amount,
            });
        }

        self.stake -= amount;
        self.tier = ValidatorTier::from_stake(self.stake);

        // Deactivate if below minimum
        if self.stake < ValidatorTier::Micro.min_stake() {
            self.active = false;
        }

        Ok(())
    }

    /// Record a validated block
    pub fn record_block(&mut self, reward: u64) {
        self.blocks_validated += 1;
        self.total_rewards += reward;
    }

    /// Calculate ROI percentage
    pub fn roi_percentage(&self) -> f64 {
        if self.stake == 0 {
            0.0
        } else {
            (self.total_rewards as f64 / self.stake as f64) * 100.0
        }
    }
}

/// Registry of all validators in the network
#[derive(Debug, Default)]
pub struct ValidatorRegistry {
    validators: HashMap<[u8; 32], Validator>,
}

impl ValidatorRegistry {
    pub fn new() -> Self {
        Self {
            validators: HashMap::new(),
        }
    }

    /// Register a new validator
    pub fn register(&mut self, validator: Validator) -> Result<(), ValidatorError> {
        if self.validators.contains_key(&validator.pubkey) {
            return Err(ValidatorError::AlreadyRegistered);
        }

        self.validators.insert(validator.pubkey, validator);
        Ok(())
    }

    /// Get a validator by pubkey
    pub fn get(&self, pubkey: &[u8; 32]) -> Option<&Validator> {
        self.validators.get(pubkey)
    }

    /// Get a mutable validator by pubkey
    pub fn get_mut(&mut self, pubkey: &[u8; 32]) -> Option<&mut Validator> {
        self.validators.get_mut(pubkey)
    }

    /// Get all active validators
    pub fn get_active(&self) -> Vec<&Validator> {
        self.validators
            .values()
            .filter(|v| v.active)
            .collect()
    }

    /// Get validators by tier
    pub fn get_by_tier(&self, tier: ValidatorTier) -> Vec<&Validator> {
        self.validators
            .values()
            .filter(|v| v.tier == tier && v.active)
            .collect()
    }

    /// Total staked amount across all validators
    pub fn total_staked(&self) -> u64 {
        self.validators
            .values()
            .filter(|v| v.active)
            .map(|v| v.stake)
            .sum()
    }

    /// Count of active validators
    pub fn active_count(&self) -> usize {
        self.validators
            .values()
            .filter(|v| v.active)
            .count()
    }

    /// Count by tier
    pub fn count_by_tier(&self) -> HashMap<ValidatorTier, usize> {
        let mut counts = HashMap::new();

        for validator in self.validators.values() {
            if validator.active {
                *counts.entry(validator.tier).or_insert(0) += 1;
            }
        }

        counts
    }

    /// Deactivate validator
    pub fn deactivate(&mut self, pubkey: &[u8; 32]) -> Result<(), ValidatorError> {
        let validator = self.validators.get_mut(pubkey)
            .ok_or(ValidatorError::NotFound)?;

        validator.active = false;
        Ok(())
    }

    /// Remove validator (only if stake is 0)
    pub fn remove(&mut self, pubkey: &[u8; 32]) -> Result<(), ValidatorError> {
        let validator = self.validators.get(pubkey)
            .ok_or(ValidatorError::NotFound)?;

        if validator.stake > 0 {
            return Err(ValidatorError::CannotRemoveWithStake);
        }

        self.validators.remove(pubkey);
        Ok(())
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ValidatorError {
    #[error("Insufficient stake: provided {provided}, minimum {minimum}")]
    InsufficientStake { provided: u64, minimum: u64 },

    #[error("Stake is locked until timestamp {unlock_time}")]
    StakeLocked { unlock_time: i64 },

    #[error("Validator already registered")]
    AlreadyRegistered,

    #[error("Validator not found")]
    NotFound,

    #[error("Cannot remove validator with non-zero stake")]
    CannotRemoveWithStake,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_validator_tiers() {
        assert_eq!(ValidatorTier::from_stake(10), ValidatorTier::Micro);
        assert_eq!(ValidatorTier::from_stake(100), ValidatorTier::Light);
        assert_eq!(ValidatorTier::from_stake(1000), ValidatorTier::Standard);
        assert_eq!(ValidatorTier::from_stake(10000), ValidatorTier::Power);
    }

    #[test]
    fn test_validator_creation() {
        let pubkey = [1u8; 32];
        let validator = Validator::new(
            pubkey,
            1000,
            "test.onion:9333".to_string(),
            0,
        ).unwrap();

        assert_eq!(validator.stake, 1000);
        assert_eq!(validator.tier, ValidatorTier::Standard);
        assert!(validator.active);
    }

    #[test]
    fn test_stake_locking() {
        let pubkey = [1u8; 32];
        let mut validator = Validator::new(
            pubkey,
            1000,
            "test.onion:9333".to_string(),
            0,
        ).unwrap();

        // Should be locked
        assert!(validator.is_locked(1000));

        // Should be unlocked after lock period
        let unlock_time = Validator::LOCK_PERIOD_DAYS * 24 * 3600;
        assert!(!validator.is_locked(unlock_time + 1));

        // Cannot remove stake while locked
        assert!(validator.remove_stake(100, 1000).is_err());

        // Can remove stake after unlock
        assert!(validator.remove_stake(100, unlock_time + 1).is_ok());
        assert_eq!(validator.stake, 900);
    }

    #[test]
    fn test_validator_registry() {
        let mut registry = ValidatorRegistry::new();

        let validator = Validator::new(
            [1u8; 32],
            1000,
            "test.onion:9333".to_string(),
            0,
        ).unwrap();

        registry.register(validator).unwrap();

        assert_eq!(registry.active_count(), 1);
        assert_eq!(registry.total_staked(), 1000);
    }

    #[test]
    fn test_validator_roi() {
        let mut validator = Validator::new(
            [1u8; 32],
            1000,
            "test.onion:9333".to_string(),
            0,
        ).unwrap();

        validator.record_block(5);
        validator.record_block(5);

        assert_eq!(validator.blocks_validated, 2);
        assert_eq!(validator.total_rewards, 10);
        assert_eq!(validator.roi_percentage(), 1.0); // 10/1000 = 1%
    }
}