blvm-node 0.1.4

Bitcoin Commons BLVM: Minimal Bitcoin node implementation using blvm-protocol and blvm-consensus
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
//! UTXO Commitments Network Client Implementation
//!
//! Implements UtxoCommitmentsNetworkClient trait for blvm-node's NetworkManager.
//! Works with both TCP and Iroh transports via the transport abstraction layer.
//!
//! This enables UTXO commitments to work seamlessly with:
//! - Traditional TCP Bitcoin P2P (backward compatible)
//! - Modern Iroh QUIC transport (encrypted, NAT-traversing)

#[cfg(feature = "utxo-commitments")]
use crate::network::{
    protocol::{GetFilteredBlockMessage, GetUTXOProofMessage, GetUTXOSetMessage},
    protocol_extensions::{
        deserialize_utxo_proof, serialize_get_filtered_block, serialize_get_utxo_proof,
        serialize_get_utxo_set,
    },
    transport::TransportType,
    NetworkManager,
};
#[cfg(feature = "utxo-commitments")]
use blvm_protocol::types::{BlockHeader, Hash, Natural};
#[cfg(feature = "utxo-commitments")]
use blvm_protocol::utxo_commitments::data_structures::UtxoCommitment;
#[cfg(feature = "utxo-commitments")]
use blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentResult;
#[cfg(feature = "utxo-commitments")]
use blvm_protocol::utxo_commitments::network_integration::{
    FilteredBlock, UtxoCommitmentsNetworkClient,
};
#[cfg(feature = "utxo-commitments")]
use std::sync::Arc;
#[cfg(feature = "utxo-commitments")]
use tokio::sync::RwLock;

/// Network client implementation for UTXO commitments
///
/// Works with both TCP and Iroh transports through the transport abstraction layer.
/// Automatically uses the appropriate transport based on peer connection type.
#[cfg(feature = "utxo-commitments")]
pub struct UtxoCommitmentsClient {
    network_manager: Arc<RwLock<NetworkManager>>,
}

/// Async body for [`UtxoCommitmentsClient::get_peer_ids`] (sync trait method).
#[cfg(feature = "utxo-commitments")]
async fn collect_utxo_peer_tcp_ids(nm: Arc<RwLock<NetworkManager>>) -> Vec<String> {
    let network = nm.read().await;
    let mut peer_addrs: Vec<String> = network
        .peer_states()
        .read()
        .await
        .keys()
        .map(|addr| format!("tcp:{addr}"))
        .collect();
    use rand::seq::SliceRandom;
    peer_addrs.shuffle(&mut rand::thread_rng());
    peer_addrs
}

#[cfg(feature = "utxo-commitments")]
impl UtxoCommitmentsClient {
    /// Create a new UTXO commitments client
    pub fn new(network_manager: Arc<RwLock<NetworkManager>>) -> Self {
        Self { network_manager }
    }

    /// Determine transport type for a peer
    ///
    /// Checks if peer is connected via TCP or Iroh transport.
    /// In hybrid mode, prefers Iroh if available.
    fn get_peer_transport_type(&self, peer_id: &str) -> TransportType {
        // Parse peer_id to determine transport type
        // TCP peers: "tcp:127.0.0.1:8333"
        // Iroh peers: "iroh:<pubkey_hex>"
        if peer_id.starts_with("iroh:") {
            #[cfg(feature = "iroh")]
            {
                return TransportType::Iroh;
            }
        }

        // Default to TCP (works for TCP addresses and fallback)
        TransportType::Tcp
    }
}

