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
//! Real Bitcoin Signet RPC via mempool.space public REST API
//!
//! This provides a production-ready RPC implementation that talks to
//! the mempool.space Signet REST API — no local Bitcoin Core node needed.
//!
//! Includes automatic retry with exponential backoff for transient failures.
//! Enable the `signet-rest` feature to use this implementation.

use bitcoin::{OutPoint, Txid};
use bitcoin_hashes::Hash as BitcoinHash;
use reqwest::blocking::Client;
use std::thread;
use std::time::{Duration, Instant};

use crate::proofs::extract_merkle_proof_from_block;
use crate::rpc::BitcoinRpc;
use crate::types::BitcoinInclusionProof;

/// Base URL for mempool.space Signet API
pub const MEMPOOL_SIGNET_BASE: &str = "https://mempool.space/signet/api";

/// Maximum number of retries for transient failures
const MAX_RETRIES: u32 = 3;
/// Initial backoff duration before the first retry
const INITIAL_BACKOFF: Duration = Duration::from_secs(2);

/// Real Bitcoin Signet RPC client backed by mempool.space REST API
pub struct MempoolSignetRpc {
    client: Client,
    base_url: String,
}

impl MempoolSignetRpc {
    /// Create a new RPC client for Signet (default: mempool.space)
    pub fn new() -> Self {
        Self::with_url(MEMPOOL_SIGNET_BASE.to_string())
    }

    /// Create with a custom base URL (for self-hosted mempool instances)
    pub fn with_url(base_url: String) -> Self {
        let client = Client::builder()
            .timeout(Duration::from_secs(30))
            .build()
            .expect("Failed to create HTTP client");
        Self { client, base_url }
    }

    /// HTTP GET with automatic retry and exponential backoff
    fn get_with_retry<T: serde::de::DeserializeOwned>(
        &self,
        url: &str,
    ) -> Result<T, Box<dyn std::error::Error + Send + Sync>> {
        let mut last_err = None;
        let mut backoff = INITIAL_BACKOFF;

        for attempt in 0..=MAX_RETRIES {
            if attempt > 0 {
                log::warn!(
                    "Retry {}/{} for {} after {:?} backoff",
                    attempt,
                    MAX_RETRIES,
                    url,
                    backoff
                );
                thread::sleep(backoff);
                backoff *= 2;
            }

            match self.client.get(url).send() {
                Ok(resp) if resp.status().is_success() => {
                    return resp.json::<T>().map_err(|e| e.into());
                }
                Ok(resp) => {
                    last_err = Some(format!("HTTP {} at {}", resp.status(), url).into());
                }
                Err(e) => {
                    last_err = Some(format!("Network error at {}: {}", url, e).into());
                }
            }
        }
        Err(last_err.unwrap_or_else(|| "Max retries exceeded".into()))
    }

    /// HTTP GET text with retry
    fn get_text_with_retry(
        &self,
        url: &str,
    ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
        let mut last_err = None;
        let mut backoff = INITIAL_BACKOFF;

        for attempt in 0..=MAX_RETRIES {
            if attempt > 0 {
                thread::sleep(backoff);
                backoff *= 2;
            }

            match self.client.get(url).send() {
                Ok(resp) if resp.status().is_success() => {
                    return resp.text().map_err(|e| e.into());
                }
                Ok(resp) => {
                    last_err = Some(format!("HTTP {} at {}", resp.status(), url).into());
                }
                Err(e) => {
                    last_err = Some(format!("Network error at {}: {}", url, e).into());
                }
            }
        }
        Err(last_err.unwrap_or_else(|| "Max retries exceeded".into()))
    }

    /// HTTP POST text with retry
    fn post_text_with_retry(
        &self,
        url: &str,
        body: String,
    ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
        let mut last_err = None;
        let mut backoff = INITIAL_BACKOFF;

        for attempt in 0..=MAX_RETRIES {
            if attempt > 0 {
                thread::sleep(backoff);
                backoff *= 2;
            }

            match self
                .client
                .post(url)
                .header("Content-Type", "text/plain")
                .body(body.clone())
                .send()
            {
                Ok(resp) if resp.status().is_success() => {
                    return resp.text().map_err(|e| e.into());
                }
                Ok(resp) => {
                    let status = resp.status();
                    let error_text = resp.text().unwrap_or_default();
                    last_err = Some(format!("HTTP {} at {}: {}", status, url, error_text).into());
                }
                Err(e) => {
                    last_err = Some(format!("Network error at {}: {}", url, e).into());
                }
            }
        }
        Err(last_err.unwrap_or_else(|| "Max retries exceeded".into()))
    }

    /// Get block info (height, tx count, etc.)
    pub fn get_block_info(
        &self,
        block_hash: &str,
    ) -> Result<BlockInfo, Box<dyn std::error::Error + Send + Sync>> {
        let url = format!("{}/block/{}", self.base_url, block_hash);
        self.get_with_retry(&url)
    }

