Skip to content

Commit

Permalink
fix retry logic in bitcoin-da (#591)
Browse files Browse the repository at this point in the history
* fix retry logic in bitcoin-da

* fix test

* review fix

* clippy fix
  • Loading branch information
eyusufatik authored May 18, 2024
1 parent 52c2507 commit 594ba01
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 19 deletions.
38 changes: 20 additions & 18 deletions crates/bitcoin-da/src/helpers/builders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ fn choose_utxos(
#[instrument(level = "trace", skip(utxos), err)]
fn build_commit_transaction(
prev_tx: Option<TxWithId>, // reuse outputs to add commit tx order
utxos: Vec<UTXO>,
mut utxos: Vec<UTXO>,
recipient: Address,
change_address: Address,
output_value: u64,
Expand Down Expand Up @@ -173,20 +173,25 @@ fn build_commit_transaction(
None,
);

// Find least one utxo from prev tx to order tx in one block
let (required_utxo, utxos) = if let Some(tx) = prev_tx {
let (requited_utxos, free_utxos) = utxos
.into_iter()
.partition::<Vec<_>, _>(|utxo| utxo.tx_id == tx.id);

let Some(required_utxo) = requited_utxos.first().cloned() else {
return Err(anyhow!("No spendable UTXO found in previous tx"));
};
// fields other then tx_id, vout, script_pubkey and amount are not really important.
let required_utxo = prev_tx.map(|tx| UTXO {
tx_id: tx.id,
vout: 0,
script_pubkey: tx.tx.output[0].script_pubkey.to_hex_string(),
address: "ANY".into(),
amount: tx.tx.output[0].value.to_sat(),
confirmations: 0,
spendable: true,
solvable: true,
});

if let Some(req_utxo) = &required_utxo {
// if we don't do this, then we might end up using the required utxo twice
// which would yield an invalid transaction
// however using a different txo from the same tx is fine.
utxos.retain(|utxo| !(utxo.vout == req_utxo.vout && utxo.tx_id == req_utxo.tx_id));
}

(Some(required_utxo), free_utxos)
} else {
(None, utxos)
};
let mut iteration = 0;
let mut last_size = size;

Expand Down Expand Up @@ -833,10 +838,7 @@ mod tests {
);

assert!(tx.is_err());
assert_eq!(
format!("{}", tx.unwrap_err()),
"No spendable UTXO found in previous tx"
);
assert_eq!(format!("{}", tx.unwrap_err()), "not enough UTXOs");

let prev_utxos: Vec<UTXO> = prev_tx
.output
Expand Down
3 changes: 2 additions & 1 deletion crates/bitcoin-da/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ impl BitcoinService {
}
};
match this
.send_transaction_with_fee_rate(prev, blob, fee_sat_per_vbyte)
.send_transaction_with_fee_rate(prev.clone(), blob, fee_sat_per_vbyte)
.await
{
Ok(tx) => {
Expand All @@ -130,6 +130,7 @@ impl BitcoinService {
Err(e) => {
error!(?e, "Failed to send transaction to DA layer");
tokio::time::sleep(Duration::from_secs(1)).await;
continue;
}
}
break;
Expand Down

0 comments on commit 594ba01

Please sign in to comment.