#[cfg(feature = "utxo-commitments")]
impl UtxoCommitmentsNetworkClient for UtxoCommitmentsClient {
    /// Request UTXO set from a peer at specific height
    ///
    /// Sends GetUTXOSet message and awaits UTXOSet response.
    /// Works with both TCP and Iroh transports automatically.
    fn request_utxo_set(
        &self,
        peer_id: &str,
        height: Natural,
        block_hash: Hash,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = UtxoCommitmentResult<UtxoCommitment>> + Send + '_>,
    > {
        // Clone Arc before async move to avoid lifetime issues
        let network_manager = self.network_manager.clone();
        let peer_id = peer_id.to_string(); // Clone string for move

        Box::pin(async move {
            // Parse peer_id to get SocketAddr or TransportAddr
            // Format: "tcp:127.0.0.1:8333" or "iroh:<pubkey_hex>"
            let peer_addr_opt: Option<(
                std::net::SocketAddr,
                Option<crate::network::transport::TransportAddr>,
            )> = if peer_id.starts_with("tcp:") {
                peer_id
                    .strip_prefix("tcp:")
                    .and_then(|s| s.parse::<std::net::SocketAddr>().ok())
                    .map(|addr| (addr, None))
            } else if peer_id.starts_with("iroh:") {
                // Parse Iroh node ID from hex
                #[cfg(feature = "iroh")]
                {
                    use crate::network::transport::TransportAddr;
                    use hex;

                    let node_id_hex = peer_id.strip_prefix("iroh:").ok_or_else(|| {
                        blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                            format!("Invalid Iroh peer_id format: {}", peer_id)
                        )
                    })?;

                    let node_id_bytes = hex::decode(node_id_hex).map_err(|e| {
                        blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                            format!("Invalid Iroh node ID hex: {}", e)
                        )
                    })?;

                    // Validate node ID length (Iroh uses 32-byte public keys)
                    if node_id_bytes.len() != 32 {
                        return Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                            format!("Invalid Iroh node ID length: expected 32 bytes, got {}", node_id_bytes.len())
                        ));
                    }

                    // Create placeholder SocketAddr for Iroh (same approach as mod.rs)
                    // Use first 4 bytes of key for IP, last 2 bytes for port
                    let ip_bytes = [
                        node_id_bytes[0],
                        node_id_bytes[1],
                        node_id_bytes[2],
                        node_id_bytes[3],
                    ];
                    let port = u16::from_be_bytes([node_id_bytes[30], node_id_bytes[31]]);
                    let placeholder_addr = std::net::SocketAddr::from((ip_bytes, port));

                    let transport_addr = TransportAddr::Iroh(node_id_bytes);
                    Some((placeholder_addr, Some(transport_addr)))
                }
                #[cfg(not(feature = "iroh"))]
                {
                    return Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                        "Iroh feature not enabled".to_string()
                    ));
                }
            } else {
                None
            };

            let (peer_addr, transport_addr_opt) = match peer_addr_opt {
                Some((addr, transport)) => (addr, transport),
                None => {
                    return Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                        format!("Invalid peer_id format: {peer_id}")
                    ));
                }
            };

            // Store TransportAddr mapping if Iroh - drop RwLock before Mutex lock
            if let Some(transport_addr) = transport_addr_opt {
                let socket_to_transport = {
                    let network = network_manager.read().await;
                    // Clone the Arc to avoid holding RwLock while locking Mutex
                    Arc::clone(network.socket_to_transport())
                };
                // Now lock the Mutex without holding the RwLock
                socket_to_transport
                    .lock()
                    .await
                    .insert(peer_addr, transport_addr);
            }

            // Check if peer supports UTXO commitments before sending request
            // Get peer_states Arc first, then drop RwLock before Mutex lock
            let peer_states_arc = {
                let network = network_manager.read().await;
                Arc::clone(network.peer_states())
            };

            // Get peer version to check capabilities - now safe to lock RwLock
            let peer_supports_utxo_commitments = {
                let peer_states = peer_states_arc.read().await;
                if let Some(peer_state) = peer_states.get(&peer_addr) {
                    #[cfg(feature = "utxo-commitments")]
                    {
                        use crate::network::protocol::NODE_UTXO_COMMITMENTS;
                        (peer_state.services & NODE_UTXO_COMMITMENTS) != 0
                    }
                    #[cfg(not(feature = "utxo-commitments"))]
                    {
                        false
                    }
                } else {
                    // No peer state yet, assume it doesn't support (will try anyway for backward compatibility)
                    false
                }
            };

            // If we know the peer doesn't support UTXO commitments, return error early
            if !peer_supports_utxo_commitments {
                return Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::VerificationFailed(
                    format!("Peer {peer_id} does not support UTXO commitments (missing NODE_UTXO_COMMITMENTS service flag)")
                ));
            }

            // Register pending request before sending - need to get network manager again
            let (request_id, response_rx) = {
                let network = network_manager.read().await;
                network.register_request(peer_addr)
            }; // RwLock guard dropped here before async wait

            // Create GetUTXOSet message (request_id is generated by the handler, not stored in the message)
            let get_utxo_set_msg = GetUTXOSetMessage { height, block_hash };

            // Serialize message using protocol adapter (handles TCP vs Iroh format)
            let wire_format = serialize_get_utxo_set(&get_utxo_set_msg)
                .map_err(|e| blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                    format!("Failed to serialize GetUTXOSet: {e}")
                ))?;

            // Send message to peer via NetworkManager
            {
                let network = network_manager.read().await;
                network.send_to_peer(peer_addr, wire_format).await
                    .map_err(|e| blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                        format!("Failed to send GetUTXOSet to peer {peer_addr}: {e}")
                    ))?;
            }

            // Await response with timeout (from config)
            let timeout_seconds = {
                let network = network_manager.read().await;
                network
                    .request_timeout_config()
                    .utxo_commitment_request_timeout_seconds
            };
            tokio::select! {
                result = response_rx => {
                    match result {
                        Ok(response_data) => {
                            // Deserialize UTXOSet response
                            use crate::network::protocol::{ProtocolMessage, ProtocolParser};
                            let parsed = ProtocolParser::parse_message(&response_data)
                                .map_err(|e| blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                                    format!("Failed to parse UTXOSet response: {e}")
                                ))?;

                            match parsed {
                                ProtocolMessage::UTXOSet(utxo_set_msg) => {
                                    // Convert to UtxoCommitment
                                    let commitment = blvm_protocol::utxo_commitments::data_structures::UtxoCommitment {
                                        merkle_root: utxo_set_msg.commitment.merkle_root,
                                        total_supply: utxo_set_msg.commitment.total_supply,
                                        utxo_count: utxo_set_msg.commitment.utxo_count,
                                        block_height: utxo_set_msg.commitment.block_height,
                                        block_hash: utxo_set_msg.commitment.block_hash,
                                    };
                                    Ok(commitment)
                                }
                                _ => Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                                    "Unexpected response type: expected UTXOSet".to_string()
                                ))
                            }
                        }
                        Err(_) => Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                            "Response channel closed".to_string()
                        ))
                    }
                }
                _ = tokio::time::sleep(tokio::time::Duration::from_secs(timeout_seconds)) => {
                    // Timeout - cleanup request - drop RwLock before Mutex lock
                    {
                        let pending_requests_arc = {
                            let network = network_manager.read().await;
                            Arc::clone(network.pending_requests())
                        };
                        let mut pending = pending_requests_arc.lock().await;
                        pending.remove(&request_id);
                    }
                    Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                        format!("Request timeout: no response received within {timeout_seconds} seconds")
                    ))
                }
            }
        })
    }

    /// Request filtered block from a peer
    ///
    /// Sends GetFilteredBlock message and awaits FilteredBlock response.
    /// Works with both TCP and Iroh transports automatically.
    fn request_filtered_block(
        &self,
        peer_id: &str,
        block_hash: Hash,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = UtxoCommitmentResult<FilteredBlock>> + Send + '_>,
    > {
        // Clone Arc before async move to avoid lifetime issues
        let network_manager = self.network_manager.clone();
        let peer_id = peer_id.to_string(); // Clone string for move

        Box::pin(async move {
            // Parse peer_id to get SocketAddr or TransportAddr
            // Format: "tcp:127.0.0.1:8333" or "iroh:<pubkey_hex>"
            let peer_addr_opt: Option<(
                std::net::SocketAddr,
                Option<crate::network::transport::TransportAddr>,
            )> = if peer_id.starts_with("tcp:") {
                peer_id
                    .strip_prefix("tcp:")
                    .and_then(|s| s.parse::<std::net::SocketAddr>().ok())
                    .map(|addr| (addr, None))
            } else if peer_id.starts_with("iroh:") {
                // Parse Iroh node ID from hex
                #[cfg(feature = "iroh")]
                {
                    use crate::network::transport::TransportAddr;
                    use hex;

                    let node_id_hex = peer_id.strip_prefix("iroh:").ok_or_else(|| {
                        blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                            format!("Invalid Iroh peer_id format: {}", peer_id)
                        )
                    })?;

                    let node_id_bytes = hex::decode(node_id_hex).map_err(|e| {
                        blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                            format!("Invalid Iroh node ID hex: {}", e)
                        )
                    })?;

                    // Validate node ID length (Iroh uses 32-byte public keys)
                    if node_id_bytes.len() != 32 {
                        return Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                            format!("Invalid Iroh node ID length: expected 32 bytes, got {}", node_id_bytes.len())
                        ));
                    }

                    // Create placeholder SocketAddr for Iroh (same approach as mod.rs)
                    // Use first 4 bytes of key for IP, last 2 bytes for port
                    let ip_bytes = [
                        node_id_bytes[0],
                        node_id_bytes[1],
                        node_id_bytes[2],
                        node_id_bytes[3],
                    ];
                    let port = u16::from_be_bytes([node_id_bytes[30], node_id_bytes[31]]);
                    let placeholder_addr = std::net::SocketAddr::from((ip_bytes, port));

                    let transport_addr = TransportAddr::Iroh(node_id_bytes);
                    Some((placeholder_addr, Some(transport_addr)))
                }
                #[cfg(not(feature = "iroh"))]
                {
                    return Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                        "Iroh feature not enabled".to_string()
                    ));
                }
            } else {
                None
            };

            let (peer_addr, transport_addr_opt) = match peer_addr_opt {
                Some((addr, transport)) => (addr, transport),
                None => {
                    return Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                        format!("Invalid peer_id format: {peer_id}")
                    ));
                }
            };

            // Store TransportAddr mapping if Iroh - drop RwLock before Mutex lock
            if let Some(transport_addr) = transport_addr_opt {
                let socket_to_transport = {
                    let network = network_manager.read().await;
                    Arc::clone(network.socket_to_transport())
                };
                socket_to_transport
                    .lock()
                    .await
                    .insert(peer_addr, transport_addr);
            }

            // Register pending request before sending
            let network = network_manager.read().await;
            let (request_id, response_rx) = network.register_request(peer_addr);
            drop(network); // Release read lock before async wait

            // Create GetFilteredBlock message with request_id
            use crate::network::protocol::FilterPreferences;
            let get_filtered_block_msg = GetFilteredBlockMessage {
                request_id,
                block_hash,
                filter_preferences: FilterPreferences {
                    filter_ordinals: true,
                    filter_dust: true,
                    filter_brc20: true,
                    min_output_value: 546, // Default dust threshold
                },
                include_bip158_filter: true,
            };

            // Serialize message using protocol adapter (handles TCP vs Iroh format)
            let wire_format = serialize_get_filtered_block(&get_filtered_block_msg)
                .map_err(|e| blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                    format!("Failed to serialize GetFilteredBlock: {e}")
                ))?;

            // Send message to peer via NetworkManager
            {
                let network = network_manager.read().await;
                network.send_to_peer(peer_addr, wire_format).await
                    .map_err(|e| blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                        format!("Failed to send GetFilteredBlock to peer {peer_addr}: {e}")
                    ))?;
            }

            // Await response with timeout (from config)
            let timeout_seconds = {
                let network = network_manager.read().await;
                network
                    .request_timeout_config()
                    .utxo_commitment_request_timeout_seconds
            };
            tokio::select! {
                result = response_rx => {
                    match result {
                        Ok(response_data) => {
                            // Deserialize FilteredBlock response
                            use crate::network::protocol::{ProtocolMessage, ProtocolParser};
                            let parsed = ProtocolParser::parse_message(&response_data)
                                .map_err(|e| blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                                    format!("Failed to parse FilteredBlock response: {e}")
                                ))?;

                            match parsed {
                                ProtocolMessage::FilteredBlock(filtered_block_msg) => {
                                    // Convert to FilteredBlock
                                    // Use header from message if available, otherwise construct from commitment
                                    let header = if filtered_block_msg.header.version != 0
                                        || filtered_block_msg.header.prev_block_hash != [0; 32] {
                                        // Use provided header
                                        filtered_block_msg.header.clone()
                                    } else {
                                        // Construct minimal header from commitment data
                                        BlockHeader {
                                            version: 1,
                                            prev_block_hash: [0; 32], // Not available in commitment
                                            merkle_root: filtered_block_msg.commitment.merkle_root,
                                            timestamp: 0, // Not available in commitment
                                            bits: 0, // Not available in commitment
                                            nonce: 0, // Not available in commitment
                                        }
                                    };
                                    let filtered_block = FilteredBlock {
                                        header,
                                        commitment: blvm_protocol::utxo_commitments::data_structures::UtxoCommitment {
                                            merkle_root: filtered_block_msg.commitment.merkle_root,
                                            total_supply: filtered_block_msg.commitment.total_supply,
                                            utxo_count: filtered_block_msg.commitment.utxo_count,
                                            block_height: filtered_block_msg.commitment.block_height,
                                            block_hash: filtered_block_msg.commitment.block_hash,
                                        },
                                        transactions: filtered_block_msg.transactions.clone(),
                                        transaction_indices: (0..filtered_block_msg.transactions.len() as u32).collect(),
                                        spam_summary: {
                                            // Convert network::protocol::SpamSummary to blvm_protocol::SpamSummary
                                            let network_summary = &filtered_block_msg.spam_summary;
                                            blvm_protocol::spam_filter::SpamSummary {
                                                filtered_count: network_summary.filtered_count,
                                                filtered_size: network_summary.filtered_size,
                                                by_type: blvm_protocol::spam_filter::SpamBreakdown {
                                                    ordinals: network_summary.by_type.ordinals,
                                                    inscriptions: network_summary.by_type.inscriptions,
                                                    dust: network_summary.by_type.dust,
                                                    brc20: network_summary.by_type.brc20,
                                                },
                                            }
                                        }
                                    };
                                    Ok(filtered_block)
                                }
                                _ => Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                                    "Unexpected response type: expected FilteredBlock".to_string()
                                ))
                            }
                        }
                        Err(_) => Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                            "Response channel closed".to_string()
                        ))
                    }
                }
                _ = tokio::time::sleep(tokio::time::Duration::from_secs(timeout_seconds)) => {
                    // Timeout - cleanup request - drop RwLock before Mutex lock
                    {
                        let pending_requests_arc = {
                            let network = network_manager.read().await;
                            Arc::clone(network.pending_requests())
                        };
                        let mut pending = pending_requests_arc.lock().await;
                        pending.remove(&request_id);
                    }
                    Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                        format!("Request timeout: no response received within {timeout_seconds} seconds")
                    ))
                }
            }
        })
    }

    /// Request full block from a peer (with witnesses)
    ///
    /// Uses GetData protocol message to request full block.
    /// Returns block with witnesses for complete validation.
    fn request_full_block(
        &self,
        peer_id: &str,
        block_hash: Hash,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<
                    Output = UtxoCommitmentResult<
                        blvm_protocol::utxo_commitments::network_integration::FullBlock,
                    >,
                > + Send
                + '_,
        >,
    > {
        let network_manager = self.network_manager.clone();
        let peer_id = peer_id.to_string();

        Box::pin(async move {
            use crate::network::protocol::{
                GetDataMessage, InventoryVector, ProtocolMessage, ProtocolParser,
            };
            use blvm_protocol::utxo_commitments::data_structures::UtxoCommitment;
            use blvm_protocol::utxo_commitments::network_integration::FullBlock;

            // Parse peer address
            let peer_addr = if peer_id.starts_with("tcp:") {
                peer_id
                    .strip_prefix("tcp:")
                    .and_then(|s| s.parse::<std::net::SocketAddr>().ok())
                    .ok_or_else(|| blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                        format!("Invalid TCP peer address: {peer_id}")
                    ))?
            } else if peer_id.starts_with("iroh:") {
                // For Iroh, we'd need to resolve the pubkey to an address
                // For now, return error - Iroh support can be added later
                return Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                    "Iroh peer addresses not yet supported for full block requests".to_string()
                ));
            } else {
                // Try parsing as direct SocketAddr
                peer_id
                    .parse::<std::net::SocketAddr>()
                    .map_err(|_| blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                        format!("Invalid peer address format: {peer_id}")
                    ))?
            };

            // Register block request before sending GetData
            let block_rx = {
                let network = network_manager.read().await;
                network.register_block_request(peer_addr, block_hash)
            };

            // Create GetData message for block (MSG_BLOCK = 2)
            let get_data_msg = GetDataMessage {
                inventory: vec![InventoryVector {
                    inv_type: 2, // MSG_BLOCK
                    hash: block_hash,
                }],
            };

            // Serialize and send GetData message
            let wire_format = ProtocolParser::serialize_message(&ProtocolMessage::GetData(get_data_msg))
                .map_err(|e| blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                    format!("Failed to serialize GetData: {e}")
                ))?;

            {
                let network = network_manager.read().await;
                network.send_to_peer(peer_addr, wire_format).await
                    .map_err(|e| blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                        format!("Failed to send GetData to peer {peer_addr}: {e}")
                    ))?;
            }

            // Await block response with timeout
            let timeout_seconds = {
                let network = network_manager.read().await;
                network
                    .request_timeout_config()
                    .utxo_commitment_request_timeout_seconds
            };

            tokio::select! {
                result = block_rx => {
                    match result {
                        Ok((block, witnesses)) => {
                            // Return full block with witnesses
                            // Commitment will be computed after validation
                            Ok(FullBlock {
                                block,
                                witnesses,
                            })
                        }
                        Err(_) => Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                            "Block response channel closed".to_string()
                        ))
                    }
                }
                _ = tokio::time::sleep(tokio::time::Duration::from_secs(timeout_seconds)) => {
                    // Timeout - cleanup request
                    {
                        let network = network_manager.read().await;
                        let mut pending = network.pending_block_requests().lock().await;
                        pending.remove(&(peer_addr.ip(), block_hash));
                    }
                    Err(blvm_protocol::utxo_commitments::data_structures::UtxoCommitmentError::SerializationError(
                        format!("Block request timeout: no response received within {timeout_seconds} seconds")
                    ))
                }
            }
        })
    }

    /// Get list of connected peer IDs
    ///
    /// Returns peer IDs in format "tcp:addr" or "iroh:pubkey" depending on transport.
    ///
    /// Sync bridge over async state: on a **multi-thread** Tokio runtime this uses
    /// [`tokio::task::block_in_place`] + [`Handle::block_on`]. On a **current-thread**
    /// runtime, returns an empty list (callers that need peers should run on a
    /// multi-thread runtime or add an async API). With no runtime, opens a
    /// short-lived multi-thread runtime.
    fn get_peer_ids(&self) -> Vec<String> {
        use tokio::runtime::{Handle, RuntimeFlavor};
        use tokio::task::block_in_place;

        let nm = Arc::clone(&self.network_manager);
        match Handle::try_current() {
            Ok(handle) => match handle.runtime_flavor() {
                RuntimeFlavor::CurrentThread => vec![],
                _ => block_in_place(|| handle.block_on(collect_utxo_peer_tcp_ids(nm))),
            },
            Err(_) => match tokio::runtime::Builder::new_multi_thread()
                .enable_all()
                .worker_threads(2)
                .build()
            {
                Ok(rt) => rt.block_on(collect_utxo_peer_tcp_ids(nm)),
                Err(_) => vec![],
            },
        }
    }
}

