From f2f64092b5dbe8a55c15cc18b6e38c1fe0f3f58f Mon Sep 17 00:00:00 2001 From: theluckystrike <51033404+theluckystrike@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:24:44 +0700 Subject: [PATCH 1/2] fix(rest): return 404 from /tx/:txid/outspend/:vout for unknown outputs An unknown txid or an out-of-range vout returned 200 {"spent":false}, the same response as a real unspent output. Look the tx up when the output has no spend and return 404, like GET /tx/:txid does. Fixes #266 --- src/rest.rs | 17 ++++++++++++++--- tests/rest.rs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/src/rest.rs b/src/rest.rs index 05eb339de..d2c111a27 100644 --- a/src/rest.rs +++ b/src/rest.rs @@ -1637,9 +1637,20 @@ fn handle_blocking_request( txid: hash, vout: index.parse::()?, }; - let spend = query - .lookup_spend(&outpoint) - .map_or_else(SpendingValue::default, SpendingValue::from); + let spend = match query.lookup_spend(&outpoint) { + Some(spend) => SpendingValue::from(spend), + None => { + // Not spent: make sure the output exists before reporting it unspent + let tx = query + .lookup_txn(&hash) + .map_err(HttpError::lookup)? + .ok_or_else(|| HttpError::not_found("Transaction not found".to_string()))?; + if outpoint.vout as usize >= tx.output.len() { + return Err(HttpError::not_found("Output not found".to_string())); + } + SpendingValue::default() + } + }; let ttl = ttl_by_depth( spend .status diff --git a/tests/rest.rs b/tests/rest.rs index edc8bc74d..f144d3d92 100644 --- a/tests/rest.rs +++ b/tests/rest.rs @@ -1218,6 +1218,42 @@ fn test_rest_tx_outspends() -> Result<()> { Ok(()) } +#[test] +fn test_rest_tx_outspend() -> Result<()> { + let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap(); + + let addr1 = tester.newaddress()?; + let txid = tester.send(&addr1, "0.5 BTC".parse().unwrap())?; + tester.mine()?; + + let status_and_body = |path: String| -> Result<(u16, String)> { + let resp = ureq::get(&format!("http://{}{}", rest_addr, path)) + .config() + .http_status_as_error(false) + .build() + .call()?; + let status = resp.status().as_u16(); + Ok((status, resp.into_body().read_to_string()?)) + }; + + // An existing unspent output is reported as unspent + let res = get_json(rest_addr, &format!("/tx/{}/outspend/0", txid))?; + assert_eq!(res["spent"].as_bool(), Some(false)); + + // An unknown txid is a 404, like GET /tx/:txid + let (status, body) = status_and_body(format!("/tx/{}/outspend/0", "00".repeat(32)))?; + assert_eq!(status, 404); + assert_eq!(body, "Transaction not found"); + + // An out-of-range vout on an existing tx is a 404 too + let (status, body) = status_and_body(format!("/tx/{}/outspend/9999", txid))?; + assert_eq!(status, 404); + assert_eq!(body, "Output not found"); + + rest_handle.stop(); + Ok(()) +} + #[test] fn test_rest_tx_merkle_proof() -> Result<()> { let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap(); From 64892475a990bb7c4d8e2fa65500647db0190210 Mon Sep 17 00:00:00 2001 From: theluckystrike <51033404+theluckystrike@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:49:37 +0700 Subject: [PATCH 2/2] fix(rest): check outspend existence with a TxOut point lookup Use the TxOut row (mempool, then chain) to confirm an unspent output exists, and only read the full tx from the local store on a miss. Never query bitcoind on this path, so a daemon error in light mode can't become a 404, and DB errors return 503. Add tests for mempool and OP_RETURN outputs, and for light mode. --- src/new_index/schema.rs | 10 +++++ src/rest.rs | 55 ++++++++++++++++++++--- tests/common.rs | 17 ++++++++ tests/rest.rs | 97 +++++++++++++++++++++++++++++++++++------ 4 files changed, 158 insertions(+), 21 deletions(-) diff --git a/src/new_index/schema.rs b/src/new_index/schema.rs index 1cef91200..1d2c82d9f 100644 --- a/src/new_index/schema.rs +++ b/src/new_index/schema.rs @@ -1503,6 +1503,16 @@ impl ChainQuery { lookup_txo(&self.store.txstore_db, outpoint) } + /// Like `lookup_txo`, but surfaces DB errors. Only spendable outputs have a TxOut row. + pub fn try_lookup_txo(&self, outpoint: &OutPoint) -> Result> { + let _timer = self.start_timer("lookup_txo"); + self.store + .txstore_db + .try_get(&TxOutRow::key(outpoint))? + .map(|val| deserialize(&val).chain_err(|| "failed to parse TxOut")) + .transpose() + } + pub fn lookup_txos(&self, outpoints: BTreeSet) -> Result> { let _timer = self.start_timer("lookup_txos"); lookup_txos(&self.store.txstore_db, outpoints) diff --git a/src/rest.rs b/src/rest.rs index d2c111a27..d30ad00f7 100644 --- a/src/rest.rs +++ b/src/rest.rs @@ -1641,13 +1641,7 @@ fn handle_blocking_request( Some(spend) => SpendingValue::from(spend), None => { // Not spent: make sure the output exists before reporting it unspent - let tx = query - .lookup_txn(&hash) - .map_err(HttpError::lookup)? - .ok_or_else(|| HttpError::not_found("Transaction not found".to_string()))?; - if outpoint.vout as usize >= tx.output.len() { - return Err(HttpError::not_found("Output not found".to_string())); - } + ensure_output_exists(query, &outpoint)?; SpendingValue::default() } }; @@ -2080,6 +2074,53 @@ fn parse_scripthash(scripthash: &str) -> Result { #[derive(Debug)] struct HttpError(StatusCode, String); +/// Returns a 404 if `outpoint` is not a known output. Spendable outputs are found with a +/// point lookup of their TxOut row. The full tx is only read from the local store on a miss +/// (unknown txid, vout out of range, or an unspendable output), and the daemon is never +/// queried, so a bitcoind failure in light mode cannot turn into a false 404. +fn ensure_output_exists(query: &Query, outpoint: &OutPoint) -> Result<(), HttpError> { + // Check the mempool first: a tx is indexed in the chain before it leaves the mempool. + { + let mempool = query.mempool(); + if mempool.lookup_txo(outpoint).is_some() { + return Ok(()); + } + if mempool.lookup_raw_txn(&outpoint.txid).is_some() { + return Err(HttpError::not_found("Output not found".to_string())); + } + } + + let chain = query.chain(); + if chain + .try_lookup_txo(outpoint) + .map_err(HttpError::lookup)? + .is_some() + { + return Ok(()); + } + + if query.config().light_mode { + // Without the tx we can't tell an unspendable output from an out-of-range vout, + // so only report a 404 when the txid itself is unknown. + return match chain + .try_tx_confirming_block(&outpoint.txid) + .map_err(HttpError::lookup)? + { + Some(_) => Ok(()), + None => Err(HttpError::not_found("Transaction not found".to_string())), + }; + } + + let tx = chain + .lookup_txn(&outpoint.txid, None) + .map_err(HttpError::lookup)? + .ok_or_else(|| HttpError::not_found("Transaction not found".to_string()))?; + if outpoint.vout as usize >= tx.output.len() { + return Err(HttpError::not_found("Output not found".to_string())); + } + Ok(()) +} + impl HttpError { fn not_found(msg: String) -> Self { HttpError(StatusCode::NOT_FOUND, msg) diff --git a/tests/common.rs b/tests/common.rs index 8e4e01416..0daa9ae39 100644 --- a/tests/common.rs +++ b/tests/common.rs @@ -431,6 +431,23 @@ impl TestRunner { .sum() } + /// Number of daemon RPC calls made for `method`, from the `daemon_rpc` latency histogram. + pub fn daemon_rpc_count(&self, method: &str) -> u64 { + self.metrics + .gather() + .iter() + .filter(|family| family.name() == "daemon_rpc") + .flat_map(|family| family.get_metric()) + .filter(|metric| { + metric + .get_label() + .iter() + .any(|label| label.name() == "method" && label.value() == method) + }) + .map(|metric| metric.get_histogram().get_sample_count()) + .sum() + } + pub fn counter_value(&self, name: &str) -> f64 { self.metrics .gather() diff --git a/tests/rest.rs b/tests/rest.rs index f144d3d92..6b19f8c7c 100644 --- a/tests/rest.rs +++ b/tests/rest.rs @@ -45,6 +45,16 @@ fn get_plain(rest_addr: net::SocketAddr, path: &str) -> Result { Ok(get(rest_addr, path)?.into_body().read_to_string()?) } +fn get_status_and_body(rest_addr: net::SocketAddr, path: &str) -> Result<(u16, String)> { + let resp = ureq::get(&format!("http://{}{}", rest_addr, path)) + .config() + .http_status_as_error(false) + .build() + .call()?; + let status = resp.status().as_u16(); + Ok((status, resp.into_body().read_to_string()?)) +} + #[cfg(feature = "liquid")] fn registry_asset_response(asset_id: &str) -> Value { json!({ @@ -1224,32 +1234,91 @@ fn test_rest_tx_outspend() -> Result<()> { let addr1 = tester.newaddress()?; let txid = tester.send(&addr1, "0.5 BTC".parse().unwrap())?; - tester.mine()?; - let status_and_body = |path: String| -> Result<(u16, String)> { - let resp = ureq::get(&format!("http://{}{}", rest_addr, path)) - .config() - .http_status_as_error(false) - .build() - .call()?; - let status = resp.status().as_u16(); - Ok((status, resp.into_body().read_to_string()?)) - }; + // An unconfirmed unspent output is reported as unspent + let res = get_json(rest_addr, &format!("/tx/{}/outspend/0", txid))?; + assert_eq!(res["spent"].as_bool(), Some(false)); + // An out-of-range vout on a mempool tx is a 404 + let (status, body) = get_status_and_body(rest_addr, &format!("/tx/{}/outspend/9999", txid))?; + assert_eq!(status, 404); + assert_eq!(body, "Output not found"); + + tester.mine()?; - // An existing unspent output is reported as unspent + // A confirmed unspent output is reported as unspent let res = get_json(rest_addr, &format!("/tx/{}/outspend/0", txid))?; assert_eq!(res["spent"].as_bool(), Some(false)); // An unknown txid is a 404, like GET /tx/:txid - let (status, body) = status_and_body(format!("/tx/{}/outspend/0", "00".repeat(32)))?; + let (status, body) = + get_status_and_body(rest_addr, &format!("/tx/{}/outspend/0", "00".repeat(32)))?; assert_eq!(status, 404); assert_eq!(body, "Transaction not found"); - // An out-of-range vout on an existing tx is a 404 too - let (status, body) = status_and_body(format!("/tx/{}/outspend/9999", txid))?; + // An out-of-range vout on a confirmed tx is a 404 too + let (status, body) = get_status_and_body(rest_addr, &format!("/tx/{}/outspend/9999", txid))?; assert_eq!(status, 404); assert_eq!(body, "Output not found"); + // Unspendable outputs have no TxOut row but still exist, matching /outspends + #[cfg(not(feature = "liquid"))] + { + let raw: String = tester.node_client().call( + "createrawtransaction", + &[ + serde_json::json!([]), + serde_json::json!([{ "data": "deadbeef" }, { addr1.to_string(): 0.1 }]), + ], + )?; + let funded: Value = tester + .node_client() + .call("fundrawtransaction", &[serde_json::json!(raw)])?; + let signed: Value = tester + .node_client() + .call("signrawtransactionwithwallet", &[funded["hex"].clone()])?; + let txid: Txid = tester + .node_client() + .call("sendrawtransaction", &[signed["hex"].clone()])?; + let vout = tester + .get_raw_transaction(txid)? + .output + .iter() + .position(|txout| txout.script_pubkey.is_op_return()) + .expect("OP_RETURN output"); + tester.sync()?; + + let path = format!("/tx/{}/outspend/{}", txid, vout); + assert_eq!(get_json(rest_addr, &path)?["spent"].as_bool(), Some(false)); + tester.mine()?; + assert_eq!(get_json(rest_addr, &path)?["spent"].as_bool(), Some(false)); + } + + rest_handle.stop(); + Ok(()) +} + +#[test] +fn test_rest_tx_outspend_light_mode() -> Result<()> { + let (rest_handle, rest_addr, mut tester) = + common::init_rest_tester_with(|config| config.light_mode = true).unwrap(); + + let addr1 = tester.newaddress()?; + let txid = tester.send(&addr1, "0.5 BTC".parse().unwrap())?; + tester.mine()?; + + // The existence check must not fetch the tx from bitcoind + let rpcs_before = tester.daemon_rpc_count("getrawtransaction"); + + let res = get_json(rest_addr, &format!("/tx/{}/outspend/0", txid))?; + assert_eq!(res["spent"].as_bool(), Some(false)); + + let (status, body) = + get_status_and_body(rest_addr, &format!("/tx/{}/outspend/0", "00".repeat(32)))?; + assert_eq!(status, 404); + assert_eq!(body, "Transaction not found"); + + assert_eq!(tester.daemon_rpc_count("getrawtransaction"), rpcs_before); + rest_handle.stop(); Ok(()) }