Skip to main content

moloch_chain/
state.rs

1//! Chain state management.
2//!
3//! The `ChainState` tracks the current state of the audit chain including:
4//! - Current head block and height
5//! - Validator set
6//! - MMR state for inclusion proofs
7
8use moloch_core::{Block, BlockHash, BlockHeader, Hash, Result};
9use moloch_storage::ChainStore;
10use std::sync::Arc;
11
12use crate::validators::ValidatorSet;
13
14/// Current state of the audit chain.
15#[derive(Debug)]
16pub struct ChainState<S: ChainStore> {
17    /// The storage backend.
18    storage: Arc<S>,
19    /// Current head block header.
20    head: Option<BlockHeader>,
21    /// Current chain height (0-indexed).
22    height: Option<u64>,
23    /// Current validator set.
24    validators: ValidatorSet,
25    /// Chain configuration.
26    config: ChainConfig,
27}
28
29/// Chain configuration parameters.
30#[derive(Debug, Clone)]
31pub struct ChainConfig {
32    /// Chain identifier (for replay protection).
33    pub chain_id: String,
34    /// Maximum events per block.
35    pub max_events_per_block: usize,
36    /// Maximum block size in bytes.
37    pub max_block_size: usize,
38    /// Target block time in milliseconds.
39    pub block_time_ms: u64,
40    /// Minimum validators required for consensus.
41    pub min_validators: usize,
42}
43
44impl Default for ChainConfig {
45    fn default() -> Self {
46        Self {
47            chain_id: "moloch-mainnet".into(),
48            max_events_per_block: 10_000,
49            max_block_size: 10 * 1024 * 1024, // 10MB
50            block_time_ms: 1000,              // 1 second
51            min_validators: 1,
52        }
53    }
54}
55
56/// Result of applying a block.
57#[derive(Debug, Clone)]
58pub struct ApplyResult {
59    /// The block that was applied.
60    pub block_hash: BlockHash,
61    /// New chain height.
62    pub height: u64,
63    /// Number of events in the block.
64    pub event_count: usize,
65    /// MMR root after applying.
66    pub mmr_root: Hash,
67}
68
69/// Errors specific to chain state operations.
70#[derive(Debug, thiserror::Error)]
71pub enum ChainError {
72    #[error("block height mismatch: expected {expected}, got {got}")]
73    HeightMismatch { expected: u64, got: u64 },
74
75    #[error("invalid parent hash: expected {expected}, got {got}")]
76    InvalidParent { expected: String, got: String },
77
78    #[error("block sealed by unknown validator: {0}")]
79    UnknownValidator(String),
80
81    #[error("block validation failed: {0}")]
82    BlockValidation(String),
83
84    #[error("block too large: {size} bytes exceeds limit {limit}")]
85    BlockTooLarge { size: usize, limit: usize },
86
87    #[error("too many events: {count} exceeds limit {limit}")]
88    TooManyEvents { count: usize, limit: usize },
89
90    #[error("chain not initialized (no genesis block)")]
91    NotInitialized,
92
93    #[error("genesis block already exists")]
94    GenesisExists,
95
96    #[error("cannot revert genesis block")]
97    CannotRevertGenesis,
98
99    #[error("storage error: {0}")]
100    Storage(#[from] moloch_core::Error),
101}
102
103impl<S: ChainStore> ChainState<S> {
104    /// Create a new chain state with the given storage and validators.
105    pub fn new(storage: Arc<S>, validators: ValidatorSet, config: ChainConfig) -> Result<Self> {
106        // Load current state from storage
107        let height = storage.latest_height()?;
108        let head = if let Some(h) = height {
109            storage.get_header(h)?
110        } else {
111            None
112        };
113
114        Ok(Self {
115            storage,
116            head,
117            height,
118            validators,
119            config,
120        })
121    }
122
123    /// Get the current chain height (None if no blocks).
124    pub fn height(&self) -> Option<u64> {
125        self.height
126    }
127
128    /// Get the current head block header.
129    pub fn head(&self) -> Option<&BlockHeader> {
130        self.head.as_ref()
131    }
132
133    /// Get the current head block hash.
134    pub fn head_hash(&self) -> Option<BlockHash> {
135        self.head.as_ref().map(|h| h.hash())
136    }
137
138    /// Get the validator set.
139    pub fn validators(&self) -> &ValidatorSet {
140        &self.validators
141    }
142
143    /// Get the chain configuration.
144    pub fn config(&self) -> &ChainConfig {
145        &self.config
146    }
147
148    /// Check if the chain has been initialized with a genesis block.
149    pub fn is_initialized(&self) -> bool {
150        self.height.is_some()
151    }
152
153    /// Get the expected height for the next block.
154    pub fn next_height(&self) -> u64 {
155        self.height.map_or(0, |h| h + 1)
156    }
157
158    /// Get the expected parent hash for the next block.
159    pub fn expected_parent(&self) -> Option<BlockHash> {
160        self.head_hash()
161    }
162
163    /// Initialize the chain with a genesis block.
164    pub fn init_genesis(&mut self, genesis: Block) -> std::result::Result<ApplyResult, ChainError> {
165        if self.is_initialized() {
166            return Err(ChainError::GenesisExists);
167        }
168
169        if genesis.header.height != 0 {
170            return Err(ChainError::HeightMismatch {
171                expected: 0,
172                got: genesis.header.height,
173            });
174        }
175
176        self.apply_block_internal(genesis)
177    }
178
179    /// Apply a block to the chain.
180    ///
181    /// Validates the block against:
182    /// - Height (must be next expected)
183    /// - Parent hash (must match current head)
184    /// - Sealer (must be valid validator)
185    /// - Signature
186    /// - Size limits
187    pub fn apply_block(&mut self, block: Block) -> std::result::Result<ApplyResult, ChainError> {
188        // Validate height
189        let expected_height = self.next_height();
190        if block.header.height != expected_height {
191            return Err(ChainError::HeightMismatch {
192                expected: expected_height,
193                got: block.header.height,
194            });
195        }
196
197        // Validate parent (skip for genesis)
198        if block.header.height > 0 {
199            let expected_parent = self.head_hash().ok_or(ChainError::NotInitialized)?;
200            if block.header.parent != expected_parent {
201                return Err(ChainError::InvalidParent {
202                    expected: hex::encode(expected_parent.as_hash().as_bytes()),
203                    got: hex::encode(block.header.parent.as_hash().as_bytes()),
204                });
205            }
206        }
207
208        // Validate sealer is a known validator
209        if !self.validators.contains(&block.header.sealer) {
210            return Err(ChainError::UnknownValidator(hex::encode(
211                block.header.sealer.as_pubkey().as_bytes(),
212            )));
213        }
214
215        // Validate block size limits
216        self.validate_block_limits(&block)?;
217
218        // Validate block signature and structure
219        let parent_header = self.head.as_ref();
220        block
221            .validate(parent_header)
222            .map_err(|e| ChainError::BlockValidation(e.to_string()))?;
223
224        self.apply_block_internal(block)
225    }
226
227    /// Internal block application (after validation).
228    fn apply_block_internal(
229        &mut self,
230        block: Block,
231    ) -> std::result::Result<ApplyResult, ChainError> {
232        let height = block.header.height;
233        let event_count = block.events.len();
234        let block_hash = block.hash();
235        let mmr_root = block.header.mmr_root;
236
237        // Store the block
238        self.storage.put_block(&block)?;
239
240        // Update MMR with block hash
241        self.storage.put_mmr_node(height, *block_hash.as_hash())?;
242        self.storage.set_mmr_meta(height + 1, height + 1)?;
243
244        // Update state
245        self.head = Some(block.header);
246        self.height = Some(height);
247
248        Ok(ApplyResult {
249            block_hash,
250            height,
251            event_count,
252            mmr_root,
253        })
254    }
255
256    /// Validate block size limits.
257    fn validate_block_limits(&self, block: &Block) -> std::result::Result<(), ChainError> {
258        if block.events.len() > self.config.max_events_per_block {
259            return Err(ChainError::TooManyEvents {
260                count: block.events.len(),
261                limit: self.config.max_events_per_block,
262            });
263        }
264
265        let size = bincode::serialize(block).map(|b| b.len()).unwrap_or(0);
266        if size > self.config.max_block_size {
267            return Err(ChainError::BlockTooLarge {
268                size,
269                limit: self.config.max_block_size,
270            });
271        }
272
273        Ok(())
274    }
275
276    /// Revert the chain to the previous block.
277    ///
278    /// This is primarily for handling reorgs in PoA (should be rare).
279    /// Returns the reverted block.
280    pub fn revert_block(&mut self) -> std::result::Result<Block, ChainError> {
281        let height = self.height.ok_or(ChainError::NotInitialized)?;
282
283        if height == 0 {
284            return Err(ChainError::CannotRevertGenesis);
285        }
286
287        // Get the block we're reverting
288        let block = self
289            .storage
290            .get_block(height)?
291            .ok_or(ChainError::NotInitialized)?;
292
293        // Load previous block header
294        let prev_height = height - 1;
295        let prev_header = self.storage.get_header(prev_height)?;
296
297        // Update state (note: we don't delete from storage, just update head)
298        self.head = prev_header;
299        self.height = Some(prev_height);
300
301        Ok(block)
302    }
303
304    /// Get a block by height.
305    pub fn get_block(&self, height: u64) -> Result<Option<Block>> {
306        self.storage.get_block(height)
307    }
308
309    /// Get a block by hash.
310    pub fn get_block_by_hash(&self, hash: &BlockHash) -> Result<Option<Block>> {
311        self.storage.get_block_by_hash(hash)
312    }
313
314    /// Create a snapshot of the current state.
315    pub fn snapshot(&self) -> ChainSnapshot {
316        ChainSnapshot {
317            height: self.height,
318            head_hash: self.head_hash(),
319            validator_count: self.validators.len(),
320            chain_id: self.config.chain_id.clone(),
321        }
322    }
323}
324
325/// A lightweight snapshot of chain state.
326#[derive(Debug, Clone)]
327pub struct ChainSnapshot {
328    pub height: Option<u64>,
329    pub head_hash: Option<BlockHash>,
330    pub validator_count: usize,
331    pub chain_id: String,
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337    use moloch_core::{
338        block::{BlockBuilder, SealerId},
339        crypto::SecretKey,
340        event::{ActorId, ActorKind, EventType, ResourceId, ResourceKind},
341        AuditEvent,
342    };
343    use moloch_storage::RocksStorage;
344
345    fn test_event(key: &SecretKey) -> AuditEvent {
346        let actor = ActorId::new(key.public_key(), ActorKind::User);
347        let resource = ResourceId::new(ResourceKind::Repository, "test");
348
349        AuditEvent::builder()
350            .now()
351            .event_type(EventType::Push {
352                force: false,
353                commits: 1,
354            })
355            .actor(actor)
356            .resource(resource)
357            .sign(key)
358            .unwrap()
359    }
360
361    fn test_chain() -> (ChainState<RocksStorage>, SecretKey) {
362        let storage = Arc::new(RocksStorage::open_temp().unwrap());
363        let key = SecretKey::generate();
364        let sealer = SealerId::new(key.public_key());
365        let validators = ValidatorSet::new(vec![sealer]);
366        let config = ChainConfig::default();
367
368        let chain = ChainState::new(storage, validators, config).unwrap();
369        (chain, key)
370    }
371
372    #[test]
373    fn test_chain_state_initial() {
374        let (chain, _) = test_chain();
375
376        assert!(!chain.is_initialized());
377        assert_eq!(chain.height(), None);
378        assert!(chain.head().is_none());
379        assert_eq!(chain.next_height(), 0);
380    }
381
382    #[test]
383    fn test_genesis_block() {
384        let (mut chain, key) = test_chain();
385        let sealer = SealerId::new(key.public_key());
386
387        let genesis = BlockBuilder::new(sealer)
388            .events(vec![test_event(&key)])
389            .seal(&key);
390
391        let result = chain.init_genesis(genesis).unwrap();
392
393        assert_eq!(result.height, 0);
394        assert_eq!(result.event_count, 1);
395        assert!(chain.is_initialized());
396        assert_eq!(chain.height(), Some(0));
397        assert_eq!(chain.next_height(), 1);
398    }
399
400    #[test]
401    fn test_genesis_already_exists() {
402        let (mut chain, key) = test_chain();
403        let sealer = SealerId::new(key.public_key());
404
405        let genesis = BlockBuilder::new(sealer.clone())
406            .events(vec![test_event(&key)])
407            .seal(&key);
408
409        chain.init_genesis(genesis).unwrap();
410
411        let genesis2 = BlockBuilder::new(sealer)
412            .events(vec![test_event(&key)])
413            .seal(&key);
414
415        let err = chain.init_genesis(genesis2).unwrap_err();
416        assert!(matches!(err, ChainError::GenesisExists));
417    }
418
419    #[test]
420    fn test_apply_block_sequence() {
421        let (mut chain, key) = test_chain();
422        let sealer = SealerId::new(key.public_key());
423
424        // Genesis
425        let genesis = BlockBuilder::new(sealer.clone())
426            .events(vec![test_event(&key)])
427            .seal(&key);
428        let genesis_header = genesis.header.clone();
429        chain.init_genesis(genesis).unwrap();
430
431        // Block 1
432        let block1 = BlockBuilder::new(sealer.clone())
433            .parent(genesis_header.clone())
434            .events(vec![test_event(&key), test_event(&key)])
435            .seal(&key);
436
437        let result = chain.apply_block(block1.clone()).unwrap();
438        assert_eq!(result.height, 1);
439        assert_eq!(result.event_count, 2);
440
441        // Block 2
442        let block2 = BlockBuilder::new(sealer)
443            .parent(block1.header.clone())
444            .events(vec![test_event(&key)])
445            .seal(&key);
446
447        let result = chain.apply_block(block2).unwrap();
448        assert_eq!(result.height, 2);
449        assert_eq!(chain.height(), Some(2));
450    }
451
452    #[test]
453    fn test_apply_block_wrong_height() {
454        let (mut chain, key) = test_chain();
455        let sealer = SealerId::new(key.public_key());
456
457        let genesis = BlockBuilder::new(sealer.clone())
458            .events(vec![test_event(&key)])
459            .seal(&key);
460        chain.init_genesis(genesis).unwrap();
461
462        // Try to apply block with wrong height (creates genesis which has height 0)
463        let bad_block = BlockBuilder::new(sealer)
464            .events(vec![test_event(&key)])
465            .seal(&key);
466
467        let err = chain.apply_block(bad_block).unwrap_err();
468        assert!(matches!(
469            err,
470            ChainError::HeightMismatch {
471                expected: 1,
472                got: 0
473            }
474        ));
475    }
476
477    #[test]
478    fn test_apply_block_wrong_parent() {
479        let (mut chain, key) = test_chain();
480        let sealer = SealerId::new(key.public_key());
481
482        let genesis = BlockBuilder::new(sealer.clone())
483            .events(vec![test_event(&key)])
484            .seal(&key);
485        let genesis_header = genesis.header.clone();
486        chain.init_genesis(genesis).unwrap();
487
488        // Create block1 correctly
489        let block1 = BlockBuilder::new(sealer.clone())
490            .parent(genesis_header.clone())
491            .events(vec![test_event(&key)])
492            .seal(&key);
493        let block1_header = block1.header.clone();
494        chain.apply_block(block1).unwrap();
495
496        // Create a fake header at height 1 with wrong hash
497        let mut fake_parent = block1_header.clone();
498        fake_parent.events_root = moloch_core::hash(b"fake"); // Change to make different hash
499
500        // Try to create block2 with wrong parent hash (but correct height)
501        let bad_block = BlockBuilder::new(sealer)
502            .parent(fake_parent) // Has correct height but wrong hash!
503            .events(vec![test_event(&key)])
504            .seal(&key);
505
506        let err = chain.apply_block(bad_block).unwrap_err();
507        // Will fail validation since parent doesn't match (height is correct but hash differs)
508        assert!(matches!(
509            err,
510            ChainError::InvalidParent { .. } | ChainError::BlockValidation(_)
511        ));
512    }
513
514    #[test]
515    fn test_apply_block_unknown_validator() {
516        let (mut chain, key) = test_chain();
517        let sealer = SealerId::new(key.public_key());
518
519        let genesis = BlockBuilder::new(sealer)
520            .events(vec![test_event(&key)])
521            .seal(&key);
522        let genesis_header = genesis.header.clone();
523        chain.init_genesis(genesis).unwrap();
524
525        // Create block with unknown validator
526        let unknown_key = SecretKey::generate();
527        let unknown_sealer = SealerId::new(unknown_key.public_key());
528
529        let bad_block = BlockBuilder::new(unknown_sealer)
530            .parent(genesis_header)
531            .events(vec![test_event(&unknown_key)])
532            .seal(&unknown_key);
533
534        let err = chain.apply_block(bad_block).unwrap_err();
535        assert!(matches!(err, ChainError::UnknownValidator(_)));
536    }
537
538    #[test]
539    fn test_revert_block() {
540        let (mut chain, key) = test_chain();
541        let sealer = SealerId::new(key.public_key());
542
543        let genesis = BlockBuilder::new(sealer.clone())
544            .events(vec![test_event(&key)])
545            .seal(&key);
546        let genesis_header = genesis.header.clone();
547        chain.init_genesis(genesis).unwrap();
548
549        let block1 = BlockBuilder::new(sealer)
550            .parent(genesis_header)
551            .events(vec![test_event(&key)])
552            .seal(&key);
553        chain.apply_block(block1).unwrap();
554
555        assert_eq!(chain.height(), Some(1));
556
557        let reverted = chain.revert_block().unwrap();
558        assert_eq!(reverted.header.height, 1);
559        assert_eq!(chain.height(), Some(0));
560    }
561
562    #[test]
563    fn test_cannot_revert_genesis() {
564        let (mut chain, key) = test_chain();
565        let sealer = SealerId::new(key.public_key());
566
567        let genesis = BlockBuilder::new(sealer)
568            .events(vec![test_event(&key)])
569            .seal(&key);
570        chain.init_genesis(genesis).unwrap();
571
572        let err = chain.revert_block().unwrap_err();
573        assert!(matches!(err, ChainError::CannotRevertGenesis));
574    }
575
576    #[test]
577    fn test_snapshot() {
578        let (mut chain, key) = test_chain();
579        let sealer = SealerId::new(key.public_key());
580
581        let genesis = BlockBuilder::new(sealer)
582            .events(vec![test_event(&key)])
583            .seal(&key);
584        let hash = genesis.hash();
585        chain.init_genesis(genesis).unwrap();
586
587        let snapshot = chain.snapshot();
588        assert_eq!(snapshot.height, Some(0));
589        assert_eq!(snapshot.head_hash, Some(hash));
590        assert_eq!(snapshot.validator_count, 1);
591        assert_eq!(snapshot.chain_id, "moloch-mainnet");
592    }
593}