    /// Get transaction status (confirmed/unconfirmed, block height, hash)
    pub fn get_tx_status(
        &self,
        txid: &str,
    ) -> Result<TxStatus, Box<dyn std::error::Error + Send + Sync>> {
        let url = format!("{}/tx/{}/status", self.base_url, txid);
        self.get_with_retry(&url)
    }

    /// Get full transaction details (inputs, outputs, fee, etc.)
    pub fn get_tx(&self, txid: &str) -> Result<TxDetail, Box<dyn std::error::Error + Send + Sync>> {
        let url = format!("{}/tx/{}", self.base_url, txid);
        self.get_with_retry(&url)
    }

    /// Get raw transaction hex
    pub fn get_tx_hex(
        &self,
        txid: &str,
    ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
        let url = format!("{}/tx/{}/hex", self.base_url, txid);
        self.get_text_with_retry(&url)
    }

    /// Get block txids for Merkle proof extraction
    pub fn get_block_txids(
        &self,
        block_hash: &str,
    ) -> Result<Vec<String>, Box<dyn std::error::Error + Send + Sync>> {
        let url = format!("{}/block/{}/txids", self.base_url, block_hash);
        self.get_with_retry(&url)
    }

    /// Wait for transaction to reach required confirmations
    pub fn wait_for_confirmation(
        &self,
        txid: [u8; 32],
        required_confirmations: u64,
        timeout_secs: u64,
    ) -> Result<u64, Box<dyn std::error::Error + Send + Sync>> {
        let txid_hex = hex::encode(txid);
        let start = Instant::now();
        let poll_interval = Duration::from_secs(10);

        loop {
            if start.elapsed() > Duration::from_secs(timeout_secs) {
                return Err("Timeout waiting for confirmation".into());
            }

            match self.get_tx_status(&txid_hex) {
                Ok(status) => {
                    if status.confirmed {
                        let tx_height = status.block_height.unwrap_or(0) as u64;
                        let new_height = self.get_block_count()?;
                        let confirmations = new_height.saturating_sub(tx_height) + 1;

                        if confirmations >= required_confirmations {
                            return Ok(confirmations);
                        }

                        log::info!(
                            "Tx {} has {} confirmations, waiting for {}...",
                            &txid_hex[..16],
                            confirmations,
                            required_confirmations
                        );
                    }
                }
                Err(e) => {
                    log::debug!("Tx {} not found yet: {}", &txid_hex[..16], e);
                }
            }

            thread::sleep(poll_interval);
        }
    }

    /// Extract Merkle proof for a transaction from its containing block
    pub fn extract_merkle_proof(
        &self,
        txid: [u8; 32],
        block_hash: [u8; 32],
    ) -> Result<BitcoinInclusionProof, Box<dyn std::error::Error + Send + Sync>> {
        let block_hash_hex = hex::encode(block_hash);

        let all_txids_hex = self.get_block_txids(&block_hash_hex)?;
        let all_txids: Vec<[u8; 32]> = all_txids_hex
            .iter()
            .map(|t| {
                let decoded = hex::decode(t)?;
                let mut arr = [0u8; 32];
                arr.copy_from_slice(&decoded);
                Ok(arr)
            })
            .collect::<Result<Vec<_>, Box<dyn std::error::Error + Send + Sync>>>()?;

        let block_info = self.get_block_info(&block_hash_hex)?;
        let block_height = block_info.height;

        extract_merkle_proof_from_block(txid, &all_txids, block_hash, block_height as u64)
            .ok_or_else(|| "Failed to extract Merkle proof for txid".into())
    }
}

impl Default for MempoolSignetRpc {
    fn default() -> Self {
        Self::new()
    }
}

impl BitcoinRpc for MempoolSignetRpc {
    fn get_block_count(&self) -> Result<u64, Box<dyn std::error::Error + Send + Sync>> {
        let url = format!("{}/blocks/tip/height", self.base_url);
        self.get_with_retry(&url)
    }

    fn get_block_hash(
        &self,
        height: u64,
    ) -> Result<[u8; 32], Box<dyn std::error::Error + Send + Sync>> {
        let url = format!("{}/block-height/{}", self.base_url, height);
        let hash_hex: String = self.get_text_with_retry(&url)?;
        let hash_bytes = hex::decode(hash_hex.trim())?;
        let mut result = [0u8; 32];
        result.copy_from_slice(&hash_bytes);
        Ok(result)
    }

    fn is_utxo_unspent(
        &self,
        txid: [u8; 32],
        vout: u32,
    ) -> Result<bool, Box<dyn std::error::Error + Send + Sync>> {
        let txid_hex = hex::encode(txid);
        let spend_url = format!("{}/tx/{}/outspend/{}", self.base_url, txid_hex, vout);
        let spend_status: OutSpendStatus = self.get_with_retry(&spend_url)?;
        Ok(!spend_status.spent)
    }

