Bitcoin Core App (GUI QML) Object Model
Complete architecture of the gui-qml application—covering every major QML view, controller, interface, model, operation, and execution owner, stopping cleanly at the Bitcoin Core interfaces::* boundary.
View → Controller → Contract ← Model. Models never know about pages or controllers.node & control threads + elastic blocking pool (1 thread per active strand, uncapped cleanup) + QmlInitExecutor & payment-link QThread.interfaces::{Init, Node, Chain, Wallet, Handler} + ArgsManager, with one documented deviation: qml/walletsigning 3-phase external signer (off cs_wallet).Finishing: <reason> / Quit anyway) → appShutdown() → destroy Views/Models → flush DeferredDelete → join threads → destroy Core roots.01 Roles, Scopes & Dependency Rules
Role defines what an object does. Scope (page, wallet, app) defines how long it lives. Keeping them separate avoids god-models and redundant forwarding layers.
| Role | Responsibility | Naming Rule | Examples |
|---|---|---|---|
| View | QML layout, bindings, focus, dialogs, and navigation. Holds no request tickets, schedulers, or native handles. | *.qml |
MainWindow.qml, SendForm.qml, ActivityListPage.qml, ReceivePage.qml, Peers.qml |
| Controller | Use-case state, prompts, busy/error state, and active operation handles. BitcoinQmlApplication::run is the composition root. |
*Controller, ShutdownCoordinator |
WalletController, SendDraftController, TransactionReviewController, FeeBumpController, WalletPasswordController, PeerCommandController |
| Interface | Narrow abstract capability contract a controller depends on. Production models implement it; tests inject a fake. | Capability contracts end in *Interface |
WalletAvailabilityInterface, SendDraftInterface, TransactionReviewInterface, FeeBumpInterface, WalletBackupInterface, WalletSecurityInterface, SettingsEditorFactoryInterface, PeerCommandInterface, PeerActionsInterface |
| Model | Observable domain data, drafts, list/proxy models, self-contained editors, or backend sessions. Outlives pages. | *Model or concrete adapter (no *Interface) |
NodeModel, ChainModel, SettingsModel, WalletModel, TransactionActivityModel, CoinsListModel, WalletReceiveModel, walletopening::Session |
| Operation | One async domain request with its own terminal state, result, and error, bound to its original target. | Operation contracts end in *Operation |
SendOperation, PreparationOperation, FeeBumpOperation, SecurityOperation, FileSaveOperation, PsbtOperation, PeerCommandOperation, PaymentImportOperation, ReceiveRequestOperation |
| Executor | Dedicated node & control threads, elastic blocking pool, typed StrandHandles, prioritized/coalescing SerialQueues, and deterministic ManualScheduler test default. |
execution::* (Internal C++) |
execution::Executor, execution::SerialQueue, execution::StrandHandle, execution::ManualScheduler, execution::ValueCleanupQueue |
| Core | External Bitcoin Core boundary (bitcoin/src/interfaces/). Owned exclusively by backend C++ owners—never QML or page controllers. |
interfaces::* |
interfaces::Init, interfaces::Node, interfaces::Chain, interfaces::Wallet, interfaces::Handler |
Three Approved Dependency Paths
1. Workflow Coordination
View → Controller → narrow contract → Model / Session. Use an abstract *Interface where a capability/test seam helps, or an existing coherent facade like WalletReceiveModel.
2. Direct Presentation
View → Model / Controller. QML binds directly to observable models (TransactionActivityModel, CoinsListModel, PeerListProxyModel, BlockClockModel) and controller state.
3. Self-Contained Editors
View → EditorModel. Dedicated editor sessions (SettingsEditorModel, PaymentRequestEditorModel) own their draft, validation, and retiring-while-saving teardown directly.
One Owner for Each Kind of State
| State | Single Authority | Lifetime & Rule |
|---|---|---|
| Focus, layout, dialogs, navigation | View page | Local to the QML page/component. Wallet pages are created once per wallet and never rebound. |
| Prompts, busy state, active requests, page errors | Controller + Operation page | One active operation per kind. Hiding a page cancels unclaimed work; committed work finishes on its wallet. |
| Domain data, drafts, busy state & unresolved effects | Model wallet / app | Outlives pages. Publishes typed busy/busyReason (driving/reusing existing operation progress interfaces) and shared history snapshots per (tx_rev, addr_rev, tip_hash). |
Native handles (Wallet, Handler) | walletopening::Session / NodeModel / WalletRegistry | Sole app-model writer per open wallet (lint-enforced; console Node::executeRpc & Core threads exempt and ordered by Core locks). Freed on a per-wallet cleanup strand—never GUI. |
| Worker threads, strands, priority & drain | Executor app | Invisible to QML and Controllers. Dedicated node & control threads + elastic pool; tests default to deterministic ManualScheduler. |
Core roots (Init, Node, Chain) | BitcoinQmlApplication::run app | Created first; moved into a final std::thread after executor.stopAndJoin(), destroyed in its body, then joined. |
02 Ownership Tree, Threads & Core Interface Boundary
Containment shows ownership directly. Construction flows top-to-bottom; orderly teardown unwinds bottom-to-top so every worker joins before Core roots are destroyed.
BitcoinQmlApplication::run app rootNativeApplicationInterfacesinterfaces::InitCreates Node & Chain via MakeGuiInitinterfaces::NodeLifecycle, settings, peers, bans, traffic, RPC, promptsinterfaces::ChainNetwork/tip info, block lookup, wallet loading & cataloginterfaces::Wallet & HandlerAcquired at runtime; owned strictly by backend sessions/modelsexecution::Executor (Dedicated node + control + Elastic Blocking Pool) & 3 Lifecycle ThreadsTarget::Node (1 dedicated thread)All node, chain, peer, banlist, traffic & fee-estimation reads/commands—never shares a thread with wallet workTarget::Control (1 dedicated thread)Urgent control (startShutdown(), shutdown polling, settings writes, RPC stop), whenDrained, outcome strands & in-memory Outcome (ex-Domain)Target::Pool (elastic blocking pool)Grows to 1 thread per active strand, warm floor (~2) & 30–60 s idle timeout (avoids thread churn on bursts—and paired IPC server-thread churn if node/wallet interfaces are later served over IPC). Runs per-wallet strands, per-request load/creation/import strands, per-wallet cleanup strands (never capped), rpc, signer & file I/O strandsQmlInitExecutor (1 std::thread)Sequential appInitMain(), subscription cleanup, appShutdown(); posts startShutdown() on Target::Controldesktopintent::transport::Service (1 QThread) & qtlog (1 std::thread)Qt IPC event loop (QLocalServer/sockets) and async Qt log sinkqml/walletsigning (3-phase adapter)Cancelable POSIX/Win32 signer subprocess on signer strand—holds no cs_wallet or wallet ref (no QProcess dependency)ApplicationModels) appShutdownCoordinator, DesktopTrayIconController, DesktopWindowBehaviorModel, DesktopIntentModel, UiPreferencesStore, QRImageProviderNodeModel (NetworkModel, PeerCommandModel, RuntimePromptModel, StartupDiagnosticsModel), ChainModel, BlockClockModel, NetworkStatusModel, NetworkTrafficTowerPeerListModel, PeerListProxyModel, PeerDetailsModel, PeerSelectionModel, BanListModel, RpcConsoleModel, DebugLogModelSettingsModel (CoreSettingsModel, SettingsEditorModel), OnboardingOptionsModel, SignerDiscoveryModelWalletController → WalletModel (1 per open wallet) walletwalletopening::SessionSole app-model writer: unique_ptr<interfaces::Wallet>, Handler[], 1 serial wallet strand (actions overtake reads; shared history snapshot per (tx_rev, addr_rev, tip_hash)), typed busy state & per-wallet cleanup strandSendRecipientsListModel, FeeSelectionModel (fee reader on node), CoinsListModel, SendImportModel, PsbtQmlModel, TransactionReviewModel, WalletSendDraft, WalletTransactionReview, walletsigningTransactionActivityModel, ActivityFilterProxyModel, ActivityDetailModel, FlowDetailsModel, FeeBumpModel, BumpTransactionModelWalletReceiveModel, AddressListModel, AddressReservationModel, ReceiveRequestHistoryModel, ReceiptReconciliationModel, WalletBackupModel, WalletSecurityModel, SignVerifyMessageModelQQmlApplicationEngine → Pages → Page Controllers → Operations pageWalletPageController SubclassesIrreversible single-wallet m_bound: FeeBumpController, WalletPasswordController, WalletBackupControllerSendDraftController, TransactionReviewController, PaymentRequestViewController, PaymentRequestDeleteController, ActivityDetailController, PeerCommandController, SettingsNavigationControllerPreparationOperation, SendOperation/WalletSendHandle, FeeBumpOperation, SecurityOperation, FileSaveOperation/BackupFileOperation, PsbtOperation, PeerCommandOperation, PaymentImportOperation, ReceiveRequestOperationBitcoin Core Interface Boundary (Where the QML App Stops)
| Core Interface | QML-Side Owner | Used By (App Side Only) | Destruction / Retirement |
|---|---|---|---|
interfaces::Init | NativeApplicationInterfaces | BitcoinQmlApplication::run (creates Node & Chain) | Destroyed last in final std::thread after all workers join |
interfaces::Node | NativeApplicationInterfaces | QmlInitExecutor, NodeModel, FeeEstimateReader, SettingsModel (control), PeerListModel, BanListModel, PeerCommandModel, NetworkTrafficTower, RpcConsoleModel (rpc strand), BlockClockHistory | Destroyed in final std::thread after appShutdown() & stopAndJoin() |
interfaces::Chain | NativeApplicationInterfaces | ChainModel (node), WalletRegistry, WalletListModel, WalletCreationController (parallel per-request load/create/import strands on pool) | Destroyed in final std::thread after all wallet sessions stop |
interfaces::Wallet | walletopening::Session | Sole app-model writer on the wallet's serial strand (lint forbids outside Session & pre-session loader/creator). Console Node::executeRpc & Core threads bypass Session and serialize via Core's cs_wallet. External signer device waits run off-lock in qml/walletsigning. | std::unique_ptr freed on per-wallet cleanup strand (elastic pool, uncapped) inside Session::stop(done) |
interfaces::Handler | NodeModel, QmlInitExecutor, WalletRegistry, Session | Core signal subscriptions (status, tip, wallet load/unload, tx/address changes, prompts) | Disconnected & destroyed on worker (Init thread or per-wallet cleanup strand), never GUI |
03 Execution & Cleanup Contract
All feature concurrency builds on three small internal C++ primitives in execution::.
execution::Executor, SerialQueue & Scheduler
namespace execution {
enum class Target { Node, Control, Pool }; // Dedicated node & control + elastic blocking pool
enum class Priority { Action, Read }; // Actions overtake queued reads; reads coalesce
struct StrandHandle { uint64_t id{0}; const char* debug_name{nullptr}; };
class Scheduler {
public:
virtual ~Scheduler() = default;
virtual bool dispatch(Target, StrandHandle, std::function<void()> turn) = 0;
};
class SerialQueue {
public:
StrandHandle handle() const noexcept;
bool post(std::function<void()> task, Priority = Priority::Action);
bool postCoalescedRead(uint64_t key, std::function<void()> task);
void close(); // Stops new posts to this strand only
void whenDrained(std::function<void()> done); // Delivered on Target::Control
private:
friend class ValueCleanupQueue;
bool reserveCleanup();
void cancelReservedCleanup();
bool postReservedCleanup(std::function<void()> cleanup);
};
class Executor {
public:
explicit Executor(Config config); // Production: node + control + elastic pool
explicit Executor(std::shared_ptr<Scheduler> scheduler); // Tests: ManualScheduler by default
SerialQueue makeStrand(Target, const char* debug_name = nullptr);
void stopAndJoin(); // Closes, drains, joins all real workers
};
} // namespace execution
Key Runtime Invariants
- No cross-wallet or node starvation (G1): Dedicated
node&controlthreads never run wallet work. An elastic pool grows to 1 thread per active strand (warm floor ~2, 30–60 s idle timeout to avoid burst churn, and IPC server-thread churn if node/wallet interfaces are later served over IPC), with per-wallet cleanup strands never capped. - Single app-model writer + console exemption (G3): One serial strand per open wallet in
Session(lint forbidsinterfaces::Wallet&outsideSession, pre-session loader/creator, and the owning-strandShowProgress→abortRescan()cancel hook). ConsoleNode::executeRpc(onrpcstrand) & Core threads bypassSessionand are ordered by Core'scs_wallet. - Cooperative rescan cancellation: Rescans that already hold an
interfaces::Wallethandle (watch-only import aftercreateWallet, and open-wallet rescans) take a shared cancel flag polled in Core'sShowProgresscallback on the owning strand's thread to callwallet.abortRescan()directly (polling avoidsChainScanner::TryReserveresettingm_abortatscan.cpp:64; nocontrol-lane path). Load/restoreAttachChainrescans have no wallet handle yet and stop only on shutdown (scan.cpp:246). - Priority, coalescing & shared history snapshot: Within a wallet strand, actions overtake queued reads, reads coalesce, and all 5
getWalletTxsreaders share one immutable snapshot keyed by(transaction_revision, address_revision, tip_hash). - Three-phase signing & shared signer enumeration (G2, G5): Signing and discovery share one cancelable POSIX/Win32 subprocess runner in
qml/walletsigningcopying Core'sExternalSigner::Enumeraterules (nocs_wallet, no wallet ref, noQProcess); signing reuses discovery's command/fingerprint, checksSameTransaction(stricter than Core'sexternal_signer.cpp:124), replaces PSBT, and finalizes under lock (output-parity tested against Core). External-signercreateWallet(GetDescriptors) is the only step that waits on an external process with no way to cancel it. - Deterministic tests by default (G6): Unit/model tests default to
ManualSchedulerstepping typedStrandHandles (no danglingstring_viewtags); real-thread tests opt in explicitly to prove G1, G2, and G5. - Reserved teardown cleanup & consent boundary:
ValueCleanupQueuepreserves accepted teardown work duringstopAndJoin(); passiveclose()stops new posts without revoking claimed send consent.
04 Feature Relationships (All 8 App Areas)
Every major area of gui-qml arranged strictly left-to-right from QML View to the Core interfaces::* boundary.
1. Startup, Onboarding, Shell & Desktop Integration
Composition root, pre-init onboarding, OS payment links, tray/window behavior, and shutdown coordination.
ApplicationModelsexposes app-scoped models/controllers cleanly to QML without puttingExecutoror native handles into QML.desktopintent::transport::Serviceowns 1 dedicatedQThreadforQLocalServer/QLocalSocketIPC and forwards payment links toDesktopIntentModelon shared strands.QmlInitExecutorrunsappInitMain(), subscription cleanup, andappShutdown()on 1 dedicated thread while postingstartShutdown()on the dedicatedcontrolthread.
2. Node Status, BlockClock, Peers, Traffic, Console & Logs
Node, chain & fee reads on dedicated node thread; interactive RPC on rpc strand (elastic pool); shutdown polling, RPC stop & outcomes on dedicated control thread.
- All node, chain, peer, banlist, traffic, and fee-estimation reads run on the dedicated
nodethread—never sharing a thread with wallet work. NodeModel::close()cancelsRuntimePromptServiceimmediately in Step 1 of shutdown so a blockedQuestionFnnever deadlocks queued shutdown work.RpcConsoleModelruns ordinary commands on therpcstrand (elastic pool), stops oncontrol, and retires redacted output oncontrol. Wallet RPCs throughNode::executeRpcbypassSessionand serialize against wallet strands via Core'scs_wallet.PeerListModelandBanListModelread onnodeand project incrementally oncontrol;DebugLogModelreadsdebug.logon a pool file strand.
3. Settings, Self-Contained Editors & Signer Discovery
SettingsModel persists changes on dedicated control before Core interruption; external signer CLIs run on the signer strand on the elastic pool.
SettingsEditorFactoryInterface::createSettingsEditor()makes ownership clear:SettingsModelowns the returnedSettingsEditorModel*.SettingsEditorModelremains visible in a "retiring" state until its accepted save finishes on the worker.SignerDiscoveryModeland 3-phase signing share one cancelable POSIX/Win32 enumerate runner inqml/walletsigningon the pool'ssignerstrand—so a hung CLI never blocksnode,control, or wallet strands, discovery & signing never disagree on device swap, and Cancel / "Quit anyway" terminate cleanly.
4. Wallet Loading, Creation, Naming & Registry
Parallel per-request load, creation, and watch-only import strands on the elastic pool; each open wallet gets one walletopening::Session and one WalletModel.
- Parallel pre-session work & cooperative rescan cancel: Each
loadWallet/restoreWallet/migrateWalletand each pre-sessioncreateWallet+importDescriptorsruns on its own per-request strand on the elastic pool (order tests cover both loads and creations). Rescans that already hold aninterfaces::Wallethandle (watch-only import aftercreateWallet, and open-wallet rescans) poll a shared cancel flag inside Core'sShowProgresscallback on the owning strand to callwallet.abortRescan()directly (avoidingTryReserve'sm_abortreset atscan.cpp:64; nocontrol-lane path). Load/restoreAttachChainrescans stop only on shutdown (scan.cpp:246;UPSTREAM-015), and external-signercreateWallet(GetDescriptors,UPSTREAM-014) is the only step waiting on an uncancelable external process. - Typed busy state: Pending loads/restores/imports surface in the wallet list; open wallets publish typed
WalletModel::busy/busyReason(Encrypting,WaitingForSigner,BackingUp,ExportingWatchOnly,Rescanning) driving/reusing existing operation progress contracts. - Single app-model writer & per-wallet cleanup: Once open, all app-model wallet calls route through
Session's serial strand (lint-enforced), and each wallet retiresunique_ptr<interfaces::Wallet>& handlers on its own uncapped cleanup strand on the pool.
5. Send Creation, Coin Control, Payment/PSBT Import & Review
Reusable form components take explicit draft values; preparation, PSBT, signer approval, and send run through narrow contracts.
- 3-phase external signing (
qml/walletsigning): Phase 1 fills PSBT under lock onSession; Phase 2 runs the cancelable POSIX/Win32 signer subprocess on thesignerstrand with nocs_walletor wallet ref (so blocks keep connecting and Wallet B stays live); Phase 3 runs an app-sideSameTransactioncheck (stricter than Core), replaces PSBT, and finalizes/verifies onSession(output-parity tested against Core). - Fee reader on
node: Fee estimation runs on the dedicatednodethread instead of contending with wallet history reads on the wallet strand. SendForm.qml,SendFeeSelection.qml,SendRecipientCard.qml,SendRecipientEditor.qml, andExternalSignerReviewActions.qmltake explicit values/signals and never depend onWalletModel.
6. Activity History, Transaction Details, Export & Speed Up (Fee Bump)
Shared immutable history snapshot per (tx_rev, addr_rev, tip_hash) across all 5 readers; RBF bumps use 3-phase external signing and survive page dismissal.
- Shared history snapshot:
Sessioncaptures one immutablegetWalletTxs()snapshot per(transaction_revision, address_revision, tip_hash)and shares it across all 5 readers (activity, addresses, payments, requests, reservations), while actions overtake queued reads on the wallet strand. TransactionActivityModelbuilds row projections in bounded chunks oncontrol;ActivityExportOperationwrites export files on a pool file strand.- External-signer RBF bumps use the same 3-phase split (
createBumpTransaction→ PSBT fill → cancelablesignerstrand →FinalizeAndExtractPSBT+commitBumpTransaction); unresolved outcomes survive overlay dismissal onFeeBumpModel.
7. Receive Addresses, Address Book & Payment Requests
WalletReceiveModel coherent facade + self-contained request editor + view/delete controllers + QR export.
WalletReceiveModelis retained as a coherent facade rather than wrapped behind a redundant forwarding interface;AddressListModel,WalletPayments,ReceiveRequestHistoryModel, andAddressReservationModelshareSession's revisioned history snapshot.PaymentRequestEditorModelstays visible while retiring accepted backend writes;RequestImageExportOperationwrites QR PNGs on a pool file strand while outcomes deliver oncontrol.
8. Wallet Security, Backup & Sign/Verify Message
Wallet settings pages bind irreversibly to one wallet via WalletSettingsHost + WalletPageController.
WalletSettingsHostinstantiates a freshWalletSettingsStackper wallet so no wallet page controller is ever rebound to a second wallet.WalletSecurityModel(encryptWallet/changeWalletPassphrase) andWalletBackupModel(backupWallet, plus pinned Core'sexportWatchOnlyWalletatwallet/interfaces.cpp:540) run on the wallet strand and publish typedWalletModel::busy/busyReason(Encrypting,BackingUp,ExportingWatchOnly), driving/reusing existing operation progress interfaces while refusing conflicting actions viaacceptAction. Encryption and watch-only export holdcs_walletfor their duration, so node validation/notifications stall for at most that hold duration.WalletBackupModelenforces app-wide destination/file-identity collision checks (refusing loaded wallet DB paths) and finishes active backups even if the page closes.
05 Concurrency & Shutdown Sequences
Time flows downward across thread lifelines. Core roots always outlive every worker join.
Orderly Application Shutdown (5 Steps + "Quit anyway")
Normal quit, early startup exit, and recoverable errors. Active signer subprocesses are cancelled cleanly so every thread joins with zero detached threads.
Three-Phase External Signing (No cs_wallet Device Wait)
qml/walletsigning keeps Core's validation callbacks, block connection, Wallet B, and wallet unload live while waiting on a hardware wallet—with a cancelable POSIX/Win32 subprocess runner and an output-parity test against Core.
Blocked Wallet / Prompt + Pre-Interrupt Settings Write
Node runs on its own dedicated thread and SettingsModel runs on dedicated control, so neither waits behind a wallet strand, restore, or watch-only import on the elastic pool before Step 2 interrupts Core.
Single Wallet Close, Per-Wallet Cleanup & Send Consent Boundary
Wallet A stops and runs cleanup on its own uncapped pool cleanup strand without delaying Wallet B; page hide cancels unclaimed sends but never aborts a claimed send.
Native-Fatal Fast-Fail Path
Kept separate from orderly shutdown so a fatal Core error reports diagnostics on control and exits without hanging on stalled pool strands.
06 Complete QML App Class Directory
All main objects across the gui-qml project up to the Bitcoin Core interfaces::* boundary. Filter by area, role, scope, or keyword (native Ctrl+F works on every row).
| Type | Area | Role | Scope | Thread / Lane | Responsibility & Key Relationships |
|---|
interfaces::{Init, Node, Chain, Wallet, Handler} + ArgsManager (with one documented deviation: qml/walletsigning's 3-phase cancelable external signer adapter). Prefer a typed strand on Executor and a narrow contract over adding custom thread loops or raw cross-strand wallet calls.