Skip to content
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
2 changes: 1 addition & 1 deletion .github/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ If the change has no user-visible effect (refactoring, tests, CI, comments), say
Mark a deprecation with the version placeholder instead of guessing the next release:

```rust
#[deprecated(since = "0.0.0-unreleased", note = "use `Receiver<Monitor>::classify`")]
#[deprecated(since = "0.0.0-unreleased", note = "use `Receiver::classify_tx`")]
```

`contrib/release/bump.sh` replaces it with the crate's version in the release PR, and the release checks fail if one is left. rustc warns callers about it like any other deprecation. Don't use `TBD`, which rustc treats as a future deprecation and does not warn about.
Expand Down
10 changes: 10 additions & 0 deletions payjoin-cli/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@
Original PSBT arrives. The message now points to
`payjoin-cli cancel <session-id>`, which broadcasts the fallback transaction
if the payjoin fails.
- `resume` checks the wallet once for transactions settling each open receiver
session, in any state, and closes a session once its settling transaction
has one confirmation. It reports whether the Payjoin, the fallback, or
another transaction settled it. Sessions with non-SegWit senders are now
tracked too. The receiver no longer polls the mempool after posting the
proposal.
- When `cancel` fails to broadcast the fallback transaction, it now says the
session is still open and points to `cancel --no-broadcast` to close it.
The hint for a cancelled session awaiting its fallback mentions the flag
too.

## 1.0.0

Expand Down
2 changes: 1 addition & 1 deletion payjoin-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ v2 = ["payjoin/v2", "payjoin/io"]
ahash = "0.7.8"
anyhow = "1.0.103"
async-trait = "0.1.89"
bitcoind-async-client = "0.16.1"
bitcoind-async-client = { version = "0.16.1", features = ["raw_rpc"] }
clap = { version = "4.5.45", features = ["derive"] }
config = "0.15.17"
dirs = "6.0.0"
Expand Down
236 changes: 149 additions & 87 deletions payjoin-cli/src/app/v2/mod.rs

Large diffs are not rendered by default.

55 changes: 42 additions & 13 deletions payjoin-cli/src/app/wallet.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use std::collections::HashMap;
#[cfg(feature = "v2")]
use std::str::FromStr;
use std::sync::Arc;

use anyhow::{anyhow, Context, Result};
Expand All @@ -12,6 +14,13 @@ use payjoin::bitcoin::{
};
use payjoin::receive::InputPair;

/// One address entry from listreceivedbyaddress.
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize)]
struct ReceivedByAddress {
txids: Vec<String>,
}

#[derive(Clone)]
pub struct BitcoindWallet {
rpc: Arc<AsyncBitcoinRpc>,
Expand Down Expand Up @@ -160,25 +169,45 @@ impl BitcoindWallet {
}
}

/// Returns a wallet transaction and its confirmation count, which is
/// negative if it conflicts with a confirmed transaction.
#[cfg(feature = "v2")]
pub fn get_raw_transaction(
&self,
txid: &Txid,
) -> Result<Option<payjoin::bitcoin::Transaction>> {
let raw_tx = tokio::task::block_in_place(|| {
pub fn get_wallet_transaction(&self, txid: &Txid) -> Result<Option<(Transaction, i64)>> {
let res = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(async {
match self.rpc.get_transaction(txid).await {
Ok(rpc_res) => Ok(Some(rpc_res.tx)),
Err(e) =>
if e.is_tx_not_found() {
Ok(None)
} else {
Err(e)
},
Ok(rpc_res) => Ok(Some((rpc_res.tx, rpc_res.confirmations))),
Err(e) if e.is_tx_not_found() => Ok(None),
Err(e) => Err(e),
}
})
})?;
Ok(raw_tx)
Ok(res)
}

/// Returns the txids of all wallet transactions paying `address`,
/// including unconfirmed ones.
#[cfg(feature = "v2")]
pub fn txids_paying(&self, address: &Address) -> Result<Vec<Txid>> {
// bitcoind-async-client has no wrapper for listreceivedbyaddress.
// Arguments: minconf, include_empty, include_watchonly, address_filter.
let params = [
serde_json::json!(0),
serde_json::json!(false),
serde_json::json!(true),
serde_json::json!(address.to_string()),
];
let received: Vec<ReceivedByAddress> = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current()
.block_on(async { self.rpc.call_raw("listreceivedbyaddress", &params).await })
})
.context("Failed to list transactions received by address")?;

