Implement BIP77 v2 async PayJoin sender
Summary
The previous PR (#752) wired the PayJoin endpoint through the confirm screen, but initiate_payment still treated it as a stub and ignored the endpoint, falling back to the existing sign-and-broadcast path.
This PR implements the actual BIP77 v2 asynchronous send flow.
When a PayJoin endpoint is present, the original PSBT is signed first to produce both the signed PSBT used for negotiation and a valid fallback transaction. A dedicated PayjoinActor then manages the negotiation:
- Posts the signed PSBT to the PayJoin directory through a randomly selected OHTTP relay
- Long-polls the directory for the receiver's proposal, retrying transient client and relay failures with a short delay
- Signs and broadcasts the PayJoin proposal when negotiation succeeds
- Broadcasts the pre-signed fallback transaction when negotiation fails
- Terminates the PayJoin actor after a terminal success or fallback result
The sender disables output substitution when constructing the PayJoin session, preserving pjos=0.
Both Android and iOS listen for the PayjoinTxBroadcast reconcile message and update the send UI after either the PayJoin proposal or fallback transaction is successfully broadcast. Broadcast failures are propagated through the existing send-flow error state.
Non-PayJoin sends remain unchanged and continue using the original synchronous sign-and-broadcast path.
Testing
- Verified that non-PayJoin sends with no
pj=endpoint continue through the existing synchronous path - Verified the PayJoin success and fallback flows
Checklist
- [x] I have read CONTRIBUTING.md
- [x] I have read ARCHITECTURE.md
Summary by CodeRabbit
-
New Features
- Added Payjoin v2 transaction protocol support for improved transaction handling.
- New broadcast state tracking for real-time transaction confirmation notifications.
- Enhanced error handling and recovery in payment flows across Android and iOS.
-
Refactor
- Streamlined transaction signing and fallback mechanism.
[!IMPORTANT]
Review skipped
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.โ๏ธ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID:
08783b37-401e-40d0-84ec-cab96945229dYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
- [ ] ๐ Trigger review
๐ Walkthrough
Walkthrough
Adds BIP77 Payjoin v2 sender support end-to-end. The Rust backend gains a PayjoinActor that performs OHTTP relay negotiation, signs/broadcasts proposal or fallback transactions, and emits a PayjoinTxBroadcast reconcile message. Android and iOS WalletManager expose a new observable state property for that message, which the send-flow confirmation screens use to drive UI state transitions asynchronously.
Changes
Payjoin Full Stack
| Layer / File(s) | Summary |
|---|---|
Payjoin message contract and workspace dependencies rust/Cargo.toml, rust/src/manager/wallet_manager.rs |
Enables v2 feature in payjoin workspace dependency, adds crate-level payjoin dependency, introduces mod payjoin, adds PayjoinTxBroadcast variant to WalletManagerReconcileMessage, and updates initiate_payment doc comment. |
Rust payment initiation and signing refactoring rust/src/manager/wallet_manager/actor.rs |
initiate_payment branches on payjoin_endpoint: non-Payjoin path continues to broadcast immediately; Payjoin path introduces refactored signing to produce both a signed PSBT and a fee-limited fallback transaction, then spawns PayjoinActor. Adds payjoin_actor field to WalletActor, initializes it to None, and cancels with fallback on shutdown. |
Rust Payjoin HTTP/OHTTP negotiation state machine rust/src/manager/wallet_manager/payjoin.rs |
Adds build_sender to construct a v2 sender from PSBT and endpoint, and PayjoinActor two-phase state machine (PrePost โ Polling). start_post iterates shuffled OHTTP relays, processes directory response, and transitions to polling. begin_poll enforces deadline, long-polls with retry/backoff, and routes proposal PSBT, stasis update, or fallback to WalletActor. Includes unit tests for recipient-output selection, endpoint encoding, and amount formatting. |
Rust Payjoin outcome handlers rust/src/manager/wallet_manager/actor.rs |
Adds handle_payjoin_success and handle_payjoin_fallback: both broadcast the appropriate transaction, insert it into the wallet, emit PayjoinTxBroadcast (or SendFlowErrorAlert on failure) to frontends, and clear payjoin_actor. |
Android Payjoin state and send-flow reconciliation android/app/src/main/java/org/bitcoinppl/cove/WalletManager.kt, android/app/src/main/java/org/bitcoinppl/cove/flows/SendFlow/SendFlowContainer.kt |
WalletManager exposes payjoinTxBroadcast: TaggedItem<Unit>? and handles PayjoinTxBroadcast in apply. SendFlowContainer adds two LaunchedEffect observers: one transitions to Sent + unlocks auth on broadcast; the other transitions to Error with derived message. Swipe-to-send with payjoinEndpoint returns early, deferring state to observers. |
iOS Payjoin state and send-flow reconciliation ios/Cove/WalletManager.swift, ios/Cove/Flows/SendFlow/SendFlowConfirmScreen.swift |
WalletManager exposes payjoinTxBroadcast: UUID? and generates a new UUID in apply(.payjoinTxBroadcast). SendFlowConfirmScreen short-circuits after initiatePayment for non-Payjoin sends, and uses onChange observers to reconcile .sent (+ auth unlock) or .error(...) states for Payjoin sends. |
Sequence Diagram(s)
sequenceDiagram
rect rgba(70, 130, 180, 0.5)
Note over UI, WalletActor: Payjoin Send Flow
end
participant UI as SendFlow UI (iOS/Android)
participant WM as WalletManager
participant WalletActor
participant PayjoinActor
participant OhttpRelay
UI->>WM: initiatePayment(psbt, payjoinEndpoint)
WM->>WalletActor: initiate_payment(psbt, Some(endpoint))
WalletActor->>WalletActor: do_sign_original_psbt โ signed_psbt + fallback_tx
WalletActor->>WalletActor: build_sender(signed_psbt, endpoint)
WalletActor->>PayjoinActor: spawn(sender, fallback_tx)
UI->>UI: stay in Sending state
PayjoinActor->>OhttpRelay: start_post (v2 POST via shuffled relays)
OhttpRelay-->>PayjoinActor: directory response
PayjoinActor->>PayjoinActor: begin_poll (loop with deadline)
alt Proposal received
OhttpRelay-->>PayjoinActor: proposed PSBT
PayjoinActor->>WalletActor: handle_payjoin_success(proposal_psbt, fallback_tx)
WalletActor->>WM: reconcile(PayjoinTxBroadcast)
WM->>UI: payjoinTxBroadcast state update
UI->>UI: transition to Sent, show success alert, unlock auth
else Timeout or relay failure
PayjoinActor->>WalletActor: handle_payjoin_fallback(fallback_tx)
WalletActor->>WM: reconcile(PayjoinTxBroadcast)
WM->>UI: payjoinTxBroadcast state update
UI->>UI: transition to Sent (fallback broadcast)
else Broadcast error
WalletActor->>WM: reconcile(SendFlowErrorAlert)
WM->>UI: sendFlowErrorAlert state update
UI->>UI: transition to Error, show error alert
end
Estimated code review effort
๐ฏ 5 (Critical) | โฑ๏ธ ~120 minutes
Possibly related PRs
- bitcoinppl/cove#423: Modifies the same
SendFlowContainerConfirm-routesendStatetransitions (Sent/Error) and alert handling that this PR extends with Payjoin observer paths. - bitcoinppl/cove#738: Adds
payjoin_endpointintoSendFlowManagerState, which this PR consumes to driveinitiatePaymentand the Payjoin broadcast reconciliation lifecycle. - bitcoinppl/cove#752: Wires
payjoinEndpointinto the confirm/send flow and adds theinitiate_paymententrypoint that this PR builds on to implement the full Payjoin broadcast lifecycle.
Suggested labels
android
Suggested reviewers
- praveenperera
๐ Hops across OHTTP relays with glee, Signs the PSBT โ one, two, three! Polling and posting through BIP77, Fallback in pocket if things go astray, Broadcast success or graceful retreat โ ๐
๐ฅ Pre-merge checks | โ 4 | โ 1
โ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | โ ๏ธ Warning | Docstring coverage is 54.76% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
โ Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | โ Passed | The title accurately summarizes the main implementation objective: adding BIP77 v2 async PayJoin sender functionality. |
| Description check | โ Passed | The description comprehensively documents the summary of changes, testing performed, and required checklist items per the template. |
| Linked Issues check | โ Passed | Check skipped because no linked issues were found for this pull request. |
| Out of Scope Changes check | โ Passed | Check skipped because no linked issues were found for this pull request. |
โ๏ธ Tip: You can configure your own custom pre-merge checks in the settings.
โจ Finishing Touches
๐งช Generate unit tests (beta)
- [ ] Create PR with unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands.
Greptile Summary
This PR wires up a complete BIP-77 v2 async PayJoin sender, replacing the previous stub in initiate_payment. A new PayjoinActor drives the negotiation state machine (POST โ long-poll โ sign proposal or broadcast fallback) via OHTTP relays, following the same actor pattern as WalletScanActor. Both iOS and Android listen for the new PayjoinTxBroadcast reconcile message and update the send UI accordingly; payjoin broadcast failures are routed through the existing sendFlowErrorAlert reconcile path.
- Adds
payjoin.rswithPayjoinActor,build_sender, and an async polling loop with relay shuffling, deadline enforcement, and proper transient/terminal error classification. - Refactors
do_sign_and_broadcast_transactionintodo_sign_original_psbt(reused for both the original and the receiver's proposal) and addsbroadcast_and_notifyto consolidate post-broadcast UI notification. - iOS and Android confirm screens guard the new
payjoinTxBroadcast/sendFlowErrorAlertobservers onsendState == Sendingto avoid double-triggering with the synchronous path.
Confidence Score: 5/5
The PayJoin flow is safe to merge: the fallback transaction is always available before the actor is spawned, broadcast failures are surfaced to the UI, and the state machine correctly prevents double-broadcasts via idempotent session closure.
All prior review-thread findings have been addressed โ insert_broadcast_transaction is called in broadcast_and_notify, the UI is unblocked on broadcast failure via sendFlowErrorAlert, relay failures during polling retry with backoff, and process_response errors are classified as terminal vs. transient. The one new concern is a narrow race in the stop() path where a stale handle_payjoin_fallback message could clear a newly-started session's actor reference, but this requires very specific timing to occur and user funds remain safe in all outcomes.
rust/src/manager/wallet_manager/actor.rs โ the handle_payjoin_fallback and handle_payjoin_success handlers unconditionally clear payjoin_actor, which could affect a concurrently-started session if stop() was called while a previous negotiation was in flight.
Important Files Changed
| Filename | Overview |
|---|---|
| rust/src/manager/wallet_manager/payjoin.rs | New file: implements PayjoinActor, build_sender, and the polling loop. State machine transitions are well-guarded with close_session() idempotency, relay failures retry with backoff, and terminal vs. transient response errors are properly classified. |
| rust/src/manager/wallet_manager/actor.rs | Adds handle_payjoin_success/fallback, broadcast_and_notify, and payjoin_actor lifecycle management. Stale handle_payjoin_fallback can theoretically clear a freshly-started session's actor reference after stop(). |
| ios/Cove/Flows/SendFlow/SendFlowConfirmScreen.swift | Adds onChange observers for payjoinTxBroadcast and sendFlowErrorAlert, both correctly gated on sendState == .sending; isShowingErrorAlert is now correctly set. |
| android/app/src/main/java/org/bitcoinppl/cove/flows/SendFlow/SendFlowContainer.kt | LaunchedEffect observers correctly gated on sendState == Sending, consistent with iOS changes. |
| rust/src/manager/wallet_manager.rs | Adds PayjoinTxBroadcast to WalletManagerReconcileMessage and exposes the payjoin module. |
Reviews (11): Last reviewed commit: "refactor payjoin sender flow and fix fee..." | Re-trigger Greptile
I also see "Poll every 5s up to 5 min," while you'll notice payjoin-cli imposes no such timeout. The poll duration is imposed on the directory side https://github.com/payjoin/rust-payjoin/blob/master/payjoin-mailroom/src/config.rs#L89. This is long-polling, so the connection stays open. It won't take 30s for an update to show up in the UI, it'll return as soon as there is one. I'm concerned the 5s polling might fingerprint this client.
5 minute waiting is also something you could opt for, but I would probably recommend against outside of an automated receiver like a store. Instead, I prefer exposing the option for a user to manually abort the payjoin and broadcast the fallback. That's because the receiver actually sets an expiration on the payjoin that they're committed to respond to if they're online. This can be displayed in UI as a reason a session may have not completed. But impatient users can always manually fall back.
There are quite a few of these best practicies baked into payjoin-cli that haven't yet made it into the BIP 77 spec as normative "SHOULD"-dos, but they're coming. We just closed out our 1.0 milestone by releasing payjoin-1.0.0-rc.3 (time to audit & review) minutes ago. Thanks for getting in here early, I know there's a lot of jockying back and forth when working with experimental pre-stability software. I'm getting a lot of feedback by following this exchange.
I also see "Poll every 5s up to 5 min," while you'll notice payjoin-cli imposes no such timeout. The poll duration is imposed on the directory side https://github.com/payjoin/rust-payjoin/blob/master/payjoin-mailroom/src/config.rs#L89. This is long-polling, so the connection stays open. It won't take 30s for an update to show up in the UI, it'll return as soon as there is one. I'm concerned the 5s polling might fingerprint this client.
5 minute waiting is also something you could opt for, but I would probably recommend against outside of an automated receiver like a store. Instead, I prefer exposing the option for a user to manually abort the payjoin and broadcast the fallback. That's because the receiver actually sets an expiration on the payjoin that they're committed to respond to if they're online. This can be displayed in UI as a reason a session may have not completed. But impatient users can always manually fall back.
There are quite a few of these best practicies baked into payjoin-cli that haven't yet made it into the BIP 77 spec as normative "SHOULD"-dos, but they're coming. We just closed out our 1.0 milestone by releasing
payjoin-1.0.0-rc.3(time to audit & review) minutes ago. Thanks for getting in here early, I know there's a lot of jockying back and forth when working with experimental pre-stability software. I'm getting a lot of feedback by following this exchange.
thanks for this ! i am removing the 5s interval and client side timeout entirely. Polls will fire immediately on stasis with the http timeout set to 35s to give the directory's own timeout room to breathe
The manual abort ux is the right call and a good candidate for a followup exposing a cancel button that broadcasts the fallback directly makes more sense than an arbitrary timeout, especially with receiver-set expiration that can be surfaced in the ui
and looking forward to rc.3
@Sandipmandal25 the actor is auto terminated when the last Addr<> is dropped. So best way to terminate is to just the parent actor holding the addr field to none
@Sandipmandal25 the actor is auto terminated when the last
Addr<>is dropped. So best way to terminate is to just the parent actor holding the addr field to none
my thinking was that the watcher closure captures its own strong reference, so setting the parent field to none still leaves one reference alive and i wasnt sure termination would ever resolve with that reference still held so i went with explicit termination from inside the actor to guarantee it exits. i am fixing it to just clear the parent field in the two result handlers
the watcher closure also holds a strong addr so when we set the parent field to none the actor still has one ref alive in the watcher. should we remove the watcher too or is there something that handles this.?
the watcher closure also holds a strong addr so when we set the parent field to none the actor still has one ref alive in the watcher. should we remove the watcher too or is there something that handles this.?
We should have one Addr and the rest should be WeakAddrs
the watcher closure also holds a strong addr so when we set the parent field to none the actor still has one ref alive in the watcher. should we remove the watcher too or is there something that handles this.?
We should have one Addr and the rest should be WeakAddrs
fixed!
@coderabbitai re review
@Sandipmandal25 I'll kick off a fresh review of the PR now, taking into account all the recent changes including the long-polling switch, the WeakAddr fix, and the actor termination cleanup.
โ Action performed
Full review finished.
@greptileai re review
@coderabbitai re review
@Sandipmandal25 Kicking off a fresh review now, incorporating all the latest changes โ the long-polling switch with the 35s HTTP timeout, the WeakAddr fix for proper actor cleanup, and the actor termination refactor.
โ Action performed
Full review finished.
@greptileai
@greptileai
merged thanks @sandipmandal25