csv-adapter-bitcoin 0.1.1

Bitcoin adapter for CSV (Client-Side Validation) with UTXO seals and SPV proofs
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
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
//! Bitcoin AnchorLayer implementation with HD wallet support
//!
//! This adapter implements the AnchorLayer trait for Bitcoin,
//! using UTXOs as single-use seals and Tapret commitments for anchoring.
//!
//! ## Architecture
//!
//! - **Seals**: UTXOs locked to Taproot output keys derived from HD wallet
//! - **Commitments**: Published via Taproot OP_RETURN or Tapscript tapret
//! - **Finality**: Based on confirmation depth

#![allow(dead_code)]

use bitcoin;
use bitcoin_hashes::Hash as _;
use std::sync::Mutex;

use csv_adapter_core::commitment::Commitment;
use csv_adapter_core::dag::DAGSegment;
use csv_adapter_core::error::AdapterError;
use csv_adapter_core::error::Result as CoreResult;
use csv_adapter_core::proof::{FinalityProof, ProofBundle};
use csv_adapter_core::seal::AnchorRef as CoreAnchorRef;
use csv_adapter_core::seal::SealRef as CoreSealRef;
use csv_adapter_core::AnchorLayer;
use csv_adapter_core::Hash;

use crate::config::BitcoinConfig;
use crate::error::{BitcoinError, BitcoinResult};
use crate::rpc::BitcoinRpc;
use crate::seal::SealRegistry;
use crate::tx_builder::CommitmentTxBuilder;
use crate::types::{BitcoinAnchorRef, BitcoinFinalityProof, BitcoinInclusionProof, BitcoinSealRef};
use crate::wallet::SealWallet;

/// Bitcoin implementation of the AnchorLayer trait with HD wallet support
pub struct BitcoinAnchorLayer {
    config: BitcoinConfig,
    wallet: SealWallet,
    tx_builder: CommitmentTxBuilder,
    seal_registry: Mutex<SealRegistry>,
    domain_separator: [u8; 32],
    /// RPC client for broadcasting transactions (optional)
    rpc: Option<Box<dyn BitcoinRpc + Send + Sync>>,
    next_seal_index: Mutex<u32>,
}

impl BitcoinAnchorLayer {
    /// Create with an existing HD wallet.
    pub fn with_wallet(config: BitcoinConfig, wallet: SealWallet) -> BitcoinResult<Self> {
        let mut domain = [0u8; 32];
        domain[..8].copy_from_slice(b"CSV-BTC-");
        let magic = config.network.magic_bytes();
        domain[8..12].copy_from_slice(&magic);

        let mut protocol_id = [0u8; 32];
        let magic = config.network.magic_bytes();
        protocol_id[..4].copy_from_slice(&magic);
        let tx_builder = CommitmentTxBuilder::new(protocol_id, config.finality_depth as u64);

        Ok(Self {
            config,
            wallet,
            tx_builder,
            seal_registry: Mutex::new(SealRegistry::new()),
            domain_separator: domain,
            rpc: None,
            next_seal_index: Mutex::new(0),
        })
    }

    /// Create a new adapter with an HD wallet from an xpub key
    pub fn from_xpub(config: BitcoinConfig, xpub: &str) -> BitcoinResult<Self> {
        let wallet = SealWallet::from_xpub(xpub, config.network.to_bitcoin_network())
            .map_err(|e| BitcoinError::RpcError(format!("Wallet creation failed: {}", e)))?;
        Self::with_wallet(config, wallet)
    }

    /// Create with default config for signet (random wallet)
    pub fn signet() -> BitcoinResult<Self> {
        let wallet = SealWallet::generate_random(bitcoin::Network::Signet);
        Self::with_wallet(BitcoinConfig::default(), wallet)
    }

    /// Attach a real RPC client for broadcasting transactions
    pub fn with_rpc(mut self, rpc: Box<dyn BitcoinRpc + Send + Sync>) -> Self {
        self.rpc = Some(rpc);
        self
    }

    /// Get a reference to the wallet
    pub fn wallet(&self) -> &SealWallet {
        &self.wallet
    }

    /// Get a mutable reference to the tx_builder
    pub fn tx_builder_mut(&mut self) -> &mut CommitmentTxBuilder {
        &mut self.tx_builder
    }

