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
//! Commitment transaction builder
//!
//! Builds transactions for CSV commitment with:
//! - UTXO coin selection and Tapret/Opret commitment construction
//! - Real Taproot tree building with proper nonce positioning
//! - Fee estimation and dust protection
//! - Proper handling of plain P2TR (key-path) vs Tapret (script-path) inputs

#[allow(unused_imports)]
use bitcoin::hashes::Hash as _;
use bitcoin::{
    absolute::LockTime, consensus::encode::serialize as tx_serialize, Address, Amount, ScriptBuf,
    Sequence, TxIn, TxOut, Txid,
};

use crate::tapret::TapretCommitment;
use crate::wallet::{Bip86Path, SealWallet, WalletUtxo};

/// Dust threshold for P2TR outputs (BIP-0448: 330 sat for P2TR)
const P2TR_DUST_SAT: u64 = 330;

/// RBF sequence number (BIP-0125)
const RBF_SEQUENCE: Sequence = Sequence::ENABLE_RBF_NO_LOCKTIME;

/// Configuration for building commitment transactions
pub struct CommitmentTxBuilder {
    /// Fee rate in sat/vB
    pub fee_rate_sat_per_vb: u64,
    /// Protocol ID for this commitment
    pub protocol_id: [u8; 32],
    /// Maximum fee rate to prevent overpaying
    pub max_fee_rate_sat_per_vb: u64,
    /// Dust threshold (satoshi)
    pub dust_threshold_sat: u64,
}

impl CommitmentTxBuilder {
    /// Create a new transaction builder
    pub fn new(protocol_id: [u8; 32], fee_rate_sat_per_vb: u64) -> Self {
        Self {
            fee_rate_sat_per_vb,
            protocol_id,
            max_fee_rate_sat_per_vb: fee_rate_sat_per_vb * 10,
            dust_threshold_sat: P2TR_DUST_SAT,
        }
    }

    /// Set the fee rate
    pub fn with_fee_rate(mut self, fee_rate: u64) -> Self {
        self.fee_rate_sat_per_vb = fee_rate;
        self
    }

    /// Set maximum fee rate (prevents overpaying during fee spikes)
    pub fn with_max_fee_rate(mut self, max_fee: u64) -> Self {
        self.max_fee_rate_sat_per_vb = max_fee;
        self
    }

    /// Estimate virtual bytes for a commitment transaction
    pub fn estimate_vbytes(input_count: usize, output_count: usize) -> usize {
        let base = 10;
        let per_input = 58;
        let per_output = 43;
        base + input_count * per_input + output_count * per_output
    }

    /// Calculate required fee
    pub fn calculate_fee(&self, input_count: usize, output_count: usize) -> u64 {
        let vbytes = Self::estimate_vbytes(input_count, output_count);
        let fee = vbytes as u64 * self.fee_rate_sat_per_vb;
        let max_fee = (vbytes as u64) * self.max_fee_rate_sat_per_vb;
        fee.min(max_fee)
    }

    /// Check if an output amount is above the dust threshold
    pub fn is_above_dust(&self, value_sat: u64) -> bool {
        value_sat >= self.dust_threshold_sat
    }