received
.into_iter()
.flat_map(|entry| entry.txids)
.map(|txid| Txid::from_str(&txid).context("Invalid txid from listreceivedbyaddress"))
.collect()
}

/// Get a new address from the wallet
Expand Down
2 changes: 1 addition & 1 deletion payjoin-cli/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ pub enum Commands {
#[arg(long = "expire-in")]
expire_in: Option<u64>,
},
/// Resume pending payjoins (BIP77/v2 only)
/// Resume pending payjoins and close receiver sessions settled in the wallet (BIP77/v2 only)
#[cfg(feature = "v2")]
Resume {
/// Only resume a specific session
Expand Down
172 changes: 172 additions & 0 deletions payjoin-cli/tests/e2e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -751,6 +751,178 @@ mod e2e {
Ok(())
}

/// A receiver session the sender settles with its fallback before the
/// receiver posts a proposal closes on `resume` once the fallback confirms.
#[cfg(feature = "v2")]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn receiver_settles_fallback_before_proposal_v2(
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
use std::cell::Cell;

use payjoin_test_utils::{init_tracing, TestServices};
use tempfile::TempDir;

type Result<T> = std::result::Result<T, BoxError>;

/// How long to wait for a payjoin-cli subprocess to print an expected line.
const STDOUT_TIMEOUT: tokio::time::Duration = tokio::time::Duration::from_secs(10);

init_tracing();
let mut services = TestServices::initialize_with_relays(3).await?;
let temp_dir = tempdir()?;

let result = tokio::select! {
res = services.take_ohttp_relay_handle() => Err(format!("Ohttp relay is long running: {res:?}").into()),
res = services.take_directory_handle() => Err(format!("Directory server is long running: {res:?}").into()),
res = settle_fallback_cli_async(&services, &temp_dir) => res,
};

assert!(
result.is_ok(),
"receiver fallback settlement test failed: {:#?}",
result.unwrap_err()
);

/// Wait for `child` to print lines containing each of `expected`, in
/// order, then terminate it.
async fn wait_for_lines(mut child: Child, expected: &[&str]) -> Result<()> {
let mut stdout = child.stdout.take().expect("Failed to take child stdout");
let next = Cell::new(0);
let res = tokio::time::timeout(
STDOUT_TIMEOUT,
wait_for_stdout_match(&mut stdout, |line| {
while next.get() < expected.len() && line.contains(expected[next.get()]) {
next.set(next.get() + 1);
}
next.get() == expected.len()
}),
)
.await;

terminate(child).await.expect("Failed to kill payjoin-cli");
match res {
Ok(Some(_)) => Ok(()),
_ => Err(format!("payjoin-cli did not report {:?}", expected[next.get()]).into()),
}
}

async fn settle_fallback_cli_async(
services: &TestServices,
temp_dir: &TempDir,
) -> Result<()> {
let receiver_db_path = temp_dir.path().join("receiver_db");
let sender_db_path = temp_dir.path().join("sender_db");
let (bitcoind, sender, receiver) = init_bitcoind_sender_receiver(None, None)?;

// Empty the receiver wallet so its session stops at input
// contribution, before a proposal exists.
let sweep_address = sender.new_address()?;
receiver.send_all(std::slice::from_ref(&sweep_address))?;
bitcoind.client.generate_to_address(1, &sweep_address)?;

let cert_path = &temp_dir.path().join("localhost.der");
tokio::fs::write(cert_path, services.cert()).await?;
services.wait_for_services_ready().await?;
let ohttp_keys = services.fetch_ohttp_keys().await?;
let ohttp_keys_path = temp_dir.path().join("ohttp_keys");
tokio::fs::write(&ohttp_keys_path, ohttp_keys.encode()?).await?;

let receiver_rpchost = format!("http://{}/wallet/receiver", bitcoind.params.rpc_socket);
let sender_rpchost = format!("http://{}/wallet/sender", bitcoind.params.rpc_socket);
let cookie_file = &bitcoind.params.cookie_file;
let payjoin_cli = env!("CARGO_BIN_EXE_payjoin-cli");
let directory = &services.directory_url();
let ohttp_relays = &services.ohttp_relay_urls();
let cli = |rpchost: &str, db_path: &std::path::Path| {
let mut cmd = Command::new(payjoin_cli);
cmd.arg("--root-certificate")
.arg(cert_path)
.arg("--rpchost")
.arg(rpchost)
.arg("--cookie-file")
.arg(cookie_file)
.arg("--db-path")
.arg(db_path)
.arg("--ohttp-relays")
.arg(ohttp_relays)
.stdout(Stdio::piped())
.stderr(Stdio::inherit());
cmd
};
let resume_receiver = || {
cli(&receiver_rpchost, &receiver_db_path)
.arg("resume")
.spawn()
.expect("Failed to execute payjoin-cli")
};

// Receiver publishes a BIP21 and then goes offline.
let cli_receive_initiator = cli(&receiver_rpchost, &receiver_db_path)
.arg("receive")
.arg(RECEIVE_SATS)
.arg("--pj-directories")
.arg(directory)
.arg("--ohttp-keys")
.arg(&ohttp_keys_path)
.spawn()
.expect("Failed to execute payjoin-cli");
let bip21 = get_bip21_from_receiver(cli_receive_initiator).await;

// Sender posts the original proposal and waits for a response.
let mut cli_send_initiator = cli(&sender_rpchost, &sender_db_path)
.arg("send")
.arg(&bip21)
.arg("--fee-rate")
.arg("1")
.spawn()
.expect("Failed to execute payjoin-cli");
let mut stdout = cli_send_initiator.stdout.take().expect("Failed to take child stdout");
let posted_line = tokio::time::timeout(
tokio::time::Duration::from_secs(35),
wait_for_stdout_match(&mut stdout, |line| line.contains("No response yet.")),
)
.await?;
terminate(cli_send_initiator).await.expect("Failed to kill payjoin-cli");
// Session-scoped lines are prefixed with `[<Role> <session id>]`.
let sender_session_id = posted_line
.expect("sender should post the original proposal")
.split_whitespace()
.nth(1)
.expect("could not split stdout")
.trim_end_matches(']')
.to_string();

// Receiver retrieves the original and stops for lack of inputs.
wait_for_lines(resume_receiver(), &["No spendable UTXOs available in wallet"]).await?;

// Sender gives up and broadcasts the fallback.
let cli_cancel = cli(&sender_rpchost, &sender_db_path)
.arg("cancel")
.arg(&sender_session_id)
.spawn()
.expect("Failed to execute payjoin-cli cancel");
wait_for_lines(cli_cancel, &["Broadcasted fallback transaction txid"]).await?;

// An unconfirmed fallback leaves the session open.
wait_for_lines(
resume_receiver(),
&["Fallback transaction", "has 0 of 1 confirmation(s)"],
)
.await?;

// Once the fallback confirms, resume closes the session.
bitcoind.client.generate_to_address(1, &sweep_address)?;
wait_for_lines(
resume_receiver(),
&["resolved the session with 1 confirmation(s)", "Session completed."],
)
.await?;
wait_for_lines(resume_receiver(), &["No sessions to resume."]).await?;
Ok(())
}
Ok(())
}