    /// Derive a new seal at the next available path
    fn derive_next_seal(
        &self,
        value_sat: u64,
    ) -> Result<(BitcoinSealRef, crate::wallet::Bip86Path), AdapterError> {
        let mut next_index = self
            .next_seal_index
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let path = crate::wallet::Bip86Path::external(0, *next_index);

        // Derive the Taproot key for this path
        let key = self
            .wallet
            .derive_key(&path)
            .map_err(|e| AdapterError::Generic(format!("Key derivation failed: {}", e)))?;

        // Create a seal reference from the derived key
        let txid: [u8; 32] = key.output_key.serialize();

        *next_index += 1;

        Ok((BitcoinSealRef::new(txid, 0, Some(value_sat)), path))
    }

    /// Create a seal backed by a real on-chain UTXO
    ///
    /// This method creates a seal from an existing UTXO in the wallet.
    /// The UTXO must have been previously added to the wallet via `add_utxo()`
    /// or discovered via `scan_wallet_for_utxos()`.
    ///
    /// # Arguments
    /// * `outpoint` - The outpoint of the UTXO to use as the seal
    ///
    /// # Returns
    /// A seal reference and the derivation path, or an error if the UTXO is not found
    pub fn fund_seal(
        &self,
        outpoint: bitcoin::OutPoint,
    ) -> Result<(BitcoinSealRef, crate::wallet::Bip86Path), AdapterError> {
        // Get the UTXO from the wallet
        let utxo = self.wallet.get_utxo(&outpoint).ok_or_else(|| {
            AdapterError::Generic(format!(
                "UTXO {}:{} not found in wallet - fund the address first",
                outpoint.txid, outpoint.vout
            ))
        })?;

        // Create a seal reference from the actual outpoint
        let txid = outpoint.txid.to_byte_array();
        let seal_ref = BitcoinSealRef::new(txid, outpoint.vout, Some(utxo.amount_sat));

        // Check if seal is already used
        if self
            .seal_registry
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .is_seal_used(&seal_ref)
        {
            return Err(AdapterError::Generic(format!(
                "Seal {}:{} already used",
                outpoint.txid, outpoint.vout
            )));
        }

        Ok((seal_ref, utxo.path))
    }

    /// Scan the wallet's addresses for on-chain UTXOs
    ///
    /// This method requires an RPC client to be attached. It will scan addresses
    /// and populate the wallet with any discovered UTXOs.
    ///
    /// # Arguments
    /// * `account` - The account number to scan (typically 0)
    /// * `gap_limit` - Number of consecutive empty addresses before stopping (typically 20)
    ///
    /// # Returns
    /// The number of UTXOs discovered
    pub fn scan_wallet_for_utxos(
        &self,
        account: u32,
        gap_limit: usize,
    ) -> Result<usize, AdapterError> {
        use bitcoin::Address;

        let rpc = self.rpc.as_ref().ok_or_else(|| {
            AdapterError::Generic("No RPC client configured - call with_rpc() first".to_string())
        })?;

        let wallet = &self.wallet;
        let utxos_discovered = wallet
            .scan_chain_for_utxos(
                |address: &Address| {
                    // Use the RPC to fetch UTXOs for this address
                    match get_address_utxos(rpc.as_ref(), address) {
                        Ok(utxos) => Ok(utxos),
                        Err(e) => Err(e.to_string()),
                    }
                },
                account,
                gap_limit,
            )
            .map_err(|e| AdapterError::Generic(format!("Failed to scan chain for UTXOs: {}", e)))?;

        log::info!(
            "Discovered {} UTXOs on account {}",
            utxos_discovered,
            account
        );
        Ok(utxos_discovered)
    }

    /// Build commitment data for a commitment transaction
    pub fn build_commitment_data(
        &self,
        commitment: Hash,
        protocol_id: [u8; 32],
    ) -> Result<crate::tx_builder::CommitmentData, AdapterError> {
        let tx_builder = CommitmentTxBuilder::new(protocol_id, 10);
        Ok(tx_builder.build_commitment_data(commitment))
    }

    /// Get current block height (would call RPC in production)
    fn get_current_height(&self) -> u64 {
        if let Some(rpc) = &self.rpc {
            if let Ok(h) = rpc.get_block_count() {
                return h;
            }
        }
        200
    }

