anya-core 1.2.0

Enterprise-grade Bitcoin Infrastructure Platform
Documentation
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
use bitcoin::{Transaction, Block, BlockHeader, Script, OutPoint};
use thiserror::Error;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{SystemTime, UNIX_EPOCH, Duration};
use super::ConsensusError;

/// [CONSENSUS CRITICAL] A consensus invariant that must always be maintained
/// for Bitcoin consensus compatibility
#[derive(Debug, Clone)]
pub struct ConsensusInvariant {
    /// Unique identifier for the invariant
    pub id: String,
    
    /// Human-readable description
    pub description: String,
    
    /// Level of severity if violated
    pub severity: InvariantSeverity,
    
    /// BIP reference (if applicable)
    pub bip_reference: Option<String>,
    
    /// Code references where this invariant is enforced
    pub code_references: Vec<String>,
}

/// Severity level for consensus invariants
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum InvariantSeverity {
    /// Critical - violation would cause immediate consensus fork
    Critical,
    
    /// High - violation would likely cause consensus issues
    High,
    
    /// Medium - violation could lead to consensus issues in some cases
    Medium,
    
    /// Low - violation unlikely to cause consensus issues but violates spec
    Low,
}

/// [CONSENSUS CRITICAL] Represents a violation of a consensus invariant
#[derive(Debug, Clone)]
pub struct InvariantViolation {
    /// The invariant that was violated
    pub invariant: ConsensusInvariant,
    
    /// Description of how it was violated
    pub violation_description: String,
    
    /// Transaction that violated the invariant (if applicable)
    pub transaction: Option<Transaction>,
    
    /// Block that violated the invariant (if applicable)
    pub block: Option<Block>,
    
    /// Timestamp when the violation was detected
    pub timestamp: u64,
    
    /// Additional context about the violation
    pub context: HashMap<String, String>,
}

/// [CONSENSUS CRITICAL] Interface for checking Bitcoin consensus invariants
pub trait ConsensusInvariantChecker {
    /// Check if a transaction violates any consensus invariants
    fn check_transaction(&self, tx: &Transaction) -> Result<(), InvariantViolation>;
    
    /// Check if a block violates any consensus invariants
    fn check_block(&self, block: &Block) -> Result<(), InvariantViolation>;
    
    /// Get all invariants monitored by this checker
    fn get_invariants(&self) -> Vec<ConsensusInvariant>;
}

/// Default implementation of ConsensusInvariantChecker that enforces
/// Bitcoin Core consensus rules
pub struct BitcoinCoreInvariantChecker {
    /// All invariants being checked
    invariants: Vec<ConsensusInvariant>,
}

impl Default for BitcoinCoreInvariantChecker {
    fn default() -> Self {
        Self {
            invariants: get_bitcoin_core_invariants(),
        }
    }
}

impl BitcoinCoreInvariantChecker {
    /// Create a new invariant checker
    pub fn new() -> Self {
        Self::default()
    }
}

impl ConsensusInvariantChecker for BitcoinCoreInvariantChecker {
    fn check_transaction(&self, tx: &Transaction) -> Result<(), InvariantViolation> {
        // Check transaction version
        if tx.version < 1 || tx.version > 2 {
            return Err(create_violation(
                "tx-version",
                format!("Transaction version {} is invalid, must be 1 or 2", tx.version),
                Some(tx.clone()),
                None,
                &self.invariants,
            ));
        }
        
        // Check transaction has inputs (non-coinbase)
        if tx.input.is_empty() {
            return Err(create_violation(
                "tx-inputs",
                "Transaction must have at least one input".into(),
                Some(tx.clone()),
                None,
                &self.invariants,
            ));
        }
        
        // Check transaction has outputs
        if tx.output.is_empty() {
            return Err(create_violation(
                "tx-outputs",
                "Transaction must have at least one output".into(),
                Some(tx.clone()),
                None,
                &self.invariants,
            ));
        }
        
        // Check for duplicate inputs
        let mut input_outpoints = HashSet::new();
        for input in &tx.input {
            if !input_outpoints.insert(input.previous_output) {
                return Err(create_violation(
                    "tx-duplicate-inputs",
                    format!("Transaction contains duplicate input: {}", input.previous_output),
                    Some(tx.clone()),
                    None,
                    &self.invariants,
                ));
            }
        }
        
        // Many more checks would be implemented in a complete version
        
        Ok(())
    }
    