#[cfg(all(feature = "v1", feature = "v2", feature = "_manual-tls"))]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn send_receive_payjoin_v2_to_v1() -> Result<(), Box<dyn std::error::Error + Send + Sync>>
Expand Down
23 changes: 23 additions & 0 deletions payjoin-ffi/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,29 @@
- Deprecate `MaybeInputsOwned.extract_tx_to_schedule_broadcast`. Cancel the
session when the payjoin fails and broadcast the `fallback_tx` of the
resulting `ReceiverPendingFallback` instead.
- Add `classify_tx` to every receiver state that holds a fallback transaction
and is advancing the Payjoin protocol, from `MaybeInputsOwned` through
`Monitor`. Pass every consensus-encoded transaction the wallet receives to
`classify_tx` on each open session, or to `classify_receiver_tx` with a
session in any state. It returns a `Resolution` whose `resolved_by` is a
`ResolvedBy` of `Payjoin`, `Fallback` or `Unrecognized`, or none for a
transaction that spends none of the sender's original inputs, and never
reports `Payjoin` before `PayjoinProposal`.
- Add `close_session` to the same states, and `close_receiver_session` for a
session in any state. Each takes a `Resolution` and returns a
`CloseTransition` that ends the session once the wallet decides the
transaction has enough confirmations. Saving it fails with a transient
error, without persisting, if the resolution was classified from another
session, or, for `close_receiver_session`, if the session state cannot be
closed via resolution. Closing classifies the transaction again against
the session's current state.
- Remove `Monitor.check_for_transaction`, with its `TransactionFinder`
callback and `MonitorTransition`. It closed the session on first sight of
a predicted txid and never saw a spend that is neither the proposal nor
the fallback. Use `classify_tx` and `close_session` instead.
- Remove `proposal_txid_is_stable` from every receiver state. It checked
only the sender's inputs, so a legacy or P2SH-wrapped receiver input could
change the txid even when it returned true. Use `classify_tx` instead.