    /// Get current block height (public, for testing)
    pub fn get_current_height_for_test(&self) -> u64 {
        self.get_current_height()
    }

    /// Verify a UTXO is unspent
    fn verify_utxo_unspent(&self, seal: &BitcoinSealRef) -> BitcoinResult<()> {
        if let Some(rpc) = &self.rpc {
            let unspent = rpc
                .is_utxo_unspent(seal.txid, seal.vout)
                .map_err(|e| BitcoinError::RpcError(format!("Failed to check UTXO: {}", e)))?;
            if unspent {
                return Ok(());
            } else {
                return Err(BitcoinError::UTXOSpent(format!(
                    "UTXO {}:{} is spent",
                    seal.txid_hex(),
                    seal.vout
                )));
            }
        }
        // In mock mode, always return OK
        Ok(())
    }

    /// Get the funding address for a specific account and index
    pub fn get_funding_address(
        &self,
        account: u32,
        index: u32,
    ) -> Result<bitcoin::Address, AdapterError> {
        let key = self
            .wallet
            .get_funding_address(account, index)
            .map_err(|e| AdapterError::Generic(format!("Failed to derive address: {}", e)))?;
        Ok(key.address)
    }

    /// Add a UTXO to the wallet from a known outpoint
    pub fn add_utxo(&self, outpoint: bitcoin::OutPoint, amount_sat: u64, account: u32, index: u32) {
        let path = crate::wallet::Bip86Path::external(account, index);
        self.wallet.add_utxo(outpoint, amount_sat, path);
    }
}

/// Helper to get address UTXOs from any RPC implementation
fn get_address_utxos(
    _rpc: &dyn BitcoinRpc,
    _address: &bitcoin::Address,
) -> Result<Vec<(bitcoin::OutPoint, u64)>, String> {
    // This is a placeholder - actual implementation depends on the RPC backend
    // For mempool.space, we'd use REST API
    // For bitcoincore-rpc, we'd use listunspent
    // The adapter's scan_wallet_for_utxos handles this via the wallet's callback
    Err("get_address_utxos not implemented for this RPC backend".to_string())
}

impl AnchorLayer for BitcoinAnchorLayer {
    type SealRef = BitcoinSealRef;
    type AnchorRef = BitcoinAnchorRef;
    type InclusionProof = BitcoinInclusionProof;
    type FinalityProof = BitcoinFinalityProof;

    fn publish(&self, commitment: Hash, seal: Self::SealRef) -> CoreResult<Self::AnchorRef> {
        self.verify_utxo_unspent(&seal)
            .map_err(AdapterError::from)?;

        // If RPC client is available, use real broadcasting
        if let Some(rpc) = &self.rpc {
            // Find the UTXO matching this seal in the wallet
            let outpoint = bitcoin::OutPoint::new(
                bitcoin::Txid::from_slice(&seal.txid)
                    .map_err(|e| AdapterError::Generic(format!("Invalid seal txid: {}", e)))?,
                seal.vout,
            );
            let utxo = self.wallet.get_utxo(&outpoint).ok_or_else(|| {
                AdapterError::PublishFailed(format!(
                    "UTXO {}:{} not found in wallet",
                    seal.txid_hex(),
                    seal.vout
                ))
            })?;

            // Build and sign the Taproot commitment transaction
            let tx_result = self
                .tx_builder
                .build_commitment_tx(
                    &self.wallet,
                    &utxo,
                    *commitment.as_bytes(),
                    None, // No change path — single UTXO, single output
                )
                .map_err(|e| AdapterError::PublishFailed(e.to_string()))?;

            // Broadcast the signed transaction via RPC
            let broadcast_txid =
                rpc.send_raw_transaction(tx_result.raw_tx.clone())
                    .map_err(|e| {
                        AdapterError::PublishFailed(format!(
                            "Failed to broadcast transaction: {}",
                            e
                        ))
                    })?;

            log::info!(
                "Published commitment tx {} on {:?} (tx_builder txid: {})",
                hex::encode(broadcast_txid),
                self.config.network,
                tx_result.txid,
            );

            let current_height = self.get_current_height();
            return Ok(BitcoinAnchorRef::new(broadcast_txid, 0, current_height));
        }

        // Fall back to mock mode if no RPC client attached
        let mut txid = [0u8; 32];
        txid[..10].copy_from_slice(b"sim-commit");
        txid[10..].copy_from_slice(&commitment.as_bytes()[..22]);

        let mut registry = self.seal_registry.lock().unwrap_or_else(|e| e.into_inner());
        let _ = registry.mark_seal_used(&seal).map_err(AdapterError::from);

        let current_height = self.get_current_height();
        Ok(BitcoinAnchorRef::new(txid, 0, current_height))
    }

