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 = std::cmp::min(
284                        MINE_BLOCK_COUNT,
285                        reorg_blocks.saturating_sub(mined_blocks.len() as u64),
286                    );
287                    da0.generate(num_mine_blocks)
288                        .await
289                        .wrap_err("Failed to generate blocks")?;
290                    let new_blocks = da1
291                        .generate(num_mine_blocks)
292                        .await
293                        .wrap_err("Failed to generate blocks")?;
294                    mined_blocks.extend(new_blocks);
295                }
296                mined_blocks.extend(
297                    da1.generate(1)
298                        .await
299                        .wrap_err("Failed to generate blocks")?,
300                );
301                e2e.bitcoin_nodes
302                    .connect_nodes()
303                    .await
304                    .map_err(|e| eyre::eyre!("Failed to connect nodes: {}", e))?;
305                e2e.bitcoin_nodes
306                    .wait_for_sync(None)
307                    .await
308                    .map_err(|e| eyre::eyre!("Failed to wait for sync: {}", e))?;
309                while mined_blocks.len() != (reorg_blocks + block_num + 1) as usize {
310                    if !are_all_state_managers_synced(self, actors).await? {
311                        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
312                        continue;
313                    }
314                    let num_mine_blocks = std::cmp::min(
315                        MINE_BLOCK_COUNT,
316                        (reorg_blocks + block_num + 1).saturating_sub(mined_blocks.len() as u64),
317                    );
318                    mined_blocks.extend(self.mine_blocks(num_mine_blocks).await?);
319                }
320                Ok(mined_blocks)
321            }
322            _ => {
323                let mut mined_blocks = Vec::new();
324                while mined_blocks.len() < block_num as usize {
325                    if !are_all_state_managers_synced(self, actors).await? {
326                        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
327                        continue;
328                    }
329                    let num_mine_blocks = std::cmp::min(
330                        MINE_BLOCK_COUNT,
331                        block_num.saturating_sub(mined_blocks.len() as u64),
332                    );
333                    let new_blocks = self.mine_blocks(num_mine_blocks).await?;
334                    mined_blocks.extend(new_blocks);
335                }
336                Ok(mined_blocks)
337            }
338        }
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use std::collections::HashMap;
345
346    use crate::actor::Actor;
347    use crate::config::protocol::{ProtocolParamset, REGTEST_PARAMSET};
348    use crate::extended_bitcoin_rpc::ExtendedBitcoinRpc;
349    use crate::test::common::{citrea, create_test_config_with_thread_name};
350    use crate::{
351        bitvm_client::SECP, extended_bitcoin_rpc::BitcoinRPCError, test::common::create_regtest_rpc,
352    };
353    use bitcoin::Amount;
354    use bitcoin::{amount, key::Keypair, Address, FeeRate, XOnlyPublicKey};
355    use bitcoincore_rpc::RpcApi;
356    use citrea_e2e::bitcoin::DEFAULT_FINALITY_DEPTH;
357    use citrea_e2e::config::{BitcoinConfig, TestCaseDockerConfig};
358    use citrea_e2e::node::NodeKind;
359    use citrea_e2e::test_case::TestCaseRunner;
360    use citrea_e2e::Result;
361    use citrea_e2e::{config::TestCaseConfig, framework::TestFramework, test_case::TestCase};
362    use tonic::async_trait;
363
364    #[tokio::test]
365    async fn new_extended_rpc_with_clone() {
366        let mut config = create_test_config_with_thread_name().await;
367        let regtest = create_regtest_rpc(&mut config).await;
368        let rpc = regtest.rpc();
369
370        rpc.mine_blocks(101).await.unwrap();
371        let height = rpc.get_block_count().await.unwrap();
372        let hash = rpc.get_block_hash(height).await.unwrap();
373
374        let cloned_rpc = rpc.clone_inner().await.unwrap();
375        assert_eq!(cloned_rpc.get_block_count().await.unwrap(), height);
376        assert_eq!(cloned_rpc.get_block_hash(height).await.unwrap(), hash);
377    }
378
379    #[tokio::test]
380    async fn test_rpc_call_retry_with_invalid_credentials() {
381        use crate::extended_bitcoin_rpc::RetryableError;
382        use secrecy::SecretString;
383
384        let mut config = create_test_config_with_thread_name().await;
385        let regtest = create_regtest_rpc(&mut config).await;
386
387        // Get a working connection first
388        let working_rpc = regtest.rpc();
389        let url = working_rpc.url().to_string();
390
391        // Create connection with invalid credentials
392        let invalid_user = SecretString::new("invalid_user".to_string().into());
393        let invalid_password = SecretString::new("invalid_password".to_string().into());
394
395        let res = ExtendedBitcoinRpc::connect(url, invalid_user, invalid_password, None).await;
396
397        assert!(res.is_err());
398        assert!(!res.unwrap_err().is_retryable());
399    }
400
401    #[tokio::test]
402    async fn tx_checks_in_mempool_and_on_chain() {
403        let mut config = create_test_config_with_thread_name().await;
404        let regtest = create_regtest_rpc(&mut config).await;
405        let rpc = regtest.rpc();
406
407        let keypair = Keypair::from_secret_key(&SECP, &config.secret_key);
408        let (xonly, _parity) = XOnlyPublicKey::from_keypair(&keypair);
409        let address = Address::p2tr(&SECP, xonly, None, config.protocol_paramset.network);
410
411        let amount = amount::Amount::from_sat(10000);
412
413        // Prepare a transaction.
414        let utxo = rpc.send_to_address(&address, amount).await.unwrap();
415        let tx = rpc.get_tx_of_txid(&utxo.txid).await.unwrap();
416        let txid = tx.compute_txid();
417        tracing::debug!("TXID: {}", txid);
418
419        assert_eq!(tx.output[utxo.vout as usize].value, amount);
420        assert_eq!(utxo.txid, txid);
421        assert!(rpc
422            .check_utxo_address_and_amount(&utxo, &address.script_pubkey(), amount)
423            .await
424            .unwrap());
425
426        // In mempool.
427        assert!(rpc.confirmation_blocks(&utxo.txid).await.is_err());
428        assert!(rpc.get_blockhash_of_tx(&utxo.txid).await.is_err());
429        assert!(!rpc.is_tx_on_chain(&txid).await.unwrap());
430        assert!(rpc.is_utxo_spent(&utxo).await.is_err());
431
432        rpc.mine_blocks(1).await.unwrap();
433        let height = rpc.get_block_count().await.unwrap();
434        assert_eq!(height as u32, rpc.get_current_chain_height().await.unwrap());
435        let blockhash = rpc.get_block_hash(height).await.unwrap();
436
437        // On chain.
438        assert_eq!(rpc.confirmation_blocks(&utxo.txid).await.unwrap(), 1);
439        assert_eq!(
440            rpc.get_blockhash_of_tx(&utxo.txid).await.unwrap(),
441            blockhash
442        );
443        assert_eq!(rpc.get_tx_of_txid(&txid).await.unwrap(), tx);
444        assert!(rpc.is_tx_on_chain(&txid).await.unwrap());
445        assert!(!rpc.is_utxo_spent(&utxo).await.unwrap());
446
447        // Doesn't matter if in mempool or on chain.
448        let txout = rpc.get_txout_from_outpoint(&utxo).await.unwrap();
449        assert_eq!(txout.value, amount);
450        assert_eq!(rpc.get_tx_of_txid(&txid).await.unwrap(), tx);
451
452        let height = rpc.get_current_chain_height().await.unwrap();
453        let (hash, header) = rpc.get_block_info_by_height(height.into()).await.unwrap();
454        assert_eq!(blockhash, hash);
455        assert_eq!(rpc.get_block_header(&hash).await.unwrap(), header);
456    }
457
458    #[tokio::test]
459    async fn bump_fee_with_fee_rate() {
460        let mut config = create_test_config_with_thread_name().await;
461        let regtest = create_regtest_rpc(&mut config).await;
462        let rpc = regtest.rpc();
463
464        let keypair = Keypair::from_secret_key(&SECP, &config.secret_key);
465        let (xonly, _parity) = XOnlyPublicKey::from_keypair(&keypair);
466        let address = Address::p2tr(&SECP, xonly, None, config.protocol_paramset.network);
467
468        let amount = amount::Amount::from_sat(10000);
469
470        // Confirmed transaction cannot be fee bumped.
471        let utxo = rpc.send_to_address(&address, amount).await.unwrap();
472        rpc.mine_blocks(1).await.unwrap();
473        assert!(rpc
474            .bump_fee_with_fee_rate(utxo.txid, FeeRate::from_sat_per_vb(1).unwrap())
475            .await
476            .inspect_err(|e| {
477                match e {
478                    BitcoinRPCError::TransactionAlreadyInBlock(_) => {}
479                    _ => panic!("Unexpected error: {e:?}"),
480                }
481            })
482            .is_err());
483
484        let current_fee_rate = FeeRate::from_sat_per_vb_unchecked(1);
485
486        // Trying to bump a transaction with a fee rate that is already enough
487        // should return the original txid.
488        let utxo = rpc.send_to_address(&address, amount).await.unwrap();
489        let txid = rpc
490            .bump_fee_with_fee_rate(utxo.txid, current_fee_rate)
491            .await
492            .unwrap();
493        assert_eq!(txid, utxo.txid);
494
495        // A bigger fee rate should return a different txid.
496        let new_fee_rate = FeeRate::from_sat_per_vb_unchecked(10000);
497        let txid = rpc
498            .bump_fee_with_fee_rate(utxo.txid, new_fee_rate)
499            .await
500            .unwrap();
501        assert_ne!(txid, utxo.txid);
502    }
503
504    struct ReorgChecks;
505    #[async_trait]
506    impl TestCase for ReorgChecks {
507        fn bitcoin_config() -> BitcoinConfig {
508            BitcoinConfig {
509                extra_args: vec![
510                    "-txindex=1",
511                    "-fallbackfee=0.000001",
512                    "-rpcallowip=0.0.0.0/0",
513                    "-dustrelayfee=0",
514                ],
515                ..Default::default()
516            }
517        }
518
519        fn test_config() -> TestCaseConfig {
520            TestCaseConfig {
521                with_sequencer: true,
522                with_batch_prover: false,
523                n_nodes: HashMap::from([(NodeKind::Bitcoin, 2)]),
524                docker: TestCaseDockerConfig {
525                    bitcoin: true,
526                    citrea: true,
527                },
528                ..Default::default()
529            }
530        }
531
532        async fn run_test(&mut self, f: &mut TestFramework) -> Result<()> {
533            let (da0, da1) = (
534                f.bitcoin_nodes.get(0).unwrap(),
535                f.bitcoin_nodes.get(1).unwrap(),
536            );
537
538            let mut config = create_test_config_with_thread_name().await;
539            const PARAMSET: ProtocolParamset = ProtocolParamset {
540                finality_depth: DEFAULT_FINALITY_DEPTH as u32,
541                ..REGTEST_PARAMSET
542            };
543            config.protocol_paramset = &PARAMSET;
544            citrea::update_config_with_citrea_e2e_values(
545                &mut config,
546                da0,
547                f.sequencer.as_ref().expect("Sequencer is present"),
548                None,
549            );
550
551            let rpc = ExtendedBitcoinRpc::connect(
552                config.bitcoin_rpc_url.clone(),
553                config.bitcoin_rpc_user.clone(),
554                config.bitcoin_rpc_password.clone(),
555                None,
556            )
557            .await
558            .unwrap();
559
560            // Reorg starts here.
561            f.bitcoin_nodes.disconnect_nodes().await?;
562
563            let before_reorg_tip_height = rpc.get_block_count().await?;
564            let before_reorg_tip_hash = rpc.get_block_hash(before_reorg_tip_height).await?;
565
566            let address = Actor::new(config.secret_key, config.protocol_paramset.network).address;
567            let tx = rpc
568                .send_to_address(&address, Amount::from_sat(10000))
569                .await?;
570
571            assert!(!rpc.is_tx_on_chain(&tx.txid).await?);
572            rpc.mine_blocks(1).await?;
573            assert!(rpc.is_tx_on_chain(&tx.txid).await?);
574
575            // Make the second branch longer and perform a reorg.
576            let reorg_depth = 4;
577            da1.generate(reorg_depth).await.unwrap();
578            f.bitcoin_nodes.connect_nodes().await?;
579            f.bitcoin_nodes.wait_for_sync(None).await?;
580
581            // Check that reorg happened.
582            let current_tip_height = rpc.get_block_count().await?;
583            assert_eq!(
584                before_reorg_tip_height + reorg_depth,
585                current_tip_height,
586                "Re-org did not occur"
587            );
588            let current_tip_hash = rpc.get_block_hash(current_tip_height).await?;
589            assert_ne!(
590                before_reorg_tip_hash, current_tip_hash,
591                "Re-org did not occur"
592            );
593
594            assert!(!rpc.is_tx_on_chain(&tx.txid).await?);
595
596            Ok(())
597        }
598    }
599
600    #[tokio::test]
601    async fn reorg_checks() -> Result<()> {
602        TestCaseRunner::new(ReorgChecks).run().await
603    }
604
605    mod retry_config_tests {
606        use crate::extended_bitcoin_rpc::RetryConfig;
607
608        use std::time::Duration;
609
610        #[test]
611        fn test_retry_config_default() {
612            let config = RetryConfig::default();
613            assert_eq!(config.initial_delay_millis, 100);
614            assert_eq!(config.max_delay, Duration::from_secs(30));
615            assert_eq!(config.max_attempts, 5);
616            assert_eq!(config.backoff_multiplier, 2);
617            assert!(!config.is_jitter);
618        }
619
620        #[test]
621        fn test_retry_config_custom() {
622            let initial = 200;
623            let max = Duration::from_secs(10);
624            let attempts = 7;
625            let backoff_multiplier = 3;
626            let jitter = true;
627            let config = RetryConfig::new(initial, max, attempts, backoff_multiplier, jitter);
628            assert_eq!(config.initial_delay_millis, initial);
629            assert_eq!(config.max_delay, max);
630            assert_eq!(config.max_attempts, attempts);
631            assert_eq!(config.backoff_multiplier, backoff_multiplier);
632            assert!(config.is_jitter);
633        }
634
635        #[test]
636        fn test_retry_strategy_initial_delay() {
637            // Test that the first delay matches the expected initial_delay_millis
638            // when initial_delay_millis is divisible by backoff_multiplier
639            let initial_delay_millis = 100;
640            let backoff_multiplier = 2;
641            let config = RetryConfig::new(
642                initial_delay_millis,
643                Duration::from_secs(30),
644                5,
645                backoff_multiplier,
646                false, // no jitter for predictable testing
647            );
648
649            let mut strategy = config.get_strategy();
650            let first_delay = strategy.next().expect("Should have first delay");
651
652            // The formula is: first_delay = base * factor
653            // We set base = initial_delay_millis / backoff_multiplier
654            // So: first_delay = (initial_delay_millis / backoff_multiplier) * backoff_multiplier = initial_delay_millis
655            assert_eq!(
656                first_delay,
657                Duration::from_millis(initial_delay_millis),
658                "First delay should match initial_delay_millis"
659            );
660
661            // Verify the second delay is approximately initial_delay_millis * backoff_multiplier
662            let second_delay = strategy.next().expect("Should have second delay");
663            assert_eq!(
664                second_delay,
665                Duration::from_millis(initial_delay_millis * backoff_multiplier),
666                "Second delay should be initial_delay_millis * backoff_multiplier"
667            );
668        }
669    }
670
671    mod retryable_error_tests {
672        use bitcoin::{hashes::Hash, BlockHash, Txid};
673
674        use crate::extended_bitcoin_rpc::RetryableError;
675
676        use super::*;
677        use std::io::{Error as IoError, ErrorKind};
678
679        #[test]
680        fn test_bitcoin_rpc_error_retryable_io_errors() {
681            let retryable_kinds = [
682                ErrorKind::ConnectionRefused,
683                ErrorKind::ConnectionReset,
684                ErrorKind::ConnectionAborted,
685                ErrorKind::NotConnected,
686                ErrorKind::BrokenPipe,
687                ErrorKind::TimedOut,
688                ErrorKind::Interrupted,
689                ErrorKind::UnexpectedEof,
690            ];
691
692            for kind in retryable_kinds {
693                let io_error = IoError::new(kind, "test error");
694                let rpc_error = bitcoincore_rpc::Error::Io(io_error);
695                assert!(
696                    rpc_error.is_retryable(),
697                    "ErrorKind::{kind:?} should be retryable"
698                );
699            }
700        }
701
702        #[test]
703        fn test_bitcoin_rpc_error_non_retryable_io_errors() {
704            let non_retryable_kinds = [
705                ErrorKind::PermissionDenied,
706                ErrorKind::NotFound,
707                ErrorKind::InvalidInput,
708                ErrorKind::InvalidData,
709            ];
710
711            for kind in non_retryable_kinds {
712                let io_error = IoError::new(kind, "test error");
713                let rpc_error = bitcoincore_rpc::Error::Io(io_error);
714                assert!(
715                    !rpc_error.is_retryable(),
716                    "ErrorKind::{kind:?} should not be retryable"
717                );
718            }
719        }
720
721        #[test]
722        fn test_bitcoin_rpc_error_auth_not_retryable() {
723            let auth_error = bitcoincore_rpc::Error::Auth("Invalid credentials".to_string());
724            assert!(!auth_error.is_retryable());
725        }
726
727        #[test]
728        fn test_bitcoin_rpc_error_url_parse_not_retryable() {
729            let url_error = url::ParseError::EmptyHost;
730            let rpc_error = bitcoincore_rpc::Error::UrlParse(url_error);
731            assert!(!rpc_error.is_retryable());
732        }
733
734        #[test]
735        fn test_bitcoin_rpc_error_invalid_cookie_not_retryable() {
736            let rpc_error = bitcoincore_rpc::Error::InvalidCookieFile;
737            assert!(!rpc_error.is_retryable());
738        }
739
740        #[test]
741        fn test_bitcoin_rpc_error_returned_error_non_retryable_patterns() {
742            let non_retryable_messages = [
743                "insufficient funds",
744                "transaction already in blockchain",
745                "invalid transaction",
746                "not found in mempool",
747                "transaction conflict",
748            ];
749
750            for msg in non_retryable_messages {
751                let rpc_error = bitcoincore_rpc::Error::ReturnedError(msg.to_string());
752                assert!(
753                    !rpc_error.is_retryable(),
754                    "Message '{msg}' should not be retryable"
755                );
756            }
757        }
758
759        #[test]
760        fn test_bitcoin_rpc_error_unexpected_structure_retryable() {
761            let rpc_error = bitcoincore_rpc::Error::UnexpectedStructure;
762            assert!(rpc_error.is_retryable());
763        }
764
765        #[test]
766        fn test_bitcoin_rpc_error_serialization_errors_not_retryable() {
767            use bitcoin::consensus::encode::Error as EncodeError;
768
769            let serialization_errors = [
770                bitcoincore_rpc::Error::BitcoinSerialization(EncodeError::Io(
771                    IoError::other("test").into(),
772                )),
773                // bitcoincore_rpc::Error::Hex(HexToBytesError::InvalidChar(InvalidCharError{invalid: 0})),
774                bitcoincore_rpc::Error::Json(serde_json::Error::io(IoError::other("test"))),
775            ];
776
777            for error in serialization_errors {
778                assert!(
779                    !error.is_retryable(),
780                    "Serialization error should not be retryable"
781                );
782            }
783        }
784
785        #[test]
786        fn test_bridge_rpc_error_retryable() {
787            // Test permanent errors
788            assert!(
789                !BitcoinRPCError::TransactionAlreadyInBlock(BlockHash::all_zeros()).is_retryable()
790            );
791            assert!(!BitcoinRPCError::BumpFeeUTXOSpent(Default::default()).is_retryable());
792
793            // Test potentially retryable errors
794            let txid = Txid::all_zeros();
795            let fee_rate = FeeRate::from_sat_per_vb_unchecked(1);
796            assert!(BitcoinRPCError::BumpFeeError(txid, fee_rate).is_retryable());
797
798            // Test Other error with retryable patterns
799            let retryable_other = BitcoinRPCError::Other(eyre::eyre!("timeout occurred"));
800            assert!(retryable_other.is_retryable());
801
802            let non_retryable_other = BitcoinRPCError::Other(eyre::eyre!("permission denied"));
803            assert!(!non_retryable_other.is_retryable());
804        }
805    }
806
807    mod rpc_call_retry_tests {
808
809        use crate::extended_bitcoin_rpc::RetryableError;
810
811        use super::*;
812        use secrecy::SecretString;
813
814        #[tokio::test]
815        async fn test_rpc_call_retry_with_invalid_host() {
816            let user = SecretString::new("user".to_string().into());
817            let password = SecretString::new("password".to_string().into());
818            let invalid_url = "http://nonexistent-host:8332".to_string();
819
820            let res = ExtendedBitcoinRpc::connect(invalid_url, user, password, None).await;
821
822            assert!(res.is_err());
823            assert!(!res.unwrap_err().is_retryable());
824        }
825    }
826
827    mod convenience_method_tests {
828        use super::*;
829
830        #[tokio::test]
831        async fn test_get_block_hash_with_retry() {
832            let mut config = create_test_config_with_thread_name().await;
833            let regtest = create_regtest_rpc(&mut config).await;
834            let rpc = regtest.rpc();
835
836            // Mine a block first
837            rpc.mine_blocks(1).await.unwrap();
838            let height = rpc.get_block_count().await.unwrap();
839
840            let result = rpc.get_block_hash(height).await;
841            assert!(result.is_ok());
842
843            let expected_hash = rpc.get_block_hash(height).await.unwrap();
844            assert_eq!(result.unwrap(), expected_hash);
845        }
846
847        #[tokio::test]
848        async fn test_get_tx_out_with_retry() {
849            let mut config = create_test_config_with_thread_name().await;
850            let regtest = create_regtest_rpc(&mut config).await;
851            let rpc = regtest.rpc();
852
853            // Create a transaction
854            let keypair = Keypair::from_secret_key(&SECP, &config.secret_key);
855            let (xonly, _parity) = XOnlyPublicKey::from_keypair(&keypair);
856            let address = Address::p2tr(&SECP, xonly, None, config.protocol_paramset.network);
857            let amount = Amount::from_sat(10000);
858
859            let utxo = rpc.send_to_address(&address, amount).await.unwrap();
860
861            let result = rpc.get_tx_of_txid(&utxo.txid).await;
862            assert!(result.is_ok());
863
864            let tx = result.unwrap();
865            assert_eq!(tx.compute_txid(), utxo.txid);
866        }
867
868        #[tokio::test]
869        async fn test_send_to_address_with_retry() {
870            let mut config = create_test_config_with_thread_name().await;
871            let regtest = create_regtest_rpc(&mut config).await;
872            let rpc = regtest.rpc();
873
874            let keypair = Keypair::from_secret_key(&SECP, &config.secret_key);
875            let (xonly, _parity) = XOnlyPublicKey::from_keypair(&keypair);
876            let address = Address::p2tr(&SECP, xonly, None, config.protocol_paramset.network);
877            let amount = Amount::from_sat(10000);
878
879            let result = rpc.send_to_address(&address, amount).await;
880            assert!(result.is_ok());
881
882            let outpoint = result.unwrap();
883
884            // Verify the transaction exists
885            let tx = rpc.get_tx_of_txid(&outpoint.txid).await.unwrap();
886            assert_eq!(tx.output[outpoint.vout as usize].value, amount);
887        }
888
889        #[tokio::test]
890        async fn test_bump_fee_with_retry() {
891            let mut config = create_test_config_with_thread_name().await;
892            let regtest = create_regtest_rpc(&mut config).await;
893            let rpc = regtest.rpc();
894
895            let keypair = Keypair::from_secret_key(&SECP, &config.secret_key);
896            let (xonly, _parity) = XOnlyPublicKey::from_keypair(&keypair);
897            let address = Address::p2tr(&SECP, xonly, None, config.protocol_paramset.network);
898            let amount = Amount::from_sat(10000);
899
900            // Create an unconfirmed transaction
901            let utxo = rpc.send_to_address(&address, amount).await.unwrap();
902            let new_fee_rate = FeeRate::from_sat_per_vb_unchecked(10000);
903
904            let result = rpc.bump_fee_with_fee_rate(utxo.txid, new_fee_rate).await;
905            assert!(result.is_ok());
906
907            let new_txid = result.unwrap();
908            // Should return a different txid since fee was actually bumped
909            assert_ne!(new_txid, utxo.txid);
910        }
911    }
912}