clementine_core/
extended_bitcoin_rpc.rs

1//! # Bitcoin Extended RPC Interface
2//!
3//! Extended RPC interface communicates with the Bitcoin node. It features some
4//! common wrappers around typical RPC operations as well as direct
5//! communication interface with the Bitcoin node.
6//!
7//! ## Tests
8//!
9//! In tests, Bitcoind node and client are usually created using
10//! [`crate::test::common::create_regtest_rpc`]. Please refer to
11//! [`crate::test::common`] for using [`ExtendedBitcoinRpc`] in tests.
12
13// Re-export types from clementine-extended-rpc
14pub use clementine_extended_rpc::{
15    get_fee_rate_from_mempool_space, BitcoinRPCError, ExtendedBitcoinRpc, RetryConfig,
16    RetryableError,
17};
18
19use async_trait::async_trait;
20#[cfg(test)]
21use bitcoin::BlockHash;
22use bitcoin::OutPoint;
23use bitcoincore_rpc::RpcApi;
24use eyre::eyre;
25use eyre::Context;
26
27use crate::builder::address::create_taproot_address;
28use crate::builder::transaction::create_round_txhandlers;
29use crate::builder::transaction::input::UtxoVout;
30use crate::builder::transaction::KickoffWinternitzKeys;
31use crate::builder::transaction::TxHandler;
32use crate::config::protocol::ProtocolParamset;
33use crate::deposit::OperatorData;
34use clementine_errors::BridgeError;
35use clementine_errors::TransactionType;
36use clementine_primitives::RoundIndex;
37
38#[cfg(test)]
39use crate::test::common::citrea::CitreaE2EData;
40#[cfg(test)]
41use crate::{
42    citrea::CitreaClientT,
43    test::common::{are_all_state_managers_synced, test_actors::TestActors},
44};
45#[cfg(test)]
46type Result<T> = std::result::Result<T, BitcoinRPCError>;
47
48#[cfg(test)]
49pub const MINE_BLOCK_COUNT: u64 = 3;
50
51/// Extension trait for bridge-specific RPC queries.
52///
53/// These methods are kept in clementine-core because they depend on
54/// bridge-specific types like `KickoffWinternitzKeys` and `OperatorData`.
55#[async_trait]
56pub trait BridgeRpcQueries {
57    /// Checks if an operator's collateral is valid and available for use.
58    ///
59    /// This function validates the operator's collateral by:
60    /// 1. Verifying the collateral UTXO exists and has the correct amount
61    /// 2. Creating the round transaction chain to track current collateral position
62    /// 3. Determining if the current collateral UTXO in the chain is spent in a non-protocol tx, signaling the exit of operator from the protocol
63    ///
64    /// # Parameters
65    ///
66    /// * `operator_data`: Data about the operator including collateral funding outpoint
67    /// * `kickoff_wpks`: Kickoff Winternitz public keys for round transaction creation
68    /// * `paramset`: Protocol parameters
69    ///
70    /// # Returns
71    ///
72    /// - [`bool`]: `true` if the collateral is still usable, thus operator is still in protocol, `false` if the collateral is spent, thus operator is not in protocol anymore
73    ///
74    /// # Errors
75    ///
76    /// - [`BridgeError`]: If there was an error retrieving transaction data, creating round transactions,
77    ///   or checking UTXO status
78    async fn collateral_check(
79        &self,
80        operator_data: &OperatorData,
81        kickoff_wpks: &KickoffWinternitzKeys,
82        paramset: &'static ProtocolParamset,
83    ) -> std::result::Result<bool, BridgeError>;
84}
85
86#[async_trait]
87impl BridgeRpcQueries for ExtendedBitcoinRpc {
88    async fn collateral_check(
89        &self,
90        operator_data: &OperatorData,
91        kickoff_wpks: &KickoffWinternitzKeys,
92        paramset: &'static ProtocolParamset,
93    ) -> std::result::Result<bool, BridgeError> {
94        // first check if the collateral utxo is on chain or mempool
95        let tx = self
96            .get_tx_of_txid(&operator_data.collateral_funding_outpoint.txid)
97            .await
98            .wrap_err(format!(
99                "Failed to find collateral utxo in chain for outpoint {:?}",
100                operator_data.collateral_funding_outpoint
101            ))?;
102        let collateral_outpoint = match tx
103            .output
104            .get(operator_data.collateral_funding_outpoint.vout as usize)
105        {
106            Some(output) => output,
107            None => {
108                tracing::warn!(
109                    "No output at index {} for txid {} while checking for collateral existence",
110                    operator_data.collateral_funding_outpoint.vout,
111                    operator_data.collateral_funding_outpoint.txid
112                );
113                return Ok(false);
114            }
115        };
116
117        if collateral_outpoint.value != paramset.collateral_funding_amount {
118            tracing::error!(
119                "Collateral amount for collateral {:?} is not correct: expected {}, got {}",
120                operator_data.collateral_funding_outpoint,
121                paramset.collateral_funding_amount,
122                collateral_outpoint.value
123            );
124            return Ok(false);
125        }
126
127        let operator_tpr_address =
128            create_taproot_address(&[], Some(operator_data.xonly_pk), paramset.network).0;
129
130        if collateral_outpoint.script_pubkey != operator_tpr_address.script_pubkey() {
131            tracing::error!(
132                "Collateral script pubkey for collateral {:?} is not correct: expected {}, got {}",
133                operator_data.collateral_funding_outpoint,
134                operator_tpr_address.script_pubkey(),
135                collateral_outpoint.script_pubkey
136            );
137            return Ok(false);
138        }
139
140        // we additionally check if collateral utxo is on chain (so not in mempool)
141        // on mainnet we fail if collateral utxo is not on chain because if it is in mempool,
142        // the txid of the utxo can change if the fee is bumped
143        // on other networks, we allow collateral to be in mempool to not wait for collateral to be on chain to do deposits for faster testing
144        let is_on_chain = self
145            .is_tx_on_chain(&operator_data.collateral_funding_outpoint.txid)
146            .await?;
147        if !is_on_chain {
148            return match paramset.network {
149                bitcoin::Network::Bitcoin => Ok(false),
150                _ => Ok(true),
151            };
152        }
153
154        let mut current_collateral_outpoint: OutPoint = operator_data.collateral_funding_outpoint;
155        let mut prev_ready_to_reimburse: Option<TxHandler> = None;
156        // iterate over all rounds
157        for round_idx in RoundIndex::iter_rounds(paramset.num_round_txs) {
158            // create round and ready to reimburse txs for the round
159            let txhandlers = create_round_txhandlers(
160                paramset,
161                round_idx,
162                operator_data,
163                kickoff_wpks,
164                prev_ready_to_reimburse.as_ref(),
165            )?;
166
167            let mut round_txhandler_opt = None;
168            let mut ready_to_reimburse_txhandler_opt = None;
169            for txhandler in &txhandlers {
170                match txhandler.get_transaction_type() {
171                    TransactionType::Round => round_txhandler_opt = Some(txhandler),
172                    TransactionType::ReadyToReimburse => {
173                        ready_to_reimburse_txhandler_opt = Some(txhandler)
174                    }
175                    _ => {}
176                }
177            }
178            if round_txhandler_opt.is_none() || ready_to_reimburse_txhandler_opt.is_none() {
179                return Err(eyre!(
180                    "Failed to create round and ready to reimburse txs for round {:?} for operator {}",
181                    round_idx,
182                    operator_data.xonly_pk
183                ).into());
184            }
185
186            let round_txid = round_txhandler_opt
187                .expect("Round txhandler should exist, checked above")
188                .get_cached_tx()
189                .compute_txid();
190            let is_round_tx_on_chain = self.is_tx_on_chain(&round_txid).await?;
191            if !is_round_tx_on_chain {
192                break;
193            }
194            let block_hash = self.get_blockhash_of_tx(&round_txid).await?;
195            let block_height = self
196                .get_block_info(&block_hash)
197                .await
198                .wrap_err(format!(
199                    "Failed to get block info for block hash {block_hash}"
200                ))?
201                .height;
202            if block_height < paramset.start_height as usize {
203                tracing::warn!(
204                    "Collateral utxo of operator {operator_data:?} is spent in a block before paramset start height: {block_height} < {0}",
205                    paramset.start_height
206                );
207                return Ok(false);
208            }
209            current_collateral_outpoint = OutPoint {
210                txid: round_txid,
211                vout: UtxoVout::CollateralInRound.get_vout(),
212            };
213            if round_idx == RoundIndex::Round(paramset.num_round_txs - 1) {
214                // for the last round, only check round tx, as if the operator sent the ready to reimburse tx of last round,
215                // it cannot create more kickoffs anymore
216                break;
217            }
218            let ready_to_reimburse_txhandler = ready_to_reimburse_txhandler_opt
219                .expect("Ready to reimburse txhandler should exist");
220            let ready_to_reimburse_txid =
221                ready_to_reimburse_txhandler.get_cached_tx().compute_txid();
222            let is_ready_to_reimburse_tx_on_chain =
223                self.is_tx_on_chain(&ready_to_reimburse_txid).await?;
224            if !is_ready_to_reimburse_tx_on_chain {
225                break;
226            }
227
228            current_collateral_outpoint = OutPoint {
229                txid: ready_to_reimburse_txid,
230                vout: UtxoVout::CollateralInReadyToReimburse.get_vout(),
231            };
232
233            prev_ready_to_reimburse = Some(ready_to_reimburse_txhandler.clone());
234        }
235
236        // if the collateral utxo we found latest in the round tx chain is spent, operators collateral is spent from Clementine
237        // bridge protocol, thus it is unusable and operator cannot fulfill withdrawals anymore
238        // if not spent, it should exist in chain, which is checked below
239        Ok(!self.is_utxo_spent(&current_collateral_outpoint).await?)
240    }
241}
242
243/// Extension trait for test-only RPC methods that depend on core test infrastructure.
244#[cfg(test)]
245#[async_trait]
246pub trait TestRpcExtensions {
247    /// A helper fn to safely mine blocks while waiting for all actors to be synced.
248    async fn mine_blocks_while_synced<C: CitreaClientT>(
249        &self,
250        block_num: u64,
251        actors: &TestActors<C>,
252        e2e: Option<&CitreaE2EData<'_>>,
253    ) -> Result<Vec<BlockHash>>;
254}
255
256#[cfg(test)]
257#[async_trait]
258impl TestRpcExtensions for ExtendedBitcoinRpc {
259    async fn mine_blocks_while_synced<C: CitreaClientT>(
260        &self,
261        block_num: u64,
262        actors: &TestActors<C>,
263        e2e: Option<&CitreaE2EData<'_>>,
264    ) -> Result<Vec<BlockHash>> {
265        match e2e {
266            Some(e2e) if e2e.bitcoin_nodes.iter().count() > 1 => {
267                use bitcoin::secp256k1::rand::{thread_rng, Rng};
268                e2e.bitcoin_nodes
269                    .disconnect_nodes()
270                    .await
271                    .map_err(|e| eyre::eyre!("Failed to disconnect nodes: {}", e))?;
272                let reorg_blocks =
273                    thread_rng().gen_range(0..e2e.config.protocol_paramset().finality_depth as u64);
274                let da0 = e2e.bitcoin_nodes.get(0).expect("node 0 should exist");
275                let da1 = e2e.bitcoin_nodes.get(1).expect("node 1 should exist");
276
277                let mut mined_blocks = Vec::new();
278                while mined_blocks.len() < reorg_blocks as usize {
279                    if !are_all_state_managers_synced(self, actors).await? {
280                        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
281                        continue;
282                    }
283                    let num_mine_blocks =
284                        std::cmp::min(MINE_BLOCK_COUNT, reorg_blocks - mined_blocks.len() as u64);
285                    da0.generate(num_mine_blocks)
286                        .await
287                        .wrap_err("Failed to generate blocks")?;
288                    let new_blocks = da1
289                        .generate(num_mine_blocks)
290                        .await
291                        .wrap_err("Failed to generate blocks")?;
292                    mined_blocks.extend(new_blocks);
293                }
294                mined_blocks.extend(
295                    da1.generate(1)
296                        .await
297                        .wrap_err("Failed to generate blocks")?,
298                );
299                e2e.bitcoin_nodes
300                    .connect_nodes()
301                    .await
302                    .map_err(|e| eyre::eyre!("Failed to connect nodes: {}", e))?;
303                e2e.bitcoin_nodes
304                    .wait_for_sync(None)
305                    .await
306                    .map_err(|e| eyre::eyre!("Failed to wait for sync: {}", e))?;
307                while mined_blocks.len() != (reorg_blocks + block_num + 1) as usize {
308                    if !are_all_state_managers_synced(self, actors).await? {
309                        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
310                        continue;
311                    }
312                    let num_mine_blocks = std::cmp::min(
313                        MINE_BLOCK_COUNT,
314                        (reorg_blocks + block_num + 1) - mined_blocks.len() as u64,
315                    );
316                    mined_blocks.extend(self.mine_blocks(num_mine_blocks).await?);
317                }
318                Ok(mined_blocks)
319            }
320            _ => {
321                let mut mined_blocks = Vec::new();
322                while mined_blocks.len() < block_num as usize {
323                    if !are_all_state_managers_synced(self, actors).await? {
324                        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
325                        continue;
326                    }
327                    let num_mine_blocks =
328                        std::cmp::min(MINE_BLOCK_COUNT, block_num - mined_blocks.len() as u64);
329                    let new_blocks = self.mine_blocks(num_mine_blocks).await?;
330                    mined_blocks.extend(new_blocks);
331                }
332                Ok(mined_blocks)
333            }
334        }
335    }
336}
337
338#[cfg(test)]
339mod tests {
340    use std::collections::HashMap;
341
342    use crate::actor::Actor;
343    use crate::config::protocol::{ProtocolParamset, REGTEST_PARAMSET};
344    use crate::extended_bitcoin_rpc::ExtendedBitcoinRpc;
345    use crate::test::common::{citrea, create_test_config_with_thread_name};
346    use crate::{
347        bitvm_client::SECP, extended_bitcoin_rpc::BitcoinRPCError, test::common::create_regtest_rpc,
348    };
349    use bitcoin::Amount;
350    use bitcoin::{amount, key::Keypair, Address, FeeRate, XOnlyPublicKey};
351    use bitcoincore_rpc::RpcApi;
352    use citrea_e2e::bitcoin::DEFAULT_FINALITY_DEPTH;
353    use citrea_e2e::config::{BitcoinConfig, TestCaseDockerConfig};
354    use citrea_e2e::node::NodeKind;
355    use citrea_e2e::test_case::TestCaseRunner;
356    use citrea_e2e::Result;
357    use citrea_e2e::{config::TestCaseConfig, framework::TestFramework, test_case::TestCase};
358    use tonic::async_trait;
359
360    #[tokio::test]
361    async fn new_extended_rpc_with_clone() {
362        let mut config = create_test_config_with_thread_name().await;
363        let regtest = create_regtest_rpc(&mut config).await;
364        let rpc = regtest.rpc();
365
366        rpc.mine_blocks(101).await.unwrap();
367        let height = rpc.get_block_count().await.unwrap();
368        let hash = rpc.get_block_hash(height).await.unwrap();
369
370        let cloned_rpc = rpc.clone_inner().await.unwrap();
371        assert_eq!(cloned_rpc.get_block_count().await.unwrap(), height);
372        assert_eq!(cloned_rpc.get_block_hash(height).await.unwrap(), hash);
373    }
374
375    #[tokio::test]
376    async fn test_rpc_call_retry_with_invalid_credentials() {
377        use crate::extended_bitcoin_rpc::RetryableError;
378        use secrecy::SecretString;
379
380        let mut config = create_test_config_with_thread_name().await;
381        let regtest = create_regtest_rpc(&mut config).await;
382
383        // Get a working connection first
384        let working_rpc = regtest.rpc();
385        let url = working_rpc.url().to_string();
386
387        // Create connection with invalid credentials
388        let invalid_user = SecretString::new("invalid_user".to_string().into());
389        let invalid_password = SecretString::new("invalid_password".to_string().into());
390
391        let res = ExtendedBitcoinRpc::connect(url, invalid_user, invalid_password, None).await;
392
393        assert!(res.is_err());
394        assert!(!res.unwrap_err().is_retryable());
395    }
396
397    #[tokio::test]
398    async fn tx_checks_in_mempool_and_on_chain() {
399        let mut config = create_test_config_with_thread_name().await;
400        let regtest = create_regtest_rpc(&mut config).await;
401        let rpc = regtest.rpc();
402
403        let keypair = Keypair::from_secret_key(&SECP, &config.secret_key);
404        let (xonly, _parity) = XOnlyPublicKey::from_keypair(&keypair);
405        let address = Address::p2tr(&SECP, xonly, None, config.protocol_paramset.network);
406
407        let amount = amount::Amount::from_sat(10000);
408
409        // Prepare a transaction.
410        let utxo = rpc.send_to_address(&address, amount).await.unwrap();
411        let tx = rpc.get_tx_of_txid(&utxo.txid).await.unwrap();
412        let txid = tx.compute_txid();
413        tracing::debug!("TXID: {}", txid);
414
415        assert_eq!(tx.output[utxo.vout as usize].value, amount);
416        assert_eq!(utxo.txid, txid);
417        assert!(rpc
418            .check_utxo_address_and_amount(&utxo, &address.script_pubkey(), amount)
419            .await
420            .unwrap());
421
422        // In mempool.
423        assert!(rpc.confirmation_blocks(&utxo.txid).await.is_err());
424        assert!(rpc.get_blockhash_of_tx(&utxo.txid).await.is_err());
425        assert!(!rpc.is_tx_on_chain(&txid).await.unwrap());
426        assert!(rpc.is_utxo_spent(&utxo).await.is_err());
427
428        rpc.mine_blocks(1).await.unwrap();
429        let height = rpc.get_block_count().await.unwrap();
430        assert_eq!(height as u32, rpc.get_current_chain_height().await.unwrap());
431        let blockhash = rpc.get_block_hash(height).await.unwrap();
432
433        // On chain.
434        assert_eq!(rpc.confirmation_blocks(&utxo.txid).await.unwrap(), 1);
435        assert_eq!(
436            rpc.get_blockhash_of_tx(&utxo.txid).await.unwrap(),
437            blockhash
438        );
439        assert_eq!(rpc.get_tx_of_txid(&txid).await.unwrap(), tx);
440        assert!(rpc.is_tx_on_chain(&txid).await.unwrap());
441        assert!(!rpc.is_utxo_spent(&utxo).await.unwrap());
442
443        // Doesn't matter if in mempool or on chain.
444        let txout = rpc.get_txout_from_outpoint(&utxo).await.unwrap();
445        assert_eq!(txout.value, amount);
446        assert_eq!(rpc.get_tx_of_txid(&txid).await.unwrap(), tx);
447
448        let height = rpc.get_current_chain_height().await.unwrap();
449        let (hash, header) = rpc.get_block_info_by_height(height.into()).await.unwrap();
450        assert_eq!(blockhash, hash);
451        assert_eq!(rpc.get_block_header(&hash).await.unwrap(), header);
452    }
453
454    #[tokio::test]
455    async fn bump_fee_with_fee_rate() {
456        let mut config = create_test_config_with_thread_name().await;
457        let regtest = create_regtest_rpc(&mut config).await;
458        let rpc = regtest.rpc();
459
460        let keypair = Keypair::from_secret_key(&SECP, &config.secret_key);
461        let (xonly, _parity) = XOnlyPublicKey::from_keypair(&keypair);
462        let address = Address::p2tr(&SECP, xonly, None, config.protocol_paramset.network);
463
464        let amount = amount::Amount::from_sat(10000);
465
466        // Confirmed transaction cannot be fee bumped.
467        let utxo = rpc.send_to_address(&address, amount).await.unwrap();
468        rpc.mine_blocks(1).await.unwrap();
469        assert!(rpc
470            .bump_fee_with_fee_rate(utxo.txid, FeeRate::from_sat_per_vb(1).unwrap())
471            .await
472            .inspect_err(|e| {
473                match e {
474                    BitcoinRPCError::TransactionAlreadyInBlock(_) => {}
475                    _ => panic!("Unexpected error: {e:?}"),
476                }
477            })
478            .is_err());
479
480        let current_fee_rate = FeeRate::from_sat_per_vb_unchecked(1);
481
482        // Trying to bump a transaction with a fee rate that is already enough
483        // should return the original txid.
484        let utxo = rpc.send_to_address(&address, amount).await.unwrap();
485        let txid = rpc
486            .bump_fee_with_fee_rate(utxo.txid, current_fee_rate)
487            .await
488            .unwrap();
489        assert_eq!(txid, utxo.txid);
490
491        // A bigger fee rate should return a different txid.
492        let new_fee_rate = FeeRate::from_sat_per_vb_unchecked(10000);
493        let txid = rpc
494            .bump_fee_with_fee_rate(utxo.txid, new_fee_rate)
495            .await
496            .unwrap();
497        assert_ne!(txid, utxo.txid);
498    }
499
500    struct ReorgChecks;
501    #[async_trait]
502    impl TestCase for ReorgChecks {
503        fn bitcoin_config() -> BitcoinConfig {
504            BitcoinConfig {
505                extra_args: vec![
506                    "-txindex=1",
507                    "-fallbackfee=0.000001",
508                    "-rpcallowip=0.0.0.0/0",
509                    "-dustrelayfee=0",
510                ],
511                ..Default::default()
512            }
513        }
514
515        fn test_config() -> TestCaseConfig {
516            TestCaseConfig {
517                with_sequencer: true,
518                with_batch_prover: false,
519                n_nodes: HashMap::from([(NodeKind::Bitcoin, 2)]),
520                docker: TestCaseDockerConfig {
521                    bitcoin: true,
522                    citrea: true,
523                },
524                ..Default::default()
525            }
526        }
527
528        async fn run_test(&mut self, f: &mut TestFramework) -> Result<()> {
529            let (da0, da1) = (
530                f.bitcoin_nodes.get(0).unwrap(),
531                f.bitcoin_nodes.get(1).unwrap(),
532            );
533
534            let mut config = create_test_config_with_thread_name().await;
535            const PARAMSET: ProtocolParamset = ProtocolParamset {
536                finality_depth: DEFAULT_FINALITY_DEPTH as u32,
537                ..REGTEST_PARAMSET
538            };
539            config.protocol_paramset = &PARAMSET;
540            citrea::update_config_with_citrea_e2e_values(
541                &mut config,
542                da0,
543                f.sequencer.as_ref().expect("Sequencer is present"),
544                None,
545            );
546
547            let rpc = ExtendedBitcoinRpc::connect(
548                config.bitcoin_rpc_url.clone(),
549                config.bitcoin_rpc_user.clone(),
550                config.bitcoin_rpc_password.clone(),
551                None,
552            )
553            .await
554            .unwrap();
555
556            // Reorg starts here.
557            f.bitcoin_nodes.disconnect_nodes().await?;
558
559            let before_reorg_tip_height = rpc.get_block_count().await?;
560            let before_reorg_tip_hash = rpc.get_block_hash(before_reorg_tip_height).await?;
561
562            let address = Actor::new(config.secret_key, config.protocol_paramset.network).address;
563            let tx = rpc
564                .send_to_address(&address, Amount::from_sat(10000))
565                .await?;
566
567            assert!(!rpc.is_tx_on_chain(&tx.txid).await?);
568            rpc.mine_blocks(1).await?;
569            assert!(rpc.is_tx_on_chain(&tx.txid).await?);
570
571            // Make the second branch longer and perform a reorg.
572            let reorg_depth = 4;
573            da1.generate(reorg_depth).await.unwrap();
574            f.bitcoin_nodes.connect_nodes().await?;
575            f.bitcoin_nodes.wait_for_sync(None).await?;
576
577            // Check that reorg happened.
578            let current_tip_height = rpc.get_block_count().await?;
579            assert_eq!(
580                before_reorg_tip_height + reorg_depth,
581                current_tip_height,
582                "Re-org did not occur"
583            );
584            let current_tip_hash = rpc.get_block_hash(current_tip_height).await?;
585            assert_ne!(
586                before_reorg_tip_hash, current_tip_hash,
587                "Re-org did not occur"
588            );
589
590            assert!(!rpc.is_tx_on_chain(&tx.txid).await?);
591
592            Ok(())
593        }
594    }
595
596    #[tokio::test]
597    async fn reorg_checks() -> Result<()> {
598        TestCaseRunner::new(ReorgChecks).run().await
599    }
600
601    mod retry_config_tests {
602        use crate::extended_bitcoin_rpc::RetryConfig;
603
604        use std::time::Duration;
605
606        #[test]
607        fn test_retry_config_default() {
608            let config = RetryConfig::default();
609            assert_eq!(config.initial_delay_millis, 100);
610            assert_eq!(config.max_delay, Duration::from_secs(30));
611            assert_eq!(config.max_attempts, 5);
612            assert_eq!(config.backoff_multiplier, 2);
613            assert!(!config.is_jitter);
614        }
615
616        #[test]
617        fn test_retry_config_custom() {
618            let initial = 200;
619            let max = Duration::from_secs(10);
620            let attempts = 7;
621            let backoff_multiplier = 3;
622            let jitter = true;
623            let config = RetryConfig::new(initial, max, attempts, backoff_multiplier, jitter);
624            assert_eq!(config.initial_delay_millis, initial);
625            assert_eq!(config.max_delay, max);
626            assert_eq!(config.max_attempts, attempts);
627            assert_eq!(config.backoff_multiplier, backoff_multiplier);
628            assert!(config.is_jitter);
629        }
630
631        #[test]
632        fn test_retry_strategy_initial_delay() {
633            // Test that the first delay matches the expected initial_delay_millis
634            // when initial_delay_millis is divisible by backoff_multiplier
635            let initial_delay_millis = 100;
636            let backoff_multiplier = 2;
637            let config = RetryConfig::new(
638                initial_delay_millis,
639                Duration::from_secs(30),
640                5,
641                backoff_multiplier,
642                false, // no jitter for predictable testing
643            );
644
645            let mut strategy = config.get_strategy();
646            let first_delay = strategy.next().expect("Should have first delay");
647
648            // The formula is: first_delay = base * factor
649            // We set base = initial_delay_millis / backoff_multiplier
650            // So: first_delay = (initial_delay_millis / backoff_multiplier) * backoff_multiplier = initial_delay_millis
651            assert_eq!(
652                first_delay,
653                Duration::from_millis(initial_delay_millis),
654                "First delay should match initial_delay_millis"
655            );
656
657            // Verify the second delay is approximately initial_delay_millis * backoff_multiplier
658            let second_delay = strategy.next().expect("Should have second delay");
659            assert_eq!(
660                second_delay,
661                Duration::from_millis(initial_delay_millis * backoff_multiplier),
662                "Second delay should be initial_delay_millis * backoff_multiplier"
663            );
664        }
665    }
666
667    mod retryable_error_tests {
668        use bitcoin::{hashes::Hash, BlockHash, Txid};
669
670        use crate::extended_bitcoin_rpc::RetryableError;
671
672        use super::*;
673        use std::io::{Error as IoError, ErrorKind};
674
675        #[test]
676        fn test_bitcoin_rpc_error_retryable_io_errors() {
677            let retryable_kinds = [
678                ErrorKind::ConnectionRefused,
679                ErrorKind::ConnectionReset,
680                ErrorKind::ConnectionAborted,
681                ErrorKind::NotConnected,
682                ErrorKind::BrokenPipe,
683                ErrorKind::TimedOut,
684                ErrorKind::Interrupted,
685                ErrorKind::UnexpectedEof,
686            ];
687
688            for kind in retryable_kinds {
689                let io_error = IoError::new(kind, "test error");
690                let rpc_error = bitcoincore_rpc::Error::Io(io_error);
691                assert!(
692                    rpc_error.is_retryable(),
693                    "ErrorKind::{kind:?} should be retryable"
694                );
695            }
696        }
697
698        #[test]
699        fn test_bitcoin_rpc_error_non_retryable_io_errors() {
700            let non_retryable_kinds = [
701                ErrorKind::PermissionDenied,
702                ErrorKind::NotFound,
703                ErrorKind::InvalidInput,
704                ErrorKind::InvalidData,
705            ];
706
707            for kind in non_retryable_kinds {
708                let io_error = IoError::new(kind, "test error");
709                let rpc_error = bitcoincore_rpc::Error::Io(io_error);
710                assert!(
711                    !rpc_error.is_retryable(),
712                    "ErrorKind::{kind:?} should not be retryable"
713                );
714            }
715        }
716
717        #[test]
718        fn test_bitcoin_rpc_error_auth_not_retryable() {
719            let auth_error = bitcoincore_rpc::Error::Auth("Invalid credentials".to_string());
720            assert!(!auth_error.is_retryable());
721        }
722
723        #[test]
724        fn test_bitcoin_rpc_error_url_parse_not_retryable() {
725            let url_error = url::ParseError::EmptyHost;
726            let rpc_error = bitcoincore_rpc::Error::UrlParse(url_error);
727            assert!(!rpc_error.is_retryable());
728        }
729
730        #[test]
731        fn test_bitcoin_rpc_error_invalid_cookie_not_retryable() {
732            let rpc_error = bitcoincore_rpc::Error::InvalidCookieFile;
733            assert!(!rpc_error.is_retryable());
734        }
735
736        #[test]
737        fn test_bitcoin_rpc_error_returned_error_non_retryable_patterns() {
738            let non_retryable_messages = [
739                "insufficient funds",
740                "transaction already in blockchain",
741                "invalid transaction",
742                "not found in mempool",
743                "transaction conflict",
744            ];
745
746            for msg in non_retryable_messages {
747                let rpc_error = bitcoincore_rpc::Error::ReturnedError(msg.to_string());
748                assert!(
749                    !rpc_error.is_retryable(),
750                    "Message '{msg}' should not be retryable"
751                );
752            }
753        }
754
755        #[test]
756        fn test_bitcoin_rpc_error_unexpected_structure_retryable() {
757            let rpc_error = bitcoincore_rpc::Error::UnexpectedStructure;
758            assert!(rpc_error.is_retryable());
759        }
760
761        #[test]
762        fn test_bitcoin_rpc_error_serialization_errors_not_retryable() {
763            use bitcoin::consensus::encode::Error as EncodeError;
764
765            let serialization_errors = [
766                bitcoincore_rpc::Error::BitcoinSerialization(EncodeError::Io(
767                    IoError::other("test").into(),
768                )),
769                // bitcoincore_rpc::Error::Hex(HexToBytesError::InvalidChar(InvalidCharError{invalid: 0})),
770                bitcoincore_rpc::Error::Json(serde_json::Error::io(IoError::other("test"))),
771            ];
772
773            for error in serialization_errors {
774                assert!(
775                    !error.is_retryable(),
776                    "Serialization error should not be retryable"
777                );
778            }
779        }
780
781        #[test]
782        fn test_bridge_rpc_error_retryable() {
783            // Test permanent errors
784            assert!(
785                !BitcoinRPCError::TransactionAlreadyInBlock(BlockHash::all_zeros()).is_retryable()
786            );
787            assert!(!BitcoinRPCError::BumpFeeUTXOSpent(Default::default()).is_retryable());
788
789            // Test potentially retryable errors
790            let txid = Txid::all_zeros();
791            let fee_rate = FeeRate::from_sat_per_vb_unchecked(1);
792            assert!(BitcoinRPCError::BumpFeeError(txid, fee_rate).is_retryable());
793
794            // Test Other error with retryable patterns
795            let retryable_other = BitcoinRPCError::Other(eyre::eyre!("timeout occurred"));
796            assert!(retryable_other.is_retryable());
797
798            let non_retryable_other = BitcoinRPCError::Other(eyre::eyre!("permission denied"));
799            assert!(!non_retryable_other.is_retryable());
800        }
801    }
802
803    mod rpc_call_retry_tests {
804
805        use crate::extended_bitcoin_rpc::RetryableError;
806
807        use super::*;
808        use secrecy::SecretString;
809
810        #[tokio::test]
811        async fn test_rpc_call_retry_with_invalid_host() {
812            let user = SecretString::new("user".to_string().into());
813            let password = SecretString::new("password".to_string().into());
814            let invalid_url = "http://nonexistent-host:8332".to_string();
815
816            let res = ExtendedBitcoinRpc::connect(invalid_url, user, password, None).await;
817
818            assert!(res.is_err());
819            assert!(!res.unwrap_err().is_retryable());
820        }
821    }
822
823    mod convenience_method_tests {
824        use super::*;
825
826        #[tokio::test]
827        async fn test_get_block_hash_with_retry() {
828            let mut config = create_test_config_with_thread_name().await;
829            let regtest = create_regtest_rpc(&mut config).await;
830            let rpc = regtest.rpc();
831
832            // Mine a block first
833            rpc.mine_blocks(1).await.unwrap();
834            let height = rpc.get_block_count().await.unwrap();
835
836            let result = rpc.get_block_hash(height).await;
837            assert!(result.is_ok());
838
839            let expected_hash = rpc.get_block_hash(height).await.unwrap();
840            assert_eq!(result.unwrap(), expected_hash);
841        }
842
843        #[tokio::test]
844        async fn test_get_tx_out_with_retry() {
845            let mut config = create_test_config_with_thread_name().await;
846            let regtest = create_regtest_rpc(&mut config).await;
847            let rpc = regtest.rpc();
848
849            // Create a transaction
850            let keypair = Keypair::from_secret_key(&SECP, &config.secret_key);
851            let (xonly, _parity) = XOnlyPublicKey::from_keypair(&keypair);
852            let address = Address::p2tr(&SECP, xonly, None, config.protocol_paramset.network);
853            let amount = Amount::from_sat(10000);
854
855            let utxo = rpc.send_to_address(&address, amount).await.unwrap();
856
857            let result = rpc.get_tx_of_txid(&utxo.txid).await;
858            assert!(result.is_ok());
859
860            let tx = result.unwrap();
861            assert_eq!(tx.compute_txid(), utxo.txid);
862        }
863
864        #[tokio::test]
865        async fn test_send_to_address_with_retry() {
866            let mut config = create_test_config_with_thread_name().await;
867            let regtest = create_regtest_rpc(&mut config).await;
868            let rpc = regtest.rpc();
869
870            let keypair = Keypair::from_secret_key(&SECP, &config.secret_key);
871            let (xonly, _parity) = XOnlyPublicKey::from_keypair(&keypair);
872            let address = Address::p2tr(&SECP, xonly, None, config.protocol_paramset.network);
873            let amount = Amount::from_sat(10000);
874
875            let result = rpc.send_to_address(&address, amount).await;
876            assert!(result.is_ok());
877
878            let outpoint = result.unwrap();
879
880            // Verify the transaction exists
881            let tx = rpc.get_tx_of_txid(&outpoint.txid).await.unwrap();
882            assert_eq!(tx.output[outpoint.vout as usize].value, amount);
883        }
884
885        #[tokio::test]
886        async fn test_bump_fee_with_retry() {
887            let mut config = create_test_config_with_thread_name().await;
888            let regtest = create_regtest_rpc(&mut config).await;
889            let rpc = regtest.rpc();
890
891            let keypair = Keypair::from_secret_key(&SECP, &config.secret_key);
892            let (xonly, _parity) = XOnlyPublicKey::from_keypair(&keypair);
893            let address = Address::p2tr(&SECP, xonly, None, config.protocol_paramset.network);
894            let amount = Amount::from_sat(10000);
895
896            // Create an unconfirmed transaction
897            let utxo = rpc.send_to_address(&address, amount).await.unwrap();
898            let new_fee_rate = FeeRate::from_sat_per_vb_unchecked(10000);
899
900            let result = rpc.bump_fee_with_fee_rate(utxo.txid, new_fee_rate).await;
901            assert!(result.is_ok());
902
903            let new_txid = result.unwrap();
904            // Should return a different txid since fee was actually bumped
905            assert_ne!(new_txid, utxo.txid);
906        }
907    }
908}