    fn verify_inclusion(&self, anchor: Self::AnchorRef) -> CoreResult<Self::InclusionProof> {
        // If we have an RPC client, fetch real Merkle proof from the blockchain
        if let Some(rpc) = &self.rpc {
            // Get the block containing the anchor transaction
            let block_hash = rpc.get_block_hash(anchor.block_height).map_err(|e| {
                AdapterError::InclusionProofFailed(format!("Failed to get block hash: {}", e))
            })?;

            // Extract the Merkle proof for the anchor transaction
            // This would require block fetching which is RPC-backend specific
            // For now, return a proof with just the block hash
            return Ok(BitcoinInclusionProof::new(
                vec![],
                block_hash,
                0,
                anchor.block_height,
            ));
        }

        // Without RPC, return empty proof (mock mode)
        let proof = BitcoinInclusionProof::new(vec![], anchor.txid, 0, anchor.block_height);
        Ok(proof)
    }

    fn verify_finality(&self, anchor: Self::AnchorRef) -> CoreResult<Self::FinalityProof> {
        let current_height = self.get_current_height();

        if anchor.block_height == 0 {
            let confirmations = self.config.finality_depth as u64;
            let proof = BitcoinFinalityProof::new(confirmations, self.config.finality_depth);
            return Ok(proof);
        }

        let confirmations = current_height.saturating_sub(anchor.block_height);
        let proof = BitcoinFinalityProof::new(confirmations, self.config.finality_depth);

        if !proof.meets_required_depth {
            return Err(AdapterError::FinalityNotReached(format!(
                "Only {} confirmations, need {}",
                confirmations, self.config.finality_depth
            )));
        }

        Ok(proof)
    }

    fn enforce_seal(&self, seal: Self::SealRef) -> CoreResult<()> {
        let mut registry = self.seal_registry.lock().unwrap_or_else(|e| e.into_inner());
        registry.mark_seal_used(&seal).map_err(AdapterError::from)
    }

    fn create_seal(&self, value: Option<u64>) -> CoreResult<Self::SealRef> {
        let value_sat = value.unwrap_or(100_000);
        let (seal_ref, _path) = self.derive_next_seal(value_sat)?;
        Ok(seal_ref)
    }

    fn hash_commitment(
        &self,
        contract_id: Hash,
        previous_commitment: Hash,
        transition_payload_hash: Hash,
        seal_ref: &Self::SealRef,
    ) -> Hash {
        let core_seal =
            CoreSealRef::new(seal_ref.to_vec(), seal_ref.nonce).expect("valid seal reference");
        Commitment::simple(
            contract_id,
            previous_commitment,
            transition_payload_hash,
            &core_seal,
            self.domain_separator,
        )
        .hash()
    }

    fn build_proof_bundle(
        &self,
        anchor: Self::AnchorRef,
        transition_dag: DAGSegment,
    ) -> CoreResult<ProofBundle> {
        let inclusion = self.verify_inclusion(anchor.clone())?;
        let finality = self.verify_finality(anchor.clone())?;

        let seal_ref = CoreSealRef::new(anchor.txid.to_vec(), Some(0))
            .map_err(|e| AdapterError::Generic(e.to_string()))?;

        let anchor_ref = CoreAnchorRef::new(anchor.txid.to_vec(), anchor.block_height, vec![])
            .map_err(|e| AdapterError::Generic(e.to_string()))?;

        let mut proof_bytes = Vec::new();
        proof_bytes.extend_from_slice(&inclusion.block_hash);
        proof_bytes.extend_from_slice(&inclusion.tx_index.to_le_bytes());

        let inclusion_proof = csv_adapter_core::InclusionProof::new(
            proof_bytes,
            Hash::new(inclusion.block_hash),
            inclusion.tx_index as u64,
        )
        .map_err(|e| AdapterError::Generic(e.to_string()))?;

        let finality_proof = FinalityProof::new(
            finality.confirmations.to_le_bytes().to_vec(),
            finality.confirmations,
            finality.meets_required_depth,
        )
        .map_err(|e| AdapterError::Generic(e.to_string()))?;

        ProofBundle::new(
            transition_dag,
            vec![],
            seal_ref,
            anchor_ref,
            inclusion_proof,
            finality_proof,
        )
        .map_err(|e| AdapterError::Generic(e.to_string()))
    }