    fn check_block(&self, block: &Block) -> Result<(), InvariantViolation> {
        // Check block version
        if block.header.version < 1 {
            return Err(create_violation(
                "block-version",
                format!("Block version {} is invalid, must be ≥ 1", block.header.version),
                None,
                Some(block.clone()),
                &self.invariants,
            ));
        }
        
        // Check block has transactions
        if block.txdata.is_empty() {
            return Err(create_violation(
                "block-tx-count",
                "Block must contain at least one transaction (coinbase)".into(),
                None,
                Some(block.clone()),
                &self.invariants,
            ));
        }
        
        // Check first transaction is coinbase
        if !block.txdata[0].is_coin_base() {
            return Err(create_violation(
                "block-coinbase",
                "First transaction in block must be coinbase".into(),
                None,
                Some(block.clone()),
                &self.invariants,
            ));
        }
        
        // Check other transactions are not coinbase
        for (i, tx) in block.txdata.iter().enumerate().skip(1) {
            if tx.is_coin_base() {
                return Err(create_violation(
                    "block-multiple-coinbase",
                    format!("Block contains multiple coinbase transactions (at index {})", i),
                    None,
                    Some(block.clone()),
                    &self.invariants,
                ));
            }
            
            // Check each transaction
            self.check_transaction(tx)?;
        }
        
        // Many more checks would be implemented in a complete version
        
        Ok(())
    }
    
    fn get_invariants(&self) -> Vec<ConsensusInvariant> {
        self.invariants.clone()
    }
}

/// Create an invariant violation from an invariant ID and description
fn create_violation(
    invariant_id: &str,
    description: String,
    tx: Option<Transaction>,
    block: Option<Block>,
    invariants: &[ConsensusInvariant],
) -> InvariantViolation {
    // Find the invariant
    let invariant = invariants
        .iter()
        .find(|i| i.id == invariant_id)
        .cloned()
        .unwrap_or_else(|| {
            // Create a default invariant if not found
            ConsensusInvariant {
                id: invariant_id.to_string(),
                description: "Unknown invariant".to_string(),
                severity: InvariantSeverity::High,
                bip_reference: None,
                code_references: vec![],
            }
        });
    
    // Create the violation
    InvariantViolation {
        invariant,
        violation_description: description,
        transaction: tx,
        block,
        timestamp: SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs(),
        context: HashMap::new(),
    }
}

