Skip to main content

blvm_protocol/utxo_commitments/
initial_sync.rs

1//! Initial Sync Algorithm
2//!
3//! Implements the peer consensus initial sync algorithm:
4//! 1. Discover diverse peers
5//! 2. Determine checkpoint height
6//! 3. Request UTXO sets from peers
7//! 4. Find consensus
8//! 5. Verify against block headers
9//! 6. Download UTXO set
10
11use crate::spam_filter::{SpamBreakdown, SpamFilter, SpamFilterConfig, SpamSummary, SpamType};
12#[cfg(feature = "utxo-commitments")]
13use crate::utxo_commitments::data_structures::{
14    UtxoCommitment, UtxoCommitmentError, UtxoCommitmentResult,
15};
16#[cfg(feature = "utxo-commitments")]
17use crate::utxo_commitments::merkle_tree::UtxoMerkleTree;
18#[cfg(feature = "utxo-commitments")]
19use crate::utxo_commitments::network_integration::UtxoCommitmentsNetworkClient;
20#[cfg(feature = "utxo-commitments")]
21use crate::utxo_commitments::peer_consensus::{ConsensusConfig, PeerConsensus, PeerInfo};
22#[cfg(feature = "utxo-commitments")]
23use blvm_consensus::types::{
24    BlockHeader, Hash as HashType, Natural, OutPoint, Transaction, UTXO, UtxoSet,
25};
26#[cfg(feature = "utxo-commitments")]
27/// Initial sync manager
28pub struct InitialSync {
29    peer_consensus: PeerConsensus,
30    spam_filter: SpamFilter,
31    // In real implementation: network_client: NetworkClient,
32}
33
34impl InitialSync {
35    /// Create a new initial sync manager
36    pub fn new(config: ConsensusConfig) -> Self {
37        Self {
38            peer_consensus: PeerConsensus::new(config),
39            spam_filter: SpamFilter::new(),
40        }
41    }
42
43    /// Create a new initial sync manager with custom spam filter config
44    pub fn with_spam_filter(config: ConsensusConfig, spam_filter_config: SpamFilterConfig) -> Self {
45        Self {
46            peer_consensus: PeerConsensus::new(config),
47            spam_filter: SpamFilter::with_config(spam_filter_config),
48        }
49    }
50
51    /// Execute initial sync algorithm
52    ///
53    /// Performs the complete initial sync process:
54    /// 1. Discover diverse peers
55    /// 2. Determine checkpoint height
56    /// 3. Request UTXO sets
57    /// 4. Find consensus
58    /// 5. Verify against headers
59    /// 6. Return verified UTXO commitment
60    pub async fn execute_initial_sync<C: UtxoCommitmentsNetworkClient>(
61        &self,
62        peers: &[(PeerInfo, String)],
63        header_chain: &[BlockHeader],
64        network_client: &C,
65    ) -> UtxoCommitmentResult<UtxoCommitment> {
66        // Step 1: Discover diverse peers (based on consensus-level PeerInfo)
67        let all_infos: Vec<PeerInfo> = peers.iter().map(|(info, _)| info.clone()).collect();
68        let diverse_infos = self.peer_consensus.discover_diverse_peers(all_infos);
69
70        if diverse_infos.len() < self.peer_consensus.config.min_peers {
71            return Err(UtxoCommitmentError::VerificationFailed(format!(
72                "Insufficient diverse peers: got {}, need {}",
73                diverse_infos.len(),
74                self.peer_consensus.config.min_peers
75            )));
76        }
77
78        // Re-attach peer IDs to the diverse set
79        let diverse_with_ids: Vec<(PeerInfo, String)> = peers
80            .iter()
81            .filter(|(info, _)| {
82                diverse_infos
83                    .iter()
84                    .any(|d| d.address == info.address && d.subnet == info.subnet)
85            })
86            .cloned()
87            .collect();
88
89        // Step 2: Determine checkpoint height from the verified header chain.
90        // Peer tip queries (version/start_height aggregation) are not wired yet; the
91        // header chain tip minus safety margin is the supported checkpoint path (REV-P-14).
92        let checkpoint_height = if !header_chain.is_empty() {
93            let tip = header_chain.len() as Natural - 1;
94            tip.saturating_sub(self.peer_consensus.config.safety_margin)
95        } else {
96            return Err(UtxoCommitmentError::VerificationFailed(
97                "No header chain available for checkpoint selection".to_string(),
98            ));
99        };
100
101        // Get checkpoint block hash from header chain (unchanged)
102        if checkpoint_height as usize >= header_chain.len() {
103            return Err(UtxoCommitmentError::VerificationFailed(format!(
104                "Checkpoint height {} exceeds header chain length {}",
105                checkpoint_height,
106                header_chain.len()
107            )));
108        }
109
110        let checkpoint_header = &header_chain[checkpoint_height as usize];
111        let checkpoint_hash = compute_block_hash(checkpoint_header);
112
113        // Step 3: Request UTXO sets from diverse peers via the network client
114        let peer_commitments = self
115            .peer_consensus
116            .request_utxo_sets(
117                network_client,
118                &diverse_with_ids,
119                checkpoint_height,
120                checkpoint_hash,
121            )
122            .await;
123
124        // Step 4: Find consensus
125        let consensus = self.peer_consensus.find_consensus(peer_commitments)?;
126
127        // Step 5: Verify consensus commitment against block headers
128        self.peer_consensus
129            .verify_consensus_commitment(&consensus, header_chain)?;
130
131        // Step 6: Per-UTXO proofs. An empty proof list is a failure, not a skip.
132        #[cfg(feature = "utxo-proof-verification")]
133        {
134            let commitment =
135                crate::utxo_commitments::peer_consensus::accept_commitment_proofs(&consensus)?;
136            return Ok(commitment);
137        }
138
139        // Step 7: Return verified commitment
140        Ok(consensus.commitment)
141    }
142
143    /// Complete sync from checkpoint to current tip
144    ///
145    /// Syncs forward from checkpoint using FULL blocks with complete validation.
146    /// Fully validates all transactions (signatures, scripts) before updating UTXO set.
147    ///
148    /// # Arguments
149    ///
150    /// * `utxo_tree` - UTXO Merkle tree to update incrementally
151    /// * `checkpoint_height` - Starting height (checkpoint)
152    /// * `current_tip` - Ending height (current chain tip)
153    /// * `network_client` - Network client for requesting blocks
154    /// * `get_block_hash` - Function to get block hash for a given height
155    /// * `peer_id` - Peer ID to request blocks from
156    /// * `network` - Network type (Mainnet, Testnet, Regtest)
157    /// * `network_time` - Current network time (Unix timestamp)
158    /// * `recent_headers` - Recent block headers for median time-past calculation
159    /// * `checkpoint_utxo_set` - Full UTXO set at checkpoint (required for validation).
160    ///   If None, starts with empty set (cannot verify checkpoint commitment until end)
161    ///
162    /// # Implementation
163    ///
164    /// 1. Requests FULL blocks from checkpoint+1 to tip
165    /// 2. For each full block:
166    ///    - Fully validates block with connect_block() (signatures, scripts, all consensus rules)
167    ///    - Updates UTXO set from validated result
168    ///    - Updates UTXO tree from validated UTXO set
169    ///    - Verifies commitment matches computed root
170    /// 3. Updates UTXO tree incrementally after validation
171    ///
172    /// **Security**: All transactions are cryptographically verified before UTXO set update.
173    #[allow(clippy::too_many_arguments)]
174    pub async fn complete_sync_from_checkpoint<C, F, Fut>(
175        &self,
176        utxo_tree: &mut UtxoMerkleTree,
177        checkpoint_height: Natural,
178        current_tip: Natural,
179        network_client: &C,
180        get_block_hash: F,
181        peer_id: &str,
182        network: crate::types::Network,
183        network_time: u64,
184        recent_headers: Option<&[BlockHeader]>,
185        checkpoint_utxo_set: Option<UtxoSet>,
186    ) -> UtxoCommitmentResult<()>
187    where
188        C: UtxoCommitmentsNetworkClient,
189        F: Fn(Natural) -> Fut,
190        Fut: std::future::Future<Output = UtxoCommitmentResult<HashType>>,
191    {
192        use crate::block::connect_block;
193
194        // Start with checkpoint UTXO set, or empty if not provided
195        // Note: If empty, we cannot verify checkpoint commitment until we've built the full set
196        let mut utxo_set: UtxoSet = checkpoint_utxo_set.unwrap_or_default();
197
198        // Process blocks incrementally from checkpoint+1 to current tip
199        for height in checkpoint_height + 1..=current_tip {
200            // Get block hash for this height
201            let block_hash = get_block_hash(height).await?;
202
203            // Request FULL block (not filtered) from network peer
204            // This includes all transactions with witnesses for complete validation
205            let full_block = network_client
206                .request_full_block(peer_id, block_hash)
207                .await?;
208
209            // Verify block header height matches expected height
210            if full_block.block.header.timestamp == 0 {
211                return Err(UtxoCommitmentError::VerificationFailed(format!(
212                    "Invalid block header at height {height}"
213                )));
214            }
215
216            let context = crate::block::block_validation_context_for_connect_ibd(
217                recent_headers,
218                network_time,
219                network,
220            );
221            let (validation_result, new_utxo_set, _undo_log) = connect_block(
222                &full_block.block,
223                &full_block.witnesses,
224                utxo_set.clone(),
225                height,
226                &context,
227            )
228            .map_err(|e| {
229                UtxoCommitmentError::VerificationFailed(format!(
230                    "connect_block failed at height {height}: {e}"
231                ))
232            })?;
233
234            // Reject if validation failed
235            if !matches!(
236                validation_result,
237                blvm_consensus::types::ValidationResult::Valid
238            ) {
239                return Err(UtxoCommitmentError::VerificationFailed(format!(
240                    "Block validation failed at height {height}: {validation_result:?}"
241                )));
242            }
243
244            // Update UTXO tree from validated UTXO set
245            // This ensures the tree matches the cryptographically verified state
246            // Pass old utxo_set to detect removals efficiently
247            let old_utxo_set = utxo_set.clone();
248            utxo_tree.update_from_utxo_set(&new_utxo_set, &old_utxo_set)?;
249
250            // Generate commitment from validated UTXO tree
251            let computed_block_hash = compute_block_hash(&full_block.block.header);
252            let computed_commitment = utxo_tree.generate_commitment(computed_block_hash, height);
253
254            // Verify commitment supply matches expected
255            use blvm_consensus::economic::total_supply;
256            let expected_supply = total_supply(height) as u64;
257            if computed_commitment.total_supply != expected_supply {
258                return Err(UtxoCommitmentError::VerificationFailed(format!(
259                    "Supply mismatch at height {}: computed {}, expected {}",
260                    height, computed_commitment.total_supply, expected_supply
261                )));
262            }
263
264            // Note: Commitment root, height, and block hash are verified implicitly
265            // by the fact that we computed them from the validated UTXO set
266
267            // Update utxo_set for next iteration
268            utxo_set = new_utxo_set;
269        }
270
271        Ok(())
272    }
273
274    /// Process a filtered block and update UTXO set
275    ///
276    /// Takes a block with transactions (already filtered or to be filtered),
277    /// applies spam filter, updates UTXO set, and verifies commitment.
278    ///
279    /// **Critical**: This function processes ALL transactions to remove spent inputs,
280    /// but only adds non-spam outputs to the UTXO tree. This ensures UTXO set consistency:
281    /// - Spam transactions that spend non-spam inputs will still remove those inputs
282    /// - Only non-spam outputs are added to the tree (bandwidth savings)
283    /// - UTXO set remains consistent with actual blockchain state
284    ///
285    /// Note: This function applies transactions to the UTXO tree for commitment
286    /// purposes. Full signature verification should be done during block validation
287    /// before calling this function. This function assumes transactions are already
288    /// validated.
289    pub fn process_filtered_block(
290        &self,
291        utxo_tree: &mut UtxoMerkleTree,
292        block_height: Natural,
293        block_transactions: &[Transaction],
294    ) -> UtxoCommitmentResult<(SpamSummary, HashType)> {
295        use blvm_consensus::transaction::is_coinbase;
296
297        let mut spam_summary = SpamSummary {
298            filtered_count: 0,
299            filtered_size: 0,
300            by_type: SpamBreakdown::default(),
301        };
302
303        // Process ALL transactions (including spam) to remove spent inputs
304        // This is critical for UTXO set consistency: even spam transactions must
305        // remove their spent inputs from the tree.
306        for tx in block_transactions {
307            // Check if transaction is spam (for output filtering)
308            let spam_result = self.spam_filter.is_spam(tx);
309            let is_spam = spam_result.is_spam;
310
311            // Update spam summary
312            if is_spam {
313                spam_summary.filtered_count += 1;
314                spam_summary.filtered_size +=
315                    blvm_consensus::transaction::calculate_transaction_size(tx) as u64;
316
317                // Update breakdown
318                for spam_type in &spam_result.detected_types {
319                    match spam_type {
320                        SpamType::Ordinals => {
321                            spam_summary.by_type.ordinals += 1;
322                        }
323                        SpamType::Dust => {
324                            spam_summary.by_type.dust += 1;
325                        }
326                        SpamType::BRC20 => {
327                            spam_summary.by_type.brc20 += 1;
328                        }
329                        SpamType::LargeWitness => {
330                            spam_summary.by_type.ordinals += 1; // Count as Ordinals
331                        }
332                        SpamType::LowFeeRate => {
333                            spam_summary.by_type.dust += 1; // Count as suspicious
334                        }
335                        SpamType::HighSizeValueRatio => {
336                            spam_summary.by_type.ordinals += 1; // Count as Ordinals
337                        }
338                        SpamType::ManySmallOutputs => {
339                            spam_summary.by_type.dust += 1; // Count as dust-like
340                        }
341                        SpamType::UnexecIf
342                        | SpamType::NullDataOp13
343                        | SpamType::NullDataMagic
344                        | SpamType::DataLikeMs => {
345                            spam_summary.by_type.ordinals += 1;
346                        }
347                        SpamType::NotSpam => {}
348                    }
349                }
350            }
351
352            // Compute transaction ID for proper outpoint creation
353            let tx_id = compute_tx_id(tx);
354
355            // CRITICAL: Remove spent inputs from ALL transactions (including spam)
356            // This ensures UTXO set consistency even when spam transactions spend non-spam inputs
357            if !is_coinbase(tx) {
358                for input in &tx.inputs {
359                    // Get the UTXO first (needed for remove to update tracking)
360                    match utxo_tree.get(&input.prevout) {
361                        Ok(Some(utxo)) => {
362                            // Remove the UTXO (even if transaction is spam)
363                            if let Err(e) = utxo_tree.remove(&input.prevout, &utxo) {
364                                return Err(UtxoCommitmentError::TransactionApplication(format!(
365                                    "Failed to remove spent input: {e:?}"
366                                )));
367                            }
368                        }
369                        Ok(None) => {
370                            // UTXO doesn't exist - this might be valid if it was already spent
371                            // or invalid if the transaction wasn't properly validated
372                            // Continue but log - this should be validated before calling
373                        }
374                        Err(e) => {
375                            return Err(UtxoCommitmentError::TransactionApplication(format!(
376                                "Failed to get UTXO for removal: {e:?}"
377                            )));
378                        }
379                    }
380                }
381            }
382
383            // Only add outputs from non-spam transactions
384            // This provides bandwidth savings while maintaining UTXO set consistency
385            if !is_spam {
386                for (i, output) in tx.outputs.iter().enumerate() {
387                    let outpoint = OutPoint {
388                        hash: tx_id,
389                        index: i as u32,
390                    };
391
392                    let utxo = UTXO {
393                        value: output.value,
394                        script_pubkey: output.script_pubkey.as_slice().into(),
395                        height: block_height,
396                        is_coinbase: is_coinbase(tx),
397                    };
398
399                    if let Err(e) = utxo_tree.insert(outpoint, utxo) {
400                        return Err(UtxoCommitmentError::TransactionApplication(format!(
401                            "Failed to add output: {e:?}"
402                        )));
403                    }
404                }
405            }
406            // Spam transaction outputs are skipped (not added to tree)
407        }
408
409        // Return summary and new root
410        let root = utxo_tree.root();
411
412        Ok((spam_summary, root))
413    }
414}
415
416/// Update UTXO commitments after block connection
417///
418/// This function should be called after successfully connecting a block
419/// to keep UTXO commitments synchronized with the blockchain state.
420///
421/// # Arguments
422///
423/// * `utxo_tree` - Mutable reference to the UTXO Merkle tree
424/// * `block` - The block that was just connected
425/// * `block_height` - Height of the connected block
426/// * `spam_filter` - Optional spam filter (if None, all transactions are included)
427///
428/// # Returns
429///
430/// Returns the new Merkle root hash of the UTXO tree.
431///
432/// # Example
433///
434/// ```rust
435/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
436/// use blvm_consensus::block::connect_block;
437/// use blvm_protocol::utxo_commitments::{UtxoMerkleTree, update_commitments_after_block};
438/// use blvm_consensus::spam_filter::SpamFilter;
439/// use blvm_consensus::types::{Network, ValidationResult};
440///
441/// # let block = blvm_consensus::types::Block {
442/// #     header: blvm_consensus::types::BlockHeader {
443/// #         version: 1, prev_block_hash: [0; 32], merkle_root: [0; 32],
444/// #         timestamp: 1234567890, bits: 0x1d00ffff, nonce: 0,
445/// #     },
446/// #     transactions: vec![].into(),
447/// # };
448/// # let witnesses = vec![];
449/// # let utxo_set = blvm_consensus::types::UtxoSet::new();
450/// # let height = 0;
451/// # let mut utxo_tree = UtxoMerkleTree::new()?;
452/// let (result, new_utxo_set, _) = connect_block(&block, &witnesses, utxo_set, height, None, Network::Regtest)?;
453/// if matches!(result, ValidationResult::Valid) {
454///     let spam_filter = SpamFilter::new();
455///     let root = update_commitments_after_block(
456///         &mut utxo_tree,
457///         &block,
458///         height,
459///         Some(&spam_filter),
460///     )?;
461///     println!("New UTXO commitment root: {:?}", root);
462/// }
463/// # Ok(())
464/// # }
465/// ```
466#[cfg(feature = "utxo-commitments")]
467pub fn update_commitments_after_block(
468    utxo_tree: &mut UtxoMerkleTree,
469    block: &crate::types::Block,
470    block_height: Natural,
471    spam_filter: Option<&SpamFilter>,
472) -> UtxoCommitmentResult<HashType> {
473    use blvm_consensus::block::calculate_tx_id;
474    use blvm_consensus::transaction::is_coinbase;
475
476    // If spam filter is provided, use filtered processing
477    if let Some(filter) = spam_filter {
478        let initial_sync = InitialSync {
479            peer_consensus: crate::utxo_commitments::peer_consensus::PeerConsensus::new(
480                crate::utxo_commitments::peer_consensus::ConsensusConfig::default(),
481            ),
482            spam_filter: filter.clone(),
483        };
484        let (_, root) =
485            initial_sync.process_filtered_block(utxo_tree, block_height, &block.transactions)?;
486        Ok(root)
487    } else {
488        // No spam filter: process all transactions normally
489        for tx in &block.transactions {
490            let tx_id = calculate_tx_id(tx);
491
492            // Remove spent inputs (except coinbase)
493            if !is_coinbase(tx) {
494                for input in &tx.inputs {
495                    // Get the UTXO first (needed for remove)
496                    match utxo_tree.get(&input.prevout) {
497                        Ok(Some(utxo)) => {
498                            utxo_tree.remove(&input.prevout, &utxo)?;
499                        }
500                        Ok(None) => {
501                            // UTXO doesn't exist - might be invalid or already spent
502                            // Continue but this should have been caught during validation
503                        }
504                        Err(e) => {
505                            return Err(UtxoCommitmentError::TransactionApplication(format!(
506                                "Failed to get UTXO for removal: {e:?}"
507                            )));
508                        }
509                    }
510                }
511            }
512
513            // Add new outputs
514            for (i, output) in tx.outputs.iter().enumerate() {
515                let outpoint = blvm_consensus::types::OutPoint {
516                    hash: tx_id,
517                    index: i as u32,
518                };
519
520                let utxo = blvm_consensus::types::UTXO {
521                    value: output.value,
522                    script_pubkey: output.script_pubkey.as_slice().into(),
523                    height: block_height,
524                    is_coinbase: is_coinbase(tx),
525                };
526
527                utxo_tree.insert(outpoint, utxo)?;
528            }
529        }
530
531        Ok(utxo_tree.root())
532    }
533}
534
535/// Compute transaction ID (txid) using Bitcoin's standard double SHA256
536///
537/// Transaction ID is computed as: SHA256(SHA256(serialized_tx))
538/// where serialized_tx is the transaction in Bitcoin wire format (non-SegWit format).
539///
540/// Note: For SegWit transactions, the txid still uses the non-witness serialization
541/// (witness data is excluded from txid calculation).
542///
543/// This matches consensus transaction ID computation exactly.
544fn compute_tx_id(tx: &Transaction) -> HashType {
545    use crate::serialization::transaction::serialize_transaction;
546    use sha2::{Digest, Sha256};
547
548    // Serialize transaction to Bitcoin wire format (non-SegWit format for txid)
549    let serialized = serialize_transaction(tx);
550
551    // Double SHA256 (Bitcoin standard for transaction IDs)
552    let first_hash = Sha256::digest(&serialized);
553    let second_hash = Sha256::digest(first_hash);
554
555    // Convert to HashType [u8; 32]
556    let mut txid = [0u8; 32];
557    txid.copy_from_slice(&second_hash);
558
559    txid
560}
561
562/// Compute block header hash (double SHA256)
563fn compute_block_hash(header: &BlockHeader) -> HashType {
564    use sha2::{Digest, Sha256};
565
566    let mut bytes = Vec::with_capacity(80);
567    bytes.extend_from_slice(&header.version.to_le_bytes());
568    bytes.extend_from_slice(&header.prev_block_hash);
569    bytes.extend_from_slice(&header.merkle_root);
570    bytes.extend_from_slice(&header.timestamp.to_le_bytes());
571    bytes.extend_from_slice(&header.bits.to_le_bytes());
572    bytes.extend_from_slice(&header.nonce.to_le_bytes());
573
574    let first_hash = Sha256::digest(&bytes);
575    let second_hash = Sha256::digest(first_hash);
576
577    let mut hash = [0u8; 32];
578    hash.copy_from_slice(&second_hash);
579    hash
580}