Skip to content

Commit

Permalink
change request struct to tuple-struct
Browse files Browse the repository at this point in the history
  • Loading branch information
jbesraa committed Jul 20, 2023
1 parent 70823bc commit 14a2484
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 33 deletions.
18 changes: 13 additions & 5 deletions payjoin-cli/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,11 @@ impl App {
.danger_accept_invalid_certs(self.config.danger_accept_invalid_certs)
.build()
.with_context(|| "Failed to build reqwest http client")?;
let req_url = req.0;
let req_body = req.1;
let mut response = client
.post(req.url)
.body(req.body)
.post(req_url)
.body(req_body)
.header("Content-Type", "text/plain")
.send()
.with_context(|| "HTTP request failed")?;
Expand Down Expand Up @@ -364,9 +366,13 @@ struct OutPointSet(HashSet<bitcoin::OutPoint>);

use std::fs::OpenOptions;
impl OutPointSet {
fn new() -> Self { Self(HashSet::new()) }
fn new() -> Self {
Self(HashSet::new())
}

fn insert(&mut self, input: bitcoin::OutPoint) -> bool { self.0.insert(input) }
fn insert(&mut self, input: bitcoin::OutPoint) -> bool {
self.0.insert(input)
}
}

#[derive(Debug, Deserialize)]
Expand Down Expand Up @@ -477,4 +483,6 @@ impl payjoin::receive::Headers for Headers<'_> {
}
}

fn serialize_psbt(psbt: &Psbt) -> String { base64::encode(&psbt.serialize()) }
fn serialize_psbt(psbt: &Psbt) -> String {
base64::encode(&psbt.serialize())
}
37 changes: 17 additions & 20 deletions payjoin/src/send/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,20 +235,14 @@ impl Configuration {
/// Represents data that needs to be transmitted to the receiver.
///
/// You need to send this request over HTTP(S) to the receiver.
/// This is full URL with scheme etc - you can pass it right to `reqwest` or a similar library.
/// Bytes to be sent to the receiver.
///
/// This is properly encoded PSBT, already in base64. You only need to make sure `Content-Type`
/// is `text/plain` and `Content-Length` is `body.len()` (most libraries do the latter
/// automatically).
#[non_exhaustive]
pub struct Request {
/// URL to send the request to.
///
/// This is full URL with scheme etc - you can pass it right to `reqwest` or a similar library.
pub url: Url,

/// Bytes to be sent to the receiver.
///
/// This is properly encoded PSBT, already in base64. You only need to make sure `Content-Type`
/// is `text/plain` and `Content-Length` is `body.len()` (most libraries do the latter
/// automatically).
pub body: Vec<u8>,
}
pub struct Request(pub Url, pub Vec<u8>);

/// Data required for validation of response.
///
Expand All @@ -267,8 +261,9 @@ pub struct Context {
macro_rules! check_eq {
($proposed:expr, $original:expr, $error:ident) => {
match ($proposed, $original) {
(proposed, original) if proposed != original =>
return Err(InternalValidationError::$error { proposed, original }),
(proposed, original) if proposed != original => {
return Err(InternalValidationError::$error { proposed, original })
}
_ => (),
}
};
Expand Down Expand Up @@ -601,8 +596,9 @@ fn find_change_index(
) -> Result<Option<(bitcoin::Amount, usize)>, InternalCreateRequestError> {
match (psbt.unsigned_tx.output.len(), clamp_fee_contribution) {
(0, _) => return Err(InternalCreateRequestError::NoOutputs),
(1, false) if psbt.unsigned_tx.output[0].script_pubkey == *payee =>
return Err(InternalCreateRequestError::FeeOutputValueLowerThanFeeContribution),
(1, false) if psbt.unsigned_tx.output[0].script_pubkey == *payee => {
return Err(InternalCreateRequestError::FeeOutputValueLowerThanFeeContribution)
}
(1, true) if psbt.unsigned_tx.output[0].script_pubkey == *payee => return Ok(None),
(1, _) => return Err(InternalCreateRequestError::MissingPayeeOutput),
(2, _) => (),
Expand Down Expand Up @@ -644,8 +640,9 @@ fn determine_fee_contribution(
) -> Result<Option<(bitcoin::Amount, usize)>, InternalCreateRequestError> {
Ok(match params.fee_contribution {
Some((fee, None)) => find_change_index(psbt, payee, fee, params.clamp_fee_contribution)?,
Some((fee, Some(index))) =>
Some(check_change_index(psbt, payee, fee, index, params.clamp_fee_contribution)?),
Some((fee, Some(index))) => {
Some(check_change_index(psbt, payee, fee, index, params.clamp_fee_contribution)?)
}
None => None,
})
}
Expand Down Expand Up @@ -706,7 +703,7 @@ pub(crate) fn from_psbt_and_uri(
.map_err(InternalCreateRequestError::Url)?;
let body = serialize_psbt(&psbt);
Ok((
Request { url, body },
Request(url, body),
Context {
original_psbt: psbt,
disable_output_substitution,
Expand Down
17 changes: 9 additions & 8 deletions payjoin/tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ mod integration {
None,
);
let (req, ctx) = pj_uri.create_pj_request(psbt, pj_params).unwrap();
let headers = HeaderMock::from_vec(&req.body);
let req_body = &req.1;
let headers = HeaderMock::from_vec(req_body);

// **********************
// Inside the Receiver:
Expand All @@ -109,7 +110,9 @@ mod integration {
struct HeaderMock(HashMap<String, String>);

impl Headers for HeaderMock {
fn get_header(&self, key: &str) -> Option<&str> { self.0.get(key).map(|e| e.as_str()) }
fn get_header(&self, key: &str) -> Option<&str> {
self.0.get(key).map(|e| e.as_str())
}
}

impl HeaderMock {
Expand All @@ -129,12 +132,10 @@ mod integration {
receiver: bitcoincore_rpc::Client,
) -> String {
// Receiver receive payjoin proposal, IRL it will be an HTTP request (over ssl or onion)
let proposal = payjoin::receive::UncheckedProposal::from_request(
req.body.as_slice(),
req.url.query().unwrap_or(""),
headers,
)
.unwrap();
let req_url = req.0.query().unwrap_or("");
let req_body = req.1.as_slice();
let proposal =
payjoin::receive::UncheckedProposal::from_request(req_body, req_url, headers).unwrap();

// 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.get_transaction_to_schedule_broadcast();
Expand Down

0 comments on commit 14a2484

Please sign in to comment.