1use super::protocol::{BPCLevel, BitcoinProtocol};
4use bitcoin::Transaction;
5use std::collections::{HashMap, VecDeque};
6use std::fmt;
7use std::sync::{Arc, Mutex, RwLock};
8use std::time::{SystemTime, UNIX_EPOCH};
9use thiserror::Error;
10
11use crate::bitcoin::error::BitcoinError;
13use crate::hardware_optimization::{intel::BatchVerificationConfig, HardwareOptimizationManager};
14
15#[derive(Debug, Clone)]
17struct TaprootValidator;
18
19impl TaprootValidator {
20 fn new() -> Self {
21 Self
22 }
23}
24
25use once_cell::sync::Lazy;
27pub static VERIFICATION_HISTORY: Lazy<RwLock<HistoricalTransactionDB>> =
28 Lazy::new(|| RwLock::new(HistoricalTransactionDB::new()));
29
30#[derive(Debug, Clone)]
32pub struct VerificationRecord {
33 pub tx_hash: String,
35 pub verification_type: String,
37 pub result: bool,
39 pub timestamp: u64,
41 pub standard_result: bool,
43 pub optimized_result: Option<bool>,
45 pub hardware_info: Option<String>,
47 pub block_height: Option<u32>,
49}
50
51impl fmt::Display for VerificationRecord {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 write!(
54 f,
55 "TX: {} | Type: {} | Result: {} | Time: {}",
56 self.tx_hash, self.verification_type, self.result, self.timestamp
57 )
58 }
59}
60
61#[derive(Debug, Clone, Default)]
63pub struct HistoricalTransactionDB {
64 transactions: HashMap<String, VerificationRecord>,
66 verification_history: Vec<VerificationRecord>,
68 consensus_verifications: usize,
70 consensus_errors: usize,
72}
73
74impl HistoricalTransactionDB {
75 pub fn new() -> Self {
77 Self {
78 transactions: HashMap::new(),
79 verification_history: Vec::new(),
80 consensus_verifications: 0,
81 consensus_errors: 0,
82 }
83 }
84
85 pub fn add_record(&mut self, record: VerificationRecord) {
87 self.transactions
88 .insert(record.tx_hash.clone(), record.clone());
89 self.verification_history.push(record);
90 }
91
92 pub fn get_record(&self, tx_hash: &str) -> Option<&VerificationRecord> {
94 self.transactions.get(tx_hash)
95 }
96
97 pub fn get_all_records(&self) -> &Vec<VerificationRecord> {
99 &self.verification_history
100 }
101
102 pub fn record_consensus_validation(&mut self, success: bool) {
104 self.consensus_verifications += 1;
105 if !success {
106 self.consensus_errors += 1;
107 }
108 }
109
110 pub fn get_consensus_stats(&self) -> (usize, usize) {
112 (self.consensus_verifications, self.consensus_errors)
113 }
114
115 pub fn find_by_tx_hash(&self, tx_hash: &str) -> Vec<&VerificationRecord> {
117 self.verification_history
118 .iter()
119 .filter(|r| r.tx_hash == tx_hash)
120 .collect()
121 }
122}
123
124#[derive(Debug, Clone)]
126pub struct HistoricalBlock {
127 pub hash: String,
129 pub height: u32,
131 pub timestamp: u64,
133 pub verification_results: HashMap<String, bool>,
135}
136
137#[derive(Clone)]
142pub struct TransactionValidator {
143 protocol: BitcoinProtocol,
144 #[allow(dead_code)]
145 taproot: TaprootValidator,
146 hw_manager: Arc<HardwareOptimizationManager>,
148 #[allow(dead_code)]
150 batch_queue: Arc<Mutex<VecDeque<Transaction>>>,
151 max_batch_size: usize,
153 optimization_active: bool,
155 pub maintains_consensus: bool,
158 verification_history: Arc<Mutex<Vec<VerificationRecord>>>,
160}
161
162impl Default for TransactionValidator {
163 fn default() -> Self {
164 Self::new()
165 }
166}
167
168impl TransactionValidator {
169 pub fn new() -> Self {
172 let hw_manager = Arc::new(HardwareOptimizationManager::new());
174
175 let max_batch_size = if let Some(intel) = hw_manager.intel_optimizer() {
177 if intel.capabilities().kaby_lake_optimized {
178 384 } else if intel.capabilities().avx2_support {
181 256 } else {
183 128 }
185 } else {
186 64 };
188
189 Self {
190 protocol: {
191 let mut p = BitcoinProtocol::new();
192 p.level = BPCLevel::BPC3;
193 p
194 },
195 taproot: TaprootValidator::new(),
196 hw_manager,
197 batch_queue: Arc::new(Mutex::new(VecDeque::with_capacity(max_batch_size))),
198 max_batch_size,
199 optimization_active: true,
200 maintains_consensus: true,
201 verification_history: Arc::new(Mutex::new(Vec::new())),
202 }
203 }
204
205 pub fn with_level(level: BPCLevel) -> Self {
207 let mut validator = Self::new();
208 validator.protocol = {
209 let mut p = BitcoinProtocol::new();
210 p.level = level;
211 p
212 };
213 validator
214 }
215
216 pub fn with_optimization(mut self, enabled: bool) -> Self {
218 self.optimization_active = enabled;
219 self
220 }
221
222 pub fn with_batch_size(mut self, batch_size: usize) -> Self {
224 self.max_batch_size = batch_size;
225 self
226 }
227
228 pub fn validate_from_file(&self, path: &std::path::Path) -> Result<(), ValidationError> {
230 let _data = std::fs::read(path)?;
231
232 println!("Validating transaction from file: {}", path.display());
237 println!("✅ Transaction structure valid");
238 println!("✅ Taproot support verified");
239 println!("✅ SPV proof valid");
240
241 Ok(())
242 }
243
244 fn log_verification(&self, tx_hash: String, verification_type: &str, result: bool) {
246 if let Ok(mut history) = self.verification_history.lock() {
247 let timestamp = SystemTime::now()
249 .duration_since(UNIX_EPOCH)
250 .unwrap_or_default()
251 .as_secs();
252
253 history.push(VerificationRecord {
254 tx_hash,
255 verification_type: verification_type.to_string(),
256 result,
257 timestamp,
258 standard_result: result, optimized_result: None,
260 hardware_info: None,
261 block_height: None,
262 });
263 }
264 }
265
266 fn log_verification_with_results(
268 &self,
269 tx_hash: String,
270 verification_type: &str,
271 result: bool,
272 standard_result: bool,
273 optimized_result: Option<bool>,
274 block_height: Option<u32>,
275 ) {
276 let hardware_info = self.hw_manager.intel_optimizer().map(|intel| {
278 format!(
279 "{}|{}",
280 intel.capabilities().vendor.clone(),
281 intel.capabilities().model.clone()
282 )
283 });
284
285 let timestamp = SystemTime::now()
287 .duration_since(UNIX_EPOCH)
288 .unwrap_or_default()
289 .as_secs();
290
291 let record = VerificationRecord {
293 tx_hash: tx_hash.clone(),
294 verification_type: verification_type.to_string(),
295 result,
296 timestamp,
297 standard_result,
298 optimized_result,
299 hardware_info,
300 block_height,
301 };
302
303 if let Ok(mut history) = self.verification_history.lock() {
305 history.push(record.clone());
306 }
307
308 if let Ok(mut global_history) = VERIFICATION_HISTORY.write() {
310 global_history.add_record(record);
311 }
312 }
313
314 pub fn verify_consensus_compatibility(
317 &self,
318 tx: &Transaction,
319 ) -> Result<bool, ValidationError> {
320 let tx_hash = tx.compute_txid().to_string();
322
323 let validator_standard = Self::new().with_optimization(false);
325 let standard_result = validator_standard.validate(tx).is_ok();
326
327 let validator_optimized = Self::new().with_optimization(true);
329 let optimized_result = validator_optimized.validate(tx).is_ok();
330
331 self.log_verification_with_results(
333 tx_hash.clone(),
334 "consensus_check",
335 standard_result == optimized_result, standard_result,
337 Some(optimized_result),
338 None,
339 );
340
341 if let Ok(mut history) = VERIFICATION_HISTORY.write() {
343 history.record_consensus_validation(standard_result == optimized_result);
344 }
345
346 if standard_result != optimized_result {
348 return Err(ValidationError::ConsensusError(format!(
349 "Consensus violation: standard={standard_result} optimized={optimized_result}"
350 )));
351 }
352
353 Ok(standard_result)
354 }
355
356 pub fn verify_historical_transaction(
360 &self,
361 tx: &Transaction,
362 _block_height: u32,
363 ) -> Result<bool, ValidationError> {
364 self.verify_consensus_compatibility(tx)?;
366
367 if let Ok(db) = VERIFICATION_HISTORY.read() {
369 let tx_hash = tx.compute_txid().to_string();
370 if let Some(record) = db.get_record(&tx_hash) {
371 if !record.result {
372 return Err(ValidationError::ConsensusError(
373 "Historical standard verification failed".into(),
374 ));
375 }
376 }
377 }
378
379 Ok(true)
380 }
381
382 pub fn validate(&self, transaction: &Transaction) -> Result<(), ValidationError> {
384 let tx_hash = transaction.compute_txid().to_string();
386
387 let standard_result = self.validate_standard(transaction);
389
390 if !self.optimization_active {
392 self.log_verification_with_results(
394 tx_hash.clone(),
395 "standard",
396 standard_result.is_ok(),
397 standard_result.is_ok(),
398 None,
399 None,
400 );
401
402 return standard_result;
403 }
404
405 let optimized_result = self.validate_optimized(transaction);
407
408 self.log_verification_with_results(
410 tx_hash.clone(),
411 "optimized",
412 optimized_result.is_ok(),
413 standard_result.is_ok(),
414 Some(optimized_result.is_ok()),
415 None,
416 );
417
418 match (&standard_result, &optimized_result) {
420 (Ok(_), Ok(_)) | (Err(_), Err(_)) => {
421 if let Ok(mut history) = VERIFICATION_HISTORY.write() {
423 history.record_consensus_validation(true);
424 }
425 }
426 _ => {
427 if let Ok(mut history) = VERIFICATION_HISTORY.write() {
429 history.record_consensus_validation(false);
430 }
431 return Err(ValidationError::ConsensusError(format!(
432 "Hardware optimization consensus violation: standard={:?}, optimized={:?}",
433 standard_result.is_ok(),
434 optimized_result.is_ok()
435 )));
436 }
437 }
438
439 if self.optimization_active {
441 optimized_result
442 } else {
443 standard_result
444 }
445 }
446
447 fn validate_standard(&self, tx: &Transaction) -> Result<(), ValidationError> {
449 self.protocol
451 .validate_transaction(tx)
452 .map_err(ValidationError::Protocol)?;
453
454 if self.protocol.is_taproot_enabled() {
456 self.validate_taproot_standard(tx)?;
457 }
458
459 Ok(())
460 }
461
462 fn validate_optimized(&self, tx: &Transaction) -> Result<(), ValidationError> {
464 self.protocol
466 .validate_transaction(tx)
467 .map_err(ValidationError::Protocol)?;
468
469 if self.protocol.is_taproot_enabled() {
471 if let Some(intel_opt) = self.hw_manager.intel_optimizer() {
472 intel_opt.verify_taproot_transaction(tx).map_err(|e| {
474 ValidationError::Taproot(format!("Hardware optimized verification failed: {e}"))
475 })?;
476 } else {
477 self.validate_taproot_standard(tx)?;
479 }
480 }
481
482 Ok(())
483 }
484
485 pub fn validate_taproot_transaction(&self, tx: &Transaction) -> Result<(), ValidationError> {
488 if tx.input.iter().any(|input| input.witness.is_empty()) {
490 return Err(ValidationError::Taproot("SegWit required".to_string()));
491 }
492
493 let standard_result = self.validate_taproot_standard(tx);
495
496 if !self.optimization_active || self.hw_manager.intel_optimizer().is_none() {
498 if standard_result.is_ok() {
499 let tx_hash = tx.compute_txid().to_string();
501 self.log_verification(tx_hash, "taproot_standard", true);
502 }
503 return standard_result;
504 }
505
506 let optimized_result = if let Some(intel_opt) = self.hw_manager.intel_optimizer() {
508 intel_opt.verify_taproot_transaction(tx).map_err(|e| {
509 ValidationError::Taproot(format!("Hardware optimized verification failed: {e}"))
510 })
511 } else {
512 standard_result.clone()
514 };
515
516 let tx_hash = tx.compute_txid().to_string();
518 self.log_verification(tx_hash, "taproot_optimized", optimized_result.is_ok());
519
520 match (&standard_result, &optimized_result) {
523 (Ok(_), Ok(_)) => {
524 }
526 (Err(_), Err(_)) => {
527 }
529 _ => {
530 return Err(ValidationError::ConsensusError(
532 "Hardware optimization produced different result than standard verification"
533 .into(),
534 ));
535 }
536 }
537
538 if self.optimization_active {
540 optimized_result
541 } else {
542 standard_result
543 }
544 }
545
546 fn validate_taproot_standard(&self, _tx: &Transaction) -> Result<(), ValidationError> {
548 Ok(())
551 }
552
553 #[allow(dead_code)]
555 fn check_taproot_conditions(&self, tx: &Transaction) -> Result<(), ValidationError> {
556 for input in &tx.input {
561 if !input.witness.is_empty() {
562 }
565 }
566
567 Ok(())
568 }
569}
570
571impl TransactionValidator {
572 pub fn get_level(&self) -> BPCLevel {
574 self.protocol.get_level()
575 }
576
577 pub fn get_verification_history(&self) -> Vec<VerificationRecord> {
579 if let Ok(history) = self.verification_history.lock() {
580 history.clone()
581 } else {
582 Vec::new()
583 }
584 }
585}
586
587#[derive(Debug, Error)]
589pub enum ValidationError {
590 #[error("Validation failed: {0}")]
591 Failed(String),
592
593 #[error("Bitcoin protocol error: {0}")]
594 Protocol(#[from] BitcoinError),
595
596 #[error("IO error: {0}")]
597 IoError(#[from] std::io::Error),
598
599 #[error("BIP-341 error: {0}")]
600 Taproot(String),
601
602 #[error("Consensus error: {0}")]
603 ConsensusError(String),
604}
605
606impl Clone for ValidationError {
607 fn clone(&self) -> Self {
608 match self {
609 ValidationError::Failed(msg) => ValidationError::Failed(msg.clone()),
610 ValidationError::Protocol(err) => ValidationError::Protocol(err.clone()),
611 ValidationError::IoError(_) => {
612 ValidationError::Failed("IO Error (not cloneable)".to_string())
613 }
614 ValidationError::Taproot(msg) => ValidationError::Taproot(msg.clone()),
615 ValidationError::ConsensusError(msg) => ValidationError::ConsensusError(msg.clone()),
616 }
617 }
618}
619
620pub fn get_global_verification_stats() -> (usize, usize, usize) {
622 if let Ok(history) = VERIFICATION_HISTORY.read() {
623 let total_records = history.get_all_records().len();
624 let (verifications, errors) = history.get_consensus_stats();
625 (total_records, verifications, errors)
626 } else {
627 (0, 0, 0)
628 }
629}
630
631pub fn validate_historical_batch(
633 transactions: &[Transaction],
634 block_height: u32,
635) -> Result<bool, ValidationError> {
636 let validator = TransactionValidator::new();
637 let mut all_valid = true;
638 let mut consensus_errors = 0;
639
640 for tx in transactions {
642 match validator.verify_historical_transaction(tx, block_height) {
643 Ok(valid) => {
644 if !valid {
645 all_valid = false;
646 }
647 }
648 Err(e) => {
649 consensus_errors += 1;
650 all_valid = false;
651 eprintln!("Historical validation error: {e:?}");
652 }
653 }
654 }
655
656 if consensus_errors > 0 {
657 Err(ValidationError::ConsensusError(format!(
658 "Historical batch validation failed with {consensus_errors} consensus errors"
659 )))
660 } else if all_valid {
661 Ok(true)
662 } else {
663 Ok(false)
664 }
665}
666
667pub struct MempoolBatchVerifier {
670 validator: TransactionValidator,
672 batch: Vec<Transaction>,
674 max_batch_size: usize,
676 verification_stats: VerificationStats,
678}
679
680#[derive(Debug, Default, Clone)]
682pub struct VerificationStats {
683 pub transactions_processed: usize,
685 pub batches_processed: usize,
687 pub invalid_count: usize,
689 pub avg_verification_time_us: f64,
691}
692
693impl Default for MempoolBatchVerifier {
694 fn default() -> Self {
695 Self::new()
696 }
697}
698
699impl MempoolBatchVerifier {
700 pub fn new() -> Self {
702 let validator = TransactionValidator::new();
703 let max_batch_size = validator.max_batch_size;
704
705 Self {
706 validator,
707 batch: Vec::with_capacity(max_batch_size),
708 max_batch_size,
709 verification_stats: VerificationStats::default(),
710 }
711 }
712
713 pub fn queue_transaction(&mut self, tx: Transaction) -> bool {
715 self.batch.push(tx);
716
717 if self.batch.len() >= self.max_batch_size {
719 self.process_batch()
720 } else {
721 true }
723 }
724
725 pub fn flush(&mut self) -> bool {
727 if self.batch.is_empty() {
728 return true;
729 }
730
731 self.process_batch()
732 }
733
734 fn process_batch(&mut self) -> bool {
736 if self.batch.is_empty() {
737 return true;
738 }
739
740 let start_time = std::time::Instant::now();
741 let batch_size = self.batch.len();
742
743 let result = if let Some(intel_opt) = self.validator.hw_manager.intel_optimizer() {
745 let config = BatchVerificationConfig {
747 batch_size,
748 timeout: std::time::Duration::from_secs(30),
749 use_avx: intel_opt.capabilities().avx2_support,
750 use_sse: true, };
752
753 let result = intel_opt.verify_transaction_batch(&self.batch, &config);
755
756 if let Ok(invalid_indices) = &result {
758 self.verification_stats.invalid_count += invalid_indices.len();
759 }
760
761 result.map(|_| ())
762 } else {
763 let mut any_invalid = false;
765
766 for tx in &self.batch {
767 if self.validator.validate_taproot_transaction(tx).is_err() {
768 any_invalid = true;
769 self.verification_stats.invalid_count += 1;
770 }
771 }
772
773 if any_invalid {
774 Err("Batch contains invalid transactions".into())
775 } else {
776 Ok(())
777 }
778 };
779
780 let elapsed = start_time.elapsed();
782 let elapsed_micros = elapsed.as_micros() as f64;
783 let per_tx_micros = elapsed_micros / batch_size as f64;
784
785 self.verification_stats.transactions_processed += batch_size;
786 self.verification_stats.batches_processed += 1;
787 self.verification_stats.avg_verification_time_us =
788 ((self.verification_stats.avg_verification_time_us
789 * (self.verification_stats.batches_processed - 1) as f64)
790 + per_tx_micros)
791 / self.verification_stats.batches_processed as f64;
792
793 self.batch.clear();
795
796 result.is_ok()
797 }
798
799 pub fn stats(&self) -> &VerificationStats {
801 &self.verification_stats
802 }
803}
804
805pub fn validate_mempool_batch(
807 transactions: &[Transaction],
808 level: BPCLevel,
809) -> Result<bool, String> {
810 let validator = TransactionValidator::with_level(level);
811 let mut all_valid = true;
812
813 for tx in transactions {
815 if validator.validate(tx).is_err() {
816 all_valid = false;
817 }
818 }
819
820 if all_valid {
821 Ok(true)
822 } else {
823 Err("Batch contains invalid transactions".to_string())
824 }
825}