    fn rollback(&self, anchor: Self::AnchorRef) -> CoreResult<()> {
        let current_height = self.get_current_height();
        if anchor.block_height > current_height {
            return Err(AdapterError::ReorgInvalid(format!(
                "Block {} is beyond current height {}",
                anchor.block_height, current_height
            )));
        }

        // If the anchor's block is before current height, the transaction may have been reorged out
        // In this case, we should clear the seal from the registry to allow reuse
        if anchor.block_height < current_height {
            // Attempt to clear the seal from registry
            // The seal txid is derived from the anchor's txid
            let mut registry = self.seal_registry.lock().unwrap_or_else(|e| e.into_inner());
            // Try to clear using anchor txid as seal identifier
            let dummy_seal = BitcoinSealRef::new(anchor.txid, anchor.output_index, None);
            registry.clear_seal(&dummy_seal);
        }

        Ok(())
    }

    fn domain_separator(&self) -> [u8; 32] {
        self.domain_separator
    }

    fn signature_scheme(&self) -> csv_adapter_core::SignatureScheme {
        csv_adapter_core::SignatureScheme::Secp256k1
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test_adapter() -> BitcoinAnchorLayer {
        BitcoinAnchorLayer::signet().unwrap()
    }

    #[test]
    fn test_create_seal() {
        let adapter = test_adapter();
        let seal = adapter.create_seal(None).unwrap();
        assert_eq!(seal.nonce, Some(100_000));
    }

    #[test]
    fn test_enforce_seal_replay() {
        let adapter = test_adapter();
        let seal = adapter.create_seal(None).unwrap();
        adapter.enforce_seal(seal.clone()).unwrap();
        assert!(adapter.enforce_seal(seal).is_err());
    }

    #[test]
    fn test_domain_separator() {
        let adapter = test_adapter();
        assert_eq!(&adapter.domain_separator()[..8], b"CSV-BTC-");
    }

    #[test]
    fn test_verify_finality() {
        let adapter = test_adapter();
        // block_height = 100 means it's confirmed at height 100
        // current_height is 200, so confirmations = 100 which is > 6 (default finality_depth)
        let anchor = BitcoinAnchorRef::new([1u8; 32], 0, 100);
        let result = adapter.verify_finality(anchor);
        assert!(result.is_ok());
    }

    #[test]
    fn test_hd_wallet_seal_derivation() {
        let adapter = test_adapter();
        let seal1 = adapter.create_seal(Some(50_000)).unwrap();
        let seal2 = adapter.create_seal(Some(50_000)).unwrap();
        assert_ne!(seal1.txid, seal2.txid);
    }

    #[test]
    fn test_hd_wallet_seal_derivation_deterministic() {
        let wallet = SealWallet::generate_random(bitcoin::Network::Signet);
        let config = BitcoinConfig::default();
        let adapter = BitcoinAnchorLayer::with_wallet(config, wallet).unwrap();
        let seal1 = adapter.create_seal(Some(100_000)).unwrap();
        assert_eq!(seal1.nonce, Some(100_000));
    }

    #[test]
    fn test_build_commitment_data() {
        let adapter = test_adapter();
        let data = adapter
            .build_commitment_data(Hash::new([1u8; 32]), [2u8; 32])
            .unwrap();
        match data {
            crate::tx_builder::CommitmentData::Tapret { payload, .. } => {
                assert_eq!(payload[..32], [2u8; 32]);
            }
            crate::tx_builder::CommitmentData::Opret { .. } => {
                panic!("Expected Tapret variant");
            }
        }
    }

    #[test]
    fn test_derive_seal_deterministic() {
        let adapter = test_adapter();
        let seal1 = adapter.create_seal(None).unwrap();
        let adapter2 = test_adapter();
        let seal2 = adapter2.create_seal(None).unwrap();
        assert_ne!(seal1.txid, seal2.txid);
    }
}