From cc0df5b0c894017806fc0091ad9db09e433bec60 Mon Sep 17 00:00:00 2001 From: Ethan Date: Thu, 12 Nov 2026 09:28:55 +0000 Subject: [PATCH 1/2] fix: keep peg-in instances from stalling on lagging backends and missed messages --- node/src/aggregates/instance.rs | 135 +++++++++++++++++++++----- node/src/aggregates/instance_jobs.rs | 9 +- node/src/aggregates/instance_scan.rs | 55 +++++++---- node/src/aggregates/instance_tests.rs | 80 +++++++++++++-- node/src/utils/btc.rs | 52 ++++++++++ node/src/utils/goat_chain.rs | 17 +--- 6 files changed, 282 insertions(+), 66 deletions(-) diff --git a/node/src/aggregates/instance.rs b/node/src/aggregates/instance.rs index f342df1a..a1c4b9b7 100644 --- a/node/src/aggregates/instance.rs +++ b/node/src/aggregates/instance.rs @@ -399,6 +399,9 @@ pub enum InstanceAlert { /// Goat refused the data of a confirmed peg-in for good: no instance /// parameters stored, no graph started by this operator. ConfirmInstanceRejected, + /// The committee answers do not yield the peg-in transactions; the instance + /// is failed instead of waiting forever for a Prepare nobody can build. + PeginTxidsUnderivable, } impl InstanceAlert { @@ -411,6 +414,7 @@ impl InstanceAlert { InstanceAlert::PeginConfirmRoundFailed => "pegin_confirm_round_failed", InstanceAlert::AnswerPeginRequestFailed => "answer_pegin_request_failed", InstanceAlert::ConfirmInstanceRejected => "confirm_instance_rejected", + InstanceAlert::PeginTxidsUnderivable => "pegin_txids_underivable", } } } @@ -636,11 +640,21 @@ pub async fn signing_gate( if status.is_failed() { return Ok(SigningGate::Closed(format!("instance is {status}"))); } - if instance.btc_height <= 0 { - return Ok(SigningGate::Open); + let mut prepare_height = instance.btc_height; + if prepare_height <= 0 { + // The scan has not stored the Prepare height yet; ask Bitcoin rather than + // signing blind, since T0 may already have passed on a lagging node. + let Some(prepare_txid) = instance.btc_txid.clone() else { + anyhow::bail!("instance {instance_id} has no Peg-In-Prepare txid yet"); + }; + match btc_client.get_tx_info(&prepare_txid.0).await?.and_then(|tx| tx.status.block_height) { + Some(height) => prepare_height = i64::from(height), + // T0 counts from the Prepare confirmation, which has not happened. + None => return Ok(SigningGate::Open), + } } let height = i64::from(btc_client.get_height().await?); - Ok(signing_gate_for(status, instance.btc_height, height, &PeginDeadlines::from_env())) + Ok(signing_gate_for(status, prepare_height, height, &PeginDeadlines::from_env())) } // -------------------------------------------------------------------- handler @@ -702,10 +716,32 @@ impl InstanceAggregate { ctx: &mut ApplyContext<'_>, instance: &Instance, status: InstanceBridgeInStatus, - transition: Transition, + mut transition: Transition, ) -> anyhow::Result<()> { let instance_id = instance.instance_id; let mut final_status = status; + // The answers fix the three peg-in txids. Answers they cannot be derived + // from never will be: fail the instance and say so. + let mut pegin_txids_derived = None; + if transition.next == Some(InstanceBridgeInStatus::CommitteesAnswered) + && let Some(answers) = transition.committees_answers.clone() + { + let mut seeded = instance.clone(); + seeded.committees_answers = answers; + match pegin_txids(&seeded) { + Ok(txids) => pegin_txids_derived = Some(txids), + Err(error) => { + warn!( + event = "instance_transition", + instance_id = %instance_id, + error = %error, + "could not derive the peg-in txids from the committee answers; failing the instance" + ); + transition.next = Some(InstanceBridgeInStatus::NoEnoughCommitteesAnswered); + transition.alerts.push(InstanceAlert::PeginTxidsUnderivable); + } + } + } if let Some(next) = transition.next.filter(|next| *next != status) { let mut update = InstanceUpdate::new_with_instance_id(instance_id) .with_status(next.to_string()) @@ -714,25 +750,13 @@ impl InstanceAggregate { update = update.with_btc_height(height); } if let Some(answers) = transition.committees_answers.clone() { - update = update.with_committees_answers(answers.clone()); - if next == InstanceBridgeInStatus::CommitteesAnswered { - let mut seeded = instance.clone(); - seeded.committees_answers = answers; - match pegin_txids(&seeded) { - Ok((deposit, confirm, cancel)) => { - update = update - .with_btc_txid(deposit) - .with_pegin_confirm_txid(confirm) - .with_pegin_cancel_txid(cancel); - } - Err(error) => warn!( - event = "instance_transition", - instance_id = %instance_id, - error = %error, - "could not derive the peg-in txids from the committee answers" - ), - } - } + update = update.with_committees_answers(answers); + } + if let Some((deposit, confirm, cancel)) = pegin_txids_derived { + update = update + .with_btc_txid(deposit) + .with_pegin_confirm_txid(confirm) + .with_pegin_cancel_txid(cancel); } if let Some(tx_hash) = transition.post_pegin_txhash.clone() { update = update.with_post_pegin(tx_hash); @@ -794,7 +818,18 @@ impl InstanceAggregate { } } RelayerL1Broadcasted => { - self.close_confirm_round(ctx, instance.instance_id, "Peg-In-Confirm confirmed"); + // The nonce rounds are over, but the relayer still needs every + // member's PeginConfirmPartialSig (it carries the endorsement for + // postPeginData): that row keeps being resent until L2Minted. + for kind in ["PeginConfirmNonce", "PeginConfirmNonceConsensus"] { + ctx.effects.close_outbox( + EngineOutboxCloseTarget::Row(format!( + "instance:{}:{kind}", + instance.instance_id + )), + "Peg-In-Confirm confirmed", + ); + } if self.relayer { self.job(ctx, JOB_POST_PEGIN_DATA, Vec::new()); } @@ -1605,6 +1640,58 @@ mod tests { } } + #[tokio::test] + async fn signing_gate_without_a_stored_prepare_height_asks_bitcoin() { + use bitcoin::hashes::Hash; + let db = store::create_local_db("sqlite::memory:").await; + let (btc, mock) = BTCClient::new_mock_client(); + let prepare = bitcoin::Txid::from_byte_array([7; 32]); + let mut row = Instance { + instance_id: Uuid::new_v4(), + network: "regtest".to_string(), + input_utxos: "[]".to_string(), + status: Presigned.to_string(), + created_at: 1, + updated_at: 1, + ..Default::default() + }; + db.acquire().await.unwrap().insert_instance_if_absent(&row).await.unwrap(); + assert!( + signing_gate(&db, &btc, row.instance_id).await.is_err(), + "no Prepare txid: undecided, retried" + ); + + row.instance_id = Uuid::new_v4(); + row.btc_txid = Some(prepare.into()); + db.acquire().await.unwrap().insert_instance_if_absent(&row).await.unwrap(); + assert!(signing_gate(&db, &btc, row.instance_id).await.unwrap().is_open(), "unconfirmed"); + + mock.set_tx( + prepare, + esplora_client::Tx { + txid: prepare, + version: 2, + locktime: 0, + vin: Vec::new(), + vout: Vec::new(), + size: 0, + weight: 0, + status: esplora_client::TxStatus { + confirmed: true, + block_height: Some(100), + block_hash: None, + block_time: None, + }, + fee: 0, + }, + ); + mock.set_height(100 + 1_000_000); + assert!( + !signing_gate(&db, &btc, row.instance_id).await.unwrap().is_open(), + "T0 counted from the confirmed Prepare" + ); + } + #[test] fn phases_follow_the_phase_table() { assert_eq!(phase_of(UserInited), PHASE_ANSWER); diff --git a/node/src/aggregates/instance_jobs.rs b/node/src/aggregates/instance_jobs.rs index cf617340..adbfb8a8 100644 --- a/node/src/aggregates/instance_jobs.rs +++ b/node/src/aggregates/instance_jobs.rs @@ -35,7 +35,7 @@ use crate::utils::{ get_committee_pub_nonce_for_instance, get_committee_pub_nonces_for_instance, get_graph_by_instance_id_and_operator_pubkey, get_instance_parameters, has_required_presigned_graphs, is_io_not_found_error, order_committee_values, - read_instance_info_from_goat, read_pegin_request, + pegin_inputs_answerable, read_instance_info_from_goat, read_pegin_request, store_committee_agg_nonce_consensus_for_instance, store_committee_endorse_sig_for_pegin, store_committee_partial_sig_for_instance, store_committee_pub_nonce_for_instance, store_instance_parameters, tx_visible, verify_pegin_endorsement, @@ -252,14 +252,17 @@ async fn answer_pegin_request(deps: &JobDeps, instance_id: Uuid) -> Result Some(InstanceBridgeInStatus::UserInited) => {} other => return Step::ignore(format!("instance is {other:?}; answer window closed")), } - let (_, _, answered_by) = - read_pegin_request(&deps.btc_client, &deps.goat_client, instance_id).await?; + let (user_info, _, answered_by) = read_pegin_request(&deps.goat_client, instance_id).await?; // Gateway.answerPeginRequest accepts a repeat answer (it overwrites the // stored pubkey and emits CommitteeResponse again), so every re-run must // check what the contract already holds for this signer. if answered_by.contains(&deps.goat_client.get_default_signer_address()) { return Step::ignore("this committee already answered"); } + // Retried until the inputs settle; leaving UserInited cancels this job. + if let Some(reason) = pegin_inputs_answerable(&deps.btc_client, &user_info.inputs).await? { + return Step::retry(reason, 30); + } let committee_master_key = CommitteeMasterKey::new(get_bitvm_key()?); let instance_keypair = load_or_create_committee_instance_keypair( &deps.local_db, diff --git a/node/src/aggregates/instance_scan.rs b/node/src/aggregates/instance_scan.rs index 49b49386..d3e0d114 100644 --- a/node/src/aggregates/instance_scan.rs +++ b/node/src/aggregates/instance_scan.rs @@ -33,6 +33,9 @@ use uuid::Uuid; const TASK_KEY_ANSWER_WINDOW: &str = "instance_answer_window_scan"; const TASK_KEY_BTC: &str = "instance_btc_scan"; +/// Instances parked in CommitteesAnswered or Timeout page separately: many +/// never move again and must not use up the live instances' budget. +const TASK_KEY_BTC_PARKED: &str = "instance_btc_scan_parked"; const SCAN_MARKS_LIMIT: usize = 50_000; // ----------------------------------------------------------------- paging @@ -177,41 +180,46 @@ fn mark_settled_timeout(instance_id: Uuid) { settled.insert(instance_id); } -/// Statuses the Bitcoin scan follows. The key-deletion statuses are only -/// followed on committee nodes with deletion enabled. -fn scanned_statuses(actor: &Actor) -> (Vec, bool) { +/// Statuses the Bitcoin scan follows: the live ones and the parked ones, +/// paged apart. The key-deletion statuses are only followed on committee +/// nodes with deletion enabled. +fn scanned_statuses(actor: &Actor) -> (Vec, Vec, bool) { use InstanceBridgeInStatus::*; let key_scan = *actor == Actor::Committee && is_enable_committee_instance_key_delete(); - let mut statuses = vec![CommitteesAnswered, UserBroadcastPeginPrepare, Presigned, Timeout]; + let mut live = vec![UserBroadcastPeginPrepare, Presigned]; if key_scan { - statuses.extend([RelayerL1Broadcasted, RelayerL2Minted]); + live.extend([RelayerL1Broadcasted, RelayerL2Minted]); } - (statuses.iter().map(ToString::to_string).collect(), key_scan) + let parked = [CommitteesAnswered, Timeout]; + ( + live.iter().map(ToString::to_string).collect(), + parked.iter().map(ToString::to_string).collect(), + key_scan, + ) } -/// Record a Bitcoin snapshot for every live instance. +/// Record a Bitcoin snapshot for every scanned instance: one page of the live +/// instances and one page of the parked ones per tick. pub async fn scan_instances_on_bitcoin( local_db: &LocalDB, btc_client: &BTCClient, engine: &EngineHandle, actor: &Actor, ) -> anyhow::Result<()> { - let (statuses, key_scan) = scanned_statuses(actor); - let mut query = InstanceQuery::default().with_statuses(statuses); + let (live, parked, key_scan) = scanned_statuses(actor); + let mut live_query = InstanceQuery::default().with_statuses(live); if key_scan { - query = query.with_raw_condition(format!( + live_query = live_query.with_raw_condition(format!( "(status NOT IN ('{}', '{}') OR key_deleted = 0)", InstanceBridgeInStatus::RelayerL1Broadcasted, InstanceBridgeInStatus::RelayerL2Minted )); } - let instances = find_one_instance_page( - local_db, - TASK_KEY_BTC, - query, - get_instance_maintenance_batch_size(), - ) - .await?; + let batch = get_instance_maintenance_batch_size(); + let mut instances = find_one_instance_page(local_db, TASK_KEY_BTC, live_query, batch).await?; + let parked_query = InstanceQuery::default().with_statuses(parked); + instances + .extend(find_one_instance_page(local_db, TASK_KEY_BTC_PARKED, parked_query, batch).await?); if instances.is_empty() { return Ok(()); } @@ -583,6 +591,19 @@ mod tests { use client::goat_chain::{PeginData, PeginStatus}; use store::GoatTxType; + #[test] + fn parked_instances_do_not_share_the_live_page() { + use InstanceBridgeInStatus::*; + let (live, parked, _) = scanned_statuses(&Actor::Operator); + for status in [CommitteesAnswered, Timeout] { + assert!(parked.contains(&status.to_string()) && !live.contains(&status.to_string())); + } + for status in [UserBroadcastPeginPrepare, Presigned] { + assert!(live.contains(&status.to_string()) && !parked.contains(&status.to_string())); + } + assert_ne!(TASK_KEY_BTC, TASK_KEY_BTC_PARKED); + } + async fn database() -> (LocalDB, tempfile::TempDir) { let dir = tempfile::tempdir().unwrap(); let db = LocalDB::new_with_busy_timeout( diff --git a/node/src/aggregates/instance_tests.rs b/node/src/aggregates/instance_tests.rs index 62894150..a78772fc 100644 --- a/node/src/aggregates/instance_tests.rs +++ b/node/src/aggregates/instance_tests.rs @@ -173,6 +173,35 @@ fn instance_row(status: InstanceBridgeInStatus, prepare_height: i64) -> Instance } } +/// A row whose committee answers yield the three peg-in txids, and those answers. +fn answerable_row( + status: InstanceBridgeInStatus, + members: usize, +) -> (Instance, IndexMap>) { + use bitcoin::secp256k1::{Keypair, SECP256K1, SecretKey}; + let key = |byte: u8| { + Keypair::from_secret_key(SECP256K1, &SecretKey::from_slice(&[byte; 32]).unwrap()) + }; + let mut row = instance_row(status, 0); + let address = crate::utils::get_rand_btc_address_p2wpkh(bitcoin::Network::Regtest); + row.to_addr = format!("0x{}", "11".repeat(20)); + row.amount = 10_000; + row.fees = store::UInt64Array3([100; 3]); + row.input_utxos = + serde_json::to_string(&[client::Utxo { txid: [9; 32], vout: 0, amount_sats: 50_000 }]) + .unwrap(); + row.user_xonly_pubkey = store::ByteArray32(key(0x51).x_only_public_key().0.serialize()); + row.user_change_addr = address.clone(); + row.user_refund_addr = address; + let answers = (0..members) + .map(|index| { + let pubkey = bitcoin::PublicKey::new(key(0x61 + index as u8).public_key()); + (format!("0x{index:040x}"), pubkey.to_bytes()) + }) + .collect(); + (row, answers) +} + impl Harness { async fn stop(self) { self.cancel.cancel(); @@ -568,20 +597,32 @@ async fn no_enough_committees_answered_when_the_window_closes_below_quorum() { async fn committees_answered_at_quorum_keeps_the_key() { use InstanceBridgeInStatus::*; let t = start(Actor::Committee, false, true).await; - let id = t.insert(&instance_row(UserInited, 0)).await; - let mut answers = IndexMap::new(); - answers.insert("0xa".to_string(), vec![1u8; 33]); - answers.insert("0xb".to_string(), vec![2u8; 33]); + let (row, answers) = answerable_row(UserInited, 2); + let id = t.insert(&row).await; let window = AnswerWindow { goat_height: 200, window_blocks: 50, quorum: 2, answers }; t.submit(window.event(id).unwrap()).await; let instance = t.wait_status(id, CommitteesAnswered).await; assert_eq!(instance.committees_answers.len(), 2); + assert!(instance.btc_txid.is_some(), "the answers fix the Prepare txid"); assert!(!instance.key_deleted); assert!(t.job_actions(id).await.is_empty()); assert_eq!(t.engine_status(id).await.1, PHASE_AWAIT_PREPARE); t.stop().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn answers_that_yield_no_peg_in_txids_fail_the_instance() { + use InstanceBridgeInStatus::*; + let t = start(Actor::Committee, false, false).await; + let id = t.insert(&instance_row(UserInited, 0)).await; + let mut answers = IndexMap::new(); + answers.insert("0xa".to_string(), vec![1u8; 33]); // not a public key + let window = AnswerWindow { goat_height: 200, window_blocks: 50, quorum: 1, answers }; + t.submit(window.event(id).unwrap()).await; + t.wait_status(id, NoEnoughCommitteesAnswered).await; + t.stop().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn user_canceled_from_the_confirm_phase_deletes_the_key() { use InstanceBridgeInStatus::*; @@ -786,14 +827,13 @@ async fn a_pegin_request_is_answered_by_committee_nodes_until_the_window_closes( t.stop().await; let t = start(Actor::Committee, false, false).await; - let id = t.insert(&instance_row(UserInited, 0)).await; + let (row, answers) = answerable_row(UserInited, 1); + let id = t.insert(&row).await; t.submit(pegin_request_event(id, &request).unwrap()).await; let job = t.wait_job(id, JOB_ANSWER_PEGIN_REQUEST, "Done").await; assert_eq!(job.phase, PHASE_ANSWER); assert_eq!(t.calls().len(), 1); // A request seen again after the Answer phase changes nothing. - let mut answers = IndexMap::new(); - answers.insert("0xa".to_string(), vec![1u8; 33]); let window = AnswerWindow { goat_height: 200, window_blocks: 50, quorum: 1, answers }; t.submit(window.event(id).unwrap()).await; t.wait_status(id, CommitteesAnswered).await; @@ -846,10 +886,34 @@ async fn a_round_message_becomes_an_ingest_job_whose_plan_is_sent_until_the_conf 1 ); - // Peg-In-Confirm confirmed: the Confirm phase's deliveries close. + // This member's partial signature, still owed to a relayer that missed it. + let partial_sig_outbox = format!("instance:{id}:PeginConfirmPartialSig"); + t.db.acquire() + .await + .unwrap() + .insert_engine_outbox_message( + &NewEngineOutboxMessage { + outbox_id: partial_sig_outbox.clone(), + aggregate_kind: INSTANCE_KIND.to_string(), + aggregate_id: id.to_string(), + phase_ref: PHASE_CONFIRM.to_string(), + kind: "PeginConfirmPartialSig".to_string(), + topic: "topic".to_string(), + payload: b"partial".to_vec(), + ack_set: None, + first_at: 1, + }, + 1, + ) + .await + .unwrap(); + + // Peg-In-Confirm confirmed: the nonce rounds' deliveries close, the + // partial signature keeps going out until Goat mints. t.snapshot(id, presign_snapshot(1_050, TxFact::confirmed_at(1_049), TxFact::UNKNOWN)).await; t.wait_status(id, RelayerL1Broadcasted).await; t.wait_outbox(&outbox_id, "Closed").await; + assert_eq!(t.outbox_state(&partial_sig_outbox).await, "Open"); // A late partial signature is still ingested (it carries the endorsement // the relayer's post needs); a late nonce is not. t.submit(t.round_message("PeginConfirmPartialSig", OTHER_PEER, id)).await; diff --git a/node/src/utils/btc.rs b/node/src/utils/btc.rs index 335b0d59..051e310d 100644 --- a/node/src/utils/btc.rs +++ b/node/src/utils/btc.rs @@ -569,6 +569,36 @@ pub async fn check_bridge_in_uxto_available_or_self_spent( Ok(true) } +/// Whether a committee member can answer a peg-in request with these inputs. +/// Only a confirmed spend by another transaction rules the request out (an +/// [`SpecialError::InvalidPeginRequest`]). An outpoint the backend does not know +/// yet, or a spend still in the mempool, may change: `Some(reason)` asks the +/// caller to look again later. +pub async fn pegin_inputs_answerable( + btc_client: &BTCClient, + inputs: &[goat::transactions::base::Input], +) -> Result> { + for input in inputs { + let (txid, vout) = (input.outpoint.txid, input.outpoint.vout); + match btc_client.get_output_status(&txid, u64::from(vout)).await? { + Some(status) if !status.spent => {} + Some(status) if status.status.as_ref().is_some_and(|tx_status| tx_status.confirmed) => { + anyhow::bail!(crate::error::SpecialError::InvalidPeginRequest(format!( + "input {txid}:{vout} is spent by confirmed transaction {:?}", + status.txid + ))); + } + Some(_) => return Ok(Some(format!("input {txid}:{vout} is spent in the mempool"))), + None => { + return Ok(Some(format!( + "input {txid}:{vout} is not known to the Bitcoin backend" + ))); + } + } + } + Ok(None) +} + #[cfg(test)] mod input_availability_tests { use super::*; @@ -608,4 +638,26 @@ mod input_availability_tests { mock.set_output_status(funding, 0, spend(other, true)); assert!(!check().await.unwrap(), "a confirmed conflict discards the request"); } + + #[tokio::test] + async fn committee_answers_wait_for_unknown_or_mempool_spent_inputs() { + use goat::transactions::base::Input; + let (btc, mock) = BTCClient::new_mock_client(); + let funding = Txid::from_byte_array([4; 32]); + let other = Txid::from_byte_array([5; 32]); + let inputs = [Input { + outpoint: bitcoin::OutPoint { txid: funding, vout: 0 }, + amount: bitcoin::Amount::from_sat(1), + }]; + + assert!(pegin_inputs_answerable(&btc, &inputs).await.unwrap().is_some(), "unknown"); + mock.set_output_status(funding, 0, spend(other, false)); + assert!(pegin_inputs_answerable(&btc, &inputs).await.unwrap().is_some(), "mempool spend"); + mock.set_output_status(funding, 0, spend(other, true)); + let error = pegin_inputs_answerable(&btc, &inputs).await.unwrap_err(); + assert!(matches!( + crate::error::classify_failure(&error), + crate::error::FailureClass::Permanent(_) + )); + } } diff --git a/node/src/utils/goat_chain.rs b/node/src/utils/goat_chain.rs index 7a44ce61..c18e7c56 100644 --- a/node/src/utils/goat_chain.rs +++ b/node/src/utils/goat_chain.rs @@ -8,7 +8,7 @@ use anyhow::{Result, anyhow, bail}; use bitcoin::hashes::Hash; use bitcoin::{Address, Amount, OutPoint, PublicKey, Txid, XOnlyPublicKey}; use bitvm_lib::types::{BitvmGcGraph, BitvmGcInstanceParameters, UserInfo}; -use client::{btc_chain::BTCClient, goat_chain::GOATClient}; +use client::goat_chain::GOATClient; use goat::transactions::base::Input; use libp2p::PeerId; use std::str::FromStr; @@ -20,8 +20,6 @@ use client::goat_chain::{GraphData, PeginStatus}; use store::GraphStatus; use uuid::Uuid; -use super::btc::outpoint_available; - pub fn build_graph_data(graph: &BitvmGcGraph) -> Result { // operator pubkey: first byte is prefix, next 32 bytes are key let op_pk_bytes = graph.parameters.operator_pubkey.to_bytes(); @@ -144,8 +142,9 @@ pub async fn validate_committee_with_evm_address( )) } +/// The pending request on Goat, parsed. Its inputs are checked on Bitcoin by +/// the caller ([`crate::utils::pegin_inputs_answerable`]). pub async fn read_pegin_request( - btc_client: &BTCClient, goat_client: &GOATClient, instance_id: Uuid, ) -> Result<(UserInfo, Amount, Vec)> { @@ -192,16 +191,6 @@ pub async fn read_pegin_request( amount: Amount::from_sat(u.amount_sats), }) .collect(); - // TODO: we need to run our own bitcoin node in case of downtime or ddos attack. - for input in &inputs { - if !outpoint_available(btc_client, &input.outpoint.txid, input.outpoint.vout.into()).await? - { - bail!(SpecialError::InvalidPeginRequest(format!( - "input {}:{} is not available", - input.outpoint.txid, input.outpoint.vout - ))); - } - } let user_info = UserInfo { depositor_evm_address: pegin_data.depositor_address, txn_fees: pegin_data.txn_fees, From d12fe4c654cdba41e97bc8bdb15c1263f152ee00 Mon Sep 17 00:00:00 2001 From: Ethan Date: Thu, 12 Nov 2026 09:55:05 +0000 Subject: [PATCH 2/2] fix: reject peg-in requests that cannot build their transactions before answering --- node/src/utils/goat_chain.rs | 90 +++++++++++++++++++++++++++++++++++- 1 file changed, 89 insertions(+), 1 deletion(-) diff --git a/node/src/utils/goat_chain.rs b/node/src/utils/goat_chain.rs index c18e7c56..8120e79f 100644 --- a/node/src/utils/goat_chain.rs +++ b/node/src/utils/goat_chain.rs @@ -199,7 +199,39 @@ pub async fn read_pegin_request( user_refund_address, user_xonly_pubkey, }; - Ok((user_info, Amount::from_sat(pegin_data.pegin_amount_sats), pegin_data.committee_addresses)) + let pegin_amount = Amount::from_sat(pegin_data.pegin_amount_sats); + check_pegin_buildable(network, instance_id, &user_info, pegin_amount)?; + Ok((user_info, pegin_amount, pegin_data.committee_addresses)) +} + +/// The secp256k1 generator, standing in for the committee key that is not known +/// before the answers. +const PLACEHOLDER_COMMITTEE_KEY: &str = + "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; + +/// Reject a request whose own fields (inputs, amount, fees) cannot make the +/// peg-in transactions. The committee key does not change what can be built, +/// so a placeholder stands in for it; without this check the request would be +/// answered and only fail once the answers are in. +fn check_pegin_buildable( + network: bitcoin::Network, + instance_id: Uuid, + user_info: &UserInfo, + pegin_amount: Amount, +) -> Result<()> { + let committee_key = PublicKey::from_str(PLACEHOLDER_COMMITTEE_KEY)?; + let parameters = BitvmGcInstanceParameters { + network, + instance_id, + user_info: user_info.clone(), + pegin_amount, + committee_pubkeys: vec![committee_key], + committee_agg_pubkey: bitvm_lib::types::checked_committee_key(&[committee_key])?, + }; + parameters.build_pegin_tx().map_err(|e| { + SpecialError::InvalidPeginRequest(format!("peg-in transactions cannot be built: {e}")) + })?; + Ok(()) } /// The fee `Gateway.postPeginData` deducts; it reverts when the fee is not @@ -301,3 +333,59 @@ mod fee_tests { assert_eq!(pegin_fee_sats(u64::MAX, u64::MAX, 10_000), 2 * u128::from(u64::MAX)); } } + +#[cfg(test)] +mod tests { + use super::*; + use bitcoin::secp256k1::{Keypair, SECP256K1, SecretKey}; + + fn request(inputs_sats: &[u64], fees: [u64; 3]) -> UserInfo { + let key = Keypair::from_secret_key(SECP256K1, &SecretKey::from_slice(&[0x51; 32]).unwrap()); + let address = Address::from_str(&crate::utils::get_rand_btc_address_p2wpkh( + bitcoin::Network::Regtest, + )) + .unwrap() + .require_network(bitcoin::Network::Regtest) + .unwrap(); + UserInfo { + depositor_evm_address: [0x11; 20], + txn_fees: fees, + inputs: inputs_sats + .iter() + .enumerate() + .map(|(vout, sats)| Input { + outpoint: OutPoint { txid: Txid::from_byte_array([9; 32]), vout: vout as u32 }, + amount: Amount::from_sat(*sats), + }) + .collect(), + user_change_address: address.clone(), + user_refund_address: address, + user_xonly_pubkey: key.x_only_public_key().0, + } + } + + fn check(user_info: &UserInfo, amount: u64) -> Result<()> { + check_pegin_buildable( + bitcoin::Network::Regtest, + Uuid::nil(), + user_info, + Amount::from_sat(amount), + ) + } + + fn rejected(result: Result<()>) -> bool { + matches!( + result.unwrap_err().downcast_ref::(), + Some(SpecialError::InvalidPeginRequest(_)) + ) + } + + #[test] + fn a_request_that_cannot_build_its_peg_in_is_not_answered() { + check(&request(&[50_000], [100; 3]), 10_000).unwrap(); + assert!(rejected(check(&request(&[], [100; 3]), 10_000)), "no inputs"); + assert!(rejected(check(&request(&[5_000], [100; 3]), 10_000)), "inputs short"); + assert!(rejected(check(&request(&[50_000], [u64::MAX, 100, 100]), 10_000)), "fee overflow"); + assert!(rejected(check(&request(&[50_000], [100, 100, u64::MAX]), 10_000)), "refund fee"); + } +}