/// Define all Bitcoin Core consensus invariants
fn get_bitcoin_core_invariants() -> Vec<ConsensusInvariant> {
    vec![
        // Transaction invariants
        ConsensusInvariant {
            id: "tx-version".to_string(),
            description: "Transaction version must be 1 or 2".to_string(),
            severity: InvariantSeverity::Critical,
            bip_reference: None,
            code_references: vec!["src/bitcoin/validation.rs".to_string()],
        },
        ConsensusInvariant {
            id: "tx-inputs".to_string(),
            description: "Transaction must have at least one input".to_string(),
            severity: InvariantSeverity::Critical,
            bip_reference: None,
            code_references: vec!["src/bitcoin/validation.rs".to_string()],
        },
        ConsensusInvariant {
            id: "tx-outputs".to_string(),
            description: "Transaction must have at least one output".to_string(),
            severity: InvariantSeverity::Critical,
            bip_reference: None,
            code_references: vec!["src/bitcoin/validation.rs".to_string()],
        },
        ConsensusInvariant {
            id: "tx-duplicate-inputs".to_string(),
            description: "Transaction must not have duplicate inputs".to_string(),
            severity: InvariantSeverity::Critical,
            bip_reference: Some("CVE-2018-17144".to_string()),
            code_references: vec!["src/bitcoin/validation.rs".to_string()],
        },
        
        // Block invariants
        ConsensusInvariant {
            id: "block-version".to_string(),
            description: "Block version must be ≥ 1".to_string(),
            severity: InvariantSeverity::Critical,
            bip_reference: None,
            code_references: vec!["src/bitcoin/validation.rs".to_string()],
        },
        ConsensusInvariant {
            id: "block-tx-count".to_string(),
            description: "Block must contain at least one transaction".to_string(),
            severity: InvariantSeverity::Critical,
            bip_reference: None,
            code_references: vec!["src/bitcoin/validation.rs".to_string()],
        },
        ConsensusInvariant {
            id: "block-coinbase".to_string(),
            description: "First transaction in block must be coinbase".to_string(),
            severity: InvariantSeverity::Critical,
            bip_reference: None,
            code_references: vec!["src/bitcoin/validation.rs".to_string()],
        },
        ConsensusInvariant {
            id: "block-multiple-coinbase".to_string(),
            description: "Block must not contain multiple coinbase transactions".to_string(),
            severity: InvariantSeverity::Critical,
            bip_reference: None,
            code_references: vec!["src/bitcoin/validation.rs".to_string()],
        },
        
        // Signature validation invariants
        ConsensusInvariant {
            id: "sig-der-encoding".to_string(),
            description: "ECDSA signatures must use strict DER encoding".to_string(),
            severity: InvariantSeverity::Critical,
            bip_reference: Some("BIP-66".to_string()),
            code_references: vec!["src/bitcoin/validation.rs".to_string()],
        },
        ConsensusInvariant {
            id: "sig-low-s-value".to_string(),
            description: "ECDSA signatures S value must be low".to_string(),
            severity: InvariantSeverity::Critical,
            bip_reference: Some("BIP-62".to_string()),
            code_references: vec!["src/bitcoin/validation.rs".to_string()],
        },
        
        // Taproot invariants
        ConsensusInvariant {
            id: "taproot-signature".to_string(),
            description: "Taproot signatures must follow Schnorr signature specs".to_string(),
            severity: InvariantSeverity::Critical,
            bip_reference: Some("BIP-340, BIP-341".to_string()),
            code_references: vec!["src/bitcoin/taproot.rs".to_string()],
        },
        
        // Script execution invariants
        ConsensusInvariant {
            id: "script-op-limit".to_string(),
            description: "Script must not exceed 201 non-push operations".to_string(),
            severity: InvariantSeverity::Critical,
            bip_reference: None,
            code_references: vec!["src/bitcoin/script.rs".to_string()],
        },
        ConsensusInvariant {
            id: "script-size-limit".to_string(),
            description: "Script size must not exceed 10,000 bytes".to_string(),
            severity: InvariantSeverity::Critical,
            bip_reference: None,
            code_references: vec!["src/bitcoin/script.rs".to_string()],
        },
        ConsensusInvariant {
            id: "script-stack-size".to_string(),
            description: "Script stack size must not exceed 1,000 items".to_string(),
            severity: InvariantSeverity::Critical,
            bip_reference: None,
            code_references: vec!["src/bitcoin/script.rs".to_string()],
        },
    ]
}

/// [CONSENSUS CRITICAL] Check transaction consensus invariants
pub fn verify_transaction_consensus_invariants(
    tx: &Transaction
) -> Result<(), ConsensusError> {
    let checker = BitcoinCoreInvariantChecker::new();
    
    match checker.check_transaction(tx) {
        Ok(()) => Ok(()),
        Err(violation) => {
            Err(ConsensusError::InvariantViolation(format!(
                "Transaction violates consensus invariant {}: {}",
                violation.invariant.id,
                violation.violation_description
            )))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bitcoin::{Transaction, TxIn, TxOut};
    
    /// [SECURITY SENSITIVE] Test basic invariant violations
    #[test]
    fn test_basic_invariant_violations() {
        let checker = BitcoinCoreInvariantChecker::new();
        
        // Create invalid transaction (empty)
        let invalid_tx = Transaction {
            version: 1,
            lock_time: bitcoin::LockTime::ZERO,
            input: vec![],
            output: vec![],
        };
        
        // Check should fail
        let result = checker.check_transaction(&invalid_tx);
        assert!(result.is_err(), "Empty transaction should violate invariants");
        
        // Check the specific violation
        if let Err(violation) = result {
            assert_eq!(violation.invariant.id, "tx-inputs");
        }
        
        // Create valid minimal transaction
        let minimal_tx = Transaction {
            version: 1,
            lock_time: bitcoin::LockTime::ZERO,
            input: vec![TxIn {
                previous_output: OutPoint::null(),
                script_sig: Script::new(),
                sequence: 0,
                witness: vec![],
            }],
            output: vec![TxOut {
                value: 1000,
                script_pubkey: Script::new(),
            }],
        };
        
        // Check should pass
        let result = checker.check_transaction(&minimal_tx);
        assert!(result.is_ok(), "Minimal valid transaction should pass invariant check");
    }
}