## [0.25.1]

Expand Down
23 changes: 22 additions & 1 deletion payjoin-ffi/csharp/IntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -796,7 +796,8 @@ public async Task TestIntegrationV2ToV2(TransitionMode mode, bool taproot)
cancellationToken);

var proposalResponseBuffer = await proposalResponse.Content.ReadAsByteArrayAsync(cancellationToken);
payjoinProposal.ProcessResponse(proposalResponseBuffer, proposalRequest.ClientResponse);
using var monitorTransition = payjoinProposal.ProcessResponse(proposalResponseBuffer, proposalRequest.ClientResponse);
using var monitor = monitorTransition.Save(recvPersister);

// *******************************
// SENDER SIDE (FINALIZATION)
Expand Down Expand Up @@ -855,6 +856,26 @@ public async Task TestIntegrationV2ToV2(TransitionMode mode, bool taproot)
var finalHex = extractionDoc.RootElement.GetProperty("hex").GetString()!;
RpcCall(sender, "sendrawtransaction", JsonSerializer.Serialize(finalHex));

// *******************************
// Inside the Receiver:
// Classify the broadcast Payjoin, then close the replayed session with
// the resolution, as a wallet that replays its open sessions would.
var finalTx = Convert.FromHexString(finalHex);
using (var monitorResolution = monitor.ClassifyTx(finalTx))
{
Assert.NotNull(monitorResolution);
Assert.Equal(ResolvedBy.Payjoin, monitorResolution!.ResolvedBy());
}
var replayed = PayjoinMethods.ReplayReceiverEventLog(recvPersister).State();
Assert.IsType<ReceiveSession.Monitor>(replayed);
using var resolution = PayjoinMethods.ClassifyReceiverTx(replayed, finalTx);
Assert.NotNull(resolution);
Assert.Equal(ResolvedBy.Payjoin, resolution!.ResolvedBy());
using var closeTransition = PayjoinMethods.CloseReceiverSession(replayed, resolution);
closeTransition.Save(recvPersister);
Assert.True(recvPersister.Closed);
Assert.IsType<ReceiveSession.Closed>(PayjoinMethods.ReplayReceiverEventLog(recvPersister).State());

// *******************************
// VERIFY RESULTS
// The broadcast transaction spends one input from each party into the
Expand Down
23 changes: 23 additions & 0 deletions payjoin-ffi/csharp/UnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,29 @@ public void ReceiverPersistence()
Assert.IsType<ReceiveSession.Initialized>(state);
}

// A consensus-encoded transaction with one input and one output. It spends
// nothing a fresh session holds.
private static readonly byte[] UnrelatedTx = Convert.FromHexString(
"02000000010000000000000000000000000000000000000000000000000000000000000000" +
"0000000000ffffffff0100000000000000000000000000");

[Fact]
public void ClassifyReceiverTxWithoutFallback()
{
// A session that has not received the original has nothing to compare
// against, and bytes that are not a transaction are rejected whatever
// the session's state.
var persister = new InMemoryReceiverPersister();
var ohttpKeys = OhttpKeys.Decode(OhttpKeysData);
var builder = new ReceiverBuilder("tb1q6d3a2w975yny0asuvd9a67ner4nks58ff0q8g4", "https://example.com", ohttpKeys);
builder.Build().Save(persister);
var state = PayjoinMethods.ReplayReceiverEventLog(persister).State();

Assert.Null(PayjoinMethods.ClassifyReceiverTx(state, UnrelatedTx));
Assert.Throws<TransactionParseException.InvalidTransaction>(() =>
PayjoinMethods.ClassifyReceiverTx(state, new byte[] { 0 }));
}

[Fact]
public void SenderPersistence()
{
Expand Down
Loading