Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only derive JsonError for errors that can return Json #526

Merged
merged 3 commits into from
Feb 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 38 additions & 38 deletions payjoin-cli/src/app/v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ use hyper_util::rt::TokioIo;
use payjoin::bitcoin::psbt::Psbt;
use payjoin::bitcoin::{self, FeeRate};
use payjoin::receive::v1::{PayjoinProposal, UncheckedProposal};
use payjoin::receive::Error;
use payjoin::receive::ImplementationError;
use payjoin::receive::ReplyableError::{self, Implementation, V1};
use payjoin::send::v1::SenderBuilder;
use payjoin::{Uri, UriExt};
use tokio::net::TcpListener;
Expand Down Expand Up @@ -225,7 +226,7 @@ impl App {
.handle_payjoin_post(req)
.await
.map_err(|e| match e {
Error::Validation(e) => {
V1(e) => {
log::error!("Error handling request: {}", e);
Response::builder().status(400).body(full(e.to_string())).unwrap()
}
Expand All @@ -246,12 +247,12 @@ impl App {
fn handle_get_bip21(
&self,
amount: Option<Amount>,
) -> Result<Response<BoxBody<Bytes, hyper::Error>>, Error> {
) -> Result<Response<BoxBody<Bytes, hyper::Error>>, ReplyableError> {
let address = self
.bitcoind()
.map_err(|e| Error::Implementation(e.into()))?
.map_err(|e| Implementation(e.into()))?
.get_new_address(None, None)
.map_err(|e| Error::Implementation(e.into()))?
.map_err(|e| Implementation(e.into()))?
.assume_checked();
let uri_string = if let Some(amount) = amount {
format!(
Expand All @@ -263,9 +264,8 @@ impl App {
} else {
format!("{}?pj={}", address.to_qr_uri(), self.config.pj_endpoint)
};
let uri = Uri::try_from(uri_string.clone()).map_err(|_| {
Error::Implementation(anyhow!("Could not parse payjoin URI string.").into())
})?;
let uri = Uri::try_from(uri_string.clone())
.map_err(|_| Implementation(anyhow!("Could not parse payjoin URI string.").into()))?;
let _ = uri.assume_checked(); // we just got it from bitcoind above

Ok(Response::new(full(uri_string)))
Expand All @@ -274,12 +274,11 @@ impl App {
async fn handle_payjoin_post(
&self,
req: Request<Incoming>,
) -> Result<Response<BoxBody<Bytes, hyper::Error>>, Error> {
) -> Result<Response<BoxBody<Bytes, hyper::Error>>, ReplyableError> {
let (parts, body) = req.into_parts();
let headers = Headers(&parts.headers);
let query_string = parts.uri.query().unwrap_or("");
let body =
body.collect().await.map_err(|e| Error::Implementation(e.into()))?.aggregate().reader();
let body = body.collect().await.map_err(|e| Implementation(e.into()))?.aggregate().reader();
let proposal = UncheckedProposal::from_request(body, query_string, headers)?;

let payjoin_proposal = self.process_v1_proposal(proposal)?;
Expand All @@ -292,29 +291,32 @@ impl App {
Ok(Response::new(full(body)))
}

fn process_v1_proposal(&self, proposal: UncheckedProposal) -> Result<PayjoinProposal, Error> {
let bitcoind = self.bitcoind().map_err(|e| Error::Implementation(e.into()))?;
fn process_v1_proposal(
&self,
proposal: UncheckedProposal,
) -> Result<PayjoinProposal, ReplyableError> {
let bitcoind = self.bitcoind().map_err(|e| Implementation(e.into()))?;

// in a payment processor where the sender could go offline, this is where you schedule to broadcast the original_tx
let _to_broadcast_in_failure_case = proposal.extract_tx_to_schedule_broadcast();

// The network is used for checks later
let network =
bitcoind.get_blockchain_info().map_err(|e| Error::Implementation(e.into()))?.chain;
let network = bitcoind.get_blockchain_info().map_err(|e| Implementation(e.into()))?.chain;

// Receive Check 1: Can Broadcast
let proposal = proposal.check_broadcast_suitability(None, |tx| {
let raw_tx = bitcoin::consensus::encode::serialize_hex(&tx);
let mempool_results = bitcoind
.test_mempool_accept(&[raw_tx])
.map_err(|e| Error::Implementation(e.into()))?;
match mempool_results.first() {
Some(result) => Ok(result.allowed),
None => Err(Error::Implementation(
anyhow!("No mempool results returned on broadcast check").into(),
)),
}
})?;
let proposal =
proposal.check_broadcast_suitability(None, |tx| {
let raw_tx = bitcoin::consensus::encode::serialize_hex(&tx);
let mempool_results = bitcoind
.test_mempool_accept(&[raw_tx])
.map_err(|e| Implementation(e.into()))?;
match mempool_results.first() {
Some(result) => Ok(result.allowed),
None => Err(ImplementationError::from(
"No mempool results returned on broadcast check",
)),
}
})?;
log::trace!("check1");

// Receive Check 2: receiver can't sign for proposal inputs
Expand All @@ -323,7 +325,7 @@ impl App {
bitcoind
.get_address_info(&address)
.map(|info| info.is_mine.unwrap_or(false))
.map_err(|e| Error::Implementation(e.into()))
.map_err(ImplementationError::from)
} else {
Ok(false)
}
Expand All @@ -332,7 +334,7 @@ impl App {

// Receive Check 3: have we seen this input before? More of a check for non-interactive i.e. payment processor receivers.
let payjoin = proposal.check_no_inputs_seen_before(|input| {
self.db.insert_input_seen_before(*input).map_err(|e| Error::Implementation(e.into()))
self.db.insert_input_seen_before(*input).map_err(ImplementationError::from)
})?;
log::trace!("check3");

Expand All @@ -341,7 +343,7 @@ impl App {
bitcoind
.get_address_info(&address)
.map(|info| info.is_mine.unwrap_or(false))
.map_err(|e| Error::Implementation(e.into()))
.map_err(ImplementationError::from)
} else {
Ok(false)
}
Expand All @@ -351,12 +353,12 @@ impl App {
.substitute_receiver_script(
&bitcoind
.get_new_address(None, None)
.map_err(|e| Error::Implementation(e.into()))?
.map_err(|e| Implementation(e.into()))?
.require_network(network)
.map_err(|e| Error::Implementation(e.into()))?
.map_err(|e| Implementation(e.into()))?
.script_pubkey(),
)
.map_err(|e| Error::Implementation(e.into()))?
.map_err(|e| Implementation(e.into()))?
.commit_outputs();

let provisional_payjoin = try_contributing_inputs(payjoin.clone(), &bitcoind)
Expand All @@ -367,12 +369,10 @@ impl App {

let payjoin_proposal = provisional_payjoin.finalize_proposal(
|psbt: &Psbt| {
bitcoind
let res = bitcoind
.wallet_process_psbt(&psbt.to_string(), None, None, Some(false))
.map(|res| {
Psbt::from_str(&res.psbt).map_err(|e| Error::Implementation(e.into()))
})
.map_err(|e| Error::Implementation(e.into()))?
.map_err(ImplementationError::from)?;
Psbt::from_str(&res.psbt).map_err(ImplementationError::from)
},
None,
self.config.max_fee_rate,
Expand Down
57 changes: 29 additions & 28 deletions payjoin-cli/src/app/v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use payjoin::bitcoin::consensus::encode::serialize_hex;
use payjoin::bitcoin::psbt::Psbt;
use payjoin::bitcoin::{Amount, FeeRate};
use payjoin::receive::v2::{Receiver, UncheckedProposal};
use payjoin::receive::Error;
use payjoin::receive::{Error, ImplementationError, ReplyableError};
use payjoin::send::v2::{Sender, SenderBuilder};
use payjoin::{bitcoin, Uri};
use tokio::signal;
Expand Down Expand Up @@ -129,9 +129,10 @@ impl App {
println!("{}", serialize_hex(&receiver.extract_tx_to_schedule_broadcast()));
let mut payjoin_proposal = match self.process_v2_proposal(receiver.clone()) {
Ok(proposal) => proposal,
Err(e) => {
return Err(handle_request_error(e, receiver, &self.config.ohttp_relay).await);
Err(Error::ReplyToSender(e)) => {
return Err(handle_recoverable_error(e, receiver, &self.config.ohttp_relay).await);
}
Err(e) => return Err(e.into()),
};
let (req, ohttp_ctx) = payjoin_proposal
.extract_v2_req(&self.config.ohttp_relay)
Expand Down Expand Up @@ -252,27 +253,29 @@ impl App {
&self,
proposal: payjoin::receive::v2::UncheckedProposal,
) -> Result<payjoin::receive::v2::PayjoinProposal, Error> {
let bitcoind = self.bitcoind().map_err(|e| Error::Implementation(e.into()))?;
let bitcoind = self.bitcoind().map_err(|e| ReplyableError::Implementation(e.into()))?;

// in a payment processor where the sender could go offline, this is where you schedule to broadcast the original_tx
let _to_broadcast_in_failure_case = proposal.extract_tx_to_schedule_broadcast();

// The network is used for checks later
let network =
bitcoind.get_blockchain_info().map_err(|e| Error::Implementation(e.into()))?.chain;
let network = bitcoind
.get_blockchain_info()
.map_err(|e| ReplyableError::Implementation(e.into()))?
.chain;
// Receive Check 1: Can Broadcast
let proposal = proposal.check_broadcast_suitability(None, |tx| {
let raw_tx = bitcoin::consensus::encode::serialize_hex(&tx);
let mempool_results = bitcoind
.test_mempool_accept(&[raw_tx])
.map_err(|e| Error::Implementation(e.into()))?;
match mempool_results.first() {
Some(result) => Ok(result.allowed),
None => Err(Error::Implementation(
anyhow!("No mempool results returned on broadcast check").into(),
)),
}
})?;
let proposal =
proposal.check_broadcast_suitability(None, |tx| {
let raw_tx = bitcoin::consensus::encode::serialize_hex(&tx);
let mempool_results =
bitcoind.test_mempool_accept(&[raw_tx]).map_err(ImplementationError::from)?;
match mempool_results.first() {
Some(result) => Ok(result.allowed),
None => Err(ImplementationError::from(
"No mempool results returned on broadcast check",
)),
}
})?;
log::trace!("check1");

// Receive Check 2: receiver can't sign for proposal inputs
Expand All @@ -281,7 +284,7 @@ impl App {
bitcoind
.get_address_info(&address)
.map(|info| info.is_mine.unwrap_or(false))
.map_err(|e| Error::Implementation(e.into()))
.map_err(ImplementationError::from)
} else {
Ok(false)
}
Expand All @@ -290,7 +293,7 @@ impl App {

// Receive Check 3: have we seen this input before? More of a check for non-interactive i.e. payment processor receivers.
let payjoin = proposal.check_no_inputs_seen_before(|input| {
self.db.insert_input_seen_before(*input).map_err(|e| Error::Implementation(e.into()))
self.db.insert_input_seen_before(*input).map_err(ImplementationError::from)
})?;
log::trace!("check3");

Expand All @@ -300,7 +303,7 @@ impl App {
bitcoind
.get_address_info(&address)
.map(|info| info.is_mine.unwrap_or(false))
.map_err(|e| Error::Implementation(e.into()))
.map_err(ImplementationError::from)
} else {
Ok(false)
}
Expand All @@ -315,12 +318,10 @@ impl App {

let payjoin_proposal = provisional_payjoin.finalize_proposal(
|psbt: &Psbt| {
bitcoind
let res = bitcoind
.wallet_process_psbt(&psbt.to_string(), None, None, Some(false))
.map(|res| {
Psbt::from_str(&res.psbt).map_err(|e| Error::Implementation(e.into()))
})
.map_err(|e| Error::Implementation(e.into()))?
.map_err(ImplementationError::from)?;
Psbt::from_str(&res.psbt).map_err(ImplementationError::from)
},
None,
self.config.max_fee_rate,
Expand All @@ -332,8 +333,8 @@ impl App {
}

/// Handle request error by sending an error response over the directory
async fn handle_request_error(
e: Error,
async fn handle_recoverable_error(
e: ReplyableError,
mut receiver: UncheckedProposal,
ohttp_relay: &payjoin::Url,
) -> anyhow::Error {
Expand Down
Loading