1use bitcoin::{OutPoint, Psbt, TxOut};
27
28pub trait ChainView {
38 fn get_prevout(&self, outpoint: OutPoint) -> Result<TxOut, ChainViewError>;
46}
47
48#[derive(Debug, thiserror::Error)]
50pub enum ChainViewError {
51 #[error("outpoint {txid}:{vout} not found on chain view")]
53 NotFound { txid: bitcoin::Txid, vout: u32 },
54 #[error("chain view transport error: {0}")]
58 Transport(String),
59 #[error("chain view response decode error: {0}")]
62 Decode(String),
63 #[error("chain view configuration error: {0}")]
65 Config(String),
66}
67
68pub fn validate_prevout_amounts_against_chain(
79 psbt: &Psbt,
80 chain: &dyn ChainView,
81) -> Result<(), String> {
82 if psbt.inputs.is_empty() {
83 return Err(
84 "REFUSED: PSBT has no inputs; cannot validate prevout amounts against chain view."
85 .to_string(),
86 );
87 }
88 if psbt.inputs.len() != psbt.unsigned_tx.input.len() {
89 return Err(format!(
90 "REFUSED: PSBT input record count ({}) does not match unsigned tx input count ({}); refusing to sign.",
91 psbt.inputs.len(),
92 psbt.unsigned_tx.input.len(),
93 ));
94 }
95 for (idx, (psbt_input, tx_input)) in psbt
96 .inputs
97 .iter()
98 .zip(psbt.unsigned_tx.input.iter())
99 .enumerate()
100 {
101 let claimed = psbt_input.witness_utxo.as_ref().ok_or_else(|| {
102 format!(
103 "REFUSED: PSBT input {idx} has no witness_utxo; #502 amount validation requires \
104 witness_utxo on every input. Refusing to sign."
105 )
106 })?;
107 let outpoint = tx_input.previous_output;
108 let actual = chain.get_prevout(outpoint).map_err(|e| {
109 format!(
110 "REFUSED: chain view could not resolve input {idx} outpoint {}:{}: {e}. \
111 Refusing to sign without an authoritative prevout amount check.",
112 outpoint.txid, outpoint.vout,
113 )
114 })?;
115 if actual.value != claimed.value {
116 return Err(format!(
117 "REFUSED: input {idx} outpoint {}:{} amount mismatch. \
118 Proposer declared {} sats but chain view says {} sats. \
119 A BIP-341 sighash over an understated prevout amount defeats every fee cap; \
120 refusing to sign.",
121 outpoint.txid,
122 outpoint.vout,
123 claimed.value.to_sat(),
124 actual.value.to_sat(),
125 ));
126 }
127 if actual.script_pubkey != claimed.script_pubkey {
128 return Err(format!(
129 "REFUSED: input {idx} outpoint {}:{} script_pubkey mismatch. \
130 Proposer declared a different script than the chain view reports; \
131 refusing to sign.",
132 outpoint.txid, outpoint.vout,
133 ));
134 }
135 }
136 Ok(())
137}
138
139pub const KEEP_CHAIN_URL_ENV: &str = "KEEP_CHAIN_URL";
144
145#[cfg(feature = "esplora-chain-view")]
150pub struct EsploraChainView {
151 base_url: url::Url,
152 client: reqwest::blocking::Client,
153}
154
155#[cfg(feature = "esplora-chain-view")]
156fn is_loopback_url(url: &url::Url) -> bool {
157 match url.host() {
158 Some(url::Host::Domain(h)) => h.eq_ignore_ascii_case("localhost"),
159 Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
160 Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
161 None => false,
162 }
163}
164
165#[cfg(feature = "esplora-chain-view")]
166impl EsploraChainView {
167 pub fn new(base_url: impl AsRef<str>) -> Result<Self, ChainViewError> {
172 let raw = base_url.as_ref();
178 let normalized = if raw.ends_with('/') {
179 raw.to_string()
180 } else {
181 format!("{raw}/")
182 };
183 let base_url = url::Url::parse(&normalized).map_err(|e| {
184 ChainViewError::Config(format!("invalid chain view base URL {raw:?}: {e}"))
185 })?;
186 if base_url.scheme() != "https" && !is_loopback_url(&base_url) {
190 return Err(ChainViewError::Config(format!(
191 "refusing non-https chain view URL {raw:?}: use https or a loopback host \
192 (127.0.0.1, ::1, localhost) for plaintext."
193 )));
194 }
195 let client = reqwest::blocking::Client::builder()
196 .user_agent(concat!(
197 "keep/",
198 env!("CARGO_PKG_VERSION"),
199 " esplora-chain-view"
200 ))
201 .timeout(std::time::Duration::from_secs(15))
202 .redirect(reqwest::redirect::Policy::custom(|attempt| {
205 let next = attempt.url();
206 if next.scheme() == "https" || is_loopback_url(next) {
207 if attempt.previous().len() >= 10 {
208 attempt.error("too many redirects")
209 } else {
210 attempt.follow()
211 }
212 } else {
213 attempt.stop()
214 }
215 }))
216 .build()
217 .map_err(|e| ChainViewError::Config(format!("build reqwest client: {e}")))?;
218 Ok(Self { base_url, client })
219 }
220}
221
222#[cfg(feature = "esplora-chain-view")]
228pub fn esplora_chain_view_from_env() -> Result<EsploraChainView, String> {
229 let chain_url = std::env::var(KEEP_CHAIN_URL_ENV).map_err(|_| {
230 format!(
231 "REFUSED: {KEEP_CHAIN_URL_ENV} is not set. Set it to an esplora / mempool.space \
232 endpoint (e.g. https://blockstream.info/api) so #502 prevout amount validation \
233 can run. Refusing to sign without an authoritative amount check."
234 )
235 })?;
236 EsploraChainView::new(&chain_url)
237 .map_err(|e| format!("REFUSED: invalid {KEEP_CHAIN_URL_ENV}={chain_url:?}: {e}"))
238}
239
240#[cfg(feature = "esplora-chain-view")]
241#[derive(serde::Deserialize)]
242struct EsploraVout {
243 value: u64,
244 scriptpubkey: String,
245}
246
247#[cfg(feature = "esplora-chain-view")]
248#[derive(serde::Deserialize)]
249struct EsploraTx {
250 txid: String,
251 vout: Vec<EsploraVout>,
252}
253
254#[cfg(feature = "esplora-chain-view")]
255impl ChainView for EsploraChainView {
256 fn get_prevout(&self, outpoint: OutPoint) -> Result<TxOut, ChainViewError> {
257 let path = format!("tx/{}", outpoint.txid);
258 let url = self
259 .base_url
260 .join(&path)
261 .map_err(|e| ChainViewError::Config(format!("join path {path}: {e}")))?;
262 let resp = self
263 .client
264 .get(url)
265 .send()
266 .map_err(|e| ChainViewError::Transport(e.to_string()))?;
267 if resp.status() == reqwest::StatusCode::NOT_FOUND {
268 return Err(ChainViewError::NotFound {
269 txid: outpoint.txid,
270 vout: outpoint.vout,
271 });
272 }
273 if !resp.status().is_success() {
274 return Err(ChainViewError::Transport(format!(
275 "HTTP {} from chain view",
276 resp.status()
277 )));
278 }
279 use std::io::Read as _;
285 const MAX_BODY: u64 = 2 * 1024 * 1024;
286 if let Some(len) = resp.content_length() {
287 if len > MAX_BODY {
288 return Err(ChainViewError::Decode(format!(
289 "chain view response too large ({len} bytes > {MAX_BODY} cap)"
290 )));
291 }
292 }
293 let mut body = Vec::new();
297 resp.take(MAX_BODY + 1)
298 .read_to_end(&mut body)
299 .map_err(|e| ChainViewError::Transport(e.to_string()))?;
300 if body.len() as u64 > MAX_BODY {
301 return Err(ChainViewError::Decode(format!(
302 "chain view response exceeds {MAX_BODY} byte cap"
303 )));
304 }
305 let tx: EsploraTx = serde_json::from_slice(&body)
306 .map_err(|e| ChainViewError::Decode(format!("parse esplora tx: {e}")))?;
307 if !tx.txid.eq_ignore_ascii_case(&outpoint.txid.to_string()) {
311 return Err(ChainViewError::Decode(format!(
312 "chain view returned txid {} but {} was requested; refusing to trust a \
313 substituted transaction.",
314 tx.txid, outpoint.txid,
315 )));
316 }
317 let vout_idx = outpoint.vout as usize;
318 let vout = tx.vout.get(vout_idx).ok_or(ChainViewError::NotFound {
319 txid: outpoint.txid,
320 vout: outpoint.vout,
321 })?;
322 let script_bytes = hex::decode(&vout.scriptpubkey)
323 .map_err(|e| ChainViewError::Decode(format!("decode scriptpubkey hex: {e}")))?;
324 Ok(TxOut {
325 value: bitcoin::Amount::from_sat(vout.value),
326 script_pubkey: bitcoin::ScriptBuf::from_bytes(script_bytes),
327 })
328 }
329}
330
331#[cfg(test)]
332mod tests {
333 use super::*;
334 use bitcoin::absolute::LockTime;
335 use bitcoin::transaction::Version;
336 use bitcoin::{Amount, ScriptBuf, Sequence, Transaction, TxIn, Txid, Witness};
337 use std::collections::HashMap;
338 use std::sync::Mutex;
339
340 struct MockChainView {
342 entries: Mutex<HashMap<OutPoint, TxOut>>,
343 }
344
345 impl MockChainView {
346 fn new() -> Self {
347 Self {
348 entries: Mutex::new(HashMap::new()),
349 }
350 }
351 fn insert(&self, op: OutPoint, out: TxOut) {
352 self.entries.lock().unwrap().insert(op, out);
353 }
354 }
355
356 impl ChainView for MockChainView {
357 fn get_prevout(&self, outpoint: OutPoint) -> Result<TxOut, ChainViewError> {
358 self.entries
359 .lock()
360 .unwrap()
361 .get(&outpoint)
362 .cloned()
363 .ok_or(ChainViewError::NotFound {
364 txid: outpoint.txid,
365 vout: outpoint.vout,
366 })
367 }
368 }
369
370 fn make_outpoint(nonce: u8) -> OutPoint {
371 OutPoint {
372 txid: Txid::from_raw_hash(bitcoin::hashes::Hash::hash(&[nonce])),
373 vout: 0,
374 }
375 }
376
377 fn make_psbt(inputs: Vec<(OutPoint, TxOut)>) -> Psbt {
378 let tx = Transaction {
379 version: Version::TWO,
380 lock_time: LockTime::ZERO,
381 input: inputs
382 .iter()
383 .map(|(op, _)| TxIn {
384 previous_output: *op,
385 script_sig: ScriptBuf::new(),
386 sequence: Sequence::MAX,
387 witness: Witness::new(),
388 })
389 .collect(),
390 output: vec![TxOut {
391 value: Amount::from_sat(500),
392 script_pubkey: ScriptBuf::new(),
393 }],
394 };
395 let mut psbt = Psbt::from_unsigned_tx(tx).unwrap();
396 for (idx, (_, prev)) in inputs.into_iter().enumerate() {
397 psbt.inputs[idx].witness_utxo = Some(prev);
398 }
399 psbt
400 }
401
402 fn taproot_script() -> ScriptBuf {
403 use bitcoin::secp256k1::{Secp256k1, SecretKey};
404 let secp = Secp256k1::new();
405 let sk = SecretKey::from_slice(&[0x22; 32]).unwrap();
406 let (xonly, _) = sk.x_only_public_key(&secp);
407 ScriptBuf::new_p2tr_tweaked(bitcoin::key::TweakedPublicKey::dangerous_assume_tweaked(
408 xonly,
409 ))
410 }
411
412 #[test]
414 fn matching_witness_utxo_amount_verifies() {
415 let chain = MockChainView::new();
416 let op = make_outpoint(1);
417 let prev = TxOut {
418 value: Amount::from_sat(100_000),
419 script_pubkey: taproot_script(),
420 };
421 chain.insert(op, prev.clone());
422 let psbt = make_psbt(vec![(op, prev)]);
423 validate_prevout_amounts_against_chain(&psbt, &chain).unwrap();
424 }
425
426 #[test]
430 fn understated_witness_utxo_amount_refuses() {
431 let chain = MockChainView::new();
432 let op = make_outpoint(2);
433 let real = TxOut {
434 value: Amount::from_sat(100_000),
435 script_pubkey: taproot_script(),
436 };
437 chain.insert(op, real);
438 let lied = TxOut {
439 value: Amount::from_sat(10_000),
440 script_pubkey: taproot_script(),
441 };
442 let psbt = make_psbt(vec![(op, lied)]);
443 let err = validate_prevout_amounts_against_chain(&psbt, &chain)
444 .expect_err("understated amount must be refused");
445 assert!(err.contains("amount mismatch"), "err was: {err}");
446 }
447
448 #[test]
451 fn script_mismatch_refuses() {
452 let chain = MockChainView::new();
453 let op = make_outpoint(3);
454 let real = TxOut {
455 value: Amount::from_sat(100_000),
456 script_pubkey: taproot_script(),
457 };
458 chain.insert(op, real);
459 let claimed = TxOut {
460 value: Amount::from_sat(100_000),
461 script_pubkey: ScriptBuf::from_bytes(vec![0xAB, 0xCD]),
462 };
463 let psbt = make_psbt(vec![(op, claimed)]);
464 let err = validate_prevout_amounts_against_chain(&psbt, &chain)
465 .expect_err("script mismatch must be refused");
466 assert!(err.contains("script_pubkey mismatch"), "err was: {err}");
467 }
468
469 #[test]
472 fn missing_witness_utxo_refuses() {
473 let chain = MockChainView::new();
474 let op = make_outpoint(4);
475 let tx = Transaction {
476 version: Version::TWO,
477 lock_time: LockTime::ZERO,
478 input: vec![TxIn {
479 previous_output: op,
480 script_sig: ScriptBuf::new(),
481 sequence: Sequence::MAX,
482 witness: Witness::new(),
483 }],
484 output: vec![TxOut {
485 value: Amount::from_sat(500),
486 script_pubkey: ScriptBuf::new(),
487 }],
488 };
489 let psbt = Psbt::from_unsigned_tx(tx).unwrap();
490 let err = validate_prevout_amounts_against_chain(&psbt, &chain)
491 .expect_err("missing witness_utxo must be refused");
492 assert!(err.contains("witness_utxo"), "err was: {err}");
493 }
494
495 #[test]
498 fn transport_error_refuses() {
499 struct FailingChain;
500 impl ChainView for FailingChain {
501 fn get_prevout(&self, _: OutPoint) -> Result<TxOut, ChainViewError> {
502 Err(ChainViewError::Transport("simulated".into()))
503 }
504 }
505 let op = make_outpoint(5);
506 let claim = TxOut {
507 value: Amount::from_sat(100_000),
508 script_pubkey: taproot_script(),
509 };
510 let psbt = make_psbt(vec![(op, claim)]);
511 let err = validate_prevout_amounts_against_chain(&psbt, &FailingChain)
512 .expect_err("transport error must be refused");
513 assert!(err.contains("chain view"), "err was: {err}");
514 }
515
516 #[test]
518 fn empty_psbt_refuses() {
519 let chain = MockChainView::new();
520 let tx = Transaction {
521 version: Version::TWO,
522 lock_time: LockTime::ZERO,
523 input: vec![],
524 output: vec![TxOut {
525 value: Amount::from_sat(500),
526 script_pubkey: ScriptBuf::new(),
527 }],
528 };
529 let psbt = Psbt::from_unsigned_tx(tx).unwrap();
530 assert!(validate_prevout_amounts_against_chain(&psbt, &chain).is_err());
531 }
532
533 #[test]
536 fn second_input_amount_divergence_refuses() {
537 let chain = MockChainView::new();
538 let op0 = make_outpoint(7);
539 let op1 = make_outpoint(8);
540 let real0 = TxOut {
541 value: Amount::from_sat(100_000),
542 script_pubkey: taproot_script(),
543 };
544 let real1 = TxOut {
545 value: Amount::from_sat(200_000),
546 script_pubkey: taproot_script(),
547 };
548 chain.insert(op0, real0.clone());
549 chain.insert(op1, real1);
550 let lied1 = TxOut {
551 value: Amount::from_sat(50_000),
552 script_pubkey: taproot_script(),
553 };
554 let psbt = make_psbt(vec![(op0, real0), (op1, lied1)]);
555 let err = validate_prevout_amounts_against_chain(&psbt, &chain)
556 .expect_err("input[1] divergence must be refused");
557 assert!(err.contains("amount mismatch"), "err was: {err}");
558 assert!(err.contains("input 1"), "should identify input 1: {err}");
559 }
560
561 #[test]
564 fn input_count_mismatch_refuses() {
565 let chain = MockChainView::new();
566 let op = make_outpoint(9);
567 let prev = TxOut {
568 value: Amount::from_sat(100_000),
569 script_pubkey: taproot_script(),
570 };
571 chain.insert(op, prev.clone());
572 let mut psbt = make_psbt(vec![(op, prev)]);
573 psbt.inputs.push(bitcoin::psbt::Input::default());
574 let err = validate_prevout_amounts_against_chain(&psbt, &chain)
575 .expect_err("input count mismatch must be refused");
576 assert!(
577 err.contains("does not match unsigned tx input count"),
578 "err was: {err}"
579 );
580 }
581
582 #[cfg(feature = "esplora-chain-view")]
584 #[test]
585 fn esplora_new_normalizes_trailing_slash() {
586 EsploraChainView::new("https://blockstream.info/api").expect("no trailing slash ok");
587 EsploraChainView::new("https://blockstream.info/api/").expect("trailing slash ok");
588 }
589
590 #[cfg(feature = "esplora-chain-view")]
592 #[test]
593 fn esplora_new_enforces_https_except_loopback() {
594 assert!(
595 EsploraChainView::new("http://evil.example/api").is_err(),
596 "non-loopback http must be refused"
597 );
598 EsploraChainView::new("http://127.0.0.1:3000/api").expect("loopback http ok");
599 }
600}