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 05eb339de..d30ad00f7 100644 --- a/src/rest.rs +++ b/src/rest.rs @@ -1637,9 +1637,14 @@ 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 + ensure_output_exists(query, &outpoint)?; + SpendingValue::default() + } + }; let ttl = ttl_by_depth( spend .status @@ -2069,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 edc8bc74d..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!({ @@ -1218,6 +1228,101 @@ 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())?; + + // 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()?; + + // 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) = + 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 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(()) +} + #[test] fn test_rest_tx_merkle_proof() -> Result<()> { let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();