mirror of
https://github.com/bitcoin-core/gui-qml.git
synced 2026-12-02 08:12:38 +00:00
Implement PSBT import, export, inspect, broadcast operations #750
No reviewers
Labels
No labels
Android
Bug
Build system
Design suggestion
Doc
Needs design review
Needs rebase
Stage
UX
Up for grabs
Upstream
Wallet
duplicate
enhancement
good first issue
question
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin-core/gui-qml!750
Loading…
Reference in a new issue
No description provided.
Delete branch "psbt-import-export"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
This PR brings the ability to import, export and view PSBT files.
PSBT operations
Screenshot
Screenshot
Screenshot
Regularscreenshot
Other UI fixes
EllipsisMenufamily of controls. Migrate existing menus to use ContextMenu across the app.screenshot
screenshot
screenshot
Fixes #662 , #663 , #664, #522, #745
Supersedes https://github.com/bitcoin-core/gui-qml/pull/557
we probably need to add the core file size guard here before readAll()
This reads the entire selected file into memory before any validation, and the decode paths also make additional full size copies.
Core defines MAX_FILE_SIZE_PSBT for this, and Qt Widgets rejects oversized PSBT files before loading them.
A very large selected file could freeze or OOM the gui before decode fails.
I think this drops a valid external signer result in the incomplete case. Core’s external signer notes that
FinalizePSBT()“won’t work in a multisig setup”.Widgets handle this differently: after external signing,
signWithExternalSigner()returns success even ifFinalizeAndExtractPSBT()leavescomplete=false, andSendCoinsDialogthen callspresentPSBT(psbtx)so the user can copy/save the partially signed PSBT for the next signer.Here we emit
INCOMPLETEand return before updatingm_current_psbt, so the partial signature is discarded; saving afterwards reconstructs an unsigned PSBT.We should probably for now preserve this behavior. I believe you are working on better multisig support, so maybe you intend this to be intentional for now?
We would reject an OP_RETURN output here, and those are quite popular
I'm not sure still why we are imposing extra restrictions on the qml side
how come our qml send flow can only support 25 max recipients?
just documenting that the core limit is weight instead of recipients.
I see with send we are imposing a 25 limit as well.
Maybe some documentation on these design choices.
This is a good catch. I should've caught this when I ported over the code (from #557)
I'll mirror the qt-widgets check to use MAX_FILE_SIZE_PSBT
Will document it.
Something @epicleafies also caught while reviewing https://github.com/bitcoin-core/gui-qml/pull/557/changes#r3370700953
the thing is that this is a new gui restriction on being able to broadcast a psbt; aside from how many recipients we allow during creation. So documentation on why we are adding that new restriction here would be valuable.
A user with many recipients will have to use the rpc, instead of our UI flow
Looks like this was inherited from https://github.com/bitcoin-core/gui-qml/pull/450/changes/5fd444135a0f118bab0681036875610d637c960e change.
The limit seems arbitrary to me. I'm okay to drop this limit on GUI.
Unless @johnny9 has more insight on the limit?
Ah! I previously hit a bug while testing wherein we'd sign automatically before exporting the PSBT. I might've regressed this there.
I changed the flow to preserve the externally signed PSBT when signing succeeds but the PSBT remains incomplete.
it looks like this is making the linux ci task fail because we switched to a real mouseClick, but the row is not created under a visible item. The click never reaches the note button, so editRequested stays false.
It should be enough to make the test case visible and put the row under a visible host item.
like so:
Maybe there is a more elegant fix.
I think this should store the original imported PSBT, not
analysis_psbt.analysis_psbthas already gone throughFinalizePSBT()above, and that call mutates the PSBT.For a complete-but-not-finalized PSBT, finalization moves data into the final script fields and clears fields like
partial_sigs, keypaths, and scripts. So if the user only imports/reviews the PSBT and then clicks “Save transaction”, they can get back a different PSBT than the one they imported.I added a local regression test for this with a complete unfinalized 2-of-2 P2WSH PSBT. It imports the PSBT, saves it without signing/broadcasting, then reloads it. On this branch the saved PSBT has 0 partial sigs, while the original has 2.
see:
A possible fix is keep using
analysis_psbtas a temporary scratch copy forFinalizePSBT(),AnalyzePSBT(), fee checks, andcan_broadcast, but keep/store the original importedpsbtfor passive save/export.Broadcasting can still finalize/extract from a temporary copy.
I think this issue is hairy, and is tangentially related to how, currently, the gui PSBT usage implementation differs from the internal core PSBT wallet possible operations/possible outputs.
Also, maybe we should add more tests for PSBT operations in this PR. Another one we can add is the oversized PSBT one we previously found.
I took some more time to think about what was going on here, and I think overall we need to revisit some invariants.
Let's think of the possible user roles in a PSBT's lifecycle:
The QML Send form is one possible user role. Imported PSBTs arrive at any later stage: unsigned, partially signed, fully signed but not finalized, finalized, foreign, watch-only, multisig, external-signer, or broadcast-only.
That means imported PSBT review cannot depend on the editable
SendRecipientmodel. Recipient rows are draft construction state. Imported PSBT outputs are review session state.For wallet-created transactions, the current Send flow makes sense:
But imported PSBTs need a different lifecycle:
The key point is object ownership. Passive review should not mutate the PSBT the user later saves.
Core finalization is intentionally mutating: it can move partial signatures and scripts into final script fields and clear the original partial data.
So the imported session needs separate concepts:
original_psbt: the exact imported PSBT.current_psbt: the working PSBT after explicit user actions.save_psbt: what Save exports.That gives us the right behavior:
The same split fixes the output issue we've been having.
A valid PSBT can contain
OP_RETURN, unknown scripts, wallet owned outputs, many outputs, or outputs that do not convert to addresses. Those are not reasons to reject import or broadcast. They are review and display concerns.The UI does not need to become a full transaction editor in this PR. It just needs to faithfully represent the imported PSBT session.
The minimum target architecture I would recommend for this PR should be:
OP_RETURNis addressless and normally zero-value, so it should render as a data output without becoming a scary failure.So I think the original PR branch should move toward this shape rather than adding more exceptions around the existing Send recipient path. The branch is trying to add PSBT import, export, inspect, sign, and broadcast -> and we should think about those in terms of creation and import PSBT session operations.
How I would adapt the current branch
The target state should look like this:
The model changes should be organized around an imported session object rather than around populated Send recipients. I would add a small private session type in
WalletQmlModelwith these fields:original_psbt: the exact PSBT loaded from disk.current_psbt: the working PSBT after explicit user actions.save_psbt: the PSBT thatSave transactionwrites.can_sign: whether the selected wallet can add signatures now.can_broadcast: whether Core can extract a final transaction with a known nonnegative fee.review_message: fee, multisig, cannot-sign, or unknown-script warning text.The important implementation rule related to my original comment here is that we use review copies:
Thanks for the detailed review. The diagrams were helpful.
I agree that send-recipient is probably overloaded here and that imported PSBT operations should eventually move into a separate review/session model rather than being projected into send-draft state.
As a middle ground for this PR, I’m planning to keep the current review flow, but change the saveable PSBT state so it preserves the original imported PSBT.
analysis_psbtwill stay as a scrattch copy forFinalizePSBT(),fillPSBT(sign=false), fee analysis etc, but it won’t be stored inm_current_psbt.For imported PSBTs,
saveCurrentTransactionAsPsbt()will write the retained original directly, so passive review + save won’t finalize or otherwise rewrite the imported PSBT.Thanks! Should be fixed now
ACK
1113aa9d31In a reduced-scope, this is okay to merge. Will open issues for what is left to address.
Concept ACK, found 2 blockers. Was able to run all automated tests and look over code but because of 1st blocker wasn't able to manually test behavior in the gui. The main issues are below, the smaller ones are inline.
Blocker: navigating to the Send tab crashes on Qt 6.4.2. Not sure if any later Qt versions are affected, my understanding was 6.4 is the minimum Qt version. Root cause: AlertPopup.qml nests a Repeater directly inside a Quick RowLayout (contentItem ColumnLayout -> RowLayout -> Repeater over visibleActions), and Component.onCompleted: refreshActions() swaps the visibleActions model during construction. This PR adds three AlertPopup instances to the Send page (broadcastSuccessPopup, unsupportedPsbtPopup, knownPsbtTxPopup), which lay out on Send-tab navigation; on Qt 6.4.x the Repeater rebuilds its delegates while the RowLayout does its first rearrange, so QQuickLayout::effectiveSizePolicy_helper (qquicklayout.cpp:1188) runs qobject_cast<QQuickLayout*> on a freed delegate and SIGSEGVs. It reproduces under a real windowing backend (xcb/wayland) but not offscreen, which is why the offscreen functional harness on the Qt 6.4.2 CI runner stays green even on the Send tests.
Blocker: the new functional test is not wired into CI. test/functional/qml_test_psbt.py wasn't added to .github/workflows/gui-functional-tests.yml
Architecture (meta): one addition to jarolrod's PSBT-lifecycle thread is the extracted PsbtQmlModel's stateful methods (sign/broadcast/refreshState/save/copy) are reachable only from unit tests, not the UI, so the refreshState finalize bug below sits in code the app never runs today, though it will once that follow-up wires it up.
Nit (a11y, raised on #557): this interactive row sets
Accessible.checkable/checkedbut noAccessible.name/Accessible.role.ContextMenuButtonsetsAccessible.role: Accessible.MenuItemandAccessible.name: text; mirror that here.Nit (raised on #557):
FormatBtchardcodes the BTC unit, ignoring the user's display setting, and it is only reached by the unusedbuildSummary. Remove it together with that code, or, if the summary path gets wired up later, format via the active display unit instead of hardcoding BTC.Nit (raised on #557): this copies the
QByteArraybyte-by-byte. You can span it directly (std::as_bytesoverbytes.constData()/bytes.size()) and drop the loop.Nit:
MAX_FILE_SIZE_PSBTis 100,000,000 bytes (100 MB, ~95.4 MiB), so the message should say 100 MB.Nit:
loadFromFiledoes not resetm_matched_txidon the success path (onlyclear()/setError()do), so a stale matched-txid can survive a reload. Low impact since the wallet flow clears the model on success, but resetting it on load makes the model self-consistent regardless of caller order.Suggestion (latent correctness, root cause):
FinalizePSBT(*m_psbt)mutates the stored PSBT.FinalizePSBTis destructive (it clearspartial_sigs/redeem_script/witness_scriptinto the final scripts for any finalizable input), so a latersaveToFile/copyToClipboardemits a finalized PSBT rather than the imported one, dropping combiner-relevant fields for a complete-but-not-finalized or partially-signed PSBT. This is the same bug class fixed in the wallet path (finalize a copy, keep the original); apply it here too: compute state on a local copy and leavem_psbtuntouched. Only reachable from unit tests today, but a landmine once this model is wired to the UI.Question (raised on #557):
> 25is a bare magic number, and this is a new GUI-only restriction on broadcasting an imported PSBT (more recipients forces the user to the RPC). If kept, name it (e.g.MAX_REVIEWABLE_RECIPIENTS) with a one-line rationale, or reference the send-side cap if this is meant to mirror it, so the two cannot drift.Blocker (crash, headed on Qt 6.4.x): this
AlertPopup, and the two siblings this PR adds on the Send page (unsupportedPsbtPopup,knownPsbtTxPopup), crash the app when navigating to the Send tab.AlertPopup.qmlnests aRepeaterdirectly inside a QuickRowLayout(contentItemColumnLayout->RowLayout->RepeaterovervisibleActions), andComponent.onCompleted: refreshActions()swaps thevisibleActionsmodel during construction. On Qt 6.4.x the Repeater rebuilds its delegates while theRowLayoutdoes its first rearrange on Send-tab navigation, soQQuickLayout::effectiveSizePolicy_helper(qquicklayout.cpp:1188) runsqobject_cast<QQuickLayout*>on a freed delegate and SIGSEGVs. Confirmed introduced by this PR via a same-machine merge-base A/B, and confirmed fixed by changing thatRowLayoutto aRow. It reproduces under a real windowing backend (xcb/wayland) but not offscreen, which is why the offscreen functional harness on the Qt 6.4.2 CI runner stays green even on the Send tests (and so wiring the newqml_test_psbt.pywould not catch it either), and it is masked on newer Qt. Fix the sharedAlertPopup(avoid a Repeater directly in a Quick Layout, or stabilizevisibleActionsbefore first layout) and verify headed on Qt 6.4.Suggestion (security-hygiene, raised on #557): this production handler has a test-only fast path backed by a hidden
psbtImportPathField(L226) that ships in the release binary, and the same shape exists for save inSendReview.qml(savePsbtAutomationPath). The C++ test bridge is already compiled behindENABLE_TEST_AUTOMATION; these QML fields and their handler branches are not. Real-world severity is bounded (only the gated bridge can populate the field, so it is inert in a release build), so this is hygiene/defense-in-depth rather than an exploitable hole, but please gate these behindENABLE_TEST_AUTOMATIONso they match the bridge and do not exist in release builds.Suggestion (cross-platform):
"file://" + homePath()is malformed on Windows.homePath()returns a plain path, so on Windows (C:/Users/Foo) this yieldsfile://C:/Users/Foo, parsingC:as the URL authority, and the save dialog's default folder will be wrong. Same at L126 (currentFolder). Return a proper URL from C++ (QUrl::fromLocalFile(QDir::homePath()).toString()) instead of concatenating the scheme in QML, and verify on Windows.