    fn send_raw_transaction(
        &self,
        tx_bytes: Vec<u8>,
    ) -> Result<[u8; 32], Box<dyn std::error::Error + Send + Sync>> {
        let url = format!("{}/tx", self.base_url);
        let tx_hex = hex::encode(&tx_bytes);

        let txid_hex = self.post_text_with_retry(&url, tx_hex)?;
        let txid_bytes = hex::decode(txid_hex.trim())?;
        let mut result = [0u8; 32];
        result.copy_from_slice(&txid_bytes);
        Ok(result)
    }

    fn get_tx_confirmations(
        &self,
        txid: [u8; 32],
    ) -> Result<u64, Box<dyn std::error::Error + Send + Sync>> {
        let txid_hex = hex::encode(txid);

        match self.get_tx_status(&txid_hex) {
            Ok(status) => {
                if status.confirmed {
                    let current_height = self.get_block_count()?;
                    let tx_height = status.block_height.unwrap_or(0) as u64;
                    Ok(current_height.saturating_sub(tx_height) + 1)
                } else {
                    Ok(0)
                }
            }
            Err(_) => Ok(0),
        }
    }
}

/// Block info response from mempool.space
#[derive(Debug, Clone, serde::Deserialize)]
pub struct BlockInfo {
    pub id: String,
    pub height: u32,
    pub version: u32,
    pub timestamp: u64,
    pub tx_count: u32,
    pub size: u64,
    pub weight: u64,
    pub merkle_root: String,
}

/// Transaction status response
#[derive(Debug, Clone, serde::Deserialize)]
pub struct TxStatus {
    pub confirmed: bool,
    #[serde(default)]
    pub block_height: Option<u32>,
    #[serde(default)]
    pub block_hash: Option<String>,
    #[serde(default)]
    pub block_time: Option<u64>,
}

/// Transaction detail response
#[derive(Debug, Clone, serde::Deserialize)]
pub struct TxDetail {
    pub txid: String,
    pub version: u32,
    pub locktime: u64,
    pub vin: Vec<TxInput>,
    pub vout: Vec<TxOutput>,
    pub size: u64,
    pub weight: u64,
    pub fee: u64,
}

#[derive(Debug, Clone, serde::Deserialize)]
pub struct TxInput {
    pub txid: String,
    pub vout: u32,
    pub prevout: Option<TxPrevout>,
    pub scriptsig: String,
    pub is_coinbase: bool,
}

#[derive(Debug, Clone, serde::Deserialize)]
pub struct TxOutput {
    pub scriptpubkey: String,
    pub scriptpubkey_asm: String,
    pub scriptpubkey_type: String,
    pub scriptpubkey_address: String,
    pub value: u64,
}

#[derive(Debug, Clone, serde::Deserialize)]
pub struct TxPrevout {
    pub scriptpubkey: String,
    pub scriptpubkey_asm: String,
    pub scriptpubkey_type: String,
    pub scriptpubkey_address: String,
    pub value: u64,
}

/// Output spend status
#[derive(Debug, Clone, serde::Deserialize)]
pub struct OutSpendStatus {
    pub spent: bool,
    #[serde(default)]
    pub txid: Option<String>,
    #[serde(default)]
    pub vin: Option<u32>,
    #[serde(default)]
    pub status: Option<TxStatus>,
}

/// Get UTXOs for a specific address
pub fn get_address_utxos(
    rpc: &MempoolSignetRpc,
    address: &bitcoin::Address,
) -> Result<Vec<(OutPoint, u64)>, Box<dyn std::error::Error + Send + Sync>> {
    let url = format!("{}/address/{}/utxo", rpc.base_url, address);
    let utxos: Vec<AddressUtxo> = rpc.get_with_retry(&url)?;

    let result: Vec<(OutPoint, u64)> = utxos
        .into_iter()
        .map(|u| {
            let mut txid_bytes = hex::decode(&u.txid)?;
            // mempool.space returns txid in display order (big-endian)
            // Bitcoin internally uses little-endian (hash byte order)
            txid_bytes.reverse();
            let txid = Txid::from_slice(&txid_bytes).expect("valid txid");
            let outpoint = OutPoint::new(txid, u.vout);
            Ok((outpoint, u.value))
        })
        .collect::<Result<Vec<_>, Box<dyn std::error::Error + Send + Sync>>>()?;

    Ok(result)
}

/// Address UTXO response
#[derive(Debug, Clone, serde::Deserialize)]
pub struct AddressUtxo {
    pub txid: String,
    pub vout: u32,
    pub value: u64,
    pub status: TxStatus,
}

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

    #[test]
    #[ignore = "requires network"]
    fn test_get_block_count() {
        let rpc = MempoolSignetRpc::new();
        let height = rpc.get_block_count().unwrap();
        assert!(height > 200_000, "Signet height should be > 200k");
        println!("Current Signet height: {}", height);
    }

    #[test]
    #[ignore = "requires network"]
    fn test_get_block_hash() {
        let rpc = MempoolSignetRpc::new();
        let height = rpc.get_block_count().unwrap();
        let hash = rpc.get_block_hash(height).unwrap();
        assert_ne!(hash, [0u8; 32]);
        println!("Block hash at {}: {}", height, hex::encode(hash));
    }
}