    /// Build a complete commitment transaction
    ///
    /// This handles two cases:
    /// 1. **Plain P2TR input** (funded externally to a simple P2TR address):
    ///    The input is spent via key-path using the tweaked keypair.
    ///    The output uses a Tapret commitment with the same internal key.
    ///
    /// 2. **Tapret input** (previously committed):
    ///    The input is spent via script-path using the tapret leaf.
    ///
    /// For freshly funded UTXOs (case 1), this is the standard flow.
    pub fn build_commitment_tx(
        &self,
        wallet: &SealWallet,
        seal_utxo: &WalletUtxo,
        commitment_hash: [u8; 32],
        _change_path: Option<&Bip86Path>,
    ) -> Result<CommitmentTxResult, TxBuilderError> {
        let secp = wallet.secp();
        let seal_key = wallet.derive_key(&seal_utxo.path)?;

        // Calculate fee (1 input, 1 output)
        let fee = self.calculate_fee(1, 1);
        let commitment_value_sat = seal_utxo.amount_sat.saturating_sub(fee);

        if !self.is_above_dust(commitment_value_sat) {
            return Err(TxBuilderError::OutputBelowDust {
                value: commitment_value_sat,
                dust: self.dust_threshold_sat,
            });
        }

        // Build Tapret commitment output
        let tapret = TapretCommitment::new(
            self.protocol_id,
            csv_adapter_core::hash::Hash::new(commitment_hash),
        );
        let leaf_script = tapret.leaf_script();

        // Build Taproot tree with single tapret leaf at depth 0
        // Use the internal key (before tweaking) from the derived seal key
        let internal_xonly = seal_key.internal_xonly;
        let builder = bitcoin::taproot::TaprootBuilder::new();
        let builder = builder
            .add_leaf(0, leaf_script.clone())
            .map_err(|e| TxBuilderError::TaprootBuildFailed(format!("{:?}", e)))?;

        let taproot_spend_info = builder
            .finalize(secp, internal_xonly)
            .map_err(|e| TxBuilderError::TaprootBuildFailed(format!("{:?}", e)))?;

        let output_key = taproot_spend_info.output_key();
        let address = Address::p2tr_tweaked(output_key, wallet.network());

        // Build unsigned transaction
        let input = TxIn {
            previous_output: seal_utxo.outpoint,
            script_sig: ScriptBuf::new(),
            sequence: RBF_SEQUENCE,
            witness: bitcoin::Witness::new(),
        };

        let outputs = vec![TxOut {
            value: commitment_value_sat,
            script_pubkey: address.script_pubkey(),
        }];

        let unsigned_tx = bitcoin::Transaction {
            version: 2,
            lock_time: LockTime::ZERO,
            input: vec![input],
            output: outputs,
        };

        // Sign via key-path spending: the input UTXO was sent to seal_key.address
        // which is a simple P2TR with no script tree.
        // Sign with the tweaked keypair matching the input's scriptPubKey.
        let sighash = bitcoin::sighash::SighashCache::new(&unsigned_tx)
            .taproot_key_spend_signature_hash(
                0,
                &bitcoin::sighash::Prevouts::All(&[&bitcoin::TxOut {
                    value: seal_utxo.amount_sat,
                    script_pubkey: seal_key.address.script_pubkey(),
                }]),
                bitcoin::sighash::TapSighashType::Default,
            )
            .map_err(|e| TxBuilderError::SighashFailed(format!("{}", e)))?;

        let mut sighash_bytes = [0u8; 32];
        sighash_bytes.copy_from_slice(sighash.as_ref());

        // Sign with the tweaked keypair for key-path spending
        let schnorr_sig = wallet
            .sign_taproot_keypath(&seal_utxo.path, &sighash_bytes)
            .map_err(|e| TxBuilderError::WalletError(e.to_string()))?;

        // Build the witness: [64-byte Schnorr signature]
        let witness = bitcoin::Witness::from_slice(&[schnorr_sig.as_slice()]);

        // Create signed transaction
        let mut signed_tx = unsigned_tx.clone();
        signed_tx.input[0].witness = witness;

        let raw_tx = tx_serialize(&signed_tx);
        let txid = signed_tx.txid();

        let script_pubkey = address.script_pubkey();
        Ok(CommitmentTxResult {
            tx: signed_tx,
            txid,
            raw_tx,
            tapret_output: TapretOutput {
                address,
                script_pubkey,
                value: Amount::from_sat(commitment_value_sat),
                taproot_spend_info,
                leaf_script,
                amount_sat: commitment_value_sat,
            },
            change_output: None,
            fee_sat: fee,
            input_value_sat: seal_utxo.amount_sat,
            commitment_output_index: 0,
        })
    }

    /// Build legacy commitment data (for backward compatibility)
    pub fn build_commitment_data(
        &self,
        commitment: csv_adapter_core::hash::Hash,
    ) -> CommitmentData {
        let tapret = TapretCommitment::new(self.protocol_id, commitment);
        CommitmentData::Tapret {
            script: tapret.leaf_script(),
            payload: tapret.payload(),
        }
    }
}

/// Tapret commitment output
#[derive(Clone, Debug)]
pub struct TapretOutput {
    pub address: Address,
    pub script_pubkey: ScriptBuf,
    pub value: Amount,
    pub taproot_spend_info: bitcoin::taproot::TaprootSpendInfo,
    pub leaf_script: ScriptBuf,
    pub amount_sat: u64,
}

/// Change output
#[derive(Clone, Debug)]
pub struct ChangeOutput {
    pub address: Address,
    pub value: Amount,
    pub derivation_path: Bip86Path,
}

/// Transaction builder output
#[derive(Clone, Debug)]
pub struct CommitmentTxResult {
    pub tx: bitcoin::Transaction,
    pub txid: Txid,
    pub raw_tx: Vec<u8>,
    pub tapret_output: TapretOutput,
    pub change_output: Option<ChangeOutput>,
    pub fee_sat: u64,
    pub input_value_sat: u64,
    pub commitment_output_index: u32,
}

impl CommitmentTxResult {
    pub fn commitment_output_index(&self) -> u32 {
        self.commitment_output_index
    }
}

/// Commitment data output (for backward compatibility)
pub enum CommitmentData {
    Tapret {
        script: ScriptBuf,
        payload: [u8; 64],
    },
    Opret {
        script: ScriptBuf,
    },
}

impl CommitmentData {
    pub fn script(&self) -> &ScriptBuf {
        match self {
            CommitmentData::Tapret { script, .. } => script,
            CommitmentData::Opret { script } => script,
        }
    }
}

/// Transaction builder errors
#[derive(Debug, thiserror::Error)]
pub enum TxBuilderError {
    #[error("Taproot build failed: {0}")]
    TaprootBuildFailed(String),

    #[error("Output value {value} sat is below dust threshold {dust} sat")]
    OutputBelowDust { value: u64, dust: u64 },

    #[error("Sighash computation failed: {0}")]
    SighashFailed(String),

    #[error("Wallet error: {0}")]
    WalletError(String),