/// Additional methods on UtxoCommitmentsClient (not part of the trait).
/// request_utxo_proof returns raw proof bytes - deserialize to MerkleProof in verification code.
#[cfg(feature = "utxo-commitments")]
impl UtxoCommitmentsClient {
    /// Request UTXO proof from a peer
    ///
    /// Sends GetUTXOProof message and awaits UTXOProof response.
    /// Returns (UTXO, proof_bytes). Proof bytes can be deserialized to sparse_merkle_tree::MerkleProof
    /// by verification code that has the sparse-merkle-tree dependency.
    /// Works with both TCP and Iroh transports automatically.
    pub fn request_utxo_proof(
        &self,
        peer_id: &str,
        tx_hash: Hash,
        output_index: u32,
        block_height: Natural,
        block_hash: Hash,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<
                    Output = Result<(blvm_protocol::types::UTXO, Vec<u8>), anyhow::Error>,
                > + Send
                + '_,
        >,
    > {
        let network_manager = self.network_manager.clone();
        let peer_id = peer_id.to_string();

        Box::pin(async move {
            // Parse peer address (similar to request_utxo_set)
            let peer_addr_opt: Option<(
                std::net::SocketAddr,
                Option<crate::network::transport::TransportAddr>,
            )> = if peer_id.starts_with("tcp:") {
                peer_id
                    .strip_prefix("tcp:")
                    .and_then(|s| s.parse::<std::net::SocketAddr>().ok())
                    .map(|addr| (addr, None))
            } else if peer_id.starts_with("iroh:") {
                #[cfg(feature = "iroh")]
                {
                    peer_id
                        .strip_prefix("iroh:")
                        .and_then(|s| hex::decode(s).ok())
                        .and_then(|bytes| {
                            if bytes.len() == 32 {
                                Some(crate::network::transport::TransportAddr::Iroh(
                                    bytes.try_into().unwrap(),
                                ))
                            } else {
                                None
                            }
                        })
                        .map(|addr| (std::net::SocketAddr::from(([0, 0, 0, 0], 0)), Some(addr)))
                }
                #[cfg(not(feature = "iroh"))]
                {
                    None
                }
            } else {
                // Try parsing as direct SocketAddr
                peer_id
                    .parse::<std::net::SocketAddr>()
                    .ok()
                    .map(|addr| (addr, None))
            };

            let peer_addr = peer_addr_opt
                .ok_or_else(|| anyhow::anyhow!("Invalid peer ID: {}", peer_id))?
                .0;

            // Register pending request
            let (request_id, response_rx) = {
                let network = network_manager.read().await;
                network.register_request(peer_addr)
            };

            // Create GetUTXOProof message
            let get_proof_msg = GetUTXOProofMessage {
                request_id,
                tx_hash,
                output_index,
                block_height,
                block_hash,
            };

            // Serialize and send
            let wire_format = serialize_get_utxo_proof(&get_proof_msg)
                .map_err(|e| anyhow::anyhow!("Failed to serialize GetUTXOProof: {}", e))?;

            {
                let network = network_manager.read().await;
                network
                    .send_to_peer(peer_addr, wire_format)
                    .await
                    .map_err(|e| {
                        anyhow::anyhow!("Failed to send GetUTXOProof to peer {}: {}", peer_addr, e)
                    })?;
            }

            // Await response
            let timeout_seconds = {
                let network = network_manager.read().await;
                network
                    .request_timeout_config()
                    .utxo_commitment_request_timeout_seconds
            };

            tokio::select! {
                result = response_rx => {
                    match result {
                        Ok(response_data) => {
                            let proof_msg = deserialize_utxo_proof(&response_data)
                                .map_err(|e| anyhow::anyhow!("Failed to parse UTXOProof response: {}", e))?;

                            // Reconstruct UTXO; proof bytes passed through for caller to deserialize
                            let utxo = blvm_protocol::types::UTXO {
                                value: proof_msg.value,
                                script_pubkey: proof_msg.script_pubkey.into(),
                                height: proof_msg.height,
                                is_coinbase: proof_msg.is_coinbase,
                            };

                            Ok((utxo, proof_msg.proof))
                        }
                        Err(_) => Err(anyhow::anyhow!("Response channel closed"))
                    }
                }
                _ = tokio::time::sleep(tokio::time::Duration::from_secs(timeout_seconds)) => {
                    // Cleanup on timeout
                    {
                        let pending_requests_arc = {
                            let network = network_manager.read().await;
                            Arc::clone(network.pending_requests())
                        };
                        let mut pending = pending_requests_arc.lock().await;
                        pending.remove(&request_id);
                    }
                    Err(anyhow::anyhow!("Request timeout: no response received within {} seconds", timeout_seconds))
                }
            }
        })
    }
}