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

Use payjoin crate #8

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
110 changes: 104 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ spec = "config_spec.toml"
test_paths = []

[dependencies]
bitcoin = { version = "0.27.0", features = ["use-serde"] }
bitcoin = { version = "0.28.1", features = ["use-serde"] }
bip78 = { git = "https://github.com/dangould/rust-payjoin", branch = "receive-logic-v3", features = ["sender", "receiver" ] }
url = "2.2.2"
hyper = "0.14.9"
tonic_lnd = "0.4.0"
tokio = { version = "1.7.1", features = ["rt-multi-thread"] }
Expand Down
54 changes: 54 additions & 0 deletions src/api.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use bitcoin::{Address, Script, TxOut};

use crate::ScheduledPayJoin;

#[derive(Default)]
pub(crate) struct PayJoinScheduler {
// maps scheduled pjs via spk
by_spk: HashMap<Script, ScheduledPayJoin>,
}

impl PayJoinScheduler {
fn insert(&mut self, addr: &Address, pj: &ScheduledPayJoin) -> Result<(), ()> {
let current_pj = &*self.by_spk.entry(addr.script_pubkey()).or_insert(pj.clone());
if current_pj == pj {
Err(()) // not inserted
} else {
Ok(()) // inserted
}
}

/// pop scheduled payjoin alongside txout
fn find_mut<'a, I>(&mut self, mut txouts: I) -> Option<(&'a mut TxOut, ScheduledPayJoin)>
where
I: Iterator<Item = &'a mut TxOut>,
{
txouts.find_map(|txo| self.by_spk.remove(&txo.script_pubkey).map(|pj| (txo, pj)))
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file is superfluous and should be outside of our history

}

pub(crate) struct Handler {
lnd_client: tonic_lnd::Client, // TODO: make this generic
scheduler: Arc<Mutex<PayJoinScheduler>>,
}

pub(crate) mod util {
use std::collections::HashMap;

use hyper::Request;

pub(crate) fn get_query_map(req: &hyper::Request<hyper::Body>) -> HashMap<&str, &str> {
req.uri()
.query()
.into_iter()
.flat_map(|query| query.split('&'))
.map(|kv| {
let eq_pos = kv.find('=').unwrap();
(&kv[..eq_pos], &kv[(eq_pos + 1)..])
})
.collect::<std::collections::HashMap<_, _>>()
}
}
72 changes: 46 additions & 26 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::fmt;
use std::sync::{Arc, Mutex};

use args::ArgError;
use bip78::receiver::*;
use bitcoin::util::address::Address;
use bitcoin::util::psbt::PartiallySignedTransaction;
use bitcoin::{Script, TxOut};
Expand Down Expand Up @@ -266,6 +267,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}

pub(crate) struct Headers(hyper::HeaderMap);
impl bip78::receiver::Headers for Headers {
fn get_header(&self, key: &str) -> Option<&str> {
if let Some(value) = self.0.get(key) {
return value.to_str().ok();
}
None
}
}

async fn handle_web_req(
mut handler: Handler,
req: Request<Body>,
Expand Down Expand Up @@ -293,32 +304,41 @@ async fn handle_web_req(
dbg!(req.uri().query());

let mut lnd = handler.client;
let query = req
.uri()
.query()
.into_iter()
.flat_map(|query| query.split('&'))
.map(|kv| {
let eq_pos = kv.find('=').unwrap();
(&kv[..eq_pos], &kv[(eq_pos + 1)..])
})
.collect::<std::collections::HashMap<_, _>>();

if query.get("disableoutputsubstitution") == Some(&"1") {

let headers = Headers(req.headers().to_owned());
let query = {
let uri = req.uri();
if let Some(query) = uri.query() {
Some(&query.to_owned());
}
None
};
let body = req.into_body();
let bytes = hyper::body::to_bytes(body).await?;
dbg!(&bytes); // this is correct by my accounts
let reader = &*bytes;
let proposal = UncheckedProposal::from_request(reader, query, headers).unwrap();
if proposal.is_output_substitution_disabled() {
panic!("Output substitution must be enabled");
}
let base64_bytes = hyper::body::to_bytes(req.into_body()).await?;
let bytes = base64::decode(&base64_bytes).unwrap();
let mut reader = &*bytes;
let mut psbt = PartiallySignedTransaction::consensus_decode(&mut reader).unwrap();

let proposal = proposal
.assume_interactive_receive_endpoint() // TODO Check
.assume_no_inputs_owned() // TODO Check
.assume_no_mixed_input_scripts() // This check is silly and could be ignored
.assume_no_inputs_seen_before(); // TODO

let mut psbt = proposal.psbt().clone();
eprintln!("Received transaction: {:#?}", psbt);
for input in &mut psbt.global.unsigned_tx.input {
// clear signature
input.script_sig = bitcoin::blockdata::script::Script::new();
{
for input in &mut psbt.unsigned_tx.input {
// clear signature
input.script_sig = bitcoin::blockdata::script::Script::new();
}
}
let (our_output, scheduled_payjoin) = handler
.payjoins
.find(&mut psbt.global.unsigned_tx.output)
.find(&mut psbt.unsigned_tx.output)
.expect("the transaction doesn't contain our output");
let total_channel_amount: bitcoin::Amount = scheduled_payjoin
.channels
Expand Down Expand Up @@ -392,9 +412,9 @@ async fn handle_web_req(
let tx = PartiallySignedTransaction::consensus_decode(&mut bytes)
.unwrap();
eprintln!("PSBT received from LND: {:#?}", tx);
assert_eq!(tx.global.unsigned_tx.output.len(), 1);
assert_eq!(tx.unsigned_tx.output.len(), 1);

txouts.extend(tx.global.unsigned_tx.output);
txouts.extend(tx.unsigned_tx.output);
break;
}
// panic?
Expand All @@ -412,11 +432,11 @@ async fn handle_web_req(
*our_output = channel_output;
} else {
our_output.value = scheduled_payjoin.wallet_amount.as_sat();
psbt.global.unsigned_tx.output.push(channel_output)
psbt.unsigned_tx.output.push(channel_output)
}

psbt.global.unsigned_tx.output.extend(txouts);
psbt.outputs.resize_with(psbt.global.unsigned_tx.output.len(), Default::default);
psbt.unsigned_tx.output.extend(txouts);
psbt.outputs.resize_with(psbt.unsigned_tx.output.len(), Default::default);

eprintln!("PSBT to be given to LND: {:#?}", psbt);
let mut psbt_bytes = Vec::new();
Expand All @@ -441,7 +461,7 @@ async fn handle_web_req(
}

// Reset transaction state to be non-finalized
psbt = PartiallySignedTransaction::from_unsigned_tx(psbt.global.unsigned_tx)
let psbt = PartiallySignedTransaction::from_unsigned_tx(psbt.unsigned_tx.clone())
.expect("resetting tx failed");
let mut psbt_bytes = Vec::new();
eprintln!("PSBT that will be returned: {:#?}", psbt);
Expand Down