|
| 1 | +use crate::error::BDKCliError as Error; |
| 2 | +use crate::handlers::{broadcast_transaction, sync_wallet}; |
| 3 | +use crate::utils::BlockchainClient; |
| 4 | +use bdk_wallet::{ |
| 5 | + SignOptions, Wallet, |
| 6 | + bitcoin::{FeeRate, Psbt, Txid, consensus::encode::serialize_hex}, |
| 7 | +}; |
| 8 | +use payjoin::bitcoin::TxIn; |
| 9 | +use payjoin::persist::{OptionalTransitionOutcome, SessionPersister}; |
| 10 | +use payjoin::receive::InputPair; |
| 11 | +use payjoin::receive::v2::{ |
| 12 | + HasReplyableError, Initialized, MaybeInputsOwned, MaybeInputsSeen, Monitor, OutputsUnknown, |
| 13 | + PayjoinProposal, ProvisionalProposal, ReceiveSession, Receiver, |
| 14 | + SessionEvent as ReceiverSessionEvent, UncheckedOriginalPayload, WantsFeeRange, WantsInputs, |
| 15 | + WantsOutputs, |
| 16 | +}; |
| 17 | +use payjoin::send::v2::{ |
| 18 | + PollingForProposal, SendSession, Sender, SessionEvent as SenderSessionEvent, |
| 19 | + SessionOutcome as SenderSessionOutcome, WithReplyKey, |
| 20 | +}; |
| 21 | +use payjoin::{ImplementationError, UriExt}; |
| 22 | +use serde_json::{json, to_string_pretty}; |
| 23 | +use std::sync::{Arc, Mutex}; |
| 24 | + |
| 25 | +use crate::payjoin::ohttp::{RelayManager, fetch_ohttp_keys}; |
| 26 | + |
| 27 | +pub mod ohttp; |
| 28 | + |
| 29 | +/// Implements all of the functions required to go through the Payjoin receive and send processes. |
| 30 | +/// |
| 31 | +/// TODO: At the time of writing, this struct is written to make a Persister implementation easier |
| 32 | +/// but the persister is not implemented yet! For instance [`PayjoinManager::proceed_sender_session`] and |
| 33 | +/// [`PayjoinManager::proceed_receiver_session`] are designed such that the manager can enable |
| 34 | +/// resuming ongoing payjoins are well. So... this is a TODO for implementing persister. |
| 35 | +pub(crate) struct PayjoinManager<'a> { |
| 36 | + wallet: &'a mut Wallet, |
| 37 | + relay_manager: Arc<Mutex<RelayManager>>, |
| 38 | +} |
| 39 | + |
| 40 | +impl<'a> PayjoinManager<'a> { |
| 41 | + pub fn new(wallet: &'a mut Wallet, relay_manager: Arc<Mutex<RelayManager>>) -> Self { |
| 42 | + Self { |
| 43 | + wallet, |
| 44 | + relay_manager, |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + async fn proceed_sender_session( |
| 49 | + &self, |
| 50 | + session: SendSession, |
| 51 | + persister: &impl SessionPersister<SessionEvent = SenderSessionEvent>, |
| 52 | + relay: url::Url, |
| 53 | + blockchain_client: BlockchainClient, |
| 54 | + ) -> Result<Txid, Error> { |
| 55 | + match session { |
| 56 | + SendSession::WithReplyKey(context) => { |
| 57 | + self.post_original_proposal(context, relay, persister, blockchain_client) |
| 58 | + .await |
| 59 | + } |
| 60 | + SendSession::PollingForProposal(context) => { |
| 61 | + self.get_proposed_payjoin_proposal(context, relay, persister, blockchain_client) |
| 62 | + .await |
| 63 | + } |
| 64 | + SendSession::Closed(SenderSessionOutcome::Success(psbt)) => { |
| 65 | + self.process_payjoin_proposal(psbt, blockchain_client).await |
| 66 | + } |
| 67 | + _ => Err(Error::Generic("Unexpected SendSession state!".to_string())), |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + async fn post_original_proposal( |
| 72 | + &self, |
| 73 | + sender: Sender<WithReplyKey>, |
| 74 | + relay: url::Url, |
| 75 | + persister: &impl SessionPersister<SessionEvent = SenderSessionEvent>, |
| 76 | + blockchain_client: BlockchainClient, |
| 77 | + ) -> Result<Txid, Error> { |
| 78 | + let (req, ctx) = sender.create_v2_post_request(relay.as_str()).map_err(|e| { |
| 79 | + Error::Generic(format!( |
| 80 | + "Failed to create a post request for a Payjoin send: {}", |
| 81 | + e |
| 82 | + )) |
| 83 | + })?; |
| 84 | + let response = self.send_payjoin_post_request(req).await?; |
| 85 | + let sender = sender |
| 86 | + .process_response(&response.bytes().await?, ctx) |
| 87 | + .save(persister) |
| 88 | + .map_err(|e| { |
| 89 | + Error::Generic(format!("Failed to persist the Payjoin send after successfully sending original proposal: {}", e)) |
| 90 | + })?; |
| 91 | + self.get_proposed_payjoin_proposal(sender, relay, persister, blockchain_client) |
| 92 | + .await |
| 93 | + } |
| 94 | + |
| 95 | + async fn get_proposed_payjoin_proposal( |
| 96 | + &self, |
| 97 | + sender: Sender<PollingForProposal>, |
| 98 | + relay: url::Url, |
| 99 | + persister: &impl SessionPersister<SessionEvent = SenderSessionEvent>, |
| 100 | + blockchain_client: BlockchainClient, |
| 101 | + ) -> Result<Txid, Error> { |
| 102 | + let mut sender = sender.clone(); |
| 103 | + loop { |
| 104 | + let (req, ctx) = sender.create_poll_request(relay.as_str()).map_err(|e| { |
| 105 | + Error::Generic(format!( |
| 106 | + "Failed to create a poll request during a Payjoin send: {}", |
| 107 | + e |
| 108 | + )) |
| 109 | + })?; |
| 110 | + let response = self.send_payjoin_post_request(req).await?; |
| 111 | + let processed_response = sender |
| 112 | + .process_response(&response.bytes().await?, ctx) |
| 113 | + .save(persister); |
| 114 | + match processed_response { |
| 115 | + Ok(OptionalTransitionOutcome::Progress(psbt)) => { |
| 116 | + println!("Proposal received. Processing..."); |
| 117 | + return self.process_payjoin_proposal(psbt, blockchain_client).await; |
| 118 | + } |
| 119 | + Ok(OptionalTransitionOutcome::Stasis(current_state)) => { |
| 120 | + println!("No response yet. Continuing polling..."); |
| 121 | + sender = current_state; |
| 122 | + continue; |
| 123 | + } |
| 124 | + Err(e) => { |
| 125 | + break Err(Error::Generic(format!( |
| 126 | + "Error occurred when polling for Payjoin v2 proposal: {}", |
| 127 | + e |
| 128 | + ))); |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + async fn process_payjoin_proposal( |
| 135 | + &self, |
| 136 | + mut psbt: Psbt, |
| 137 | + blockchain_client: BlockchainClient, |
| 138 | + ) -> Result<Txid, Error> { |
| 139 | + if !self.wallet.sign(&mut psbt, SignOptions::default())? { |
| 140 | + return Err(Error::Generic( |
| 141 | + "Failed to sign and finalize the Payjoin proposal PSBT.".to_string(), |
| 142 | + )); |
| 143 | + } |
| 144 | + |
| 145 | + broadcast_transaction(blockchain_client, psbt.extract_tx_fee_rate_limit()?).await |
| 146 | + } |
| 147 | + |
| 148 | + async fn send_payjoin_post_request( |
| 149 | + &self, |
| 150 | + req: payjoin::Request, |
| 151 | + ) -> reqwest::Result<reqwest::Response> { |
| 152 | + let client = reqwest::Client::new(); |
| 153 | + client |
| 154 | + .post(req.url) |
| 155 | + .header("Content-Type", req.content_type) |
| 156 | + .body(req.body) |
| 157 | + .send() |
| 158 | + .await |
| 159 | + } |
| 160 | +} |
0 commit comments