    #[error("Insufficient funds: available {available} sat, required {required} sat")]
    InsufficientFunds { available: u64, required: u64 },
}

impl From<crate::wallet::WalletError> for TxBuilderError {
    fn from(e: crate::wallet::WalletError) -> Self {
        TxBuilderError::WalletError(e.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bitcoin::{Network, OutPoint};

    fn make_utxo(path: Bip86Path, amount: u64) -> WalletUtxo {
        let txid = Txid::from_raw_hash(bitcoin::hashes::sha256d::Hash::from_byte_array([0xAB; 32]));
        WalletUtxo {
            outpoint: OutPoint::new(txid, 0),
            amount_sat: amount,
            path,
            reserved: false,
            reserved_for: None,
        }
    }

    #[test]
    fn test_builder_creation() {
        let builder = CommitmentTxBuilder::new([1u8; 32], 10);
        assert_eq!(builder.fee_rate_sat_per_vb, 10);
        assert_eq!(builder.protocol_id, [1u8; 32]);
    }

    #[test]
    fn test_builder_with_fee_rate() {
        let builder = CommitmentTxBuilder::new([1u8; 32], 5).with_fee_rate(20);
        assert_eq!(builder.fee_rate_sat_per_vb, 20);
    }

    #[test]
    fn test_vbyte_estimation() {
        let vbytes = CommitmentTxBuilder::estimate_vbytes(1, 1);
        assert!(vbytes > 50);
        assert!(vbytes < 300);
    }

    #[test]
    fn test_fee_calculation() {
        let builder = CommitmentTxBuilder::new([1u8; 32], 10);
        let fee = builder.calculate_fee(1, 1);
        let expected_vbytes = CommitmentTxBuilder::estimate_vbytes(1, 1);
        assert_eq!(fee, expected_vbytes as u64 * 10);
    }

    #[test]
    fn test_max_fee_rate_cap() {
        let builder = CommitmentTxBuilder::new([1u8; 32], 1000).with_max_fee_rate(10);
        let fee = builder.calculate_fee(1, 1);
        let vbytes = CommitmentTxBuilder::estimate_vbytes(1, 1);
        assert_eq!(fee, vbytes as u64 * 10);
    }

    #[test]
    fn test_dust_check() {
        let builder = CommitmentTxBuilder::new([1u8; 32], 10);
        assert!(builder.is_above_dust(P2TR_DUST_SAT));
        assert!(builder.is_above_dust(2000));
        assert!(!builder.is_above_dust(100));
    }

    #[test]
    fn test_build_commitment_data() {
        let builder = CommitmentTxBuilder::new([1u8; 32], 10);
        let data = builder.build_commitment_data(csv_adapter_core::hash::Hash::new([2u8; 32]));
        match data {
            CommitmentData::Tapret { script, payload } => {
                assert_eq!(payload[..32], [1u8; 32]);
                assert!(script.is_op_return());
            }
            _ => panic!("Expected Tapret"),
        }
    }

    #[test]
    fn test_build_commitment_tx() {
        let wallet = SealWallet::generate_random(Network::Regtest);
        let path = Bip86Path::external(0, 0);
        let seal_utxo = make_utxo(path.clone(), 1_000_000);
        wallet.add_utxo(seal_utxo.outpoint, seal_utxo.amount_sat, path);

        let builder = CommitmentTxBuilder::new([0xAB; 32], 10);
        let result = builder
            .build_commitment_tx(&wallet, &seal_utxo, [0xCD; 32], None)
            .expect("tx build should succeed");

        assert!(result.fee_sat > 0);
        assert_eq!(result.input_value_sat, 1_000_000);
        assert_eq!(result.raw_tx.len(), result.tx.size());
        assert_eq!(
            result.tapret_output.amount_sat,
            result.input_value_sat - result.fee_sat
        );
    }

    #[test]
    fn test_tx_has_witness() {
        let wallet = SealWallet::generate_random(Network::Regtest);
        let path = Bip86Path::external(0, 0);
        let seal_utxo = make_utxo(path.clone(), 500_000);
        wallet.add_utxo(seal_utxo.outpoint, seal_utxo.amount_sat, path);

        let builder = CommitmentTxBuilder::new([0xAB; 32], 10);
        let result = builder
            .build_commitment_tx(&wallet, &seal_utxo, [0xCD; 32], None)
            .expect("tx build should succeed");

        // Transaction should have valid witness data
        assert!(!result.tx.input[0].witness.is_empty());
        assert!(result.raw_tx.len() > 0);
    }

    #[test]
    fn test_dust_prevention() {
        let wallet = SealWallet::generate_random(Network::Regtest);
        let path = Bip86Path::external(0, 0);
        let seal_utxo = make_utxo(path.clone(), 500);
        wallet.add_utxo(seal_utxo.outpoint, seal_utxo.amount_sat, path);

        let builder = CommitmentTxBuilder::new([0xAB; 32], 10);
        let result = builder.build_commitment_tx(&wallet, &seal_utxo, [0xCD; 32], None);

        // Should fail due to dust or insufficient funds
        assert!(result.is_err());
    }
}