diff --git a/CHANGELOG.md b/CHANGELOG.md index 1fb4d05db..d874e5355 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -139,16 +139,66 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **Masternodes tab**: a new "Masternodes" entry in the left nav (visible when Expert mode is on) for loading and managing masternode and evonode (HP masternode) identities by ProTxHash. Loaded nodes appear as a card list - showing type, voter-key readiness, key status, and DPNS-voting status; - opening a card shows a detail view with inline DPNS contested-name voting, - Withdraw / Top up / Transfer actions, key management, and — for evonodes - only — a link to claim token rewards. The load form accepts an optional - password to encrypt the entered voting/owner/payout keys immediately - instead of only after a separate step; leaving it blank keeps today's - behavior, and protection can always be added later from the key screen. - This replaces loading a masternode or evonode from *Identities → Load - Existing Identity → Show Advanced Options*, which no longer offers those - identity types. + showing type, voter-key readiness, key status, and username-voting status; + opening a card shows a detail view with Withdraw / Top up / Transfer + actions, key management, "This node's votes", a "Vote with this node" + button that opens Masternodes → Votes with that node selected, and — for + evonodes only — a link to claim token rewards. + The load form accepts an optional password to encrypt the entered + voting/owner/payout keys immediately instead of only after a separate + step; leaving it blank keeps today's behavior, and protection can always + be added later from the key screen. This replaces loading a masternode or + evonode from *Identities → Load Existing Identity → Show Advanced + Options*, which no longer offers those identity types. + +- **Username voting in Masternodes → Votes**: decide contests across your + masternodes with To decide / Voted / Scheduled / History views, remembered + node sets, bulk choices, and one aggregate confirmation for the batch. + Cards show weighted tallies and your nodes' influence. The confirmation + lists names, choices with full contender identities, node counts and timing + (scheduled times as explicit UTC timestamps). Node details show remaining + vote changes (four after the initial vote, or Unknown when this device has + no count). If a first vote becomes a change before + submission, another review is required. Nodes without available voting + information are skipped with a refresh action; missing voting keys can be + added from node detail without replacing other keys. + + Cast now, choose a UTC time, or schedule shortly before voting ends. + Scheduled decisions can be edited or removed before execution; missed + schedules and failed attempts offer recovery actions. Mixed batches report + cast and scheduled results together. A progress drawer shows live results. + Decisions staged or changed during submission survive its completion, and + entering Votes picks up newly added voting nodes without changing staged + choices: such a node stays out of them until it is included in the confirm + step. Uncertain votes stay visible and blocked from resubmission; neither + passing the estimated deadline nor the contest closing releases them. + Completed history is bounded without discarding unresolved votes. Removing a + node cancels its unstarted scheduled votes. + + A top-bar indicator and navigation badge highlight contests needing a vote, + with background refresh every 30 minutes on Mainnet and every 3 minutes on + other networks. History has a final “details” column that opens the contest + in Platform Explorer on Mainnet or Testnet. + +- **Usernames in Identities**: check availability, request a name, and follow + its status without opening the voting screen. Names needing a community + vote show the non-refundable fee before payment, and availability is + checked again before registration. Registration prevents duplicate payment; + if the app cannot confirm that a paid request went through, it says so + instead of reporting a failure and asks you to check the Usernames list + before paying again. Returning from a top-up preserves the chosen name and + payment review. + Changing the name, payer, network or fee requires a fresh review; the backend + rejects an unapproved community vote fee before spending funds. + Request status shows the timeline, tally and outcome, with alternatives + that need no vote. Saved requests refresh before the wider contest search; + after the estimated deadline they show “Awaiting result” until the network + confirms an outcome. Removed identities disappear immediately from username + views; failed record cleanup is retried after restarting. + Won usernames retry failed fetches and identity writes, including after + restarting the app. + Profile → Usernames lists names and requests, with a “Show as main” choice + for the username displayed when no profile display name is set. - **Wallet/identity indicator on more screens (rollout in progress)**: the wallet and identity picker previously shown only at the top of the Identity @@ -853,6 +903,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Removed +- Scheduled votes now use only the voting journal. Schedules from the previous + SQLite storage are no longer imported or executed automatically; a startup + notice asks you to schedule them again in Masternodes → Votes. The notice + lists no votes, returns on each launch, and stops once no contest such a + schedule could refer to can still be open (14 days after it first appeared + on Mainnet, 90 minutes on Testnet). + Votes scheduled with an earlier development (pre-release) build of this + version were saved in a storage format that is no longer read: they are not + carried over and raise no notice, so schedule them again in + Masternodes → Votes. + +- The standalone DPNS tool and voting controls embedded in node details. Voting now + lives in Masternodes → Votes and username management in Identities; + existing shortcuts redirect to their replacements. + - Local names for User identities in profile, create, load, and owned-name screens. Existing records remain readable; node administrative names and contact nicknames remain available. - Proof log screen (internal developer tool, not part of the public feature set). @@ -947,16 +1012,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). hidden. Switching Identity Hub tabs also keeps paid request actions disabled until their original task finishes. -- **Your settings and scheduled votes now survive an upgrade**: upgrading from an - earlier version no longer starts the app with a blank configuration. The first - launch after the upgrade brings across your selected network, start screen, - theme, onboarding state, Dash-Qt path and the remaining toggles — so a testnet - user is no longer relaunched on Mainnet — along with your scheduled DPNS votes - (choice, time and already-cast state) and your identities' top-up history. - Scheduled votes are imported even on an install whose wallets were already - moved by a previous launch. If a scheduled vote cannot be read, the app says so - in a banner with a "Retry now" action instead of dropping it silently; the - original data is never deleted from the previous version's storage. +- **Your settings and top-up history now survive an upgrade**: upgrading from an + earlier version restores your selected network, start screen, theme, + onboarding state, Dash-Qt path and the remaining toggles, together with your + identities' top-up history. Scheduled votes from the previous SQLite storage + require a new decision; a startup notice asks you to cast or schedule them again. - **Expert mode now reveals the Masternodes tab without a restart**: turning on Expert mode in Settings immediately shows the "Masternodes" entry in the left diff --git a/Cargo.toml b/Cargo.toml index 9a93d0c0a..bd1648d5e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,7 +68,9 @@ tokio = { version = "1.46.1", features = ["full"] } # Historical-profile migration tests verify the old encodings remain readable. # Any encoder change that breaks that compatibility needs a read-old/write-new migration: # this crate encodes the on-disk wallet-secret envelopes and QualifiedIdentity blobs. -bincode = { package = "grovedb-bincode", version = "=2.1.0", features = ["serde"] } +bincode = { package = "grovedb-bincode", version = "=2.1.0", features = [ + "serde", +] } hex = { version = "0.4.3" } async-trait = "0.1.89" itertools = "0.15.0" @@ -120,7 +122,11 @@ tempfile = "3.20.0" arc-swap = "1" urlencoding = "2" rmcp = { version = "3.3", optional = true, default-features = false } -axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "json"], optional = true } +axum = { version = "0.8", default-features = false, features = [ + "http1", + "tokio", + "json", +], optional = true } # Constant-time equality for `model::secret::Secret` (unconditional) and the # MCP API-key check. Not optional: `PartialEq for Secret` is always compiled. subtle = "2.6" @@ -138,8 +144,23 @@ raw-cpuid = "11.5.0" default = [] testing = [] bench = [] -mcp = ["dep:rmcp", "rmcp/server", "rmcp/macros", "rmcp/transport-streamable-http-server", "dep:axum"] -cli = ["dep:rmcp", "rmcp/server", "rmcp/macros", "rmcp/client", "rmcp/transport-io", "rmcp/transport-streamable-http-client-reqwest", "dep:clap", "dep:clap_complete"] +mcp = [ + "dep:rmcp", + "rmcp/server", + "rmcp/macros", + "rmcp/transport-streamable-http-server", + "dep:axum", +] +cli = [ + "dep:rmcp", + "rmcp/server", + "rmcp/macros", + "rmcp/client", + "rmcp/transport-io", + "rmcp/transport-streamable-http-client-reqwest", + "dep:clap", + "dep:clap_complete", +] headless = ["cli", "mcp"] [dev-dependencies] @@ -150,7 +171,9 @@ criterion = "0.8.2" # `refinery::Error` (the upstream `WalletStorageError::Migration` source). Same # version already in the graph via `platform-wallet-storage`; the `rusqlite` # feature is already enabled transitively, so this adds no new build. -refinery = { version = "0.9.1", default-features = false, features = ["rusqlite"] } +refinery = { version = "0.9.1", default-features = false, features = [ + "rusqlite", +] } [[bin]] name = "det-cli" @@ -207,7 +230,10 @@ opt-level = 3 [lints.rust.unexpected_cfgs] level = "warn" -check-cfg = ["cfg(tokio_unstable)", "cfg(feature, values(\"testing\", \"bench\", \"mcp\", \"cli\", \"headless\"))"] +check-cfg = [ + "cfg(tokio_unstable)", + "cfg(feature, values(\"testing\", \"bench\", \"mcp\", \"cli\", \"headless\"))", +] [lints.clippy] diff --git a/docs/ai-design/2026-04-23-identity-hub-impl/02-ux-plan.md b/docs/ai-design/2026-04-23-identity-hub-impl/02-ux-plan.md index 608d000b2..21ac86678 100644 --- a/docs/ai-design/2026-04-23-identity-hub-impl/02-ux-plan.md +++ b/docs/ai-design/2026-04-23-identity-hub-impl/02-ux-plan.md @@ -33,7 +33,7 @@ entry (tt-1), developer-mode chip footer hidden for Alex / Priya, shown for Jord **Interaction patterns**: - Hero card avatar is a `StyledCard` with gradient background overriding the default surface. -- Quick-actions row uses three `StyledButton::primary` instances with equal width. +- Quick-actions row uses three `StyledButton::new` instances with equal width. - Secondary-actions row uses three `StyledButton::ghost` instances. - Onboarding checklist dismiss button uses tt-20. - Recent activity preview: each row is a new `ActivityRow` component with compact 48px diff --git a/docs/ai-design/2026-07-16-dpns-voting-experience/01-requirements.md b/docs/ai-design/2026-07-16-dpns-voting-experience/01-requirements.md new file mode 100644 index 000000000..1c2fe74a8 --- /dev/null +++ b/docs/ai-design/2026-07-16-dpns-voting-experience/01-requirements.md @@ -0,0 +1,432 @@ +# DPNS Voting Experience — Requirements + +## Status + +Implemented in PR [#901](https://github.com/dashpay/dash-evo-tool/pull/901) +(`feat(dpns): unify safe masternode voting operations`). **Revised 2026-10-01** +by the usernames/voting redesign (`docs/ai-design/2026-10-01-usernames-redesign/`): +operator convenience is the top priority; the safety model is unchanged. + +Markers: **[Changed 2026-10-01]**, **[New 2026-10-01]**, **[Superseded 2026-10-01 → ID]**. +Superseded text is kept struck through for traceability; do not implement it. + +Implementation stream: everything here is **Stream V** (voting). Identity-side +usernames are Stream U (`2026-10-01-usernames-redesign/01-requirements.md`). +Platform rules: `2026-10-01-usernames-redesign/platform-facts.md` (PF §n). + +## Problem statement + +DET previously exposed DPNS voting through disconnected per-node and bulk +experiences, both calling the same backend without a complete, authoritative +operation model: a vote could be accepted while DET showed no confirmation, the +same choice could be offered again, bulk results could not identify the node, +and a second click could submit another state transition while the first was +unresolved. + +Voting is free for the voter (paid from the contest fund, PF §4), but each node +may vote only five times per contest (initial vote plus four changes), and each +vote is one state transition per node — there is no batching, even with a shared +voting key (PF §4). Duplicate, ambiguous, or wasted votes therefore have a real +cost, and operators with many nodes fan out to many transactions. + +**[New 2026-10-01]** The #901 surface was safe but slow at scale: DPNS lived +under Tools, every batch blocked the whole window, review listed every +node × contest row, the node choice was not remembered, and nothing outside the +voting screen signalled that a vote was needed. + +## Primary persona + +Priya, the power-user masternode operator, runs 1–40 nodes (often several on +one voting key) and expects: + +- current vote state to be accurate; +- to notice from anywhere in the app that a vote is needed **[New]**; +- one decision per contest applied to all chosen nodes **[New]**; +- to see her weight (evonode = 4) and each node's remaining changes **[New]**; +- bulk and scheduled operations for many nodes; +- progress that survives navigation and restart, without blocking the app **[Changed]**; +- exact per-node results; and +- safe recovery when Platform accepted a request but DET could not confirm it. + +The voting workspace remains hidden below Detailed interface mode (Masternodes +gate). It is not an Everyday User workflow. + +Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. + +## Current-state audit + +| Finding | Source behavior | User impact | +|---|---|---| +| Vote ownership is never populated | Contest cache reconstructs `ContestedName::my_votes` as empty and no task fills it | A successful vote is offered again after refresh | +| Existing votes are treated as closed | `is_open_for_voter` excludes any contest where the node already voted | Operators cannot inspect or change an existing vote | +| Same-node bulk execution races | `VoteOnDPNSNames` runs contests with `join_all`; each task independently fetches the same voter nonce | Multiple votes for one node can conflict | +| Bulk results lose node identity | `DPNSVoteResults` contains only name, choice, and result | Partial results cannot say which node succeeded | +| Scheduled casts can report false success | Scheduled paths treat an outer `Ok(DPNSVoteResults)` as success without inspecting inner failures | A failed or unconfirmed scheduled vote is marked executed | +| Progress is screen-owned | App results are routed to the currently visible screen | Navigation can strand controls in progress or deliver feedback to the wrong page | +| Duplicate prevention is local or absent | Quick and bulk submit buttons do not share an operation lock | Repeated clicks or cross-screen actions can submit duplicates | +| Post-broadcast wait failure is ambiguous | A cause-less `StateTransitionBroadcastError` can follow successful broadcast | DET must not label it rejected or invite immediate retry | +| Voting entry points were disconnected | Per-node and bulk flows used different UI ownership | Operators could miss capabilities or assume they were removed | +| **[New]** Voting buried under Tools ▸ DPNS, mixed with "My usernames" | `tools_subscreen_chooser_panel.rs`, `dpns_subscreen_chooser_panel.rs` | Operators must remember to look; owners enter a governance tool | +| **[New]** Whole-window overlay per batch | #901 FR-035 | A 50-transaction fan-out blocks the app for minutes with no safety gain over target locks | + +## Product decisions + +1. ~~DPNS Active contests is the single home for immediate, bulk, and scheduled + vote composition.~~ **[Changed 2026-10-01]** **Masternodes ▸ Votes** is the + single home for immediate, bulk, and scheduled vote composition. +2. ~~Masternode detail links plainly to Active contests without carrying a node + filter or draft.~~ **[Changed 2026-10-01]** Masternode detail offers + `Vote with this node`, which opens Votes with the node set set to that node, + visibly. It never carries a draft. +3. Single and bulk/scheduled voting use one confirm step and one shared + operation coordinator. **[Changed: "review sheet" → aggregate confirm, VOTE-FR-080]** +4. Current vote state is authoritative Platform data, not UI-local memory. +5. A vote row remains visible after voting and shows the current choice. Voting + again is presented as a change, not a new missing vote. +6. Operation state is global, correlated, and durable enough to survive + navigation and process restart. +7. Exact targets, not whole screens, are locked. Unrelated nodes and contests + remain usable. **[Reinforced: no whole-window blocking, VOTE-FR-083]** +8. **[New]** One decision per contest is applied to every node in the + persistent node set; DET fans it out into one transaction per node. +9. **[New]** "Needs a vote" is signalled outside the voting page. + +## Functional requirements + +### Information architecture + +- ~~**VOTE-FR-001** — Masternodes provides only the node list and node detail.~~ + **[Superseded 2026-10-01 → VOTE-FR-070]** +- **VOTE-FR-002** **[Changed 2026-10-01]** — Masternodes ▸ Votes owns the single + vote composer, the confirm step, and the progress drawer. +- ~~**VOTE-FR-003** — A node detail page offers one `DPNS Voting` action that + navigates plainly to Active contests.~~ **[Superseded 2026-10-01 → VOTE-FR-076]** +- **VOTE-FR-070** **[New]** — Masternodes has a segmented header `Votes | Nodes`. + Votes is listed first and opens by default when VOTE-FR-073's count > 0, + otherwise the last-used segment opens. Tools ▸ DPNS is removed. Persisted + `RootScreenDPNSActiveContests/PastContests/ScheduledVotes` values route to + Votes (To decide / History / Scheduled). The `My usernames` sub-screen leaves + voting (owned by Stream U); `RootScreenDPNSOwnedNames` routes to the Identity + hub. +- **VOTE-FR-071** **[New]** — Votes sub-views: `To decide` · `Voted` · + `Scheduled` · `History`. To decide is sorted by time left and includes + contests where only some node-set nodes have voted (`Voted with {n} of {total} + nodes`). Contests no node-set node can vote on go to a collapsed + `Can't vote with your nodes` group with the reason. +- **VOTE-FR-072** **[New]** — Top-bar attention chip on every screen (Power role, + ≥ 1 node with a voting key): `{count} names need your vote`. It is amber with + `first ends in {time}` when the soonest deadline is within the urgency window + (VOTE-FR-085), otherwise calm. A second chip `{count} vote is still being + checked` appears while targets are Unconfirmed. Either chip opens Votes. +- **VOTE-FR-073** **[New]** — The Masternodes nav item shows a badge = contests + needing a decision from ≥ 1 node-set node + unresolved targets. +- **VOTE-FR-074** **[New]** — A background refresh of contests and node vote state + feeds VOTE-FR-072/073 while voting nodes are loaded: every 30 min on mainnet, + every 3 min on testnet/devnet, and immediately on Votes arrival. A refresh + that fails, or leaves any contest's contenders or end time unread or any + node's vote state unchecked, does not count as completed and is retried + after a sixth of the interval. Proved vote + state stays valid for display and for VOTE-FR-072/073 for two refresh + intervals, so the signal does not blank between refreshes. Submission never + relies on it: preflight fetches its own proof and accepts it for 120 seconds. + The same limit applies to deciding that nothing needs sending: the confirm + step skips a node as already voted only on proof within 120 seconds. On older + proof the vote is sent to preflight, which confirms it without broadcasting + when the choice is in place, or asks for another review when it changed. + The tray and the confirm step present such a vote as one to check again + (VOTE-FR-080/086): never as `Not voted yet`, and never as a transaction. + A node with no changes left (VOTE-FR-078) is the exception: it can send + nothing whatever a fresh check finds, so on older proof it is skipped with + the `no changes left` reason instead of being checked again, and the tray + does not offer it. +- **VOTE-FR-076** **[New]** — Node detail shows `This node's votes` (name, choice, + changes left, deadline), its masternode-list status, and `Vote with this node` + (VOTE-FR-075 node set = that node). + +### Authoritative state + +- **VOTE-FR-010** — DET queries each loaded node's proved Platform votes and + joins them with active contests. Use `ResourceVote::fetch_many` + + `ContestedResourceVotesGivenByIdentityQuery` keyed by proTxHash; never the + `get_contested_dpns_identity_votes` stub (PF §5d). +- **VOTE-FR-011** — Each active contest shows the node's current choice, or + `Not voted`. +- **VOTE-FR-012** — Existing votes remain actionable while the contest is + votable, allowing a deliberate vote change. +- **VOTE-FR-013** — Selecting the already-current choice is a no-op and cannot + create a state transition. +- **VOTE-FR-014** — Refresh updates contests, tallies, and node vote state as one + coherent snapshot. +- **VOTE-FR-015** **[Changed 2026-10-01]** — A change to an existing vote is + labelled as a change once per batch in the confirm step. Changes left per node + follow VOTE-FR-078. +- **VOTE-FR-016** — If current vote state cannot be proved, DET shows it as + unavailable and excludes that node from submission instead of assuming + `Not voted`. Other nodes remain usable. +- **VOTE-FR-017** — Node summaries distinguish active contests from contests + where the node has not voted yet. +- **VOTE-FR-077** **[New]** — Cards show weighted tallies (Platform tallies are + weighted, PF §3) with the hint `Evonodes count as 4 votes.` and an influence + line built from node-set weight: `{leader} leads by {margin} votes. Your + {weight} votes can change who leads.` Show it only when weight ≥ margin. Ties + read `If still tied at the end, the most recent request wins.` (PF §3). +- **VOTE-FR-078** **[New]** — Changes left per node per contest: with n = + confirmed votes for that proTxHash × contest in the journal, it is 4 when n = 0, + otherwise 5 − n. Label it `counted on this device`. If proved state shows a vote not present in the + journal, show `Changes left unknown. This device has no record of this node's + earlier votes.` + A node with 0 left is skipped with the reason `no changes left (4 of 4 changes + used)`. +- **VOTE-FR-079** **[New]** — A node not in the current masternode list is + excluded from the node set, with `Not in the masternode list. Its votes don't + count.` (PF §4 vote expiry). + +### Vote composition + +- **VOTE-FR-020** — Voting supports one node across one or more contests. +- **VOTE-FR-021** — Voting supports one or more contests across one or more + nodes. +- **VOTE-FR-022** **[Changed 2026-10-01]** — A single timing applies to the whole + batch, and individual nodes can be overridden under `Adjust nodes` in the + confirm step. A node loaded after decisions were staged starts on + `Don't use this node` every time the confirm step opens for those decisions, + until the operator picks another option for it under `Adjust nodes`. + Decisions staged after all earlier ones were cast or cleared use every + loaded node again. +- **VOTE-FR-023** **[Changed 2026-10-01]** — Timing choices: `Now`, + `When voting is about to end` (VOTE-FR-081), `At a specific time`, and per node + `Don't use this node`. +- **VOTE-FR-024** **[Changed 2026-10-01]** — Before submission, the confirm step + shows an aggregate (VOTE-FR-080). The full node × contest list (current → + requested choice, timing, changes left) is available under `Adjust nodes`. + A node already shown on the requested choice whose vote is only checked again + (VOTE-FR-074) reads `Current choice: {choice}, as requested. It will be + checked again before a vote is sent.` +- **VOTE-FR-025** — The confirm step removes no-op targets and explains why + (counted under `Skipped`). +- **VOTE-FR-075** **[New]** — Persistent node-set selector per network: `All my + nodes` · `Evonodes only` · `Masternodes only` · `Custom` (checklist), plus + `Save as my default`. The chip shows `{n} nodes · {weight} votes`. Nodes + without a voting key, out of changes, or not in the list are shown with the + reason and cannot be selected. +- **VOTE-FR-080** **[New]** — The confirm popover shows: + - title `Cast {d} decisions with {n} nodes`; + - a decision list (name, choice, nodes, deadline); + - `{t} transactions, one per node and name. Voting is free for your nodes.`; + `{t}` leaves out votes that are only checked again (VOTE-FR-074), and the + line is not shown when `{t}` is 0; + - when there are such votes: `{r} votes are already shown as cast. Dash Evo + Tool checks them again first and sends nothing for nodes that still hold + their choice.`; + - the change warning, once: `{c} of these change an earlier vote. Each node can + change its vote 4 times per name.`; + - `Skipped: {s} votes` with reasons; + - the timing selector and `Adjust nodes`; + - primary `Cast {t} votes` / `Schedule {t} votes`; when every vote is only + checked again, `Check {r} votes` / `Schedule {r} checks`. + - Enter confirms and Esc cancels. + Relative schedule display presets are stored in one network-scoped metadata record per vote operation, without changing the vote journal binary format. Changing the absolute scheduled time clears the preset; cancellation and identity removal retain metadata only with its journal owner under the same retention rules. Network-data clearing retains journal history and uncertain locks under existing rules, and display metadata follows those owners. Reads never create or delete metadata. +- **VOTE-FR-082** **[New]** — Keyboard (only when focus is in the contest list): + J/K or ↓/↑ move card focus · 1–9 vote for contender n · L lock · A abstain · + 0 clear · Space select · Enter open confirm. Selecting ≥ 2 cards shows a bulk + bar: `Lock name` · `Abstain` · `Clear`. A `Shortcuts` popover lists the keys. +- **VOTE-FR-086** **[New]** — The tray reads `{d} decisions ready · {t} + transactions, one per node and name` with `Clear` and `Cast`. Votes that are + only checked again (VOTE-FR-074) are left out of `{t}` and shown beside it as + `{r} votes already shown as cast will be checked again`; `Cast` stays + available for them. When `{t}` is 0 the tray reads `{d} decisions ready` + without the transaction half. + +### Operation lifecycle + +- **VOTE-FR-030** — Every submitted batch has a stable operation ID. +- **VOTE-FR-031** — Every target result includes operation ID, node ID, contest + ID/name, requested choice, and typed status. +- **VOTE-FR-032** — Target statuses are `Scheduled`, `Queued`, `Submitting`, + `Confirming`, `Confirmed`, `Unconfirmed`, `Rejected`, and + `Failed before submission`, plus `Cancelled` when the user cancels a + scheduled target before it is submitted (see VOTE-FR-055). `Not applied` + (definitive post-broadcast reconciliation) is **not implemented — blocked on + [dashpay/platform#4137](https://github.com/dashpay/platform/issues/4137)**: + the status is reserved in the journal encoding, and nothing produces it. +- **VOTE-FR-033** — Same-node targets execute sequentially to preserve nonce + order. Different nodes may execute concurrently with a fixed bound. +- **VOTE-FR-034** — A target lock prevents a second operation for the same + network + node + contest while the first is unresolved. +- **VOTE-FR-035** **[Changed 2026-10-01]** — Button state derives from the shared + coordinator. A click disables the affected targets immediately. Progress shows + in the non-blocking drawer (VOTE-FR-083), never in a full-window overlay. +- **VOTE-FR-036** — Navigation does not cancel an operation or lose its state. +- **VOTE-FR-037** — Restart restores scheduled and unresolved operations before + enabling conflicting actions. A vote that was still queued (never claimed, so + never broadcast) when the app stopped is sent after restart only while it is + fresh: within 2 minutes of the review for an immediate vote, or of its time + for an admitted schedule. Older ones are not sent by themselves — an + immediate vote becomes `Not submitted` with `Review again`, a schedule is + shown as missed. An immediate vote that recovery stops or sends again is + dated by that recovery, so the progress drawer and `Needs attention` of that + session show its outcome even though it was reviewed in an earlier one. A recovered immediate vote that was reviewed as a first + vote is likewise not sent when Platform now shows a different vote for the + node. +- **VOTE-FR-083** **[New]** — The progress drawer (bottom-right, collapsible, + persists across screens) has the header `Casting {t} votes · {done} done · + {sending} sending · {checking} being checked`, a segmented progress bar, and + per node × name rows with typed status and the valid action (`Check again`, + `Review again`, `Add voting key`). `Review again` opens the confirm step for + that one node × name only; decisions staged in the tray are not part of it + and are still staged when it is confirmed or cancelled. Cards whose targets + are in flight show + `Sending with {n} nodes…` and lock their choices. Everything else stays + interactive. +- **VOTE-FR-084** **[New]** — A `Needs attention` row at the top of Votes appears + when any target is Unconfirmed, Rejected, Failed before submission, or a missed + schedule. It summarizes and links to the drawer (`Show progress`) or Scheduled + (`Open Scheduled`). Unconfirmed targets and missed schedules always count. A + failure counts while it is the latest outcome for its target, has not been + dismissed in the drawer, and was sent in this session — for a scheduled vote + that is its scheduled time, so a vote scheduled days ago that fails today is + shown. +- **VOTE-FR-087** **[New]** — Targets not yet submitted when their contest's + voting ends become `Failed before submission` with the reason `Not submitted. + Voting ended.` + +### Confirmation and recovery + +- **VOTE-FR-040** — Structured Platform consensus causes are treated as + confirmed rejection. A rejection reported by the broadcast step is checked + once against the proved current vote first, because that step retries and + reports only its last attempt: when Platform already shows the requested + choice, the target is `Confirmed`. Any other read, or a failed read, keeps + the rejection. +- **VOTE-FR-041** — A cause-less post-broadcast wait failure is treated as + `Unconfirmed`, never as rejection. +- **VOTE-FR-042** — Unconfirmed targets are reconciled against the proved + current vote: an exact match confirms the target, and a missing or different + vote leaves it Unconfirmed and locked. The scheduled-vote sweep re-checks them + after it has executed the due votes — on the three sweeps after startup or + vote activity, then every 10 minutes — and reports a result only when a vote + was confirmed. Targets of a decided contest are not queried, because Platform + has dropped their vote references. `Check again` re-checks on demand. Retry + by transition hash is **not implemented — blocked on + [dashpay/platform#4137](https://github.com/dashpay/platform/issues/4137)**. +- **VOTE-FR-043** — A target becomes `Confirmed` when authoritative state + matches the requested choice. +- **VOTE-FR-044** — DET never offers `Submit again` while the result remains + ambiguous. It offers `Check again`. +- **VOTE-FR-045** — **Not implemented — blocked on + [dashpay/platform#4137](https://github.com/dashpay/platform/issues/4137).** + A retry would become available only after authoritative reconciliation proves + the requested change was not applied. No reconciliation result proves that + today, so an Unconfirmed target keeps its lock. +- **VOTE-FR-046** — If saved voting-operation progress cannot be read, DET + shows a persistent notice that the displayed history may be incomplete, + offers `Retry loading`, and keeps cached progress and existing target + locks intact until a refresh succeeds. + +### Scheduled votes + +- **VOTE-FR-050** — Scheduled votes use the same target model, result model, + locking, execution order, and reconciliation as immediate votes. +- **VOTE-FR-051** — A scheduled target is marked executed only after confirmed + application. +- **VOTE-FR-052** — Rejected and failed-before-submission targets remain visible + with an actionable status. +- **VOTE-FR-053** — Unconfirmed scheduled targets are not automatically + rebroadcast. +- **VOTE-FR-054** — Schedules use only the voting journal. Startup reports + unexecuted schedules in previous SQLite storage and asks the user to schedule + them again; it neither imports, lists, nor executes them. The notice stops + one contest duration after it first appeared, when no such contest can still + be open. +- **VOTE-FR-055** — A scheduled target can be edited or cancelled until + execution begins. Once submitting, it follows normal operation locking. +- **VOTE-FR-056** — A target still `Scheduled` more than 120 seconds past its + due time is explained in Scheduled as a missed automatic vote, with + `Cast now`, `Edit`, and `Remove` actions. +- **VOTE-FR-081** **[New]** — `When voting is about to end` resolves to + end_time − preset (default 6 h on mainnet, 10 min on testnet/devnet, editable). + Store the absolute UTC time as today, and display both: `6 hours before the end + · {abs UTC}`. A contest already inside the lead time is voted now instead of + rejecting the batch; the confirm step says so with a count: `{n} of these + votes will be sent now because voting ends soon.` `{n}` leaves out votes that + are only checked again (VOTE-FR-074), and the line is hidden when none is + left. Every other contest is + scheduled as above. A contest whose deadline has not been read yet cannot be + placed: its votes are listed under Skipped (`The end of voting is not known + yet for these names. …`) and the rest of the batch goes ahead; a node set to + `Now` under `Adjust nodes` still votes on it. Deadlines are read from the + contest list when the confirm step is built, not when a choice was staged. + Absolute times (`At a specific time`) at or after the deadline are still + rejected (existing rule). +- **VOTE-FR-088** **[New]** — The Scheduled view groups rows by decision (name × + choice × time) with an expandable node list (`24 nodes ▾`). Per-node status + shows inside the expansion. Groups are listed by name, then time; the view + has no sort control and does not follow the History sort. + +### Feedback + +- **VOTE-FR-060** — One confirmed target shows a concise success banner. +- **VOTE-FR-061** **[Changed 2026-10-01]** — Batch feedback is the drawer plus one + final banner summarizing counts: `{n} nodes voted on {d} names.`, or, while + some are unconfirmed, `Participating nodes: {n}. Names with confirmed votes: + {d}. Votes still being checked: {k}. Dash Evo Tool will keep checking. Do not + submit the pending votes again.` A batch with several different outcomes + lists one `{Outcome}: {count}.` unit per non-empty outcome. A batch in which + nothing was submitted names the cause: a connection problem, voting ended, or + a voting key that is not loaded. +- **VOTE-FR-062** — Messages name node aliases and contested names where useful. +- **VOTE-FR-063** — Technical errors stay in banner details. +- **VOTE-FR-064** — Unconfirmed copy explicitly says DET will keep checking and + warns against resubmission. +- **VOTE-FR-065** — Loading a voting private key that does not match the + selected node's voter identity is rejected with a key-specific error, + without merging or altering the node's existing stored keys. +- **VOTE-FR-085** **[New]** — Durations and urgency come from the network's + platform version (PF §3): contest 14 days / joinable 7 days on mainnet, + 90 min / 45 min on testnet/devnet. Urgency window: 24 h mainnet, 30 min + otherwise. Never hard-code "two weeks". Source: shared + `model/dpns.rs` helper (owned by Stream U). + +## Non-functional requirements + +- **VOTE-NFR-001 Safety** — No UI path can bypass target locking. +- **VOTE-NFR-002 Correctness** — Same-voter transitions are serialized. +- **VOTE-NFR-003 Durability** — A crash after broadcast cannot erase the only + record that the outcome is unresolved. +- **VOTE-NFR-004 Proofs** — Current vote state is obtained through proved SDK + queries. +- **VOTE-NFR-005 Accessibility** — Disabled actions explain why; progress is not + color-only; keyboard focus follows the composer step order. +- **VOTE-NFR-006 Localization** — User-facing strings are complete translation + units with no parsed error text; plural pairs for counts. +- **VOTE-NFR-007 Performance** — Refresh queries votes once per node, not once + per contest, and bounds cross-node concurrency. The background refresh + (VOTE-FR-074) reuses the same path. +- **VOTE-NFR-008 Network isolation** — Drafts, schedules, operations, locks, + results, and node-set preferences are network-scoped. +- **VOTE-NFR-009 Secret handling** — The coordinator stores identifiers and + choices, never private keys. +- **VOTE-NFR-010** **[New]** **Shortcuts** — Single-key shortcuts act only while + focus is in the contest list and never in text fields. Every shortcut has a + visible control equivalent (WCAG 2.1.4). + +## Platform dependency + +The preferred recovery contract is +[dashpay/platform#4137](https://github.com/dashpay/platform/issues/4137) (retryable +post-broadcast wait errors; transition hash after broadcast). DET still supports +fallback reconciliation via the node's proved vote. Until either proves the +result, the operation remains unconfirmed and locked. + +**[New]** Upstream ask: expose the per-node vote count in the proved +identity-votes response so VOTE-FR-078 can stop relying on the local journal. + +## Out of scope + +- Changing Platform's five-vote protocol limit. +- ~~Showing a remaining-change count before Platform exposes it in the proved + identity-votes response.~~ **[Superseded 2026-10-01 → VOTE-FR-078]** (local + count, labelled as such). +- Embedding Platform Explorer. +- Allowing arbitrary cancellation after broadcast. +- Unlocking locked names (not implemented in Platform, PF §1). diff --git a/docs/ai-design/2026-07-16-dpns-voting-experience/02-ux-spec.md b/docs/ai-design/2026-07-16-dpns-voting-experience/02-ux-spec.md new file mode 100644 index 000000000..e37f1b1ac --- /dev/null +++ b/docs/ai-design/2026-07-16-dpns-voting-experience/02-ux-spec.md @@ -0,0 +1,178 @@ +# DPNS Voting Experience — UX Specification + +## Adopted direction (revised 2026-10-01) + +This revision supersedes the 2026-07-21 "DPNS ▸ Active contests" placement. The +durable operation coordinator remains the safety model. What changed: + +- Voting lives in **Masternodes ▸ Votes**, and a top-bar chip signals from every + screen. +- One decision per contest is applied to a persistent node set. +- The confirm step is an aggregate. +- Progress is a non-blocking drawer. +- Each node shows its weight and changes left. +- Keyboard and bulk shortcuts are added. + +Stream V. Wireframes: `../2026-10-01-usernames-redesign/wireframes.html` +frames V0–V6. Requirement IDs: `01-requirements.md`. + +## Rationale + +- Operators vote repeatedly and manage nodes occasionally, so voting sits next + to the keys, node types (weight) and node fixes. +- Operators run many nodes and Platform has no vote batching. One decision + fanned out to N transactions is the right unit; per-target rows are detail. +- Target locks already prevent duplicates. Blocking the whole window added time, + not safety. +- Running out of changes is the costliest mistake, so changes left are shown, + honestly labelled. +- Read-only tallies and selectable choices keep different shapes (unchanged + from #901). + +## Information architecture + +```text +Top bar (every screen): breadcrumb · [N names need your vote] · [1 vote is still being checked] · network +Masternodes (badge = needs-decision contests + unresolved targets) +├── [ Votes | Nodes ] Votes first; opens on Votes when badge > 0 +├── Votes +│ ├── To decide (default; sorted by time left; partly voted included) +│ ├── Voted +│ ├── Scheduled +│ └── History +│ + node-set chip · filter · Shortcuts · Needs-attention row · tray · confirm · drawer +└── Nodes list + detail (detail: This node's votes · Vote with this node) +Tools — DPNS entry removed. My usernames → Identity hub (Stream U). +``` + +## Votes ▸ To decide (frame V1) + +Header row: sub-view chips · node-set chip `Vote with: All my nodes · 24 nodes · +51 votes ▾` · a `Filter by name` field (homoglyph tooltip: `The letters i and l +match the digit 1, and the letter o matches 0.`). + +Card (two columns): +- Left, read-only: + - `alice.dash` and `Ends in 6 hours` (amber within the urgency window); + - `2 requests · Voting ends {date} {time} UTC.` During the join window: + `Others can join until {date} {time} UTC.`; + - weighted tally bars with numbers (`Vote for` rows = contenders, then + `Lock name`, `Abstain`); + - influence line (VOTE-FR-077). +- Right: `Your decision` pills `Vote for {name} ({full_base58_id})` (1–9) · `Lock name` (L) · + `Abstain` (A). The node line reads `19 of your nodes have not voted. + 4 of your nodes voted: Abstain. mn-07 has no changes left.` When the decision changes earlier votes: + `Changing 4 earlier votes uses 1 of each node's 4 changes.` Unavailable state: + `Vote state is unavailable for 3 nodes; they're left out.` with + [Refresh voting]. +- Checkbox at top-left for bulk selection. Keyboard focus ring on the focused + card. + +Below the cards, a collapsed `Can't vote with your nodes ({n})` group (dimmed, +reason per card). + +Tray (outside scroll): `{d} decisions ready · {t} transactions, one per node and +name` [Clear] [Cast ⏎]. + +Needs-attention row (warning style, only when present): `Votes still being checked: 1. +Missed scheduled votes: 1. Do not submit the pending votes again.` +[Show progress] while votes are being checked or have failed, [Open Scheduled] +when a scheduled vote was missed. + +## Node set (frame V1b) + +A popover with radios: All my nodes · Evonodes only · Masternodes only · Custom. +- Each radio shows `{n} nodes · {weight} votes ({e} evonodes × 4 + {m} + masternodes)`. +- Custom shows a checklist with node, votes, voting-key status and note. +- Disabled rows: `No key` [Add voting key] · `Not in the masternode list` · + `No changes left`. +- `Save as my default` (per network) · [Done]. + +Candidate choices show the full Base58 identity in the confirmation, node adjustment, +schedule editor, and progress drawer, even when the candidate name is unavailable. + +## Confirm (frame V2) + +Popover per VOTE-FR-080. Timing segmented control: `Now` | `When voting is about +to end` | `At a specific time`. +- Helper for the relative option: `"When voting is about to end" casts each vote + 6 hours before its name's deadline. Keep Dash Evo Tool open and connected + until then.` Names already closer to their deadline are voted now, and the + confirm reads `{n} of these votes will be sent now because voting ends soon.` +- `Adjust nodes` table: Node · Name · Current → new · Changes left · Timing + (Now / Before the end / Don't use this node). + +Rules (unchanged from #901, now in the confirm step): +- remove exact no-ops; +- block targets held by an unresolved operation, with the reason; +- refuse nodes whose proved state is unavailable; +- if a first vote becomes a change during preflight, reopen the confirm with the + change warning. + +## Progress drawer (frame V2b) + +As specified in VOTE-FR-083. +- Row copy by status: `Confirmed` · `Submitting` · `Confirming` · + `Still being checked. Do not submit it again.` [Check again] · + `Rejected` [Review again] · `Not submitted` [Review again] · + `Not submitted. The voting key is not loaded.` [Add voting key] · + `Not submitted. Voting ended.` (no action). A `Not applied` row is not + implemented (VOTE-FR-032). +- A different current vote does not prove that an ambiguous submission failed. + Checking retains the duplicate-prevention lock until a conclusive result. +- The drawer is a fixed 360 px panel anchored bottom-right. Collapsed, it + keeps its header (`Casting 44 votes · 33 done · …`) with [Show]; expanded, + the header offers [Hide], and [Dismiss] once nothing is in flight. +- The final banner is defined in VOTE-FR-061. + +## Scheduled (frame V3) + +Columns: Name · Nodes (`24 nodes ▾`) · Vote · When · Status · actions. +- When shows the relative label plus absolute UTC and a relative time. +- Statuses: `Scheduled` [Edit] [Remove] · `Missed automatic vote` + guidance + [Cast now] [Edit] [Remove] · `Not submitted` + saved reason + valid action · + `Confirmed`. Node labels use the alias or the same hexadecimal ProTxHash + handle as the Nodes view. +- Bulk `Remove finished votes` asks for confirmation. +- Note: `Keep Dash Evo Tool open and connected so scheduled votes are cast on + time.` + +## History (frame V4) + +Name · Ended · Last updated · Outcome · details [details] +(`Went to {name} ({short_id})` [Copy ID] · `Locked for good, no one can register it`). + +The explorer link opens that contest in the system browser on the active Mainnet +or Testnet network. Devnet and Regtest have no public explorer link. + +## Empty and gate states (frame V5) + +| State | Copy | Action | +|---|---|---| +| No nodes loaded | `No masternodes are loaded.` · `Load a masternode with its voting key to cast votes.` | Load a masternode | +| Nodes, no voting key | `None of your nodes has a voting key on this device. Add a voting key to vote. One key can serve several nodes.` | Add a voting key | +| No open contests | `There are no open name contests right now. New contests appear here automatically.` | Refresh | +| Journal unreadable | `Saved voting progress could not be read. The displayed history may be incomplete or out of date. Do not submit votes again until you have retried loading and checked their status.` | Retry loading | + +## Node detail (frame V6) + +Header: node alias, `Voting ready`, a type badge `Evonode · 4 votes`, and the +masternode-list status. Primary [Vote with this node]. `This node's votes` is a +grid without a header row: name · vote · changes left · time left. Each row +with a vote carries its own `{n} of 4 changes left, counted on this device`. + +## Top-bar chip (frame V0) + +Defined in VOTE-FR-072. Tooltip lists up to 3 names with deadlines. It is hidden +below the Power role or when no node has a voting key. + +## Accessibility and responsive behavior + +- Tally bars and numbers are labels with no focus. Choices are + `selectable_label`s with the full phrase. +- Shortcut rules are in VOTE-NFR-010. +- Status is always text plus icon; color is supplementary. +- The drawer never steals focus. +- Narrow widths: tally stacks above choices; the drawer keeps its fixed-width + bottom-right panel; the tray stays outside the scroll area. diff --git a/docs/ai-design/2026-07-16-dpns-voting-experience/03-test-case-spec.md b/docs/ai-design/2026-07-16-dpns-voting-experience/03-test-case-spec.md new file mode 100644 index 000000000..80bae38f0 --- /dev/null +++ b/docs/ai-design/2026-07-16-dpns-voting-experience/03-test-case-spec.md @@ -0,0 +1,124 @@ +# DPNS Voting Experience — Test Case Specification + +Stream V. Revised 2026-10-01. Markers as in `01-requirements.md`. Level: U = unit, +K = kittest, B = backend test with fake SDK seam. + +## Authoritative state + +| ID | Description | Preconditions | Steps | Expected outcome | Requirements | +|---|---|---|---|---|---| +| VOTE-TC-001 | Current vote loads from Platform | Node has a proved Lock vote | Refresh voting | Node line shows the node voted Lock | FR-010, FR-011 | +| VOTE-TC-002 | Existing vote remains visible | Node already voted; contest active | Open Votes | Contest in Voted (or To decide if other node-set nodes have not voted); proved choice highlighted; change possible | FR-012, FR-071 | +| VOTE-TC-003 | Current choice is a no-op | Current vote is Lock | Select Lock, open confirm | Counted under Skipped; nothing submittable for that target | FR-013, FR-025 | +| VOTE-TC-004 | Coherent refresh | Tally and current vote changed | Refresh | One snapshot shows both | FR-014 | +| VOTE-TC-005 | Vote query is per node | One node, 100 contests | Refresh | One identity-votes query for the node | NFR-007 | +| VOTE-TC-006 **[Changed]** | Change warning once | 3 nodes with existing votes | Pick a different choice, open confirm | One line `3 of these change an earlier vote…`; no per-node repetition | FR-015, FR-080 | +| VOTE-TC-007 | Vote query failure is not `Not voted` | Proved query fails for 1 of 3 nodes | Open Votes | Card says unavailable for 1 node; that node excluded; others submittable | FR-016 | +| VOTE-TC-008 | Node summary distinguishes active and unvoted | 3 active; node voted in 2 | View node card | Summary: three active, one needs a vote | FR-017 | + +## Composition + +| ID | Description | Preconditions | Steps | Expected outcome | Requirements | +|---|---|---|---|---|---| +| VOTE-TC-010 | Single decision | Node set = 3 nodes, one choice | Cast → confirm → Cast | One target per node for that contest | FR-020, FR-075 | +| VOTE-TC-011 **[Changed]** | Multi-contest aggregate | 3 choices, 3 nodes | Open confirm | Title `Cast 3 decisions with 3 nodes`; `9 transactions…`; Adjust nodes lists 9 rows | FR-024, FR-080 | +| VOTE-TC-012 | Schedule at a specific time | One draft | Choose At a specific time | Targets appear in Scheduled with that UTC time | FR-023, FR-050 | +| VOTE-TC-013 **[Changed]** | No voting key | Nodes loaded, none with voting key | Open Votes | Gate copy + `Add a voting key`; no submit | FR-075, V5 | +| VOTE-TC-014 | Voting key does not match node | Wrong voting key | Submit load | Key-specific rejection; existing keys unchanged | FR-065 | +| VOTE-TC-020 | Multiple contests and nodes | 2 contests, 3 nodes | Confirm | 6 targets in Adjust nodes | FR-021, FR-024 | +| VOTE-TC-021 **[Changed]** | Batch timing | 3 nodes | Choose `When voting is about to end` | All targets scheduled at end − preset | FR-022, FR-081 | +| VOTE-TC-022 | Per-node override | Batch Now | Set one node to Before the end in Adjust nodes | Two Now, one Scheduled target | FR-022 | +| VOTE-TC-023 **[Changed]** | Tray | 3 nodes | Pick a choice | Tray `1 decision ready · 3 transactions…` | FR-086 | +| ~~VOTE-TC-024~~ | ~~Node navigation is plain~~ | | | **[Superseded → VOTE-TC-091]** | | +| VOTE-TC-025 **[Changed]** | Adjust nodes defaults | 3 nodes | Expand Adjust nodes | All rows default to batch timing; each overridable incl. Don't use this node | FR-022, FR-023 | + +## Execution correctness (unchanged) + +| ID | Description | Preconditions | Steps | Expected outcome | Requirements | +|---|---|---|---|---|---| +| VOTE-TC-030 | Same-node serialization | One node, three immediate targets | Submit | Nonce fetch/broadcast for target N+1 starts after N finishes submission | FR-033, NFR-002 | +| VOTE-TC-031 | Cross-node bounded concurrency | Four nodes, one target each | Submit | Different nodes run concurrently up to the configured bound | FR-033, NFR-007 | +| VOTE-TC-032 | Structured result correlation | Two nodes vote on same name; one fails | Complete operation | Result identifies the exact successful and failed node | FR-031 | +| VOTE-TC-033 | Scheduled inner error is not success | Scheduled backend returns an inner rejection | Execute | Target is Needs attention; record is not marked executed | FR-051, FR-052 | +| VOTE-TC-034 | Scheduled unconfirmed is not rebroadcast | Scheduled wait fails after broadcast | Run next sweep | Target remains Checking result; no second broadcast occurs | FR-053 | + +## Duplicate prevention + +| ID | Description | Preconditions | Steps | Expected outcome | Requirements | +|---|---|---|---|---|---| +| VOTE-TC-040 | Double click | Confirm open | Double-click Cast | One operation, one broadcast per target | FR-034, FR-035 | +| VOTE-TC-041 | Cross-screen duplicate | Target confirming | Return to Votes | Card shows `Sending with {n} nodes…`, choices locked for those targets | FR-034, FR-083 | +| VOTE-TC-042 | Unrelated target stays usable | One target confirming | Pick another contest | Enabled | Decision 7 | +| VOTE-TC-043 | Navigation preserves lock | Submit, navigate, return | Inspect | Drawer and lock persist | FR-036 | +| VOTE-TC-044 | Restart preserves lock | Unresolved target persisted | Restart | Restored and reconciled before resubmission | FR-037, NFR-003 | + +## Confirmation and recovery + +| ID | Description | Preconditions | Steps | Expected outcome | Requirements | +|---|---|---|---|---|---| +| VOTE-TC-050 | Confirmed success | Broadcast and result wait succeed | Complete target | Status Confirmed; success banner shown | FR-043, FR-060 | +| VOTE-TC-051 | Structured rejection | Platform returns typed consensus cause | Complete target | Status Rejected with actionable typed message | FR-040 | +| VOTE-TC-052 | Cause-less wait failure | Broadcast succeeds; wait returns no cause | Complete target | Status Unconfirmed; warning forbids resubmission | FR-041, FR-044, FR-064 | +| VOTE-TC-053 | Reconcile to success | Unconfirmed target; proved vote matches request | Check again | Status changes to Confirmed without rebroadcast | FR-042, FR-043 | +| VOTE-TC-054 | Reconcile to safe retry — **not implemented, blocked on dashpay/platform#4137** | Unconfirmed target; proved vote absent or different | Check again | Target stays Unconfirmed and locked; no resubmission is offered | FR-045 | +| VOTE-TC-055 | Reconciliation unavailable | DAPI remains unavailable | Check again | Target stays Unconfirmed and locked; no false failure/success | FR-044 | +| VOTE-TC-056 **[Changed]** | Partial batch | Two confirmed, one unconfirmed, one rejected | Complete batch | Drawer maps every target; final banner shows counts | FR-061, FR-062, FR-083 | +| VOTE-TC-057 | Journal read failure stays visible until retried | Saved vote-operation progress cannot be read | Open Votes ▸ Scheduled, then click `Retry loading` once the read succeeds | Persistent notice and `Retry loading` remain visible across renders until a successful refresh, then clear | FR-046 | + +## Scheduling and upgrade notices + +| ID | Description | Preconditions | Steps | Expected outcome | Requirements | +|---|---|---|---|---|---| +| VOTE-TC-060 | Previous schedule notice | Unexecuted SQLite schedule, no matching journal target | Start the app | A persistent notice asks for a new decision; the schedule is neither imported nor executed | FR-054 | +| VOTE-TC-061 | Due schedule uses shared coordinator | Scheduled target becomes due | Sweep | Same lock, result, and reconciliation model is used | FR-050 | +| VOTE-TC-062 | Failed schedule remains visible | Submission fails before broadcast | Open Scheduled | Needs attention row shows corrective action | FR-052, FR-084 | +| VOTE-TC-063 | Scheduled target can be edited | Target is Scheduled, not due | Change time or choice | Updated target persists and keeps one lock | FR-055 | +| VOTE-TC-064 | Scheduled target can be cancelled | Target is Scheduled, not due | Cancel and confirm | Target is removed and its lock is released | FR-055 | +| VOTE-TC-065 | Submitting schedule cannot be edited | Target is Submitting | Inspect actions | Edit and Cancel are disabled with an explanation | FR-055 | +| VOTE-TC-066 | Missed automatic vote is explained | Due time > 120 s past, not executed | Reopen Scheduled | Row shows `Missed` with `Cast now`, `Edit`, `Remove` | FR-056 | +| VOTE-TC-067 **[New]** | Relative schedule resolves | Mainnet contest ends T | Schedule `When voting is about to end` | Stored time = T − 6 h; row shows `6 hours before the end · {abs UTC}` | FR-081 | +| VOTE-TC-068 **[New]** | Testnet preset | Testnet contest | Same | T − 10 min | FR-081, FR-085 | +| VOTE-TC-069 **[New]** | Grouped scheduled rows | One decision on 24 nodes | Open Scheduled | One row `24 nodes ▾`; expansion lists 24 statuses | FR-088 | + +## Convenience (new) + +| ID | Description | Preconditions | Steps | Expected outcome | Requirements | Lvl | +|---|---|---|---|---|---|---| +| VOTE-TC-080 | Votes first | Badge > 0 | Open Masternodes | Votes segment active | FR-070 | K | +| VOTE-TC-081 | Last used when nothing pending | Badge 0, last segment Nodes | Open Masternodes | Nodes active | FR-070 | K | +| VOTE-TC-082 | Legacy routes | Persisted `RootScreenDPNSScheduledVotes` | Start app | Votes ▸ Scheduled opens | FR-070 | K | +| VOTE-TC-083 | Owned-names route | Persisted `RootScreenDPNSOwnedNames` | Start app | Identity hub opens | FR-070 | K | +| VOTE-TC-084 | Tools has no DPNS | Any | Open Tools | No DPNS entry | FR-070 | K | +| VOTE-TC-085 | Attention chip urgent | Power, voting node, contest ends in 3 h (mainnet) | Any screen | Amber chip `1 name needs your vote · first ends in 3 hours`; click opens Votes | FR-072, FR-085 | K | +| VOTE-TC-086 | Chip hidden | Below Power role, or no voting key | Any screen | No chip | FR-072 | K | +| VOTE-TC-087 | Unresolved chip | One Unconfirmed target | Any screen | `1 vote is still being checked` chip | FR-072 | K | +| VOTE-TC-088 | Sort by time left | Contests ending in 4 d, 6 h, 12 min | To decide | Order 12 min, 6 h, 4 d | FR-071 | K | +| VOTE-TC-089 | Partly voted stays | 5 of 24 nodes voted | To decide | Card present with `Voted with 5 of 24 nodes` | FR-071 | K | +| VOTE-TC-090 | Node set persists per network | Choose Evonodes only, save | Restart; switch network | Evonodes only restored on that network only | FR-075, NFR-008 | U+K | +| VOTE-TC-091 | Vote with this node | Node detail | Click | Votes with node-set chip naming that node; no draft carried | FR-076 | K | +| VOTE-TC-092 | Weighted influence | Leader margin 6; node set weight 51 | Render card | Influence line shown; hidden when weight < margin | FR-077 | U | +| VOTE-TC-093 | Tie copy | Two contenders equal | Render | `If still tied at the end, the most recent request wins.` | FR-077 | K | +| VOTE-TC-094 | Changes left count | Journal: 3 confirmed votes for node × contest | Render node detail | `2 of 4` (5 − 3) | FR-078 | U | +| VOTE-TC-095 | Changes unknown | Proved vote exists, journal empty | Render | `Changes left unknown. This device has no record of this node's earlier votes.` | FR-078 | U | +| VOTE-TC-096 | Out of changes skipped | Journal 5 votes | Confirm | Node under Skipped with `no changes left (4 of 4 changes used)`; not submitted | FR-078, FR-025 | B | +| VOTE-TC-097 | Not in list excluded | Node absent from masternode list | Node set | Row disabled with reason; not submitted | FR-079 | K | +| VOTE-TC-098 | Keyboard flow | 2 cards | J, 2, J, L, Enter | Choices set, confirm opens; shortcuts ignored while filter field focused | FR-082, NFR-010 | K | +| VOTE-TC-099 | Bulk bar | 3 cards selected | Click Abstain | All three drafts = Abstain | FR-082 | K | +| VOTE-TC-100 | Drawer non-blocking | Batch sending | Interact with another card, navigate | Other controls enabled; drawer persists; no full-window overlay | FR-035, FR-083 | K | +| VOTE-TC-101 | Drawer statuses | Mixed outcomes | Inspect | Each row has typed status and the single valid action; unconfirmed never offers resubmit | FR-083, FR-044 | K | +| VOTE-TC-102 | Needs-attention row | One Unconfirmed + one missed | Open Votes | Row summarises both; `Show progress` opens the drawer, `Open Scheduled` opens Scheduled | FR-084 | K | +| VOTE-TC-103 | Contest ends mid-batch | Queued targets past end | Execute | `Failed before submission` + `Not submitted. Voting ended.` | FR-087 | B | +| VOTE-TC-104 | Background refresh cadence | Voting nodes loaded | Advance clock | Contest + vote-state refresh at 30 min mainnet / 3 min testnet; one query per node | FR-074, NFR-007 | U | +| VOTE-TC-105 | Votes stub not used | — | Code search / seam test | Vote state uses `ResourceVote::fetch_many` by proTxHash | FR-010 | B | + +## UX, accessibility, and isolation + +| ID | Description | Expected outcome | Requirements | +|---|---|---|---| +| ~~VOTE-TC-070~~ | ~~Blocking submission feedback~~ | **[Superseded → VOTE-TC-100]** | | +| VOTE-TC-071 **[Changed]** | Keyboard confirm | Tab order: decisions → timing → Adjust nodes → Cast; Enter confirms, Esc cancels | NFR-005, FR-080 | +| VOTE-TC-072 | Network isolation | No cross-network locks, rows, or node sets | NFR-008 | +| VOTE-TC-073 | No secret persistence | Serialized operation has no key bytes | NFR-009 | +| VOTE-TC-074 | Complete message units | Complete strings and plural pairs | NFR-006 | +| VOTE-TC-075 | One submit path | Every path (Votes, node-scoped, due schedule) creates a coordinator operation | NFR-001 | +| VOTE-TC-076 | Technical error in details | Plain copy; diagnostics attached | FR-063 | diff --git a/docs/ai-design/2026-07-16-dpns-voting-experience/04-development-plan.md b/docs/ai-design/2026-07-16-dpns-voting-experience/04-development-plan.md new file mode 100644 index 000000000..f16b331ac --- /dev/null +++ b/docs/ai-design/2026-07-16-dpns-voting-experience/04-development-plan.md @@ -0,0 +1,257 @@ +# DPNS Voting Experience — Development Plan + +Revised 2026-10-01. Sections up to "Message handling" describe what #901 built: +the safety model, which is **unchanged**. "2026-10-01 revision: Stream V work" +lists what changes. Identity usernames are Stream U +(`../2026-10-01-usernames-redesign/`). File ownership across streams: +"Shared backend and file ownership". + +## Architecture + +```text +Platform proved queries + │ + ▼ +DPNS vote-state store ────────┐ + │ +Draft / node set / composer ──> Vote operation coordinator + │ + ├─ durable operation journal + ├─ target lock registry + ├─ scheduled dispatcher + └─ immediate executor + │ + group by node ───┤ + sequential/node │ + bounded nodes ▼ + Platform broadcast + wait + │ + ▼ + reconciliation service + │ + ▼ + shared operation/result views (Votes, drawer, chip, node detail) +``` + +Screens never own the authoritative in-progress flag. They render coordinator +state and submit typed drafts. + +## Domain model (built in #901) + +`src/model/dpns_voting/` contains `mod.rs` (journal and vote-state types), +`composer.rs` (draft expansion), `operator.rs` (node sets, influence and +scheduling), and `progress.rs` (progress summaries). The journal types include: + +- `DpnsVoteTargetKey { network, voter_id, vote_poll_id }` +- `DpnsVoteTarget { key, voter_alias, contested_name, requested_choice, current_choice, timing }` +- `DpnsVoteOperationId([u8; 16])`, generated with the existing RNG dependency +- `VoteTiming { Now, Scheduled(TimestampMillis) }` +- `DpnsVoteTargetStatus`: Scheduled, Queued, Submitting, Confirming, Confirmed, + Unconfirmed, Rejected, FailedBeforeSubmission, NotApplied, Cancelled +- `DpnsVoteOutcome { operation_id, target, status, failure }` +- `DpnsVoteFailure`: a pure domain enum, mapped structurally from backend + errors. It never serializes `TaskError` or secrets. + +Operator helpers in `src/model/dpns_voting/operator.rs`: + +- `NodeSet { All, EvonodesOnly, MasternodesOnly, Custom(BTreeSet) }` + plus resolution against the loaded nodes, producing excluded nodes with typed + reasons (`NoVotingKey`, `NotInMasternodeList`). Contest-specific checks + separately exclude exhausted or unavailable vote states. +- `ChangesLeft { Known(u8), Unknown }`, computed from journal counts and proved + state (VOTE-FR-078). +- `node_weight(kind) -> u32` (1 or 4) and + `influence(contenders, lock_votes, node_set_weight) -> Option` + (VOTE-FR-077). +- `relative_schedule(end_time, preset, now_ms) -> Result` + (VOTE-FR-081). +- `DpnsVoteFailure::VotingEnded` in `mod.rs` for VOTE-FR-087. + +## Data ownership (built in #901) + +- `src/backend_task/contested_names/refresh_vote_states.rs`: proved votes per + node via `ResourceVote::fetch_many` keyed by proTxHash. +- `src/context/dpns_vote_state.rs`: vote-state cache indexed by node + poll + and persisted per network and node scope. +- `src/context/dpns_vote_operations/`: journal and target locks. Persists + before the first broadcast, restores on startup, and releases a lock only on a + terminal state or on cancelling an unsubmitted schedule. Unconfirmed targets + stay locked. + +## Backend tasks (built in #901) + +`ContestedResourceTask::SubmitDpnsVoteOperation`, +`ReconcileDpnsVoteOperation`, `CastDueScheduledVotes { … }`; +`BackendTaskSuccessResult::DpnsVoteOperationUpdated { network, operation_id }`. +The due-schedule sweep +runs on a timer of about 60 s in `AppState::update()`. + +## Execution algorithm + +1. Refresh proved state for the operation's queued voters and validate it. +2. Remove no-ops. +3. Persist the operation and take locks atomically. +4. Group by node. +5. Bound concurrency across nodes, and run each node sequentially: claim the + target → check the contest deadline → nonce → build and validate → persist + the broadcast boundary (`Confirming`) → broadcast → wait → classify. +6. Persist the outcome. Errors after the broadcast boundary remain Unconfirmed + unless rejection is established; reconcile them without rebroadcasting. +7. Cache confirmed choices and persist terminal outcomes in the voting journal. + +Before dispatching a queued target, re-check the contest end time. +If voting has ended, mark it `FailedBeforeSubmission(VotingEnded)`. + +## Reconciliation + +The journal stores no transition hash. Reconciliation uses a proved +per-identity range query starting at the exact poll ID (#4138 workaround). +An exact choice match confirms the vote. A missing or different choice remains +Unconfirmed, including after closure: Platform removes per-voter references when +resolving contests, so their absence cannot establish whether a vote was counted. +Transition-based recovery is a future integration tracked by dashpay/platform#4137. + +## Scheduling (built in #901) + +Scheduled targets are journal operations with `VoteTiming::Scheduled`. Edit and +cancel are atomic under the lock. The dispatcher uses the shared executor. A +target counts as executed only when Confirmed. A schedule more than 120 s past +due and never admitted is marked missed. + +## Message handling (unchanged) + +One formatter over typed outcomes produces the summary, per-target copy, +details, and the recovery action. Never parse strings. + +--- + +## 2026-10-01 revision: Stream V work + +### Navigation and routing +- Masternodes root screen: add the `Votes | Nodes` segmented header and default + segment logic (VOTE-FR-070). Votes renders the existing DPNS voting screen + body: move `ui/dpns/` content under the Masternodes root, or embed + `DPNSScreen` as the Votes segment. Either way there is one screen instance + and one contest cache. +- Remove the DPNS item from the Tools chooser (`tools_subscreen_chooser_panel.rs`). + Replace `dpns_subscreen_chooser_panel.rs` with the in-page sub-view chips + `To decide · Voted · Scheduled · History`. +- Remove the `Owned` sub-screen and its table and "Set Alias" code from + `ui/dpns/`. +- Routing in `ui/mod.rs`: `RootScreenDPNS{Active,Past,Scheduled}` map to the + Masternodes root with the matching sub-view. `RootScreenDPNSOwnedNames` maps + to `RootScreenIdentityHub`. Keep the enum values for persisted settings. +- `left_panel.rs`: Masternodes badge count from the attention summary. + +### Attention signal +- New `src/context/dpns_vote_attention.rs`: an `AttentionSummary { needs_decision, + soonest_end, unresolved }` derived from the contest cache, vote state, node + set and journal. It is recomputed on refresh and on coordinator updates, never + per frame. +- Background refresh (VOTE-FR-074): a timer in `AppState::update()` beside the + due-schedule sweep. It dispatches the existing contest query plus the vote + state refresh while ≥ 1 voting node is loaded. Cadence comes from network. +- `ui/components/top_panel.rs`: render the attention chip(s) next to the network + chip (VOTE-FR-072), gated by `FeatureGate::Masternodes` and voting-node + presence. + +### Votes screen +- Cards: two-column layout with weighted tally (read-only), influence line, + node line, checkbox, and choice pills with key hints. Sorted by time left. + Groups per VOTE-FR-071. +- Node-set chip and popover (VOTE-FR-075). The preference persists per network + in local KV (new key in the vote-state context or settings). +- Keyboard handling scoped to list focus, plus the bulk bar (VOTE-FR-082). +- Tray copy (VOTE-FR-086). +- Needs-attention row (VOTE-FR-084). + +### Confirm and drawer +- Replace the review sheet with the aggregate confirm popover (VOTE-FR-080). The + existing per-node matrix becomes the `Adjust nodes` table. The timing control + gains `When voting is about to end`. +- Replace the full-window progress overlay for vote submissions with the + progress drawer (VOTE-FR-083), driven by coordinator snapshots. It persists + across screens and is rendered at AppState level like other global overlays. +- Final banner per VOTE-FR-061. + +### Changes left and node status +- Journal query: count confirmed votes per (proTxHash, poll). Combine it with + proved state to get `ChangesLeft` (VOTE-FR-078). Exclude nodes with + `Known(0)` during draft expansion. +- Masternode-list membership per node (VOTE-FR-079): read from the masternode + list already available via SPV/DAPI if present. Otherwise add a lightweight + `in_list` refresh on the existing masternode refresh path (MN-011). **Needs + investigation**; flag as a backend gap if no source exists. + +### Node detail +- Replace the `DPNS Voting` button with `Vote with this node`, which sets + NodeSet::Custom({node}) for the session, not as a saved default. +- Add the `This node's votes` table from the vote-state store and the journal + (VOTE-FR-076). + +### Scheduled and History +- Scheduled view: group by (poll, choice, scheduled time) with an expandable node + list (VOTE-FR-088). Show the relative label when the schedule was created + relative (store a `relative_preset: Option` alongside the absolute + time for display only). +- History: show contest outcomes and a per-contest Platform Explorer browser link for Mainnet and Testnet. + +### Durations +Consume `model/dpns.rs` contest-duration and urgency helpers (owned by Stream U, +see below) for countdowns, presets and the chip. + +## Shared backend and file ownership + +| File / op | Owner | Consumer | Note | +|---|---|---|---| +| `model/dpns.rs`: contested-name rule (delegating to the contract's `field_matches`), contest/join durations per network, urgency window | **U** | V | Lands first. Replaces both `is_contested_name` copies. | +| `model/fee_estimation.rs`: contest fee from `sdk.version()` / `prefunded_voting_balance_for_document` | **U** | — | Repo rule: fee math only here | +| `model/dpns_voting/` (journal, composer, operator helpers, progress) | **V** | — | | +| `context/contested_names_db.rs`: pending usernames → `Vec`, outcomes | **U** | — | V doesn't edit it; V reads contests via the existing API | +| `context/dpns_vote_state.rs`, `dpns_vote_operations/`, `dpns_vote_attention.rs` | **V** | — | | +| `backend_task/contested_names/*` | **V** | U reads `get_contested_dpns_vote_state` via its own new op | U adds no code here | +| New `backend_task/identity/dpns_usernames.rs` (`CheckUsernameAvailability`, `RefreshMyUsernameRequests`) | **U** | — | | +| `backend_task/mod.rs` (`BackendTaskSuccessResult` variants) | both | — | Each stream adds its variants in its own contiguous block (V first, U after). Rebase conflict expected and trivial. | +| `app.rs` timers | **V** only | — | U triggers its refresh from the hub screen, not app.rs | +| `ui/mod.rs` routing, `left_panel.rs`, `top_panel.rs`, `tools_subscreen_chooser_panel.rs`, `ui/dpns/*`, `ui/masternodes/*` | **V** | — | | +| `ui/identity/*` (register screen, settings/profile, home, hero card, checklist, request card) | **U** | — | U removes the "View all usernames" link; V removes the Owned sub-screen | +| `docs/user-stories.md` | both | — | Disjoint stories (V: DPN-003…007, 011, MN-003/011; U: DPN-001/002/008/010, new DPN-012+) | + +## Implementation workstreams (one PR, #901) + +The A–D workstreams from #901 are done. New: + +### Workstream E — Stream V convenience (this revision) +- E1 Navigation, routing, Tools removal, owned-names exit. Tests VOTE-TC-080…084. +- E2 Attention summary, background refresh, chip, badge. Tests VOTE-TC-085…087, + 104. +- E3 Cards, sorting, groups, node set, influence, changes left, list + exclusion. Tests VOTE-TC-002, 007, 088…097. +- E4 Aggregate confirm, relative scheduling, Adjust nodes. Tests VOTE-TC-006, + 010–025, 067–069. +- E5 Progress drawer, needs-attention row, voting-ended failure. Tests + VOTE-TC-041, 056, 100–103. +- E6 Keyboard and bulk bar. Tests VOTE-TC-098, 099. +- E7 Node detail table and `Vote with this node`. Tests VOTE-TC-091, 094. + +Stream U runs in parallel (plan: `../2026-10-01-usernames-redesign/01-requirements.md` +§Implementation plan). It must merge `model/dpns.rs` before E2/E4 consume the +duration helpers. Until then, V may stub them behind the same function +signatures. + +## Verification +- Unit: NodeSet resolution, ChangesLeft, influence, relative schedule, attention + summary, draft expansion with exclusions. +- Backend (fake SDK): voting-ended failure, out-of-changes skip, per-node query + count. +- Kittest: segments and routing, chip, keyboard, bulk, confirm, drawer + non-blocking, node detail. +- Testnet backend E2E (manual, `#[ignore]`): 2 nodes × 2 contests with a relative + schedule in a 90-minute contest. +- `cargo fmt --all`; clippy scoped per AGENTS.md. + +## Documentation updates +- `docs/user-stories.md`: revise DPN-003…007, DPN-011, MN-003, MN-011; add + DPN-013 (attention chip), DPN-014 (node set + weight + changes left), DPN-015 + (non-blocking progress). +- Remove references to "DPNS ▸ Active contests" in docs and in-app copy. diff --git a/docs/ai-design/2026-10-01-usernames-redesign/01-requirements.md b/docs/ai-design/2026-10-01-usernames-redesign/01-requirements.md new file mode 100644 index 000000000..e52963037 --- /dev/null +++ b/docs/ai-design/2026-10-01-usernames-redesign/01-requirements.md @@ -0,0 +1,242 @@ +# Usernames Redesign — Requirements (Stream U) + +Scope: identity-side usernames. Voting is Stream V in +`../2026-07-16-dpns-voting-experience/` (shared ownership table in its +`04-development-plan.md`). Platform rules: `platform-facts.md` (PF §n). Frames: +`wireframes.html` U1–U7. UX detail: `02-ux-spec.md`. + +## Principles +- Usernames belong to the identity. Show and manage them in the Identity hub + only, never on a voting screen. +- The Everyday User (Alex) is the validation floor. Identity-side copy never + uses "DPNS", "contest", "contested" or "alias". +- Never offer an action Platform rejects (delete), and never imply a refund. + +## Problems fixed (code refs at time of writing) +| # | Problem | Ref | +|---|---|---| +| P1 | Own names live in Tools ▸ DPNS ▸ My usernames | `settings.rs` `usernames_screen_action` | +| P3 | No availability check; the SDK helper reports contested and locked names as available | `register_dpns_name_screen.rs:516-557`; PF §5a | +| P4 | Hard-coded `0.2006` fee, red "contested" copy, no consent | `register_dpns_name_screen.rs:531-540` | +| P5 | Only one pending request, and only when the identity owns no name; status depends on a cache refreshed by voting screens | `contested_names_db.rs:261-272` | +| P6/P7 | "Set Alias" writes a username into the device-only name; "alias" has three meanings | `dpns_contested_names_screen.rs:955-984`, `settings.rs:554` | +| P8 | Disabled stubs "Add an alias" / "Make primary" / "Remove" | `settings.rs:573-595` | +| P9/P10 | Self-contradicting rules panel; identity picker when opened from an identity; dead-end red errors | `register_dpns_name_screen.rs:435-505, 638-657` | +| P12/P13 | Success copy points to a label that may not update; contest rules misstated | `register_dpns_name_screen.rs:333, 651-657` | + +## Functional requirements + +### Usernames card (Profile tab) — U1, U1b +- **USR-FR-001** — Profile ▸ `Usernames` lists for the selected identity, in + this order: + - main name, then other active names; + - pending requests: `Open for other requests` during the join window, + `Waiting for vote` after it, and `Awaiting result` once the estimated end + has passed but the network has not confirmed an outcome; + - finished outcomes from the last 30 days: `Went to someone else`, + `Locked for good`, `No one got it`. + - **AC:** + - Given an identity owning `@a` with a pending request `@b`, both rows + render. + - Given 2 pending requests, both render. +- **USR-FR-002** — Active row menu: `Copy username` · `Show QR code` · `Show as + main` (hidden on the main row). `Main` badge only when the identity has > 1 + active name. + - **AC:** after `Show as main` on `@b`, the header subtitle, pills and switcher + show `@b`. No network call. The preference persists per identity and + network. +- **USR-FR-003** — Pending rows show `View status` → U3. Outcome rows show + `Dismiss`; lost rows also show `Choose another username` → U4. +- **USR-FR-004** — Footer button `Get another username` → U4, with the note + `Each username is a separate payment from this identity's balance.` +- **USR-FR-005** — Empty state: `This identity has no username yet. A username + lets people pay you as @name instead of a long address.` [Get a username]. + View-only identity (no auth key): button disabled, tooltip `Add a key to this + identity to register usernames.` + `Add a key` link. +- **USR-FR-006** — Remove the "Aliases" block, the disabled `Make primary`, + `Remove` and `Add an alias` controls, and the `View all usernames` jump. Never + offer delete (PF §2). Transfer/sale is deferred; reserve no visible control. + +### Header, Home, banners — U2 +- **USR-FR-010** — Header subtitle: the main name, or, when the identity has no + active name, `@{name}` with the request's current status (`Open for other + requests`, `Waiting for vote` or `Awaiting result`). +- **USR-FR-011** — Home card for each pending request: `@{name} is waiting for a + community vote. It ends around {date}.` plus one of `You're leading right + now.` / `No one else has asked so far.` / `Another request is leading.` + [View status]. +- **USR-FR-012** — One-time outcome banners, each shown once per (identity, + name, outcome) via a local "seen" flag: + - won: Success `You're @{name}. People can now find and pay you by this name.` + - lost: Info `@{name} went to someone else. You can choose a different + username.` [Choose another username] + - locked: Info `No one can register @{name} anymore. The community vote locked + it.` + - no winner: Info `The vote for @{name} ended without a winner. You can choose + a different username.` [Choose another username] +- **USR-FR-013** — Onboarding checklist and hero card keep DPN-010 behaviour + (pending counts as done), sourced from USR-FR-020. + +### Own-request status — U3 +- **USR-FR-020** — New backend op `RefreshMyUsernameRequests` (all loaded + identities): + - first re-reads each saved pending request with + `get_contested_dpns_vote_state`, then discovers further requests with + `get_contested_non_resolved_usernames`, keeping the contests the identity + is a contender in; + - returns per identity a `Vec`; + - `AwaitingOutcome` is a local reading of the clock only: the estimated end + has passed and no outcome is confirmed. Elapsed time never awards or + rejects a name; + - persists it and replaces the single-`Option` pending API; + - a won name is listed as owned while it waits to be read back into the + identity's names. Once those names listed it, the request records that; + if the name is missing afterwards it has left the identity and is not + listed or read back again. + - **AC:** an identity owning a name still reports its pending requests. A + finished contest yields Won/Lost/Locked/NoWinner. +- **USR-FR-021** — Refresh cadence: on hub arrival when the last refresh is + > 5 min old; while ≥ 1 request is pending, every 15 min (testnet/devnet: + 2 min); and on the `Refresh status` button. It is triggered from the hub + screen (no `app.rs` timer). +- **USR-FR-022** — The Request status page (pushed; breadcrumb `Identities › + {identity} › @{name}`) shows: + - a timeline: Requested · Open for other requests until {join_end} · + Community vote until {end} · Result; + - a read-only weighted tally (You · Other request ({short_id}) · Lock, so no + one gets it · Abstain) with the words `Leading` / `Tied`, and the note + `Evonodes count as 4 votes. Votes can change until the vote ends. Last + updated {time}.`; + - `What happens next` with exactly these rules (PF §3): + - lone/leading request wins at the end; + - a tie goes to the most recent request; + - lock > top request → nobody can ever register it; + - the fee isn't returned in any case. + - Secondary [Get a username without a vote]. Power role + a loaded node with a + voting key: link `Your nodes can vote on this name` → Masternodes ▸ Votes + filtered to the name (Stream V route; U only emits the navigation action). + +### Registration flow — U4–U7 +- **USR-FR-030** — `Get another username` is opened from an identity. There is + no identity picker; the signing key is auto-picked (Power role: `Advanced` + disclosure with the key selector). The first username for a new identity + keeps the 2026-09-22 create flow. +- **USR-FR-031** — New backend op `CheckUsernameAvailability(label)` → typed + `Available | NeedsVote | Joinable { contenders, join_end } | JoinClosed | + Taken | Locked | AlreadyRequested` (the asking identity is already in the + running vote; Platform rejects a second request). It combines the + awarded-domain lookup with + `get_contested_dpns_vote_state` and never relies on `is_dpns_name_available` + alone (PF §5a). The UI debounces 400 ms. Network failure → `CantCheck` UI + state (retry). + - **AC:** a locked name → `Locked`; an active contest within the join window + → `Joinable`; after it → `JoinClosed`. +- **USR-FR-032** — Availability copy, one row at a time: + - `Checking if @{name} is available…` + - `@{name} is available.` + - `@{name} is available, but it needs a community vote.` + - `{count} other people already asked for @{name}. You can join the vote until + {time}.` (plural pair) + - `@{name} is already taken. Try another name.` + - `@{name} can't be registered. A community vote locked this name for good.` + - `Others can no longer join the vote for @{name}. Try another name.` + - `You already asked for @{name}. Its status is on your identity's Usernames + list.` + - `Availability can't be checked right now. Check your internet connection and + try again.` [Try again] + - Continue is enabled only for Available / NeedsVote / Joinable. +- **USR-FR-033** — Suggestions `Try one without a vote:` for NeedsVote, Joinable + and Taken: three labels that fail the contested rule (e.g. appending a digit + 2–9). Generated by `model/dpns.rs`. +- **USR-FR-034** — `Username rules` disclosure (collapsed), one correct list: + - 3–63 characters; + - letters, numbers and hyphens, with no hyphen at the start or end; + - capital letters are treated as lowercase; + - names under 20 characters that use only letters, hyphens, 0 and 1 need a + community vote, and adding a digit 2–9 avoids it. +- **USR-FR-035** — The consent modal for NeedsVote/Joinable shows: + - `Anyone can also ask for @{name} during the first {join_duration}. After + that, only Dash masternode votes decide.`; + - `The vote ends after {duration}, even if no one else asks. You'll see the + result on your identity's page.`; + - `The community vote fee is {contest_fee} DASH. It isn't returned, whether + you get the name or not.`; + - `If more votes go to locking the name, no one can register it, including + you.`; + - `Until the vote ends, people can't find you by this name.`; + - buttons [Choose another name] [I understand, continue]. + - Durations come from `model/dpns.rs`. Never use the word "deposit". +- **USR-FR-036** — The confirm step shows: + - `Username` (+ `Community vote` badge); + - `Registration fee` `about {fee} DASH`; + - `Community vote fee (not returned)` `{contest_fee} DASH`, read via + `model/fee_estimation.rs` from `sdk.version()`: 0.2 DASH before protocol + 14, 0.1 DASH from 14 (PF §1); + - `Total`, and `Paid from {identity}'s balance · Available {balance} DASH`; + - primary `Pay {total} DASH and get @{name}` / `… and request @{name}`. + - Low balance: `This identity has {balance} DASH. Add at least {missing} DASH + to continue.` [Top up], which returns here with the name kept. + - Not synced: Pay disabled, tooltip `Available after sync finishes.` +- **USR-FR-037** — On Pay, re-run the availability check. If it changed to + Taken/Locked/JoinClosed/AlreadyRequested, return to U4 with that row; nothing + is spent. +- **USR-FR-038** — Progress: blocking overlay `Registering @{name}.` `Keep Dash + Evo Tool open until this finishes.` Results: + - registered: `You're @{name}`; + - request: `Your request for @{name} is in` + `If no one else asks and no one + votes to lock it, @{name} becomes yours then.` [View request status] + [Go to my identity]; + - failure: errors per AGENTS.md (no jargon, an action, details via + `with_details`); + - unconfirmed: a failed send of the name request does not prove the fee was + not spent, because the same signed request is re-sent and only the last + attempt is reported. The app therefore first re-reads the vote (or the + owned names) after any failed send, a refusal included, and continues as a + success if the request is there. A refusal keeps its own error only when + that re-read succeeds and does not show the request; a re-read that fails + proves nothing, so a refusal followed by one is unconfirmed too. Otherwise + it reports `The app could + not confirm whether your request for this username went through. Do not + pay again yet. Wait a few minutes, then check the Usernames list on your + identity. If the name is not there, try again.` and returns to U4 with a + fresh availability check, never to the Pay step. + +### Model/shared (Stream U owns; Stream V consumes durations) +- **USR-FR-040** — `model/dpns.rs`: `is_contested_label(label)` delegating to + the contract's contested index `field_matches` (or the equivalent pure regex + derived from it). Delete `register_dpns_name_screen.rs::is_contested_name` and + any other copy. +- **USR-FR-041** — `model/dpns.rs`: `contest_durations(network/platform_version) + -> { total, join }` (mainnet 14 d / 7 d; testnet/devnet 90 / 45 min, PF §3) + and `urgency_window(network)` (24 h / 30 min). +- **USR-FR-042** — `model/fee_estimation.rs`: `contest_fee_credits(platform_version)`; + remove the `0.2006` literal. +- **USR-FR-043** — Local settings: main username per identity; outcome-seen + flags (both network-scoped KV). + +## Non-functional +- **USR-NFR-001** — Complete i18n units, plural pairs, durations formatted from + values. +- **USR-NFR-002** — Validation placement per AGENTS.md: format and contested + rules live in `model/`; availability is enforced in the backend op; the UI + only renders. +- **USR-NFR-003** — Status is shown as text plus icon. Read-only tally bars are + not focusable. +- **USR-NFR-004** — No UI path offers deletion or calls the fee a deposit. + +## Implementation plan (Stream U) +1. `model/` helpers (USR-FR-040–042) — merge first; Stream V depends on 041. +2. Backend ops `CheckUsernameAvailability`, `RefreshMyUsernameRequests` in new + `backend_task/identity/dpns_usernames.rs`; context API returning + `Vec` (`contested_names_db.rs`). +3. Registration flow rework of `register_dpns_name_screen.rs` (U4–U7). +4. Usernames card, request status page, home card, banners (`ui/identity/*`). +5. Remove alias stubs and the "View all usernames" jump. Update user stories + DPN-001/002/008/010, add DPN-012/016/017. + +## Out of scope +Transfer/sale of names (PF §2, deferred); deleting names (rejected on-chain); +unlocking locked names (not implemented in Platform). diff --git a/docs/ai-design/2026-10-01-usernames-redesign/02-ux-spec.md b/docs/ai-design/2026-10-01-usernames-redesign/02-ux-spec.md new file mode 100644 index 000000000..019f36b60 --- /dev/null +++ b/docs/ai-design/2026-10-01-usernames-redesign/02-ux-spec.md @@ -0,0 +1,78 @@ +# Usernames and Name Votes — UX Specification (developer edition) + +Two streams with separate homes: +- **Stream U**: identity usernames, in the Identities hub. Requirements and copy + are in `01-requirements.md`. +- **Stream V**: voting, in Masternodes ▸ Votes. Requirements are in + `../2026-07-16-dpns-voting-experience/`. + +Wireframes: `wireframes.html` (U1–U7, V0–V6). Platform rules: +`platform-facts.md`. + +## Personas and jobs +| Persona | Jobs | Home | +|---|---|---| +| Alex (Everyday) | get a payable name; see/share it; understand vote, cost (not refunded), risk; follow the request without a voting tool; recover after losing | Identities hub | +| Priya, owner (Power) | names per identity; pick the main name; add a name paid from identity balance | Identities hub | +| Priya, operator (Power, 1–40 nodes, shared voting keys) | know from anywhere that a vote is needed; one decision → all chosen nodes; see weight and changes left; vote now or before the deadline; trust no duplicates; per-node results | Masternodes ▸ Votes | +| Jordan (Developer, testnet) | fast test names (digit 2–9 avoids votes); 90-minute contests | both | + +## IA +```text +Top bar: breadcrumb · [N names need your vote] (V) · network +Identities hub (U) + header subtitle: @main | "@name · Waiting for vote" + Home: request card · one-time outcome banners · checklist + Profile ▸ Usernames: rows (••• Copy · QR · Show as main) · pending → Request status + [Get another username] → Choose → (Consent) → Confirm & pay → Result +Masternodes (V, Power gate): [Votes | Nodes]; Votes = To decide · Voted · Scheduled · History +Tools: DPNS removed. +``` + +## Decisions (former open questions) +| Topic | Decision | Why | +|---|---|---| +| Where voting lives | Masternodes ▸ Votes (first segment), plus the top-bar chip | Operator convenience; keys and weights live there | +| Contest browser for non-operators | None; own contests via Request status | No listed job; less surface | +| Fee | Live from `sdk.version()` (0.2 DASH before protocol 14, 0.1 DASH from 14); "isn't returned"; never "deposit" | PF §1 | +| Delete / transfer | Delete never offered; transfer/sale deferred to phase 2 | PF §2; irreversible flow with no backend op | +| Lost-request retention | 30 days in Profile | Noticeable after a break; Platform keeps the poll record | +| Refresh cadence | U: hub arrival (> 5 min) + 15 min while pending (testnet 2 min). V: 30 min (testnet 3 min) while voting nodes are loaded | Fresh enough for 14-day and 90-minute contests | + +## Vocabulary +| Identity side (U) | Operator side (V) | Never in UI copy | +|---|---|---| +| username, `@name`, Waiting for vote, Open for other requests, community vote, community vote fee (not returned), Show as main, Name on this device | name contest, decision, node set, votes (weighted), changes left, Vote with this node | DPNS, contested, alias, deposit, state transition, nonce | + +## Interaction states (U) +- Availability row: exactly one state (USR-FR-032), 400 ms debounce. Format + checks update per keystroke. +- Disabled controls always carry a tooltip reason. View-only identity → `Add a + key`. Not synced → `Available after sync finishes.` +- Blocking progress overlay only during registration. Request-status refresh shows inline + `Last updated {time}`, no overlay. +- Outcome banners: once each, dismissible. Profile rows carry the state for + 30 days. + +## Interaction states (V) +See `../2026-07-16-dpns-voting-experience/02-ux-spec.md`. In short: +- the node-set chip is remembered; +- cards are sorted by time left; +- the confirm is an aggregate; +- progress is a non-blocking drawer; +- keyboard J/K, 1–9, L, A, Space, Enter. + +## Accessibility and responsive +- Status is text plus icon. Tallies are non-focusable labels. Single-key + shortcuts act only in list focus (WCAG 2.1.4). Modals trap and return focus. +- Narrow layout: Profile columns stack, with the Usernames card first when it + has a pending row. Contest card tally stacks above choices. The drawer becomes + a bottom sheet. + +## Backend gaps (summary) +- U: `CheckUsernameAvailability`, `RefreshMyUsernameRequests`, `Vec` pending + API, contest fee and contested rule in `model/`, contest durations helper, + local main-name and outcome-seen settings. +- V: attention summary and background refresh, node-set preference, + changes-left journal count (upstream ask: vote count in proved votes), + masternode-list membership per node. diff --git a/docs/ai-design/2026-10-01-usernames-redesign/03-test-case-spec.md b/docs/ai-design/2026-10-01-usernames-redesign/03-test-case-spec.md new file mode 100644 index 000000000..f232c2332 --- /dev/null +++ b/docs/ai-design/2026-10-01-usernames-redesign/03-test-case-spec.md @@ -0,0 +1,61 @@ +# Usernames Redesign — Test Case Specification + +Level: U = unit, K = kittest (`tests/kittest/` or inline harness), B = backend test with fake SDK seam. +Stream V test cases live in `../2026-07-16-dpns-voting-experience/03-test-case-spec.md` (VOTE-TC-*). This file covers Stream U and the shared `model/` helpers. + +## Shared model helpers (Stream U owns) + +| ID | Description | Steps | Expected | Req | Lvl | +|---|---|---|---|---|---| +| USR-TC-001 | Contested rule | `is_contested_label` on `alice`, `al1ce`, `alice2`, `a`·20, `b0b-01`, `Alice` | true, true, false, false, true, true (homograph-normalized) | FR-040 | U | +| USR-TC-002 | Single source | grep for `is_contested_name` | No copy outside `model/dpns.rs` | FR-040 | U | +| USR-TC-003 | Durations | `contest_durations` mainnet / testnet / devnet | 14 d + 7 d; 90 min + 45 min; 90 min + 45 min | FR-041 | U | +| USR-TC-004 | Urgency window | `urgency_window` mainnet / testnet | 24 h / 30 min | FR-041 | U | +| USR-TC-005 | Contest fee | `contest_fee_credits` for PV13, PV14 | 20,000,000,000 / 10,000,000,000 credits | FR-042 | U | +| USR-TC-006 | No literal fee | grep `0.2006` | No match | FR-042 | U | +| USR-TC-007 | Suggestions avoid vote | `suggest_uncontested("alice")` | 3 labels, each valid and `is_contested_label == false` | FR-033 | U | + +## Backend ops + +| ID | Description | Preconditions | Expected | Req | Lvl | +|---|---|---|---|---|---| +| USR-TC-010 | Available | No domain, no contest; label non-contested | `Available` | FR-031 | B | +| USR-TC-011 | Needs vote | No domain, no contest; contested label | `NeedsVote` | FR-031 | B | +| USR-TC-012 | Joinable | Active contest, now < join_end, 2 contenders | `Joinable { contenders: 2, join_end }` | FR-031 | B | +| USR-TC-013 | Join closed | Active contest, now ≥ join_end | `JoinClosed` | FR-031 | B | +| USR-TC-014 | Taken | Awarded domain exists | `Taken` | FR-031 | B | +| USR-TC-015 | Locked | Vote state winner = Locked; `is_dpns_name_available` returns true | `Locked` (SDK helper not trusted) | FR-031 | B | +| USR-TC-016 | Multiple requests | Identity owns `@a`, contender in `b`, `c` | `RefreshMyUsernameRequests` returns 2 requests for it | FR-020 | B | +| USR-TC-017 | Outcomes | Finished contests: won, lost, locked, no winner | Phases Won / Lost / Locked / NoWinner with dates | FR-020 | B | +| USR-TC-018 | Re-check on pay | Check said NeedsVote; at pay time Taken, Locked, JoinClosed or AlreadyRequested | Nothing is broadcast; U4 shows the matching row | FR-037 | B+K | +| USR-TC-041 | Already requested | Running vote lists the asking identity | `AlreadyRequested`; Continue disabled | FR-031, FR-032 | U+B | +| USR-TC-042 | Awaiting result | Saved pending request, estimated end passed, no confirmed outcome | Phase `AwaitingOutcome`; never Won/Lost by the clock alone | FR-020 | U | +| USR-TC-043 | Unconfirmed request | Name request fails without a refusal; request not readable / readable | `UsernameRegistrationUnconfirmed`, Pay step not restored / registration continues as success | FR-038 | B+K | +| USR-TC-044 | Refusal after an applied send | Name request is refused; the vote shows / does not show this identity's request / cannot be read | Registration continues as success / the refusal keeps its own error / `UsernameRegistrationUnconfirmed` | FR-038 | B | +| USR-TC-045 | Won name leaves the identity | Saved win recorded in the identity's names; a later refresh no longer lists the name | Not listed as an owned username; no further read-back; request ages out with other outcomes | FR-020, FR-001 | U+B | + +## UI (kittest) + +| ID | Description | Preconditions | Steps | Expected | Req | +|---|---|---|---|---|---| +| USR-TC-020 | Card lists all states | Identity: 2 active, 1 joinable, 1 voting, 1 lost, 1 locked | Open Profile | Six rows in order; `Main` badge on first; plain status words | FR-001 | +| USR-TC-021 | Show as main | 2 active names | Row menu → Show as main on `@b` | Header subtitle `@b`; persists after restart; no backend task | FR-002, FR-043 | +| USR-TC-022 | No stubs | Any identity | Open Profile | No `Aliases`, `Make primary`, `Remove`, `Add an alias`, `View all usernames` | FR-006 | +| USR-TC-023 | Empty state | No names | Open Profile | Empty copy + `Get a username` enabled | FR-005 | +| USR-TC-024 | View-only | Identity without auth key | Open Profile | Button disabled with tooltip; `Add a key` link | FR-005 | +| USR-TC-025 | Header pending | No active name, 1 request | Open hub | Subtitle `@{name}` with the request's status: `Open for other requests` in the join window, `Waiting for vote` after it | FR-010 | +| USR-TC-026 | Home card copy | Leading / no rival / trailing | Open Home | Matching second sentence | FR-011 | +| USR-TC-027 | Banner once | Request becomes Won | Open hub twice | Success banner first time only | FR-012 | +| USR-TC-028 | Refresh cadence | Last refresh 2 min ago | Arrive at hub | No refresh dispatched; at 6 min, dispatched | FR-021 | +| USR-TC-029 | Request status rules | Pending request | Open status page | Timeline phases; tally with `Leading`/`Tied`; 4 rule sentences | FR-022 | +| USR-TC-030 | Voter link gating | Power + voting node / Everyday | Open status page | Link visible / absent | FR-022 | +| USR-TC-031 | No identity picker | Open Get another username from identity X | Render | Title names X; no identity selector | FR-030 | +| USR-TC-032 | Availability rows | Each typed result incl. network error | Type a label, wait 400 ms | Exactly one matching row; Continue enabled only for Available/NeedsVote/Joinable | FR-032 | +| USR-TC-033 | Plural copy | Joinable with 1 and 3 contenders | Render | Singular and plural variants | FR-032, NFR-001 | +| USR-TC-034 | Consent copy | NeedsVote, mainnet and testnet | Continue | Modal with network durations, fee from model, "isn't returned"; no "deposit" | FR-035, NFR-004 | +| USR-TC-035 | Confirm fee rows | Contested label, PV14 context | Open confirm | `Community vote fee (not returned)` = 0.1 DASH; total correct | FR-036 | +| USR-TC-036 | Low balance | Balance < total | Open confirm | Warning with missing amount; Pay disabled; Top up returns with name kept | FR-036 | +| USR-TC-037 | Not synced | SPV syncing | Open confirm | Pay disabled with `Available after sync finishes.` | FR-036 | +| USR-TC-038 | Result variants | Non-contested / contested success | Complete | `You're @name` / `Your request for @name is in` with lone-request sentence | FR-038 | +| USR-TC-039 | Rules disclosure | Open U4 | Expand rules | Four correct rules; no "case-sensitive" | FR-034 | +| USR-TC-040 | Owned-names route gone | Persisted `RootScreenDPNSOwnedNames` | Start app | Identity hub (route owned by Stream V; U asserts no owned-names UI remains in `ui/identity`) | FR-006 | diff --git a/docs/ai-design/2026-10-01-usernames-redesign/platform-facts.md b/docs/ai-design/2026-10-01-usernames-redesign/platform-facts.md new file mode 100644 index 000000000..27c04f6ae --- /dev/null +++ b/docs/ai-design/2026-10-01-usernames-redesign/platform-facts.md @@ -0,0 +1,116 @@ +# DPNS usernames & contested-resource voting — platform facts + +Source: dashpay/platform @ `9f7ed16935bd540e4c2a542688800d2953f9f67a` (DET pin). Paths are relative to +`packages/` in that repository at that commit. +`LATEST_VERSION = PROTOCOL_VERSION_14` (`rs-platform-version/src/version/mod.rs:36`). +Network status (web, unverified against chain): mainnet + testnet run **PV13** (Platform 4.1); PV14 (4.2) is the next upgrade. +Credits: 1 DASH = 100,000,000,000 credits. + +Abbreviations: PV = protocol version; "testing" = any network != Mainnet (testnet, devnet, regtest). + +## 1. Fees + +| Fact | Value | PV-dependent | Citation | +|---|---|---|---| +| Contested registration contribution ("vote resolution fund") | **0.2 DASH** (20,000,000,000 cr) PV1–PV13; **0.1 DASH** (10,000,000,000 cr) PV14+ | Yes (`fee_version`) | `rs-platform-version/src/version/fee/vote_resolution_fund_fees/v1.rs:4`, `.../v2.rs:4-8`; `fee/v3.rs:6-10`; `version/v14.rs:537` (FEE_VERSION3), `v13.rs:91` (FEE_VERSION2) | +| Same on mainnet vs testnet | identical | — | (no network branch in fee version) | +| How the amount gets into the tx | dpp auto-sets `prefunded_voting_balance = (index_name, amount)` from the **client SDK's** `PlatformVersion` when the document matches the contested index | Yes | `rs-dpp/src/data_contract/document_type/methods/versioned_methods.rs:649-681`; `rs-dpp/.../document_create_transition/v0/from_document.rs:34` | +| Exact-match rule | Platform rejects if paid amount != active PV amount (`DocumentContestNotPaidForError`); also rejects a prefund on a non-contested doc (`DocumentContestNotRequiredError`) and a prefund naming a different index | Yes | `rs-drive-abci/.../document_create_transition_action/advanced_structure_v1/mod.rs:59-124` | +| How DET reads it | `sdk.version().fee_version.vote_resolution_fund_fees.contested_document_vote_resolution_fund_required_amount` (SDK auto-detects network PV unless pinned with `with_version`) | — | `rs-platform-version/src/version/fee/vote_resolution_fund_fees/mod.rs:5-13`; `rs-sdk/src/sdk.rs:397,639-645,1044` | +| Who pays / when | The registering identity, at execution of the `domain` create batch (same tx as the document). Moved from identity balance into a per-contest prefunded specialized balance | — | `rs-drive/src/state_transition_action/action_convert_to_operations/batch/document/document_create_transition.rs:98-113` | +| Every joiner pays too | Yes — each contender's create carries its own prefund into the same contest balance | — | same as above | +| Refund on win / lose / lock | **Never refunded.** Each vote spends 0.0001 DASH from the fund; at contest end the remainder is emptied into epoch processing credits (masternode reward pool). Applies equally to winner, losers, lock | — | `rs-drive/.../masternode_vote_transition.rs:48-56`; `rs-drive-abci/.../clean_up_after_contested_resources_vote_polls_end/v1/mod.rs:42-75` | +| "Unlock" amount | 4 DASH constant exists (`contested_document_vote_resolution_unlock_fund_required_amount`) but is only quoted in the `DocumentContestCurrentlyLockedError`; **no unlock path is implemented** | — | `vote_resolution_fund_fees/v1.rs:5`; `rs-drive-abci/.../document_create_transition_action/state_v1/mod.rs:239-247` | +| Non-contested cost | No fixed fee. Normal document fees for 2 docs (preorder + domain): storage 27,000 cr/byte + processing; min 100,000 cr per batch sub-transition. Order of magnitude ~0.0005–0.001 DASH (DET's "0.2006" = 0.2 + ~0.0006 estimate) | Fee tables versioned, unchanged PV14 | `rs-platform-version/src/version/fee/storage/v1.rs:6-9`; `fee/state_transition_min_fees/v1.rs:8` | +| Registration is 2 txs | preorder (salted double-sha256 of salt‖`label.dash`) then domain; domain create verifies the preorder exists | — | `rs-sdk/src/platform/dpns_usernames/mod.rs:148-311`; `rs-drive-abci/.../triggers/dpns/v1/mod.rs:329-396` | + +## 2. Document mutability + +| Flag / capability | Value | PV-dependent | Citation | +|---|---|---|---| +| `documentsMutable` | false (Replace impossible) | — | `dpns-contract/schema/v1/dpns-contract-documents.json:3` | +| `canBeDeleted` | true in schema, **but Delete is rejected by a DPNS data trigger** on all PVs | — | schema `:4`; `rs-drive-abci/.../data_triggers/bindings/list/v2/mod.rs:39-51` | +| `transferable: 1`, `tradeMode: 1` (direct purchase) | Declared since genesis; Transfer/Purchase/UpdatePrice were blocked by reject triggers until **PV13**, allowed PV13+ | Yes (bindings v0 → v1/v2) | schema `:5-6`; `bindings/list/v0/mod.rs:49-61`; `bindings/list/v1/mod.rs:16-26` | +| History | DPNS contract v2 (PV13+) adds `keepsTransferHistory/PurchaseHistory/PricingHistory` (via document-history contract) | Yes | `dpns-contract/schema/v2/dpns-contract-documents.json:7-9`; `system_data_contract_versions/v2.rs:5-11`; upgrade at `rs-drive-abci/.../perform_events_on_first_block_of_protocol_change/v0/mod.rs:682` | +| `records.identity` on transfer/purchase | Drive rewrites it to the new owner | PV13+ | `rs-drive/.../batch/document/mod.rs:18-26`; `document_transfer_transition.rs:102,138`; `document_purchase_transition.rs:114,155` | +| `records.identity` at create | Schema requires `records` with only `identity` (32-byte id). The trigger's owner-equality checks target legacy keys `dashUniqueIdentityId`/`dashAliasIdentityId`, which the schema forbids → **`records.identity` is not enforced to equal `$ownerId`** | — | schema `:83-99`; `triggers/dpns/v1/mod.rs:150-183`; `dpns-contract/src/v1/mod.rs:17-18` | +| Primary/"main" name | **No on-chain concept.** Schema has no such field; purely client-side | — | schema `:41-115` | +| Owned-by-identity index | `identityId` index on `records.identity` (`nullSearchable: false`) | — | schema `:31-39` | +| Subdomains | `subdomainRules.allowSubdomains` required; SDK sets false | — | schema `:100-114`; `rs-sdk/.../dpns_usernames/mod.rs:232-238` | + +## 3. Contest lifecycle + +| Fact | Value | PV-dependent | Citation | +|---|---|---|---| +| When a contest exists | First create of a name matching the contested index opens it **immediately with one contender**; no 2-contender minimum | — | `rs-drive/src/drive/document/insert_contested/add_contested_document_for_contract_operations/v0/mod.rs:54-104` | +| Contested rule | `normalizedLabel` matches `^[a-zA-Z01-]{3,19}$` (after homograph normalization: only letters, `0`, `1`, `-`; length 3–19) | — | schema `:20-29` | +| Contest duration (end = start block time + duration) | Mainnet **14 days** (1,209,600,000 ms). Testing **90 min** (5,400,000 ms) PV3+; 14 days PV1–2 | Yes (`voting_versions`) | `dpp_voting_versions/v2.rs:3-7`, `v1.rs:3-7`; insert code `:54-70` | +| Join window (new contenders) | Mainnet **7 days** (604,800,000 ms). Testing **45 min** (2,700,000 ms) PV2+; 7 days PV1. After it: `DocumentContestNotJoinableError` | Yes | `dpp_validation_versions/v1.rs:31-32`, `v2.rs:31-32`, `v3.rs:32-33`; `state_v1/mod.rs:249-260` | +| When voting is possible | Whole time the poll status is `Started` (includes join window) until resolution; otherwise `VotePollNotAvailableForVotingError` | — | `rs-drive-abci/.../masternode_vote/state/v0/mod.rs:72-92` | +| What ends it | Per-block `check_for_ended_vote_polls` using block time ≥ end date; max 2 end-time entries processed per block → resolution can lag a few blocks | constants versioned | `rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v0/mod.rs:66-85`; `drive_abci_validation_versions/v10.rs:391-392` | +| Winner | Highest weighted tally among contenders (top 100 considered). Abstain is ignored. If **lock tally > top tally → Locked**; lock tie → contender wins | — | `check_for_ended_vote_polls/v0/mod.rs:203-290`; `tally_votes.../v0/mod.rs:25-38` | +| Tie between contenders | `max_by(created_at, then block height, core height, doc id)` → the **latest-created** document wins the tie (counter-intuitive; not first-come) | — | `check_for_ended_vote_polls/v0/mod.rs:252-268` | +| Zero votes | All contenders tie at 0 → latest-created contender **wins** unless ≥1 lock vote. A lone uncontested requester wins after 14 days with no votes | — | same | +| Losers | Contender documents, votes, end-date entries removed; loser's doc is not stored | — | `rs-drive-abci/.../clean_up_after_contested_resources_vote_polls_end/v1/mod.rs:34-40`; `rs-drive/src/drive/votes/cleanup/` | +| Record kept | Stored poll info persists with `WonByIdentity(id)` / `Locked` / `NoWinner` plus voter lists | — | `rs-dpp/src/voting/vote_info_storage/contested_document_vote_poll_winner_info/mod.rs:18-23`; `check_for_ended_vote_polls/v0/mod.rs:292-300` | +| Locked name | **Permanently unregistrable** in this version: new contested create → `DocumentContestCurrentlyLockedError` (unlock not implemented) | — | `state_v1/mod.rs:239-247` | +| Awarded name re-request | Rejected (`DocumentAlreadyPresentError`); domain cannot be deleted so the name only moves via transfer/purchase | — | `state_v1/mod.rs:230-238` | + +## 4. Voting rules + +| Fact | Value | PV-dependent | Citation | +|---|---|---|---| +| Who votes | Any masternode in the platform's full masternode list (regular or Evo) | — | `rs-drive-abci/.../masternode_vote/transform_into_action/v0/mod.rs:111-124` | +| Weight | Regular **1**, Evonode **4** | — | same `:121-124` | +| Voter identity | Auto-created per masternode: id = `create_voter_identifier(proTxHash, votingAddress)` | — | `rs-dpp/src/identifier/mod.rs:15`; `masternode_vote/advanced_structure/v0/mod.rs:58-73` | +| Voting key | `ECDSA_HASH160`, purpose `VOTING`, security `HIGH`, read-only; data = masternode voting address. Signer pubkey hash must equal the MN's current voting address | — | `rs-drive-abci/.../get_voter_identity_key/v0/mod.rs:12-25`; `advanced_structure/v0/mod.rs:43-55` | +| Choices | `TowardsIdentity(id)`, `Abstain`, `Lock` | — | `rs-dpp/src/voting/vote_choices/resource_vote_choice/` | +| Max votes per masternode per contest | **5 total** (first vote + 4 changes); 6th → `MasternodeVotedTooManyTimesError`. Re-casting the same choice → `MasternodeVoteAlreadyPresentError` | Yes (`votes_allowed_per_masternode`, 5 in all versions) | `transform_into_action/v0/mod.rs:60-103`; `rs-drive/.../register_contested_resource_identity_vote/v0/mod.rs:95-117`; `dpp_validation_versions/v1.rs:33` | +| Counting key | Votes keyed by **proTxHash**, not voter identity (changing the voting key keeps the count) | — | `rs-drive/.../masternode_vote_transition.rs:41-47` | +| Cutoff | Only while `Started`; none after end/award/lock | — | `masternode_vote/state/v0/mod.rs:72-92` | +| Cost to voter | **Zero.** Fixed 0.0001 DASH (10,000,000 cr) per vote deducted from the contest's prefunded balance; tx fails if balance < 100,000 cr | — | `masternode_vote_transition.rs:48-56`; `rs-drive-abci/src/execution/types/execution_event/mod.rs:337-347`; `masternode_vote/balance/v0/mod.rs:45-80`; `fee/state_transition_min_fees/v1.rs:11` | +| Fund capacity | 0.2 DASH ⇒ 2,000 votes per contender contribution (0.1 DASH ⇒ 1,000 in PV14) | Yes | derived | +| Shared voting key across MNs | Allowed by protocol, but each MN has its own voter identity + nonce → **one transition per masternode**, all signed by the same key | — | `MasternodeVoteTransitionV0` fields `rs-dpp/.../masternode_vote_transition/v0/mod.rs:43-53` | +| Batching | **None** — one `MasternodeVoteTransition` = one `proTxHash` × one vote | — | same | +| Vote expiry | Votes of masternodes removed from the list are deleted each block | — | `rs-drive-abci/.../remove_votes_for_removed_masternodes/v0/mod.rs:16`; `run_dao_platform_events/v0/mod.rs:23-33` | + +## 5. SDK queryability (rs-sdk) + +| Need | API | Gotchas | Citation | +|---|---|---|---| +| (a) availability | `Sdk::is_dpns_name_available(name)` / `check_dpns_name_availability(label)` | **Only checks awarded `domain` docs.** Returns `true` for names in an active contest (contenders are not in primary storage) and for **locked** names. Must also query the contest vote state | `rs-sdk/src/platform/dpns_usernames/mod.rs:313-366`; `queries.rs:91` | +| (a') contest for a label | `get_contested_dpns_vote_state(label, limit)` → `Contenders { winner, contenders, abstain_vote_tally, lock_vote_tally }` | `winner` is `Some` once finished (incl. `Locked`) | `contested_queries.rs:125-158`; `rs-drive-proof-verifier/src/types.rs:163-172` | +| (b) active contests | `get_current_dpns_contests(start,end,limit)` → `label → end_time` (auto-paginates, default 100/page); low level `VotePollsByEndDateDriveQuery` | `get_contested_dpns_normalized_usernames` lists contested resources incl. historical; `get_contested_non_resolved_usernames` fans out one vote-state query per contest | `contested_queries.rs:432-502, 62-112, 325-375` | +| (c) tally & contenders | `ContenderWithSerializedDocument` via (a'); voters per contender: `get_contested_dpns_voters_for_identity` | `limit` u16 | `contested_queries.rs:171-200` | +| (d) a masternode's current votes | `ResourceVote::fetch_many(sdk, ContestedResourceVotesGivenByIdentityQuery{ identity_id = proTxHash, .. })` | **`Sdk::get_contested_dpns_identity_votes` is a stub that always returns empty** — do not use. Votes are keyed by proTxHash | `rs-sdk/src/platform/fetch_many.rs:515`; stub `contested_queries.rs:213-232`; `rs-drive/src/query/contested_resource_votes_given_by_identity_query.rs:37,244` | +| (e) finished result | Same vote-state query; `winner: Option<(WonByIdentity/Locked/NoWinner, BlockInfo)>` | — | `rs-drive-proof-verifier/src/types.rs:163-166` | +| (f) names owned | `get_dpns_usernames_by_identity(id, limit)` (index on `records.identity`, default limit 10); pending contests: `get_non_resolved_dpns_contests_for_identity` | owner semantics follow `records.identity` (rewritten on transfer) | `queries.rs:40-89`; `contested_queries.rs:390-415` | +| register | `Sdk::register_dpns_name(RegisterDpnsNameInput)` — preorder + domain, prefund auto-set | — | `mod.rs:148-311` | + +## 6. Normalization & contest detection + +| Fact | Citation | +|---|---| +| Homograph: lowercase, `o→0`, `i,l→1` — `dpp::util::strings::convert_to_homograph_safe_chars` (public; DET already uses it) | `rs-dpp/src/util/strings.rs:1-13` | +| Enforced on-chain: `normalizedLabel == convert(label)` | `triggers/dpns/v1/mod.rs:121-131` | +| Label regex `^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]$`, 3–63 chars; full name ≤ 253 | schema `:42-48`; `triggers/dpns/v1/mod.rs:30,108-118` | +| Contested regex lives only in the contract JSON (`contested.fieldMatches`). Callable from DET without duplication: `dpns_contract.document_type_for_name("domain")?.find_contested_index()` → `contested_index.field_matches[..].matches(value)`, or build the domain `Document` and call `document_type.prefunded_voting_balance_for_document(&doc, sdk.version())` (returns `Some((index, amount))` ⇒ contested **and** gives the exact fee) | `rs-dpp/.../versioned_methods.rs:649-681`; `rs-dpp/src/data_contract/document_type/mod.rs:202-216` | + +## 7. Other UX-relevant facts + +- Contest opens with a single requester; the requester sees "in contest" for 14 days (mainnet) even with no rival, then wins automatically unless a lock vote exists. +- One identity cannot submit a second contested create with the same document id (`DocumentContestDocumentWithSameIdAlreadyPresentError`); a non-contested create may not reuse a live contested id either. `rs-drive-abci/.../state_v1/mod.rs:192-220`, `state_v2/mod.rs:74-111`. +- Testnet only: structure checks skipped before epoch 2080 (historic). `advanced_structure_v1/mod.rs:52-56`. +- A contender cannot withdraw (domain Delete rejected; contested docs are not in primary storage). +- End time is block-time based (ms), not height; displayed end_time = start block time + duration. + +## Contradictions with DET before the redesign + +Recorded against the code as it stood when these facts were collected. Items 1 and 3 are resolved by the redesign (the fee is read from the platform version in `model/fee_estimation.rs`; the contested rule lives in `model/dpns.rs`); the others are the rules it was built to respect. + +1. `src/ui/identity/register_dpns_name_screen.rs:539` hard-coded "Cost ≈ 0.2006 Dash": correct for PV13 (0.2 + ~0.0006 fees), **wrong from PV14 (0.1 DASH)**. Read it from `sdk.version()` or via `prefunded_voting_balance_for_document`. +2. The 0.2/0.1 DASH is **not refundable** in any outcome, and losers keep nothing. UI copy must not call it a deposit. +3. `is_contested_name` lived in `ui/` (`register_dpns_name_screen.rs:678`) — duplicated the contract regex; placement policy wants `model/`, ideally delegating to the contract's `field_matches`. +4. If DET relies on SDK availability helpers, active-contest and locked names show as "available". +5. Masternode "my votes" via `get_contested_dpns_identity_votes` returns nothing (stub); use `ResourceVote::fetch_many` with the proTxHash. +6. Ties go to the **latest** created contender, not the first. diff --git a/docs/ai-design/2026-10-01-usernames-redesign/wireframes.html b/docs/ai-design/2026-10-01-usernames-redesign/wireframes.html new file mode 100644 index 000000000..f3f6408dc --- /dev/null +++ b/docs/ai-design/2026-10-01-usernames-redesign/wireframes.html @@ -0,0 +1,817 @@ + + + + + +Usernames and Name Votes — Wireframes (2026-10-01) + + + + +

Usernames and Name Votes — redesign wireframes

+

Dash Evo Tool, 2026-10-01. Companion to ux-spec.md. Light theme, mid-fi, same visual system as the 2026-09-22 identities canvas. Identity-side frames (blue tag) live in Identities; voting frames (purple tag) live in Masternodes › Votes. Rev 2: voting redesigned for operator convenience (node set, weighted impact, changes left, keyboard, non-blocking fan-out); #901 safety semantics kept, every #901 change listed in spec §4. Platform rules per platform-facts.md. Hover, focus (Tab) and selected states are live.

+ + + + +
+
0

Information architecture: before and after

+
    +
  • Today one DPNS tool under Tools mixes "My usernames" with voting. After: names live with the identity; voting lives with the nodes.
  • +
  • Decided (Q1): Masternodes opens on Votes when anything needs a decision; a top-bar chip carries the signal to every screen. Changes #901 VOTE-FR-001 (spec §4).
  • +
+
+

Before

Identities ▸ hub ▸ Settings tab
+   └ Username · "Aliases" (3 disabled stubs)
+   └ [View all usernames] ──jumps to──┐
+Masternodes ▸ list ▸ detail ▸ DPNS Voting ─┐
+Tools ▸ DPNS                         ◄─┘◄─┘
+   ├ Active contests   (voting)
+   ├ Past contests     (voting)
+   ├ My usernames      (owner!)  ← mixed
+   ├ Scheduled votes   (voting)
+   └ [Register Name]   (owner!)  ← mixed
+

After

Identities ▸ hub          (everyone)
+   ├ header: @main | @alex · Waiting for vote
+   ├ Home: request card, result banner
+   └ Profile ▸ Usernames card
+        ├ rows ••• Copy · QR · Show as main
+        ├ pending ▸ Request status
+        └ [Get another username] ▸ choose ▸ consent ▸ pay
+Top bar ▸ "2 names need your vote" (every screen)
+Masternodes  badge 2      (Power role)
+   ├ [ Votes 2 | Nodes ]   Votes first
+   │    node set: All my nodes · 24 · 51 votes
+   │    To decide · Voted · Scheduled · History
+   │    progress drawer (non-blocking)
+   └ node detail ▸ This node's votes
+                 ▸ [Vote with this node]
+Tools ▸ DPNS
+
+
+ + + + +
+
U1

Profile › Usernames card, all row states

Alex · Priya-owner
+
    +
  • One list per identity: main, other active, waiting for vote (any number, even with an owned name; fixes P5), open-for-requests phase, lost (30 days, dismissible).
  • +
  • No "Aliases", no disabled stubs. "Make primary" becomes device-only Show as main (needs a new local setting). "Add an alias" was just "register another name", now Get another username.
  • +
  • The menu is shown open on the second row to demo it; Tab through rows to see focus.
  • +
+
+
Identities › @alice
Mainnet · Connected
+
+ +
+
+
AN
Alice Novak ▾
@alice
+
Identity balance
0.4215 DASH
+
+ +
+
+

Public profile

+

Everyone on Dash Platform can see this.

+
AN
Display name, photo and About me editor (2026-09-22 A08, unchanged).
+
Profile fields (A08)
+
+
+
+

Usernames

+
+
@alice Main
Registered on Mar 12, 2026.
+ +
+
+
@alice-design
Registered on Jun 2, 2026.
+ + +
+
+
@ali ◷ Waiting for vote
Voting ends around Oct 9, 2026.
+ +
+
+
@novak ◷ Open for other requests
Others can ask for this name until Oct 5, 2026. Voting starts after that.
+ +
+
+
@al Went to someone else
The community vote ended on Sep 20, 2026.
+
+
+
+
@aa Locked for good
More votes went to locking this name, so no one can register it.
+ +
+
+ +

Each username is a separate small payment from this identity's balance.

+
+

Name on this device

Only you see this name. It's never published. (unchanged)

+
+
+
+
+
+
+ + +
+
U1b

Usernames card: empty and view-only

Alex
+
  • Empty = one sentence of value + primary CTA. View-only identity (no keys) keeps the button visible but disabled, with the reason and a way forward (never a dead-end red line, P10).
+
+

Usernames

This identity has no username yet. A username lets people pay you as @name instead of a long address.

+

Usernames

This identity has no username yet.

Add a key to this identity to register usernames. Add a key

+
+
+ + +
+
U2

Home: pending request card and one-time result banners

Alex
+
    +
  • Status refreshes on hub arrival via new RefreshMyUsernameRequests (own contests only), so Alex never visits a voting screen.
  • +
  • Result banners show once per outcome (new local "seen" flag), then the Profile row carries the state.
  • +
+
+
+

◷ Waiting for vote

+

@ali is waiting for a community vote. The vote ends around Oct 9, 2026.

+

You're leading right now. Votes can change until the vote ends.

+ +
+
+ + + +
+
+
+ + +
+
U3

Request status (pushed page)

Alex · Priya-owner
+
    +
  • Answers the three questions Alex has: where is it, am I winning, what happens next. Tally is read-only, numbers in text, leader marked with a word.
  • +
  • Power role with eligible nodes sees one plain link to Masternodes › Votes, filtered to this name.
  • +
+
+
Identities › @alice › @ali
Mainnet · Connected
+
+ +
+
+ +

Your request for @ali

◷ Waiting for vote
+

Other people asked for the same name, so Dash masternodes vote on who gets it.

+
+
+
+
✓
Requested
Sep 25, 2026
+
✓
Open for other requests
Ended Oct 2, 2026. 1 other person asked.
+
●
Community vote
Ends around Oct 9, 2026, 14:00.
+
Result
Not decided yet.
+
+
+
+
+

How the vote is going

+
+
YouLeading
31
+
Other request (7Yk2…d1Rt)
18
+
Lock, so no one gets it
8
+
Abstain
3
+
+

Evonodes count as 4 votes. Votes can change until the vote ends. Last updated 2 minutes ago.

+
+
What happens next +
    +
  • If you still have the most votes when the vote ends, @ali becomes yours automatically.
  • +
  • If requests are tied at the end, the most recent request wins.
  • +
  • If more votes go to locking than to any request, no one can ever register @ali.
  • +
  • The community vote fee isn't returned in any case.
+
Your nodes can vote on this name
+
+
+
+
+
+
+
+ + +
+
U4

Get another username: choose name

Alex · Priya-owner · Jordan
+
    +
  • Opened from a specific identity, so no identity picker (P10). Availability is checked live (new CheckUsernameAvailability op); format rules show only as they matter.
  • +
  • Shown: joinable contest. Suggestions avoid the vote using the model's contested rule. Rules are collapsed and consistent (P9).
  • +
+
+
Identities › @alice › Get another username
Mainnet · Connected
+
+ +
+
+
1Choose name—2Confirm
+

Get another username

+

For Alice Novak. People will use it to find and pay you. You can't change a username later.

+ +
@.dash
+
+
✓Between 3 and 63 characters
+
✓Only letters, numbers, and hyphens
+
◷1 other person already asked for @nova. You can join the vote until Oct 5, 2026.
+
+
Try one without a vote:
+
Username rules +
  • Between 3 and 63 characters.
  • Letters, numbers, and hyphens. No hyphen at the start or end.
  • Capital letters are treated as lowercase.
  • Names shorter than 20 characters that use only letters, hyphens, 0, and 1 need a community vote. Adding a digit from 2 to 9 avoids the vote.
+
+
+
+
+
+
+ + +
+
U4b

Availability row: every state

Alex
+
  • Exactly one row at a time, 400 ms debounce. Continue enabled only for the first three outcomes. Plurals are separate translation units.
+
+
◌Checking if @nova is available…
+
✓@nova2 is available.
+
◷@nova is available, but it needs a community vote.
+
◷{count} other people already asked for @nova. You can join the vote until {date}.
+
✗@alice is already taken. Try another name.
+
✗@bob can't be registered. A community vote locked this name for good.
+
✗Others can no longer join the vote for @nova. Try another name. (join window over: 7 days mainnet, 45 min testnet)
+
▲Availability can't be checked right now. Check your internet connection and try again.
+
+
+ + +
+
U5

Community vote consent (reuses 2026-09-22 M1)

Alex
+
  • Replaces the red "This is a contested name. Cost ≈ 0.2006 Dash" (P4). Fee read live from sdk.version(): 0.2 DASH before protocol 14, 0.1 DASH from 14; never refunded, never called a deposit. Durations from the network (mainnet shown; testnet: 45 / 90 minutes).
+
+
Identities › @alice › Get another username
+
+ +
+
+
+ + +
+
U6

Confirm and pay from the identity balance

Alex · Priya-owner
+
    +
  • One summary, one total, amount and name in the button. Signing key auto-picked; Power role can open Advanced (replaces the "Advanced Options" checkbox).
  • +
  • Right card shows the low-balance variant: inline reason + Top up (A09) that returns here with the name kept.
  • +
+
+
Identities › @alice › Get another username
Mainnet · Connected
+
+ +
+
+
✓Choose name—2Confirm
+
+
+

Review and pay

+
+
Username@nova Community vote
+
Registration feeabout {fee} DASH
+
Community vote fee (not returned)0.2 DASH
+
Total{total} DASH
+
Paid fromAlice Novak's balance · Available 0.4215 DASH
+
+
Advanced

Signing key: Authentication key 1 (Power role only).

+
+
+
+

Variant: balance too low

+
+
Total{total} DASH
+ +
+
+

Not synced: button disabled, tooltip "Available after sync finishes." Name choosing stays available.

+
+
+
+
+
+
+
+ + +
+
U7

Result: request submitted for a vote

Alex
+
  • After the blocking progress overlay ("Registering @nova. Keep Dash Evo Tool open until this finishes."). Registered and failed variants = 2026-09-22 A04 B/D. Replaces "Check the Pending label on your identity for updates" (P12).
+
+
◷
+

Your request for @nova is in

+

Others can still ask for this name until Oct 5, 2026. The community vote ends around Oct 12, 2026. If no one else asks and no one votes to lock it, @nova becomes yours then.

+

We'll show the result on your identity's page. You don't need to keep this screen open.

+
+
+
+ + +
+
V0

Top-bar attention chip, on any screen

Priya-operator
+
    +
  • Zero clicks to know a vote is needed (VOT-01). Shown only for the Power role with at least one node that has a voting key. Amber within the urgency window (24 h mainnet, 30 min testnet), calm blue otherwise.
  • +
  • A second chip appears only while votes are unconfirmed. Click on either opens Masternodes › Votes. Fed by a background refresh (30 min mainnet, 3 min testnet).
  • +
+
+
Wallets › Main wallet
+
+ + +
Mainnet · Connected
+
+
Calm variant (nothing urgent):   Testnet urgent:
+
+
+ + +
+
V1

Masternodes › Votes › To decide

Priya-operator
+
    +
  • Node set chosen once and remembered: every choice applies to all 24 nodes. One click on a choice plus Cast = done (VOT-02). Cards sorted by time left.
  • +
  • Weighted tally (Platform tallies are weighted; evonode = 4) plus your influence: what your 51 votes can do (VOT-03). Node line shows who voted what and changes left (VOT-04).
  • +
  • Keyboard: J/K move (focus ring on first card), 1–9 contender, L lock, A abstain, Space select. Two cards selected → dark bulk bar. Partly voted contests stay in To decide.
  • +
  • #901 kept: no-op skip, unresolved locks (needs-attention row), vote-state-unavailable notes, read-only tally vs selectable choices.
  • +
+
+
Masternodes › Votes
Mainnet · Connected
+
+ +
+
+
+
+
+
+
+
+
+ +
+
+
+ +
2 selected
+ +
+
+
alice.dash▲ Ends in 6 hours
+

2 requests · Voting ends Oct 1, 2026, 21:00 UTC.

+
+
Alice (3MN5…s8Qp)
80
+
Alyce (7Yk2…d1Rt)
74
+
Lock name
46
+
Abstain
12
+
+ Alice leads by 6 votes. Your 51 votes can change who leads. +
+
+
Your decision
+
+

Your nodes: 19 not voted · 4 voted Abstain · mn-07 has no changes left

+

Changing 4 earlier votes uses 1 of each node's 4 changes.

+
+
+
+
+
cooltoken.dashEnds in 4 days
+

3 requests · Others can join until Oct 2, 2026, 12:00 UTC.

+
+
Dana (9Hq1…)
20
+
Erin (2Ba7…)
20
+
Lock name
8
+
+ Dana and Erin are tied. If still tied at the end, the most recent request wins. +
+
+
Your decision
+
+

Your nodes: 21 not voted · vote state unavailable for 3 nodes; they're left out.

+
+
+ +
+
2 decisions ready · 44 transactions, one per node and name
+
+
+
+
+ + +
+
V1b

Node set popover

Priya-operator
+
    +
  • Saved per network as the default (new local setting). Shared voting key needs no extra step: each node still gets its own transaction (PF §4).
  • +
  • Nodes that can't vote are listed with the reason and left out automatically, never silently.
  • +
+
+
Vote with
+ + + + +
+
NodeVotesVoting keyNote
+
evo-014✓ Ready 
+
mn-021✓ Ready 
+
mn-091✗ No key
+
mn-141✓ ReadyNot in the masternode list
+
+
+
+
+ + +
+
V2

Confirm popover: aggregate, not a per-target table

Priya-operator
+
    +
  • Changes #901 VOTE-FR-024: totals first (decisions × nodes = transactions), the change warning once, skips with reasons. The per-node table is one click away under "Adjust nodes".
  • +
  • Scheduling relative to the deadline ("When voting is about to end", 6 h before on mainnet, 10 min on testnet); absolute UTC still stored. Enter confirms, Esc cancels.
  • +
+
+
Masternodes › Votes
+
+ +
+
+
+ + +
+
V2b

Progress drawer: non-blocking fan-out

Priya-operator
+
    +
  • Changes #901's full-window overlay: the screen stays usable, and only the targets being sent are locked (VOTE-FR-034). The drawer persists across screens and collapses to a chip.
  • +
  • Per node×name typed statuses from #901. Unconfirmed: "Check again", never "Submit again". The final banner summarizes the counts.
  • +
+
+
Masternodes › Votes
Mainnet · Connected
+
Votes list stays interactive behind the drawer (cards already sent show "Sending with 23 nodes…" and their choices are locked).
+
+
Casting 44 votes33 done · 9 sending · 2 being checked
+ +
evo-01 · alice.dash · Vote for Alice✓ Done
+
mn-02 · alice.dash · Vote for Alice◌ Sending
+
mn-12 · cooltoken.dash · Lock name
This vote may already have been submitted. Don't submit it again.
◷ Being checked
+
mn-20 · cooltoken.dash · Lock name
Not applied. Platform shows a different vote.
✗ Not applied
+
+
+
+
+ + +
+
V3

Scheduled votes

Priya-operator
+
  • Grouped by decision (one row = one name × node set; expand for nodes), relative timing shown with the absolute UTC time it resolves to. #901 kept: typed status, edit/remove until sending starts, missed after 120 s with Cast now, failure reasons survive restart.
+
+
Masternodes › Votes
Mainnet · Connected
+
+ +
+
+
+
+

Keep Dash Evo Tool open and connected so scheduled votes are cast on time.

+ + + + + + +
NameNodesVoteWhenStatus
cooltoken.dashVote for Dana6 hours before the end
Oct 5, 2026, 06:00 UTC · in 4 days
◷ Scheduled  
dashfan.dashLock nameSep 30, 2026, 08:00 UTC
yesterday
▲ Missed
Dash Evo Tool wasn't running at that time. Voting is still open for 20 hours.
quantum.dashmn-09AbstainSep 29, 2026, 18:00 UTC✗ Not cast
This node had no voting key on this device.
oldname.dash24 nodesVote for ZedSep 20, 2026, 10:00 UTC✓ Cast with 24 nodes
+
+
+
+
+
+ + +
+
V4

History

Priya-operator
+
  • Outcome in words, winner ID labelled and copyable, plus what your nodes did and how much weight that was.
+
+
+ + + + + +
NameEndedOutcomeYour nodes voted
oldname.dashSep 21, 2026Went to Zed (4c8e…1b70) Vote for Zed (24 nodes, 51 votes)
takenname.dashSep 18, 2026Locked for good, no one can register itLock name (9 evonodes, 36 votes)
calm.dashSep 10, 2026Went to Kai (8Pq2…aa10) Your nodes didn't vote.
+
+
+ + +
+
V5

Empty and gate states

Priya-operator · Power without nodes
+
  • Never a raw error. No nodes: contests stay browsable read-only (choices disabled) under the banner. Journal unreadable keeps #901 FR-046 behaviour.
+
+

Below: contest cards, read-only. Choice tooltip: "Load a masternode with a voting key to vote."

+

None of your nodes has a voting key on this device. Add a voting key to vote. One key can serve several nodes.

+

There are no open name contests right now. New contests appear here automatically.

+
+
+
+ + +
+
V6

Node detail: this node's votes

Priya-operator
+
  • Changes #901 decision 2: Vote with this node opens Votes with the node set = this node, shown visibly on the node-set chip. Lists this node's votes with changes left and its masternode-list status (votes of removed nodes don't count, PF §4).
+
+
evo-01 ✓ Voting ready Evonode · 4 votes
In the masternode list · ProTx 1a2b…9f0e
+

This node's votes

+ + + + + +
NameVoteChanges leftVoting ends
alice.dashAbstain3 of 4in 6 hours
cooltoken.dashNot voted4 of 4in 4 days
dashfan.dashLock nameUnknown. Voted outside Dash Evo Tool.in 20 hours
+

Changes left are counted on this device.

+
+
+ + + diff --git a/docs/kv-keys.md b/docs/kv-keys.md index 66a63a066..9e36e6419 100644 --- a/docs/kv-keys.md +++ b/docs/kv-keys.md @@ -1,6 +1,6 @@ # DET k/v key reference -`DetKv` wraps the upstream `platform_wallet_storage::KvStore`. Values are encoded as `[ schema_version (1 byte) | bincode(payload) ]` using `bincode::config::standard()`. Keys are colon-separated namespaces. Every `DetKv` call takes a `DetScope` argument: `DetScope::Global` = global slot, `DetScope::Wallet(&seed_hash)` = per-wallet slot (cascades on wallet delete), `DetScope::Identity(&id)` = per-identity slot (active — used for identities, top-ups, scheduled votes, and DashPay `private`/`address_index` overlays), `DetScope::Token { identity_id, token_id }` = per-token slot (defined and mapped, currently unused — token balances are read live from upstream). `DetScope::Identity` and `DetScope::Token` map to the upstream `meta_identity` / `meta_token` tables; an upstream `AFTER DELETE` soft-cascade reaps that metadata only when the parent object row is actually deleted. DET identity unloads do not delete that upstream row, so `delete_local_qualified_identity` explicitly purges the identity scope and owner-scoped Global sidecars. `DetScope` is the DET-side seam over the upstream `ObjectId` enum — the upstream scope type never crosses the wallet-backend boundary. +`DetKv` wraps the upstream `platform_wallet_storage::KvStore`. Values are encoded as `[ schema_version (1 byte) | bincode(payload) ]` using `bincode::config::standard()`. Keys are colon-separated namespaces. Every `DetKv` call takes a `DetScope` argument: `DetScope::Global` = global slot, `DetScope::Wallet(&seed_hash)` = per-wallet slot (cascades on wallet delete), `DetScope::Identity(&id)` = per-identity slot (active — used for identities, top-ups, and DashPay `private`/`address_index` overlays), `DetScope::Token { identity_id, token_id }` = per-token slot (defined and mapped, currently unused — token balances are read live from upstream). `DetScope::Identity` and `DetScope::Token` map to the upstream `meta_identity` / `meta_token` tables; an upstream `AFTER DELETE` soft-cascade reaps that metadata only when the parent object row is actually deleted. DET identity unloads do not delete that upstream row, so `delete_local_qualified_identity` explicitly purges the identity scope and owner-scoped Global sidecars. `DetScope` is the DET-side seam over the upstream `ObjectId` enum — the upstream scope type never crosses the wallet-backend boundary. Three backing stores exist: @@ -88,7 +88,7 @@ The identity blob and top-up history are **identity-scoped** (`DetScope::Identit | `det:identity_index:v1` | `None` | `det-.sqlite` | `Vec<[u8;32]>` | Complete enumeration index of stored identity ids. Rewritten wholesale on every add/remove, so all read-modify-write access is serialized by one process-wide lock — absence from this roster authorizes the vault-cleanup sweep to delete an identity's private keys, and a lost update would forge that evidence | | `det:identity_order:v1` | `None` | `det-.sqlite` | `Vec<[u8;32]>` | User-chosen display ordering of identity ID raw bytes | | `det:top_ups:v1` | `DetScope::Identity(&id)` | `det-.sqlite` | `BTreeMap` | Top-up history: account index → credits | -| `det:vault_cleanup_pending:v1:` | `None` | `det-.sqlite` | `Vec<(StoredPrivateKeyTarget, KeyID)>` | Durable manifest of the vault-key placements a `delete_local_qualified_identity` call must still clear; persisted before that call's first mutation, cleared once every listed key and the owner's DashPay/token-list sidecars are deleted (a clear that fails leaves a stale manifest, not a failed removal — the sweep re-runs the idempotent deletes and clears it). Global-scoped (not `DetScope::Identity`) so it survives the index removal that unlists `id` — the exact step it exists to protect against. Resumed by the boot-time `AppContext::resume_pending_vault_cleanups` sweep. | +| `det:vault_cleanup_pending:v1:` | `None` | `det-.sqlite` | `Vec<(StoredPrivateKeyTarget, KeyID)>` | Durable manifest of the vault-key placements a `delete_local_qualified_identity` call must still clear; persisted before that call's first mutation, cleared once every listed key, the owner's DashPay/token-list sidecars and its username records are deleted and its pending DPNS votes are cancelled (a clear that fails leaves a stale manifest, not a failed removal — the sweep re-runs the idempotent deletes and clears it). Global-scoped (not `DetScope::Identity`) so it survives the index removal that unlists `id` — the exact step it exists to protect against. Resumed by the boot-time `AppContext::resume_pending_vault_cleanups` sweep. | | `det:identity_unloaded:v1:` | `None` | `det-.sqlite` | `u64` | Presence-only marker that the user unloaded this identity from this device; the stored value is the unload's unix timestamp, kept for diagnostics only and never read for a decision. Written by `delete_local_qualified_identity` **before** `index_remove_identity` delists the identity, and by the devnet wipe for every identity it clears, so no window exists in which the identity is gone and the marker is not yet on file. Consulted by `AppContext::store_discovered_identity` — the single guarded store used by the discovery passes and by the `finish_unwire` migration import — which refuses to store an identity carrying one. That refusal is what makes an unload survive the automatic passes (boot sweep, post-unlock, wallet import, resumed migration), all of which re-derive or re-read the same identity from material that outlives the removal. The absent-record branch of `write_local_qualified_identity_locked` declines the same way, as a backstop covering every update path that could otherwise re-create a record for an identity a removal had already taken away. Global-scoped for the same reason as the manifest above: it must outlive the identity's own scope. Retired only by `insert_local_qualified_identity`, i.e. by the user deliberately loading the identity again. Never expired on a timer — an expiring tombstone is a resurrection with a delay — and never reaped: it grows by one entry per identity the user has actually unloaded on this network, a bound set by user action rather than by anything automatic, which any change letting an automatic path write these would break. | **Exception to the cascade above**: an identity stored without a wallet association (`wallet_hash: None`) is *also* mirrored into the upstream `identities` table under the **unowned scope** — the all-zero `WalletId`, which upstream stores as a NULL `wallet_id`. Masternode/evonode nodes are the expected case, but any wallet-less identity DET stores takes this path (e.g. a `User` identity looked up by id with no owning wallet). The scope is load-bearing, not incidental: a NULL `wallet_id` activates no foreign key, so no wallet's `ON DELETE CASCADE` reaches the row, and the `cascade_meta_on_identity_delete` trigger — which would delete the identity's `meta_identity` rows, i.e. the `det:identity:v1` record above — never fires for it. That is the whole point: filing the same identity under a real wallet's scope would make removing that unrelated wallet destroy the node's DET record. These rows are also kept out of every wallet's `IdentityManager`, because the `identities` upsert promotes an unowned row to the first wallet that flushes it. @@ -107,16 +107,61 @@ Source: `src/context/identity_db.rs`, `src/wallet_backend/identity_ops.rs` --- -## Scheduled votes +## Scheduled votes (retired) -Scheduled votes are **voter-scoped** (`DetScope::Identity(&voter_id)`); the contested name is the key suffix. A Global `det:scheduled_vote_voters:v1` slot holds the complete set of voter ids that have at least one scheduled vote, driving the network-wide read / clear paths (Identity scope has no cross-voter listing). +These keys are **retired**. No current code reads or writes them; scheduled votes live only in the DPNS vote journal below. Entries left behind by an earlier development build are ignored: they are neither imported nor reported. + +| Key | Scope | Store | Status | +|-----|-------|-------|--------| +| `det:scheduled_vote:` | `DetScope::Identity(&voter_id)` | `det-.sqlite` | Retired; never read | +| `det:scheduled_vote_voters:v1` | `None` | `det-.sqlite` | Retired; never read | +| `det:migration:unreadable_votes::v1` | `None` | `det-app.sqlite` | Retired; never read (the storage update no longer inspects legacy scheduled votes) | + +Unexecuted schedules in the legacy SQLite `scheduled_votes` table of `data.db` are detected read-only at startup (`src/context/legacy_scheduled_votes.rs`) and raise a notice; they are never imported. One live key bounds that notice: + +| Key | Scope | Store | Value type | Notes | +|-----|-------|-------|------------|-------| +| `det:legacy_scheduled_votes_noticed_at:v1:` | `None` | `det-.sqlite` | `u64` | Unix time in milliseconds when the notice was first due. The notice stops one full contest duration later, when every contest an old schedule could refer to has closed | + +Source: `src/context/legacy_scheduled_votes.rs` + +--- + +## DPNS vote journal + +The journal is the sole store of immediate and scheduled DPNS votes. Every key is Global-scoped and carries the network in its name, so one network's journal cannot be read as another's. `` is one of `mainnet`, `testnet`, `devnet`, `regtest`; `` is the 16-byte `DpnsVoteOperationId` as lowercase hex. + +| Key | Scope | Store | Value type | Notes | +|-----|-------|-------|------------|-------| +| `det:dpns_vote_operations:v2:` | `None` | `det-.sqlite` | `Vec<[u8;16]>` | Index of operation ids present in the journal | +| `det:dpns_vote_operation:v2::` | `None` | `det-.sqlite` | `DpnsVoteOperation` | One submitted batch: its targets (voter, vote poll, requested choice, timing) with per-target status and failure | +| `det:dpns_vote_operation_locks:v2:` | `None` | `det-.sqlite` | `BTreeMap` | Which operation currently owns each target; rebuilt from the operation records when missing or dirty | +| `det:dpns_vote_operation_locks_dirty:v2:` | `None` | `det-.sqlite` | `bool` | Set while the lock index is being rewritten, so an interrupted rewrite forces a rebuild | +| `det:dpns_vote_relative_labels:v1::` | `None` | `det-.sqlite` | `BTreeMap` | Display-only record of the relative schedule preset chosen per target; shares the operation's retention | +| `det:dpns_vote_recovery_times:v1::` | `None` | `det-.sqlite` | `BTreeMap` | Unix time in milliseconds when restart recovery picked up each immediate target of the operation. Written only by restart recovery; shares the operation's retention | +| `det:dpns_vote_schedule_dismissals:v1::` | `None` | `det-.sqlite` | `BTreeSet` | Scheduled targets the user dismissed from the Scheduled view | +| `det:dpns_vote_immediate_history:v1:` | `None` | `det-.sqlite` | `Vec` | Completion order of finished immediate operations, used to bound history | +| `det:dpns_vote_scheduled_history:v1:` | `None` | `det-.sqlite` | `Vec` | Completion order of finished scheduled operations, used to bound history | +| `det:dpns_vote_counts:v1:::` | `None` | `det-.sqlite` | `u8` | Votes this device saw Platform apply for one node on one contest, used for "changes left". Kept outside the operation records so history pruning does not lose it; dropped only when the contest is proven closed | +| `det:dpns_vote_counted:v1:::` | `None` | `det-.sqlite` | `[u8;16]` | Id of the operation whose confirmed vote was last added to the matching `det:dpns_vote_counts:v1:` count, so a repeated confirmation is not counted twice. Dropped together with the count | + +Loading the journal fails closed: one unreadable operation record fails every operation that reads the journal. Identity removal is the exception. It deletes the identity's keys regardless and leaves the vote cancellation to the retained `det:vault_cleanup_pending:v1:` manifest, which startup recovery retries. + +Source: `src/context/dpns_vote_operations/keys.rs` (key schema), `src/context/dpns_vote_operations/mod.rs`, `src/context/dpns_vote_operations/retention.rs`, `src/context/dpns_vote_operations/counts.rs` + +--- + +## Usernames (identity side) + +Per-identity username state. Global-scoped with the identity id in the key, so it outlives the identity's own scope until identity removal clears it explicitly; a failed clear is retried by the vault-cleanup manifest. | Key | Scope | Store | Value type | Notes | |-----|-------|-------|------------|-------| -| `det:scheduled_vote:` | `DetScope::Identity(&voter_id)` | `det-.sqlite` | `StoredScheduledVote` | Fields: `voter_id: [u8;32]`, `contested_name: String`, `choice: StoredVoteChoice`, `unix_timestamp: u64`, `executed_successfully: bool` | -| `det:scheduled_vote_voters:v1` | `None` | `det-.sqlite` | `Vec<[u8;32]>` | Enumeration index of voter ids with scheduled votes | +| `det:username_requests:` | `None` | `det-.sqlite` | `Vec` (stored as `StoredUsernameRequest`) | The identity's requests for names that need a community vote. Fields per request: `label`, `normalized_label`, `phase`, `requested_at`, `join_end`, `end`, `decided_at`, `tally`, `last_updated`. The layout is positional, so no field can be added: the in-memory flag `reflected_in_owned_names` is stored as the appended `phase` index `WonReflected`, and entries written before it existed load as not reflected | +| `det:main_username:` | `None` | `det-.sqlite` | `String` | Device-only choice of the username shown as main | +| `det:username_outcomes_seen:` | `None` | `det-.sqlite` | `BTreeSet` | Outcome banners already shown, as `:` | -Source: `src/context/identity_db.rs` +Source: `src/context/contested_names_db.rs`, `src/model/dpns_usernames.rs` --- diff --git a/docs/user-stories.md b/docs/user-stories.md index 66718b000..0bf8413cd 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -751,9 +751,9 @@ As a user, I want the identities I loaded before an upgrade — and the keys the - Identities stored before the upgrade are imported from the previous version's storage on the first launch afterward, keeping each identity's keys, alias, and wallet link. Progress is shown as its own step. - An identity that cannot be read is reported in a banner naming the recovery action (load it again), rather than dropped silently. The previous version's data is never deleted, so a later build can still import it. -- A single unreadable identity costs only itself: the readable identities in the same batch still import, and neither the wallet migration that restores access to funds nor the scheduled-vote import is blocked by it. +- A single unreadable identity costs only itself: the readable identities in the same batch still import, and the wallet migration that restores access to funds is not blocked by it. - The report of unreadable identities returns on every launch until it is explicitly acknowledged, so a user who stepped away cannot lose the only notice that some of their keys were not carried over. -- When identities and scheduled votes are both unreadable on the same launch, one banner names both remedies, and acknowledging it retires both reports — neither report can bury the other. +- When identities and records of earlier balance top-ups are both unreadable on the same launch, one banner names both remedies, and acknowledging it retires both reports — neither report can bury the other. Scheduled votes are not part of this import; DPN-009 covers them. - An identity the user deletes after the upgrade stays deleted. The import runs once, so a later launch never restores a removed identity, its alias, or its keys. ### IDN-020: Restore keys an upgrade left behind, without re-entering them [Implemented] @@ -792,66 +792,93 @@ As a user, I want to remove an identity from this device from the identity's own - A removal that cannot be completed at all leaves the identity's private keys intact, so a retry still has everything it needs; no identity is ever left listed without its keys, and no identity is ever reported as still removable once it is already gone from every list. - The unload sticks. The wallet that derives the identity stays loaded, and the app re-derives and looks up that wallet's identities on its own — at start-up, after a wallet is unlocked, and when a wallet is imported — but none of those automatic passes put back an identity the user unloaded, whether the pass starts before, during, or after the removal. The same holds for the developer-only devnet "clear all identities" sweep. - Adding a key to an identity that is unloaded while the key is being registered on the network does not leave that key's private half on this device. The key exists on Dash Platform and the app says so plainly, naming what to do — load the identity again, then add the key again — rather than reporting a save that did not happen. -- Loading the identity again ends the exclusion, so later automatic passes keep its public record up to date. Loading does not restore private keys deleted by the unload: using the identity for signed actions again requires the user's own backup, either an unlocked wallet that can derive a matching key or a key the user imports. +- Loading the identity again ends the exclusion, so later automatic passes keep its public record up to date. Loading does not restore private keys deleted by the unload: using the identity for signed actions again requires the user's own backup, either an unlocked wallet that can derive a matching key or a key the user imports. Loading does not bring back DPNS votes reviewed before the unload either, including votes that were still being checked when the identity was unloaded: they end as cancelled and are sent only if the user reviews them again. --- ## DPNS (DPN) -### DPN-001: Register a DPNS username [Implemented] +### DPN-001: Register a username [Implemented] **Persona:** Alex, Priya -As a user, I want to register a human-readable username on DPNS so that others can send me Dash using a name instead of an address. +As a user, I want to register a username for one of my identities so that others can send me Dash using a name instead of an address. -- Choose identity, enter desired name. -- Cost estimate displayed before confirmation. -- While registration runs, a full-window blocking overlay (UX-001) is shown so the same name cannot be submitted twice; it lowers automatically on success or error. -- Completion feedback distinguishes a username registered for immediate use from a request submitted for community voting. +- Started from the identity (Profile ▸ Usernames ▸ Get another username, Home checklist, or header). No identity picker; the signing key is chosen automatically, and Power users can change it under Advanced. +- Availability is checked live before paying: available · needs a community vote · others already asked (joinable until a shown time) · taken · locked for good · request window closed · already requested by this identity · can't check. Only the first three allow continuing. Contested and locked names are never reported as available. +- Names that need a vote show a consent step: other people can ask during the join window (7 days on Mainnet, 45 minutes on Testnet), the vote lasts 14 days (90 minutes on Testnet) even without a rival, the community vote fee (read from the network: 0.2 DASH before protocol 14, 0.1 DASH from 14) is never returned, and a lock vote means no one gets the name. +- The confirm step shows the registration fee, the community vote fee, the total, and the identity balance it is paid from. A low balance offers Top up and returns with the name kept. Availability is re-checked on Pay. +- Changing the name, identity, network or fees invalidates the payment review and vote consent. The backend rejects an unapproved community vote fee before spending funds. +- While registration runs, a full-window blocking progress overlay prevents a duplicate submission. +- Completion distinguishes a username registered for immediate use from a request submitted for a community vote. +- If the app cannot confirm whether a paid request went through, it says so, asks me not to pay again until I have checked the Usernames list, and does not put the Pay step back with the same review. -### DPN-002: View owned usernames [Implemented] +### DPN-002: View my usernames [Implemented] **Persona:** Alex, Priya -As a user, I want to see all DPNS usernames I own so that I can manage my registered names. +As a user, I want to see each identity's usernames and their state so that I know which names I have and which are still being decided. -- Lists all usernames tied to the current wallet's identities. +- Profile ▸ Usernames lists the main name, other active names, every pending request (also when the identity already owns a name), and outcomes from the last 30 days (went to someone else, locked for good, no one got it). +- Saved requests refresh before the wider contest search. After the estimated deadline, Home, the identity badge, and the status page show “Awaiting result” until the network confirms an outcome; elapsed time alone never awards or rejects a name. +- Refreshing preserves concurrent requests, main-name choices, and seen outcomes. A failed storage read keeps the last complete snapshot available for later updates. +- Won usernames keep retrying failed fetches and local writes after a restart until the identity records the owned name. +- A won username that the identity recorded and that later leaves the identity (for example after a transfer) is no longer listed as one of its usernames. +- Row actions: Copy username, Show QR code, Show as main. Usernames can't be deleted, so no delete action is offered. +- The identity switcher and "See all identities" show each identity's usernames. There is no separate cross-identity usernames table. -### DPN-003: View active name contests [Implemented] +### DPN-003: See name contests my nodes can vote on [Implemented] **Persona:** Priya -As a power user, I want to view active DPNS name contests so that I can participate in voting on contested names. +As a masternode operator, I want to see the name contests that need a decision from my nodes so that I can vote before they end. -- Lists all contests with status and vote counts. +- Masternodes ▸ Votes (first segment) lists contests under To decide, sorted by time left. Contests where only some of my nodes voted stay in To decide. Contests none of my nodes can vote on are grouped separately, with the reason. +- Each card shows a weighted tally (evonodes count as 4), the deadline with network-correct durations, and how my nodes currently voted. +- Contest refresh remains available if saved voting progress cannot be recovered. +- Tools no longer has a DPNS entry. ### DPN-004: View past name contests [Implemented] **Persona:** Priya -As a power user, I want to review past DPNS contests so that I can see outcomes and historical voting data. +As a power user, I want to review past contests so that I can see outcomes and how my nodes voted. -- Lists completed contests with results. +- Votes ▸ History lists finished contests with the outcome in words (went to a named requester with a copyable identifier, or locked for good), and a final “details” column with a link that opens the contest in Platform Explorer for the active Mainnet or Testnet network. ### DPN-005: Vote on contested names [Implemented] **Persona:** Priya -As a masternode operator, I want to vote on contested DPNS name registrations so that I can participate in network governance. +As a masternode operator, I want to make one decision per contest and have all my chosen nodes cast it so that voting with many nodes takes seconds. -- Cast, change, or abstain votes (max 4 vote changes per contest). -- Evonode/masternode identity required. -- Note: The max 4 vote changes constraint is enforced at the Platform protocol level, not validated in the app UI. +- One choice per card (Vote for a requester, Lock name, Abstain) applies to every node in the remembered node set. Cast opens one confirm step for all decisions. +- Each node votes in its own transaction (Platform has no batching). The confirm shows decisions × nodes = transactions, warns once when votes change earlier choices, and lists skipped nodes with reasons (already voted this way, no changes left, vote state unavailable, not in the masternode list). +- A node may vote five times per contest: the initial vote plus four changes. Changes left are shown per node, counted on this device, or marked unknown when the node voted outside Dash Evo Tool. Nodes with none left are skipped. +- Choosing the current choice submits nothing. The node's proved current choice is shown before casting. +- An uncertain vote stays locked after the estimated deadline until authoritative network evidence resolves it; the local clock cannot establish that the vote failed. +- Unavailable voting information leaves the affected nodes out and offers Refresh voting. Other nodes can still vote. +- If a first vote becomes a change during preflight, the confirm reopens with the change warning. ### DPN-006: Schedule votes [Implemented] **Persona:** Priya -As a masternode operator, I want to schedule votes for later execution so that I can plan my voting strategy in advance. +As a masternode operator, I want to schedule votes so that they are cast before the deadline without my watching. -- Set vote to be cast at a future time. -- View and manage scheduled votes. +- Timing: Now, When voting is about to end (default 6 hours before the end on Mainnet, 10 minutes on Testnet), or At a specific time. The absolute UTC time is stored and shown next to the relative label. +- Votes ▸ Scheduled groups rows by decision with an expandable node list. Edit changes the choice or time before execution starts. Remove is permanent. Times at or after the deadline are rejected. +- Scheduled and immediate votes share the same target locks and result states. An ambiguous result is never rebroadcast automatically. +- Missed votes (more than 120 seconds past due) explain why and offer Cast now, Edit, and Remove. +- Completed scheduled and mixed batches retain the latest 256 operations per network, without discarding unresolved votes or bringing removed schedules back. -### DPN-007: Batch voting across contests [Implemented] +### DPN-007: Vote with many nodes and contests at once [Implemented] **Persona:** Priya -As a masternode operator, I want to apply voting choices across multiple contests in bulk so that I do not have to vote on each contest individually. +As a masternode operator, I want to choose which nodes vote and decide many contests quickly so that I do not repeat work per node or per contest. -- "Set all" option for batch vote assignment. +- A node-set selector (All my nodes, Evonodes only, Masternodes only, Custom) shows node count and total weight, is saved per network, and lists nodes that can't vote with the reason. +- Keyboard: J/K move between cards, 1–9 vote for a requester, L lock, A abstain, Space select, Enter cast. Shortcuts act only in the contest list. Selecting several cards shows a bulk bar (Lock name, Abstain, Clear). +- Adjust nodes in the confirm step shows every node × contest target (current → new choice, timing, changes left) and allows per-node timing or Don't use this node. +- A vote for a requester shows their name and a shortened identity ID, or the ID alone when the name is unavailable, so similar names remain distinguishable. +- Switching networks clears drafts and open dialogs. +- A successful mixed batch reports cast and scheduled counts. +- A node loaded after decisions were staged is left out of them in the confirm step until the operator includes it under Adjust nodes; decisions staged after the earlier ones were cast or cleared use it. +- Decisions staged or changed while a batch is submitting remain in the tray when that batch finishes. Another batch can be submitted after the pending submission returns. ### DPN-008: Recognise an identity by its profile name [Implemented] **Persona:** Alex, Priya @@ -859,28 +886,102 @@ As a masternode operator, I want to apply voting choices across multiple contest As a user, I want my identity's Display name to identify it throughout the app so that I recognise it consistently. - Change Display name in the identity profile. -- Lists and navigation use Display name, then a registered username, then a shortened identity ID. -- My usernames lists registered names without assigning local identity aliases. +- Lists and navigation use Display name, then the main username (DPN-018), then a shortened identity ID. +- Profile → Usernames lists registered names without assigning local identity aliases. -### DPN-009: Scheduled votes preserved across an app upgrade [Implemented] +### DPN-009: Notice schedules that need a fresh decision after an upgrade [Implemented] **Persona:** Priya -As a masternode operator, I want my previously scheduled DPNS votes to survive an app upgrade so that I do not miss a contest's vote window after updating. +As a masternode operator, I want to be told when an upgrade cannot carry over my scheduled votes so that I can cast or schedule them again. -- Scheduled votes stored before the upgrade remain visible and executable afterward. -- The first launch after the upgrade imports them from the previous version's storage, keeping each vote's choice, timestamp, and already-cast state. A vote that cannot be read is reported in a banner, with the recovery action, rather than dropped silently — and never blocks the wallet migration that restores access to funds. -- A single unreadable vote row costs only itself: the readable votes in the same batch still import. -- The report of unreadable votes returns on every launch until it is explicitly acknowledged, so a vote whose deadline is still open cannot lose its only notice to a missed or dismissed banner. +- Startup checks for unexecuted schedules in the previous SQLite storage on the selected network. +- A dismissible notice says the old schedules were not carried over and directs me to Masternodes → Votes to schedule the ones I still want. It does not list them. +- The notice returns on each launch until one contest duration after it first appeared (14 days on Mainnet, 90 minutes on Testnet), when no contest an old schedule could refer to can still be open. +- Old schedules are neither imported, listed, nor executed automatically; their source records remain untouched. +- Executed schedules and votes already represented in the voting journal do not raise the notice. +- New schedules use only the voting journal, including editing, cancellation, execution and recovery. -### DPN-010: See a pending username registration [Implemented] +### DPN-010: See a pending username request [Implemented] **Persona:** Alex -As a user who has requested a username that is not yet awarded, I want to see that the request is pending so that I am not told to "pick a username" for a name I have already chosen. +As a user who has requested a username that is not yet awarded, I want to see that the request is pending so that I am not told to pick a username I have already chosen. -- A requested-but-unawarded name shows a "Pending" pill next to the identity — on both the Identity Home hero card and the Identity Settings tab. -- The hero card shows the requested name with the pill instead of the "No username yet — Pick a username" prompt. -- The onboarding checklist counts the submitted request as completing "Pick a username" while clearly stating that Dash masternodes are voting. -- The pill's tooltip explains that Dash masternodes decide who receives the username and, when the decision time is known, gives an estimated decision time. +- When the identity has no active name, the header subtitle shows `@name` with the request's status: `Open for other requests` while others can still join, `Waiting for vote` after that, `Awaiting result` once the estimated end has passed. The Home card and Profile row show every pending request. +- The onboarding checklist counts a submitted request as completing "Pick a username" while stating that Dash masternodes are voting. +- The status refreshes on its own: on hub arrival when older than 5 minutes, and every 15 minutes (2 minutes on Testnet) while a request is pending. It doesn't depend on visiting a voting screen. + +### DPN-011: Recover an ambiguous vote result [Implemented] +**Persona:** Priya + +As a masternode operator, I want DET to keep checking a submitted vote whose result was temporarily unavailable so that I do not spend a vote change by submitting the same vote again. + +- The exact network, node, and contest remain locked while the result is unconfirmed. +- Navigation and restart preserve the operation and its target-level progress. +- If saved voting progress cannot be read, show a persistent incomplete-history notice with a retry action, preserve cached progress, and keep unknown vote locks protected. +- DET reconciles against proved current vote state without rebroadcasting. The progress drawer and Needs-attention row offer Check again, never Submit again. +- A confirmed match updates the current vote and releases the target lock. + +### DPN-012: Follow my username request to a result [Implemented] +**Persona:** Alex + +As a user waiting for a community vote, I want to see how my request is doing and what happens next so that I know whether I'm likely to get the name. + +- The Request status page shows a timeline (requested, open for other requests until, voting until, result), a weighted tally (me, other requests, lock, abstain) with Leading/Tied, and the last update time. +- Plain rules: if I'm leading at the end the name becomes mine; ties go to the most recent request; more lock votes than any request means no one can ever register the name; the fee is never returned. +- Outcomes (won, went to someone else, locked, ended without a winner) are announced once with a banner and stay in Profile for 30 days. +- Power users with a loaded node that can vote get a link to Masternodes ▸ Votes for that name. + +### DPN-013: Know from anywhere that a vote is needed [Implemented] +**Persona:** Priya + +As a masternode operator, I want the app to tell me when my nodes have contests to decide so that I never miss a deadline. + +- A top-bar chip `{count} names need your vote` appears on every screen for Power users with at least one voting node. It turns amber with the soonest deadline within 24 hours (30 minutes on Testnet). A separate chip shows votes still being checked. +- The Masternodes nav item shows a badge, and Masternodes opens on Votes when something needs a decision. +- A background refresh keeps the signal current: every 30 minutes on Mainnet and every 3 minutes on Testnet while voting nodes are loaded. + +### DPN-014: See my voting weight and remaining changes [Implemented] +**Persona:** Priya + +As a masternode operator, I want to see how much my votes matter and how many changes each node has left so that I use my votes well. + +- Cards state my node-set weight and, when it can change the leader, say so. +- Node detail lists the node's votes with changes left and its masternode-list status. A node removed from the masternode list is excluded, with the explanation that its votes don't count. + +### DPN-015: Keep working while votes are cast [Implemented] +**Persona:** Priya + +As a masternode operator, I want votes to go out in the background with per-node progress so that a large batch doesn't block the app. + +- A progress drawer shows totals (done, sending, being checked) and per node × name rows with their status and the one valid action. It persists across screens and can be collapsed. +- Only the contests and nodes being sent are locked. Everything else stays usable. +- Votes not sent before their contest ends are reported as not cast because voting ended. + +### DPN-016: Avoid a community vote when I just need a name [Implemented] +**Persona:** Alex, Jordan + +As a user, I want suggestions that need no vote so that I can get a working username right away. + +- When a name needs a vote, has open requests, or is taken, three suggestions that need no vote are offered (for example by adding a digit from 2 to 9). +- The username rules are available in a collapsed section and are consistent: 3–63 characters; letters, numbers and hyphens; no hyphen at the start or end; capital letters treated as lowercase; and which names need a vote. + +### DPN-017: Usernames stay with the identity [Implemented] +**Persona:** Alex, Priya + +As a user, I want my usernames managed on my identity, apart from masternode voting, so that I never need a governance tool to see my own name. + +- No voting controls appear in the Identities hub, and no "My usernames" list appears in voting. +- Old shortcuts to the former "My usernames" screen open the Identities hub. +- The former "Aliases" block and its disabled Make primary, Remove and Add an alias controls are removed. Adding another name uses "Get another username". + +### DPN-018: Choose which username is shown [Implemented] +**Persona:** Alex, Priya + +As a user with several usernames on one identity, I want to choose the one shown by default so that people and lists see the name I prefer. + +- Show as main (Profile ▸ Usernames row menu) is stored on this device only. Platform has no main-name concept. +- Where the identity has no Display name, the header, identity pills and switcher use the chosen name. +- Replaces the former "Set Alias" action, which wrote a username into the device-only identity name. --- @@ -1475,7 +1576,7 @@ As an expert user, I want to clear the cached SPV headers and filter data for a As a user, I want my saved settings — selected network, theme, onboarding state, and paths — to survive an app upgrade so that I do not silently relaunch into the wrong network or a reset configuration. - Settings stored before the upgrade remain applied afterward. -- The first launch after the upgrade imports the saved network, start screen, theme, onboarding state, Dash-Qt path, and the remaining toggles before the network is selected, so a testnet user is never relaunched on Mainnet. Top-up history is imported alongside the scheduled votes of DPN-009. +- The first launch after the upgrade imports the saved network, start screen, theme, onboarding state, Dash-Qt path, and the remaining toggles before the network is selected, so a testnet user is never relaunched on Mainnet. Top-up history is imported; schedules from the previous storage are reported as described in DPN-009. --- @@ -1671,11 +1772,12 @@ As a masternode operator, I want a card list of my loaded masternodes showing ty ### MN-003: Open a masternode and vote [Implemented] **Persona:** Priya -As a masternode operator, I want to open a node and vote on the DPNS contests it can vote on, so that I can fulfil my node's governance role. +As a masternode operator, I want to open a node, see its votes, and vote with just that node when needed, so that I can fulfil and check my node's governance role. -- Clicking a card opens a detail view with a keys summary, the voter identity, and a collapsible DPNS-voting section (collapsed by default, open-contest count shown in its header). -- Votes (Abstain, Lock, or a candidate) are cast inline through the existing DPNS voting backend. -- A node with no voter identity is told a voting key is required, with a way to add one, instead of a raw error. +- Clicking a card opens a detail view with the keys summary, node actions, the node's type and voting weight, its masternode-list status, and a "This node's votes" table (name, choice, changes left, deadline). +- `Vote with this node` opens Masternodes ▸ Votes with the node set limited to that node, shown on the node-set chip. No draft is carried. +- Voting uses the shared durable voting-operation path. +- When no loaded node has a voting key, Votes explains what is missing and offers `Add a voting key` (or `Load a masternode` when no node is loaded). ### MN-004: Remove a masternode [Implemented] **Persona:** Priya @@ -1741,10 +1843,11 @@ As a masternode operator, I want the Masternodes tab to reset to a clean state w ### MN-011: Refresh masternode and voting state [Implemented] **Persona:** Priya -As a masternode operator, I want a Refresh control on the Masternodes tab, so that I can pull the latest identity and DPNS-contest state without leaving the page. +As a masternode operator, I want a Refresh control on the Masternodes tab, so that I can pull the latest node identity and voting state without leaving the page. -- The card-list toolbar and a node's detail view each expose a Refresh action that re-reads the local cache immediately and dispatches a network re-fetch — one identity refresh per loaded node (or the single open node on the detail view) plus a DPNS-contest re-query so vote counts update too. -- Refresh is a no-op when no node is loaded, and the detail-view re-query is skipped for a node that has no voter identity. +- The Nodes list and a node's detail view each expose a Refresh action that re-reads the local cache immediately and dispatches one identity refresh per loaded node (or for the single open node on the detail view). +- The Nodes-list Refresh also queries contests and node vote state when at least one node is loaded. The detail-view Refresh updates only that node. Refresh is a no-op when no node is loaded. Votes has its own refresh action. +- A background refresh keeps contest and vote state current while voting nodes are loaded (see DPN-013). ### MN-012: Switch wallet/identity from the Masternodes header [Implemented] **Persona:** Priya diff --git a/docs/ux-design-patterns.md b/docs/ux-design-patterns.md index 0b465a1fc..af77e0ff3 100644 --- a/docs/ux-design-patterns.md +++ b/docs/ux-design-patterns.md @@ -83,7 +83,7 @@ Use `StyledButton` from `src/ui/components/styled.rs`. Never use bare `ui.button - Disabled fill: `DISABLED` - Hover: pointing hand cursor - Min click target: WCAG AA compliant -- Usage: `StyledButton::primary("Label").show(ui)` +- Usage: `StyledButton::new("Label").show(ui)` - **Styling**: Use `ComponentStyles` helpers -- `primary_button_fill()`, `primary_button_text()`, `primary_button_stroke()`, `secondary_button_fill()`, `secondary_button_text()`, `secondary_button_stroke()`, `danger_button_fill()`, `danger_button_text()`. Never style buttons ad-hoc at call sites. ## 4. Dialogs and Modals diff --git a/src/app.rs b/src/app.rs index 51092d509..3431577f2 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,3 +1,6 @@ +#[cfg(test)] +use crate::model::dpns_voting::{DpnsVoteOperation, DpnsVoteTargetStatus}; +use crate::ui::dpns::copy::{DPNS_ALL_VOTES_ALREADY_CAST, dpns_vote_feedback}; mod reconcilers; use reconcilers::{ AccessibilityActivator, ConnectionBanner, GateEvent, MigrationReconciler, PendingConfirmation, @@ -24,7 +27,8 @@ use crate::ui::components::secret_prompt_host::{ActivePrompt, EguiSecretPromptHo use crate::ui::components::{BannerHandle, MessageBanner, OptionBannerExt, ProgressOverlay}; use crate::ui::contracts_documents::contracts_documents_screen::DocumentQueryScreen; use crate::ui::dashpay::{DashPayScreen, DashPaySubscreen, ProfileSearchScreen}; -use crate::ui::dpns::dpns_contested_names_screen::{DPNSScreen, DPNSSubscreen}; +use crate::ui::dpns::copy::scheduled_vote_clear_feedback; +use crate::ui::dpns::dpns_contested_names_screen::DPNSScreen; use crate::ui::identity::identity_pill::shorten_id; use crate::ui::network_chooser_screen::{NetworkChooserScreen, chooser_network_label}; use crate::ui::theme::ThemeMode; @@ -61,11 +65,11 @@ use tokio::sync::mpsc as tokiompsc; /// risking a typo collision. Exposed for kittest coverage. pub const MIGRATION_RETRY_ACTION_ID: &str = "migration:retry:finish_unwire"; -/// Banner action id pushed when the user acknowledges the unreadable-vote -/// warning. Until it fires, the warning is re-raised on every launch — a -/// dismissed banner is not an acknowledgement, because the vote it names may -/// still have a live deadline. Exposed for kittest coverage. -pub const MIGRATION_VOTES_ACK_ACTION_ID: &str = "migration:ack:unreadable_votes"; +/// Banner action id pushed when the user acknowledges the warning about +/// unreadable balance top-up records. Until it fires, the warning is re-raised +/// on every launch — a dismissed banner is not an acknowledgement. Exposed for +/// kittest coverage. +pub const MIGRATION_APP_DATA_ACK_ACTION_ID: &str = "migration:ack:unreadable_app_data"; /// Banner action id pushed when the user acknowledges the unreadable-identity /// warning. Until it fires, the warning is re-raised on every launch — a @@ -75,13 +79,14 @@ pub const MIGRATION_VOTES_ACK_ACTION_ID: &str = "migration:ack:unreadable_votes" pub const MIGRATION_IDENTITIES_ACK_ACTION_ID: &str = "migration:ack:unreadable_identities"; /// Banner action id pushed when the user acknowledges the combined warning — the -/// launch where both unreadable identities and unreadable votes were left behind. +/// launch where both unreadable identities and unreadable top-up records were +/// left behind. /// One banner names both problems, so its single acknowledgement retires both /// records: re-raising either half after the user has read and dismissed the /// sentence describing it would be a notice they have already acted on. Exposed /// for kittest coverage. pub const MIGRATION_UNREADABLE_ACK_ACTION_ID: &str = - "migration:ack:unreadable_identities_and_votes"; + "migration:ack:unreadable_identities_and_app_data"; const WALLET_BACKEND_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30); const SHUTDOWN_DEADLINE_MARGIN: Duration = Duration::from_secs(5); @@ -222,6 +227,33 @@ fn show_legacy_settings_import_warning(ctx: &egui::Context, error: &impl std::fm handle.with_details(error); } +/// Startup notice for schedules left behind by an earlier version. They are +/// neither imported nor listed, so the copy says so instead of offering a review. +fn legacy_scheduled_votes_notice(network: Network) -> String { + let network = chooser_network_label(network); + format!( + "Votes you scheduled in an earlier version of the app on {network} were not carried over and will not be cast. They are not listed in this version. Open Masternodes > Votes and schedule the ones you still want." + ) +} + +fn notify_legacy_scheduled_votes(app_context: &AppContext) { + let ctx = app_context.egui_ctx(); + match app_context.legacy_scheduled_votes_notice_due() { + Ok(true) => { + MessageBanner::set_global( + ctx, + legacy_scheduled_votes_notice(app_context.network), + MessageType::Warning, + ) + .disable_auto_dismiss(); + } + Ok(false) => {} + Err(error) => { + MessageBanner::set_global(ctx, "Your previous scheduled votes could not be checked. Restart the app and try again.", MessageType::Warning).with_details(error); + } + } +} + fn legacy_settings_import_requires_network_selection( _error: &crate::backend_task::migration::legacy_settings::SettingsImportError, ) -> bool { @@ -302,6 +334,57 @@ fn clear_profile_saving_banner_after_success( } } +/// How often local state re-derives the voting attention summary. +const DPNS_ATTENTION_RECOMPUTE_INTERVAL: Duration = Duration::from_secs(60); + +/// Sweeps that re-check unconfirmed votes right after startup or vote activity. +const UNCONFIRMED_VOTE_QUICK_CHECKS: u8 = 3; + +/// How often unconfirmed votes are re-checked once the quick checks are used. +const UNCONFIRMED_VOTE_RECHECK_INTERVAL: Duration = Duration::from_secs(10 * 60); + +/// Paces the sweep's re-check of unconfirmed votes. A vote can stay +/// unconfirmed until its contest closes, so it is queried on a few sweeps and +/// then only every [`UNCONFIRMED_VOTE_RECHECK_INTERVAL`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct UnconfirmedVoteChecks { + quick_left: u8, + last_check: Option, +} + +impl Default for UnconfirmedVoteChecks { + fn default() -> Self { + Self { + quick_left: UNCONFIRMED_VOTE_QUICK_CHECKS, + last_check: None, + } + } +} + +impl UnconfirmedVoteChecks { + /// Whether the sweep starting at `now` re-checks; records the check if so. + fn take_due(&mut self, now: Instant) -> bool { + let due = self.quick_left > 0 + || self + .last_check + .is_none_or(|last| now.duration_since(last) >= UNCONFIRMED_VOTE_RECHECK_INTERVAL); + if due { + self.quick_left = self.quick_left.saturating_sub(1); + self.last_check = Some(now); + } + due + } +} + +/// Whether `result` reports vote activity that can leave a vote unconfirmed. +fn restarts_unconfirmed_vote_checks(result: &BackendTaskSuccessResult) -> bool { + matches!( + result, + BackendTaskSuccessResult::DpnsVoteOperationUpdated { .. } + | BackendTaskSuccessResult::ScheduledVotesInProgress(_) + ) +} + fn unix_time_ms() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) @@ -364,6 +447,32 @@ fn identity_hub_is_visible(selected: RootScreenType, screen_stack_is_empty: bool selected == RootScreenType::RootScreenIdentityHub && screen_stack_is_empty } +/// The root screen hosting the voting workspace (Masternodes ▸ Votes). +const VOTING_ROOT_SCREEN: RootScreenType = RootScreenType::RootScreenMasternodes; + +/// Whether a DPNS root screen is currently out of view, either because another +/// root screen is selected or because a modal covers it. Shared by success and +/// error routing so both agree on what "hidden" means. +fn dpns_screen_is_hidden( + target: RootScreenType, + selected: RootScreenType, + screen_stack_is_empty: bool, +) -> bool { + selected != target || !screen_stack_is_empty +} + +fn dpns_result_needs_hidden_route( + target: RootScreenType, + selected: RootScreenType, + screen_stack_is_empty: bool, + result: &BackendTaskSuccessResult, +) -> bool { + // The voting panel says which results it acts on, so it receives each of + // them even while its root screen is hidden. + DPNSScreen::handles_result(result) + && dpns_screen_is_hidden(target, selected, screen_stack_is_empty) +} + /// Plain, jargon-free descriptions for the SPV-sync block (Everyday-User rule: /// no "SPV"/"headers"/"masternodes"/raw heights/percentages — the jargon-free /// "Step N of 5" counter carries the granularity). Complete sentences (NFR-2). @@ -707,7 +816,7 @@ mod backend_task_join_tests { let unavailable_result = TaskError::ScheduledVoteSweepFailed { network: Network::Regtest, - source: Box::new(TaskError::ScheduledVoteResultUnavailable), + source: Box::new(TaskError::DpnsCurrentVoteUnavailable), }; assert!(!scheduled_vote_sweep_is_quiet(&unavailable_result)); @@ -756,7 +865,7 @@ pub fn migration_running_text(step: MigrationStep) -> &'static str { match step { MigrationStep::Wiring => "The app is opening your saved data.", MigrationStep::Detecting => "The app is checking your wallet data.", - MigrationStep::AppData => "The app is restoring your scheduled votes.", + MigrationStep::AppData => "The app is restoring your identity balance history.", MigrationStep::SingleKey => "The app is updating your imported keys.", MigrationStep::Shielded => "The app is verifying your shielded balance.", MigrationStep::WalletSeeds => "The app is moving your wallets into secure storage.", @@ -766,26 +875,13 @@ pub fn migration_running_text(step: MigrationStep) -> &'static str { } } -/// User-facing banner copy for a migration that finished the wallet drain but -/// left `count` undecodable scheduled votes behind. The votes stay in the -/// previous version's storage (nothing is deleted), but they will not be cast, -/// so the sentence names the one action that recovers them. No "Retry now" — -/// a corrupt row decodes no better on a second pass. Exposed for kittest -/// coverage. -pub fn migration_unreadable_votes_text(count: u32) -> String { - format!( - "Some scheduled votes from the previous version could not be read and were not carried \ - over ({count} in total). Schedule them again on the Scheduled Votes screen." - ) -} - /// User-facing banner copy for a migration that finished the wallet drain but /// could not decode `count` identities. Their keys are therefore not loaded, so /// the sentence names both the screen and the control that restore them — a user -/// who has never opened that flow cannot act on "load them again" alone. Kept -/// separate from the scheduled-votes copy because the remedy is different — load -/// an identity, not re-schedule a vote. The previous version's data is never -/// deleted, so the re-import is always possible. Exposed for kittest coverage. +/// who has never opened that flow cannot act on "load them again" alone. The +/// previous version's data is never deleted, so the re-import is always +/// possible. No "Retry now": a corrupt row decodes no better on a second pass. +/// Exposed for kittest coverage. pub fn migration_unreadable_identities_text(count: u32) -> String { format!( "Some identities from the previous version could not be read and were not carried over \ @@ -795,26 +891,9 @@ pub fn migration_unreadable_identities_text(count: u32) -> String { ) } -/// User-facing banner copy for the launch where both DET-owned passes left rows -/// behind: `identities` identities and `votes` scheduled votes could not be read. -/// One sentence per problem, each naming its own remedy — the remedies differ -/// (load an identity vs re-schedule a vote), and the identity warning recurs on -/// every launch, so it must never be the reason the deadline-critical vote notice -/// goes unseen. No "Retry now": neither corrupt row decodes better on a second -/// pass. Exposed for kittest coverage. -pub fn migration_unreadable_identities_and_votes_text(identities: u32, votes: u32) -> String { - format!( - "Some identities ({identities} in total) and some scheduled votes ({votes} in total) from \ - the previous version could not be read and were not carried over. Your previous data is \ - untouched. For a user identity, choose Load Identity on the Identities screen. For a \ - masternode or evonode identity, choose + Load on the Masternodes tab. Schedule the votes \ - again on the Scheduled Votes screen." - ) -} - /// User-facing banner copy for the rare launch where both DET-owned passes broke: /// `count` identities could not be read AND updating the rest of the previous -/// version's data (such as scheduled votes) hit a hard error. Names each problem +/// version's data (such as balance top-up records) hit a hard error. Names each problem /// in its own sentence and offers the retry the app-data half needs — the /// identity half recovers by loading the identities again. The previous version's /// data is never deleted, so both are recoverable. Exposed for kittest coverage. @@ -828,44 +907,26 @@ pub fn migration_failed_with_unreadable_identities_text(count: u32) -> String { ) } -/// User-facing banner copy for every non-empty combination of unreadable -/// legacy identity, scheduled-vote and top-up rows. -pub fn migration_unreadable_data_text(identities: u32, votes: u32, top_ups: u32) -> String { - match (identities > 0, votes > 0, top_ups > 0) { - (true, false, false) => migration_unreadable_identities_text(identities), - (false, true, false) => migration_unreadable_votes_text(votes), - (true, true, false) => { - migration_unreadable_identities_and_votes_text(identities, votes) - } - (false, false, true) => format!( +/// User-facing banner copy for every combination of unreadable legacy identity +/// and top-up rows. One sentence per problem, each naming its own remedy. +/// Exposed for kittest coverage. +pub fn migration_unreadable_data_text(identities: u32, top_ups: u32) -> String { + match (identities > 0, top_ups > 0) { + (true, false) => migration_unreadable_identities_text(identities), + (false, true) => format!( "Some records of earlier additions to identity balances from the previous version \ could not be read and were not carried over ({top_ups} in total). Check each \ identity's balance history before adding more funds." ), - (true, false, true) => format!( + (true, true) => format!( "Some identities ({identities} in total) and some records of earlier additions to \ identity balances ({top_ups} in total) from the previous version could not be read \ and were not carried over. For a user identity, choose Load Identity on the \ Identities screen. For a masternode or evonode identity, choose + Load on the \ Masternodes tab. Check each identity's balance history before adding more funds." ), - (false, true, true) => format!( - "Some scheduled votes ({votes} in total) and some records of earlier additions to \ - identity balances ({top_ups} in total) from the previous version could not be read \ - and were not carried over. Schedule the votes again on the Scheduled Votes screen. \ - Check each identity's balance history before adding more funds." - ), - (true, true, true) => format!( - "Some identities ({identities} in total), some scheduled votes ({votes} in total), \ - and some records of earlier additions to identity balances ({top_ups} in total) \ - from the previous version could not be read and were not carried over. For a user \ - identity, choose Load Identity on the Identities screen. For a masternode or \ - evonode identity, choose + Load on the Masternodes tab. Schedule the votes again on \ - the Scheduled Votes screen, and check each identity's balance history before adding \ - more funds." - ), - (false, false, false) => { - "Some data from the previous version could not be read. Check your identities, scheduled votes, and identity balance history before continuing.".to_string() + (false, false) => { + "Some data from the previous version could not be read. Check your identities and identity balance history before continuing.".to_string() } } } @@ -1210,6 +1271,17 @@ pub struct AppState { scheduled_vote_sweep_deferred_since_ms: BTreeMap, /// Networks with a scheduled-vote sweep currently running. scheduled_vote_sweeps_in_progress: BTreeSet, + /// Per-network pacing of the sweep's re-check of unconfirmed votes. + unconfirmed_vote_checks: BTreeMap, + /// Unix ms of the last background contest refresh dispatched per network. + dpns_background_refresh_dispatched_at_ms: BTreeMap, + /// Unix ms at which an incomplete background refresh is retried per network. + dpns_background_refresh_retry_at_ms: BTreeMap, + /// When the voting attention summary was last recomputed per network, so + /// nodes loaded or keys added elsewhere reach the chip, badge and timer. + dpns_attention_recomputed_at: BTreeMap, + /// The vote progress drawer shown over every screen (VOTE-FR-083). + dpns_progress_drawer: crate::ui::dpns::progress_drawer::DrawerState, /// Last recovery-sweep attempt per network, used to throttle retries while /// retaining the original eligibility cutoff. scheduled_vote_recovery_last_attempt: BTreeMap, @@ -1466,6 +1538,24 @@ impl BackendInitReason { } } +fn route_username_refresh_to_hidden_screens( + stack: &mut [Screen], + context: &BackendTaskContext, + result: Result<&BackendTaskSuccessResult, &TaskError>, +) { + let Some((_, hidden)) = stack.split_last_mut() else { + return; + }; + for screen in hidden { + if let Screen::UsernameRequestScreen(screen) = screen { + match result { + Ok(result) => screen.display_backend_task_result(context, result.clone()), + Err(error) => screen.display_backend_task_error(context, error), + } + } + } +} + impl AppState { /// Creates a new `AppState`, opening the seed vault keyless. /// @@ -1770,6 +1860,11 @@ impl AppState { last_scheduled_vote_check: Instant::now(), scheduled_vote_sweep_deferred_since_ms: BTreeMap::new(), scheduled_vote_sweeps_in_progress: BTreeSet::new(), + unconfirmed_vote_checks: BTreeMap::new(), + dpns_background_refresh_dispatched_at_ms: BTreeMap::new(), + dpns_background_refresh_retry_at_ms: BTreeMap::new(), + dpns_attention_recomputed_at: BTreeMap::new(), + dpns_progress_drawer: crate::ui::dpns::progress_drawer::DrawerState::new(unix_time_ms()), scheduled_vote_recovery_last_attempt: BTreeMap::new(), last_repaint_request: Instant::now(), subtasks, @@ -1874,11 +1969,6 @@ impl AppState { /// before the gate: an install that cannot determine its network has to /// render it to get one. fn build_main_screens(active_context: &Arc) -> BTreeMap { - let dpns_active_contests_screen = DPNSScreen::new(active_context, DPNSSubscreen::Active); - let dpns_past_contests_screen = DPNSScreen::new(active_context, DPNSSubscreen::Past); - let dpns_my_usernames_screen = DPNSScreen::new(active_context, DPNSSubscreen::Owned); - let dpns_scheduled_votes_screen = - DPNSScreen::new(active_context, DPNSSubscreen::ScheduledVotes); let transition_visualizer_screen = TransitionVisualizerScreen::new(active_context); let proof_visualizer_screen = ProofVisualizerScreen::new(active_context); let document_visualizer_screen = DocumentVisualizerScreen::new(active_context); @@ -1902,22 +1992,6 @@ impl AppState { let wallets_balances_screen = WalletsBalancesScreen::new(active_context); [ - ( - RootScreenType::RootScreenDPNSActiveContests, - Screen::DPNSScreen(dpns_active_contests_screen), - ), - ( - RootScreenType::RootScreenDPNSPastContests, - Screen::DPNSScreen(dpns_past_contests_screen), - ), - ( - RootScreenType::RootScreenDPNSOwnedNames, - Screen::DPNSScreen(dpns_my_usernames_screen), - ), - ( - RootScreenType::RootScreenDPNSScheduledVotes, - Screen::DPNSScreen(dpns_scheduled_votes_screen), - ), ( RootScreenType::RootScreenWalletsBalances, Screen::WalletsBalancesScreen(wallets_balances_screen), @@ -2095,6 +2169,7 @@ impl AppState { /// alongside it. fn finish_boot_phase(&mut self, start_spv: bool, arm_spv_block: bool) { let active_context = self.current_app_context().clone(); + notify_legacy_scheduled_votes(&active_context); let first_screen_build = self.main_screens.len() == 1 && self .main_screens @@ -2105,12 +2180,19 @@ impl AppState { } // Now that the map exists, an unregistered persisted route can finally - // be detected and replaced. + // be detected and replaced. Retired DPNS routes resolve to Votes first. + let (persisted, votes_view) = crate::ui::resolve_root_screen(self.selected_main_screen); self.selected_main_screen = initial_root_screen( - self.selected_main_screen, - self.main_screens.contains_key(&self.selected_main_screen), + persisted, + self.main_screens.contains_key(&persisted), self.network_selection_required, ); + if let Some(view) = votes_view + && self.selected_main_screen == RootScreenType::RootScreenMasternodes + && let Some(masternodes) = self.masternodes_screen_mut() + { + masternodes.open_votes(view); + } // Every root screen refreshes, not just the visible one, so screens the // user has not opened yet (e.g. DashPay Profile) already hold their data. @@ -2605,6 +2687,71 @@ impl AppState { } } + /// Called when a background contest refresh ends: if it failed, or left a + /// contest unread or a node's vote state unchecked, try again soon instead + /// of a whole interval later. + fn retry_incomplete_dpns_background_refresh(&mut self, network: Network) { + use crate::model::dpns_voting::operator::{ + background_refresh_incomplete, background_refresh_retry_delay, + }; + let Some(dispatched_at) = self + .dpns_background_refresh_dispatched_at_ms + .get(&network) + .copied() + else { + return; + }; + let completed_at = self + .network_contexts + .get(&network) + .and_then(|context| context.dpns_contests_refreshed_at_ms()); + if background_refresh_incomplete(completed_at, dispatched_at) { + let delay = u64::try_from(background_refresh_retry_delay(network).as_millis()) + .unwrap_or(u64::MAX); + self.dpns_background_refresh_retry_at_ms + .insert(network, unix_time_ms().saturating_add(delay)); + } + } + + /// Deliver a vote result to the voting panel while Masternodes is hidden. + /// While it is visible, the Masternodes screen forwards it itself. + fn route_dpns_vote_result_to_hidden_screens( + &mut self, + context: &BackendTaskContext, + result: &BackendTaskSuccessResult, + ) { + if dpns_result_needs_hidden_route( + VOTING_ROOT_SCREEN, + self.selected_main_screen, + self.screen_stack.is_empty(), + result, + ) && let Some(masternodes) = self.masternodes_screen_mut() + { + let votes = masternodes.votes_mut(); + votes.display_backend_task_result(context, result.clone()); + } + } + + fn route_dpns_vote_error_to_hidden_screens( + &mut self, + context: &BackendTaskContext, + error: &TaskError, + ) { + if !context.is_dpns_vote_task() { + return; + } + if dpns_screen_is_hidden( + VOTING_ROOT_SCREEN, + self.selected_main_screen, + self.screen_stack.is_empty(), + ) && let Some(masternodes) = self.masternodes_screen_mut() + { + let votes = masternodes.votes_mut(); + votes.display_backend_task_error(context, error); + votes.display_task_error(error); + } + } + /// Promote at most one queued passphrase request before overlay handling. fn activate_secret_prompt(&mut self, ctx: &egui::Context) { if self.active_secret_prompt.is_none() @@ -2628,6 +2775,7 @@ impl AppState { } fn set_main_screen(&mut self, root_screen_type: RootScreenType) { + let (root_screen_type, votes_view) = crate::ui::resolve_root_screen(root_screen_type); if !network_selection_allows_root(self.network_selection_required, root_screen_type) { return; } @@ -2635,11 +2783,27 @@ impl AppState { let active_screen = self.active_root_screen_mut(); active_screen.reset_to_root_view(); active_screen.refresh_on_arrival(); + if let Some(view) = votes_view + && let Some(masternodes) = self.masternodes_screen_mut() + { + masternodes.open_votes(view); + } self.current_app_context() .update_settings(root_screen_type) .ok(); } + /// The Masternodes root screen, which hosts the voting workspace. + fn masternodes_screen_mut(&mut self) -> Option<&mut crate::ui::masternodes::MasternodesScreen> { + match self + .main_screens + .get_mut(&RootScreenType::RootScreenMasternodes)? + { + Screen::MasternodesScreen(screen) => Some(screen), + _ => None, + } + } + /// Auto-start chain sync for the active context when the user opted in. /// /// Wires the wallet backend first (via the async chokepoint) so the start @@ -2967,8 +3131,21 @@ impl App for AppState { let active_context = self.current_app_context().clone(); let migration_state = active_context.migration_status().state(); - // Poll the receiver for any new task results - while let Ok(task_result) = self.task_result_receiver.try_recv() { + // Bound result work so refresh bursts cannot starve window input and painting. + let result_work_started = Instant::now(); + let mut refresh_pending = false; + for processed in 0..64 { + if processed > 0 && result_work_started.elapsed() >= Duration::from_millis(8) { + break; + } + let Ok(task_result) = self.task_result_receiver.try_recv() else { + break; + }; + // Merge adjacent cache invalidations without moving refreshes past typed results. + if refresh_pending && !matches!(task_result, TaskResult::Refresh) { + self.visible_screen_mut().refresh(); + refresh_pending = false; + } active_context .connection_status() .handle_task_result(&task_result, active_context.network); @@ -2989,8 +3166,20 @@ impl App for AppState { result: message, } => { let unboxed_message = *message; + if let BackendTaskContext::DpnsBackgroundRefresh { network } = &context { + self.retry_incomplete_dpns_background_refresh(*network); + } clear_profile_saving_banner_after_success(ctx, &context, &unboxed_message); + route_username_refresh_to_hidden_screens( + &mut self.screen_stack, + &context, + Ok(&unboxed_message), + ); self.route_identity_result_to_hidden_hub(&context, &unboxed_message); + self.route_dpns_vote_result_to_hidden_screens(&context, &unboxed_message); + if restarts_unconfirmed_vote_checks(&unboxed_message) { + self.unconfirmed_vote_checks.clear(); + } match unboxed_message { BackendTaskSuccessResult::RemovedIdentities { .. } => { deliver_identity_removal_result( @@ -3141,19 +3330,61 @@ impl App for AppState { MessageType::Success, ); } - BackendTaskSuccessResult::CastScheduledVote(ref vote) => { - let _ = self.current_app_context().mark_vote_executed( - vote.voter_id.as_slice(), - vote.contested_name.clone(), - ); - MessageBanner::set_global( - ctx, - "Successfully cast scheduled vote", - MessageType::Success, - ); - self.visible_screen_mut().display_message( - "Successfully cast scheduled vote", - MessageType::Success, + BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network, + operation_id, + } => { + let operation_context = self.network_contexts.get(&network).cloned(); + match operation_context + .as_ref() + .map(|context| context.dpns_vote_operation(operation_id)) + { + Some(Ok(Some(operation))) => { + let diagnostics = operation_context + .as_ref() + .map(|context| { + context.dpns_vote_operation_diagnostics(operation_id) + }) + .unwrap_or_default(); + let (message, message_type, keep_visible) = + dpns_vote_feedback(&operation); + let handle = + MessageBanner::set_global(ctx, message, message_type); + if !diagnostics.is_empty() { + handle.with_details(&diagnostics); + } + if keep_visible { + handle.disable_auto_dismiss(); + } + } + // A submit whose targets were all no-ops never + // persists an operation, so the skipped count is + // not recoverable here: use the plural copy. + Some(Ok(None)) => { + MessageBanner::set_global( + ctx, + DPNS_ALL_VOTES_ALREADY_CAST, + MessageType::Info, + ); + } + Some(Err(error)) => tracing::warn!( + ?error, + ?network, + operation_id = %operation_id, + "Could not load DPNS vote operation feedback" + ), + None => tracing::warn!( + ?network, + operation_id = %operation_id, + "Could not find the originating network for DPNS vote feedback" + ), + } + self.visible_screen_mut().display_backend_task_result( + &context, + BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network, + operation_id, + }, ); self.visible_screen_mut().refresh(); } @@ -3169,6 +3400,22 @@ impl App for AppState { ) { self.scheduled_vote_recovery_last_attempt.remove(&network); } + self.visible_screen_mut().display_backend_task_result( + &context, + BackendTaskSuccessResult::ScheduledVoteSweepCompleted { + network, + preserve_eligibility_since_ms, + }, + ); + } + BackendTaskSuccessResult::ScheduledVotesCleared(outcomes) => { + let (message, message_type) = scheduled_vote_clear_feedback(&outcomes); + MessageBanner::set_global(ctx, message, message_type); + self.visible_screen_mut().display_backend_task_result( + &context, + BackendTaskSuccessResult::ScheduledVotesCleared(outcomes), + ); + self.visible_screen_mut().refresh(); } BackendTaskSuccessResult::NetworkContextCreated { network, @@ -3244,6 +3491,15 @@ impl App for AppState { // Its reconciler supplies the typed details and applicable // recovery path, so suppress the duplicate generic banner. } + TaskResult::Error { + context: BackendTaskContext::DpnsBackgroundRefresh { network }, + error, + } => { + // A background refresh retries by itself; the voting + // panel's Refresh is where failures are reported. + tracing::debug!(?error, ?network, "Background contest refresh failed"); + self.retry_incomplete_dpns_background_refresh(network); + } TaskResult::Error { context, error: @@ -3255,6 +3511,7 @@ impl App for AppState { &context, &err, ); + self.route_dpns_vote_error_to_hidden_screens(&context, &err); self.visible_screen_mut() .display_backend_task_error(&context, &err); let handled = self.visible_screen_mut().display_task_error(&err); @@ -3277,7 +3534,13 @@ impl App for AppState { &context, &err, ); + route_username_refresh_to_hidden_screens( + &mut self.screen_stack, + &context, + Err(&err), + ); self.route_identity_error_to_hidden_hub(&context, &err); + self.route_dpns_vote_error_to_hidden_screens(&context, &err); let chooser_owned = network_chooser_owns_task(&context); let suppress_stale_error = !chooser_owned && !recovery_delivered @@ -3342,7 +3605,7 @@ impl App for AppState { } } TaskResult::Refresh => { - self.visible_screen_mut().refresh(); + refresh_pending = true; } TaskResult::Repaint => { // SenderAsync/SenderSync already requested a repaint when sending; avoid @@ -3351,6 +3614,13 @@ impl App for AppState { } } + if refresh_pending { + self.visible_screen_mut().refresh(); + } + if !self.task_result_receiver.is_empty() { + ctx.request_repaint(); + } + // Schedule a periodic repaint every ~1 second so timed messages update // their countdown and other periodic UI elements stay current. // Throttled so we don't re-schedule on every frame during user interaction. @@ -3360,11 +3630,11 @@ impl App for AppState { } // Periodically cast any scheduled masternode votes that have come due. - // The poll itself — the DB query, local-identity load, and per-vote + // The poll itself — the journal read, local-identity load, and per-vote // casting — runs off the UI thread in the `CastDueScheduledVotes` - // backend task; this tick only dispatches it. The DPNS Scheduled Votes - // screen learns which votes are in progress / cast via - // `display_task_result`, so a slow or failing query never stalls a frame. + // backend task; this tick only dispatches it. The voting panel learns + // which votes are in progress / cast via `display_task_result`, so a + // slow or failing query never stalls a frame. let now = Instant::now(); let network = active_context.network; if !migration_allows_scheduled_vote_sweep(migration_state.as_ref()) { @@ -3392,10 +3662,16 @@ impl App for AppState { .insert(network, now); } self.scheduled_vote_sweeps_in_progress.insert(network); + let reconcile_unconfirmed = self + .unconfirmed_vote_checks + .entry(network) + .or_default() + .take_due(now); self.handle_backend_task_with_context( BackendTask::ContestedResourceTask( ContestedResourceTask::CastDueScheduledVotes { preserve_eligibility_since_ms, + reconcile_unconfirmed, }, ), BackendTaskContext::ScheduledVoteSweep { network }, @@ -3403,6 +3679,56 @@ impl App for AppState { } } + // Prime and periodically re-derive the attention summary from local + // state (no network); the timer below depends on its voting-node count. + if self.boot.phase().renders_screens() + && !self.network_selection_required + && FeatureGate::Masternodes.is_available(&active_context) + && active_context.wallet_backend().is_ok() + && self + .dpns_attention_recomputed_at + .get(&network) + .is_none_or(|at| at.elapsed() >= DPNS_ATTENTION_RECOMPUTE_INTERVAL) + { + self.dpns_attention_recomputed_at + .insert(network, Instant::now()); + active_context.recompute_dpns_vote_attention(); + } + + // Background contest + vote-state refresh feeding the attention chip and + // the Masternodes badge (VOTE-FR-074): only while voting nodes are loaded. + if self.boot.phase().renders_screens() + && !self.network_selection_required + && FeatureGate::Masternodes.is_available(&active_context) + && active_context.dpns_vote_attention().voting_nodes > 0 + { + let now_ms = unix_time_ms(); + let retry_due = self + .dpns_background_refresh_retry_at_ms + .get(&network) + .is_some_and(|retry_at| now_ms >= *retry_at); + if retry_due + || crate::model::dpns_voting::operator::background_refresh_due( + active_context.dpns_contests_refreshed_at_ms(), + self.dpns_background_refresh_dispatched_at_ms + .get(&network) + .copied(), + now_ms, + crate::model::dpns_voting::operator::background_refresh_interval(network), + ) + { + self.dpns_background_refresh_retry_at_ms.remove(&network); + self.dpns_background_refresh_dispatched_at_ms + .insert(network, now_ms); + self.handle_backend_task_with_context( + BackendTask::ContestedResourceTask( + ContestedResourceTask::RefreshContestsInBackground, + ), + BackendTaskContext::DpnsBackgroundRefresh { network }, + ); + } + } + // Drive the SPV-sync block BEFORE claiming input and running the screen, so // a freshly-armed episode RAISES the overlay in time for THIS frame's input // claim + global render. Otherwise (raising after the claim + screen) the @@ -3488,6 +3814,15 @@ impl App for AppState { actions.push(welcome_screen.ui(ui)); } else { actions.push(self.visible_screen_mut().ui(ui)); + if !self.network_selection_required + && FeatureGate::Masternodes.is_available(&active_context) + { + actions.push(crate::ui::dpns::progress_drawer::show( + ctx, + &active_context, + &mut self.dpns_progress_drawer, + )); + } }; // A blocking progress overlay remains active underneath a secret prompt, @@ -3685,6 +4020,353 @@ impl App for AppState { #[cfg(test)] mod migration_banner_tests { use super::*; + use crate::model::dpns_voting::{DpnsVoteTarget, DpnsVoteTargetKey, VoteTiming}; + use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; + + fn feedback_operation(statuses: &[DpnsVoteTargetStatus]) -> DpnsVoteOperation { + let mut operation = AppContext::new_dpns_vote_operation( + statuses + .iter() + .enumerate() + .map(|(index, _)| DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([index as u8; 32]), + }, + voter_alias: Some("Eve".to_owned()), + contested_name: format!("contest-{index}"), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Now, + }) + .collect(), + ); + for (outcome, status) in operation.targets.iter_mut().zip(statuses) { + outcome.status = *status; + } + operation + } + + #[test] + fn review_fixes_mixed_immediate_and_scheduled_success_is_successful() { + let mut operation = feedback_operation(&[ + DpnsVoteTargetStatus::Confirmed, + DpnsVoteTargetStatus::Scheduled, + ]); + operation.targets[1].target.timing = VoteTiming::Scheduled(u64::MAX); + let (message, kind, persistent) = dpns_vote_feedback(&operation); + assert_eq!(kind, MessageType::Success); + assert_eq!(message, "Votes cast successfully: 1. Votes scheduled: 1."); + assert!(!persistent); + } + + #[test] + fn vote_feedback_uses_copy_for_each_complete_outcome() { + let cases = [ + ( + vec![DpnsVoteTargetStatus::Confirmed], + 0, + "Vote cast successfully.", + MessageType::Success, + false, + ), + ( + vec![ + DpnsVoteTargetStatus::Confirmed, + DpnsVoteTargetStatus::Confirmed, + ], + 0, + "1 node voted on 2 names.", + MessageType::Success, + false, + ), + ( + vec![ + DpnsVoteTargetStatus::Confirmed, + DpnsVoteTargetStatus::Confirmed, + ], + 1, + "1 node voted on 2 names.", + MessageType::Success, + false, + ), + ( + vec![ + DpnsVoteTargetStatus::Scheduled, + DpnsVoteTargetStatus::Scheduled, + ], + 0, + "2 votes were scheduled.", + MessageType::Success, + false, + ), + ( + vec![ + DpnsVoteTargetStatus::Scheduled, + DpnsVoteTargetStatus::Scheduled, + ], + 1, + "2 votes were scheduled.", + MessageType::Success, + false, + ), + ( + vec![DpnsVoteTargetStatus::Unconfirmed], + 0, + "The vote was submitted, but the result could not be confirmed yet. Dash Evo Tool will keep checking. Do not submit it again.", + MessageType::Warning, + true, + ), + ( + vec![ + DpnsVoteTargetStatus::Unconfirmed, + DpnsVoteTargetStatus::Unconfirmed, + ], + 0, + "2 votes were submitted, but their results could not be confirmed yet. Dash Evo Tool will keep checking. Do not submit them again.", + MessageType::Warning, + true, + ), + ( + vec![DpnsVoteTargetStatus::Rejected], + 0, + "The vote was rejected. Review the vote and try again.", + MessageType::Error, + false, + ), + ( + vec![DpnsVoteTargetStatus::FailedBeforeSubmission], + 0, + "This vote was not submitted. Check your connection and try again.", + MessageType::Error, + false, + ), + ( + Vec::new(), + 1, + "The selected node already has the requested vote. Nothing was submitted.", + MessageType::Info, + false, + ), + ( + Vec::new(), + 4, + "Every selected node already has the requested vote. Nothing was submitted.", + MessageType::Info, + false, + ), + ]; + + for (statuses, no_op_count, expected_message, expected_type, expected_visibility) in cases { + let mut operation = feedback_operation(&statuses); + operation.no_op_count = no_op_count; + + assert_eq!( + dpns_vote_feedback(&operation), + ( + expected_message.to_owned(), + expected_type, + expected_visibility + ) + ); + } + } + + /// Single and batch outcomes each get a complete sentence with matching + /// number, never a count spliced into singular or plural copy. + #[test] + fn vote_feedback_matches_singular_and_plural_copy_to_the_count() { + use DpnsVoteTargetStatus as S; + let cases = [ + (S::Scheduled, 1, "Vote scheduled successfully."), + (S::Scheduled, 3, "3 votes were scheduled."), + ( + S::Rejected, + 2, + "The votes were rejected. Review the votes and try again.", + ), + ( + S::FailedBeforeSubmission, + 2, + "These votes were not submitted. Check your connection and try again.", + ), + ( + S::NotApplied, + 2, + "The submitted votes were not applied. Review the votes and try again.", + ), + ( + S::Cancelled, + 2, + "The scheduled votes were cancelled. Nothing was submitted.", + ), + ]; + for (status, count, expected) in cases { + let (message, _, _) = dpns_vote_feedback(&feedback_operation(&vec![status; count])); + assert_eq!(message, expected, "{count} × {status:?}"); + } + } + + #[test] + fn mixed_vote_feedback_reports_partial_result_and_unconfirmed_guidance() { + let operation = feedback_operation(&[ + DpnsVoteTargetStatus::Confirmed, + DpnsVoteTargetStatus::Scheduled, + DpnsVoteTargetStatus::Unconfirmed, + DpnsVoteTargetStatus::Rejected, + DpnsVoteTargetStatus::FailedBeforeSubmission, + DpnsVoteTargetStatus::Cancelled, + DpnsVoteTargetStatus::NotApplied, + ]); + + let (message, message_type, keep_visible) = dpns_vote_feedback(&operation); + + assert_eq!(message_type, MessageType::Warning); + assert!(keep_visible); + assert_eq!( + message, + "Votes confirmed: 1. Votes scheduled: 1. Votes needing review: 3. Votes cancelled: 1. Votes still being checked: 1. Review failed votes before retrying. Wait for votes in progress or still being checked. Do not submit those votes again." + ); + } + + /// The banner must name the real cause: retrying over a good connection + /// cannot cast a vote on a closed contest or without a voting key. + #[test] + fn not_submitted_feedback_names_the_cause_and_a_possible_action() { + use crate::model::dpns_voting::DpnsVoteFailure as F; + let connection_single = "This vote was not submitted. Check your connection and try again."; + let connection_plural = + "These votes were not submitted. Check your connection and try again."; + let cases: [(&[Option], &str, MessageType); 9] = [ + ( + &[Some(F::VotingEnded)], + "This vote was not submitted because voting on the name has already ended. No further action is needed.", + MessageType::Warning, + ), + ( + &[Some(F::VotingEnded), Some(F::VotingEnded)], + "These votes were not submitted because voting on the names has already ended. No further action is needed.", + MessageType::Warning, + ), + ( + &[Some(F::VotingKeyMissing)], + "This vote was not submitted because the node's voting key is not loaded. Load the key on the Nodes tab, then cast the vote again.", + MessageType::Error, + ), + ( + &[Some(F::VotingKeyMissing), Some(F::VotingKeyMissing)], + "These votes were not submitted because the voting keys of the nodes are not loaded. Load the keys on the Nodes tab, then cast the votes again.", + MessageType::Error, + ), + ( + &[Some(F::VotingEnded), Some(F::VotingKeyMissing)], + "These votes were not submitted for different reasons. Open the vote progress list to see what to do for each vote.", + MessageType::Error, + ), + ( + &[Some(F::VotingEnded), Some(F::SubmissionFailed)], + "These votes were not submitted for different reasons. Open the vote progress list to see what to do for each vote.", + MessageType::Error, + ), + ( + &[Some(F::SubmissionFailed)], + connection_single, + MessageType::Error, + ), + ( + &[Some(F::CurrentVoteUnavailable), Some(F::SubmissionFailed)], + connection_plural, + MessageType::Error, + ), + (&[None, None], connection_plural, MessageType::Error), + ]; + for (failures, expected_message, expected_type) in cases { + let mut operation = feedback_operation(&vec![ + DpnsVoteTargetStatus::FailedBeforeSubmission; + failures.len() + ]); + for (outcome, failure) in operation.targets.iter_mut().zip(failures) { + outcome.failure = *failure; + } + assert_eq!( + dpns_vote_feedback(&operation), + (expected_message.to_owned(), expected_type, false), + "{failures:?}" + ); + } + } + + /// Counts drive which sentence is built, so no single template has to carry + /// a verb that is only correct for one of them. + /// VOTE-FR-061: confirmed plus still-checking targets read as nodes × names + /// and keep the banner up with the do-not-resubmit guidance. + #[test] + fn batch_feedback_counts_nodes_names_and_checking() { + let operation = feedback_operation(&[ + DpnsVoteTargetStatus::Confirmed, + DpnsVoteTargetStatus::Confirmed, + DpnsVoteTargetStatus::Unconfirmed, + ]); + let (message, message_type, keep_visible) = dpns_vote_feedback(&operation); + assert_eq!(message_type, MessageType::Warning); + assert!(keep_visible); + assert_eq!( + message, + "Participating nodes: 1. Names with confirmed votes: 2. Votes still being checked: 1. Dash Evo Tool will keep checking. Do not submit the pending votes again." + ); + } + + #[test] + fn mixed_vote_feedback_matches_its_verbs_to_the_counts() { + let operation = feedback_operation(&[ + DpnsVoteTargetStatus::Confirmed, + DpnsVoteTargetStatus::Confirmed, + DpnsVoteTargetStatus::Rejected, + ]); + + let (message, message_type, keep_visible) = dpns_vote_feedback(&operation); + + assert_eq!(message_type, MessageType::Warning); + assert!(!keep_visible); + assert_eq!( + message, + "Votes confirmed: 2. Votes needing review: 1. Review failed votes before retrying." + ); + } + + #[test] + fn vote_feedback_reports_mixed_failures_without_confirmations() { + let operation = feedback_operation(&[ + DpnsVoteTargetStatus::Rejected, + DpnsVoteTargetStatus::NotApplied, + ]); + + let (message, _, _) = dpns_vote_feedback(&operation); + + assert_eq!( + message, + "Votes needing review: 2. Review failed votes before retrying." + ); + } + + #[test] + fn mixed_vote_feedback_omits_empty_outcomes_and_unneeded_guidance() { + let operation = feedback_operation(&[ + DpnsVoteTargetStatus::Scheduled, + DpnsVoteTargetStatus::Submitting, + ]); + + let (message, message_type, keep_visible) = dpns_vote_feedback(&operation); + + assert_eq!(message_type, MessageType::Warning); + assert!(!keep_visible); + assert_eq!( + message, + "Votes scheduled: 1. Votes in progress: 1. Wait for votes in progress or still being checked. Do not submit those votes again." + ); + assert!(!message.contains(": 0")); + } /// A frame owns one migration snapshot even if the task publishes mid-frame. #[test] @@ -3735,12 +4417,59 @@ mod migration_banner_tests { assert!(migration_allows_scheduled_vote_sweep( &MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 1, top_ups: 1, }, )); } + #[test] + fn startup_reports_old_schedules_without_queueing_them() { + let dir = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(dir.path()); + context.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(Arc::new( + crate::wallet_backend::kv_test_support::InMemoryKv::default(), + ))); + MessageBanner::clear_all_global(context.egui_ctx()); + notify_legacy_scheduled_votes(&context); + assert!(!MessageBanner::has_global(context.egui_ctx())); + crate::database::test_helpers::create_legacy_scheduled_votes_table(&context.db).unwrap(); + crate::database::test_helpers::seed_legacy_scheduled_vote_row( + &context.db, + &[1; 32], + "alice", + "Lock", + context.network, + ) + .unwrap(); + notify_legacy_scheduled_votes(&context); + assert!(MessageBanner::has_global(context.egui_ctx())); + assert!(context.dpns_vote_operations().unwrap().is_empty()); + } + + /// Old schedules are not listed anywhere, so the notice must not promise a + /// review, and it names the network the way the rest of the app does. + #[test] + fn legacy_schedule_notice_is_truthful_about_what_the_user_can_do() { + let notice = legacy_scheduled_votes_notice(Network::Mainnet); + assert_eq!( + notice, + "Votes you scheduled in an earlier version of the app on Mainnet were not carried over and will not be cast. They are not listed in this version. Open Masternodes > Votes and schedule the ones you still want." + ); + assert!(!notice.contains("review")); + } + + /// Scheduled votes are never imported or inspected by the storage update: + /// no migration copy may claim otherwise. + #[test] + fn migration_copy_does_not_mention_scheduled_votes() { + let progress = MigrationStep::ALL.map(|step| migration_running_text(step).to_owned()); + let warnings = [(0, 0), (1, 0), (0, 2), (1, 2)] + .map(|(identities, top_ups)| migration_unreadable_data_text(identities, top_ups)); + for text in progress.iter().chain(&warnings) { + assert!(!text.to_lowercase().contains("scheduled vote"), "{text}"); + } + } + #[test] fn failed_legacy_settings_import_raises_a_sticky_warning() { use crate::backend_task::migration::legacy_settings::SettingsImportError; @@ -3854,7 +4583,7 @@ mod migration_banner_tests { #[test] fn unreadable_top_up_copy_is_actionable() { - let text = migration_unreadable_data_text(0, 0, 2); + let text = migration_unreadable_data_text(0, 2); assert!(text.contains("balance history")); assert!(text.contains("before adding more funds")); assert!(text.ends_with('.')); @@ -3904,7 +4633,7 @@ mod migration_banner_tests { fn migration_action_ids_are_distinct() { let ids = [ MIGRATION_RETRY_ACTION_ID, - MIGRATION_VOTES_ACK_ACTION_ID, + MIGRATION_APP_DATA_ACK_ACTION_ID, MIGRATION_IDENTITIES_ACK_ACTION_ID, MIGRATION_UNREADABLE_ACK_ACTION_ID, ]; @@ -4032,6 +4761,313 @@ mod contact_request_routing_tests { } } +#[cfg(test)] +mod dpns_result_routing_tests { + use super::*; + use crate::model::dpns_voting::{ + DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome, DpnsScheduledVoteKey, + DpnsVoteOperationId, + }; + + #[test] + fn username_refresh_completes_under_registration_and_after_pop() { + use crate::ui::identity::register_dpns_name_screen::{ + RegisterDpnsNameScreen, RegisterDpnsNameSource, + }; + use crate::ui::identity::username_request_screen::UsernameRequestScreen; + for fail in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let app_context = crate::context::test_support::test_app_context(dir.path()); + let mut status = + UsernameRequestScreen::new(&app_context, Identifier::from([1; 32]), "alice".into()); + let AppAction::BackendTaskWithContext { context, .. } = status.begin_refresh() else { + panic!("expected refresh dispatch"); + }; + let mut stack = vec![ + Screen::UsernameRequestScreen(status), + Screen::RegisterDpnsNameScreen(RegisterDpnsNameScreen::new( + &app_context, + RegisterDpnsNameSource::Identities, + )), + ]; + let completed = BackendTaskSuccessResult::MyUsernameRequestsRefreshed; + let error = TaskError::DataContractNotFound; + let result = if fail { Err(&error) } else { Ok(&completed) }; + route_username_refresh_to_hidden_screens( + &mut stack, + &BackendTaskContext::Unknown, + result, + ); + let Screen::UsernameRequestScreen(status) = &mut stack[0] else { + unreachable!() + }; + assert!( + matches!(status.begin_refresh(), AppAction::None), + "unrelated completions must not release the pending refresh" + ); + route_username_refresh_to_hidden_screens(&mut stack, &context, result); + stack.pop(); + let Screen::UsernameRequestScreen(status) = &mut stack[0] else { + unreachable!() + }; + assert!( + matches!( + status.begin_refresh(), + AppAction::BackendTaskWithContext { .. } + ), + "refresh must be enabled after returning to the status page" + ); + } + } + + /// A vote can stay unconfirmed until its contest closes: it is re-checked + /// on a few sweeps, then rarely, and promptly again after vote activity. + #[test] + fn unconfirmed_votes_are_rechecked_a_few_times_then_rarely() { + let start = Instant::now(); + let minute = Duration::from_secs(60); + let mut checks = UnconfirmedVoteChecks::default(); + let due: Vec = (0..15u32) + .map(|sweep| checks.take_due(start + minute * sweep)) + .collect(); + let mut expected = vec![false; 15]; + expected[..usize::from(UNCONFIRMED_VOTE_QUICK_CHECKS)].fill(true); + // The last quick check ran at minute 2; the next is one interval later. + expected[12] = true; + assert_eq!(due, expected); + + assert!(restarts_unconfirmed_vote_checks( + &BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: Network::Testnet, + operation_id: DpnsVoteOperationId::from_bytes([7; 16]), + } + )); + assert!(restarts_unconfirmed_vote_checks( + &BackendTaskSuccessResult::ScheduledVotesInProgress(Vec::new()) + )); + assert!(!restarts_unconfirmed_vote_checks( + &BackendTaskSuccessResult::ScheduledVoteSweepCompleted { + network: Network::Testnet, + preserve_eligibility_since_ms: None, + } + )); + } + + #[test] + fn voting_ui_results_route_to_the_hidden_voting_panel_only_once() { + let result = BackendTaskSuccessResult::ScheduledVoteSweepCompleted { + network: Network::Testnet, + preserve_eligibility_since_ms: None, + }; + let root = VOTING_ROOT_SCREEN; + assert_eq!(root, RootScreenType::RootScreenMasternodes); + assert!(!dpns_result_needs_hidden_route(root, root, true, &result)); + assert!(dpns_result_needs_hidden_route(root, root, false, &result)); + assert!(dpns_result_needs_hidden_route( + root, + RootScreenType::RootScreenIdentityHub, + true, + &result + )); + assert!(!dpns_result_needs_hidden_route( + root, + RootScreenType::RootScreenIdentityHub, + true, + &BackendTaskSuccessResult::None + )); + } + + #[test] + fn correlated_vote_result_routes_when_masternodes_is_hidden() { + let result = BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: Network::Testnet, + operation_id: DpnsVoteOperationId::from_bytes([7; 16]), + }; + + assert!(dpns_result_needs_hidden_route( + VOTING_ROOT_SCREEN, + RootScreenType::RootScreenWalletsBalances, + true, + &result, + )); + assert!(dpns_result_needs_hidden_route( + VOTING_ROOT_SCREEN, + VOTING_ROOT_SCREEN, + false, + &result, + )); + assert!(!dpns_result_needs_hidden_route( + VOTING_ROOT_SCREEN, + VOTING_ROOT_SCREEN, + true, + &result, + )); + } + + #[test] + fn refreshed_contests_route_when_masternodes_is_hidden() { + assert!(dpns_result_needs_hidden_route( + VOTING_ROOT_SCREEN, + RootScreenType::RootScreenWalletsBalances, + true, + &BackendTaskSuccessResult::RefreshedDpnsContests, + )); + } + + #[test] + fn scheduled_vote_sweep_completion_routes_when_masternodes_is_hidden() { + let result = BackendTaskSuccessResult::ScheduledVoteSweepCompleted { + network: Network::Testnet, + preserve_eligibility_since_ms: None, + }; + + assert!(dpns_result_needs_hidden_route( + VOTING_ROOT_SCREEN, + RootScreenType::RootScreenWalletsBalances, + true, + &result, + )); + assert!(dpns_result_needs_hidden_route( + VOTING_ROOT_SCREEN, + VOTING_ROOT_SCREEN, + false, + &result, + )); + assert!(!dpns_result_needs_hidden_route( + VOTING_ROOT_SCREEN, + VOTING_ROOT_SCREEN, + true, + &result, + )); + } + + #[test] + fn cleared_scheduled_votes_route_when_masternodes_is_hidden() { + assert!(dpns_result_needs_hidden_route( + VOTING_ROOT_SCREEN, + RootScreenType::RootScreenIdentityHub, + true, + &BackendTaskSuccessResult::ScheduledVotesCleared(Vec::new()), + )); + } + + /// The panel itself says which results it handles, so routing follows the + /// handler: every such result reaches a hidden panel, and nothing else does. + #[test] + fn hidden_routing_follows_the_results_the_voting_panel_handles() { + let hidden = |result: &BackendTaskSuccessResult| { + dpns_result_needs_hidden_route( + VOTING_ROOT_SCREEN, + RootScreenType::RootScreenIdentityHub, + true, + result, + ) + }; + for handled in [ + BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: Network::Testnet, + operation_id: DpnsVoteOperationId::from_bytes([5; 16]), + }, + BackendTaskSuccessResult::ScheduledVoteSweepCompleted { + network: Network::Testnet, + preserve_eligibility_since_ms: None, + }, + BackendTaskSuccessResult::ScheduledVotesInProgress(Vec::new()), + BackendTaskSuccessResult::ScheduledVotesCleared(Vec::new()), + BackendTaskSuccessResult::RefreshedDpnsContests, + ] { + assert!(DPNSScreen::handles_result(&handled)); + assert!(hidden(&handled)); + } + for unrelated in [ + BackendTaskSuccessResult::None, + BackendTaskSuccessResult::Refresh, + BackendTaskSuccessResult::MyUsernameRequestsRefreshed, + ] { + assert!(!DPNSScreen::handles_result(&unrelated)); + assert!(!hidden(&unrelated)); + } + } + + #[test] + fn scheduled_votes_in_progress_route_when_masternodes_is_hidden() { + assert!(dpns_result_needs_hidden_route( + VOTING_ROOT_SCREEN, + RootScreenType::RootScreenWalletsBalances, + true, + &BackendTaskSuccessResult::ScheduledVotesInProgress(Vec::new()), + )); + } + + /// The visibility rule both `route_dpns_vote_result_to_hidden_screens` and + /// `route_dpns_vote_error_to_hidden_screens` route on. + #[test] + fn the_voting_panel_is_hidden_behind_another_root_screen_or_a_modal() { + let target = VOTING_ROOT_SCREEN; + + assert!(!dpns_screen_is_hidden(target, target, true)); + assert!(dpns_screen_is_hidden(target, target, false)); + assert!(dpns_screen_is_hidden( + target, + RootScreenType::RootScreenWalletsBalances, + true + )); + } + + #[test] + fn scheduled_vote_clear_feedback_reports_removed_and_retained_counts() { + let outcome = |name: &str, disposition| DpnsScheduledVoteClearOutcome { + operation_id: None, + key: DpnsScheduledVoteKey { + network: Network::Testnet, + voter_id: Identifier::from([name.len() as u8; 32]), + contested_name: name.to_owned(), + }, + disposition, + }; + let outcomes = vec![ + outcome("removed", DpnsScheduledVoteClearDisposition::Cleared), + outcome( + "queued", + DpnsScheduledVoteClearDisposition::InFlight(DpnsVoteTargetStatus::Queued), + ), + outcome( + "submitting", + DpnsScheduledVoteClearDisposition::InFlight(DpnsVoteTargetStatus::Submitting), + ), + ]; + + assert_eq!( + scheduled_vote_clear_feedback(&outcomes), + ( + "Scheduled votes removed: 1. Votes already in progress: 2. Wait for voting to finish before trying again.".to_owned(), + MessageType::Info, + ) + ); + assert_eq!( + scheduled_vote_clear_feedback(&outcomes[..1]), + ( + "Scheduled votes removed: 1.".to_owned(), + MessageType::Success, + ) + ); + assert_eq!( + scheduled_vote_clear_feedback(&outcomes[1..]), + ( + "No scheduled votes were removed. Votes already in progress: 2. Wait for voting to finish before trying again.".to_owned(), + MessageType::Info, + ) + ); + assert_eq!( + scheduled_vote_clear_feedback(&[]), + ( + "No scheduled votes were removed.".to_owned(), + MessageType::Info + ) + ); + } +} + #[cfg(test)] mod pending_confirmation_tests { use super::*; diff --git a/src/app/reconcilers.rs b/src/app/reconcilers.rs index 21e862d3e..8555629c5 100644 --- a/src/app/reconcilers.rs +++ b/src/app/reconcilers.rs @@ -35,14 +35,14 @@ use crate::ui::components::{ }; use super::{ - AppAction, BootPhase, MAX_PENDING_WATCHES, MIGRATION_IDENTITIES_ACK_ACTION_ID, - MIGRATION_RETRY_ACTION_ID, MIGRATION_UNREADABLE_ACK_ACTION_ID, MIGRATION_VOTES_ACK_ACTION_ID, - PENDING_POLL_INTERVAL, PENDING_STALE_MESSAGE, PendingStep, SPV_CANCEL_ACTION_ID, - SPV_CANCEL_CONFIRM_ACTION_ID, SPV_CANCEL_KEEP_ACTION_ID, SPV_CANCEL_QUESTION, - SPV_CONNECTING_DESCRIPTION, SPV_SYNCING_DESCRIPTION, STORAGE_PREP_CLOSE_ACTION_ID, - STORAGE_PREP_FAILED_MESSAGE, STORAGE_PREP_PASSWORD_DESCRIPTION, STORAGE_PREP_RETRY_ACTION_ID, - STORAGE_PREP_STUCK_MESSAGE, STORAGE_PREP_STUCK_TIMEOUT, SpvBlockStep, - migration_failed_with_unreadable_identities_text, migration_running_text, + AppAction, BootPhase, MAX_PENDING_WATCHES, MIGRATION_APP_DATA_ACK_ACTION_ID, + MIGRATION_IDENTITIES_ACK_ACTION_ID, MIGRATION_RETRY_ACTION_ID, + MIGRATION_UNREADABLE_ACK_ACTION_ID, PENDING_POLL_INTERVAL, PENDING_STALE_MESSAGE, PendingStep, + SPV_CANCEL_ACTION_ID, SPV_CANCEL_CONFIRM_ACTION_ID, SPV_CANCEL_KEEP_ACTION_ID, + SPV_CANCEL_QUESTION, SPV_CONNECTING_DESCRIPTION, SPV_SYNCING_DESCRIPTION, + STORAGE_PREP_CLOSE_ACTION_ID, STORAGE_PREP_FAILED_MESSAGE, STORAGE_PREP_PASSWORD_DESCRIPTION, + STORAGE_PREP_RETRY_ACTION_ID, STORAGE_PREP_STUCK_MESSAGE, STORAGE_PREP_STUCK_TIMEOUT, + SpvBlockStep, migration_failed_with_unreadable_identities_text, migration_running_text, migration_unreadable_data_text, pending_confirmed_message, pending_step, spv_block_step, }; @@ -991,21 +991,20 @@ impl MigrationReconciler { } MigrationState::SucceededWithUnreadableData { identities, - votes, top_ups, } => { let handle = MessageBanner::set_global( ctx, - migration_unreadable_data_text(identities, votes, top_ups), + migration_unreadable_data_text(identities, top_ups), MessageType::Warning, ); handle.disable_auto_dismiss(); - let action = if identities > 0 && (votes > 0 || top_ups > 0) { + let action = if identities > 0 && top_ups > 0 { MIGRATION_UNREADABLE_ACK_ACTION_ID } else if identities > 0 { MIGRATION_IDENTITIES_ACK_ACTION_ID } else { - MIGRATION_VOTES_ACK_ACTION_ID + MIGRATION_APP_DATA_ACK_ACTION_ID }; handle.with_action("Got it", action); self.banner_handle = Some(handle); @@ -1160,7 +1159,7 @@ impl MigrationReconciler { // overwrites the stale Failed one. self.last_state = None; task = Some(BackendTask::MigrationTask(MigrationTask::FinishUnwire)); - } else if action_id == MIGRATION_VOTES_ACK_ACTION_ID { + } else if action_id == MIGRATION_APP_DATA_ACK_ACTION_ID { tracing::info!( target = "migration::cold_start", ?network, @@ -2119,7 +2118,6 @@ mod tests { let task = click_banner_action( MigrationState::SucceededWithUnreadableData { identities: 2, - votes: 0, top_ups: 0, }, "Got it", @@ -2142,8 +2140,7 @@ mod tests { let task = click_banner_action( MigrationState::SucceededWithUnreadableData { identities: 2, - votes: 3, - top_ups: 0, + top_ups: 3, }, "Got it", ); @@ -2156,15 +2153,14 @@ mod tests { ); } - /// The vote warning keeps its own acknowledgement — the identity work above + /// The top-up warning keeps its own acknowledgement — the identity work above /// must not have re-routed the sibling banner to the wrong task. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn unreadable_votes_banner_acknowledgement_routes_to_its_task() { + async fn unreadable_top_ups_banner_acknowledgement_routes_to_its_task() { let task = click_banner_action( MigrationState::SucceededWithUnreadableData { identities: 0, - votes: 2, - top_ups: 0, + top_ups: 2, }, "Got it", ); diff --git a/src/backend_task/contested_names/edit_scheduled_vote.rs b/src/backend_task/contested_names/edit_scheduled_vote.rs new file mode 100644 index 000000000..6bc782846 --- /dev/null +++ b/src/backend_task/contested_names/edit_scheduled_vote.rs @@ -0,0 +1,67 @@ +//! Validated, in-place edits of unstarted DPNS schedules. + +use crate::app::TaskResult; +use crate::backend_task::{BackendTaskSuccessResult, error::TaskError}; +use crate::context::AppContext; +use crate::model::dpns_voting::{ + DpnsScheduleEditValidationError, DpnsScheduledVoteEdit, validate_dpns_schedule_edit, +}; +use crate::utils::time::now_ms; +use dash_sdk::Sdk; + +impl AppContext { + pub(super) async fn edit_scheduled_dpns_vote( + &self, + edit: DpnsScheduledVoteEdit, + sdk: &Sdk, + sender: crate::utils::egui_mpsc::SenderAsync, + ) -> Result { + let target = self.scheduled_dpns_vote_edit_target(&edit)?; + if self.dpns_vote_poll_id(&target.contested_name)? != edit.key.vote_poll_id { + return Err(TaskError::DpnsScheduledVoteNotEditable); + } + self.checked_dpns_vote_poll(&target.contested_name, sdk) + .await?; + let normalized_name = + dash_sdk::dpp::util::strings::convert_to_homograph_safe_chars(&target.contested_name); + self.query_dpns_vote_contenders(&normalized_name, sdk, sender) + .await?; + // Identity removal takes this guard before the journal guard too. No + // network work or state-publication mutex is held while editing storage. + let lock = self.identity_record_lock(edit.key.voter_id); + let _identity_guard = lock + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if !self.is_identity_listed(&edit.key.voter_id)? + || !self + .get_local_qualified_identity(&edit.key.voter_id)? + .is_some_and(|identity| identity.can_cast_masternode_vote()) + { + return Err(TaskError::DpnsScheduledVoteVoterUnavailable); + } + let contest = self + .all_contested_names()? + .into_iter() + .find(|contest| contest.normalized_contested_name == normalized_name) + .ok_or_else(|| TaskError::VotePollNotFound { + name: target.contested_name.clone(), + })?; + let now_ms = now_ms(); + validate_dpns_schedule_edit(edit.choice, edit.unix_timestamp, now_ms, &contest).map_err( + |error| match error { + DpnsScheduleEditValidationError::Time => TaskError::DpnsScheduledVoteInvalidTime, + DpnsScheduleEditValidationError::Choice => { + TaskError::DpnsScheduledVoteInvalidChoice + } + DpnsScheduleEditValidationError::Contest => TaskError::VotePollNotFound { + name: target.contested_name.clone(), + }, + }, + )?; + let operation_id = self.edit_scheduled_dpns_vote_target(&edit)?; + Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: self.network, + operation_id, + }) + } +} diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 51d1ca3db..3a59001e4 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -1,43 +1,77 @@ +mod edit_scheduled_vote; mod query_dpns_contested_resources; mod query_dpns_vote_contenders; mod query_ending_times; +mod refresh_vote_states; mod vote_on_dpns_name; use crate::app::TaskResult; use crate::backend_task::BackendTaskSuccessResult; -use crate::backend_task::error::TaskError; -use crate::context::AppContext; +use crate::backend_task::error::{DapiAddressAvailability, TaskError}; +use crate::context::{AppContext, DpnsVoterLifecycles, MAX_CONCURRENT_DPNS_VOTERS}; +use crate::model::contested_name::ContestedName; +use crate::model::dpns_voting::{ + DpnsCurrentVoteState, DpnsScheduleEditValidationError, DpnsScheduledVoteEdit, DpnsVoteFailure, + DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVotePollAvailability, + DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + authoritative_dpns_vote_outcome, dpns_schedule_is_overdue, dpns_vote_lock_holders, + dpns_vote_poll_availability, failed_before_broadcast_outcome, unavailable_preflight_outcome, + validate_dpns_schedule_edit, validate_dpns_schedule_time, +}; use crate::model::qualified_identity::QualifiedIdentity; use crate::model::request_type::RequestType; +use crate::utils::time::now_ms; use dash_sdk::Sdk; +use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; -use dash_sdk::dpp::platform_value::string_encoding::Encoding; use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; -use dash_sdk::platform::Identifier; -use futures::future::join_all; +use dash_sdk::dpp::voting::votes::resource_vote::ResourceVote; +use dash_sdk::dpp::voting::votes::resource_vote::accessors::v0::ResourceVoteGettersV0; +use dash_sdk::drive::query::contested_resource_votes_given_by_identity_query::ContestedResourceVotesGivenByIdentityQuery; +use dash_sdk::platform::{FetchMany, Identifier}; +use futures::{StreamExt, stream}; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; -use std::time::{SystemTime, UNIX_EPOCH}; -/// Widest window past a scheduled vote's time that the sweep will still cast it. -/// Beyond this a due vote is considered stale and left for the user to reschedule -/// rather than cast late (mirrors the original 2-minute UI-poll grace). -const SCHEDULED_VOTE_MAX_LATENESS_MS: u64 = 120_000; +#[cfg(test)] +use crate::model::dpns_voting::SCHEDULED_VOTE_MAX_LATENESS_MS; #[derive(Debug, Clone, PartialEq)] pub enum ContestedResourceTask { QueryDPNSContests, - VoteOnDPNSNames(Vec<(String, ResourceVoteChoice)>, Vec), - ScheduleDPNSVotes(Vec), + /// Persist a voting preference chosen in the UI. + SaveDpnsVotingPreference(DpnsVotingPreference), + /// The same contest + vote-state refresh, run by the background timer: + /// partial failures are logged instead of reported to the user. + RefreshContestsInBackground, + /// Journal and submit a reviewed voting batch. + SubmitDpnsVoteOperation { + operation: DpnsVoteOperation, + voters: Vec, + /// Scheduled target this submission replaces, if any. + replacing_scheduled_key: Option, + network: Network, + /// Relative preset of "before the end" targets, kept for display + /// (VOTE-FR-081). + relative_labels: Option, + }, + ReconcileDpnsVoteOperation(DpnsVoteOperationId, Network), CastScheduledVote(ScheduledDPNSVote, Box), - /// Sweep the scheduled-vote table and cast every vote that is now due. + /// Sweep the vote journal and cast every scheduled vote that is now due. /// `preserve_eligibility_since_ms` keeps a vote eligible when its normal /// grace window overlapped a migration that deferred the sweep. + /// `reconcile_unconfirmed` also re-checks unconfirmed votes afterwards. CastDueScheduledVotes { preserve_eligibility_since_ms: Option, + reconcile_unconfirmed: bool, }, ClearAllScheduledVotes, ClearExecutedScheduledVotes, - DeleteScheduledVote(Identifier, String), + CancelScheduledDpnsVote { + operation_id: DpnsVoteOperationId, + key: DpnsVoteTargetKey, + }, + EditScheduledDpnsVote(DpnsScheduledVoteEdit), } #[derive(Debug, Clone, PartialEq)] @@ -49,6 +83,104 @@ pub struct ScheduledDPNSVote { pub executed_successfully: bool, } +fn classify_vote_attempt( + attempt: &Result, + timing: VoteTiming, +) -> (DpnsVoteTargetStatus, Option) { + match attempt { + Ok(vote_on_dpns_name::DpnsVoteAttempt::Confirmed) => { + (DpnsVoteTargetStatus::Confirmed, None) + } + Ok(vote_on_dpns_name::DpnsVoteAttempt::Unconfirmed(_)) => ( + DpnsVoteTargetStatus::Unconfirmed, + Some(DpnsVoteFailure::ResultUnconfirmed), + ), + Ok(vote_on_dpns_name::DpnsVoteAttempt::Rejected(_)) => ( + DpnsVoteTargetStatus::Rejected, + Some(DpnsVoteFailure::PlatformRejected), + ), + Ok(vote_on_dpns_name::DpnsVoteAttempt::FailedBeforeSubmission(_)) | Err(_) => { + failed_before_broadcast_outcome(timing) + } + } +} + +/// A voting preference the UI asks the backend to persist. +#[derive(Debug, Clone, PartialEq)] +pub enum DpnsVotingPreference { + /// Save as the default node set on this network. + NodeSet(crate::model::dpns_voting::operator::NodeSet), + /// The last-used Masternodes segment on this network. + MasternodesSegment(crate::model::dpns_voting::operator::MasternodesSegment), +} + +/// "Before the end" targets of a submitted batch and the preset they used. +#[derive(Debug, Clone, PartialEq)] +pub struct RelativeScheduleLabels { + pub preset: std::time::Duration, + pub targets: std::collections::BTreeSet, +} + +/// Attach display metadata before journal insertion so its lifecycle follows the outcome. +fn set_relative_schedule_labels( + operation: &mut DpnsVoteOperation, + labels: &RelativeScheduleLabels, +) { + let preset_ms = u64::try_from(labels.preset.as_millis()).unwrap_or(u64::MAX); + for outcome in &mut operation.targets { + if matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + && labels.targets.contains(&outcome.target.key) + { + outcome.relative_schedule_preset_ms = Some(preset_ms); + } + } +} + +/// Reject new submissions after the deadline or an authoritative terminal outcome. +fn voting_ended_outcome( + contest: Option<&ContestedName>, + now_ms: u64, +) -> Option<(DpnsVoteTargetStatus, Option)> { + (dpns_vote_poll_availability(contest) == DpnsVotePollAvailability::ProvedClosed + || contest.is_some_and(|contest| contest.end_time.is_some_and(|end| end <= now_ms))) + .then_some(( + DpnsVoteTargetStatus::FailedBeforeSubmission, + Some(DpnsVoteFailure::VotingEnded), + )) +} + +/// A missing voter keeps the pre-broadcast status rules but names the cause, +/// so the UI can offer "Add voting key" (VOTE-FR-083). +fn missing_voter_outcome( + timing: VoteTiming, +) -> (DpnsVoteTargetStatus, Option, bool) { + let (status, _) = failed_before_broadcast_outcome(timing); + ( + status, + Some(DpnsVoteFailure::VotingKeyMissing), + matches!(timing, VoteTiming::Scheduled(_)), + ) +} + +/// Only an exact current vote proves the requested choice was applied. +/// Closed polls lose their per-voter references, so absence cannot prove failure. +fn classify_reconciled_vote( + observed: Option, + requested: ResourceVoteChoice, +) -> Option { + (observed == Some(requested)).then_some(DpnsVoteTargetStatus::Confirmed) +} + +fn wrap_scheduled_vote_sweep_result( + network: Network, + result: Result, +) -> Result { + result.map_err(|source| TaskError::ScheduledVoteSweepFailed { + network, + source: Box::new(source), + }) +} + /// Logs a Drive proof-verification failure raised by a contested-resource query. /// /// No-op unless `e` is a [`dash_sdk::Error::Proof`] carrying a GroveDB proof @@ -76,223 +208,1088 @@ pub(super) fn log_contested_proof_error(e: &dash_sdk::Error, request_type: Reque } impl AppContext { + fn record_dpns_vote_diagnostic_with_dapi_context( + &self, + operation_id: DpnsVoteOperationId, + key: DpnsVoteTargetKey, + error: TaskError, + sdk: &Sdk, + ) { + let error = error.contextualize_dapi_availability(DapiAddressAvailability::from_sdk(sdk)); + self.record_dpns_vote_diagnostic(operation_id, key, error); + } + pub async fn run_contested_resource_task( self: &Arc, task: ContestedResourceTask, sdk: &Sdk, sender: crate::utils::egui_mpsc::SenderAsync, ) -> Result { + // Read before the first wait: a node removed and loaded again during + // one must not have the votes this task carries stored afterwards. + let submitted = self.dpns_voter_lifecycles(); + let is_scheduled_sweep = + matches!(&task, ContestedResourceTask::CastDueScheduledVotes { .. }); + if !is_scheduled_sweep + && !matches!( + &task, + ContestedResourceTask::QueryDPNSContests + | ContestedResourceTask::RefreshContestsInBackground + | ContestedResourceTask::SaveDpnsVotingPreference(_) + ) + { + self.ensure_dpns_vote_recovery(sdk).await?; + } match task { ContestedResourceTask::QueryDPNSContests => self - .query_dpns_contested_resources(sdk, sender) + .query_dpns_contested_resources(sdk, sender, false) .await .map(|_| BackendTaskSuccessResult::None), - ContestedResourceTask::VoteOnDPNSNames(votes, all_voters) => { - let all_voters = &all_voters; - let futures = votes - .iter() - .map(|(name, choice)| { - let cloned_sender = sender.clone(); - let app_context = self.clone(); - - async move { - let result = app_context - .vote_on_dpns_name(name, *choice, all_voters, sdk, cloned_sender) - .await; - - (name, choice, result) - } - }) - .collect::>(); - - let results = join_all(futures).await; - - let final_results = results - .into_iter() - .flat_map( - |(name, vote_choice, det_execution_result)| match det_execution_result { - Ok(BackendTaskSuccessResult::DPNSVoteResults(platform_results)) => { - platform_results - } - Err(det_err) => { - vec![( - name.clone(), - *vote_choice, - Err(std::sync::Arc::new(det_err)), - )] - } - Ok(_) => { - vec![(name.clone(), *vote_choice, Ok(()))] - } - }, - ) - .collect::>(); - - Ok(BackendTaskSuccessResult::DPNSVoteResults(final_results)) + ContestedResourceTask::RefreshContestsInBackground => self + .query_dpns_contested_resources(sdk, sender, true) + .await + .map(|_| BackendTaskSuccessResult::None), + ContestedResourceTask::SaveDpnsVotingPreference(preference) => { + match preference { + DpnsVotingPreference::NodeSet(node_set) => { + self.save_dpns_node_set(&node_set)?; + self.recompute_dpns_vote_attention(); + } + DpnsVotingPreference::MasternodesSegment(segment) => { + self.set_masternodes_last_segment(segment)?; + } + } + Ok(BackendTaskSuccessResult::None) + } + ContestedResourceTask::SubmitDpnsVoteOperation { + mut operation, + voters, + replacing_scheduled_key, + network: _, + relative_labels, + } => { + if let Some(labels) = relative_labels { + set_relative_schedule_labels(&mut operation, &labels); + } + self.execute_dpns_vote_operation_with_recovery( + operation, + voters, + replacing_scheduled_key, + &submitted, + sdk, + ) + .await } - ContestedResourceTask::ScheduleDPNSVotes(scheduled_votes) => { - self.insert_scheduled_votes(&scheduled_votes)?; - Ok(BackendTaskSuccessResult::ScheduledVotes) + ContestedResourceTask::ReconcileDpnsVoteOperation(operation_id, _) => { + self.reconcile_dpns_vote_operation(operation_id, sdk).await } ContestedResourceTask::CastScheduledVote(scheduled_vote, voter) => { - let result = self - .vote_on_dpns_name( - &scheduled_vote.contested_name, - scheduled_vote.choice, - &[*voter], + let operation = self.operation_for_scheduled_vote(&scheduled_vote, &voter)?; + self.execute_dpns_vote_operation_with_recovery( + operation, + vec![*voter], + None, + &submitted, + sdk, + ) + .await + } + ContestedResourceTask::CastDueScheduledVotes { + preserve_eligibility_since_ms, + reconcile_unconfirmed, + } => { + let result = async { + self.ensure_dpns_vote_recovery(sdk).await?; + self.cast_due_scheduled_votes( sdk, sender, + preserve_eligibility_since_ms, + reconcile_unconfirmed, ) - .await?; - confirm_scheduled_vote_result(result)?; - Ok(BackendTaskSuccessResult::CastScheduledVote(scheduled_vote)) + .await + } + .await; + wrap_scheduled_vote_sweep_result(self.network, result) } - ContestedResourceTask::CastDueScheduledVotes { - preserve_eligibility_since_ms, - } => self - .cast_due_scheduled_votes(sdk, sender, preserve_eligibility_since_ms) - .await - .map_err(|source| TaskError::ScheduledVoteSweepFailed { - network: self.network, - source: Box::new(source), - }), ContestedResourceTask::ClearAllScheduledVotes => { - self.clear_all_scheduled_votes()?; - Ok(BackendTaskSuccessResult::Refresh) + let outcomes = self.clear_all_scheduled_dpns_votes()?; + Ok(BackendTaskSuccessResult::ScheduledVotesCleared(outcomes)) } ContestedResourceTask::ClearExecutedScheduledVotes => { self.clear_executed_scheduled_votes()?; Ok(BackendTaskSuccessResult::Refresh) } - ContestedResourceTask::DeleteScheduledVote(voter_id, contested_name) => { - self.delete_scheduled_vote(voter_id.as_slice(), &contested_name)?; + ContestedResourceTask::CancelScheduledDpnsVote { operation_id, key } => { + self.cancel_scheduled_dpns_vote_target(operation_id, &key)?; Ok(BackendTaskSuccessResult::Refresh) } + ContestedResourceTask::EditScheduledDpnsVote(edit) => { + self.edit_scheduled_dpns_vote(edit, sdk, sender).await + } } } - /// Cast every scheduled vote that is now due, off the UI thread. - /// - /// Queries the scheduled-vote table, keeps the votes whose time has arrived - /// (and are not already executed or stale beyond - /// [`SCHEDULED_VOTE_MAX_LATENESS_MS`]), pairs each with its local voting - /// identity, and casts them independently so one failure cannot abort the - /// rest. Emits [`ScheduledVotesInProgress`] before casting and a - /// [`CastScheduledVote`] per success so the Scheduled Votes screen can - /// reflect progress via `display_task_result`. - /// - /// [`ScheduledVotesInProgress`]: BackendTaskSuccessResult::ScheduledVotesInProgress - /// [`CastScheduledVote`]: BackendTaskSuccessResult::CastScheduledVote - async fn cast_due_scheduled_votes( + async fn ensure_dpns_vote_recovery(self: &Arc, sdk: &Sdk) -> Result<(), TaskError> { + let mut recovered = self.dpns_vote_recovery.lock().await; + if recovered.initialized { + for (operation_id, keys) in recovered.pending.clone() { + self.recover_idle_dpns_vote_targets(operation_id, &keys) + .await?; + recovered.pending.remove(&operation_id); + } + return Ok(()); + } + self.recover_interrupted_dpns_vote_operations()?; + let queued = self + .dpns_vote_operations()? + .into_iter() + .filter(|operation| { + operation + .targets + .iter() + .any(|outcome| outcome.status == DpnsVoteTargetStatus::Queued) + }) + .collect::>(); + if !queued.is_empty() { + let voters = self.load_local_voting_identities()?; + for operation in queued { + self.execute_dpns_vote_operation(operation, voters.clone(), None, sdk) + .await?; + } + } + recovered.initialized = true; + Ok(()) + } + + fn dpns_vote_target( + &self, + voter: &QualifiedIdentity, + name: &str, + choice: ResourceVoteChoice, + timing: VoteTiming, + require_current_state: bool, + ) -> Result { + let voter_id = voter.identity.id(); + let vote_poll_id = self.dpns_vote_poll_id(name)?; + let current_choice = match self.dpns_current_vote_state(voter_id, vote_poll_id)? { + DpnsCurrentVoteState::Available(choice) => choice, + DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable + if require_current_state => + { + return Err(TaskError::DpnsCurrentVoteUnavailable); + } + DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable => None, + }; + Ok(DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: self.network, + voter_id, + vote_poll_id, + }, + voter_alias: voter.alias.clone(), + contested_name: name.to_owned(), + requested_choice: choice, + current_choice, + timing, + }) + } + + fn operation_for_scheduled_vote( + &self, + scheduled_vote: &ScheduledDPNSVote, + voter: &QualifiedIdentity, + ) -> Result { + let key = DpnsVoteTargetKey { + network: self.network, + voter_id: scheduled_vote.voter_id, + vote_poll_id: self.dpns_vote_poll_id(&scheduled_vote.contested_name)?, + }; + let operations = self.dpns_vote_operations()?; + let outcome = preferred_outcome_for_scheduled_key(&operations, &key)? + .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; + match outcome.status { + DpnsVoteTargetStatus::Scheduled => { + if !self + .queue_scheduled_dpns_vote_target(outcome.operation_id, &outcome.target.key)? + { + return Err(TaskError::DpnsVoteTargetBusy); + } + let mut operation = self + .dpns_vote_operation(outcome.operation_id)? + .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; + operation.targets.retain(|target| target.target.key == key); + return Ok(operation); + } + DpnsVoteTargetStatus::Unconfirmed + | DpnsVoteTargetStatus::Queued + | DpnsVoteTargetStatus::Submitting + | DpnsVoteTargetStatus::Confirming => { + return Err(TaskError::DpnsVoteTargetBusy); + } + DpnsVoteTargetStatus::Confirmed + | DpnsVoteTargetStatus::Rejected + | DpnsVoteTargetStatus::FailedBeforeSubmission + | DpnsVoteTargetStatus::Cancelled + | DpnsVoteTargetStatus::NotApplied => { + // An explicit Cast now action is a deliberate retry and + // may create a new operation below. + } + } + + let target = self.dpns_vote_target( + voter, + &scheduled_vote.contested_name, + scheduled_vote.choice, + VoteTiming::Scheduled(scheduled_vote.unix_timestamp), + false, + )?; + // An explicit retry must reach fresh preflight even if the cached + // choice matches. Preflight records an already-satisfied target durably. + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + current_choice: None, + ..target + }]); + for outcome in &mut operation.targets { + outcome.status = DpnsVoteTargetStatus::Queued; + } + Ok(operation) + } + + fn revalidate_dpns_vote_preflight( + &self, + operation: &mut DpnsVoteOperation, + was_persisted: bool, + key: &DpnsVoteTargetKey, + state: DpnsCurrentVoteState, + ) -> Result<(), TaskError> { + if was_persisted { + self.revalidate_queued_dpns_vote_target(operation.id, key, state)?; + return Ok(()); + } + let Some(outcome) = operation + .targets + .iter_mut() + .find(|outcome| outcome.target.key == *key) + else { + return Ok(()); + }; + match state { + DpnsCurrentVoteState::Available(current) => { + if outcome.target.timing == VoteTiming::Now + && outcome.target.current_choice.is_none() + && current.is_some() + && current != Some(outcome.target.requested_choice) + { + return Err(TaskError::DpnsVoteReviewRequired); + } + outcome.target.current_choice = current; + if current == Some(outcome.target.requested_choice) { + outcome.status = DpnsVoteTargetStatus::Confirmed; + outcome.failure = None; + } + } + DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable => { + (outcome.status, outcome.failure) = + unavailable_preflight_outcome(outcome.target.timing); + } + } + Ok(()) + } + + fn validate_new_dpns_schedules(&self, targets: &[DpnsVoteTarget]) -> Result<(), TaskError> { + if targets.is_empty() { + return Ok(()); + } + let now_ms = now_ms(); + // Reject invalid times even when the contest has not been cached yet. + for target in targets { + if let VoteTiming::Scheduled(timestamp) = target.timing { + validate_dpns_schedule_time(timestamp, now_ms, None) + .map_err(|_| TaskError::DpnsScheduledVoteInvalidTime)?; + } + } + let contests = self.all_contested_names()?; + for target in targets { + let VoteTiming::Scheduled(timestamp) = target.timing else { + continue; + }; + let contest = contests + .iter() + .find(|contest| contest.normalized_contested_name == target.contested_name) + .ok_or_else(|| TaskError::VotePollNotFound { + name: target.contested_name.clone(), + })?; + validate_dpns_schedule_edit(target.requested_choice, timestamp, now_ms, contest) + .map_err(|error| match error { + DpnsScheduleEditValidationError::Time => { + TaskError::DpnsScheduledVoteInvalidTime + } + DpnsScheduleEditValidationError::Choice => { + TaskError::DpnsScheduledVoteInvalidChoice + } + DpnsScheduleEditValidationError::Contest => TaskError::VotePollNotFound { + name: target.contested_name.clone(), + }, + })?; + } + Ok(()) + } + + /// Execute an operation handed over with no wait since it was submitted. + async fn execute_dpns_vote_operation( self: &Arc, + operation: DpnsVoteOperation, + voters: Vec, + replacing_scheduled_key: Option, + sdk: &Sdk, + ) -> Result { + let submitted = self.dpns_voter_lifecycles(); + self.execute_submitted_dpns_vote_operation( + operation, + voters, + replacing_scheduled_key, + &submitted, + sdk, + ) + .await + } + + /// Preflight, store and send an operation. `submitted` is + /// [`Self::dpns_voter_lifecycles`] as read when the work was submitted. + async fn execute_submitted_dpns_vote_operation( + self: &Arc, + mut operation: DpnsVoteOperation, + voters: Vec, + replacing_scheduled_key: Option, + submitted: &DpnsVoterLifecycles, sdk: &Sdk, - sender: crate::utils::egui_mpsc::SenderAsync, - preserve_eligibility_since_ms: Option, ) -> Result { - let now_ms = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_millis() as u64) - .unwrap_or(0); - let due: Vec = self - .get_scheduled_votes()? + if operation.targets.is_empty() { + return Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: self.network, + operation_id: operation.id, + }); + } + let requested_keys: BTreeSet<_> = operation + .targets + .iter() + .map(|outcome| outcome.target.key.clone()) + .collect(); + let was_persisted = self.dpns_vote_operation(operation.id)?.is_some(); + let new_schedules = operation + .targets + .iter() + .filter(|outcome| !was_persisted && outcome.status == DpnsVoteTargetStatus::Scheduled) + .map(|outcome| outcome.target.clone()) + .collect::>(); + self.validate_new_dpns_schedules(&new_schedules)?; + let mut preflight_error = None; + if operation + .targets + .iter() + .any(|outcome| outcome.status == DpnsVoteTargetStatus::Queued) + { + // A fresh proved snapshot is a submission precondition. This also + // prevents a due schedule from replaying a vote already observed. + let queued_keys = operation + .targets + .iter() + .filter(|outcome| outcome.status == DpnsVoteTargetStatus::Queued) + .map(|outcome| outcome.target.key.clone()) + .collect::>(); + let queued_voters = queued_keys.iter().map(|key| key.voter_id).collect(); + let refreshed = self + .refresh_dpns_vote_states_for(sdk, &queued_voters) + .await + .map_err(Arc::new); + for key in queued_keys { + let snapshot = match &refreshed { + Ok(results) => results + .get(&key.voter_id) + .ok_or_else(|| Arc::new(TaskError::DpnsCurrentVoteUnavailable)) + .and_then(|result| result.as_ref().map_err(Arc::clone)), + Err(error) => Err(Arc::clone(error)), + }; + let validation = self.with_dpns_vote_preflight_state( + key.voter_id, + key.vote_poll_id, + snapshot, + |state| { + matches!(state, DpnsCurrentVoteState::Available(_)).then(|| { + self.revalidate_dpns_vote_preflight( + &mut operation, + was_persisted, + &key, + state, + ) + }) + }, + ); + let source = match validation { + Ok(Some(result)) => { + result?; + continue; + } + Ok(None) => Arc::new(TaskError::DpnsCurrentVoteUnavailable), + Err(source) => source, + }; + self.record_dpns_vote_diagnostic_with_dapi_context( + operation.id, + key.clone(), + TaskError::DpnsVotePreflightFailed { + source: Arc::clone(&source), + }, + sdk, + ); + self.revalidate_dpns_vote_preflight( + &mut operation, + was_persisted, + &key, + DpnsCurrentVoteState::Unavailable, + )?; + // Scheduled preflight failures remain retryable and must reach the + // scheduler. Immediate failures are durable per-target outcomes; + // report the batch summary, including any successful siblings. + if operation.outcome(&key).is_some_and(|outcome| { + matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + }) { + preflight_error.get_or_insert(source); + } + } + } + + if was_persisted { + operation = self + .dpns_vote_operation(operation.id)? + .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; + operation + .targets + .retain(|outcome| requested_keys.contains(&outcome.target.key)); + } else { + self.validate_new_dpns_schedules(&new_schedules)?; + self.admit_dpns_vote_operation( + &mut operation, + replacing_scheduled_key.as_ref(), + submitted, + )?; + // A replacement comes back as the whole stored operation; only the + // requested targets belong to this run. + operation + .targets + .retain(|outcome| requested_keys.contains(&outcome.target.key)); + } + + let voters_by_id: BTreeMap = voters .into_iter() - .filter(|vote| { - scheduled_vote_is_due( - vote.unix_timestamp, - vote.executed_successfully, - now_ms, - preserve_eligibility_since_ms, - ) + .map(|voter| (voter.identity.id(), voter)) + .collect(); + // An unreadable cache leaves every contest "may accept": Platform still + // rejects a vote on a closed poll, so this check only saves a broadcast. + let contests: Arc> = Arc::new( + self.all_contested_names() + .inspect_err(|error| { + tracing::debug!( + ?error, + "Contest cache unreadable; skipping the voting-ended check" + ); + }) + .unwrap_or_default() + .into_iter() + .map(|contest| (contest.normalized_contested_name.clone(), contest)) + .collect(), + ); + let mut groups: BTreeMap> = BTreeMap::new(); + for outcome in operation + .targets + .iter() + .filter(|outcome| outcome.status == DpnsVoteTargetStatus::Queued) + { + groups + .entry(outcome.target.key.voter_id) + .or_default() + .push(outcome.target.clone()); + } + + stream::iter(groups) + .map(|(voter_id, targets)| { + let app_context = Arc::clone(self); + let sdk = sdk.clone(); + let voter = voters_by_id.get(&voter_id).cloned(); + let operation_id = operation.id; + let contests = Arc::clone(&contests); + async move { + // Every claim, including missing-voter cleanup, shares recovery's gate. + let _dispatch_guard = app_context.dpns_vote_dispatch.acquire(voter_id).await?; + let Some(voter) = voter else { + let mut scheduled_voter_missing = false; + for target in targets { + if app_context.claim_dpns_vote_target(operation_id, &target.key)? { + let (status, failure, retryable) = + missing_voter_outcome(target.timing); + app_context.update_dpns_vote_target( + operation_id, + &target.key, + status, + failure, + )?; + scheduled_voter_missing |= retryable; + } + } + if scheduled_voter_missing { + return Err(TaskError::IdentityNotFoundLocally); + } + return Ok::<(), TaskError>(()); + }; + + // One voter's targets are deliberately sequential: PutVote + // obtains and consumes the same masternode nonce. + for target in targets { + if !app_context.claim_dpns_vote_target(operation_id, &target.key)? { + continue; + } + if let Some((status, failure)) = + voting_ended_outcome(contests.get(&target.contested_name), now_ms()) + { + tracing::info!( + voter_id = %target.key.voter_id, + contested_name = %target.contested_name, + "DPNS vote not sent because voting on the name has ended" + ); + app_context.update_dpns_vote_target( + operation_id, + &target.key, + status, + failure, + )?; + continue; + } + let attempt = app_context + .submit_dpns_vote( + operation_id, + &target.key, + &target.contested_name, + target.requested_choice, + &voter, + &sdk, + ) + .await; + let (status, failure) = classify_vote_attempt(&attempt, target.timing); + let confirmed = status == DpnsVoteTargetStatus::Confirmed; + let mut retryable_scheduled_error = None; + match attempt { + // Nothing to log or record for a confirmed vote. + Ok(vote_on_dpns_name::DpnsVoteAttempt::Confirmed) => {} + Ok(vote_on_dpns_name::DpnsVoteAttempt::Unconfirmed(error)) => { + tracing::warn!( + ?error, + voter_id = %target.key.voter_id, + contested_name = %target.contested_name, + "DPNS vote was submitted but remains unconfirmed" + ); + app_context.record_dpns_vote_diagnostic_with_dapi_context( + operation_id, + target.key.clone(), + error, + &sdk, + ); + } + Ok(vote_on_dpns_name::DpnsVoteAttempt::Rejected(error)) => { + tracing::warn!( + ?error, + voter_id = %target.key.voter_id, + contested_name = %target.contested_name, + "Platform rejected a DPNS vote" + ); + app_context.record_dpns_vote_diagnostic_with_dapi_context( + operation_id, + target.key.clone(), + error, + &sdk, + ); + } + Ok(vote_on_dpns_name::DpnsVoteAttempt::FailedBeforeSubmission( + error, + )) => { + tracing::warn!( + ?error, + voter_id = %target.key.voter_id, + contested_name = %target.contested_name, + "DPNS vote failed before it reached the network" + ); + if matches!(target.timing, VoteTiming::Scheduled(_)) { + retryable_scheduled_error = Some(error); + } else { + app_context.record_dpns_vote_diagnostic_with_dapi_context( + operation_id, + target.key.clone(), + error, + &sdk, + ); + } + } + Err(error) => { + tracing::warn!( + ?error, + voter_id = %target.key.voter_id, + contested_name = %target.contested_name, + "DPNS vote failed before a confirmed submission" + ); + if matches!(target.timing, VoteTiming::Scheduled(_)) { + retryable_scheduled_error = Some(error); + } else { + app_context.record_dpns_vote_diagnostic_with_dapi_context( + operation_id, + target.key.clone(), + error, + &sdk, + ); + } + } + } + app_context.update_dpns_vote_target( + operation_id, + &target.key, + status, + failure, + )?; + if confirmed { + app_context.cache_confirmed_dpns_vote( + target.key.voter_id, + target.key.vote_poll_id, + target.requested_choice, + )?; + } + if let Some(error) = retryable_scheduled_error { + return Err(error); + } + } + Ok(()) + } }) + .buffer_unordered(MAX_CONCURRENT_DPNS_VOTERS) + .collect::>>() + .await + .into_iter() + .collect::, _>>()?; + + if let Some(source) = preflight_error { + return Err(TaskError::DpnsVotePreflightFailed { source }); + } + + Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: self.network, + operation_id: operation.id, + }) + } + + async fn execute_dpns_vote_operation_with_recovery( + self: &Arc, + operation: DpnsVoteOperation, + voters: Vec, + replacing_scheduled_key: Option, + submitted: &DpnsVoterLifecycles, + sdk: &Sdk, + ) -> Result { + let operation_id = operation.id; + let keys = operation + .targets + .iter() + .map(|outcome| outcome.target.key.clone()) .collect(); - if due.is_empty() { - return Ok(BackendTaskSuccessResult::ScheduledVoteSweepCompleted { - network: self.network, - preserve_eligibility_since_ms, - }); + let result = self + .execute_submitted_dpns_vote_operation( + operation, + voters, + replacing_scheduled_key, + submitted, + sdk, + ) + .await; + if let Err(error) = &result { + self.recover_failed_dpns_vote_operation(operation_id, &keys, error) + .await; } + result + } - let voters = self.load_local_voting_identities()?; - let mut castable: Vec<(ScheduledDPNSVote, QualifiedIdentity)> = Vec::new(); - let mut first_error = None; - for vote in due { - match voters.iter().find(|i| i.identity.id() == vote.voter_id) { - Some(voter) => castable.push((vote, voter.clone())), - None => { + /// Cleanup cannot release a claim while an executor still owns its voter gate. + /// Acquire only one gate at a time, then the journal lock; never the reverse. + async fn recover_idle_dpns_vote_targets( + &self, + operation_id: DpnsVoteOperationId, + keys: &BTreeSet, + ) -> Result<(), TaskError> { + let voters: BTreeSet<_> = keys.iter().map(|key| key.voter_id).collect(); + for voter_id in voters { + let _dispatch_guard = self.dpns_vote_dispatch.acquire(voter_id).await?; + let voter_keys = keys + .iter() + .filter(|key| key.voter_id == voter_id) + .cloned() + .collect(); + self.recover_interrupted_dpns_vote_operation(operation_id, &voter_keys)?; + } + Ok(()) + } + + async fn recover_failed_dpns_vote_operation( + &self, + operation_id: DpnsVoteOperationId, + keys: &BTreeSet, + original_error: &TaskError, + ) { + if let Err(recovery_error) = self + .recover_idle_dpns_vote_targets(operation_id, keys) + .await + { + tracing::error!( + error = %recovery_error, + original_error = %original_error, + operation_id = %operation_id, + "Failed to persist recovery for an interrupted DPNS vote operation" + ); + self.dpns_vote_recovery + .lock() + .await + .pending + .entry(operation_id) + .or_default() + .extend(keys.iter().cloned()); + } + } + + async fn reconcile_dpns_vote_operation( + &self, + operation_id: DpnsVoteOperationId, + sdk: &Sdk, + ) -> Result { + if let Some(operation) = self.dpns_vote_operation(operation_id)? { + self.reconcile_unconfirmed_dpns_vote_targets(&operation, |_| true, sdk) + .await?; + } + Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: self.network, + operation_id, + }) + } + + /// Ask Platform about each `selected` unconfirmed target of `operation`. + /// Returns whether any of them was confirmed. + async fn reconcile_unconfirmed_dpns_vote_targets( + &self, + operation: &DpnsVoteOperation, + selected: impl Fn(&DpnsVoteOutcome) -> bool, + sdk: &Sdk, + ) -> Result { + let operation_id = operation.id; + let mut confirmed_any = false; + for outcome in operation.targets.iter().filter(|outcome| { + outcome.status == DpnsVoteTargetStatus::Unconfirmed && selected(outcome) + }) { + let poll_id = outcome.target.key.vote_poll_id; + let query = ContestedResourceVotesGivenByIdentityQuery { + identity_id: outcome.target.key.voter_id, + offset: None, + limit: Some(1), + start_at: Some((poll_id.to_buffer(), true)), + order_ascending: true, + }; + match ResourceVote::fetch_many(sdk, query).await { + Ok(votes) => { + let observed = votes + .get(&poll_id) + .and_then(Option::as_ref) + .map(ResourceVoteGettersV0::resource_vote_choice); + let status = + classify_reconciled_vote(observed, outcome.target.requested_choice) + .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); + if !self.update_dpns_vote_reconciliation( + operation_id, + &outcome.target.key, + outcome.target.current_choice, + observed, + status, + )? { + continue; + } + if status != DpnsVoteTargetStatus::Confirmed { + continue; + } + confirmed_any = true; + self.cache_confirmed_dpns_vote( + outcome.target.key.voter_id, + poll_id, + outcome.target.requested_choice, + )?; + } + Err(error) => { + let error = TaskError::from(error); tracing::warn!( - contested_name = %vote.contested_name, - "No local voting identity for a scheduled vote; skipping it" + ?error, + operation_id = %operation_id, + voter_id = %outcome.target.key.voter_id, + contested_name = %outcome.target.contested_name, + "Could not reconcile an unconfirmed DPNS vote" + ); + self.record_dpns_vote_diagnostic_with_dapi_context( + operation_id, + outcome.target.key.clone(), + error, + sdk, ); - first_error.get_or_insert_with(|| TaskError::NoVotingIdentity { - identity_id: vote.voter_id.to_string(Encoding::Base58), - }); } } } - if castable.is_empty() { - return Err(first_error.unwrap_or(TaskError::ScheduledVoteResultUnavailable)); + Ok(confirmed_any) + } + + /// The sweep's re-check of unconfirmed votes. An operation is reported to + /// the UI only when one of its votes was confirmed, so an unchanged result + /// never raises its message again. + /// + /// A decided contest has dropped its per-voter vote references, so its + /// targets can no longer be confirmed and are not queried. + async fn reconcile_unconfirmed_dpns_votes( + &self, + sdk: &Sdk, + sender: &crate::utils::egui_mpsc::SenderAsync, + ) -> Result<(), TaskError> { + let operations: Vec<_> = self + .dpns_vote_operations()? + .into_iter() + .filter(|operation| { + operation + .targets + .iter() + .any(|outcome| outcome.status == DpnsVoteTargetStatus::Unconfirmed) + }) + .collect(); + if operations.is_empty() { + return Ok(()); + } + // An unreadable cache proves nothing closed, so every target is queried. + let closed: BTreeSet = self + .all_contested_names() + .inspect_err(|error| { + tracing::debug!( + ?error, + "Contest cache unreadable; re-checking every unconfirmed DPNS vote" + ); + }) + .unwrap_or_default() + .into_iter() + .filter(|contest| { + dpns_vote_poll_availability(Some(contest)) == DpnsVotePollAvailability::ProvedClosed + }) + .map(|contest| contest.normalized_contested_name) + .collect(); + for operation in operations { + let confirmed = self + .reconcile_unconfirmed_dpns_vote_targets( + &operation, + |outcome| !closed.contains(&outcome.target.contested_name), + sdk, + ) + .await?; + if confirmed { + let _ = sender + .send(TaskResult::unattributed_success( + BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: self.network, + operation_id: operation.id, + }, + )) + .await; + } + } + Ok(()) + } + + /// One scheduled-vote sweep: admit due schedules durably, execute them, + /// then run `reconcile`, so unrelated unconfirmed votes never delay a due + /// vote. Schedules that came due meanwhile are admitted at the end, so a + /// long sweep cannot turn them stale; targets this sweep already tried + /// stay under the next sweep's lateness rule. + async fn sweep_due_scheduled_votes( + &self, + clock: impl Fn() -> u64, + preserve_eligibility_since_ms: Option, + execute: impl FnOnce(Vec, Vec) -> E, + reconcile: impl std::future::Future>, + ) -> Result<(), TaskError> + where + E: std::future::Future>, + { + let started_at = clock(); + let eligibility_cutoff = preserve_eligibility_since_ms.unwrap_or(started_at); + // Persist admissions before any await so an error or interruption + // cannot turn an eligible target into a stale schedule. + let (due_operations, in_progress) = + self.queue_due_scheduled_votes_at(started_at, eligibility_cutoff, &BTreeMap::new())?; + let attempted: BTreeMap> = due_operations + .iter() + .map(|operation| { + let keys = operation + .targets + .iter() + .filter(|outcome| outcome.status == DpnsVoteTargetStatus::Queued) + .map(|outcome| outcome.target.key.clone()) + .collect(); + (operation.id, keys) + }) + .collect(); + let executed = execute(due_operations, in_progress).await; + let reconciled = reconcile.await; + let admitted_late = + self.queue_due_scheduled_votes_at(clock(), eligibility_cutoff, &attempted); + executed?; + reconciled?; + admitted_late?; + Ok(()) + } + + /// Queue every due scheduled target, except those in `already_attempted`. + fn queue_due_scheduled_votes_at( + &self, + now_ms: u64, + eligibility_cutoff: u64, + already_attempted: &BTreeMap>, + ) -> Result<(Vec, Vec), TaskError> { + let mut due_operations = Vec::new(); + let mut in_progress = Vec::new(); + for mut operation in self.dpns_vote_operations()? { + let attempted = already_attempted.get(&operation.id); + let mut due = false; + for outcome in &mut operation.targets { + let VoteTiming::Scheduled(scheduled_at) = outcome.target.timing else { + continue; + }; + if attempted.is_some_and(|keys| keys.contains(&outcome.target.key)) + || !scheduled_target_should_execute( + outcome.status, + scheduled_at, + now_ms, + Some(eligibility_cutoff), + ) + { + continue; + } + if outcome.status == DpnsVoteTargetStatus::Scheduled + && !self.queue_scheduled_dpns_vote_target(operation.id, &outcome.target.key)? + { + continue; + } + outcome.status = DpnsVoteTargetStatus::Queued; + due = true; + in_progress.push(ScheduledDPNSVote { + contested_name: outcome.target.contested_name.clone(), + voter_id: outcome.target.key.voter_id, + choice: outcome.target.requested_choice, + unix_timestamp: scheduled_at, + executed_successfully: false, + }); + } + if due { + due_operations.push(operation); + } } + Ok((due_operations, in_progress)) + } + + /// Execute each admitted scheduled operation, then re-check unconfirmed + /// votes when `reconcile_unconfirmed` is set. Emits progress before + /// execution; terminal results remain in the journal. + async fn cast_due_scheduled_votes( + self: &Arc, + sdk: &Sdk, + sender: crate::utils::egui_mpsc::SenderAsync, + preserve_eligibility_since_ms: Option, + reconcile_unconfirmed: bool, + ) -> Result { + self.sweep_due_scheduled_votes( + now_ms, + preserve_eligibility_since_ms, + |due_operations, in_progress| { + self.execute_due_scheduled_votes(due_operations, in_progress, sdk, &sender) + }, + async { + if reconcile_unconfirmed { + self.reconcile_unconfirmed_dpns_votes(sdk, &sender).await + } else { + Ok(()) + } + }, + ) + .await?; + Ok(BackendTaskSuccessResult::ScheduledVoteSweepCompleted { + network: self.network, + preserve_eligibility_since_ms, + }) + } - // Tell the Scheduled Votes screen which votes are now in flight. - let in_progress = castable.iter().map(|(v, _)| v.clone()).collect(); + async fn execute_due_scheduled_votes( + self: &Arc, + due_operations: Vec, + in_progress: Vec, + sdk: &Sdk, + sender: &crate::utils::egui_mpsc::SenderAsync, + ) -> Result<(), TaskError> { + if due_operations.is_empty() { + return Ok(()); + } + let voters = self.load_local_voting_identities()?; + // Tell the Scheduled view which votes are now in flight. let _ = sender .send(TaskResult::unattributed_success( BackendTaskSuccessResult::ScheduledVotesInProgress(in_progress), )) .await; - for (vote, voter) in castable { - let result = self - .vote_on_dpns_name( - &vote.contested_name, - vote.choice, - &[voter], - sdk, - sender.clone(), - ) - .await - .and_then(confirm_scheduled_vote_result); - match result { - Ok(()) => { - sender - .send(TaskResult::unattributed_success( - BackendTaskSuccessResult::CastScheduledVote(vote), - )) + let results = stream::iter(due_operations) + .map(|operation| { + let app_context = Arc::clone(self); + let sdk = sdk.clone(); + let voters = voters.clone(); + let operation_id = operation.id; + async move { + // Due operations are stored already; nothing is admitted. + let submitted = app_context.dpns_voter_lifecycles(); + let result = app_context + .execute_dpns_vote_operation_with_recovery( + operation, voters, None, &submitted, &sdk, + ) .await - .map_err(|_| TaskError::InternalSendError)?; - } - Err(e) => { - tracing::error!( - error = %e, - contested_name = %vote.contested_name, - "Failed to cast a due scheduled vote; leaving it for the next sweep" - ); - first_error.get_or_insert(e); + .map(|_| ()); + (operation_id, result) } - } - } - if let Some(error) = first_error { - Err(error) - } else { - Ok(BackendTaskSuccessResult::ScheduledVoteSweepCompleted { - network: self.network, - preserve_eligibility_since_ms, }) + .buffer_unordered(MAX_CONCURRENT_DPNS_VOTERS) + .collect::>() + .await; + let mut first_error = None; + for (operation_id, result) in results { + if let Err(error) = result { + tracing::error!( + error = %error, + operation_id = %operation_id, + "Failed to execute a due DPNS vote operation; leaving it for recovery" + ); + first_error.get_or_insert(error); + } } + first_error.map_or(Ok(()), Err) } } -fn confirm_scheduled_vote_result(result: BackendTaskSuccessResult) -> Result<(), TaskError> { - let BackendTaskSuccessResult::DPNSVoteResults(results) = result else { - return Err(TaskError::ScheduledVoteResultUnavailable); - }; - if results.is_empty() { - return Err(TaskError::ScheduledVoteResultUnavailable); +/// The outcome that speaks for `key`, rejecting a journal holding two locks on it. +pub(crate) fn preferred_outcome_for_scheduled_key<'a>( + operations: &'a [DpnsVoteOperation], + key: &'a DpnsVoteTargetKey, +) -> Result, TaskError> { + if dpns_vote_lock_holders(operations, key).nth(1).is_some() { + return Err(TaskError::DpnsVoteTargetBusy); } - for (_, _, result) in results { - result.map_err(|source| TaskError::ScheduledVoteRejected { source })?; - } - Ok(()) + Ok(authoritative_dpns_vote_outcome(operations, key)) } fn scheduled_vote_is_due( @@ -304,32 +1301,2320 @@ fn scheduled_vote_is_due( let eligibility_cutoff_ms = preserve_eligibility_since_ms.unwrap_or(now_ms); !executed_successfully && scheduled_at_ms <= now_ms - && scheduled_at_ms.saturating_add(SCHEDULED_VOTE_MAX_LATENESS_MS) >= eligibility_cutoff_ms + && !dpns_schedule_is_overdue(scheduled_at_ms, eligibility_cutoff_ms) +} + +fn scheduled_target_should_execute( + status: DpnsVoteTargetStatus, + scheduled_at_ms: u64, + now_ms: u64, + preserve_eligibility_since_ms: Option, +) -> bool { + status == DpnsVoteTargetStatus::Queued + || (status == DpnsVoteTargetStatus::Scheduled + && scheduled_vote_is_due( + scheduled_at_ms, + false, + now_ms, + preserve_eligibility_since_ms, + )) } #[cfg(test)] mod tests { use super::*; + use crate::model::qualified_identity::{IdentityStatus, IdentityType}; + use dash_sdk::dpp::identity::Identity; + use dash_sdk::dpp::version::PlatformVersion; + use std::collections::{BTreeMap, BTreeSet}; - #[test] - fn a_nested_platform_rejection_is_not_a_successful_scheduled_vote() { - let result = BackendTaskSuccessResult::DPNSVoteResults(vec![( - "alice".to_string(), - ResourceVoteChoice::Lock, - Err(Arc::new(TaskError::InternalSendError)), - )]); + fn dapi_connection_refused_error() -> TaskError { + use dash_sdk::Error as SdkError; + use dash_sdk::dapi_client::DapiClientError; + use dash_sdk::dapi_client::transport::TransportError; - assert!(matches!( - confirm_scheduled_vote_result(result), - Err(TaskError::ScheduledVoteRejected { .. }) - )); + let status = dash_sdk::dapi_grpc::tonic::Status::unavailable("tcp connect error"); + TaskError::from(SdkError::DapiClientError(DapiClientError::Transport( + TransportError::Grpc(status), + ))) + } + + fn qualified_identity(byte: u8) -> QualifiedIdentity { + let identity = Identity::create_basic_identity( + Identifier::from([byte; 32]), + PlatformVersion::latest(), + ) + .expect("basic identity"); + QualifiedIdentity { + identity, + associated_voter_identity: None, + associated_operator_identity: None, + associated_owner_key_id: None, + identity_type: IdentityType::User, + alias: None, + private_keys: Default::default(), + dpns_names: vec![], + associated_wallets: BTreeMap::new(), + secret_access: None, + wallet_index: None, + top_ups: BTreeMap::new(), + status: IdentityStatus::Active, + network: Network::Testnet, + } + } + + fn vote_context() -> (tempfile::TempDir, Arc) { + let temp = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(temp.path()); + context.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(Arc::new( + crate::wallet_backend::kv_test_support::InMemoryKv::default(), + ))); + (temp, context) } #[test] - fn an_empty_nested_result_is_not_a_successful_scheduled_vote() { + fn casting_a_schedule_requires_an_existing_journal_record() { + let (_temp, context) = vote_context(); + let voter = qualified_identity(1); + let vote = ScheduledDPNSVote { + contested_name: "alice".into(), + voter_id: voter.identity.id(), + choice: ResourceVoteChoice::Lock, + unix_timestamp: 42, + executed_successfully: false, + }; assert!(matches!( - confirm_scheduled_vote_result(BackendTaskSuccessResult::DPNSVoteResults(Vec::new())), - Err(TaskError::ScheduledVoteResultUnavailable) + context.operation_for_scheduled_vote(&vote, &voter), + Err(TaskError::DpnsVoteOperationRecordMissing) + )); + assert!(context.dpns_vote_operations().unwrap().is_empty()); + } + + #[tokio::test] + async fn journal_only_recovery_does_not_import_legacy_schedules() { + let (_temp, context) = vote_context(); + crate::database::test_helpers::create_legacy_scheduled_votes_table(&context.db).unwrap(); + crate::database::test_helpers::seed_legacy_scheduled_vote_row( + &context.db, + &[1; 32], + "old-schedule", + "Lock", + Network::Testnet, + ) + .unwrap(); + context + .ensure_dpns_vote_recovery(&context.sdk()) + .await + .unwrap(); + assert!(context.dpns_vote_operations().unwrap().is_empty()); + } + + fn scheduled_operation_for( + context: &AppContext, + name: &str, + timestamp: u64, + ) -> DpnsVoteOperation { + AppContext::new_dpns_vote_operation(vec![ + context + .dpns_vote_target( + &qualified_identity(1), + name, + ResourceVoteChoice::Lock, + VoteTiming::Scheduled(timestamp), + false, + ) + .unwrap(), + ]) + } + + #[tokio::test] + async fn blocker_partial_preflight_failure_reports_durable_success_and_failure() { + let (_dir, ctx) = vote_context(); + let mut first = scheduled_operation_for(&ctx, "alice", 42).targets[0] + .target + .clone(); + first.timing = VoteTiming::Now; + let mut second = first.clone(); + second.key.voter_id = Identifier::from([2; 32]); + let mut operation = AppContext::new_dpns_vote_operation(vec![first, second]); + operation.targets[0].status = DpnsVoteTargetStatus::Confirmed; + ctx.insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + let id = operation.id; + let result = ctx + .execute_dpns_vote_operation(operation, vec![], None, &Sdk::new_mock()) + .await; + assert!( + matches!(result, Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated { operation_id, .. }) if operation_id == id), + "{result:?}" + ); + let saved = ctx.dpns_vote_operation(id).unwrap().unwrap(); + assert_eq!(saved.targets[0].status, DpnsVoteTargetStatus::Confirmed); + assert_eq!( + saved.targets[1].status, + DpnsVoteTargetStatus::FailedBeforeSubmission + ); + let (message, _, _) = crate::ui::dpns::copy::dpns_vote_feedback(&saved); + assert!( + message.contains("Votes confirmed: 1.") && message.contains("Votes needing review: 1."), + "{message}" + ); + } + + #[tokio::test] + async fn blocker_scheduled_preflight_failure_stays_retryable() { + let (_dir, ctx) = vote_context(); + let mut operation = scheduled_operation_for(&ctx, "alice", 42); + ctx.insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + let key = operation.targets[0].target.key.clone(); + ctx.queue_scheduled_dpns_vote_target(operation.id, &key) + .unwrap(); + operation = ctx.dpns_vote_operation(operation.id).unwrap().unwrap(); + let id = operation.id; + let result = ctx + .execute_dpns_vote_operation(operation, vec![], None, &Sdk::new_mock()) + .await; + assert!( + matches!(result, Err(TaskError::DpnsVotePreflightFailed { .. })), + "{result:?}" + ); + let saved = ctx.dpns_vote_operation(id).unwrap().unwrap(); + assert_eq!(saved.targets[0].status, DpnsVoteTargetStatus::Scheduled); + assert!(saved.targets[0].failure.is_some()); + } + + #[tokio::test] + async fn blocker_preflight_persistence_failure_still_propagates() { + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(crate::wallet_backend::kv_test_support::FailingKv::default()); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(store.clone())); + let mut operation = scheduled_operation_for(&ctx, "alice", 42); + operation.targets[0].target.timing = VoteTiming::Now; + operation.targets[0].status = DpnsVoteTargetStatus::Queued; + ctx.insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + store.fail_next_puts_containing(&operation.id.to_string(), 1); + let id = operation.id; + let result = ctx + .execute_dpns_vote_operation(operation, vec![], None, &Sdk::new_mock()) + .await; + assert!( + result.is_err(), + "A failed journal write must not produce a success summary: {result:?}" + ); + assert_eq!( + ctx.dpns_vote_operation(id).unwrap().unwrap().targets[0].status, + DpnsVoteTargetStatus::Queued + ); + } + + #[tokio::test] + async fn blocker_cancelled_relative_schedule_leaves_no_app_sidecar() { + let (_dir, ctx) = vote_context(); + let mut operation = scheduled_operation_for(&ctx, "alice", now_ms() + 60_000); + let key = operation.targets[0].target.key.clone(); + set_relative_schedule_labels( + &mut operation, + &RelativeScheduleLabels { + preset: std::time::Duration::from_secs(600), + targets: BTreeSet::from([key.clone()]), + }, + ); + ctx.insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + assert_eq!( + ctx.dpns_vote_operation(operation.id) + .unwrap() + .unwrap() + .targets[0] + .relative_schedule_preset_ms, + Some(600_000) + ); + ctx.remove_scheduled_dpns_vote(operation.id, &key).unwrap(); + let prefix = format!("{}:dpns_voting:relative:", ctx.network()); + assert!( + ctx.app_kv() + .list(crate::wallet_backend::DetScope::Global, Some(&prefix)) + .unwrap() + .is_empty(), + "cancelled schedules must not leave immortal app-level display metadata" + ); + } + + #[tokio::test] + async fn review_regression_cast_now_keeps_other_queued_targets_unchanged() { + for sibling_status in [ + DpnsVoteTargetStatus::Queued, + DpnsVoteTargetStatus::Submitting, + DpnsVoteTargetStatus::Confirming, + ] { + let (_temp, context) = vote_context(); + let mut operation = scheduled_operation_for(&context, "alice", 42); + let mut sibling = operation.targets[0].target.clone(); + sibling.key.voter_id = Identifier::from([2; 32]); + operation = AppContext::new_dpns_vote_operation(vec![ + operation.targets[0].target.clone(), + sibling, + ]); + operation.targets[1].status = sibling_status; + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + let original_sibling = operation.targets[1].clone(); + let selected = context + .operation_for_scheduled_vote( + &ScheduledDPNSVote { + voter_id: Identifier::from([1; 32]), + contested_name: "alice".into(), + choice: ResourceVoteChoice::Lock, + unix_timestamp: 42, + executed_successfully: false, + }, + &qualified_identity(1), + ) + .unwrap(); + let _ = context + .execute_dpns_vote_operation_with_recovery( + selected, + vec![qualified_identity(1)], + None, + &context.dpns_voter_lifecycles(), + &Sdk::new_mock(), + ) + .await; + let saved = context.dpns_vote_operation(operation.id).unwrap().unwrap(); + assert_eq!(saved.targets[1], original_sibling); + } + } + + #[test] + fn scheduled_retry_keeps_choice_after_different_immediate_success() { + let (_temp, context) = vote_context(); + let mut previous = scheduled_operation_for(&context, "alice", 42); + previous.created_at = 1; + previous.targets[0].status = DpnsVoteTargetStatus::Rejected; + context + .insert_dpns_vote_operation(&mut previous, None) + .unwrap(); + let mut newer = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + requested_choice: ResourceVoteChoice::Abstain, + timing: VoteTiming::Now, + ..previous.targets[0].target.clone() + }]); + newer.created_at = 2; + newer.targets[0].status = DpnsVoteTargetStatus::Confirmed; + context + .insert_dpns_vote_operation(&mut newer, None) + .unwrap(); + let retry = context + .operation_for_scheduled_vote( + &ScheduledDPNSVote { + voter_id: previous.targets[0].target.key.voter_id, + contested_name: "alice".into(), + choice: ResourceVoteChoice::Lock, + unix_timestamp: 42, + executed_successfully: false, + }, + &qualified_identity(1), + ) + .unwrap(); + assert_ne!(retry.id, newer.id); + assert_eq!( + retry.targets[0].target.requested_choice, + ResourceVoteChoice::Lock + ); + assert_eq!(retry.targets[0].status, DpnsVoteTargetStatus::Queued); + } + + #[test] + fn new_immediate_vote_requires_review_when_it_becomes_a_change() { + let (_temp, context) = vote_context(); + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + timing: VoteTiming::Now, + ..scheduled_operation_for(&context, "alice", 42).targets[0] + .target + .clone() + }]); + let key = operation.targets[0].target.key.clone(); + assert!( + context + .revalidate_dpns_vote_preflight( + &mut operation, + false, + &key, + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Abstain)), + ) + .is_err(), + "a newly required vote-change warning must return to review" + ); + assert_eq!(operation.targets[0].target.current_choice, None); + assert!(context.dpns_vote_operation(operation.id).unwrap().is_none()); + } + + #[tokio::test] + async fn contest_query_does_not_require_readable_vote_journal() { + use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; + use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; + use dash_sdk::drive::query::vote_polls_by_document_type_query::VotePollsByDocumentTypeQuery; + use dash_sdk::query_types::{ContestedResource, ContestedResources}; + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(crate::wallet_backend::kv_test_support::FailingKv::default()); + let kv = crate::wallet_backend::DetKv::from_store(store.clone()); + let context = crate::context::test_support::test_app_context_with_kv( + dir.path(), + Arc::new(kv.clone()), + ); + context.set_det_kv_override_for_test(kv); + store.fail_next_gets_containing("det:dpns_vote_operations:v2:", 2); + let mut sdk = Sdk::new_mock(); + let document_type = context + .dpns_contract + .document_type_for_name("domain") + .unwrap(); + sdk.mock() + .expect_fetch_many::( + VotePollsByDocumentTypeQuery { + contract_id: context.dpns_contract.id(), + document_type_name: document_type.name().to_owned(), + index_name: document_type.find_contested_index().unwrap().name.clone(), + start_at_value: None, + start_index_values: vec!["dash".into()], + end_index_values: vec![], + limit: Some(100), + order_ascending: true, + }, + Some(ContestedResources::default()), + ) + .await + .unwrap(); + let (tx, mut rx) = tokio::sync::mpsc::channel(16); + let sender = crate::utils::egui_mpsc::SenderAsync::new(tx, context.egui_ctx().clone()); + let result = context + .run_contested_resource_task(ContestedResourceTask::QueryDPNSContests, &sdk, sender) + .await; + assert!( + result.is_ok(), + "independent contest reads must survive journal errors: {result:?}" + ); + assert!( + std::iter::from_fn(|| rx.try_recv().ok()).any(|result| matches!( + result, TaskResult::Success { result, .. } + if matches!(*result, BackendTaskSuccessResult::RefreshedDpnsContests) + )) + ); + assert!( + context.ensure_dpns_vote_recovery(&sdk).await.is_err(), + "vote recovery must still fail closed" + ); + } + + #[test] + fn preflight_preserves_matching_noop_and_reviewed_changes() { + let (_temp, context) = vote_context(); + for (reviewed, observed, expected_status) in [ + ( + None, + Some(ResourceVoteChoice::Lock), + DpnsVoteTargetStatus::Confirmed, + ), + ( + Some(ResourceVoteChoice::Abstain), + Some(ResourceVoteChoice::Abstain), + DpnsVoteTargetStatus::Queued, + ), + (None, None, DpnsVoteTargetStatus::Queued), + ] { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + timing: VoteTiming::Now, + current_choice: reviewed, + ..scheduled_operation_for(&context, "alice", 42).targets[0] + .target + .clone() + }]); + let key = operation.targets[0].target.key.clone(); + context + .revalidate_dpns_vote_preflight( + &mut operation, + false, + &key, + DpnsCurrentVoteState::Available(observed), + ) + .unwrap(); + assert_eq!(operation.targets[0].status, expected_status); + } + } + + #[test] + fn terminal_retry_with_matching_cache_reaches_durable_no_op_preflight() { + let (_temp, context) = vote_context(); + let mut previous = scheduled_operation_for(&context, "alice", 42); + previous.targets[0].status = DpnsVoteTargetStatus::Rejected; + context + .insert_dpns_vote_operation(&mut previous, None) + .unwrap(); + let key = previous.targets[0].target.key.clone(); + context + .cache_confirmed_dpns_vote(key.voter_id, key.vote_poll_id, ResourceVoteChoice::Lock) + .unwrap(); + let scheduled = ScheduledDPNSVote { + voter_id: key.voter_id, + contested_name: "alice".into(), + choice: ResourceVoteChoice::Lock, + unix_timestamp: 42, + executed_successfully: false, + }; + let mut retry = context + .operation_for_scheduled_vote(&scheduled, &qualified_identity(1)) + .unwrap(); + assert_eq!(retry.targets.len(), 1); + assert_eq!( + retry.targets[0].status, + DpnsVoteTargetStatus::Queued, + "cache alone must not confirm a retry" + ); + context + .revalidate_dpns_vote_preflight( + &mut retry, + false, + &key, + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)), + ) + .unwrap(); + context + .insert_dpns_vote_operation(&mut retry, None) + .unwrap(); + let saved = context.dpns_vote_operation(retry.id).unwrap().unwrap(); + assert_eq!(saved.targets[0].status, DpnsVoteTargetStatus::Confirmed); + assert!(!saved.targets[0].status.holds_lock()); + assert_eq!( + context + .dpns_vote_operation(previous.id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Rejected + ); + } + + #[tokio::test] + async fn sweep_executes_due_votes_before_reconciling_unconfirmed_ones() { + let (_temp, context) = vote_context(); + let started = 1_000_000; + let mut operation = scheduled_operation_for(&context, "alice", started); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + let events = std::cell::RefCell::new(Vec::new()); + context + .sweep_due_scheduled_votes( + || started, + None, + |due, in_progress| { + events + .borrow_mut() + .push(("execute", due.len(), in_progress.len())); + std::future::ready(Ok(())) + }, + async { + events.borrow_mut().push(("reconcile", 0, 0)); + Ok(()) + }, + ) + .await + .unwrap(); + assert_eq!( + *events.borrow(), + vec![("execute", 1, 1), ("reconcile", 0, 0)], + "a due vote must not wait behind reconciliation of unrelated votes" + ); + assert_eq!( + context + .dpns_vote_operation(operation.id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Queued, + "the admission is durable before execution starts" + ); + } + + #[tokio::test] + async fn sweep_reconciliation_failure_retains_durable_due_admission() { + let (_temp, context) = vote_context(); + let started = 1_000_000; + let clock = std::cell::Cell::new(started); + let mut due = scheduled_operation_for(&context, "alice", started); + let mut newly_due = scheduled_operation_for(&context, "bob", started + 10); + context.insert_dpns_vote_operation(&mut due, None).unwrap(); + context + .insert_dpns_vote_operation(&mut newly_due, None) + .unwrap(); + let result = context + .sweep_due_scheduled_votes( + || clock.get(), + None, + |_, _| std::future::ready(Ok(())), + async { + clock.set(started + SCHEDULED_VOTE_MAX_LATENESS_MS * 2); + Err(TaskError::DpnsVoteTargetBusy) + }, + ) + .await; + assert!(matches!(result, Err(TaskError::DpnsVoteTargetBusy))); + for id in [due.id, newly_due.id] { + assert_eq!( + context.dpns_vote_operation(id).unwrap().unwrap().targets[0].status, + DpnsVoteTargetStatus::Queued, + "failed reconciliation must retain entry and newly due admissions" + ); + } + } + + /// A retryable failure returns a scheduled target to `Scheduled`; the + /// end-of-sweep admission must not queue it again, or it would escape the + /// lateness rule that eventually reports it as missed. + #[tokio::test] + async fn sweep_does_not_readmit_a_target_it_already_tried() { + let (_temp, context) = vote_context(); + let started = 1_000_000; + let mut operation = scheduled_operation_for(&context, "alice", started); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + let key = operation.targets[0].target.key.clone(); + context + .sweep_due_scheduled_votes( + || started, + None, + |due, _| { + assert_eq!(due.len(), 1); + assert!(context.claim_dpns_vote_target(due[0].id, &key).unwrap()); + let (status, failure) = + failed_before_broadcast_outcome(VoteTiming::Scheduled(started)); + context + .update_dpns_vote_target(due[0].id, &key, status, failure) + .unwrap(); + std::future::ready(Ok(())) + }, + std::future::ready(Ok(())), + ) + .await + .unwrap(); + assert_eq!( + context + .dpns_vote_operation(operation.id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Scheduled + ); + } + + /// Removing a node cancels its votes already in the journal. A vote + /// reviewed before the removal but stored after it, once its proof came + /// back, must end the same way: otherwise loading the node again would let + /// the sweep send a schedule the removal was meant to drop. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn votes_stored_after_their_node_was_removed_are_cancelled() { + let temp = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp.path()); + let (tx, _rx) = tokio::sync::mpsc::channel::(8); + context + .ensure_wallet_backend(crate::utils::egui_mpsc::SenderAsync::new( + tx, + context.egui_ctx().clone(), + )) + .await + .expect("wire wallet backend offline"); + let [removed, kept] = [1, 2].map(|byte| { + let mut node = qualified_identity(byte); + node.identity_type = IdentityType::Masternode; + context + .insert_local_qualified_identity(&node, &None) + .expect("load node"); + node + }); + let later = now_ms() + 600_000; + let target = |node: &QualifiedIdentity, name: &str, timing| { + context + .dpns_vote_target(node, name, ResourceVoteChoice::Lock, timing, false) + .unwrap() + }; + // Reviewed while both nodes were loaded. + let mut operation = AppContext::new_dpns_vote_operation(vec![ + target(&removed, "alice", VoteTiming::Scheduled(later)), + target(&removed, "bob", VoteTiming::Now), + target(&kept, "alice", VoteTiming::Scheduled(later)), + ]); + let schedule_key = operation.targets[0].target.key.clone(); + + context + .delete_local_qualified_identity(&removed.identity.id()) + .expect("remove node"); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + + let saved = context.dpns_vote_operation(operation.id).unwrap().unwrap(); + for stored in [&saved, &operation] { + assert_eq!( + stored + .targets + .iter() + .map(|outcome| outcome.status) + .collect::>(), + vec![ + DpnsVoteTargetStatus::Cancelled, + DpnsVoteTargetStatus::Cancelled, + DpnsVoteTargetStatus::Scheduled, + ], + "the removed node's votes are cancelled, the other node's vote is kept" + ); + } + assert_eq!( + context.dpns_vote_target_status(&schedule_key).unwrap(), + None + ); + + context + .insert_local_qualified_identity(&removed, &None) + .expect("load the node again"); + assert!( + !context + .queue_scheduled_dpns_vote_target(operation.id, &schedule_key) + .unwrap(), + "loading the node again must not revive the schedule" + ); + let mut reviewed_again = AppContext::new_dpns_vote_operation(vec![target( + &removed, + "carol", + VoteTiming::Scheduled(later), + )]); + context + .insert_dpns_vote_operation(&mut reviewed_again, None) + .unwrap(); + assert_eq!( + reviewed_again.targets[0].status, + DpnsVoteTargetStatus::Scheduled, + "a vote reviewed after the node was loaded again is accepted" + ); + context.wallet_backend().unwrap().shutdown().await; + } + + /// A node removed and loaded again while its reviewed votes wait for their + /// proof must not have them stored. The removal cancels only votes the + /// journal already holds, and loading the node again retires the record + /// that it was removed, so nothing else stops them. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn votes_waiting_for_proof_while_their_node_is_removed_and_loaded_again_are_cancelled() { + use dash_sdk::query_types::ResourceVotesByIdentity; + let temp = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp.path()); + let (tx, _rx) = tokio::sync::mpsc::channel::(8); + context + .ensure_wallet_backend(crate::utils::egui_mpsc::SenderAsync::new( + tx, + context.egui_ctx().clone(), + )) + .await + .expect("wire wallet backend offline"); + let [reloaded, kept] = [1, 2].map(|byte| { + let mut node = qualified_identity(byte); + node.identity_type = IdentityType::Masternode; + context + .insert_local_qualified_identity(&node, &None) + .expect("load node"); + node + }); + let now = now_ms(); + context.seed_dpns_contest_for_test("alice", Some(now + 600_000), false); + let mut sdk = Sdk::new_mock(); + sdk.mock() + .expect_fetch_many::( + ContestedResourceVotesGivenByIdentityQuery { + identity_id: reloaded.identity.id(), + offset: None, + limit: Some(100), + start_at: None, + order_ascending: true, + }, + Some(ResourceVotesByIdentity::default()), + ) + .await + .expect("mock vote query"); + let target = |node: &QualifiedIdentity, name: &str, timing| { + context + .dpns_vote_target(node, name, ResourceVoteChoice::Lock, timing, false) + .unwrap() + }; + let later = VoteTiming::Scheduled(now + 60_000); + let operation = AppContext::new_dpns_vote_operation(vec![ + target(&reloaded, "alice", later), + target(&reloaded, "bob", VoteTiming::Now), + target(&kept, "alice", later), + ]); + let operation_id = operation.id; + + // With every refresh permit taken, the run parks on its proof query. + let permits = context + .dpns_vote_refresh_permits + .acquire_many(u32::try_from(MAX_CONCURRENT_DPNS_VOTERS).expect("permit count")) + .await + .expect("refresh permits"); + let mut run = std::pin::pin!(context.execute_dpns_vote_operation( + operation, + vec![reloaded.clone(), kept.clone()], + None, + &sdk, + )); + assert!( + futures::poll!(&mut run).is_pending(), + "the run must be waiting for the vote proof" + ); + context + .delete_local_qualified_identity(&reloaded.identity.id()) + .expect("remove node"); + context + .insert_local_qualified_identity(&reloaded, &None) + .expect("load the node again"); + drop(permits); + let result = run.await; + + assert!(result.is_ok(), "{result:?}"); + let stored = context + .dpns_vote_operation(operation_id) + .unwrap() + .expect("the operation is journaled"); + assert_eq!( + stored + .targets + .iter() + .map(|outcome| outcome.status) + .collect::>(), + vec![ + DpnsVoteTargetStatus::Cancelled, + DpnsVoteTargetStatus::Cancelled, + DpnsVoteTargetStatus::Scheduled, + ], + "the reloaded node's votes are cancelled, the other node's vote is kept" + ); + context.wallet_backend().unwrap().shutdown().await; + } + + /// A schedule stored after the node was loaded again was reviewed afresh. + /// A replacement submitted before the removal must not overwrite it. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_replacement_submitted_before_its_node_was_removed_and_loaded_again_is_refused() { + let temp = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp.path()); + let (tx, _rx) = tokio::sync::mpsc::channel::(8); + context + .ensure_wallet_backend(crate::utils::egui_mpsc::SenderAsync::new( + tx, + context.egui_ctx().clone(), + )) + .await + .expect("wire wallet backend offline"); + let mut node = qualified_identity(1); + node.identity_type = IdentityType::Masternode; + context + .insert_local_qualified_identity(&node, &None) + .expect("load node"); + let later = now_ms() + 600_000; + let schedule = |timestamp| { + AppContext::new_dpns_vote_operation(vec![ + context + .dpns_vote_target( + &node, + "alice", + ResourceVoteChoice::Lock, + VoteTiming::Scheduled(timestamp), + false, + ) + .unwrap(), + ]) + }; + let mut original = schedule(later); + context + .insert_dpns_vote_operation(&mut original, None) + .unwrap(); + let key = original.targets[0].target.key.clone(); + let mut replacement = schedule(later + 60_000); + let submitted = context.dpns_voter_lifecycles(); + + context + .delete_local_qualified_identity(&node.identity.id()) + .expect("remove node"); + context + .insert_local_qualified_identity(&node, &None) + .expect("load the node again"); + let mut reviewed_again = schedule(later); + context + .insert_dpns_vote_operation(&mut reviewed_again, None) + .unwrap(); + + assert!(matches!( + context.admit_dpns_vote_operation(&mut replacement, Some(&key), &submitted), + Err(TaskError::DpnsScheduledVoteNotEditable) + )); + let stored = context + .dpns_vote_operation(reviewed_again.id) + .unwrap() + .expect("the schedule reviewed again is journaled"); + assert_eq!( + stored.targets[0].target.timing, + VoteTiming::Scheduled(later), + "the schedule reviewed after the node was loaded again is untouched" + ); + context.wallet_backend().unwrap().shutdown().await; + } + + /// When an executor ends with an error, the immediate votes it had not + /// reached yet must not stay queued: nothing would send them, and their + /// lock would refuse every new vote on those names until a restart. + #[tokio::test] + async fn an_executor_error_releases_its_immediate_votes_that_were_still_queued() { + let (_temp, context) = vote_context(); + context.dpns_vote_recovery.lock().await.initialized = true; + let immediate = |name: &str| DpnsVoteTarget { + timing: VoteTiming::Now, + ..scheduled_operation_for(&context, name, 42).targets[0] + .target + .clone() + }; + let schedule = scheduled_operation_for(&context, "carol", now_ms() + 600_000).targets[0] + .target + .clone(); + let mut operation = AppContext::new_dpns_vote_operation(vec![ + immediate("alice"), + immediate("bob"), + schedule, + ]); + operation.targets[2].status = DpnsVoteTargetStatus::Queued; + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + let keys: BTreeSet = operation + .targets + .iter() + .map(|outcome| outcome.target.key.clone()) + .collect(); + let [claimed, unreached, queued_schedule] = + [0, 1, 2].map(|index| operation.targets[index].target.key.clone()); + // The executor claimed the first vote, then failed before the second. + assert!( + context + .claim_dpns_vote_target(operation.id, &claimed) + .unwrap() + ); + + context + .recover_failed_dpns_vote_operation(operation.id, &keys, &TaskError::DpnsVoteTargetBusy) + .await; + + let saved = context.dpns_vote_operation(operation.id).unwrap().unwrap(); + for index in [0, 1] { + assert_eq!( + saved.targets[index].status, + DpnsVoteTargetStatus::FailedBeforeSubmission, + "target {index}" + ); + assert_eq!( + saved.targets[index].failure, + Some(DpnsVoteFailure::SubmissionFailed) + ); + } + assert_eq!(context.dpns_vote_target_status(&claimed).unwrap(), None); + assert_eq!( + context.dpns_vote_target_status(&unreached).unwrap(), + None, + "the vote the executor never reached must be free to cast again" + ); + assert_eq!( + context.dpns_vote_target_status(&queued_schedule).unwrap(), + Some(DpnsVoteTargetStatus::Queued), + "a queued schedule stays for the sweep to send" + ); + } + + /// Replacing one scheduled target must not pull the stored operation's + /// other targets into the run, where a queued one would be claimed + /// without its voter. + #[tokio::test] + async fn replacing_a_schedule_leaves_sibling_targets_of_the_operation_alone() { + let now = now_ms(); + let (_temp, context) = vote_context(); + context.seed_dpns_contest_for_test("alice", Some(now + 600_000), false); + let replaced = scheduled_operation_for(&context, "alice", now + 60_000).targets[0] + .target + .clone(); + let mut sibling = replaced.clone(); + sibling.key.voter_id = Identifier::from([2; 32]); + let mut existing = AppContext::new_dpns_vote_operation(vec![replaced.clone(), sibling]); + existing.targets[1].status = DpnsVoteTargetStatus::Queued; + context + .insert_dpns_vote_operation(&mut existing, None) + .unwrap(); + let original_sibling = existing.targets[1].clone(); + let replacement = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + timing: VoteTiming::Scheduled(now + 120_000), + ..replaced.clone() + }]); + + let result = context + .execute_dpns_vote_operation( + replacement, + vec![], + Some(replaced.key.clone()), + &context.sdk(), + ) + .await; + + assert!(result.is_ok(), "{result:?}"); + let saved = context.dpns_vote_operation(existing.id).unwrap().unwrap(); + assert_eq!( + saved.targets[0].target.timing, + VoteTiming::Scheduled(now + 120_000) + ); + assert_eq!(saved.targets[1], original_sibling); + } + + /// A pass in which one node's proof query failed must not count as a + /// completed refresh, or its retry waits a whole refresh interval. + #[tokio::test] + async fn a_refresh_pass_with_an_unchecked_node_is_not_complete() { + use super::refresh_vote_states::every_voter_refreshed; + use dash_sdk::dapi_client::{DapiClientError, transport::TransportError}; + + let (_temp, context) = vote_context(); + let kv = context.det_kv().unwrap(); + let checked = Identifier::from([1; 32]); + let unchecked = Identifier::from([2; 32]); + let mut results = BTreeMap::new(); + results.insert( + checked, + context + .publish_dpns_vote_state(&kv, checked, async { Ok(BTreeMap::new()) }) + .await + .map_err(Arc::new), + ); + assert!(every_voter_refreshed(&results)); + assert!(every_voter_refreshed(&BTreeMap::new())); + + results.insert( + unchecked, + context + .publish_dpns_vote_state(&kv, unchecked, async { + Err(Box::new(dash_sdk::Error::DapiClientError( + DapiClientError::Transport(TransportError::Grpc( + dash_sdk::dapi_grpc::tonic::Status::unavailable("tcp connect error"), + )), + ))) + }) + .await + .map_err(Arc::new), + ); + assert!(!every_voter_refreshed(&results)); + } + + /// A background pass whose contest end times could not be read must not + /// count as a completed refresh either. The mock answers only the contest + /// list, so the end-time query fails; the pass still ends quietly. + #[tokio::test] + async fn a_refresh_pass_with_a_failed_contest_query_is_not_complete() { + use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; + use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; + use dash_sdk::drive::query::vote_polls_by_document_type_query::VotePollsByDocumentTypeQuery; + use dash_sdk::query_types::{ContestedResource, ContestedResources}; + let (_temp, context) = vote_context(); + let mut sdk = Sdk::new_mock(); + let document_type = context + .dpns_contract + .document_type_for_name("domain") + .unwrap(); + sdk.mock() + .expect_fetch_many::( + VotePollsByDocumentTypeQuery { + contract_id: context.dpns_contract.id(), + document_type_name: document_type.name().to_owned(), + index_name: document_type.find_contested_index().unwrap().name.clone(), + start_at_value: None, + start_index_values: vec!["dash".into()], + end_index_values: vec![], + limit: Some(100), + order_ascending: true, + }, + Some(ContestedResources::default()), + ) + .await + .unwrap(); + let (tx, mut rx) = tokio::sync::mpsc::channel(16); + let sender = crate::utils::egui_mpsc::SenderAsync::new(tx, context.egui_ctx().clone()); + + let result = context + .run_contested_resource_task( + ContestedResourceTask::RefreshContestsInBackground, + &sdk, + sender, + ) + .await; + + assert!(result.is_ok(), "{result:?}"); + assert_eq!( + context.dpns_contests_refreshed_at_ms(), + None, + "a pass with unread end times must stay open to an early retry" + ); + let sent: Vec = std::iter::from_fn(|| rx.try_recv().ok()).collect(); + assert!( + sent.iter().any(|sent| matches!( + sent, TaskResult::Success { result, .. } + if matches!(**result, BackendTaskSuccessResult::RefreshedDpnsContests) + )), + "what the pass did refresh is still published" + ); + assert!( + !sent + .iter() + .any(|sent| matches!(sent, TaskResult::Error { .. })), + "a background pass reports no error to the UI" + ); + } + + fn unconfirmed_operation_for(context: &AppContext, name: &str) -> DpnsVoteOperation { + let mut target = scheduled_operation_for(context, name, 42).targets[0] + .target + .clone(); + target.timing = VoteTiming::Now; + let mut operation = AppContext::new_dpns_vote_operation(vec![target]); + operation.targets[0].status = DpnsVoteTargetStatus::Unconfirmed; + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + operation + } + + async fn expect_current_vote( + sdk: &mut Sdk, + context: &AppContext, + key: &DpnsVoteTargetKey, + name: &str, + choice: Option, + ) { + use dash_sdk::dpp::voting::vote_polls::VotePoll; + use dash_sdk::dpp::voting::votes::resource_vote::v0::ResourceVoteV0; + use dash_sdk::query_types::ResourceVotesByIdentity; + + let votes: ResourceVotesByIdentity = choice + .map(|resource_vote_choice| { + let vote_poll = VotePoll::ContestedDocumentResourceVotePoll( + crate::model::dpns_voting::dpns_vote_poll(&context.dpns_contract, name) + .unwrap(), + ); + ( + key.vote_poll_id, + Some(ResourceVote::V0(ResourceVoteV0 { + vote_poll, + resource_vote_choice, + })), + ) + }) + .into_iter() + .collect(); + sdk.mock() + .expect_fetch_many::( + ContestedResourceVotesGivenByIdentityQuery { + identity_id: key.voter_id, + offset: None, + limit: Some(1), + start_at: Some((key.vote_poll_id.to_buffer(), true)), + order_ascending: true, + }, + Some(votes), + ) + .await + .unwrap(); + } + + /// An unchanged re-check must stay silent: forwarding it would raise the + /// "could not be confirmed yet" message again on every sweep. + #[tokio::test] + async fn sweep_reports_an_unconfirmed_vote_only_once_it_is_confirmed() { + let (_temp, context) = vote_context(); + context.seed_dpns_contest_for_test("alice", Some(now_ms() + 600_000), false); + let operation = unconfirmed_operation_for(&context, "alice"); + let key = operation.targets[0].target.key.clone(); + let (tx, mut rx) = tokio::sync::mpsc::channel(4); + let sender = crate::utils::egui_mpsc::SenderAsync::new(tx, context.egui_ctx().clone()); + + let mut still_absent = Sdk::new_mock(); + expect_current_vote(&mut still_absent, &context, &key, "alice", None).await; + context + .reconcile_unconfirmed_dpns_votes(&still_absent, &sender) + .await + .unwrap(); + assert!( + rx.try_recv().is_err(), + "an unchanged unconfirmed vote must not be reported again" + ); + assert_eq!( + context.dpns_vote_target_status(&key).unwrap(), + Some(DpnsVoteTargetStatus::Unconfirmed) + ); + + let mut applied = Sdk::new_mock(); + expect_current_vote( + &mut applied, + &context, + &key, + "alice", + Some(ResourceVoteChoice::Lock), + ) + .await; + context + .reconcile_unconfirmed_dpns_votes(&applied, &sender) + .await + .unwrap(); + assert!(matches!( + rx.try_recv(), + Ok(TaskResult::Success { result, .. }) + if matches!( + *result, + BackendTaskSuccessResult::DpnsVoteOperationUpdated { operation_id, .. } + if operation_id == operation.id + ) + )); + assert_eq!( + context + .dpns_vote_operation(operation.id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Confirmed + ); + } + + /// A decided contest has dropped its vote references, so the sweep must + /// not query it again; the target keeps its lock and status. + #[tokio::test] + async fn sweep_does_not_query_unconfirmed_votes_of_decided_contests() { + let (_temp, context) = vote_context(); + context.seed_dpns_contest_for_test("alice", Some(1), true); + let operation = unconfirmed_operation_for(&context, "alice"); + let key = operation.targets[0].target.key.clone(); + let (tx, mut rx) = tokio::sync::mpsc::channel(4); + let sender = crate::utils::egui_mpsc::SenderAsync::new(tx, context.egui_ctx().clone()); + + // No expectation: any query fails and would be recorded as a diagnostic. + context + .reconcile_unconfirmed_dpns_votes(&Sdk::new_mock(), &sender) + .await + .unwrap(); + + assert!( + context + .dpns_vote_operation_diagnostics(operation.id) + .is_empty(), + "a decided contest must not be queried" + ); + assert!(rx.try_recv().is_err()); + assert_eq!( + context.dpns_vote_target_status(&key).unwrap(), + Some(DpnsVoteTargetStatus::Unconfirmed), + "skipping the query must not release the lock" + ); + } + + /// Preference saves run offline: they skip vote recovery and persist. + #[tokio::test] + async fn voting_preferences_save_through_the_backend() { + use crate::model::dpns_voting::operator::NodeSet; + let (_temp, context) = vote_context(); + let (tx, _rx) = tokio::sync::mpsc::channel(4); + let sender = crate::utils::egui_mpsc::SenderAsync::new(tx, context.egui_ctx().clone()); + let result = context + .run_contested_resource_task( + ContestedResourceTask::SaveDpnsVotingPreference(DpnsVotingPreference::NodeSet( + NodeSet::EvonodesOnly, + )), + &Sdk::new_mock(), + sender, + ) + .await; + assert!( + matches!(result, Ok(BackendTaskSuccessResult::None)), + "{result:?}" + ); + assert_eq!( + context.saved_dpns_node_set().unwrap(), + NodeSet::EvonodesOnly + ); + } + + /// VOTE-FR-081: the backend records the relative preset only for the + /// listed targets that were actually scheduled. + #[test] + fn relative_labels_are_saved_for_listed_scheduled_targets() { + let (_temp, context) = vote_context(); + let scheduled = scheduled_operation_for(&context, "alice", 9_000); + let mut immediate = scheduled_operation_for(&context, "bob", 9_000); + immediate.targets[0].target.timing = VoteTiming::Now; + let mut operation = scheduled.clone(); + operation.targets.push(immediate.targets[0].clone()); + let preset = std::time::Duration::from_secs(600); + let labels = RelativeScheduleLabels { + preset, + targets: operation + .targets + .iter() + .map(|outcome| outcome.target.key.clone()) + .collect(), + }; + set_relative_schedule_labels(&mut operation, &labels); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + let saved = context.dpns_vote_operation(operation.id).unwrap().unwrap(); + assert_eq!(saved.targets[0].relative_schedule_preset_ms, Some(600_000)); + assert_eq!(saved.targets[1].relative_schedule_preset_ms, None); + let mut legacy = serde_json::to_value(&saved).unwrap(); + legacy["targets"][0] + .as_object_mut() + .unwrap() + .remove("relative_schedule_preset_ms"); + let legacy: DpnsVoteOperation = serde_json::from_value(legacy).unwrap(); + assert_eq!(legacy.targets[0].relative_schedule_preset_ms, None); + } + + #[tokio::test] + async fn new_schedule_rejects_past_time_before_persistence() { + let (_temp, context) = vote_context(); + let operation = scheduled_operation_for(&context, "alice", 1); + let result = context + .execute_dpns_vote_operation(operation, vec![], None, &context.sdk()) + .await; + assert!(matches!( + result, + Err(TaskError::DpnsScheduledVoteInvalidTime) + )); + assert!(context.dpns_vote_operations().unwrap().is_empty()); + } + + #[tokio::test] + async fn new_schedule_validates_known_deadline_and_unknown_deadline_policy() { + let now = now_ms(); + let end = now + 120_000; + for (timestamp, deadline, expected_valid) in [ + (end - 1, Some(end), true), + (end, Some(end), false), + (end + 1, Some(end), false), + (end, None, true), + ] { + let (_temp, context) = vote_context(); + context.seed_dpns_contest_for_test("alice", deadline, false); + let operation = scheduled_operation_for(&context, "alice", timestamp); + let result = context + .execute_dpns_vote_operation(operation, vec![], None, &context.sdk()) + .await; + if expected_valid { + result.unwrap(); + assert_eq!(context.dpns_vote_operations().unwrap().len(), 1); + } else { + assert!(matches!( + result, + Err(TaskError::DpnsScheduledVoteInvalidTime) + )); + assert!(context.dpns_vote_operations().unwrap().is_empty()); + } + } + } + + #[tokio::test] + async fn new_schedule_rejects_mixed_deadlines_atomically_and_missing_or_closed_contests() { + let now = now_ms(); + let timestamp = now + 60_000; + let (_temp, context) = vote_context(); + context.seed_dpns_contest_for_test("alice", Some(timestamp + 1), false); + context.seed_dpns_contest_for_test("bob", Some(timestamp), false); + let mut targets = scheduled_operation_for(&context, "alice", timestamp).targets; + targets.extend(scheduled_operation_for(&context, "bob", timestamp).targets); + let operation = + AppContext::new_dpns_vote_operation(targets.into_iter().map(|o| o.target).collect()); + let result = context + .execute_dpns_vote_operation(operation, vec![], None, &context.sdk()) + .await; + assert!(matches!( + result, + Err(TaskError::DpnsScheduledVoteInvalidTime) + )); + assert!(context.dpns_vote_operations().unwrap().is_empty()); + for name in ["missing", "closed"] { + if name == "closed" { + context.seed_dpns_contest_for_test(name, None, true); + } + let result = context + .execute_dpns_vote_operation( + scheduled_operation_for(&context, name, timestamp), + vec![], + None, + &context.sdk(), + ) + .await; + assert!(matches!(result, Err(TaskError::VotePollNotFound { .. }))); + assert!(context.dpns_vote_operations().unwrap().is_empty()); + } + } + + #[tokio::test] + async fn sweep_preserves_newly_due_but_excludes_already_stale_and_future_targets() { + let (_temp, context) = vote_context(); + let started = 1_000_000; + let finished = started + SCHEDULED_VOTE_MAX_LATENESS_MS * 2; + let clock = std::cell::Cell::new(started); + let mut statuses = Vec::new(); + for (name, timestamp, expected) in [ + ("newlydue", started + 10, DpnsVoteTargetStatus::Queued), + ( + "stale", + started - SCHEDULED_VOTE_MAX_LATENESS_MS - 1, + DpnsVoteTargetStatus::Scheduled, + ), + ("future", finished + 1, DpnsVoteTargetStatus::Scheduled), + ] { + let mut operation = scheduled_operation_for(&context, name, timestamp); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + statuses.push((name, operation.id, expected)); + } + context + .sweep_due_scheduled_votes( + || clock.get(), + None, + |due, _| { + assert!(due.is_empty(), "nothing is due at sweep entry"); + std::future::ready(Ok(())) + }, + async { + clock.set(finished); + Ok(()) + }, + ) + .await + .unwrap(); + for (name, id, expected) in statuses { + assert_eq!( + context.dpns_vote_operation(id).unwrap().unwrap().targets[0].status, + expected, + "{name}" + ); + } + } + + #[test] + fn cast_now_durably_queues_an_existing_scheduled_operation() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp_dir.path()); + let kv = crate::wallet_backend::DetKv::from_store(Arc::new( + crate::wallet_backend::kv_test_support::InMemoryKv::default(), + )); + context.set_det_kv_override_for_test(kv); + let voter = qualified_identity(1); + let scheduled_vote = ScheduledDPNSVote { + contested_name: "dominguez".to_owned(), + voter_id: Identifier::from([1; 32]), + choice: ResourceVoteChoice::Lock, + unix_timestamp: 42, + executed_successfully: false, + }; + let target = context + .dpns_vote_target( + &voter, + &scheduled_vote.contested_name, + scheduled_vote.choice, + VoteTiming::Scheduled(scheduled_vote.unix_timestamp), + false, + ) + .expect("scheduled target"); + let mut operation = AppContext::new_dpns_vote_operation(vec![target]); + let operation_id = operation.id; + context + .insert_dpns_vote_operation(&mut operation, None) + .expect("persist scheduled operation"); + + let returned = context + .operation_for_scheduled_vote(&scheduled_vote, &voter) + .expect("queue scheduled operation"); + let persisted = context + .dpns_vote_operation(operation_id) + .expect("load operation") + .expect("persisted operation"); + + assert_eq!(returned.targets[0].status, DpnsVoteTargetStatus::Queued); + assert_eq!(persisted.targets[0].status, DpnsVoteTargetStatus::Queued); + } + + #[test] + fn scheduled_lookup_prefers_lock_holder_then_newest_terminal() { + let key = DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([2; 32]), + }; + let target = DpnsVoteTarget { + key: key.clone(), + voter_alias: None, + contested_name: "dominguez".to_owned(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Scheduled(42), + }; + let mut older = AppContext::new_dpns_vote_operation(vec![target.clone()]); + older.created_at = 1; + older.targets[0].status = DpnsVoteTargetStatus::Confirmed; + let mut newer = AppContext::new_dpns_vote_operation(vec![target.clone()]); + newer.created_at = 2; + newer.targets[0].status = DpnsVoteTargetStatus::Cancelled; + let mut lock_holder = AppContext::new_dpns_vote_operation(vec![target]); + lock_holder.created_at = 0; + lock_holder.targets[0].status = DpnsVoteTargetStatus::Scheduled; + let operations = vec![older.clone(), lock_holder.clone(), newer.clone()]; + + assert_eq!( + preferred_outcome_for_scheduled_key(&operations, &key) + .unwrap() + .unwrap() + .operation_id, + lock_holder.id + ); + + let terminal_operations = vec![older, newer.clone()]; + assert_eq!( + preferred_outcome_for_scheduled_key(&terminal_operations, &key) + .unwrap() + .unwrap() + .operation_id, + newer.id + ); + } + + #[test] + fn vote_diagnostic_contextualizes_exhausted_dapi_addresses() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp_dir.path()); + let sdk = context.sdk(); + let addresses = sdk.address_list(); + let live_addresses = addresses.get_live_addresses(); + assert!( + !live_addresses.is_empty(), + "test SDK must have DAPI addresses" + ); + for address in live_addresses { + assert!(addresses.ban(&address)); + } + + let operation_id = DpnsVoteOperationId::from_bytes([3; 16]); + let key = DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([4; 32]), + vote_poll_id: Identifier::from([5; 32]), + }; + context.record_dpns_vote_diagnostic_with_dapi_context( + operation_id, + key, + dapi_connection_refused_error(), + &sdk, + ); + + let diagnostics = context.dpns_vote_operation_diagnostics(operation_id); + assert!(matches!( + diagnostics.as_slice(), + [error] if matches!(error.as_ref(), TaskError::DapiAllAddressesExhausted { .. }) + )); + } + + #[test] + fn preflight_diagnostics_preserve_network_cause_and_exhaustion_context() { + let temp_dir = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(temp_dir.path()); + let sdk = context.sdk(); + let addresses = sdk.address_list(); + for address in addresses.get_live_addresses() { + assert!(addresses.ban(&address)); + } + let source = Arc::new(dapi_connection_refused_error()); + let operation_id = DpnsVoteOperationId::from_bytes([3; 16]); + context.record_dpns_vote_diagnostic_with_dapi_context( + operation_id, + DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([4; 32]), + vote_poll_id: Identifier::from([5; 32]), + }, + TaskError::DpnsVotePreflightFailed { + source: Arc::clone(&source), + }, + &sdk, + ); + let diagnostics = context.dpns_vote_operation_diagnostics(operation_id); + let TaskError::DapiAllAddressesExhausted { + source: contextualized, + } = diagnostics[0].as_ref() + else { + panic!("preflight diagnostics must explain exhausted addresses"); + }; + let TaskError::DpnsVotePreflightFailed { source: retained } = contextualized.as_ref() + else { + panic!("preflight diagnostics must retain the typed envelope"); + }; + assert!(Arc::ptr_eq(&source, retained)); + assert!(diagnostics[0].contains_dapi_reachability_failure()); + } + + /// VOTE-TC-033: an inner scheduled rejection is never classified as success. + #[test] + fn scheduled_inner_rejection_needs_attention() { + let attempt = Ok(vote_on_dpns_name::DpnsVoteAttempt::Rejected( + TaskError::DpnsVoteTargetBusy, + )); + assert_eq!( + classify_vote_attempt(&attempt, VoteTiming::Scheduled(42)), + ( + DpnsVoteTargetStatus::Rejected, + Some(DpnsVoteFailure::PlatformRejected) + ) + ); + } + + /// VOTE-TC-034/052: an ambiguous post-broadcast result stays locked. + #[test] + fn cause_less_wait_failure_is_unconfirmed_not_retryable() { + let attempt = Ok(vote_on_dpns_name::DpnsVoteAttempt::Unconfirmed( + TaskError::DpnsVoteTargetBusy, + )); + let (status, _) = classify_vote_attempt(&attempt, VoteTiming::Scheduled(42)); + assert_eq!(status, DpnsVoteTargetStatus::Unconfirmed); + assert!(status.holds_lock()); + } + + #[test] + fn exact_reconciliation_confirms_only_the_requested_choice() { + assert_eq!( + classify_reconciled_vote(Some(ResourceVoteChoice::Lock), ResourceVoteChoice::Lock,), + Some(DpnsVoteTargetStatus::Confirmed) + ); + assert_eq!( + classify_reconciled_vote(Some(ResourceVoteChoice::Abstain), ResourceVoteChoice::Lock,), + None, + "a mismatched row may predate the submitted transition and remains ambiguous" + ); + assert_eq!( + classify_reconciled_vote(None, ResourceVoteChoice::Lock,), + None, + "an absent exact row remains ambiguous and must not release its lock" + ); + } + + /// Neither an elapsed local deadline nor a missing or different current + /// vote proves that an ambiguous broadcast was not applied: reconciliation + /// and restart recovery must both leave the target unconfirmed and locked. + #[tokio::test] + async fn review_safety_elapsed_deadline_keeps_ambiguous_votes_locked() { + let (_temp, context) = vote_context(); + context.seed_dpns_contest_for_test("dominguez", Some(1_000), false); + let contests = context.all_contested_names().unwrap(); + assert!( + voting_ended_outcome(contests.first(), now_ms()).is_some(), + "the contest deadline has elapsed" + ); + let operation = unconfirmed_operation_for(&context, "dominguez"); + let key = operation.targets[0].target.key.clone(); + + for observed in [None, Some(ResourceVoteChoice::Abstain)] { + let mut sdk = Sdk::new_mock(); + expect_current_vote(&mut sdk, &context, &key, "dominguez", observed).await; + context + .reconcile_dpns_vote_operation(operation.id, &sdk) + .await + .unwrap(); + context.recover_interrupted_dpns_vote_operations().unwrap(); + assert_eq!( + context + .dpns_vote_operation(operation.id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Unconfirmed, + "observed {observed:?}" + ); + assert_eq!( + context.dpns_vote_target_status(&key).unwrap(), + Some(DpnsVoteTargetStatus::Unconfirmed), + "the lock must survive, observed {observed:?}" + ); + } + } + + #[test] + fn poll_availability_requires_a_cached_decided_contest() { + let (_temp, context) = vote_context(); + assert_eq!( + dpns_vote_poll_availability(None), + DpnsVotePollAvailability::MayAccept, + "an uncached contest is unknown, not closed" + ); + + for (end_time, closed, expected) in [ + (Some(2_000), false, DpnsVotePollAvailability::MayAccept), + (None, false, DpnsVotePollAvailability::MayAccept), + (Some(1_000), false, DpnsVotePollAvailability::MayAccept), + (Some(2_000), true, DpnsVotePollAvailability::ProvedClosed), + ] { + context.seed_dpns_contest_for_test("dominguez", end_time, closed); + let contests = context.all_contested_names().expect("cached contests"); + assert_eq!( + dpns_vote_poll_availability(contests.first()), + expected, + "end_time {end_time:?}, closed {closed}" + ); + } + } + + #[tokio::test] + async fn closed_contest_cleanup_does_not_prove_a_vote_failed() { + let (_temp, context) = vote_context(); + context.seed_dpns_contest_for_test("dominguez", Some(1), true); + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: context.dpns_vote_poll_id("dominguez").unwrap(), + }, + voter_alias: None, + contested_name: "dominguez".into(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Now, + }]); + operation.targets[0].status = DpnsVoteTargetStatus::Unconfirmed; + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + let key = &operation.targets[0].target.key; + let mut sdk = Sdk::new_mock(); + sdk.mock().expect_fetch_many::( + ContestedResourceVotesGivenByIdentityQuery { + identity_id: key.voter_id, + offset: None, + limit: Some(1), + start_at: Some((key.vote_poll_id.to_buffer(), true)), + order_ascending: true, + }, + Some(Default::default()), + ).await.unwrap(); + context + .reconcile_dpns_vote_operation(operation.id, &sdk) + .await + .unwrap(); + let saved = context.dpns_vote_operation(operation.id).unwrap().unwrap(); + assert_eq!(saved.targets[0].status, DpnsVoteTargetStatus::Unconfirmed); + assert_eq!( + context + .dpns_vote_count(key.voter_id, key.vote_poll_id) + .unwrap(), + None + ); + } + + #[test] + fn repeated_mismatches_keep_an_ambiguous_vote_locked() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp_dir.path()); + let kv = crate::wallet_backend::DetKv::from_store(Arc::new( + crate::wallet_backend::kv_test_support::InMemoryKv::default(), + )); + context.set_det_kv_override_for_test(kv); + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([2; 32]), + }, + voter_alias: None, + contested_name: "dominguez".to_owned(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: Some(ResourceVoteChoice::Abstain), + timing: VoteTiming::Now, + }]); + operation.targets[0].status = DpnsVoteTargetStatus::Confirming; + let operation_id = operation.id; + let key = operation.targets[0].target.key.clone(); + context + .insert_dpns_vote_operation(&mut operation, None) + .expect("persist confirming operation"); + context + .update_dpns_vote_target( + operation_id, + &key, + DpnsVoteTargetStatus::Unconfirmed, + Some(DpnsVoteFailure::ResultUnconfirmed), + ) + .expect("persist unconfirmed operation"); + assert_eq!( + context + .dpns_vote_operation(operation_id) + .unwrap() + .unwrap() + .targets[0] + .target + .current_choice, + None, + "the pre-broadcast choice must not count as reconciliation corroboration" + ); + + let observed = Some(ResourceVoteChoice::Abstain); + let first_status = classify_reconciled_vote(observed, ResourceVoteChoice::Lock) + .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); + assert!( + context + .update_dpns_vote_reconciliation(operation_id, &key, None, observed, first_status,) + .expect("persist first observation") + ); + assert_eq!(first_status, DpnsVoteTargetStatus::Unconfirmed); + + let persisted = context.dpns_vote_operation(operation_id).unwrap().unwrap(); + let second_status = classify_reconciled_vote(observed, ResourceVoteChoice::Lock) + .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); + assert!( + context + .update_dpns_vote_reconciliation( + operation_id, + &key, + persisted.targets[0].target.current_choice, + observed, + second_status, + ) + .expect("persist corroborated observation") + ); + + let target = &context + .dpns_vote_operation(operation_id) + .unwrap() + .unwrap() + .targets[0]; + assert_eq!(target.status, DpnsVoteTargetStatus::Unconfirmed); + assert!(target.status.holds_lock()); + assert_eq!( + context.dpns_vote_target_status(&key).unwrap(), + Some(DpnsVoteTargetStatus::Unconfirmed) + ); + } + + #[test] + fn scheduled_terminal_or_unconfirmed_targets_are_not_due_for_rebroadcast() { + use DpnsVoteTargetStatus as S; + let due_at = 1_000_000; + assert!( + scheduled_target_should_execute(S::Scheduled, due_at, due_at, None), + "control: a due schedule is executed" + ); + for status in [ + S::Submitting, + S::Confirming, + S::Confirmed, + S::Unconfirmed, + S::Rejected, + S::FailedBeforeSubmission, + S::NotApplied, + S::Cancelled, + ] { + for preserve_eligibility_since_ms in [None, Some(due_at)] { + assert!( + !scheduled_target_should_execute( + status, + due_at, + due_at, + preserve_eligibility_since_ms + ), + "{status:?} must never be sent again by the sweep" + ); + } + } + } + + #[tokio::test] + async fn scheduled_sweep_dispatch_wraps_recovery_failures() { + use crate::app::TaskResult; + use crate::app_dir::ensure_env_file; + use crate::context::connection_status::ConnectionStatus; + use crate::database::test_helpers::create_database_at_path; + use crate::utils::egui_mpsc::SenderAsync; + use crate::utils::tasks::TaskManager; + + let temp_dir = tempfile::tempdir().expect("tempdir"); + let data_dir = temp_dir.path().to_path_buf(); + ensure_env_file(&data_dir); + let database = + Arc::new(create_database_at_path(&data_dir.join("data.db")).expect("test database")); + let app_kv = AppContext::open_app_kv(&data_dir).expect("app kv"); + let secret_store = AppContext::open_secret_store(&data_dir).expect("secret store"); + let context = AppContext::new( + data_dir, + Network::Testnet, + database, + Arc::new(TaskManager::new()), + Arc::new(ConnectionStatus::new()), + egui::Context::default(), + app_kv, + secret_store, + crate::model::user_role::UserRoleCell::default(), + ) + .expect("offline testnet AppContext"); + let (tx, _rx) = tokio::sync::mpsc::channel::(1); + let sender = SenderAsync::new(tx, context.egui_ctx().clone()); + + let error = context + .run_contested_resource_task( + ContestedResourceTask::CastDueScheduledVotes { + preserve_eligibility_since_ms: None, + reconcile_unconfirmed: true, + }, + &context.sdk(), + sender, + ) + .await + .expect_err("an unwired recovery must fail the scheduled sweep"); + + assert!(matches!( + error, + TaskError::ScheduledVoteSweepFailed { + network: Network::Testnet, + .. + } + )); + } + + #[tokio::test] + async fn failed_migration_retries_in_the_same_process() { + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(crate::wallet_backend::kv_test_support::FailingKv::default()); + let kv = crate::wallet_backend::DetKv::from_store(store.clone()); + let context = crate::context::test_support::test_app_context_with_kv( + dir.path(), + Arc::new(kv.clone()), + ); + context.set_det_kv_override_for_test(kv); + store.fail_next_gets_containing("det:dpns_vote_operations:v2:", 1); + assert!( + context + .ensure_dpns_vote_recovery(&context.sdk()) + .await + .is_err() + ); + assert!(!context.dpns_vote_recovery.lock().await.initialized); + context + .ensure_dpns_vote_recovery(&context.sdk()) + .await + .unwrap(); + assert!(context.dpns_vote_recovery.lock().await.initialized); + } + + #[tokio::test] + async fn followup_failed_scoped_recovery_preserves_other_live_claims() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let store = Arc::new(crate::wallet_backend::kv_test_support::FailingKv::default()); + let context = crate::context::test_support::test_app_context_with_kv( + temp_dir.path(), + Arc::new(crate::wallet_backend::DetKv::from_store(store.clone())), + ); + let (sender, _receiver) = tokio::sync::mpsc::channel::(8); + context + .ensure_wallet_backend(crate::utils::egui_mpsc::SenderAsync::new( + sender, + context.egui_ctx().clone(), + )) + .await + .expect("wire wallet backend offline"); + context + .set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(store.clone())); + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([2; 32]), + }, + voter_alias: None, + contested_name: "dominguez".to_owned(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Now, + }]); + operation.targets[0].status = DpnsVoteTargetStatus::Submitting; + let operation_id = operation.id; + let target_key = operation.targets[0].target.key.clone(); + context + .insert_dpns_vote_operation(&mut operation, None) + .expect("persist in-flight operation"); + context.dpns_vote_recovery.lock().await.initialized = true; + let mut live = operation.clone(); + live.id = AppContext::new_dpns_vote_operation(Vec::new()).id; + live.targets[0].target.key.voter_id = Identifier::from([3; 32]); + let live_key = live.targets[0].target.key.clone(); + context.insert_dpns_vote_operation(&mut live, None).unwrap(); + let _live_guard = context + .dpns_vote_dispatch + .acquire(live_key.voter_id) + .await + .unwrap(); + let own_guard = context + .dpns_vote_dispatch + .acquire(target_key.voter_id) + .await + .unwrap(); + assert!( + tokio::time::timeout( + std::time::Duration::from_millis(20), + context.recover_idle_dpns_vote_targets( + operation_id, + &BTreeSet::from([target_key.clone()]) + ), + ) + .await + .is_err(), + "recovery must wait for this target's live executor" + ); + assert_eq!( + context + .dpns_vote_operation(operation_id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Submitting + ); + drop(own_guard); + store.fail_next_puts_containing(&operation_id.to_string(), 2); + + let terminal_error = context + .update_dpns_vote_target( + operation_id, + &target_key, + DpnsVoteTargetStatus::Confirmed, + None, + ) + .expect_err("terminal operation write must fail"); + context + .recover_failed_dpns_vote_operation( + operation_id, + &BTreeSet::from([target_key.clone()]), + &terminal_error, + ) + .await; + + assert_eq!( + context + .dpns_vote_operation(operation_id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Submitting + ); + + store.fail_next_puts_containing(&operation_id.to_string(), 1); + assert!( + context + .ensure_dpns_vote_recovery(&context.sdk()) + .await + .is_err() + ); + assert!( + context + .dpns_vote_recovery + .lock() + .await + .pending + .get(&operation_id) + .is_some_and(|keys| keys.contains(&target_key)), + "failed persistence must retain recovery keys" + ); + tokio::time::timeout( + std::time::Duration::from_secs(2), + context.ensure_dpns_vote_recovery(&context.sdk()), + ) + .await + .expect("unrelated live voter cannot block scoped recovery") + .unwrap(); + assert_eq!( + context + .dpns_vote_operation(live.id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Submitting, + "recovery cannot release an unrelated live claim" + ); + assert_eq!( + context + .dpns_vote_operation(operation_id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::FailedBeforeSubmission + ); + } + + #[test] + fn scheduled_pre_broadcast_failure_remains_retryable() { + let attempt = Err(TaskError::DpnsVoteTargetBusy); + + assert_eq!( + classify_vote_attempt(&attempt, VoteTiming::Scheduled(42)), + ( + DpnsVoteTargetStatus::Scheduled, + Some(DpnsVoteFailure::SubmissionFailed), + ) + ); + assert_eq!( + classify_vote_attempt(&attempt, VoteTiming::Now), + ( + DpnsVoteTargetStatus::FailedBeforeSubmission, + Some(DpnsVoteFailure::SubmissionFailed), + ) + ); + } + + /// VOTE-TC-103 (executor half): a target whose contest closed before it + /// was sent fails before submission with `VotingEnded`, even when scheduled. + #[test] + fn a_closed_contest_fails_its_unsent_targets_as_voting_ended() { + let (_temp, context) = vote_context(); + assert_eq!( + voting_ended_outcome(None, 5_000), + None, + "uncached is not closed" + ); + context.seed_dpns_contest_for_test("dominguez", Some(5_000), false); + let contests = context.all_contested_names().expect("cached contests"); + assert_eq!(voting_ended_outcome(contests.first(), 4_999), None); + assert_eq!( + voting_ended_outcome(contests.first(), 5_000), + Some(( + DpnsVoteTargetStatus::FailedBeforeSubmission, + Some(DpnsVoteFailure::VotingEnded) + )) + ); + } + + /// A contest skeleton whose contenders never loaded is `Unknown`, which + /// is no evidence of closure: the target must neither fail as + /// `VotingEnded` nor lose its lock on a nonmatching reconciliation. + #[test] + fn an_unknown_contest_is_not_treated_as_closed() { + let (_temp, context) = vote_context(); + context + .insert_name_contests_as_normalized_names(vec!["dominguez".to_owned()]) + .expect("store contest skeleton"); + let contests = context.all_contested_names().expect("cached contests"); + let skeleton = contests.first().expect("skeleton is cached"); + assert_eq!( + skeleton.state, + crate::model::contested_name::ContestState::Unknown + ); + + let availability = dpns_vote_poll_availability(Some(skeleton)); + assert_eq!(availability, DpnsVotePollAvailability::MayAccept); + assert_eq!( + voting_ended_outcome(Some(skeleton), 5_000), + None, + "an unknown contest must not fail a vote as VotingEnded" + ); + for observed in [None, Some(ResourceVoteChoice::Abstain)] { + assert_eq!( + classify_reconciled_vote(observed, ResourceVoteChoice::Lock), + None, + "observed {observed:?}: the unresolved target stays locked" + ); + } + } + + /// Submission preflight refreshes only the operation's own voters, not + /// every loaded masternode. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn scoped_vote_state_refresh_queries_only_the_requested_voters() { + use dash_sdk::query_types::ResourceVotesByIdentity; + let temp = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp.path()); + let (tx, _rx) = tokio::sync::mpsc::channel::(8); + context + .ensure_wallet_backend(crate::utils::egui_mpsc::SenderAsync::new( + tx, + context.egui_ctx().clone(), + )) + .await + .expect("wire wallet backend offline"); + let mut voters = Vec::new(); + for byte in [1, 2] { + let mut voter = qualified_identity(byte); + voter.identity_type = IdentityType::Masternode; + context + .insert_local_qualified_identity(&voter, &None) + .expect("load masternode"); + voters.push(voter.identity.id()); + } + let mut sdk = Sdk::new_mock(); + sdk.mock() + .expect_fetch_many::( + ContestedResourceVotesGivenByIdentityQuery { + identity_id: voters[0], + offset: None, + limit: Some(100), + start_at: None, + order_ascending: true, + }, + Some(ResourceVotesByIdentity::default()), + ) + .await + .expect("mock vote query"); + + let results = context + .refresh_dpns_vote_states_for(&sdk, &std::collections::BTreeSet::from([voters[0]])) + .await + .expect("refresh"); + + assert_eq!(results.keys().copied().collect::>(), vec![voters[0]]); + assert!(results[&voters[0]].is_ok(), "{results:?}"); + context.wallet_backend().unwrap().shutdown().await; + } + + /// VOTE-TC-103 (executor half): a queued target on a contest that closed + /// after review is claimed and failed as `VotingEnded`; nothing is sent + /// (the mock SDK has no broadcast expectation, so a submit would fail). + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn executor_fails_a_closed_contest_target_without_sending() { + use crate::context::connection_status::ConnectionStatus; + use crate::database::test_helpers::create_database_at_path; + use crate::utils::tasks::TaskManager; + use dash_sdk::query_types::ResourceVotesByIdentity; + // Loading a local masternode needs the wallet backend wired offline. + let temp = tempfile::tempdir().unwrap(); + let data_dir = temp.path().to_path_buf(); + crate::app_dir::ensure_env_file(&data_dir); + let context = AppContext::new( + data_dir.clone(), + Network::Testnet, + Arc::new(create_database_at_path(&data_dir.join("data.db")).unwrap()), + Arc::new(TaskManager::new()), + Arc::new(ConnectionStatus::new()), + egui::Context::default(), + AppContext::open_app_kv(&data_dir).unwrap(), + AppContext::open_secret_store(&data_dir).unwrap(), + crate::model::user_role::UserRoleCell::default(), + ) + .unwrap(); + let (tx, _rx) = tokio::sync::mpsc::channel::(32); + context + .ensure_wallet_backend(crate::utils::egui_mpsc::SenderAsync::new( + tx, + context.egui_ctx().clone(), + )) + .await + .unwrap(); + let mut voter = qualified_identity(1); + voter.identity_type = IdentityType::Masternode; + context + .insert_local_qualified_identity(&voter, &None) + .unwrap(); + context.seed_dpns_contest_for_test("alice", Some(1), false); + let mut sdk = Sdk::new_mock(); + sdk.mock() + .expect_fetch_many::( + ContestedResourceVotesGivenByIdentityQuery { + identity_id: voter.identity.id(), + offset: None, + limit: Some(100), + start_at: None, + order_ascending: true, + }, + Some(ResourceVotesByIdentity::default()), + ) + .await + .unwrap(); + let operation = AppContext::new_dpns_vote_operation(vec![ + context + .dpns_vote_target( + &voter, + "alice", + ResourceVoteChoice::Lock, + VoteTiming::Now, + false, + ) + .unwrap(), + ]); + let operation_id = operation.id; + let result = context + .execute_dpns_vote_operation(operation, vec![voter], None, &sdk) + .await; + let stored = context + .dpns_vote_operation(operation_id) + .unwrap() + .expect("the operation is journaled"); + assert_eq!( + (stored.targets[0].status, stored.targets[0].failure), + ( + DpnsVoteTargetStatus::FailedBeforeSubmission, + Some(DpnsVoteFailure::VotingEnded) + ), + "executor result: {result:?}" + ); + context.wallet_backend().unwrap().shutdown().await; + } + + #[test] + fn scheduled_missing_voter_remains_retryable() { + assert_eq!( + missing_voter_outcome(VoteTiming::Scheduled(42)), + ( + DpnsVoteTargetStatus::Scheduled, + Some(DpnsVoteFailure::VotingKeyMissing), + true, + ) + ); + assert_eq!( + missing_voter_outcome(VoteTiming::Now), + ( + DpnsVoteTargetStatus::FailedBeforeSubmission, + Some(DpnsVoteFailure::VotingKeyMissing), + false, + ) + ); + } + + #[test] + fn queued_schedule_remains_eligible_for_redrive() { + let now_ms = 1_000_000; + let stale_scheduled_at = now_ms - SCHEDULED_VOTE_MAX_LATENESS_MS - 1; + + assert!(scheduled_target_should_execute( + DpnsVoteTargetStatus::Queued, + stale_scheduled_at, + now_ms, + None, + )); + assert!(!scheduled_target_should_execute( + DpnsVoteTargetStatus::Scheduled, + stale_scheduled_at, + now_ms, + None, )); } diff --git a/src/backend_task/contested_names/query_dpns_contested_resources.rs b/src/backend_task/contested_names/query_dpns_contested_resources.rs index bb1391769..6c80394bb 100644 --- a/src/backend_task/contested_names/query_dpns_contested_resources.rs +++ b/src/backend_task/contested_names/query_dpns_contested_resources.rs @@ -10,14 +10,85 @@ use dash_sdk::dpp::platform_value::Value; use dash_sdk::drive::query::vote_polls_by_document_type_query::VotePollsByDocumentTypeQuery; use dash_sdk::platform::FetchMany; use dash_sdk::query_types::ContestedResource; +use std::future::Future; use std::sync::Arc; +use std::time::Duration; use tokio::sync::{OwnedSemaphorePermit, Semaphore}; +use tokio::task::JoinHandle; + +/// Extra attempts one contest page query gets after a retryable failure. +const MAX_PAGE_RETRIES: usize = 3; +/// Pause before the first retry of a page query; each later retry waits longer. +const PAGE_RETRY_DELAY: Duration = Duration::from_millis(500); + +/// Whether asking again, likely on another node, can answer a failed page query. +fn page_query_is_retryable(error: &dash_sdk::Error) -> bool { + // TODO(#875): replace substring match once the SDK exposes a + // structural "contract not found" variant. + matches!(error, dash_sdk::Error::StaleNode(_)) + || error + .to_string() + .contains("contract not found when querying from value with contract info") +} + +/// Run one contest page query, retrying a retryable failure at most +/// [`MAX_PAGE_RETRIES`] times with a growing pause in between. +async fn fetch_page_with_retries( + retry_delay: Duration, + mut fetch: impl FnMut() -> Fut, +) -> Result +where + Fut: Future>, +{ + let mut retries: u32 = 0; + loop { + let error = match fetch().await { + Ok(page) => return Ok(page), + Err(error) => error, + }; + tracing::error!("Error fetching contested resources: {}", error); + super::log_contested_proof_error(&error, RequestType::GetContestedResources); + if !page_query_is_retryable(&error) { + return Err(TaskError::from(error)); + } + if retries as usize >= MAX_PAGE_RETRIES { + tracing::error!("Max retries reached for query: {}", error); + return Err(TaskError::from(error)); + } + retries += 1; + tokio::time::sleep(retry_delay.saturating_mul(retries)).await; + } +} + +/// Wait for every contest query of a pass and tell whether all of them +/// succeeded. One that failed, or did not run to its end, left its contest +/// data stale. +async fn every_contest_query_succeeded(queries: Vec>) -> bool { + let mut succeeded = true; + for query in queries { + match query.await { + Ok(refreshed) => succeeded &= refreshed, + Err(e) => { + tracing::error!("Task failed: {:?}", e); + succeeded = false; + } + } + } + succeeded +} impl AppContext { + /// Refresh the contest cache, contenders, end times and every loaded node's + /// proved votes as one snapshot. + /// + /// `quiet` (the background timer) logs per-contest failures instead of + /// sending them to the UI, so an offline app does not raise a banner every + /// few minutes. pub(super) async fn query_dpns_contested_resources( self: &Arc, sdk: &Sdk, sender: crate::utils::egui_mpsc::SenderAsync, + quiet: bool, ) -> Result<(), TaskError> { let data_contract = self.dpns_contract.as_ref(); let document_type = data_contract @@ -30,7 +101,6 @@ impl AppContext { detail: "No contested index found on DPNS domain document type", }); }; - const MAX_RETRIES: usize = 3; let mut start_at_value = None; let mut names_to_be_updated = Vec::new(); loop { @@ -45,33 +115,10 @@ impl AppContext { order_ascending: true, }; - let mut retries = 0; - - let contested_resources = match ContestedResource::fetch_many(sdk, query.clone()).await - { - Ok(contested_resources) => contested_resources, - Err(e) => { - tracing::error!("Error fetching contested resources: {}", e); - super::log_contested_proof_error(&e, RequestType::GetContestedResources); - // TODO(#875): replace substring match once the SDK exposes a - // structural "contract not found" variant. - if matches!(e, dash_sdk::Error::StaleNode(_)) - || e.to_string().contains( - "contract not found when querying from value with contract info", - ) - { - retries += 1; - if retries > MAX_RETRIES { - tracing::error!("Max retries reached for query: {}", e); - return Err(TaskError::from(e)); - } else { - continue; - } - } else { - return Err(TaskError::from(e)); - } - } - }; + let contested_resources = fetch_page_with_retries(PAGE_RETRY_DELAY, || { + ContestedResource::fetch_many(sdk, query.clone()) + }) + .await?; let contested_resources_len = contested_resources.0.len(); if contested_resources_len == 0 { @@ -128,7 +175,7 @@ impl AppContext { Ok(permit) => permit, Err(e) => { tracing::error!("Semaphore closed while querying dpns end times: {}", e); - return; + return false; } }; @@ -143,6 +190,11 @@ impl AppContext { e ); } + true + } + Err(e) if quiet => { + tracing::debug!(error = ?e, "Background refresh could not query contest end times"); + false } Err(e) => { tracing::error!("Error querying dpns end times: {}", e); @@ -156,6 +208,7 @@ impl AppContext { send_err ); } + false } } }) @@ -178,7 +231,7 @@ impl AppContext { name, e ); - return; + return false; } }; @@ -194,6 +247,11 @@ impl AppContext { e ); } + true + } + Err(e) if quiet => { + tracing::debug!(error = ?e, %name, "Background refresh could not query contenders"); + false } Err(e) => { tracing::error!("Error querying dpns vote contenders for {}: {}", name, e); @@ -208,6 +266,7 @@ impl AppContext { send_err ); } + false } } }); @@ -215,13 +274,28 @@ impl AppContext { handles.push(handle); } - for handle in handles { - if let Err(e) = handle.await { - tracing::error!("Task failed: {:?}", e); - } - } + let contests_refreshed = every_contest_query_succeeded(handles).await; + // Publish contests and every loaded node's proved current votes as one + // completed refresh snapshot. Per-node failures are stored explicitly + // as unavailable instead of being mistaken for "Not voted". + let vote_states_refreshed = match self.refresh_dpns_vote_states(sdk).await { + Ok(results) => super::refresh_vote_states::every_voter_refreshed(&results), + Err(error) => { + tracing::warn!(?error, "Could not refresh DPNS current votes with contests"); + false + } + }; + self.refresh_masternode_list_membership().await; + self.forget_closed_dpns_vote_counts(); + self.recompute_dpns_vote_attention(); self.refresh_pending_dpns_usernames()?; + // A pass that left a contest stale or a node unchecked is not a + // completed refresh: the timer and the Votes-arrival refresh must be + // free to try again soon. + if contests_refreshed && vote_states_refreshed { + self.mark_dpns_contests_refreshed(); + } sender .send(TaskResult::unattributed_success( @@ -232,3 +306,75 @@ impl AppContext { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + use dash_sdk::error::StaleNodeError; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn stale_node() -> dash_sdk::Error { + dash_sdk::Error::StaleNode(StaleNodeError::Height { + expected_height: 10, + received_height: 1, + tolerance_blocks: 1, + }) + } + + /// A node that keeps answering as stale must end the query, not loop on it. + #[tokio::test] + async fn a_persistently_stale_node_ends_the_page_query_after_bounded_retries() { + let attempts = AtomicUsize::new(0); + let result: Result<(), _> = fetch_page_with_retries(Duration::ZERO, || async { + attempts.fetch_add(1, Ordering::SeqCst); + Err(stale_node()) + }) + .await; + + assert!(matches!(result, Err(TaskError::DapiStaleNode { .. }))); + assert_eq!(attempts.load(Ordering::SeqCst), MAX_PAGE_RETRIES + 1); + } + + #[tokio::test] + async fn a_page_query_recovers_when_a_retry_succeeds() { + let attempts = AtomicUsize::new(0); + let result = fetch_page_with_retries(Duration::ZERO, || async { + if attempts.fetch_add(1, Ordering::SeqCst) == 0 { + Err(stale_node()) + } else { + Ok(7) + } + }) + .await; + + assert!(matches!(result, Ok(7))); + assert_eq!(attempts.load(Ordering::SeqCst), 2); + } + + /// A pass is complete only when every contest query ran to its end and + /// succeeded. + #[tokio::test] + async fn contest_queries_succeed_only_when_every_one_of_them_did() { + let query = |refreshed: bool| tokio::spawn(async move { refreshed }); + assert!(every_contest_query_succeeded(vec![]).await); + assert!(every_contest_query_succeeded(vec![query(true), query(true)]).await); + assert!(!every_contest_query_succeeded(vec![query(false), query(true)]).await); + + let stopped = tokio::spawn(std::future::pending::()); + stopped.abort(); + assert!(!every_contest_query_succeeded(vec![stopped, query(true)]).await); + } + + #[tokio::test] + async fn a_failure_another_node_cannot_fix_is_not_retried() { + let attempts = AtomicUsize::new(0); + let result: Result<(), _> = fetch_page_with_retries(Duration::ZERO, || async { + attempts.fetch_add(1, Ordering::SeqCst); + Err(dash_sdk::Error::Generic("unreachable".to_owned())) + }) + .await; + + assert!(result.is_err()); + assert_eq!(attempts.load(Ordering::SeqCst), 1); + } +} diff --git a/src/backend_task/contested_names/refresh_vote_states.rs b/src/backend_task/contested_names/refresh_vote_states.rs new file mode 100644 index 000000000..7892a0416 --- /dev/null +++ b/src/backend_task/contested_names/refresh_vote_states.rs @@ -0,0 +1,121 @@ +//! Proved current-vote queries against Platform, one pass per loaded masternode. + +use crate::backend_task::error::TaskError; +use crate::context::{AppContext, DpnsVoteRefreshResults, MAX_CONCURRENT_DPNS_VOTERS}; +use dash_sdk::Sdk; +use dash_sdk::dpp::identity::accessors::IdentityGettersV0; +use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use dash_sdk::dpp::voting::votes::resource_vote::ResourceVote; +use dash_sdk::dpp::voting::votes::resource_vote::accessors::v0::ResourceVoteGettersV0; +use dash_sdk::drive::query::contested_resource_votes_given_by_identity_query::ContestedResourceVotesGivenByIdentityQuery; +use dash_sdk::platform::{FetchMany, Identifier}; +use futures::{StreamExt, stream}; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +const VOTE_QUERY_PAGE_SIZE: u16 = 100; + +/// Whether a refresh pass proved the vote state of every voter it covered. +pub(super) fn every_voter_refreshed(results: &DpnsVoteRefreshResults) -> bool { + results.values().all(Result::is_ok) +} + +impl AppContext { + /// Refresh proved vote state once per loaded masternode, paging only as needed. + pub(crate) async fn refresh_dpns_vote_states( + &self, + sdk: &Sdk, + ) -> Result { + let voters = self + .load_local_masternode_identities()? + .into_iter() + .map(|voter| voter.identity.id()) + .collect(); + self.refresh_voter_states(sdk, voters).await + } + + /// Refresh proved vote state for the loaded masternodes among `voter_ids`. + /// + /// Submission preflight uses this so one operation queries only its own + /// voters; ids that are not loaded masternodes are skipped and therefore + /// absent from the results. + pub(crate) async fn refresh_dpns_vote_states_for( + &self, + sdk: &Sdk, + voter_ids: &BTreeSet, + ) -> Result { + let voters = self + .load_local_masternode_identities()? + .into_iter() + .map(|voter| voter.identity.id()) + .filter(|voter_id| voter_ids.contains(voter_id)) + .collect(); + self.refresh_voter_states(sdk, voters).await + } + + async fn refresh_voter_states( + &self, + sdk: &Sdk, + voters: Vec, + ) -> Result { + let kv = self.det_kv()?; + + Ok(stream::iter(voters) + .map(|voter_id| { + let sdk = sdk.clone(); + let kv = kv.clone(); + async move { + let result = async { + let _permit = self.dpns_vote_refresh_permits.acquire().await + .map_err(|_| TaskError::DpnsVoteCoordinatorUnavailable)?; + self.publish_dpns_vote_state( + &kv, voter_id, fetch_votes_for_voter(&sdk, voter_id), + ).await + }.await.map_err(Arc::new); + if let Err(error) = &result { + tracing::warn!(?error, %voter_id, "Could not refresh proved DPNS vote state"); + } + (voter_id, result) + } + }) + .buffer_unordered(MAX_CONCURRENT_DPNS_VOTERS) + .collect::>() + .await) + } +} + +async fn fetch_votes_for_voter( + sdk: &Sdk, + voter_id: Identifier, +) -> Result, Box> { + let mut votes = BTreeMap::new(); + let mut start_at = None; + loop { + let page = ResourceVote::fetch_many( + sdk, + ContestedResourceVotesGivenByIdentityQuery { + identity_id: voter_id, + offset: None, + limit: Some(VOTE_QUERY_PAGE_SIZE), + start_at, + order_ascending: true, + }, + ) + .await?; + let page_len = page.len(); + let last_key = page.last().map(|(id, _)| id.to_buffer()); + for (poll_id, vote) in page { + if let Some(vote) = vote { + votes.insert(poll_id.to_buffer(), vote.resource_vote_choice()); + } + } + if page_len < usize::from(VOTE_QUERY_PAGE_SIZE) { + break; + } + let Some(last_key) = last_key else { + break; + }; + start_at = Some((last_key, false)); + } + Ok(votes) +} diff --git a/src/backend_task/contested_names/vote_on_dpns_name.rs b/src/backend_task/contested_names/vote_on_dpns_name.rs index 23ac03f5a..a0e7e8fb4 100644 --- a/src/backend_task/contested_names/vote_on_dpns_name.rs +++ b/src/backend_task/contested_names/vote_on_dpns_name.rs @@ -1,78 +1,183 @@ -use crate::app::TaskResult; -use crate::backend_task::BackendTaskSuccessResult; use crate::backend_task::error::TaskError; use crate::context::AppContext; +use crate::model::dpns_voting::{DpnsVoteOperationId, DpnsVoteTargetKey, dpns_vote_poll}; use crate::model::qualified_identity::QualifiedIdentity; use dash_sdk::Sdk; -use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; -use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; +use dash_sdk::dpp::consensus::ConsensusError; +use dash_sdk::dpp::consensus::basic::BasicError; +use dash_sdk::dpp::identifier::MasternodeIdentifiers; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; +use dash_sdk::dpp::identity::hash::IdentityPublicKeyHashMethodsV0; use dash_sdk::dpp::platform_value::Value; use dash_sdk::dpp::platform_value::string_encoding::Encoding; +use dash_sdk::dpp::state_transition::masternode_vote_transition::MasternodeVoteTransition; +use dash_sdk::dpp::state_transition::masternode_vote_transition::methods::MasternodeVoteTransitionMethodsV0; +use dash_sdk::dpp::state_transition::{StateTransition, StateTransitionStructureValidation}; use dash_sdk::dpp::util::strings::convert_to_homograph_safe_chars; use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; use dash_sdk::dpp::voting::vote_polls::contested_document_resource_vote_poll::ContestedDocumentResourceVotePoll; use dash_sdk::dpp::voting::votes::Vote; use dash_sdk::dpp::voting::votes::resource_vote::ResourceVote; +use dash_sdk::dpp::voting::votes::resource_vote::accessors::v0::ResourceVoteGettersV0; use dash_sdk::dpp::voting::votes::resource_vote::v0::ResourceVoteV0; +use dash_sdk::drive::query::contested_resource_votes_given_by_identity_query::ContestedResourceVotesGivenByIdentityQuery; use dash_sdk::drive::query::vote_polls_by_document_type_query::VotePollsByDocumentTypeQuery; use dash_sdk::platform::FetchMany; -use dash_sdk::platform::transition::vote::PutVote; +use dash_sdk::platform::Identifier; +use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; +use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; +use dash_sdk::platform::transition::put_settings::PutSettings; +use dash_sdk::platform::transition::waitable::Waitable; use dash_sdk::query_types::ContestedResource; use std::sync::Arc; -/// Build `[Value::from("dash"), Value::Text(normalized_label.to_owned())]` for a DPNS vote poll. +#[derive(Debug)] +pub(super) enum DpnsVoteAttempt { + Confirmed, + Unconfirmed(TaskError), + Rejected(TaskError), + FailedBeforeSubmission(TaskError), +} + +fn ensure_valid_vote_transition_structure( + state_transition: &StateTransition, + sdk: &Sdk, +) -> Result<(), TaskError> { + let validation_result = state_transition.validate_structure(sdk.version()); + if validation_result.is_valid() + || validation_result.errors.iter().all(|error| { + matches!( + error, + ConsensusError::BasicError(BasicError::UnsupportedFeatureError(_)) + ) + }) + { + Ok(()) + } else { + Err(TaskError::from(dash_sdk::Error::from(validation_result))) + } +} + +fn classify_post_broadcast_error(error: dash_sdk::Error) -> DpnsVoteAttempt { + let rejected = matches!( + &error, + dash_sdk::Error::StateTransitionBroadcastError(broadcast_error) + if broadcast_error.cause.is_some() + ); + let error = TaskError::from(error); + if rejected { + DpnsVoteAttempt::Rejected(error) + } else { + DpnsVoteAttempt::Unconfirmed(error) + } +} + +fn classify_broadcast_error(error: dash_sdk::Error) -> DpnsVoteAttempt { + match &error { + dash_sdk::Error::Protocol(dash_sdk::dpp::ProtocolError::ConsensusError(_)) => { + DpnsVoteAttempt::Rejected(TaskError::from(error)) + } + dash_sdk::Error::StateTransitionBroadcastError(broadcast_error) => { + let rejected = broadcast_error.cause.is_some(); + let error = TaskError::from(error); + if rejected { + DpnsVoteAttempt::Rejected(error) + } else { + DpnsVoteAttempt::Unconfirmed(error) + } + } + _ => DpnsVoteAttempt::Unconfirmed(TaskError::from(error)), + } +} + +fn classify_broadcast_journal_result( + result: Result, +) -> Result<(), DpnsVoteAttempt> { + match result { + Ok(true) => Ok(()), + Ok(false) => Err(DpnsVoteAttempt::FailedBeforeSubmission( + TaskError::DpnsVoteBroadcastPhaseNotMarked, + )), + Err(error) => Err(DpnsVoteAttempt::FailedBeforeSubmission(error)), + } +} + +/// Read one node's proved current vote on one contest. +pub(super) async fn proved_dpns_vote_choice( + key: &DpnsVoteTargetKey, + sdk: &Sdk, +) -> Result, TaskError> { + let query = ContestedResourceVotesGivenByIdentityQuery { + identity_id: key.voter_id, + offset: None, + limit: Some(1), + start_at: Some((key.vote_poll_id.to_buffer(), true)), + order_ascending: true, + }; + let votes = ResourceVote::fetch_many(sdk, query) + .await + .map_err(TaskError::from)?; + Ok(votes + .get(&key.vote_poll_id) + .and_then(Option::as_ref) + .map(ResourceVoteGettersV0::resource_vote_choice)) +} + +/// Settle a rejection that `broadcast` reported. /// -/// Caller must pre-normalize the label via `convert_to_homograph_safe_chars` -/// (`alice` → `a11ce`); Platform indexes polls under the normalized form. -fn dpns_vote_poll_index_values(normalized_label: &str) -> Vec { - vec![ - Value::from("dash"), - Value::Text(normalized_label.to_owned()), - ] +/// `broadcast` retries internally and reports only its last attempt, so the +/// rejection can follow an earlier attempt that Platform applied (a repeated +/// transition is refused once the first one is in a block). A proved current +/// vote equal to the requested choice shows the vote went in. Anything else, +/// including a failed read, leaves the rejection standing: the next vote on +/// the target starts from a fresh proved read anyway. +fn settle_broadcast_rejection( + rejection: TaskError, + requested: ResourceVoteChoice, + proved_current: Result, TaskError>, +) -> DpnsVoteAttempt { + match proved_current { + Ok(Some(current)) if current == requested => DpnsVoteAttempt::Confirmed, + Ok(_) => DpnsVoteAttempt::Rejected(rejection), + Err(read_error) => { + tracing::debug!( + ?read_error, + "Could not read the current vote after a rejected DPNS vote broadcast" + ); + DpnsVoteAttempt::Rejected(rejection) + } + } +} + +async fn broadcast_after_journal_mark( + mark_broadcast: Mark, + broadcast: Broadcast, +) -> Result<(), DpnsVoteAttempt> +where + Mark: FnOnce() -> Result, + Broadcast: FnOnce() -> BroadcastFuture, + BroadcastFuture: std::future::Future>, +{ + classify_broadcast_journal_result(mark_broadcast())?; + broadcast().await.map_err(classify_broadcast_error) } impl AppContext { - pub(super) async fn vote_on_dpns_name( - self: &Arc, + /// Build a DPNS poll only after proving that it currently exists. + pub(super) async fn checked_dpns_vote_poll( + &self, name: &str, - vote_choice: ResourceVoteChoice, - voters: &[QualifiedIdentity], sdk: &Sdk, - sender: crate::utils::egui_mpsc::SenderAsync, - ) -> Result { - sender - .send(TaskResult::Refresh) - .await - .map_err(|_| TaskError::InternalSendError)?; - - let data_contract = self.dpns_contract.as_ref(); - let document_type = data_contract - .document_type_for_name("domain") - .map_err(|_| TaskError::DataContractNotFound)?; - - let Some(contested_index) = document_type.find_contested_index() else { - return Err(TaskError::ContractSchemaMismatch { - detail: "DPNS domain document type has no contested index", - }); - }; - + ) -> Result { + let vote_poll = dpns_vote_poll(&self.dpns_contract, name)?; let normalized_label = convert_to_homograph_safe_chars(name); - let index_values = dpns_vote_poll_index_values(&normalized_label); - - let vote_poll = ContestedDocumentResourceVotePoll { - index_name: contested_index.name.clone(), - index_values, - document_type_name: document_type.name().to_string(), - contract_id: data_contract.id(), - }; // Pre-flight: confirm Platform has an open poll for this label before // broadcasting — fails fast with VotePollNotFound if it doesn't. let existence_query = VotePollsByDocumentTypeQuery { - contract_id: data_contract.id(), - document_type_name: document_type.name().to_string(), - index_name: contested_index.name.clone(), + contract_id: vote_poll.contract_id, + document_type_name: vote_poll.document_type_name.clone(), + index_name: vote_poll.index_name.clone(), start_index_values: vec![Value::from("dash")], end_index_values: vec![], // Start exactly at our normalized label (inclusive) — a single @@ -94,38 +199,75 @@ impl AppContext { name: name.to_owned(), }); } + Ok(vote_poll) + } - let mut vote_results = vec![]; - - for qualified_identity in voters.iter() { - if let Some((_, public_key)) = &qualified_identity.associated_voter_identity { - let resource_vote = ResourceVoteV0 { - vote_poll: vote_poll.clone().into(), - resource_vote_choice: vote_choice, - }; - let vote = Vote::ResourceVote(ResourceVote::V0(resource_vote)); - - let result = vote - .put_to_platform_and_wait_for_response( - qualified_identity.identity.id(), - public_key, - sdk, - qualified_identity, - None, - ) - .await - .map(|_| ()) - .map_err(|e| std::sync::Arc::new(TaskError::from(e))); - - vote_results.push((name.to_owned(), vote_choice, result)); - } else { - return Err(TaskError::NoVotingIdentity { - identity_id: qualified_identity.identity.id().to_string(Encoding::Base58), - }); - } + pub(super) async fn submit_dpns_vote( + self: &Arc, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, + name: &str, + vote_choice: ResourceVoteChoice, + qualified_identity: &QualifiedIdentity, + sdk: &Sdk, + ) -> Result { + let vote_poll = self.checked_dpns_vote_poll(name, sdk).await?; + let Some((_, public_key)) = &qualified_identity.associated_voter_identity else { + return Err(TaskError::NoVotingIdentity { + identity_id: qualified_identity.identity.id().to_string(Encoding::Base58), + }); + }; + let resource_vote = ResourceVoteV0 { + vote_poll: vote_poll.into(), + resource_vote_choice: vote_choice, + }; + let vote = Vote::ResourceVote(ResourceVote::V0(resource_vote)); + let voter_pro_tx_hash = qualified_identity.identity.id(); + let voting_public_key_hash = public_key + .public_key_hash() + .map_err(dash_sdk::Error::from)?; + let voting_identity_id = Identifier::create_voter_identifier( + voter_pro_tx_hash.as_bytes(), + &voting_public_key_hash, + ); + let settings = PutSettings::default(); + let nonce = sdk + .get_identity_nonce(voting_identity_id, true, Some(settings)) + .await + .map_err(TaskError::from)?; + let state_transition = MasternodeVoteTransition::try_from_vote_with_signer( + vote, + qualified_identity, + voter_pro_tx_hash, + public_key, + nonce, + sdk.version(), + None, + ) + .await + .map_err(dash_sdk::Error::from)?; + ensure_valid_vote_transition_structure(&state_transition, sdk)?; + state_transition.broadcast_request_for_state_transition()?; + if let Err(attempt) = broadcast_after_journal_mark( + || self.mark_dpns_vote_broadcast(operation_id, key), + || state_transition.broadcast(sdk, Some(settings)), + ) + .await + { + return Ok(match attempt { + DpnsVoteAttempt::Rejected(rejection) => settle_broadcast_rejection( + rejection, + vote_choice, + proved_dpns_vote_choice(key, sdk).await, + ), + attempt => attempt, + }); } - Ok(BackendTaskSuccessResult::DPNSVoteResults(vote_results)) + match Vote::wait_for_response(sdk, state_transition, Some(settings)).await { + Ok(_) => Ok(DpnsVoteAttempt::Confirmed), + Err(error) => Ok(classify_post_broadcast_error(error)), + } } } @@ -134,39 +276,155 @@ mod tests { use super::*; #[test] - fn index_values_uses_the_given_normalized_label() { - // Given: a pre-normalized DPNS label (homographs already substituted). - let normalized = "a11ce"; + fn convert_to_homograph_safe_chars_maps_alice_to_a11ce() { + // Given: the canonical DPNS homograph substitutions (i/l → 1, o → 0). + // When: normalizing a label with i/l/o. + let normalized = convert_to_homograph_safe_chars("alice"); + + // Then: the result matches the constant used by the vote poll tests. + assert_eq!(normalized, "a11ce"); + } - // When: constructing the vote poll index values. - let values = dpns_vote_poll_index_values(normalized); + #[test] + fn non_broadcast_wait_error_is_unconfirmed() { + let attempt = + classify_post_broadcast_error(dash_sdk::Error::Generic("wait failed".to_owned())); - // Then: first element is the `"dash"` parent, second is the label as-given. - assert_eq!(values.len(), 2); - assert_eq!(values[0], Value::from("dash")); - assert_eq!(values[1], Value::Text("a11ce".to_owned())); + assert!(matches!(attempt, DpnsVoteAttempt::Unconfirmed(_))); } #[test] - fn index_values_do_not_renormalize_the_label() { - // Given: a label that still contains homograph characters. - let not_yet_normalized = "alice"; + fn broadcast_transport_error_after_phase_boundary_is_unconfirmed() { + let attempt = + classify_broadcast_error(dash_sdk::Error::Generic("connection refused".to_owned())); - // When: passing it directly to the helper (violating the contract). - let values = dpns_vote_poll_index_values(not_yet_normalized); + assert!(matches!(attempt, DpnsVoteAttempt::Unconfirmed(_))); + } + + #[test] + fn followup_cause_less_broadcast_error_remains_unconfirmed() { + let attempt = classify_broadcast_error( + dash_sdk::error::StateTransitionBroadcastError { + code: 1, + message: "broadcast rejected".to_owned(), + cause: None, + } + .into(), + ); - // Then: the helper does NOT renormalize — the raw label is returned as-is. - // (Caller is responsible for normalizing before calling.) - assert_eq!(values[1], Value::Text("alice".to_owned())); + assert!(matches!(attempt, DpnsVoteAttempt::Unconfirmed(_))); } #[test] - fn convert_to_homograph_safe_chars_maps_alice_to_a11ce() { - // Given: the canonical DPNS homograph substitutions (i/l → 1, o → 0). - // When: normalizing a label with i/l/o. - let normalized = convert_to_homograph_safe_chars("alice"); + fn broadcast_consensus_error_is_rejected() { + let attempt = classify_broadcast_error(dash_sdk::Error::Protocol( + dash_sdk::dpp::ProtocolError::ConsensusError(Box::new(ConsensusError::DefaultError)), + )); - // Then: the result matches the constant used by the vote poll tests. - assert_eq!(normalized, "a11ce"); + assert!(matches!(attempt, DpnsVoteAttempt::Rejected(_))); + } + + /// A rejection reported by a retried broadcast does not prove the vote + /// was not applied by an earlier attempt; the proved current vote does. + #[test] + fn a_rejected_broadcast_is_confirmed_when_platform_shows_the_requested_vote() { + let lock = ResourceVoteChoice::Lock; + let rejection = || TaskError::DpnsVoteTargetBusy; + + assert!(matches!( + settle_broadcast_rejection(rejection(), lock, Ok(Some(lock))), + DpnsVoteAttempt::Confirmed + )); + for proved_current in [ + Ok(None), + Ok(Some(ResourceVoteChoice::Abstain)), + Err(TaskError::DpnsCurrentVoteUnavailable), + ] { + assert!(matches!( + settle_broadcast_rejection(rejection(), lock, proved_current), + DpnsVoteAttempt::Rejected(TaskError::DpnsVoteTargetBusy) + )); + } + } + + #[test] + fn journal_failure_before_broadcast_fails_before_submission() { + let attempt = classify_broadcast_journal_result(Err(TaskError::DpnsVoteTargetBusy)) + .expect_err("a failed journal mark must prevent the broadcast"); + + assert!(matches!( + attempt, + DpnsVoteAttempt::FailedBeforeSubmission(_) + )); + } + + #[test] + fn journal_no_op_before_broadcast_fails_before_submission() { + let attempt = classify_broadcast_journal_result(Ok(false)) + .expect_err("a no-op journal mark must prevent the broadcast"); + + assert!(matches!( + attempt, + DpnsVoteAttempt::FailedBeforeSubmission(_) + )); + } + + #[tokio::test] + async fn durable_phase_boundary_precedes_broadcast() { + let marked = std::cell::Cell::new(false); + let broadcast_called = std::cell::Cell::new(false); + + broadcast_after_journal_mark( + || { + marked.set(true); + Ok(true) + }, + || async { + assert!(marked.get(), "journal must be marked before broadcasting"); + broadcast_called.set(true); + Ok(()) + }, + ) + .await + .expect("journal mark and broadcast succeed"); + + assert!(broadcast_called.get()); + } + + #[tokio::test] + async fn failed_phase_boundaries_prevent_broadcast() { + let broadcast_called = std::cell::Cell::new(false); + + let attempt = broadcast_after_journal_mark( + || Ok(false), + || async { + broadcast_called.set(true); + Ok(()) + }, + ) + .await + .expect_err("a no-op journal mark must stop submission"); + + assert!(matches!( + attempt, + DpnsVoteAttempt::FailedBeforeSubmission(_) + )); + assert!(!broadcast_called.get()); + + let attempt = broadcast_after_journal_mark( + || Err(TaskError::DpnsVoteTargetBusy), + || async { + broadcast_called.set(true); + Ok(()) + }, + ) + .await + .expect_err("a failed journal write must stop submission"); + + assert!(matches!( + attempt, + DpnsVoteAttempt::FailedBeforeSubmission(_) + )); + assert!(!broadcast_called.get()); } } diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index b99d6f5ff..beca24ddc 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -115,6 +115,12 @@ pub(crate) const BACKUP_RETENTION_SAVED_CLEANUP_INCOMPLETE: &str = "Your backup /// Shown whenever another window or session holds the wallet database. pub(crate) const WALLET_DATA_IN_USE: &str = "Your wallet data is open in another Dash Evo Tool window or command-line session. Close it and try again."; +/// Shown when the network could not be asked whether a username is free: the +/// message of [`TaskError::UsernameAvailabilityCheckFailed`] and the text of +/// the availability row that reports the same failure. +pub(crate) const USERNAME_AVAILABILITY_CHECK_FAILED: &str = + "Availability can't be checked right now. Check your internet connection and try again."; + /// App-level error envelope for backend tasks. #[derive(Debug, Error)] pub enum TaskError { @@ -971,6 +977,17 @@ pub enum TaskError { source: Box, }, + /// A masternode-voting preference (saved node set, last Masternodes + /// segment) could not be read or written in the app k/v store. Only the + /// convenience preference is lost; voting itself is unaffected. + #[error( + "Could not save your voting preferences. Check available disk space and try again." + )] + VotingPreferenceStorage { + #[source] + source: Box, + }, + /// The DET avatar image cache could not be read or written. /// Lives in the same cross-network `det-app.sqlite` k/v file as /// [`Self::KvSidecarStorage`]; a failure here only costs the offline @@ -1049,14 +1066,11 @@ pub enum TaskError { source: crate::wallet_backend::KvAdapterError, }, - /// A scheduled DPNS vote could not be read or written in the per-network - /// wallet k/v store. - #[error( - "Could not access your scheduled vote queue. Check available disk space and try again." - )] - ScheduledVoteStorage { + /// The startup check could not read schedules from the previous version. + #[error("Your previous scheduled votes could not be checked. Restart the app and try again.")] + LegacyScheduledVotesRead { #[source] - source: crate::wallet_backend::KvAdapterError, + source: rusqlite::Error, }, /// A scheduled vote failed inside the otherwise successful per-voter result payload. @@ -1131,12 +1145,103 @@ pub enum TaskError { /// A DPNS contest record could not be read or written in the /// per-network wallet k/v store. - #[error("Could not access your DPNS contest data. Check available disk space and try again.")] + #[error("Could not access your name contest data. Check available disk space and try again.")] ContestStorage { #[source] source: crate::wallet_backend::KvAdapterError, }, + /// A DPNS vote operation or current-vote snapshot could not be persisted. + #[error( + "Could not save voting progress. Check available disk space and try again." + )] + DpnsVoteOperationStorage { + #[source] + source: crate::wallet_backend::KvAdapterError, + }, + + /// An indexed journal row could not be decoded, so unresolved target locks + /// cannot be reconstructed safely. + #[error( + "Saved voting progress is unreadable. Restart the app and try loading your votes again." + )] + DpnsVoteOperationUnreadable { + #[source] + source: crate::wallet_backend::KvAdapterError, + }, + + /// An operation index referenced a missing row, so target locks are unknown. + #[error( + "Saved voting progress is incomplete. Restart the app and try loading your votes again." + )] + DpnsVoteOperationRecordMissing, + + /// A non-terminal operation was found under a different network namespace. + #[error( + "Saved voting progress belongs to another network. Switch back to that network or resolve the pending vote there." + )] + DpnsVoteJournalNetworkMismatch, + + /// The bounded in-process vote coordinator was shut down unexpectedly. + #[error("Voting is stopping. Wait for the app to finish closing, then open it and try again.")] + DpnsVoteCoordinatorUnavailable, + + /// Another unresolved operation already owns this exact node and contest. + #[error( + "This node's vote for this name is already in progress. Wait for its result or check again." + )] + DpnsVoteTargetBusy, + + /// The journal could not advance the exact claimed target into its + /// ambiguous network phase, so broadcasting must not start. + #[error( + "This vote could not be prepared safely. Check its saved status before trying again." + )] + DpnsVoteBroadcastPhaseNotMarked, + + /// A cancellation lost the race to execution after the target was claimed. + #[error( + "This scheduled vote has already started and can no longer be cancelled. Check its result once it finishes." + )] + DpnsScheduledVoteAlreadyStarted, + + /// The schedule changed or started after the edit dialog opened. + #[error("This scheduled vote has changed or already started. Refresh the schedule and try again.")] + DpnsScheduledVoteNotEditable, + + /// A requested schedule does not fall inside the remaining voting window. + #[error("This voting time is outside the available window. Choose a future time before voting ends.")] + DpnsScheduledVoteInvalidTime, + + /// The requested contender is absent from the current contest. + #[error("This choice is no longer available. Refresh the contest and choose another option.")] + DpnsScheduledVoteInvalidChoice, + + /// The original voter has been removed or lacks an eligible voting key. + #[error("This node is no longer available for voting. Load a node with its voting key and try again.")] + DpnsScheduledVoteVoterUnavailable, + + /// Current proved state is required to suppress duplicate/no-op votes safely. + #[error( + "This node's current vote could not be checked. Refresh vote state before submitting." + )] + DpnsCurrentVoteUnavailable, + + /// A newer refresh or confirmation superseded a submission's proved snapshot. + #[error("Newer voting information is available. Refresh vote state and try again.")] + DpnsVoteStateChanged, + + /// Fresh preflight discovered a vote change that the operator has not reviewed. + #[error("This node has voted since your review. Review its current choice and the vote-change warning before submitting again.")] + DpnsVoteReviewRequired, + + /// Retains the per-voter cause of a strict current-vote preflight failure. + #[error("This node's current vote could not be checked. Refresh vote state before submitting.")] + DpnsVotePreflightFailed { + #[source] + source: std::sync::Arc, + }, + /// A local identity record could not be read or written in the /// per-network wallet k/v store. #[error("Could not access your saved identities. Check available disk space and try again.")] @@ -1145,15 +1250,6 @@ pub enum TaskError { source: crate::wallet_backend::KvAdapterError, }, - /// A voter identifier handed to a scheduled-vote operation was not a valid - /// 32-byte identity id. Callers always pass an [`Identifier`]'s bytes, so - /// this signals an internal inconsistency rather than user input. - #[error("Could not read the voter for this scheduled vote. Please refresh and try again.")] - InvalidVoterIdentifier { - #[source] - source: dash_sdk::dpp::platform_value::Error, - }, - /// A stored [`QualifiedIdentity`](crate::model::qualified_identity::QualifiedIdentity) /// blob could not be decoded. Private keys and balance state are at stake, /// so this is surfaced rather than silently skipped. @@ -1427,6 +1523,10 @@ pub enum TaskError { #[error("Identity not found on the platform. Please check the ID or name and try again.")] IdentityNotFound, + /// No voter identity exists for the selected node and supplied key address. + #[error("This voting key could not be matched to the selected node. Check that node's voting private key and try again.")] + MasternodeVotingKeyNotFound, + /// An owner-key withdrawal was directed at an address other than the /// masternode's registered payout address, which the network does not allow. #[error( @@ -1940,6 +2040,13 @@ pub enum TaskError { )] DataContractNotFound, + /// The loaded username contract cannot identify a voting poll. + #[error("The username voting information is incomplete. Refresh and try again.")] + DpnsVotePollSchema { + #[from] + source: crate::model::dpns_voting::DpnsVotePollError, + }, + // ────────────────────────────────────────────────────────────────────────── // Identity creation / parsing errors // ────────────────────────────────────────────────────────────────────────── @@ -1963,6 +2070,10 @@ pub enum TaskError { )] IdentityLoadInProgress { identity_id: Identifier }, + /// The load was invalidated by removal or a scoped target changed protection. + #[error("This identity changed while its key was loading. Open the current identity and try again.")] + IdentityLoadSuperseded { identity_id: Identifier }, + /// The ProTxHash could not be read as a hex ProTxHash or a Base58 identity /// id. Carries the offending input (data, not a message). #[error( @@ -1992,6 +2103,50 @@ pub enum TaskError { #[error("The private key you entered is invalid. Please check the format and try again.")] InvalidPrivateKey, + /// The network could not be asked whether a username is free. + #[error("{}", USERNAME_AVAILABILITY_CHECK_FAILED)] + UsernameAvailabilityCheckFailed { + #[source] + source: Box, + }, + + /// The username stopped being available between choosing it and paying. + #[error("This username is no longer available. Nothing was spent. Choose another username.")] + UsernameNoLongerAvailable { + availability: crate::model::dpns_usernames::UsernameAvailability, + }, + + #[error("The username payment terms changed. Nothing was spent. Review the name and fees again.")] + UsernameRegistrationTermsChanged, + + /// The name request was sent, but nothing proves whether the network applied + /// it. It may already be paid for, so this never reads as a plain failure. + #[error( + "The app could not confirm whether your request for this username went through. Do not pay again yet. Wait a few minutes, then check the Usernames list on your identity. If the name is not there, try again." + )] + UsernameRegistrationUnconfirmed { + #[source] + source_error: Box, + }, + + /// Username requests or preferences could not be read or written on this device. + #[error( + "Your username settings could not be saved on this device. Check available disk space and try again." + )] + UsernameStorage { + #[source] + source: crate::wallet_backend::KvAdapterError, + }, + + /// The status of username requests could not be read from the network. + #[error( + "Username request status can't be updated right now. Check your internet connection and try again." + )] + UsernameRequestRefreshFailed { + #[source] + source: Box, + }, + /// Fetching DPNS names for an identity failed. #[error("Could not look up names for this identity. Please check your connection and retry.")] DpnsFetchError { @@ -2453,6 +2608,17 @@ pub enum TaskError { )] VotePollNotFound { name: String }, + /// The masternode has used every vote allowed for a contested name. + #[error( + "This node has already cast the maximum {max_times_allowed} votes allowed for this contest and can't vote again. Choose another contest to vote on." + )] + MasternodeVoteLimitReached { + times_already_voted: u16, + max_times_allowed: u16, + #[source] + source_error: Box, + }, + /// The identity does not have an authentication key required to sign documents. #[error( "This identity does not have a key for signing documents. Please add an authentication key." @@ -3703,6 +3869,17 @@ impl From for TaskError { } })) } + ConsensusError::StateError(StateError::MasternodeVotedTooManyTimesError(e)) => { + let (times_already_voted, max_times_allowed) = + (e.times_already_voted(), e.max_times_allowed()); + Some(Box::new(move |source_error| { + TaskError::MasternodeVoteLimitReached { + times_already_voted, + max_times_allowed, + source_error, + } + })) + } ConsensusError::BasicError( BasicError::InvalidInstantAssetLockProofSignatureError(_), ) => Some(Box::new(|source_error| { @@ -3987,6 +4164,7 @@ mod tests { use dash_sdk::dpp::consensus::state::identity::duplicated_identity_public_key_state_error::DuplicatedIdentityPublicKeyStateError; use dash_sdk::dpp::consensus::state::identity::IdentityInsufficientBalanceError; use dash_sdk::dpp::consensus::state::identity::identity_public_key_already_exists_for_unique_contract_bounds_error::IdentityPublicKeyAlreadyExistsForUniqueContractBoundsError; + use dash_sdk::dpp::consensus::state::voting::masternode_voted_too_many_times::MasternodeVotedTooManyTimesError; use dash_sdk::dpp::identity::Purpose; use dash_sdk::platform::Identifier; @@ -5206,6 +5384,63 @@ mod tests { ); } + #[test] + fn from_sdk_error_vote_limit_via_consensus_is_specific() { + let consensus = ConsensusError::from(MasternodeVotedTooManyTimesError::new( + Identifier::random(), + 6, + 5, + )); + let err = TaskError::from(SdkError::from(consensus)); + + assert!( + matches!( + &err, + TaskError::MasternodeVoteLimitReached { + times_already_voted: 6, + max_times_allowed: 5, + .. + } + ), + "Expected MasternodeVoteLimitReached, got: {err:?}" + ); + assert_eq!( + err.to_string(), + "This node has already cast the maximum 5 votes allowed for this contest and can't vote again. Choose another contest to vote on." + ); + } + + #[test] + fn from_sdk_error_vote_limit_via_broadcast_is_specific() { + let consensus = ConsensusError::from(MasternodeVotedTooManyTimesError::new( + Identifier::random(), + 6, + 5, + )); + let broadcast_err = dash_sdk::error::StateTransitionBroadcastError { + code: 40303, + message: "vote limit reached".to_string(), + cause: Some(consensus), + }; + let err = TaskError::from(SdkError::StateTransitionBroadcastError(broadcast_err)); + + assert!( + matches!( + &err, + TaskError::MasternodeVoteLimitReached { + times_already_voted: 6, + max_times_allowed: 5, + .. + } + ), + "Expected MasternodeVoteLimitReached, got: {err:?}" + ); + assert_eq!( + err.to_string(), + "This node has already cast the maximum 5 votes allowed for this contest and can't vote again. Choose another contest to vote on." + ); + } + #[test] fn connection_failed_display_includes_url() { let socket_err = dashcore_rpc::jsonrpc::simple_http::Error::SocketError( diff --git a/src/backend_task/identity/dpns_usernames.rs b/src/backend_task/identity/dpns_usernames.rs new file mode 100644 index 000000000..3af5c4d0e --- /dev/null +++ b/src/backend_task/identity/dpns_usernames.rs @@ -0,0 +1,836 @@ +//! Identity-side username ops: availability checks and own-request status. + +use std::collections::BTreeMap; + +use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; +use dash_sdk::dpp::document::DocumentV0Getters; +use dash_sdk::dpp::identity::accessors::IdentityGettersV0; +use dash_sdk::dpp::platform_value::Value; +use dash_sdk::dpp::voting::vote_info_storage::contested_document_vote_poll_winner_info::ContestedDocumentVotePollWinnerInfo; +use dash_sdk::drive::query::{SelectProjection, WhereClause, WhereOperator}; +use dash_sdk::platform::{Document, DocumentQuery, FetchMany, Identifier}; +use dash_sdk::query_types::Contenders; +use dash_sdk::{Error as SdkError, Sdk}; + +use super::BackendTaskSuccessResult; +use crate::backend_task::error::TaskError; +use crate::context::AppContext; +use crate::model::dpns::{ + ContestDurations, DpnsNameValidationResult, contest_durations, is_contested_label, + normalize_dpns_label, validate_dpns_name, +}; +use crate::model::dpns_usernames::{ + ContenderTally, ContestSnapshot, ContestWinner, RequestPhase, UsernameAvailability, + UsernameRequest, classify_availability, mark_wins_reflected, merge_requests, + username_request_from_contest, +}; +use crate::model::qualified_identity::QualifiedIdentity; +use crate::utils::time::now_ms; + +fn availability_error(source: SdkError) -> TaskError { + TaskError::UsernameAvailabilityCheckFailed { + source: Box::new(source), + } +} + +impl AppContext { + fn username_contest_durations(&self, sdk: &Sdk) -> ContestDurations { + contest_durations(self.network, sdk.version()) + } + + /// Whether `label` can be requested now, combining the registered-name + /// lookup with the proved contest state. Never trusts + /// `Sdk::is_dpns_name_available`, which reports contested and locked names as free. + /// + /// `requester` is the identity asking; its own running request reports + /// `AlreadyRequested`, because Platform rejects a second request. + pub(crate) async fn username_availability( + &self, + sdk: &Sdk, + requester: Identifier, + label: &str, + ) -> Result { + let validation = validate_dpns_name(label); + if validation != DpnsNameValidationResult::Valid { + return Err(TaskError::InvalidDpnsName { validation }); + } + let normalized = normalize_dpns_label(label); + let awarded = self.dpns_domain_exists(sdk, &normalized).await?; + let contest = if !awarded && is_contested_label(label) { + let contenders = sdk + .get_contested_dpns_vote_state(&normalized, None) + .await + .map_err(availability_error)?; + Some(self.contest_snapshot(sdk, &contenders)) + } else { + None + }; + Ok(classify_availability( + requester, + label, + awarded, + contest.as_ref(), + now_ms(), + self.username_contest_durations(sdk), + )) + } + + pub(super) async fn check_username_availability( + &self, + sdk: &Sdk, + identity_id: Identifier, + label: String, + ) -> Result { + let availability = self.username_availability(sdk, identity_id, &label).await?; + Ok(BackendTaskSuccessResult::UsernameAvailability { + label, + availability, + }) + } + + /// The lookup for a registered name with this normalized label. + pub(super) fn dpns_domain_query(&self, normalized: &str) -> DocumentQuery { + DocumentQuery { + sub_queries: Vec::new(), + select: SelectProjection::documents(), + data_contract: self.dpns_contract.clone(), + document_type_name: "domain".to_string(), + where_clauses: vec![ + WhereClause { + field: "normalizedParentDomainName".to_string(), + operator: WhereOperator::Equal, + value: Value::Text("dash".to_string()), + }, + WhereClause { + field: "normalizedLabel".to_string(), + operator: WhereOperator::Equal, + value: Value::Text(normalized.to_owned()), + }, + ], + time_range_clauses: Vec::new(), + group_by: Vec::new(), + having: Vec::new(), + order_by_clauses: vec![], + limit: 1, + offset: None, + start: None, + } + } + + async fn dpns_domain_exists(&self, sdk: &Sdk, normalized: &str) -> Result { + let documents = Document::fetch_many(sdk, self.dpns_domain_query(normalized)) + .await + .map_err(availability_error)?; + Ok(documents.values().any(Option::is_some)) + } + + /// Convert a proved vote state into the pure snapshot the model decides on. + fn contest_snapshot(&self, sdk: &Sdk, contenders: &Contenders) -> ContestSnapshot { + let documents = self + .dpns_contract + .document_type_cloned_for_name("domain") + .ok() + .and_then(|document_type| { + contenders + .to_contenders(&document_type, sdk.version()) + .inspect_err(|error| { + tracing::debug!(?error, "Username contest documents could not be decoded") + }) + .ok() + }) + .unwrap_or_default(); + let contenders_list = contenders + .contenders + .iter() + .map(|(identity_id, contender)| { + let document = documents + .get(identity_id) + .and_then(|contender| contender.document().as_ref()); + ContenderTally { + identity_id: *identity_id, + label: document + .and_then(|doc| doc.get("label")) + .and_then(|label| label.to_str().ok()) + .map(str::to_owned), + votes: contender.vote_tally().unwrap_or(0), + created_at: document.and_then(|doc| doc.created_at()), + } + }) + .collect(); + let (winner, decided_at) = match &contenders.winner { + Some((info, block)) => ( + Some(match info { + ContestedDocumentVotePollWinnerInfo::WonByIdentity(id) => { + ContestWinner::Identity(*id) + } + ContestedDocumentVotePollWinnerInfo::Locked => ContestWinner::Locked, + ContestedDocumentVotePollWinnerInfo::NoWinner => ContestWinner::NoWinner, + }), + Some(block.time_ms), + ), + None => (None, None), + }; + ContestSnapshot { + winner, + decided_at, + contenders: contenders_list, + lock_votes: contenders.lock_vote_tally.unwrap_or(0), + abstain_votes: contenders.abstain_vote_tally.unwrap_or(0), + } + } + + /// Refresh the username requests of every loaded identity. + /// + /// Saved pending requests are checked and published before the wider scan, + /// so a slow or failing discovery query cannot hold their outcomes back. + /// Discovery also finds requests made on other devices. + pub(super) async fn refresh_my_username_requests( + &self, + sdk: &Sdk, + ) -> Result { + let now = now_ms(); + let identities = self.load_local_user_identities()?; + if identities.is_empty() { + return Ok(BackendTaskSuccessResult::MyUsernameRequestsRefreshed); + } + let durations = self.username_contest_durations(sdk); + let mut checked = BTreeMap::new(); + let mut first_error = None; + for identity in &identities { + let identity_id = identity.identity.id(); + let previous = self.username_requests_for(&identity_id); + let mut fresh = Vec::new(); + for old in previous.iter().filter(|old| old.phase.is_pending()) { + if !checked.contains_key(&old.normalized_label) { + match sdk + .get_contested_dpns_vote_state(&old.normalized_label, None) + .await + { + Ok(contenders) => { + checked.insert( + old.normalized_label.clone(), + self.contest_snapshot(sdk, &contenders), + ); + } + Err(error) => tracing::debug!( + name = %old.normalized_label, ?error, + "Username request outcome could not be read; keeping the stored status" + ), + } + } + if let Some(snapshot) = checked.get(&old.normalized_label) { + fresh.extend(username_request_from_contest( + identity_id, + &old.normalized_label, + snapshot, + old.end, + now, + durations, + )); + } + } + if let Err(error) = self.apply_username_refresh(sdk, identity, fresh).await { + first_error.get_or_insert(error); + } + } + // TODO(usernames): the SDK scan pages only while a timestamp group holds 100 polls and drops + // names whose vote state fails; requests made on another device can be missed past that cap. + let running = match sdk.get_contested_non_resolved_usernames(None).await { + Ok(running) => running, + Err(source) => { + return Err(first_error.unwrap_or_else(|| { + TaskError::UsernameRequestRefreshFailed { + source: Box::new(source), + } + })); + } + }; + let snapshots: BTreeMap<&String, (ContestSnapshot, u64)> = running + .iter() + .map(|(name, info)| { + ( + name, + (self.contest_snapshot(sdk, &info.contenders), info.end_time), + ) + }) + .collect(); + + for identity in identities { + let identity_id = identity.identity.id(); + let previous = self.username_requests_for(&identity_id); + let fresh: Vec = snapshots + .iter() + .filter(|(name, _)| { + !previous.iter().any(|request| { + request.normalized_label == name.as_str() && !request.phase.is_pending() + }) + }) + .filter_map(|(name, (snapshot, end))| { + username_request_from_contest( + identity_id, + name, + snapshot, + Some(*end), + now, + durations, + ) + }) + .collect(); + if let Err(error) = self.apply_username_refresh(sdk, &identity, fresh).await { + first_error.get_or_insert(error); + } + } + if let Some(error) = first_error { + return Err(error); + } + Ok(BackendTaskSuccessResult::MyUsernameRequestsRefreshed) + } + + async fn apply_username_refresh( + &self, + sdk: &Sdk, + identity: &QualifiedIdentity, + fresh: Vec, + ) -> Result<(), TaskError> { + let identity_id = identity.identity.id(); + { + let lock = self.identity_record_lock(identity_id); + let _guard = lock + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if !self.is_identity_listed(&identity_id)? { + return Ok(()); + } + let Some(current_identity) = self.get_local_qualified_identity(&identity_id)? else { + return Ok(()); + }; + self.update_username_requests(&identity_id, |current| { + merge_requests(current, fresh, now_ms(), Some(¤t_identity.dpns_names)) + })?; + } + self.egui_ctx().request_repaint(); + self.record_won_usernames(sdk, identity_id).await; + Ok(()) + } + + /// Retry saved wins until the owned names are durably reflected in the identity. + async fn record_won_usernames(&self, sdk: &Sdk, identity_id: Identifier) { + let requests = self.username_requests_for(&identity_id); + if !requests + .iter() + .any(|request| request.phase == RequestPhase::Won) + { + self.update_username_hydration_status(identity_id, &[]); + return; + } + let identity = match self.get_local_qualified_identity(&identity_id) { + Ok(Some(identity)) => identity, + Ok(None) => { + return; + } + Err(error) => { + tracing::warn!(?error, %identity_id, "Won username identity could not be read; refresh will retry"); + self.update_username_hydration_status(identity_id, &[]); + return; + } + }; + let missing = self.update_username_hydration_status(identity_id, &identity.dpns_names); + if !missing { + return; + } + match self.fetch_owned_dpns_names(sdk, identity_id).await { + Ok(names) => { + match self.edit_local_qualified_identity(&identity_id, |fresh| { + fresh.dpns_names = names; + Ok(()) + }) { + Ok(saved) => { + // Recorded at once: a name transferred away before the + // next refresh must not look like a win still to read back. + if let Err(error) = self.update_username_requests(&identity_id, |current| { + let mut requests = current.to_vec(); + mark_wins_reflected(&mut requests, &saved.dpns_names); + requests + }) { + tracing::warn!(?error, %identity_id, "Won username was saved but could not be marked as read back; the next refresh will mark it"); + } + self.update_username_hydration_status(identity_id, &saved.dpns_names); + } + Err(error) => { + tracing::warn!(?error, %identity_id, "Won username could not be saved; refresh will retry") + } + } + } + Err(error) => { + tracing::debug!(?error, %identity_id, "Won username could not be fetched; refresh will retry") + } + } + } + + /// Record a just-submitted contested request so the hub shows it at once. + /// + /// `joined_until` is the join deadline when the request joined a running contest. + pub(super) fn record_submitted_username_request( + &self, + sdk: &Sdk, + identity_id: &Identifier, + label: &str, + joined_until: Option, + ) -> Result<(), TaskError> { + let now = now_ms(); + let submitted = UsernameRequest::submitted( + label, + now, + self.username_contest_durations(sdk), + joined_until, + ); + self.update_username_requests(identity_id, |current| { + let previous: Vec<_> = current + .iter() + .filter(|request| request.normalized_label != submitted.normalized_label) + .cloned() + .collect(); + merge_requests(&previous, vec![submitted], now, None) + }) + } + + /// Show `name` as the main username of `identity_id` on this device. + pub(super) fn save_main_username( + &self, + identity_id: Identifier, + name: String, + ) -> Result { + self.set_main_username(&identity_id, &name)?; + Ok(BackendTaskSuccessResult::UsernamePreferencesSaved) + } + + /// Remove a finished request from the identity's list. + pub(super) fn dismiss_username_outcome( + &self, + identity_id: Identifier, + normalized_label: String, + ) -> Result { + self.dismiss_username_request(&identity_id, &normalized_label)?; + Ok(BackendTaskSuccessResult::UsernamePreferencesSaved) + } + + /// Record that outcome banners were shown, so each appears only once. + pub(super) fn save_username_outcomes_seen( + &self, + identity_id: Identifier, + requests: Vec, + ) -> Result { + self.note_username_seen_mark(&identity_id, None); + let result = self.mark_username_outcomes_seen(&identity_id, &requests); + self.note_username_seen_mark(&identity_id, Some(result.is_ok())); + result?; + Ok(BackendTaskSuccessResult::UsernamePreferencesSaved) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::context::test_support::bare_user_identity; + use dash_sdk::dpp::block::block_info::BlockInfo; + use dash_sdk::dpp::voting::contender_structs::ContenderWithSerializedDocument; + use dash_sdk::drive::query::vote_poll_vote_state_query::{ + ContestedDocumentVotePollDriveQuery, ContestedDocumentVotePollDriveQueryResultType, + }; + + async fn sdk_with_owned_name(ctx: &AppContext, id: Identifier) -> Sdk { + let query = DocumentQuery { + sub_queries: vec![], + select: SelectProjection::documents(), + data_contract: ctx.dpns_contract.clone(), + document_type_name: "domain".into(), + where_clauses: vec![WhereClause { + field: "records.identity".into(), + operator: WhereOperator::Equal, + value: Value::Identifier(id.into()), + }], + time_range_clauses: vec![], + group_by: vec![], + having: vec![], + order_by_clauses: vec![], + limit: 100, + offset: None, + start: None, + }; + let document = Document::V0(dash_sdk::dpp::document::DocumentV0 { + id: Identifier::from([88; 32]), + owner_id: id, + creator_id: None, + properties: BTreeMap::from([("label".into(), Value::Text("Alice".into()))]), + revision: None, + created_at: Some(100), + updated_at: None, + transferred_at: None, + created_at_block_height: None, + updated_at_block_height: None, + transferred_at_block_height: None, + created_at_core_block_height: None, + updated_at_core_block_height: None, + transferred_at_core_block_height: None, + contract_version: None, + }); + let documents: dash_sdk::query_types::Documents = + [(document.id(), Some(document))].into_iter().collect(); + let mut sdk = Sdk::new_mock(); + sdk.mock() + .expect_fetch_many::( + query, + Some(documents), + ) + .await + .unwrap(); + sdk + } + + #[tokio::test] + async fn stale_pending_refresh_preserves_saved_win_and_hydration_retry() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store( + std::sync::Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()), + )); + let id = Identifier::from([42; 32]); + let identity = bare_user_identity(id, ctx.network); + ctx.insert_local_qualified_identity_sidecar_only(&identity) + .unwrap(); + let sdk = Sdk::new_mock(); + let pending = + UsernameRequest::submitted("Alice", 100, ctx.username_contest_durations(&sdk), None); + let mut won = pending.clone(); + won.phase = RequestPhase::Won; + won.last_updated = 200; + won.decided_at = Some(200); + ctx.store_username_requests(&id, vec![won.clone()]).unwrap(); + ctx.apply_username_refresh(&sdk, &identity, vec![pending]) + .await + .unwrap(); + assert_eq!(ctx.username_requests_for(&id), vec![won.clone()]); + assert!(ctx.username_requests_need_refresh()); + ctx.refresh_pending_dpns_usernames().unwrap(); + assert_eq!(ctx.username_requests_for(&id), vec![won]); + assert!(ctx.username_requests_need_refresh()); + + ctx.record_submitted_username_request(&sdk, &id, "Alice", None) + .unwrap(); + assert_eq!( + ctx.username_requests_for(&id)[0].phase, + RequestPhase::Joinable + ); + assert!(ctx.username_requests_for(&id)[0].requested_at.unwrap() > 200); + } + + #[tokio::test] + async fn removed_identity_ignores_an_awaited_username_refresh() { + for phase in [RequestPhase::Joinable, RequestPhase::Won] { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store( + std::sync::Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()), + )); + let id = Identifier::from([42; 32]); + let captured = bare_user_identity(id, ctx.network); + ctx.insert_local_qualified_identity_sidecar_only(&captured) + .unwrap(); + let sdk = Sdk::new_mock(); + let mut request = UsernameRequest::submitted( + "Alice", + now_ms(), + ctx.username_contest_durations(&sdk), + None, + ); + request.phase = phase; + ctx.store_username_requests(&id, vec![request.clone()]) + .unwrap(); + let cleanup = ctx + .delete_local_qualified_identity_with_outcome(&id) + .unwrap(); + assert!(cleanup.is_incomplete(), "the fixture has no wallet backend"); + assert!(!ctx.is_identity_listed(&id).unwrap()); + ctx.apply_username_refresh(&sdk, &captured, vec![request]) + .await + .unwrap(); + assert!(ctx.username_requests_for(&id).is_empty()); + assert!(!ctx.username_requests_need_refresh()); + ctx.refresh_pending_dpns_usernames().unwrap(); + assert!(ctx.username_requests_for(&id).is_empty()); + assert!(!ctx.username_requests_need_refresh()); + } + } + + #[tokio::test] + async fn username_refresh_reports_identity_load_failure() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let store = + std::sync::Arc::new(crate::wallet_backend::kv_test_support::FailingKv::default()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(store.clone())); + store.fail_next_gets_containing("det:identity_index:v1", 1); + assert!( + ctx.refresh_my_username_requests(&Sdk::new_mock()) + .await + .is_err() + ); + } + + #[tokio::test] + async fn username_refresh_reports_storage_failure_and_keeps_successful_siblings() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let store = + std::sync::Arc::new(crate::wallet_backend::kv_test_support::FailingKv::default()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(store.clone())); + for byte in [42, 43] { + let id = Identifier::from([byte; 32]); + ctx.insert_local_qualified_identity_sidecar_only(&bare_user_identity(id, ctx.network)) + .unwrap(); + ctx.store_username_requests( + &id, + vec![UsernameRequest::submitted( + "Alice", + 1, + ctx.username_contest_durations(&Sdk::new_mock()), + None, + )], + ) + .unwrap(); + } + let mut sdk = Sdk::new_mock(); + sdk.mock() + .expect_fetch_many::( + ContestedDocumentVotePollDriveQuery { + vote_poll: crate::model::dpns_voting::dpns_vote_poll( + &ctx.dpns_contract, + &normalize_dpns_label("Alice"), + ) + .unwrap(), + result_type: + ContestedDocumentVotePollDriveQueryResultType::DocumentsAndVoteTally, + allow_include_locked_and_abstaining_vote_tally: true, + start_at: None, + limit: None, + offset: None, + }, + Some(Contenders { + winner: Some(( + ContestedDocumentVotePollWinnerInfo::Locked, + BlockInfo { + time_ms: now_ms(), + ..Default::default() + }, + )), + ..Default::default() + }), + ) + .await + .unwrap(); + sdk.mock().expect_fetch_many::( + dash_sdk::drive::query::VotePollsByEndDateDriveQuery { + start_time: None, end_time: None, limit: Some(100), offset: None, order_ascending: true, + }, + Some(Default::default()), + ).await.unwrap(); + store.fail_next_puts_containing("det:username_requests:", 1); + assert!(matches!( + ctx.refresh_my_username_requests(&sdk).await, + Err(TaskError::UsernameStorage { .. }) + )); + let phases = + [42, 43].map(|byte| ctx.username_requests_for(&Identifier::from([byte; 32]))[0].phase); + assert_eq!( + phases + .iter() + .filter(|phase| **phase == RequestPhase::Locked) + .count(), + 1 + ); + } + + #[tokio::test] + async fn won_username_retries_fetch_after_restart() { + won_username_retries_after_restart(false).await; + } + + #[tokio::test] + async fn won_username_retries_identity_write_after_restart() { + won_username_retries_after_restart(true).await; + } + + async fn won_username_retries_after_restart(fail_write: bool) { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let store = + std::sync::Arc::new(crate::wallet_backend::kv_test_support::FailingKv::default()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(store.clone())); + let id = Identifier::from([43; 32]); + let identity = bare_user_identity(id, ctx.network); + ctx.insert_local_qualified_identity_sidecar_only(&identity) + .unwrap(); + let mut won = UsernameRequest::submitted( + "Alice", + now_ms(), + ctx.username_contest_durations(&Sdk::new_mock()), + None, + ); + won.phase = RequestPhase::Won; + won.decided_at = Some(now_ms()); + let sdk = if fail_write { + sdk_with_owned_name(&ctx, id).await + } else { + Sdk::new_mock() + }; + if fail_write { + store.fail_next_puts_containing("det:identity:v1", 1); + } + ctx.apply_username_refresh(&sdk, &identity, vec![won.clone()]) + .await + .unwrap(); + assert_eq!(ctx.username_requests_for(&id)[0].phase, RequestPhase::Won); + assert!( + ctx.username_requests_need_refresh(), + "a saved win keeps periodic retries active" + ); + assert!( + ctx.get_local_qualified_identity(&id) + .unwrap() + .unwrap() + .dpns_names + .is_empty() + ); + drop(ctx); + let restarted_dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(restarted_dir.path()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(store)); + ctx.refresh_pending_dpns_usernames().unwrap(); + assert!( + ctx.username_requests_need_refresh(), + "startup restores the retry obligation" + ); + let sdk = sdk_with_owned_name(&ctx, id).await; + // Discovery is deliberately unavailable; saved winners must be repaired before it. + let _ = ctx.refresh_my_username_requests(&sdk).await; + let saved = ctx.get_local_qualified_identity(&id).unwrap().unwrap(); + assert_eq!(ctx.main_username(&saved).as_deref(), Some("Alice")); + assert_eq!(saved.dpns_names.len(), 1); + assert!( + !ctx.username_requests_need_refresh(), + "successful persistence clears the retry obligation" + ); + } + + /// A won name is marked as read back the moment the identity stores it, so + /// its later disappearance (the name left the identity) is not taken for a + /// win still waiting to be read back, and is not fetched again. + #[tokio::test] + async fn saved_win_is_marked_once_the_identity_lists_the_name() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store( + std::sync::Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()), + )); + let id = Identifier::from([44; 32]); + let identity = bare_user_identity(id, ctx.network); + ctx.insert_local_qualified_identity_sidecar_only(&identity) + .unwrap(); + let mut won = UsernameRequest::submitted( + "Alice", + now_ms(), + ctx.username_contest_durations(&Sdk::new_mock()), + None, + ); + won.phase = RequestPhase::Won; + won.decided_at = Some(now_ms()); + let sdk = sdk_with_owned_name(&ctx, id).await; + + ctx.apply_username_refresh(&sdk, &identity, vec![won]) + .await + .unwrap(); + + assert!(ctx.username_requests_for(&id)[0].reflected_in_owned_names); + assert!(!ctx.username_requests_need_refresh()); + + // The name has since left the identity; no owned-names read is mocked, + // so a renewed attempt to read the win back would keep the retry alive. + let without_name = ctx + .edit_local_qualified_identity(&id, |identity| { + identity.dpns_names.clear(); + Ok(()) + }) + .unwrap(); + ctx.apply_username_refresh(&Sdk::new_mock(), &without_name, vec![]) + .await + .unwrap(); + + assert!(ctx.username_requests_for(&id)[0].reflected_in_owned_names); + assert!(!ctx.username_requests_need_refresh()); + } + + #[tokio::test] + async fn known_username_outcome_refresh_survives_discovery_failure() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store( + std::sync::Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()), + )); + let id = Identifier::from([42; 32]); + let identity = bare_user_identity(id, ctx.network); + ctx.insert_local_qualified_identity_sidecar_only(&identity) + .unwrap(); + ctx.store_username_requests( + &id, + vec![UsernameRequest::submitted( + "d1ssh", + 1, + ContestDurations { + total: std::time::Duration::from_secs(10), + join: std::time::Duration::from_secs(5), + }, + None, + )], + ) + .unwrap(); + let mut sdk = Sdk::new_mock(); + sdk.mock() + .expect_fetch_many::( + ContestedDocumentVotePollDriveQuery { + vote_poll: crate::model::dpns_voting::dpns_vote_poll( + &ctx.dpns_contract, + "d1ssh", + ) + .unwrap(), + result_type: + ContestedDocumentVotePollDriveQueryResultType::DocumentsAndVoteTally, + allow_include_locked_and_abstaining_vote_tally: true, + start_at: None, + limit: None, + offset: None, + }, + Some(Contenders { + winner: Some(( + ContestedDocumentVotePollWinnerInfo::Locked, + BlockInfo { + time_ms: now_ms(), + ..Default::default() + }, + )), + ..Default::default() + }), + ) + .await + .unwrap(); + // No discovery expectation: scanning unrelated contests fails. + assert!(matches!( + ctx.refresh_my_username_requests(&sdk).await, + Err(TaskError::UsernameRequestRefreshFailed { .. }) + )); + ctx.refresh_pending_dpns_usernames().unwrap(); + assert_eq!( + ctx.username_requests_for(&id)[0].phase, + RequestPhase::Locked + ); + } +} diff --git a/src/backend_task/identity/load_identity.rs b/src/backend_task/identity/load_identity.rs index 42fa5f2cc..51d1ceb6b 100644 --- a/src/backend_task/identity/load_identity.rs +++ b/src/backend_task/identity/load_identity.rs @@ -70,6 +70,15 @@ fn merge_existing_keys_into(new: &mut QualifiedIdentity, existing: QualifiedIden } } +/// How a load writes the identity record once its keys are settled. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum IdentityRecordWrite { + /// Deliberate import: lists the identity and retires an unload marker. + Import, + /// Scoped update of a listed identity; never restores a removed one. + UpdateListed, +} + impl AppContext { pub(super) async fn load_identity( &self, @@ -153,6 +162,9 @@ impl AppContext { IdentityLoadMode::RejectIfExists if existing_stored.is_some() => { return Err(TaskError::DuplicateProTxHash { identity_id }); } + IdentityLoadMode::MergeIntoExisting if existing_stored.is_none() => { + return Err(TaskError::IdentityNotFoundLocally); + } _ => {} } @@ -276,7 +288,7 @@ impl AppContext { .await? { Ok(Some(identity)) => identity, - Ok(None) => return Err(TaskError::IdentityNotFound), + Ok(None) => return Err(TaskError::MasternodeVotingKeyNotFound), Err(e) => return Err(TaskError::from(e)), }; @@ -471,17 +483,19 @@ impl AppContext { status: IdentityStatus::Active, network: self.network, }; - qualified_identity.initialize_node_alias(Some(&alias_input), None); - let wallet_info = - if load_mode == IdentityLoadMode::MergeIntoExisting && encryption_password.is_none() { - self.persist_merged_identity(&mut qualified_identity, merge_seal_password.as_ref())? - } else { - self.persist_loaded_identity( - &mut qualified_identity, - encryption_password.as_ref(), - load_mode, - )? - }; + // Name an unnamed node after its main username, never an arbitrary one. + let main_username = self.main_username(&qualified_identity); + qualified_identity.initialize_node_alias(Some(&alias_input), main_username.as_deref()); + // Recheck the scoped load and merge the current stored keys under the + // record guard before any seal or write: removal and protection changes + // may have happened while the network requests were in flight. + let wallet_info = self.finish_identity_load_storage( + &mut qualified_identity, + load_mode, + merge_seal_password.as_ref(), + &load_guard, + encryption_password.as_ref(), + )?; if let Some((wallet_seed_hash, identity_index)) = wallet_info && let Some(wallet_arc) = wallets.get(&wallet_seed_hash) @@ -492,12 +506,94 @@ impl AppContext { .insert(identity_index, qualified_identity.identity.clone()); } - // Keys and identity storage are complete before the load reports success. + // Past the last fallible step: the node is stored with its keys as + // requested. Anything that failed before this — including a key seal that + // left the insert behind — reported `Failed` when the guard dropped. load_guard.loaded(); Ok(BackendTaskSuccessResult::LoadedIdentity(qualified_identity)) } + /// Store a fetched identity under its record lock, after confirming that + /// this load is still current: removal, a fresh import and protection + /// changes may have happened while the network requests were in flight. + fn finish_identity_load_storage( + &self, + qualified_identity: &mut QualifiedIdentity, + load_mode: IdentityLoadMode, + merge_password: Option<&crate::wallet_backend::VerifiedIdentityPassword>, + load_guard: &crate::context::identity_load_registry::IdentityLoadGuard, + encryption_password: Option<&crate::model::secret::Secret>, + ) -> Result, TaskError> { + if let Some(password) = encryption_password { + validate_protection_password(password)?; + } + let identity_id = qualified_identity.identity.id(); + let lock = self.identity_record_lock(identity_id); + let _guard = lock + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + load_guard.ensure_current()?; + if load_mode != IdentityLoadMode::MergeIntoExisting { + let existing = self.get_local_qualified_identity(&identity_id)?; + return self.persist_loaded_identity_locked( + qualified_identity, + existing, + encryption_password, + load_mode, + IdentityRecordWrite::Import, + ); + } + // A scoped merge is a key fix-up of a listed identity; it must never + // restore an identity removed while the network requests were in flight. + if !self.is_identity_listed(&identity_id)? { + return Err(TaskError::IdentityNotFoundLocally); + } + let existing = self + .get_identity_by_id(&identity_id)? + .ok_or(TaskError::IdentityNotFoundLocally)?; + if encryption_password.is_none() { + // A verified password belongs to the protection state observed before + // the fetch. Never seal a new key using it after that state changes. + match ( + self.protected_identity_verify_scope(&existing)?, + merge_password, + ) { + (None, None) => {} + (Some(scope), Some(password)) + if self + .wallet_backend()? + .secret_access() + .identity_object_password_still_opens(&scope, password)? => {} + _ => return Err(TaskError::IdentityLoadSuperseded { identity_id }), + } + } + // The form may carry metadata captured before the fetch; preserve edits + // made to the current local record. + qualified_identity.alias = existing.alias.clone(); + qualified_identity.associated_wallets = existing.associated_wallets.clone(); + qualified_identity.wallet_index = existing.wallet_index; + qualified_identity.top_ups = existing.top_ups.clone(); + qualified_identity.status = existing.status; + match encryption_password { + None => self.persist_merged_identity_locked( + qualified_identity, + Some(existing), + merge_password, + IdentityRecordWrite::UpdateListed, + ), + Some(password) => self.persist_loaded_identity_locked( + qualified_identity, + Some(existing), + Some(password), + load_mode, + IdentityRecordWrite::UpdateListed, + ), + } + } + + /// Merge `qi` into its stored record, taking the record lock itself. + #[cfg(test)] fn persist_merged_identity( &self, qi: &mut QualifiedIdentity, @@ -509,6 +605,19 @@ impl AppContext { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); let existing = self.get_local_qualified_identity(&identity_id)?; + self.persist_merged_identity_locked(qi, existing, password, IdentityRecordWrite::Import) + } + + /// Merge the newly supplied keys of `qi` into `existing` and seal them under + /// the revalidated identity password. The caller holds the record lock. + fn persist_merged_identity_locked( + &self, + qi: &mut QualifiedIdentity, + existing: Option, + password: Option<&crate::wallet_backend::VerifiedIdentityPassword>, + write: IdentityRecordWrite, + ) -> Result, TaskError> { + let identity_id = qi.identity.id(); let published = existing.is_some(); if let Some(existing) = existing { merge_existing_keys_into(qi, existing); @@ -552,10 +661,12 @@ impl AppContext { let wallet_info = qi .determine_wallet_info() .map_err(|detail| TaskError::WalletInfoDeterminationFailed { detail })?; - self.insert_local_qualified_identity_under_lock(qi, &wallet_info)?; + self.write_loaded_identity_locked(qi, &wallet_info, write)?; Ok(wallet_info) } + /// Store a loaded identity, taking the record lock itself. + #[cfg(test)] fn persist_loaded_identity( &self, qi: &mut QualifiedIdentity, @@ -571,6 +682,27 @@ impl AppContext { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); let existing = self.get_local_qualified_identity(&identity_id)?; + self.persist_loaded_identity_locked( + qi, + existing, + password, + load_mode, + IdentityRecordWrite::Import, + ) + } + + /// Store a loaded identity, sealing every key under `password` before the + /// record is written. The caller holds the record lock and has validated + /// `password`. + fn persist_loaded_identity_locked( + &self, + qi: &mut QualifiedIdentity, + existing: Option, + password: Option<&crate::model::secret::Secret>, + load_mode: IdentityLoadMode, + write: IdentityRecordWrite, + ) -> Result, TaskError> { + let identity_id = qi.identity.id(); if load_mode == IdentityLoadMode::RejectIfExists && existing.is_some() { return Err(TaskError::DuplicateProTxHash { identity_id }); } @@ -584,7 +716,7 @@ impl AppContext { let wallet_info = qi .determine_wallet_info() .map_err(|detail| TaskError::WalletInfoDeterminationFailed { detail })?; - self.insert_local_qualified_identity_under_lock(qi, &wallet_info)?; + self.write_loaded_identity_locked(qi, &wallet_info, write)?; return Ok(wallet_info); }; let mut relevant_keys = qi.private_keys.keys_set(); @@ -665,10 +797,24 @@ impl AppContext { let wallet_info = qi .determine_wallet_info() .map_err(|detail| TaskError::WalletInfoDeterminationFailed { detail })?; - self.insert_local_qualified_identity_under_lock(qi, &wallet_info)?; + self.write_loaded_identity_locked(qi, &wallet_info, write)?; Ok(wallet_info) } + fn write_loaded_identity_locked( + &self, + qi: &QualifiedIdentity, + wallet_info: &Option<(WalletSeedHash, u32)>, + write: IdentityRecordWrite, + ) -> Result<(), TaskError> { + match write { + IdentityRecordWrite::Import => { + self.insert_local_qualified_identity_under_lock(qi, wallet_info) + } + IdentityRecordWrite::UpdateListed => self.write_local_qualified_identity_locked(qi), + } + } + /// Record placements and seal plaintext under the caller-held record lock and revalidated password. pub(super) fn seal_merged_plaintext_keys( &self, @@ -934,6 +1080,309 @@ mod tests { const M: PrivateKeyTarget = PrivateKeyTarget::PrivateKeyOnMainIdentity; const V: PrivateKeyTarget = PrivateKeyTarget::PrivateKeyOnVoterIdentity; + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn additional_scenarios_wrong_node_voting_key_is_rejected_without_merge() { + let staged = crate::context::test_staging::stage_identity_with_vaulted_keys( + rand::random(), + rand::random(), + ) + .await; + let before = staged + .ctx + .get_local_qualified_identity(&staged.id) + .unwrap() + .unwrap(); + let private_key = PrivateKey::from_byte_array(&rand::random(), Network::Testnet).unwrap(); + let address = private_key.public_key(&Secp256k1::new()).pubkey_hash(); + let other_node = Identifier::from([0x75; 32]); + let other_voter = + Identifier::create_voter_identifier(other_node.as_bytes(), address.as_ref()); + let selected_voter = + Identifier::create_voter_identifier(staged.id.as_bytes(), address.as_ref()); + assert_ne!(selected_voter, other_voter); + let mut sdk = Sdk::new_mock(); + sdk.mock() + .expect_fetch(staged.id, Some(before.identity.clone())) + .await + .unwrap(); + let mut other_identity = + Identity::create_basic_identity(other_voter, PlatformVersion::latest()).unwrap(); + other_identity.add_public_keys([IdentityPublicKey::V0( + dash_sdk::dpp::identity::identity_public_key::v0::IdentityPublicKeyV0 { + id: 0, + purpose: dash_sdk::dpp::identity::Purpose::VOTING, + security_level: SecurityLevel::HIGH, + contract_bounds: None, + key_type: KeyType::ECDSA_HASH160, + read_only: false, + data: address.to_byte_array().to_vec().into(), + disabled_at: None, + }, + )]); + staged + .ctx + .verify_voting_key_exists_on_identity( + &other_identity, + &private_key.inner.secret_bytes(), + ) + .unwrap(); + sdk.mock() + .expect_fetch(other_voter, Some(other_identity)) + .await + .unwrap(); + sdk.mock() + .expect_fetch(selected_voter, None::) + .await + .unwrap(); + let input = IdentityInputToLoad { + identity_id_input: staged.id.to_string(Encoding::Hex), + identity_type: IdentityType::Masternode, + alias_input: String::new(), + voting_private_key_input: Secret::new(private_key.to_wif()), + owner_private_key_input: Secret::default(), + payout_address_private_key_input: Secret::default(), + keys_input: vec![], + derive_keys_from_wallets: false, + selected_wallet_seed_hash: None, + encryption_password: None, + load_mode: IdentityLoadMode::MergeIntoExisting, + load_token: None, + }; + let error = staged.ctx.load_identity(&sdk, input).await.unwrap_err(); + let after = staged + .ctx + .get_local_qualified_identity(&staged.id) + .unwrap() + .unwrap(); + assert_eq!( + after.associated_voter_identity, + before.associated_voter_identity + ); + assert!( + after.private_keys == before.private_keys, + "a rejected key must preserve all stored key placements and values" + ); + assert_eq!( + error.to_string(), + "This voting key could not be matched to the selected node. Check that node's voting private key and try again." + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn scoped_merge_cannot_restore_an_identity_removed_during_loading() { + let staged = + crate::context::test_staging::stage_identity_with_vaulted_keys([0x77; 32], [0x88; 32]) + .await; + let mut loaded = staged + .ctx + .get_local_qualified_identity(&staged.id) + .unwrap() + .unwrap(); + let claim = staged.ctx.begin_identity_load(staged.id, None).unwrap(); + staged + .ctx + .delete_local_qualified_identity(&staged.id) + .unwrap(); + let result = staged.ctx.finish_identity_load_storage( + &mut loaded, + IdentityLoadMode::MergeIntoExisting, + None, + &claim, + None, + ); + assert!(result.is_err(), "a scoped merge must not undo a removal"); + assert!(!staged.ctx.is_identity_listed(&staged.id).unwrap()); + assert!( + staged + .ctx + .get_local_qualified_identity(&staged.id) + .unwrap() + .is_none() + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn scoped_merge_cannot_modify_a_reimported_identity() { + let staged = + crate::context::test_staging::stage_identity_with_vaulted_keys([0x79; 32], [0x89; 32]) + .await; + let mut loaded = staged + .ctx + .get_local_qualified_identity(&staged.id) + .unwrap() + .unwrap(); + let claim = staged.ctx.begin_identity_load(staged.id, None).unwrap(); + staged + .ctx + .delete_local_qualified_identity(&staged.id) + .unwrap(); + let mut reimported = loaded.clone(); + reimported.alias = Some("explicit reimport".into()); + staged + .ctx + .insert_local_qualified_identity(&reimported, &None) + .unwrap(); + assert!(matches!( + staged.ctx.finish_identity_load_storage( + &mut loaded, + IdentityLoadMode::MergeIntoExisting, + None, + &claim, + None + ), + Err(TaskError::IdentityLoadSuperseded { .. }) + )); + claim.loaded(); + assert_eq!( + staged + .ctx + .get_local_qualified_identity(&staged.id) + .unwrap() + .unwrap() + .alias, + reimported.alias + ); + assert_eq!( + staged.ctx.last_identity_load_phase(&staged.id), + Some(crate::context::identity_load_registry::IdentityLoadPhase::Failed) + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn removal_cancels_older_imports_but_allows_a_fresh_explicit_import() { + let staged = + crate::context::test_staging::stage_identity_with_vaulted_keys([0x7c; 32], [0x8c; 32]) + .await; + let mut loaded = staged + .ctx + .get_local_qualified_identity(&staged.id) + .unwrap() + .unwrap(); + let old_claim = staged.ctx.begin_identity_load(staged.id, None).unwrap(); + staged + .ctx + .delete_local_qualified_identity(&staged.id) + .unwrap(); + for mode in [ + IdentityLoadMode::Overwrite, + IdentityLoadMode::RejectIfExists, + ] { + assert!( + matches!( + staged.ctx.finish_identity_load_storage( + &mut loaded, + mode, + None, + &old_claim, + None + ), + Err(TaskError::IdentityLoadSuperseded { .. }) + ), + "a removed load must not store after its claim was invalidated" + ); + } + let fresh_claim = staged.ctx.begin_identity_load(staged.id, None).unwrap(); + loaded.alias = Some("fresh explicit import".into()); + staged + .ctx + .finish_identity_load_storage( + &mut loaded, + IdentityLoadMode::Overwrite, + None, + &fresh_claim, + None, + ) + .unwrap(); + fresh_claim.loaded(); + drop(old_claim); + assert!(staged.ctx.is_identity_listed(&staged.id).unwrap()); + assert_eq!( + staged.ctx.last_identity_load_phase(&staged.id), + Some(crate::context::identity_load_registry::IdentityLoadPhase::Loaded) + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn scoped_merge_preserves_changes_made_while_loading() { + let staged = + crate::context::test_staging::stage_identity_with_vaulted_keys([0x7a; 32], [0x8a; 32]) + .await; + let mut loaded = staged.ctx.get_identity_by_id(&staged.id).unwrap().unwrap(); + let claim = staged.ctx.begin_identity_load(staged.id, None).unwrap(); + let mut current = loaded.clone(); + current.alias = Some("renamed during load".into()); + current.top_ups.insert(9, 77); + staged + .ctx + .save_top_ups(&staged.id, ¤t.top_ups) + .unwrap(); + current.status = IdentityStatus::NotFound; + loaded.alias = Some("stale form alias".into()); + loaded.private_keys = Default::default(); + staged + .ctx + .insert_local_qualified_identity(¤t, &None) + .unwrap(); + staged + .ctx + .finish_identity_load_storage( + &mut loaded, + IdentityLoadMode::MergeIntoExisting, + None, + &claim, + None, + ) + .unwrap(); + let stored = staged.ctx.get_identity_by_id(&staged.id).unwrap().unwrap(); + assert_eq!(stored.alias, current.alias); + assert_eq!(stored.top_ups, current.top_ups); + assert_eq!(stored.status, current.status); + assert_eq!( + stored.private_keys.keys_set(), + current.private_keys.keys_set() + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn scoped_merge_rejects_protection_changed_while_loading() { + let staged = + crate::context::test_staging::stage_identity_with_vaulted_keys([0x7b; 32], [0x8b; 32]) + .await; + let mut loaded = staged + .ctx + .get_local_qualified_identity(&staged.id) + .unwrap() + .unwrap(); + let claim = staged.ctx.begin_identity_load(staged.id, None).unwrap(); + staged + .ctx + .protect_identity_keys(staged.id, Secret::new("new-identity-password"), None) + .unwrap(); + assert!(matches!( + staged.ctx.finish_identity_load_storage( + &mut loaded, + IdentityLoadMode::MergeIntoExisting, + None, + &claim, + None + ), + Err(TaskError::IdentityLoadSuperseded { .. }) + )); + let backend = staged.ctx.wallet_backend().unwrap(); + let view = IdentityKeyView::new(backend.secret_store(), staged.id.to_buffer()); + for (target, key_id) in [(M, 1), (M, 2)] { + assert_eq!( + view.scheme(&target, key_id).unwrap(), + SecretScheme::Protected + ); + assert!( + view.get_protected(&target, key_id, &SecretString::new("new-identity-password")) + .unwrap() + .is_some() + ); + } + } + #[tokio::test] async fn identity_network_timeout_is_typed_and_actionable() { let error = crate::backend_task::await_network_request_with_timeout( @@ -2163,8 +2612,38 @@ mod tests { .verify_identity_object_password(&verify_scope) .await .expect("scripted password verifies"); - ctx.persist_merged_identity(&mut existing, Some(&password)) - .expect("persist merged protected key"); + let claim = ctx.begin_identity_load(identity_id, None).unwrap(); + // A password rotation during the fetch must reject the old verified + // password before writing even one new key into the vault. + ctx.unprotect_identity_keys(identity_id, Secret::new(PW)) + .unwrap(); + ctx.protect_identity_keys(identity_id, Secret::new("rotated-identity-password"), None) + .unwrap(); + assert!(matches!( + ctx.finish_identity_load_storage( + &mut existing, + IdentityLoadMode::MergeIntoExisting, + Some(&password), + &claim, + None + ), + Err(TaskError::IdentityLoadSuperseded { .. }) + )); + let backend = ctx.wallet_backend().unwrap(); + let view = IdentityKeyView::new(backend.secret_store(), identity_id.to_buffer()); + assert_eq!(view.scheme(&V, new_voter_id).unwrap(), SecretScheme::Absent); + ctx.unprotect_identity_keys(identity_id, Secret::new("rotated-identity-password")) + .unwrap(); + ctx.protect_identity_keys(identity_id, Secret::new(PW), None) + .unwrap(); + ctx.finish_identity_load_storage( + &mut existing, + IdentityLoadMode::MergeIntoExisting, + Some(&password), + &claim, + None, + ) + .expect("seal and persist a merged key under the current password"); // The new key flipped to InVault in the in-memory identity... assert!( @@ -2193,6 +2672,88 @@ mod tests { backend.shutdown().await; } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn protected_merge_seals_resident_plaintext_alongside_new_key() { + use crate::wallet_backend::secret_prompt::test_support::{ScriptedAnswer, TestPrompt}; + const PW: &str = "synthetic-resident-merge-password"; + for always_clear in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let ctx = open_import_context( + dir.path(), + Some(Arc::new(TestPrompt::new([ScriptedAnswer::once(PW)]))), + ) + .await; + let (qi, _) = masternode_shaped_qi(); + let id = qi.identity.id(); + ctx.insert_local_qualified_identity(&qi, &None).unwrap(); + ctx.protect_identity_keys(id, Secret::new(PW), None) + .unwrap(); + let mut resident = ctx.get_local_qualified_identity(&id).unwrap().unwrap(); + let mut incoming = resident.clone(); + let pv = PlatformVersion::latest(); + let resident_key = IdentityPublicKey::random_key(10, Some(10), pv); + let new_key = IdentityPublicKey::random_key(11, Some(11), pv); + let resident_bytes = zeroize::Zeroizing::new(rand::random::<[u8; 32]>()); + let new_bytes = zeroize::Zeroizing::new(rand::random::<[u8; 32]>()); + // An incomplete migration can leave a resident key absent from the vault. + resident.private_keys.insert_at( + (V, 10), + ( + QualifiedIdentityPublicKey::from(resident_key), + if always_clear { + PrivateKeyData::AlwaysClear(*resident_bytes) + } else { + PrivateKeyData::Clear(*resident_bytes) + }, + ), + ); + incoming.private_keys.insert_at( + (V, 11), + ( + QualifiedIdentityPublicKey::from(new_key), + PrivateKeyData::Clear(*new_bytes), + ), + ); + let backend = ctx.wallet_backend().unwrap(); + let scope = ctx + .protected_identity_verify_scope(&incoming) + .unwrap() + .unwrap(); + let verified = backend + .secret_access() + .verify_identity_object_password(&scope) + .await + .unwrap(); + { + let lock = ctx.identity_record_lock(id); + let _guard = lock.lock().unwrap(); + ctx.persist_merged_identity_locked( + &mut incoming, + Some(resident), + Some(&verified), + IdentityRecordWrite::UpdateListed, + ) + .unwrap(); + } + let reread = ctx.get_local_qualified_identity(&id).unwrap().unwrap(); + assert!(!reread.private_keys.has_plaintext_for_vault()); + let view = IdentityKeyView::new(backend.secret_store(), id.to_buffer()); + for (key_id, expected) in [(10, &resident_bytes), (11, &new_bytes)] { + assert!(matches!( + reread.private_keys.entry_at(&(V, key_id)), + Some((_, PrivateKeyData::InVault)) + )); + assert_eq!(view.scheme(&V, key_id).unwrap(), SecretScheme::Protected); + let actual = view + .get_protected(&V, key_id, &SecretString::new(PW)) + .unwrap() + .unwrap(); + assert!(actual.as_slice() == expected.as_slice()); + } + backend.shutdown().await; + } + } + /// Merge×Tier-2 with a stored legacy `Encrypted` key: sealing skips that key /// (no vault entry), so a merge that keeps it must fail before any secret /// write. Resupplying the key replaces the legacy entry and the merge seals it. diff --git a/src/backend_task/identity/mod.rs b/src/backend_task/identity/mod.rs index 6acf5ba50..9719af650 100644 --- a/src/backend_task/identity/mod.rs +++ b/src/backend_task/identity/mod.rs @@ -1,6 +1,7 @@ mod add_key_to_identity; mod auth_pubkey_resolve; mod discover_identities; +mod dpns_usernames; mod load_identity; mod load_identity_by_dpns_name; mod load_identity_from_wallet; @@ -447,6 +448,10 @@ impl PartialEq for IdentityTopUpInfo { pub struct RegisterDpnsNameInput { pub qualified_identity: QualifiedIdentity, pub name_input: String, + /// Community vote fee explicitly approved for this name; zero declines a vote. + pub approved_contest_fee: u64, + /// Authentication key to sign with; `None` picks the identity's default document key. + pub signing_key_id: Option, } #[derive(Debug, Clone, PartialEq)] @@ -543,6 +548,30 @@ pub enum IdentityTask { }, RefreshIdentity(QualifiedIdentity), RefreshLoadedIdentitiesOwnedDPNSNames, + /// Check whether a username label can be requested right now. + CheckUsernameAvailability { + /// The identity that would request it. + identity_id: Identifier, + /// The bare label, as typed. + label: String, + }, + /// Refresh the community-vote requests of every loaded identity. + RefreshMyUsernameRequests, + /// Show `name` as the identity's main username on this device. + SetMainUsername { + identity_id: Identifier, + name: String, + }, + /// Remove a finished username request from the identity's list. + DismissUsernameRequest { + identity_id: Identifier, + normalized_label: String, + }, + /// Record that the outcome banners of `requests` were shown. + MarkUsernameOutcomesSeen { + identity_id: Identifier, + requests: Vec, + }, } /// Returns the default key specifications for a new identity. @@ -947,6 +976,22 @@ impl AppContext { IdentityTask::RefreshLoadedIdentitiesOwnedDPNSNames => { Ok(self.refresh_loaded_identities_dpns_names(sender).await?) } + IdentityTask::CheckUsernameAvailability { identity_id, label } => { + self.check_username_availability(sdk, identity_id, label) + .await + } + IdentityTask::RefreshMyUsernameRequests => self.refresh_my_username_requests(sdk).await, + IdentityTask::SetMainUsername { identity_id, name } => { + self.save_main_username(identity_id, name) + } + IdentityTask::DismissUsernameRequest { + identity_id, + normalized_label, + } => self.dismiss_username_outcome(identity_id, normalized_label), + IdentityTask::MarkUsernameOutcomesSeen { + identity_id, + requests, + } => self.save_username_outcomes_seen(identity_id, requests), IdentityTask::ProtectIdentityKeys { identity_id, password, diff --git a/src/backend_task/identity/protect_identity_keys.rs b/src/backend_task/identity/protect_identity_keys.rs index 8e21c06f0..cbd50635a 100644 --- a/src/backend_task/identity/protect_identity_keys.rs +++ b/src/backend_task/identity/protect_identity_keys.rs @@ -68,6 +68,7 @@ impl AppContext { /// [`Self::protect_identity_keys`] so the fail-closed guard, the seal, and /// the success result are exercised on a real `qi` as the task runs them — /// proving the guard is wired into the protect path, not merely callable. + /// The caller must hold this identity's record guard through the seal. fn protect_loaded_identity_keys( &self, qi: &QualifiedIdentity, diff --git a/src/backend_task/identity/refresh_loaded_identities_dpns_names.rs b/src/backend_task/identity/refresh_loaded_identities_dpns_names.rs index 3df6ed6fd..a4e2a926e 100644 --- a/src/backend_task/identity/refresh_loaded_identities_dpns_names.rs +++ b/src/backend_task/identity/refresh_loaded_identities_dpns_names.rs @@ -7,7 +7,7 @@ use dash_sdk::dpp::document::DocumentV0Getters; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::platform_value::Value; use dash_sdk::drive::query::{SelectProjection, WhereClause, WhereOperator}; -use dash_sdk::platform::{Document, DocumentQuery, FetchMany}; +use dash_sdk::platform::{Document, DocumentQuery, FetchMany, Identifier}; impl AppContext { pub(super) async fn refresh_loaded_identities_dpns_names( @@ -18,71 +18,259 @@ impl AppContext { let sdk = self.sdk.load().as_ref().clone(); - for mut qualified_identity in qualified_identities { - let identity_id = qualified_identity.identity.id(); - - let dpns_names_document_query = DocumentQuery { - sub_queries: Vec::new(), - select: SelectProjection::documents(), - data_contract: self.dpns_contract.clone(), - document_type_name: "domain".to_string(), - where_clauses: vec![WhereClause { - field: "records.identity".to_string(), - operator: WhereOperator::Equal, - value: Value::Identifier(identity_id.into()), - }], - time_range_clauses: Vec::new(), - group_by: Vec::new(), - having: Vec::new(), - order_by_clauses: vec![], - limit: 100, - offset: None, - start: None, - }; - - let owned_dpns_names = Document::fetch_many(&sdk, dpns_names_document_query) - .await - .map(|document_map| { - document_map - .values() - .filter_map(|maybe_doc| { - maybe_doc.as_ref().and_then(|doc| { - let name = doc - .get("label") - .map(|label| label.to_str().unwrap_or_default()); - let acquired_at = doc - .created_at() - .into_iter() - .chain(doc.transferred_at()) - .max(); - - match (name, acquired_at) { - (Some(name), Some(acquired_at)) => Some(DPNSNameInfo { - name: name.to_string(), - acquired_at, - }), - _ => None, - } - }) - }) - .collect::>() - }) - .map_err(|e| TaskError::DpnsFetchError { - source: Box::new(e), - })?; - - qualified_identity.dpns_names = owned_dpns_names; - - qualified_identity.initialize_node_alias(None, None); - - self.update_local_qualified_identity(&qualified_identity)?; - } + let refreshed = self + .refresh_owned_names_of(&sdk, qualified_identities) + .await; sender .send(TaskResult::Refresh) .await .map_err(|_| TaskError::InternalSendError)?; - Ok(BackendTaskSuccessResult::RefreshedOwnedDpnsNames) + refreshed.map(|()| BackendTaskSuccessResult::RefreshedOwnedDpnsNames) + } + + /// Refresh the owned names of every identity in the `identities` snapshot. + /// + /// An identity removed since the snapshot is skipped. Any other failure is + /// returned only after the remaining identities were refreshed. + async fn refresh_owned_names_of( + &self, + sdk: &dash_sdk::Sdk, + identities: Vec, + ) -> Result<(), TaskError> { + let mut first_error = None; + for identity in identities { + let refreshed = match self + .fetch_owned_dpns_names(sdk, identity.identity.id()) + .await + { + Ok(names) => self.finish_owned_names_refresh(identity, names), + Err(error) => Err(error), + }; + match refreshed { + Ok(()) | Err(TaskError::IdentityNotFoundLocally) => {} + Err(error) => { + first_error.get_or_insert(error); + } + } + } + first_error.map_or(Ok(()), Err) + } + + fn finish_owned_names_refresh( + &self, + identity: crate::model::qualified_identity::QualifiedIdentity, + names: Vec, + ) -> Result<(), TaskError> { + self.edit_local_qualified_identity(&identity.identity.id(), |fresh| { + fresh.dpns_names = names; + let main_username = self.main_username(fresh); + fresh.initialize_node_alias(None, main_username.as_deref()); + Ok(()) + })?; + Ok(()) + } + + /// Every DPNS name whose records point at `identity_id`. + pub(crate) async fn fetch_owned_dpns_names( + &self, + sdk: &dash_sdk::Sdk, + identity_id: Identifier, + ) -> Result, TaskError> { + let documents = Document::fetch_many(sdk, self.owned_dpns_names_query(identity_id)) + .await + .map_err(|e| TaskError::DpnsFetchError { + source: Box::new(e), + })?; + Ok(documents + .values() + .flatten() + .filter_map(|doc| { + let name = doc.get("label")?.to_str().ok()?.to_owned(); + let acquired_at = doc + .created_at() + .into_iter() + .chain(doc.transferred_at()) + .max()?; + Some(DPNSNameInfo { name, acquired_at }) + }) + .collect()) + } + + /// The lookup for every DPNS name whose records point at `identity_id`. + pub(super) fn owned_dpns_names_query(&self, identity_id: Identifier) -> DocumentQuery { + DocumentQuery { + sub_queries: Vec::new(), + select: SelectProjection::documents(), + data_contract: self.dpns_contract.clone(), + document_type_name: "domain".to_string(), + where_clauses: vec![WhereClause { + field: "records.identity".to_string(), + operator: WhereOperator::Equal, + value: Value::Identifier(identity_id.into()), + }], + time_range_clauses: Vec::new(), + group_by: Vec::new(), + having: Vec::new(), + order_by_clauses: vec![], + limit: 100, + offset: None, + start: None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn bare_identity(byte: u8) -> crate::model::qualified_identity::QualifiedIdentity { + crate::context::test_support::bare_user_identity( + [byte; 32].into(), + dash_sdk::dpp::dashcore::Network::Testnet, + ) + } + + #[test] + fn followup_owned_names_refresh_preserves_concurrent_identity_edits() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store( + std::sync::Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()), + )); + let stale = bare_identity(8); + let mut current = stale.clone(); + current.alias = Some("Updated during registration".into()); + let key = dash_sdk::platform::IdentityPublicKey::random_key( + 9, + Some(8), + dash_sdk::dpp::version::PlatformVersion::latest(), + ); + current.private_keys.insert_at((crate::model::qualified_identity::PrivateKeyTarget::PrivateKeyOnMainIdentity, 9), ( + crate::model::qualified_identity::qualified_identity_public_key::QualifiedIdentityPublicKey::from(key.clone()), + crate::model::qualified_identity::encrypted_key_storage::PrivateKeyData::InVault, + )); + ctx.update_local_qualified_identity(¤t).unwrap(); + ctx.finish_owned_names_refresh( + stale, + vec![DPNSNameInfo { + name: "alice-123".into(), + acquired_at: 1_000, + }], + ) + .unwrap(); + let saved = ctx + .get_local_qualified_identity(¤t.identity.id()) + .unwrap() + .unwrap(); + assert_eq!(saved.alias, current.alias); + assert!(saved.private_keys.first_live_candidate(&key).is_some()); + assert!(saved.dpns_names.iter().any(|name| name.name == "alice-123")); + } + + /// Mock the owned-names lookup of `owner` to return one name. + async fn expect_owned_name(sdk: &mut dash_sdk::Sdk, ctx: &AppContext, owner: Identifier) { + let document = Document::V0(dash_sdk::dpp::document::DocumentV0 { + id: owner, + owner_id: owner, + creator_id: None, + properties: std::collections::BTreeMap::from([( + "label".to_string(), + Value::Text("owned-name-2".to_string()), + )]), + revision: None, + created_at: Some(100), + updated_at: None, + transferred_at: None, + created_at_block_height: None, + updated_at_block_height: None, + transferred_at_block_height: None, + created_at_core_block_height: None, + updated_at_core_block_height: None, + transferred_at_core_block_height: None, + contract_version: None, + }); + let documents: dash_sdk::query_types::Documents = + [(document.id(), Some(document))].into_iter().collect(); + sdk.mock() + .expect_fetch_many::( + ctx.owned_dpns_names_query(owner), + Some(documents), + ) + .await + .expect("owned names expectation"); + } + + fn owned_names(ctx: &AppContext, id: &Identifier) -> Vec { + ctx.get_local_qualified_identity(id) + .unwrap() + .expect("identity is stored") + .dpns_names + .into_iter() + .map(|name| name.name) + .collect() + } + + /// An identity removed while the refresh runs is skipped without an error, + /// and the identities after it are still refreshed. + #[tokio::test] + async fn owned_names_refresh_skips_an_identity_removed_mid_run() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store( + std::sync::Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()), + )); + let (removed, kept) = (bare_identity(5), bare_identity(6)); + let (removed_id, kept_id) = (removed.identity.id(), kept.identity.id()); + for identity in [&removed, &kept] { + ctx.update_local_qualified_identity(identity).unwrap(); + } + let mut sdk = dash_sdk::Sdk::new_mock(); + expect_owned_name(&mut sdk, &ctx, removed_id).await; + expect_owned_name(&mut sdk, &ctx, kept_id).await; + // Removed after the snapshot below was taken, before its write lands. + ctx.delete_local_qualified_identity_with_outcome(&removed_id) + .unwrap(); + + ctx.refresh_owned_names_of(&sdk, vec![removed, kept]) + .await + .expect("a removed identity is not a refresh failure"); + + assert_eq!(owned_names(&ctx, &kept_id), ["owned-name-2"]); + assert!( + ctx.get_local_qualified_identity(&removed_id) + .unwrap() + .is_none(), + "the refresh must not bring a removed identity back" + ); + } + + /// One identity whose names cannot be read does not stop the others from + /// being refreshed; the failure is still reported. + #[tokio::test] + async fn owned_names_refresh_continues_past_a_failed_identity() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store( + std::sync::Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()), + )); + let (unreadable, readable) = (bare_identity(5), bare_identity(6)); + let readable_id = readable.identity.id(); + for identity in [&unreadable, &readable] { + ctx.update_local_qualified_identity(identity).unwrap(); + } + // Only the second identity's lookup is mocked; the first one fails. + let mut sdk = dash_sdk::Sdk::new_mock(); + expect_owned_name(&mut sdk, &ctx, readable_id).await; + + let result = ctx + .refresh_owned_names_of(&sdk, vec![unreadable, readable]) + .await; + + assert!( + matches!(result, Err(TaskError::DpnsFetchError { .. })), + "{result:?}" + ); + assert_eq!(owned_names(&ctx, &readable_id), ["owned-name-2"]); } } diff --git a/src/backend_task/identity/register_dpns_name.rs b/src/backend_task/identity/register_dpns_name.rs index ccf07073c..75305b329 100644 --- a/src/backend_task/identity/register_dpns_name.rs +++ b/src/backend_task/identity/register_dpns_name.rs @@ -5,7 +5,11 @@ use crate::backend_task::error::TaskError; use crate::{ context::AppContext, model::{ - dpns::{DpnsNameValidationResult, classify_dpns_registration_outcome, validate_dpns_name}, + dpns::{ + DpnsNameValidationResult, DpnsRegistrationOutcome, classify_dpns_registration_outcome, + normalize_dpns_label, validate_dpns_name, + }, + fee_estimation::contest_fee_credits, qualified_identity::DPNSNameInfo, }, }; @@ -16,17 +20,18 @@ use dash_sdk::{ data_contract::{ accessors::v0::DataContractV0Getters, document_type::accessors::DocumentTypeV0Getters, }, - document::{DocumentV0, DocumentV0Getters}, - identity::accessors::IdentityGettersV0, - platform_value::{Bytes32, Value}, + document::DocumentV0, + identity::accessors::{IdentityGettersV0, IdentitySettersV0}, + platform_value::Bytes32, util::{hash::hash_double, strings::convert_to_homograph_safe_chars}, + version::PlatformVersion, }, - drive::query::{SelectProjection, WhereClause, WhereOperator}, platform::Fetch, - platform::{Document, DocumentQuery, FetchMany, transition::put_document::PutDocument}, + platform::{Document, Identifier, transition::put_document::PutDocument}, }; use super::{BackendTaskSuccessResult, RegisterDpnsNameInput}; +use crate::model::dpns_usernames::{dpns_signing_requirement, key_can_sign_documents}; fn rebrand_dpns_domain_conflict(error: TaskError) -> TaskError { match error { @@ -37,6 +42,31 @@ fn rebrand_dpns_domain_conflict(error: TaskError) -> TaskError { } } +/// Whether the network refused the last broadcast attempt. +/// +/// `broadcast` re-sends the same signed transition and reports only its last +/// attempt, so a refusal can follow an attempt that was applied: it is believed +/// only once the network does not show the request. Any other failure (a +/// timeout, a dropped connection, no reachable node) proves nothing either way. +fn broadcast_was_rejected(error: &SdkError) -> bool { + match error { + SdkError::Protocol(dash_sdk::dpp::ProtocolError::ConsensusError(_)) => true, + SdkError::StateTransitionBroadcastError(broadcast_error) => broadcast_error.cause.is_some(), + _ => false, + } +} + +/// The community vote fee the user must have approved for `outcome`. +fn required_contest_fee( + outcome: DpnsRegistrationOutcome, + platform_version: &PlatformVersion, +) -> u64 { + match outcome { + DpnsRegistrationOutcome::PendingCommunityVote => contest_fee_credits(platform_version), + DpnsRegistrationOutcome::Registered => 0, + } +} + impl AppContext { pub(super) async fn register_dpns_name( &self, @@ -51,7 +81,7 @@ impl AppContext { let mut rng = StdRng::from_entropy(); let dpns_contract = self.dpns_contract.clone(); - let mut qualified_identity = input.qualified_identity; + let qualified_identity = input.qualified_identity; let entropy = Bytes32::random_with_rng(&mut rng); let preorder_document_type = dpns_contract @@ -152,9 +182,32 @@ impl AppContext { ) .map_err(|error| SdkError::Protocol(*error))?; - let public_key = qualified_identity - .document_signing_key(&preorder_document_type) - .ok_or(TaskError::NoDocumentSigningKey)?; + // The approval is checked against the document that is broadcast, so it + // can never cover a different charge than the one Platform applies. + if input.approved_contest_fee != required_contest_fee(outcome, sdk.version()) { + return Err(TaskError::UsernameRegistrationTermsChanged); + } + + // Authoritative re-check before any fee is spent: the name may have been + // taken, locked, or closed to new requests since the user chose it. + let availability = self + .username_availability(sdk, qualified_identity.identity.id(), &input.name_input) + .await?; + if !availability.allows_registration() { + return Err(TaskError::UsernameNoLongerAvailable { availability }); + } + let joined_until = availability.join_deadline(); + + let public_key = match input.signing_key_id { + Some(key_id) => qualified_identity + .identity + .get_public_key_by_id(key_id) + .filter(|key| { + key_can_sign_documents(key, dpns_signing_requirement(&self.dpns_contract)) + }), + None => qualified_identity.document_signing_key(&preorder_document_type), + } + .ok_or(TaskError::NoDocumentSigningKey)?; let fee_estimator = self.fee_estimator(); let estimated_fee = fee_estimator.estimate_document_batch(2); @@ -175,7 +228,7 @@ impl AppContext { // usernames, so conflicts keep the generic `PlatformEntryConflict` message. .await?; - let _ = domain_document + if let Err(error) = domain_document .put_to_platform_and_wait_for_response( sdk, domain_document_type.to_owned_document_type(), @@ -186,103 +239,226 @@ impl AppContext { None, ) .await - .map_err(|error| rebrand_dpns_domain_conflict(TaskError::from(error)))?; - - let dpns_names_document_query = DocumentQuery { - sub_queries: Vec::new(), - select: SelectProjection::documents(), - data_contract: self.dpns_contract.clone(), - document_type_name: "domain".to_string(), - where_clauses: vec![WhereClause { - field: "records.identity".to_string(), - operator: WhereOperator::Equal, - value: Value::Identifier(qualified_identity.identity.id().into()), - }], - time_range_clauses: Vec::new(), - group_by: Vec::new(), - having: Vec::new(), - order_by_clauses: vec![], - limit: 100, - offset: None, - start: None, - }; + { + self.resolve_failed_domain_broadcast( + sdk, + qualified_identity.identity.id(), + &input.name_input, + outcome, + error, + ) + .await?; + } + + Ok(self + .finish_username_registration( + sdk, + qualified_identity, + &input.name_input, + outcome, + joined_until, + balance_before, + estimated_fee, + ) + .await) + } - let owned_dpns_names = Document::fetch_many(sdk, dpns_names_document_query) + /// Decide what a failed name-request broadcast means, given it may be paid for. + /// + /// `Ok(())` when the network already shows the request, so the registration + /// carries on as a success, even after a refusal. A refusal keeps its own + /// error only when a successful read does not show the request. Anything + /// else, a failed read included, is reported as unconfirmed, never as a + /// plain failure that invites paying again. + async fn resolve_failed_domain_broadcast( + &self, + sdk: &Sdk, + identity_id: Identifier, + name: &str, + outcome: DpnsRegistrationOutcome, + error: SdkError, + ) -> Result<(), TaskError> { + match self + .username_request_reached_network(sdk, identity_id, name, outcome) .await - .map(|document_map| { - document_map - .values() - .filter_map(|maybe_doc| { - maybe_doc.as_ref().and_then(|doc| { - let name = doc - .get("label") - .map(|label| label.to_str().unwrap_or_default()); - let acquired_at = doc - .created_at() - .into_iter() - .chain(doc.transferred_at()) - .max(); - - match (name, acquired_at) { - (Some(name), Some(acquired_at)) => Some(DPNSNameInfo { - name: name.to_string(), - acquired_at, - }), - _ => None, - } - }) - }) - .collect::>() - }) - .map_err(|e| TaskError::DpnsFetchError { - source: Box::new(e), - })?; - - qualified_identity.dpns_names = owned_dpns_names; - - qualified_identity.initialize_node_alias(None, Some(&input.name_input)); - - let refreshed_identity = dash_sdk::platform::Identity::fetch_by_identifier( - sdk, - qualified_identity.identity.id(), - ) - .await? - .ok_or(TaskError::IdentityNotFound)?; + { + Ok(true) => { + tracing::warn!( + ?error, + %identity_id, + "Username registration reported an error, but the network shows the request; continuing as submitted" + ); + return Ok(()); + } + Ok(false) if broadcast_was_rejected(&error) => { + return Err(rebrand_dpns_domain_conflict(TaskError::from(error))); + } + Ok(false) => {} + Err(read_error) => tracing::warn!( + ?read_error, + %identity_id, + "Username request could not be looked up after its broadcast failed; reporting the registration as unconfirmed" + ), + } + Err(TaskError::UsernameRegistrationUnconfirmed { + source_error: Box::new(error), + }) + } - let balance_after = refreshed_identity.balance(); - let actual_fee = balance_before.saturating_sub(balance_after); + /// Whether the network shows `identity_id`'s request for `name`. + /// + /// # Errors + /// + /// The read failed, which says nothing about the request either way. + async fn username_request_reached_network( + &self, + sdk: &Sdk, + identity_id: Identifier, + name: &str, + outcome: DpnsRegistrationOutcome, + ) -> Result { + match outcome { + DpnsRegistrationOutcome::PendingCommunityVote => { + let vote = sdk + .get_contested_dpns_vote_state(&normalize_dpns_label(name), None) + .await?; + Ok(vote.contenders.contains_key(&identity_id)) + } + DpnsRegistrationOutcome::Registered => { + let names = self.fetch_owned_dpns_names(sdk, identity_id).await?; + Ok(names.iter().any(|owned| owned.name == name)) + } + } + } - tracing::info!( - "DPNS registration complete: estimated fee {} credits, actual fee {} credits", - estimated_fee, - actual_fee - ); - if actual_fee != estimated_fee { + /// Wrap up a registration whose documents were already broadcast and paid for. + /// + /// Infallible on purpose: the user has paid, so a failed re-read or local + /// save is logged and the registration still reports success, never inviting + /// a second payment. + #[expect( + clippy::too_many_arguments, + reason = "the registration's already-computed facts, passed once" + )] + async fn finish_username_registration( + &self, + sdk: &Sdk, + identity: crate::model::qualified_identity::QualifiedIdentity, + name: &str, + outcome: DpnsRegistrationOutcome, + joined_until: Option, + balance_before: u64, + estimated_fee: u64, + ) -> BackendTaskSuccessResult { + // The name request is broadcast and paid for: from here on nothing may + // report failure, or the user would be invited to pay again. + let identity_id = identity.identity.id(); + if outcome == DpnsRegistrationOutcome::PendingCommunityVote + && let Err(error) = + self.record_submitted_username_request(sdk, &identity_id, name, joined_until) + { tracing::warn!( - "Fee mismatch: estimated {} vs actual {} (diff: {})", - estimated_fee, - actual_fee, - actual_fee as i64 - estimated_fee as i64 + ?error, + "Submitted username request could not be stored locally" ); } - qualified_identity.identity = refreshed_identity; + let refreshed_names = match self.fetch_owned_dpns_names(sdk, identity_id).await { + Ok(names) => Some(names), + Err(error) => { + tracing::warn!( + ?error, + "Registered names could not be re-read after registration" + ); + None + } + }; - self.update_local_qualified_identity(&qualified_identity)?; + let mut refreshed_balance = None; + let fee_result = match dash_sdk::platform::Identity::fetch_by_identifier(sdk, identity_id) + .await + { + Ok(Some(refreshed_identity)) => { + let actual_fee = balance_before.saturating_sub(refreshed_identity.balance()); + refreshed_balance = Some(refreshed_identity.balance()); + if actual_fee != estimated_fee { + tracing::warn!( + estimated_fee, + actual_fee, + "Username registration fee differs from the estimate" + ); + } + FeeResult::new(estimated_fee, actual_fee) + } + Ok(None) | Err(_) => { + tracing::warn!("Identity balance could not be re-read after username registration"); + FeeResult::estimated_only(estimated_fee) + } + }; - let fee_result = FeeResult::new(estimated_fee, actual_fee); - Ok(BackendTaskSuccessResult::RegisteredDpnsName { + if let Err(error) = self.edit_local_qualified_identity(&identity_id, |fresh| { + if let Some(names) = refreshed_names { + fresh.dpns_names = names; + } + // A re-read served by a node that has not seen the new name yet + // must not drop it: the registration is already paid for. + if outcome == DpnsRegistrationOutcome::Registered + && !fresh.dpns_names.iter().any(|known| known.name == name) + { + fresh.dpns_names.push(DPNSNameInfo { + name: name.to_owned(), + acquired_at: crate::utils::time::now_ms(), + }); + } + if let Some(balance) = refreshed_balance { + fresh.identity.set_balance(balance); + } + let main_username = self.main_username(fresh); + fresh.initialize_node_alias(None, main_username.as_deref()); + Ok(()) + }) { + tracing::warn!( + ?error, + "Identity could not be saved locally after username registration" + ); + } + + BackendTaskSuccessResult::RegisteredDpnsName { outcome, fee_result, - }) + } } } #[cfg(test)] mod tests { use super::*; + use crate::model::dpns_usernames::UsernameAvailability; + use dash_sdk::dpp::block::block_info::BlockInfo; use dash_sdk::dpp::consensus::ConsensusError::StateError as ConsensusStateError; use dash_sdk::dpp::consensus::state::state_error::StateError; + use dash_sdk::dpp::document::DocumentV0Getters; + use dash_sdk::dpp::voting::contender_structs::{ + ContenderWithSerializedDocument, ContenderWithSerializedDocumentV0, + }; + use dash_sdk::dpp::voting::vote_info_storage::contested_document_vote_poll_winner_info::ContestedDocumentVotePollWinnerInfo; + use dash_sdk::drive::query::vote_poll_vote_state_query::{ + ContestedDocumentVotePollDriveQuery, ContestedDocumentVotePollDriveQueryResultType, + }; + use dash_sdk::query_types::{Contenders, Documents}; + + #[test] + fn dpns_registration_needs_a_high_or_critical_key() { + use dash_sdk::dpp::data_contracts::SystemDataContract; + use dash_sdk::dpp::identity::SecurityLevel; + use dash_sdk::dpp::system_data_contracts::load_system_data_contract; + let contract = load_system_data_contract( + SystemDataContract::DPNS, + dash_sdk::dpp::version::PlatformVersion::latest(), + ) + .expect("DPNS"); + assert_eq!(dpns_signing_requirement(&contract), SecurityLevel::HIGH); + } fn duplicate_unique_index_conflict(properties: Vec<&str>) -> TaskError { let source_error = Box::new(crate::test_support::duplicate_unique_index_broadcast_error( @@ -324,4 +500,594 @@ mod tests { assert!(matches!(error, TaskError::DataContractNotFound)); } + + /// A user identity with no names, alias, or keys. + fn bare_identity(byte: u8) -> crate::model::qualified_identity::QualifiedIdentity { + crate::context::test_support::bare_user_identity( + [byte; 32].into(), + dash_sdk::dpp::dashcore::Network::Testnet, + ) + } + + #[tokio::test] + async fn review_regression_registration_preserves_concurrent_identity_edits() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store( + std::sync::Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()), + )); + let stale = bare_identity(8); + let mut current = stale.clone(); + current.alias = Some("Updated during registration".into()); + let key = dash_sdk::platform::IdentityPublicKey::random_key( + 9, + Some(8), + dash_sdk::dpp::version::PlatformVersion::latest(), + ); + current.private_keys.insert_at((crate::model::qualified_identity::PrivateKeyTarget::PrivateKeyOnMainIdentity, 9), ( + crate::model::qualified_identity::qualified_identity_public_key::QualifiedIdentityPublicKey::from(key.clone()), + crate::model::qualified_identity::encrypted_key_storage::PrivateKeyData::InVault, + )); + ctx.update_local_qualified_identity(¤t).unwrap(); + ctx.finish_username_registration( + &Sdk::new_mock(), + stale, + "alice-123", + DpnsRegistrationOutcome::Registered, + None, + 1_000, + 100, + ) + .await; + let saved = ctx + .get_local_qualified_identity(¤t.identity.id()) + .unwrap() + .unwrap(); + assert_eq!(saved.alias, current.alias); + assert!(saved.private_keys.first_live_candidate(&key).is_some()); + assert!(saved.dpns_names.iter().any(|name| name.name == "alice-123")); + } + + /// A re-read that succeeds but lags behind the registration must not drop + /// the name the user just paid for from the identity. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn registered_name_survives_a_lagging_reread() { + let dir = tempfile::tempdir().expect("tempdir"); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store( + std::sync::Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()), + )); + let identity = bare_identity(5); + let id = identity.identity.id(); + ctx.update_local_qualified_identity(&identity).unwrap(); + // The node answers, but only with a name registered earlier. + let mut sdk = Sdk::new_mock(); + sdk.mock() + .expect_fetch_many::( + ctx.owned_dpns_names_query(id), + Some(documents(Some(domain_document(id, "earlier-name-2")))), + ) + .await + .expect("owned names expectation"); + + ctx.finish_username_registration( + &sdk, + identity, + "alice-123", + DpnsRegistrationOutcome::Registered, + None, + 1_000, + 100, + ) + .await; + + let saved = ctx.get_local_qualified_identity(&id).unwrap().unwrap(); + let names: Vec<&str> = saved.dpns_names.iter().map(|n| n.name.as_str()).collect(); + assert_eq!(names, ["earlier-name-2", "alice-123"]); + } + + /// Once the documents are broadcast and paid for, failed re-reads must not + /// turn into an error that re-enables Pay; the request is recorded and no + /// automatic alias hides the user's chosen main name. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn paid_registration_succeeds_when_rereads_fail() { + use crate::model::dpns_usernames::RequestPhase; + let dir = tempfile::tempdir().expect("tempdir"); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store( + std::sync::Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()), + )); + // No expectations: every network re-read fails. + let sdk = Sdk::new_mock(); + let identity = bare_identity(7); + let id = identity.identity.id(); + ctx.update_local_qualified_identity(&identity).unwrap(); + + let pending = ctx + .finish_username_registration( + &sdk, + identity.clone(), + "alice", + DpnsRegistrationOutcome::PendingCommunityVote, + None, + 1_000, + 200, + ) + .await; + let BackendTaskSuccessResult::RegisteredDpnsName { + outcome, + fee_result, + } = pending + else { + panic!("expected a successful registration, got {pending:?}"); + }; + assert_eq!(outcome, DpnsRegistrationOutcome::PendingCommunityVote); + assert_eq!(fee_result.estimated_fee, 200); + let requests = ctx.username_requests_for(&id); + assert_eq!(requests.len(), 1, "the paid request must be listed"); + assert_eq!(requests[0].phase, RequestPhase::Joinable); + + let registered = ctx + .finish_username_registration( + &sdk, + identity, + "bob", + DpnsRegistrationOutcome::Registered, + None, + 1_000, + 100, + ) + .await; + assert!(matches!( + registered, + BackendTaskSuccessResult::RegisteredDpnsName { .. } + )); + } + + #[tokio::test] + async fn registration_rejects_unapproved_vote_fee_before_network_or_payment() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let sdk = Sdk::new_mock(); + let fee = crate::model::fee_estimation::contest_fee_credits(sdk.version()); + for (label, approved_contest_fee) in [("alice", 0), ("alice", fee + 1), ("alice-123", fee)] + { + let result = ctx + .register_dpns_name( + &sdk, + RegisterDpnsNameInput { + qualified_identity: bare_identity(9), + name_input: label.into(), + approved_contest_fee, + signing_key_id: None, + }, + ) + .await; + assert!( + matches!(result, Err(TaskError::UsernameRegistrationTermsChanged)), + "{label}: {result:?}" + ); + } + } + + /// The fee the user must have approved follows the document's own + /// classification: a document that opens a vote always requires the fee, + /// whatever any other predicate said about its label. + #[test] + fn required_contest_fee_follows_the_broadcast_document() { + let version = PlatformVersion::latest(); + let fee = contest_fee_credits(version); + assert!(fee > 0); + assert_eq!( + required_contest_fee(DpnsRegistrationOutcome::PendingCommunityVote, version), + fee + ); + assert_eq!( + required_contest_fee(DpnsRegistrationOutcome::Registered, version), + 0 + ); + } + + /// A registered-name document as the network returns it for `label`. + fn domain_document(owner: Identifier, label: &str) -> Document { + Document::V0(DocumentV0 { + id: Identifier::from([0x5D; 32]), + owner_id: owner, + creator_id: None, + properties: BTreeMap::from([("label".to_string(), label.into())]), + revision: None, + created_at: Some(100), + updated_at: None, + transferred_at: None, + created_at_block_height: None, + updated_at_block_height: None, + transferred_at_block_height: None, + created_at_core_block_height: None, + updated_at_core_block_height: None, + transferred_at_core_block_height: None, + contract_version: None, + }) + } + + fn documents(found: Option) -> Documents { + found + .map(|document| (document.id(), Some(document))) + .into_iter() + .collect() + } + + /// Mock the registered-name lookup for `label`. + async fn expect_domain_lookup(sdk: &mut Sdk, ctx: &AppContext, label: &str, found: bool) { + let found = found.then(|| domain_document(Identifier::from([0x5E; 32]), label)); + sdk.mock() + .expect_fetch_many::( + ctx.dpns_domain_query(&normalize_dpns_label(label)), + Some(documents(found)), + ) + .await + .expect("domain lookup expectation"); + } + + /// Mock the community-vote state for `label`. + async fn expect_vote_state(sdk: &mut Sdk, ctx: &AppContext, label: &str, state: Contenders) { + sdk.mock() + .expect_fetch_many::( + ContestedDocumentVotePollDriveQuery { + vote_poll: crate::model::dpns_voting::dpns_vote_poll( + &ctx.dpns_contract, + &normalize_dpns_label(label), + ) + .expect("vote poll"), + result_type: + ContestedDocumentVotePollDriveQueryResultType::DocumentsAndVoteTally, + allow_include_locked_and_abstaining_vote_tally: true, + start_at: None, + limit: None, + offset: None, + }, + Some(state), + ) + .await + .expect("vote state expectation"); + } + + /// A running vote whose requests come from `requesters`. + fn running_vote(requesters: &[Identifier]) -> Contenders { + Contenders { + contenders: requesters + .iter() + .map(|id| { + ( + *id, + ContenderWithSerializedDocument::V0(ContenderWithSerializedDocumentV0 { + identity_id: *id, + serialized_document: None, + vote_tally: Some(0), + }), + ) + }) + .collect(), + ..Default::default() + } + } + + /// The pay-time re-check must stop a registration the network no longer + /// accepts before the preorder or the name request is paid for. No broadcast + /// is mocked, so reaching one would fail with a different error. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn registration_stops_before_paying_when_the_name_is_no_longer_available() { + let dir = tempfile::tempdir().expect("tempdir"); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let requester = bare_identity(8); + let requester_id = requester.identity.id(); + let fee = contest_fee_credits(Sdk::new_mock().version()); + let locked = Contenders { + winner: Some(( + ContestedDocumentVotePollWinnerInfo::Locked, + BlockInfo::default(), + )), + ..Default::default() + }; + let cases = [ + ("alice-123", 0, true, None, UsernameAvailability::Taken), + ( + "alice", + fee, + false, + Some(locked), + UsernameAvailability::Locked, + ), + ( + "alice", + fee, + false, + Some(running_vote(&[Identifier::from([0x77; 32])])), + UsernameAvailability::JoinClosed, + ), + ( + "alice", + fee, + false, + Some(running_vote(&[requester_id])), + UsernameAvailability::AlreadyRequested, + ), + ]; + for (label, approved_contest_fee, registered, vote, expected) in cases { + let mut sdk = Sdk::new_mock(); + expect_domain_lookup(&mut sdk, &ctx, label, registered).await; + if let Some(vote) = vote { + expect_vote_state(&mut sdk, &ctx, label, vote).await; + } + let result = ctx + .register_dpns_name( + &sdk, + RegisterDpnsNameInput { + qualified_identity: requester.clone(), + name_input: label.to_owned(), + approved_contest_fee, + signing_key_id: None, + }, + ) + .await; + assert!( + matches!( + &result, + Err(TaskError::UsernameNoLongerAvailable { availability }) + if *availability == expected + ), + "{label}: expected {expected:?}, got {result:?}" + ); + } + } + + fn unproven_broadcast_failure() -> SdkError { + SdkError::TimeoutReached(std::time::Duration::from_secs(1), "no answer".to_owned()) + } + + fn refused_broadcast() -> SdkError { + crate::test_support::duplicate_unique_index_broadcast_error(vec![ + "normalizedParentDomainName", + "normalizedLabel", + ]) + } + + /// A refusal the network does not contradict keeps its own error and is not + /// turned into an "unconfirmed" warning. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn refused_name_request_keeps_its_own_error() { + let dir = tempfile::tempdir().expect("tempdir"); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let id = Identifier::from([8; 32]); + + // The vote is readable and shows only someone else's request. + let mut sdk = Sdk::new_mock(); + expect_vote_state( + &mut sdk, + &ctx, + "alice", + running_vote(&[Identifier::from([0x77; 32])]), + ) + .await; + + let result = ctx + .resolve_failed_domain_broadcast( + &sdk, + id, + "alice", + DpnsRegistrationOutcome::PendingCommunityVote, + refused_broadcast(), + ) + .await; + + assert!( + matches!(result, Err(TaskError::DpnsUsernameAlreadyTaken { .. })), + "{result:?}" + ); + } + + /// The broadcast is re-sent and only its last attempt is reported, so a + /// refusal can follow an attempt that was applied and paid for. When the + /// network shows the request, the registration carries on as submitted. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn refused_name_request_continues_when_the_request_is_on_the_network() { + let dir = tempfile::tempdir().expect("tempdir"); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let id = Identifier::from([8; 32]); + + let mut sdk = Sdk::new_mock(); + expect_vote_state(&mut sdk, &ctx, "alice", running_vote(&[id])).await; + + let result = ctx + .resolve_failed_domain_broadcast( + &sdk, + id, + "alice", + DpnsRegistrationOutcome::PendingCommunityVote, + refused_broadcast(), + ) + .await; + + assert!(result.is_ok(), "{result:?}"); + } + + /// A broadcast failure that proves nothing is reconciled first: when the + /// network already shows the request, the registration carries on. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn unproven_broadcast_failure_continues_when_the_request_is_on_the_network() { + let dir = tempfile::tempdir().expect("tempdir"); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let id = Identifier::from([8; 32]); + + let mut sdk = Sdk::new_mock(); + expect_vote_state(&mut sdk, &ctx, "alice", running_vote(&[id])).await; + let contested = ctx + .resolve_failed_domain_broadcast( + &sdk, + id, + "alice", + DpnsRegistrationOutcome::PendingCommunityVote, + unproven_broadcast_failure(), + ) + .await; + assert!(contested.is_ok(), "{contested:?}"); + + let mut sdk = Sdk::new_mock(); + sdk.mock() + .expect_fetch_many::( + ctx.owned_dpns_names_query(id), + Some(documents(Some(domain_document(id, "alice-123")))), + ) + .await + .expect("owned names expectation"); + let registered = ctx + .resolve_failed_domain_broadcast( + &sdk, + id, + "alice-123", + DpnsRegistrationOutcome::Registered, + unproven_broadcast_failure(), + ) + .await; + assert!(registered.is_ok(), "{registered:?}"); + } + + /// When nothing proves the outcome, the user is told the request may have + /// gone through and must not be paid for again, never that it simply failed. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn unproven_broadcast_failure_is_reported_as_unconfirmed() { + let dir = tempfile::tempdir().expect("tempdir"); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let id = Identifier::from([8; 32]); + + // The vote is readable but does not show this identity's request yet. + let mut lagging = Sdk::new_mock(); + expect_vote_state( + &mut lagging, + &ctx, + "alice", + running_vote(&[Identifier::from([0x77; 32])]), + ) + .await; + // No expectations: the reconciling read itself fails. + let unreachable = Sdk::new_mock(); + + for sdk in [lagging, unreachable] { + let result = ctx + .resolve_failed_domain_broadcast( + &sdk, + id, + "alice", + DpnsRegistrationOutcome::PendingCommunityVote, + unproven_broadcast_failure(), + ) + .await; + let error = match result { + Err(error @ TaskError::UsernameRegistrationUnconfirmed { .. }) => error, + other => panic!("expected an unconfirmed registration, got {other:?}"), + }; + let message = error.to_string(); + assert!(message.contains("Do not pay again yet."), "{message}"); + assert!(!message.contains("failed"), "{message}"); + } + } + + /// A refusal is only the last attempt's answer. When the read that would + /// show whether an earlier attempt was applied fails, the request may be + /// paid for, so the refusal is not reported as a plain failure. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn refused_name_request_is_unconfirmed_when_the_network_cannot_be_read() { + let dir = tempfile::tempdir().expect("tempdir"); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let id = Identifier::from([8; 32]); + + for (name, outcome) in [ + ("alice", DpnsRegistrationOutcome::PendingCommunityVote), + ("alice-123", DpnsRegistrationOutcome::Registered), + ] { + // No expectations: the reconciling read itself fails. + let unreachable = Sdk::new_mock(); + let result = ctx + .resolve_failed_domain_broadcast( + &unreachable, + id, + name, + outcome, + refused_broadcast(), + ) + .await; + let error = match result { + Err(error @ TaskError::UsernameRegistrationUnconfirmed { .. }) => error, + other => panic!("{name}: expected an unconfirmed registration, got {other:?}"), + }; + assert!( + error.to_string().contains("Do not pay again yet."), + "{error}" + ); + } + } + + /// A request that joins a running vote is saved with that vote's deadlines, + /// not with ones counted from the moment of payment. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn joined_request_is_saved_with_the_running_vote_deadlines() { + let dir = tempfile::tempdir().expect("tempdir"); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store( + std::sync::Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()), + )); + let sdk = Sdk::new_mock(); + let identity = bare_identity(6); + let id = identity.identity.id(); + ctx.update_local_qualified_identity(&identity).unwrap(); + let durations = crate::model::dpns::contest_durations(ctx.network, sdk.version()); + let join = u64::try_from(durations.join.as_millis()).unwrap(); + let total = u64::try_from(durations.total.as_millis()).unwrap(); + // The vote opened ten minutes ago, so its join window closes that much sooner. + let join_end = crate::utils::time::now_ms() + join - 600_000; + + ctx.finish_username_registration( + &sdk, + identity, + "alice", + DpnsRegistrationOutcome::PendingCommunityVote, + Some(join_end), + 1_000, + 200, + ) + .await; + + let requests = ctx.username_requests_for(&id); + assert_eq!(requests.len(), 1, "the paid request must be listed"); + assert_eq!(requests[0].join_end, Some(join_end)); + assert_eq!(requests[0].end, Some(join_end - join + total)); + } + + /// USR-TC-018 backend half: availability is re-checked before anything is + /// broadcast, so a failed or changed check spends nothing. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn registration_rechecks_availability_before_spending() { + let dir = tempfile::tempdir().expect("tempdir"); + let ctx = crate::context::test_support::test_app_context(dir.path()); + // No expectations: the first network call (the re-check) fails. + let result = ctx + .register_dpns_name( + &Sdk::new_mock(), + RegisterDpnsNameInput { + qualified_identity: bare_identity(8), + name_input: "alice".to_owned(), + approved_contest_fee: crate::model::fee_estimation::contest_fee_credits( + Sdk::new_mock().version(), + ), + signing_key_id: None, + }, + ) + .await; + assert!( + matches!( + result, + Err(TaskError::UsernameAvailabilityCheckFailed { .. }) + ), + "expected the re-check to stop the registration, got {result:?}" + ); + } } diff --git a/src/backend_task/migration/finish_unwire.rs b/src/backend_task/migration/finish_unwire.rs index e47afc4f8..8f48fbc81 100644 --- a/src/backend_task/migration/finish_unwire.rs +++ b/src/backend_task/migration/finish_unwire.rs @@ -214,18 +214,8 @@ pub enum MigrationError { failed: u32, }, - /// The decoded scheduled votes could not be written into the k/v store. - /// The app-data sentinel stays unwritten so the next launch retries the - /// idempotent import rather than leaving the votes behind. It never blocks - /// the wallet drain — [`run`] judges this only after the wallets are safe. - #[error("could not save scheduled votes from the previous version")] - ScheduledVotesWrite { - #[source] - source: Box, - }, - /// The app-data pass failed with an error that did not already originate in - /// the migration layer (a k/v read while checking which votes exist, say). + /// the migration layer (a top-up history write rejected by the k/v store, say). /// Wrapped so the combined [`MigrationState::FailedWithUnreadableIdentities`] /// banner keeps a typed chain when both DET-owned passes break together. #[error("could not import the previous version's app data")] @@ -255,16 +245,6 @@ pub enum MigrationError { source: Box, }, - /// Could not read, write or clear the durable unreadable-vote warning. That - /// record is what re-raises the warning on every launch until the user - /// acknowledges it, so a failure here is surfaced rather than dropped — a - /// silently-lost warning is a silently-missed vote deadline. - #[error("could not access the unreadable-vote warning")] - VoteWarningRecord { - #[source] - source: KvAdapterError, - }, - /// Could not read, write or clear the durable unreadable-top-up warning. #[error("could not access the unreadable top-up history warning")] TopUpWarningRecord { @@ -589,8 +569,9 @@ fn write_dapi_refresh_completion( /// /// Three independent recovery passes, each under its own sentinel, in this order: /// -/// 1. **App data** (scheduled votes, top-up history) — DET-owned rows the -/// wallet drain never touched. +/// 1. **App data** (top-up history) — DET-owned rows the wallet drain never +/// touched. Legacy scheduled votes are not read here: they are never +/// imported, and the startup notice reports the ones that will not run. /// 2. **Wallet drain** (single keys, HD seeds, wallet metadata, upstream /// registration) — the pass that restores access to funds. /// 3. **Identities** (identity rows and the keys they hold) — last, because it @@ -600,7 +581,7 @@ fn write_dapi_refresh_completion( /// **Neither DET-owned pass gates the other.** The wallet drain runs regardless /// of the app-data outcome, and the identity import runs regardless of it too — /// both results are held, never propagated on the spot, and judged together at -/// the end. A legacy vote row that cannot be imported must never stand between +/// the end. A legacy top-up row that cannot be imported must never stand between /// the user and their seeds, nor between the user and their identity keys: an /// app-data failure is deterministic, so letting it short-circuit the identity /// import would strand those keys outside the vault on every launch, not just @@ -613,16 +594,15 @@ fn write_dapi_refresh_completion( /// /// Both DET-owned passes write their sentinel unconditionally, so their counters /// exist for exactly one launch. What outlives them are the durable -/// [`UnreadableVotesWarning`], [`UnreadableTopUpsWarning`] and -/// [`UnreadableIdentitiesWarning`] records, and +/// [`UnreadableTopUpsWarning`] and [`UnreadableIdentitiesWarning`] records, and /// those — never the counters — are what this function publishes: each is /// re-raised on every launch, not only the one that discovered it, until /// [`acknowledge_unreadable_app_data`] / [`acknowledge_unreadable_identities`] /// retires it. When both are pending they ride one /// [`MigrationState::SucceededWithUnreadableData`], so a lone -/// identity warning can never outrank the vote warning and silently cost the -/// user a live vote deadline. If reading the vote-warning record fails, the vote -/// half is withheld until a later launch reads it successfully — the identity +/// identity warning can never hide the top-up warning. If reading the +/// top-up-warning record fails, the top-up half is withheld until a later launch +/// reads it successfully — the identity /// half still reaches the user, and neither is reported as a failed migration — /// a *hard* app-data failure (not merely a failed later read of this record) is /// the only thing that publishes [`MigrationState::FailedWithUnreadableIdentities`] @@ -748,11 +728,11 @@ where let status = app_context.migration_status(); - // Scheduled votes and top-up history carry their own sentinel and run - // ahead of the wallet-drain gate below: an install that already completed - // the wallet drain under an earlier build (which had no app-data import) - // still has those rows in `data.db`, and the wallet sentinel would - // otherwise short-circuit the launch and strand them. + // Top-up history carries its own sentinel and runs ahead of the + // wallet-drain gate below: an install that already completed the wallet + // drain under an earlier build (which had no app-data import) still has + // those rows in `data.db`, and the wallet sentinel would otherwise + // short-circuit the launch and strand them. status.set_state(MigrationState::Running { step: MigrationStep::AppData, }); @@ -760,8 +740,8 @@ where // The app-data result is deliberately held, not propagated: the wallet drain // is what restores access to funds, so nothing about DET's own rows may gate - // it. Propagating here would let one bad vote row wedge the drain on every - // launch, with no user-reachable way out. + // it. Propagating here would let a damaged top-up table wedge the drain on + // every launch, with no user-reachable way out. let wallet_moved = match drain_wallets(app_context, wallet_password).await { Ok(moved) => moved, Err(drain_error) => { @@ -783,11 +763,11 @@ where // The identity pass needs the drain's output (backend wired, vault reachable, // the wallet context's HD registry hydrated) so a wallet-derived key lands against a wallet that // exists. It must NOT wait on the app-data result: a hard app-data failure — - // one malformed vote-index blob is enough — is deterministic, so unwrapping - // it first would skip the identity import on this launch *and every retry* - // (the app-data sentinel is never written, so the failure recurs forever). - // That would strand a masternode owner's private keys outside the vault - // permanently, over a corrupt vote queue. + // a structurally damaged top-up table is enough — is deterministic, so + // unwrapping it first would skip the identity import on this launch *and + // every retry* (the app-data sentinel is never written, so the failure + // recurs forever). That would strand a masternode owner's private keys + // outside the vault permanently, over a damaged top-up history. status.set_state(MigrationState::Running { step: MigrationStep::Identities, }); @@ -800,7 +780,7 @@ where // Both DET-owned passes have now run. A hard failure in either still reaches // the user's "Retry now" banner, but only after neither could block the // other. The identity failure takes precedence when both fail: keys outrank - // votes. + // top-up history. let identities = match identities { Ok(outcome) => outcome, Err(identity_error) => { @@ -842,10 +822,10 @@ where }; // Unreadable identities outrank a *readable* app-data pass: an identity that - // did not come across took its keys with it, so the user cannot sign — let - // alone vote — until it is loaded again. But a *hard* app-data failure on the + // did not come across took its keys with it, so the user cannot sign until + // it is loaded again. But a *hard* app-data failure on the // same launch is not something the identity warning may swallow: it would - // leave the user no retry for their scheduled votes, silently and every + // leave the user no retry for their top-up history, silently and every // launch (the app-data sentinel is never written, so it recurs). So when both // break together, a single combined banner names each — the app-data half // retryable — instead of one eating the other. @@ -861,37 +841,35 @@ where Ok(outcome) => { let moved_data = wallet_moved || outcome.moved_data() || identities.moved_data(); - // A pending vote warning must ride along, or the identity signal + // A pending top-up warning must ride along, or the identity signal // buries it forever: the identity warning is re-published on every // launch until acknowledged, so this branch would otherwise return - // ahead of the `read_vote_warning` re-publish below. Both counts + // ahead of the top-up warning re-publish below. Both counts // come from storage, not from this launch's counters: after the // discovery run both passes short-circuit on their sentinels and // honestly report zero — exactly on the launches where this branch // is the only one the user ever sees. // - // A k/v read that itself fails costs only the vote half of the + // A k/v read that itself fails costs only the top-up half of the // banner, never the identity half: the record is durable and this // branch re-runs on every launch (the identity sentinel stays // unwritten), so the next successful read re-publishes it. Reporting // the read error as a *failure* state instead would tell the user the // app-data pass did not finish — it did, and wrote its sentinel — and // offer a retry that re-runs nothing. - match read_unreadable_app_data(&app_context.app_kv(), app_context.network) { - Ok(warning) if !warning.is_empty() => { + match pending_unreadable_top_ups(&app_context.app_kv(), app_context.network) { + Ok(top_ups_unreadable) if top_ups_unreadable > 0 => { tracing::warn!( target = "migration::finish_unwire", unreadable, imported = identities.imported, - votes_unreadable = warning.votes, - top_ups_unreadable = warning.top_ups, + top_ups_unreadable, network = ?app_context.network, - "Some legacy identities and some legacy scheduled votes could not be decoded; they stay in the previous version's data.db and must be loaded / scheduled again", + "Some legacy identities and some legacy top-up rows could not be decoded; they stay in the previous version's data.db, the identities must be loaded again and the top-up history reviewed", ); status.set_state(MigrationState::SucceededWithUnreadableData { identities: unreadable, - votes: warning.votes, - top_ups: warning.top_ups, + top_ups: top_ups_unreadable, }); } Ok(_) => { @@ -904,7 +882,6 @@ where ); status.set_state(MigrationState::SucceededWithUnreadableData { identities: unreadable, - votes: 0, top_ups: 0, }); } @@ -915,11 +892,10 @@ where imported = identities.imported, error = ?warning_error, network = ?app_context.network, - "Some legacy identities could not be decoded, and the pending vote-warning record could not be read so any vote notice is withheld until the next launch; the identity rows stay in the previous version's data.db and must be loaded again", + "Some legacy identities could not be decoded, and the pending top-up-warning record could not be read so any top-up notice is withheld until the next launch; the identity rows stay in the previous version's data.db and must be loaded again", ); status.set_state(MigrationState::SucceededWithUnreadableData { identities: unreadable, - votes: 0, top_ups: 0, }); } @@ -952,22 +928,20 @@ where // The warnings are read back from storage rather than taken from this pass's // counters: on every launch after the discovery run the import short-circuits - // on its sentinel and reports zero, yet unreadable votes still need - // re-scheduling and unreadable top-up history still needs review. Re-published - // until the user acknowledges it. - let warning = read_unreadable_app_data(&app_context.app_kv(), app_context.network)?; - if !warning.is_empty() { + // on its sentinel and reports zero, yet unreadable top-up history still + // needs review. Re-published until the user acknowledges it. + let top_ups_unreadable = + pending_unreadable_top_ups(&app_context.app_kv(), app_context.network)?; + if top_ups_unreadable > 0 { tracing::warn!( target = "migration::finish_unwire", - votes_unreadable = warning.votes, - top_ups_unreadable = warning.top_ups, + top_ups_unreadable, network = ?app_context.network, - "Some legacy scheduled votes or top-up rows could not be decoded; they stay in the previous version's data.db and require user review", + "Some legacy top-up rows could not be decoded; they stay in the previous version's data.db and require user review", ); status.set_state(MigrationState::SucceededWithUnreadableData { identities: 0, - votes: warning.votes, - top_ups: warning.top_ups, + top_ups: top_ups_unreadable, }); return Ok(moved_data); } @@ -1273,77 +1247,15 @@ fn unlock_with_supplied_password( Ok(()) } -/// Per-network sentinel for the DET app-data import (scheduled votes and -/// top-up history). Separate from the wallet-drain sentinel on purpose: an -/// install that already completed the wallet drain under an earlier build -/// still has its votes sitting in `data.db`, and a shared sentinel would -/// declare that install "done" and drop them. +/// Per-network completion marker for top-up import and unreadable-data checks. pub fn app_data_sentinel_key_for(network: Network) -> String { format!("det:migration:app_data:{}:v1", network_prefix(network)) } -/// Per-network key of the un-acknowledged unreadable-vote warning. Distinct -/// from the app-data sentinel: the sentinel records that the import *ran*, this -/// record that the user has not yet been *told* what it could not carry across. -fn vote_warning_key_for(network: Network) -> String { - format!( - "det:migration:unreadable_votes:{}:v1", - network_prefix(network) - ) -} - -/// Durable "some scheduled votes could not be read" warning. -/// -/// The import runs once (the app-data sentinel short-circuits every later -/// launch), so the pass counters exist for exactly one launch. A user who was -/// away, or who dismissed the banner without reading it, would never hear about -/// it again — while the vote it names may still have a live deadline. This -/// record outlives the pass: [`run`] re-publishes it on every launch until -/// [`acknowledge_unreadable_app_data`] clears it. -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct UnreadableVotesWarning { - /// Legacy vote rows the import could not decode. Never `0` — a zero-count - /// warning is not written at all. - pub count: u32, -} - -/// The pending unreadable-vote warning for `network`, if the user has not -/// acknowledged it yet. -fn read_vote_warning( - app_kv: &crate::wallet_backend::DetKv, - network: Network, -) -> Result, MigrationError> { - app_kv - .get::(DetScope::Global, &vote_warning_key_for(network)) - .map_err(|source| MigrationError::VoteWarningRecord { source }) -} - -/// Record `count` unreadable vote rows as a pending warning. A zero count -/// writes nothing — there is nothing to tell the user. -/// -/// Written BEFORE the app-data sentinel: a crash between the two re-runs the -/// idempotent import, whereas the reverse order would lose the warning for good. -fn write_vote_warning( - app_kv: &crate::wallet_backend::DetKv, - network: Network, - count: u32, -) -> Result<(), MigrationError> { - if count == 0 { - return Ok(()); - } - app_kv - .put( - DetScope::Global, - &vote_warning_key_for(network), - &UnreadableVotesWarning { count }, - ) - .map_err(|source| MigrationError::VoteWarningRecord { source }) -} - -/// Retire the unreadable-vote warning for the active network: the user has read -/// it. Clears the durable record so later launches stay quiet, and drops the -/// banner. The legacy rows in `data.db` are untouched — only the notice is -/// retired, so a build with a better decoder can still recover the votes. +/// Retire the unreadable top-up warning for the active network: the user has +/// read it. Clears the durable record so later launches stay quiet, and drops +/// the banner. The legacy rows in `data.db` are untouched — only the notice is +/// retired, so a build with a better decoder can still recover the history. pub fn acknowledge_unreadable_app_data(app_context: &Arc) -> Result<(), TaskError> { let network = app_context.network; clear_unreadable_app_data(&app_context.app_kv(), network)?; @@ -1362,13 +1274,9 @@ fn clear_unreadable_app_data( app_kv: &crate::wallet_backend::DetKv, network: Network, ) -> Result<(), MigrationError> { - app_kv - .delete(DetScope::Global, &vote_warning_key_for(network)) - .map_err(|source| MigrationError::VoteWarningRecord { source })?; app_kv .delete(DetScope::Global, &top_up_warning_key_for(network)) - .map_err(|source| MigrationError::TopUpWarningRecord { source })?; - Ok(()) + .map_err(|source| MigrationError::TopUpWarningRecord { source }) } fn top_up_warning_key_for(network: Network) -> String { @@ -1410,26 +1318,13 @@ fn write_top_up_warning( .map_err(|source| MigrationError::TopUpWarningRecord { source }) } -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -struct UnreadableAppData { - votes: u32, - top_ups: u32, -} - -impl UnreadableAppData { - fn is_empty(self) -> bool { - self.votes == 0 && self.top_ups == 0 - } -} - -fn read_unreadable_app_data( +/// Unreadable legacy top-up rows the user has not acknowledged yet; `0` when +/// no warning is pending. +fn pending_unreadable_top_ups( app_kv: &crate::wallet_backend::DetKv, network: Network, -) -> Result { - Ok(UnreadableAppData { - votes: read_vote_warning(app_kv, network)?.map_or(0, |warning| warning.count), - top_ups: read_top_up_warning(app_kv, network)?.map_or(0, |warning| warning.count), - }) +) -> Result { + Ok(read_top_up_warning(app_kv, network)?.map_or(0, |warning| warning.count)) } /// Per-network key of the un-acknowledged unreadable-identity warning. Distinct @@ -1515,23 +1410,7 @@ pub fn acknowledge_unreadable_identities(app_context: &Arc) -> Resul Ok(()) } -/// Import the DET-owned rows the wallet drain never touched: scheduled DPNS -/// votes (deadline-critical) and top-up history (audit trail). -/// -/// Returns the pass counters, including `votes_unreadable` — rows that could -/// not be decoded. Those are *not* an error: a corrupt row decodes no better on -/// a retry, so failing here would only wedge the launch. [`run`] reports the -/// count to the user instead, and the legacy rows are never deleted. -/// -/// Idempotent — votes already in the k/v store are left alone, so a retry can -/// never overwrite a vote the user has since cast with its stale legacy -/// `executed` flag. -/// -/// # Errors -/// -/// [`TaskError::MigrationFailed`] when the legacy file cannot be opened or read, -/// or the decoded votes cannot be written to the k/v store. The app-data -/// sentinel stays unwritten in those cases, so the next launch retries. +/// Import top-up history and report unreadable records from the previous version. fn migrate_app_data(app_context: &Arc) -> Result { let app_kv = app_context.app_kv(); let network = app_context.network; @@ -1558,7 +1437,7 @@ fn migrate_app_data(app_context: &Arc) -> Result) -> Result = app_context - .get_scheduled_votes() - .map_err(|source| MigrationError::AppDataImport { - source: Box::new(source), - })? - .into_iter() - .map(|v| (v.voter_id.to_buffer(), v.contested_name)) - .collect(); - - let outcome = migrate_app_data_from_conn( - &conn, - network, - &existing_votes, - |votes| app_context.insert_scheduled_votes(votes), - |id, top_ups| app_context.save_top_ups(id, top_ups), - )?; + let outcome = migrate_app_data_from_conn(&conn, network, |id, top_ups| { + app_context.save_top_ups(id, top_ups) + })?; tracing::info!( target = "migration::finish_unwire", - votes_imported = outcome.votes_imported, - votes_skipped_existing = outcome.votes_skipped_existing, - votes_unreadable = outcome.votes_unreadable, top_up_identities_imported = outcome.top_up_identities_imported, top_ups_unreadable = outcome.top_ups_unreadable, network = ?network, @@ -1609,13 +1466,9 @@ fn migrate_app_data(app_context: &Arc) -> Result( +/// Imports top-up history only. The legacy `scheduled_votes` table is never +/// read, so damage in it cannot fail this pass. +fn migrate_app_data_from_conn( conn: &Connection, network: dash_sdk::dpp::dashcore::Network, - existing_votes: &std::collections::BTreeSet<([u8; 32], String)>, - insert_votes: I, mut save_top_ups: T, ) -> Result where - I: FnOnce(&[crate::backend_task::contested_names::ScheduledDPNSVote]) -> Result<(), TaskError>, T: FnMut( &dash_sdk::platform::Identifier, &std::collections::BTreeMap, @@ -1665,40 +1514,6 @@ where { let mut outcome = AppDataMigrationOutcome::default(); - let legacy_votes = crate::database::legacy_import::read_scheduled_votes(conn, network) - .map_err(|source| MigrationError::LegacyDbRead { - table: "scheduled_votes", - source, - })?; - outcome.votes_unreadable = legacy_votes.unreadable; - - let to_import: Vec<_> = legacy_votes - .votes - .into_iter() - .filter(|v| { - let known = - existing_votes.contains(&(v.voter_id.to_buffer(), v.contested_name.clone())); - if known { - outcome.votes_skipped_existing = outcome.votes_skipped_existing.saturating_add(1); - } - !known - }) - .collect(); - - if !to_import.is_empty() { - insert_votes(&to_import).map_err(|source| MigrationError::ScheduledVotesWrite { - source: Box::new(source), - })?; - outcome.votes_imported = u32::try_from(to_import.len()).unwrap_or(u32::MAX); - } - - // Top-ups are audit trail, not funds, so a failure never blocks the votes that - // already landed — every identity is attempted before the pass gives up. But it - // is not swallowed either: the caller withholds the app-data sentinel on `Err`, - // so the next launch retries the idempotent import. Swallowing would freeze a - // one-off k/v error into permanent loss, because the sentinel short-circuits - // every later launch. Undecodable *rows* never reach here — the reader skips - // and logs them — so an error here is structural and a retry is worth taking. let failure = match crate::database::legacy_import::read_top_ups(conn, network) { Ok(top_ups) => { outcome.top_ups_unreadable = top_ups.unreadable; @@ -2109,17 +1924,6 @@ fn table_has_rows(conn: &Connection, table: &'static str) -> Result bool { - self.votes_imported > 0 || self.top_up_identities_imported > 0 + self.top_up_identities_imported > 0 } } @@ -3467,15 +3271,13 @@ mod tests { ); } - // ── App-data import: scheduled votes + top-up history ──────────── + // ── App-data import: top-up history ──────────── mod app_data { use super::*; use dash_sdk::dpp::dashcore::Network; - use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; - use dash_sdk::platform::Identifier; use std::cell::RefCell; - use std::collections::{BTreeMap, BTreeSet}; + use std::collections::BTreeMap; const VOTER: [u8; 32] = [0x11u8; 32]; @@ -3522,129 +3324,62 @@ mod tests { conn } - /// The core promise: a queued vote survives the upgrade. Losing it - /// means a masternode voter silently misses a vote window. #[test] - fn imports_scheduled_votes_and_top_ups() { + fn imports_top_ups_without_importing_scheduled_votes() { let conn = legacy_conn(); - let votes = RefCell::new(Vec::new()); let top_ups = RefCell::new(Vec::new()); - let outcome = migrate_app_data_from_conn( - &conn, - Network::Testnet, - &BTreeSet::new(), - |v| { - votes.borrow_mut().extend_from_slice(v); - Ok(()) - }, - |id, map| { - top_ups.borrow_mut().push((*id, map.clone())); - Ok(()) - }, - ) + let outcome = migrate_app_data_from_conn(&conn, Network::Testnet, |id, map| { + top_ups.borrow_mut().push((*id, map.clone())); + Ok(()) + }) .expect("import"); - assert_eq!(outcome.votes_imported, 1); - assert_eq!(outcome.votes_unreadable, 0); assert_eq!(outcome.top_up_identities_imported, 1); assert_eq!(outcome.top_ups_unreadable, 0); - let votes = votes.borrow(); - assert_eq!(votes.len(), 1); - assert_eq!(votes[0].contested_name, "alice"); - assert_eq!(votes[0].choice, ResourceVoteChoice::Lock); - assert_eq!(votes[0].voter_id, Identifier::from(VOTER)); - assert!(!votes[0].executed_successfully); - let top_ups = top_ups.borrow(); assert_eq!(top_ups.len(), 1); assert_eq!(top_ups[0].1, BTreeMap::from([(0, 5000)])); } - /// A retry must not overwrite a vote the user already cast in the new - /// build — the legacy row still says `executed = 0`, so re-importing - /// it would queue the vote a second time. - #[test] - fn skips_votes_already_present_in_the_kv_store() { - let conn = legacy_conn(); - let existing = BTreeSet::from([(VOTER, "alice".to_string())]); - let votes = RefCell::new(Vec::new()); - - let outcome = migrate_app_data_from_conn( - &conn, - Network::Testnet, - &existing, - |v| { - votes.borrow_mut().extend_from_slice(v); - Ok(()) - }, - |_, _| Ok(()), - ) - .expect("import"); - - assert_eq!(outcome.votes_imported, 0); - assert_eq!(outcome.votes_skipped_existing, 1); - assert!( - votes.borrow().is_empty(), - "an already-migrated vote must not be re-queued", - ); - } - - /// An undecodable vote row is counted and reported — never dropped in - /// silence, and never fatal. Fatal would be worse than useless: the row - /// decodes no better on a retry, so it would wedge every launch, and the - /// wallet drain behind it (QA-101). The readable votes around it still - /// import. + /// Scheduled votes are never imported, so a structurally damaged + /// `scheduled_votes` table (here: no `vote_choice` column) must not + /// stand between the user and their top-up history. #[test] - fn unreadable_vote_row_is_counted_without_failing_the_import() { + fn damaged_scheduled_votes_table_does_not_block_top_up_import() { let conn = legacy_conn(); - conn.execute( - "INSERT INTO scheduled_votes - (identity_id, contested_name, vote_choice, time, executed, network) - VALUES (?1, 'corrupt', 'Nonsense', 1, 0, 'testnet')", - rusqlite::params![VOTER.as_slice()], + conn.execute_batch( + "DROP TABLE scheduled_votes; + CREATE TABLE scheduled_votes ( + identity_id BLOB NOT NULL, + network TEXT NOT NULL + );", ) - .expect("corrupt vote"); + .expect("damaged schema"); + let saved = RefCell::new(Vec::new()); - let votes = RefCell::new(Vec::new()); - let outcome = migrate_app_data_from_conn( - &conn, - Network::Testnet, - &BTreeSet::new(), - |v| { - votes.borrow_mut().extend_from_slice(v); - Ok(()) - }, - |_, _| Ok(()), - ) - .expect("an unreadable vote must not fail the import"); + let outcome = migrate_app_data_from_conn(&conn, Network::Testnet, |_, history| { + saved.borrow_mut().push(history.clone()); + Ok(()) + }) + .expect("a damaged vote table must not fail the top-up import"); - assert_eq!(outcome.votes_imported, 1, "the readable vote still lands"); - assert_eq!( - outcome.votes_unreadable, 1, - "the corrupt row must be reported, not swallowed", - ); - assert_eq!(votes.borrow().len(), 1); - assert_eq!(votes.borrow()[0].contested_name, "alice"); + assert_eq!(outcome.top_up_identities_imported, 1); + assert_eq!(saved.borrow()[0], BTreeMap::from([(0, 5_000)])); } /// A top-up write failure must fail the pass. It is audit trail, so it /// never blocks the wallet drain — but swallowing it would let the /// app-data sentinel record "done" over a history that never landed, - /// making a transient k/v error permanent. The votes that already - /// imported stay imported; the retry is idempotent. + /// making a transient k/v error permanent. The retry is idempotent. #[test] fn top_up_write_failure_fails_the_pass() { let conn = legacy_conn(); - let result = migrate_app_data_from_conn( - &conn, - Network::Testnet, - &BTreeSet::new(), - |_| Ok(()), - |_, _| Err(TaskError::WalletNotFound), - ); + let result = migrate_app_data_from_conn(&conn, Network::Testnet, |_, _| { + Err(TaskError::WalletNotFound) + }); assert!( matches!(result, Err(MigrationError::TopUpHistoryWrite { .. })), @@ -3662,16 +3397,10 @@ mod tests { .expect("corrupt top up"); let saved = RefCell::new(Vec::new()); - let outcome = migrate_app_data_from_conn( - &conn, - Network::Testnet, - &BTreeSet::new(), - |_| Ok(()), - |_, history| { - saved.borrow_mut().push(history.clone()); - Ok(()) - }, - ) + let outcome = migrate_app_data_from_conn(&conn, Network::Testnet, |_, history| { + saved.borrow_mut().push(history.clone()); + Ok(()) + }) .expect("row-level damage is non-fatal"); assert_eq!(outcome.top_ups_unreadable, 1); @@ -3693,13 +3422,7 @@ mod tests { ) .expect("schema"); - let result = migrate_app_data_from_conn( - &conn, - Network::Testnet, - &BTreeSet::new(), - |_| Ok(()), - |_, _| Ok(()), - ); + let result = migrate_app_data_from_conn(&conn, Network::Testnet, |_, _| Ok(())); assert!( matches!( @@ -3718,21 +3441,15 @@ mod tests { fn missing_tables_are_a_no_op() { let conn = Connection::open_in_memory().expect("open"); - let outcome = migrate_app_data_from_conn( - &conn, - Network::Testnet, - &BTreeSet::new(), - |_| Ok(()), - |_, _| Ok(()), - ) - .expect("import"); + let outcome = + migrate_app_data_from_conn(&conn, Network::Testnet, |_, _| Ok(())).expect("import"); assert_eq!(outcome, AppDataMigrationOutcome::default()); } /// The app-data sentinel is per network and distinct from the /// wallet-drain sentinel: an install that already drained its wallets - /// under an earlier build must still import its votes. + /// under an earlier build must still import its top-up history. #[test] fn sentinel_is_per_network_and_distinct_from_the_wallet_sentinel() { let testnet = app_data_sentinel_key_for(Network::Testnet); @@ -6673,15 +6390,14 @@ mod tests { .expect("corrupt identity row"); } - /// QA-101 — the headline funds regression. A single undecodable legacy vote - /// row must NOT stand between the user and their wallet: the drain runs to - /// completion (seeds copied, wallet hydrated AND upstream-registered, the - /// completion sentinel written), while the corrupt row is still surfaced — - /// counted on the terminal state and left in `data.db` — rather than - /// silently dropped. Before the fix the vote import ran first, unconditionally - /// and fatally, so this wallet stayed unreachable on every launch forever. + /// The headline funds regression. A single undecodable legacy vote row must + /// NOT stand between the user and their wallet: the drain runs to completion + /// (seeds copied, wallet hydrated AND upstream-registered, the completion + /// sentinel written). The migration reports nothing about the row itself — + /// it stays in `data.db`, where the startup notice for old schedules finds + /// it — so the launch ends as a plain success. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn run_completes_the_wallet_drain_despite_an_unreadable_vote_row() { + async fn run_completes_the_wallet_drain_and_leaves_legacy_votes_to_the_startup_notice() { use dash_sdk::dpp::dashcore::Network; let tmp = tempfile::tempdir().expect("tempdir"); @@ -6726,23 +6442,17 @@ mod tests { "the completion sentinel must be written once the drain succeeds", ); - // No silent loss: the readable vote came across, and the unreadable one is - // reported on the terminal state (the banner the user sees), not swallowed. - let votes = ctx.get_scheduled_votes().expect("read scheduled votes"); - assert_eq!(votes.len(), 1, "the readable vote must still be imported"); - assert_eq!(votes[0].contested_name, "alice"); + // Votes remain in the old database, un-queued, for the startup notice to + // report; the migration itself raises no vote warning of its own. + assert!(ctx.dpns_vote_operations().unwrap().is_empty()); + assert!(ctx.has_legacy_scheduled_votes().unwrap()); assert_eq!( *ctx.migration_status().state(), - MigrationState::SucceededWithUnreadableData { - identities: 0, - votes: 1, - top_ups: 0, - }, - "the corrupt vote row must be surfaced to the user, not dropped in silence", + MigrationState::Success, + "old schedules are reported by the startup notice, not by the storage update", ); - // The legacy rows survive, so a build with a better decoder can still get - // the vote back. + // The legacy rows survive, so the startup notice keeps finding them. let conn = Connection::open(tmp.path().join("data.db")).expect("open data.db"); let remaining: i64 = conn .query_row("SELECT COUNT(*) FROM scheduled_votes", [], |r| r.get(0)) @@ -6778,20 +6488,16 @@ mod tests { ); wait_for_dapi_refresh(&ctx).await; assert!(backend.is_wallet_registered(&seed_hash)); - assert_eq!(ctx.get_scheduled_votes().expect("read votes").len(), 1); + assert!(ctx.has_legacy_scheduled_votes().unwrap()); let sentinel_after_first = read_sentinel(&ctx.app_kv(), network) .expect("read sentinel") .expect("sentinel written by the first run"); - // The user casts the vote, so the app drops it from the queue. The legacy - // row still says `executed = 0` — a re-import would queue it a second time. - ctx.clear_all_scheduled_votes().expect("clear vote queue"); - let did_work = run(&ctx).await.expect("second run"); assert!(!did_work, "the second launch must move nothing"); assert!( - ctx.get_scheduled_votes().expect("read votes").is_empty(), + ctx.dpns_vote_operations().unwrap().is_empty(), "a re-run must not resurrect a vote the user has already dealt with", ); assert_eq!( @@ -6977,7 +6683,7 @@ mod tests { backend.shutdown().await; } - /// A failed *vote-warning read* is not an app-data failure, and the banner may + /// A failed *top-up-warning read* is not an app-data failure, and the banner may /// not say it is. Here the app-data pass SUCCEEDS (its sentinel is written) and /// only the follow-up warning-record read fails, alongside an undecodable /// identity row. `FailedWithUnreadableIdentities` tells the user "updating the @@ -6987,7 +6693,7 @@ mod tests { /// honest `SucceededWithUnreadableIdentities` and the unreadable notice record /// is left for the next launch to re-read. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn an_unreadable_vote_warning_record_does_not_claim_the_app_data_pass_failed() { + async fn an_unreadable_top_up_warning_record_does_not_claim_the_app_data_pass_failed() { use dash_sdk::dpp::dashcore::Network; let tmp = tempfile::tempdir().expect("tempdir"); @@ -7006,14 +6712,14 @@ mod tests { } // Poison the warning record: a unit value encodes to an empty bincode body, - // so decoding it back as an `UnreadableVotesWarning` hits an unexpected end - // of input. The app-data pass decodes zero unreadable votes and therefore + // so decoding it back as an `UnreadableTopUpsWarning` hits an unexpected end + // of input. The app-data pass decodes zero unreadable top-ups and therefore // never overwrites it. ctx.app_kv() - .put(DetScope::Global, &vote_warning_key_for(network), &()) - .expect("poison the vote-warning record"); + .put(DetScope::Global, &top_up_warning_key_for(network), &()) + .expect("poison the top-up-warning record"); assert!( - read_vote_warning(&ctx.app_kv(), network).is_err(), + read_top_up_warning(&ctx.app_kv(), network).is_err(), "precondition: the poisoned record must make the warning read fail, \ otherwise this test would pass for the wrong reason", ); @@ -7028,7 +6734,6 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 0, top_ups: 0, }, "an unreadable notice record must not be reported as an app-data failure", @@ -7047,13 +6752,13 @@ mod tests { backend.shutdown().await; } - /// Fix-8 — the unreadable-vote warning is durable. The discovery run records - /// it; every later launch re-publishes it from that record even though both - /// sentinels short-circuit the passes, so a user who was away when the - /// migration finished still learns that a vote with a live deadline needs - /// re-scheduling. Only an explicit acknowledgement retires it. + /// The unreadable top-up warning is durable. Every launch re-publishes it + /// from its record even though both sentinels short-circuit the passes, so a + /// user who was away when the migration finished still learns that part of + /// the top-up history needs review. Only an explicit acknowledgement retires + /// it. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn unreadable_vote_warning_is_republished_until_acknowledged() { + async fn unreadable_top_up_warning_is_republished_until_acknowledged() { use dash_sdk::dpp::dashcore::Network; let tmp = tempfile::tempdir().expect("tempdir"); @@ -7061,7 +6766,8 @@ mod tests { let network = Network::Testnet; seed_legacy_wallet(&ctx, &[0xC5u8; 64], "funds", network); - seed_legacy_votes(&ctx, &[0x33u8; 32], &[("corrupt", "Nonsense")], network); + // The record a discovery pass leaves behind for one undecodable row. + write_top_up_warning(&ctx.app_kv(), network, 1).expect("pending top-up warning"); wire_backend(&ctx).await; let backend = ctx.wallet_backend().expect("backend wired"); @@ -7071,10 +6777,9 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 0, - votes: 1, - top_ups: 0, + top_ups: 1, }, - "the discovery run surfaces the warning", + "a pending warning is surfaced", ); // A later launch starts from a fresh in-memory status, and both sentinels @@ -7085,8 +6790,7 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 0, - votes: 1, - top_ups: 0, + top_ups: 1, }, "a warning the user may have missed must survive a restart", ); @@ -7107,16 +6811,15 @@ mod tests { backend.shutdown().await; } - /// An unreadable identity must not permanently hide an unreadable *vote*. - /// Both damaged on the same launch is the trap: the identity branch returns - /// early, ahead of the durable vote-warning read, so a lone identity signal - /// would bury the vote half — and the user would silently miss a vote whose - /// deadline is still live. Both counts ride one terminal state instead, both - /// halves survive a restart (each re-read from its own durable record, since - /// both sentinels short-circuit their passes by then), and acknowledging the - /// vote half retires only that half. + /// An unreadable identity must not permanently hide unreadable *top-up + /// history*. Both pending on the same launch is the trap: the identity branch + /// returns early, ahead of the durable top-up-warning read, so a lone + /// identity signal would bury the top-up half. Both counts ride one terminal + /// state instead, both halves survive a restart (each re-read from its own + /// durable record, since both sentinels short-circuit their passes by then), + /// and acknowledging the top-up half retires only that half. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn unreadable_identities_do_not_hide_the_unreadable_vote_warning() { + async fn unreadable_identities_do_not_hide_the_unreadable_top_up_warning() { use dash_sdk::dpp::dashcore::Network; let tmp = tempfile::tempdir().expect("tempdir"); @@ -7124,14 +6827,8 @@ mod tests { let network = Network::Testnet; seed_legacy_wallet(&ctx, &[0xE7u8; 64], "funds", network); - // One vote decodes, one does not → the app-data pass succeeds AND records - // a durable unreadable-vote warning. - seed_legacy_votes( - &ctx, - &[0x55u8; 32], - &[("alice", "Lock"), ("corrupt", "Nonsense")], - network, - ); + // The record a discovery pass leaves behind for one undecodable top-up row. + write_top_up_warning(&ctx.app_kv(), network, 1).expect("pending top-up warning"); { // A corrupt identity blob → the identity pass counts it unreadable and // records a durable warning, so the identity branch recurs on every launch. @@ -7147,17 +6844,12 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 1, - top_ups: 0, + top_ups: 1, }, - "the discovery run must name BOTH remedies — the identity warning may \ - not swallow a vote with a live deadline", + "the run must name BOTH remedies — the identity warning may not swallow \ + the top-up one", ); - // The readable vote still came across; only the corrupt one did not. - let votes = ctx.get_scheduled_votes().expect("read scheduled votes"); - assert_eq!(votes.len(), 1, "the readable vote must still be imported"); - // Both sentinels are now written, which is what makes the next launch a // real test of the durable reads: both passes short-circuit and report // zero unreadable rows, so *neither* half of the banner can come from a @@ -7186,13 +6878,12 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 1, - top_ups: 0, + top_ups: 1, }, - "the vote warning must survive a restart even while identities stay unreadable", + "the top-up warning must survive a restart even while identities stay unreadable", ); - // Acknowledging retires the vote half only: the identities are still + // Acknowledging retires the top-up half only: the identities are still // unreadable, so their warning must keep coming back on its own. acknowledge_unreadable_app_data(&ctx).expect("acknowledge"); ctx.migration_status().set_state(MigrationState::Idle); @@ -7201,10 +6892,9 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 0, top_ups: 0, }, - "an acknowledged vote warning must not come back, but the identity one must", + "an acknowledged top-up warning must not come back, but the identity one must", ); backend.shutdown().await; @@ -7261,7 +6951,6 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 0, top_ups: 0, }, "precondition: the corrupt row is reported to the user", @@ -7295,7 +6984,6 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 0, top_ups: 0, }, "the unreadable row is still reported once the import itself is complete", @@ -7332,7 +7020,6 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 0, top_ups: 0, }, "the discovery run surfaces the warning", @@ -7355,7 +7042,6 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 0, top_ups: 0, }, "a warning the user may have missed must survive a restart", diff --git a/src/backend_task/migration/mod.rs b/src/backend_task/migration/mod.rs index 2f54c5f8f..ed7f634c0 100644 --- a/src/backend_task/migration/mod.rs +++ b/src/backend_task/migration/mod.rs @@ -35,8 +35,8 @@ pub enum MigrationTask { /// completion sentinel exists in `det-app.sqlite`, subsequent calls /// return `Success` immediately without touching the legacy file. FinishUnwire, - /// Retire warnings for unreadable scheduled-vote and top-up rows on the - /// active network. The legacy rows themselves are never touched. + /// Retire the warning for unreadable top-up rows on the active network. + /// The legacy rows themselves are never touched. AcknowledgeUnreadableAppData, /// Retire the "some identities could not be read" warning for the active /// network. Same contract as [`Self::AcknowledgeUnreadableAppData`]: the diff --git a/src/backend_task/migration/v093_upgrade.rs b/src/backend_task/migration/v093_upgrade.rs index e984e561c..582fe4d5b 100644 --- a/src/backend_task/migration/v093_upgrade.rs +++ b/src/backend_task/migration/v093_upgrade.rs @@ -32,7 +32,6 @@ use dash_sdk::dpp::identity::{ }; use dash_sdk::dpp::key_wallet::bip32::DerivationPath; use dash_sdk::dpp::platform_value::BinaryData; -use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; use dash_sdk::platform::Identifier; use rusqlite::{Connection, params}; @@ -1007,15 +1006,8 @@ async fn assert_v093_install_upgrades(network: Network) { ); // ── Scheduled votes ────────────────────────────────────────────── - let votes = ctx.get_scheduled_votes().expect("read scheduled votes"); - assert_eq!(votes.len(), 1, "the queued vote must come across"); - assert_eq!(votes[0].contested_name, CONTESTED_NAME); - assert_eq!(votes[0].choice, ResourceVoteChoice::Lock); - assert_eq!(votes[0].voter_id, Identifier::from(IDENTITY_ID)); - assert!( - !votes[0].executed_successfully, - "an uncast vote must not arrive marked as cast — that would skip the vote window", - ); + assert!(ctx.has_legacy_scheduled_votes().unwrap()); + assert!(ctx.dpns_vote_operations().unwrap().is_empty()); // ── Top-up history ─────────────────────────────────────────────── assert_eq!( @@ -1309,8 +1301,6 @@ async fn second_launch_after_a_v093_upgrade_changes_nothing() { app_kv .put(DetScope::Global, AppSettings::KV_KEY, &chosen) .expect("user switches network"); - ctx.clear_all_scheduled_votes() - .expect("user casts the vote"); // …and renames the imported masternode identity. The identity sentinel is what // must protect the edit; the same guarantee under an undecodable row is covered @@ -1341,7 +1331,7 @@ async fn second_launch_after_a_v093_upgrade_changes_nothing() { "a re-import must not resurrect the legacy network over the user's choice", ); assert!( - ctx.get_scheduled_votes().expect("read votes").is_empty(), + ctx.dpns_vote_operations().unwrap().is_empty(), "a re-run must not requeue a vote the user has already cast", ); assert_eq!( @@ -1471,28 +1461,15 @@ async fn the_import_never_writes_a_plaintext_key_to_disk() { backend.shutdown().await; } -/// A corrupt vote queue must never cost the user their identity keys. -/// -/// The app-data pass (scheduled votes, top-up history) can fail hard — one -/// malformed `det:scheduled_vote_voters:v1` blob is enough. That failure is -/// deterministic: it recurs on every launch, and the app-data sentinel is never -/// written. So if the identity import waited on the app-data result, a masternode -/// owner's owner/voting keys would never reach the vault — not on this launch, -/// not on any retry — because of a broken vote queue they cannot even see. -/// -/// The two DET-owned passes are independent; neither may gate the other. +/// An unused vote index cannot block startup or the import of identity keys. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_corrupt_vote_index_never_strands_the_identity_keys() { +async fn an_unused_vote_index_does_not_block_startup_or_identity_import() { let tmp = tempfile::tempdir().expect("tempdir"); write_v093_database(tmp.path()); let (ctx, _) = boot(tmp.path()); let backend = wire_backend(&ctx).await; - // Poison the scheduled-vote roster with a blob that cannot decode into the - // voter list, so the app-data pass fails hard the way a corrupted entry would. - // (`det:scheduled_vote_voters:v1` is private to `context::identity_db`; a key - // rename surfaces here as an un-poisoned index, not a silent pass.) ctx.det_kv() .expect("per-network k/v") .put( @@ -1502,13 +1479,9 @@ async fn a_corrupt_vote_index_never_strands_the_identity_keys() { ) .expect("poison the vote index"); - // The failure still reaches the user — it is not swallowed… - assert!( - run_migration_with_wallet_passwords(&ctx).await.is_err(), - "a hard app-data failure must still surface, so the user gets a retry", - ); - - // …but it must not have taken the identities down with it. + run_migration_with_wallet_passwords(&ctx).await.unwrap(); + assert!(ctx.dpns_vote_operations().unwrap().is_empty()); + assert!(ctx.has_legacy_scheduled_votes().unwrap()); assert_eq!( ctx.load_local_qualified_identities() .expect("load identities") @@ -1526,8 +1499,7 @@ async fn a_corrupt_vote_index_never_strands_the_identity_keys() { .expect("the owner key must be in the vault") .as_slice(), secrets().owner_key.as_slice(), - "the masternode owner key must reach the vault even when the vote import fails — \ - otherwise a broken vote queue permanently costs the user control of their node", + "the masternode owner key must reach the vault", ); backend.shutdown().await; @@ -1583,7 +1555,6 @@ async fn a_second_launch_after_an_unreadable_identity_preserves_user_edits_and_d *ctx.migration_status().state(), crate::context::migration_status::MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 0, top_ups: 0, }, "the user must learn that an identity did not come across", diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index a5ec7731a..d1a355f0e 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -12,6 +12,9 @@ use crate::backend_task::wallet::WalletTask; use crate::context::AppContext; use crate::context::identity_load_registry::IdentityLoadToken; use crate::model::masternode_input::decode_identity_id; +use crate::model::dpns_voting::{ + DpnsScheduledVoteClearOutcome, DpnsScheduledVoteKey, DpnsVoteOperationId, DpnsVoteTargetKey, +}; use dash_sdk::dpp::address_funds::PlatformAddress; use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; @@ -31,7 +34,6 @@ use dash_sdk::dpp::group::group_action::GroupAction; use dash_sdk::dpp::prelude::DataContract; use dash_sdk::dpp::state_transition::StateTransition; use dash_sdk::dpp::tokens::token_pricing_schedule::TokenPricingSchedule; -use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; use dash_sdk::platform::proto::get_documents_request::get_documents_request_v0::Start; use dash_sdk::platform::{Document, DocumentQuery, Identifier}; use dash_sdk::query_types::{Documents, IndexMap}; @@ -334,12 +336,26 @@ pub enum BackendTaskContext { TokenRewardEstimate(IdentityTokenIdentifier), /// The destructive per-network database clear. ClearNetworkDatabase, + /// One durable DPNS vote operation. + DpnsVoteOperation { + network: Network, + operation_id: DpnsVoteOperationId, + }, /// The Settings "Restore from Previous Version" run. RestoreFromPreviousVersion, /// Saving the upgrade-backup retention policy. UpdateBackupRetention, /// A scheduled-vote sweep for one network. ScheduledVoteSweep { network: Network }, + /// The background contest + vote-state refresh; its failures are logged, + /// never bannered. + DpnsBackgroundRefresh { network: Network }, + /// A user-requested contest refresh. + DpnsContestRefresh, + /// A single schedule action, before its journal operation is resolved. + DpnsScheduledVote { key: DpnsScheduledVoteKey }, + /// An optimistic edit of one durable scheduled target. + DpnsScheduledVoteEdit { key: DpnsVoteTargetKey }, /// Receive-address derivation for one wallet's deposit flow. GenerateReceiveAddress { seed_hash: WalletSeedHash }, /// Live asset-lock builder ceiling query for one wallet. @@ -382,8 +398,9 @@ pub enum BackendTaskContext { } impl BackendTaskContext { - /// Bind payment and recovery outcomes to their dispatch network, so a late - /// result cannot affect a screen after the user switches networks. + /// Bind tasks whose payload omits a network to their originating network, + /// so late wallet, recovery and scheduled-vote results cannot affect + /// another context. pub(crate) fn for_task_on(task: &BackendTask, network: Network) -> Self { match task { BackendTask::IdentityTask( @@ -393,6 +410,21 @@ impl BackendTaskContext { network, operation: Box::new(Self::from(task)), }, + BackendTask::ContestedResourceTask(ContestedResourceTask::EditScheduledDpnsVote( + edit, + )) => Self::DpnsScheduledVoteEdit { + key: edit.key.clone(), + }, + BackendTask::ContestedResourceTask(ContestedResourceTask::CastScheduledVote( + vote, + _, + )) => Self::DpnsScheduledVote { + key: DpnsScheduledVoteKey { + network, + voter_id: vote.voter_id, + contested_name: vote.contested_name.clone(), + }, + }, BackendTask::CoreTask(CoreTask::SendWalletPayment { .. }) => { Self::WalletPaymentBroadcast { network } } @@ -423,6 +455,25 @@ impl BackendTaskContext { } } + pub(crate) fn is_dpns_vote_task(&self) -> bool { + matches!( + self.operation(), + Self::DpnsVoteOperation { .. } + | Self::DpnsContestRefresh + | Self::DpnsScheduledVote { .. } + | Self::DpnsScheduledVoteEdit { .. } + | Self::ScheduledVoteSweep { .. } + ) + } + + /// Unique UI correlation for one task on its originating network. + pub(crate) fn for_dispatch_on(task: &BackendTask, network: Network) -> Self { + Self::Dispatched { + dispatch_id: BACKEND_TASK_DISPATCH_ID.fetch_add(1, Ordering::Relaxed), + operation: Box::new(Self::for_task_on(task, network)), + } + } + fn operation(&self) -> &Self { match self { Self::Dispatched { operation, .. } @@ -431,6 +482,10 @@ impl BackendTaskContext { } } + pub(crate) fn is_dpns_contest_refresh(&self) -> bool { + matches!(self.operation(), Self::DpnsContestRefresh) + } + pub(crate) fn is_fetch_documents(&self) -> bool { matches!(self.operation(), Self::FetchDocuments(_)) } @@ -582,6 +637,23 @@ impl From<&BackendTask> for BackendTaskContext { identity_index: *identity_index, }, BackendTask::SystemTask(SystemTask::ClearNetworkDatabase) => Self::ClearNetworkDatabase, + BackendTask::ContestedResourceTask( + ContestedResourceTask::SubmitDpnsVoteOperation { + operation, network, .. + }, + ) => Self::DpnsVoteOperation { + network: *network, + operation_id: operation.id, + }, + BackendTask::ContestedResourceTask( + ContestedResourceTask::ReconcileDpnsVoteOperation(operation_id, network), + ) => Self::DpnsVoteOperation { + network: *network, + operation_id: *operation_id, + }, + BackendTask::ContestedResourceTask(ContestedResourceTask::QueryDPNSContests) => { + Self::DpnsContestRefresh + } BackendTask::MigrationTask(MigrationTask::RestoreFromPreviousVersion) => { Self::RestoreFromPreviousVersion } @@ -611,11 +683,6 @@ impl From<&BackendTask> for BackendTaskContext { } } -/// How one contest in a DPNS vote cast turned out: the normalized contested -/// name, the choice sent for it, and whether Platform took it. A cast is -/// per-contest, so one contest failing says nothing about the rest. -pub type DPNSVoteOutcome = (String, ResourceVoteChoice, Result<(), Arc>); - #[derive(Debug, Clone)] #[allow(clippy::large_enum_variant)] pub enum BackendTaskSuccessResult { @@ -655,8 +722,6 @@ pub enum BackendTaskSuccessResult { CoreItem(CoreItem), RegisteredIdentity(QualifiedIdentity, FeeResult), ToppedUpIdentity(QualifiedIdentity, FeeResult), - DPNSVoteResults(Vec), - CastScheduledVote(ScheduledDPNSVote), /// A scheduled-vote sweep finished without a query, identity or Platform /// failure. The app uses this acknowledgement to retire a preserved /// migration eligibility cutoff only after the recovery attempt succeeds. @@ -664,6 +729,11 @@ pub enum BackendTaskSuccessResult { network: Network, preserve_eligibility_since_ms: Option, }, + DpnsVoteOperationUpdated { + network: Network, + operation_id: DpnsVoteOperationId, + }, + ScheduledVotesCleared(Vec), /// The scheduled votes that the `CastDueScheduledVotes` sweep is about to /// cast this cycle, so the Scheduled Votes screen can mark them in progress. ScheduledVotesInProgress(Vec), @@ -1010,6 +1080,17 @@ pub enum BackendTaskSuccessResult { RefreshedDpnsContests, RefreshedOwnedDpnsNames, + // Identity username results (Stream U) + /// Result of an availability check for `label`. + UsernameAvailability { + label: String, + availability: crate::model::dpns_usernames::UsernameAvailability, + }, + /// Every loaded identity's username requests were refreshed and stored. + MyUsernameRequestsRefreshed, + /// A device-only username preference (main name, dismissal, seen banner) was saved. + UsernamePreferencesSaved, + // Broadcast results BroadcastedStateTransition, @@ -1083,11 +1164,6 @@ pub enum BackendTaskSuccessResult { impl BackendTaskSuccessResult { fn contains_dapi_reachability_failure(&self) -> bool { match self { - Self::DPNSVoteResults(results) => results.iter().any(|(_, _, result)| { - result - .as_ref() - .is_err_and(|error| error.contains_dapi_reachability_failure()) - }), Self::RefreshedWallet { warning } => warning .as_ref() .is_some_and(|error| error.contains_dapi_reachability_failure()), @@ -1097,17 +1173,6 @@ impl BackendTaskSuccessResult { fn contextualize_dapi_availability(self, availability: DapiAddressAvailability) -> Self { match self { - Self::DPNSVoteResults(results) => Self::DPNSVoteResults( - results - .into_iter() - .map(|(name, choice, result)| { - let result = result.map_err(|error| { - error.contextualize_shared_dapi_availability(availability) - }); - (name, choice, result) - }) - .collect(), - ), Self::RefreshedWallet { warning } => Self::RefreshedWallet { warning: warning .map(|error| error.contextualize_shared_dapi_availability(availability)), @@ -1874,29 +1939,6 @@ mod tests { assert!(!inspected.get()); } - #[test] - fn dapi_context_maps_errors_embedded_in_success_results() { - let result = contextualize_dapi_result( - Ok(BackendTaskSuccessResult::DPNSVoteResults(vec![( - "alice".to_owned(), - ResourceVoteChoice::Lock, - Err(Arc::new(dapi_connection_refused_error())), - )])), - || DapiAddressAvailability { - configured_total: 1, - live_count: 0, - }, - ); - - let Ok(BackendTaskSuccessResult::DPNSVoteResults(results)) = result else { - panic!("expected DPNS vote results"); - }; - assert!(matches!( - results[0].2, - Err(ref error) if matches!(error.as_ref(), TaskError::DapiAllAddressesExhausted { .. }) - )); - } - #[test] fn dapi_context_maps_spawned_dpns_query_task_result() { let result = contextualize_dapi_task_result( @@ -2006,6 +2048,22 @@ mod tests { ); } + #[test] + fn dpns_vote_context_preserves_the_originating_network() { + let operation_id = DpnsVoteOperationId::from_bytes([7; 16]); + let task = BackendTask::ContestedResourceTask( + ContestedResourceTask::ReconcileDpnsVoteOperation(operation_id, Network::Mainnet), + ); + + assert_eq!( + BackendTaskContext::from(&task), + BackendTaskContext::DpnsVoteOperation { + network: Network::Mainnet, + operation_id, + } + ); + } + /// Both shapes of payment broadcast must carry the network they were /// dispatched on: it is the only way a late "outcome unknown" error can be /// told apart from one belonging to the network the user has since left. diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 32e2a39f8..4e9ab8f41 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -9,9 +9,17 @@ use super::AppContext; use crate::backend_task::error::TaskError; use crate::model::contested_name::{ - ContestState, Contestant, ContestedName, PendingUsername, pending_usernames_in, + ContestState, Contestant, ContestedName, MasternodeVoteStateSummary, +}; +use crate::model::dpns_usernames::{ + RequestPhase, SeenMarkAttempts, UsernameRequest, won_username_is_missing, +}; +use crate::model::dpns_voting::{ + DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, VoteTiming, + authoritative_dpns_vote_outcomes, }; use crate::model::qualified_identity::QualifiedIdentity; +use crate::utils::time::now_ms; use crate::wallet_backend::{DetScope, KvAdapterError}; use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::data_contract::document_type::DocumentTypeRef; @@ -23,7 +31,7 @@ use dash_sdk::dpp::voting::vote_info_storage::contested_document_vote_poll_winne use dash_sdk::platform::Identifier; use dash_sdk::query_types::Contenders; use serde::{Deserialize, Serialize}; -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::time::Duration; /// Key prefix for DPNS contest cache entries in the per-network wallet @@ -35,6 +43,26 @@ fn contested_name_key(normalized_name: &str) -> String { format!("{CONTESTED_NAME_KEY_PREFIX}{normalized_name}") } +fn scheduled_vote_journal_summary( + operations: &[DpnsVoteOperation], + voter_id: Identifier, + dismissed: &BTreeSet<(DpnsVoteOperationId, DpnsVoteTargetKey)>, +) -> (bool, bool) { + let authoritative_by_target = authoritative_dpns_vote_outcomes(operations, |outcome| { + outcome.target.key.voter_id == voter_id + && matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + }); + + let pending = authoritative_by_target + .values() + .any(|(_, outcome)| outcome.status.holds_lock()); + let failed = authoritative_by_target.values().any(|(_, outcome)| { + outcome.status.is_reviewable_failure() + && !dismissed.contains(&(outcome.operation_id, outcome.target.key.clone())) + }); + (pending, failed) +} + /// Persisted shape of a single DPNS contest. Contenders are nested so /// the whole record reads atomically — pre-C6 stored them in a separate /// `contestant` table joined at load time. @@ -64,24 +92,23 @@ struct StoredContestant { document_id: [u8; 32], } -/// How long a DPNS name contest stays open before it locks or resolves. -/// Mainnet runs the two-week production window; every other network uses a -/// 90-minute fast-cycle window for testing. Mirrors platform's DPNS -/// contested-name governance parameters (`ACTIVE_VOTE_DURATION`). -const MAINNET_CONTEST_DURATION: Duration = Duration::from_secs(60 * 60 * 24 * 14); -const NON_MAINNET_CONTEST_DURATION: Duration = Duration::from_secs(60 * 90); - -fn contest_duration_for_network(network: Network) -> Duration { - if network == Network::Mainnet { - MAINNET_CONTEST_DURATION +fn vote_state_summary(states: &[DpnsCurrentVoteState]) -> MasternodeVoteStateSummary { + if states.contains(&DpnsCurrentVoteState::Checking) { + MasternodeVoteStateSummary::Checking + } else if states.contains(&DpnsCurrentVoteState::Unavailable) { + MasternodeVoteStateSummary::Unavailable } else { - NON_MAINNET_CONTEST_DURATION + MasternodeVoteStateSummary::Ready } } impl StoredContestedName { fn to_contested_name(&self, network: Network) -> ContestedName { - let contest_duration = contest_duration_for_network(network); + let join_window = crate::model::dpns::contest_durations( + network, + crate::context::default_platform_version(&network), + ) + .join; let awarded_to_id = self.awarded_to.map(Identifier::from); // Match pre-C6 semantics: state is computed from the latest @@ -93,16 +120,8 @@ impl StoredContestedName { } else if let Some(id) = awarded_to_id { ContestState::WonBy(id) } else if let Some(created_at) = latest_created_at { - let elapsed = Duration::from_millis( - (std::time::UNIX_EPOCH - .elapsed() - .unwrap_or_default() - .as_millis() as u64) - .saturating_sub(created_at), - ); - // New contenders may join only during the first half of the - // contest window; the second half is vote-only. - if elapsed <= contest_duration / 2 { + let elapsed = Duration::from_millis(now_ms().saturating_sub(created_at)); + if elapsed <= join_window { ContestState::Joinable } else { ContestState::Ongoing @@ -145,7 +164,50 @@ fn contest_err(source: KvAdapterError) -> TaskError { TaskError::ContestStorage { source } } +fn username_err(source: KvAdapterError) -> TaskError { + TaskError::UsernameStorage { source } +} + impl AppContext { + /// Protocol version the SDK currently speaks; it sets the community vote fee charged at registration. + pub fn sdk_platform_version(&self) -> &'static dash_sdk::dpp::version::PlatformVersion { + self.sdk.load().version() + } + + /// Warm contestant labels once storage becomes available. + pub(crate) fn refresh_dpns_candidate_labels(&self) -> Result<(), TaskError> { + let mut labels = self + .dpns_candidate_labels + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); + *labels = self + .all_contested_names()? + .into_iter() + .map(|contest| { + ( + contest.normalized_contested_name, + contest + .contestants + .unwrap_or_default() + .into_iter() + .map(|candidate| (candidate.id, candidate.name)) + .collect(), + ) + }) + .collect(); + Ok(()) + } + + /// Return a cached display label without reading persistent storage. + pub(crate) fn dpns_candidate_label(&self, name: &str, candidate: Identifier) -> Option { + self.dpns_candidate_labels + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(name)? + .get(&candidate) + .cloned() + } + /// Fetches every DPNS contest cached in the per-network k/v store. pub fn all_contested_names(&self) -> std::result::Result, TaskError> { let kv = self.det_kv()?; @@ -170,10 +232,7 @@ impl AppContext { /// Fetches every DPNS contest cached in the per-network k/v store whose /// `end_time` is in the future (or unknown). pub fn ongoing_contested_names(&self) -> std::result::Result, TaskError> { - let current_timestamp = std::time::UNIX_EPOCH - .elapsed() - .unwrap_or_default() - .as_millis() as u64; + let current_timestamp = now_ms(); let kv = self.det_kv()?; let keys = kv .list(DetScope::Global, Some(CONTESTED_NAME_KEY_PREFIX)) @@ -196,99 +255,386 @@ impl AppContext { Ok(out) } - /// Rebuild the frame-safe pending-name snapshot from the contest store. + /// Reload the frame-safe username snapshot from the per-network store. + /// + /// Called at startup and after contest refreshes so the hub reads requests, + /// main-name choices and seen outcomes without touching storage per frame. pub(crate) fn refresh_pending_dpns_usernames(&self) -> Result<(), TaskError> { - let contests = self.ongoing_contested_names()?; - let pending = pending_usernames_in(&contests); - *self - .pending_dpns_usernames - .write() - .unwrap_or_else(std::sync::PoisonError::into_inner) = pending; + let kv = self.det_kv()?; + let mut current = self.username_cache_mut(); + let mut cache = UsernameCache::default(); + for key in kv + .list(DetScope::Global, Some(USERNAME_REQUESTS_KEY_PREFIX)) + .map_err(username_err)? + { + let Some(id) = identity_from_key(&key, USERNAME_REQUESTS_KEY_PREFIX) else { + continue; + }; + if self.is_identity_unloaded(&kv, &id.to_buffer())? && !self.is_identity_listed(&id)? { + continue; + } + if let Some(requests) = kv + .get::>(DetScope::Global, &key) + .map_err(username_err)? + { + if requests + .iter() + .any(|request| request.phase == RequestPhase::Won) + { + cache.hydration_pending.insert(id); + } + cache.requests.insert(id, requests); + } + } + for key in kv + .list(DetScope::Global, Some(MAIN_USERNAME_KEY_PREFIX)) + .map_err(username_err)? + { + if let Some(id) = identity_from_key(&key, MAIN_USERNAME_KEY_PREFIX) + && !(self.is_identity_unloaded(&kv, &id.to_buffer())? + && !self.is_identity_listed(&id)?) + && let Some(name) = kv + .get::(DetScope::Global, &key) + .map_err(username_err)? + { + cache.main.insert(id, name); + } + } + for key in kv + .list(DetScope::Global, Some(SEEN_OUTCOMES_KEY_PREFIX)) + .map_err(username_err)? + { + if let Some(id) = identity_from_key(&key, SEEN_OUTCOMES_KEY_PREFIX) + && !(self.is_identity_unloaded(&kv, &id.to_buffer())? + && !self.is_identity_listed(&id)?) + && let Some(seen) = kv + .get::>(DetScope::Global, &key) + .map_err(username_err)? + { + cache.seen.insert(id, seen); + } + } + cache.seen_marks = std::mem::take(&mut current.seen_marks); + *current = cache; Ok(()) } - /// The DPNS username `identity_id` has requested but not yet been awarded, - /// if any — read from the frame-safe snapshot. - /// - /// Read-only; returns `Ok(None)` when nothing is pending. Lets the UI tell - /// "requested but still being decided" apart from "no username requested". - pub fn pending_dpns_username_for( - &self, - identity_id: &Identifier, - ) -> std::result::Result, TaskError> { - let now_ms = std::time::UNIX_EPOCH - .elapsed() - .unwrap_or_default() - .as_millis() as u64; - Ok(self - .pending_dpns_usernames + fn username_cache(&self) -> std::sync::RwLockReadGuard<'_, UsernameCache> { + self.pending_dpns_usernames .read() .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Write guard over the username snapshot. Every username write holds it + /// across its read-modify-write and store update, so writers never interleave. + pub(crate) fn username_cache_mut(&self) -> std::sync::RwLockWriteGuard<'_, UsernameCache> { + self.pending_dpns_usernames + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Every stored username request of `identity_id`, pending first. Frame-safe. + pub fn username_requests_for(&self, identity_id: &Identifier) -> Vec { + let now = crate::utils::time::now_ms(); + self.username_cache() + .requests .get(identity_id) - .filter(|pending| pending.decided_at.is_none_or(|end| end > now_ms)) - .cloned()) + .into_iter() + .flatten() + .cloned() + .map(|mut request| { + request.phase = request.phase_at(now); + request + }) + .collect() + } + + /// Whether any identity has a request still in its community vote. Frame-safe. + pub fn any_pending_username_request(&self) -> bool { + self.username_cache() + .requests + .values() + .flatten() + .any(|request| request.phase.is_pending()) + } + + /// Pending contests and saved wins both need periodic refresh until owned names are stored. + pub fn username_requests_need_refresh(&self) -> bool { + self.any_pending_username_request() || !self.username_cache().hydration_pending.is_empty() + } + + pub(crate) fn update_username_hydration_status( + &self, + identity_id: Identifier, + names: &[crate::model::qualified_identity::DPNSNameInfo], + ) -> bool { + let mut cache = self.username_cache_mut(); + let pending = cache.requests.get(&identity_id).is_some_and(|requests| { + requests + .iter() + .any(|request| won_username_is_missing(request, names)) + }); + if pending { + cache.hydration_pending.insert(identity_id); + } else { + cache.hydration_pending.remove(&identity_id); + } + pending } - /// Map each of `identity_ids` to its pending DPNS username request, if any. + /// Persist `requests` as the full request list of `identity_id`. + pub fn store_username_requests( + &self, + identity_id: &Identifier, + requests: Vec, + ) -> Result<(), TaskError> { + self.update_username_requests(identity_id, |_| requests) + } + + /// Replace the request list of `identity_id` with `update(current list)`. /// - /// Reads only the frame-safe snapshot. Identities with nothing pending are - /// omitted. - pub fn pending_dpns_usernames( + /// The read, the store write and the snapshot update run under one guard, + /// so a request recorded by a concurrent registration is never lost. + pub(crate) fn update_username_requests( &self, - identity_ids: &[Identifier], - ) -> std::result::Result, TaskError> { - let now_ms = std::time::UNIX_EPOCH - .elapsed() - .unwrap_or_default() - .as_millis() as u64; - let pending = self - .pending_dpns_usernames - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner); - Ok(identity_ids - .iter() - .filter_map(|id| { - pending - .get(id) - .filter(|name| name.decided_at.is_none_or(|end| end > now_ms)) - .cloned() - .map(|name| (*id, name)) - }) - .collect()) + identity_id: &Identifier, + update: impl FnOnce(&[UsernameRequest]) -> Vec, + ) -> Result<(), TaskError> { + let kv = self.det_kv()?; + let key = identity_key(USERNAME_REQUESTS_KEY_PREFIX, identity_id); + let mut cache = self.username_cache_mut(); + let current = kv + .get::>(DetScope::Global, &key) + .map_err(username_err)? + .unwrap_or_default(); + let requests = update(¤t); + if requests != current { + if requests.is_empty() { + kv.delete(DetScope::Global, &key).map_err(username_err)?; + } else { + kv.put(DetScope::Global, &key, &requests) + .map_err(username_err)?; + } + } + if requests.is_empty() { + cache.requests.remove(identity_id); + cache.hydration_pending.remove(identity_id); + } else { + if requests + .iter() + .any(|request| request.phase == RequestPhase::Won) + { + cache.hydration_pending.insert(*identity_id); + } + cache.requests.insert(*identity_id, requests); + } + Ok(()) } - /// Return a pending DPNS username only while `identity` owns no awarded name. + /// The first pending request while `identity` owns no registered name. Frame-safe. pub fn pending_dpns_username_for_identity( &self, identity: &QualifiedIdentity, - ) -> Option { + ) -> Option { if identity_owns_dpns_name(identity) { - None - } else { - self.pending_dpns_username_for(&identity.identity.id()) - .ok() - .flatten() + return None; } + self.username_requests_for(&identity.identity.id()) + .into_iter() + .find(|request| request.phase.is_pending()) } - /// Map identities without an awarded name to their pending DPNS usernames. - pub fn pending_dpns_usernames_for_identities( - &self, - identities: &[QualifiedIdentity], - ) -> HashMap { - let identity_ids = identities + /// The registered name `identity` shows as its main one. Frame-safe. + /// + /// The local "Show as main" choice wins while the identity still owns that + /// name; otherwise the first registered name. + pub fn main_username(&self, identity: &QualifiedIdentity) -> Option { + let owned = identity + .dpns_names .iter() - .filter(|identity| !identity_owns_dpns_name(identity)) - .map(|identity| identity.identity.id()) - .collect::>(); - self.pending_dpns_usernames(&identity_ids) - .unwrap_or_default() + .map(|name| name.name.trim()) + .filter(|name| !name.is_empty()); + let preferred = self + .username_cache() + .main + .get(&identity.identity.id()) + .cloned(); + let mut first = None; + for name in owned { + if preferred.as_deref() == Some(name) { + return Some(name.to_owned()); + } + first.get_or_insert(name); + } + first.map(str::to_owned) + } + + /// Move the identity's main username to the front of `dpns_names`, so every + /// surface that shows the first registered name shows the chosen one. + pub(crate) fn order_main_username_first(&self, identity: &mut QualifiedIdentity) { + let Some(main) = self.main_username(identity) else { + return; + }; + if let Some(index) = identity + .dpns_names + .iter() + .position(|n| n.name.trim() == main) + { + identity.dpns_names[..=index].rotate_right(1); + } + } + + /// Show `name` as the main username of `identity_id` on this device. + pub fn set_main_username(&self, identity_id: &Identifier, name: &str) -> Result<(), TaskError> { + let kv = self.det_kv()?; + let mut cache = self.username_cache_mut(); + kv.put( + DetScope::Global, + &identity_key(MAIN_USERNAME_KEY_PREFIX, identity_id), + &name.to_owned(), + ) + .map_err(username_err)?; + cache.main.insert(*identity_id, name.to_owned()); + Ok(()) + } + + /// Whether the one-time banner for `request`'s outcome was already shown. Frame-safe. + pub fn username_outcome_seen( + &self, + identity_id: &Identifier, + request: &UsernameRequest, + ) -> bool { + self.username_cache() + .seen + .get(identity_id) + .is_some_and(|seen| seen.contains(&outcome_key(request))) + } + + /// Whether a "banner seen" write for `identity_id` may be dispatched in + /// frame `pass`; records the dispatch when it may. Frame-safe, in memory only. + pub fn try_dispatch_username_seen_mark(&self, identity_id: &Identifier, pass: u64) -> bool { + let mut cache = self.username_cache_mut(); + let attempts = cache.seen_marks.entry(*identity_id).or_default(); + if !attempts.may_dispatch(pass, std::time::Instant::now()) { + return false; + } + attempts.dispatched(pass); + true + } + + /// Update the in-memory "banner seen" write bounds as the backend runs it. + pub(crate) fn note_username_seen_mark(&self, identity_id: &Identifier, outcome: Option) { + let mut cache = self.username_cache_mut(); + let attempts = cache.seen_marks.entry(*identity_id).or_default(); + match outcome { + None => attempts.started(), + Some(succeeded) => attempts.finished(succeeded, std::time::Instant::now()), + } + } + + /// Record that the outcome banners for `requests` were shown. + pub fn mark_username_outcomes_seen( + &self, + identity_id: &Identifier, + requests: &[UsernameRequest], + ) -> Result<(), TaskError> { + let kv = self.det_kv()?; + let mut cache = self.username_cache_mut(); + let mut seen = cache.seen.get(identity_id).cloned().unwrap_or_default(); + let before = seen.len(); + seen.extend(requests.iter().map(outcome_key)); + if seen.len() == before { + return Ok(()); + } + kv.put( + DetScope::Global, + &identity_key(SEEN_OUTCOMES_KEY_PREFIX, identity_id), + &seen, + ) + .map_err(username_err)?; + cache.seen.insert(*identity_id, seen); + Ok(()) + } + + /// Remove a finished request from the identity's list. + pub fn dismiss_username_request( + &self, + identity_id: &Identifier, + normalized_label: &str, + ) -> Result<(), TaskError> { + self.update_username_requests(identity_id, |requests| { + requests + .iter() + .filter(|r| r.phase.is_pending() || r.normalized_label != normalized_label) + .cloned() + .collect() + }) + } + + /// Drop every username record of a removed identity, so its requests stop + /// driving refreshes and its main-name choice does not return on re-import. + pub(crate) fn forget_identity_usernames( + &self, + kv: &crate::wallet_backend::DetKv, + identity_id: &Identifier, + ) -> Result<(), TaskError> { + let mut cache = self.username_cache_mut(); + cache.requests.remove(identity_id); + cache.hydration_pending.remove(identity_id); + cache.main.remove(identity_id); + cache.seen.remove(identity_id); + cache.seen_marks.remove(identity_id); + let mut first_error = None; + for prefix in [ + USERNAME_REQUESTS_KEY_PREFIX, + MAIN_USERNAME_KEY_PREFIX, + SEEN_OUTCOMES_KEY_PREFIX, + ] { + if let Err(error) = kv.delete(DetScope::Global, &identity_key(prefix, identity_id)) { + first_error.get_or_insert(error); + } + } + first_error.map_or(Ok(()), |error| Err(username_err(error))) + } + + /// Seed a current contest through the persisted shape for backend contract tests. + #[cfg(test)] + pub(crate) fn seed_dpns_contest_for_test( + &self, + name: &str, + end_time: Option, + closed: bool, + ) { + let now = now_ms(); + let stored = StoredContestedName { + normalized_contested_name: name.into(), + end_time, + locked: closed, + contestants: vec![StoredContestant { + id: [3; 32], + name: name.into(), + info: String::new(), + votes: 0, + created_at: Some(now), + created_at_block_height: None, + created_at_core_block_height: None, + document_id: [4; 32], + }], + ..Default::default() + }; + self.det_kv() + .unwrap() + .put(DetScope::Global, &contested_name_key(name), &stored) + .unwrap(); } /// Summarise a masternode/evonode node's DPNS voting position for its card. /// - /// `voter_id` is the node's voter-identity id (`associated_voter_identity`); - /// pass `None` for a node with no voting key loaded — it can vote on + /// `voter_id` is the node's **own** identity id — its ProTxHash, the id + /// Platform records masternode votes under and the key both the proved-vote + /// cache and the vote journal use. It is never the separate + /// `associated_voter_identity` record, which only supplies the signing key. + /// Pass `None` for a node with no voting key loaded — it can vote on /// nothing, so the summary is empty. The open count reads the ongoing /// contest cache and the scheduled-vote flag reuses the existing DPNS /// Scheduled Votes state (no new backend concept — §10.1). @@ -300,22 +646,82 @@ impl AppContext { let Some(voter_id) = voter_id else { return Ok(crate::model::contested_name::MasternodeContestSummary::default()); }; + Ok(self + .masternode_contest_summaries(&[voter_id])? + .remove(&voter_id) + .unwrap_or_default()) + } - let open_contest_count = self - .ongoing_contested_names()? - .iter() - .filter(|contest| contest.is_open_for_voter(&voter_id)) - .count(); + /// Summarise many nodes at once, reading the shared state a single time. + /// + /// The contest cache, the derived vote-poll ids, the operation journal and + /// the schedule dismissals all depend on the contest set rather than the + /// node, so an operator with a large fleet must not pay for them per card. + /// Only the proved current-vote snapshot is genuinely per node. Nodes whose + /// summary cannot be built are omitted. + pub fn masternode_contest_summaries( + &self, + voter_ids: &[Identifier], + ) -> std::result::Result< + BTreeMap, + TaskError, + > { + if voter_ids.is_empty() { + return Ok(BTreeMap::new()); + } - let has_scheduled_vote = self - .get_scheduled_votes()? + let contests = self.ongoing_contested_names()?; + let open_polls: Vec> = contests .iter() - .any(|vote| vote.voter_id == voter_id && !vote.executed_successfully); + .filter(|contest| contest.is_votable()) + .map(|contest| { + self.dpns_vote_poll_id(&contest.normalized_contested_name) + .ok() + }) + .collect(); + let open_contest_count = open_polls.len(); + let poll_ids: Vec = open_polls.iter().flatten().copied().collect(); + let operations = self.dpns_vote_operations()?; + let dismissed = self.dismissed_dpns_vote_schedules()?; - Ok(crate::model::contested_name::MasternodeContestSummary { - open_contest_count, - has_scheduled_vote, - }) + Ok(voter_ids + .iter() + .map(|voter_id| { + // One storage read per node for every open contest's proved state + // (VOTE-NFR-007), instead of one read per contest. A read failure + // degrades each contest to `Unavailable`, matching the prior + // per-contest fallback. + let poll_states = if poll_ids.is_empty() { + BTreeMap::new() + } else { + self.dpns_current_vote_states(*voter_id, poll_ids.iter().copied()) + .unwrap_or_default() + }; + let states = open_polls + .iter() + .map(|poll| { + poll.and_then(|poll_id| poll_states.get(&poll_id).copied()) + .unwrap_or(DpnsCurrentVoteState::Unavailable) + }) + .collect::>(); + let needs_vote_count = states + .iter() + .filter(|state| **state == DpnsCurrentVoteState::Available(None)) + .count(); + let (has_scheduled_vote, has_failed_scheduled_vote) = + scheduled_vote_journal_summary(&operations, *voter_id, &dismissed); + ( + *voter_id, + crate::model::contested_name::MasternodeContestSummary { + open_contest_count, + needs_vote_count, + vote_state: vote_state_summary(&states), + has_scheduled_vote, + has_failed_scheduled_vote, + }, + ) + }) + .collect()) } /// Apply a batch of newly-seen normalized names. New names are stored @@ -373,6 +779,10 @@ impl AppContext { dpns_domain_document_type: DocumentTypeRef, ) -> std::result::Result<(), TaskError> { let kv = self.det_kv()?; + let mut labels = self + .dpns_candidate_labels + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); let key = contested_name_key(normalized_contested_name); let last_updated = chrono::Utc::now().timestamp() as u64; @@ -402,6 +812,14 @@ impl AppContext { .map_err(contest_err)?; } } + labels.insert( + normalized_contested_name.to_owned(), + stored + .contestants + .iter() + .map(|candidate| (Identifier::from(candidate.id), candidate.name.clone())) + .collect(), + ); return Ok(()); } @@ -459,6 +877,14 @@ impl AppContext { kv.put(DetScope::Global, &key, &stored) .map_err(contest_err)?; + labels.insert( + normalized_contested_name.to_owned(), + stored + .contestants + .iter() + .map(|candidate| (Identifier::from(candidate.id), candidate.name.clone())) + .collect(), + ); Ok(()) } @@ -494,6 +920,43 @@ impl AppContext { } } +/// Per-identity request lists, keyed `det:username_requests:`. +const USERNAME_REQUESTS_KEY_PREFIX: &str = "det:username_requests:"; +/// Device-only main-name choice, keyed `det:main_username:`. +const MAIN_USERNAME_KEY_PREFIX: &str = "det:main_username:"; +/// Outcome banners already shown, keyed `det:username_outcomes_seen:`. +const SEEN_OUTCOMES_KEY_PREFIX: &str = "det:username_outcomes_seen:"; + +/// Frame-safe copy of the identity-side username state. +#[derive(Debug, Default)] +pub(crate) struct UsernameCache { + requests: HashMap>, + hydration_pending: BTreeSet, + main: HashMap, + seen: HashMap>, + /// In-memory write bounds for "banner seen"; never persisted. + pub(crate) seen_marks: HashMap, +} + +fn identity_key(prefix: &str, identity_id: &Identifier) -> String { + format!( + "{prefix}{}", + identity_id.to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58) + ) +} + +fn identity_from_key(key: &str, prefix: &str) -> Option { + Identifier::from_string( + key.strip_prefix(prefix)?, + dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58, + ) + .ok() +} + +fn outcome_key(request: &UsernameRequest) -> String { + format!("{}:{:?}", request.normalized_label, request.phase) +} + fn identity_owns_dpns_name(identity: &QualifiedIdentity) -> bool { identity .dpns_names @@ -505,7 +968,8 @@ fn identity_owns_dpns_name(identity: &QualifiedIdentity) -> bool { mod tests { use super::*; use crate::context::test_support::test_app_context; - use crate::model::contested_name::pending_username_in; + use crate::model::dpns_usernames::RequestPhase; + use crate::model::dpns_voting::DpnsVoteTargetStatus; use crate::model::qualified_identity::encrypted_key_storage::KeyStorage; use crate::model::qualified_identity::{ DPNSNameInfo, IdentityStatus, IdentityType, QualifiedIdentity, @@ -514,7 +978,9 @@ mod tests { use crate::wallet_backend::kv_test_support::InMemoryKv; use dash_sdk::dpp::identity::Identity; use dash_sdk::dpp::version::PlatformVersion; + use platform_wallet_storage::{KvError, KvStore, ObjectId}; use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; fn empty_kv() -> DetKv { DetKv::from_store(Arc::new(InMemoryKv::default())) @@ -558,48 +1024,339 @@ mod tests { } } + fn request(label: &str, phase: RequestPhase) -> UsernameRequest { + UsernameRequest { + label: label.to_owned(), + normalized_label: label.to_owned(), + phase, + requested_at: None, + join_end: None, + end: None, + decided_at: None, + tally: Default::default(), + last_updated: 0, + reflected_in_owned_names: false, + } + } + + #[derive(Default)] + struct ReloadReadHookKv { + inner: InMemoryKv, + after_read: std::sync::Mutex>>, + } + + impl KvStore for ReloadReadHookKv { + fn get(&self, scope: &ObjectId, key: &str) -> Result>, KvError> { + let value = self.inner.get(scope, key)?; + let hook = self.after_read.lock().unwrap().take(); + if let Some(hook) = hook { + hook(); + } + Ok(value) + } + + fn put(&self, scope: &ObjectId, key: &str, value: &[u8]) -> Result<(), KvError> { + self.inner.put(scope, key, value) + } + + fn delete(&self, scope: &ObjectId, key: &str) -> Result<(), KvError> { + self.inner.delete(scope, key) + } + + fn list_keys( + &self, + scope: &ObjectId, + prefix: Option<&str>, + ) -> Result, KvError> { + self.inner.list_keys(scope, prefix) + } + } + #[test] - fn pending_dpns_usernames_for_identities_omits_owned_identity() { - let temp_dir = tempfile::tempdir().expect("tempdir"); - let context = test_app_context(temp_dir.path()); - let owned = qualified_identity(1, "alice"); - let unowned = qualified_identity(2, " "); - { - let mut pending = context - .pending_dpns_usernames - .write() - .unwrap_or_else(std::sync::PoisonError::into_inner); - pending.insert( - owned.identity.id(), - PendingUsername { - name: "alice".to_string(), - decided_at: None, - }, + fn review_safety_username_reload_preserves_overlapping_request_write() { + let temp = tempfile::tempdir().unwrap(); + let context = test_app_context(temp.path()); + let store = Arc::new(ReloadReadHookKv::default()); + context.set_det_kv_override_for_test(DetKv::from_store(store.clone())); + let id = Identifier::from([1; 32]); + let original = request("alpha", RequestPhase::Voting); + context + .store_username_requests(&id, vec![original.clone()]) + .unwrap(); + let weak = Arc::downgrade(&context); + let (worker_tx, worker_rx) = std::sync::mpsc::channel(); + *store.after_read.lock().unwrap() = Some(Box::new(move || { + let context = weak.upgrade().unwrap(); + let serialized = matches!( + context.pending_dpns_usernames.try_write(), + Err(std::sync::TryLockError::WouldBlock) ); - pending.insert( - unowned.identity.id(), - PendingUsername { - name: "bob".to_string(), - decided_at: None, - }, + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let worker = std::thread::spawn(move || { + context + .update_username_requests(&id, |current| { + let mut requests = current.to_vec(); + requests.push(request("beta", RequestPhase::Voting)); + requests + }) + .unwrap(); + let _ = done_tx.send(()); + }); + worker_tx.send(worker).unwrap(); + // Force the stale-read interleaving unless the reload excludes the writer. + if !serialized { + done_rx.recv().unwrap(); + } + })); + context.refresh_pending_dpns_usernames().unwrap(); + worker_rx.recv().unwrap().join().unwrap(); + let expected = vec![original, request("beta", RequestPhase::Voting)]; + assert_eq!(context.username_requests_for(&id), expected); + context.refresh_pending_dpns_usernames().unwrap(); + assert_eq!(context.username_requests_for(&id), expected); + } + + #[test] + fn review_safety_username_reload_preserves_snapshot_on_record_read_failure() { + use crate::wallet_backend::kv_test_support::FailingKv; + for prefix in [ + USERNAME_REQUESTS_KEY_PREFIX, + MAIN_USERNAME_KEY_PREFIX, + SEEN_OUTCOMES_KEY_PREFIX, + ] { + let temp = tempfile::tempdir().unwrap(); + let context = test_app_context(temp.path()); + let store = Arc::new(FailingKv::default()); + context.set_det_kv_override_for_test(DetKv::from_store(store.clone())); + let id = Identifier::from([1; 32]); + let original = request("alpha", RequestPhase::Won); + context + .store_username_requests(&id, vec![original.clone()]) + .unwrap(); + context.set_main_username(&id, "alpha").unwrap(); + context + .mark_username_outcomes_seen(&id, std::slice::from_ref(&original)) + .unwrap(); + store.fail_next_gets_containing(prefix, 1); + let result = context.refresh_pending_dpns_usernames(); + assert_eq!( + context.username_requests_for(&id), + vec![original.clone()], + "{prefix}" + ); + assert_eq!( + context.username_cache().main.get(&id).map(String::as_str), + Some("alpha"), + "{prefix}" + ); + assert!(context.username_outcome_seen(&id, &original), "{prefix}"); + assert!(result.is_err(), "a failed {prefix} read must be reported"); + context + .update_username_requests(&id, |current| { + let mut requests = current.to_vec(); + requests.push(request("beta", RequestPhase::Voting)); + requests + }) + .unwrap(); + context.refresh_pending_dpns_usernames().unwrap(); + assert_eq!( + context.username_requests_for(&id), + vec![original, request("beta", RequestPhase::Voting)] ); } + } - let pending = context.pending_dpns_usernames_for_identities(&[owned, unowned]); + #[test] + fn username_append_after_failed_initial_load_preserves_saved_requests() { + use crate::wallet_backend::kv_test_support::FailingKv; + let temp = tempfile::tempdir().unwrap(); + let context = test_app_context(temp.path()); + let store = Arc::new(FailingKv::default()); + let kv = DetKv::from_store(store.clone()); + context.set_det_kv_override_for_test(kv.clone()); + let id = Identifier::from([1; 32]); + let key = identity_key(USERNAME_REQUESTS_KEY_PREFIX, &id); + let original = request("alpha", RequestPhase::Won); + kv.put(DetScope::Global, &key, &vec![original.clone()]) + .unwrap(); + store.fail_next_gets_containing(USERNAME_REQUESTS_KEY_PREFIX, 1); + assert!(context.refresh_pending_dpns_usernames().is_err()); + assert!(context.username_requests_for(&id).is_empty()); + // An unreadable authoritative record must never be treated as an empty list. + store.fail_next_gets_containing(USERNAME_REQUESTS_KEY_PREFIX, 1); assert!( - !pending.contains_key(&Identifier::from([1; 32])), - "an awarded DPNS name must suppress the stale pending indicator" + context + .update_username_requests(&id, |_| panic!("must not update")) + .is_err() ); + context + .update_username_requests(&id, |current| { + let mut requests = current.to_vec(); + requests.push(request("beta", RequestPhase::Voting)); + requests + }) + .unwrap(); + let expected = vec![original, request("beta", RequestPhase::Voting)]; + assert_eq!(context.username_requests_for(&id), expected); + assert!(context.username_requests_need_refresh()); assert_eq!( - pending - .get(&Identifier::from([2; 32])) - .map(|name| name.name.as_str()), - Some("bob"), - "a blank DPNS entry is not ownership and must keep the pending indicator" + kv.get::>(DetScope::Global, &key) + .unwrap(), + Some(expected) ); } + #[test] + fn unchanged_username_update_populates_an_unloaded_cache() { + let temp = tempfile::tempdir().unwrap(); + let context = test_app_context(temp.path()); + let kv = empty_kv(); + context.set_det_kv_override_for_test(kv.clone()); + let id = Identifier::from([1; 32]); + let saved = vec![request("alpha", RequestPhase::Won)]; + kv.put( + DetScope::Global, + &identity_key(USERNAME_REQUESTS_KEY_PREFIX, &id), + &saved, + ) + .unwrap(); + context + .update_username_requests(&id, |current| current.to_vec()) + .unwrap(); + assert_eq!(context.username_requests_for(&id), saved); + assert!(context.username_requests_need_refresh()); + } + + #[test] + fn reloaded_expired_request_has_current_phase_without_rewriting_snapshot() { + let temp_dir = tempfile::tempdir().unwrap(); + let context = test_app_context(temp_dir.path()); + context.set_det_kv_override_for_test(empty_kv()); + let identity = qualified_identity(1, ""); + let id = identity.identity.id(); + let mut expired = request("d1ssh", RequestPhase::Joinable); + expired.join_end = Some(1); + expired.end = Some(2); + context + .store_username_requests(&id, vec![expired.clone()]) + .unwrap(); + *context.username_cache_mut() = UsernameCache::default(); + context.refresh_pending_dpns_usernames().unwrap(); + + assert_eq!( + context.username_requests_for(&id)[0].phase, + RequestPhase::AwaitingOutcome + ); + assert_eq!( + context + .pending_dpns_username_for_identity(&identity) + .unwrap() + .phase, + RequestPhase::AwaitingOutcome + ); + assert!(context.any_pending_username_request()); + assert_eq!(context.username_cache().requests[&id], vec![expired]); + } + + #[test] + fn pending_username_is_suppressed_once_identity_owns_a_name() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = test_app_context(temp_dir.path()); + context.set_det_kv_override_for_test(empty_kv()); + let owned = qualified_identity(1, "alice"); + let unowned = qualified_identity(2, " "); + for identity in [&owned, &unowned] { + context + .store_username_requests( + &identity.identity.id(), + vec![ + request("lost", RequestPhase::Lost), + request("b0b", RequestPhase::Voting), + ], + ) + .expect("store"); + } + assert!(context.pending_dpns_username_for_identity(&owned).is_none()); + assert_eq!( + context + .pending_dpns_username_for_identity(&unowned) + .map(|r| r.label), + Some("b0b".to_owned()) + ); + // An owned name never hides the full request list. + assert_eq!(context.username_requests_for(&owned.identity.id()).len(), 2); + } + + #[test] + fn username_state_survives_a_snapshot_reload() { + // USR-TC-021 persistence half: the main-name choice and seen flags reload. + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = test_app_context(temp_dir.path()); + context.set_det_kv_override_for_test(empty_kv()); + let mut identity = qualified_identity(1, "alice"); + identity.dpns_names.push(DPNSNameInfo { + name: "bob".to_owned(), + acquired_at: 0, + }); + let id = identity.identity.id(); + assert_eq!(context.main_username(&identity).as_deref(), Some("alice")); + context.set_main_username(&id, "bob").expect("set main"); + let won = request("carol", RequestPhase::Won); + context + .store_username_requests(&id, vec![won.clone()]) + .expect("store"); + context + .mark_username_outcomes_seen(&id, std::slice::from_ref(&won)) + .expect("seen"); + + *context.username_cache_mut() = UsernameCache::default(); + context.refresh_pending_dpns_usernames().expect("reload"); + + assert_eq!(context.main_username(&identity).as_deref(), Some("bob")); + assert!(context.username_outcome_seen(&id, &won)); + assert_eq!(context.username_requests_for(&id), vec![won.clone()]); + + context + .dismiss_username_request(&id, "carol") + .expect("dismiss"); + assert!(context.username_requests_for(&id).is_empty()); + } + + #[test] + fn forgetting_an_identity_drops_its_username_records() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = test_app_context(temp_dir.path()); + let kv = empty_kv(); + context.set_det_kv_override_for_test(kv.clone()); + let id = qualified_identity(1, "alice").identity.id(); + let pending = request("carol", RequestPhase::Voting); + context + .store_username_requests(&id, vec![pending.clone()]) + .expect("store"); + context.set_main_username(&id, "alice").expect("main"); + assert!(context.any_pending_username_request()); + + context.forget_identity_usernames(&kv, &id).expect("forget"); + context.refresh_pending_dpns_usernames().expect("reload"); + + assert!(!context.any_pending_username_request()); + assert!(context.username_requests_for(&id).is_empty()); + assert!(!context.username_cache().main.contains_key(&id)); + } + + #[test] + fn main_username_falls_back_when_preferred_name_is_gone() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = test_app_context(temp_dir.path()); + context.set_det_kv_override_for_test(empty_kv()); + let identity = qualified_identity(1, "alice"); + context + .set_main_username(&identity.identity.id(), "gone") + .expect("set main"); + assert_eq!(context.main_username(&identity).as_deref(), Some("alice")); + } + // ---------------------------------------------------------------- // Decode: contest state branches the cache resolves at read time. // ---------------------------------------------------------------- @@ -716,38 +1473,329 @@ mod tests { assert_eq!(contested_name_key("dash"), "det:contested_name:dash"); } - // ---------------------------------------------------------------- - // Bridge: a stored contest decodes into a detectable pending username. - // ---------------------------------------------------------------- + #[test] + fn card_summary_does_not_treat_checking_as_all_votes_cast() { + assert_eq!( + vote_state_summary(&[ + DpnsCurrentVoteState::Available(Some( + dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice::Lock, + )), + DpnsCurrentVoteState::Checking, + ]), + MasternodeVoteStateSummary::Checking + ); + } #[test] - fn stored_undecided_contest_yields_pending_username() { - // A contestant with a timestamp and no winner resolves to an active - // (Ongoing) state, so the identity has a pending username request. - let stored = StoredContestedName { - normalized_contested_name: "det1".to_string(), - end_time: Some(9_999), - contestants: vec![contestant(5, Some(100))], - ..Default::default() - }; - let cn = stored.to_contested_name(Network::Testnet); - let me = Identifier::from([5u8; 32]); - let pending = pending_username_in(std::slice::from_ref(&cn), &me) - .expect("undecided contender must surface a pending username"); - assert_eq!(pending.name, "name-5"); - assert_eq!(pending.decided_at, Some(9_999)); + fn card_summary_does_not_treat_unavailable_as_all_votes_cast() { + assert_eq!( + vote_state_summary(&[ + DpnsCurrentVoteState::Available(None), + DpnsCurrentVoteState::Unavailable, + ]), + MasternodeVoteStateSummary::Unavailable + ); } #[test] - fn stored_awarded_contest_yields_no_pending_username() { - let stored = StoredContestedName { - normalized_contested_name: "det1".to_string(), - awarded_to: Some([5u8; 32]), - contestants: vec![contestant(5, Some(100))], - ..Default::default() + fn dismissed_failure_does_not_hide_unresolved_sibling() { + let temp = tempfile::tempdir().unwrap(); + let context = test_app_context(temp.path()); + context.set_det_kv_override_for_test(empty_kv()); + let voter_id = Identifier::from([7; 32]); + let targets = ["alice", "bob"].map(|name| crate::model::dpns_voting::DpnsVoteTarget { + key: crate::model::dpns_voting::DpnsVoteTargetKey { + network: Network::Testnet, + voter_id, + vote_poll_id: context.dpns_vote_poll_id(name).unwrap(), + }, + voter_alias: None, + contested_name: name.into(), + requested_choice: + dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Scheduled(42), + }); + let mut operation = AppContext::new_dpns_vote_operation(targets.into()); + operation.targets[0].status = DpnsVoteTargetStatus::Rejected; + operation.targets[1].status = DpnsVoteTargetStatus::Unconfirmed; + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + assert!( + context + .masternode_contest_summary(Some(voter_id)) + .unwrap() + .has_failed_scheduled_vote + ); + context + .remove_scheduled_dpns_vote(operation.id, &operation.targets[0].target.key) + .unwrap(); + let summary = context.masternode_contest_summary(Some(voter_id)).unwrap(); + assert!( + !summary.has_failed_scheduled_vote, + "dismissed terminal history is not an actionable failure" + ); + assert!( + summary.has_scheduled_vote, + "unresolved sibling remains visible" + ); + assert_eq!( + context + .dpns_vote_operation(operation.id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Rejected, + "removal must retain the original result" + ); + } + + #[test] + fn terminal_schedule_failure_is_not_reported_as_pending() { + let voter_id = Identifier::from([7; 32]); + let mut operation = AppContext::new_dpns_vote_operation(vec![ + crate::model::dpns_voting::DpnsVoteTarget { + key: crate::model::dpns_voting::DpnsVoteTargetKey { + network: Network::Testnet, + voter_id, + vote_poll_id: Identifier::from([8; 32]), + }, + voter_alias: Some("Eve".to_owned()), + contested_name: "dominguez".to_owned(), + requested_choice: dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Scheduled(42), + }, + ]); + for status in [ + DpnsVoteTargetStatus::FailedBeforeSubmission, + DpnsVoteTargetStatus::Rejected, + DpnsVoteTargetStatus::NotApplied, + ] { + operation.targets[0].status = status; + assert_eq!( + scheduled_vote_journal_summary( + std::slice::from_ref(&operation), + voter_id, + &BTreeSet::new() + ), + (false, true), + "{status:?} must remain actionable" + ); + let dismissed = + BTreeSet::from([(operation.id, operation.targets[0].target.key.clone())]); + assert_eq!( + scheduled_vote_journal_summary( + std::slice::from_ref(&operation), + voter_id, + &dismissed + ), + (false, false) + ); + } + } + + #[test] + fn cancelled_schedule_is_not_reported_as_failed() { + let voter_id = Identifier::from([7; 32]); + let mut operation = AppContext::new_dpns_vote_operation(vec![ + crate::model::dpns_voting::DpnsVoteTarget { + key: crate::model::dpns_voting::DpnsVoteTargetKey { + network: Network::Testnet, + voter_id, + vote_poll_id: Identifier::from([8; 32]), + }, + voter_alias: Some("Eve".to_owned()), + contested_name: "dominguez".to_owned(), + requested_choice: dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Scheduled(42), + }, + ]); + operation.targets[0].status = DpnsVoteTargetStatus::Cancelled; + + assert_eq!( + scheduled_vote_journal_summary(&[operation], voter_id, &BTreeSet::new()), + (false, false) + ); + } + + #[test] + fn later_success_supersedes_historical_schedule_failure() { + let voter_id = Identifier::from([7; 32]); + let target = crate::model::dpns_voting::DpnsVoteTarget { + key: crate::model::dpns_voting::DpnsVoteTargetKey { + network: Network::Testnet, + voter_id, + vote_poll_id: Identifier::from([8; 32]), + }, + voter_alias: Some("Eve".to_owned()), + contested_name: "dominguez".to_owned(), + requested_choice: + dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Scheduled(42), }; - let cn = stored.to_contested_name(Network::Testnet); - let me = Identifier::from([5u8; 32]); - assert!(pending_username_in(std::slice::from_ref(&cn), &me).is_none()); + let mut failed = AppContext::new_dpns_vote_operation(vec![target.clone()]); + failed.created_at = 1; + failed.targets[0].status = DpnsVoteTargetStatus::Rejected; + let mut confirmed = AppContext::new_dpns_vote_operation(vec![target]); + confirmed.created_at = 2; + confirmed.targets[0].status = DpnsVoteTargetStatus::Confirmed; + + assert_eq!( + scheduled_vote_journal_summary(&[failed, confirmed], voter_id, &BTreeSet::new()), + (false, false) + ); + } + + /// Counts reads of the keys a summary pass touches, so a test can prove how + /// many loads a caller performs. `snapshot_reads` counts the per-node + /// current-vote snapshot (`current_votes_key`); `shared_reads` counts the + /// contest cache and operation journal, which do not depend on the node. + #[derive(Default)] + struct CurrentVotesReadCounter { + inner: InMemoryKv, + snapshot_reads: AtomicUsize, + shared_reads: AtomicUsize, + } + + impl KvStore for CurrentVotesReadCounter { + fn get(&self, scope: &ObjectId, key: &str) -> Result>, KvError> { + if key.starts_with("det:dpns_current_votes:v3:") { + self.snapshot_reads.fetch_add(1, Ordering::Relaxed); + } + if key.starts_with(CONTESTED_NAME_KEY_PREFIX) + || key.starts_with("det:dpns_vote_operation:v2:") + { + self.shared_reads.fetch_add(1, Ordering::Relaxed); + } + self.inner.get(scope, key) + } + + fn put(&self, scope: &ObjectId, key: &str, value: &[u8]) -> Result<(), KvError> { + self.inner.put(scope, key, value) + } + + fn delete(&self, scope: &ObjectId, key: &str) -> Result<(), KvError> { + self.inner.delete(scope, key) + } + + fn list_keys( + &self, + scope: &ObjectId, + prefix: Option<&str>, + ) -> Result, KvError> { + self.inner.list_keys(scope, prefix) + } + } + + /// VOTE-NFR-007 / VOTE-TC-005: the masternode-card summary reads a node's + /// proved current-vote snapshot once, not once per open contest. + #[test] + fn masternode_summary_reads_current_votes_once_per_node() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let store = Arc::new(CurrentVotesReadCounter::default()); + let kv = DetKv::from_store(store.clone()); + let context = crate::context::test_support::test_app_context_with_kv( + temp_dir.path(), + Arc::new(kv.clone()), + ); + context.set_det_kv_override_for_test(kv.clone()); + + let voter = Identifier::from([1; 32]); + + // Seed several open (Ongoing) contests: a contestant dated in the deep + // past pushes each contest past the joinable half-window, and a missing + // `end_time` keeps it in the ongoing set. + for name in ["alice", "bob", "carol", "dave", "erin"] { + let stored = StoredContestedName { + normalized_contested_name: name.to_string(), + contestants: vec![contestant(1, Some(1))], + ..Default::default() + }; + kv.put(DetScope::Global, &contested_name_key(name), &stored) + .unwrap(); + } + + // Seed a proved snapshot so each summary read decodes a real record. + context + .cache_confirmed_dpns_vote( + voter, + Identifier::from([9; 32]), + dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice::Abstain, + ) + .expect("seed current-vote snapshot"); + + let before = store.snapshot_reads.load(Ordering::Relaxed); + let summary = context + .masternode_contest_summary(Some(voter)) + .expect("summary"); + let reads = store.snapshot_reads.load(Ordering::Relaxed) - before; + + assert_eq!(summary.open_contest_count, 5); + assert_eq!( + reads, 1, + "expected one snapshot read per node, got {reads} for 5 open contests" + ); + } + + /// The contest cache and the operation journal do not depend on the node, so + /// summarising a fleet must read them once — not once per card. + #[test] + fn masternode_summaries_read_node_independent_state_once_for_the_whole_fleet() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let store = Arc::new(CurrentVotesReadCounter::default()); + let kv = DetKv::from_store(store.clone()); + let context = crate::context::test_support::test_app_context_with_kv( + temp_dir.path(), + Arc::new(kv.clone()), + ); + context.set_det_kv_override_for_test(kv.clone()); + + for name in ["alice", "bob", "carol"] { + let stored = StoredContestedName { + normalized_contested_name: name.to_string(), + contestants: vec![contestant(1, Some(1))], + ..Default::default() + }; + kv.put(DetScope::Global, &contested_name_key(name), &stored) + .unwrap(); + } + let mut operation = + AppContext::new_dpns_vote_operation(vec![crate::model::dpns_voting::DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: context.dpns_vote_poll_id("alice").unwrap(), + }, + voter_alias: None, + contested_name: "alice".into(), + requested_choice: + dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Scheduled(42), + }]); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + + let voters: Vec = (1..=8).map(|byte| Identifier::from([byte; 32])).collect(); + let before = store.shared_reads.load(Ordering::Relaxed); + let summaries = context + .masternode_contest_summaries(&voters) + .expect("fleet summaries"); + let reads = store.shared_reads.load(Ordering::Relaxed) - before; + + assert_eq!(summaries.len(), voters.len()); + assert_eq!( + reads, + 4, + "expected one read of each of the 3 contests and 1 journal record for the whole \ + fleet, got {reads} for {} nodes", + voters.len() + ); } } diff --git a/src/context/dpns_vote_attention.rs b/src/context/dpns_vote_attention.rs new file mode 100644 index 000000000..5b73f8377 --- /dev/null +++ b/src/context/dpns_vote_attention.rs @@ -0,0 +1,551 @@ +//! The voting attention signal: which open contests still need a decision +//! from the operator's node set, and how many targets are unresolved. +//! +//! Recomputed on refresh and on coordinator updates, cached for the per-frame +//! readers (top-bar chip, Masternodes badge). + +use super::AppContext; +use crate::backend_task::error::TaskError; +use crate::model::dpns_voting::operator::{ + AttentionSummary, ChangesLeft, ContestAttention, ListMembership, NodeVoteRow, VotingNode, + changes_left, contest_needs_decision, +}; +use crate::model::dpns_voting::{ + DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOutcome, DpnsVotePollAvailability, + DpnsVoteTargetKey, DpnsVoteTargetStatus, authoritative_dpns_vote_outcomes, + dpns_vote_lock_holders, dpns_vote_poll_availability, +}; +use crate::model::qualified_identity::QualifiedIdentity; +use crate::utils::time::now_ms; +use dash_sdk::dpp::identity::accessors::IdentityGettersV0; +use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use dash_sdk::platform::Identifier; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +/// Distinct targets whose authoritative outcome is still `Unconfirmed`. +pub(crate) fn unresolved_target_count(operations: &[DpnsVoteOperation]) -> usize { + authoritative_dpns_vote_outcomes(operations, |_| true) + .values() + .filter(|(_, outcome)| outcome.status == DpnsVoteTargetStatus::Unconfirmed) + .count() +} + +impl AppContext { + /// The latest attention summary (cheap; safe to call every frame). + pub fn dpns_vote_attention(&self) -> Arc { + Arc::clone( + &self + .dpns_vote_attention + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner), + ) + } + + /// Live durable journal progress (cheap; safe to call every frame). + pub fn dpns_vote_progress(&self) -> Arc<[Arc]> { + Arc::clone( + &self + .dpns_vote_progress + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner), + ) + } + + /// Ask the voting panel to reopen the confirm step for one failed target + /// (`Review again` in the progress drawer). + pub fn request_dpns_vote_review(&self, outcome: DpnsVoteOutcome) { + *self + .dpns_vote_review_request + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(outcome); + } + + /// Take a pending `Review again` request, if any. + pub fn take_dpns_vote_review_request(&self) -> Option { + self.dpns_vote_review_request + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + } + + /// Ask the voting panel to show one contest, filtered to its normalized + /// label. Pair with + /// `AppAction::SetMainScreenThenGoToMainScreen(RootScreenDPNSActiveContests)`. + pub fn request_dpns_votes_for_name(&self, normalized_label: String) { + *self + .dpns_votes_name_request + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(normalized_label); + } + + /// Dismiss settled operations from the progress drawer and the + /// `Needs attention` row for this session. + pub fn dismiss_dpns_vote_operations( + &self, + ids: impl IntoIterator, + ) { + self.dpns_dismissed_vote_operations + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .extend(ids); + } + + /// Operations dismissed in the progress drawer this session. + pub fn dismissed_dpns_vote_operations( + &self, + ) -> std::collections::BTreeSet { + self.dpns_dismissed_vote_operations + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } + + /// Take a pending show-one-contest request, if any. + pub fn take_dpns_votes_name_request(&self) -> Option { + self.dpns_votes_name_request + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + } + + /// Record that a contest + vote-state refresh just completed. + pub(crate) fn mark_dpns_contests_refreshed(&self) { + self.dpns_contests_refreshed_at_ms + .store(now_ms(), std::sync::atomic::Ordering::Relaxed); + } + + /// When the last contest + vote-state refresh completed (Unix ms). + pub fn dpns_contests_refreshed_at_ms(&self) -> Option { + match self + .dpns_contests_refreshed_at_ms + .load(std::sync::atomic::Ordering::Relaxed) + { + 0 => None, + at => Some(at), + } + } + + /// Replace the masternode-list membership snapshot (`None`: list unavailable). + pub(crate) fn set_masternode_list_membership( + &self, + membership: Option>, + ) { + *self + .masternode_list_membership + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = membership.map(Arc::new); + } + + /// Re-read masternode-list membership from the SPV list. A list that is + /// temporarily unavailable keeps the last known snapshot. + pub(crate) async fn refresh_masternode_list_membership(&self) { + let Ok(backend) = self.wallet_backend() else { + return; + }; + match backend.masternode_list_membership().await { + Some(membership) => self.set_masternode_list_membership(Some(membership)), + None => tracing::debug!("Masternode list unavailable; keeping the last membership"), + } + } + + /// Drop vote counts for polls the contest cache proves closed. + pub(crate) fn forget_closed_dpns_vote_counts(&self) { + let closed: BTreeSet = self + .all_contested_names() + .unwrap_or_default() + .iter() + .filter(|contest| { + dpns_vote_poll_availability(Some(contest)) == DpnsVotePollAvailability::ProvedClosed + }) + .filter_map(|contest| { + self.dpns_vote_poll_id(&contest.normalized_contested_name) + .ok() + }) + .collect(); + if let Err(error) = self.forget_dpns_vote_counts(&closed) { + tracing::debug!( + ?error, + "Closed-contest vote counts will be pruned on the next refresh" + ); + } + } + + /// Whether `node_id` is in the current masternode list, as far as DET knows. + pub fn masternode_list_membership(&self, node_id: Identifier) -> ListMembership { + match self + .masternode_list_membership + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_deref() + { + None => ListMembership::Unknown, + Some(list) if list.contains_key(&node_id) => ListMembership::Listed, + Some(_) => ListMembership::NotListed, + } + } + + /// One loaded masternode/evonode as the node-set resolver sees it. + pub fn dpns_voting_node(&self, identity: &QualifiedIdentity) -> VotingNode { + let id = identity.identity.id(); + VotingNode { + id, + kind: identity.identity_type.into(), + has_voting_key: identity.can_cast_masternode_vote(), + membership: self.masternode_list_membership(id), + alias: identity.alias.clone(), + } + } + + /// Every loaded masternode/evonode as the node-set resolver sees it. + pub fn dpns_voting_nodes(&self) -> Result, TaskError> { + Ok(self + .load_local_masternode_identities()? + .iter() + .map(|identity| self.dpns_voting_node(identity)) + .collect()) + } + + /// Every open contest with this node's proved choice and changes left, + /// soonest deadline first (VOTE-FR-076). + pub fn dpns_node_votes(&self, node_id: Identifier) -> Result, TaskError> { + let now = now_ms(); + let contests: Vec<(crate::model::contested_name::ContestedName, Identifier)> = self + .ongoing_contested_names()? + .into_iter() + .filter(|contest| contest.end_time.is_none_or(|end| end > now)) + .filter_map(|contest| { + let poll = self + .dpns_vote_poll_id(&contest.normalized_contested_name) + .ok()?; + Some((contest, poll)) + }) + .collect(); + let states = self + .dpns_current_vote_states(node_id, contests.iter().map(|(_, poll)| *poll)) + .unwrap_or_default(); + let mut rows: Vec = contests + .into_iter() + .map(|(contest, poll)| { + let state = states + .get(&poll) + .copied() + .unwrap_or(DpnsCurrentVoteState::Unavailable); + let choice = match state { + DpnsCurrentVoteState::Available(choice) => choice, + _ => None, + }; + let contender_name = match choice { + Some(ResourceVoteChoice::TowardsIdentity(id)) => contest + .contestants + .iter() + .flatten() + .find(|contender| contender.id == id) + .map(|contender| contender.name.clone()), + _ => None, + }; + NodeVoteRow { + contested_name: contest.normalized_contested_name, + choice, + contender_name, + state_known: matches!(state, DpnsCurrentVoteState::Available(_)), + changes: self.dpns_changes_left(node_id, poll, state), + end_time: contest.end_time, + } + }) + .collect(); + rows.sort_by_key(|row| (row.end_time.unwrap_or(u64::MAX), row.contested_name.clone())); + Ok(rows) + } + + /// Changes left for one node × poll given its proved state. + pub fn dpns_changes_left( + &self, + voter_id: Identifier, + vote_poll_id: Identifier, + state: DpnsCurrentVoteState, + ) -> ChangesLeft { + let count = self + .dpns_vote_count(voter_id, vote_poll_id) + .inspect_err(|error| { + tracing::debug!(?error, %voter_id, "Vote count unavailable; changes left unknown"); + }) + .ok(); + match count { + Some(count) => changes_left( + count, + matches!(state, DpnsCurrentVoteState::Available(Some(_))), + ), + None => ChangesLeft::Unknown, + } + } + + /// Recompute and cache the attention summary from the contest cache, the + /// proved vote state, the journal and the saved node set. + /// + /// Storage failures keep the previous summary rather than signalling + /// nothing. + pub fn recompute_dpns_vote_attention(&self) -> Arc { + let operations = match self.dpns_vote_operations() { + Ok(operations) => operations, + Err(error) => { + tracing::debug!(?error, "Keeping the previous voting attention and progress"); + return self.dpns_vote_attention(); + } + }; + match self.compute_dpns_vote_attention(&operations) { + Ok(summary) => { + let summary = Arc::new(summary); + *self + .dpns_vote_attention + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::clone(&summary); + summary + } + Err(error) => { + tracing::debug!(?error, "Keeping the previous voting attention summary"); + self.dpns_vote_attention() + } + } + } + + fn compute_dpns_vote_attention( + &self, + operations: &[DpnsVoteOperation], + ) -> Result { + let resolved = self + .saved_dpns_node_set() + .unwrap_or_default() + .resolve(&self.dpns_voting_nodes()?); + Ok(AttentionSummary::new( + &self.dpns_contest_attention(&resolved.included, operations)?, + unresolved_target_count(operations), + resolved.included.len(), + )) + } + + /// Every open contest and whether one of `voters` still has to decide on it. + fn dpns_contest_attention( + &self, + voters: &[Identifier], + operations: &[DpnsVoteOperation], + ) -> Result, TaskError> { + let now = now_ms(); + let contests: Vec<(String, Option, Identifier)> = self + .ongoing_contested_names()? + .into_iter() + .filter(|contest| contest.end_time.is_none_or(|end| end > now)) + .filter_map(|contest| { + let poll = self + .dpns_vote_poll_id(&contest.normalized_contested_name) + .ok()?; + Some((contest.normalized_contested_name, contest.end_time, poll)) + }) + .collect(); + let polls: Vec = contests.iter().map(|(_, _, poll)| *poll).collect(); + let mut states = BTreeMap::new(); + for voter in voters { + let voter_states = self + .dpns_current_vote_states(*voter, polls.iter().copied()) + .unwrap_or_default(); + states.insert(*voter, voter_states); + } + + let network = self.network(); + Ok(contests + .into_iter() + .map(|(name, end_time, poll)| { + let needs_decision = contest_needs_decision(voters.iter().map(|voter| { + let state = states + .get(voter) + .and_then(|voter_states| voter_states.get(&poll)) + .copied() + .unwrap_or(DpnsCurrentVoteState::Unavailable); + let key = DpnsVoteTargetKey { + network, + voter_id: *voter, + vote_poll_id: poll, + }; + let locked = dpns_vote_lock_holders(operations, &key).next().is_some(); + (state, locked, self.dpns_changes_left(*voter, poll, state)) + })); + ContestAttention { + name, + end_time, + needs_decision, + } + }) + .collect()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::dpns_voting::{DpnsVoteTarget, VoteTiming}; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; + + fn operation(poll: u8, status: DpnsVoteTargetStatus, created_at: u64) -> DpnsVoteOperation { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([poll; 32]), + }, + voter_alias: None, + contested_name: format!("name-{poll}"), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Now, + }]); + operation.targets[0].status = status; + operation.created_at = created_at; + operation + } + + /// VOTE-TC-087 (count half): only targets whose authoritative outcome is + /// still unconfirmed count, once each. + #[test] + fn unresolved_count_follows_the_authoritative_outcome() { + let operations = vec![ + operation(2, DpnsVoteTargetStatus::Unconfirmed, 1), + operation(3, DpnsVoteTargetStatus::Unconfirmed, 1), + operation(3, DpnsVoteTargetStatus::Unconfirmed, 2), + operation(4, DpnsVoteTargetStatus::Confirmed, 1), + ]; + assert_eq!(unresolved_target_count(&operations), 2); + assert_eq!(unresolved_target_count(&[]), 0); + } + + #[test] + fn unresolved_count_preserves_authority_order_for_competing_outcomes() { + use crate::model::dpns_voting::DpnsVoteOperationId; + use DpnsVoteTargetStatus::{Confirmed, Scheduled, Unconfirmed}; + + for (first_status, first_time, second_status, second_time, expected) in [ + (Unconfirmed, 1, Confirmed, 2, 1), + (Scheduled, 1, Unconfirmed, 2, 1), + (Unconfirmed, 2, Scheduled, 1, 1), + (Unconfirmed, 1, Scheduled, 1, 0), + (Scheduled, 1, Unconfirmed, 1, 1), + ] { + let mut first = operation(2, first_status, first_time); + first.id = DpnsVoteOperationId::from_bytes([1; 16]); + first.targets[0].operation_id = first.id; + let mut second = operation(2, second_status, second_time); + second.id = DpnsVoteOperationId::from_bytes([2; 16]); + second.targets[0].operation_id = second.id; + let mut operations = vec![first, second]; + assert_eq!(unresolved_target_count(&operations), expected); + operations.reverse(); + assert_eq!(unresolved_target_count(&operations), expected); + } + } + + #[test] + fn unresolved_count_handles_bulk_operations_and_distinct_nodes() { + let mut bulk = operation(2, DpnsVoteTargetStatus::Confirmed, 1); + for poll in 3..=100 { + let mut outcome = bulk.targets[0].clone(); + outcome.target.key.vote_poll_id = Identifier::from([poll; 32]); + bulk.targets.push(outcome); + } + let first_node = operation(2, DpnsVoteTargetStatus::Unconfirmed, 2); + let mut second_node = first_node.clone(); + second_node.targets[0].target.key.voter_id = Identifier::from([2; 32]); + assert_eq!(unresolved_target_count(&[bulk.clone()]), 0); + assert_eq!(unresolved_target_count(&[bulk, first_node, second_node]), 2); + } + + /// VOTE-TC-094 (node detail half): the node's votes list every open + /// contest with its proved choice, contender and changes left. + #[test] + fn node_votes_list_open_contests_with_choice_and_changes() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let kv = crate::wallet_backend::DetKv::from_store(Arc::new( + crate::wallet_backend::kv_test_support::InMemoryKv::default(), + )); + let context = crate::context::test_support::test_app_context_with_kv( + temp_dir.path(), + Arc::new(kv.clone()), + ); + context.set_det_kv_override_for_test(kv); + context.seed_dpns_contest_for_test("beta", Some(now_ms() + 600_000), false); + context.seed_dpns_contest_for_test("alpha", Some(now_ms() + 60_000), false); + let node = Identifier::from([1; 32]); + let alpha = context.dpns_vote_poll_id("alpha").unwrap(); + let contender = ResourceVoteChoice::TowardsIdentity(Identifier::from([3; 32])); + context + .cache_confirmed_dpns_vote(node, alpha, contender) + .unwrap(); + + let rows = context.dpns_node_votes(node).unwrap(); + assert_eq!( + rows.iter() + .map(|row| row.contested_name.as_str()) + .collect::>(), + vec!["alpha", "beta"], + "soonest deadline first" + ); + assert_eq!(rows[0].choice, Some(contender)); + assert_eq!(rows[0].contender_name.as_deref(), Some("alpha")); + assert!(rows[0].state_known); + assert_eq!( + rows[0].changes, + ChangesLeft::Unknown, + "a proved vote this device never counted" + ); + } + + /// The background refresh runs minutes apart; a contest must keep needing + /// a vote in between, long after the proof is too old to submit with. + #[test] + fn a_contest_keeps_needing_a_vote_between_background_refreshes() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let kv = crate::wallet_backend::DetKv::from_store(Arc::new( + crate::wallet_backend::kv_test_support::InMemoryKv::default(), + )); + let context = crate::context::test_support::test_app_context_with_kv( + temp_dir.path(), + Arc::new(kv.clone()), + ); + context.set_det_kv_override_for_test(kv); + context.seed_dpns_contest_for_test("alpha", Some(now_ms() + 600_000), false); + let node = Identifier::from([1; 32]); + let four_minutes_ago = now_ms() - 240_000; + context + .seed_proved_dpns_votes_at_for_test(node, BTreeMap::new(), four_minutes_ago) + .unwrap(); + + let attention = context.dpns_contest_attention(&[node], &[]).unwrap(); + assert_eq!(attention.len(), 1); + assert!( + attention[0].needs_decision, + "a proved not-voted node must keep the contest in the attention signal" + ); + let summary = AttentionSummary::new(&attention, 0, 1); + assert_eq!(summary.needs_decision, 1); + assert!(summary.soonest_end.is_some()); + } + + #[test] + fn membership_is_unknown_until_the_list_is_available() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp_dir.path()); + let listed = Identifier::from([1; 32]); + assert_eq!( + context.masternode_list_membership(listed), + ListMembership::Unknown + ); + context.set_masternode_list_membership(Some(BTreeMap::from([(listed, true)]))); + assert_eq!( + context.masternode_list_membership(listed), + ListMembership::Listed + ); + assert_eq!( + context.masternode_list_membership(Identifier::from([2; 32])), + ListMembership::NotListed + ); + } +} diff --git a/src/context/dpns_vote_operations/counts.rs b/src/context/dpns_vote_operations/counts.rs new file mode 100644 index 000000000..02c8b4a06 --- /dev/null +++ b/src/context/dpns_vote_operations/counts.rs @@ -0,0 +1,243 @@ +//! Durable count of votes this device saw Platform apply, per node × poll. +//! +//! Journal history is pruned, so "changes left" cannot be counted from it. The +//! count lives in its own namespace, survives pruning, and is dropped only for +//! polls proven closed. + +use super::keys::{operation_err, unreadable_operation_err}; +use crate::backend_task::error::TaskError; +use crate::model::dpns_voting::{ + DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, DpnsVoteTargetStatus, +}; +use crate::wallet_backend::{DetKv, DetScope, network_prefix}; +use dash_sdk::dpp::dashcore::Network; +use dash_sdk::platform::Identifier; + +const VOTE_COUNT_KEY_PREFIX: &str = "det:dpns_vote_counts:v1:"; +/// The operation whose confirmed vote was last added to a node × poll count. +const COUNTED_OPERATION_KEY_PREFIX: &str = "det:dpns_vote_counted:v1:"; + +fn count_key_prefix(network: Network) -> String { + format!("{VOTE_COUNT_KEY_PREFIX}{}:", network_prefix(network)) +} + +fn count_key(network: Network, voter_id: Identifier, vote_poll_id: Identifier) -> String { + format!("{}{voter_id}:{vote_poll_id}", count_key_prefix(network)) +} + +fn counted_operation_key_prefix(network: Network) -> String { + format!("{COUNTED_OPERATION_KEY_PREFIX}{}:", network_prefix(network)) +} + +fn counted_operation_key(key: &DpnsVoteTargetKey) -> String { + format!( + "{}{}:{}", + counted_operation_key_prefix(key.network), + key.voter_id, + key.vote_poll_id + ) +} + +/// Whether moving `previous` → `next` records a vote Platform applied. +/// +/// Only a broadcast target (Confirming or Unconfirmed) that becomes Confirmed +/// spent a vote; a queued target confirmed as an exact no-op did not. +fn spent_a_vote(previous: Option, next: DpnsVoteTargetStatus) -> bool { + next == DpnsVoteTargetStatus::Confirmed + && matches!( + previous, + Some(DpnsVoteTargetStatus::Confirming | DpnsVoteTargetStatus::Unconfirmed) + ) +} + +/// Targets of `next` that spent a vote relative to the stored `previous` record. +pub(super) fn newly_spent_targets<'a>( + previous: Option<&DpnsVoteOperation>, + next: &'a DpnsVoteOperation, +) -> Vec<&'a DpnsVoteTargetKey> { + next.targets + .iter() + .filter(|outcome| { + let before = previous + .and_then(|operation| operation.outcome(&outcome.target.key)) + .map(|previous| previous.status); + spent_a_vote(before, outcome.status) + }) + .map(|outcome| &outcome.target.key) + .collect() +} + +/// Add the vote `operation_id` spent on `key`, unless it is already counted. +/// +/// Callers hold the journal guard and bump before persisting the transition. +/// When that write fails the target is confirmed, and reaches here, a second +/// time; the recorded operation keeps the same vote from counting twice. One +/// record per node × poll is enough: an unresolved target holds its lock, so +/// no other operation can confirm on it in between. +/// +/// The count is written before the record of who was counted, so a failure +/// between the two over-counts, which understates changes left instead of +/// overstating them. +pub(super) fn bump_vote_count( + kv: &DetKv, + key: &DpnsVoteTargetKey, + operation_id: DpnsVoteOperationId, +) -> Result<(), TaskError> { + let counted_key = counted_operation_key(key); + let counted: Option<[u8; 16]> = kv + .get(DetScope::Global, &counted_key) + .map_err(unreadable_operation_err)?; + if counted == Some(operation_id.to_bytes()) { + return Ok(()); + } + let storage_key = count_key(key.network, key.voter_id, key.vote_poll_id); + let count: u8 = kv + .get(DetScope::Global, &storage_key) + .map_err(unreadable_operation_err)? + .unwrap_or(0); + kv.put(DetScope::Global, &storage_key, &count.saturating_add(1)) + .map_err(operation_err)?; + kv.put(DetScope::Global, &counted_key, &operation_id.to_bytes()) + .map_err(operation_err) +} + +/// Votes this device saw applied for one node × poll; `None` without a record. +pub(super) fn vote_count( + kv: &DetKv, + network: Network, + voter_id: Identifier, + vote_poll_id: Identifier, +) -> Result, TaskError> { + kv.get( + DetScope::Global, + &count_key(network, voter_id, vote_poll_id), + ) + .map_err(unreadable_operation_err) +} + +/// Forget the counts of every poll in `closed_polls`. +pub(super) fn forget_vote_counts( + kv: &DetKv, + network: Network, + closed_polls: &std::collections::BTreeSet, +) -> Result { + if closed_polls.is_empty() { + return Ok(0); + } + let suffixes: Vec = closed_polls.iter().map(|poll| format!(":{poll}")).collect(); + let mut removed = 0; + for (prefix, is_count) in [ + (count_key_prefix(network), true), + (counted_operation_key_prefix(network), false), + ] { + for key in kv + .list(DetScope::Global, Some(&prefix)) + .map_err(unreadable_operation_err)? + { + if suffixes.iter().any(|suffix| key.ends_with(suffix.as_str())) { + kv.delete(DetScope::Global, &key).map_err(operation_err)?; + removed += usize::from(is_count); + } + } + } + Ok(removed) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::context::AppContext; + use crate::model::dpns_voting::{DpnsVoteTarget, VoteTiming}; + use crate::wallet_backend::kv_test_support::InMemoryKv; + use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; + use std::collections::BTreeSet; + use std::sync::Arc; + + fn key(poll: u8) -> DpnsVoteTargetKey { + DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([poll; 32]), + } + } + + fn operation(status: DpnsVoteTargetStatus) -> DpnsVoteOperation { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: key(2), + voter_alias: None, + contested_name: "alice".to_owned(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Now, + }]); + operation.targets[0].status = status; + operation + } + + #[test] + fn only_a_broadcast_target_that_confirms_spends_a_vote() { + use DpnsVoteTargetStatus::*; + assert!(spent_a_vote(Some(Confirming), Confirmed)); + assert!(spent_a_vote(Some(Unconfirmed), Confirmed)); + assert!(!spent_a_vote(Some(Queued), Confirmed), "exact no-op"); + assert!(!spent_a_vote(Some(Confirmed), Confirmed), "already counted"); + assert!(!spent_a_vote(None, Confirmed), "migrated legacy record"); + assert!(!spent_a_vote(Some(Unconfirmed), NotApplied)); + } + + #[test] + fn newly_spent_targets_compare_against_the_stored_record() { + let before = operation(DpnsVoteTargetStatus::Confirming); + let mut after = before.clone(); + after.targets[0].status = DpnsVoteTargetStatus::Confirmed; + assert_eq!(newly_spent_targets(Some(&before), &after), vec![&key(2)]); + assert!(newly_spent_targets(Some(&after), &after).is_empty()); + assert!(newly_spent_targets(None, &after).is_empty()); + } + + #[test] + fn counts_accumulate_saturate_and_are_forgotten_for_closed_polls() { + let kv = DetKv::from_store(Arc::new(InMemoryKv::default())); + let network = Network::Testnet; + let voter = Identifier::from([1; 32]); + assert_eq!( + vote_count(&kv, network, voter, Identifier::from([2; 32])).unwrap(), + None + ); + for operation in 1..=3 { + let id = DpnsVoteOperationId::from_bytes([operation; 16]); + bump_vote_count(&kv, &key(2), id).unwrap(); + bump_vote_count(&kv, &key(2), id).unwrap(); + } + bump_vote_count(&kv, &key(3), DpnsVoteOperationId::from_bytes([3; 16])).unwrap(); + assert_eq!( + vote_count(&kv, network, voter, Identifier::from([2; 32])).unwrap(), + Some(3) + ); + assert_eq!( + vote_count(&kv, Network::Mainnet, voter, Identifier::from([2; 32])).unwrap(), + None, + "counts are network-scoped" + ); + + let removed = + forget_vote_counts(&kv, network, &BTreeSet::from([Identifier::from([2; 32])])).unwrap(); + assert_eq!(removed, 1); + assert_eq!( + vote_count(&kv, network, voter, Identifier::from([2; 32])).unwrap(), + None + ); + assert_eq!( + kv.list(DetScope::Global, Some(COUNTED_OPERATION_KEY_PREFIX)) + .unwrap() + .len(), + 1, + "a closed poll keeps no record of who was counted" + ); + assert_eq!( + vote_count(&kv, network, voter, Identifier::from([3; 32])).unwrap(), + Some(1), + "open polls keep their count" + ); + } +} diff --git a/src/context/dpns_vote_operations/keys.rs b/src/context/dpns_vote_operations/keys.rs new file mode 100644 index 000000000..f3342d24a --- /dev/null +++ b/src/context/dpns_vote_operations/keys.rs @@ -0,0 +1,73 @@ +//! Key schema for the DPNS vote journal's k/v namespaces. +//! +//! Every key the journal owns is built here so the on-disk layout has one definition. + +use crate::backend_task::error::TaskError; +use crate::model::dpns_voting::DpnsVoteOperationId; +use crate::wallet_backend::{KvAdapterError, network_prefix}; +use dash_sdk::dpp::dashcore::Network; + +pub(super) const OPERATION_INDEX_KEY_PREFIX: &str = "det:dpns_vote_operations:v2:"; +pub(super) const OPERATION_KEY_PREFIX: &str = "det:dpns_vote_operation:v2:"; +pub(super) const OPERATION_LOCK_INDEX_KEY_PREFIX: &str = "det:dpns_vote_operation_locks:v2:"; +pub(super) const OPERATION_LOCK_INDEX_DIRTY_KEY_PREFIX: &str = + "det:dpns_vote_operation_locks_dirty:v2:"; + +pub(super) const RELATIVE_LABEL_KEY_PREFIX: &str = "det:dpns_vote_relative_labels:v1:"; +pub(super) const RECOVERY_TIME_KEY_PREFIX: &str = "det:dpns_vote_recovery_times:v1:"; + +pub(super) const SCHEDULE_DISMISSAL_KEY_PREFIX: &str = "det:dpns_vote_schedule_dismissals:v1:"; +pub(super) const IMMEDIATE_HISTORY_KEY_PREFIX: &str = "det:dpns_vote_immediate_history:v1:"; +pub(super) const SCHEDULED_HISTORY_KEY_PREFIX: &str = "det:dpns_vote_scheduled_history:v1:"; + +pub(super) fn operation_index_key(network: Network) -> String { + format!("{OPERATION_INDEX_KEY_PREFIX}{}", network_prefix(network)) +} + +pub(super) fn operation_key(network: Network, id: DpnsVoteOperationId) -> String { + format!("{OPERATION_KEY_PREFIX}{}:{id}", network_prefix(network)) +} + +pub(super) fn operation_key_prefix(network: Network) -> String { + format!("{OPERATION_KEY_PREFIX}{}:", network_prefix(network)) +} + +pub(super) fn schedule_dismissal_key(network: Network, id: DpnsVoteOperationId) -> String { + format!( + "{SCHEDULE_DISMISSAL_KEY_PREFIX}{}:{id}", + network_prefix(network) + ) +} + +pub(super) fn operation_lock_index_key(network: Network) -> String { + format!( + "{OPERATION_LOCK_INDEX_KEY_PREFIX}{}", + network_prefix(network) + ) +} + +pub(super) fn operation_lock_index_dirty_key(network: Network) -> String { + format!( + "{OPERATION_LOCK_INDEX_DIRTY_KEY_PREFIX}{}", + network_prefix(network) + ) +} + +pub(super) fn operation_err(source: KvAdapterError) -> TaskError { + TaskError::DpnsVoteOperationStorage { source } +} + +pub(super) fn unreadable_operation_err(source: KvAdapterError) -> TaskError { + TaskError::DpnsVoteOperationUnreadable { source } +} + +/// One display record per operation, owned by the same retention lifecycle. +pub(super) fn relative_labels_key(operation_key: &str) -> String { + operation_key.replacen(OPERATION_KEY_PREFIX, RELATIVE_LABEL_KEY_PREFIX, 1) +} + +/// When restart recovery picked up an operation's immediate targets; one +/// display record per operation, owned by the same retention lifecycle. +pub(super) fn recovery_times_key(operation_key: &str) -> String { + operation_key.replacen(OPERATION_KEY_PREFIX, RECOVERY_TIME_KEY_PREFIX, 1) +} diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs new file mode 100644 index 000000000..13d5b5c42 --- /dev/null +++ b/src/context/dpns_vote_operations/mod.rs @@ -0,0 +1,2855 @@ +//! Durable DPNS vote operation journal and exact-target lock registry. + +mod counts; +mod keys; +mod retention; +mod transitions; + +pub(super) use retention::{dismiss_confirmed_scheduled_targets, prune_terminal_operations}; + +use keys::*; +use retention::*; +use transitions::*; + +use super::AppContext; +use crate::backend_task::error::TaskError; +use crate::model::dpns_voting::{ + DpnsCurrentVoteState, DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome, + DpnsScheduledVoteEdit, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, + DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, + VoteTiming, authoritative_dpns_vote_outcomes, failed_before_broadcast_outcome, + unavailable_preflight_outcome, +}; +use crate::utils::time::now_ms; +use crate::wallet_backend::{DetKv, DetScope}; +use dash_sdk::dpp::dashcore::Network; +use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +const DPNS_VOTE_DIAGNOSTIC_LIMIT: usize = 256; + +type DpnsVoteLockIndex = BTreeMap; +type DpnsVoteDiagnosticMap = + BTreeMap<(DpnsVoteOperationId, DpnsVoteTargetKey), (u64, Arc)>; + +type RelativeSchedulePresets = BTreeMap; + +/// How many times each voter was loaded again after a removal in this session. +pub(crate) type DpnsVoterLifecycles = BTreeMap; + +/// Display metadata never changes the interpretation of a vote record or its locks. +fn load_operation( + kv: &DetKv, + key: &str, +) -> Result, crate::wallet_backend::KvAdapterError> { + let Some(mut operation) = kv.get::(DetScope::Global, key)? else { + return Ok(None); + }; + match kv.get::(DetScope::Global, &relative_labels_key(key)) { + Ok(Some(labels)) => { + for outcome in &mut operation.targets { + if let VoteTiming::Scheduled(at) = outcome.target.timing + && let Some(&(recorded_at, preset)) = labels.get(&outcome.target.key) + && at == recorded_at + { + outcome.relative_schedule_preset_ms = Some(preset); + } + } + } + Ok(None) => {} + Err(error) => tracing::debug!(?error, "Relative schedule labels unreadable"), + } + if operation.targets.iter().any(is_immediate) { + match kv.get::(DetScope::Global, &recovery_times_key(key)) { + Ok(Some(times)) => { + for outcome in operation.targets.iter_mut().filter(|o| is_immediate(o)) { + outcome.recovered_at_ms = times.get(&outcome.target.key).copied(); + } + } + Ok(None) => {} + Err(error) => tracing::debug!(?error, "Vote recovery times unreadable"), + } + } + Ok(Some(operation)) +} + +/// When restart recovery picked up each immediate target of one operation, Unix ms. +type RecoveryTimes = BTreeMap; + +fn is_immediate(outcome: &DpnsVoteOutcome) -> bool { + outcome.target.timing == VoteTiming::Now +} + +/// Record that restart recovery picked up `keys` of an operation at `at_ms`. +/// +/// Display metadata, like the relative labels: a failed write is logged and +/// never fails the recovery it describes. Callers hold the journal guard. +fn save_recovery_times( + kv: &DetKv, + network: Network, + operation_id: DpnsVoteOperationId, + keys: &[DpnsVoteTargetKey], + at_ms: u64, +) { + if keys.is_empty() { + return; + } + let key = recovery_times_key(&operation_key(network, operation_id)); + let result = kv + .get::(DetScope::Global, &key) + .and_then(|times| { + let mut times = times.unwrap_or_default(); + times.extend(keys.iter().cloned().map(|key| (key, at_ms))); + kv.put(DetScope::Global, &key, ×) + }); + if let Err(error) = result { + tracing::debug!(?error, "Could not save vote recovery times"); + } +} + +fn save_relative_presets(kv: &DetKv, network: Network, operation: &DpnsVoteOperation) { + let labels: RelativeSchedulePresets = operation + .targets + .iter() + .filter_map(|outcome| { + let VoteTiming::Scheduled(at) = outcome.target.timing else { + return None; + }; + Some(( + outcome.target.key.clone(), + (at, outcome.relative_schedule_preset_ms?), + )) + }) + .collect(); + let key = relative_labels_key(&operation_key(network, operation.id)); + let result = if labels.is_empty() { + kv.delete(DetScope::Global, &key) + } else { + kv.put(DetScope::Global, &key, &labels) + }; + if let Err(error) = result { + tracing::debug!(?error, "Could not save relative schedule labels"); + } +} + +fn load_operation_ids(kv: &DetKv, network: Network) -> Result, TaskError> { + kv.get(DetScope::Global, &operation_index_key(network)) + .map(|ids| ids.unwrap_or_default()) + .map_err(unreadable_operation_err) +} + +fn operation_matches_network( + operation: &DpnsVoteOperation, + network: Network, +) -> Result { + if operation + .targets + .iter() + .all(|outcome| outcome.target.key.network == network) + { + return Ok(true); + } + if operation + .targets + .iter() + .any(|outcome| outcome.target.key.network != network && outcome.status.holds_lock()) + { + return Err(TaskError::DpnsVoteJournalNetworkMismatch); + } + Ok(false) +} + +fn load_operations_read_only( + kv: &DetKv, + network: Network, +) -> Result, TaskError> { + let mut operations = Vec::new(); + for bytes in load_operation_ids(kv, network)? { + let id = DpnsVoteOperationId::from_bytes(bytes); + let operation: DpnsVoteOperation = load_operation(kv, &operation_key(network, id)) + .map_err(unreadable_operation_err)? + .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; + if operation_matches_network(&operation, network)? { + operations.push(operation); + } + } + Ok(operations) +} + +fn load_operations(kv: &DetKv, network: Network) -> Result, TaskError> { + load_or_rebuild_lock_index(kv, network)?; + load_operations_read_only(kv, network) +} + +fn rebuild_lock_index(kv: &DetKv, network: Network) -> Result { + kv.put( + DetScope::Global, + &operation_lock_index_dirty_key(network), + &true, + ) + .map_err(operation_err)?; + let mut ids = Vec::new(); + let mut locks = DpnsVoteLockIndex::new(); + for key in kv + .list(DetScope::Global, Some(&operation_key_prefix(network))) + .map_err(unreadable_operation_err)? + { + let operation: DpnsVoteOperation = load_operation(kv, &key) + .map_err(unreadable_operation_err)? + .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; + if !operation_matches_network(&operation, network)? { + continue; + } + ids.push(operation.id.to_bytes()); + for outcome in operation + .targets + .iter() + .filter(|outcome| outcome.status.holds_lock()) + { + if locks + .insert(outcome.target.key.clone(), operation.id) + .is_some_and(|owner| owner != operation.id) + { + return Err(TaskError::DpnsVoteTargetBusy); + } + } + } + ids.sort_unstable(); + ids.dedup(); + kv.put(DetScope::Global, &operation_index_key(network), &ids) + .map_err(operation_err)?; + kv.put(DetScope::Global, &operation_lock_index_key(network), &locks) + .map_err(operation_err)?; + kv.delete(DetScope::Global, &operation_lock_index_dirty_key(network)) + .map_err(operation_err)?; + Ok(locks) +} + +fn load_or_rebuild_lock_index( + kv: &DetKv, + network: Network, +) -> Result { + let dirty = kv + .get::(DetScope::Global, &operation_lock_index_dirty_key(network)) + .map_err(unreadable_operation_err)? + .unwrap_or(false); + if !dirty + && let Some(index) = kv + .get(DetScope::Global, &operation_lock_index_key(network)) + .map_err(unreadable_operation_err)? + { + return Ok(index); + } + rebuild_lock_index(kv, network) +} + +fn persist_operation( + kv: &DetKv, + network: Network, + operation: &DpnsVoteOperation, +) -> Result<(), TaskError> { + if !operation_matches_network(operation, network)? { + return Err(TaskError::DpnsVoteJournalNetworkMismatch); + } + let complete = operation.is_complete(); + // The stored record is read only when this write can complete the + // operation or confirm a target; other transitions use the lock index alone. + let confirms_a_target = operation + .targets + .iter() + .any(|outcome| outcome.status == DpnsVoteTargetStatus::Confirmed); + let previous = if complete || confirms_a_target { + load_operation(kv, &operation_key(network, operation.id)) + .map_err(unreadable_operation_err)? + } else { + None + }; + let newly_complete = complete + && previous + .as_ref() + .is_none_or(|previous| !previous.is_complete()); + let mut locks = load_or_rebuild_lock_index(kv, network)?; + // Only this operation's own entries are removed and reinserted, so the + // index changes exactly when the set of keys it owns changes. + let mut previously_owned = BTreeSet::new(); + locks.retain(|key, owner| { + let owned = *owner == operation.id; + if owned { + previously_owned.insert(key.clone()); + } + !owned + }); + let mut now_owned = BTreeSet::new(); + for outcome in operation + .targets + .iter() + .filter(|outcome| outcome.status.holds_lock()) + { + if locks + .get(&outcome.target.key) + .is_some_and(|owner| *owner != operation.id) + { + return Err(TaskError::DpnsVoteTargetBusy); + } + locks.insert(outcome.target.key.clone(), operation.id); + now_owned.insert(outcome.target.key.clone()); + } + + for key in counts::newly_spent_targets(previous.as_ref(), operation) { + counts::bump_vote_count(kv, key, operation.id)?; + } + + let mut ids = load_operation_ids(kv, network)?; + let new_operation = !ids.contains(&operation.id.to_bytes()); + let locks_changed = previously_owned != now_owned; + if new_operation || locks_changed { + kv.put( + DetScope::Global, + &operation_lock_index_dirty_key(network), + &true, + ) + .map_err(operation_err)?; + } + kv.put( + DetScope::Global, + &operation_key(network, operation.id), + operation, + ) + .map_err(operation_err)?; + if new_operation { + ids.push(operation.id.to_bytes()); + kv.put(DetScope::Global, &operation_index_key(network), &ids) + .map_err(operation_err)?; + } + if locks_changed { + kv.put(DetScope::Global, &operation_lock_index_key(network), &locks) + .map_err(operation_err)?; + } + if new_operation || locks_changed { + kv.delete(DetScope::Global, &operation_lock_index_dirty_key(network)) + .map_err(operation_err)?; + } + save_relative_presets(kv, network, operation); + if complete + && let Err(error) = prune_completed_history( + kv, + network, + newly_complete.then_some(operation.id), + HistoryKind::of(operation), + ) + { + // The submitted result is durable; cleanup failure must not invite a retry. + tracing::warn!( + ?error, + "Completed DPNS voting history cleanup will retry during recovery" + ); + } + Ok(()) +} + +/// Cancel executable votes before their voter is delisted, while the caller owns the journal guard. +pub(super) fn cancel_removed_identity_votes( + kv: &DetKv, + network: Network, + voter_id: dash_sdk::platform::Identifier, +) -> Result<(), TaskError> { + for mut operation in load_operations(kv, network)? { + if cancel_executable_targets(&mut operation, |voter| voter == voter_id) { + persist_operation(kv, network, &operation)?; + } + } + Ok(()) +} + +/// Cancel the targets that could still be sent for the voters `is_removed` names. +fn cancel_executable_targets( + operation: &mut DpnsVoteOperation, + is_removed: impl Fn(dash_sdk::platform::Identifier) -> bool, +) -> bool { + let mut changed = false; + for outcome in &mut operation.targets { + if matches!( + outcome.status, + DpnsVoteTargetStatus::Scheduled + | DpnsVoteTargetStatus::Queued + | DpnsVoteTargetStatus::Submitting + ) && is_removed(outcome.target.key.voter_id) + { + outcome.status = DpnsVoteTargetStatus::Cancelled; + outcome.failure = None; + changed = true; + } + } + changed +} + +fn insert_diagnostic( + diagnostics: &mut DpnsVoteDiagnosticMap, + key: (DpnsVoteOperationId, DpnsVoteTargetKey), + sequence: u64, + error: Arc, + limit: usize, +) { + diagnostics.insert(key, (sequence, error)); + while diagnostics.len() > limit { + let Some(oldest) = diagnostics + .iter() + .min_by_key(|(_, (recorded_at, _))| recorded_at) + .map(|(key, _)| key.clone()) + else { + break; + }; + diagnostics.remove(&oldest); + } +} + +fn is_authorized_scheduled_replacement( + existing_status: DpnsVoteTargetStatus, + existing_key: &DpnsVoteTargetKey, + operation: &DpnsVoteOperation, + replacing_scheduled_key: Option<&DpnsVoteTargetKey>, +) -> bool { + existing_status == DpnsVoteTargetStatus::Scheduled + && replacing_scheduled_key == Some(existing_key) + && operation.targets.iter().any(|outcome| { + outcome.target.key == *existing_key + && outcome.status == DpnsVoteTargetStatus::Scheduled + && matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + }) +} + +fn replace_scheduled_operation( + kv: &DetKv, + network: Network, + operation: &mut DpnsVoteOperation, + replacing_scheduled_key: &DpnsVoteTargetKey, +) -> Result<(), TaskError> { + if operation.targets.len() != 1 + || !is_authorized_scheduled_replacement( + DpnsVoteTargetStatus::Scheduled, + replacing_scheduled_key, + operation, + Some(replacing_scheduled_key), + ) + { + return Err(TaskError::DpnsVoteTargetBusy); + } + let replacement = operation.targets[0].clone(); + for mut existing in load_operations(kv, network)? { + let Some(outcome) = existing + .targets + .iter_mut() + .find(|outcome| outcome.target.key == *replacing_scheduled_key) + else { + continue; + }; + if outcome.status != DpnsVoteTargetStatus::Scheduled { + continue; + } + *outcome = replacement; + outcome.operation_id = existing.id; + persist_operation(kv, network, &existing)?; + *operation = existing; + return Ok(()); + } + Err(TaskError::DpnsVoteTargetBusy) +} + +fn operation_for_schedule_edit( + kv: &DetKv, + network: Network, + edit: &DpnsScheduledVoteEdit, +) -> Result { + if edit.key.network != network { + return Err(TaskError::DpnsScheduledVoteNotEditable); + } + let locks = load_or_rebuild_lock_index(kv, network)?; + let id = edit.operation_id; + if locks.get(&edit.key) != Some(&id) { + return Err(TaskError::DpnsScheduledVoteNotEditable); + } + let operation: DpnsVoteOperation = load_operation(kv, &operation_key(network, id)) + .map_err(unreadable_operation_err)? + .ok_or(TaskError::DpnsScheduledVoteNotEditable)?; + if !operation.outcome(&edit.key).is_some_and(|outcome| { + outcome.status == DpnsVoteTargetStatus::Scheduled + && outcome.target.requested_choice == edit.expected_choice + && outcome.target.timing == VoteTiming::Scheduled(edit.expected_timestamp) + }) { + return Err(TaskError::DpnsScheduledVoteNotEditable); + } + Ok(operation) +} + +impl AppContext { + /// Build a voting batch with a fresh operation ID and the current creation time. + pub fn new_dpns_vote_operation(targets: Vec) -> DpnsVoteOperation { + DpnsVoteOperation::new( + DpnsVoteOperationId::from_bytes(rand::random()), + now_ms(), + targets, + ) + } + + /// Take the process-wide journal guard, recovering from a poisoned lock. + /// + /// Every read and write of the operation journal, its lock index + /// must be serialized behind this one guard; a method + /// that touches those namespaces without holding it can interleave with a + /// target claim and hand the same target to two executors. + fn journal_guard(&self) -> std::sync::MutexGuard<'_, ()> { + self.dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Take the journal guard together with the k/v handle it protects. + /// + /// Bind the guard to a named local (`let (_guard, kv) = self.journal()?;`) + /// so it lives until the end of the statement's scope rather than being + /// dropped immediately. + fn journal(&self) -> Result<(std::sync::MutexGuard<'_, ()>, DetKv), TaskError> { + let guard = self.journal_guard(); + Ok((guard, self.det_kv()?)) + } + + /// Serialize a journal mutation and publish its durable result before releasing the guard. + fn mutate_dpns_vote_operation( + &self, + operation_id: DpnsVoteOperationId, + mutate: impl FnOnce(&DetKv) -> Result, + ) -> Result { + let (_guard, kv) = self.journal()?; + let result = mutate(&kv); + // A write can fail after the record commits but before index maintenance finishes. + match load_operation(&kv, &operation_key(self.network, operation_id)) { + Ok(Some(operation)) => { + let mut progress = self + .dpns_vote_progress + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(index) = progress.iter().position(|old| old.id == operation.id) { + if *progress[index] != operation { + Arc::make_mut(&mut progress)[index] = Arc::new(operation); + } + } else { + let operations = progress + .iter() + .cloned() + .chain([Arc::new(operation)]) + .collect(); + *progress = operations; + } + self.egui_ctx().request_repaint(); + } + Ok(None) => {} + Err(error) => tracing::warn!(?error, "Could not publish durable vote progress"), + } + result + } + + /// Read the exact unstarted target selected by an optimistic schedule edit. + pub(crate) fn scheduled_dpns_vote_edit_target( + &self, + edit: &DpnsScheduledVoteEdit, + ) -> Result { + let _guard = self.journal_guard(); + operation_for_schedule_edit(&self.det_kv()?, self.network, edit)? + .outcome(&edit.key) + .map(|outcome| outcome.target.clone()) + .ok_or(TaskError::DpnsScheduledVoteNotEditable) + } + + /// Apply a validated edit under one journal guard without releasing its target lock. + pub(crate) fn edit_scheduled_dpns_vote_target( + &self, + edit: &DpnsScheduledVoteEdit, + ) -> Result { + let (_guard, kv) = self.journal()?; + let mut operation = operation_for_schedule_edit(&kv, self.network, edit)?; + if edit.unix_timestamp <= now_ms() { + return Err(TaskError::DpnsScheduledVoteInvalidTime); + } + let outcome = operation + .targets + .iter_mut() + .find(|outcome| outcome.target.key == edit.key) + .ok_or(TaskError::DpnsScheduledVoteNotEditable)?; + outcome.target.requested_choice = edit.choice; + if outcome.target.timing != VoteTiming::Scheduled(edit.unix_timestamp) { + outcome.relative_schedule_preset_ms = None; + } + outcome.target.timing = VoteTiming::Scheduled(edit.unix_timestamp); + outcome.failure = None; + persist_operation(&kv, self.network, &operation)?; + Ok(operation.id) + } + + /// Durably claim one due scheduled target before any executor can observe it. + pub(crate) fn queue_scheduled_dpns_vote_target( + &self, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, + ) -> Result { + self.mutate_dpns_vote_operation(operation_id, |kv| { + transition_scheduled_target_to_queued(kv, self.network, operation_id, key) + }) + } + + /// The voter lifecycles as they stand now. Vote work reads them when it is + /// submitted and hands them to [`Self::admit_dpns_vote_operation`]. + pub(crate) fn dpns_voter_lifecycles(&self) -> DpnsVoterLifecycles { + self.dpns_voter_lifecycles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } + + /// Record that `voter` is being loaded again after a removal. The caller + /// holds the journal guard, so no admission runs between the cancellation + /// of the voter's stored votes and this. + pub(super) fn begin_dpns_voter_lifecycle(&self, voter: dash_sdk::platform::Identifier) { + let mut lifecycles = self + .dpns_voter_lifecycles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let lifecycle = lifecycles.entry(voter).or_default(); + *lifecycle = lifecycle.wrapping_add(1); + } + + /// Persist a reviewed operation and atomically acquire all unresolved locks. + pub fn insert_dpns_vote_operation( + &self, + operation: &mut DpnsVoteOperation, + replacing_scheduled_key: Option<&DpnsVoteTargetKey>, + ) -> Result<(), TaskError> { + let submitted = self.dpns_voter_lifecycles(); + self.admit_dpns_vote_operation(operation, replacing_scheduled_key, &submitted) + } + + /// [`Self::insert_dpns_vote_operation`] for work that waited after it was + /// submitted. `submitted` is [`Self::dpns_voter_lifecycles`] read before + /// the wait: a voter loaded again since then has its votes cancelled. + pub(crate) fn admit_dpns_vote_operation( + &self, + operation: &mut DpnsVoteOperation, + replacing_scheduled_key: Option<&DpnsVoteTargetKey>, + submitted: &DpnsVoterLifecycles, + ) -> Result<(), TaskError> { + self.mutate_dpns_vote_operation(operation.id, |kv| { + if operation + .targets + .iter() + .any(|outcome| outcome.target.key.network != self.network) + { + return Err(TaskError::DpnsVoteTargetBusy); + } + // Removing an identity cancels its votes under this guard, but it + // sees only those already stored. A vote reviewed before the + // removal and arriving after it must end the same way. + let removed = self.removed_dpns_voters(kv, operation, submitted)?; + if let Some(key) = replacing_scheduled_key { + // A schedule stored for a voter loaded again was reviewed + // afresh; it is not this work's to replace. + if removed.contains(&key.voter_id) { + return Err(TaskError::DpnsScheduledVoteNotEditable); + } + replace_scheduled_operation(kv, self.network, operation, key)?; + *self + .dpns_vote_progress + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = + load_operations_read_only(kv, self.network)? + .into_iter() + .map(Arc::new) + .collect(); + return Ok(()); + } + // A stored record under this ID may hold targets an executor has + // already claimed or broadcast; writing the caller's snapshot over + // it would make them claimable again. + if load_operation(kv, &operation_key(self.network, operation.id)) + .map_err(unreadable_operation_err)? + .is_some() + { + return Err(TaskError::DpnsVoteTargetBusy); + } + cancel_executable_targets(operation, |voter| removed.contains(&voter)); + persist_operation(kv, self.network, operation) + }) + } + + /// Voters of `operation` removed from this device since its votes were + /// reviewed: either not loaded again, or loaded again after `submitted` + /// was read. The caller holds the journal guard, which a removal keeps + /// from cancelling the voter's votes until the voter is delisted, and + /// which loading the voter again keeps until its lifecycle has moved on. + fn removed_dpns_voters( + &self, + kv: &DetKv, + operation: &DpnsVoteOperation, + submitted: &DpnsVoterLifecycles, + ) -> Result, TaskError> { + let voters: BTreeSet<_> = operation + .targets + .iter() + .map(|outcome| outcome.target.key.voter_id) + .collect(); + let current = self.dpns_voter_lifecycles(); + let mut removed = BTreeSet::new(); + for voter in voters { + if submitted.get(&voter) != current.get(&voter) + || (self.is_identity_unloaded(kv, &voter.to_buffer())? + && !self.is_identity_listed(&voter)?) + { + removed.insert(voter); + } + } + Ok(removed) + } + + /// Persist updated target statuses while retaining the original operation ID. + pub fn update_dpns_vote_operation( + &self, + operation: &DpnsVoteOperation, + ) -> Result<(), TaskError> { + self.mutate_dpns_vote_operation(operation.id, |kv| { + persist_operation(kv, self.network, operation) + }) + } + + /// Load every operation for this network, including completed history. + pub fn dpns_vote_operations(&self) -> Result, TaskError> { + let (_guard, kv) = self.journal()?; + if kv + .get::( + DetScope::Global, + &operation_lock_index_dirty_key(self.network), + ) + .map_err(unreadable_operation_err)? + .unwrap_or(false) + { + rebuild_lock_index(&kv, self.network)?; + } + let operations = load_operations_read_only(&kv, self.network)?; + *self + .dpns_vote_progress + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = + operations.iter().cloned().map(Arc::new).collect(); + Ok(operations) + } + + /// Read dismissed schedule rows without changing their recorded vote outcomes. + pub fn dismissed_dpns_vote_schedules( + &self, + ) -> Result, TaskError> { + let (_guard, kv) = self.journal()?; + let mut dismissed = BTreeSet::new(); + for bytes in load_operation_ids(&kv, self.network)? { + let id = DpnsVoteOperationId::from_bytes(bytes); + let keys: BTreeSet = kv + .get(DetScope::Global, &schedule_dismissal_key(self.network, id)) + .map_err(unreadable_operation_err)? + .unwrap_or_default(); + dismissed.extend(keys.into_iter().map(|key| (id, key))); + } + Ok(dismissed) + } + + /// Votes this device saw Platform apply for one node × poll; `None` + /// when it holds no record. + pub fn dpns_vote_count( + &self, + voter_id: dash_sdk::platform::Identifier, + vote_poll_id: dash_sdk::platform::Identifier, + ) -> Result, TaskError> { + let _guard = self.journal_guard(); + counts::vote_count(&self.det_kv()?, self.network, voter_id, vote_poll_id) + } + + /// Drop the vote counts of polls proven closed. + pub(crate) fn forget_dpns_vote_counts( + &self, + closed_polls: &BTreeSet, + ) -> Result { + let (_guard, kv) = self.journal()?; + counts::forget_vote_counts(&kv, self.network, closed_polls) + } + + /// Load one operation by its stable ID. + pub fn dpns_vote_operation( + &self, + id: DpnsVoteOperationId, + ) -> Result, TaskError> { + let _guard = self.journal_guard(); + let operation = load_operation(&self.det_kv()?, &operation_key(self.network, id)) + .map_err(unreadable_operation_err)?; + match operation { + Some(operation) if operation_matches_network(&operation, self.network)? => { + Ok(Some(operation)) + } + Some(_) | None => Ok(None), + } + } + + /// Return the unresolved status that currently locks an exact target. + pub fn dpns_vote_target_status( + &self, + key: &DpnsVoteTargetKey, + ) -> Result, TaskError> { + Ok(self + .dpns_vote_operations()? + .into_iter() + .flat_map(|operation| operation.targets) + .find(|outcome| outcome.target.key == *key && outcome.status.holds_lock()) + .map(|outcome| outcome.status)) + } + + /// Atomically update one target in the durable journal. + /// + /// A cancelled target is never revived, and a target that has left the + /// journal is left alone. + pub(crate) fn update_dpns_vote_target( + &self, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, + status: DpnsVoteTargetStatus, + failure: Option, + ) -> Result<(), TaskError> { + self.mutate_dpns_vote_operation(operation_id, |kv| { + with_target(kv, self.network, operation_id, key, |outcome| { + if outcome.status == DpnsVoteTargetStatus::Cancelled { + return TargetUpdate::Skip(()); + } + outcome.status = status; + if status == DpnsVoteTargetStatus::Unconfirmed { + outcome.target.current_choice = None; + } + outcome.failure = failure; + TargetUpdate::Persist(()) + })?; + Ok(()) + }) + } + + /// Atomically persist one corroborated reconciliation observation. + /// + /// Returns `false` when the target moved on since the observation was read + /// — a different status or a different cached choice — so the caller must + /// not act on a verdict derived from a stale snapshot. + pub(crate) fn update_dpns_vote_reconciliation( + &self, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, + expected_current_choice: Option, + observed_choice: Option, + status: DpnsVoteTargetStatus, + ) -> Result { + self.mutate_dpns_vote_operation(operation_id, |kv| { + Ok(with_target(kv, self.network, operation_id, key, |outcome| { + if outcome.status != DpnsVoteTargetStatus::Unconfirmed + || outcome.target.current_choice != expected_current_choice + { + return TargetUpdate::Skip(false); + } + if outcome.target.current_choice == observed_choice && outcome.status == status { + return TargetUpdate::Skip(true); + } + outcome.target.current_choice = observed_choice; + outcome.status = status; + outcome.failure = (status == DpnsVoteTargetStatus::Unconfirmed) + .then_some(DpnsVoteFailure::ResultUnconfirmed); + TargetUpdate::Persist(true) + })? + .unwrap_or(false)) + }) + } + + /// Atomically claim a queued target before any network or nonce work. + pub(crate) fn claim_dpns_vote_target( + &self, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, + ) -> Result { + self.mutate_dpns_vote_operation(operation_id, |kv| { + Ok(with_target(kv, self.network, operation_id, key, |outcome| { + if outcome.status != DpnsVoteTargetStatus::Queued { + return TargetUpdate::Skip(false); + } + outcome.status = DpnsVoteTargetStatus::Submitting; + outcome.failure = None; + TargetUpdate::Persist(true) + })? + .unwrap_or(false)) + }) + } + + /// Record that a target is entering the ambiguous broadcast phase. + pub(crate) fn mark_dpns_vote_broadcast( + &self, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, + ) -> Result { + self.mutate_dpns_vote_operation(operation_id, |kv| { + mark_target_broadcast(kv, self.network, operation_id, key) + }) + } + + /// Apply fresh proved state only while the target is still queued. + /// + /// Returning `false` means another executor already advanced the target; + /// callers must not write their stale operation snapshot back. + pub(crate) fn revalidate_queued_dpns_vote_target( + &self, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, + state: DpnsCurrentVoteState, + ) -> Result { + self.mutate_dpns_vote_operation(operation_id, |kv| { + Ok(with_target(kv, self.network, operation_id, key, |outcome| { + if outcome.status != DpnsVoteTargetStatus::Queued { + return TargetUpdate::Skip(false); + } + match state { + // Reviewed as a first vote, but Platform now shows another + // one: sending it would spend a change nobody reviewed. + DpnsCurrentVoteState::Available(Some(current)) + if outcome.target.timing == VoteTiming::Now + && outcome.target.current_choice.is_none() + && current != outcome.target.requested_choice => + { + (outcome.status, outcome.failure) = + failed_before_broadcast_outcome(VoteTiming::Now); + } + DpnsCurrentVoteState::Available(current) => { + outcome.target.current_choice = current; + if current == Some(outcome.target.requested_choice) { + outcome.status = DpnsVoteTargetStatus::Confirmed; + outcome.failure = None; + } + } + DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable => { + (outcome.status, outcome.failure) = + unavailable_preflight_outcome(outcome.target.timing); + } + } + TargetUpdate::Persist(outcome.status == DpnsVoteTargetStatus::Queued) + })? + .unwrap_or(false)) + }) + } + + /// Recover interrupted targets according to their durable broadcast phase, + /// and stop queued targets that are too old to send without another look. + /// + /// Runs once per process, before any executor, so every non-terminal + /// status it sees was left behind by an earlier run. + pub(crate) fn recover_interrupted_dpns_vote_operations(&self) -> Result<(), TaskError> { + let (_guard, kv) = self.journal()?; + let now_ms = now_ms(); + for mut operation in load_operations(&kv, self.network)? { + // Whatever becomes of these from here on happens in this session, + // however long ago the operation was reviewed. + let picked_up: Vec = operation + .targets + .iter() + .filter(|outcome| { + is_immediate(outcome) + && matches!( + outcome.status, + DpnsVoteTargetStatus::Queued | DpnsVoteTargetStatus::Submitting + ) + }) + .map(|outcome| outcome.target.key.clone()) + .collect(); + let interrupted = recover_interrupted_target_statuses(&mut operation, |_| true); + let expired = expire_stale_queued_targets(&mut operation, now_ms); + if interrupted || expired { + persist_operation(&kv, self.network, &operation)?; + } + save_recovery_times(&kv, self.network, operation.id, &picked_up, now_ms); + } + prune_completed_history(&kv, self.network, None, HistoryKind::Immediate)?; + prune_completed_history(&kv, self.network, None, HistoryKind::Scheduled)?; + prune_orphaned_schedule_dismissals(&kv, self.network)?; + Ok(()) + } + + /// Conservatively recover one operation after its executor has returned. + /// + /// `keys` are the targets that executor ran with. Besides normalising the + /// ones it had claimed, this settles its immediate targets still queued: + /// their executor is gone, and nothing else would ever send or release them. + pub(crate) fn recover_interrupted_dpns_vote_operation( + &self, + operation_id: DpnsVoteOperationId, + keys: &BTreeSet, + ) -> Result<(), TaskError> { + self.mutate_dpns_vote_operation(operation_id, |kv| { + let Some(mut operation): Option = + load_operation(kv, &operation_key(self.network, operation_id)) + .map_err(unreadable_operation_err)? + else { + return Ok(()); + }; + let interrupted = + recover_interrupted_target_statuses(&mut operation, |key| keys.contains(key)); + let abandoned = fail_abandoned_queued_targets(&mut operation, |key| keys.contains(key)); + if interrupted || abandoned { + persist_operation(kv, self.network, &operation)?; + } + Ok(()) + }) + } + + pub(crate) fn record_dpns_vote_diagnostic( + &self, + operation_id: DpnsVoteOperationId, + key: DpnsVoteTargetKey, + error: TaskError, + ) { + let sequence = self + .dpns_vote_diagnostic_sequence + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let mut diagnostics = self + .dpns_vote_diagnostics + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + insert_diagnostic( + &mut diagnostics, + (operation_id, key), + sequence, + Arc::new(error), + DPNS_VOTE_DIAGNOSTIC_LIMIT, + ); + } + + pub(crate) fn dpns_vote_operation_diagnostics( + &self, + operation_id: DpnsVoteOperationId, + ) -> Vec> { + self.dpns_vote_diagnostics + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .iter() + .filter(|((id, _), _)| *id == operation_id) + .map(|(_, (_, error))| Arc::clone(error)) + .collect() + } + + /// Remove lock-releasing operation history when the user clears completed votes. + #[cfg(test)] + pub(crate) fn prune_terminal_dpns_vote_operations(&self) -> Result { + let _guard = self.journal_guard(); + prune_terminal_operations(&self.det_kv()?, self.network) + } + + /// Remove a schedule only after its authoritative journal state permits it. + pub(crate) fn remove_scheduled_dpns_vote( + &self, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, + ) -> Result<(), TaskError> { + let (_guard, kv) = self.journal()?; + let operations = load_operations(&kv, self.network)?; + let lock_index = load_or_rebuild_lock_index(&kv, self.network)?; + let selected = operations + .iter() + .find(|operation| operation.id == operation_id) + .and_then(|operation| { + operation + .outcome(key) + .map(|outcome| (operation.id, outcome.status)) + }); + + match selected { + Some((operation_id, DpnsVoteTargetStatus::Scheduled)) => { + if lock_index + .get(key) + .is_some_and(|owner| *owner != operation_id) + { + return Err(TaskError::DpnsScheduledVoteAlreadyStarted); + } + if !cancel_scheduled_target(&kv, self.network, operation_id, key)? { + return Err(TaskError::DpnsScheduledVoteAlreadyStarted); + } + } + Some(( + _, + DpnsVoteTargetStatus::Queued + | DpnsVoteTargetStatus::Submitting + | DpnsVoteTargetStatus::Confirming + | DpnsVoteTargetStatus::Unconfirmed, + )) => return Err(TaskError::DpnsScheduledVoteAlreadyStarted), + Some((operation_id, _)) => { + if lock_index + .get(key) + .is_some_and(|owner| *owner != operation_id) + { + return Err(TaskError::DpnsScheduledVoteAlreadyStarted); + } + dismiss_scheduled_target(&kv, self.network, operation_id, key)?; + } + None => { + if lock_index.contains_key(key) { + return Err(TaskError::DpnsScheduledVoteAlreadyStarted); + } + } + }; + + Ok(()) + } + + /// Release a not-yet-submitting scheduled target after explicit cancellation. + pub(crate) fn cancel_scheduled_dpns_vote_target( + &self, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, + ) -> Result<(), TaskError> { + self.remove_scheduled_dpns_vote(operation_id, key) + } + + /// Dismiss confirmed scheduled targets without changing their recorded outcomes. + pub fn clear_executed_scheduled_votes(&self) -> Result<(), TaskError> { + let (_guard, kv) = self.journal()?; + dismiss_confirmed_scheduled_targets(&kv, self.network)?; + prune_terminal_operations(&kv, self.network)?; + Ok(()) + } + + /// Clear removable schedules and report in-flight targets retained for safety. + pub(crate) fn clear_all_scheduled_dpns_votes( + &self, + ) -> Result, TaskError> { + let (_guard, kv) = self.journal()?; + let operations = load_operations(&kv, self.network)?; + let selected: BTreeSet<_> = authoritative_dpns_vote_outcomes(&operations, |outcome| { + matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + }) + .into_values() + .map(|(operation, outcome)| (operation.id, outcome.target.key.clone())) + .collect(); + let mut outcomes = Vec::new(); + for mut operation in operations { + let mut changed = false; + for outcome in operation + .targets + .iter_mut() + .filter(|outcome| matches!(outcome.target.timing, VoteTiming::Scheduled(_))) + { + let key = DpnsScheduledVoteKey { + network: outcome.target.key.network, + voter_id: outcome.target.key.voter_id, + contested_name: outcome.target.contested_name.clone(), + }; + let status = outcome.status; + let disposition = match status { + DpnsVoteTargetStatus::Scheduled => { + outcome.status = DpnsVoteTargetStatus::Cancelled; + outcome.failure = None; + changed = true; + DpnsScheduledVoteClearDisposition::Cleared + } + DpnsVoteTargetStatus::Queued + | DpnsVoteTargetStatus::Submitting + | DpnsVoteTargetStatus::Confirming + | DpnsVoteTargetStatus::Unconfirmed => { + DpnsScheduledVoteClearDisposition::InFlight(status) + } + _ => { + dismiss_scheduled_target( + &kv, + self.network, + operation.id, + &outcome.target.key, + )?; + DpnsScheduledVoteClearDisposition::Cleared + } + }; + if selected.contains(&(operation.id, outcome.target.key.clone())) { + outcomes.push(DpnsScheduledVoteClearOutcome { + operation_id: Some(operation.id), + key, + disposition, + }); + } + } + if changed { + persist_operation(&kv, self.network, &operation)?; + } + } + + prune_terminal_operations(&kv, self.network)?; + Ok(outcomes) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::dpns_voting::{ + DpnsScheduledVoteClearDisposition, DpnsVoteTarget, VoteTiming, + }; + use crate::wallet_backend::kv_test_support::{FailingKv, InMemoryKv}; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; + use dash_sdk::platform::Identifier; + use platform_wallet_storage::{KvStore, ObjectId}; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[derive(Default)] + struct CountingKv { + inner: InMemoryKv, + puts: AtomicUsize, + operation_gets: AtomicUsize, + } + + impl CountingKv { + fn reset_counts(&self) { + self.puts.store(0, Ordering::Relaxed); + self.operation_gets.store(0, Ordering::Relaxed); + } + + fn put_count(&self) -> usize { + self.puts.load(Ordering::Relaxed) + } + + fn operation_get_count(&self) -> usize { + self.operation_gets.load(Ordering::Relaxed) + } + } + + impl KvStore for CountingKv { + fn get( + &self, + scope: &ObjectId, + key: &str, + ) -> Result>, platform_wallet_storage::KvError> { + if key.starts_with(OPERATION_KEY_PREFIX) { + self.operation_gets.fetch_add(1, Ordering::Relaxed); + } + self.inner.get(scope, key) + } + + fn put( + &self, + scope: &ObjectId, + key: &str, + value: &[u8], + ) -> Result<(), platform_wallet_storage::KvError> { + self.puts.fetch_add(1, Ordering::Relaxed); + self.inner.put(scope, key, value) + } + + fn delete( + &self, + scope: &ObjectId, + key: &str, + ) -> Result<(), platform_wallet_storage::KvError> { + self.inner.delete(scope, key) + } + + fn list_keys( + &self, + scope: &ObjectId, + prefix: Option<&str>, + ) -> Result, platform_wallet_storage::KvError> { + self.inner.list_keys(scope, prefix) + } + } + + fn kv() -> DetKv { + DetKv::from_store(Arc::new(InMemoryKv::default())) + } + + fn operation(status: DpnsVoteTargetStatus) -> DpnsVoteOperation { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([2; 32]), + }, + voter_alias: Some("Eve".to_owned()), + contested_name: "dominguez".to_owned(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Now, + }]); + operation.targets[0].status = status; + operation + } + + fn scheduled_operation( + status: DpnsVoteTargetStatus, + poll: u8, + contested_name: &str, + ) -> DpnsVoteOperation { + let mut operation = operation(status); + operation.targets[0].target.timing = VoteTiming::Scheduled(42); + operation.targets[0].target.key.vote_poll_id = Identifier::from([poll; 32]); + operation.targets[0].target.contested_name = contested_name.to_owned(); + operation + } + + #[test] + fn vote_progress_publishes_admission_and_each_target_transition() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(kv()); + let mut operation = operation(DpnsVoteTargetStatus::Queued); + let key = operation.targets[0].target.key.clone(); + ctx.insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + assert_eq!( + ctx.dpns_vote_progress()[0].targets[0].status, + DpnsVoteTargetStatus::Queued + ); + let admitted = ctx.dpns_vote_progress(); + assert!(ctx.claim_dpns_vote_target(operation.id, &key).unwrap()); + assert_eq!( + ctx.dpns_vote_progress()[0].targets[0].status, + DpnsVoteTargetStatus::Submitting + ); + assert_eq!(admitted[0].targets[0].status, DpnsVoteTargetStatus::Queued); + assert!(ctx.mark_dpns_vote_broadcast(operation.id, &key).unwrap()); + assert_eq!( + ctx.dpns_vote_progress()[0].targets[0].status, + DpnsVoteTargetStatus::Confirming + ); + ctx.update_dpns_vote_target(operation.id, &key, DpnsVoteTargetStatus::Confirmed, None) + .unwrap(); + assert_eq!( + ctx.dpns_vote_progress()[0].targets[0].status, + DpnsVoteTargetStatus::Confirmed + ); + } + + /// A reader holding the publication must not make one target's transition + /// copy the other retained operations. + #[test] + fn a_target_transition_shares_every_other_published_operation() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(kv()); + let mut changed = operation(DpnsVoteTargetStatus::Queued); + let mut untouched = operation(DpnsVoteTargetStatus::Queued); + untouched.targets[0].target.key.vote_poll_id = Identifier::from([3; 32]); + let key = changed.targets[0].target.key.clone(); + ctx.insert_dpns_vote_operation(&mut changed, None).unwrap(); + ctx.insert_dpns_vote_operation(&mut untouched, None) + .unwrap(); + let published = |progress: &[Arc], id: DpnsVoteOperationId| { + Arc::clone( + progress + .iter() + .find(|operation| operation.id == id) + .expect("published operation"), + ) + }; + + let before = ctx.dpns_vote_progress(); + assert!(ctx.claim_dpns_vote_target(changed.id, &key).unwrap()); + let after = ctx.dpns_vote_progress(); + + assert_eq!( + published(&after, changed.id).targets[0].status, + DpnsVoteTargetStatus::Submitting + ); + assert_eq!( + published(&before, changed.id).targets[0].status, + DpnsVoteTargetStatus::Queued, + "the reader's publication is left as it was" + ); + assert!( + Arc::ptr_eq( + &published(&before, untouched.id), + &published(&after, untouched.id) + ), + "the untouched operation is shared, not copied" + ); + } + + #[test] + fn new_vote_batches_have_distinct_operation_ids() { + let ids: BTreeSet<_> = (0..64) + .map(|_| AppContext::new_dpns_vote_operation(Vec::new()).id) + .collect(); + assert_eq!(ids.len(), 64); + assert!(!ids.contains(&DpnsVoteOperationId::from_bytes([0; 16]))); + } + + /// Two operations stamped inside the same millisecond — reachable whenever a + /// bulk review commits — must not make the four sites that pick "the + /// operation that speaks for this target" disagree with each other. + #[test] + fn operations_sharing_a_millisecond_agree_on_the_authoritative_operation() { + let older_id = DpnsVoteOperationId::from_bytes([1; 16]); + let newer_id = DpnsVoteOperationId::from_bytes([2; 16]); + let voter_id = Identifier::from([1; 32]); + let key = DpnsVoteTargetKey { + network: Network::Testnet, + voter_id, + vote_poll_id: Identifier::from([2; 32]), + }; + // Two of the four sites consume what they select, so each gets its own + // journal. The higher id is written first so that "last record wins" + // and "highest id wins" cannot agree by accident. + let seed = || { + let temp = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp.path()); + context.set_det_kv_override_for_test(kv()); + for (id, status) in [ + (newer_id, DpnsVoteTargetStatus::Rejected), + (older_id, DpnsVoteTargetStatus::Confirmed), + ] { + let mut operation = scheduled_operation(status, 2, "alice"); + operation.id = id; + operation.created_at = 1_000; + operation.targets[0].operation_id = id; + context + .insert_dpns_vote_operation(&mut operation, None) + .expect("seed journal record"); + } + (temp, context) + }; + + let (_temp, context) = seed(); + let operations = context.dpns_vote_operations().unwrap(); + assert_eq!( + crate::backend_task::contested_names::preferred_outcome_for_scheduled_key( + &operations, + &key + ) + .unwrap() + .map(|outcome| outcome.operation_id), + Some(newer_id), + "cast-now selection must break the tie on the operation id" + ); + + let (_temp, context) = seed(); + context.remove_scheduled_dpns_vote(newer_id, &key).unwrap(); + assert!( + context + .dismissed_dpns_vote_schedules() + .unwrap() + .contains(&(newer_id, key.clone())), + "dismissal must land on the same operation the other sites prefer" + ); + + let (_temp, context) = seed(); + assert_eq!( + context + .clear_all_scheduled_dpns_votes() + .unwrap() + .into_iter() + .map(|outcome| outcome.operation_id) + .collect::>(), + vec![Some(newer_id)], + "Clear All must report the same operation the other sites prefer" + ); + + let (_temp, context) = seed(); + assert!( + context + .masternode_contest_summary(Some(voter_id)) + .unwrap() + .has_failed_scheduled_vote, + "the node card must report the failure of the same operation the other sites prefer" + ); + + let (_temp, context) = seed(); + let rows = + crate::ui::state::dpns_vote_operations::DpnsVoteOperationSnapshot::load(&context) + .scheduled_vote_rows(); + assert_eq!( + rows.iter() + .map(|row| Some(row.journal_target.0)) + .collect::>(), + vec![Some(newer_id)], + "Scheduled Votes must show the same operation the other sites prefer" + ); + } + + /// VOTE-TC-040/041: one unresolved target cannot be inserted twice. + #[test] + fn unresolved_target_rejects_a_competing_operation() { + let kv = kv(); + persist_operation( + &kv, + Network::Testnet, + &operation(DpnsVoteTargetStatus::Submitting), + ) + .unwrap(); + + let error = persist_operation( + &kv, + Network::Testnet, + &operation(DpnsVoteTargetStatus::Queued), + ) + .expect_err("the exact target must stay locked"); + assert!(matches!(error, TaskError::DpnsVoteTargetBusy)); + } + + /// VOTE-TC-044: reloading the journal reconstructs an Unconfirmed lock. + #[test] + fn unconfirmed_lock_survives_journal_reload() { + let kv = kv(); + let operation = operation(DpnsVoteTargetStatus::Unconfirmed); + persist_operation(&kv, Network::Testnet, &operation).unwrap(); + + let restored = load_operations(&kv, Network::Testnet).unwrap(); + assert_eq!(restored, vec![operation]); + assert!(restored[0].targets[0].status.holds_lock()); + } + + /// VOTE-TC-042: a different poll remains usable. + #[test] + fn unrelated_target_can_be_persisted() { + let kv = kv(); + persist_operation( + &kv, + Network::Testnet, + &operation(DpnsVoteTargetStatus::Confirming), + ) + .unwrap(); + let mut unrelated = operation(DpnsVoteTargetStatus::Queued); + unrelated.targets[0].target.key.vote_poll_id = Identifier::from([3; 32]); + + persist_operation(&kv, Network::Testnet, &unrelated).unwrap(); + assert_eq!(load_operations(&kv, Network::Testnet).unwrap().len(), 2); + } + + #[test] + fn scheduled_replacement_requires_the_exact_edit_key() { + let mut replacement = operation(DpnsVoteTargetStatus::Scheduled); + replacement.targets[0].target.timing = VoteTiming::Scheduled(42); + let key = replacement.targets[0].target.key.clone(); + let other = DpnsVoteTargetKey { + vote_poll_id: Identifier::from([9; 32]), + ..key.clone() + }; + + assert!(is_authorized_scheduled_replacement( + DpnsVoteTargetStatus::Scheduled, + &key, + &replacement, + Some(&key), + )); + assert!(!is_authorized_scheduled_replacement( + DpnsVoteTargetStatus::Scheduled, + &key, + &replacement, + None, + )); + assert!(!is_authorized_scheduled_replacement( + DpnsVoteTargetStatus::Scheduled, + &key, + &replacement, + Some(&other), + )); + } + + #[test] + fn scheduled_replacement_reuses_the_existing_record_in_one_write() { + let store = Arc::new(CountingKv::default()); + let kv = DetKv::from_store(store.clone()); + let mut scheduled = operation(DpnsVoteTargetStatus::Scheduled); + scheduled.targets[0].target.timing = VoteTiming::Scheduled(42); + let key = scheduled.targets[0].target.key.clone(); + persist_operation(&kv, Network::Testnet, &scheduled).unwrap(); + + let mut replacement = operation(DpnsVoteTargetStatus::Scheduled); + replacement.targets[0].target.timing = VoteTiming::Scheduled(84); + store.reset_counts(); + + replace_scheduled_operation(&kv, Network::Testnet, &mut replacement, &key).unwrap(); + + assert_eq!(store.put_count(), 1); + assert_eq!(replacement.id, scheduled.id); + assert_eq!( + load_operations(&kv, Network::Testnet).unwrap(), + vec![replacement] + ); + } + + #[test] + fn due_schedule_is_durably_queued_once_through_the_kv_seam() { + let kv = kv(); + let mut scheduled = operation(DpnsVoteTargetStatus::Scheduled); + scheduled.targets[0].target.timing = VoteTiming::Scheduled(42); + let key = scheduled.targets[0].target.key.clone(); + persist_operation(&kv, Network::Testnet, &scheduled).unwrap(); + + assert!( + transition_scheduled_target_to_queued(&kv, Network::Testnet, scheduled.id, &key,) + .unwrap() + ); + assert_eq!( + load_operations(&kv, Network::Testnet).unwrap()[0].targets[0].status, + DpnsVoteTargetStatus::Queued + ); + assert!( + !transition_scheduled_target_to_queued(&kv, Network::Testnet, scheduled.id, &key,) + .unwrap(), + "a second executor must not claim the same schedule" + ); + } + + #[test] + fn unavailable_preflight_preserves_retryability_by_timing() { + assert_eq!( + unavailable_preflight_outcome(VoteTiming::Scheduled(42)), + ( + DpnsVoteTargetStatus::Scheduled, + Some(DpnsVoteFailure::CurrentVoteUnavailable), + ) + ); + assert_eq!( + unavailable_preflight_outcome(VoteTiming::Now), + ( + DpnsVoteTargetStatus::FailedBeforeSubmission, + Some(DpnsVoteFailure::CurrentVoteUnavailable), + ) + ); + } + + #[test] + fn cancellation_does_not_overwrite_a_queued_target() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp_dir.path()); + let kv = kv(); + context.set_det_kv_override_for_test(kv); + let mut scheduled = scheduled_operation(DpnsVoteTargetStatus::Scheduled, 2, "dominguez"); + let key = scheduled.targets[0].target.key.clone(); + context + .insert_dpns_vote_operation(&mut scheduled, None) + .unwrap(); + context + .queue_scheduled_dpns_vote_target(scheduled.id, &key) + .unwrap(); + + assert!(matches!( + context + .remove_scheduled_dpns_vote(scheduled.id, &key) + .expect_err("queued targets must not be removed"), + TaskError::DpnsScheduledVoteAlreadyStarted + )); + assert_eq!( + context.dpns_vote_operations().unwrap()[0].targets[0].status, + DpnsVoteTargetStatus::Queued + ); + } + + #[test] + fn cancellation_records_cancelled_without_claiming_a_proved_outcome() { + let kv = kv(); + let mut scheduled = operation(DpnsVoteTargetStatus::Scheduled); + scheduled.targets[0].target.timing = VoteTiming::Scheduled(42); + scheduled.targets[0].failure = Some(DpnsVoteFailure::SubmissionFailed); + let key = scheduled.targets[0].target.key.clone(); + persist_operation(&kv, Network::Testnet, &scheduled).unwrap(); + + assert!(cancel_scheduled_target(&kv, Network::Testnet, scheduled.id, &key).unwrap()); + let cancelled = load_operations(&kv, Network::Testnet).unwrap().remove(0); + assert_eq!(cancelled.targets[0].status, DpnsVoteTargetStatus::Cancelled); + assert_eq!(cancelled.targets[0].failure, None); + assert!(!cancelled.targets[0].status.holds_lock()); + } + + #[test] + fn cancel_all_preserves_targets_that_are_already_queued() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp_dir.path()); + let kv = kv(); + context.set_det_kv_override_for_test(kv); + let mut queued = scheduled_operation(DpnsVoteTargetStatus::Queued, 3, "queued"); + context + .insert_dpns_vote_operation(&mut queued, None) + .unwrap(); + + let outcomes = context.clear_all_scheduled_dpns_votes().unwrap(); + + assert_eq!( + context.dpns_vote_operations().unwrap()[0].targets[0].status, + DpnsVoteTargetStatus::Queued + ); + assert_eq!(outcomes.len(), 1); + assert_eq!( + outcomes[0].disposition, + DpnsScheduledVoteClearDisposition::InFlight(DpnsVoteTargetStatus::Queued) + ); + } + + #[test] + fn scheduled_removal_persists_cancelled() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let store = Arc::new(FailingKv::default()); + let kv = DetKv::from_store(store.clone()); + let context = crate::context::test_support::test_app_context_with_kv( + temp_dir.path(), + Arc::new(kv.clone()), + ); + context.set_det_kv_override_for_test(kv); + let mut scheduled = scheduled_operation(DpnsVoteTargetStatus::Scheduled, 2, "cancel-me"); + let key = scheduled.targets[0].target.key.clone(); + context + .insert_dpns_vote_operation(&mut scheduled, None) + .unwrap(); + + context + .remove_scheduled_dpns_vote(scheduled.id, &key) + .unwrap(); + + assert_eq!( + context.dpns_vote_operations().unwrap()[0].targets[0].status, + DpnsVoteTargetStatus::Cancelled + ); + } + + #[test] + fn stale_terminal_operation_cannot_remove_a_newer_locked_schedule() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp_dir.path()); + let kv = kv(); + context.set_det_kv_override_for_test(kv); + let mut terminal = scheduled_operation(DpnsVoteTargetStatus::Confirmed, 2, "same-target"); + let mut current = scheduled_operation(DpnsVoteTargetStatus::Scheduled, 2, "same-target"); + let key = current.targets[0].target.key.clone(); + context + .insert_dpns_vote_operation(&mut terminal, None) + .unwrap(); + context + .insert_dpns_vote_operation(&mut current, None) + .unwrap(); + + assert!(matches!( + context + .remove_scheduled_dpns_vote(terminal.id, &key) + .expect_err("stale terminal history must not remove the current schedule"), + TaskError::DpnsScheduledVoteAlreadyStarted + )); + assert!( + context + .dpns_vote_operations() + .unwrap() + .iter() + .any(|operation| { + operation.id == current.id + && operation.targets[0].status == DpnsVoteTargetStatus::Scheduled + }) + ); + } + + #[test] + fn clear_all_cancels_pending_and_retains_every_in_flight_target() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp_dir.path()); + let kv = kv(); + context.set_det_kv_override_for_test(kv); + let cases = [ + ("scheduled", DpnsVoteTargetStatus::Scheduled), + ("queued", DpnsVoteTargetStatus::Queued), + ("submitting", DpnsVoteTargetStatus::Submitting), + ("confirming", DpnsVoteTargetStatus::Confirming), + ("unconfirmed", DpnsVoteTargetStatus::Unconfirmed), + ("confirmed", DpnsVoteTargetStatus::Confirmed), + ]; + for (index, (name, status)) in cases.into_iter().enumerate() { + let mut operation = scheduled_operation(status, index as u8 + 2, name); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + } + let outcomes = context.clear_all_scheduled_dpns_votes().unwrap(); + assert_eq!(outcomes.len(), 6); + for (name, status) in [ + ("queued", DpnsVoteTargetStatus::Queued), + ("submitting", DpnsVoteTargetStatus::Submitting), + ("confirming", DpnsVoteTargetStatus::Confirming), + ("unconfirmed", DpnsVoteTargetStatus::Unconfirmed), + ] { + assert!(outcomes.iter().any(|outcome| { + outcome.key.contested_name == name + && outcome.disposition == DpnsScheduledVoteClearDisposition::InFlight(status) + })); + } + for name in ["scheduled", "confirmed"] { + assert!(outcomes.iter().any(|outcome| { + outcome.key.contested_name == name + && outcome.disposition == DpnsScheduledVoteClearDisposition::Cleared + })); + } + let remaining_operations = context.dpns_vote_operations().unwrap(); + assert_eq!( + remaining_operations + .iter() + .filter(|op| op.targets[0].status.holds_lock()) + .count(), + 4 + ); + assert!( + remaining_operations + .iter() + .any(|op| op.targets[0].status == DpnsVoteTargetStatus::Cancelled) + ); + } + + /// A corrupt indexed row must block lock reconstruction rather than being skipped. + #[test] + fn unreadable_indexed_operation_fails_closed() { + let store = Arc::new(InMemoryKv::default()); + let kv = DetKv::from_store(store.clone()); + let operation = operation(DpnsVoteTargetStatus::Unconfirmed); + persist_operation(&kv, Network::Testnet, &operation).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context_with_kv( + dir.path(), + Arc::new(kv.clone()), + ); + context.set_det_kv_override_for_test(kv.clone()); + let completed = scheduled_operation(DpnsVoteTargetStatus::Confirmed, 3, "readable"); + persist_operation(&kv, Network::Testnet, &completed).unwrap(); + let mut snapshot = + crate::ui::state::dpns_vote_operations::DpnsVoteOperationSnapshot::load(&context); + store + .put( + &ObjectId::Global, + &operation_key(Network::Testnet, operation.id), + &[0xff, 0x00], + ) + .unwrap(); + + assert!( + load_operations(&kv, Network::Testnet).is_err(), + "an unreadable lock record must never be treated as absent" + ); + assert!(snapshot.refresh(&context).is_err()); + assert!(snapshot.read_error().is_some()); + assert_eq!( + snapshot.target_status(&operation.targets[0].target.key), + Some(DpnsVoteTargetStatus::Unconfirmed) + ); + assert_eq!(snapshot.operation(completed.id), Some(&completed)); + let reopened = + crate::ui::state::dpns_vote_operations::DpnsVoteOperationSnapshot::load(&context); + assert!(reopened.read_error().is_some()); + assert!( + !reopened.is_loaded(), + "a failed read must not advertise a complete empty history" + ); + kv.put( + DetScope::Global, + &operation_lock_index_dirty_key(Network::Testnet), + &true, + ) + .unwrap(); + assert!( + load_or_rebuild_lock_index(&kv, Network::Testnet).is_err(), + "corruption must not permit a partial lock rebuild" + ); + kv.put( + DetScope::Global, + &operation_key(Network::Testnet, operation.id), + &operation, + ) + .unwrap(); + snapshot.refresh(&context).unwrap(); + assert!(snapshot.read_error().is_none()); + } + + #[test] + fn blocker_relative_metadata_preserves_legacy_binary_and_fails_closed_on_corruption() { + let store = Arc::new(InMemoryKv::default()); + let kv = DetKv::from_store(store.clone()); + let mut operation = operation(DpnsVoteTargetStatus::Unconfirmed); + let legacy_targets: Vec<_> = operation + .targets + .iter() + .map(|outcome| { + ( + outcome.operation_id, + &outcome.target, + outcome.status, + &outcome.failure, + ) + }) + .collect(); + // Frozen pre-metadata tuple layout, independent of the current struct serializer. + let legacy = bincode::serde::encode_to_vec( + ( + operation.id, + operation.created_at, + legacy_targets, + operation.no_op_count, + ), + bincode::config::standard(), + ) + .unwrap(); + operation.targets[0].relative_schedule_preset_ms = Some(600_000); + assert_eq!( + bincode::serde::encode_to_vec(&operation, bincode::config::standard()).unwrap(), + legacy + ); + let mut raw = vec![crate::wallet_backend::KV_SCHEMA_VERSION]; + raw.extend(legacy); + let key = operation_key(Network::Testnet, operation.id); + store.put(&ObjectId::Global, &key, &raw).unwrap(); + let saved = load_operation(&kv, &key).unwrap().unwrap(); + assert_eq!(saved.targets[0].status, DpnsVoteTargetStatus::Unconfirmed); + assert_eq!(saved.targets[0].relative_schedule_preset_ms, None); + assert_eq!( + load_or_rebuild_lock_index(&kv, Network::Testnet) + .unwrap() + .get(&saved.targets[0].target.key), + Some(&operation.id) + ); + store + .put( + &ObjectId::Global, + &key, + &[crate::wallet_backend::KV_SCHEMA_VERSION], + ) + .unwrap(); + assert!(load_operation(&kv, &key).is_err()); + assert!(rebuild_lock_index(&kv, Network::Testnet).is_err()); + } + + #[test] + fn blocker_relative_metadata_cleanup_retries_and_stale_time_never_displays() { + let store = Arc::new(FailingKv::default()); + let kv = DetKv::from_store(store.clone()); + let mut operation = scheduled_operation(DpnsVoteTargetStatus::Cancelled, 2, "label"); + operation.targets[0].relative_schedule_preset_ms = Some(600_000); + persist_operation(&kv, Network::Testnet, &operation).unwrap(); + let key = operation_key(Network::Testnet, operation.id); + let label_key = relative_labels_key(&key); + assert!(kv.contains(DetScope::Global, &label_key).unwrap()); + assert!( + load_operations_read_only(&kv, Network::Mainnet) + .unwrap() + .is_empty() + ); + // A failed display-metadata write cannot make an old preset describe a new time. + operation.targets[0].target.timing = VoteTiming::Scheduled(43); + operation.targets[0].relative_schedule_preset_ms = None; + store.fail_next_deletes_containing(RELATIVE_LABEL_KEY_PREFIX, 1); + persist_operation(&kv, Network::Testnet, &operation).unwrap(); + assert_eq!( + load_operation(&kv, &key).unwrap().unwrap().targets[0].relative_schedule_preset_ms, + None + ); + store.fail_next_deletes_containing(RELATIVE_LABEL_KEY_PREFIX, 1); + assert!(delete_terminal_operations(&kv, Network::Testnet, &[operation.id]).is_err()); + assert!( + kv.contains(DetScope::Global, &key).unwrap(), + "failed label cleanup keeps its owner discoverable" + ); + delete_terminal_operations(&kv, Network::Testnet, &[operation.id]).unwrap(); + assert!(!kv.contains(DetScope::Global, &label_key).unwrap()); + assert!(!kv.contains(DetScope::Global, &key).unwrap()); + } + + #[test] + fn network_qualified_journals_are_isolated() { + let kv = kv(); + persist_operation( + &kv, + Network::Testnet, + &operation(DpnsVoteTargetStatus::Unconfirmed), + ) + .unwrap(); + + assert_eq!(load_operations(&kv, Network::Testnet).unwrap().len(), 1); + assert!(load_operations(&kv, Network::Mainnet).unwrap().is_empty()); + } + + /// VOTE-FR-078: the durable count advances once per vote Platform applied, + /// and survives pruning of the operation that spent it. + #[test] + fn confirming_a_broadcast_target_counts_one_vote_that_outlives_the_record() { + let kv = kv(); + let mut operation = operation(DpnsVoteTargetStatus::Confirming); + let key = operation.targets[0].target.key.clone(); + persist_operation(&kv, Network::Testnet, &operation).unwrap(); + operation.targets[0].status = DpnsVoteTargetStatus::Confirmed; + persist_operation(&kv, Network::Testnet, &operation).unwrap(); + persist_operation(&kv, Network::Testnet, &operation).unwrap(); + + let count = + || counts::vote_count(&kv, Network::Testnet, key.voter_id, key.vote_poll_id).unwrap(); + assert_eq!( + count(), + Some(1), + "rewriting a confirmed target is not a new vote" + ); + kv.delete( + DetScope::Global, + &operation_key(Network::Testnet, operation.id), + ) + .unwrap(); + assert_eq!(count(), Some(1)); + + let mut no_op = super::tests::operation(DpnsVoteTargetStatus::Queued); + no_op.targets[0].target.key.vote_poll_id = Identifier::from([9; 32]); + persist_operation(&kv, Network::Testnet, &no_op).unwrap(); + no_op.targets[0].status = DpnsVoteTargetStatus::Confirmed; + persist_operation(&kv, Network::Testnet, &no_op).unwrap(); + assert_eq!( + counts::vote_count( + &kv, + Network::Testnet, + key.voter_id, + Identifier::from([9; 32]) + ) + .unwrap(), + None, + "a queued target confirmed as a no-op spent no vote" + ); + } + + /// A confirmation whose record write fails leaves the target unresolved, + /// and the next check confirms it again. That is still one vote. + #[test] + fn a_vote_confirmed_again_after_a_failed_record_write_is_counted_once() { + let store = Arc::new(FailingKv::default()); + let kv = DetKv::from_store(store.clone()); + let mut sent = operation(DpnsVoteTargetStatus::Confirming); + let key = sent.targets[0].target.key.clone(); + persist_operation(&kv, Network::Testnet, &sent).unwrap(); + let count = + || counts::vote_count(&kv, Network::Testnet, key.voter_id, key.vote_poll_id).unwrap(); + + sent.targets[0].status = DpnsVoteTargetStatus::Confirmed; + store.fail_next_puts_containing(OPERATION_KEY_PREFIX, 1); + assert!(persist_operation(&kv, Network::Testnet, &sent).is_err()); + // The executor's error path leaves the stored target unconfirmed. + sent.targets[0].status = DpnsVoteTargetStatus::Unconfirmed; + sent.targets[0].failure = Some(DpnsVoteFailure::ResultUnconfirmed); + persist_operation(&kv, Network::Testnet, &sent).unwrap(); + sent.targets[0].status = DpnsVoteTargetStatus::Confirmed; + sent.targets[0].failure = None; + persist_operation(&kv, Network::Testnet, &sent).unwrap(); + assert_eq!(count(), Some(1), "the same vote must not count twice"); + + let mut change = operation(DpnsVoteTargetStatus::Confirming); + persist_operation(&kv, Network::Testnet, &change).unwrap(); + change.targets[0].status = DpnsVoteTargetStatus::Confirmed; + persist_operation(&kv, Network::Testnet, &change).unwrap(); + assert_eq!(count(), Some(2), "a later change is another vote"); + } + + #[test] + fn persisted_lock_index_avoids_full_journal_reads_on_transition() { + let store = Arc::new(CountingKv::default()); + let kv = DetKv::from_store(store.clone()); + let mut first = operation(DpnsVoteTargetStatus::Queued); + let mut second = operation(DpnsVoteTargetStatus::Queued); + second.targets[0].target.key.vote_poll_id = Identifier::from([3; 32]); + persist_operation(&kv, Network::Testnet, &first).unwrap(); + persist_operation(&kv, Network::Testnet, &second).unwrap(); + + first.targets[0].status = DpnsVoteTargetStatus::Submitting; + store.reset_counts(); + persist_operation(&kv, Network::Testnet, &first).unwrap(); + + assert_eq!( + store.operation_get_count(), + 0, + "a status transition must consult the lock index, not every operation record" + ); + } + + #[test] + fn operation_getter_repairs_a_dirty_record_and_lock_index() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let store = Arc::new(InMemoryKv::default()); + let kv = DetKv::from_store(store.clone()); + let context = crate::context::test_support::test_app_context_with_kv( + temp_dir.path(), + Arc::new(DetKv::from_store(store)), + ); + context.set_det_kv_override_for_test(kv.clone()); + let operation = operation(DpnsVoteTargetStatus::Unconfirmed); + persist_operation(&kv, Network::Testnet, &operation).unwrap(); + kv.put( + DetScope::Global, + &operation_index_key(Network::Testnet), + &vec![ + operation.id.to_bytes(), + DpnsVoteOperationId::from_bytes([9; 16]).to_bytes(), + ], + ) + .unwrap(); + kv.put( + DetScope::Global, + &operation_lock_index_dirty_key(Network::Testnet), + &true, + ) + .unwrap(); + + assert_eq!(context.dpns_vote_operations().unwrap(), vec![operation]); + assert!( + kv.get::( + DetScope::Global, + &operation_lock_index_dirty_key(Network::Testnet), + ) + .unwrap() + .is_none(), + "a successful rebuild must clear the dirty marker" + ); + } + + #[test] + fn pruning_retains_scheduled_and_mixed_history_below_the_limit() { + let kv = kv(); + let mut scheduled = operation(DpnsVoteTargetStatus::Confirmed); + scheduled.targets[0].target.timing = VoteTiming::Scheduled(42); + scheduled.targets[0].target.contested_name = "scheduled".to_owned(); + let mut immediate = operation(DpnsVoteTargetStatus::Confirmed); + immediate.targets[0].target.contested_name = "immediate".to_owned(); + immediate.targets[0].target.key.vote_poll_id = Identifier::from([3; 32]); + let mut mixed = operation(DpnsVoteTargetStatus::Confirmed); + mixed.targets[0].target.contested_name = "mixed-immediate".to_owned(); + mixed.targets[0].target.key.vote_poll_id = Identifier::from([4; 32]); + let mut mixed_scheduled = mixed.targets[0].clone(); + mixed_scheduled.target.timing = VoteTiming::Scheduled(43); + mixed_scheduled.target.contested_name = "mixed-scheduled".to_owned(); + mixed_scheduled.target.key.vote_poll_id = Identifier::from([5; 32]); + mixed.targets.push(mixed_scheduled); + let live = operation(DpnsVoteTargetStatus::Unconfirmed); + persist_operation(&kv, Network::Testnet, &scheduled).unwrap(); + persist_operation(&kv, Network::Testnet, &immediate).unwrap(); + persist_operation(&kv, Network::Testnet, &mixed).unwrap(); + persist_operation(&kv, Network::Testnet, &live).unwrap(); + + assert_eq!(prune_terminal_operations(&kv, Network::Testnet).unwrap(), 0); + let remaining_ids = load_operations_read_only(&kv, Network::Testnet) + .unwrap() + .into_iter() + .map(|operation| operation.id) + .collect::>(); + assert_eq!( + remaining_ids, + BTreeSet::from([scheduled.id, mixed.id, immediate.id, live.id]) + ); + assert!( + kv.get::( + DetScope::Global, + &operation_key(Network::Testnet, scheduled.id), + ) + .unwrap() + .is_some() + ); + assert!( + kv.get::( + DetScope::Global, + &operation_key(Network::Testnet, immediate.id), + ) + .unwrap() + .is_some() + ); + assert!( + kv.get::( + DetScope::Global, + &operation_key(Network::Testnet, mixed.id), + ) + .unwrap() + .is_some() + ); + } + + #[test] + fn scheduled_and_mixed_history_is_bounded() { + let dir = tempfile::tempdir().unwrap(); + let context = + crate::context::test_support::test_app_context_with_kv(dir.path(), Arc::new(kv())); + context.set_det_kv_override_for_test(kv()); + let mut oldest = None; + // One completion past the prune threshold, so exactly one prune runs and + // trims the history back to its cap. + for index in 0..(DPNS_SCHEDULED_HISTORY_LIMIT + DPNS_HISTORY_PRUNE_SLACK + 1) as u64 { + let mut completed = scheduled_operation( + DpnsVoteTargetStatus::Confirmed, + 2, + &format!("history-{index}"), + ); + completed.created_at = index; + if index % 2 == 0 { + completed + .targets + .push(operation(DpnsVoteTargetStatus::Confirmed).targets.remove(0)); + } + if index == 0 { + oldest = Some(completed.id); + } + context + .insert_dpns_vote_operation(&mut completed, None) + .unwrap(); + } + let mut unresolved = + scheduled_operation(DpnsVoteTargetStatus::Unconfirmed, 3, "unresolved"); + unresolved + .targets + .push(operation(DpnsVoteTargetStatus::Confirmed).targets.remove(0)); + context + .insert_dpns_vote_operation(&mut unresolved, None) + .unwrap(); + assert_eq!(context.dpns_vote_operations().unwrap().len(), 257); + assert!( + context + .dpns_vote_operation(oldest.unwrap()) + .unwrap() + .is_none() + ); + context.prune_terminal_dpns_vote_operations().unwrap(); + assert_eq!(context.dpns_vote_operations().unwrap().len(), 257); + } + + #[test] + fn terminal_immediate_history_is_bounded_without_pruning_unresolved_votes() { + let kv = kv(); + let mut ids = Vec::new(); + for created_at in 0..258 { + let mut completed = operation(DpnsVoteTargetStatus::Confirmed); + completed.created_at = created_at; + ids.push(completed.id); + persist_operation(&kv, Network::Testnet, &completed).unwrap(); + } + let unresolved = operation(DpnsVoteTargetStatus::Unconfirmed); + persist_operation(&kv, Network::Testnet, &unresolved).unwrap(); + + prune_terminal_operations(&kv, Network::Testnet).unwrap(); + let remaining = load_operations_read_only(&kv, Network::Testnet).unwrap(); + assert_eq!(remaining.len(), 257); + assert!(remaining.iter().any(|item| item.id == unresolved.id)); + assert!(remaining.iter().all(|item| !ids[..2].contains(&item.id))); + assert!(remaining.iter().any(|item| item.id == ids[257])); + assert_eq!( + load_or_rebuild_lock_index(&kv, Network::Testnet) + .unwrap() + .len(), + 1 + ); + } + + #[test] + fn oldest_created_vote_is_retained_when_it_finishes_after_newer_batches() { + let kv = kv(); + let mut delayed = operation(DpnsVoteTargetStatus::Unconfirmed); + delayed.created_at = 0; + persist_operation(&kv, Network::Testnet, &delayed).unwrap(); + for created_at in 1..=256 { + let mut completed = operation(DpnsVoteTargetStatus::Confirmed); + completed.created_at = created_at; + persist_operation(&kv, Network::Testnet, &completed).unwrap(); + } + delayed.targets[0].status = DpnsVoteTargetStatus::Confirmed; + persist_operation(&kv, Network::Testnet, &delayed).unwrap(); + assert!( + kv.get::( + DetScope::Global, + &operation_key(Network::Testnet, delayed.id) + ) + .unwrap() + .is_some() + ); + prune_completed_history(&kv, Network::Testnet, None, HistoryKind::Immediate).unwrap(); + let remaining = load_operations_read_only(&kv, Network::Testnet).unwrap(); + assert_eq!(remaining.len(), 256); + assert!(remaining.iter().any(|item| item.id == delayed.id)); + } + + #[test] + fn schedule_edit_preserves_operation_lock_and_siblings_and_rejects_stale_edits() { + let dir = tempfile::tempdir().unwrap(); + let context = + crate::context::test_support::test_app_context_with_kv(dir.path(), Arc::new(kv())); + context.set_det_kv_override_for_test(kv()); + let mut scheduled = scheduled_operation(DpnsVoteTargetStatus::Scheduled, 2, "edit-me"); + scheduled.targets[0].target.timing = VoteTiming::Scheduled(u64::MAX - 2); + let sibling = scheduled_operation(DpnsVoteTargetStatus::Scheduled, 3, "sibling") + .targets + .remove(0); + scheduled.targets.push(sibling); + for outcome in &mut scheduled.targets { + outcome.relative_schedule_preset_ms = Some(600_000); + } + context + .insert_dpns_vote_operation(&mut scheduled, None) + .unwrap(); + let edit = DpnsScheduledVoteEdit { + operation_id: scheduled.id, + key: scheduled.targets[0].target.key.clone(), + expected_choice: ResourceVoteChoice::Lock, + expected_timestamp: u64::MAX - 2, + choice: ResourceVoteChoice::Abstain, + unix_timestamp: u64::MAX - 1, + }; + let choice_only = DpnsScheduledVoteEdit { + unix_timestamp: edit.expected_timestamp, + ..edit.clone() + }; + context + .edit_scheduled_dpns_vote_target(&choice_only) + .unwrap(); + assert_eq!( + context + .dpns_vote_operation(scheduled.id) + .unwrap() + .unwrap() + .targets[0] + .relative_schedule_preset_ms, + Some(600_000) + ); + let edit = DpnsScheduledVoteEdit { + expected_choice: choice_only.choice, + ..edit + }; + let id = context.edit_scheduled_dpns_vote_target(&edit).unwrap(); + assert_eq!(id, scheduled.id); + let saved = context.dpns_vote_operation(id).unwrap().unwrap(); + assert_eq!(saved.targets[1], scheduled.targets[1]); + assert_eq!(saved.targets[0].relative_schedule_preset_ms, None); + assert_eq!( + saved.targets[0].target.requested_choice, + ResourceVoteChoice::Abstain + ); + assert_eq!( + saved.targets[0].target.timing, + VoteTiming::Scheduled(edit.unix_timestamp) + ); + assert_eq!( + context.dpns_vote_target_status(&edit.key).unwrap(), + Some(DpnsVoteTargetStatus::Scheduled) + ); + assert!(matches!( + context.edit_scheduled_dpns_vote_target(&edit), + Err(TaskError::DpnsScheduledVoteNotEditable) + )); + let refreshed = DpnsScheduledVoteEdit { + expected_choice: edit.choice, + expected_timestamp: edit.unix_timestamp, + ..edit + }; + context + .queue_scheduled_dpns_vote_target(id, &refreshed.key) + .unwrap(); + assert!(matches!( + context.edit_scheduled_dpns_vote_target(&refreshed), + Err(TaskError::DpnsScheduledVoteNotEditable) + )); + } + + #[test] + fn schedule_edit_rejects_wrong_identity_poll_network_and_past_time_without_mutation() { + let dir = tempfile::tempdir().unwrap(); + let context = + crate::context::test_support::test_app_context_with_kv(dir.path(), Arc::new(kv())); + context.set_det_kv_override_for_test(kv()); + let mut scheduled = scheduled_operation(DpnsVoteTargetStatus::Scheduled, 2, "edit-me"); + context + .insert_dpns_vote_operation(&mut scheduled, None) + .unwrap(); + let edit = DpnsScheduledVoteEdit { + operation_id: scheduled.id, + key: scheduled.targets[0].target.key.clone(), + expected_choice: ResourceVoteChoice::Lock, + expected_timestamp: 42, + choice: ResourceVoteChoice::Abstain, + unix_timestamp: u64::MAX - 1, + }; + let mut invalid = vec![edit.clone(); 4]; + invalid[0].key.voter_id = Identifier::from([99; 32]); + invalid[1].key.vote_poll_id = Identifier::from([99; 32]); + invalid[2].key.network = Network::Mainnet; + invalid[3].operation_id = DpnsVoteOperationId::from_bytes(rand::random()); + for request in invalid { + assert!(matches!( + context.edit_scheduled_dpns_vote_target(&request), + Err(TaskError::DpnsScheduledVoteNotEditable) + )); + } + assert!(matches!( + context.edit_scheduled_dpns_vote_target(&DpnsScheduledVoteEdit { + unix_timestamp: 1, + ..edit + }), + Err(TaskError::DpnsScheduledVoteInvalidTime) + )); + assert_eq!( + context.dpns_vote_operation(scheduled.id).unwrap(), + Some(scheduled) + ); + } + + #[test] + fn immediate_history_delete_failure_is_retried_without_losing_unresolved_locks() { + let store = Arc::new(FailingKv::default()); + let kv = DetKv::from_store(store.clone()); + // Fill the history to the prune threshold so the `newest` write below is + // the one that prunes, and meets the injected delete failure. + let prune_threshold = DPNS_IMMEDIATE_HISTORY_LIMIT + DPNS_HISTORY_PRUNE_SLACK; + for created_at in 0..prune_threshold as u64 { + let mut completed = operation(DpnsVoteTargetStatus::Confirmed); + completed.created_at = created_at; + persist_operation(&kv, Network::Testnet, &completed).unwrap(); + } + let unresolved = operation(DpnsVoteTargetStatus::Unconfirmed); + persist_operation(&kv, Network::Testnet, &unresolved).unwrap(); + store.fail_next_deletes_containing(OPERATION_KEY_PREFIX, 1); + let newest = operation(DpnsVoteTargetStatus::Confirmed); + persist_operation(&kv, Network::Testnet, &newest).unwrap(); + assert_eq!( + load_operations(&kv, Network::Testnet).unwrap().len(), + prune_threshold + 2, + "a failed cleanup must retain every record" + ); + assert_eq!( + prune_completed_history(&kv, Network::Testnet, None, HistoryKind::Immediate).unwrap(), + DPNS_HISTORY_PRUNE_SLACK + 1 + ); + let remaining = load_operations(&kv, Network::Testnet).unwrap(); + assert_eq!(remaining.len(), DPNS_IMMEDIATE_HISTORY_LIMIT + 1); + assert!(remaining.iter().any(|item| item.id == newest.id)); + assert_eq!( + load_or_rebuild_lock_index(&kv, Network::Testnet) + .unwrap() + .get(&unresolved.targets[0].target.key), + Some(&unresolved.id) + ); + } + + #[test] + fn orphaned_schedule_dismissal_cleanup_retries_after_record_deletion() { + let store = Arc::new(FailingKv::default()); + let kv = DetKv::from_store(store.clone()); + let completed = scheduled_operation(DpnsVoteTargetStatus::Confirmed, 2, "dismissed"); + persist_operation(&kv, Network::Testnet, &completed).unwrap(); + dismiss_scheduled_target( + &kv, + Network::Testnet, + completed.id, + &completed.targets[0].target.key, + ) + .unwrap(); + let unresolved = scheduled_operation(DpnsVoteTargetStatus::Unconfirmed, 3, "unresolved"); + persist_operation(&kv, Network::Testnet, &unresolved).unwrap(); + dismiss_scheduled_target( + &kv, + Network::Testnet, + unresolved.id, + &unresolved.targets[0].target.key, + ) + .unwrap(); + store.fail_next_deletes_containing(SCHEDULE_DISMISSAL_KEY_PREFIX, 1); + assert!(delete_terminal_operations(&kv, Network::Testnet, &[completed.id]).is_err()); + assert!( + kv.get::( + DetScope::Global, + &operation_key(Network::Testnet, completed.id) + ) + .unwrap() + .is_none() + ); + prune_terminal_operations(&kv, Network::Testnet).unwrap(); + assert!( + kv.get::>( + DetScope::Global, + &schedule_dismissal_key(Network::Testnet, completed.id) + ) + .unwrap() + .is_none(), + "retry must remove the orphaned dismissal sidecar" + ); + assert!( + kv.get::>( + DetScope::Global, + &schedule_dismissal_key(Network::Testnet, unresolved.id) + ) + .unwrap() + .is_some() + ); + } + + #[test] + fn clearing_confirmed_schedules_preserves_failures_and_in_flight_locks() { + let dir = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(dir.path()); + context.set_det_kv_override_for_test(kv()); + let statuses = [ + DpnsVoteTargetStatus::Confirmed, + DpnsVoteTargetStatus::FailedBeforeSubmission, + DpnsVoteTargetStatus::Unconfirmed, + ]; + let mut operations = Vec::new(); + for (i, status) in statuses.into_iter().enumerate() { + let mut op = scheduled_operation(status, i as u8 + 1, &format!("schedule-{i}")); + context.insert_dpns_vote_operation(&mut op, None).unwrap(); + operations.push(op); + } + context.clear_executed_scheduled_votes().unwrap(); + let rows = + crate::ui::state::dpns_vote_operations::DpnsVoteOperationSnapshot::load(&context) + .scheduled_vote_rows(); + assert_eq!(rows.len(), 2); + assert!( + rows.iter() + .all(|row| row.status != DpnsVoteTargetStatus::Confirmed) + ); + for op in &operations { + assert_eq!( + context.dpns_vote_operation(op.id).unwrap().as_ref(), + Some(op) + ); + } + assert_eq!( + context + .dpns_vote_target_status(&operations[2].targets[0].target.key) + .unwrap(), + Some(DpnsVoteTargetStatus::Unconfirmed) + ); + } + + #[test] + fn terminal_schedule_dismissal_preserves_outcome() { + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(FailingKv::default()); + let context = crate::context::test_support::test_app_context_with_kv( + dir.path(), + Arc::new(DetKv::from_store(store.clone())), + ); + context.set_det_kv_override_for_test(DetKv::from_store(store.clone())); + let mut completed = scheduled_operation(DpnsVoteTargetStatus::Confirmed, 2, "dismiss-me"); + context + .insert_dpns_vote_operation(&mut completed, None) + .unwrap(); + let key = &completed.targets[0].target.key; + context + .remove_scheduled_dpns_vote(completed.id, key) + .unwrap(); + assert_eq!( + context.dpns_vote_operation(completed.id).unwrap(), + Some(completed.clone()) + ); + assert!( + context + .dismissed_dpns_vote_schedules() + .unwrap() + .contains(&(completed.id, key.clone())) + ); + } + + #[test] + fn diagnostics_evict_the_least_recently_recorded_entry() { + let mut diagnostics = BTreeMap::new(); + let first_key = ( + DpnsVoteOperationId::from_bytes([1; 16]), + operation(DpnsVoteTargetStatus::Queued).targets[0] + .target + .key + .clone(), + ); + let second_key = ( + DpnsVoteOperationId::from_bytes([2; 16]), + operation(DpnsVoteTargetStatus::Queued).targets[0] + .target + .key + .clone(), + ); + insert_diagnostic( + &mut diagnostics, + first_key.clone(), + 1, + Arc::new(TaskError::DpnsVoteTargetBusy), + 1, + ); + insert_diagnostic( + &mut diagnostics, + second_key.clone(), + 2, + Arc::new(TaskError::DpnsVoteTargetBusy), + 1, + ); + + assert!(!diagnostics.contains_key(&first_key)); + assert!(diagnostics.contains_key(&second_key)); + } + + /// Inserting is for new operations only: a second insert under the same ID + /// must not put a claimed target back in the queue. + #[test] + fn inserting_an_existing_operation_id_cannot_requeue_a_claimed_target() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(kv()); + let mut operation = operation(DpnsVoteTargetStatus::Queued); + let key = operation.targets[0].target.key.clone(); + ctx.insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + let mut duplicate = operation.clone(); + assert!(ctx.claim_dpns_vote_target(operation.id, &key).unwrap()); + assert!(ctx.mark_dpns_vote_broadcast(operation.id, &key).unwrap()); + + assert!(matches!( + ctx.insert_dpns_vote_operation(&mut duplicate, None), + Err(TaskError::DpnsVoteTargetBusy) + )); + + assert_eq!( + ctx.dpns_vote_operation(operation.id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Confirming, + "the broadcast marker must survive" + ); + assert!( + !ctx.claim_dpns_vote_target(operation.id, &key).unwrap(), + "a broadcast target must not become claimable again" + ); + } + + /// A vote still queued from an earlier run must not go out by itself long + /// after it was reviewed; one queued moments ago is still sent. + #[test] + fn restart_recovery_does_not_send_an_immediate_vote_queued_long_ago() { + use crate::model::dpns_voting::SCHEDULED_VOTE_MAX_LATENESS_MS; + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(kv()); + let mut stale = operation(DpnsVoteTargetStatus::Queued); + stale.created_at = now_ms() - SCHEDULED_VOTE_MAX_LATENESS_MS - 1_000; + let stale_key = stale.targets[0].target.key.clone(); + ctx.insert_dpns_vote_operation(&mut stale, None).unwrap(); + let mut fresh = operation(DpnsVoteTargetStatus::Queued); + fresh.targets[0].target.key.voter_id = Identifier::from([7; 32]); + let fresh_key = fresh.targets[0].target.key.clone(); + ctx.insert_dpns_vote_operation(&mut fresh, None).unwrap(); + let session_start = now_ms(); + + ctx.recover_interrupted_dpns_vote_operations().unwrap(); + + let recovered = ctx.dpns_vote_operation(stale.id).unwrap().unwrap(); + assert_eq!( + recovered.targets[0].status, + DpnsVoteTargetStatus::FailedBeforeSubmission + ); + assert_eq!( + recovered.targets[0].failure, + Some(DpnsVoteFailure::SubmissionFailed) + ); + assert_eq!( + ctx.dpns_vote_target_status(&stale_key).unwrap(), + None, + "nothing was broadcast, so the target is free to be voted again" + ); + assert!( + recovered.targets[0] + .recovered_at_ms + .is_some_and(|recovered_at| recovered_at >= session_start), + "the stop is dated in this session, not by the operation's age" + ); + let operations = ctx.dpns_vote_operations().unwrap(); + assert_eq!( + crate::model::dpns_voting::progress::needs_attention( + &operations, + session_start, + &BTreeSet::new(), + now_ms(), + ) + .failed, + 1, + "the stopped vote must be reported to the operator after the restart" + ); + assert!( + crate::model::dpns_voting::progress::drawer_operations( + &operations, + session_start, + &BTreeSet::new(), + ) + .into_iter() + .any(|operation| operation.id == stale.id), + "the progress drawer must list the stopped vote with its Review again action" + ); + assert_eq!( + ctx.dpns_vote_target_status(&fresh_key).unwrap(), + Some(DpnsVoteTargetStatus::Queued) + ); + } + + /// An admitted schedule interrupted by a restart is redriven only close + /// to its time; later it is a missed schedule the operator decides on. + #[test] + fn restart_recovery_returns_an_overdue_admitted_schedule_to_scheduled() { + let now = 10_000_000; + let mut overdue = scheduled_operation(DpnsVoteTargetStatus::Queued, 2, "dominguez"); + let mut due = scheduled_operation(DpnsVoteTargetStatus::Queued, 3, "other"); + due.targets[0].target.timing = VoteTiming::Scheduled(now - 1_000); + let mut running = scheduled_operation(DpnsVoteTargetStatus::Confirming, 4, "third"); + let running_before = running.clone(); + + assert!(expire_stale_queued_targets(&mut overdue, now)); + assert_eq!(overdue.targets[0].status, DpnsVoteTargetStatus::Scheduled); + assert_eq!( + overdue.targets[0].failure, + Some(DpnsVoteFailure::SubmissionFailed) + ); + assert!(!expire_stale_queued_targets(&mut due, now)); + assert_eq!(due.targets[0].status, DpnsVoteTargetStatus::Queued); + assert!(!expire_stale_queued_targets(&mut running, now)); + assert_eq!(running, running_before); + } + + /// A recovered vote reviewed as a first vote must not be sent as a change + /// when Platform now shows a different vote for the node. + #[test] + fn a_recovered_first_vote_that_became_a_change_is_not_sent() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(kv()); + let observed = DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Abstain)); + + let mut first_vote = operation(DpnsVoteTargetStatus::Queued); + let key = first_vote.targets[0].target.key.clone(); + ctx.insert_dpns_vote_operation(&mut first_vote, None) + .unwrap(); + ctx.recover_interrupted_dpns_vote_operations().unwrap(); + assert!( + !ctx.revalidate_queued_dpns_vote_target(first_vote.id, &key, observed) + .unwrap() + ); + let saved = ctx.dpns_vote_operation(first_vote.id).unwrap().unwrap(); + assert_eq!( + saved.targets[0].status, + DpnsVoteTargetStatus::FailedBeforeSubmission + ); + assert!( + saved.targets[0].recovered_at_ms.is_some(), + "the stop is dated by the recovery that queued the vote again" + ); + assert_eq!(ctx.dpns_vote_target_status(&key).unwrap(), None); + + let mut reviewed_change = operation(DpnsVoteTargetStatus::Queued); + reviewed_change.targets[0].target.key.voter_id = Identifier::from([7; 32]); + reviewed_change.targets[0].target.current_choice = Some( + ResourceVoteChoice::TowardsIdentity(Identifier::from([9; 32])), + ); + let change_key = reviewed_change.targets[0].target.key.clone(); + ctx.insert_dpns_vote_operation(&mut reviewed_change, None) + .unwrap(); + assert!( + ctx.revalidate_queued_dpns_vote_target(reviewed_change.id, &change_key, observed) + .unwrap(), + "a vote reviewed as a change stays queued" + ); + let saved = ctx + .dpns_vote_operation(reviewed_change.id) + .unwrap() + .unwrap(); + assert_eq!(saved.targets[0].status, DpnsVoteTargetStatus::Queued); + assert_eq!( + saved.targets[0].target.current_choice, + Some(ResourceVoteChoice::Abstain) + ); + } + + #[test] + fn interrupted_immediate_submission_recovers_before_submission() { + let mut operation = operation(DpnsVoteTargetStatus::Submitting); + assert!(recover_interrupted_target_statuses(&mut operation, |_| { + true + })); + assert_eq!( + operation.targets[0].status, + DpnsVoteTargetStatus::FailedBeforeSubmission + ); + assert_eq!( + operation.targets[0].failure, + Some(DpnsVoteFailure::SubmissionFailed) + ); + } + + #[test] + fn interrupted_scheduled_submission_is_restored_for_retry() { + let mut operation = operation(DpnsVoteTargetStatus::Submitting); + operation.targets[0].target.timing = VoteTiming::Scheduled(42); + + assert!(recover_interrupted_target_statuses(&mut operation, |_| { + true + })); + assert_eq!(operation.targets[0].status, DpnsVoteTargetStatus::Scheduled); + assert_eq!( + operation.targets[0].failure, + Some(DpnsVoteFailure::SubmissionFailed) + ); + } + + #[test] + fn interrupted_confirmation_recovers_to_unconfirmed() { + let mut operation = operation(DpnsVoteTargetStatus::Confirming); + + assert!(recover_interrupted_target_statuses(&mut operation, |_| { + true + })); + assert_eq!( + operation.targets[0].status, + DpnsVoteTargetStatus::Unconfirmed + ); + assert_eq!( + operation.targets[0].failure, + Some(DpnsVoteFailure::ResultUnconfirmed) + ); + } + + #[test] + fn marking_broadcast_crosses_the_durable_phase_boundary() { + let kv = kv(); + let submitting = operation(DpnsVoteTargetStatus::Submitting); + let key = submitting.targets[0].target.key.clone(); + persist_operation(&kv, Network::Testnet, &submitting).unwrap(); + + mark_target_broadcast(&kv, Network::Testnet, submitting.id, &key).unwrap(); + + assert_eq!( + load_operations(&kv, Network::Testnet).unwrap()[0].targets[0].status, + DpnsVoteTargetStatus::Confirming + ); + } + + #[test] + fn marking_broadcast_fails_closed_without_submitting_target() { + let kv = kv(); + let confirmed = operation(DpnsVoteTargetStatus::Confirmed); + let missing_key = DpnsVoteTargetKey { + vote_poll_id: Identifier::from([9; 32]), + ..confirmed.targets[0].target.key.clone() + }; + + assert!( + !mark_target_broadcast( + &kv, + Network::Testnet, + confirmed.id, + &confirmed.targets[0].target.key, + ) + .unwrap() + ); + persist_operation(&kv, Network::Testnet, &confirmed).unwrap(); + assert!( + !mark_target_broadcast(&kv, Network::Testnet, confirmed.id, &missing_key,).unwrap() + ); + assert!( + !mark_target_broadcast( + &kv, + Network::Testnet, + confirmed.id, + &confirmed.targets[0].target.key, + ) + .unwrap() + ); + } +} diff --git a/src/context/dpns_vote_operations/retention.rs b/src/context/dpns_vote_operations/retention.rs new file mode 100644 index 000000000..66932da57 --- /dev/null +++ b/src/context/dpns_vote_operations/retention.rs @@ -0,0 +1,236 @@ +//! Retention for completed vote batches and their dismissal and display metadata. +//! +//! Only lock-releasing operations are ever retired: unresolved work is never +//! capped, so a target that still holds its lock cannot be pruned away. + +use super::keys::*; +use super::{load_operations, rebuild_lock_index}; +use crate::backend_task::error::TaskError; +use crate::model::dpns_voting::{ + DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, +}; +use crate::wallet_backend::{DetKv, DetScope, network_prefix}; +use dash_sdk::dpp::dashcore::Network; +use std::collections::BTreeSet; + +/// Completed immediate batches retained per network; unresolved work is never capped. +pub(super) const DPNS_IMMEDIATE_HISTORY_LIMIT: usize = 256; +pub(super) const DPNS_SCHEDULED_HISTORY_LIMIT: usize = 256; +/// Completed records tolerated above a retention limit before pruning runs. +/// +/// Every completing write would otherwise rescan the whole journal, so a bulk +/// vote across a large node fleet serialised one full scan per node against the +/// UI's own journal reads. Eviction is amortised over this many completions +/// instead; the cost is retaining up to that many extra completed records. +pub(super) const DPNS_HISTORY_PRUNE_SLACK: usize = 64; + +pub(super) fn dismiss_scheduled_target( + kv: &DetKv, + network: Network, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, +) -> Result<(), TaskError> { + let storage_key = schedule_dismissal_key(network, operation_id); + let mut dismissed: BTreeSet = kv + .get(DetScope::Global, &storage_key) + .map_err(unreadable_operation_err)? + .unwrap_or_default(); + if dismissed.insert(key.clone()) { + kv.put(DetScope::Global, &storage_key, &dismissed) + .map_err(operation_err)?; + } + Ok(()) +} + +/// Dismiss confirmed schedule rows under the journal guard. +pub(crate) fn dismiss_confirmed_scheduled_targets( + kv: &DetKv, + network: Network, +) -> Result<(), TaskError> { + for operation in load_operations(kv, network)? { + for outcome in operation.targets.iter().filter(|outcome| { + outcome.status == DpnsVoteTargetStatus::Confirmed + && matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + }) { + dismiss_scheduled_target(kv, network, operation.id, &outcome.target.key)?; + } + } + Ok(()) +} + +/// Which retention list a completed operation belongs to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum HistoryKind { + Immediate, + Scheduled, +} + +impl HistoryKind { + /// One scheduled target makes the whole batch scheduled history. + pub(super) fn of(operation: &DpnsVoteOperation) -> Self { + if operation + .targets + .iter() + .any(|outcome| matches!(outcome.target.timing, VoteTiming::Scheduled(_))) + { + Self::Scheduled + } else { + Self::Immediate + } + } + + pub(super) fn key_prefix_and_limit(self) -> (&'static str, usize) { + match self { + Self::Immediate => (IMMEDIATE_HISTORY_KEY_PREFIX, DPNS_IMMEDIATE_HISTORY_LIMIT), + Self::Scheduled => (SCHEDULED_HISTORY_KEY_PREFIX, DPNS_SCHEDULED_HISTORY_LIMIT), + } + } +} + +pub(crate) fn prune_terminal_operations(kv: &DetKv, network: Network) -> Result { + let scheduled_count = prune_completed_history(kv, network, None, HistoryKind::Scheduled)?; + let immediate_count = prune_completed_history(kv, network, None, HistoryKind::Immediate)?; + prune_orphaned_schedule_dismissals(kv, network)?; + Ok(scheduled_count + immediate_count) +} + +pub(super) fn prune_completed_history( + kv: &DetKv, + network: Network, + newly_completed: Option, + kind: HistoryKind, +) -> Result { + let (prefix, limit) = kind.key_prefix_and_limit(); + let history_key = format!("{prefix}{}", network_prefix(network)); + let previous: Vec = kv + .get(DetScope::Global, &history_key) + .map_err(unreadable_operation_err)? + .unwrap_or_default(); + // Reconciling the completion order against the journal costs a full scan, so + // a write that merely completes an operation records its order and stops + // while the slack lasts. Recovery (`newly_completed` is `None`) always + // reconciles. + if let Some(id) = newly_completed + && previous.len() < limit + DPNS_HISTORY_PRUNE_SLACK + { + let mut ordered = previous.clone(); + ordered.retain(|existing| *existing != id); + ordered.push(id); + if ordered != previous { + kv.put(DetScope::Global, &history_key, &ordered) + .map_err(operation_err)?; + } + return Ok(0); + } + let operations = load_operations(kv, network)?; + let mut terminal = operations + .iter() + .filter(|operation| operation.is_complete() && HistoryKind::of(operation) == kind) + .collect::>(); + terminal.sort_unstable_by_key(|operation| (operation.created_at, operation.id)); + let terminal_ids = terminal + .iter() + .map(|operation| operation.id) + .collect::>(); + let mut ordered = terminal + .iter() + .map(|operation| operation.id) + .filter(|id| !previous.contains(id)) + .collect::>(); + ordered.extend( + previous + .iter() + .filter(|id| terminal_ids.contains(id)) + .copied(), + ); + if let Some(id) = newly_completed { + ordered.retain(|existing| *existing != id); + ordered.push(id); + } + // Persist deletion candidates as well as survivors before deleting records. + // A partial failure retains the completion order and is retried at recovery. + if ordered != previous { + kv.put(DetScope::Global, &history_key, &ordered) + .map_err(operation_err)?; + } + let remove_count = ordered.len().saturating_sub(limit); + let removed = delete_terminal_operations(kv, network, &ordered[..remove_count])?; + if remove_count > 0 { + ordered.drain(..remove_count); + kv.put(DetScope::Global, &history_key, &ordered) + .map_err(operation_err)?; + } + Ok(removed) +} + +/// Remove orphan display and dismissal metadata left by interrupted cleanup. +/// A record delete may succeed before its dismissal-sidecar delete fails. +/// Recover directly from the owned key namespaces so rebuilding the operation +/// index cannot make that cleanup obligation unreachable. +pub(super) fn prune_orphaned_schedule_dismissals( + kv: &DetKv, + network: Network, +) -> Result<(), TaskError> { + let operation_prefix = operation_key_prefix(network); + let dismissal_prefix = format!( + "{SCHEDULE_DISMISSAL_KEY_PREFIX}{}:", + network_prefix(network) + ); + let live_suffixes = kv + .list(DetScope::Global, Some(&operation_prefix)) + .map_err(unreadable_operation_err)? + .into_iter() + .filter_map(|key| key.strip_prefix(&operation_prefix).map(str::to_owned)) + .collect::>(); + let relative_prefix = format!("{RELATIVE_LABEL_KEY_PREFIX}{}:", network_prefix(network)); + let recovery_prefix = format!("{RECOVERY_TIME_KEY_PREFIX}{}:", network_prefix(network)); + for prefix in [dismissal_prefix, relative_prefix, recovery_prefix] { + for key in kv + .list(DetScope::Global, Some(&prefix)) + .map_err(unreadable_operation_err)? + { + if key + .strip_prefix(&prefix) + .is_some_and(|suffix| !live_suffixes.contains(suffix)) + { + kv.delete(DetScope::Global, &key).map_err(operation_err)?; + } + } + } + Ok(()) +} + +pub(super) fn delete_terminal_operations( + kv: &DetKv, + network: Network, + terminal_ids: &[DpnsVoteOperationId], +) -> Result { + if terminal_ids.is_empty() { + return Ok(0); + } + kv.put( + DetScope::Global, + &operation_lock_index_dirty_key(network), + &true, + ) + .map_err(operation_err)?; + for id in terminal_ids { + // Keep the owner discoverable if deleting its display metadata fails. + kv.delete( + DetScope::Global, + &relative_labels_key(&operation_key(network, *id)), + ) + .map_err(operation_err)?; + kv.delete( + DetScope::Global, + &recovery_times_key(&operation_key(network, *id)), + ) + .map_err(operation_err)?; + kv.delete(DetScope::Global, &operation_key(network, *id)) + .map_err(operation_err)?; + kv.delete(DetScope::Global, &schedule_dismissal_key(network, *id)) + .map_err(operation_err)?; + } + rebuild_lock_index(kv, network)?; + Ok(terminal_ids.len()) +} diff --git a/src/context/dpns_vote_operations/transitions.rs b/src/context/dpns_vote_operations/transitions.rs new file mode 100644 index 000000000..5e212ee69 --- /dev/null +++ b/src/context/dpns_vote_operations/transitions.rs @@ -0,0 +1,183 @@ +//! The per-target state machine, expressed as guarded read-modify-writes. +//! +//! Each transition names the status it will act on and leaves every other +//! status untouched, so a target can only ever advance along one path. + +use super::keys::*; +use super::{load_operation, persist_operation}; +use crate::backend_task::error::TaskError; +use crate::model::dpns_voting::{ + DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTargetKey, + DpnsVoteTargetStatus, VoteTiming, dpns_schedule_is_overdue, failed_before_broadcast_outcome, +}; +use crate::wallet_backend::DetKv; +use dash_sdk::dpp::dashcore::Network; + +/// What [`with_target`] should do once its mutator has inspected an outcome. +pub(super) enum TargetUpdate { + /// Persist the mutated operation, then yield `T`. + Persist(T), + /// Leave the stored record untouched, but still yield `T`. + Skip(T), +} + +/// Run one guarded read-modify-write against a single journal target. +/// +/// The caller must already hold the journal guard. `mutate` sees the outcome +/// matching `key` and decides whether its change is worth a write; returns +/// `Ok(None)` when the operation record or the target is gone, which is the +/// single place the missing-record policy lives. +pub(super) fn with_target( + kv: &DetKv, + network: Network, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, + mutate: impl FnOnce(&mut DpnsVoteOutcome) -> TargetUpdate, +) -> Result, TaskError> { + let Some(mut operation): Option = + load_operation(kv, &operation_key(network, operation_id)) + .map_err(unreadable_operation_err)? + else { + return Ok(None); + }; + let Some(outcome) = operation + .targets + .iter_mut() + .find(|outcome| outcome.target.key == *key) + else { + return Ok(None); + }; + match mutate(outcome) { + TargetUpdate::Persist(value) => { + persist_operation(kv, network, &operation)?; + Ok(Some(value)) + } + TargetUpdate::Skip(value) => Ok(Some(value)), + } +} + +pub(super) fn transition_scheduled_target_to_queued( + kv: &DetKv, + network: Network, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, +) -> Result { + Ok(with_target(kv, network, operation_id, key, |outcome| { + if outcome.status != DpnsVoteTargetStatus::Scheduled { + return TargetUpdate::Skip(false); + } + outcome.status = DpnsVoteTargetStatus::Queued; + TargetUpdate::Persist(true) + })? + .unwrap_or(false)) +} + +pub(super) fn cancel_scheduled_target( + kv: &DetKv, + network: Network, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, +) -> Result { + Ok(with_target(kv, network, operation_id, key, |outcome| { + if outcome.status != DpnsVoteTargetStatus::Scheduled { + return TargetUpdate::Skip(false); + } + outcome.status = DpnsVoteTargetStatus::Cancelled; + outcome.failure = None; + TargetUpdate::Persist(true) + })? + .unwrap_or(false)) +} + +pub(super) fn recover_interrupted_target_statuses( + operation: &mut DpnsVoteOperation, + includes: impl Fn(&DpnsVoteTargetKey) -> bool, +) -> bool { + let mut changed = false; + for outcome in &mut operation.targets { + if !includes(&outcome.target.key) { + continue; + } + match outcome.status { + DpnsVoteTargetStatus::Submitting => { + (outcome.status, outcome.failure) = + failed_before_broadcast_outcome(outcome.target.timing); + changed = true; + } + DpnsVoteTargetStatus::Confirming => { + outcome.status = DpnsVoteTargetStatus::Unconfirmed; + outcome.target.current_choice = None; + outcome.failure = Some(DpnsVoteFailure::ResultUnconfirmed); + changed = true; + } + _ => {} + } + } + changed +} + +/// Settle the immediate targets among `includes` that are still queued after +/// their executor ended with an error. +/// +/// Nothing claimed them, so nothing was broadcast, but left queued they would +/// hold their lock with no executor until the next start. A queued schedule +/// is left alone: the sweep sends it again. +pub(super) fn fail_abandoned_queued_targets( + operation: &mut DpnsVoteOperation, + includes: impl Fn(&DpnsVoteTargetKey) -> bool, +) -> bool { + let mut changed = false; + for outcome in &mut operation.targets { + if outcome.status == DpnsVoteTargetStatus::Queued + && outcome.target.timing == VoteTiming::Now + && includes(&outcome.target.key) + { + (outcome.status, outcome.failure) = failed_before_broadcast_outcome(VoteTiming::Now); + changed = true; + } + } + changed +} + +/// Keep restart recovery from sending a queued target nobody is waiting for. +/// +/// A queued target was never claimed, so nothing was broadcast. An immediate +/// vote reviewed longer ago than the lateness bound, or an admitted schedule +/// that far past its time, ends like an interrupted submission: a failure the +/// operator reviews, or a schedule shown as missed. Fresher targets stay +/// queued and are sent. +pub(super) fn expire_stale_queued_targets(operation: &mut DpnsVoteOperation, now_ms: u64) -> bool { + let created_at = operation.created_at; + let mut changed = false; + for outcome in &mut operation.targets { + if outcome.status != DpnsVoteTargetStatus::Queued { + continue; + } + let due_at = match outcome.target.timing { + VoteTiming::Now => created_at, + VoteTiming::Scheduled(at) => at, + }; + if dpns_schedule_is_overdue(due_at, now_ms) { + (outcome.status, outcome.failure) = + failed_before_broadcast_outcome(outcome.target.timing); + changed = true; + } + } + changed +} + +pub(super) fn mark_target_broadcast( + kv: &DetKv, + network: Network, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, +) -> Result { + Ok(with_target(kv, network, operation_id, key, |outcome| { + if outcome.status != DpnsVoteTargetStatus::Submitting { + return TargetUpdate::Skip(false); + } + outcome.status = DpnsVoteTargetStatus::Confirming; + TargetUpdate::Persist(true) + })? + .unwrap_or(false)) +} diff --git a/src/context/dpns_vote_preferences.rs b/src/context/dpns_vote_preferences.rs new file mode 100644 index 000000000..e0d49d2b2 --- /dev/null +++ b/src/context/dpns_vote_preferences.rs @@ -0,0 +1,110 @@ +//! Per-network operator preferences for masternode voting: the last-used +//! Masternodes segment and the saved node set. +//! +//! Stored in the app-level k/v store under network-prefixed keys, so they are +//! readable before the wallet backend is wired and never cross networks. + +use super::AppContext; +use crate::backend_task::error::TaskError; +use crate::model::dpns_voting::operator::{MasternodesSegment, NodeSet}; +use crate::wallet_backend::DetScope; +use dash_sdk::dpp::dashcore::Network; +use serde::Serialize; +use serde::de::DeserializeOwned; + +fn segment_key(network: Network) -> String { + format!("{network}:dpns_voting:masternodes_segment") +} + +fn node_set_key(network: Network) -> String { + format!("{network}:dpns_voting:node_set") +} + +impl AppContext { + fn voting_preference(&self, key: &str) -> Result, TaskError> { + self.app_kv().get(DetScope::Global, key).map_err(|source| { + TaskError::VotingPreferenceStorage { + source: Box::new(source), + } + }) + } + + fn put_voting_preference(&self, key: &str, value: &T) -> Result<(), TaskError> { + self.app_kv() + .put(DetScope::Global, key, value) + .map_err(|source| TaskError::VotingPreferenceStorage { + source: Box::new(source), + }) + } + + /// The Masternodes segment last opened on this network, if any. + pub fn masternodes_last_segment(&self) -> Result, TaskError> { + self.voting_preference(&segment_key(self.network())) + } + + /// Remember the Masternodes segment just opened on this network. + pub fn set_masternodes_last_segment( + &self, + segment: MasternodesSegment, + ) -> Result<(), TaskError> { + self.put_voting_preference(&segment_key(self.network()), &segment) + } + + /// The node set saved as default on this network (`All` when none is saved). + pub fn saved_dpns_node_set(&self) -> Result { + Ok(self + .voting_preference(&node_set_key(self.network()))? + .unwrap_or_default()) + } + + /// Save `node_set` as the default on this network. + pub fn save_dpns_node_set(&self, node_set: &NodeSet) -> Result<(), TaskError> { + self.put_voting_preference(&node_set_key(self.network()), node_set) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use dash_sdk::platform::Identifier; + use std::collections::BTreeSet; + + #[test] + fn keys_are_network_scoped() { + assert_ne!(segment_key(Network::Mainnet), segment_key(Network::Testnet)); + assert_ne!( + node_set_key(Network::Mainnet), + node_set_key(Network::Testnet) + ); + assert_ne!( + segment_key(Network::Testnet), + node_set_key(Network::Testnet) + ); + } + + /// VOTE-TC-090 (store half): a saved node set reads back on its network only. + #[test] + fn node_set_and_segment_persist_per_network() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp_dir.path()); + assert_eq!(context.saved_dpns_node_set().expect("read"), NodeSet::All); + assert_eq!(context.masternodes_last_segment().expect("read"), None); + + let custom = NodeSet::Custom(BTreeSet::from([Identifier::from([3; 32])])); + context.save_dpns_node_set(&custom).expect("save"); + context + .set_masternodes_last_segment(MasternodesSegment::Votes) + .expect("save segment"); + + assert_eq!(context.saved_dpns_node_set().expect("read"), custom); + assert_eq!( + context.masternodes_last_segment().expect("read"), + Some(MasternodesSegment::Votes) + ); + let other = context + .app_kv() + .get::(DetScope::Global, &node_set_key(Network::Mainnet)) + .expect("read other network"); + assert_eq!(other, None, "another network sees no saved set"); + } +} diff --git a/src/context/dpns_vote_state.rs b/src/context/dpns_vote_state.rs new file mode 100644 index 000000000..5fe5f8dbc --- /dev/null +++ b/src/context/dpns_vote_state.rs @@ -0,0 +1,1256 @@ +//! Proved, per-node DPNS current-vote snapshots. + +use super::AppContext; +use crate::backend_task::error::TaskError; +use crate::model::dpns_voting::operator::vote_state_display_max_age; +use crate::model::dpns_voting::{DpnsCurrentVoteState, dpns_vote_poll}; +use crate::utils::time::now_ms; +use crate::wallet_backend::{DetKv, DetScope, KvAdapterError, network_prefix}; +use dash_sdk::dpp::dashcore::Network; +use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use dash_sdk::platform::Identifier; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::future::Future; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +const CURRENT_VOTES_KEY_PREFIX: &str = "det:dpns_current_votes:v3:"; +/// Oldest proof that may authorise a submission. Display and the attention +/// signal use the longer `vote_state_display_max_age` instead. +const CURRENT_VOTE_MAX_AGE_MS: u64 = + crate::model::dpns_voting::operator::VOTE_STATE_DECISION_MAX_AGE_MS; + +#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)] +struct StoredCurrentVotes { + available: bool, + updated_at: u64, + votes: BTreeMap<[u8; 32], ResourceVoteChoice>, + confirmed: BTreeMap<[u8; 32], (u64, ResourceVoteChoice)>, +} + +#[derive(Debug, Default)] +pub(super) struct DpnsVoteStatePublications { + sequence: AtomicU64, + voters: Mutex>, +} + +#[derive(Debug)] +struct DpnsVoteStatePublication { + generation: u64, + // A failed publication must not authorize fallback to older stored proof. + persisted: Option, +} + +impl DpnsVoteStatePublications { + fn next_generation(&self) -> Result { + self.sequence + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| { + value.checked_add(1) + }) + .map_err(|_| TaskError::DpnsVoteStateChanged) + } +} + +pub(crate) type DpnsVoteRefreshResults = + BTreeMap>>; + +#[derive(Debug)] +pub(crate) struct RefreshedDpnsVotes { + voter_id: Identifier, + generation: u64, + snapshot: StoredCurrentVotes, +} + +impl RefreshedDpnsVotes { + /// Consume this proof while excluding newer publications through journal revalidation. + pub(crate) fn with_state( + &self, + app_context: &AppContext, + poll_id: Identifier, + consume: impl FnOnce(DpnsCurrentVoteState) -> T, + ) -> Result { + // Lock order: vote-state publications, then the operation journal. + let publications = app_context + .dpns_vote_state_publications + .voters + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if publications + .get(&self.voter_id) + .map(|entry| entry.generation) + != Some(self.generation) + { + return Err(TaskError::DpnsVoteStateChanged); + } + Ok(consume(snapshot_vote_state( + Some(&self.snapshot), + poll_id, + now_ms(), + CURRENT_VOTE_MAX_AGE_MS, + ))) + } + + #[cfg(test)] + pub(crate) fn state( + &self, + app_context: &AppContext, + poll_id: Identifier, + ) -> Result { + self.with_state(app_context, poll_id, std::convert::identity) + } +} + +fn vote_state_err(source: KvAdapterError) -> TaskError { + TaskError::DpnsVoteOperationStorage { source } +} + +fn current_votes_key(network: Network) -> String { + format!("{CURRENT_VOTES_KEY_PREFIX}{}", network_prefix(network)) +} + +fn load_snapshot( + kv: &DetKv, + network: Network, + voter_id: &Identifier, +) -> Result, TaskError> { + kv.get( + DetScope::Identity(&voter_id.to_buffer()), + ¤t_votes_key(network), + ) + .map_err(vote_state_err) +} + +fn save_snapshot( + kv: &DetKv, + network: Network, + voter_id: &Identifier, + snapshot: &StoredCurrentVotes, +) -> Result<(), TaskError> { + kv.put( + DetScope::Identity(&voter_id.to_buffer()), + ¤t_votes_key(network), + snapshot, + ) + .map_err(vote_state_err) +} + +/// One poll's state from a stored snapshot; proof older than `max_age_ms` +/// reads as `Checking`. +fn snapshot_vote_state( + snapshot: Option<&StoredCurrentVotes>, + vote_poll_id: Identifier, + checked_at_ms: u64, + max_age_ms: u64, +) -> DpnsCurrentVoteState { + proved_vote_state(snapshot, vote_poll_id, checked_at_ms, max_age_ms).0 +} + +/// [`snapshot_vote_state`] with the time the returned state was proved, Unix +/// ms; `None` when the state is not `Available`. +fn proved_vote_state( + snapshot: Option<&StoredCurrentVotes>, + vote_poll_id: Identifier, + checked_at_ms: u64, + max_age_ms: u64, +) -> (DpnsCurrentVoteState, Option) { + if let Some((updated_at, choice)) = + snapshot.and_then(|snapshot| snapshot.confirmed.get(&vote_poll_id.to_buffer())) + && checked_at_ms.saturating_sub(*updated_at) <= max_age_ms + { + return ( + DpnsCurrentVoteState::Available(Some(*choice)), + Some(*updated_at), + ); + } + match snapshot { + None => (DpnsCurrentVoteState::Checking, None), + Some(snapshot) if checked_at_ms.saturating_sub(snapshot.updated_at) > max_age_ms => { + (DpnsCurrentVoteState::Checking, None) + } + Some(snapshot) if !snapshot.available => (DpnsCurrentVoteState::Unavailable, None), + Some(snapshot) => ( + DpnsCurrentVoteState::Available(snapshot.votes.get(&vote_poll_id.to_buffer()).copied()), + Some(snapshot.updated_at), + ), + } +} + +impl AppContext { + /// Consume fresh proof, using a newer successful publication if superseded. + pub(crate) fn with_dpns_vote_preflight_state( + &self, + voter_id: Identifier, + poll_id: Identifier, + refresh: Result<&RefreshedDpnsVotes, Arc>, + mut consume: impl FnMut(DpnsCurrentVoteState) -> T, + ) -> Result> { + let result = refresh.and_then(|snapshot| { + if snapshot.voter_id != voter_id { + return Err(Arc::new(TaskError::DpnsCurrentVoteUnavailable)); + } + snapshot + .with_state(self, poll_id, &mut consume) + .map_err(Arc::new) + }); + if !matches!(&result, Err(error) if matches!(error.as_ref(), TaskError::DpnsVoteStateChanged)) + { + return result; + } + let publications = self + .dpns_vote_state_publications + .voters + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let snapshot = publications + .get(&voter_id) + .and_then(|entry| entry.persisted.as_ref()) + .ok_or_else(|| Arc::new(TaskError::DpnsCurrentVoteUnavailable))?; + Ok(consume(snapshot_vote_state( + Some(snapshot), + poll_id, + now_ms(), + CURRENT_VOTE_MAX_AGE_MS, + ))) + } + + fn dpns_vote_display_max_age_ms(&self) -> u64 { + u64::try_from(vote_state_display_max_age(self.network).as_millis()).unwrap_or(u64::MAX) + } + + /// Publish a deterministic proof failure without network I/O. + #[cfg(test)] + pub(crate) async fn fail_proved_dpns_votes_for_test( + &self, + voter_id: Identifier, + ) -> Result<(), TaskError> { + self.publish_dpns_vote_state( + &self.det_kv()?, + voter_id, + std::future::ready(Err(Box::new(dash_sdk::Error::InvalidProvedResponse( + "test proof unavailable".into(), + )))), + ) + .await + .map(|_| ()) + } + + /// Store a successful proof stamped at `updated_at`, as an earlier refresh left it. + #[cfg(test)] + pub(crate) fn seed_proved_dpns_votes_at_for_test( + &self, + voter_id: Identifier, + votes: BTreeMap<[u8; 32], ResourceVoteChoice>, + updated_at: u64, + ) -> Result<(), TaskError> { + save_snapshot( + &self.det_kv()?, + self.network, + &voter_id, + &StoredCurrentVotes { + available: true, + updated_at, + votes, + confirmed: BTreeMap::new(), + }, + ) + } + + #[cfg(test)] + pub(crate) async fn seed_proved_dpns_votes_for_test( + &self, + voter_id: Identifier, + votes: BTreeMap<[u8; 32], ResourceVoteChoice>, + ) -> Result<(), TaskError> { + self.publish_dpns_vote_state(&self.det_kv()?, voter_id, async { Ok(votes) }) + .await + .map(|_| ()) + } + + /// Publish one voter's fetched choices as the newest proof, or record the + /// failure. Takes the query as a future so no network I/O lives in `context/`. + pub(crate) async fn publish_dpns_vote_state( + &self, + kv: &DetKv, + voter_id: Identifier, + fetch: impl Future< + Output = Result, Box>, + >, + ) -> Result { + let generation = self.dpns_vote_state_publications.next_generation()?; + let checked_at = now_ms(); + let result = fetch.await; + let mut publications = self + .dpns_vote_state_publications + .voters + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if publications + .get(&voter_id) + .is_some_and(|published| published.generation > generation) + { + return Err(TaskError::DpnsVoteStateChanged); + } + publications.insert( + voter_id, + DpnsVoteStatePublication { + generation, + persisted: None, + }, + ); + let confirmed = if result.is_err() { + load_snapshot(kv, self.network, &voter_id)? + .unwrap_or_default() + .confirmed + } else { + BTreeMap::new() + }; + let snapshot = StoredCurrentVotes { + available: result.is_ok(), + updated_at: checked_at, + votes: result.as_ref().cloned().unwrap_or_default(), + confirmed, + }; + save_snapshot(kv, self.network, &voter_id, &snapshot)?; + publications.insert( + voter_id, + DpnsVoteStatePublication { + generation, + persisted: Some(snapshot.clone()), + }, + ); + if let Err(error) = result { + tracing::warn!(?error, %voter_id, "Proved DPNS vote-state query was unavailable"); + return Err(TaskError::from(*error)); + } + Ok(RefreshedDpnsVotes { + voter_id, + generation, + snapshot, + }) + } + + /// Build the exact Platform vote-poll ID for one DPNS label. + pub fn dpns_vote_poll_id(&self, name: &str) -> Result { + dpns_vote_poll(&self.dpns_contract, name)? + .unique_id() + .map_err(|source| TaskError::SdkError { + source_error: Box::new(dash_sdk::Error::Protocol(source)), + }) + } + + /// Read the latest proved state for display, without network I/O. Never + /// authorises a submission: preflight fetches and checks its own proof. + pub fn dpns_current_vote_state( + &self, + voter_id: Identifier, + vote_poll_id: Identifier, + ) -> Result { + let snapshot = load_snapshot(&self.det_kv()?, self.network, &voter_id)?; + Ok(snapshot_vote_state( + snapshot.as_ref(), + vote_poll_id, + now_ms(), + self.dpns_vote_display_max_age_ms(), + )) + } + + /// Read one node's current choices for many polls with a single storage + /// read. Display-only, like [`Self::dpns_current_vote_state`]. + pub fn dpns_current_vote_states( + &self, + voter_id: Identifier, + vote_poll_ids: impl IntoIterator, + ) -> Result, TaskError> { + Ok(self + .dpns_current_vote_states_with_proof_time(voter_id, vote_poll_ids)? + .into_iter() + .map(|(vote_poll_id, (state, _))| (vote_poll_id, state)) + .collect()) + } + + /// [`Self::dpns_current_vote_states`] with the time each state was proved, + /// Unix ms. A reader that derives a decision from a displayed state (such + /// as "already voted, nothing to send") must check that time with + /// `vote_proof_can_decide`, because displayed proof may be much older. + pub fn dpns_current_vote_states_with_proof_time( + &self, + voter_id: Identifier, + vote_poll_ids: impl IntoIterator, + ) -> Result)>, TaskError> { + let snapshot = load_snapshot(&self.det_kv()?, self.network, &voter_id)?; + let checked_at_ms = now_ms(); + let max_age_ms = self.dpns_vote_display_max_age_ms(); + Ok(vote_poll_ids + .into_iter() + .map(|vote_poll_id| { + ( + vote_poll_id, + proved_vote_state(snapshot.as_ref(), vote_poll_id, checked_at_ms, max_age_ms), + ) + }) + .collect()) + } + + /// Update the proved-state cache after a confirmed target. + pub(crate) fn cache_confirmed_dpns_vote( + &self, + voter_id: Identifier, + vote_poll_id: Identifier, + choice: ResourceVoteChoice, + ) -> Result<(), TaskError> { + let mut publications = self + .dpns_vote_state_publications + .voters + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let generation = self.dpns_vote_state_publications.next_generation()?; + publications.insert( + voter_id, + DpnsVoteStatePublication { + generation, + persisted: None, + }, + ); + let kv = self.det_kv()?; + let mut snapshot = load_snapshot(&kv, self.network, &voter_id)?.unwrap_or_default(); + let confirmed_at = now_ms(); + // Keep confirmations as long as any reader may still use them; each + // reader applies its own age cap. + let max_age_ms = self.dpns_vote_display_max_age_ms(); + snapshot + .confirmed + .retain(|_, (updated_at, _)| confirmed_at.saturating_sub(*updated_at) <= max_age_ms); + snapshot + .confirmed + .insert(vote_poll_id.to_buffer(), (confirmed_at, choice)); + save_snapshot(&kv, self.network, &voter_id, &snapshot)?; + publications.insert( + voter_id, + DpnsVoteStatePublication { + generation, + persisted: Some(snapshot), + }, + ); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::wallet_backend::kv_test_support::InMemoryKv; + use platform_wallet_storage::{KvError, KvStore, ObjectId}; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[derive(Default)] + struct CountingKv { + inner: InMemoryKv, + gets: AtomicUsize, + } + + impl KvStore for CountingKv { + fn get(&self, scope: &ObjectId, key: &str) -> Result>, KvError> { + self.gets.fetch_add(1, Ordering::Relaxed); + self.inner.get(scope, key) + } + + fn put(&self, scope: &ObjectId, key: &str, value: &[u8]) -> Result<(), KvError> { + self.inner.put(scope, key, value) + } + + fn delete(&self, scope: &ObjectId, key: &str) -> Result<(), KvError> { + self.inner.delete(scope, key) + } + + fn list_keys( + &self, + scope: &ObjectId, + prefix: Option<&str>, + ) -> Result, KvError> { + self.inner.list_keys(scope, prefix) + } + } + + fn kv() -> DetKv { + DetKv::from_store(Arc::new(InMemoryKv::default())) + } + + fn connection_error() -> Box { + use dash_sdk::dapi_client::{DapiClientError, transport::TransportError}; + Box::new(dash_sdk::Error::DapiClientError( + DapiClientError::Transport(TransportError::Grpc( + dash_sdk::dapi_grpc::tonic::Status::unavailable("tcp connect error"), + )), + )) + } + + #[tokio::test] + async fn review_fixes_overlapping_refreshes_keep_both_due_targets_admitted() { + use crate::model::dpns_voting::{ + DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + }; + let temp = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(temp.path()); + let kv = kv(); + context.set_det_kv_override_for_test(kv.clone()); + let voter = Identifier::from([1; 32]); + let polls = [Identifier::from([2; 32]), Identifier::from([3; 32])]; + let mut operations = polls.map(|poll| { + AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: context.network(), + voter_id: voter, + vote_poll_id: poll, + }, + voter_alias: None, + contested_name: poll + .to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Hex), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Scheduled(1), + }]) + }); + for operation in &mut operations { + operation.targets[0].status = DpnsVoteTargetStatus::Queued; + context.insert_dpns_vote_operation(operation, None).unwrap(); + } + let (published_tx, published_rx) = tokio::sync::oneshot::channel(); + let first = async { + let snapshot = context + .publish_dpns_vote_state(&kv, voter, async { Ok(BTreeMap::new()) }) + .await + .unwrap(); + published_tx.send(()).unwrap(); + snapshot + }; + let second = async { + published_rx.await.unwrap(); + context + .publish_dpns_vote_state(&kv, voter, async { Ok(BTreeMap::new()) }) + .await + .unwrap() + }; + let (first, second) = tokio::join!(first, second); + assert!(first.with_state(&context, polls[0], |_| ()).is_err()); + for (operation, snapshot) in operations.iter().zip([&first, &second]) { + let key = &operation.targets[0].target.key; + context + .with_dpns_vote_preflight_state(voter, key.vote_poll_id, Ok(snapshot), |state| { + context.revalidate_queued_dpns_vote_target(operation.id, key, state) + }) + .expect("a successful sibling publication must supply current proof") + .unwrap(); + assert_eq!( + context + .dpns_vote_operation(operation.id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Queued, + "due admission must survive overlapping successful queries" + ); + } + } + + #[tokio::test] + async fn review_fixes_preflight_uses_new_confirmation_and_rejects_failed_publication() { + use crate::wallet_backend::kv_test_support::FailingKv; + let temp = tempfile::tempdir().unwrap(); + let store = Arc::new(FailingKv::default()); + let kv = DetKv::from_store(store.clone()); + let context = crate::context::test_support::test_app_context(temp.path()); + context.set_det_kv_override_for_test(kv.clone()); + let voter = Identifier::from([1; 32]); + let poll = Identifier::from([2; 32]); + let older = context + .publish_dpns_vote_state(&kv, voter, async { Ok(BTreeMap::new()) }) + .await + .unwrap(); + context + .cache_confirmed_dpns_vote(voter, poll, ResourceVoteChoice::Lock) + .unwrap(); + assert_eq!( + context + .with_dpns_vote_preflight_state(voter, poll, Ok(&older), |state| state) + .unwrap(), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + store.fail_next_puts_containing("det:dpns_current_votes:", 1); + assert!( + context + .cache_confirmed_dpns_vote(voter, poll, ResourceVoteChoice::Abstain) + .is_err() + ); + assert!( + context + .with_dpns_vote_preflight_state(voter, poll, Ok(&older), |_| ()) + .is_err(), + "a failed newer write must not authorize using older persisted data" + ); + } + + #[tokio::test] + async fn review_fixes_superseded_fetch_uses_latest_proof_but_failed_fetch_does_not() { + let temp = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(temp.path()); + let kv = kv(); + context.set_det_kv_override_for_test(kv.clone()); + let voter = Identifier::from([1; 32]); + let poll = Identifier::from([2; 32]); + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let (finish_tx, finish_rx) = tokio::sync::oneshot::channel(); + let older = context.publish_dpns_vote_state(&kv, voter, async { + started_tx.send(()).unwrap(); + finish_rx.await.unwrap(); + Ok(BTreeMap::new()) + }); + let newer = async { + started_rx.await.unwrap(); + context + .cache_confirmed_dpns_vote(voter, poll, ResourceVoteChoice::Lock) + .unwrap(); + finish_tx.send(()).unwrap(); + }; + let (older, ()) = tokio::join!(older, newer); + assert!(matches!(older, Err(TaskError::DpnsVoteStateChanged))); + assert_eq!( + context + .with_dpns_vote_preflight_state( + voter, + poll, + older + .as_ref() + .map_err(|_| Arc::new(TaskError::DpnsVoteStateChanged)), + |state| state, + ) + .unwrap(), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + assert!( + context + .with_dpns_vote_preflight_state( + voter, + poll, + Err(Arc::new(TaskError::DpnsCurrentVoteUnavailable)), + |_| (), + ) + .is_err(), + "unrelated fetch errors must not fall back to cached data" + ); + } + + #[tokio::test] + async fn review_fixes_new_failed_refresh_keeps_fallback_unavailable() { + let temp = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(temp.path()); + let kv = kv(); + context.set_det_kv_override_for_test(kv.clone()); + let voter = Identifier::from([1; 32]); + let poll = Identifier::from([2; 32]); + let older = context + .publish_dpns_vote_state(&kv, voter, async { Ok(BTreeMap::new()) }) + .await + .unwrap(); + assert!( + context + .publish_dpns_vote_state(&kv, voter, async { Err(connection_error()) }) + .await + .is_err() + ); + assert_eq!( + context + .with_dpns_vote_preflight_state(voter, poll, Ok(&older), |state| state) + .unwrap(), + DpnsCurrentVoteState::Unavailable + ); + context + .cache_confirmed_dpns_vote(voter, poll, ResourceVoteChoice::Lock) + .unwrap(); + let other_poll = Identifier::from([3; 32]); + assert_eq!( + context + .with_dpns_vote_preflight_state(voter, other_poll, Ok(&older), |state| state) + .unwrap(), + DpnsCurrentVoteState::Unavailable, + "one confirmed poll cannot authorize another poll" + ); + } + + #[tokio::test] + async fn review_fixes_failed_refresh_read_invalidates_older_publication() { + use crate::wallet_backend::kv_test_support::FailingKv; + let temp = tempfile::tempdir().unwrap(); + let store = Arc::new(FailingKv::default()); + let kv = DetKv::from_store(store.clone()); + let context = crate::context::test_support::test_app_context(temp.path()); + context.set_det_kv_override_for_test(kv.clone()); + let voter = Identifier::from([1; 32]); + let poll = Identifier::from([2; 32]); + let older = context + .publish_dpns_vote_state(&kv, voter, async { Ok(BTreeMap::new()) }) + .await + .unwrap(); + store.fail_next_gets_containing("det:dpns_current_votes:", 1); + assert!( + context + .publish_dpns_vote_state(&kv, voter, async { Err(connection_error()) }) + .await + .is_err() + ); + assert!( + context + .with_dpns_vote_preflight_state(voter, poll, Ok(&older), |_| ()) + .is_err(), + "a failed refresh cannot leave older proof authorized after a storage error" + ); + } + + #[tokio::test] + async fn an_older_refresh_cannot_replace_a_newer_publication() { + let temp = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(temp.path()); + let kv = kv(); + context.set_det_kv_override_for_test(kv.clone()); + let voter = Identifier::from([1; 32]); + let poll = Identifier::from([2; 32]); + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let (finish_tx, finish_rx) = tokio::sync::oneshot::channel(); + let older = context.publish_dpns_vote_state(&kv, voter, async { + started_tx.send(()).unwrap(); + finish_rx.await.unwrap(); + Ok(BTreeMap::from([( + poll.to_buffer(), + ResourceVoteChoice::Abstain, + )])) + }); + let newer = async { + started_rx.await.unwrap(); + let result = context + .publish_dpns_vote_state(&kv, voter, async { + Ok(BTreeMap::from([( + poll.to_buffer(), + ResourceVoteChoice::Lock, + )])) + }) + .await; + finish_tx.send(()).unwrap(); + result + }; + let (older, newer) = tokio::join!(older, newer); + newer.unwrap(); + assert!( + older.is_err(), + "a superseded result cannot authorize preflight" + ); + assert_eq!( + context.dpns_current_vote_state(voter, poll).unwrap(), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + } + + #[tokio::test] + async fn a_delayed_refresh_failure_cannot_erase_a_confirmation() { + let temp = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(temp.path()); + let kv = kv(); + context.set_det_kv_override_for_test(kv.clone()); + let voter = Identifier::from([1; 32]); + let poll = Identifier::from([2; 32]); + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let (finish_tx, finish_rx) = tokio::sync::oneshot::channel(); + let refresh = context.publish_dpns_vote_state(&kv, voter, async { + started_tx.send(()).unwrap(); + finish_rx.await.unwrap(); + Err(connection_error()) + }); + let confirmation = async { + started_rx.await.unwrap(); + context + .cache_confirmed_dpns_vote(voter, poll, ResourceVoteChoice::Lock) + .unwrap(); + finish_tx.send(()).unwrap(); + }; + let (result, ()) = tokio::join!(refresh, confirmation); + assert!(result.is_err()); + assert_eq!( + context.dpns_current_vote_state(voter, poll).unwrap(), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + } + + #[tokio::test] + async fn a_returned_snapshot_cannot_authorize_preflight_after_confirmation() { + let temp = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(temp.path()); + let kv = kv(); + context.set_det_kv_override_for_test(kv.clone()); + let voter = Identifier::from([1; 32]); + let poll = Identifier::from([2; 32]); + let result = context + .publish_dpns_vote_state(&kv, voter, async { Ok(BTreeMap::new()) }) + .await + .unwrap(); + context + .cache_confirmed_dpns_vote(voter, poll, ResourceVoteChoice::Lock) + .unwrap(); + assert!(result.state(&context, poll).is_err()); + + use crate::model::dpns_voting::{ + DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + }; + let key = DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: voter, + vote_poll_id: poll, + }; + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: key.clone(), + voter_alias: None, + contested_name: "example".to_owned(), + current_choice: None, + requested_choice: ResourceVoteChoice::Abstain, + timing: VoteTiming::Now, + }]); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + assert!( + result + .with_state(&context, poll, |state| { + context.revalidate_queued_dpns_vote_target(operation.id, &key, state) + }) + .is_err() + ); + assert_eq!( + context.dpns_vote_target_status(&key).unwrap(), + Some(DpnsVoteTargetStatus::Queued) + ); + } + + #[tokio::test] + async fn a_new_failed_refresh_preserves_unexpired_confirmed_polls() { + let temp = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(temp.path()); + let kv = kv(); + context.set_det_kv_override_for_test(kv.clone()); + let voter = Identifier::from([1; 32]); + let poll = Identifier::from([2; 32]); + context + .cache_confirmed_dpns_vote(voter, poll, ResourceVoteChoice::Lock) + .unwrap(); + assert!( + context + .publish_dpns_vote_state(&kv, voter, async { Err(connection_error()) }) + .await + .is_err() + ); + assert_eq!( + context.dpns_current_vote_state(voter, poll).unwrap(), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + assert_eq!( + context + .dpns_current_vote_state(voter, Identifier::from([3; 32])) + .unwrap(), + DpnsCurrentVoteState::Unavailable + ); + } + + #[test] + fn concurrent_confirmations_retain_every_poll() { + let temp = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(temp.path()); + let kv = kv(); + context.set_det_kv_override_for_test(kv); + let voter = Identifier::from([1; 32]); + let start = std::sync::Barrier::new(8); + std::thread::scope(|scope| { + for poll_byte in 2..10 { + let context = &context; + let start = &start; + scope.spawn(move || { + start.wait(); + context + .cache_confirmed_dpns_vote( + voter, + Identifier::from([poll_byte; 32]), + ResourceVoteChoice::Lock, + ) + .unwrap(); + }); + } + }); + for poll_byte in 2..10 { + assert_eq!( + context + .dpns_current_vote_state(voter, Identifier::from([poll_byte; 32])) + .unwrap(), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + } + } + + #[test] + fn per_poll_confirmation_expires_without_authorizing_other_polls() { + let poll = Identifier::from([2; 32]); + let other = Identifier::from([3; 32]); + let snapshot = StoredCurrentVotes { + confirmed: BTreeMap::from([(poll.to_buffer(), (10, ResourceVoteChoice::Lock))]), + ..Default::default() + }; + assert_eq!( + snapshot_vote_state(Some(&snapshot), poll, 11, CURRENT_VOTE_MAX_AGE_MS), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + assert_eq!( + snapshot_vote_state(Some(&snapshot), other, 11, CURRENT_VOTE_MAX_AGE_MS), + DpnsCurrentVoteState::Unavailable + ); + assert_eq!( + snapshot_vote_state( + Some(&snapshot), + poll, + 11 + CURRENT_VOTE_MAX_AGE_MS, + CURRENT_VOTE_MAX_AGE_MS + ), + DpnsCurrentVoteState::Checking + ); + } + + #[tokio::test] + async fn failed_refresh_preserves_its_typed_network_cause() { + let temp = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(temp.path()); + let kv = kv(); + context.set_det_kv_override_for_test(kv.clone()); + let voter = Identifier::from([1; 32]); + let error = context + .publish_dpns_vote_state(&kv, voter, async { Err(connection_error()) }) + .await + .unwrap_err(); + assert!(error.contains_dapi_reachability_failure()); + assert_eq!( + context + .dpns_current_vote_state(voter, Identifier::from([2; 32])) + .unwrap(), + DpnsCurrentVoteState::Unavailable + ); + } + + #[test] + fn confirming_one_poll_preserves_other_polls_unavailable() { + let temp = tempfile::tempdir().unwrap(); + let kv = kv(); + let context = crate::context::test_support::test_app_context(temp.path()); + context.set_det_kv_override_for_test(kv.clone()); + let voter = Identifier::from([1; 32]); + let confirmed = Identifier::from([2; 32]); + let other = Identifier::from([3; 32]); + save_snapshot( + &kv, + Network::Testnet, + &voter, + &StoredCurrentVotes { + available: false, + updated_at: now_ms(), + ..Default::default() + }, + ) + .unwrap(); + + context + .cache_confirmed_dpns_vote(voter, confirmed, ResourceVoteChoice::Lock) + .unwrap(); + + assert_eq!( + context.dpns_current_vote_state(voter, confirmed).unwrap(), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + assert_eq!( + context.dpns_current_vote_state(voter, other).unwrap(), + DpnsCurrentVoteState::Unavailable + ); + } + + #[test] + fn confirming_one_poll_does_not_renew_an_expired_full_snapshot() { + let temp = tempfile::tempdir().unwrap(); + let kv = kv(); + let context = crate::context::test_support::test_app_context(temp.path()); + context.set_det_kv_override_for_test(kv.clone()); + let voter = Identifier::from([1; 32]); + let confirmed = Identifier::from([2; 32]); + let other = Identifier::from([3; 32]); + save_snapshot( + &kv, + Network::Testnet, + &voter, + &StoredCurrentVotes { + available: true, + updated_at: 1, + votes: BTreeMap::from([(other.to_buffer(), ResourceVoteChoice::Abstain)]), + ..Default::default() + }, + ) + .unwrap(); + + context + .cache_confirmed_dpns_vote(voter, confirmed, ResourceVoteChoice::Lock) + .unwrap(); + + assert_eq!( + context.dpns_current_vote_state(voter, confirmed).unwrap(), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + assert_eq!( + context.dpns_current_vote_state(voter, other).unwrap(), + DpnsCurrentVoteState::Checking + ); + } + + /// VOTE-TC-001: a proved current choice round-trips by node and poll. + #[test] + fn proved_current_vote_round_trips() { + let kv = kv(); + let voter = Identifier::from([1; 32]); + let poll = Identifier::from([2; 32]); + let snapshot = StoredCurrentVotes { + available: true, + updated_at: 3, + votes: BTreeMap::from([(poll.to_buffer(), ResourceVoteChoice::Lock)]), + ..Default::default() + }; + save_snapshot(&kv, Network::Testnet, &voter, &snapshot).unwrap(); + + assert_eq!( + load_snapshot(&kv, Network::Testnet, &voter).unwrap(), + Some(snapshot) + ); + } + + /// VOTE-TC-007: query failure is represented explicitly, never as no vote. + #[test] + fn unavailable_snapshot_is_distinct_from_an_empty_proved_snapshot() { + let unavailable = StoredCurrentVotes { + available: false, + ..Default::default() + }; + let empty = StoredCurrentVotes { + available: true, + ..Default::default() + }; + + assert_ne!(unavailable, empty); + } + + #[test] + fn current_vote_snapshots_are_network_qualified() { + let kv = kv(); + let voter = Identifier::from([1; 32]); + let snapshot = StoredCurrentVotes { + available: true, + updated_at: now_ms(), + votes: BTreeMap::new(), + ..Default::default() + }; + save_snapshot(&kv, Network::Testnet, &voter, &snapshot).unwrap(); + + assert_eq!( + load_snapshot(&kv, Network::Testnet, &voter).unwrap(), + Some(snapshot) + ); + assert_eq!(load_snapshot(&kv, Network::Mainnet, &voter).unwrap(), None); + } + + #[test] + fn stale_proved_snapshot_cannot_authorize_submission() { + let poll = Identifier::from([2; 32]); + let snapshot = StoredCurrentVotes { + available: true, + updated_at: 1, + votes: BTreeMap::from([(poll.to_buffer(), ResourceVoteChoice::Lock)]), + ..Default::default() + }; + + assert_eq!( + snapshot_vote_state( + Some(&snapshot), + poll, + CURRENT_VOTE_MAX_AGE_MS + 2, + CURRENT_VOTE_MAX_AGE_MS + ), + DpnsCurrentVoteState::Checking + ); + } + + /// The attention signal reads snapshots between background refreshes, which + /// are far apart; only proof older than two refresh intervals is dropped. + #[test] + fn displayed_state_survives_between_background_refreshes() { + let voted = Identifier::from([2; 32]); + let not_voted = Identifier::from([3; 32]); + let snapshot = StoredCurrentVotes { + available: true, + updated_at: 1, + votes: BTreeMap::from([(voted.to_buffer(), ResourceVoteChoice::Lock)]), + ..Default::default() + }; + let ten_minutes_later = 1 + 10 * 60_000; + for network in [Network::Mainnet, Network::Testnet] { + let display_max_age = + u64::try_from(vote_state_display_max_age(network).as_millis()).unwrap(); + let one_interval_later = 1 + display_max_age / 2; + assert_eq!( + snapshot_vote_state( + Some(&snapshot), + not_voted, + one_interval_later, + display_max_age + ), + DpnsCurrentVoteState::Available(None), + "{network}: a contest must keep needing a vote until the next refresh" + ); + assert_eq!( + snapshot_vote_state(Some(&snapshot), voted, one_interval_later, display_max_age), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + assert_eq!( + snapshot_vote_state( + Some(&snapshot), + not_voted, + 2 + display_max_age, + display_max_age + ), + DpnsCurrentVoteState::Checking, + "{network}: proof older than two refresh intervals is not shown" + ); + } + let mainnet_max_age = + u64::try_from(vote_state_display_max_age(Network::Mainnet).as_millis()).unwrap(); + assert_eq!( + snapshot_vote_state( + Some(&snapshot), + not_voted, + ten_minutes_later, + mainnet_max_age + ), + DpnsCurrentVoteState::Available(None) + ); + assert_eq!( + snapshot_vote_state( + Some(&snapshot), + not_voted, + ten_minutes_later, + CURRENT_VOTE_MAX_AGE_MS + ), + DpnsCurrentVoteState::Checking, + "the same proof is too old to authorise a submission" + ); + } + + #[test] + fn stored_state_older_than_the_submission_cap_is_still_displayed() { + let temp = tempfile::tempdir().unwrap(); + let kv = kv(); + let context = crate::context::test_support::test_app_context(temp.path()); + context.set_det_kv_override_for_test(kv.clone()); + let voter = Identifier::from([1; 32]); + let poll = Identifier::from([2; 32]); + context + .seed_proved_dpns_votes_at_for_test( + voter, + BTreeMap::new(), + now_ms() - 2 * CURRENT_VOTE_MAX_AGE_MS, + ) + .unwrap(); + + assert_eq!( + context.dpns_current_vote_state(voter, poll).unwrap(), + DpnsCurrentVoteState::Available(None) + ); + assert_eq!( + context + .dpns_current_vote_states(voter, [poll]) + .unwrap() + .get(&poll), + Some(&DpnsCurrentVoteState::Available(None)) + ); + } + + #[test] + fn an_earlier_confirmation_survives_a_later_one_for_display() { + let temp = tempfile::tempdir().unwrap(); + let kv = kv(); + let context = crate::context::test_support::test_app_context(temp.path()); + context.set_det_kv_override_for_test(kv.clone()); + let voter = Identifier::from([1; 32]); + let earlier = Identifier::from([2; 32]); + let later = Identifier::from([3; 32]); + let earlier_confirmed_at = now_ms() - 2 * CURRENT_VOTE_MAX_AGE_MS; + save_snapshot( + &kv, + context.network(), + &voter, + &StoredCurrentVotes { + available: true, + updated_at: earlier_confirmed_at, + confirmed: BTreeMap::from([( + earlier.to_buffer(), + (earlier_confirmed_at, ResourceVoteChoice::Abstain), + )]), + ..Default::default() + }, + ) + .unwrap(); + + context + .cache_confirmed_dpns_vote(voter, later, ResourceVoteChoice::Lock) + .unwrap(); + + assert_eq!( + context.dpns_current_vote_state(voter, earlier).unwrap(), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Abstain)), + "a vote confirmed minutes ago must not read as not voted" + ); + } + + #[test] + fn many_poll_states_use_one_storage_read_per_node() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let store = Arc::new(CountingKv::default()); + let kv = DetKv::from_store(store.clone()); + let voter = Identifier::from([1; 32]); + let polls = (0..100) + .map(|byte| Identifier::from([byte; 32])) + .collect::>(); + save_snapshot( + &kv, + Network::Testnet, + &voter, + &StoredCurrentVotes { + available: true, + updated_at: now_ms(), + votes: BTreeMap::new(), + ..Default::default() + }, + ) + .expect("seed current-vote snapshot"); + let context = crate::context::test_support::test_app_context_with_kv( + temp_dir.path(), + Arc::new(kv.clone()), + ); + context.set_det_kv_override_for_test(kv); + let before = store.gets.load(Ordering::Relaxed); + + let states = context + .dpns_current_vote_states(voter, polls.iter().copied()) + .expect("load current-vote states"); + + assert_eq!(states.len(), polls.len()); + assert_eq!(store.gets.load(Ordering::Relaxed) - before, 1); + } +} diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index ae4d9d250..bda4d0fa1 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -1,5 +1,4 @@ use super::AppContext; -use crate::backend_task::contested_names::ScheduledDPNSVote; use crate::backend_task::error::TaskError; use crate::model::identity_discovery::DiscoveryIntent; use crate::model::qualified_identity::{ @@ -13,6 +12,7 @@ use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::identity::KeyID; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::platform_value::string_encoding::Encoding; +#[cfg(test)] use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; use dash_sdk::platform::Identifier; use serde::{Deserialize, Serialize}; @@ -43,19 +43,6 @@ const IDENTITY_ORDER_KEY: &str = "det:identity_order:v1"; /// full set. const IDENTITY_INDEX_KEY: &str = "det:identity_index:v1"; -/// Scheduled-vote slot key, scoped to [`DetScope::Identity`] of the -/// voter. The full key is `det:scheduled_vote:` — the -/// voter id is carried by the scope. -const SCHEDULED_VOTE_KEY_PREFIX: &str = "det:scheduled_vote:"; - -/// Global enumeration index: the complete set of voter ids that have at -/// least one scheduled vote. Scheduled votes are scoped to -/// [`DetScope::Identity`] of the voter, which has no cross-voter listing, -/// so this Global slot drives the network-wide enumeration and clear -/// paths. Maintained on insert and pruned when a voter's last scheduled -/// vote is removed. -const SCHEDULED_VOTE_VOTERS_KEY: &str = "det:scheduled_vote_voters:v1"; - /// Top-up history slot, scoped to [`DetScope::Identity`]. One entry per /// identity; the identity id is carried by the scope. const TOP_UPS_KEY: &str = "det:top_ups:v1"; @@ -76,7 +63,8 @@ const VAULT_CLEANUP_PENDING_PREFIX: &str = "det:vault_cleanup_pending:v1:"; /// this record needs to start existing. const IDENTITY_UNLOADED_PREFIX: &str = "det:identity_unloaded:v1:"; -/// Whether every owner-scoped DashPay and token-list sidecar was removed. +/// Whether all secondary local data of a removed identity was cleared: its +/// DashPay and token-list sidecars, username records and pending votes. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum IdentitySidecarCleanup { Complete, @@ -193,20 +181,11 @@ impl From for PrivateKeyTarget { } } -fn scheduled_vote_key(contested_name: &str) -> String { - format!("{SCHEDULED_VOTE_KEY_PREFIX}{contested_name}") -} - /// Map a k/v adapter failure to the identity-blob storage error. fn identity_err(source: KvAdapterError) -> TaskError { TaskError::IdentityStorage { source } } -/// Map a k/v adapter failure to the scheduled-vote storage error. -fn scheduled_vote_err(source: KvAdapterError) -> TaskError { - TaskError::ScheduledVoteStorage { source } -} - /// Map a k/v adapter failure to the top-up-history storage error. fn top_up_err(source: KvAdapterError) -> TaskError { TaskError::TopUpHistoryStorage { source } @@ -234,15 +213,6 @@ fn save_top_ups_in( kv.put(scope, TOP_UPS_KEY, &merged).map_err(top_up_err) } -/// Validate a raw voter id and return it as the `[u8; 32]` the -/// [`DetScope::Identity`] scope borrows. Surfaces a typed error rather -/// than panicking on a wrong-length slice. -fn voter_buffer(identity_id: &[u8]) -> std::result::Result<[u8; 32], TaskError> { - Identifier::from_bytes(identity_id) - .map(|id| id.to_buffer()) - .map_err(|source| TaskError::InvalidVoterIdentifier { source }) -} - /// Decode a stored bincode'd [`QualifiedIdentity`] blob, attaching the /// active network. The encoder skips `status` / `network` (rehydrated by /// callers) and `associated_wallets` / `top_ups` (filled by callers from @@ -321,62 +291,6 @@ impl std::fmt::Debug for StoredQualifiedIdentity { } } -/// Persisted shape of a scheduled DPNS vote. Mirrors -/// [`ScheduledDPNSVote`] but with a serde-friendly representation of -/// the SDK's [`ResourceVoteChoice`] (which only derives bincode under -/// this feature set). -#[derive(Debug, Serialize, Deserialize)] -struct StoredScheduledVote { - voter_id: [u8; 32], - contested_name: String, - choice: StoredVoteChoice, - unix_timestamp: u64, - executed_successfully: bool, -} - -#[derive(Debug, Serialize, Deserialize)] -enum StoredVoteChoice { - TowardsIdentity([u8; 32]), - Abstain, - Lock, -} - -impl From<&ScheduledDPNSVote> for StoredScheduledVote { - fn from(v: &ScheduledDPNSVote) -> Self { - Self { - voter_id: v.voter_id.to_buffer(), - contested_name: v.contested_name.clone(), - choice: match v.choice { - ResourceVoteChoice::TowardsIdentity(id) => { - StoredVoteChoice::TowardsIdentity(id.to_buffer()) - } - ResourceVoteChoice::Abstain => StoredVoteChoice::Abstain, - ResourceVoteChoice::Lock => StoredVoteChoice::Lock, - }, - unix_timestamp: v.unix_timestamp, - executed_successfully: v.executed_successfully, - } - } -} - -impl From for ScheduledDPNSVote { - fn from(v: StoredScheduledVote) -> Self { - ScheduledDPNSVote { - voter_id: Identifier::from(v.voter_id), - contested_name: v.contested_name, - choice: match v.choice { - StoredVoteChoice::TowardsIdentity(id) => { - ResourceVoteChoice::TowardsIdentity(Identifier::from(id)) - } - StoredVoteChoice::Abstain => ResourceVoteChoice::Abstain, - StoredVoteChoice::Lock => ResourceVoteChoice::Lock, - }, - unix_timestamp: v.unix_timestamp, - executed_successfully: v.executed_successfully, - } - } -} - /// Serializes every read-modify-write of [`IDENTITY_INDEX_KEY`]. /// /// The roster is a single blob rewritten wholesale, so two identities being @@ -559,77 +473,7 @@ fn purge_identity_scope(kv: &DetKv, id: &[u8; 32]) -> std::result::Result<(), Ta let scope = DetScope::Identity(id); kv.delete(scope, IDENTITY_KEY).map_err(identity_err)?; kv.delete(scope, TOP_UPS_KEY).map_err(top_up_err)?; - delete_scheduled_votes_for_voter(kv, id) -} - -/// Read the Global scheduled-vote voter index. Returns an empty vector -/// when no voter has ever queued a scheduled vote. -fn load_scheduled_vote_voters(kv: &DetKv) -> std::result::Result, TaskError> { - Ok(kv - .get::>(DetScope::Global, SCHEDULED_VOTE_VOTERS_KEY) - .map_err(scheduled_vote_err)? - .unwrap_or_default()) -} - -/// Add `voter` to the Global scheduled-vote voter index if absent. -fn index_add_vote_voter(kv: &DetKv, voter: &[u8; 32]) -> std::result::Result<(), TaskError> { - let mut voters = load_scheduled_vote_voters(kv)?; - if voters.contains(voter) { - return Ok(()); - } - voters.push(*voter); - kv.put(DetScope::Global, SCHEDULED_VOTE_VOTERS_KEY, &voters) - .map_err(scheduled_vote_err) -} - -/// List the scheduled-vote entry keys queued under `voter`'s Identity scope. -fn scheduled_vote_keys( - kv: &DetKv, - voter: &[u8; 32], -) -> std::result::Result, TaskError> { - kv.list(DetScope::Identity(voter), Some(SCHEDULED_VOTE_KEY_PREFIX)) - .map_err(scheduled_vote_err) -} - -/// Drop `voter` from the Global scheduled-vote voter index. No-op when the -/// voter is not present, so repeated calls stay idempotent. -fn remove_vote_voter_from_index( - kv: &DetKv, - voter: &[u8; 32], -) -> std::result::Result<(), TaskError> { - let mut voters = load_scheduled_vote_voters(kv)?; - let before = voters.len(); - voters.retain(|v| v != voter); - if voters.len() == before { - return Ok(()); - } - kv.put(DetScope::Global, SCHEDULED_VOTE_VOTERS_KEY, &voters) - .map_err(scheduled_vote_err) -} - -/// Prune `voter` from the Global scheduled-vote voter index when it no -/// longer has any scheduled votes left in its Identity scope. Keeps the -/// index from accumulating dangling voter entries. -fn prune_vote_voter_if_empty(kv: &DetKv, voter: &[u8; 32]) -> std::result::Result<(), TaskError> { - if scheduled_vote_keys(kv, voter)?.is_empty() { - remove_vote_voter_from_index(kv, voter) - } else { - Ok(()) - } -} - -/// Delete every scheduled vote queued under `voter`'s Identity scope and -/// drop the voter from the index. Used by the identity-removal cleanup -/// path. -fn delete_scheduled_votes_for_voter( - kv: &DetKv, - voter: &[u8; 32], -) -> std::result::Result<(), TaskError> { - let scope = DetScope::Identity(voter); - for key in scheduled_vote_keys(kv, voter)? { - kv.delete(scope, &key).map_err(scheduled_vote_err)?; - } - remove_vote_voter_from_index(kv, voter) + Ok(()) } impl AppContext { @@ -744,7 +588,8 @@ impl AppContext { ) } - /// Deliberate import while the caller holds this identity's record lock. + /// Deliberate import, including retirement of an unload marker. The caller + /// must hold this identity's record lock across authorization and this write. pub(crate) fn insert_local_qualified_identity_under_lock( &self, qualified_identity: &QualifiedIdentity, @@ -754,10 +599,21 @@ impl AppContext { // changed their mind about unloading it, so this is the only place the // unload marker is retired. Under the same guard as the write, so a // discovery pass cannot observe a retired marker and a missing record. - self.clear_identity_unloaded( - &self.det_kv()?, - &qualified_identity.identity.id().to_buffer(), - )?; + let kv = self.det_kv()?; + let id = qualified_identity.identity.id(); + if !identity_is_listed(&kv, &id.to_buffer())? + && self.is_identity_unloaded(&kv, &id.to_buffer())? + { + let _vote_guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + super::dpns_vote_operations::cancel_removed_identity_votes(&kv, self.network, id)?; + // Votes still waiting to be stored were reviewed before the removal + // too, and no marker will say so once it is retired below. + self.begin_dpns_voter_lifecycle(id); + } + self.clear_identity_unloaded(&kv, &id.to_buffer())?; self.insert_local_qualified_identity_locked(qualified_identity, wallet_and_identity_id_info) } @@ -1448,6 +1304,7 @@ impl AppContext { qi.associated_wallets = wallets.clone(); qi.secret_access = self.wallet_backend().ok().map(|b| b.secret_access()); qi.top_ups = BTreeMap::new(); + self.order_main_username_first(&mut qi); Ok(qi) } @@ -1636,10 +1493,28 @@ impl AppContext { // storage says the identity is absent. The reverse order would leave a // delisted identity with no marker, which is the defect itself. self.mark_identity_unloaded(&kv, &id)?; + // Identity-record guard is outermost. Hold the journal guard until the + // roster and mirrors are gone, so neither claiming nor broadcasting + // can race cancellation and a re-import cannot revive an old schedule. + let _vote_guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + // A journal that cannot be read must not keep keys on the device. No + // vote runs from an unreadable journal, and a re-import cancels before + // it relists, so the cancellation is deferred: the retained manifest + // makes startup recovery retry it. + let vote_cancellation = super::dpns_vote_operations::cancel_removed_identity_votes( + &kv, + self.network, + *identifier, + ); index_remove_identity(&kv, &id)?; + self.invalidate_identity_load(*identifier); purge_identity_scope(&kv, &id)?; self.save_identity_profile_name(*identifier, None); - let sidecar_cleanup = self.finish_identity_removal_cleanup(&kv, &id, vault_keys)?; + let sidecar_cleanup = + self.finish_identity_removal_cleanup(&kv, &id, vault_keys, vote_cancellation)?; // Mirror removal into the upstream unowned scope; wallet-owned identities are unaffected. if let Ok(backend) = self.wallet_backend() && let Err(error) = backend.remove_unowned_identity(identifier) @@ -1658,8 +1533,10 @@ impl AppContext { kv: &DetKv, id: &[u8; 32], vault_keys: impl IntoIterator, + vote_cancellation: std::result::Result<(), TaskError>, ) -> std::result::Result { let identifier = Identifier::from(*id); + let username_cleanup = self.forget_identity_usernames(kv, &identifier); // Both callers hold the record lock through inventory retirement. // Failed re-imports can add keys after the removal manifest was saved. let mut vault_keys: std::collections::BTreeSet<_> = vault_keys.into_iter().collect(); @@ -1673,7 +1550,18 @@ impl AppContext { .wallet_backend() .and_then(|backend| backend.dashpay_clear_owner_overlays(&identifier)); let token_cleanup = super::contract_token_db::forget_identity_token_state(kv, &identifier); - let sidecar_cleanup = sidecar_cleanup_outcome(dashpay_cleanup, token_cleanup, &identifier); + let mut sidecar_cleanup = + sidecar_cleanup_outcome(dashpay_cleanup, token_cleanup, &identifier); + if let Err(error) = username_cleanup { + tracing::warn!(identity_id = %identifier, ?error, + "Removed identity's username records could not be cleared; cleanup will retry"); + sidecar_cleanup = IdentitySidecarCleanup::Incomplete; + } + if let Err(error) = vote_cancellation { + tracing::warn!(identity_id = %identifier, ?error, + "Removed identity's pending votes could not be cancelled; cleanup will retry"); + sidecar_cleanup = IdentitySidecarCleanup::Incomplete; + } if !sidecar_cleanup.is_incomplete() { clear_vault_cleanup_manifest(kv, id); } @@ -1821,6 +1709,17 @@ impl AppContext { continue; } }; + let _vote_guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + // As in the removal itself: an unreadable journal defers only the + // vote cancellation, never the key deletion below. + let vote_cancellation = super::dpns_vote_operations::cancel_removed_identity_votes( + &kv, + self.network, + Identifier::from(id), + ); if let Err(error) = purge_identity_scope(&kv, &id) { tracing::warn!( identity = %Identifier::from(id), @@ -1832,7 +1731,7 @@ impl AppContext { let vault_keys = placements .into_iter() .map(|(target, key_id)| (target.into(), key_id)); - match self.finish_identity_removal_cleanup(&kv, &id, vault_keys) { + match self.finish_identity_removal_cleanup(&kv, &id, vault_keys, vote_cancellation) { Ok(IdentitySidecarCleanup::Complete) => resumed += 1, Ok(IdentitySidecarCleanup::Incomplete) => {} Err(error) => tracing::warn!( @@ -1951,7 +1850,7 @@ impl AppContext { /// Whether `id` was deliberately unloaded and not deliberately re-loaded /// since. - fn is_identity_unloaded( + pub(super) fn is_identity_unloaded( &self, kv: &DetKv, id: &[u8; 32], @@ -2187,124 +2086,6 @@ impl AppContext { Ok(kept) } - /// Persist a batch of scheduled votes in the per-network wallet k/v - /// store. Each vote is scoped to [`DetScope::Identity`] of its voter; - /// existing entries with the same `(voter, contested_name)` are - /// overwritten — matching the pre-C5 `INSERT OR REPLACE` semantics. - /// Voters are tracked in a Global index so the network-wide read / - /// clear paths can find them. - pub fn insert_scheduled_votes( - &self, - scheduled_votes: &[ScheduledDPNSVote], - ) -> std::result::Result<(), TaskError> { - let kv = self.det_kv()?; - for vote in scheduled_votes { - let voter = vote.voter_id.to_buffer(); - let stored = StoredScheduledVote::from(vote); - kv.put( - DetScope::Identity(&voter), - &scheduled_vote_key(&vote.contested_name), - &stored, - ) - .map_err(scheduled_vote_err)?; - index_add_vote_voter(&kv, &voter)?; - } - Ok(()) - } - - /// Fetch every scheduled vote queued for this network from the - /// wallet k/v store, across all voters in the Global voter index. - pub fn get_scheduled_votes(&self) -> std::result::Result, TaskError> { - let kv = self.det_kv()?; - let voters = load_scheduled_vote_voters(&kv)?; - let mut out = Vec::new(); - for voter in voters { - let scope = DetScope::Identity(&voter); - for key in scheduled_vote_keys(&kv, &voter)? { - match kv.get::(scope, &key) { - Ok(Some(stored)) => out.push(stored.into()), - Ok(None) => {} - Err(e) => { - tracing::warn!( - key = %key, - error = ?e, - "Skipping unreadable scheduled vote entry" - ); - } - } - } - } - Ok(out) - } - - /// Drop every scheduled vote queued for this network. - pub fn clear_all_scheduled_votes(&self) -> std::result::Result<(), TaskError> { - let kv = self.det_kv()?; - let voters = load_scheduled_vote_voters(&kv)?; - for voter in &voters { - let scope = DetScope::Identity(voter); - for key in scheduled_vote_keys(&kv, voter)? { - kv.delete(scope, &key).map_err(scheduled_vote_err)?; - } - } - kv.delete(DetScope::Global, SCHEDULED_VOTE_VOTERS_KEY) - .map_err(scheduled_vote_err) - } - - /// Drop every scheduled vote that has already been cast successfully. - pub fn clear_executed_scheduled_votes(&self) -> std::result::Result<(), TaskError> { - let kv = self.det_kv()?; - let voters = load_scheduled_vote_voters(&kv)?; - for voter in &voters { - let scope = DetScope::Identity(voter); - for key in scheduled_vote_keys(&kv, voter)? { - match kv.get::(scope, &key) { - Ok(Some(stored)) if stored.executed_successfully => { - kv.delete(scope, &key).map_err(scheduled_vote_err)?; - } - _ => {} - } - } - prune_vote_voter_if_empty(&kv, voter)?; - } - Ok(()) - } - - /// Drop a single scheduled vote keyed by `(voter_id, contested_name)`. - pub fn delete_scheduled_vote( - &self, - identity_id: &[u8], - contested_name: &str, - ) -> std::result::Result<(), TaskError> { - let voter = voter_buffer(identity_id)?; - let kv = self.det_kv()?; - kv.delete( - DetScope::Identity(&voter), - &scheduled_vote_key(contested_name), - ) - .map_err(scheduled_vote_err)?; - prune_vote_voter_if_empty(&kv, &voter) - } - - /// Mark a single scheduled vote as executed so future cast loops skip it. - pub fn mark_vote_executed( - &self, - identity_id: &[u8], - contested_name: String, - ) -> std::result::Result<(), TaskError> { - let voter = voter_buffer(identity_id)?; - let key = scheduled_vote_key(&contested_name); - let scope = DetScope::Identity(&voter); - let kv = self.det_kv()?; - let Some(mut stored): Option = - kv.get(scope, &key).map_err(scheduled_vote_err)? - else { - return Ok(()); - }; - stored.executed_successfully = true; - kv.put(scope, &key, &stored).map_err(scheduled_vote_err) - } - /// Fetches the local identities from the k/v store and maps them to their DPNS names. pub fn local_dpns_names( &self, @@ -2606,21 +2387,11 @@ pub(crate) mod test_staging { } } - /// Break the Global scheduled-vote voter index, so the next - /// `delete_local_qualified_identity` fails at the last step of - /// `purge_identity_scope` — strictly *after* `index_remove_identity` has - /// already delisted the identity. The reachable shape of a removal that - /// failed past its point of no return: the identity is gone from every - /// screen, and only its vault cleanup is outstanding. + /// Fail the top-up deletion after the identity has been delisted and its blob deleted. pub(crate) fn fail_removals_after_delisting(ctx: &Arc) { - ctx.det_kv() - .expect("identity kv") - .put( - DetScope::Global, - SCHEDULED_VOTE_VOTERS_KEY, - &"not a voter index".to_string(), - ) - .expect("corrupt the scheduled-vote voter index"); + let store = ctx.det_kv().unwrap().failing_store(); + store.fail_next_deletes_containing(TOP_UPS_KEY, 1); + ctx.set_det_kv_override_for_test(DetKv::from_store(store)); } /// Break `identity_id`'s vault-cleanup manifest slot, so its next @@ -2676,6 +2447,9 @@ mod tests { use super::test_staging::*; use super::*; use crate::context::lock_probe::{LockProbe, LockSite}; + use crate::model::dpns_voting::{ + DpnsVoteOperation, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + }; use crate::wallet_backend::kv_test_support::{FailingKv, InMemoryKv, RendezvousKv}; use DetKv; use std::sync::Arc; @@ -2771,6 +2545,28 @@ mod tests { [b; 32] } + fn scheduled_operation( + voter_id: Identifier, + poll: u8, + contested_name: &str, + status: DpnsVoteTargetStatus, + ) -> DpnsVoteOperation { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id, + vote_poll_id: Identifier::from([poll; 32]), + }, + voter_alias: None, + contested_name: contested_name.to_owned(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Scheduled(42), + }]); + operation.targets[0].status = status; + operation + } + /// Minimal stored-identity blob carrying a synthetic `qi_bytes` /// payload and the chosen type label. Avoids constructing a full /// `QualifiedIdentity` (which needs an SDK identity) for storage-layer @@ -3087,168 +2883,21 @@ mod tests { // --------------------------------------------------------------- #[test] - fn purge_identity_scope_drains_blob_top_ups_and_votes() { + fn purge_identity_scope_drains_blob_and_top_ups() { let kv = empty_kv(); let a = id(1); put_identity(&kv, &a, "Masternode"); kv.put( DetScope::Identity(&a), TOP_UPS_KEY, - &std::collections::BTreeMap::from([(0u32, 5u64)]), + &BTreeMap::from([(0u32, 5u64)]), ) .unwrap(); - kv.put( - DetScope::Identity(&a), - &scheduled_vote_key("alice"), - &StoredScheduledVote { - voter_id: a, - contested_name: "alice".to_string(), - choice: StoredVoteChoice::Lock, - unix_timestamp: 0, - executed_successfully: false, - }, - ) - .unwrap(); - index_add_vote_voter(&kv, &a).unwrap(); - purge_identity_scope(&kv, &a).unwrap(); - - assert!( - kv.get::(DetScope::Identity(&a), IDENTITY_KEY) - .unwrap() - .is_none() - ); - assert!( - kv.get::>(DetScope::Identity(&a), TOP_UPS_KEY) - .unwrap() - .is_none() - ); - assert!( - kv.list(DetScope::Identity(&a), Some(SCHEDULED_VOTE_KEY_PREFIX)) - .unwrap() - .is_empty() - ); - // The voter index is pruned by the cascade-free cleanup path. - assert!(load_scheduled_vote_voters(&kv).unwrap().is_empty()); - } - - // --------------------------------------------------------------- - // Scheduled votes: per-voter Identity scope + Global voter index. - // --------------------------------------------------------------- - - #[test] - fn scheduled_vote_round_trips_in_voter_scope() { - let kv = empty_kv(); - let voter = id(1); - let key = scheduled_vote_key("dash"); - kv.put( - DetScope::Identity(&voter), - &key, - &StoredScheduledVote { - voter_id: voter, - contested_name: "dash".to_string(), - choice: StoredVoteChoice::Abstain, - unix_timestamp: 42, - executed_successfully: false, - }, - ) - .unwrap(); - index_add_vote_voter(&kv, &voter).unwrap(); - - let got: StoredScheduledVote = kv.get(DetScope::Identity(&voter), &key).unwrap().unwrap(); - assert_eq!(got.contested_name, "dash"); - assert_eq!(got.unix_timestamp, 42); - // Voter index tracks the single voter. - assert_eq!(load_scheduled_vote_voters(&kv).unwrap(), vec![voter]); - } - - #[test] - fn scheduled_votes_for_two_voters_share_a_contested_name_without_aliasing() { - let kv = empty_kv(); - let v1 = id(1); - let v2 = id(2); - let key = scheduled_vote_key("contested"); - for (v, ts) in [(v1, 10u64), (v2, 20u64)] { - kv.put( - DetScope::Identity(&v), - &key, - &StoredScheduledVote { - voter_id: v, - contested_name: "contested".to_string(), - choice: StoredVoteChoice::Lock, - unix_timestamp: ts, - executed_successfully: false, - }, - ) - .unwrap(); - index_add_vote_voter(&kv, &v).unwrap(); - } - let got1: StoredScheduledVote = kv.get(DetScope::Identity(&v1), &key).unwrap().unwrap(); - let got2: StoredScheduledVote = kv.get(DetScope::Identity(&v2), &key).unwrap().unwrap(); - assert_eq!(got1.unix_timestamp, 10); - assert_eq!(got2.unix_timestamp, 20); - let mut voters = load_scheduled_vote_voters(&kv).unwrap(); - voters.sort_unstable(); - assert_eq!(voters, vec![v1, v2]); - } - - #[test] - fn delete_scheduled_votes_for_voter_drains_scope_and_prunes_index() { - let kv = empty_kv(); - let voter = id(1); - for name in ["a", "b"] { - kv.put( - DetScope::Identity(&voter), - &scheduled_vote_key(name), - &StoredScheduledVote { - voter_id: voter, - contested_name: name.to_string(), - choice: StoredVoteChoice::Lock, - unix_timestamp: 0, - executed_successfully: false, - }, - ) - .unwrap(); - } - index_add_vote_voter(&kv, &voter).unwrap(); - - delete_scheduled_votes_for_voter(&kv, &voter).unwrap(); - assert!( - kv.list(DetScope::Identity(&voter), Some(SCHEDULED_VOTE_KEY_PREFIX)) - .unwrap() - .is_empty() - ); - assert!(load_scheduled_vote_voters(&kv).unwrap().is_empty()); - } - - #[test] - fn prune_vote_voter_keeps_voter_with_remaining_votes() { - let kv = empty_kv(); - let voter = id(1); - kv.put( - DetScope::Identity(&voter), - &scheduled_vote_key("still-here"), - &StoredScheduledVote { - voter_id: voter, - contested_name: "still-here".to_string(), - choice: StoredVoteChoice::Lock, - unix_timestamp: 0, - executed_successfully: false, - }, - ) - .unwrap(); - index_add_vote_voter(&kv, &voter).unwrap(); - - prune_vote_voter_if_empty(&kv, &voter).unwrap(); - assert_eq!(load_scheduled_vote_voters(&kv).unwrap(), vec![voter]); + assert!(!kv.contains(DetScope::Identity(&a), IDENTITY_KEY).unwrap()); + assert!(!kv.contains(DetScope::Identity(&a), TOP_UPS_KEY).unwrap()); } - // --------------------------------------------------------------- - // dashpay private / address_index Identity-scope contracts are - // covered in `src/wallet_backend/dashpay.rs`; here we assert the - // identity domain's own scope isolation against a foreign scope. - // --------------------------------------------------------------- - #[test] fn identity_blob_is_isolated_from_a_different_identity_scope() { let kv = empty_kv(); @@ -3268,25 +2917,6 @@ mod tests { // upstream error as a `#[source]`, not a stringified detail. // --------------------------------------------------------------- - #[test] - fn voter_buffer_accepts_a_32_byte_id() { - let bytes = [7u8; 32]; - assert_eq!(voter_buffer(&bytes).unwrap(), bytes); - } - - #[test] - fn voter_buffer_rejects_short_id_with_typed_source() { - let err = voter_buffer(&[0u8; 5]).expect_err("a 5-byte voter id must be rejected"); - assert!( - matches!(err, TaskError::InvalidVoterIdentifier { .. }), - "expected InvalidVoterIdentifier, got {err:?}" - ); - assert!( - std::error::Error::source(&err).is_some(), - "the typed upstream error must be preserved as the source" - ); - } - // --------------------------------------------------------------- // F63: the index is written before the blob, so a reader tolerates a // dangling index entry rather than hiding a written identity. @@ -4074,6 +3704,136 @@ mod tests { /// `purge_identity_scope`'s first step drops the blob before the index /// removal that actually delists the identity has even run for the case /// this distinction exists to catch (a failure strictly after delisting). + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn identity_removal_cancels_executable_journal_targets_and_preserves_uncertainty() { + let staged = stage_identity_with_vaulted_keys([0x77; 32], [0x88; 32]).await; + let imported = staged + .ctx + .get_local_qualified_identity(&staged.id) + .unwrap() + .unwrap(); + let mut operations = Vec::new(); + for (index, status) in [ + DpnsVoteTargetStatus::Scheduled, + DpnsVoteTargetStatus::Queued, + DpnsVoteTargetStatus::Submitting, + DpnsVoteTargetStatus::Confirming, + DpnsVoteTargetStatus::Unconfirmed, + ] + .into_iter() + .enumerate() + { + let mut operation = scheduled_operation(staged.id, index as u8 + 1, "removed", status); + if index == 0 { + let mut sibling = operation.targets[0].clone(); + sibling.target.key.voter_id = Identifier::from([99; 32]); + operation.targets.push(sibling); + } + staged + .ctx + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + operations.push(operation); + } + staged + .ctx + .delete_local_qualified_identity(&staged.id) + .unwrap(); + for (index, operation) in operations.iter().enumerate() { + let saved = staged + .ctx + .dpns_vote_operation(operation.id) + .unwrap() + .unwrap(); + let expected = if index < 3 { + DpnsVoteTargetStatus::Cancelled + } else { + operation.targets[0].status + }; + assert_eq!(saved.targets[0].status, expected); + if index == 0 { + assert_eq!(saved.targets[1].status, DpnsVoteTargetStatus::Scheduled); + } + } + let cancelled = &operations[2]; + let key = &cancelled.targets[0].target.key; + assert!( + !staged + .ctx + .mark_dpns_vote_broadcast(cancelled.id, key) + .unwrap() + ); + staged + .ctx + .update_dpns_vote_target(cancelled.id, key, DpnsVoteTargetStatus::Scheduled, None) + .unwrap(); + assert_eq!( + staged + .ctx + .dpns_vote_operation(cancelled.id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Cancelled + ); + staged + .ctx + .insert_local_qualified_identity(&imported, &None) + .unwrap(); + staged + .ctx + .recover_interrupted_dpns_vote_operations() + .unwrap(); + assert!( + !staged + .ctx + .queue_scheduled_dpns_vote_target(cancelled.id, key) + .unwrap() + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn identity_removal_cleanup_cancels_votes_left_by_an_interrupted_removal() { + let staged = stage_identity_with_vaulted_keys([0x77; 32], [0x88; 32]).await; + let kv = staged.ctx.det_kv().unwrap(); + let id = staged.id.to_buffer(); + // The vote is scheduled while the identity is still loaded, so the + // interrupted removal below leaves it for the cleanup to cancel. + let mut scheduled = + scheduled_operation(staged.id, 9, "interrupted", DpnsVoteTargetStatus::Scheduled); + staged + .ctx + .insert_dpns_vote_operation(&mut scheduled, None) + .unwrap(); + let placements = staged.ctx.pending_vault_key_placements(&kv, &id).unwrap(); + staged + .ctx + .persist_vault_cleanup_manifest(&kv, &id, &placements) + .unwrap(); + staged.ctx.mark_identity_unloaded(&kv, &id).unwrap(); + index_remove_identity(&kv, &id).unwrap(); + + staged.ctx.resume_pending_vault_cleanups(); + + assert_eq!( + staged + .ctx + .dpns_vote_operation(scheduled.id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Cancelled + ); + assert!( + !staged + .ctx + .queue_scheduled_dpns_vote_target(scheduled.id, &scheduled.targets[0].target.key) + .unwrap() + ); + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn is_identity_listed_tracks_the_index_not_the_blob() { let staged = stage_identity_with_vaulted_keys([0x77; 32], [0x88; 32]).await; @@ -4149,7 +3909,7 @@ mod tests { } /// `purge_identity_scope` is not atomic: it can fail on its own last step - /// (pruning the scheduled-vote voter index) after its first step has + /// (deleting top-up history) after its first step has /// already deleted `IDENTITY_KEY` — the blob `identity_vault_key_placements` /// needs to re-derive a delete set. Without a durable manifest, a retry /// after such a failure would read an empty placement set from the (now @@ -4165,21 +3925,12 @@ mod tests { let staged = stage_identity_with_vaulted_keys(HIGH, LOW).await; let kv = staged.ctx.det_kv().expect("identity kv"); - // Break the Global scheduled-vote voter index so `purge_identity_scope` - // fails at its LAST step (`delete_scheduled_votes_for_voter` -> - // `remove_vote_voter_from_index`) — strictly after `IDENTITY_KEY` (the - // blob) and `TOP_UPS_KEY` are already gone. - kv.put( - DetScope::Global, - SCHEDULED_VOTE_VOTERS_KEY, - &"not a voter index".to_string(), - ) - .expect("corrupt the scheduled-vote voter index"); + fail_removals_after_delisting(&staged.ctx); let error = staged .ctx .delete_local_qualified_identity(&staged.id) - .expect_err("a corrupt voter index must fail the delete"); + .expect_err("a top-up delete failure must fail the delete"); assert!( !matches!(error, TaskError::WalletStorageNotReady), "the delete must reach purge_identity_scope, not stop at the migration guard: {error:?}" @@ -4194,13 +3945,10 @@ mod tests { before its own later step failed" ); - // Repair the index so the retry can actually complete. - kv.delete(DetScope::Global, SCHEDULED_VOTE_VOTERS_KEY) - .expect("repair the voter index"); staged .ctx .delete_local_qualified_identity(&staged.id) - .expect("the retry must complete now that the index is repaired"); + .expect("the retry must complete after the one-shot failure"); let view = IdentityKeyView::new(&staged.store, staged.id.to_buffer()); for key_id in [1, 2] { @@ -4261,20 +4009,6 @@ mod tests { &std::collections::BTreeMap::from([(0u32, 5u64)]), ) .expect("stage a top-up entry purge_identity_scope never reached"); - kv.put( - DetScope::Identity(&id_buf), - &scheduled_vote_key("alice"), - &StoredScheduledVote { - voter_id: id_buf, - contested_name: "alice".to_string(), - choice: StoredVoteChoice::Lock, - unix_timestamp: 0, - executed_successfully: false, - }, - ) - .expect("stage a scheduled vote purge_identity_scope never reached"); - index_add_vote_voter(&kv, &id_buf).expect("add to the voter index"); - staged.ctx.resume_pending_vault_cleanups(); let view = IdentityKeyView::new(&staged.store, id_buf); @@ -4301,18 +4035,6 @@ mod tests { .is_none(), "the sweep must drain the top-up history left behind by the interrupted purge" ); - assert!( - kv.list(DetScope::Identity(&id_buf), Some(SCHEDULED_VOTE_KEY_PREFIX)) - .expect("list scheduled votes") - .is_empty(), - "the sweep must drain any scheduled votes left behind by the interrupted purge" - ); - assert!( - load_scheduled_vote_voters(&kv) - .expect("read the voter index") - .is_empty(), - "the sweep must prune this voter from the Global scheduled-vote index" - ); assert!( kv.get::>( DetScope::Global, @@ -4665,7 +4387,7 @@ mod tests { ) .expect("stage the manifest the delete is meant to clear"); - failing.fail_deletes(true); + failing.fail_all_deletes(true); view.delete_all([(MAIN, 1)]).expect("delete keys"); clear_vault_cleanup_manifest(&kv, &id_buf); @@ -4673,7 +4395,7 @@ mod tests { view.get(&MAIN, 1).unwrap().is_none(), "the vault delete must have landed before the manifest clear was even attempted" ); - failing.fail_deletes(false); + failing.fail_all_deletes(false); assert!( kv.get::>(DetScope::Global, &manifest_key) .expect("read the manifest slot") @@ -5545,8 +5267,6 @@ mod tests { fail_removals_after_delisting(&staged.ctx); assert!(staged.ctx.delete_local_qualified_identity(&owner).is_err()); assert!(!staged.ctx.is_identity_listed(&owner).unwrap()); - kv.delete(DetScope::Global, SCHEDULED_VOTE_VOTERS_KEY) - .unwrap(); staged.ctx.resume_pending_vault_cleanups(); @@ -5579,6 +5299,135 @@ mod tests { backend.shutdown().await; } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn username_cleanup_failure_is_hidden_and_retried_without_skipping_vault_cleanup() { + use crate::model::dpns_usernames::{RequestPhase, UsernameRequest}; + let staged = stage_identity_with_vaulted_keys([0x33; 32], [0x44; 32]).await; + let kv = staged.ctx.det_kv().unwrap(); + let failing = kv.failing_store(); + staged + .ctx + .set_det_kv_override_for_test(DetKv::from_store(failing.clone())); + let mut request = UsernameRequest::submitted( + "Alice", + 100, + crate::model::dpns::contest_durations( + staged.ctx.network, + staged.ctx.platform_version(), + ), + None, + ); + request.phase = RequestPhase::Won; + staged + .ctx + .store_username_requests(&staged.id, vec![request]) + .unwrap(); + failing.fail_next_deletes_containing("det:username_requests:", 2); + let cleanup = staged + .ctx + .delete_local_qualified_identity_with_outcome(&staged.id) + .unwrap(); + assert!(cleanup.is_incomplete()); + assert!(!staged.ctx.is_identity_listed(&staged.id).unwrap()); + let view = IdentityKeyView::new(&staged.store, staged.id.to_buffer()); + for key in [1, 2] { + assert!( + view.get(&PrivateKeyTarget::PrivateKeyOnMainIdentity, key) + .unwrap() + .is_none() + ); + } + assert!(staged.ctx.username_requests_for(&staged.id).is_empty()); + assert!(!staged.ctx.username_requests_need_refresh()); + staged.ctx.refresh_pending_dpns_usernames().unwrap(); + assert!(staged.ctx.username_requests_for(&staged.id).is_empty()); + assert!(!staged.ctx.username_requests_need_refresh()); + staged.ctx.resume_pending_vault_cleanups(); + assert!( + !kv.list(DetScope::Global, Some(VAULT_CLEANUP_PENDING_PREFIX)) + .unwrap() + .is_empty() + ); + staged.ctx.resume_pending_vault_cleanups(); + assert!( + kv.list(DetScope::Global, Some("det:username_requests:")) + .unwrap() + .is_empty() + ); + assert!( + kv.list(DetScope::Global, Some(VAULT_CLEANUP_PENDING_PREFIX)) + .unwrap() + .is_empty() + ); + staged.ctx.wallet_backend().unwrap().shutdown().await; + } + + /// An unreadable voting journal must not keep an identity's keys on the + /// device. Removal still delists the identity and deletes its keys; the + /// retained manifest makes startup recovery cancel its votes once the + /// journal can be read again. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn identity_removal_deletes_keys_when_the_vote_journal_is_unreadable() { + let staged = stage_identity_with_vaulted_keys([0x33; 32], [0x44; 32]).await; + let kv = staged.ctx.det_kv().unwrap(); + let failing = kv.failing_store(); + staged + .ctx + .set_det_kv_override_for_test(DetKv::from_store(failing.clone())); + let mut scheduled = + scheduled_operation(staged.id, 7, "unreadable", DpnsVoteTargetStatus::Scheduled); + staged + .ctx + .insert_dpns_vote_operation(&mut scheduled, None) + .unwrap(); + + failing.fail_next_gets_containing("det:dpns_vote_operation:v2:", 1); + let cleanup = staged + .ctx + .delete_local_qualified_identity_with_outcome(&staged.id) + .expect("an unreadable vote journal must not block identity removal"); + + assert!( + cleanup.is_incomplete(), + "the vote cancellation is still owed" + ); + assert!(!staged.ctx.is_identity_listed(&staged.id).unwrap()); + let view = IdentityKeyView::new(&staged.store, staged.id.to_buffer()); + for key in [1, 2] { + assert!( + view.get(&PrivateKeyTarget::PrivateKeyOnMainIdentity, key) + .unwrap() + .is_none(), + "key {key} must be deleted even though the journal could not be read" + ); + } + assert!( + !kv.list(DetScope::Global, Some(VAULT_CLEANUP_PENDING_PREFIX)) + .unwrap() + .is_empty(), + "the manifest is kept so recovery retries the cancellation" + ); + + // The journal reads again at the next start. + staged.ctx.resume_pending_vault_cleanups(); + assert_eq!( + staged + .ctx + .dpns_vote_operation(scheduled.id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Cancelled + ); + assert!( + kv.list(DetScope::Global, Some(VAULT_CLEANUP_PENDING_PREFIX)) + .unwrap() + .is_empty() + ); + staged.ctx.wallet_backend().unwrap().shutdown().await; + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn removal_recovery_retains_manifest_until_sidecars_succeed() { let staged = stage_identity_with_vaulted_keys([0x33; 32], [0x44; 32]).await; diff --git a/src/context/identity_load_registry.rs b/src/context/identity_load_registry.rs index 6a35f89f6..3abd1d7b4 100644 --- a/src/context/identity_load_registry.rs +++ b/src/context/identity_load_registry.rs @@ -26,6 +26,10 @@ //! operation, so two overlapping loads of one identity would otherwise both pass //! the duplicate check and clobber each other's insert. //! +//! Removal invalidates outstanding claims. Final load persistence rechecks the +//! claim while holding the identity record guard, so a fresh import can start +//! without allowing an older network request to recreate the removed identity. +//! //! A record outlives its load and is replaced by the next load of that identity — //! the map holds at most one entry per identity loaded this session. @@ -103,6 +107,26 @@ pub struct IdentityLoadGuard { } impl IdentityLoadGuard { + /// Check under the identity record guard before a load writes. + /// Removal invalidates this claim even if an explicit import later restores + /// the same identity ID. + pub(crate) fn ensure_current(&self) -> Result<(), TaskError> { + let registry = self.registry.lock().unwrap_or_else(|e| e.into_inner()); + if registry + .records + .get(&self.identity_id) + .is_some_and(|record| { + record.token == self.token && record.phase == IdentityLoadPhase::Running + }) + { + Ok(()) + } else { + Err(TaskError::IdentityLoadSuperseded { + identity_id: self.identity_id, + }) + } + } + /// Record that the load fully applied. Call it after the last step that can /// fail — anything left undone after this point is reported as a success. pub fn loaded(mut self) { @@ -119,7 +143,7 @@ impl Drop for IdentityLoadGuard { let Some(record) = registry.records.get_mut(&self.identity_id) else { return; }; - if record.token != self.token { + if record.token != self.token || record.phase != IdentityLoadPhase::Running { return; } record.phase = if self.loaded { @@ -168,6 +192,20 @@ impl Drop for IdentityLoadDispatch { } impl AppContext { + /// Invalidate outstanding work after delisting, while holding the identity + /// record guard shared by identity loads and explicit imports. + pub(crate) fn invalidate_identity_load(&self, identity_id: Identifier) { + let mut registry = self + .identity_loads + .lock() + .unwrap_or_else(|e| e.into_inner()); + if let Some(record) = registry.records.get_mut(&identity_id) + && record.phase.is_outstanding() + { + record.phase = IdentityLoadPhase::Failed; + } + } + /// Record that a load of `identity_id` has been dispatched, before its task /// runs, and return the token identifying it. Callers that gate on a load must /// mark it here: until its task claims the identity, nothing else records that @@ -235,6 +273,9 @@ impl AppContext { Some(record) if record.phase.is_outstanding() => { return Err(TaskError::IdentityLoadInProgress { identity_id }); } + _ if token.is_some() => { + return Err(TaskError::IdentityLoadSuperseded { identity_id }); + } _ => registry.mint(), }; registry.records.insert( @@ -354,6 +395,37 @@ mod tests { .expect("a finished identity can be loaded again"); } + #[test] + fn an_invalidated_submission_cannot_mint_a_replacement_claim() { + let tmp = tempfile::tempdir().expect("tempdir"); + let ctx = test_app_context(tmp.path()); + let id = Identifier::from([0x31; 32]); + let old_token = ctx.mark_identity_load_submitted(id).unwrap(); + ctx.invalidate_identity_load(id); + assert!(matches!( + ctx.begin_identity_load(id, Some(old_token)), + Err(TaskError::IdentityLoadSuperseded { .. }) + )); + let fresh_token = ctx.mark_identity_load_submitted(id).unwrap(); + drop(ctx.begin_identity_load(id, Some(fresh_token)).unwrap()); + assert_eq!( + ctx.identity_load_phase(&id, fresh_token), + Some(IdentityLoadPhase::Failed) + ); + let fresh_token = ctx.mark_identity_load_submitted(id).unwrap(); + ctx.begin_identity_load(id, Some(fresh_token)) + .unwrap() + .loaded(); + assert!(matches!( + ctx.begin_identity_load(id, Some(old_token)), + Err(TaskError::IdentityLoadSuperseded { .. }) + )); + assert_eq!( + ctx.identity_load_phase(&id, fresh_token), + Some(IdentityLoadPhase::Loaded) + ); + } + /// Regression: a load must never adopt a record it was not dispatched under. /// Only the Masternodes form marks its load `Submitted`; the other entry points /// (Add Existing, the detail screen, an MCP tool) dispatch straight to the task. diff --git a/src/context/identity_names.rs b/src/context/identity_names.rs index 39d984838..290ef4a9d 100644 --- a/src/context/identity_names.rs +++ b/src/context/identity_names.rs @@ -64,12 +64,11 @@ impl AppContext { }) } - /// Name an identity consistently with its profile, username, or shortened identifier. + /// Name an identity consistently with its profile, main username, or shortened identifier. pub fn identity_display_label(&self, identity: &QualifiedIdentity) -> String { - identity.display_name_label( - self.identity_display_name(identity.identity.id()) - .as_deref(), - ) + let display_name = self.identity_display_name(identity.identity.id()); + let main_username = self.main_username(identity); + identity.display_name_label_with_username(display_name.as_deref(), main_username.as_deref()) } /// Serialize profile fetch/mirror/write operations for this owner and network. diff --git a/src/context/legacy_scheduled_votes.rs b/src/context/legacy_scheduled_votes.rs new file mode 100644 index 000000000..bd28fea26 --- /dev/null +++ b/src/context/legacy_scheduled_votes.rs @@ -0,0 +1,229 @@ +//! Read-only detection of schedules that require a new voting decision. + +use super::AppContext; +use crate::backend_task::error::TaskError; +use crate::utils::time::now_ms; +use crate::wallet_backend::{DetScope, network_prefix}; +use std::collections::BTreeSet; +use std::time::Duration; + +const NOTICED_AT_KEY_PREFIX: &str = "det:legacy_scheduled_votes_noticed_at:v1:"; + +/// Whether a notice first raised at `first_noticed_at_ms` is still worth +/// showing: once a full contest has passed, every contest an old schedule +/// could refer to has closed and nothing is left to schedule again. +fn legacy_notice_is_current( + first_noticed_at_ms: u64, + now_ms: u64, + contest_duration: Duration, +) -> bool { + let window_ms = u64::try_from(contest_duration.as_millis()).unwrap_or(u64::MAX); + now_ms.saturating_sub(first_noticed_at_ms) < window_ms +} + +impl AppContext { + /// Whether startup should tell the user about old, unexecuted schedules. + /// + /// Old schedules are neither imported nor listed, so the user cannot retire + /// the notice for a contest that has ended. It therefore stops one contest + /// duration after its first appearance, which this call records. + pub(crate) fn legacy_scheduled_votes_notice_due(&self) -> Result { + if !self.has_legacy_scheduled_votes()? { + return Ok(false); + } + let kv = self.det_kv()?; + let key = format!("{NOTICED_AT_KEY_PREFIX}{}", network_prefix(self.network)); + let storage_err = |source| TaskError::DpnsVoteOperationStorage { source }; + let now = now_ms(); + let first_noticed_at = match kv.get::(DetScope::Global, &key).map_err(storage_err)? { + Some(at) => at, + None => { + kv.put(DetScope::Global, &key, &now).map_err(storage_err)?; + now + } + }; + let contest_duration = crate::model::dpns::contest_durations( + self.network, + super::default_platform_version(&self.network), + ) + .total; + Ok(legacy_notice_is_current( + first_noticed_at, + now, + contest_duration, + )) + } + + /// Whether unexecuted SQLite schedules still need an explicit voting decision. + pub(crate) fn has_legacy_scheduled_votes(&self) -> Result { + let old = crate::database::legacy_import::read_scheduled_votes( + &self.db.locked_conn(), + self.network, + ) + .map_err(|source| TaskError::LegacyScheduledVotesRead { source })?; + if old.unreadable > 0 { + return Ok(true); + } + if old.votes.iter().all(|vote| vote.executed_successfully) { + return Ok(false); + } + let operations = self.dpns_vote_operations()?; + let represented: BTreeSet<_> = operations + .iter() + .flat_map(|operation| &operation.targets) + .map(|outcome| { + ( + outcome.target.key.voter_id, + outcome.target.contested_name.as_str(), + ) + }) + .collect(); + Ok(old.votes.iter().any(|vote| { + !vote.executed_successfully + && !represented.contains(&(vote.voter_id, vote.contested_name.as_str())) + })) + } +} + +#[cfg(test)] +mod tests { + use crate::context::AppContext; + use crate::database::test_helpers::{ + create_legacy_scheduled_votes_table, seed_legacy_scheduled_vote_row, + }; + use crate::model::dpns_voting::{DpnsVoteTarget, DpnsVoteTargetKey, VoteTiming}; + use crate::wallet_backend::{DetKv, kv_test_support::InMemoryKv}; + use dash_sdk::dpp::{ + dashcore::Network, voting::vote_choices::resource_vote_choice::ResourceVoteChoice, + }; + use dash_sdk::platform::Identifier; + use std::sync::Arc; + + #[test] + fn startup_notice_detects_old_schedules_without_importing_them() { + let dir = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(dir.path()); + context.set_det_kv_override_for_test(DetKv::from_store(Arc::new(InMemoryKv::default()))); + assert!(!context.has_legacy_scheduled_votes().unwrap()); + create_legacy_scheduled_votes_table(&context.db).unwrap(); + seed_legacy_scheduled_vote_row(&context.db, &[1; 32], "alice", "Lock", Network::Testnet) + .unwrap(); + assert!(context.has_legacy_scheduled_votes().unwrap()); + assert!(context.dpns_vote_operations().unwrap().is_empty()); + assert!( + context.has_legacy_scheduled_votes().unwrap(), + "detection leaves the old record intact" + ); + + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([2; 32]), + }, + voter_alias: None, + contested_name: "alice".into(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Scheduled(u64::MAX), + }]); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + assert!( + !context.has_legacy_scheduled_votes().unwrap(), + "already represented votes do not need a new decision" + ); + } + + /// The user cannot retire the notice for a contest that already ended, so + /// it must stop by itself once no old schedule can still matter. + #[test] + fn startup_notice_stops_one_contest_duration_after_it_first_appeared() { + use super::{NOTICED_AT_KEY_PREFIX, legacy_notice_is_current}; + use crate::utils::time::now_ms; + use crate::wallet_backend::{DetScope, network_prefix}; + use std::time::Duration; + + let hour = Duration::from_secs(3600); + assert!(legacy_notice_is_current(1_000, 1_000, hour)); + assert!(legacy_notice_is_current(1_000, 1_000 + 3_599_999, hour)); + assert!(!legacy_notice_is_current(1_000, 1_000 + 3_600_000, hour)); + + let dir = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(dir.path()); + let kv = DetKv::from_store(Arc::new(InMemoryKv::default())); + context.set_det_kv_override_for_test(kv.clone()); + assert!(!context.legacy_scheduled_votes_notice_due().unwrap()); + create_legacy_scheduled_votes_table(&context.db).unwrap(); + seed_legacy_scheduled_vote_row(&context.db, &[1; 32], "alice", "Lock", Network::Testnet) + .unwrap(); + assert!(context.legacy_scheduled_votes_notice_due().unwrap()); + assert!( + context.legacy_scheduled_votes_notice_due().unwrap(), + "the notice returns on later launches while a contest may still be open" + ); + + let contest_duration = crate::model::dpns::contest_durations( + Network::Testnet, + crate::context::default_platform_version(&Network::Testnet), + ) + .total; + let long_ago = now_ms() - u64::try_from(contest_duration.as_millis()).unwrap() - 1; + kv.put( + DetScope::Global, + &format!( + "{NOTICED_AT_KEY_PREFIX}{}", + network_prefix(Network::Testnet) + ), + &long_ago, + ) + .unwrap(); + assert!(!context.legacy_scheduled_votes_notice_due().unwrap()); + assert!( + context.has_legacy_scheduled_votes().unwrap(), + "the old record itself stays untouched" + ); + } + + #[test] + fn startup_notice_ignores_executed_votes_and_other_networks() { + let dir = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(dir.path()); + create_legacy_scheduled_votes_table(&context.db).unwrap(); + seed_legacy_scheduled_vote_row( + &context.db, + &[1; 32], + "other-network", + "Lock", + Network::Mainnet, + ) + .unwrap(); + seed_legacy_scheduled_vote_row(&context.db, &[1; 32], "executed", "Lock", Network::Testnet) + .unwrap(); + context + .db + .execute( + "UPDATE scheduled_votes SET executed = 1 WHERE contested_name = 'executed'", + [], + ) + .unwrap(); + assert!(!context.has_legacy_scheduled_votes().unwrap()); + } + + #[test] + fn startup_notice_reports_unreadable_schedules() { + let dir = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(dir.path()); + create_legacy_scheduled_votes_table(&context.db).unwrap(); + seed_legacy_scheduled_vote_row( + &context.db, + &[1; 32], + "alice", + "invalid choice", + Network::Testnet, + ) + .unwrap(); + assert!(context.has_legacy_scheduled_votes().unwrap()); + } +} diff --git a/src/context/migration_status.rs b/src/context/migration_status.rs index 66d3afe5f..4386d5c69 100644 --- a/src/context/migration_status.rs +++ b/src/context/migration_status.rs @@ -34,8 +34,8 @@ pub enum MigrationStep { Wiring, /// Sniffing `data.db` for legacy rows. Detecting, - /// Importing DET-owned rows the wallet drain never touched: scheduled - /// DPNS votes and top-up history. + /// Importing DET-owned rows the wallet drain never touched: top-up + /// history. Legacy scheduled DPNS votes are not imported. AppData, /// Copying `single_key_wallet` rows into the upstream `SecretStore`. SingleKey, @@ -122,11 +122,7 @@ pub enum MigrationState { /// The storage update completed, but one or more legacy rows could not be /// decoded. Each non-zero counter is backed by a durable warning record and /// identifies the recovery instructions the banner must show. - SucceededWithUnreadableData { - identities: u32, - votes: u32, - top_ups: u32, - }, + SucceededWithUnreadableData { identities: u32, top_ups: u32 }, /// Both DET-owned passes are damaged on the same launch: the wallet drain /// landed, but `count` legacy identities could not be decoded AND the /// app-data import hit a hard failure. Rendered as a single retryable error @@ -170,15 +166,13 @@ impl PartialEq for MigrationState { ( MigrationState::SucceededWithUnreadableData { identities: ia, - votes: va, top_ups: ta, }, MigrationState::SucceededWithUnreadableData { identities: ib, - votes: vb, top_ups: tb, }, - ) => ia == ib && va == vb && ta == tb, + ) => ia == ib && ta == tb, (MigrationState::Running { step: a }, MigrationState::Running { step: b }) => a == b, ( MigrationState::AwaitingWalletPasswords { wallets: a }, diff --git a/src/context/mod.rs b/src/context/mod.rs index 2fde46f41..0a49b9871 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -1,6 +1,13 @@ pub mod connection_status; mod contested_names_db; mod contract_token_db; +mod dpns_vote_attention; +mod dpns_vote_operations; +mod dpns_vote_preferences; +mod dpns_vote_state; +mod legacy_scheduled_votes; +pub(crate) use dpns_vote_operations::DpnsVoterLifecycles; +pub(crate) use dpns_vote_state::DpnsVoteRefreshResults; pub mod feature_gate; mod identity_db; mod identity_names; @@ -25,6 +32,7 @@ use crate::config::{Config, NetworkConfig}; use crate::context::feature_gate::ExperimentalFeature; use crate::context_provider::SpvProvider; use crate::database::Database; +use crate::model::dpns_voting::{DpnsVoteOperationId, DpnsVoteTargetKey}; use crate::model::fee_estimation::PlatformFeeEstimator; use crate::model::qualified_identity::{IdentityType, QualifiedIdentity}; use crate::model::request_type::RequestType; @@ -55,7 +63,7 @@ use dash_sdk::platform::Identifier; use egui::Context; use migration_status::MigrationStatus; use platform_wallet_storage::secrets::SecretStore; -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::PathBuf; use std::str::FromStr as _; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; @@ -67,6 +75,10 @@ use crate::model::user_role::{UserRole, UserRoleCell}; const ANIMATION_REFRESH_TIME: std::time::Duration = std::time::Duration::from_millis(100); pub const SDK_THREAD_STACK_SIZE: usize = 4 * 1024 * 1024; // 4 MB stack size for each worker thread +type DpnsVoteDiagnosticKey = (DpnsVoteOperationId, DpnsVoteTargetKey); +type DpnsVoteDiagnosticEntry = (u64, Arc); +type DpnsVoteDiagnostics = BTreeMap; + /// A guard that ensures settings cache invalidation happens atomically /// /// This guard holds a write lock on the cached settings, preventing reads @@ -87,6 +99,67 @@ impl Drop for ContactRequestActionClaim<'_> { } } +/// Voters DET talks to Platform about at once — the dispatch semaphore, the +/// per-operation submission fan-out, the due-schedule sweep and the proved +/// vote-state refresh all share this single budget. +pub(crate) const MAX_CONCURRENT_DPNS_VOTERS: usize = 4; + +/// Startup recovery runs once. Later failures retry only the affected targets. +#[derive(Debug, Default)] +pub(crate) struct DpnsVoteRecovery { + pub(crate) initialized: bool, + pub(crate) pending: std::collections::BTreeMap< + crate::model::dpns_voting::DpnsVoteOperationId, + std::collections::BTreeSet, + >, +} + +#[derive(Debug)] +pub(crate) struct DpnsVoteDispatchCoordinator { + voter_gates: Mutex>>>, + permits: Arc, +} + +impl Default for DpnsVoteDispatchCoordinator { + fn default() -> Self { + Self { + voter_gates: Mutex::new(HashMap::new()), + permits: Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_DPNS_VOTERS)), + } + } +} + +pub(crate) struct DpnsVoteDispatchGuard { + _voter: tokio::sync::OwnedMutexGuard<()>, + _permit: tokio::sync::OwnedSemaphorePermit, +} + +impl DpnsVoteDispatchCoordinator { + pub(crate) async fn acquire( + &self, + voter_id: Identifier, + ) -> Result { + let voter_gate = self + .voter_gates + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .entry(voter_id) + .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(()))) + .clone(); + // Take the per-voter gate first so queued work for one busy voter + // cannot consume all of the cross-voter capacity. + let voter = voter_gate.lock_owned().await; + let permit = Arc::clone(&self.permits) + .acquire_owned() + .await + .map_err(|_| TaskError::DpnsVoteCoordinatorUnavailable)?; + Ok(DpnsVoteDispatchGuard { + _voter: voter, + _permit: permit, + }) + } +} + #[derive(Debug)] pub struct AppContext { pub(crate) data_dir: PathBuf, @@ -139,14 +212,36 @@ pub struct AppContext { /// Cached settings to avoid repeated k/v reads + bincode decoding. /// Use RwLock to allow multiple readers but exclusive writers for cache invalidation. cached_settings: RwLock>, - /// Frame-safe pending DPNS names rebuilt after the contest cache changes. - pending_dpns_usernames: - RwLock>, + /// Frame-safe identity username state (requests, main name, seen outcomes). + pending_dpns_usernames: RwLock, + /// Contestant labels read by the progress drawer without storage access. + dpns_candidate_labels: RwLock>>, + /// What needs the masternode operator's vote, recomputed on refresh and on + /// coordinator updates (never per frame). Read by the top-bar chip and nav badge. + dpns_vote_attention: RwLock>, + /// Current masternode-list membership (ProTxHash → is evonode); `None` + /// until the SPV masternode list is available. + masternode_list_membership: RwLock>>>, + /// Journal operations published after executor transitions (progress drawer). + /// Each is shared, so publishing one change copies no other operation. + dpns_vote_progress: RwLock]>>, + /// A `Review again` request from the progress drawer for the voting panel. + dpns_vote_review_request: std::sync::Mutex>, + /// Vote operations dismissed in the progress drawer this session. + dpns_dismissed_vote_operations: std::sync::Mutex< + std::collections::BTreeSet, + >, + /// A request from outside the voting panel to show one contest by label. + dpns_votes_name_request: std::sync::Mutex>, + /// Unix ms of the last completed contest + vote-state refresh; 0 = never. + dpns_contests_refreshed_at_ms: std::sync::atomic::AtomicU64, /// Shared app-level k/v store at `/det-app.sqlite`. /// Cross-network, global-scoped slot used for `AppSettings` and other /// DET-owned application data that must outlive a single network's /// wallet persister. Cheap to clone (`Arc` is `Arc`-backed). app_kv: Arc, + #[cfg(test)] + det_kv_override: Mutex>, /// Shared encrypted HD-seed vault at `/secrets/det-secrets.pwsvault`. /// Opened once and handed to every per-network `AppContext` and to the /// `WalletBackend`, because the file backend takes an exclusive advisory @@ -177,6 +272,22 @@ pub struct AppContext { /// Process-local claim shared by every UI surface before a paid DashPay /// request action enters its backend flow. contact_request_actions_in_flight: Mutex>, + /// Serializes operation journal writes and target-lock acquisition. + dpns_vote_operation_guard: Mutex<()>, + /// Bumped under `dpns_vote_operation_guard` when a removed voter is loaded + /// again; see [`AppContext::dpns_voter_lifecycles`]. + dpns_voter_lifecycles: Mutex, + /// Coordinates proof publication and short state-to-journal validation. + dpns_vote_state_publications: dpns_vote_state::DpnsVoteStatePublications, + /// Serializes all nonce-consuming vote submissions per voter across tasks, + /// while bounding unrelated voters globally. + pub(crate) dpns_vote_dispatch: DpnsVoteDispatchCoordinator, + pub(crate) dpns_vote_refresh_permits: tokio::sync::Semaphore, + /// Runs crash recovery before this context first accepts vote work. + pub(crate) dpns_vote_recovery: tokio::sync::Mutex, + /// Full in-process diagnostics keyed to sanitized durable outcomes. + dpns_vote_diagnostics: Mutex, + dpns_vote_diagnostic_sequence: AtomicU64, /// Pending wallet selection - set after creating/importing a wallet /// so the wallet screen can auto-select the new wallet pub(crate) pending_wallet_selection: Mutex>, @@ -495,8 +606,18 @@ impl AppContext { identity_profile_names: Mutex::default(), animations_disabled: AtomicBool::new(false), cached_settings: RwLock::new(None), - pending_dpns_usernames: RwLock::new(HashMap::new()), + pending_dpns_usernames: RwLock::new(Default::default()), + dpns_candidate_labels: RwLock::new(Default::default()), + dpns_vote_attention: RwLock::new(Default::default()), + masternode_list_membership: RwLock::new(None), + dpns_contests_refreshed_at_ms: std::sync::atomic::AtomicU64::new(0), + dpns_vote_progress: RwLock::new(Arc::from(Vec::new())), + dpns_vote_review_request: std::sync::Mutex::new(None), + dpns_votes_name_request: std::sync::Mutex::new(None), + dpns_dismissed_vote_operations: std::sync::Mutex::new(Default::default()), app_kv, + #[cfg(test)] + det_kv_override: Mutex::new(None), secret_store, subtasks, token_balance_refresh_in_flight: AtomicBool::new(false), @@ -505,6 +626,14 @@ impl AppContext { prepare_gate: tokio::sync::Mutex::new(()), storage_prepared: AtomicBool::new(false), contact_request_actions_in_flight: Mutex::new(HashSet::new()), + dpns_vote_operation_guard: Mutex::new(()), + dpns_voter_lifecycles: Mutex::default(), + dpns_vote_dispatch: DpnsVoteDispatchCoordinator::default(), + dpns_vote_refresh_permits: tokio::sync::Semaphore::new(MAX_CONCURRENT_DPNS_VOTERS), + dpns_vote_state_publications: dpns_vote_state::DpnsVoteStatePublications::default(), + dpns_vote_recovery: tokio::sync::Mutex::new(DpnsVoteRecovery::default()), + dpns_vote_diagnostics: Mutex::new(BTreeMap::new()), + dpns_vote_diagnostic_sequence: AtomicU64::new(0), pending_wallet_selection: Mutex::new(None), selected_wallet_hash: Mutex::new(selected_wallet_hash), selected_single_key_hash: Mutex::new(selected_single_key_hash), @@ -594,9 +723,26 @@ impl AppContext { /// backend is not yet initialized. Single accessor shared by every /// `context/*_db.rs` module. pub(crate) fn det_kv(&self) -> Result { + #[cfg(test)] + if let Some(kv) = self + .det_kv_override + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + { + return Ok(kv); + } Ok(self.wallet_backend()?.kv()) } + #[cfg(test)] + pub(crate) fn set_det_kv_override_for_test(&self, kv: DetKv) { + *self + .det_kv_override + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(kv); + } + /// Shared encrypted HD-seed vault. Cheap clone — `Arc` is /// `Arc`-backed. The wallet backend reuses this same handle rather than /// opening its own, because the file vault takes an exclusive advisory @@ -1172,6 +1318,9 @@ impl AppContext { "Pending DPNS username cache could not be warmed from stored contests" ); } + if let Err(error) = self.refresh_dpns_candidate_labels() { + tracing::warn!(?error, "DPNS candidate labels could not be loaded"); + } self.restore_selected_wallet_from_kv(); self.restore_selected_identity_from_kv(); // Render the platform section (per-address tab, total, "Addresses synced" @@ -1677,6 +1826,28 @@ mod tests { } } + /// Contest timing is read from this pin on the voting side and from the live + /// SDK version on the identity side. The SDK only ratchets upward from the + /// pin, so both sides describe one contest as long as every newer version + /// this build knows keeps the pinned windows. + #[test] + fn contest_durations_match_the_pin_for_every_version_the_sdk_can_report() { + use crate::model::dpns::contest_durations; + + let newest = PlatformVersion::latest().protocol_version; + for network in [Network::Mainnet, Network::Testnet] { + let pinned = contest_durations(network, default_platform_version(&network)); + for protocol_version in DET_PLATFORM_VERSION.protocol_version..=newest { + let live = PlatformVersion::get(protocol_version).expect("known version"); + assert_eq!( + contest_durations(network, live), + pinned, + "protocol {protocol_version} on {network}" + ); + } + } + } + #[test] fn install_secret_prompt_recovers_poisoned_slot() { use crate::context::test_support::test_app_context; @@ -2099,4 +2270,63 @@ mod tests { "a User selection is kept by the sanitizer", ); } + + async fn observe_dispatch( + coordinator: Arc, + voter_id: Identifier, + active: Arc, + maximum: Arc, + ) { + let _guard = coordinator.acquire(voter_id).await.unwrap(); + let now = active.fetch_add(1, Ordering::SeqCst) + 1; + maximum.fetch_max(now, Ordering::SeqCst); + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + active.fetch_sub(1, Ordering::SeqCst); + } + + #[tokio::test] + async fn dpns_dispatch_serializes_independent_operations_for_one_voter() { + let coordinator = Arc::new(DpnsVoteDispatchCoordinator::default()); + let active = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let maximum = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let voter = Identifier::from([7; 32]); + let first = tokio::spawn(observe_dispatch( + Arc::clone(&coordinator), + voter, + Arc::clone(&active), + Arc::clone(&maximum), + )); + let second = tokio::spawn(observe_dispatch( + coordinator, + voter, + Arc::clone(&active), + Arc::clone(&maximum), + )); + first.await.unwrap(); + second.await.unwrap(); + + assert_eq!(maximum.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn dpns_dispatch_bounds_independent_voters() { + let coordinator = Arc::new(DpnsVoteDispatchCoordinator::default()); + let active = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let maximum = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let tasks = (0..8) + .map(|voter| { + tokio::spawn(observe_dispatch( + Arc::clone(&coordinator), + Identifier::from([voter; 32]), + Arc::clone(&active), + Arc::clone(&maximum), + )) + }) + .collect::>(); + for task in tasks { + task.await.unwrap(); + } + + assert_eq!(maximum.load(Ordering::SeqCst), MAX_CONCURRENT_DPNS_VOTERS); + } } diff --git a/src/context/settings_db.rs b/src/context/settings_db.rs index 933c10409..7dd083115 100644 --- a/src/context/settings_db.rs +++ b/src/context/settings_db.rs @@ -317,7 +317,7 @@ mod tests { let ctx = test_app_context_with_kv(tmp.path(), Arc::new(DetKv::from_store(store.clone()))); ctx.set_backup_retention(BackupRetention::KeepForever) .unwrap(); - store.fail_reads(true); + store.fail_all_reads(true); assert!(ctx.backup_retention().is_err()); } @@ -541,7 +541,7 @@ mod tests { let puts_before = store.put_count(); // Every read now fails. Bypass the cache so the load actually hits it. - store.fail_reads(true); + store.fail_all_reads(true); drop(ctx.invalidate_settings_cache()); let got = ctx.get_app_settings(); @@ -556,7 +556,7 @@ mod tests { ); // The store recovers: the stored settings must be exactly as they were. - store.fail_reads(false); + store.fail_all_reads(false); drop(ctx.invalidate_settings_cache()); let recovered = ctx.get_app_settings(); assert_eq!( @@ -593,7 +593,7 @@ mod tests { ctx.set_app_settings(&stored).unwrap(); // One failing read, with the cache cold so the load actually hits the store. - store.fail_reads(true); + store.fail_all_reads(true); drop(ctx.invalidate_settings_cache()); assert_eq!( ctx.get_app_settings().network, @@ -602,7 +602,7 @@ mod tests { ); // The store recovers on its own; nothing invalidates the cache in between. - store.fail_reads(false); + store.fail_all_reads(false); let recovered = ctx.get_app_settings(); assert_eq!( @@ -676,7 +676,7 @@ mod tests { .unwrap(); let puts_before = store.put_count(); - store.fail_reads(true); + store.fail_all_reads(true); drop(ctx.invalidate_settings_cache()); let result = ctx.update_app_settings(|s| s.auto_start_spv = true); @@ -687,7 +687,7 @@ mod tests { "a failed read-modify-write must not commit anything" ); - store.fail_reads(false); + store.fail_all_reads(false); drop(ctx.invalidate_settings_cache()); let recovered = ctx.get_app_settings(); assert_eq!(recovered.user_role, Some(UserRole::Developer)); @@ -711,7 +711,7 @@ mod tests { .expect("a healthy store persists the role"); assert_eq!(ctx.user_role(), UserRole::Everyday); - store.fail_reads(true); + store.fail_all_reads(true); drop(ctx.invalidate_settings_cache()); let result = ctx.set_and_persist_user_role(UserRole::Developer); @@ -784,7 +784,7 @@ mod tests { // nothing would be indistinguishable from neither fallback firing. ctx.set_user_role(UserRole::Developer); - store.fail_reads(true); + store.fail_all_reads(true); drop(ctx.invalidate_settings_cache()); ctx.seed_user_role_from_settings(); @@ -801,7 +801,7 @@ mod tests { // The store recovers. The user's real role is still Everyday — a restart // (or re-picking the mode) seeds it, and the failed read left nothing behind. - store.fail_reads(false); + store.fail_all_reads(false); drop(ctx.invalidate_settings_cache()); ctx.seed_user_role_from_settings(); diff --git a/src/context/test_support.rs b/src/context/test_support.rs index 5110f2ab0..ff6bae856 100644 --- a/src/context/test_support.rs +++ b/src/context/test_support.rs @@ -7,11 +7,39 @@ use std::path::Path; use std::sync::Arc; use dash_sdk::dpp::dashcore::Network; +use dash_sdk::platform::Identifier; use super::AppContext; +use crate::model::qualified_identity::QualifiedIdentity; use crate::model::user_role::UserRoleCell; use crate::wallet_backend::DetKv; +/// A user identity with no names, alias, keys or wallet. +pub(crate) fn bare_user_identity(id: Identifier, network: Network) -> QualifiedIdentity { + use crate::model::qualified_identity::encrypted_key_storage::KeyStorage; + use crate::model::qualified_identity::{IdentityStatus, IdentityType}; + QualifiedIdentity { + identity: dash_sdk::platform::Identity::create_basic_identity( + id, + dash_sdk::dpp::version::PlatformVersion::latest(), + ) + .expect("identity"), + associated_voter_identity: None, + associated_operator_identity: None, + associated_owner_key_id: None, + identity_type: IdentityType::User, + alias: None, + private_keys: KeyStorage::default(), + dpns_names: Vec::new(), + associated_wallets: Default::default(), + secret_access: None, + wallet_index: None, + top_ups: Default::default(), + status: IdentityStatus::Active, + network, + } +} + /// Build a network-free [`AppContext`] backed by throwaway temp storage — enough /// to exercise the settings read-modify-write and feature-gate paths. pub(crate) fn test_app_context(dir: &Path) -> Arc { diff --git a/src/mcp/tools/meta.rs b/src/mcp/tools/meta.rs index d9be4f987..47a12eb7f 100644 --- a/src/mcp/tools/meta.rs +++ b/src/mcp/tools/meta.rs @@ -133,6 +133,8 @@ pub struct NetworkSentinels { #[derive(Serialize, schemars::JsonSchema)] pub struct UnreadableCounts { identities: u32, + /// Always `0`. The upgrade does not read scheduled votes from the previous + /// version; the field stays so existing clients keep parsing the summary. votes: u32, top_ups: u32, } @@ -516,12 +518,11 @@ fn summarize_migration(state: &MigrationState) -> MigrationSummary { MigrationState::Success => summary("success"), MigrationState::SucceededWithUnreadableData { identities, - votes, top_ups, } => MigrationSummary { unreadable: Some(UnreadableCounts { identities: *identities, - votes: *votes, + votes: 0, top_ups: *top_ups, }), ..summary("succeeded_with_unreadable_data") @@ -678,14 +679,13 @@ mod tests { fn succeeded_with_unreadable_data_reports_every_counter() { let summary = summarize_migration(&MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 2, top_ups: 3, }); assert_eq!(summary.state, "succeeded_with_unreadable_data"); assert!(summary.error.is_none()); let counts = summary.unreadable.expect("counts"); - assert_eq!((counts.identities, counts.votes, counts.top_ups), (1, 2, 3)); + assert_eq!((counts.identities, counts.votes, counts.top_ups), (1, 0, 3)); } /// A profile with no app store is a legitimate "nothing applied yet", not a diff --git a/src/mcp/tools/network.rs b/src/mcp/tools/network.rs index 8ad85ca95..13aed368f 100644 --- a/src/mcp/tools/network.rs +++ b/src/mcp/tools/network.rs @@ -293,7 +293,7 @@ mod tests { let ctx = test_app_context_with_kv(tmp.path(), Arc::new(DetKv::from_store(store.clone()))); let service = DashMcpService::new_shared(Arc::new(arc_swap::ArcSwap::from(Arc::clone(&ctx)))); - store.fail_next_puts(usize::MAX); + store.fail_next_puts_containing("", usize::MAX); let result = NetworkSwitch::invoke( &service, NetworkSwitchParams { diff --git a/src/model/contested_name.rs b/src/model/contested_name.rs index c8da5396b..bac538c89 100644 --- a/src/model/contested_name.rs +++ b/src/model/contested_name.rs @@ -3,8 +3,7 @@ use bincode::{Decode, Encode}; use dash_sdk::dpp::identity::{KeyID, TimestampMillis}; use dash_sdk::dpp::prelude::{BlockHeight, CoreBlockHeight, Identifier}; use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; -use std::cmp::Ordering; -use std::collections::{BTreeMap, HashMap}; +use std::collections::BTreeMap; /// Maximum number of Unicode scalar values rendered for a pending DPNS label. pub const MAX_PENDING_USERNAME_DISPLAY_CHARS: usize = 63; @@ -23,6 +22,13 @@ impl ContestState { pub fn state_is_votable(&self) -> bool { matches!(self, ContestState::Joinable | ContestState::Ongoing) } + + /// Whether the contest is positively known to be decided — won or locked. + /// + /// `Unknown` is not decided: it only means DET lacks the data to tell. + pub fn is_decided(&self) -> bool { + matches!(self, ContestState::WonBy(_) | ContestState::Locked) + } } #[derive(Debug, Encode, Decode, Clone)] @@ -39,105 +45,10 @@ pub struct ContestedName { } impl ContestedName { - /// Whether `voter_id` still has an actionable vote to cast on this contest: - /// the contest is in a votable state and the voter has not already recorded - /// a vote on it. Drives the Masternodes card DPNS status line (§10.1). - pub fn is_open_for_voter(&self, voter_id: &Identifier) -> bool { - self.state.state_is_votable() && !self.my_votes.keys().any(|(id, _, _)| id == voter_id) - } - - /// The pending DPNS username this contest represents for `identity_id`, if - /// the identity is a still-undecided contender in it. - /// - /// Returns `None` when the contest is already decided (`WonBy` or `Locked`) - /// or the identity is not among its contenders — an awarded or lost name is - /// no longer "pending". Used to tell "requested but not yet awarded" apart - /// from "no username requested". - pub fn pending_username_for(&self, identity_id: &Identifier) -> Option { - if matches!(self.state, ContestState::WonBy(_) | ContestState::Locked) { - return None; - } - let mine = self - .contestants - .as_ref()? - .iter() - .find(|c| c.id == *identity_id)?; - Some(PendingUsername { - name: mine.name.clone(), - decided_at: self.end_time, - }) - } -} - -/// A DPNS username an identity has requested but has not yet been awarded — the -/// name contest is still open. Surfaced in the UI as a "Pending" indicator so a -/// requested-but-unawarded name is not mistaken for "no username requested". -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PendingUsername { - /// The requested name label (without the `.dash` suffix), as submitted. - pub name: String, - /// When the request is expected to be decided, in Unix milliseconds. - /// `None` when the timing is not yet known. - pub decided_at: Option, -} - -/// The highest-priority pending DPNS username `identity_id` has across `contests`. -/// -/// Pure and side-effect-free: the caller supplies the contest set (typically the -/// ongoing-contest cache). The earliest known decision time wins; unknown times -/// follow known times, and the name provides a stable tie-breaker. -pub fn pending_username_in<'a, I>(contests: I, identity_id: &Identifier) -> Option -where - I: IntoIterator, -{ - contests - .into_iter() - .filter_map(|contest| contest.pending_username_for(identity_id)) - .min_by(pending_username_priority) -} - -/// Build the deterministic pending-username snapshot for every contender. -pub fn pending_usernames_in<'a, I>(contests: I) -> HashMap -where - I: IntoIterator, -{ - let mut pending_by_identity = HashMap::::new(); - for contest in contests { - if matches!(contest.state, ContestState::WonBy(_) | ContestState::Locked) { - continue; - } - let Some(contestants) = contest.contestants.as_ref() else { - continue; - }; - for contestant in contestants { - let candidate = PendingUsername { - name: contestant.name.clone(), - decided_at: contest.end_time, - }; - pending_by_identity - .entry(contestant.id) - .and_modify(|current| { - if pending_username_priority(&candidate, current).is_lt() { - current.clone_from(&candidate); - } - }) - .or_insert(candidate); - } + /// Whether the contest's state still accepts votes. + pub fn is_votable(&self) -> bool { + self.state.state_is_votable() } - pending_by_identity -} - -fn pending_username_priority(left: &PendingUsername, right: &PendingUsername) -> Ordering { - ( - left.decided_at.is_none(), - left.decided_at.unwrap_or(u64::MAX), - &left.name, - ) - .cmp(&( - right.decided_at.is_none(), - right.decided_at.unwrap_or(u64::MAX), - &right.name, - )) } /// Return a bounded pending-name label safe to interpolate into UI text. @@ -184,19 +95,48 @@ pub fn approximate_time_until(decided_at_ms: TimestampMillis, now_ms: u64) -> Op }) } +/// How complete the node's proved current-vote state is across its contests. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub enum MasternodeVoteStateSummary { + /// Every active contest has a proved current-vote state. + #[default] + Ready, + /// At least one contest is still being proved, and none has given up. + Checking, + /// At least one contest's proved state could not be obtained. + Unavailable, +} + /// Per-node DPNS voting summary shown on the Masternodes card grid. /// /// Composed by a display-layer read of existing contest + scheduled-vote state /// (no new backend concept). Feeds the count-first status line: open contests -/// take precedence, then a pending scheduled vote, then "no open contests" -/// (requirements §10.1). +/// take precedence, then failed or pending scheduled votes, then no open +/// contests (requirements §10.1). #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct MasternodeContestSummary { - /// Number of open contests this node can still vote on. + /// Number of active contests, including contests with an existing vote. pub open_contest_count: usize, + /// Number of active contests whose proved state is `Not voted`. + pub needs_vote_count: usize, + /// Whether the node's proved current-vote state is complete, still being + /// checked, or unavailable. + pub vote_state: MasternodeVoteStateSummary, /// Whether the node has at least one pending (not-yet-executed) scheduled - /// vote, reusing the DPNS Scheduled Votes screen's existing state. + /// vote in the authoritative operation journal. pub has_scheduled_vote: bool, + /// Whether a scheduled target reached a terminal failure that needs review. + pub has_failed_scheduled_vote: bool, +} + +impl MasternodeContestSummary { + /// Represent a failed summary read without implying that no contests exist. + pub fn unavailable() -> Self { + Self { + vote_state: MasternodeVoteStateSummary::Unavailable, + ..Self::default() + } + } } #[derive(Debug, Encode, Decode, Clone)] @@ -214,7 +154,6 @@ pub struct Contestant { #[cfg(test)] mod tests { use super::*; - use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; fn contest(state: ContestState) -> ContestedName { ContestedName { @@ -230,183 +169,32 @@ mod tests { } } - fn contestant(id: [u8; 32], name: &str) -> Contestant { - Contestant { - id: Identifier::from(id), - name: name.to_string(), - info: String::new(), - votes: 0, - created_at: None, - created_at_block_height: None, - created_at_core_block_height: None, - document_id: Identifier::from([0u8; 32]), - } - } - - fn contest_with(state: ContestState, contestants: Vec) -> ContestedName { - ContestedName { - contestants: Some(contestants), - end_time: Some(9_999), - ..contest(state) - } - } - - #[test] - fn open_for_voter_when_votable_and_not_yet_voted() { - let voter = Identifier::from([7u8; 32]); - assert!(contest(ContestState::Ongoing).is_open_for_voter(&voter)); - assert!(contest(ContestState::Joinable).is_open_for_voter(&voter)); - } - #[test] - fn not_open_when_state_not_votable() { - let voter = Identifier::from([7u8; 32]); - assert!(!contest(ContestState::Locked).is_open_for_voter(&voter)); - assert!(!contest(ContestState::Unknown).is_open_for_voter(&voter)); - assert!( - !contest(ContestState::WonBy(Identifier::from([9u8; 32]))).is_open_for_voter(&voter) - ); - } - - #[test] - fn not_open_when_voter_already_voted() { - let voter = Identifier::from([7u8; 32]); - let mut c = contest(ContestState::Ongoing); - c.my_votes.insert( - (voter, PrivateKeyTarget::PrivateKeyOnVoterIdentity, 0), - ResourceVoteChoice::Abstain, - ); - assert!(!c.is_open_for_voter(&voter)); - } - - #[test] - fn open_when_a_different_voter_already_voted() { - let voter = Identifier::from([7u8; 32]); - let other = Identifier::from([8u8; 32]); - let mut c = contest(ContestState::Ongoing); - c.my_votes.insert( - (other, PrivateKeyTarget::PrivateKeyOnVoterIdentity, 0), - ResourceVoteChoice::Abstain, - ); - assert!(c.is_open_for_voter(&voter)); - } - - // ---------------------------------------------------------------- - // Pending username detection: requested-but-unawarded vs owned/none. - // ---------------------------------------------------------------- - - #[test] - fn pending_username_reported_when_contender_and_undecided() { - let me = [5u8; 32]; - for state in [ - ContestState::Ongoing, - ContestState::Joinable, - ContestState::Unknown, + fn contest_is_votable_only_in_open_states() { + for (state, expected) in [ + (ContestState::Unknown, false), + (ContestState::Joinable, true), + (ContestState::Ongoing, true), + (ContestState::WonBy(Identifier::from([9u8; 32])), false), + (ContestState::Locked, false), ] { - let c = contest_with(state.clone(), vec![contestant(me, "det1")]); - let pending = c - .pending_username_for(&Identifier::from(me)) - .expect("an undecided contender has a pending username"); - assert_eq!(pending.name, "det1"); - assert_eq!(pending.decided_at, Some(9_999)); + assert_eq!(contest(state).is_votable(), expected); } } #[test] - fn no_pending_username_when_contest_is_decided() { - let me = [5u8; 32]; - // Won by me, won by another, and locked are all "decided" — the name is - // no longer pending regardless of who ends up owning it. - for state in [ - ContestState::WonBy(Identifier::from(me)), - ContestState::WonBy(Identifier::from([9u8; 32])), - ContestState::Locked, + fn contest_is_decided_only_when_won_or_locked() { + for (state, expected) in [ + (ContestState::Unknown, false), + (ContestState::Joinable, false), + (ContestState::Ongoing, false), + (ContestState::WonBy(Identifier::from([9u8; 32])), true), + (ContestState::Locked, true), ] { - let c = contest_with(state, vec![contestant(me, "det1")]); - assert!(c.pending_username_for(&Identifier::from(me)).is_none()); + assert_eq!(state.is_decided(), expected, "{state:?}"); } } - #[test] - fn no_pending_username_when_identity_is_not_a_contender() { - let c = contest_with(ContestState::Ongoing, vec![contestant([5u8; 32], "det1")]); - assert!( - c.pending_username_for(&Identifier::from([6u8; 32])) - .is_none() - ); - } - - #[test] - fn no_pending_username_when_contest_has_no_contenders() { - let c = contest(ContestState::Ongoing); // contestants: None - assert!( - c.pending_username_for(&Identifier::from([5u8; 32])) - .is_none() - ); - } - - #[test] - fn pending_username_in_scans_multiple_contests() { - let me = Identifier::from([5u8; 32]); - let contests = vec![ - contest_with(ContestState::Locked, vec![contestant([5u8; 32], "taken")]), - contest_with(ContestState::Ongoing, vec![contestant([5u8; 32], "det1")]), - ]; - let pending = pending_username_in(&contests, &me).expect("second contest is pending"); - assert_eq!(pending.name, "det1"); - } - - #[test] - fn pending_username_in_prioritizes_earliest_known_decision_deterministically() { - let me = Identifier::from([5u8; 32]); - let mut later = contest_with(ContestState::Ongoing, vec![contestant([5u8; 32], "later")]); - later.end_time = Some(20_000); - let mut earlier = contest_with( - ContestState::Ongoing, - vec![contestant([5u8; 32], "earlier")], - ); - earlier.end_time = Some(10_000); - let mut unknown = contest_with( - ContestState::Ongoing, - vec![contestant([5u8; 32], "unknown")], - ); - unknown.end_time = None; - - for contests in [ - vec![later.clone(), unknown.clone(), earlier.clone()], - vec![unknown.clone(), earlier.clone(), later.clone()], - vec![earlier.clone(), later.clone(), unknown.clone()], - ] { - assert_eq!( - pending_username_in(&contests, &me).map(|pending| pending.name), - Some("earlier".to_string()) - ); - } - } - - #[test] - fn pending_username_in_uses_name_as_a_stable_deadline_tiebreaker() { - let me = Identifier::from([5u8; 32]); - let alpha = contest_with(ContestState::Ongoing, vec![contestant([5u8; 32], "alpha")]); - let zulu = contest_with(ContestState::Ongoing, vec![contestant([5u8; 32], "zulu")]); - - for contests in [vec![zulu.clone(), alpha.clone()], vec![alpha, zulu]] { - assert_eq!( - pending_username_in(&contests, &me).map(|pending| pending.name), - Some("alpha".to_string()) - ); - } - } - - #[test] - fn pending_username_in_returns_none_without_matches() { - let contests = vec![contest_with( - ContestState::Ongoing, - vec![contestant([1u8; 32], "other")], - )]; - assert!(pending_username_in(&contests, &Identifier::from([5u8; 32])).is_none()); - } - // ---------------------------------------------------------------- // ETA humanization. // ---------------------------------------------------------------- diff --git a/src/model/dpns.rs b/src/model/dpns.rs index 7853480ae..6bcb73a60 100644 --- a/src/model/dpns.rs +++ b/src/model/dpns.rs @@ -4,10 +4,20 @@ //! pipeline so every DPNS lookup uses the same logic, and provides shared //! extraction utilities for DPNS domain documents. +use std::collections::BTreeMap; +use std::sync::LazyLock; +use std::time::Duration; + use dash_sdk::dpp::ProtocolError; +use dash_sdk::dpp::dashcore::Network; +use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; +use dash_sdk::dpp::data_contract::document_type::ContestedIndexFieldMatch; +use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; use dash_sdk::dpp::data_contract::document_type::methods::DocumentTypeV0Methods; +use dash_sdk::dpp::data_contracts::SystemDataContract; use dash_sdk::dpp::document::DocumentV0Getters; use dash_sdk::dpp::platform_value::Value; +use dash_sdk::dpp::system_data_contracts::load_system_data_contract; use dash_sdk::dpp::util::strings::convert_to_homograph_safe_chars; use dash_sdk::dpp::version::PlatformVersion; use dash_sdk::dpp::voting::vote_polls::VotePoll; @@ -39,6 +49,119 @@ pub fn classify_dpns_registration_outcome( } } +/// How long a DPNS name contest runs and how long others may join it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ContestDurations { + /// Time from the first request until the vote ends. + pub total: Duration, + /// Time from the first request during which others may also ask for the name. + pub join: Duration, +} + +/// Contest timing on `network` at `platform_version`. +/// +/// Mainnet uses the production windows (14 days / 7 days at PV13); every other +/// network uses the testing windows (90 / 45 minutes). Values come from the +/// platform version tables, never from literals. +pub fn contest_durations(network: Network, platform_version: &PlatformVersion) -> ContestDurations { + let voting = &platform_version.dpp.voting_versions; + let joining = &platform_version.dpp.validation.voting; + let (total_ms, join_ms) = if network == Network::Mainnet { + ( + voting.default_vote_poll_time_duration_mainnet_ms, + joining.allow_other_contenders_time_mainnet_ms, + ) + } else { + ( + voting.default_vote_poll_time_duration_test_network_ms, + joining.allow_other_contenders_time_testing_ms, + ) + }; + ContestDurations { + total: Duration::from_millis(total_ms), + join: Duration::from_millis(join_ms), + } +} + +/// Mainnet urgency window before a contest ends. +const MAINNET_URGENCY_WINDOW: Duration = Duration::from_secs(24 * 60 * 60); +/// Urgency window on testing networks, scaled to their 90-minute contests. +const TESTING_URGENCY_WINDOW: Duration = Duration::from_secs(30 * 60); + +/// How close to its end a contest counts as urgent: 24 h on mainnet, 30 min elsewhere. +pub fn urgency_window(network: Network) -> Duration { + if network == Network::Mainnet { + MAINNET_URGENCY_WINDOW + } else { + TESTING_URGENCY_WINDOW + } +} + +/// Field matches of the bundled DPNS contract's contested `domain` index. +/// +/// The contested rule lives only in the contract JSON, so it is read from the +/// bundled system contract once instead of being duplicated here. +static CONTESTED_FIELD_MATCHES: LazyLock>> = + LazyLock::new(|| { + let contract = + load_system_data_contract(SystemDataContract::DPNS, PlatformVersion::latest()).ok()?; + let document_type = contract.document_type_for_name("domain").ok()?; + document_type + .find_contested_index() + .and_then(|index| index.contested_index.as_ref()) + .map(|contested| contested.field_matches.clone()) + }); + +/// Whether registering `label` opens a community vote. +/// +/// Applies the DPNS contract's contested-index rule to the homograph-normalized +/// label (letters, `0`, `1`, and `-`, shorter than 20 characters). Accepts a bare +/// label or a `.dash` name. Returns `true` if the bundled rule cannot be read, +/// so callers never under-warn about a vote. +pub fn is_contested_label(label: &str) -> bool { + let normalized = Value::Text(normalize_dpns_label(label)); + match CONTESTED_FIELD_MATCHES.as_ref() { + Some(matches) => matches + .get("normalizedLabel") + .is_some_and(|field_match| field_match.matches(&normalized)), + None => true, + } +} + +/// Suffixes tried, in order, when suggesting names that avoid a community vote. +const UNCONTESTED_SUFFIXES: [&str; 5] = ["2", "-3", "99", "7", "-2026"]; +/// Number of suggestions offered. +const SUGGESTION_COUNT: usize = 3; +/// Longest label DPNS accepts. +const MAX_LABEL_LEN: usize = 63; + +/// Up to three valid labels close to `label` that do not need a community vote. +/// +/// Each suggestion appends a short suffix from `UNCONTESTED_SUFFIXES` that +/// takes the name out of the contested rule. Returns an empty list when `label` +/// has no usable base. +pub fn suggest_uncontested(label: &str) -> Vec { + let base = strip_dash_suffix(label).to_ascii_lowercase(); + let base = base.trim_end_matches('-'); + if base.is_empty() || !base.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { + return Vec::new(); + } + UNCONTESTED_SUFFIXES + .iter() + .map(|suffix| { + let room = MAX_LABEL_LEN.saturating_sub(suffix.len()); + let trimmed = base[..base.len().min(room)].trim_end_matches('-'); + format!("{trimmed}{suffix}") + }) + .filter(|candidate| { + candidate != base + && validate_dpns_name(candidate) == DpnsNameValidationResult::Valid + && !is_contested_label(candidate) + }) + .take(SUGGESTION_COUNT) + .collect() +} + /// The `.dash` parent domain suffix (case-insensitive match target). const DASH_SUFFIX: &str = ".dash"; @@ -58,7 +181,7 @@ pub fn validate_dpns_name(name: &str) -> DpnsNameValidationResult { if name.len() < 3 { return DpnsNameValidationResult::TooShort; } - if name.len() > 63 { + if name.len() > MAX_LABEL_LEN { return DpnsNameValidationResult::TooLong; } if name.starts_with('-') { @@ -269,6 +392,75 @@ mod tests { ); } + #[test] + fn contested_rule_matches_contract() { + // USR-TC-001 + assert!(is_contested_label("alice")); + assert!(is_contested_label("al1ce")); + assert!(!is_contested_label("alice2")); + assert!(!is_contested_label(&"a".repeat(20))); + assert!(is_contested_label(&"a".repeat(19))); + assert!(is_contested_label("b0b-01")); + assert!(is_contested_label("Alice")); + assert!(is_contested_label("alice.dash")); + } + + #[test] + fn contest_durations_per_network() { + // USR-TC-003 + let pv = PlatformVersion::get(13).expect("PV13"); + let day = Duration::from_secs(24 * 60 * 60); + let minute = Duration::from_secs(60); + assert_eq!( + contest_durations(Network::Mainnet, pv), + ContestDurations { + total: 14 * day, + join: 7 * day + } + ); + for network in [Network::Testnet, Network::Devnet, Network::Regtest] { + assert_eq!( + contest_durations(network, pv), + ContestDurations { + total: 90 * minute, + join: 45 * minute + } + ); + } + } + + #[test] + fn urgency_window_per_network() { + // USR-TC-004 + assert_eq!( + urgency_window(Network::Mainnet), + Duration::from_secs(24 * 60 * 60) + ); + assert_eq!( + urgency_window(Network::Testnet), + Duration::from_secs(30 * 60) + ); + } + + #[test] + fn suggestions_avoid_the_vote() { + // USR-TC-007 + for label in ["alice", "Nova", "b0b-", &"a".repeat(63)] { + let suggestions = suggest_uncontested(label); + assert_eq!(suggestions.len(), 3, "{label}: {suggestions:?}"); + for suggestion in &suggestions { + assert_eq!( + validate_dpns_name(suggestion), + DpnsNameValidationResult::Valid, + "{suggestion}" + ); + assert!(!is_contested_label(suggestion), "{suggestion}"); + } + } + assert!(suggest_uncontested("").is_empty()); + assert!(suggest_uncontested("a_b").is_empty()); + } + #[test] fn normalize_bare_label() { assert_eq!(normalize_dpns_label("alice"), "a11ce"); diff --git a/src/model/dpns_usernames.rs b/src/model/dpns_usernames.rs new file mode 100644 index 000000000..ddff8fe45 --- /dev/null +++ b/src/model/dpns_usernames.rs @@ -0,0 +1,1420 @@ +//! An identity's own DPNS username requests: availability and request status. +//! +//! Pure decision logic over proved contest snapshots. The backend fetches the +//! snapshots; this module decides what they mean for one label or identity. + +use std::time::Duration; + +use dash_sdk::dpp::identity::TimestampMillis; +use dash_sdk::platform::Identifier; +use serde::{Deserialize, Serialize}; + +use super::dpns::{ContestDurations, is_contested_label}; +use super::qualified_identity::QualifiedIdentity; + +/// How long a finished request stays listed on the identity. +pub const OUTCOME_RETENTION: Duration = Duration::from_secs(30 * 24 * 60 * 60); + +/// Re-read request status on hub arrival only when the last read is older than this. +pub const ARRIVAL_REFRESH_AFTER: Duration = Duration::from_secs(5 * 60); +/// Periodic refresh while a request is pending on mainnet. +const MAINNET_PENDING_REFRESH: Duration = Duration::from_secs(15 * 60); +/// Periodic refresh while a request is pending on testing networks (90-minute contests). +const TESTING_PENDING_REFRESH: Duration = Duration::from_secs(2 * 60); + +/// How often to re-read status while at least one request is pending. +pub fn pending_refresh_interval(network: dash_sdk::dpp::dashcore::Network) -> Duration { + if network == dash_sdk::dpp::dashcore::Network::Mainnet { + MAINNET_PENDING_REFRESH + } else { + TESTING_PENDING_REFRESH + } +} + +/// Whether the hub should refresh username requests now. +/// +/// `arriving` is true on the first frame after the hub is shown; `last` is the +/// time of the previous refresh, if any. +pub fn username_refresh_due( + now: TimestampMillis, + last: Option, + arriving: bool, + any_pending: bool, + network: dash_sdk::dpp::dashcore::Network, +) -> bool { + let Some(last) = last else { + return true; + }; + let elapsed = now.saturating_sub(last); + (arriving && elapsed > duration_ms(ARRIVAL_REFRESH_AFTER)) + || (any_pending && elapsed >= duration_ms(pending_refresh_interval(network))) +} + +/// Failed "banner seen" writes allowed per identity and session before giving up. +pub const SEEN_MARK_MAX_FAILURES: u32 = 3; +/// Wait after each failed "banner seen" write, multiplied by the failure count. +pub const SEEN_MARK_BACKOFF: Duration = Duration::from_secs(5); +/// Frames a dispatched "banner seen" task may take to start before it is +/// treated as dropped (its action replaced by another) and sent again. +const SEEN_MARK_START_GRACE_PASSES: u64 = 2; + +/// Bounds the "banner seen" writes for one identity: one in flight at a time, +/// a backoff after each failure, and none after repeated failures. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct SeenMarkAttempts { + dispatched_pass: Option, + started: bool, + failures: u32, + last_failure: Option, +} + +impl SeenMarkAttempts { + /// Whether a new write may be dispatched in frame `pass` at `now`. + pub fn may_dispatch(&self, pass: u64, now: std::time::Instant) -> bool { + if self.started || self.failures >= SEEN_MARK_MAX_FAILURES { + return false; + } + if self + .dispatched_pass + .is_some_and(|dispatched| pass <= dispatched + SEEN_MARK_START_GRACE_PASSES) + { + return false; + } + self.last_failure.is_none_or(|failed| { + now.saturating_duration_since(failed) >= SEEN_MARK_BACKOFF * self.failures + }) + } + + /// A write was dispatched in frame `pass`. + pub fn dispatched(&mut self, pass: u64) { + self.dispatched_pass = Some(pass); + } + + /// The backend started the write. + pub fn started(&mut self) { + self.started = true; + } + + /// Test seam: pretend the backoff after the last failure has elapsed. + #[cfg(test)] + pub(crate) fn expire_backoff_for_test(&mut self) { + self.last_failure = None; + } + + /// The write finished; a failure starts the backoff. + pub fn finished(&mut self, succeeded: bool, now: std::time::Instant) { + self.started = false; + self.dispatched_pass = None; + if succeeded { + self.failures = 0; + self.last_failure = None; + } else { + self.failures += 1; + self.last_failure = Some(now); + } + } +} + +/// Whether `key` may sign documents that require `required` security: an enabled +/// authentication key at least as strong as required, and never a master key. +pub fn key_can_sign_documents( + key: &dash_sdk::platform::IdentityPublicKey, + required: dash_sdk::dpp::identity::SecurityLevel, +) -> bool { + use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; + use dash_sdk::dpp::identity::{Purpose, SecurityLevel}; + key.purpose() == Purpose::AUTHENTICATION + && !key.is_disabled() + && key.security_level() != SecurityLevel::MASTER + && key.security_level() <= required +} + +/// The weakest key security level that may sign both DPNS documents a registration +/// creates (preorder and domain); falls back to `HIGH` if the contract lacks them. +pub fn dpns_signing_requirement( + contract: &dash_sdk::platform::DataContract, +) -> dash_sdk::dpp::identity::SecurityLevel { + use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; + use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; + ["preorder", "domain"] + .into_iter() + .filter_map(|name| contract.document_type_for_name(name).ok()) + .map(|document_type| document_type.security_level_requirement()) + .min() + .unwrap_or(dash_sdk::dpp::identity::SecurityLevel::HIGH) +} + +/// Whether this device holds a private key that can sign username registrations +/// (documents requiring `required` security) for `identity`. +pub fn can_register_usernames( + identity: &QualifiedIdentity, + required: dash_sdk::dpp::identity::SecurityLevel, +) -> bool { + identity + .private_keys + .identity_public_keys() + .iter() + .any(|(_, key)| key_can_sign_documents(&key.identity_public_key, required)) +} + +/// Whether a username can be requested right now, and on what terms. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UsernameAvailability { + /// No one owns or asked for it, and it needs no community vote. + Available, + /// No one owns or asked for it, but registering it opens a community vote. + NeedsVote, + /// Others already asked for it and new requests may still join the vote. + Joinable { + /// Number of requests already in the vote. + contenders: u32, + /// When new requests stop being accepted. + join_end: TimestampMillis, + }, + /// A vote is running and no longer accepts new requests. + JoinClosed, + /// Someone already owns the name. + Taken, + /// A community vote locked the name; no one can register it. + Locked, + /// This identity already asked for the name; the request is in the vote. + AlreadyRequested, +} + +impl UsernameAvailability { + /// Whether registration may proceed with this result. + pub fn allows_registration(self) -> bool { + matches!( + self, + Self::Available | Self::NeedsVote | Self::Joinable { .. } + ) + } + + /// Whether registration opens or joins a community vote. + pub fn needs_vote(self) -> bool { + matches!(self, Self::NeedsVote | Self::Joinable { .. }) + } + + /// When a running vote stops accepting new requests, if registering joins one. + pub fn join_deadline(self) -> Option { + match self { + Self::Joinable { join_end, .. } => Some(join_end), + _ => None, + } + } +} + +/// Whether a saved win still needs to be reflected in the identity's owned names. +/// +/// A win that was reflected once is never missing again: if the name is gone +/// afterwards, it left the identity. +pub fn won_username_is_missing( + request: &UsernameRequest, + names: &[super::qualified_identity::DPNSNameInfo], +) -> bool { + request.phase == RequestPhase::Won + && !request.reflected_in_owned_names + && !owned_names_include(request, names) +} + +fn owned_names_include( + request: &UsernameRequest, + names: &[super::qualified_identity::DPNSNameInfo], +) -> bool { + names + .iter() + .any(|name| super::dpns::normalize_dpns_label(&name.name) == request.normalized_label) +} + +/// Record, on every saved win that `names` lists, that the owned names reflected it. +pub fn mark_wins_reflected( + requests: &mut [UsernameRequest], + names: &[super::qualified_identity::DPNSNameInfo], +) { + for request in requests.iter_mut() { + if request.phase == RequestPhase::Won && owned_names_include(request, names) { + request.reflected_in_owned_names = true; + } + } +} + +/// How a finished contest ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ContestWinner { + /// The name went to this identity. + Identity(Identifier), + /// More votes went to locking the name. + Locked, + /// The contest ended without a winner. + NoWinner, +} + +/// One request in a contest, with its weighted vote count. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ContenderTally { + /// The requesting identity. + pub identity_id: Identifier, + /// The label as the requester typed it, when the document is available. + pub label: Option, + /// Weighted votes for this request. + pub votes: u32, + /// When the request was made. + pub created_at: Option, +} + +/// The proved state of one name contest. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ContestSnapshot { + /// The result, once the contest has ended. + pub winner: Option, + /// When the result was decided. + pub decided_at: Option, + /// Current requests and their votes. + pub contenders: Vec, + /// Weighted votes to lock the name. + pub lock_votes: u32, + /// Weighted abstain votes. + pub abstain_votes: u32, +} + +impl ContestSnapshot { + /// When the contest started: the earliest request. + pub fn started_at(&self) -> Option { + self.contenders.iter().filter_map(|c| c.created_at).min() + } +} + +/// Decide whether `requester` can ask for `label`. +/// +/// `awarded` says whether a registered name already exists; `contest` is the +/// proved contest for the label, if one was fetched. A contested label with no +/// contest is never reported as `Available`, and a contest the requester is +/// already in is `AlreadyRequested` (Platform rejects a second request). +pub fn classify_availability( + requester: Identifier, + label: &str, + awarded: bool, + contest: Option<&ContestSnapshot>, + now: TimestampMillis, + durations: ContestDurations, +) -> UsernameAvailability { + if awarded { + return UsernameAvailability::Taken; + } + if let Some(contest) = contest { + if contest.winner.is_none() + && contest + .contenders + .iter() + .any(|c| c.identity_id == requester) + { + return UsernameAvailability::AlreadyRequested; + } + match contest.winner { + Some(ContestWinner::Locked) => return UsernameAvailability::Locked, + Some(ContestWinner::Identity(_)) => return UsernameAvailability::Taken, + Some(ContestWinner::NoWinner) => {} + None if !contest.contenders.is_empty() => { + return match contest.started_at() { + Some(start) => { + let join_end = start.saturating_add(duration_ms(durations.join)); + if now < join_end { + UsernameAvailability::Joinable { + contenders: u32::try_from(contest.contenders.len()) + .unwrap_or(u32::MAX), + join_end, + } + } else { + UsernameAvailability::JoinClosed + } + } + // Without a start time the join window can't be proven open. + None => UsernameAvailability::JoinClosed, + }; + } + None => {} + } + } + if is_contested_label(label) { + UsernameAvailability::NeedsVote + } else { + UsernameAvailability::Available + } +} + +/// Where an identity's username request stands. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum RequestPhase { + /// Others may still ask for the same name. + Joinable, + /// Only masternode votes decide now. + Voting, + /// The name went to this identity. + Won, + /// The name went to someone else. + Lost, + /// The vote locked the name for everyone. + Locked, + /// The vote ended and no one got the name. + NoWinner, + /// The estimated voting period elapsed; the network outcome is not known yet. + AwaitingOutcome, +} + +impl RequestPhase { + /// Whether the request still needs a confirmed network outcome. + pub fn is_pending(self) -> bool { + matches!(self, Self::Joinable | Self::Voting | Self::AwaitingOutcome) + } +} + +/// Weighted votes in a request's contest, seen from the requester. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct RequestTally { + /// Votes for this identity's request. + pub you: u32, + /// Votes for each other request. + pub others: Vec<(Identifier, u32)>, + /// Votes to lock the name. + pub lock: u32, + /// Abstain votes. + pub abstain: u32, +} + +/// What would happen to the requester if the vote ended now (PF §3). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TallyStanding { + /// The requester would get the name: more votes than every other request, + /// or no other request at all, and lock is not ahead. + Leading, + /// Level with the strongest other request; ties go to the most recent request. + Tied, + /// Another request has more votes. + Trailing, + /// More votes to lock than to any request: no one would get the name. + LockAhead, +} + +impl RequestTally { + /// The requester's standing under Platform's resolution rules. + pub fn standing(&self) -> TallyStanding { + let best_other = self.others.iter().map(|(_, votes)| *votes).max(); + let top_request = best_other.map_or(self.you, |other| other.max(self.you)); + if self.lock > top_request { + return TallyStanding::LockAhead; + } + match best_other { + None => TallyStanding::Leading, + Some(other) => match self.you.cmp(&other) { + std::cmp::Ordering::Greater => TallyStanding::Leading, + std::cmp::Ordering::Equal => TallyStanding::Tied, + std::cmp::Ordering::Less => TallyStanding::Trailing, + }, + } + } +} + +/// An identity's request for a username that needs a community vote. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(from = "StoredUsernameRequest", into = "StoredUsernameRequest")] +pub struct UsernameRequest { + /// The label as requested. + pub label: String, + /// The homograph-normalized label that identifies the contest. + pub normalized_label: String, + /// Where the request stands. + pub phase: RequestPhase, + /// When the request was made. + pub requested_at: Option, + /// When others stop being able to join. + pub join_end: Option, + /// When the vote ends. + pub end: Option, + /// When the result was decided, for finished requests. + pub decided_at: Option, + /// Current weighted votes. + pub tally: RequestTally, + /// When this status was last read from the network. + pub last_updated: TimestampMillis, + /// Whether the identity's owned names listed this won name at least once. + /// + /// Tells a win that has not been read back yet from one whose name has + /// since left the identity. Only meaningful for [`RequestPhase::Won`]. + pub reflected_in_owned_names: bool, +} + +/// Stored form of [`UsernameRequest`]. +/// +/// The store is positional, so the field order here and the variant order of +/// [`StoredRequestPhase`] are the on-disk layout: fields cannot be added, and +/// variants may only be appended. +#[derive(Serialize, Deserialize)] +struct StoredUsernameRequest { + label: String, + normalized_label: String, + phase: StoredRequestPhase, + requested_at: Option, + join_end: Option, + end: Option, + decided_at: Option, + tally: RequestTally, + last_updated: TimestampMillis, +} + +/// Stored form of [`RequestPhase`], in the same variant order. +#[derive(Serialize, Deserialize)] +enum StoredRequestPhase { + Joinable, + Voting, + Won, + Lost, + Locked, + NoWinner, + AwaitingOutcome, + /// A win with [`UsernameRequest::reflected_in_owned_names`] set. Appended + /// so requests stored before the flag existed still load, as not reflected. + WonReflected, +} + +impl From for StoredUsernameRequest { + fn from(request: UsernameRequest) -> Self { + let phase = match request.phase { + RequestPhase::Joinable => StoredRequestPhase::Joinable, + RequestPhase::Voting => StoredRequestPhase::Voting, + RequestPhase::Won if request.reflected_in_owned_names => { + StoredRequestPhase::WonReflected + } + RequestPhase::Won => StoredRequestPhase::Won, + RequestPhase::Lost => StoredRequestPhase::Lost, + RequestPhase::Locked => StoredRequestPhase::Locked, + RequestPhase::NoWinner => StoredRequestPhase::NoWinner, + RequestPhase::AwaitingOutcome => StoredRequestPhase::AwaitingOutcome, + }; + Self { + label: request.label, + normalized_label: request.normalized_label, + phase, + requested_at: request.requested_at, + join_end: request.join_end, + end: request.end, + decided_at: request.decided_at, + tally: request.tally, + last_updated: request.last_updated, + } + } +} + +impl From for UsernameRequest { + fn from(stored: StoredUsernameRequest) -> Self { + let (phase, reflected_in_owned_names) = match stored.phase { + StoredRequestPhase::Joinable => (RequestPhase::Joinable, false), + StoredRequestPhase::Voting => (RequestPhase::Voting, false), + StoredRequestPhase::Won => (RequestPhase::Won, false), + StoredRequestPhase::Lost => (RequestPhase::Lost, false), + StoredRequestPhase::Locked => (RequestPhase::Locked, false), + StoredRequestPhase::NoWinner => (RequestPhase::NoWinner, false), + StoredRequestPhase::AwaitingOutcome => (RequestPhase::AwaitingOutcome, false), + StoredRequestPhase::WonReflected => (RequestPhase::Won, true), + }; + Self { + label: stored.label, + normalized_label: stored.normalized_label, + phase, + requested_at: stored.requested_at, + join_end: stored.join_end, + end: stored.end, + decided_at: stored.decided_at, + tally: stored.tally, + last_updated: stored.last_updated, + reflected_in_owned_names, + } + } +} + +impl UsernameRequest { + /// Advance cached timing without inferring an outcome from the local clock. + pub fn phase_at(&self, now: TimestampMillis) -> RequestPhase { + if !self.phase.is_pending() { + return self.phase; + } + if self.end.is_some_and(|end| now >= end) { + return RequestPhase::AwaitingOutcome; + } + if self.phase == RequestPhase::Joinable && self.join_end.is_some_and(|end| now >= end) { + return RequestPhase::Voting; + } + self.phase + } + + /// A request just submitted at `now`, before the network reports its contest. + /// + /// `joined_until` is the join deadline of an existing contest the request + /// joined; the contest's dates are derived from it instead of from `now`. + pub fn submitted( + label: &str, + now: TimestampMillis, + durations: ContestDurations, + joined_until: Option, + ) -> Self { + let start = joined_until.map_or(now, |join_end| { + join_end.saturating_sub(duration_ms(durations.join)) + }); + Self { + label: label.to_owned(), + normalized_label: super::dpns::normalize_dpns_label(label), + phase: RequestPhase::Joinable, + requested_at: Some(now), + join_end: Some(start.saturating_add(duration_ms(durations.join))), + end: Some(start.saturating_add(duration_ms(durations.total))), + decided_at: None, + tally: RequestTally::default(), + last_updated: now, + reflected_in_owned_names: false, + } + } +} + +/// Build `identity_id`'s request from a contest snapshot. +/// +/// Returns `None` when a running contest does not include the identity. +/// `end_time` is the network-reported end, used in preference to the +/// computed one. `normalized_label` stands in for the label when no contender +/// document carries it. +pub fn username_request_from_contest( + identity_id: Identifier, + normalized_label: &str, + contest: &ContestSnapshot, + end_time: Option, + now: TimestampMillis, + durations: ContestDurations, +) -> Option { + let mine = contest + .contenders + .iter() + .find(|c| c.identity_id == identity_id); + let start = contest.started_at(); + let join_end = start.map(|s| s.saturating_add(duration_ms(durations.join))); + let phase = match contest.winner { + Some(ContestWinner::Identity(winner)) if winner == identity_id => RequestPhase::Won, + Some(ContestWinner::Locked) => RequestPhase::Locked, + Some(ContestWinner::NoWinner) => RequestPhase::NoWinner, + Some(ContestWinner::Identity(_)) => RequestPhase::Lost, + None => { + mine?; + if join_end.is_some_and(|end| now < end) { + RequestPhase::Joinable + } else { + RequestPhase::Voting + } + } + }; + let tally = RequestTally { + you: mine.map_or(0, |c| c.votes), + others: contest + .contenders + .iter() + .filter(|c| c.identity_id != identity_id) + .map(|c| (c.identity_id, c.votes)) + .collect(), + lock: contest.lock_votes, + abstain: contest.abstain_votes, + }; + Some(UsernameRequest { + label: mine + .and_then(|c| c.label.clone()) + .unwrap_or_else(|| normalized_label.to_owned()), + normalized_label: normalized_label.to_owned(), + phase, + requested_at: mine.and_then(|c| c.created_at), + join_end, + end: end_time.or_else(|| start.map(|s| s.saturating_add(duration_ms(durations.total)))), + decided_at: contest.decided_at, + tally, + last_updated: now, + reflected_in_owned_names: false, + }) +} + +/// Merge observations without regressing a newer or finished request. +/// +/// Finished outcomes keep the dates and tally they were last seen with when the +/// fresh snapshot no longer carries them, and drop out after +/// [`OUTCOME_RETENTION`]. Pending requests not in `fresh` stay as stored until +/// their result can be read. Wins stay until they are reflected in `owned_names`, +/// which is recorded on the request: a name that later leaves the identity is +/// then not mistaken for a win still waiting to be read back. `None` keeps +/// unreflected wins when the caller has no current owned-name snapshot. +pub fn merge_requests( + previous: &[UsernameRequest], + fresh: Vec, + now: TimestampMillis, + owned_names: Option<&[super::qualified_identity::DPNSNameInfo]>, +) -> Vec { + let mut merged: Vec = fresh + .into_iter() + .map(|mut request| { + if let Some(old) = previous + .iter() + .find(|old| old.normalized_label == request.normalized_label) + { + if request.last_updated < old.last_updated + || (!old.phase.is_pending() && request.phase.is_pending()) + { + return old.clone(); + } + if !request.phase.is_pending() { + if request.tally == RequestTally::default() { + request.tally = old.tally.clone(); + } + request.requested_at = request.requested_at.or(old.requested_at); + request.join_end = request.join_end.or(old.join_end); + request.end = request.end.or(old.end); + request.decided_at = request.decided_at.or(old.end).or(Some(now)); + request.reflected_in_owned_names |= old.reflected_in_owned_names; + } + if request.label == request.normalized_label && old.label != old.normalized_label { + request.label = old.label.clone(); + } + } else if !request.phase.is_pending() && request.decided_at.is_none() { + request.decided_at = Some(now); + } + request + }) + .collect(); + for old in previous { + if !merged + .iter() + .any(|r| r.normalized_label == old.normalized_label) + { + merged.push(old.clone()); + } + } + if let Some(names) = owned_names { + mark_wins_reflected(&mut merged, names); + } + let retention = duration_ms(OUTCOME_RETENTION); + merged.retain(|r| { + r.phase.is_pending() + || (r.phase == RequestPhase::Won && !r.reflected_in_owned_names) + || r.decided_at + .is_none_or(|decided| now.saturating_sub(decided) < retention) + }); + merged.sort_by(|a, b| { + (!a.phase.is_pending(), a.end, &a.normalized_label).cmp(&( + !b.phase.is_pending(), + b.end, + &b.normalized_label, + )) + }); + merged +} + +fn duration_ms(duration: Duration) -> TimestampMillis { + u64::try_from(duration.as_millis()).unwrap_or(u64::MAX) +} + +#[cfg(test)] +mod tests { + use super::*; + + const MINUTE: u64 = 60_000; + + fn durations() -> ContestDurations { + ContestDurations { + total: Duration::from_secs(90 * 60), + join: Duration::from_secs(45 * 60), + } + } + + fn id(byte: u8) -> Identifier { + Identifier::from([byte; 32]) + } + + fn contender(byte: u8, votes: u32, created_at: u64) -> ContenderTally { + ContenderTally { + identity_id: id(byte), + label: Some(format!("Name{byte}")), + votes, + created_at: Some(created_at), + } + } + + fn running(contenders: Vec) -> ContestSnapshot { + ContestSnapshot { + contenders, + ..Default::default() + } + } + + #[test] + fn cached_request_phase_advances_at_deadlines_without_inventing_outcome() { + let mut request = UsernameRequest::submitted( + "d1ssh", + 1_000, + ContestDurations { + total: Duration::from_secs(10), + join: Duration::from_secs(5), + }, + None, + ); + assert_eq!(request.phase_at(5_999), RequestPhase::Joinable); + assert_eq!(request.phase_at(6_000), RequestPhase::Voting); + assert_eq!(request.phase_at(10_999), RequestPhase::Voting); + assert_eq!(request.phase_at(11_000), RequestPhase::AwaitingOutcome); + assert!(request.phase_at(11_000).is_pending()); + for phase in [ + RequestPhase::Won, + RequestPhase::Lost, + RequestPhase::Locked, + RequestPhase::NoWinner, + ] { + request.phase = phase; + assert_eq!(request.phase_at(11_000), phase); + } + request.phase = RequestPhase::Voting; + request.end = None; + assert_eq!(request.phase_at(u64::MAX), RequestPhase::Voting); + } + + #[test] + fn refresh_cadence_follows_arrival_and_pending_rules() { + // USR-TC-028 + use dash_sdk::dpp::dashcore::Network; + let min = |m: u64| m * MINUTE; + assert!(username_refresh_due( + min(1), + None, + true, + false, + Network::Mainnet + )); + assert!(!username_refresh_due( + min(2), + Some(0), + true, + false, + Network::Mainnet + )); + assert!(username_refresh_due( + min(6), + Some(0), + true, + false, + Network::Mainnet + )); + assert!(!username_refresh_due( + min(14), + Some(0), + false, + true, + Network::Mainnet + )); + assert!(username_refresh_due( + min(15), + Some(0), + false, + true, + Network::Mainnet + )); + assert!(username_refresh_due( + min(2), + Some(0), + false, + true, + Network::Testnet + )); + assert!(!username_refresh_due( + min(60), + Some(0), + false, + false, + Network::Testnet + )); + } + + #[test] + fn available_when_nothing_exists_and_label_is_uncontested() { + // USR-TC-010 + assert_eq!( + classify_availability(id(9), "alice2", false, None, 0, durations()), + UsernameAvailability::Available + ); + } + + #[test] + fn contested_label_without_contest_needs_vote() { + // USR-TC-011 + assert_eq!( + classify_availability(id(9), "alice", false, None, 0, durations()), + UsernameAvailability::NeedsVote + ); + assert_eq!( + classify_availability( + id(9), + "alice", + false, + Some(&ContestSnapshot::default()), + 0, + durations() + ), + UsernameAvailability::NeedsVote + ); + } + + #[test] + fn running_contest_inside_join_window_is_joinable() { + // USR-TC-012 + let contest = running(vec![contender(1, 0, 1_000), contender(2, 0, 5_000)]); + assert_eq!( + classify_availability( + id(9), + "alice", + false, + Some(&contest), + 1_000 + 10 * MINUTE, + durations() + ), + UsernameAvailability::Joinable { + contenders: 2, + join_end: 1_000 + 45 * MINUTE + } + ); + } + + #[test] + fn running_contest_after_join_window_is_closed() { + // USR-TC-013 + let contest = running(vec![contender(1, 0, 1_000)]); + assert_eq!( + classify_availability( + id(9), + "alice", + false, + Some(&contest), + 1_000 + 45 * MINUTE, + durations() + ), + UsernameAvailability::JoinClosed + ); + } + + #[test] + fn awarded_name_is_taken() { + // USR-TC-014 + assert_eq!( + classify_availability(id(9), "alice", true, None, 0, durations()), + UsernameAvailability::Taken + ); + assert_eq!( + classify_availability(id(9), "alice2", true, None, 0, durations()), + UsernameAvailability::Taken + ); + } + + #[test] + fn own_running_request_is_already_requested() { + // QA regression: the requester must not be told to join its own contest, + // because Platform rejects a second request after the preorder is paid. + let contest = running(vec![contender(9, 0, 1_000)]); + let availability = + classify_availability(id(9), "alice", false, Some(&contest), 1_000, durations()); + assert_eq!(availability, UsernameAvailability::AlreadyRequested); + assert!(!availability.allows_registration()); + assert_eq!( + classify_availability(id(8), "alice", false, Some(&contest), 1_000, durations()), + UsernameAvailability::Joinable { + contenders: 1, + join_end: 1_000 + 45 * MINUTE + } + ); + } + + #[test] + fn one_identity_gets_a_request_per_contest_it_is_in() { + // USR-TC-016: contender in two of three running contests → two requests. + let snapshots = [ + ( + "b", + running(vec![contender(9, 0, 1_000), contender(8, 0, 1_100)]), + ), + ("c", running(vec![contender(9, 4, 2_000)])), + ("d", running(vec![contender(7, 1, 3_000)])), + ]; + let requests: Vec<_> = snapshots + .iter() + .filter_map(|(name, snapshot)| { + username_request_from_contest( + id(9), + name, + snapshot, + Some(9_000), + 5_000, + durations(), + ) + }) + .collect(); + assert_eq!( + requests + .iter() + .map(|r| r.normalized_label.as_str()) + .collect::>(), + ["b", "c"] + ); + assert_eq!(requests[1].tally.you, 4); + } + + #[test] + fn joined_request_uses_the_contest_dates() { + // QA regression: joining a running contest must not push its deadlines out. + let join_end = 1_000 + 45 * MINUTE; + let request = UsernameRequest::submitted("alice", 30 * MINUTE, durations(), Some(join_end)); + assert_eq!(request.join_end, Some(join_end)); + assert_eq!(request.end, Some(1_000 + 90 * MINUTE)); + let opened = UsernameRequest::submitted("alice", 5_000, durations(), None); + assert_eq!(opened.join_end, Some(5_000 + 45 * MINUTE)); + } + + #[test] + fn seen_mark_attempts_are_bounded() { + let t0 = std::time::Instant::now(); + let mut attempts = SeenMarkAttempts::default(); + assert!(attempts.may_dispatch(1, t0)); + attempts.dispatched(1); + // One in flight: no new dispatch while it may still start. + assert!(!attempts.may_dispatch(2, t0)); + assert!(!attempts.may_dispatch(3, t0)); + // Never started (its action was replaced): sent again. + assert!(attempts.may_dispatch(4, t0)); + attempts.dispatched(4); + attempts.started(); + assert!(!attempts.may_dispatch(100, t0)); + // Each failure backs off longer; three failures stop it for the session. + for failure in 1..=SEEN_MARK_MAX_FAILURES { + attempts.finished(false, t0); + let wait = SEEN_MARK_BACKOFF * failure; + assert!(!attempts.may_dispatch(200, t0 + wait - Duration::from_millis(1))); + let ready = attempts.may_dispatch(200, t0 + wait); + assert_eq!(ready, failure < SEEN_MARK_MAX_FAILURES); + attempts.started(); + } + assert!(!attempts.may_dispatch(1_000, t0 + Duration::from_secs(3_600))); + } + + #[test] + fn legacy_automatic_alias_never_labels_the_identity() { + // QA regression: earlier versions wrote `{name}.dash` at registration, + // also for requests later lost; such an alias must not hide the main name. + use crate::model::qualified_identity::encrypted_key_storage::KeyStorage; + use crate::model::qualified_identity::{ + DPNSNameInfo, IdentityStatus, IdentityType, QualifiedIdentity, + }; + let mut identity = QualifiedIdentity { + identity: dash_sdk::dpp::identity::Identity::create_basic_identity( + id(1), + dash_sdk::dpp::version::PlatformVersion::latest(), + ) + .expect("identity"), + associated_voter_identity: None, + associated_operator_identity: None, + associated_owner_key_id: None, + identity_type: IdentityType::User, + alias: Some("alice.dash".to_owned()), + private_keys: KeyStorage::default(), + dpns_names: vec![DPNSNameInfo { + name: "bob".to_owned(), + acquired_at: 0, + }], + associated_wallets: Default::default(), + secret_access: None, + wallet_index: None, + top_ups: Default::default(), + status: IdentityStatus::Active, + network: dash_sdk::dpp::dashcore::Network::Testnet, + }; + assert_eq!(identity.to_string(), "bob"); + // A User identity's device-only name never replaces its username. + identity.alias = Some("Alice Novak".to_owned()); + assert_eq!(identity.to_string(), "bob"); + identity.alias = Some(" ".to_owned()); + assert_eq!(identity.to_string(), "bob"); + } + + #[test] + fn signing_gate_matches_platform_key_rules() { + use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; + use dash_sdk::dpp::identity::{Purpose, SecurityLevel}; + let key = |purpose, level| { + let mut key = dash_sdk::platform::IdentityPublicKey::random_key( + 1, + Some(1), + dash_sdk::dpp::version::PlatformVersion::latest(), + ); + key.set_purpose(purpose); + key.set_security_level(level); + key + }; + let high = SecurityLevel::HIGH; + assert!(key_can_sign_documents( + &key(Purpose::AUTHENTICATION, SecurityLevel::CRITICAL), + high + )); + assert!(key_can_sign_documents( + &key(Purpose::AUTHENTICATION, high), + high + )); + assert!(!key_can_sign_documents( + &key(Purpose::AUTHENTICATION, SecurityLevel::MEDIUM), + high + )); + assert!(!key_can_sign_documents( + &key(Purpose::AUTHENTICATION, SecurityLevel::MASTER), + high + )); + assert!(!key_can_sign_documents( + &key(Purpose::TRANSFER, SecurityLevel::CRITICAL), + high + )); + } + + #[test] + fn locked_contest_is_locked_even_without_awarded_domain() { + // USR-TC-015: the SDK availability helper would report this name as free. + let contest = ContestSnapshot { + winner: Some(ContestWinner::Locked), + ..Default::default() + }; + assert_eq!( + classify_availability(id(9), "alice", false, Some(&contest), 0, durations()), + UsernameAvailability::Locked + ); + } + + #[test] + fn only_a_joinable_vote_carries_a_join_deadline() { + assert_eq!( + UsernameAvailability::Joinable { + contenders: 2, + join_end: 42, + } + .join_deadline(), + Some(42) + ); + for availability in [ + UsernameAvailability::Available, + UsernameAvailability::NeedsVote, + UsernameAvailability::JoinClosed, + UsernameAvailability::Taken, + UsernameAvailability::Locked, + UsernameAvailability::AlreadyRequested, + ] { + assert_eq!(availability.join_deadline(), None, "{availability:?}"); + } + } + + #[test] + fn only_available_needs_vote_and_joinable_allow_registration() { + assert!(UsernameAvailability::Available.allows_registration()); + assert!(UsernameAvailability::NeedsVote.allows_registration()); + assert!( + UsernameAvailability::Joinable { + contenders: 1, + join_end: 0 + } + .allows_registration() + ); + for blocked in [ + UsernameAvailability::JoinClosed, + UsernameAvailability::Taken, + UsernameAvailability::Locked, + UsernameAvailability::AlreadyRequested, + ] { + assert!(!blocked.allows_registration(), "{blocked:?}"); + } + } + + #[test] + fn request_tracks_phase_dates_and_tally() { + // USR-TC-016 + let contest = ContestSnapshot { + contenders: vec![contender(1, 31, 1_000), contender(2, 18, 2_000)], + lock_votes: 8, + abstain_votes: 3, + ..Default::default() + }; + let request = username_request_from_contest( + id(1), + "a11ce", + &contest, + Some(1_000 + 90 * MINUTE), + 1_000 + 50 * MINUTE, + durations(), + ) + .expect("identity is a contender"); + assert_eq!(request.label, "Name1"); + assert_eq!(request.phase, RequestPhase::Voting); + assert_eq!(request.requested_at, Some(1_000)); + assert_eq!(request.join_end, Some(1_000 + 45 * MINUTE)); + assert_eq!(request.end, Some(1_000 + 90 * MINUTE)); + assert_eq!( + request.tally, + RequestTally { + you: 31, + others: vec![(id(2), 18)], + lock: 8, + abstain: 3 + } + ); + assert_eq!(request.tally.standing(), TallyStanding::Leading); + assert!( + username_request_from_contest(id(9), "a11ce", &contest, None, 0, durations()).is_none() + ); + } + + #[test] + fn finished_contests_yield_outcomes() { + // USR-TC-017 + let finished = |winner| ContestSnapshot { + winner: Some(winner), + decided_at: Some(7_000), + ..Default::default() + }; + let phase = |winner| { + username_request_from_contest(id(1), "x", &finished(winner), None, 9_000, durations()) + .map(|r| (r.phase, r.decided_at)) + }; + assert_eq!( + phase(ContestWinner::Identity(id(1))), + Some((RequestPhase::Won, Some(7_000))) + ); + assert_eq!( + phase(ContestWinner::Identity(id(2))), + Some((RequestPhase::Lost, Some(7_000))) + ); + assert_eq!( + phase(ContestWinner::Locked), + Some((RequestPhase::Locked, Some(7_000))) + ); + assert_eq!( + phase(ContestWinner::NoWinner), + Some((RequestPhase::NoWinner, Some(7_000))) + ); + } + + #[test] + fn standing_reports_ties_and_lock() { + let tally = |you, others: Vec, lock| RequestTally { + you, + others: others.into_iter().map(|v| (id(2), v)).collect(), + lock, + abstain: 0, + }; + // A lone request wins at the end even with no votes. + let lone = RequestTally::default(); + assert_eq!(lone.standing(), TallyStanding::Leading); + assert_eq!(tally(5, vec![5], 0).standing(), TallyStanding::Tied); + assert_eq!(tally(5, vec![9], 0).standing(), TallyStanding::Trailing); + // Lock ahead of every request means no one gets the name; a lock tie does not. + assert_eq!(tally(5, vec![1], 6).standing(), TallyStanding::LockAhead); + assert_eq!( + RequestTally { + you: 0, + lock: 3, + ..Default::default() + } + .standing(), + TallyStanding::LockAhead + ); + assert_eq!(tally(6, vec![1], 6).standing(), TallyStanding::Leading); + } + + fn stored(label: &str, phase: RequestPhase, decided_at: Option) -> UsernameRequest { + UsernameRequest { + label: label.to_owned(), + normalized_label: label.to_owned(), + phase, + requested_at: Some(1), + join_end: Some(2), + end: Some(3), + decided_at, + tally: RequestTally { + you: 4, + ..Default::default() + }, + last_updated: 0, + reflected_in_owned_names: false, + } + } + + #[test] + fn merge_keeps_unseen_pending_and_prunes_old_outcomes() { + let now = duration_ms(OUTCOME_RETENTION) + 10; + let previous = vec![ + stored("b", RequestPhase::Voting, None), + stored("old", RequestPhase::Lost, Some(5)), + stored("recent", RequestPhase::Locked, Some(now - 1)), + ]; + let fresh = vec![stored("c", RequestPhase::Joinable, None)]; + let labels: Vec<_> = merge_requests(&previous, fresh, now, None) + .into_iter() + .map(|r| r.normalized_label) + .collect(); + assert_eq!(labels, ["b", "c", "recent"]); + } + + #[test] + fn merge_keeps_old_win_until_owned_names_are_saved() { + let now = duration_ms(OUTCOME_RETENTION) + 10; + let previous = vec![stored( + &super::super::dpns::normalize_dpns_label("alice"), + RequestPhase::Won, + Some(1), + )]; + assert_eq!(merge_requests(&previous, vec![], now, None).len(), 1); + assert_eq!(merge_requests(&previous, vec![], now, Some(&[])).len(), 1); + let names = [super::super::qualified_identity::DPNSNameInfo { + name: "alice".into(), + acquired_at: 1, + }]; + assert!(merge_requests(&previous, vec![], now, Some(&names)).is_empty()); + } + + fn owned(name: &str) -> super::super::qualified_identity::DPNSNameInfo { + super::super::qualified_identity::DPNSNameInfo { + name: name.into(), + acquired_at: 1, + } + } + + /// Once the owned names listed a won name, its later absence means the name + /// left the identity: the win stops waiting to be read back and ages out. + #[test] + fn win_reflected_once_is_not_missing_after_the_name_leaves() { + let label = super::super::dpns::normalize_dpns_label("alice"); + let decided = 1_000; + let previous = vec![stored(&label, RequestPhase::Won, Some(decided))]; + + let hydrated = merge_requests(&previous, vec![], decided + 1, Some(&[owned("alice")])); + assert_eq!(hydrated.len(), 1); + assert!(hydrated[0].reflected_in_owned_names); + + // Within the retention window the win is kept, but no longer as missing. + let gone = merge_requests(&hydrated, vec![], decided + 2, Some(&[])); + assert_eq!(gone.len(), 1); + assert!(!won_username_is_missing(&gone[0], &[])); + + let later = decided + duration_ms(OUTCOME_RETENTION) + 1; + assert!(merge_requests(&hydrated, vec![], later, Some(&[])).is_empty()); + assert!(merge_requests(&hydrated, vec![], later, None).is_empty()); + } + + /// A fresh observation of the same win must not forget that it was reflected. + #[test] + fn fresh_win_observation_keeps_the_reflected_mark() { + let mut saved = stored("b", RequestPhase::Won, Some(5)); + saved.reflected_in_owned_names = true; + let mut fresh = stored("b", RequestPhase::Won, Some(5)); + fresh.last_updated = 10; + + let merged = merge_requests(&[saved], vec![fresh], 20, None); + + assert!(merged[0].reflected_in_owned_names); + } + + /// Requests stored before the reflected mark existed must still load, and + /// an unmarked request must keep its stored bytes. + #[test] + fn stored_requests_from_before_the_reflected_mark_still_load() { + #[derive(Serialize)] + struct BeforeTheMark { + label: String, + normalized_label: String, + phase: RequestPhase, + requested_at: Option, + join_end: Option, + end: Option, + decided_at: Option, + tally: RequestTally, + last_updated: TimestampMillis, + } + let config = bincode::config::standard(); + + for phase in [ + RequestPhase::Joinable, + RequestPhase::Voting, + RequestPhase::Won, + RequestPhase::Lost, + RequestPhase::Locked, + RequestPhase::NoWinner, + RequestPhase::AwaitingOutcome, + ] { + let current = stored("alice", phase, Some(7)); + let old_bytes = bincode::serde::encode_to_vec( + vec![BeforeTheMark { + label: current.label.clone(), + normalized_label: current.normalized_label.clone(), + phase, + requested_at: current.requested_at, + join_end: current.join_end, + end: current.end, + decided_at: current.decided_at, + tally: current.tally.clone(), + last_updated: current.last_updated, + }], + config, + ) + .expect("encode the earlier layout"); + + let (loaded, _): (Vec, _) = + bincode::serde::decode_from_slice(&old_bytes, config).expect("load"); + assert_eq!(loaded, vec![current.clone()], "{phase:?}"); + assert_eq!( + bincode::serde::encode_to_vec(vec![current], config).expect("encode"), + old_bytes, + "{phase:?}" + ); + } + + let mut reflected = stored("alice", RequestPhase::Won, Some(7)); + reflected.reflected_in_owned_names = true; + let bytes = bincode::serde::encode_to_vec(vec![reflected.clone()], config).expect("encode"); + let (loaded, _): (Vec, _) = + bincode::serde::decode_from_slice(&bytes, config).expect("load"); + assert_eq!(loaded, vec![reflected]); + } + + #[test] + fn merge_rejects_stale_observations_and_preserves_finished_requests() { + for phase in [RequestPhase::Won, RequestPhase::Lost, RequestPhase::Locked] { + let mut finished = stored("alice", phase, Some(50)); + finished.last_updated = 60; + for observed_at in [40, 70] { + let mut pending = stored("alice", RequestPhase::Voting, None); + pending.last_updated = observed_at; + assert_eq!( + merge_requests(std::slice::from_ref(&finished), vec![pending], 80, None), + vec![finished.clone()] + ); + } + } + let mut current = stored("alice", RequestPhase::Voting, None); + current.last_updated = 60; + let older = stored("alice", RequestPhase::Joinable, None); + assert_eq!( + merge_requests(std::slice::from_ref(¤t), vec![older], 80, None), + vec![current] + ); + } + + #[test] + fn merge_fills_outcome_from_previous_pending() { + let previous = vec![stored("b", RequestPhase::Voting, None)]; + let mut won = stored("b", RequestPhase::Won, None); + won.tally = RequestTally::default(); + won.end = None; + let merged = merge_requests(&previous, vec![won], 100, None); + assert_eq!(merged[0].phase, RequestPhase::Won); + assert_eq!(merged[0].tally.you, 4); + assert_eq!(merged[0].end, Some(3)); + assert_eq!(merged[0].decided_at, Some(3)); + } +} diff --git a/src/model/dpns_vote_schedule.rs b/src/model/dpns_vote_schedule.rs new file mode 100644 index 000000000..7d6859007 --- /dev/null +++ b/src/model/dpns_vote_schedule.rs @@ -0,0 +1,25 @@ +//! Absolute UTC schedule input, independent of the time the form is submitted. + +use chrono::NaiveDate; + +pub(crate) fn parse_utc_schedule(date: &str, hour: u32, minute: u32) -> Option { + let timestamp = NaiveDate::parse_from_str(date, "%Y-%m-%d") + .ok()? + .and_hms_opt(hour, minute, 0)? + .and_utc() + .timestamp_millis(); + u64::try_from(timestamp).ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn utc_input_rejects_invalid_dates_and_times() { + assert_eq!(parse_utc_schedule("2026-02-30", 12, 0), None); + assert_eq!(parse_utc_schedule("2026-09-08", 24, 0), None); + assert_eq!(parse_utc_schedule("1960-01-01", 12, 0), None); + assert!(parse_utc_schedule("2028-02-29", 23, 59).is_some()); + } +} diff --git a/src/model/dpns_voting/composer.rs b/src/model/dpns_voting/composer.rs new file mode 100644 index 000000000..4fae92600 --- /dev/null +++ b/src/model/dpns_voting/composer.rs @@ -0,0 +1,747 @@ +//! Aggregate vote composition: staged decisions × node set → targets (VOTE-FR-080). +//! +//! Pure: callers resolve each node's proved state, target lock and changes +//! left beforehand. Every node × decision either becomes a target or a +//! [`SkipReason`]; nothing is silently dropped. + +use super::operator::{ChangesLeft, relative_schedule}; +use super::{ + DpnsCurrentVoteState, DpnsVoteTarget, DpnsVoteTargetKey, VoteTiming, + validate_dpns_schedule_time, +}; +use dash_sdk::dpp::dashcore::Network; +use dash_sdk::dpp::identity::TimestampMillis; +use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use dash_sdk::platform::Identifier; +use std::collections::{BTreeMap, BTreeSet}; +use std::time::Duration; + +/// One staged decision: a contest and the choice for every node-set node. +#[derive(Debug, Clone, PartialEq)] +pub struct Decision { + pub contested_name: String, + pub vote_poll_id: Identifier, + pub choice: ResourceVoteChoice, + pub end_time: Option, +} + +/// One node-set node's standing on one decision's contest. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct NodeStanding { + pub state: DpnsCurrentVoteState, + /// An unresolved operation holds this node × contest target. + pub locked: bool, + pub changes: ChangesLeft, + /// Whether `state` rests on proof fresh enough to decide that nothing + /// needs sending. Display keeps older proof, which may not. + pub proof_can_decide: bool, +} + +/// A node of the node set, as the composer sees it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ComposerNode { + pub voter_id: Identifier, + pub alias: Option, +} + +/// When the batch is cast (VOTE-FR-023). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BatchTiming { + Now, + /// `preset` before each contest's end (VOTE-FR-081). + BeforeEnd(Duration), + At(TimestampMillis), +} + +/// A per-node override under `Adjust nodes`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NodeTiming { + Batch, + Override(BatchTiming), + DontUse, +} + +/// Why a node × decision produces no target. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum SkipReason { + /// The node already holds the requested choice (VOTE-FR-013). + AlreadyVoted, + /// Five of five votes used on this contest (VOTE-FR-078). + NoChangesLeft, + /// Proved state is unavailable (VOTE-FR-016). + VoteStateUnavailable, + /// An earlier vote on this contest is still unresolved (VOTE-FR-034). + AlreadyInProgress, + /// The operator chose `Don't use this node`. + NotUsed, + /// The vote was to be cast shortly before voting ends, but the contest's + /// deadline has not been read yet. + DeadlineUnknown, +} + +/// One skipped node × decision. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SkippedTarget { + pub voter_id: Identifier, + pub contested_name: String, + pub reason: SkipReason, +} + +/// Why no plan can be built. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ComposeError { + #[error("Choose a future time before the contest ends for {contested_name}.dash.")] + ScheduleOutlastsContest { contested_name: String }, + #[error("Voting has ended for {contested_name}.dash. Clear it from your decisions.")] + VotingEnded { contested_name: String }, +} + +/// Exactly what a confirm click submits. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct AggregatePlan { + pub targets: Vec, + /// Targets whose node is shown on the requested choice by proof too old + /// to decide. They are submitted for a fresh check, which sends a vote + /// only when the choice is not in place: neither first votes nor + /// transactions the operator can count on. + pub recheck: BTreeSet, + pub skipped: Vec, + /// Votes asked for "when voting is about to end" whose contest is already + /// inside the lead time, so they are sent now. Targets only checked again + /// are left out: they are not votes the operator is told will be sent. + pub ends_soon_now: usize, +} + +impl AggregatePlan { + /// Targets that change an earlier vote. + pub fn change_count(&self) -> usize { + self.targets + .iter() + .filter(|target| target.current_choice.is_some()) + .count() + } + + /// Whether `key` is submitted only to check again a choice its node + /// already shows. + pub fn is_recheck(&self, key: &DpnsVoteTargetKey) -> bool { + self.recheck.contains(key) + } + + /// Targets that send a vote: every target but the ones only checked again. + pub fn transaction_count(&self) -> usize { + self.targets + .iter() + .filter(|target| !self.is_recheck(&target.key)) + .count() + } + + /// Distinct nodes casting at least one vote. + pub fn node_count(&self) -> usize { + self.targets + .iter() + .map(|target| target.key.voter_id) + .collect::>() + .len() + } + + /// Whether every target is cast immediately. + pub fn all_now(&self) -> bool { + self.targets + .iter() + .all(|target| target.timing == VoteTiming::Now) + } + + /// Skips grouped by reason, in a stable order. + pub fn skipped_by_reason(&self) -> BTreeMap { + let mut counts = BTreeMap::new(); + for skipped in &self.skipped { + *counts.entry(skipped.reason).or_default() += 1; + } + counts + } +} + +/// Resolve a timing for one decision. "Before the end" on a contest already +/// inside the lead time votes now; the flag reports that fallback. `None` +/// means "before the end" cannot be placed because the deadline is unknown. +fn resolve_timing( + timing: BatchTiming, + decision: &Decision, + now_ms: u64, +) -> Result, ComposeError> { + match timing { + BatchTiming::Now => Ok(Some((VoteTiming::Now, false))), + BatchTiming::BeforeEnd(preset) => { + Ok(decision + .end_time + .map(|end| match relative_schedule(end, preset, now_ms) { + Ok(at) => (VoteTiming::Scheduled(at), false), + Err(_) => (VoteTiming::Now, true), + })) + } + BatchTiming::At(at) => validate_dpns_schedule_time(at, now_ms, decision.end_time) + .map(|()| Some((VoteTiming::Scheduled(at), false))) + .map_err(|_| ComposeError::ScheduleOutlastsContest { + contested_name: decision.contested_name.clone(), + }), + } +} + +/// Build the plan for `decisions` across `nodes`. +/// +/// `standing(voter, poll)` reports each node's state on a contest; `overrides` +/// holds per-node timing from `Adjust nodes`. +/// +/// # Errors +/// +/// [`ComposeError`] when a contest has ended or a scheduled time falls +/// outside a contest's window. +pub fn compose( + network: Network, + decisions: &[Decision], + nodes: &[ComposerNode], + standing: impl Fn(Identifier, Identifier) -> NodeStanding, + batch: BatchTiming, + overrides: &BTreeMap, + now_ms: u64, +) -> Result { + let mut plan = AggregatePlan::default(); + for decision in decisions { + if decision.end_time.is_some_and(|end| end <= now_ms) { + return Err(ComposeError::VotingEnded { + contested_name: decision.contested_name.clone(), + }); + } + // A fixed batch time must fit every decision, whichever nodes end up voting. + let batch_timing = resolve_timing(batch, decision, now_ms)?; + for node in nodes { + let skip = |reason| SkippedTarget { + voter_id: node.voter_id, + contested_name: decision.contested_name.clone(), + reason, + }; + let timing = match overrides.get(&node.voter_id).copied() { + Some(NodeTiming::DontUse) => { + plan.skipped.push(skip(SkipReason::NotUsed)); + continue; + } + Some(NodeTiming::Override(timing)) => Some(timing), + Some(NodeTiming::Batch) | None => None, + }; + let standing = standing(node.voter_id, decision.vote_poll_id); + if standing.locked { + plan.skipped.push(skip(SkipReason::AlreadyInProgress)); + continue; + } + let DpnsCurrentVoteState::Available(current) = standing.state else { + plan.skipped.push(skip(SkipReason::VoteStateUnavailable)); + continue; + }; + // Proof too old to decide cannot settle "already voted": the target + // goes out without a reviewed current choice, and the backend's + // fresh proof either confirms the no-op without broadcasting or + // asks for another review because the vote changed elsewhere. + // `recheck` keeps what the node shows, so the review does not + // present it as a first vote. + let unverified_no_op = current == Some(decision.choice) && !standing.proof_can_decide; + if current == Some(decision.choice) && !unverified_no_op { + plan.skipped.push(skip(SkipReason::AlreadyVoted)); + continue; + } + // A node with no changes left can send nothing whatever a fresh + // check finds, so it is skipped before the stale-proof routing. + if current.is_some() && standing.changes.is_exhausted() { + plan.skipped.push(skip(SkipReason::NoChangesLeft)); + continue; + } + let current = if unverified_no_op { None } else { current }; + let resolved = match timing { + Some(timing) => resolve_timing(timing, decision, now_ms)?, + None => batch_timing, + }; + let Some((timing, ends_soon)) = resolved else { + plan.skipped.push(skip(SkipReason::DeadlineUnknown)); + continue; + }; + plan.ends_soon_now += usize::from(ends_soon && !unverified_no_op); + let key = DpnsVoteTargetKey { + network, + voter_id: node.voter_id, + vote_poll_id: decision.vote_poll_id, + }; + if unverified_no_op { + plan.recheck.insert(key.clone()); + } + plan.targets.push(DpnsVoteTarget { + key, + voter_alias: node.alias.clone(), + contested_name: decision.contested_name.clone(), + requested_choice: decision.choice, + current_choice: current, + timing, + }); + } + } + Ok(plan) +} + +#[cfg(test)] +mod tests { + use super::*; + + const MIN: u64 = 60_000; + + fn id(byte: u8) -> Identifier { + Identifier::from([byte; 32]) + } + + fn decision(name: &str, poll: u8, choice: ResourceVoteChoice, end: u64) -> Decision { + Decision { + contested_name: name.to_owned(), + vote_poll_id: id(poll), + choice, + end_time: Some(end), + } + } + + fn nodes(bytes: &[u8]) -> Vec { + bytes + .iter() + .map(|byte| ComposerNode { + voter_id: id(*byte), + alias: None, + }) + .collect() + } + + fn available(current: Option) -> NodeStanding { + NodeStanding { + state: DpnsCurrentVoteState::Available(current), + locked: false, + changes: ChangesLeft::Known(4), + proof_can_decide: true, + } + } + + /// VOTE-FR-080: two decisions × three nodes give six targets, one per node and name. + #[test] + fn one_target_per_node_and_name() { + let lock = ResourceVoteChoice::Lock; + let plan = compose( + Network::Testnet, + &[ + decision("alice", 10, lock, 100 * MIN), + decision("bob", 11, ResourceVoteChoice::Abstain, 100 * MIN), + ], + &nodes(&[1, 2, 3]), + |_, _| available(None), + BatchTiming::Now, + &BTreeMap::new(), + 0, + ) + .unwrap(); + assert_eq!(plan.targets.len(), 6); + assert_eq!(plan.transaction_count(), 6); + assert!(plan.recheck.is_empty()); + assert_eq!(plan.node_count(), 3); + assert_eq!(plan.change_count(), 0); + assert!(plan.all_now()); + assert!(plan.skipped.is_empty()); + } + + /// VOTE-TC-003/007/041/096: every exclusion becomes a typed skip. + #[test] + fn exclusions_are_skipped_with_reasons() { + let lock = ResourceVoteChoice::Lock; + let abstain = ResourceVoteChoice::Abstain; + let standing = |voter: Identifier, _| match voter.to_buffer()[0] { + 1 => available(Some(lock)), + 2 => NodeStanding { + changes: ChangesLeft::Known(0), + ..available(Some(abstain)) + }, + 3 => NodeStanding { + state: DpnsCurrentVoteState::Unavailable, + ..available(None) + }, + 4 => NodeStanding { + locked: true, + ..available(None) + }, + 6 => available(Some(abstain)), + _ => available(None), + }; + let overrides = BTreeMap::from([(id(5), NodeTiming::DontUse)]); + let plan = compose( + Network::Testnet, + &[decision("alice", 10, lock, 100 * MIN)], + &nodes(&[1, 2, 3, 4, 5, 6, 7]), + standing, + BatchTiming::Now, + &overrides, + 0, + ) + .unwrap(); + assert_eq!( + plan.skipped_by_reason(), + BTreeMap::from([ + (SkipReason::AlreadyVoted, 1), + (SkipReason::NoChangesLeft, 1), + (SkipReason::VoteStateUnavailable, 1), + (SkipReason::AlreadyInProgress, 1), + (SkipReason::NotUsed, 1), + ]) + ); + assert_eq!( + plan.targets + .iter() + .map(|target| target.key.voter_id) + .collect::>(), + vec![id(6), id(7)] + ); + assert_eq!(plan.change_count(), 1, "node 6 changes Abstain → Lock"); + } + + /// Unknown changes never block: Platform enforces the five-vote limit. + #[test] + fn unknown_changes_left_still_submits() { + let plan = compose( + Network::Testnet, + &[decision("alice", 10, ResourceVoteChoice::Lock, 100 * MIN)], + &nodes(&[1]), + |_, _| NodeStanding { + changes: ChangesLeft::Unknown, + ..available(Some(ResourceVoteChoice::Abstain)) + }, + BatchTiming::Now, + &BTreeMap::new(), + 0, + ) + .unwrap(); + assert_eq!(plan.targets.len(), 1); + } + + /// VOTE-TC-067/068: "about to end" resolves per contest; per-node overrides win. + #[test] + fn before_end_resolves_per_contest_and_overrides_apply() { + let lock = ResourceVoteChoice::Lock; + let overrides = BTreeMap::from([(id(2), NodeTiming::Override(BatchTiming::Now))]); + let plan = compose( + Network::Testnet, + &[ + decision("alice", 10, lock, 60 * MIN), + decision("bob", 11, lock, 90 * MIN), + ], + &nodes(&[1, 2]), + |_, _| available(None), + BatchTiming::BeforeEnd(Duration::from_secs(10 * 60)), + &overrides, + 0, + ) + .unwrap(); + let timings: Vec<(u8, &str, VoteTiming)> = plan + .targets + .iter() + .map(|target| { + ( + target.key.voter_id.to_buffer()[0], + target.contested_name.as_str(), + target.timing, + ) + }) + .collect(); + assert_eq!( + timings, + vec![ + (1, "alice", VoteTiming::Scheduled(50 * MIN)), + (2, "alice", VoteTiming::Now), + (1, "bob", VoteTiming::Scheduled(80 * MIN)), + (2, "bob", VoteTiming::Now), + ] + ); + assert!(!plan.all_now()); + } + + /// Display keeps proof far older than a submission may rest on. Such + /// proof must not conclude "already voted": the vote may have been changed + /// elsewhere since, so the target has to reach the backend's fresh check. + #[test] + fn stale_proof_of_the_requested_choice_does_not_skip_the_vote() { + let lock = ResourceVoteChoice::Lock; + let standing = |voter: Identifier, _| NodeStanding { + proof_can_decide: voter == id(1), + ..available(Some(lock)) + }; + let plan = compose( + Network::Testnet, + &[decision("alice", 10, lock, 100 * MIN)], + &nodes(&[1, 2]), + standing, + BatchTiming::Now, + &BTreeMap::new(), + 0, + ) + .unwrap(); + + assert_eq!( + plan.skipped, + vec![SkippedTarget { + voter_id: id(1), + contested_name: "alice".to_owned(), + reason: SkipReason::AlreadyVoted, + }], + "fresh proof still settles an exact no-op" + ); + assert_eq!(plan.targets.len(), 1); + assert_eq!(plan.targets[0].key.voter_id, id(2)); + assert_eq!( + plan.targets[0].current_choice, None, + "no reviewed current choice, so the backend cannot drop it as a no-op" + ); + assert!(!plan.targets[0].is_no_op()); + assert_eq!(plan.change_count(), 0); + assert!( + plan.is_recheck(&plan.targets[0].key), + "the review must still know the node is shown on the requested choice" + ); + assert_eq!( + plan.transaction_count(), + 0, + "a vote that is only checked again is not a promised transaction" + ); + } + + /// A vote that replaces another choice is a transaction however old the + /// proof is: only a node shown on the requested choice is merely checked. + #[test] + fn stale_proof_of_another_choice_is_still_a_counted_change() { + let plan = compose( + Network::Testnet, + &[decision("alice", 10, ResourceVoteChoice::Lock, 100 * MIN)], + &nodes(&[1]), + |_, _| NodeStanding { + proof_can_decide: false, + ..available(Some(ResourceVoteChoice::Abstain)) + }, + BatchTiming::Now, + &BTreeMap::new(), + 0, + ) + .unwrap(); + + assert!(plan.recheck.is_empty()); + assert_eq!(plan.transaction_count(), 1); + assert_eq!(plan.change_count(), 1); + assert_eq!( + plan.targets[0].current_choice, + Some(ResourceVoteChoice::Abstain) + ); + } + + /// "Before the end" needs a deadline. A contest whose deadline has not + /// been read yet is skipped with a reason; it must not block the rest of + /// the batch, and a node told to vote now still votes on it. + #[test] + fn before_end_skips_only_the_contest_with_an_unknown_deadline() { + let lock = ResourceVoteChoice::Lock; + let unknown_deadline = Decision { + end_time: None, + ..decision("bob", 11, lock, 0) + }; + let overrides = BTreeMap::from([(id(2), NodeTiming::Override(BatchTiming::Now))]); + let plan = compose( + Network::Testnet, + &[decision("alice", 10, lock, 60 * MIN), unknown_deadline], + &nodes(&[1, 2]), + |_, _| available(None), + BatchTiming::BeforeEnd(Duration::from_secs(10 * 60)), + &overrides, + 0, + ) + .unwrap(); + + assert_eq!( + plan.targets + .iter() + .map(|target| ( + target.key.voter_id.to_buffer()[0], + target.contested_name.as_str(), + target.timing, + )) + .collect::>(), + vec![ + (1, "alice", VoteTiming::Scheduled(50 * MIN)), + (2, "alice", VoteTiming::Now), + (2, "bob", VoteTiming::Now), + ] + ); + assert_eq!( + plan.skipped, + vec![SkippedTarget { + voter_id: id(1), + contested_name: "bob".to_owned(), + reason: SkipReason::DeadlineUnknown, + }] + ); + } + + /// VOTE-FR-081: a time at or after the deadline is refused. + #[test] + fn schedules_outside_the_window_are_rejected() { + let lock = ResourceVoteChoice::Lock; + let compose_at = |timing| { + compose( + Network::Testnet, + &[decision("alice", 10, lock, 5 * MIN)], + &nodes(&[1]), + |_, _| available(None), + timing, + &BTreeMap::new(), + 0, + ) + }; + let outlasts = Err(ComposeError::ScheduleOutlastsContest { + contested_name: "alice".to_owned(), + }); + assert_eq!(compose_at(BatchTiming::At(5 * MIN)), outlasts); + assert!(compose_at(BatchTiming::At(4 * MIN)).is_ok()); + + let all_skipped = compose( + Network::Testnet, + &[decision("alice", 10, lock, 5 * MIN)], + &nodes(&[1]), + |_, _| NodeStanding { + state: DpnsCurrentVoteState::Unavailable, + ..available(None) + }, + BatchTiming::At(5 * MIN), + &BTreeMap::new(), + 0, + ); + assert_eq!( + all_skipped, outlasts, + "the batch time is checked even when every node is skipped" + ); + } + + /// VOTE-FR-081: "before the end" votes now on contests already inside the + /// lead time and schedules the rest; the plan counts the early votes. + #[test] + fn before_end_votes_now_inside_the_lead_time() { + let lock = ResourceVoteChoice::Lock; + let hour = 60 * MIN; + let plan = compose( + Network::Mainnet, + &[ + decision("far", 10, lock, 240 * hour), + decision("urgent", 11, lock, 3 * hour), + ], + &nodes(&[1, 2]), + |_, _| available(None), + BatchTiming::BeforeEnd(Duration::from_secs(6 * 3600)), + &BTreeMap::new(), + 0, + ) + .expect("the urgent contest no longer blocks the batch"); + let timing = |name: &str| { + plan.targets + .iter() + .filter(|target| target.contested_name == name) + .map(|target| target.timing) + .collect::>() + }; + assert_eq!(timing("far"), vec![VoteTiming::Scheduled(234 * hour); 2]); + assert_eq!(timing("urgent"), vec![VoteTiming::Now; 2]); + assert_eq!(plan.ends_soon_now, 2); + } + + /// A node with no changes left can send nothing, so stale proof of the + /// requested choice does not make it a vote to check again: it is skipped + /// for the reason the operator can act on, as the cards and tray show it. + #[test] + fn an_exhausted_node_is_skipped_even_on_stale_proof_of_the_requested_choice() { + let lock = ResourceVoteChoice::Lock; + let plan = compose( + Network::Testnet, + &[decision("alice", 10, lock, 100 * MIN)], + &nodes(&[1]), + |_, _| NodeStanding { + changes: ChangesLeft::Known(0), + proof_can_decide: false, + ..available(Some(lock)) + }, + BatchTiming::Now, + &BTreeMap::new(), + 0, + ) + .unwrap(); + + assert!(plan.targets.is_empty()); + assert!(plan.recheck.is_empty()); + assert_eq!( + plan.skipped_by_reason(), + BTreeMap::from([(SkipReason::NoChangesLeft, 1)]) + ); + } + + /// Inside the lead time a vote is sent now and the confirm step says so. + /// A node only checked again sends nothing, so it is not part of that count. + #[test] + fn a_vote_only_checked_again_is_not_announced_as_sent_now() { + let lock = ResourceVoteChoice::Lock; + let hour = 60 * MIN; + let standing = |voter: Identifier, _| match voter.to_buffer()[0] { + 1 => NodeStanding { + proof_can_decide: false, + ..available(Some(lock)) + }, + _ => available(None), + }; + let plan_for = |voters: &[u8]| { + compose( + Network::Mainnet, + &[decision("urgent", 11, lock, 3 * hour)], + &nodes(voters), + standing, + BatchTiming::BeforeEnd(Duration::from_secs(6 * 3600)), + &BTreeMap::new(), + 0, + ) + .expect("a contest inside the lead time is voted now") + }; + + let checked_only = plan_for(&[1]); + assert_eq!(checked_only.targets.len(), 1); + assert!(checked_only.all_now()); + assert_eq!(checked_only.recheck.len(), 1); + assert_eq!(checked_only.ends_soon_now, 0); + + let mixed = plan_for(&[1, 2]); + assert_eq!(mixed.targets.len(), 2); + assert_eq!(mixed.transaction_count(), 1); + assert_eq!( + mixed.ends_soon_now, 1, + "only the vote that is really sent is announced" + ); + } + + /// VOTE-TC-103 (compose half): a decision whose voting ended is refused. + #[test] + fn ended_contests_are_refused() { + let result = compose( + Network::Testnet, + &[decision("alice", 10, ResourceVoteChoice::Lock, MIN)], + &nodes(&[1]), + |_, _| available(None), + BatchTiming::Now, + &BTreeMap::new(), + MIN, + ); + assert_eq!( + result, + Err(ComposeError::VotingEnded { + contested_name: "alice".to_owned() + }) + ); + } +} diff --git a/src/model/dpns_voting/mod.rs b/src/model/dpns_voting/mod.rs new file mode 100644 index 000000000..2c00a3de0 --- /dev/null +++ b/src/model/dpns_voting/mod.rs @@ -0,0 +1,799 @@ +use dash_sdk::dpp::dashcore::Network; +use dash_sdk::dpp::data_contract::DataContract; +use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; +use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; +use dash_sdk::dpp::identity::TimestampMillis; +use dash_sdk::dpp::platform_value::Value; +use dash_sdk::dpp::util::strings::convert_to_homograph_safe_chars; +use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use dash_sdk::dpp::voting::vote_polls::contested_document_resource_vote_poll::ContestedDocumentResourceVotePoll; +use dash_sdk::platform::Identifier; +use serde::{Deserialize, Serialize}; +use std::fmt; + +pub mod composer; +pub mod operator; +pub mod progress; + +/// Grace period for admitting a scheduled vote to automatic execution. +pub const SCHEDULED_VOTE_MAX_LATENESS_MS: u64 = 120_000; + +/// Whether the normal automatic admission window has passed. +pub fn dpns_schedule_is_overdue(scheduled_at_ms: u64, now_ms: u64) -> bool { + scheduled_at_ms.saturating_add(SCHEDULED_VOTE_MAX_LATENESS_MS) < now_ms +} + +/// Proved current vote state for one node × poll. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DpnsCurrentVoteState { + Checking, + Available(Option), + Unavailable, +} + +/// Whether a vote poll can still accept a submitted transition. +/// +/// Reconciliation needs a terminal negative verdict, and a current choice that +/// merely differs from the requested one never supplies it — the submitted +/// transition may still be waiting to apply. A closed poll does supply it: no +/// transition can apply to a decided contest. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DpnsVotePollAvailability { + /// The poll is open, or DET has no proof that it closed. Absence of + /// evidence must never be read as closure, so unknown polls land here. + MayAccept, + /// The contest has an authoritative terminal outcome. + ProvedClosed, +} + +/// Classify a poll from its cached contest, if DET has one. +/// +/// A local deadline cannot prove closure; Platform may still accept votes until resolution. +pub fn dpns_vote_poll_availability( + contest: Option<&crate::model::contested_name::ContestedName>, +) -> DpnsVotePollAvailability { + let Some(contest) = contest else { + return DpnsVotePollAvailability::MayAccept; + }; + if contest.state.is_decided() { + DpnsVotePollAvailability::ProvedClosed + } else { + DpnsVotePollAvailability::MayAccept + } +} + +/// Durable identity of one submitted voting batch. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct DpnsVoteOperationId([u8; 16]); + +impl DpnsVoteOperationId { + /// Return the stable persisted byte representation. + pub fn to_bytes(self) -> [u8; 16] { + self.0 + } + + /// Restore an identifier from its persisted byte representation. + pub fn from_bytes(bytes: [u8; 16]) -> Self { + Self(bytes) + } +} + +impl fmt::Display for DpnsVoteOperationId { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + for byte in self.0 { + write!(formatter, "{byte:02x}")?; + } + Ok(()) + } +} + +/// Exact network + node + poll lock identity for one vote target. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct DpnsVoteTargetKey { + pub network: Network, + /// The masternode ProTxHash used by Platform's proved vote query. + pub voter_id: Identifier, + pub vote_poll_id: Identifier, +} + +/// Compare-and-set request for one scheduled target; the voter and poll cannot change. +#[derive(Debug, Clone, PartialEq)] +pub struct DpnsScheduledVoteEdit { + pub operation_id: DpnsVoteOperationId, + pub key: DpnsVoteTargetKey, + pub expected_choice: ResourceVoteChoice, + pub expected_timestamp: u64, + pub choice: ResourceVoteChoice, + pub unix_timestamp: u64, +} + +/// Reason a schedule edit cannot be applied to the selected contest. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DpnsScheduleEditValidationError { + Time, + Choice, + Contest, +} + +/// Validate a future voting time against the contest deadline, when known. +pub fn validate_dpns_schedule_time( + unix_timestamp: u64, + now_ms: u64, + end_time: Option, +) -> Result<(), DpnsScheduleEditValidationError> { + if unix_timestamp <= now_ms || end_time.is_some_and(|end| unix_timestamp >= end) { + return Err(DpnsScheduleEditValidationError::Time); + } + Ok(()) +} + +/// Validate the new schedule against the current time and the selected contest. +pub fn validate_dpns_schedule_edit( + choice: ResourceVoteChoice, + unix_timestamp: u64, + now_ms: u64, + contest: &crate::model::contested_name::ContestedName, +) -> Result<(), DpnsScheduleEditValidationError> { + if !contest.is_votable() { + return Err(DpnsScheduleEditValidationError::Contest); + } + validate_dpns_schedule_time(unix_timestamp, now_ms, contest.end_time)?; + if let ResourceVoteChoice::TowardsIdentity(id) = choice + && !contest + .contestants + .as_ref() + .is_some_and(|contenders| contenders.iter().any(|contender| contender.id == id)) + { + return Err(DpnsScheduleEditValidationError::Choice); + } + Ok(()) +} + +/// Identity of one scheduled vote as the Scheduled view addresses it: a node +/// and a contested name on one network. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct DpnsScheduledVoteKey { + pub network: Network, + pub voter_id: Identifier, + pub contested_name: String, +} + +/// Result of clearing one scheduled target from the voting journal. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DpnsScheduledVoteClearDisposition { + Cleared, + InFlight(DpnsVoteTargetStatus), +} + +/// Typed Clear All result for one scheduled target. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DpnsScheduledVoteClearOutcome { + pub operation_id: Option, + pub key: DpnsScheduledVoteKey, + pub disposition: DpnsScheduledVoteClearDisposition, +} + +/// When a target should enter the shared executor. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum VoteTiming { + Now, + Scheduled(TimestampMillis), +} + +/// Where a target lands when nothing was broadcast for it: a scheduled vote +/// stays scheduled for another attempt, an immediate one has failed. +fn not_broadcast_outcome( + timing: VoteTiming, + failure: DpnsVoteFailure, +) -> (DpnsVoteTargetStatus, Option) { + let status = match timing { + VoteTiming::Scheduled(_) => DpnsVoteTargetStatus::Scheduled, + VoteTiming::Now => DpnsVoteTargetStatus::FailedBeforeSubmission, + }; + (status, Some(failure)) +} + +pub(crate) fn unavailable_preflight_outcome( + timing: VoteTiming, +) -> (DpnsVoteTargetStatus, Option) { + not_broadcast_outcome(timing, DpnsVoteFailure::CurrentVoteUnavailable) +} + +pub(crate) fn failed_before_broadcast_outcome( + timing: VoteTiming, +) -> (DpnsVoteTargetStatus, Option) { + not_broadcast_outcome(timing, DpnsVoteFailure::SubmissionFailed) +} + +/// One reviewed node × contest action. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct DpnsVoteTarget { + pub key: DpnsVoteTargetKey, + pub voter_alias: Option, + pub contested_name: String, + pub requested_choice: ResourceVoteChoice, + pub current_choice: Option, + pub timing: VoteTiming, +} + +impl DpnsVoteTarget { + /// Whether submitting this target would change nothing on Platform. + /// + /// The single definition of no-op suppression: the review step filters on + /// it before the operator commits, and [`DpnsVoteOperation::new`] applies + /// it again when the batch is built. + pub fn is_no_op(&self) -> bool { + self.current_choice == Some(self.requested_choice) + } +} + +/// Persistable, user-meaningful failure category without task diagnostics. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum DpnsVoteFailure { + PlatformRejected, + SubmissionFailed, + CurrentVoteUnavailable, + ResultUnconfirmed, + /// The contest closed before the target was submitted. Appended last: + /// journal records are positionally encoded. + VotingEnded, + /// The node's voting key was not loaded when the target was due. + VotingKeyMissing, +} + +/// Lifecycle of one target. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum DpnsVoteTargetStatus { + Scheduled, + Queued, + Submitting, + Confirming, + Confirmed, + Unconfirmed, + Rejected, + FailedBeforeSubmission, + /// Reserved: nothing produces it, because reconciliation cannot prove a + /// submitted vote was not applied (dashpay/platform#4137). Kept because + /// journal records are positionally encoded. + NotApplied, + /// The user cancelled a scheduled vote before it was submitted. + Cancelled, +} + +impl DpnsVoteTargetStatus { + /// Whether another operation must remain blocked for the same target. + pub fn holds_lock(self) -> bool { + matches!( + self, + Self::Scheduled + | Self::Queued + | Self::Submitting + | Self::Confirming + | Self::Unconfirmed + ) + } + + /// Whether the vote ended without taking effect, so the user may review + /// and submit it again. + pub fn is_reviewable_failure(self) -> bool { + match self { + Self::Rejected | Self::FailedBeforeSubmission | Self::NotApplied => true, + Self::Scheduled + | Self::Queued + | Self::Submitting + | Self::Confirming + | Self::Confirmed + | Self::Unconfirmed + | Self::Cancelled => false, + } + } +} + +/// Durable result and progress for one operation target. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct DpnsVoteOutcome { + pub operation_id: DpnsVoteOperationId, + pub target: DpnsVoteTarget, + pub status: DpnsVoteTargetStatus, + pub failure: Option, + /// Display-only relative preset, hydrated from journal-owned metadata. + /// Excluded from the established binary vote record format. + #[serde(skip)] + pub relative_schedule_preset_ms: Option, + /// When restart recovery stopped this immediate vote or queued it to be + /// sent again, in Unix ms. Display-only and hydrated like the preset: the + /// outcome belongs to the session that recovered the vote, not to the + /// earlier one that reviewed it. + #[serde(skip)] + pub recovered_at_ms: Option, +} + +/// Reviewed voting batch stored before its first broadcast. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct DpnsVoteOperation { + pub id: DpnsVoteOperationId, + pub created_at: TimestampMillis, + pub targets: Vec, + pub no_op_count: usize, +} + +impl DpnsVoteOperation { + /// Build an operation while removing targets that match proved current state. + pub fn new( + id: DpnsVoteOperationId, + created_at: TimestampMillis, + targets: Vec, + ) -> Self { + let original_len = targets.len(); + let targets = targets + .into_iter() + .filter(|target| !target.is_no_op()) + .map(|target| { + let status = match target.timing { + VoteTiming::Now => DpnsVoteTargetStatus::Queued, + VoteTiming::Scheduled(_) => DpnsVoteTargetStatus::Scheduled, + }; + DpnsVoteOutcome { + operation_id: id, + target, + status, + failure: None, + relative_schedule_preset_ms: None, + recovered_at_ms: None, + } + }) + .collect::>(); + let no_op_count = original_len.saturating_sub(targets.len()); + Self { + id, + created_at, + targets, + no_op_count, + } + } + + /// Find one outcome by its exact target key. + pub fn outcome(&self, key: &DpnsVoteTargetKey) -> Option<&DpnsVoteOutcome> { + self.targets + .iter() + .find(|outcome| &outcome.target.key == key) + } + + /// Whether all targets have reached a lock-releasing state. + pub fn is_complete(&self) -> bool { + self.targets + .iter() + .all(|outcome| !outcome.status.holds_lock()) + } +} + +/// Build `[Value::from("dash"), Value::Text(normalized_label.to_owned())]` for a DPNS vote poll. +/// +/// Caller must pre-normalize the label via `convert_to_homograph_safe_chars` +/// (`alice` → `a11ce`); Platform indexes polls under the normalized form. +fn dpns_vote_poll_index_values(normalized_label: &str) -> Vec { + vec![ + Value::from("dash"), + Value::Text(normalized_label.to_owned()), + ] +} + +/// A DPNS contract schema cannot describe the requested vote poll. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum DpnsVotePollError { + #[error("The username contract is missing its domain definition. Refresh and try again.")] + MissingDomain, + #[error("The username contract does not support voting. Refresh and try again.")] + MissingContestedIndex, +} + +/// The exact Platform vote poll for one DPNS label under `dpns_contract`. +/// +/// Normalizes `name` itself, so callers pass the label as the user typed it. +/// This is the only construction of the poll: its `unique_id()` keys every +/// target lock and journal record, while the poll itself is what gets voted on, +/// so a second spelling would let DET lock one poll and submit another. +/// +/// # Errors +/// +/// Returns a schema error if the domain document or its contested index is missing. +pub fn dpns_vote_poll( + dpns_contract: &DataContract, + name: &str, +) -> Result { + let document_type = dpns_contract + .document_type_for_name("domain") + .map_err(|_| DpnsVotePollError::MissingDomain)?; + let Some(contested_index) = document_type.find_contested_index() else { + return Err(DpnsVotePollError::MissingContestedIndex); + }; + Ok(ContestedDocumentResourceVotePoll { + index_name: contested_index.name.clone(), + index_values: dpns_vote_poll_index_values(&convert_to_homograph_safe_chars(name)), + document_type_name: document_type.name().to_owned(), + contract_id: dpns_contract.id(), + }) +} + +/// Ordering that decides which operation currently speaks for one target. +pub type DpnsVoteAuthorityRank = (bool, TimestampMillis, DpnsVoteOperationId); + +/// Rank one operation's outcome for a target: a lock holder outranks history, +/// then the newest `(created_at, operation id)` wins. +/// +/// The operation id is part of the rank, not a fallback: `created_at` comes from +/// a millisecond clock, so a bulk review commits several operations under one +/// timestamp and ties are routinely reachable. Every site that asks "which +/// operation speaks for this target" must order by this rank, or the Scheduled +/// Votes screen, the node cards and the cast/cancel paths can each name a +/// different operation for the same journal. +pub fn dpns_vote_authority_rank( + created_at: TimestampMillis, + operation_id: DpnsVoteOperationId, + status: DpnsVoteTargetStatus, +) -> DpnsVoteAuthorityRank { + (status.holds_lock(), created_at, operation_id) +} + +/// Select one outcome per exact target, optionally restricting the eligible history. +/// A lock holder wins, then the newest operation; equal ranks select the last record. +pub fn authoritative_dpns_vote_outcomes( + operations: &[DpnsVoteOperation], + include: impl Fn(&DpnsVoteOutcome) -> bool, +) -> std::collections::BTreeMap<&DpnsVoteTargetKey, (&DpnsVoteOperation, &DpnsVoteOutcome)> { + let mut selected = std::collections::BTreeMap::new(); + for operation in operations { + for outcome in operation.targets.iter().filter(|outcome| include(outcome)) { + let rank = dpns_vote_authority_rank(operation.created_at, operation.id, outcome.status); + let entry = selected + .entry(&outcome.target.key) + .or_insert((operation, outcome)); + if rank >= dpns_vote_authority_rank(entry.0.created_at, entry.0.id, entry.1.status) { + *entry = (operation, outcome); + } + } + } + selected +} + +/// The outcome that currently speaks for `key`, or `None` when it is absent. +pub fn authoritative_dpns_vote_outcome<'a>( + operations: &'a [DpnsVoteOperation], + key: &DpnsVoteTargetKey, +) -> Option<&'a DpnsVoteOutcome> { + authoritative_dpns_vote_outcomes(operations, |outcome| &outcome.target.key == key) + .into_values() + .next() + .map(|(_, outcome)| outcome) +} + +/// Operations still holding the target lock for `key`; more than one is a conflict. +pub fn dpns_vote_lock_holders<'a>( + operations: &'a [DpnsVoteOperation], + key: &'a DpnsVoteTargetKey, +) -> impl Iterator { + operations.iter().filter(move |operation| { + operation + .outcome(key) + .is_some_and(|outcome| outcome.status.holds_lock()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; + use dash_sdk::platform::Identifier; + + #[test] + fn authoritative_outcomes_preserve_exact_keys_and_share_tie_breaking() { + let key_target = target(1, 1, None, ResourceVoteChoice::Lock); + let mut locked = DpnsVoteOperation::new( + DpnsVoteOperationId::from_bytes([1; 16]), + 1, + vec![key_target.clone()], + ); + locked.targets[0].status = DpnsVoteTargetStatus::Unconfirmed; + let mut newer = DpnsVoteOperation::new( + DpnsVoteOperationId::from_bytes([2; 16]), + 2, + vec![key_target.clone()], + ); + newer.targets[0].status = DpnsVoteTargetStatus::Confirmed; + let mut another_network = newer.clone(); + another_network.targets[0].target.key.network = Network::Mainnet; + let mut another_poll = newer.clone(); + another_poll.targets[0].target.key.vote_poll_id = Identifier::from([2; 32]); + let operations = vec![newer, locked, another_network, another_poll]; + let selected = authoritative_dpns_vote_outcomes(&operations, |_| true); + assert_eq!( + selected.len(), + 3, + "same name must not collapse networks or polls" + ); + assert_eq!(selected[&key_target.key].0.id, operations[1].id); + for (key, (_, outcome)) in selected { + assert_eq!( + authoritative_dpns_vote_outcome(&operations, key), + Some(outcome) + ); + } + let mut tied = operations[1].clone(); + tied.id = DpnsVoteOperationId::from_bytes([3; 16]); + tied.targets[0].operation_id = tied.id; + for history in [ + vec![operations[1].clone(), tied.clone()], + vec![tied.clone(), operations[1].clone()], + ] { + assert_eq!( + authoritative_dpns_vote_outcomes(&history, |_| true)[&key_target.key] + .0 + .id, + tied.id + ); + } + } + + #[test] + fn automatic_window_boundary_and_overflow() { + assert!(!dpns_schedule_is_overdue(1_000, 121_000)); + assert!(dpns_schedule_is_overdue(1_000, 121_001)); + assert!(!dpns_schedule_is_overdue(1_000, 999)); + assert!(!dpns_schedule_is_overdue(u64::MAX, u64::MAX)); + } + + #[test] + fn operation_preserves_supplied_id_and_creation_time() { + let id = DpnsVoteOperationId::from_bytes([7; 16]); + let operation = + DpnsVoteOperation::new(id, 123, vec![target(1, 1, None, ResourceVoteChoice::Lock)]); + assert_eq!(operation.id, id); + assert_eq!(operation.created_at, 123); + assert_eq!(operation.targets[0].operation_id, id); + } + + fn target( + voter: u8, + poll: u8, + current: Option, + requested: ResourceVoteChoice, + ) -> DpnsVoteTarget { + DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([voter; 32]), + vote_poll_id: Identifier::from([poll; 32]), + }, + voter_alias: Some(format!("node-{voter}")), + contested_name: format!("contest-{poll}"), + requested_choice: requested, + current_choice: current, + timing: VoteTiming::Now, + } + } + + #[test] + fn index_values_uses_the_given_normalized_label() { + // Given: a pre-normalized DPNS label (homographs already substituted). + let normalized = "a11ce"; + + // When: constructing the vote poll index values. + let values = dpns_vote_poll_index_values(normalized); + + // Then: first element is the `"dash"` parent, second is the label as-given. + assert_eq!(values.len(), 2); + assert_eq!(values[0], Value::from("dash")); + assert_eq!(values[1], Value::Text("a11ce".to_owned())); + } + + #[test] + fn index_values_do_not_renormalize_the_label() { + // Given: a label that still contains homograph characters. + let not_yet_normalized = "alice"; + + // When: passing it directly to the helper (violating the contract). + let values = dpns_vote_poll_index_values(not_yet_normalized); + + // Then: the helper does NOT renormalize — the raw label is returned as-is. + // (Caller is responsible for normalizing before calling.) + assert_eq!(values[1], Value::Text("alice".to_owned())); + } + + /// VOTE-TC-003: choosing the proved current vote cannot create a target. + #[test] + fn operation_suppresses_exact_no_ops() { + let operation = DpnsVoteOperation::new( + DpnsVoteOperationId::from_bytes([1; 16]), + 1, + vec![ + target( + 1, + 1, + Some(ResourceVoteChoice::Lock), + ResourceVoteChoice::Lock, + ), + target(1, 2, None, ResourceVoteChoice::Abstain), + ], + ); + + assert_eq!(operation.targets.len(), 1); + assert_eq!(operation.no_op_count, 1); + assert_eq!( + operation.targets[0].target.key.vote_poll_id, + Identifier::from([2; 32]) + ); + } + + /// VOTE-TC-032: outcomes retain the exact voter × contest target. + #[test] + fn outcomes_retain_target_correlation() { + let operation = DpnsVoteOperation::new( + DpnsVoteOperationId::from_bytes([1; 16]), + 1, + vec![target(7, 9, None, ResourceVoteChoice::Abstain)], + ); + let outcome = &operation.targets[0]; + + assert_eq!(outcome.operation_id, operation.id); + assert_eq!(outcome.target.key.voter_id, Identifier::from([7; 32])); + assert_eq!(outcome.target.contested_name, "contest-9"); + } + + /// VOTE-TC-040/044: unresolved states keep the target lock across restart. + #[test] + fn unresolved_statuses_hold_target_locks() { + for status in [ + DpnsVoteTargetStatus::Scheduled, + DpnsVoteTargetStatus::Queued, + DpnsVoteTargetStatus::Submitting, + DpnsVoteTargetStatus::Confirming, + DpnsVoteTargetStatus::Unconfirmed, + ] { + assert!(status.holds_lock(), "{status:?} must hold its lock"); + } + for status in [ + DpnsVoteTargetStatus::Confirmed, + DpnsVoteTargetStatus::Rejected, + DpnsVoteTargetStatus::FailedBeforeSubmission, + DpnsVoteTargetStatus::Cancelled, + DpnsVoteTargetStatus::NotApplied, + ] { + assert!(!status.holds_lock(), "{status:?} must release its lock"); + } + } + + /// VOTE-TC-072: the network is part of target identity. + #[test] + fn target_keys_are_network_scoped() { + let testnet = DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([2; 32]), + }; + let mainnet = DpnsVoteTargetKey { + network: Network::Mainnet, + ..testnet.clone() + }; + + assert_ne!(testnet, mainnet); + } + + /// VOTE-TC-073: the durable operation shape contains no signing material. + #[test] + fn only_terminal_unapplied_statuses_are_reviewable_failures() { + use DpnsVoteTargetStatus as S; + for (status, expected) in [ + (S::Scheduled, false), + (S::Queued, false), + (S::Submitting, false), + (S::Confirming, false), + (S::Confirmed, false), + (S::Unconfirmed, false), + (S::Rejected, true), + (S::FailedBeforeSubmission, true), + (S::NotApplied, true), + (S::Cancelled, false), + ] { + assert_eq!(status.is_reviewable_failure(), expected, "{status:?}"); + assert!( + !(status.is_reviewable_failure() && status.holds_lock()), + "{status:?}: a reviewable failure never holds the target lock" + ); + } + } + + #[test] + fn serialized_operation_contains_identifiers_and_choices_only() { + fn collect_keys(value: &serde_json::Value, keys: &mut std::collections::BTreeSet) { + match value { + serde_json::Value::Object(object) => { + for (key, nested) in object { + keys.insert(key.clone()); + collect_keys(nested, keys); + } + } + serde_json::Value::Array(items) => { + items.iter().for_each(|item| collect_keys(item, keys)); + } + _ => {} + } + } + + let operation = DpnsVoteOperation::new( + DpnsVoteOperationId::from_bytes([1; 16]), + 1, + vec![target(4, 5, None, ResourceVoteChoice::Lock)], + ); + let serialized = serde_json::to_value(&operation).expect("serialize operation"); + let mut keys = std::collections::BTreeSet::new(); + collect_keys(&serialized, &mut keys); + + // Any new persisted field — signing material included — must be + // reviewed here, whatever its name. + let expected: std::collections::BTreeSet = [ + // Serde tag of the upstream `ResourceVoteChoice`. + "$type", + "contested_name", + "created_at", + "current_choice", + "failure", + "id", + "key", + "network", + "no_op_count", + "operation_id", + "requested_choice", + "status", + "target", + "targets", + "timing", + "vote_poll_id", + "voter_alias", + "voter_id", + ] + .into_iter() + .map(str::to_owned) + .collect(); + assert_eq!(keys, expected); + } + + #[test] + fn scheduled_edit_validation_rejects_past_deadline_and_unknown_contender() { + let mut contest = crate::model::contested_name::ContestedName { + normalized_contested_name: "name".to_owned(), + contestants: Some(vec![]), + locked_votes: None, + abstain_votes: None, + awarded_to: None, + end_time: Some(200), + state: crate::model::contested_name::ContestState::Ongoing, + last_updated: None, + my_votes: Default::default(), + }; + assert_eq!( + validate_dpns_schedule_edit(ResourceVoteChoice::Lock, 101, 100, &contest), + Ok(()) + ); + for time in [0, 100, 200, u64::MAX] { + assert_eq!( + validate_dpns_schedule_edit(ResourceVoteChoice::Lock, time, 100, &contest), + Err(DpnsScheduleEditValidationError::Time) + ); + } + assert_eq!( + validate_dpns_schedule_edit( + ResourceVoteChoice::TowardsIdentity(Identifier::from([1; 32])), + 101, + 100, + &contest + ), + Err(DpnsScheduleEditValidationError::Choice) + ); + contest.state = crate::model::contested_name::ContestState::Locked; + assert_eq!( + validate_dpns_schedule_edit(ResourceVoteChoice::Abstain, 101, 100, &contest), + Err(DpnsScheduleEditValidationError::Contest) + ); + } +} diff --git a/src/model/dpns_voting/operator.rs b/src/model/dpns_voting/operator.rs new file mode 100644 index 000000000..c8eab6634 --- /dev/null +++ b/src/model/dpns_voting/operator.rs @@ -0,0 +1,967 @@ +//! Operator-convenience model for masternode voting: node sets and their vote +//! weight, changes left per node, tally influence, relative schedules, the +//! attention summary, and the Masternodes segment preference. +//! +//! Pure and stateless: callers supply journal counts, proved state and +//! masternode-list membership. + +use super::{DpnsCurrentVoteState, DpnsScheduleEditValidationError, validate_dpns_schedule_time}; +use crate::model::qualified_identity::IdentityType; +use dash_sdk::dpp::dashcore::Network; +use dash_sdk::dpp::identity::TimestampMillis; +use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use dash_sdk::platform::Identifier; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; +use std::time::Duration; + +/// Which half of the Masternodes page is showing. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +pub enum MasternodesSegment { + Votes, + #[default] + Nodes, +} + +/// The segment Masternodes opens on: Votes while anything needs the operator, +/// otherwise the segment they used last (Nodes when there is no history). +pub fn opening_masternodes_segment( + attention_count: usize, + last_used: Option, +) -> MasternodesSegment { + if attention_count > 0 { + MasternodesSegment::Votes + } else { + last_used.unwrap_or_default() + } +} + +/// Vote weight of a regular masternode. +pub const MASTERNODE_VOTE_WEIGHT: u32 = 1; +/// Vote weight of an evonode (Platform counts its vote four times). +pub const EVONODE_VOTE_WEIGHT: u32 = 4; +/// Votes Platform accepts per node per contest: the first vote plus four changes. +pub const MAX_VOTES_PER_NODE_PER_CONTEST: u8 = 5; + +/// Node kind as far as vote weight is concerned. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VotingNodeKind { + Masternode, + Evonode, +} + +/// An evonode votes as one; every other loaded node votes as a regular +/// masternode. +impl From for VotingNodeKind { + fn from(identity_type: IdentityType) -> Self { + match identity_type { + IdentityType::Evonode => Self::Evonode, + IdentityType::Masternode | IdentityType::User => Self::Masternode, + } + } +} + +/// Platform vote weight of one node. +pub fn node_weight(kind: VotingNodeKind) -> u32 { + match kind { + VotingNodeKind::Masternode => MASTERNODE_VOTE_WEIGHT, + VotingNodeKind::Evonode => EVONODE_VOTE_WEIGHT, + } +} + +/// Whether a node is in the current deterministic masternode list. +/// +/// `Unknown` (list not synced yet) never excludes a node: Platform itself +/// rejects votes from nodes outside the list. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ListMembership { + Listed, + NotListed, + Unknown, +} + +/// The facts about one loaded node a node set is resolved against. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VotingNode { + /// ProTxHash identity of the masternode. + pub id: Identifier, + pub kind: VotingNodeKind, + pub has_voting_key: bool, + pub membership: ListMembership, + /// The operator's name for the node, if set. + pub alias: Option, +} + +/// The operator's persistent choice of which nodes vote. +#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] +pub enum NodeSet { + #[default] + All, + EvonodesOnly, + MasternodesOnly, + Custom(BTreeSet), +} + +/// Why a node in the set cannot vote at all. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NodeExclusion { + NoVotingKey, + NotInMasternodeList, +} + +/// A node set resolved against the loaded nodes. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ResolvedNodeSet { + /// Nodes that vote, in input order. + pub included: Vec, + /// Nodes the set selects but that cannot vote, with the reason. + pub excluded: Vec<(Identifier, NodeExclusion)>, + /// Summed vote weight of `included`. + pub weight: u32, + pub evonodes: usize, + pub masternodes: usize, +} + +impl NodeSet { + /// Whether the set selects `node`, ignoring whether it can vote. + pub fn selects(&self, node: &VotingNode) -> bool { + match self { + Self::All => true, + Self::EvonodesOnly => node.kind == VotingNodeKind::Evonode, + Self::MasternodesOnly => node.kind == VotingNodeKind::Masternode, + Self::Custom(ids) => ids.contains(&node.id), + } + } + + /// Resolve the set: selected nodes that can vote are included, the rest are + /// excluded with a typed reason. + pub fn resolve(&self, nodes: &[VotingNode]) -> ResolvedNodeSet { + let mut resolved = ResolvedNodeSet::default(); + for node in nodes.iter().filter(|node| self.selects(node)) { + if let Some(reason) = node_exclusion(node) { + resolved.excluded.push((node.id, reason)); + continue; + } + resolved.included.push(node.id); + resolved.weight += node_weight(node.kind); + match node.kind { + VotingNodeKind::Evonode => resolved.evonodes += 1, + VotingNodeKind::Masternode => resolved.masternodes += 1, + } + } + resolved + } +} + +/// Why `node` cannot vote at all, if it cannot. +pub fn node_exclusion(node: &VotingNode) -> Option { + if !node.has_voting_key { + Some(NodeExclusion::NoVotingKey) + } else if node.membership == ListMembership::NotListed { + Some(NodeExclusion::NotInMasternodeList) + } else { + None + } +} + +/// Your nodes' votes on one contest grouped by choice, heaviest first. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChoiceTally { + pub choice: ResourceVoteChoice, + pub nodes: usize, + pub weight: u32, +} + +/// Group nodes' proved choices by choice with summed vote weight; ties break +/// by node count (History). +pub fn tally_node_choices( + votes: impl IntoIterator, +) -> Vec { + let mut tallies: Vec = Vec::new(); + for (kind, choice) in votes { + match tallies.iter_mut().find(|tally| tally.choice == choice) { + Some(tally) => { + tally.nodes += 1; + tally.weight += node_weight(kind); + } + None => tallies.push(ChoiceTally { + choice, + nodes: 1, + weight: node_weight(kind), + }), + } + } + tallies.sort_by(|a, b| b.weight.cmp(&a.weight).then(b.nodes.cmp(&a.nodes))); + tallies +} + +/// One open contest as a node's detail page lists it (VOTE-FR-076). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NodeVoteRow { + pub contested_name: String, + /// `None` = not voted yet; `Some` = the proved current choice. + pub choice: Option, + /// Display name of the contender the choice goes to, when cached. + pub contender_name: Option, + /// Whether the proved state could be read at all. + pub state_known: bool, + pub changes: ChangesLeft, + pub end_time: Option, +} + +/// Vote changes a node has left on one contest. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChangesLeft { + Known(u8), + /// Platform shows a vote this device never counted. + Unknown, +} + +impl ChangesLeft { + /// Whether the node has used all of its votes on the contest. + pub fn is_exhausted(self) -> bool { + self == Self::Known(0) + } + + /// Changes left once this device saw Platform apply one more vote. + /// + /// `had_vote` is whether the node already had a vote on the contest: the + /// first vote is not a change. An unknown remainder becomes known, because + /// the device now holds its first record (see [`changes_left`]). + pub fn after_applied_vote(self, had_vote: bool) -> Self { + match self { + Self::Unknown => Self::Known(MAX_VOTES_PER_NODE_PER_CONTEST - 1), + Self::Known(left) if had_vote => Self::Known(left.saturating_sub(1)), + Self::Known(left) => Self::Known(left), + } + } +} + +/// Changes left for one node × contest. +/// +/// `confirmed_votes` is this device's durable count of confirmed votes, `None` +/// when it holds no record; `proved_vote_present` is whether Platform shows a +/// current vote. A proved vote the count does not cover was cast elsewhere, so +/// the remainder is unknown rather than guessed. +pub fn changes_left(confirmed_votes: Option, proved_vote_present: bool) -> ChangesLeft { + match confirmed_votes.unwrap_or(0) { + 0 if proved_vote_present => ChangesLeft::Unknown, + 0 => ChangesLeft::Known(MAX_VOTES_PER_NODE_PER_CONTEST - 1), + used => ChangesLeft::Known(MAX_VOTES_PER_NODE_PER_CONTEST.saturating_sub(used)), + } +} + +/// What the operator's node set can do to a contest's current leader. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Influence { + /// `leader` is ahead by `margin` weighted votes and the set's weight can + /// change who leads. + CanChangeLeader { + leader: ResourceVoteChoice, + margin: u32, + }, + /// The top contenders are tied. + Tied, + /// Lock name has as many votes as the single top request; the request + /// still wins, because Lock needs strictly more votes. + TiedWithLock, +} + +/// Influence of a node set of `node_set_weight` on a weighted tally. +/// +/// `contenders` are `(identity, weighted votes)`; abstain never wins and is +/// not passed. Lock leads only when strictly ahead of every contender. +/// Returns `None` when there is no lead to change or the set's weight is +/// below the margin. +pub fn influence( + contenders: &[(Identifier, u32)], + lock_votes: u32, + node_set_weight: u32, +) -> Option { + let mut ranked = contenders.to_vec(); + ranked.sort_by_key(|(_, votes)| std::cmp::Reverse(*votes)); + let (top_id, top_votes) = *ranked.first()?; + let runner_up = ranked.get(1).map_or(0, |(_, votes)| *votes); + if top_votes.max(lock_votes) == 0 { + return None; + } + if ranked.len() > 1 && top_votes == runner_up && lock_votes <= top_votes { + return Some(Influence::Tied); + } + if lock_votes == top_votes { + return Some(Influence::TiedWithLock); + } + let (leader, margin) = if lock_votes > top_votes { + (ResourceVoteChoice::Lock, lock_votes - top_votes) + } else { + ( + ResourceVoteChoice::TowardsIdentity(top_id), + top_votes - runner_up.max(lock_votes), + ) + }; + let leader_votes = top_votes.max(lock_votes); + (leader_votes > 0 && node_set_weight >= margin) + .then_some(Influence::CanChangeLeader { leader, margin }) +} + +/// A coarse remaining time, in the largest whole unit that fits. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TimeLeft { + Minutes(u64), + Hours(u64), + Days(u64), +} + +/// Remaining time until `deadline_ms`, or `None` once it has passed. +/// +/// Under an hour counts minutes (at least 1), under two days counts hours, +/// otherwise days. +pub fn time_left(deadline_ms: u64, now_ms: u64) -> Option { + const MINUTE: u64 = 60_000; + const HOUR: u64 = 60 * MINUTE; + const DAY: u64 = 24 * HOUR; + let remaining = deadline_ms.checked_sub(now_ms).filter(|ms| *ms > 0)?; + Some(if remaining < HOUR { + TimeLeft::Minutes((remaining / MINUTE).max(1)) + } else if remaining < 2 * DAY { + TimeLeft::Hours(remaining / HOUR) + } else { + TimeLeft::Days(remaining / DAY) + }) +} + +/// Default lead time for "When voting is about to end". +pub fn relative_schedule_preset(network: Network) -> Duration { + match network { + Network::Mainnet => Duration::from_secs(6 * 60 * 60), + _ => Duration::from_secs(10 * 60), + } +} + +/// Absolute UTC time for "`preset` before the end" of a contest ending at `end_time`. +/// +/// # Errors +/// +/// [`DpnsScheduleEditValidationError::Time`] when that moment is not in the +/// future or not before the deadline. +pub fn relative_schedule( + end_time: TimestampMillis, + preset: Duration, + now_ms: u64, +) -> Result { + let preset_ms = u64::try_from(preset.as_millis()).unwrap_or(u64::MAX); + let at = end_time + .checked_sub(preset_ms) + .ok_or(DpnsScheduleEditValidationError::Time)?; + validate_dpns_schedule_time(at, now_ms, Some(end_time))?; + Ok(at) +} + +/// Whether a background contest + vote-state refresh should be dispatched. +/// +/// Due once `interval` has passed since both the last completed refresh and +/// the last dispatch (so an in-flight refresh is not re-dispatched). All times +/// are Unix milliseconds; `None` means never. +pub fn background_refresh_due( + last_completed_ms: Option, + last_dispatched_ms: Option, + now_ms: u64, + interval: Duration, +) -> bool { + let interval = u64::try_from(interval.as_millis()).unwrap_or(u64::MAX); + let elapsed = |at: Option| at.is_none_or(|at| now_ms.saturating_sub(at) >= interval); + elapsed(last_completed_ms) && elapsed(last_dispatched_ms) +} + +/// How often contests and node vote state refresh in the background. +pub fn background_refresh_interval(network: Network) -> Duration { + match network { + Network::Mainnet => Duration::from_secs(30 * 60), + _ => Duration::from_secs(3 * 60), + } +} + +/// How soon a background refresh that failed, or left a contest unread or a +/// node's vote state unchecked, is tried again instead of waiting a whole +/// interval. +pub fn background_refresh_retry_delay(network: Network) -> Duration { + background_refresh_interval(network) / 6 +} + +/// Whether the refresh dispatched at `dispatched_ms` ended without completing: +/// a complete refresh stamps a completion time at or after its dispatch. +pub fn background_refresh_incomplete(last_completed_ms: Option, dispatched_ms: u64) -> bool { + last_completed_ms.is_none_or(|completed| completed < dispatched_ms) +} + +/// Oldest proof, in ms, that may decide what is sent: it authorises a +/// submission, and it alone may conclude that a vote is already in place. +pub const VOTE_STATE_DECISION_MAX_AGE_MS: u64 = 120_000; + +/// Whether proof read at `proved_at_ms` is still fresh enough to decide that +/// nothing needs sending. Older proof may be shown, but the decision then +/// belongs to the backend's own fresh proof. +pub fn vote_proof_can_decide(proved_at_ms: Option, now_ms: u64) -> bool { + proved_at_ms + .is_some_and(|proved_at| now_ms.saturating_sub(proved_at) <= VOTE_STATE_DECISION_MAX_AGE_MS) +} + +/// How long a proved vote-state snapshot stays valid for display and for the +/// attention signal: two refresh intervals, so one late or failed background +/// refresh does not blank them. Authorising a submission needs fresher proof. +pub fn vote_state_display_max_age(network: Network) -> Duration { + background_refresh_interval(network) * 2 +} + +/// Whether a contest still needs a decision from at least one node-set node. +/// +/// Each item is one node's proved state, whether its target is locked by an +/// unresolved operation, and its changes left. A node needs to decide when it +/// has proved "not voted", holds no lock and still has votes. +pub fn contest_needs_decision( + nodes: impl IntoIterator, +) -> bool { + nodes.into_iter().any(|(state, locked, changes)| { + state == DpnsCurrentVoteState::Available(None) && !locked && !changes.is_exhausted() + }) +} + +/// One open contest as the attention summary sees it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ContestAttention { + pub name: String, + pub end_time: Option, + pub needs_decision: bool, +} + +/// Names listed in the attention chip tooltip. +pub const ATTENTION_TOOLTIP_NAMES: usize = 3; + +/// What needs the operator, shown outside the Votes page. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct AttentionSummary { + /// Open contests a node-set node still has to decide on. + pub needs_decision: usize, + /// Earliest deadline among those contests. + pub soonest_end: Option, + /// Targets still `Unconfirmed`. + pub unresolved: usize, + /// Up to [`ATTENTION_TOOLTIP_NAMES`] soonest-ending names needing a decision. + pub soonest_names: Vec<(String, Option)>, + /// Node-set nodes able to vote; the chip is hidden when there are none. + pub voting_nodes: usize, +} + +impl AttentionSummary { + /// Build the summary from open contests and the unresolved-target count. + pub fn new(contests: &[ContestAttention], unresolved: usize, voting_nodes: usize) -> Self { + let mut pending: Vec<&ContestAttention> = + contests.iter().filter(|c| c.needs_decision).collect(); + pending.sort_by_key(|contest| contest.end_time.unwrap_or(u64::MAX)); + Self { + needs_decision: pending.len(), + soonest_end: pending.iter().filter_map(|c| c.end_time).min(), + unresolved, + soonest_names: pending + .iter() + .take(ATTENTION_TOOLTIP_NAMES) + .map(|contest| (contest.name.clone(), contest.end_time)) + .collect(), + voting_nodes, + } + } + + /// Count shown on the Masternodes nav badge. + pub fn badge_count(&self) -> usize { + self.needs_decision + self.unresolved + } + + /// Whether the soonest deadline falls within `urgency_window` of `now_ms`. + pub fn is_urgent(&self, now_ms: u64, urgency_window: Duration) -> bool { + let window = u64::try_from(urgency_window.as_millis()).unwrap_or(u64::MAX); + self.soonest_end + .is_some_and(|end| end > now_ms && end - now_ms <= window) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn node(byte: u8, kind: VotingNodeKind, key: bool, membership: ListMembership) -> VotingNode { + VotingNode { + id: Identifier::from([byte; 32]), + kind, + has_voting_key: key, + membership, + alias: None, + } + } + + fn fleet() -> Vec { + vec![ + node(1, VotingNodeKind::Evonode, true, ListMembership::Listed), + node(2, VotingNodeKind::Masternode, true, ListMembership::Listed), + node(3, VotingNodeKind::Masternode, false, ListMembership::Listed), + node(4, VotingNodeKind::Evonode, true, ListMembership::NotListed), + node(5, VotingNodeKind::Masternode, true, ListMembership::Unknown), + ] + } + + #[test] + fn segment_opens_on_votes_only_while_something_needs_attention() { + assert_eq!( + opening_masternodes_segment(2, Some(MasternodesSegment::Nodes)), + MasternodesSegment::Votes + ); + assert_eq!( + opening_masternodes_segment(0, Some(MasternodesSegment::Nodes)), + MasternodesSegment::Nodes + ); + assert_eq!( + opening_masternodes_segment(0, Some(MasternodesSegment::Votes)), + MasternodesSegment::Votes + ); + assert_eq!( + opening_masternodes_segment(0, None), + MasternodesSegment::Nodes + ); + } + + #[test] + fn evonodes_weigh_four_masternodes_one() { + assert_eq!(node_weight(VotingNodeKind::Evonode), 4); + assert_eq!(node_weight(VotingNodeKind::Masternode), 1); + } + + #[test] + fn all_nodes_excludes_keyless_and_unlisted_nodes_with_reasons() { + let resolved = NodeSet::All.resolve(&fleet()); + assert_eq!( + resolved.included, + vec![ + Identifier::from([1; 32]), + Identifier::from([2; 32]), + Identifier::from([5; 32]) + ], + "unknown membership fails open" + ); + assert_eq!( + resolved.excluded, + vec![ + (Identifier::from([3; 32]), NodeExclusion::NoVotingKey), + ( + Identifier::from([4; 32]), + NodeExclusion::NotInMasternodeList + ), + ] + ); + assert_eq!(resolved.weight, 4 + 1 + 1); + assert_eq!((resolved.evonodes, resolved.masternodes), (1, 2)); + } + + #[test] + fn typed_node_sets_select_by_kind_and_custom_by_id() { + let nodes = fleet(); + assert_eq!( + NodeSet::EvonodesOnly.resolve(&nodes).included, + vec![Identifier::from([1; 32])] + ); + assert_eq!(NodeSet::EvonodesOnly.resolve(&nodes).weight, 4); + assert_eq!( + NodeSet::MasternodesOnly.resolve(&nodes).included, + vec![Identifier::from([2; 32]), Identifier::from([5; 32])] + ); + let custom = NodeSet::Custom(BTreeSet::from([ + Identifier::from([2; 32]), + Identifier::from([4; 32]), + ])); + let resolved = custom.resolve(&nodes); + assert_eq!(resolved.included, vec![Identifier::from([2; 32])]); + assert_eq!( + resolved.excluded, + vec![( + Identifier::from([4; 32]), + NodeExclusion::NotInMasternodeList + )] + ); + } + + /// VOTE-TC-090 (unit half): the preference round-trips through the + /// persisted encoding unchanged. + #[test] + fn node_set_preference_round_trips() { + for set in [ + NodeSet::All, + NodeSet::EvonodesOnly, + NodeSet::MasternodesOnly, + NodeSet::Custom(BTreeSet::from([Identifier::from([9; 32])])), + ] { + let bytes = + bincode::serde::encode_to_vec(&set, bincode::config::standard()).expect("encode"); + let (decoded, _): (NodeSet, usize) = + bincode::serde::decode_from_slice(&bytes, bincode::config::standard()) + .expect("decode"); + assert_eq!(decoded, set); + } + } + + /// VOTE-TC-094: three confirmed votes leave two changes. + #[test] + fn changes_left_counts_down_from_the_journal() { + assert_eq!(changes_left(Some(3), true), ChangesLeft::Known(2)); + assert_eq!(changes_left(Some(1), true), ChangesLeft::Known(4)); + assert_eq!(changes_left(None, false), ChangesLeft::Known(4)); + assert_eq!(changes_left(Some(0), false), ChangesLeft::Known(4)); + } + + /// VOTE-TC-095: a proved vote the device never counted is unknown. + #[test] + fn uncounted_proved_vote_leaves_changes_unknown() { + assert_eq!(changes_left(None, true), ChangesLeft::Unknown); + assert_eq!(changes_left(Some(0), true), ChangesLeft::Unknown); + } + + /// VOTE-TC-096 (model half): five confirmed votes exhaust the node. + #[test] + fn five_votes_exhaust_a_node() { + assert!(changes_left(Some(5), true).is_exhausted()); + assert!(changes_left(Some(9), true).is_exhausted()); + assert!(!changes_left(Some(4), true).is_exhausted()); + assert!(!ChangesLeft::Unknown.is_exhausted()); + } + + /// VOTE-TC-092: influence shows when the set's weight reaches the margin. + /// History aggregate: choices group with weight, heaviest first. + #[test] + fn node_choices_tally_by_weight() { + let zed = ResourceVoteChoice::TowardsIdentity(Identifier::from([9; 32])); + let tallies = tally_node_choices([ + (VotingNodeKind::Masternode, ResourceVoteChoice::Lock), + (VotingNodeKind::Masternode, ResourceVoteChoice::Lock), + (VotingNodeKind::Evonode, zed), + (VotingNodeKind::Masternode, zed), + ]); + assert_eq!( + tallies, + vec![ + ChoiceTally { + choice: zed, + nodes: 2, + weight: 5 + }, + ChoiceTally { + choice: ResourceVoteChoice::Lock, + nodes: 2, + weight: 2 + }, + ] + ); + assert!(tally_node_choices([]).is_empty()); + } + + #[test] + fn influence_needs_weight_at_least_the_margin() { + let zed = Identifier::from([1; 32]); + let amy = Identifier::from([2; 32]); + let tally = [(zed, 20), (amy, 14)]; + assert_eq!( + influence(&tally, 0, 51), + Some(Influence::CanChangeLeader { + leader: ResourceVoteChoice::TowardsIdentity(zed), + margin: 6 + }) + ); + assert_eq!( + influence(&tally, 0, 6), + Some(Influence::CanChangeLeader { + leader: ResourceVoteChoice::TowardsIdentity(zed), + margin: 6 + }) + ); + assert_eq!(influence(&tally, 0, 5), None); + } + + #[test] + fn lock_leads_only_when_strictly_ahead() { + let zed = Identifier::from([1; 32]); + assert_eq!( + influence(&[(zed, 10)], 12, 4), + Some(Influence::CanChangeLeader { + leader: ResourceVoteChoice::Lock, + margin: 2 + }) + ); + assert_eq!( + influence(&[(zed, 10)], 7, 4), + Some(Influence::CanChangeLeader { + leader: ResourceVoteChoice::TowardsIdentity(zed), + margin: 3 + }) + ); + } + + /// Lock equal to the single top request is a Lock tie, never a 0-vote lead. + #[test] + fn lock_equal_to_the_leader_is_a_lock_tie() { + let zed = Identifier::from([1; 32]); + let amy = Identifier::from([2; 32]); + assert_eq!( + influence(&[(zed, 5), (amy, 3)], 5, 4), + Some(Influence::TiedWithLock) + ); + assert_eq!(influence(&[(zed, 5)], 5, 4), Some(Influence::TiedWithLock)); + } + + /// VOTE-TC-093 (model half): equal top contenders are a tie. + #[test] + fn equal_top_contenders_tie() { + let tally = [ + (Identifier::from([1; 32]), 8), + (Identifier::from([2; 32]), 8), + ]; + assert_eq!(influence(&tally, 3, 0), Some(Influence::Tied)); + assert_eq!( + influence(&tally, 8, 0), + Some(Influence::Tied), + "a two-request tie stays a request tie when Lock matches it" + ); + assert_eq!( + influence(&[(tally[0].0, 0), (tally[1].0, 0)], 0, 4), + None, + "a contest with no votes has no tie line" + ); + assert_eq!( + influence(&[(Identifier::from([1; 32]), 0)], 0, 10), + None, + "an empty tally has no lead" + ); + assert_eq!(influence(&[], 5, 10), None); + } + + /// VOTE-TC-067 / VOTE-TC-068. + #[test] + fn relative_schedule_uses_the_network_preset() { + let end = 100 * 60 * 60 * 1000; + let mainnet = + relative_schedule(end, relative_schedule_preset(Network::Mainnet), 0).expect("mainnet"); + assert_eq!(mainnet, end - 6 * 60 * 60 * 1000); + let testnet = + relative_schedule(end, relative_schedule_preset(Network::Testnet), 0).expect("testnet"); + assert_eq!(testnet, end - 10 * 60 * 1000); + } + + #[test] + fn relative_schedule_rejects_a_moment_already_passed() { + let preset = Duration::from_secs(600); + assert_eq!( + relative_schedule(1_000_000, preset, 500_000), + Err(DpnsScheduleEditValidationError::Time) + ); + assert_eq!( + relative_schedule(1_000, preset, 0), + Err(DpnsScheduleEditValidationError::Time), + "a preset longer than the whole contest underflows" + ); + } + + /// VOTE-TC-104 (cadence half). + #[test] + fn background_refresh_is_slower_on_mainnet() { + assert_eq!( + background_refresh_interval(Network::Mainnet), + Duration::from_secs(1800) + ); + assert_eq!( + background_refresh_interval(Network::Testnet), + Duration::from_secs(180) + ); + assert_eq!( + background_refresh_interval(Network::Devnet), + Duration::from_secs(180) + ); + } + + /// The live card must agree with what a recount would show after the vote. + #[test] + fn an_applied_vote_updates_changes_left_like_a_recount() { + // (votes counted before, vote present before) + for (counted, had_vote) in [(0, false), (0, true), (1, true), (2, true), (5, true)] { + let before = changes_left(Some(counted), had_vote); + assert_eq!( + before.after_applied_vote(had_vote), + changes_left(Some(counted + 1), true), + "counted {counted}, had_vote {had_vote}" + ); + } + assert_eq!( + ChangesLeft::Unknown.after_applied_vote(true), + ChangesLeft::Known(4), + "the device has a record now, so the remainder is no longer unknown" + ); + } + + #[test] + fn only_proof_within_the_submission_cap_can_decide_a_vote_is_in_place() { + let now = 10_000_000; + assert!(vote_proof_can_decide(Some(now), now)); + assert!(vote_proof_can_decide( + Some(now - VOTE_STATE_DECISION_MAX_AGE_MS), + now + )); + assert!(!vote_proof_can_decide( + Some(now - VOTE_STATE_DECISION_MAX_AGE_MS - 1), + now + )); + assert!(!vote_proof_can_decide(None, now)); + assert!( + Duration::from_millis(VOTE_STATE_DECISION_MAX_AGE_MS) + < vote_state_display_max_age(Network::Testnet), + "display keeps proof that may no longer decide" + ); + } + + #[test] + fn displayed_vote_state_outlives_one_missed_background_refresh() { + for network in [Network::Mainnet, Network::Testnet, Network::Devnet] { + assert_eq!( + vote_state_display_max_age(network), + background_refresh_interval(network) * 2 + ); + } + } + + #[test] + fn an_incomplete_background_refresh_is_retried_well_before_the_next_interval() { + assert_eq!( + background_refresh_retry_delay(Network::Mainnet), + Duration::from_secs(300) + ); + assert_eq!( + background_refresh_retry_delay(Network::Testnet), + Duration::from_secs(30) + ); + assert!(background_refresh_incomplete(None, 1_000)); + assert!( + background_refresh_incomplete(Some(999), 1_000), + "an older completion stamp belongs to an earlier refresh" + ); + assert!(!background_refresh_incomplete(Some(1_000), 1_000)); + assert!(!background_refresh_incomplete(Some(5_000), 1_000)); + } + + #[test] + fn time_left_uses_the_largest_whole_unit() { + let minute = 60_000; + assert_eq!(time_left(10, 10), None); + assert_eq!(time_left(5, 10), None); + assert_eq!(time_left(30_000, 0), Some(TimeLeft::Minutes(1))); + assert_eq!(time_left(12 * minute, 0), Some(TimeLeft::Minutes(12))); + assert_eq!(time_left(3 * 60 * minute + 5, 0), Some(TimeLeft::Hours(3))); + assert_eq!(time_left(47 * 60 * minute, 0), Some(TimeLeft::Hours(47))); + assert_eq!(time_left(4 * 24 * 60 * minute, 0), Some(TimeLeft::Days(4))); + } + + /// VOTE-TC-104 (dispatch half): due after the interval since both the last + /// completion and the last dispatch. + #[test] + fn background_refresh_waits_for_completion_and_dispatch() { + let interval = Duration::from_secs(180); + let ms = 180_000; + assert!(background_refresh_due(None, None, 0, interval)); + assert!(!background_refresh_due( + Some(1_000), + None, + 1_000 + ms - 1, + interval + )); + assert!(background_refresh_due( + Some(1_000), + None, + 1_000 + ms, + interval + )); + assert!( + !background_refresh_due(Some(0), Some(500_000), 600_000, interval), + "an in-flight refresh is not dispatched again" + ); + assert!(background_refresh_due( + Some(0), + Some(500_000), + 500_000 + ms, + interval + )); + } + + #[test] + fn a_contest_needs_a_decision_while_an_unlocked_node_has_not_voted() { + let open = ( + DpnsCurrentVoteState::Available(None), + false, + ChangesLeft::Known(4), + ); + let voted = ( + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)), + false, + ChangesLeft::Known(3), + ); + assert!(contest_needs_decision([voted, open])); + assert!(!contest_needs_decision([voted])); + assert!(!contest_needs_decision([( + DpnsCurrentVoteState::Available(None), + true, + ChangesLeft::Known(4) + )])); + assert!(!contest_needs_decision([( + DpnsCurrentVoteState::Unavailable, + false, + ChangesLeft::Known(4) + )])); + } + + #[test] + fn attention_summary_counts_and_orders_by_deadline() { + let contest = |name: &str, end: Option, needs: bool| ContestAttention { + name: name.to_owned(), + end_time: end, + needs_decision: needs, + }; + let summary = AttentionSummary::new( + &[ + contest("late", Some(900), true), + contest("done", Some(10), false), + contest("soon", Some(100), true), + contest("unknown", None, true), + contest("mid", Some(500), true), + ], + 2, + 3, + ); + assert_eq!(summary.needs_decision, 4); + assert_eq!(summary.voting_nodes, 3); + assert_eq!(summary.unresolved, 2); + assert_eq!(summary.badge_count(), 6); + assert_eq!(summary.soonest_end, Some(100)); + assert_eq!( + summary + .soonest_names + .iter() + .map(|(name, _)| name.as_str()) + .collect::>(), + vec!["soon", "mid", "late"] + ); + } + + #[test] + fn urgency_is_within_the_window_and_before_the_deadline() { + let summary = AttentionSummary { + needs_decision: 1, + soonest_end: Some(10_000), + ..AttentionSummary::default() + }; + assert!(summary.is_urgent(9_000, Duration::from_secs(1))); + assert!(!summary.is_urgent(8_000, Duration::from_secs(1))); + assert!(!summary.is_urgent(10_000, Duration::from_secs(1))); + assert!(!AttentionSummary::default().is_urgent(0, Duration::from_secs(1))); + } +} diff --git a/src/model/dpns_voting/progress.rs b/src/model/dpns_voting/progress.rs new file mode 100644 index 000000000..60c6832de --- /dev/null +++ b/src/model/dpns_voting/progress.rs @@ -0,0 +1,406 @@ +//! What the vote progress drawer and the `Needs attention` row show +//! (VOTE-FR-083/084). Pure: callers pass journal operations and the clock. + +use super::{ + DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTargetStatus, VoteTiming, + authoritative_dpns_vote_outcomes, dpns_schedule_is_overdue, +}; +use std::collections::BTreeSet; + +/// Where one sent target stands, as the drawer groups it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ProgressPhase { + /// Queued, submitting or confirming. + Sending, + /// Sent, result not confirmed yet; DET keeps checking. + Checking, + Confirmed, + /// Rejected, not applied, or failed before submission. + Failed, +} + +/// The drawer phase of an outcome; `None` for scheduled or cancelled targets, +/// which belong to the Scheduled view. +pub fn progress_phase(outcome: &DpnsVoteOutcome) -> Option { + match outcome.status { + DpnsVoteTargetStatus::Queued + | DpnsVoteTargetStatus::Submitting + | DpnsVoteTargetStatus::Confirming => Some(ProgressPhase::Sending), + DpnsVoteTargetStatus::Unconfirmed => Some(ProgressPhase::Checking), + DpnsVoteTargetStatus::Confirmed => Some(ProgressPhase::Confirmed), + DpnsVoteTargetStatus::Rejected + | DpnsVoteTargetStatus::FailedBeforeSubmission + | DpnsVoteTargetStatus::NotApplied => Some(ProgressPhase::Failed), + DpnsVoteTargetStatus::Scheduled | DpnsVoteTargetStatus::Cancelled => None, + } +} + +/// Header counts of the drawer. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct ProgressCounts { + pub total: usize, + pub confirmed: usize, + pub failed: usize, + pub sending: usize, + pub checking: usize, +} + +impl ProgressCounts { + /// Settled targets: confirmed or failed. + pub fn done(&self) -> usize { + self.confirmed + self.failed + } + + /// Whether anything is still on its way or being checked. + pub fn in_flight(&self) -> bool { + self.sending + self.checking > 0 + } +} + +/// Count the drawer phases across `operations`. +pub fn progress_counts<'a>( + operations: impl IntoIterator, +) -> ProgressCounts { + let mut counts = ProgressCounts::default(); + for phase in operations + .into_iter() + .flat_map(|operation| &operation.targets) + .filter_map(progress_phase) + { + counts.total += 1; + match phase { + ProgressPhase::Sending => counts.sending += 1, + ProgressPhase::Checking => counts.checking += 1, + ProgressPhase::Confirmed => counts.confirmed += 1, + ProgressPhase::Failed => counts.failed += 1, + } + } + counts +} + +/// When a target was sent: its scheduled time for a scheduled vote, otherwise +/// when its operation was created. A vote scheduled in an earlier session +/// therefore counts as recent once it runs in this one, and so does a vote +/// from an earlier session that restart recovery stopped or sent again. +fn sent_at(operation: &DpnsVoteOperation, outcome: &DpnsVoteOutcome) -> u64 { + let sent = match outcome.target.timing { + VoteTiming::Scheduled(at) => at.max(operation.created_at), + VoteTiming::Now => operation.created_at, + }; + outcome + .recovered_at_ms + .map_or(sent, |recovered| recovered.max(sent)) +} + +/// Operations the drawer lists: anything still in flight, plus operations +/// with a target sent since `since_ms` that the operator has not dismissed. +pub fn drawer_operations<'a>( + operations: impl IntoIterator, + since_ms: u64, + dismissed: &BTreeSet, +) -> Vec<&'a DpnsVoteOperation> { + operations + .into_iter() + .filter(|operation| { + let counts = progress_counts([*operation]); + if counts.total == 0 { + return false; + } + counts.in_flight() + || (!dismissed.contains(&operation.id) + && operation.targets.iter().any(|outcome| { + progress_phase(outcome).is_some() && sent_at(operation, outcome) >= since_ms + })) + }) + .collect() +} + +/// What the `Needs attention` row summarizes (VOTE-FR-084). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct NeedsAttention { + pub checking: usize, + pub failed: usize, + pub missed_schedules: usize, +} + +impl NeedsAttention { + pub fn is_empty(&self) -> bool { + self.checking + self.failed + self.missed_schedules == 0 + } +} + +/// Targets that need the operator: unconfirmed, failed, or schedules missed. +/// +/// A failure counts only while it is the latest outcome for its target, the +/// target was sent since `since_ms` and the operator has not dismissed it in +/// the progress drawer. Unconfirmed and missed targets still hold their lock +/// and always count. +pub fn needs_attention( + operations: &[DpnsVoteOperation], + since_ms: u64, + dismissed: &BTreeSet, + now_ms: u64, +) -> NeedsAttention { + let mut attention = NeedsAttention::default(); + for (operation, outcome) in authoritative_dpns_vote_outcomes(operations, |_| true).into_values() + { + match (outcome.status, outcome.target.timing) { + (DpnsVoteTargetStatus::Unconfirmed, _) => attention.checking += 1, + (DpnsVoteTargetStatus::Scheduled, VoteTiming::Scheduled(at)) + if dpns_schedule_is_overdue(at, now_ms) => + { + attention.missed_schedules += 1; + } + _ if sent_at(operation, outcome) >= since_ms + && !dismissed.contains(&operation.id) + && progress_phase(outcome) == Some(ProgressPhase::Failed) => + { + attention.failed += 1; + } + _ => {} + } + } + attention +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::dpns_voting::{DpnsVoteTarget, DpnsVoteTargetKey}; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; + use dash_sdk::platform::Identifier; + + fn operation( + created_at: u64, + statuses: &[(DpnsVoteTargetStatus, VoteTiming)], + ) -> DpnsVoteOperation { + let mut operation = DpnsVoteOperation::new( + DpnsVoteOperationId::from_bytes((created_at as u128).to_be_bytes()), + created_at, + statuses + .iter() + .enumerate() + .map(|(index, (_, timing))| DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([index as u8; 32]), + vote_poll_id: Identifier::from([9; 32]), + }, + voter_alias: None, + contested_name: "alice".to_owned(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: *timing, + }) + .collect(), + ); + for (outcome, (status, _)) in operation.targets.iter_mut().zip(statuses) { + outcome.status = *status; + } + operation + } + + use DpnsVoteTargetStatus as S; + const NOW: VoteTiming = VoteTiming::Now; + + /// VOTE-TC-101: the drawer header counts done, sending and checking. + #[test] + fn counts_group_targets_by_phase_and_skip_schedules() { + let op = operation( + 0, + &[ + (S::Confirmed, NOW), + (S::Rejected, NOW), + (S::Submitting, NOW), + (S::Queued, NOW), + (S::Unconfirmed, NOW), + (S::Scheduled, VoteTiming::Scheduled(10)), + (S::Cancelled, VoteTiming::Scheduled(10)), + ], + ); + let counts = progress_counts([&op]); + assert_eq!( + counts, + ProgressCounts { + total: 5, + confirmed: 1, + failed: 1, + sending: 2, + checking: 1, + } + ); + assert_eq!(counts.done(), 2); + assert!(counts.in_flight()); + } + + /// In-flight operations always show; settled ones only from this session + /// and until dismissed; schedule-only operations never. + #[test] + fn drawer_lists_in_flight_and_recent_undismissed_operations() { + let old_in_flight = operation(1, &[(S::Unconfirmed, NOW)]); + let old_settled = operation(2, &[(S::Confirmed, NOW)]); + let recent_settled = operation(100, &[(S::Confirmed, NOW)]); + let dismissed_settled = operation(101, &[(S::Rejected, NOW)]); + let schedule_only = operation(102, &[(S::Scheduled, VoteTiming::Scheduled(500))]); + let operations = vec![ + old_in_flight.clone(), + old_settled, + recent_settled.clone(), + dismissed_settled.clone(), + schedule_only, + ]; + let dismissed = BTreeSet::from([dismissed_settled.id, old_in_flight.id]); + let shown: Vec<_> = drawer_operations(&operations, 50, &dismissed) + .into_iter() + .map(|operation| operation.id) + .collect(); + assert_eq!(shown, vec![old_in_flight.id, recent_settled.id]); + } + + /// VOTE-TC-102: unconfirmed, failed and missed targets need attention. + #[test] + fn needs_attention_counts_each_kind() { + let operations = vec![ + operation( + 100, + &[ + (S::Unconfirmed, NOW), + (S::FailedBeforeSubmission, NOW), + (S::Scheduled, VoteTiming::Scheduled(1_000)), + (S::Confirmed, NOW), + ], + ), + operation(1, &[(S::Rejected, NOW)]), + ]; + let attention = needs_attention(&operations, 50, &BTreeSet::new(), 1_000 + 121_000); + assert_eq!( + attention, + NeedsAttention { + checking: 1, + failed: 1, + missed_schedules: 1, + } + ); + assert!(needs_attention(&[], 0, &BTreeSet::new(), 0).is_empty()); + } + + /// A failure stops needing attention once the same target is recast + /// successfully, or once its operation is dismissed in the drawer. + #[test] + fn failures_clear_after_a_recast_or_dismiss() { + let failed = operation(100, &[(S::FailedBeforeSubmission, NOW)]); + let recast = operation(200, &[(S::Confirmed, NOW)]); + let none = BTreeSet::new(); + assert_eq!( + needs_attention(std::slice::from_ref(&failed), 0, &none, 300).failed, + 1 + ); + assert_eq!( + needs_attention(&[failed.clone(), recast], 0, &none, 300).failed, + 0 + ); + let dismissed = BTreeSet::from([failed.id]); + assert_eq!(needs_attention(&[failed], 0, &dismissed, 300).failed, 0); + } + + /// A scheduled vote is created long before it runs, usually in an earlier + /// session. Its rejection must still reach the operator when it runs now. + #[test] + fn a_vote_scheduled_in_an_earlier_session_is_surfaced_when_it_fails_now() { + let session_start = 1_000; + let due_this_session = VoteTiming::Scheduled(session_start + 500); + let due_before_session = VoteTiming::Scheduled(session_start - 500); + let rejected_now = operation(10, &[(S::Rejected, due_this_session)]); + let ended_now = operation( + 11, + &[ + (S::FailedBeforeSubmission, due_this_session), + (S::Scheduled, VoteTiming::Scheduled(session_start + 900_000)), + ], + ); + let stale = operation(12, &[(S::Rejected, due_before_session)]); + let mut operations = vec![rejected_now.clone(), ended_now.clone(), stale]; + // Distinct nodes, so no outcome supersedes another. + for (node, outcome) in operations + .iter_mut() + .flat_map(|operation| &mut operation.targets) + .enumerate() + { + outcome.target.key.voter_id = Identifier::from([node as u8 + 10; 32]); + } + let none = BTreeSet::new(); + + let now = session_start + 1_000; + assert_eq!( + needs_attention(&operations, session_start, &none, now), + NeedsAttention { + checking: 0, + failed: 2, + missed_schedules: 0, + } + ); + let shown: Vec<_> = drawer_operations(&operations, session_start, &none) + .into_iter() + .map(|operation| operation.id) + .collect(); + assert_eq!(shown, vec![rejected_now.id, ended_now.id]); + + let dismissed = BTreeSet::from([rejected_now.id, ended_now.id]); + assert!(needs_attention(&operations, session_start, &dismissed, now).is_empty()); + assert!(drawer_operations(&operations, session_start, &dismissed).is_empty()); + } + + /// An immediate vote left over from an earlier session and settled after + /// restart recovery picked it up is this session's news: the operator + /// must see it as not submitted and be able to review it again. + #[test] + fn a_vote_recovered_after_a_restart_is_surfaced_in_the_new_session() { + let session_start = 1_000; + let mut stopped = operation(10, &[(S::FailedBeforeSubmission, NOW)]); + stopped.targets[0].recovered_at_ms = Some(session_start + 60); + let mut old_failure = operation(11, &[(S::FailedBeforeSubmission, NOW)]); + old_failure.targets[0].target.key.voter_id = Identifier::from([42; 32]); + let operations = vec![stopped.clone(), old_failure]; + let none = BTreeSet::new(); + + assert_eq!( + needs_attention(&operations, session_start, &none, session_start + 100).failed, + 1 + ); + let shown: Vec<_> = drawer_operations(&operations, session_start, &none) + .into_iter() + .map(|operation| operation.id) + .collect(); + assert_eq!(shown, vec![stopped.id]); + + let later_session = session_start + 10_000; + assert!(needs_attention(&operations, later_session, &none, later_session).is_empty()); + assert!(drawer_operations(&operations, later_session, &none).is_empty()); + } + + #[test] + fn attention_uses_authority_for_equal_timestamps_and_lock_holders() { + let mut failed = operation(100, &[(S::Rejected, NOW)]); + failed.id = DpnsVoteOperationId([1; 16]); + failed.targets[0].operation_id = failed.id; + let mut confirmed = operation(100, &[(S::Confirmed, NOW)]); + confirmed.id = DpnsVoteOperationId([2; 16]); + confirmed.targets[0].operation_id = confirmed.id; + for operations in [ + vec![failed.clone(), confirmed.clone()], + vec![confirmed, failed.clone()], + ] { + assert!(needs_attention(&operations, 0, &BTreeSet::new(), 300).is_empty()); + } + let checking = operation(50, &[(S::Unconfirmed, NOW)]); + assert_eq!( + needs_attention(&[failed, checking], 0, &BTreeSet::new(), 300), + NeedsAttention { + checking: 1, + failed: 0, + missed_schedules: 0 + } + ); + } +} diff --git a/src/model/fee_estimation.rs b/src/model/fee_estimation.rs index 8fd9ea0bd..6c9a988b3 100644 --- a/src/model/fee_estimation.rs +++ b/src/model/fee_estimation.rs @@ -741,6 +741,17 @@ impl PlatformFeeEstimator { } } +/// Community vote fee for registering a contested username, in credits. +/// +/// Read from the protocol's vote-resolution fund (0.2 DASH before protocol 14, +/// 0.1 DASH from 14). Platform never returns it, whatever the vote outcome. +pub fn contest_fee_credits(platform_version: &PlatformVersion) -> Credits { + platform_version + .fee_version + .vote_resolution_fund_fees + .contested_document_vote_resolution_fund_required_amount +} + /// Credits per DASH: 1 DASH = 10^DASH_DECIMAL_PLACES credits (100 billion). pub const CREDITS_PER_DASH: u64 = 10u64.pow(DASH_DECIMAL_PLACES as u32); @@ -1101,6 +1112,15 @@ pub fn shield_from_balance_fee_headroom( mod tests { use super::*; + #[test] + fn contest_fee_follows_protocol_version() { + // USR-TC-005 + let pv13 = PlatformVersion::get(13).expect("PV13"); + let pv14 = PlatformVersion::get(14).expect("PV14"); + assert_eq!(contest_fee_credits(pv13), 20_000_000_000); + assert_eq!(contest_fee_credits(pv14), 10_000_000_000); + } + #[test] fn test_credit_transfer_estimate() { let estimator = PlatformFeeEstimator::new(); diff --git a/src/model/identity_name.rs b/src/model/identity_name.rs index fda2c5bd9..553ff979c 100644 --- a/src/model/identity_name.rs +++ b/src/model/identity_name.rs @@ -1,5 +1,15 @@ //! Shared identity label resolution. +/// Resolve a masternode alias or its shortened hexadecimal ProTxHash. +pub fn masternode_label(id: dash_sdk::platform::Identifier, alias: Option<&str>) -> String { + alias + .filter(|alias| !alias.trim().is_empty()) + .map(str::to_owned) + .unwrap_or_else(|| { + shorten_id(&id.to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Hex)) + }) +} + /// Resolve a profile name, username, or shortened identity identifier. pub fn display_label(display_name: Option<&str>, username: Option<&str>, id: &str) -> String { [display_name, username] @@ -33,7 +43,7 @@ pub(super) fn is_safe_display_character(character: char) -> bool { ) } -/// Shorten a Base58 identifier while preserving both ends. +/// Shorten an identifier while preserving both ends. pub fn shorten_id(id: &str) -> String { let chars: Vec = id.chars().collect(); if chars.len() <= 10 { diff --git a/src/model/mod.rs b/src/model/mod.rs index b4bcef028..19fe3747e 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -9,6 +9,9 @@ pub mod dashpay_derivation; pub(crate) mod data_migration; pub mod derived_identity_key; pub mod dpns; +pub mod dpns_usernames; +pub(crate) mod dpns_vote_schedule; +pub mod dpns_voting; pub mod fee_estimation; pub mod grovestark_prover; pub mod identity_discovery; diff --git a/src/model/qualified_identity/mod.rs b/src/model/qualified_identity/mod.rs index 1840bd494..31ec7f1b4 100644 --- a/src/model/qualified_identity/mod.rs +++ b/src/model/qualified_identity/mod.rs @@ -606,6 +606,14 @@ impl QualifiedIdentity { .map_err(|e| format!("Failed to decode QualifiedIdentity: {}", e)) } + /// Whether a voter identity and a matching signing-key reference are loaded. + /// Secret availability is checked by the signer at submission time. + pub fn can_cast_masternode_vote(&self) -> bool { + self.associated_voter_identity + .as_ref() + .is_some_and(|(_, key)| self.can_sign_with(key)) + } + /// Which masternode/evonode key roles are loaded for this identity. /// /// Voting presence is signalled by a loaded voter identity @@ -1070,11 +1078,27 @@ impl QualifiedIdentity { } /// Resolve the profile name with username and identifier fallbacks. + /// + /// The username is the first registered name; hydrated identities list + /// their main username first. Prefer + /// [`Self::display_name_label_with_username`] when the main username is known. pub fn display_name_label(&self, display_name: Option<&str>) -> String { + self.display_name_label_with_username( + display_name, + self.dpns_names.first().map(|name| name.name.as_str()), + ) + } + + /// Resolve the profile name with the given username and identifier fallbacks. + pub fn display_name_label_with_username( + &self, + display_name: Option<&str>, + username: Option<&str>, + ) -> String { let preferred = self.administrative_alias().or(display_name); crate::model::identity_name::display_label( preferred, - self.dpns_names.first().map(|name| name.name.as_str()), + username, &self.identity.id().to_string(Encoding::Base58), ) } @@ -2392,6 +2416,36 @@ mod masternode_key_presence_tests { let presence = qi_with(false, &[]).masternode_key_presence(); assert_eq!(presence, MasternodeKeyPresence::default()); } + + /// VOTE-TC-013: only a loaded voter identity satisfies the vote submission + /// path. A read-only node, and a node carrying nothing but a `VOTING`-purpose + /// main key, must both be refused before a vote is composed. + #[test] + fn review_regression_only_a_loaded_voter_identity_can_cast_a_masternode_vote() { + assert!(!qi_with(true, &[]).can_cast_masternode_vote()); + assert!(!qi_with(false, &[]).can_cast_masternode_vote()); + assert!(!qi_with(false, &[Purpose::VOTING]).can_cast_masternode_vote()); + let mut identity = qi_with(true, &[]); + let key = identity + .associated_voter_identity + .as_ref() + .unwrap() + .1 + .clone(); + identity.private_keys.insert_at( + (PrivateKeyTarget::PrivateKeyOnVoterIdentity, key.id()), + ( + QualifiedIdentityPublicKey::from(key), + PrivateKeyData::InVault, + ), + ); + assert!( + identity.can_cast_masternode_vote(), + "protected references remain eligible for the signer to unlock" + ); + identity.private_keys = KeyStorage::default(); + assert!(!identity.can_cast_masternode_vote()); + } } #[cfg(test)] diff --git a/src/ui/components/README.md b/src/ui/components/README.md index 194aab695..152cf5631 100644 --- a/src/ui/components/README.md +++ b/src/ui/components/README.md @@ -18,6 +18,7 @@ Concise catalog of all reusable UI components. Consult before creating new UI el | `PasswordInput` | `password_input.rs` | N/A (security) | Masked input with hold-to-reveal, zeroizes on drop; `with_read_only()` for display-only secrets. NOT ComponentResponse | | `AliasInput` | `alias_input.rs` | `String` | Wallet/key name field. Optional label wired as the field's accessible name, live counter of the cleaned length (`model::wallet::alias::alias_char_count`), truncation at 64 characters on a grapheme-cluster boundary, helper text. Collects raw text only — cleaning, default naming, and uniqueness are resolved by the backend on save | | `IdentitySelector` | `identity_selector.rs` | N/A (Widget) | ComboBox dropdown for identity selection | +| `UtcScheduleInput` | `utc_schedule_input.rs` | `u64` (Unix ms) | Labelled ISO date field + hour/minute spinners read as UTC. Parses only — reports whether the entry is a real instant; range rules ("in the future", "before the deadline") stay with the caller. Builders: `with_label`, `with_time`. Used by the DPNS review-and-cast sheet and the scheduled-vote editor | ## Breadcrumb Components diff --git a/src/ui/components/address_input.rs b/src/ui/components/address_input.rs index d55bd1adf..b732e6782 100644 --- a/src/ui/components/address_input.rs +++ b/src/ui/components/address_input.rs @@ -616,7 +616,7 @@ impl AddressInput { for qi in identities { let id = qi.identity.id(); let id_str = id.to_string(Encoding::Base58); - let dpns_name = qi.dpns_names.first().map(|n| n.name.clone()); + let dpns_name = app_context.main_username(qi); let name_label = Some(app_context.identity_display_label(qi)); self.all_entries.push(AddressEntry { address_string: id_str, diff --git a/src/ui/components/dpns_subscreen_chooser_panel.rs b/src/ui/components/dpns_subscreen_chooser_panel.rs deleted file mode 100644 index 38fe91295..000000000 --- a/src/ui/components/dpns_subscreen_chooser_panel.rs +++ /dev/null @@ -1,48 +0,0 @@ -use crate::app::AppAction; -use crate::context::AppContext; -use crate::ui::RootScreenType; -use crate::ui::components::subscreen_chooser_panel::{ - SubscreenNavItem, add_subscreen_chooser_panel, -}; -use crate::ui::dpns::dpns_contested_names_screen::DPNSSubscreen; -use egui::Ui; - -pub fn add_dpns_subscreen_chooser_panel(ui: &mut Ui, app_context: &AppContext) -> AppAction { - let active = match app_context.get_app_settings().root_screen_type { - RootScreenType::RootScreenDPNSActiveContests => DPNSSubscreen::Active, - RootScreenType::RootScreenDPNSPastContests => DPNSSubscreen::Past, - RootScreenType::RootScreenDPNSOwnedNames => DPNSSubscreen::Owned, - RootScreenType::RootScreenDPNSScheduledVotes => DPNSSubscreen::ScheduledVotes, - _ => DPNSSubscreen::Active, - }; - - let items = [ - ( - DPNSSubscreen::Active, - RootScreenType::RootScreenDPNSActiveContests, - ), - ( - DPNSSubscreen::Past, - RootScreenType::RootScreenDPNSPastContests, - ), - ( - DPNSSubscreen::Owned, - RootScreenType::RootScreenDPNSOwnedNames, - ), - ( - DPNSSubscreen::ScheduledVotes, - RootScreenType::RootScreenDPNSScheduledVotes, - ), - ] - .into_iter() - .map(|(subscreen, target)| { - SubscreenNavItem::new( - subscreen.display_name(), - subscreen == active, - AppAction::SetMainScreen(target), - ) - }) - .collect(); - - add_subscreen_chooser_panel(ui, "dpns_subscreen_chooser_panel", true, false, items) -} diff --git a/src/ui/components/global_nav_switcher.rs b/src/ui/components/global_nav_switcher.rs index 154a8cb7a..433106c9e 100644 --- a/src/ui/components/global_nav_switcher.rs +++ b/src/ui/components/global_nav_switcher.rs @@ -524,7 +524,7 @@ fn render_app_global_identity_pill( let label = app_context.identity_display_label(active_qi); let kind: HeroIdentityKind = active_qi.identity_type.into(); - let dpns = active_qi.dpns_names.first().map(|n| n.name.clone()); + let dpns = app_context.main_username(active_qi); let id_b58 = active_qi.identity.id().to_string(Encoding::Base58); if let PillConsumption::Unwired { tooltip } = consumption { diff --git a/src/ui/components/left_panel.rs b/src/ui/components/left_panel.rs index 979d9ed69..cf7fef1ca 100644 --- a/src/ui/components/left_panel.rs +++ b/src/ui/components/left_panel.rs @@ -100,6 +100,33 @@ fn nav_tooltip(screen: RootScreenType) -> &'static str { } } +/// Paint a small count badge on the top-right corner of a nav icon; nothing +/// when `count` is zero. The count stays readable as text, not color alone. +fn paint_count_badge(ui: &Ui, icon_rect: egui::Rect, count: usize) { + if count == 0 { + return; + } + let text = if count > 99 { + "99+".to_owned() + } else { + count.to_string() + }; + let center = icon_rect.right_top() + egui::vec2(-2.0, 4.0); + let radius = if text.len() > 1 { 9.0 } else { 7.0 }; + ui.painter().circle_filled( + center, + radius, + DashColors::warning_color(ui.visuals().dark_mode), + ); + ui.painter().text( + center, + egui::Align2::CENTER_CENTER, + text, + egui::FontId::proportional(10.0), + egui::Color32::BLACK, + ); +} + pub fn add_left_panel( ui: &mut Ui, app_context: &Arc, @@ -189,15 +216,6 @@ pub fn add_left_panel( | RootScreenType::RootScreenToolsGroveSTARKScreen | RootScreenType::RootScreenToolsAddressBalanceScreen ), - // Contracts: check if any Contracts/DPNS subscreen is selected - RootScreenType::RootScreenDocumentQuery => matches!( - selected_screen, - RootScreenType::RootScreenDocumentQuery - | RootScreenType::RootScreenDPNSActiveContests - | RootScreenType::RootScreenDPNSPastContests - | RootScreenType::RootScreenDPNSOwnedNames - | RootScreenType::RootScreenDPNSScheduledVotes - ), // All other screens: exact match _ => selected_screen == *screen_type, }; @@ -216,6 +234,13 @@ pub fn add_left_panel( // clicking the text behaves like the icon, and // both show the pointer cursor + tooltip. let added = ui.add(button).clickable_tooltip(tooltip); + if *screen_type == RootScreenType::RootScreenMasternodes { + paint_count_badge( + ui, + added.rect, + app_context.dpns_vote_attention().badge_count(), + ); + } // Provide an accessible name for the image-only button added.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, is_selected, *label)); diff --git a/src/ui/components/mod.rs b/src/ui/components/mod.rs index ccdc4d9d7..7a4181123 100644 --- a/src/ui/components/mod.rs +++ b/src/ui/components/mod.rs @@ -8,7 +8,6 @@ pub mod component_trait; pub mod confirmation_dialog; pub mod contract_chooser_panel; pub mod dashpay_subscreen_chooser_panel; -pub mod dpns_subscreen_chooser_panel; pub mod entropy_grid; pub mod global_nav_switcher; pub mod icons; @@ -29,6 +28,7 @@ pub mod subscreen_chooser_panel; pub mod tokens_subscreen_chooser_panel; pub mod tools_subscreen_chooser_panel; pub mod top_panel; +pub mod utc_schedule_input; pub mod wallet_unlock_popup; // Re-export the main traits for easy access diff --git a/src/ui/components/pill.rs b/src/ui/components/pill.rs index a64312a3f..ff33460a1 100644 --- a/src/ui/components/pill.rs +++ b/src/ui/components/pill.rs @@ -6,15 +6,13 @@ //! builds the DPNS "still being decided" indicator on top of it so the Identity //! Home hero card and the Identities list render an identical badge. -use crate::model::contested_name::{PendingUsername, approximate_time_until}; +use crate::model::contested_name::approximate_time_until; +use crate::model::dpns_usernames::UsernameRequest; use crate::ui::theme::{DashColors, ResponseExt, Shape}; use eframe::egui::{ Color32, CornerRadius, Frame, Margin, Response, RichText, Sense, Stroke, StrokeKind, Ui, }; -/// Label shown on the DPNS pending-registration pill. -pub const PENDING_USERNAME_PILL_LABEL: &str = "Pending"; - /// Paint an inline pill: `label` in `accent`, on a 12%-accent fill with a 1px /// accent ring. `tooltip`, when present, is attached on hover. Returns the /// pill's [`Response`]. @@ -47,14 +45,14 @@ pub fn accent_pill(ui: &mut Ui, label: &str, accent: Color32, tooltip: Option<&s } } -/// Paint the DPNS "Pending" pill for a username the identity has requested but +/// Paint the request phase pill for a username the identity has requested but /// not yet been awarded. The hover tooltip carries the estimated ready time /// when known (see [`pending_username_tooltip`]). -pub fn pending_username_pill(ui: &mut Ui, pending: &PendingUsername) -> Response { +pub fn pending_username_pill(ui: &mut Ui, pending: &UsernameRequest) -> Response { let tooltip = pending_username_tooltip(pending); accent_pill( ui, - PENDING_USERNAME_PILL_LABEL, + crate::ui::identity::username_copy::phase_label(pending.phase), DashColors::WARNING_BRIGHT, Some(&tooltip), ) @@ -64,13 +62,13 @@ pub fn pending_username_pill(ui: &mut Ui, pending: &PendingUsername) -> Response /// decision time is known and still in the future, the estimate is included; /// otherwise a generic reassurance is returned. Kept separate from the render /// path so it is unit-testable without a frame. -pub fn pending_username_tooltip(pending: &PendingUsername) -> String { +pub fn pending_username_tooltip(pending: &UsernameRequest) -> String { let now_ms = std::time::UNIX_EPOCH .elapsed() .unwrap_or_default() .as_millis() as u64; pending - .decided_at + .end .and_then(|decided_at| approximate_time_until(decided_at, now_ms)) .unwrap_or_else(|| { "Dash masternodes vote on who receives this username. Check back later for updates." @@ -84,16 +82,27 @@ mod tests { use egui_kittest::Harness; use egui_kittest::kittest::Queryable; + fn waiting(end: Option) -> UsernameRequest { + let mut request = UsernameRequest::submitted( + "det1", + 0, + crate::model::dpns::ContestDurations { + total: std::time::Duration::ZERO, + join: std::time::Duration::ZERO, + }, + None, + ); + request.end = end; + request + } + #[test] fn tooltip_includes_eta_when_decision_time_is_in_the_future() { let now_ms = std::time::UNIX_EPOCH .elapsed() .unwrap_or_default() .as_millis() as u64; - let pending = PendingUsername { - name: "det1".to_string(), - decided_at: Some(now_ms + 3 * 3_600 * 1_000), - }; + let pending = waiting(Some(now_ms + 3 * 3_600 * 1_000)); let tip = pending_username_tooltip(&pending); assert!( tip.contains("about 3 hours"), @@ -106,10 +115,7 @@ mod tests { #[test] fn tooltip_omits_eta_when_decision_time_is_unknown_or_past() { for decided_at in [None, Some(0)] { - let pending = PendingUsername { - name: "det1".to_string(), - decided_at, - }; + let pending = waiting(decided_at); let tip = pending_username_tooltip(&pending); assert!( !tip.contains("expected in"), @@ -121,20 +127,22 @@ mod tests { } #[test] - fn pending_pill_renders_the_pending_label() { - let pending = PendingUsername { - name: "det1".to_string(), - decided_at: None, - }; - let mut harness = Harness::builder().build_ui(move |ui| { - pending_username_pill(ui, &pending); - }); - harness.run(); - assert!( - harness - .query_by_label(PENDING_USERNAME_PILL_LABEL) - .is_some(), - "the pending pill must render its '{PENDING_USERNAME_PILL_LABEL}' label" - ); + fn followup_pending_pill_uses_the_request_phase() { + for phase in [ + crate::model::dpns_usernames::RequestPhase::Joinable, + crate::model::dpns_usernames::RequestPhase::Voting, + ] { + let mut pending = waiting(None); + pending.phase = phase; + let mut harness = Harness::builder().build_ui(move |ui| { + pending_username_pill(ui, &pending); + }); + harness.run(); + assert!( + harness + .query_by_label(crate::ui::identity::username_copy::phase_label(phase)) + .is_some() + ); + } } } diff --git a/src/ui/components/styled.rs b/src/ui/components/styled.rs index 59a2f461b..79d722394 100644 --- a/src/ui/components/styled.rs +++ b/src/ui/components/styled.rs @@ -26,10 +26,6 @@ impl StyledButton { } } - pub fn primary(text: impl Into) -> Self { - Self::new(text) - } - pub fn show(self, ui: &mut Ui) -> Response { let mut button = Button::new( RichText::new(self.text) diff --git a/src/ui/components/tools_subscreen_chooser_panel.rs b/src/ui/components/tools_subscreen_chooser_panel.rs index 1c2d89b39..6d3f41b04 100644 --- a/src/ui/components/tools_subscreen_chooser_panel.rs +++ b/src/ui/components/tools_subscreen_chooser_panel.rs @@ -18,10 +18,6 @@ pub fn add_tools_subscreen_chooser_panel(ui: &mut Ui, app_context: &AppContext) RootScreenType::RootScreenToolsDocumentVisualizerScreen => ToolsSubscreen::DocumentViewer, RootScreenType::RootScreenToolsContractVisualizerScreen => ToolsSubscreen::ContractViewer, RootScreenType::RootScreenToolsGroveSTARKScreen => ToolsSubscreen::GroveSTARK, - RootScreenType::RootScreenDPNSActiveContests - | RootScreenType::RootScreenDPNSPastContests - | RootScreenType::RootScreenDPNSOwnedNames - | RootScreenType::RootScreenDPNSScheduledVotes => ToolsSubscreen::DPNS, _ => ToolsSubscreen::PlatformInfo, }; @@ -70,10 +66,6 @@ fn visible_tools_nav_items() -> Vec<(ToolsSubscreen, RootScreenType)> { ToolsSubscreen::ContractViewer, RootScreenType::RootScreenToolsContractVisualizerScreen, ), - ( - ToolsSubscreen::DPNS, - RootScreenType::RootScreenDPNSActiveContests, - ), ] } @@ -94,6 +86,21 @@ mod tests { ); } + /// VOTE-TC-084: voting moved to Masternodes ▸ Votes, so Tools has no DPNS entry. + #[test] + fn tools_menu_has_no_dpns_entry() { + assert!(visible_tools_nav_items().iter().all( + |(subscreen, target)| subscreen.display_name() != "DPNS" + && !matches!( + target, + RootScreenType::RootScreenDPNSActiveContests + | RootScreenType::RootScreenDPNSPastContests + | RootScreenType::RootScreenDPNSOwnedNames + | RootScreenType::RootScreenDPNSScheduledVotes + ) + )); + } + #[test] fn other_tools_still_listed() { let names: Vec<&str> = visible_tools_nav_items() @@ -108,7 +115,6 @@ mod tests { ToolsSubscreen::TransactionViewer, ToolsSubscreen::DocumentViewer, ToolsSubscreen::ContractViewer, - ToolsSubscreen::DPNS, ] { assert!( names.contains(&expected.display_name()), diff --git a/src/ui/components/top_panel.rs b/src/ui/components/top_panel.rs index c86d6667e..d841edf7d 100644 --- a/src/ui/components/top_panel.rs +++ b/src/ui/components/top_panel.rs @@ -320,6 +320,9 @@ fn render_top_island( action = btn_act.create_action(app_context); } } + + ui.add_space(3.0); + action |= crate::ui::dpns::attention_chip::show(ui, app_context); }, ); }); diff --git a/src/ui/components/utc_schedule_input.rs b/src/ui/components/utc_schedule_input.rs new file mode 100644 index 000000000..2209eafd7 --- /dev/null +++ b/src/ui/components/utc_schedule_input.rs @@ -0,0 +1,202 @@ +//! Absolute UTC date-and-time input for scheduling deferred work. + +use chrono::{DateTime, Timelike, Utc}; +use egui::{InnerResponse, Ui}; + +use crate::model::dpns_vote_schedule::parse_utc_schedule; +use crate::ui::components::component_trait::{Component, ComponentResponse}; + +/// The row's own copy, shared by every caller so the sentence stays one +/// translation unit instead of drifting per screen. +const UTC_SCHEDULE_LABEL: &str = "Cast on (UTC):"; +const DATE_HINT_TEXT: &str = "YYYY-MM-DD"; +const HOUR_PREFIX: &str = "Hour: "; +const MINUTE_PREFIX: &str = "Minute: "; +const DATE_FIELD_WIDTH: f32 = 100.0; + +/// Response from [`UtcScheduleInput::show`]. +#[derive(Clone)] +pub struct UtcScheduleInputResponse { + changed: bool, + changed_value: Option, + value: Option, +} + +impl ComponentResponse for UtcScheduleInputResponse { + /// Unix milliseconds of the chosen UTC instant. + type DomainType = u64; + + fn has_changed(&self) -> bool { + self.changed + } + + fn changed_value(&self) -> &Option { + &self.changed_value + } + + fn is_valid(&self) -> bool { + self.value.is_some() + } + + /// Always `None`: an unparseable entry is reported by `is_valid`, and the + /// caller owns the sentence, because only the caller knows which instants + /// its own workflow accepts. + fn error_message(&self) -> Option<&str> { + None + } +} + +/// A labelled ISO date field plus hour and minute spinners, read as UTC. +/// +/// The widget parses only — it reports whether the entry is a real UTC instant +/// and says nothing about whether that instant is acceptable. Range rules +/// ("must be in the future", "must precede the contest deadline") stay with the +/// caller, which is the layer that knows them. +/// +/// Deliberately not `egui_extras::DatePickerButton`: that widget is behind an +/// `egui_extras` feature this crate does not enable, and it replaces typed ISO +/// entry with a calendar popup — a different input model than the callers have. +/// +/// # Usage +/// +/// ```rust,ignore +/// let response = self.schedule.show(ui).inner; +/// if response.has_changed() { +/// response.update(&mut self.scheduled_at); +/// } +/// ``` +#[derive(Clone)] +pub struct UtcScheduleInput { + label: String, + date: String, + hour: u32, + minute: u32, +} + +impl UtcScheduleInput { + /// An empty input at midnight UTC. + pub fn new() -> Self { + Self { + label: UTC_SCHEDULE_LABEL.to_owned(), + date: String::new(), + hour: 0, + minute: 0, + } + } + + /// Replace the leading label. + pub fn with_label(mut self, label: impl Into) -> Self { + self.label = label.into(); + self + } + + /// Pre-fill the fields from an instant. Seconds are dropped: the widget's + /// resolution is one minute. + pub fn with_time(mut self, time: DateTime) -> Self { + self.date = time.format("%Y-%m-%d").to_string(); + self.hour = time.hour(); + self.minute = time.minute(); + self + } +} + +impl Default for UtcScheduleInput { + fn default() -> Self { + Self::new() + } +} + +impl Component for UtcScheduleInput { + type DomainType = u64; + type Response = UtcScheduleInputResponse; + + fn show(&mut self, ui: &mut Ui) -> InnerResponse { + let InnerResponse { inner, response } = ui.horizontal(|ui| { + ui.label(&self.label); + let mut changed = ui + .add( + egui::TextEdit::singleline(&mut self.date) + .desired_width(DATE_FIELD_WIDTH) + .hint_text(DATE_HINT_TEXT), + ) + .changed(); + changed |= ui + .add( + egui::DragValue::new(&mut self.hour) + .prefix(HOUR_PREFIX) + .range(0..=23), + ) + .changed(); + changed |= ui + .add( + egui::DragValue::new(&mut self.minute) + .prefix(MINUTE_PREFIX) + .range(0..=59), + ) + .changed(); + changed + }); + let value = self.current_value(); + InnerResponse::new( + UtcScheduleInputResponse { + changed: inner, + changed_value: inner.then_some(value).flatten(), + value, + }, + response, + ) + } + + fn current_value(&self) -> Option { + parse_utc_schedule(&self.date, self.hour, self.minute) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::NaiveDate; + + fn at(year: i32, month: u32, day: u32, hour: u32, minute: u32) -> DateTime { + NaiveDate::from_ymd_opt(year, month, day) + .and_then(|date| date.and_hms_opt(hour, minute, 0)) + .expect("valid test instant") + .and_utc() + } + + #[test] + fn utc_schedule_input_round_trips_the_instant_it_was_given() { + let requested = at(2031, 2, 3, 4, 5); + + let input = UtcScheduleInput::new().with_time(requested); + + assert_eq!( + input.current_value(), + Some(requested.timestamp_millis() as u64) + ); + } + + #[test] + fn utc_schedule_input_reports_an_unparseable_entry_as_having_no_value() { + assert_eq!(UtcScheduleInput::new().current_value(), None); + assert_eq!( + UtcScheduleInput::new() + .with_time(at(2031, 2, 3, 4, 5)) + .with_label("Other label:") + .current_value(), + Some(at(2031, 2, 3, 4, 5).timestamp_millis() as u64), + ); + } + + #[test] + fn utc_schedule_input_drops_seconds_so_the_minute_is_what_was_chosen() { + let with_seconds = at(2031, 2, 3, 4, 5) + chrono::Duration::seconds(37); + + let input = UtcScheduleInput::new().with_time(with_seconds); + + assert_eq!( + input.current_value(), + Some(at(2031, 2, 3, 4, 5).timestamp_millis() as u64) + ); + } +} diff --git a/src/ui/dashpay/profile_screen.rs b/src/ui/dashpay/profile_screen.rs index ee6947278..7666c4fce 100644 --- a/src/ui/dashpay/profile_screen.rs +++ b/src/ui/dashpay/profile_screen.rs @@ -816,14 +816,12 @@ impl ProfileScreen { // Username from identity if let Some(identity) = &self.selected_identity - && !identity.dpns_names.is_empty() + && let Some(name) = + self.app_context.main_username(identity) { let dark_mode = ui.style().visuals.dark_mode; ui.label( - RichText::new(format!( - "@{}", - identity.dpns_names[0].name - )) + RichText::new(format!("@{name}")) .color(DashColors::text_secondary(dark_mode)), ); } diff --git a/src/ui/dpns/attention_chip.rs b/src/ui/dpns/attention_chip.rs new file mode 100644 index 000000000..073cc04a1 --- /dev/null +++ b/src/ui/dpns/attention_chip.rs @@ -0,0 +1,173 @@ +//! Top-bar voting attention chips (VOTE-FR-072): shown on every screen to +//! operators at the Power role with at least one voting node. + +use crate::app::AppAction; +use crate::context::AppContext; +use crate::context::feature_gate::FeatureGate; +use crate::model::dpns::urgency_window; +use crate::model::dpns_voting::operator::{AttentionSummary, TimeLeft, time_left}; +use crate::ui::RootScreenType; +use crate::ui::components::pill::accent_pill; +use crate::ui::dpns::copy::{deadline_line, needs_vote_chip_label, unresolved_chip_label}; +use crate::ui::theme::DashColors; +use crate::utils::time::now_ms; +use eframe::egui::Ui; + +/// Chips to render for one summary; pure so it is testable without a frame. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AttentionChips { + /// Label and whether the soonest deadline is urgent. + pub needs_vote: Option<(String, bool)>, + pub unresolved: Option, + pub tooltip: String, +} + +/// Decide which chips show. `visible` is the role + voting-node gate. +pub fn attention_chips( + summary: &AttentionSummary, + visible: bool, + now_ms: u64, + urgency: std::time::Duration, +) -> AttentionChips { + if !visible || summary.voting_nodes == 0 { + return AttentionChips { + needs_vote: None, + unresolved: None, + tooltip: String::new(), + }; + } + let urgent = summary.is_urgent(now_ms, urgency); + let soonest: Option = summary.soonest_end.and_then(|end| time_left(end, now_ms)); + let needs_vote = (summary.needs_decision > 0).then(|| { + ( + needs_vote_chip_label(summary.needs_decision, soonest.filter(|_| urgent)), + urgent, + ) + }); + let unresolved = (summary.unresolved > 0).then(|| unresolved_chip_label(summary.unresolved)); + let tooltip = summary + .soonest_names + .iter() + .map(|(name, end)| deadline_line(name, end.and_then(|end| time_left(end, now_ms)))) + .collect::>() + .join("\n"); + AttentionChips { + needs_vote, + unresolved, + tooltip, + } +} + +/// Render the chips; a click opens Masternodes ▸ Votes. +pub fn show(ui: &mut Ui, app_context: &AppContext) -> AppAction { + let chips = attention_chips( + &app_context.dpns_vote_attention(), + FeatureGate::Masternodes.is_available(app_context), + now_ms(), + urgency_window(app_context.network()), + ); + let dark_mode = ui.visuals().dark_mode; + let mut clicked = false; + if let Some(label) = &chips.unresolved { + clicked |= accent_pill( + ui, + label, + DashColors::warning_color(dark_mode), + Some("Dash Evo Tool is still checking these votes with Platform. Don't submit them again."), + ) + .interact(eframe::egui::Sense::click()) + .clicked(); + } + if let Some((label, urgent)) = &chips.needs_vote { + let accent = if *urgent { + DashColors::warning_color(dark_mode) + } else { + DashColors::text_secondary(dark_mode) + }; + let tooltip = (!chips.tooltip.is_empty()).then_some(chips.tooltip.as_str()); + clicked |= accent_pill(ui, label, accent, tooltip) + .interact(eframe::egui::Sense::click()) + .clicked(); + } + if clicked { + // Resolves to Masternodes ▸ Votes ▸ To decide (see `resolve_root_screen`). + AppAction::SetMainScreenThenGoToMainScreen(RootScreenType::RootScreenDPNSActiveContests) + } else { + AppAction::None + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + const HOUR: u64 = 3_600_000; + + fn summary(needs: usize, unresolved: usize, soonest_end: Option) -> AttentionSummary { + AttentionSummary { + needs_decision: needs, + soonest_end, + unresolved, + soonest_names: vec![("alice".to_owned(), soonest_end)], + voting_nodes: 2, + } + } + + /// VOTE-TC-085: an urgent mainnet deadline turns the chip amber with the time. + #[test] + fn urgent_chip_names_the_soonest_deadline() { + let chips = attention_chips( + &summary(1, 0, Some(3 * HOUR + 1)), + true, + 0, + Duration::from_secs(86_400), + ); + assert_eq!( + chips.needs_vote, + Some(( + "1 name needs your vote · first ends in 3 hours".to_owned(), + true + )) + ); + assert_eq!(chips.tooltip, "alice.dash ends in 3 hours."); + } + + #[test] + fn calm_chip_omits_the_deadline() { + let chips = attention_chips( + &summary(2, 0, Some(30 * HOUR)), + true, + 0, + Duration::from_secs(86_400), + ); + assert_eq!( + chips.needs_vote, + Some(("2 names need your vote".to_owned(), false)) + ); + } + + /// VOTE-TC-086: hidden below the Power role or without a voting node. + #[test] + fn chips_hide_without_the_gate_or_voting_nodes() { + let hidden = attention_chips(&summary(3, 1, Some(HOUR)), false, 0, Duration::ZERO); + assert_eq!(hidden.needs_vote, None); + assert_eq!(hidden.unresolved, None); + + let mut keyless = summary(3, 1, Some(HOUR)); + keyless.voting_nodes = 0; + let hidden = attention_chips(&keyless, true, 0, Duration::ZERO); + assert_eq!((hidden.needs_vote, hidden.unresolved), (None, None)); + } + + /// VOTE-TC-087: an unconfirmed target shows the second chip on its own. + #[test] + fn unresolved_chip_shows_without_pending_decisions() { + let chips = attention_chips(&summary(0, 1, None), true, 0, Duration::ZERO); + assert_eq!(chips.needs_vote, None); + assert_eq!( + chips.unresolved, + Some("1 vote is still being checked".to_owned()) + ); + } +} diff --git a/src/ui/dpns/contest_card.rs b/src/ui/dpns/contest_card.rs new file mode 100644 index 000000000..3a7a2576d --- /dev/null +++ b/src/ui/dpns/contest_card.rs @@ -0,0 +1,533 @@ +//! One contest card in Masternodes ▸ Votes (frame V1): a read-only weighted +//! tally on the left, the decision pills and node line on the right. + +use crate::model::dpns::ContestDurations; +use crate::model::dpns_voting::operator::{Influence, influence, time_left}; +use crate::ui::dpns::copy; +use crate::ui::state::dpns_vote_cards::{NodeContestStatus, VoteCard}; +use crate::ui::theme::{DashColors, ResponseExt}; +use chrono::{DateTime, Utc}; +use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use dash_sdk::platform::Identifier; +use eframe::egui::{self, RichText, Ui}; +use std::collections::BTreeMap; +use std::time::Duration; + +/// Shortcut keys shown next to contender pills, in contender order. +pub const CONTENDER_KEYS: [&str; 9] = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]; + +/// What the operator did to a card this frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CardEvent { + Choose(ResourceVoteChoice), + ToggleSelected, + RefreshVoting, +} + +/// The decision choices of a card, in pill and shortcut order. +pub fn card_choices(card: &VoteCard) -> Vec<(ResourceVoteChoice, String)> { + let mut choices: Vec<(ResourceVoteChoice, String)> = card + .contest + .contestants + .iter() + .flatten() + .map(|contender| { + ( + ResourceVoteChoice::TowardsIdentity(contender.id), + copy::vote_choice_label( + ResourceVoteChoice::TowardsIdentity(contender.id), + Some(&contender.name), + ), + ) + }) + .collect(); + choices.push((ResourceVoteChoice::Lock, "Lock name".to_owned())); + choices.push((ResourceVoteChoice::Abstain, "Abstain".to_owned())); + choices +} + +/// Short label of a choice for node lines and summaries. +pub fn choice_short_label(card: &VoteCard, choice: ResourceVoteChoice) -> String { + let name = card + .contest + .contestants + .iter() + .flatten() + .find(|contender| choice == ResourceVoteChoice::TowardsIdentity(contender.id)) + .map(|contender| contender.name.as_str()); + copy::vote_choice_label(choice, name) +} + +/// The node line for a card, or `None` when no node is loaded. +pub fn card_node_line( + card: &VoteCard, + node_labels: &BTreeMap, +) -> Option { + let mut parts = Vec::new(); + let not_voted = card.count(|status| status == NodeContestStatus::NotVoted); + if not_voted > 0 { + parts.push(copy::not_voted_part(not_voted)); + } + let mut voted: BTreeMap = BTreeMap::new(); + for node in &card.nodes { + if let NodeContestStatus::Voted(choice) = node.status { + *voted.entry(choice_short_label(card, choice)).or_default() += 1; + } + } + parts.extend( + voted + .into_iter() + .map(|(label, count)| copy::voted_part(count, &label)), + ); + let exhausted: Vec = card + .nodes + .iter() + .filter(|node| matches!(node.status, NodeContestStatus::NoChangesLeft(_))) + .map(|node| node_label(node.node, node_labels)) + .collect(); + if !exhausted.is_empty() { + parts.push(copy::no_changes_part(&exhausted)); + } + let sending = card.in_flight_count(); + if sending > 0 { + parts.push(copy::sending_part(sending)); + } + let scheduled = card.scheduled_count(); + if scheduled > 0 { + parts.push(copy::scheduled_part(scheduled)); + } + (!parts.is_empty()).then(|| copy::node_line(&parts)) +} + +/// How many submittable nodes a staged `choice` would change from an earlier vote. +pub fn changed_vote_count(card: &VoteCard, choice: ResourceVoteChoice) -> usize { + card.nodes + .iter() + .filter(|node| node.status.can_submit()) + .filter(|node| node.current.is_some_and(|current| current != choice)) + .count() +} + +/// Display label for a node: its alias, else a short identifier. +pub fn node_label(node: Identifier, labels: &BTreeMap) -> String { + crate::model::identity_name::masternode_label(node, labels.get(&node).map(String::as_str)) +} + +#[test] +fn node_labels_match_the_hex_pro_tx_hash_and_preserve_aliases() { + let node = Identifier::from([0xab; 32]); + assert_eq!(node_label(node, &BTreeMap::new()), "ababa…bab"); + assert_eq!( + node_label(node, &BTreeMap::from([(node, "My node".into())])), + "My node" + ); +} + +fn utc_label(ms: u64) -> String { + DateTime::::from_timestamp_millis(ms as i64) + .map(|date| date.format("%Y-%m-%d %H:%M").to_string()) + .unwrap_or_default() +} + +/// The schedule caption under a card title. +pub fn schedule_caption( + card: &VoteCard, + durations: ContestDurations, + now_ms: u64, +) -> Option { + let end = card.contest.end_time?; + let requests = copy::requests_label(card.contest.contestants.as_ref().map_or(0, Vec::len)); + let total = u64::try_from(durations.total.as_millis()).unwrap_or(u64::MAX); + let join = u64::try_from(durations.join.as_millis()).unwrap_or(u64::MAX); + let join_until = end.saturating_sub(total).saturating_add(join); + Some(if now_ms < join_until { + format!( + "{requests} · Others can join until {when} UTC.", + when = utc_label(join_until) + ) + } else { + format!( + "{requests} · Voting ends {when} UTC.", + when = utc_label(end) + ) + }) +} + +/// Everything a card needs besides the card itself. +pub struct CardView<'a> { + pub card: &'a VoteCard, + pub staged: Option, + pub selected: bool, + pub focused: bool, + /// Scroll the card into view this frame (keyboard focus moved to it). + pub scroll_into_view: bool, + pub node_labels: &'a BTreeMap, + pub node_set_weight: u32, + pub now_ms: u64, + pub urgency: Duration, + pub durations: ContestDurations, + pub has_voting_nodes: bool, +} + +impl CardView<'_> { + /// Render the card; returns the operator's interactions in order. + pub fn show(self, ui: &mut Ui) -> Vec { + let mut events = Vec::new(); + let dark_mode = ui.visuals().dark_mode; + let stroke = if self.focused { + egui::Stroke::new(2.0, DashColors::DASH_BLUE) + } else { + egui::Stroke::new(1.0, DashColors::border_light(dark_mode)) + }; + let frame = egui::Frame::group(ui.style()) + .stroke(stroke) + .show(ui, |ui| { + ui.set_min_width(ui.available_width()); + ui.columns(2, |columns| { + self.show_tally(&mut columns[0], &mut events); + self.show_decision(&mut columns[1], &mut events); + }); + }); + if self.scroll_into_view { + ui.scroll_to_rect(frame.response.rect, None); + } + events + } + + fn show_tally(&self, ui: &mut Ui, events: &mut Vec) { + let dark_mode = ui.visuals().dark_mode; + let card = self.card; + ui.horizontal(|ui| { + let mut selected = self.selected; + if ui + .checkbox(&mut selected, "") + .on_hover_text("Select this name for a bulk decision.") + .changed() + { + events.push(CardEvent::ToggleSelected); + } + ui.label( + RichText::new(format!("{name}.dash", name = card.name())) + .heading() + .strong() + .color(DashColors::text_primary(dark_mode)), + ); + }); + let remaining = card + .contest + .end_time + .and_then(|end| time_left(end, self.now_ms)); + let urgent = card.contest.end_time.is_some_and(|end| { + end > self.now_ms && u128::from(end - self.now_ms) <= self.urgency.as_millis() + }); + if card.contest.end_time.is_some() { + let color = if urgent { + DashColors::warning_color(dark_mode) + } else { + DashColors::text_secondary(dark_mode) + }; + ui.label(RichText::new(copy::ends_in_label(remaining)).color(color)); + } + if let Some(caption) = schedule_caption(card, self.durations, self.now_ms) { + ui.label(RichText::new(caption).color(DashColors::text_secondary(dark_mode))); + } + ui.add_space(4.0); + + let mut rows: Vec<(String, u32)> = card + .contest + .contestants + .iter() + .flatten() + .map(|contender| { + ( + copy::vote_choice_label( + ResourceVoteChoice::TowardsIdentity(contender.id), + Some(&contender.name), + ), + contender.votes, + ) + }) + .collect(); + rows.push(( + "Lock name".to_owned(), + card.contest.locked_votes.unwrap_or_default(), + )); + rows.push(( + "Abstain".to_owned(), + card.contest.abstain_votes.unwrap_or_default(), + )); + let max = rows + .iter() + .map(|(_, votes)| *votes) + .max() + .unwrap_or(0) + .max(1); + egui::Grid::new(("tally", card.name())) + .num_columns(2) + .show(ui, |ui| { + for (label, votes) in rows { + ui.label(label); + ui.add( + egui::ProgressBar::new(votes as f32 / max as f32) + .desired_width(140.0) + .text(votes.to_string()), + ); + ui.end_row(); + } + }); + ui.label( + RichText::new(copy::EVONODE_WEIGHT_HINT) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); + let contenders: Vec<(Identifier, u32)> = card + .contest + .contestants + .iter() + .flatten() + .map(|contender| (contender.id, contender.votes)) + .collect(); + match influence( + &contenders, + card.contest.locked_votes.unwrap_or_default(), + self.node_set_weight, + ) { + Some(Influence::Tied) => { + ui.label(copy::TIE_LINE); + } + Some(Influence::TiedWithLock) => { + ui.label(copy::LOCK_TIE_LINE); + } + Some(Influence::CanChangeLeader { leader, margin }) if self.has_voting_nodes => { + let leader = match leader { + ResourceVoteChoice::TowardsIdentity(id) => card + .contest + .contestants + .iter() + .flatten() + .find(|contender| contender.id == id) + .map_or_else(|| "A contender".to_owned(), |c| c.name.clone()), + _ => "Lock name".to_owned(), + }; + ui.label(copy::influence_line(&leader, margin, self.node_set_weight)); + } + _ => {} + } + } + + fn show_decision(&self, ui: &mut Ui, events: &mut Vec) { + let dark_mode = ui.visuals().dark_mode; + let card = self.card; + ui.label(RichText::new("Your decision").strong()); + let enabled = card.accepts_decision(); + let disabled_reason = if !self.has_voting_nodes { + "Load a masternode with a voting key to vote." + } else if card.in_flight_count() > 0 { + "These nodes are still sending a vote on this name. Wait for the result." + } else if card.scheduled_count() > 0 { + "These nodes already have a scheduled vote on this name. Edit it on the Scheduled tab." + } else { + "None of your nodes can vote on this name right now." + }; + let shared = card.shared_choice(); + let highlighted = self.staged.or(shared); + let mut contender_index = 0usize; + ui.horizontal_wrapped(|ui| { + for (choice, label) in card_choices(card) { + let key = match choice { + ResourceVoteChoice::TowardsIdentity(_) => { + let key = CONTENDER_KEYS.get(contender_index).copied(); + contender_index += 1; + key + } + ResourceVoteChoice::Lock => Some("L"), + ResourceVoteChoice::Abstain => Some("A"), + }; + let text = match key { + Some(key) => format!("{label} [{key}]"), + None => label.clone(), + }; + let response = ui + .add_enabled( + enabled, + egui::Button::selectable(highlighted == Some(choice), text), + ) + .disabled_tooltip(disabled_reason); + if let ResourceVoteChoice::TowardsIdentity(id) = choice { + response.clone().on_hover_text(id.to_string( + dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58, + )); + } + if response.clicked() { + events.push(CardEvent::Choose(choice)); + } + } + }); + let in_flight = card.in_flight_count(); + if in_flight > 0 { + ui.label( + RichText::new(copy::sending_with_label(in_flight)) + .color(DashColors::warning_color(dark_mode)), + ); + } + if let Some(line) = card_node_line(card, self.node_labels) { + ui.label(RichText::new(line).color(DashColors::text_secondary(dark_mode))); + } + if card.nodes.len() > 1 && card.voted_count() > 0 && card.voted_count() < card.nodes.len() { + ui.label(copy::voted_with_label(card.voted_count(), card.nodes.len())); + } + if let Some(staged) = self.staged { + let changed = changed_vote_count(card, staged); + if changed > 0 { + ui.label( + RichText::new(copy::change_warning_line(changed)) + .color(DashColors::warning_color(dark_mode)), + ); + } + } + let unavailable = card.count(|status| status == NodeContestStatus::Unavailable); + if unavailable > 0 { + ui.horizontal_wrapped(|ui| { + ui.label( + RichText::new(copy::unavailable_line(unavailable)) + .color(DashColors::warning_color(dark_mode)), + ); + if ui.button("Refresh voting").clicked() { + events.push(CardEvent::RefreshVoting); + } + }); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::contested_name::{ContestState, Contestant, ContestedName}; + use crate::model::dpns_voting::operator::ChangesLeft; + use crate::ui::state::dpns_vote_cards::NodeContestState; + use std::sync::Arc; + + fn card(statuses: &[NodeContestStatus]) -> VoteCard { + let contest = ContestedName { + normalized_contested_name: "alice".to_owned(), + contestants: Some(vec![Contestant { + name: "alice".to_owned(), + id: Identifier::from([7; 32]), + info: String::new(), + votes: 6, + created_at: None, + created_at_block_height: None, + created_at_core_block_height: None, + document_id: Identifier::from([8; 32]), + }]), + locked_votes: Some(2), + abstain_votes: Some(0), + awarded_to: None, + end_time: Some(10_000_000), + state: ContestState::Ongoing, + last_updated: None, + my_votes: Default::default(), + }; + let nodes = statuses + .iter() + .enumerate() + .map(|(index, status)| { + let current = match status { + NodeContestStatus::Voted(choice) | NodeContestStatus::NoChangesLeft(choice) => { + Some(*choice) + } + _ => None, + }; + NodeContestState { + node: Identifier::from([index as u8 + 1; 32]), + status: *status, + current, + changes: ChangesLeft::Known(4), + } + }) + .collect(); + VoteCard::new(Arc::new(contest), Some(Identifier::from([9; 32])), nodes) + } + + #[test] + fn choices_list_contenders_then_lock_and_abstain() { + let card = card(&[]); + let labels: Vec = card_choices(&card).into_iter().map(|(_, l)| l).collect(); + assert_eq!( + labels, + vec![ + copy::vote_choice_label( + ResourceVoteChoice::TowardsIdentity(Identifier::from([7; 32])), + Some("alice") + ), + "Lock name".to_owned(), + "Abstain".to_owned() + ] + ); + } + + #[test] + fn equal_contender_names_keep_distinct_vote_handles() { + let mut card = card(&[]); + let contest = Arc::make_mut(&mut card.contest); + let mut other = contest.contestants.as_ref().unwrap()[0].clone(); + other.id = Identifier::from([9; 32]); + contest.contestants.as_mut().unwrap().push(other); + let choices = card_choices(&card); + assert_ne!(choices[0].1, choices[1].1); + assert!(choices[0].1.starts_with("Vote for alice (")); + assert!(choices[1].1.starts_with("Vote for alice (")); + } + + #[test] + fn node_line_groups_by_status() { + let abstain = ResourceVoteChoice::Abstain; + let card = card(&[ + NodeContestStatus::NotVoted, + NodeContestStatus::NotVoted, + NodeContestStatus::Voted(abstain), + NodeContestStatus::NoChangesLeft(abstain), + ]); + let labels = BTreeMap::from([(Identifier::from([4; 32]), "mn-07".to_owned())]); + assert_eq!( + card_node_line(&card, &labels).as_deref(), + Some( + "2 of your nodes have not voted. 1 of your nodes voted: Abstain. mn-07 has no changes left." + ) + ); + } + + /// VOTE-TC-006 (card half): the change count covers only nodes that would + /// really change. + #[test] + fn change_count_excludes_matching_and_unsubmittable_nodes() { + let lock = ResourceVoteChoice::Lock; + let abstain = ResourceVoteChoice::Abstain; + let card = card(&[ + NodeContestStatus::Voted(abstain), + NodeContestStatus::Voted(abstain), + NodeContestStatus::Voted(lock), + NodeContestStatus::NoChangesLeft(abstain), + NodeContestStatus::NotVoted, + ]); + assert_eq!(changed_vote_count(&card, lock), 2); + assert_eq!(changed_vote_count(&card, abstain), 1); + } + + #[test] + fn caption_mentions_the_join_window_only_while_it_is_open() { + let card = card(&[]); + let durations = ContestDurations { + total: Duration::from_millis(9_000_000), + join: Duration::from_millis(4_000_000), + }; + let open = schedule_caption(&card, durations, 2_000_000).unwrap(); + assert!( + open.starts_with("1 request · Others can join until"), + "{open}" + ); + let closed = schedule_caption(&card, durations, 6_000_000).unwrap(); + assert!(closed.starts_with("1 request · Voting ends"), "{closed}"); + } +} diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs new file mode 100644 index 000000000..311da2898 --- /dev/null +++ b/src/ui/dpns/copy.rs @@ -0,0 +1,1062 @@ +//! User-facing sentences for the voting workspace. +//! +//! Shared labels and sentences; count-sensitive sentences keep their plural forms here. + +use crate::model::dpns_voting::composer::SkipReason; +use crate::model::dpns_voting::operator::{ChangesLeft, NodeExclusion, TimeLeft}; +use crate::model::dpns_voting::progress::{NeedsAttention, ProgressCounts}; +use crate::model::dpns_voting::{ + DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome, DpnsVoteFailure, + DpnsVoteOperation, DpnsVoteTargetStatus, +}; +use crate::ui::MessageType; +use std::collections::BTreeSet; + +/// A node with no vote on a contest. +pub const NOT_VOTED_YET: &str = "Not voted yet"; + +/// A node outside the current masternode list (VOTE-FR-079). +pub const NOT_IN_MASTERNODE_LIST: &str = "Not in the masternode list. Its votes don't count."; + +/// Tooltip of a name filter: which look-alike characters it treats as equal. +pub const NAME_FILTER_LOOKALIKES_HINT: &str = + "The letters i and l match the digit 1, and the letter o matches 0."; + +/// Recovery guidance while saved voting progress is unreadable. +pub const JOURNAL_UNAVAILABLE_MESSAGE: &str = "Saved voting progress could not be read. The displayed history may be incomplete or out of date. Do not submit votes again until you have retried loading and checked their status."; + +/// Feedback for removing scheduled votes, including votes already in progress. +pub fn scheduled_vote_clear_feedback( + outcomes: &[DpnsScheduledVoteClearOutcome], +) -> (String, MessageType) { + let cleared = outcomes + .iter() + .filter(|outcome| outcome.disposition == DpnsScheduledVoteClearDisposition::Cleared) + .count(); + let in_flight = outcomes.len().saturating_sub(cleared); + match (cleared, in_flight) { + (0, 0) => ( + "No scheduled votes were removed.".to_owned(), + MessageType::Info, + ), + (cleared, 0) => ( + format!("Scheduled votes removed: {cleared}."), + MessageType::Success, + ), + (0, in_flight) => ( + format!( + "No scheduled votes were removed. Votes already in progress: {in_flight}. Wait for voting to finish before trying again." + ), + MessageType::Info, + ), + (cleared, in_flight) => ( + format!( + "Scheduled votes removed: {cleared}. Votes already in progress: {in_flight}. Wait for voting to finish before trying again." + ), + MessageType::Info, + ), + } +} + +/// Candidate choice with an identity handle, including when its name is unavailable. +pub fn vote_choice_label( + choice: dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice, + candidate_name: Option<&str>, +) -> String { + use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; + match choice { + ResourceVoteChoice::Lock => "Lock name".to_owned(), + ResourceVoteChoice::Abstain => "Abstain".to_owned(), + ResourceVoteChoice::TowardsIdentity(id) => { + let handle = + id.to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58); + match candidate_name { + Some(name) => format!("Vote for {name} ({handle})"), + None => format!("Vote for {handle}"), + } + } + } +} + +/// Shared status label for a vote in progress or history. +pub fn target_status_label(status: DpnsVoteTargetStatus) -> &'static str { + match status { + DpnsVoteTargetStatus::Scheduled => "Scheduled", + DpnsVoteTargetStatus::Queued => "Queued", + DpnsVoteTargetStatus::Submitting => "Submitting", + DpnsVoteTargetStatus::Confirming => "Confirming", + DpnsVoteTargetStatus::Confirmed => "Confirmed", + DpnsVoteTargetStatus::Unconfirmed => "Still being checked", + DpnsVoteTargetStatus::Rejected => "Rejected", + DpnsVoteTargetStatus::FailedBeforeSubmission => "Not submitted", + DpnsVoteTargetStatus::NotApplied => "Not applied", + DpnsVoteTargetStatus::Cancelled => "Cancelled", + } +} + +/// A remaining time as a phrase, e.g. `3 hours`. +pub fn time_left_phrase(time_left: TimeLeft) -> String { + match time_left { + TimeLeft::Minutes(1) => "1 minute".to_owned(), + TimeLeft::Minutes(minutes) => format!("{minutes} minutes"), + TimeLeft::Hours(1) => "1 hour".to_owned(), + TimeLeft::Hours(hours) => format!("{hours} hours"), + TimeLeft::Days(1) => "1 day".to_owned(), + TimeLeft::Days(days) => format!("{days} days"), + } +} + +/// `Ends in {time}`, or `Voting has ended` once the deadline has passed. +pub fn ends_in_label(time_left: Option) -> String { + match time_left { + Some(time_left) => format!("Ends in {time}", time = time_left_phrase(time_left)), + None => "Voting has ended".to_owned(), + } +} + +/// Top-bar chip: contests needing the operator's vote (VOTE-FR-072). +/// +/// `urgent` carries the soonest deadline when it falls within the urgency window. +pub fn needs_vote_chip_label(count: usize, urgent: Option) -> String { + match (count, urgent) { + (1, Some(time_left)) => format!( + "1 name needs your vote · first ends in {time}", + time = time_left_phrase(time_left) + ), + (count, Some(time_left)) => format!( + "{count} names need your vote · first ends in {time}", + time = time_left_phrase(time_left) + ), + (1, None) => "1 name needs your vote".to_owned(), + (count, None) => format!("{count} names need your vote"), + } +} + +/// Top-bar chip: targets whose result is still being checked (VOTE-FR-072). +pub fn unresolved_chip_label(count: usize) -> String { + match count { + 1 => "1 vote is still being checked".to_owned(), + count => format!("{count} votes are still being checked"), + } +} + +/// One tooltip line naming a contest and its deadline. +pub fn deadline_line(name: &str, time_left: Option) -> String { + match time_left { + Some(time_left) => format!( + "{name}.dash ends in {time}.", + time = time_left_phrase(time_left) + ), + None => format!("{name}.dash has no known deadline yet."), + } +} + +/// `Voted with {n} of {total} nodes` (VOTE-FR-071). +pub fn voted_with_label(voted: usize, total: usize) -> String { + match total { + 1 => format!("Voted with {voted} of 1 node"), + total => format!("Voted with {voted} of {total} nodes"), + } +} + +/// `{k} requests` for a contest's contender count. +pub fn requests_label(contenders: usize) -> String { + match contenders { + 1 => "1 request".to_owned(), + count => format!("{count} requests"), + } +} + +/// Influence line (VOTE-FR-077). +pub fn influence_line(leader: &str, margin: u32, weight: u32) -> String { + match (margin, weight) { + (1, 1) => format!("{leader} leads by 1 vote. Your 1 vote can change who leads."), + (1, weight) => { + format!("{leader} leads by 1 vote. Your {weight} votes can change who leads.") + } + (margin, 1) => { + format!("{leader} leads by {margin} votes. Your 1 vote can change who leads.") + } + (margin, weight) => { + format!("{leader} leads by {margin} votes. Your {weight} votes can change who leads.") + } + } +} + +/// Tie line (VOTE-FR-077, PF §3). +pub const TIE_LINE: &str = "If still tied at the end, the most recent request wins."; + +/// Lock tied with the single leading request (Lock needs strictly more votes). +pub const LOCK_TIE_LINE: &str = + "Lock name is tied with the leading request. If still tied at the end, the request wins."; + +/// Weighted-tally hint (VOTE-FR-077). +pub const EVONODE_WEIGHT_HINT: &str = "Evonodes count as 4 votes."; + +/// One part of the node line: nodes that have not voted. +pub fn not_voted_part(count: usize) -> String { + match count { + 1 => "1 of your nodes has not voted.".to_owned(), + count => format!("{count} of your nodes have not voted."), + } +} + +/// One part of the node line: nodes that voted `choice`. +pub fn voted_part(count: usize, choice_label: &str) -> String { + match count { + 1 => format!("1 of your nodes voted: {choice_label}."), + count => format!("{count} of your nodes voted: {choice_label}."), + } +} + +/// One part of the node line: nodes out of changes, named when few. +pub fn no_changes_part(names: &[String]) -> String { + match names { + [one] => format!("{one} has no changes left."), + [first, second] => format!("{first} and {second} have no changes left."), + many => format!("{count} nodes have no changes left.", count = many.len()), + } +} + +/// One part of the node line: nodes whose targets are being sent. +pub fn sending_part(count: usize) -> String { + match count { + 1 => "1 of your nodes is sending a vote.".to_owned(), + count => format!("{count} of your nodes are sending votes."), + } +} + +/// One part of the node line: nodes with a scheduled vote. +pub fn scheduled_part(count: usize) -> String { + match count { + 1 => "1 of your nodes has a scheduled vote.".to_owned(), + count => format!("{count} of your nodes have scheduled votes."), + } +} + +/// The node line under a card's choices, from its parts. +pub fn node_line(parts: &[String]) -> String { + parts.join(" ") +} + +/// Shown when picking a decision changes earlier votes (VOTE-FR-015). +pub fn change_warning_line(changed: usize) -> String { + match changed { + 1 => "Changing 1 earlier vote uses 1 of that node's 4 changes.".to_owned(), + changed => format!("Changing {changed} earlier votes uses 1 of each node's 4 changes."), + } +} + +/// Shown when some nodes' proved state is unavailable (VOTE-FR-016). +pub fn unavailable_line(count: usize) -> String { + match count { + 1 => "Vote state is unavailable for 1 node; it's left out.".to_owned(), + count => format!("Vote state is unavailable for {count} nodes; they're left out."), + } +} + +/// Card caption while its targets are in flight (VOTE-FR-083). +pub fn sending_with_label(count: usize) -> String { + match count { + 1 => "Sending with 1 node…".to_owned(), + count => format!("Sending with {count} nodes…"), + } +} + +/// Tray summary (VOTE-FR-086). With no transaction to send it names the +/// staged decisions alone. +pub fn tray_label(decisions: usize, transactions: usize) -> String { + match (decisions, transactions) { + (1, 0) => "1 decision ready".to_owned(), + (decisions, 0) => format!("{decisions} decisions ready"), + (1, 1) => "1 decision ready · 1 transaction, one per node and name".to_owned(), + (1, transactions) => { + format!("1 decision ready · {transactions} transactions, one per node and name") + } + (decisions, 1) => { + format!("{decisions} decisions ready · 1 transaction, one per node and name") + } + (decisions, transactions) => format!( + "{decisions} decisions ready · {transactions} transactions, one per node and name" + ), + } +} + +/// Tray note beside the summary (VOTE-FR-086): staged votes on nodes that +/// already show the choice are checked again instead of counted as +/// transactions. +pub fn tray_recheck_label(rechecks: usize) -> String { + match rechecks { + 1 => "1 vote already shown as cast will be checked again".to_owned(), + count => format!("{count} votes already shown as cast will be checked again"), + } +} + +/// Node-set chip (VOTE-FR-075). +pub fn node_set_chip_label(set_name: &str, nodes: usize, weight: u32) -> String { + match (nodes, weight) { + (1, 1) => format!("Vote with: {set_name} · 1 node · 1 vote"), + (1, weight) => format!("Vote with: {set_name} · 1 node · {weight} votes"), + (nodes, 1) => format!("Vote with: {set_name} · {nodes} nodes · 1 vote"), + (nodes, weight) => format!("Vote with: {set_name} · {nodes} nodes · {weight} votes"), + } +} + +/// Final batch banner (VOTE-FR-061): `{n} nodes voted on {d} names.`, with +/// the still-checking count and VOTE-FR-064 guidance when `checking > 0`. +pub fn batch_voted_line(nodes: usize, names: usize, checking: usize) -> String { + if checking > 0 { + return format!( + "Participating nodes: {nodes}. Names with confirmed votes: {names}. Votes still being checked: {checking}. Dash Evo Tool will keep checking. Do not submit the pending votes again." + ); + } + match (nodes, names) { + (1, 1) => "1 node voted on 1 name.".to_owned(), + (1, names) => format!("1 node voted on {names} names."), + (nodes, 1) => format!("{nodes} nodes voted on 1 name."), + (nodes, names) => format!("{nodes} nodes voted on {names} names."), + } +} + +/// Drawer header (VOTE-FR-083). +pub fn drawer_header(counts: ProgressCounts) -> String { + let done = counts.done(); + let ProgressCounts { + total, + sending, + checking, + .. + } = counts; + match total { + 1 => format!("Casting 1 vote · {done} done · {sending} sending · {checking} being checked"), + total => format!( + "Casting {total} votes · {done} done · {sending} sending · {checking} being checked" + ), + } +} + +/// Drawer row status (VOTE-FR-083/087). +pub fn progress_row_status( + status: DpnsVoteTargetStatus, + failure: Option, +) -> &'static str { + match (status, failure) { + (DpnsVoteTargetStatus::FailedBeforeSubmission, Some(DpnsVoteFailure::VotingEnded)) => { + "Not submitted. Voting ended." + } + (DpnsVoteTargetStatus::FailedBeforeSubmission, Some(DpnsVoteFailure::VotingKeyMissing)) => { + "Not submitted. The voting key is not loaded." + } + (DpnsVoteTargetStatus::Unconfirmed, _) => "Still being checked. Do not submit it again.", + (status, _) => target_status_label(status), + } +} + +/// `Needs attention` summary (VOTE-FR-084). +pub fn needs_attention_line(attention: NeedsAttention) -> String { + let NeedsAttention { + checking, + failed, + missed_schedules, + } = attention; + match (checking > 0, failed > 0, missed_schedules > 0) { + (true, true, true) => format!( + "Votes still being checked: {checking}. Failed votes: {failed}. Missed scheduled votes: {missed_schedules}. Do not submit the pending votes again." + ), + (true, true, false) => format!( + "Votes still being checked: {checking}. Failed votes: {failed}. Do not submit the pending votes again." + ), + (true, false, true) => format!( + "Votes still being checked: {checking}. Missed scheduled votes: {missed_schedules}. Do not submit the pending votes again." + ), + (true, false, false) => { + format!("Votes still being checked: {checking}. Do not submit the pending votes again.") + } + (false, true, true) => { + format!("Failed votes: {failed}. Missed scheduled votes: {missed_schedules}.") + } + (false, true, false) => format!("Failed votes: {failed}."), + (false, false, true) => format!("Missed scheduled votes: {missed_schedules}."), + (false, false, false) => String::new(), + } +} + +/// A node's voting weight on its detail page (MN-003). +pub fn voting_weight_label(weight: u32) -> String { + match weight { + 1 => "Voting weight: 1 vote".to_owned(), + weight => format!("Voting weight: {weight} votes"), + } +} + +/// History outcome of an awarded contest. +pub fn went_to_label(name: Option<&str>, short_id: &str) -> String { + match name { + Some(name) => format!("Went to {name} ({short_id})"), + None => format!("Went to {short_id}"), + } +} + +/// History outcome of a locked contest. +pub const LOCKED_FOR_GOOD: &str = "Locked for good, no one can register it"; + +/// Expander label of a scheduled decision's node list (VOTE-FR-088). +pub fn scheduled_nodes_label(nodes: usize) -> String { + match nodes { + 1 => "1 node".to_owned(), + nodes => format!("{nodes} nodes"), + } +} + +/// Confirm title (VOTE-FR-080). +pub fn confirm_title(decisions: usize, nodes: usize) -> String { + match (decisions, nodes) { + (1, 1) => "Cast 1 decision with 1 node".to_owned(), + (1, nodes) => format!("Cast 1 decision with {nodes} nodes"), + (decisions, 1) => format!("Cast {decisions} decisions with 1 node"), + (decisions, nodes) => format!("Cast {decisions} decisions with {nodes} nodes"), + } +} + +/// Confirm transaction line (VOTE-FR-080); none when nothing is sent. +pub fn confirm_transactions_line(transactions: usize) -> Option { + match transactions { + 0 => None, + 1 => { + Some("1 transaction, one per node and name. Voting is free for your nodes.".to_owned()) + } + count => Some(format!( + "{count} transactions, one per node and name. Voting is free for your nodes." + )), + } +} + +/// Confirm line for votes on nodes that already show the requested choice +/// (VOTE-FR-080): they are checked again, not promised as transactions. +pub fn confirm_recheck_line(rechecks: usize) -> String { + match rechecks { + 1 => "1 vote is already shown as cast. Dash Evo Tool checks it again first and sends nothing if the node still holds this choice." + .to_owned(), + count => format!( + "{count} votes are already shown as cast. Dash Evo Tool checks them again first and sends nothing for nodes that still hold their choice." + ), + } +} + +/// `Adjust nodes` row of a node that holds another choice, or none +/// (VOTE-FR-024). +pub fn review_choice_line(current: &str, requested: &str) -> String { + format!("Current choice: {current}. Requested choice: {requested}.") +} + +/// `Adjust nodes` row of a node that already shows the requested choice +/// (VOTE-FR-024). +pub fn review_recheck_line(choice: &str) -> String { + format!( + "Current choice: {choice}, as requested. It will be checked again before a vote is sent." + ) +} + +/// Confirm change warning, shown once per batch (VOTE-FR-015/080). +pub fn confirm_change_warning(changes: usize) -> String { + match changes { + 1 => "1 of these changes an earlier vote. Each node can change its vote 4 times per name." + .to_owned(), + count => format!( + "{count} of these change an earlier vote. Each node can change its vote 4 times per name." + ), + } +} + +/// Confirm skipped header (VOTE-FR-080). +pub fn skipped_header(count: usize) -> String { + match count { + 1 => "Skipped: 1 vote".to_owned(), + count => format!("Skipped: {count} votes"), + } +} + +/// Confirm line for "when voting is about to end" votes whose contest is +/// already inside the lead time (VOTE-FR-081). +pub fn ends_soon_now_line(count: usize) -> String { + format!("{count} of these votes will be sent now because voting ends soon.") +} + +/// Confirm line for nodes in the set that cannot vote at all (VOTE-FR-080). +pub fn excluded_nodes_line(count: usize, exclusion: NodeExclusion) -> String { + match (count, exclusion) { + (1, NodeExclusion::NotInMasternodeList) => { + "1 node not used: it is not in the masternode list, so its votes don't count." + .to_owned() + } + (count, NodeExclusion::NotInMasternodeList) => format!( + "{count} nodes not used: they are not in the masternode list, so their votes don't count." + ), + (1, NodeExclusion::NoVotingKey) => { + "1 node not used: no voting key is loaded for it.".to_owned() + } + (count, NodeExclusion::NoVotingKey) => { + format!("{count} nodes not used: no voting key is loaded for them.") + } + } +} + +/// One line of the confirm step's Skipped list: how many votes, and why. +pub fn skipped_reason_line(count: usize, reason: SkipReason) -> String { + match reason { + SkipReason::AlreadyVoted => { + format!("Votes skipped: {count}. The selected nodes already voted this way.") + } + SkipReason::NoChangesLeft => format!( + "Votes skipped: {count}. The selected nodes have no changes left (4 of 4 changes used)." + ), + SkipReason::VoteStateUnavailable => format!( + "Votes skipped: {count}. Vote state is unavailable. Refresh voting to include these nodes." + ), + SkipReason::AlreadyInProgress => { + format!("Votes skipped: {count}. Earlier votes on these names are still being sent.") + } + SkipReason::NotUsed => format!("Votes skipped: {count}. You chose not to use these nodes."), + SkipReason::DeadlineUnknown => format!( + "Votes skipped: {count}. The end of voting is not known yet for these names. Refresh the contests, or choose to vote now or at a fixed time." + ), + } +} + +/// Confirm primary button (VOTE-FR-080). `transactions` leaves out the +/// `rechecks`; those name the button only when nothing else is sent. +pub fn confirm_button_label(transactions: usize, rechecks: usize, all_now: bool) -> String { + match (transactions, rechecks, all_now) { + (0, 1, true) => "Check 1 vote".to_owned(), + (0, rechecks @ 2.., true) => format!("Check {rechecks} votes"), + (0, 1, false) => "Schedule 1 check".to_owned(), + (0, rechecks @ 2.., false) => format!("Schedule {rechecks} checks"), + (1, _, true) => "Cast 1 vote".to_owned(), + (count, _, true) => format!("Cast {count} votes"), + (1, _, false) => "Schedule 1 vote".to_owned(), + (count, _, false) => format!("Schedule {count} votes"), + } +} + +/// `6 hours before the end` for a relative preset (VOTE-FR-081). +pub fn before_end_phrase(preset: std::time::Duration) -> String { + let minutes = preset.as_secs() / 60; + match (minutes / 60, minutes % 60) { + (0, 0) => "Less than a minute before the end".to_owned(), + (0, 1) => "1 minute before the end".to_owned(), + (0, minutes) => format!("{minutes} minutes before the end"), + (1, 0) => "1 hour before the end".to_owned(), + (hours, 0) => format!("{hours} hours before the end"), + (hours, minutes) => format!("{hours} h {minutes} min before the end"), + } +} + +/// A relative schedule with its absolute time: `6 hours before the end · 2026-10-03 12:00 UTC`. +pub fn relative_schedule_label(preset: std::time::Duration, absolute_utc: &str) -> String { + format!( + "{relative} · {absolute_utc} UTC", + relative = before_end_phrase(preset) + ) +} + +/// One decision row in the confirm list. +pub fn decision_row(name: &str, choice: &str, nodes: usize) -> String { + match nodes { + 1 => format!("{name}.dash · {choice} · 1 node"), + nodes => format!("{name}.dash · {choice} · {nodes} nodes"), + } +} + +/// Changes-left cell under `Adjust nodes` (VOTE-FR-078). +pub fn changes_left_label(changes: ChangesLeft) -> String { + match changes { + ChangesLeft::Known(left) => format!("{left} of 4 changes left, counted on this device"), + ChangesLeft::Unknown => { + "Changes left unknown. This device has no record of this node's earlier votes." + .to_owned() + } + } +} + +#[derive(Debug, Default, PartialEq, Eq)] +struct DpnsVoteFeedbackCounts { + confirmed: usize, + scheduled: usize, + unconfirmed: usize, + rejected: usize, + failed_before_submission: usize, + cancelled: usize, + not_applied: usize, + in_progress: usize, +} + +/// Feedback for a submit whose single requested vote was already in place. +const DPNS_ONE_VOTE_ALREADY_CAST: &str = + "The selected node already has the requested vote. Nothing was submitted."; + +/// Feedback for a submit in which every requested vote was already in place. +/// Also used where the skipped count is unavailable, so it has to read true for +/// a single selected node too. +pub(crate) const DPNS_ALL_VOTES_ALREADY_CAST: &str = + "Every selected node already has the requested vote. Nothing was submitted."; + +/// Guidance for votes that reached Platform without a confirmed outcome. Shared +/// by the all-unconfirmed and mixed branches so the "do not resubmit" warning +/// never differs between them. +fn dpns_unconfirmed_guidance(unconfirmed: usize) -> String { + match unconfirmed { + 1 => "The vote was submitted, but the result could not be confirmed yet. Dash Evo Tool will keep checking. Do not submit it again.".to_owned(), + count => format!( + "{count} votes were submitted, but their results could not be confirmed yet. Dash Evo Tool will keep checking. Do not submit them again." + ), + } +} + +/// Feedback for a batch in which no target reached submission, by cause: only +/// a connection problem is worth retrying as is. +fn dpns_not_submitted_feedback(operation: &DpnsVoteOperation) -> (&'static str, MessageType) { + let single = operation.targets.len() == 1; + let caused_by = |cause| { + operation + .targets + .iter() + .filter(|outcome| outcome.failure == Some(cause)) + .count() + }; + let voting_ended = caused_by(DpnsVoteFailure::VotingEnded); + let key_missing = caused_by(DpnsVoteFailure::VotingKeyMissing); + let total = operation.targets.len(); + if voting_ended == total { + let message = if single { + "This vote was not submitted because voting on the name has already ended. No further action is needed." + } else { + "These votes were not submitted because voting on the names has already ended. No further action is needed." + }; + return (message, MessageType::Warning); + } + let message = if key_missing == total { + if single { + "This vote was not submitted because the node's voting key is not loaded. Load the key on the Nodes tab, then cast the vote again." + } else { + "These votes were not submitted because the voting keys of the nodes are not loaded. Load the keys on the Nodes tab, then cast the votes again." + } + } else if voting_ended + key_missing > 0 { + "These votes were not submitted for different reasons. Open the vote progress list to see what to do for each vote." + } else if single { + "This vote was not submitted. Check your connection and try again." + } else { + "These votes were not submitted. Check your connection and try again." + }; + (message, MessageType::Error) +} + +/// Feedback for a batch that ended in several different outcomes: one +/// complete unit per non-empty outcome, then the guidance that applies. +fn dpns_mixed_vote_feedback(counts: &DpnsVoteFeedbackCounts) -> String { + let DpnsVoteFeedbackCounts { + confirmed, + scheduled, + cancelled, + in_progress, + unconfirmed, + .. + } = *counts; + let reviewable = counts.rejected + counts.failed_before_submission + counts.not_applied; + let mut units = Vec::new(); + if confirmed > 0 { + units.push(format!("Votes confirmed: {confirmed}.")); + } + if scheduled > 0 { + units.push(format!("Votes scheduled: {scheduled}.")); + } + if reviewable > 0 { + units.push(format!("Votes needing review: {reviewable}.")); + } + if cancelled > 0 { + units.push(format!("Votes cancelled: {cancelled}.")); + } + if in_progress > 0 { + units.push(format!("Votes in progress: {in_progress}.")); + } + if unconfirmed > 0 { + units.push(format!("Votes still being checked: {unconfirmed}.")); + } + if reviewable > 0 { + units.push("Review failed votes before retrying.".to_owned()); + } + if in_progress + unconfirmed > 0 { + units.push( + "Wait for votes in progress or still being checked. Do not submit those votes again." + .to_owned(), + ); + } + units.join(" ") +} + +pub(crate) fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, MessageType, bool) { + let mut counts = DpnsVoteFeedbackCounts::default(); + for outcome in &operation.targets { + match outcome.status { + DpnsVoteTargetStatus::Confirmed => counts.confirmed += 1, + DpnsVoteTargetStatus::Scheduled => counts.scheduled += 1, + DpnsVoteTargetStatus::Unconfirmed => counts.unconfirmed += 1, + DpnsVoteTargetStatus::Rejected => counts.rejected += 1, + DpnsVoteTargetStatus::FailedBeforeSubmission => { + counts.failed_before_submission += 1; + } + DpnsVoteTargetStatus::Cancelled => counts.cancelled += 1, + DpnsVoteTargetStatus::NotApplied => counts.not_applied += 1, + DpnsVoteTargetStatus::Queued + | DpnsVoteTargetStatus::Submitting + | DpnsVoteTargetStatus::Confirming => counts.in_progress += 1, + } + } + if operation.targets.is_empty() { + let message = match operation.no_op_count { + 1 => DPNS_ONE_VOTE_ALREADY_CAST, + _ => DPNS_ALL_VOTES_ALREADY_CAST, + }; + return (message.to_owned(), MessageType::Info, false); + } + let target_count = operation.targets.len(); + if target_count == 1 && counts.confirmed == 1 { + return ( + "Vote cast successfully.".to_owned(), + MessageType::Success, + false, + ); + } + // VOTE-FR-061: a batch that only confirmed, or confirmed with some still + // being checked, reads as nodes × names. + if counts.confirmed > 0 && counts.confirmed + counts.unconfirmed == target_count { + let confirmed = operation + .targets + .iter() + .filter(|outcome| outcome.status == DpnsVoteTargetStatus::Confirmed); + let nodes = confirmed + .clone() + .map(|outcome| outcome.target.key.voter_id) + .collect::>() + .len(); + let names = confirmed + .map(|outcome| outcome.target.key.vote_poll_id) + .collect::>() + .len(); + let checking = counts.unconfirmed; + let message_type = if checking == 0 { + MessageType::Success + } else { + MessageType::Warning + }; + return ( + batch_voted_line(nodes, names, checking), + message_type, + checking > 0, + ); + } + let single = target_count == 1; + if counts.scheduled == target_count { + let message = if single { + "Vote scheduled successfully.".to_owned() + } else { + format!("{target_count} votes were scheduled.") + }; + return (message, MessageType::Success, false); + } + if counts.confirmed + counts.scheduled == target_count { + return ( + format!( + "Votes cast successfully: {confirmed}. Votes scheduled: {scheduled}.", + confirmed = counts.confirmed, + scheduled = counts.scheduled, + ), + MessageType::Success, + false, + ); + } + if counts.unconfirmed == target_count { + return ( + dpns_unconfirmed_guidance(counts.unconfirmed), + MessageType::Warning, + true, + ); + } + if counts.rejected == target_count { + let message = if single { + "The vote was rejected. Review the vote and try again." + } else { + "The votes were rejected. Review the votes and try again." + }; + return (message.to_owned(), MessageType::Error, false); + } + if counts.failed_before_submission == target_count { + let (message, message_type) = dpns_not_submitted_feedback(operation); + return (message.to_owned(), message_type, false); + } + if counts.not_applied == target_count { + let message = if single { + "The submitted vote was not applied. Review the vote and try again." + } else { + "The submitted votes were not applied. Review the votes and try again." + }; + return (message.to_owned(), MessageType::Error, false); + } + if counts.cancelled == target_count { + let message = if single { + "The scheduled vote was cancelled. Nothing was submitted." + } else { + "The scheduled votes were cancelled. Nothing was submitted." + }; + return (message.to_owned(), MessageType::Info, false); + } + if counts.in_progress == target_count { + return ( + "Voting is still in progress. Wait for the result before submitting again.".to_owned(), + MessageType::Info, + false, + ); + } + + ( + dpns_mixed_vote_feedback(&counts), + MessageType::Warning, + counts.unconfirmed > 0, + ) +} + +#[cfg(test)] +mod tests { + #[test] + fn blocker_exhausted_vote_limit_uses_changes_consistently() { + let copy = super::skipped_reason_line(1, super::SkipReason::NoChangesLeft); + assert!(copy.contains("4 of 4 changes used"), "{copy}"); + assert!(!copy.contains("5 of 5 votes")); + } + + /// History outcome and node-vote wording (frame V4). + #[test] + fn history_copy_names_the_outcome_and_votes() { + use super::*; + assert_eq!(went_to_label(Some("zed"), "AbC1…"), "Went to zed (AbC1…)"); + assert_eq!(went_to_label(None, "AbC1…"), "Went to AbC1…"); + assert_eq!(voting_weight_label(4), "Voting weight: 4 votes"); + assert_eq!(voting_weight_label(1), "Voting weight: 1 vote"); + assert_eq!( + before_end_phrase(std::time::Duration::from_secs(30)), + "Less than a minute before the end" + ); + assert_eq!( + excluded_nodes_line(2, NodeExclusion::NotInMasternodeList), + "2 nodes not used: they are not in the masternode list, so their votes don't count." + ); + } + + use super::*; + + /// VOTE-TC-085 (copy half). + #[test] + fn needs_vote_chip_reads_as_a_complete_sentence() { + assert_eq!( + needs_vote_chip_label(1, Some(TimeLeft::Hours(3))), + "1 name needs your vote · first ends in 3 hours" + ); + assert_eq!( + needs_vote_chip_label(4, Some(TimeLeft::Minutes(1))), + "4 names need your vote · first ends in 1 minute" + ); + assert_eq!(needs_vote_chip_label(1, None), "1 name needs your vote"); + assert_eq!(needs_vote_chip_label(6, None), "6 names need your vote"); + } + + /// VOTE-TC-087 (copy half). + #[test] + fn unresolved_chip_has_a_plural_pair() { + assert_eq!(unresolved_chip_label(1), "1 vote is still being checked"); + assert_eq!(unresolved_chip_label(3), "3 votes are still being checked"); + } + + #[test] + fn card_lines_read_as_complete_units() { + assert_eq!(voted_with_label(5, 24), "Voted with 5 of 24 nodes"); + assert_eq!( + influence_line("Zed", 6, 51), + "Zed leads by 6 votes. Your 51 votes can change who leads." + ); + assert_eq!( + node_line(&[ + not_voted_part(19), + voted_part(4, "Abstain"), + no_changes_part(&["mn-07".to_owned()]), + ]), + "19 of your nodes have not voted. 4 of your nodes voted: Abstain. mn-07 has no changes left." + ); + assert_eq!( + change_warning_line(4), + "Changing 4 earlier votes uses 1 of each node's 4 changes." + ); + assert_eq!( + tray_label(1, 3), + "1 decision ready · 3 transactions, one per node and name" + ); + assert_eq!(tray_label(1, 0), "1 decision ready"); + assert_eq!(tray_label(2, 0), "2 decisions ready"); + assert_eq!( + node_set_chip_label("All my nodes", 24, 51), + "Vote with: All my nodes · 24 nodes · 51 votes" + ); + assert_eq!( + unavailable_line(3), + "Vote state is unavailable for 3 nodes; they're left out." + ); + } + + /// A node already shown on the requested choice is neither a first vote + /// nor a promised transaction: the copy says it is checked again. + #[test] + fn votes_only_checked_again_are_worded_apart_from_transactions() { + assert_eq!( + tray_recheck_label(1), + "1 vote already shown as cast will be checked again" + ); + assert_eq!( + tray_recheck_label(3), + "3 votes already shown as cast will be checked again" + ); + assert_eq!( + confirm_recheck_line(1), + "1 vote is already shown as cast. Dash Evo Tool checks it again first and sends nothing if the node still holds this choice." + ); + assert_eq!( + confirm_recheck_line(3), + "3 votes are already shown as cast. Dash Evo Tool checks them again first and sends nothing for nodes that still hold their choice." + ); + assert_eq!( + review_recheck_line("Lock name"), + "Current choice: Lock name, as requested. It will be checked again before a vote is sent." + ); + assert_eq!( + review_choice_line("Not voted yet", "Abstain"), + "Current choice: Not voted yet. Requested choice: Abstain." + ); + // The button counts transactions; checks name it only on their own. + assert_eq!(confirm_button_label(2, 3, true), "Cast 2 votes"); + assert_eq!(confirm_button_label(1, 3, false), "Schedule 1 vote"); + assert_eq!(confirm_button_label(0, 1, true), "Check 1 vote"); + assert_eq!(confirm_button_label(0, 3, true), "Check 3 votes"); + assert_eq!(confirm_button_label(0, 1, false), "Schedule 1 check"); + assert_eq!(confirm_button_label(0, 3, false), "Schedule 3 checks"); + } + + /// VOTE-TC-006/094/095/096 (copy half): the confirm lines follow VOTE-FR-080. + #[test] + fn confirm_copy_follows_the_spec() { + assert_eq!(confirm_title(3, 24), "Cast 3 decisions with 24 nodes"); + assert_eq!( + confirm_transactions_line(72).as_deref(), + Some("72 transactions, one per node and name. Voting is free for your nodes.") + ); + assert_eq!( + confirm_transactions_line(0), + None, + "a batch that sends nothing has no transaction sentence" + ); + assert_eq!( + confirm_change_warning(4), + "4 of these change an earlier vote. Each node can change its vote 4 times per name." + ); + assert_eq!(skipped_header(2), "Skipped: 2 votes"); + assert_eq!( + skipped_reason_line(1, SkipReason::NoChangesLeft), + "Votes skipped: 1. The selected nodes have no changes left (4 of 4 changes used)." + ); + assert_eq!(confirm_button_label(72, 0, true), "Cast 72 votes"); + assert_eq!(confirm_button_label(1, 0, false), "Schedule 1 vote"); + assert_eq!( + relative_schedule_label(std::time::Duration::from_secs(6 * 3600), "2026-10-03 12:00"), + "6 hours before the end · 2026-10-03 12:00 UTC" + ); + assert_eq!( + before_end_phrase(std::time::Duration::from_secs(600)), + "10 minutes before the end" + ); + assert_eq!( + changes_left_label(ChangesLeft::Known(3)), + "3 of 4 changes left, counted on this device" + ); + assert_eq!( + changes_left_label(ChangesLeft::Unknown), + "Changes left unknown. This device has no record of this node's earlier votes." + ); + } + + /// VOTE-FR-061: the batch banner counts nodes and names. + #[test] + fn batch_banner_counts_nodes_and_names() { + assert_eq!(batch_voted_line(24, 3, 0), "24 nodes voted on 3 names."); + assert_eq!( + batch_voted_line(2, 1, 1), + "Participating nodes: 2. Names with confirmed votes: 1. Votes still being checked: 1. Dash Evo Tool will keep checking. Do not submit the pending votes again." + ); + } + + /// VOTE-TC-101/102/103 (copy half). + #[test] + fn drawer_and_attention_copy() { + assert_eq!( + drawer_header(ProgressCounts { + total: 72, + confirmed: 40, + failed: 2, + sending: 25, + checking: 5, + }), + "Casting 72 votes · 42 done · 25 sending · 5 being checked" + ); + assert_eq!( + progress_row_status( + DpnsVoteTargetStatus::FailedBeforeSubmission, + Some(DpnsVoteFailure::VotingEnded) + ), + "Not submitted. Voting ended." + ); + assert_eq!( + needs_attention_line(NeedsAttention { + checking: 1, + failed: 0, + missed_schedules: 2, + }), + "Votes still being checked: 1. Missed scheduled votes: 2. Do not submit the pending votes again." + ); + } + + #[test] + fn attention_copy_omits_zero_counts_and_warns_about_pending_votes() { + for checking in 0..=1 { + for failed in 0..=1 { + for missed_schedules in 0..=1 { + let message = needs_attention_line(NeedsAttention { + checking, + failed, + missed_schedules, + }); + assert!(!message.contains(": 0.")); + assert_eq!(message.contains("Do not submit"), checking > 0); + assert_eq!( + message.is_empty(), + checking + failed + missed_schedules == 0 + ); + } + } + } + } + + #[test] + fn deadlines_read_naturally() { + assert_eq!(ends_in_label(Some(TimeLeft::Days(1))), "Ends in 1 day"); + assert_eq!(ends_in_label(None), "Voting has ended"); + assert_eq!( + deadline_line("alice", Some(TimeLeft::Hours(6))), + "alice.dash ends in 6 hours." + ); + } +} diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index b7d258d13..5b9622210 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -1,57 +1,435 @@ +mod scheduled_vote_editor; +use scheduled_vote_editor::{EditOutcome, ScheduledVoteEditor}; + use crate::wallet_backend::poison::MutexRecover; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::{Arc, Mutex}; -use tracing::error; use chrono::{DateTime, LocalResult, TimeZone, Utc}; use chrono_humanize::HumanTime; +use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::platform_value::string_encoding::Encoding; use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; use dash_sdk::platform::Identifier; -use eframe::egui::{self, Button, Color32, ComboBox, Label, RichText, Ui}; +use eframe::egui::{self, Button, ComboBox, Label, RichText, Ui}; use egui_extras::{Column, TableBuilder}; -use itertools::Itertools; -use crate::app::{ - AppAction, BackendTasksExecutionMode, DesiredAppAction, scheduled_vote_sweep_is_quiet, -}; -use crate::backend_task::BackendTask; -use crate::backend_task::contested_names::{ContestedResourceTask, ScheduledDPNSVote}; +use crate::app::{AppAction, scheduled_vote_sweep_is_quiet}; +use crate::backend_task::contested_names::ContestedResourceTask; +use crate::backend_task::contested_names::{DpnsVotingPreference, RelativeScheduleLabels}; use crate::backend_task::error::TaskError; -use crate::backend_task::identity::IdentityTask; +use crate::backend_task::{BackendTask, BackendTaskContext}; use crate::context::AppContext; use crate::model::contested_name::{ContestState, ContestedName}; -use crate::model::qualified_identity::{DPNSNameInfo, QualifiedIdentity}; -use crate::ui::components::dpns_subscreen_chooser_panel::add_dpns_subscreen_chooser_panel; -use crate::ui::components::left_panel::add_left_panel; -use crate::ui::components::styled::{StyledButton, island_central_panel}; -use crate::ui::components::tools_subscreen_chooser_panel::add_tools_subscreen_chooser_panel; -use crate::ui::components::top_panel::{add_top_panel_with_global_nav, subdued_everyday_spec}; +use crate::model::dpns::normalize_dpns_label; +use crate::model::dpns::{contest_durations, urgency_window}; +use crate::model::dpns_voting::composer::{ + AggregatePlan, BatchTiming, ComposeError, ComposerNode, Decision, NodeStanding, NodeTiming, + SkipReason, compose, +}; +use crate::model::dpns_voting::operator::NodeExclusion; +use crate::model::dpns_voting::operator::{ + ChangesLeft, NodeSet, ResolvedNodeSet, VotingNode, relative_schedule_preset, time_left, + vote_proof_can_decide, +}; +use crate::model::dpns_voting::progress::needs_attention; +use crate::model::dpns_voting::{ + DpnsCurrentVoteState, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, + DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, + VoteTiming, dpns_schedule_is_overdue, validate_dpns_schedule_time, +}; +use crate::model::qualified_identity::QualifiedIdentity; +use crate::ui::components::component_trait::{Component, ComponentResponse}; +use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; +use crate::ui::components::utc_schedule_input::UtcScheduleInput; use crate::ui::components::{BannerHandle, MessageBanner, OptionBannerExt}; -use crate::ui::identity::register_dpns_name_screen::RegisterDpnsNameSource; +use crate::ui::dpns::contest_card::node_label; +use crate::ui::dpns::contest_card::{CardEvent, CardView}; +use crate::ui::dpns::copy::needs_attention_line; +use crate::ui::dpns::copy::{ + JOURNAL_UNAVAILABLE_MESSAGE, LOCKED_FOR_GOOD, NAME_FILTER_LOOKALIKES_HINT, NOT_VOTED_YET, + before_end_phrase, changes_left_label, confirm_button_label, confirm_change_warning, + confirm_title, confirm_transactions_line, decision_row, ends_in_label, relative_schedule_label, + scheduled_nodes_label, skipped_header, skipped_reason_line, went_to_label, +}; +use crate::ui::dpns::copy::{ + confirm_recheck_line, review_choice_line, review_recheck_line, tray_label, tray_recheck_label, +}; +use crate::ui::dpns::copy::{ends_soon_now_line, excluded_nodes_line}; +use crate::ui::dpns::node_set_picker; +use crate::ui::dpns::progress_drawer; +use crate::ui::state::dpns_contests::ActiveDpnsContestSnapshot; +use crate::ui::state::dpns_vote_cards::{ + CantVoteReason, CardPlacement, NodeContestState, NodeContestStatus, SHORTCUT_HELP, Shortcut, + VoteCard, move_focus, place_card, shortcut_for, sort_by_time_left, +}; +use crate::ui::state::dpns_vote_operations::{ + DpnsVoteOperationSnapshot, ScheduledDecisionGroup, ScheduledDpnsVoteRow, group_scheduled_rows, +}; +use crate::ui::state::dpns_vote_state::DpnsVoteStateSnapshot; use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; -use crate::ui::{BackendTaskSuccessResult, MessageType, RootScreenType, ScreenLike, ScreenType}; +use crate::ui::{BackendTaskSuccessResult, MessageType, ScreenLike}; +use crate::utils::time::now_ms; -/// Which DPNS sub-screen is currently showing. -#[derive(PartialEq)] -pub enum DPNSSubscreen { - Active, - Past, - Owned, - ScheduledVotes, +pub use super::VotesView; + +const NO_OPEN_CONTESTS_MESSAGE: &str = + "There are no open name contests right now. New contests appear here automatically."; +const CANT_VOTE_REASON: &str = "None of the nodes you vote with has a voting key that is in the masternode list. Load a voting key or change the nodes you vote with."; +const NO_VOTING_NODES_MESSAGE: &str = "No masternodes are loaded."; +const NO_VOTING_NODES_DETAIL: &str = "Load a masternode with its voting key to cast votes."; +const MISSED_SCHEDULE_GUIDANCE: &str = "The automatic voting time was missed. On the Scheduled tab, use Cast now to vote, Edit to reschedule, or Remove to cancel."; +const SCHEDULE_IN_FUTURE_MESSAGE: &str = + "Choose a future date and time before scheduling these votes."; +const KEEP_RUNNING_MESSAGE: &str = "Keep Dash Evo Tool running and connected until the scheduled time, or the scheduled votes will not be cast."; + +/// An absolute UTC time next to how far away it is, e.g. +/// `2026-01-02 03:04:05 UTC (in 2 days)`. +fn timestamp_with_relative(date_time: DateTime) -> String { + let distance = HumanTime::from(date_time).to_string(); + let relative = if distance.contains("seconds") { + "now" + } else { + &distance + }; + format!( + "{absolute} ({relative})", + absolute = date_time.format("%Y-%m-%d %H:%M:%S UTC"), + ) +} + +fn schedule_is_missed(status: DpnsVoteTargetStatus, timing: VoteTiming, now_ms: u64) -> bool { + status == DpnsVoteTargetStatus::Scheduled + && matches!(timing, VoteTiming::Scheduled(timestamp) if dpns_schedule_is_overdue(timestamp, now_ms)) +} + +fn short_identifier(identifier: Identifier) -> String { + crate::model::identity_name::shorten_id(&identifier.to_string(Encoding::Base58)) +} + +use super::copy::{target_status_label, vote_choice_label}; + +/// Candidate display names resolved once per refresh: contest → candidate → name. +/// +/// The render path is immediate-mode, so it looks candidates up here instead of +/// rescanning the contested-name cache — which grows without bound — on every +/// frame, for every row. +type CandidateNameIndex = BTreeMap>; + +fn candidate_name_index( + active_contests: &ActiveDpnsContestSnapshot, + contested_names: &[ContestedName], +) -> CandidateNameIndex { + let active = active_contests.contests(); + let mut index = CandidateNameIndex::new(); + // Active contests are the fresher source, so they are indexed last and win. + let contests = contested_names + .iter() + .chain(active.iter().map(|view| view.contest.as_ref())); + for contest in contests { + let Some(candidates) = contest.contestants.as_ref() else { + continue; + }; + let entry = index + .entry(contest.normalized_contested_name.clone()) + .or_default(); + for candidate in candidates { + entry.insert(candidate.id, candidate.name.clone()); + } + } + index +} + +fn target_outcome_label( + status: DpnsVoteTargetStatus, + failure: Option, +) -> &'static str { + if scheduled_failure_guidance(status, failure).is_some() { + "Not submitted" + } else { + target_status_label(status) + } +} + +/// Whether a target this panel last saw as `previous` was applied by Platform +/// on its way to `Confirmed`, as opposed to being confirmed as an exact no-op. +/// +/// A broadcast target keeps the choice it replaced, so it is not a no-op; a +/// reconciled one records the observed choice, but was `Unconfirmed` before. +/// A target first seen already confirmed is history the cards already count. +fn newly_applied_vote(previous: Option, outcome: &DpnsVoteOutcome) -> bool { + match previous { + None | Some(DpnsVoteTargetStatus::Confirmed) => false, + Some(DpnsVoteTargetStatus::Unconfirmed) => true, + Some(_) => !outcome.target.is_no_op(), + } +} + +fn scheduled_failure_guidance( + status: DpnsVoteTargetStatus, + failure: Option, +) -> Option<&'static str> { + if status != DpnsVoteTargetStatus::Scheduled { + return None; + } + match failure? { + DpnsVoteFailure::CurrentVoteUnavailable => Some( + "Current vote could not be verified. On the Scheduled tab, use Cast now to check again or Edit to reschedule.", + ), + DpnsVoteFailure::SubmissionFailed => Some( + "The vote could not be submitted. Check your connection and voting key, then use Cast now or Edit on the Scheduled tab.", + ), + DpnsVoteFailure::VotingKeyMissing => Some( + "This node's voting key is not loaded. Load it on the Nodes tab, then use Cast now on the Scheduled tab.", + ), + DpnsVoteFailure::PlatformRejected + | DpnsVoteFailure::ResultUnconfirmed + | DpnsVoteFailure::VotingEnded => None, + } +} + +fn scheduled_vote_remove_enabled(status: DpnsVoteTargetStatus) -> bool { + !matches!( + status, + DpnsVoteTargetStatus::Queued + | DpnsVoteTargetStatus::Submitting + | DpnsVoteTargetStatus::Confirming + | DpnsVoteTargetStatus::Unconfirmed + ) +} + +fn scheduled_vote_cast_enabled(status: DpnsVoteTargetStatus, dispatch_pending: bool) -> bool { + !dispatch_pending + && (status.is_reviewable_failure() + || matches!( + status, + DpnsVoteTargetStatus::Scheduled | DpnsVoteTargetStatus::Cancelled + )) +} + +fn scheduled_vote_removal_task(row: &ScheduledDpnsVoteRow) -> ContestedResourceTask { + ContestedResourceTask::CancelScheduledDpnsVote { + operation_id: row.journal_target.0, + key: row.journal_target.1.clone(), + } +} + +/// The loaded nodes that can actually cast a vote. +/// +/// A masternode loaded read-only passes the identity-type filter but has no +/// voting key, so the DPNS surfaces must drop it here — otherwise it reaches the +/// composer and only fails once the vote is submitted. +fn loaded_voting_identities(app_context: &AppContext) -> Result, TaskError> { + Ok(app_context + .load_local_voting_identities()? + .into_iter() + .filter(QualifiedIdentity::can_cast_masternode_vote) + .collect()) +} + +/// Exactly what a confirm click would submit, resolved before the confirm +/// step is shown. +struct ReviewPlan { + aggregate: AggregatePlan, + /// One line per staged decision: name, choice, and the nodes casting it. + decisions: Vec<(Decision, usize)>, +} + +impl ReviewPlan { + /// The targets that will really be submitted. + fn targets(&self) -> &[DpnsVoteTarget] { + &self.aggregate.targets + } + + /// Every submitted target, including the ones only checked again. + fn effective_count(&self) -> usize { + self.aggregate.targets.len() + } + + /// Targets that send a vote. + fn transaction_count(&self) -> usize { + self.aggregate.transaction_count() + } + + /// Targets whose node already shows the requested choice: submitted to be + /// checked again, sending a vote only if the choice is not in place. + fn recheck_count(&self) -> usize { + self.aggregate.recheck.len() + } + + fn node_count(&self) -> usize { + self.aggregate.node_count() + } + + fn has_scheduled(&self) -> bool { + self.targets() + .iter() + .any(|target| matches!(target.timing, VoteTiming::Scheduled(_))) + } +} + +/// What the staged decisions would submit, as the tray counts it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +struct TrayCounts { + /// Votes that would be sent. + transactions: usize, + /// Nodes shown on the staged choice by proof too old to decide: the + /// backend's fresh proof settles whether their vote is really in place. + rechecks: usize, +} + +/// The batch timing picked in the confirm step (VOTE-FR-023). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum ConfirmTiming { + #[default] + Now, + BeforeEnd, + At, } -impl DPNSSubscreen { - pub fn display_name(&self) -> &'static str { +impl ConfirmTiming { + const ALL: [Self; 3] = [Self::Now, Self::BeforeEnd, Self::At]; + + fn label(self) -> &'static str { match self { - Self::Active => "Active contests", - Self::Past => "Past contests", - Self::Owned => "My usernames", - Self::ScheduledVotes => "Scheduled votes", + Self::Now => "Now", + Self::BeforeEnd => "When voting is about to end", + Self::At => "At a specific time", } } } +/// A per-node choice under `Adjust nodes`. +fn node_timing_label(timing: NodeTiming) -> &'static str { + match timing { + NodeTiming::Batch => "Same as above", + NodeTiming::Override(BatchTiming::Now) => "Now", + NodeTiming::Override(BatchTiming::BeforeEnd(_)) => "When voting is about to end", + NodeTiming::Override(BatchTiming::At(_)) => "At a specific time", + NodeTiming::DontUse => "Don't use this node", + } +} + +fn utc_minute(timestamp: u64) -> String { + DateTime::from_timestamp_millis(timestamp as i64) + .map(|date| date.format("%Y-%m-%d %H:%M").to_string()) + .unwrap_or_default() +} + +fn review_current_choice_label( + current: Option, + candidate_name: Option<&str>, +) -> String { + match current { + Some(choice) => vote_choice_label(choice, candidate_name), + None => NOT_VOTED_YET.to_owned(), + } +} + +/// Why the reviewed selection cannot be turned into a submittable plan. +/// +/// One variant per condition so a caller can match on the outcome instead of +/// comparing sentences; the copy lives in the `#[error(...)]` attributes. +#[derive(Debug, Clone, thiserror::Error)] +pub enum ReviewPlanError { + #[error("{}", SCHEDULE_IN_FUTURE_MESSAGE)] + ScheduleIsNotInTheFuture, + #[error("Choose a valid UTC date and time.")] + ScheduleIsNotAValidTime, + #[error("This vote could not be prepared. Refresh the contests and try again.")] + VotePollUnavailable { + #[source] + source: Arc, + }, + /// The composer refused the selection; the sentence is the composer's. + #[error(transparent)] + Compose(#[from] ComposeError), +} + +/// A backend result the votes panel acts on. +/// +/// The one place that names them: `AppState` routes exactly these to the +/// panel while it is hidden (via [`DPNSScreen::handles_result`]) and +/// `display_task_result` matches on this type, so a result cannot be handled +/// without also being routed. +enum VotesPanelResult { + OperationUpdated { + network: Network, + operation_id: DpnsVoteOperationId, + }, + ScheduledSweepCompleted { + network: Network, + }, + ScheduledVotesInProgress, + ScheduledVotesCleared, + ContestsRefreshed, +} + +impl VotesPanelResult { + fn of(result: &BackendTaskSuccessResult) -> Option { + match result { + BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network, + operation_id, + } => Some(Self::OperationUpdated { + network: *network, + operation_id: *operation_id, + }), + BackendTaskSuccessResult::ScheduledVoteSweepCompleted { network, .. } => { + Some(Self::ScheduledSweepCompleted { network: *network }) + } + BackendTaskSuccessResult::ScheduledVotesInProgress(_) => { + Some(Self::ScheduledVotesInProgress) + } + BackendTaskSuccessResult::ScheduledVotesCleared(_) => Some(Self::ScheduledVotesCleared), + BackendTaskSuccessResult::RefreshedDpnsContests => Some(Self::ContestsRefreshed), + _ => None, + } + } +} + +/// Why a submit click produced nothing to send. +#[derive(Debug, Clone, thiserror::Error)] +pub enum VoteSubmissionError { + #[error(transparent)] + Plan(#[from] ReviewPlanError), + #[error("No votes selected. Choose at least one node and contest.")] + NoTargets, + #[error("Every selected node already has the requested vote. Nothing will be submitted.")] + AllNoOps, +} + +fn platform_explorer_contest_url(network: Network, normalized_label: &str) -> Option { + use base64::Engine; + + let host = match network { + Network::Mainnet => "platform-explorer.com", + Network::Testnet => "testnet.platform-explorer.com", + Network::Devnet | Network::Regtest => return None, + }; + let resource = serde_json::json!(["dash", normalized_label]).to_string(); + let encoded = base64::engine::general_purpose::STANDARD.encode(resource); + Some(format!( + "https://{host}/contestedResource/{}", + urlencoding::encode(&encoded) + )) +} + +fn dpns_operation_id( + context: &BackendTaskContext, + network: dash_sdk::dpp::dashcore::Network, +) -> Option { + match context { + BackendTaskContext::Dispatched { operation, .. } => dpns_operation_id(operation, network), + BackendTaskContext::DpnsVoteOperation { + operation_id, + network: origin, + } if *origin == network => Some(*operation_id), + _ => None, + } +} + /// Minimal object for storing the user’s currently selected vote on a single contested name. #[derive(Clone, Debug, PartialEq)] pub struct SelectedVote { @@ -60,29 +438,24 @@ pub struct SelectedVote { pub end_time: Option, } -#[derive(Clone)] -pub enum VoteOption { - NoVote, - CastNow, - Scheduled { days: u32, hours: u32, minutes: u32 }, -} - -/// Tracks the casting status for each scheduled vote item. -#[derive(Clone, Copy, PartialEq, Eq)] -pub enum ScheduledVoteCastingStatus { - NotStarted, - InProgress, - Failed, - Completed, +/// A failed target under review from the progress drawer (`Review again`). +/// +/// The confirm step covers this one node and decision instead of the staged +/// decisions, which stay in the tray untouched. +#[derive(Clone, Debug, PartialEq)] +struct RetryReview { + voter: Identifier, + vote: SelectedVote, } -#[derive(PartialEq)] +/// What the open confirm step has to show about its last submit click. +/// +/// A dispatched submission closes the confirm step, so being in flight is +/// `pending_vote_operation`, not a state of this window. pub enum VoteHandlingStatus { NotStarted, - CastingVotes, - SchedulingVotes, - Completed, - Failed(String), + /// The click produced nothing to send; the window stays open on the reason. + Failed(VoteSubmissionError), } #[derive(PartialEq)] @@ -95,8 +468,6 @@ pub enum RefreshingStatus { #[derive(Clone, Copy, PartialEq, Eq)] enum SortColumn { ContestedName, - LockedVotes, - AbstainVotes, EndingTime, LastUpdated, AwardedTo, @@ -108,112 +479,259 @@ enum SortOrder { Descending, } -/// The main, combined DPNSScreen: -/// - Displays active/past/owned DPNS contests -/// - Allows clicking selection of votes (bulk scheduling) -/// - Allows single immediate vote or single schedule -/// - Shows scheduled votes listing +/// The Masternodes ▸ Votes panel: the single voting workspace. +/// +/// One instance lives inside [`crate::ui::masternodes::MasternodesScreen`]; it +/// owns the contest cache, the composer and the scheduled-vote views. pub struct DPNSScreen { voting_identities: Vec, - user_identities: Vec, + voting_identity_load_error: Option, contested_names: Arc>>, - local_dpns_names: Arc>>, - pub scheduled_votes: Arc>>, - pub scheduled_vote_cast_in_progress: bool, + active_contests: ActiveDpnsContestSnapshot, + /// Rebuilt from `active_contests` and `contested_names` whenever either is + /// replaced. Keep the three in step: the render path reads only this. + candidate_names: CandidateNameIndex, + scheduled_votes: Arc>>, + scheduled_groups: Arc<[ScheduledDecisionGroup]>, pub selected_votes: Vec, pub app_context: Arc, pending_backend_task: Option, + /// A preference to persist through the backend once no user action is out. + pending_preference: Option, + vote_operations: DpnsVoteOperationSnapshot, + vote_state: DpnsVoteStateSnapshot, + pending_vote_operation: Option, + submitted_votes: BTreeMap, + submitted_cards: BTreeSet, + pending_scheduled_actions: BTreeMap, + /// Set by `display_backend_task_error` when the failed task is this + /// panel's pending submission; `display_task_error` then releases it. + release_pending_on_error: bool, + scheduled_clear_dialog: Option<(bool, ConfirmationDialog)>, + scheduled_vote_editor: Option, /// Sorting sort_column: SortColumn, sort_order: SortOrder, active_filter_term: String, past_filter_term: String, - owned_filter_term: String, - /// Which sub-screen is active: Active contests, Past, Owned, or Scheduled - pub dpns_subscreen: DPNSSubscreen, + /// The visible Votes sub-view. + pub view: VotesView, refreshing_status: RefreshingStatus, refresh_banner: Option, + journal_error_banner: Option, + + /// Whether the confirm step is open. + confirm_open: bool, + /// Per-node overrides under `Adjust nodes`; absent means "same as above". + node_overrides: BTreeMap, + /// Nodes loaded after decisions were staged. The confirm step opens with + /// them on `Don't use this node` until the operator picks another option + /// for them or a fresh set of decisions is staged. + late_nodes: BTreeSet, + /// Set by `Review again`: the confirm step covers only this target. + retry: Option, + /// The retried target of the pending submission, kept so a submission + /// that needs another review reopens on it. + submitted_retry: Option, + confirm_status: VoteHandlingStatus, + submission_error_banner: Option, + confirm_timing: ConfirmTiming, + /// Lead time for "When voting is about to end" (VOTE-FR-081). + relative_preset: std::time::Duration, + /// Eagerly built, unlike most components: its default is the construction + /// time plus a day, and the read-only accessors below must see it. + confirm_schedule: UtcScheduleInput, + /// Set when the operator asks to load a node; the hosting Masternodes + /// screen consumes it and opens its load form. + load_node_requested: bool, - /// Selected vote handling - show_bulk_schedule_popup: bool, - bulk_identity_options: Vec, - bulk_schedule_message: Option<(MessageType, String)>, - bulk_vote_handling_status: VoteHandlingStatus, - vote_banner: Option, - set_all_option: VoteOption, + /// Node set for this session; starts from the saved default (VOTE-FR-075). + node_set: NodeSet, + /// Network `node_set` was loaded for; `None` forces a reload. + node_set_network: Option, + voting_nodes: Vec, + resolved_nodes: ResolvedNodeSet, + node_labels: BTreeMap, + /// Open contests as cards, sorted by time left. Rebuilt by `rebuild_cards`. + cards: Vec, + /// "Before the end" presets of scheduled rows, by target and time; a row + /// without one shows its absolute time only (VOTE-FR-081). + relative_schedule_labels: BTreeMap<(DpnsVoteTargetKey, u64), std::time::Duration>, + /// Settled failures older than this are not raised in `Needs attention`. + session_started_ms: u64, + /// Cards ticked for a bulk decision, by contest name. + selected_cards: BTreeSet, + focused_card: Option, + /// Whether the contest list has keyboard focus for shortcuts. + list_focused: bool, } impl DPNSScreen { - pub fn new(app_context: &Arc, dpns_subscreen: DPNSSubscreen) -> Self { - // Load contested names, local dpns, scheduled, etc.: - let contested_names = Arc::new(Mutex::new(match dpns_subscreen { - DPNSSubscreen::Active => app_context.ongoing_contested_names().unwrap_or_default(), - DPNSSubscreen::Past => app_context.all_contested_names().unwrap_or_default(), - DPNSSubscreen::Owned => Vec::new(), - DPNSSubscreen::ScheduledVotes => Vec::new(), - })); - - let local_dpns_names = Arc::new(Mutex::new(match dpns_subscreen { - DPNSSubscreen::Active => Vec::new(), - DPNSSubscreen::Past => Vec::new(), - DPNSSubscreen::Owned => app_context.local_dpns_names().unwrap_or_default(), - DPNSSubscreen::ScheduledVotes => Vec::new(), - })); - - let scheduled_votes = app_context.get_scheduled_votes().unwrap_or_default(); - let scheduled_votes_with_status = Arc::new(Mutex::new( - scheduled_votes - .iter() - .map(|vote| { - if vote.executed_successfully { - (vote.clone(), ScheduledVoteCastingStatus::Completed) - } else { - (vote.clone(), ScheduledVoteCastingStatus::NotStarted) - } - }) - .collect::>(), + /// Whether `display_task_result` acts on `result`. `AppState` delivers + /// such results even while the panel is hidden; a missed one would strand + /// the panel in the state that result was meant to clear. + pub(crate) fn handles_result(result: &BackendTaskSuccessResult) -> bool { + VotesPanelResult::of(result).is_some() + } + + pub fn new(app_context: &Arc, view: VotesView) -> Self { + let vote_operations = DpnsVoteOperationSnapshot::load(app_context); + let scheduled_votes = Arc::new(Mutex::new(vote_operations.scheduled_vote_rows())); + + // One instance serves every sub-view, so it loads every cache. + let contested_names = Arc::new(Mutex::new( + app_context.all_contested_names().unwrap_or_default(), )); + let active_contests = ActiveDpnsContestSnapshot::new( + app_context, + app_context.ongoing_contested_names().unwrap_or_default(), + ); - let voting_identities = app_context - .load_local_voting_identities() - .unwrap_or_default(); - let user_identities = app_context.load_local_user_identities().unwrap_or_default(); + let candidate_names = + candidate_name_index(&active_contests, &contested_names.lock_recover()); + + let (voting_identities, voting_identity_load_error) = + match loaded_voting_identities(app_context) { + Ok(identities) => (identities, None), + Err(error) => { + tracing::warn!(?error, "Could not load local DPNS voting identities"); + (Vec::new(), Some(error)) + } + }; + let vote_poll_ids = active_contests.vote_poll_ids(); + let voter_ids = voting_identities + .iter() + .map(|identity| identity.identity.id()) + .collect::>(); + let mut vote_state = DpnsVoteStateSnapshot::default(); + if let Err(error) = vote_state.refresh(app_context, &voter_ids, &vote_poll_ids) { + tracing::warn!(?error, "Could not cache proved DPNS vote state"); + } - // Initialize vote handling pop-up state to hidden - let identity_count = voting_identities.len(); - let bulk_identity_options = vec![VoteOption::CastNow; identity_count]; + // The confirm step's fixed-time input starts one day ahead. + let default_schedule_time = Utc::now() + chrono::Duration::days(1); - Self { + let mut screen = Self { voting_identities, - user_identities, + voting_identity_load_error, contested_names, - local_dpns_names, - scheduled_votes: scheduled_votes_with_status, + active_contests, + candidate_names, + scheduled_votes, + scheduled_groups: Arc::from([]), selected_votes: Vec::new(), app_context: app_context.clone(), sort_column: SortColumn::ContestedName, sort_order: SortOrder::Ascending, active_filter_term: String::new(), past_filter_term: String::new(), - owned_filter_term: String::new(), - scheduled_vote_cast_in_progress: false, pending_backend_task: None, - dpns_subscreen, + pending_preference: None, + vote_operations, + vote_state, + pending_vote_operation: None, + submitted_votes: BTreeMap::new(), + submitted_cards: BTreeSet::new(), + pending_scheduled_actions: BTreeMap::new(), + release_pending_on_error: false, + session_started_ms: now_ms(), + scheduled_clear_dialog: None, + scheduled_vote_editor: None, + view, refreshing_status: RefreshingStatus::NotRefreshing, refresh_banner: None, + journal_error_banner: None, // Vote handling - show_bulk_schedule_popup: false, - bulk_identity_options, - bulk_schedule_message: None, - bulk_vote_handling_status: VoteHandlingStatus::NotStarted, - vote_banner: None, - set_all_option: VoteOption::CastNow, + confirm_open: false, + node_overrides: BTreeMap::new(), + late_nodes: BTreeSet::new(), + retry: None, + submitted_retry: None, + confirm_status: VoteHandlingStatus::NotStarted, + submission_error_banner: None, + confirm_timing: ConfirmTiming::Now, + relative_preset: relative_schedule_preset(app_context.network()), + confirm_schedule: UtcScheduleInput::new().with_time(default_schedule_time), + load_node_requested: false, + node_set: NodeSet::All, + node_set_network: None, + voting_nodes: Vec::new(), + resolved_nodes: ResolvedNodeSet::default(), + node_labels: BTreeMap::new(), + cards: Vec::new(), + relative_schedule_labels: BTreeMap::new(), + selected_cards: BTreeSet::new(), + focused_card: None, + list_focused: false, + }; + screen.rebuild_cards(); + screen.rebuild_scheduled_vote_rows(); + screen + } + + /// Consume a pending "load a masternode" request from this panel. + pub fn take_load_node_request(&mut self) -> bool { + std::mem::take(&mut self.load_node_requested) + } + + fn finish_scheduled_dispatch(&mut self, context: &BackendTaskContext) -> bool { + let key = self + .pending_scheduled_actions + .iter() + .find(|(_, pending)| *pending == context) + .map(|(key, _)| key.clone()); + if let Some(key) = key { + self.pending_scheduled_actions.remove(&key); + true + } else { + false } } + pub(crate) fn reset_for_network_switch(&mut self) { + self.selected_votes.clear(); + self.confirm_open = false; + self.confirm_status = VoteHandlingStatus::NotStarted; + self.node_overrides.clear(); + self.late_nodes.clear(); + self.retry = None; + self.submitted_retry = None; + self.confirm_timing = ConfirmTiming::Now; + self.relative_preset = relative_schedule_preset(self.app_context.network()); + self.pending_backend_task = None; + self.pending_preference = None; + self.pending_vote_operation = None; + self.submitted_votes.clear(); + self.submitted_cards.clear(); + self.pending_scheduled_actions.clear(); + self.release_pending_on_error = false; + self.scheduled_clear_dialog = None; + self.scheduled_vote_editor = None; + self.refresh_banner.take_and_clear(); + self.journal_error_banner.take_and_clear(); + self.submission_error_banner.take_and_clear(); + self.refreshing_status = RefreshingStatus::NotRefreshing; + self.voting_identities.clear(); + self.voting_identity_load_error = None; + self.vote_state = DpnsVoteStateSnapshot::default(); + self.vote_operations = DpnsVoteOperationSnapshot::default(); + self.active_contests = ActiveDpnsContestSnapshot::default(); + self.candidate_names.clear(); + self.contested_names.lock_recover().clear(); + self.scheduled_votes.lock_recover().clear(); + self.scheduled_groups = Arc::from([]); + self.node_set_network = None; + self.voting_nodes.clear(); + self.resolved_nodes = ResolvedNodeSet::default(); + self.cards.clear(); + self.selected_cards.clear(); + self.focused_card = None; + self.list_focused = false; + } + // --------------------------- // Sorting // --------------------------- @@ -235,8 +753,6 @@ impl DPNSScreen { SortColumn::ContestedName => a .normalized_contested_name .cmp(&b.normalized_contested_name), - SortColumn::LockedVotes => a.locked_votes.cmp(&b.locked_votes), - SortColumn::AbstainVotes => a.abstain_votes.cmp(&b.abstain_votes), SortColumn::EndingTime => a.end_time.cmp(&b.end_time), SortColumn::LastUpdated => a.last_updated.cmp(&b.last_updated), SortColumn::AwardedTo => a.awarded_to.cmp(&b.awarded_to), @@ -252,442 +768,745 @@ impl DPNSScreen { // --------------------------- // Rendering: Empty states // --------------------------- - fn render_no_active_contests_or_owned_names(&mut self, ui: &mut Ui) -> AppAction { - let mut app_action = AppAction::None; + fn no_voting_nodes_copy(&self) -> (&'static str, &'static str, &'static str) { + if self.voting_nodes.is_empty() { + ( + NO_VOTING_NODES_MESSAGE, + NO_VOTING_NODES_DETAIL, + "Load a masternode", + ) + } else { + ( + "None of your nodes has a voting key on this device.", + "Add a voting key to vote. One key can serve several nodes.", + "Add a voting key", + ) + } + } + + fn render_no_voting_nodes(&mut self, ui: &mut Ui) { + let (heading, detail, button) = self.no_voting_nodes_copy(); + let dark_mode = ui.style().visuals.dark_mode; ui.vertical_centered(|ui| { - ui.add_space(20.0); - match self.dpns_subscreen { - DPNSSubscreen::Active => { + ui.add_space(24.0); + egui::Frame::group(ui.style()).show(ui, |ui| { + ui.set_max_width(520.0); + ui.vertical_centered(|ui| { ui.label( - egui::RichText::new("No active contests at the moment.") - .heading() + RichText::new(heading) .strong() - .color(Color32::GRAY), + .color(DashColors::warning_color(dark_mode)), ); - } - DPNSSubscreen::Past => { - ui.label( - egui::RichText::new("No active or past contests at the moment.") - .heading() - .strong() - .color(Color32::GRAY), - ); - } - DPNSSubscreen::Owned => { - ui.label( - egui::RichText::new("No owned usernames.") - .heading() - .strong() - .color(Color32::GRAY), - ); - } - DPNSSubscreen::ScheduledVotes => { - ui.label( - egui::RichText::new("No scheduled votes.") - .heading() - .strong() - .color(Color32::GRAY), - ); - } - } - ui.add_space(10.0); + ui.label(RichText::new(detail).color(DashColors::text_primary(dark_mode))); + ui.add_space(12.0); + if ComponentStyles::add_primary_button(ui, button).clicked() { + self.load_node_requested = true; + } + }); + }); + }); + } - if self.dpns_subscreen != DPNSSubscreen::ScheduledVotes { - let dark_mode = ui.style().visuals.dark_mode; - ui.label(RichText::new("Please check back later or try refreshing the list.").color(DashColors::text_primary(dark_mode))); + fn render_empty_view(&mut self, ui: &mut Ui) -> AppAction { + let mut app_action = AppAction::None; + let dark_mode = ui.style().visuals.dark_mode; + let (heading, detail) = match self.view { + VotesView::ToDecide | VotesView::Voted => (NO_OPEN_CONTESTS_MESSAGE, None), + VotesView::History => ("There are no finished name contests yet.", None), + VotesView::Scheduled => ( + "No scheduled votes.", + Some("Pick a decision in To decide, then choose a later time in the confirm step."), + ), + }; + ui.vertical_centered(|ui| { + ui.add_space(20.0); + ui.label( + RichText::new(heading) + .heading() + .strong() + .color(DashColors::text_secondary(dark_mode)), + ); + if let Some(detail) = detail { + ui.add_space(10.0); + ui.label(RichText::new(detail).color(DashColors::text_primary(dark_mode))); + } + if self.view != VotesView::Scheduled { ui.add_space(20.0); - if StyledButton::primary("Refresh").show(ui).clicked() { - if let RefreshingStatus::Refreshing = self.refreshing_status { - app_action = AppAction::None; - } else { - self.refreshing_status = RefreshingStatus::Refreshing; - match self.dpns_subscreen { - DPNSSubscreen::Active | DPNSSubscreen::Past => { - app_action = AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::QueryDPNSContests, - )); - } - DPNSSubscreen::Owned => { - app_action = AppAction::BackendTask(BackendTask::IdentityTask( - IdentityTask::RefreshLoadedIdentitiesOwnedDPNSNames, - )); - } - _ => { - app_action = AppAction::Refresh; - } - } - } + let refreshing = self.refreshing_status == RefreshingStatus::Refreshing; + if ComponentStyles::add_primary_button_enabled(ui, !refreshing, "Refresh") + .disabled_tooltip("Contests are already being refreshed.") + .clicked() + { + app_action = AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::QueryDPNSContests, + )); } - } else { - let dark_mode = ui.style().visuals.dark_mode; - let text_color = DashColors::text_primary(dark_mode); - ui.label( - RichText::new("To schedule votes, go to the Active Contests subscreen, click your choices, and then click the 'Vote' button in the top-right.").color(text_color) - ); } }); - app_action } // --------------------------- - // Rendering: Active, Past, Owned, Scheduled + // Rendering: To decide, Voted, Scheduled, History // --------------------------- - /// Show the Active Contests table - fn render_table_active_contests(&mut self, ui: &mut Ui) { - ui.horizontal(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - ui.label(RichText::new("Filter by name:").color(DashColors::text_primary(dark_mode))); - ui.text_edit_singleline(&mut self.active_filter_term); - }); + /// The loaded voting nodes plus key-less ones, as the node-set picker sees them. + fn collect_voting_nodes(&self) -> Vec { + let mut nodes: Vec = self + .voting_identities + .iter() + .map(|identity| self.app_context.dpns_voting_node(identity)) + .collect(); + match self.app_context.dpns_voting_nodes() { + Ok(all) => { + let known: BTreeSet = nodes.iter().map(|node| node.id).collect(); + nodes.extend( + all.into_iter() + .filter(|node| !node.has_voting_key && !known.contains(&node.id)), + ); + } + Err(error) => tracing::debug!(?error, "Could not list key-less nodes for the node set"), + } + nodes + } - let contested_names = { - let guard = self.contested_names.lock_recover(); - let mut cn = guard.clone(); - if !self.active_filter_term.is_empty() { - let mut filter_lc = self.active_filter_term.to_lowercase(); - // Convert o and O to 0 and l to 1 in filter_lc - filter_lc = filter_lc - .chars() - .map(|c| match c { - 'o' | 'O' => '0', - 'l' => '1', - _ => c, - }) - .collect(); - cn.retain(|c| { - c.normalized_contested_name - .to_lowercase() - .contains(&filter_lc) + /// Rebuild the card view-model from contests, proved state, the journal and + /// the node set. Call after any of them changes; rendering only reads it. + pub(crate) fn rebuild_cards(&mut self) { + let network = self.app_context.network(); + if self.node_set_network != Some(network) { + self.node_set = self + .app_context + .saved_dpns_node_set() + .unwrap_or_else(|error| { + tracing::debug!( + ?error, + "Could not read the saved node set; voting with all nodes" + ); + NodeSet::All + }); + self.node_set_network = Some(network); + } + self.voting_nodes = self.collect_voting_nodes(); + self.resolved_nodes = self.node_set.resolve(&self.voting_nodes); + self.node_labels = self + .voting_nodes + .iter() + .filter_map(|node| node.alias.clone().map(|alias| (node.id, alias))) + .collect(); + let mut cards: Vec = self + .active_contests + .contests() + .iter() + .map(|view| { + let nodes = view.vote_poll_id.map_or_else(Vec::new, |poll| { + self.resolved_nodes + .included + .iter() + .map(|voter| { + let state = self.vote_state.state(*voter, poll); + let lock = self.vote_operations.target_status(&DpnsVoteTargetKey { + network, + voter_id: *voter, + vote_poll_id: poll, + }); + let changes = self.app_context.dpns_changes_left(*voter, poll, state); + NodeContestState { + node: *voter, + status: NodeContestStatus::classify(state, lock, changes), + current: match state { + DpnsCurrentVoteState::Available(current) => current, + _ => None, + }, + changes, + } + }) + .collect() }); + VoteCard::new(view.contest.clone(), view.vote_poll_id, nodes) + }) + .collect(); + sort_by_time_left(&mut cards); + self.cards = cards; + let names: BTreeSet<&str> = self.cards.iter().map(VoteCard::name).collect(); + self.selected_cards + .retain(|name| names.contains(name.as_str())); + } + + /// What the staged decisions would submit across their submittable + /// nodes: votes for nodes not on the choice, and checks for nodes shown on + /// it by proof too old to decide. Nodes proved on it recently count as + /// neither, and so do nodes with no changes left, which the composer + /// skips on any proof. + fn tray_counts(&self) -> TrayCounts { + let now = now_ms(); + let mut counts = TrayCounts::default(); + for vote in &self.selected_votes { + let Some(card) = self + .cards + .iter() + .find(|card| card.name() == vote.contested_name) + else { + continue; + }; + for node in card.nodes.iter().filter(|node| node.status.can_submit()) { + if node.current != Some(vote.vote_choice) { + counts.transactions += 1; + } else if !card.vote_poll_id.is_some_and(|poll| { + vote_proof_can_decide(self.vote_state.proved_at(node.node, poll), now) + }) { + counts.rechecks += 1; + } } - self.sort_contested_names(&mut cn); - cn + } + counts + } + + /// Show one contest by normalized label: the view holding its card, the + /// filter set to the label and the card focused. + pub(crate) fn show_contest(&mut self, label: String) { + self.view = match self + .cards + .iter() + .find(|card| card.name() == label) + .map(|card| card.placement) + { + Some(CardPlacement::Voted) => VotesView::Voted, + _ => VotesView::ToDecide, }; + self.active_filter_term = label.clone(); + self.focused_card = Some(label); + self.list_focused = true; + } - // Space allocation for UI elements is handled by the layout system + /// Give up list keyboard focus, e.g. when the Votes segment is left. + pub(crate) fn release_list_focus(&mut self) { + self.list_focused = false; + } - egui::ScrollArea::both().show(ui, |ui| { - TableBuilder::new(ui) - .striped(false) - .resizable(true) - .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) - .column(Column::auto().resizable(true)) // Contested Name - .column(Column::auto().resizable(true)) // Locked - .column(Column::auto().resizable(true)) // Abstain - .column(Column::auto().resizable(true)) // Ending Time - .column(Column::auto().resizable(true)) // Last Updated - .column(Column::auto().resizable(true)) // Contestants - .header(30.0, |mut header| { - header.col(|ui| { - if ui.button("Name").clicked() { - self.toggle_sort(SortColumn::ContestedName); - } - }); - header.col(|ui| { - if ui.button("Locked Votes").clicked() { - self.toggle_sort(SortColumn::LockedVotes); - } - }); - header.col(|ui| { - if ui.button("Abstain Votes").clicked() { - self.toggle_sort(SortColumn::AbstainVotes); - } - }); - header.col(|ui| { - if ui.button("Ending Time").clicked() { - self.toggle_sort(SortColumn::EndingTime); - } - }); - header.col(|ui| { - if ui.button("Last Updated").clicked() { - self.toggle_sort(SortColumn::LastUpdated); - } - }); - header.col(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - ui.heading( - RichText::new("Contestants").color(DashColors::text_primary(dark_mode)), + /// Vote with one node for this session (VOTE-FR-076): To decide opens with + /// that node as the node set and no staged decisions carried over. + pub fn vote_with_node(&mut self, node: Identifier) { + self.selected_votes.clear(); + self.selected_cards.clear(); + self.view = VotesView::ToDecide; + // The node may have been loaded after this panel last read its nodes. + self.refresh_on_arrival(); + self.apply_node_set(NodeSet::Custom(BTreeSet::from([node]))); + } + + fn apply_node_set(&mut self, node_set: NodeSet) { + self.node_set = node_set; + self.rebuild_cards(); + } + + /// The `Vote with:` chip and its popover, when any node is loaded. + fn render_node_set_chip(&mut self, ui: &mut Ui) { + if self.voting_nodes.is_empty() { + return; + } + let picked = + node_set_picker::show(ui, &self.node_set, &self.resolved_nodes, &self.voting_nodes); + if picked.save_default { + self.pending_preference = Some(DpnsVotingPreference::NodeSet(self.node_set.clone())); + } + if let Some(node_set) = picked.changed { + self.apply_node_set(node_set); + } + } + + /// Render To decide or Voted: node-set chip, filter, cards and the tray. + fn render_active_contests(&mut self, ui: &mut Ui) { + let dark_mode = ui.style().visuals.dark_mode; + ui.horizontal(|ui| { + self.render_node_set_chip(ui); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let shortcuts = ui.button("Shortcuts"); + egui::Popup::from_toggle_button_response(&shortcuts) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| { + ui.label( + RichText::new("Shortcuts work while the list of names has focus.") + .strong(), ); + egui::Grid::new("dpns_vote_shortcuts").show(ui, |ui| { + for (keys, action) in SHORTCUT_HELP { + ui.label(RichText::new(keys).monospace()); + ui.label(action); + ui.end_row(); + } + }); }); + let filter = ui + .add( + egui::TextEdit::singleline(&mut self.active_filter_term) + .hint_text("Filter by name") + .desired_width(180.0), + ) + .on_hover_text(NAME_FILTER_LOOKALIKES_HINT); + if filter.has_focus() { + self.list_focused = false; + } + }); + }); + ui.add_space(8.0); + + let filter = normalize_dpns_label(&self.active_filter_term); + let view = self.view; + let now = crate::utils::time::now_ms(); + let network = self.app_context.network(); + let durations = contest_durations(network, self.app_context.platform_version()); + let urgency = urgency_window(network); + let has_voting_nodes = !self.resolved_nodes.included.is_empty(); + let matches_filter = + |card: &VoteCard| filter.is_empty() || card.name().to_lowercase().contains(&filter); + let listed: Vec = self + .cards + .iter() + .enumerate() + .filter(|(_, card)| matches_filter(card)) + .filter(|(_, card)| match view { + VotesView::Voted => card.placement == CardPlacement::Voted, + // Unproved state is temporary and fixed by a refresh, so those + // cards stay in view rather than in the collapsed group. + _ => matches!( + card.placement, + CardPlacement::ToDecide + | CardPlacement::CantVote(CantVoteReason::VoteStateUnavailable) + ), + }) + .map(|(index, _)| index) + .collect(); + let cant_vote: Vec = if view == VotesView::ToDecide { + self.cards + .iter() + .enumerate() + .filter(|(_, card)| matches_filter(card)) + .filter(|(_, card)| { + card.placement == CardPlacement::CantVote(CantVoteReason::NoVotingNodes) }) - .body(|mut body| { - for contested_name in &contested_names { - body.row(25.0, |mut row| { - let locked_votes = contested_name.locked_votes.unwrap_or(0); - let max_contestant_votes = contested_name - .contestants - .as_ref() - .map(|contestants| { - contestants.iter().map(|c| c.votes).max().unwrap_or(0) - }) - .unwrap_or(0); - let is_locked_votes_bold = locked_votes > max_contestant_votes; - - // Contested Name - row.col(|ui| { - let (used_name, highlighted) = - if let Some(contestants) = &contested_name.contestants { - if let Some(first) = contestants.first() { - if contestants.iter().all(|c| c.name == first.name) { - // Everyone has same name - ( - first.name.clone(), - Some( - contested_name - .normalized_contested_name - .clone(), - ), - ) - } else { - // Multiple different names - ( - contestants - .iter() - .map(|c| c.name.clone()) - .join(" or "), - Some( - contestants - .iter() - .map(|c| { - format!( - "{} trying to get {}", - c.id, - c.name.clone() - ) - }) - .join(" and "), - ), - ) - } - } else { - (contested_name.normalized_contested_name.clone(), None) - } - } else { - (contested_name.normalized_contested_name.clone(), None) - }; + .map(|(index, _)| index) + .collect() + } else { + Vec::new() + }; - let dark_mode = ui.style().visuals.dark_mode; - let label_response = ui.label( - RichText::new(used_name) - .color(DashColors::text_primary(dark_mode)), - ); - if let Some(tooltip) = highlighted { - label_response.info_tooltip(tooltip); - } - }); + let scroll_to = self.handle_shortcuts(ui, &listed); + self.render_bulk_bar(ui); - // LOCK button - row.col(|ui| { - let label_text = format!("{}", locked_votes); - let dark_green = Color32::from_rgb(0, 100, 0); - let dark_mode = ui.style().visuals.dark_mode; - let normal_color = DashColors::text_primary(dark_mode); - let text_widget = if is_locked_votes_bold { - RichText::new(label_text).strong().color(dark_green) - } else { - RichText::new(label_text).color(normal_color) - }; + let mut events: Vec<(usize, CardEvent)> = Vec::new(); + let list = egui::ScrollArea::vertical() + .id_salt("active_contest_cards") + .max_height(ui.available_height() - 48.0) + .show(ui, |ui| { + if listed.is_empty() { + let empty = match view { + VotesView::Voted => "Your nodes haven't voted on any open contest yet.", + _ => "Nothing needs your vote right now.", + }; + ui.label(RichText::new(empty).color(DashColors::text_secondary(dark_mode))); + } + let render = |ui: &mut Ui, index: usize, events: &mut Vec<(usize, CardEvent)>| { + let card = &self.cards[index]; + let staged = self + .selected_votes + .iter() + .find(|vote| vote.contested_name == card.name()) + .map(|vote| vote.vote_choice); + let card_events = CardView { + card, + staged, + selected: self.selected_cards.contains(card.name()), + focused: self.focused_card.as_deref() == Some(card.name()), + scroll_into_view: scroll_to.as_deref() == Some(card.name()), + node_labels: &self.node_labels, + node_set_weight: self.resolved_nodes.weight, + now_ms: now, + urgency, + durations, + has_voting_nodes, + } + .show(ui); + events.extend(card_events.into_iter().map(|event| (index, event))); + ui.add_space(8.0); + }; + for index in &listed { + render(ui, *index, &mut events); + } + if !cant_vote.is_empty() { + egui::CollapsingHeader::new(format!( + "Can't vote with your nodes ({count})", + count = cant_vote.len() + )) + .default_open(!has_voting_nodes) + .show(ui, |ui| { + ui.label( + RichText::new(CANT_VOTE_REASON) + .color(DashColors::text_secondary(dark_mode)), + ); + for index in &cant_vote { + render(ui, *index, &mut events); + } + }); + } + }); - // See if this (LOCK) is selected - let is_selected = self.selected_votes.iter().any(|sv| { - sv.contested_name == contested_name.normalized_contested_name - && sv.vote_choice == ResourceVoteChoice::Lock - }); + // The list owns keyboard focus after a click inside it (VOTE-NFR-010). + if let Some(pos) = ui.input(|input| { + input + .pointer + .any_pressed() + .then(|| input.pointer.interact_pos()) + .flatten() + }) { + self.list_focused = list.inner_rect.contains(pos); + } + if !events.is_empty() { + self.list_focused = true; + } + for (index, event) in events { + let name = self.cards[index].name().to_owned(); + match event { + CardEvent::Choose(choice) => { + let contest = Arc::clone(&self.cards[index].contest); + self.set_selected_vote(&contest, choice); + } + CardEvent::ToggleSelected => { + if !self.selected_cards.remove(&name) { + self.selected_cards.insert(name.clone()); + } + } + CardEvent::RefreshVoting + if self.refreshing_status != RefreshingStatus::Refreshing => + { + self.pending_backend_task = Some(BackendTask::ContestedResourceTask( + ContestedResourceTask::QueryDPNSContests, + )); + } + CardEvent::RefreshVoting => {} + } + self.focused_card = Some(name); + } - let button = if is_selected { - Button::new(text_widget).fill(Color32::from_rgb(0, 150, 255)) - } else { - Button::new(text_widget) - }; - let resp = ui.add(button); - if resp.clicked() { - // Is there already a selection for this contested name? - if let Some(existing_index) = - self.selected_votes.iter().position(|sv| { - sv.contested_name - == contested_name.normalized_contested_name - }) - { - // If the user clicked the same choice, that toggles it off (unselect). - if self.selected_votes[existing_index].vote_choice - == ResourceVoteChoice::Lock - { - // Remove it entirely -> no selection - self.selected_votes.remove(existing_index); - } else { - // Otherwise replace the old choice with Lock - self.selected_votes[existing_index].vote_choice = - ResourceVoteChoice::Lock; - } - } else { - // No existing selection for this name, so add this new Lock - self.selected_votes.push(SelectedVote { - contested_name: contested_name - .normalized_contested_name - .clone(), - vote_choice: ResourceVoteChoice::Lock, - end_time: contested_name.end_time, - }); - } - } - }); + self.render_tray(ui); + } - // ABSTAIN button - row.col(|ui| { - let abstain_votes = contested_name.abstain_votes.unwrap_or(0); - let label_text = format!("{}", abstain_votes); + /// Stage `choice` for a contest (never toggles it off). + fn stage_choice(&mut self, contest: &ContestedName, choice: ResourceVoteChoice) { + match self + .selected_votes + .iter_mut() + .find(|vote| vote.contested_name == contest.normalized_contested_name) + { + Some(vote) => vote.vote_choice = choice, + None => { + // A fresh set of decisions starts with every loaded node. + if self.selected_votes.is_empty() { + self.late_nodes.clear(); + } + self.selected_votes.push(SelectedVote { + contested_name: contest.normalized_contested_name.clone(), + vote_choice: choice, + end_time: contest.end_time, + }); + } + } + } - let is_selected = self.selected_votes.iter().any(|sv| { - sv.contested_name == contested_name.normalized_contested_name - && sv.vote_choice == ResourceVoteChoice::Abstain - }); + fn clear_choice(&mut self, contested_name: &str) { + self.selected_votes + .retain(|vote| vote.contested_name != contested_name); + } - let button = if is_selected { - Button::new(label_text).fill(Color32::from_rgb(0, 150, 255)) - } else { - Button::new(label_text) - }; - let resp = ui.add(button); - if resp.clicked() { - // Is there already a selection for this contested name? - if let Some(existing_index) = - self.selected_votes.iter().position(|sv| { - sv.contested_name - == contested_name.normalized_contested_name - }) - { - // If the user clicked the same choice, that toggles it off (unselect). - if self.selected_votes[existing_index].vote_choice - == ResourceVoteChoice::Abstain - { - // Remove it entirely -> no selection - self.selected_votes.remove(existing_index); - } else { - // Otherwise replace the old choice with Abstain - self.selected_votes[existing_index].vote_choice = - ResourceVoteChoice::Abstain; - } - } else { - // No existing selection for this name, so add this new Abstain - self.selected_votes.push(SelectedVote { - contested_name: contested_name - .normalized_contested_name - .clone(), - vote_choice: ResourceVoteChoice::Abstain, - end_time: contested_name.end_time, - }); - } - } - }); + /// Apply this frame's list shortcuts (VOTE-FR-082). Active only while the + /// list has focus and no text field wants the keyboard (VOTE-NFR-010). + /// Returns the card to scroll into view when focus moved. + fn handle_shortcuts(&mut self, ui: &Ui, listed: &[usize]) -> Option { + if !self.list_focused || self.confirm_open || ui.ctx().egui_wants_keyboard_input() { + return None; + } + let shortcuts: Vec = ui.input(|input| { + input + .events + .iter() + .filter_map(|event| match event { + egui::Event::Key { + key, + pressed: true, + modifiers, + .. + } if modifiers.is_none() => shortcut_for(*key), + _ => None, + }) + .collect() + }); + let mut scroll_to = None; + for shortcut in shortcuts { + let position = listed + .iter() + .position(|index| Some(self.cards[*index].name()) == self.focused_card.as_deref()); + let focused = position.map(|position| listed[position]); + match shortcut { + Shortcut::Next | Shortcut::Previous => { + if let Some(next) = move_focus(position, listed.len(), shortcut) { + let name = self.cards[listed[next]].name().to_owned(); + scroll_to = Some(name.clone()); + self.focused_card = Some(name); + } + } + Shortcut::Contender(_) | Shortcut::Lock | Shortcut::Abstain => { + let Some(index) = focused else { continue }; + let card = &self.cards[index]; + if !card.accepts_decision() { + continue; + } + let choice = match shortcut { + Shortcut::Lock => Some(ResourceVoteChoice::Lock), + Shortcut::Abstain => Some(ResourceVoteChoice::Abstain), + Shortcut::Contender(n) => card + .contest + .contestants + .as_ref() + .and_then(|contenders| contenders.get(n)) + .map(|contender| ResourceVoteChoice::TowardsIdentity(contender.id)), + _ => None, + }; + if let Some(choice) = choice { + let contest = Arc::clone(&card.contest); + self.stage_choice(&contest, choice); + } + } + Shortcut::Clear => { + if let Some(index) = focused { + let name = self.cards[index].name().to_owned(); + self.clear_choice(&name); + } + } + Shortcut::ToggleSelected => { + if let Some(index) = focused { + let name = self.cards[index].name().to_owned(); + if !self.selected_cards.remove(&name) { + self.selected_cards.insert(name); + } + } + } + Shortcut::Confirm => { + if !self.selected_votes.is_empty() { + self.open_review_for_node_set(); + } + } + } + } + scroll_to + } - // Ending Time - row.col(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - if let Some(ending_time) = contested_name.end_time { - if let LocalResult::Single(dt) = - Utc.timestamp_millis_opt(ending_time as i64) - { - let iso_date = dt.format("%Y-%m-%d %H:%M:%S"); - let relative_time = HumanTime::from(dt).to_string(); - let text = format!("{} ({})", iso_date, relative_time); - ui.label( - RichText::new(text) - .color(DashColors::text_primary(dark_mode)), - ); - } else { - ui.label( - RichText::new("Invalid timestamp") - .color(DashColors::text_primary(dark_mode)), - ); - } - } else { - ui.label( - RichText::new("Fetching") - .color(DashColors::text_primary(dark_mode)), - ); - } - }); + /// Bulk bar for two or more selected names (VOTE-FR-082). + fn render_bulk_bar(&mut self, ui: &mut Ui) { + let selected = self.selected_cards.len(); + if selected < 2 { + return; + } + let mut apply: Option> = None; + ui.horizontal(|ui| { + ui.label(RichText::new(format!("{selected} names selected")).strong()); + if ui.button("Lock name").clicked() { + apply = Some(Some(ResourceVoteChoice::Lock)); + } + if ui.button("Abstain").clicked() { + apply = Some(Some(ResourceVoteChoice::Abstain)); + } + if ui.button("Clear").clicked() { + apply = Some(None); + } + }); + let Some(apply) = apply else { + return; + }; + let targets: Vec> = self + .cards + .iter() + .filter(|card| self.selected_cards.contains(card.name())) + .filter(|card| apply.is_none() || card.accepts_decision()) + .map(|card| Arc::clone(&card.contest)) + .collect(); + for contest in targets { + match apply { + Some(choice) => self.stage_choice(&contest, choice), + None => self.clear_choice(&contest.normalized_contested_name), + } + } + } - // Last Updated - row.col(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - if let Some(last_updated) = contested_name.last_updated { - if let LocalResult::Single(dt) = - Utc.timestamp_opt(last_updated as i64, 0) - { - let rel_time = HumanTime::from(dt).to_string(); - if rel_time.contains("seconds") { - ui.label( - RichText::new("now") - .color(DashColors::text_primary(dark_mode)), - ); - } else { - ui.label( - RichText::new(rel_time) - .color(DashColors::text_primary(dark_mode)), - ); - } - } else { - ui.label( - RichText::new("Invalid timestamp") - .color(DashColors::text_primary(dark_mode)), - ); - } - } else { - ui.label( - RichText::new("Fetching") - .color(DashColors::text_primary(dark_mode)), - ); - } - }); + /// The tray under the list: what is staged and the Cast action (VOTE-FR-086). + fn render_tray(&mut self, ui: &mut Ui) { + let decisions = self.selected_votes.len(); + if decisions == 0 { + return; + } + let TrayCounts { + transactions, + rechecks, + } = self.tray_counts(); + ui.separator(); + ui.horizontal(|ui| { + ui.label(RichText::new(tray_label(decisions, transactions)).strong()); + if rechecks > 0 { + ui.label(tray_recheck_label(rechecks)); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ComponentStyles::add_primary_button_enabled( + ui, + transactions + rechecks > 0 && self.pending_vote_operation.is_none(), + "Cast", + ) + .disabled_tooltip(if self.pending_vote_operation.is_some() { + "Votes are being submitted. Wait for the result before sending another batch." + } else { + "Your nodes already hold these choices. Pick a different decision." + }) + .clicked() + { + self.open_review_for_node_set(); + } + if ui.button("Clear").clicked() { + self.selected_votes.clear(); + } + }); + }); + } - // Contestants - row.col(|ui| { - self.show_contestants_for_contested_name( - ui, - contested_name, - is_locked_votes_bold, - max_contestant_votes, - ); - }); - }); + /// Open the confirm step for the staged decisions across the node set. + fn open_review_for_node_set(&mut self) { + if self.pending_vote_operation.is_some() { + return; + } + self.retry = None; + self.node_overrides.clear(); + for node in &self.late_nodes { + self.node_overrides.insert(*node, NodeTiming::DontUse); + } + self.confirm_status = VoteHandlingStatus::NotStarted; + self.confirm_open = true; + } + + /// Apply an `Adjust nodes` choice for one node. Any choice other than + /// `Don't use this node` includes a node loaded after the decisions were + /// staged. + fn set_node_timing(&mut self, voter: Identifier, timing: NodeTiming) { + if timing == NodeTiming::Batch { + self.node_overrides.remove(&voter); + } else { + self.node_overrides.insert(voter, timing); + } + if timing != NodeTiming::DontUse { + self.late_nodes.remove(&voter); + } + } + + /// Stage `choice` for a contest, or clear it when it is already staged. + fn set_selected_vote(&mut self, contest: &ContestedName, choice: ResourceVoteChoice) { + let name = &contest.normalized_contested_name; + if self + .selected_votes + .iter() + .any(|vote| vote.contested_name == *name && vote.vote_choice == choice) + { + self.clear_choice(name); + } else { + self.stage_choice(contest, choice); + } + } + + /// The contest's voting deadline as the cards last read it. + fn contest_end_time(&self, contested_name: &str) -> Option { + self.cards + .iter() + .find(|card| card.name() == contested_name) + .and_then(|card| card.contest.end_time) + } + + /// Decisions the confirm step covers: the retried one alone, else every + /// staged one. + fn review_votes(&self) -> &[SelectedVote] { + match &self.retry { + Some(retry) => std::slice::from_ref(&retry.vote), + None => &self.selected_votes, + } + } + + /// `Review again` on a failed drawer row: confirm that one node × name + /// again. The staged decisions are not part of it and stay in the tray. + fn review_failed_target(&mut self, outcome: &DpnsVoteOutcome) { + self.retry = Some(RetryReview { + voter: outcome.target.key.voter_id, + vote: SelectedVote { + contested_name: outcome.target.contested_name.clone(), + vote_choice: outcome.target.requested_choice, + end_time: self.contest_end_time(&outcome.target.contested_name), + }, + }); + self.node_overrides.clear(); + self.confirm_timing = ConfirmTiming::Now; + self.confirm_status = VoteHandlingStatus::NotStarted; + self.confirm_open = true; + } + + /// `Needs attention` row (VOTE-FR-084): unconfirmed, failed or missed + /// targets, linking to the drawer or Scheduled. + fn render_needs_attention(&mut self, ui: &mut Ui) { + let attention = needs_attention( + self.vote_operations.operations(), + self.session_started_ms, + &self.app_context.dismissed_dpns_vote_operations(), + now_ms(), + ); + if attention.is_empty() { + return; + } + let dark_mode = ui.visuals().dark_mode; + egui::Frame::group(ui.style()) + .stroke(egui::Stroke::new(1.0, DashColors::warning_color(dark_mode))) + .show(ui, |ui| { + ui.set_min_width(ui.available_width()); + ui.horizontal_wrapped(|ui| { + ui.label( + RichText::new(needs_attention_line(attention)) + .color(DashColors::warning_color(dark_mode)), + ); + if attention.checking + attention.failed > 0 + && ui.button("Show progress").clicked() + { + self.show_vote_progress(ui.ctx()); + } + if attention.missed_schedules > 0 && ui.button("Open Scheduled").clicked() { + self.view = VotesView::Scheduled; } }); - }); + }); + ui.add_space(6.0); } - /// Show a Past Contests table + /// Progress shows in the non-blocking drawer, never a window overlay + /// (VOTE-FR-035/083). + fn show_vote_progress(&self, ctx: &egui::Context) { + progress_drawer::expand(ctx); + } fn render_table_past_contests(&mut self, ui: &mut Ui) { ui.horizontal(|ui| { let dark_mode = ui.style().visuals.dark_mode; ui.label(RichText::new("Filter by name:").color(DashColors::text_primary(dark_mode))); - ui.text_edit_singleline(&mut self.past_filter_term); + ui.text_edit_singleline(&mut self.past_filter_term) + .on_hover_text(NAME_FILTER_LOOKALIKES_HINT); }); let contested_names = { let guard = self.contested_names.lock_recover(); let mut cn = guard.clone(); cn.retain(|c| c.awarded_to.is_some() || c.state == ContestState::Locked); - // 1) Filter by `past_filter_term` if !self.past_filter_term.is_empty() { - let mut filter_lc = self.past_filter_term.to_lowercase(); - // Convert o and O to 0 and l to 1 in filter_lc - filter_lc = filter_lc - .chars() - .map(|c| match c { - 'o' | 'O' => '0', - 'l' => '1', - _ => c, - }) - .collect(); - - cn.retain(|c| { - c.normalized_contested_name - .to_lowercase() - .contains(&filter_lc) - }); + let filter = normalize_dpns_label(&self.past_filter_term); + + cn.retain(|c| c.normalized_contested_name.to_lowercase().contains(&filter)); } self.sort_contested_names(&mut cn); cn @@ -704,7 +1523,8 @@ impl DPNSScreen { .column(Column::auto().resizable(true)) // Name .column(Column::auto().resizable(true)) // Ended Time .column(Column::auto().resizable(true)) // Last Updated - .column(Column::auto().resizable(true)) // Awarded To + .column(Column::auto().resizable(true)) // Outcome + .column(Column::remainder()) // details .header(30.0, |mut header| { header.col(|ui| { if ui.button("Name").clicked() { @@ -722,10 +1542,13 @@ impl DPNSScreen { } }); header.col(|ui| { - if ui.button("Awarded To").clicked() { + if ui.button("Outcome").clicked() { self.toggle_sort(SortColumn::AwardedTo); } }); + header.col(|ui| { + ui.label(RichText::new("details").strong()); + }); }) .body(|mut body| { for contested_name in &contested_names { @@ -745,10 +1568,8 @@ impl DPNSScreen { if let LocalResult::Single(dt) = Utc.timestamp_millis_opt(ended_time as i64) { - let iso = dt.format("%Y-%m-%d %H:%M:%S").to_string(); - let relative = HumanTime::from(dt).to_string(); ui.label( - RichText::new(format!("{} ({})", iso, relative)) + RichText::new(timestamp_with_relative(dt)) .color(DashColors::text_primary(dark_mode)), ); } else { @@ -813,944 +1634,951 @@ impl DPNSScreen { ); } ContestState::WonBy(identifier) => { - ui.add( - egui::Label::new( - identifier.to_string(Encoding::Base58), - ) - .sense(egui::Sense::hover()) - .truncate(), - ); + let winner = contested_name + .contestants + .as_ref() + .and_then(|contestants| { + contestants + .iter() + .find(|contestant| contestant.id == identifier) + }) + .map(|contestant| contestant.name.as_str()); + ui.label(went_to_label( + winner, + &short_identifier(identifier), + )); + if ui.small_button("Copy ID").clicked() { + ui.ctx() + .copy_text(identifier.to_string(Encoding::Base58)); + } } ContestState::Locked => { ui.label( - RichText::new("Locked") + RichText::new(LOCKED_FOR_GOOD) .color(DashColors::text_primary(dark_mode)), ); } } }); + row.col(|ui| { + if let Some(url) = platform_explorer_contest_url( + self.app_context.network(), + &contested_name.normalized_contested_name, + ) { + ui.hyperlink_to("details", url) + .on_hover_text("Open this contest in Platform Explorer in your web browser."); + } + }); }); } }); }); } - /// Show the Owned DPNS names table - fn render_table_local_dpns_names(&mut self, ui: &mut Ui) { - ui.horizontal(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - ui.label(RichText::new("Filter by name:").color(DashColors::text_primary(dark_mode))); - ui.text_edit_singleline(&mut self.owned_filter_term); - }); - - let mut filtered_names = { - let guard = self.local_dpns_names.lock_recover(); - let mut name_infos = guard.clone(); - if !self.owned_filter_term.is_empty() { - let filter_lc = self.owned_filter_term.to_lowercase(); - name_infos.retain(|c| c.1.name.to_lowercase().contains(&filter_lc)); - } - name_infos - }; - // Sort - filtered_names.sort_by(|a, b| match self.sort_column { - SortColumn::ContestedName => { - let order = a.1.name.cmp(&b.1.name); - if self.sort_order == SortOrder::Descending { - order.reverse() - } else { - order - } - } - SortColumn::AwardedTo => { - let order = a.0.cmp(&b.0); - if self.sort_order == SortOrder::Descending { - order.reverse() - } else { - order - } - } - SortColumn::EndingTime => { - let order = a.1.acquired_at.cmp(&b.1.acquired_at); - if self.sort_order == SortOrder::Descending { - order.reverse() - } else { - order - } + /// Scheduled view grouped by decision (VOTE-FR-088): one row per name × + /// choice × time with an expandable node list carrying per-node status + /// and actions. The order is fixed (name, then time): the view has no + /// sort control, and the History sort must not reach it. + fn render_table_scheduled_votes(&mut self, ui: &mut Ui) -> AppAction { + let mut action = AppAction::None; + let mut show_cast_progress = false; + let groups = Arc::clone(&self.scheduled_groups); + let now = Utc::now().timestamp_millis().max(0) as u64; + egui::ScrollArea::both().show(ui, |ui| { + for (index, group) in groups.iter().enumerate() { + let dark_mode = ui.visuals().dark_mode; + let choice = vote_choice_label( + group.choice, + self.candidate_name(&group.contested_name, group.choice), + ); + let preset = group.rows.iter().find_map(|row| { + let (_, key) = &row.journal_target; + self.relative_schedule_labels + .get(&(key.clone(), group.unix_timestamp)) + }); + let when = match preset { + Some(preset) => { + relative_schedule_label(*preset, &utc_minute(group.unix_timestamp)) + } + None => match Utc.timestamp_millis_opt(group.unix_timestamp as i64) { + LocalResult::Single(date) => timestamp_with_relative(date), + _ => "Invalid timestamp".to_owned(), + }, + }; + let needs_attention = group.rows.iter().any(|row| { + schedule_is_missed( + row.status, + VoteTiming::Scheduled(row.vote.unix_timestamp), + now, + ) || scheduled_failure_guidance(row.status, row.failure).is_some() + }); + egui::Frame::group(ui.style()).show(ui, |ui| { + ui.set_min_width(ui.available_width()); + ui.label( + RichText::new(format!( + "{name}.dash · {choice}", + name = group.contested_name + )) + .strong() + .color(DashColors::text_primary(dark_mode)), + ); + ui.label(RichText::new(when).color(DashColors::text_secondary(dark_mode))); + egui::CollapsingHeader::new(scheduled_nodes_label(group.rows.len())) + .id_salt(("scheduled_group", index)) + .default_open(group.rows.len() <= 3 || needs_attention) + .show(ui, |ui| { + self.render_scheduled_group_rows( + ui, + index, + &group.rows, + &mut action, + &mut show_cast_progress, + ); + }); + }); + ui.add_space(6.0); } - _ => std::cmp::Ordering::Equal, }); + if show_cast_progress { + self.show_vote_progress(ui.ctx()); + } + action + } - // Space allocation for UI elements is handled by the layout system - - egui::ScrollArea::both().show(ui, |ui| { - TableBuilder::new(ui) - .striped(false) - .resizable(true) - .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) - .column(Column::auto().resizable(true)) // DPNS Name - .column(Column::auto().resizable(true)) // Owner ID - .column(Column::auto().resizable(true)) // Acquired At - .column(Column::auto()) // Node naming - .header(30.0, |mut header| { - header.col(|ui| { - if ui.button("Name").clicked() { - self.toggle_sort(SortColumn::ContestedName); - } - }); - header.col(|ui| { - if ui.button("Owner ID").clicked() { - self.toggle_sort(SortColumn::AwardedTo); - } - }); - header.col(|ui| { - if ui.button("Acquired At").clicked() { - self.toggle_sort(SortColumn::EndingTime); - } - }); - header.col(|ui| { - ui.label("Actions"); - }); - }) - .body(|mut body| { - for (identifier, dpns_info) in filtered_names { - let username = dpns_info.name.clone(); - // Display name with .dash suffix - let display_name = if username.ends_with(".dash") { - username.clone() - } else { - format!("{}.dash", username) - }; - body.row(25.0, |mut row| { - row.col(|ui| { - let dark_mode = ui.style().visuals.dark_mode; + /// The node list inside one scheduled decision: status, guidance and the + /// per-node Remove / Edit / Cast now actions. + fn render_scheduled_group_rows( + &mut self, + ui: &mut Ui, + group_index: usize, + rows: &[ScheduledDpnsVoteRow], + action: &mut AppAction, + show_cast_progress: &mut bool, + ) { + let now = Utc::now().timestamp_millis().max(0) as u64; + TableBuilder::new(ui) + .id_salt(("scheduled_group_rows", group_index)) + .striped(false) + .resizable(true) + .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) + .column(Column::auto().resizable(true)) // Voter + .column(Column::initial(280.0).resizable(true)) // Status + .column(Column::auto().resizable(true)) // Actions + .body(|mut body| { + for scheduled_row in rows { + let vote = &scheduled_row.vote; + let pending_key = DpnsScheduledVoteKey { + network: scheduled_row.journal_target.1.network, + voter_id: vote.voter_id, + contested_name: vote.contested_name.clone(), + }; + let missed = schedule_is_missed( + scheduled_row.status, + VoteTiming::Scheduled(vote.unix_timestamp), + now, + ); + let failure_guidance = if missed { + Some(MISSED_SCHEDULE_GUIDANCE) + } else { + scheduled_failure_guidance(scheduled_row.status, scheduled_row.failure) + }; + let height = if failure_guidance.is_some() { 95.0 } else { 25.0 }; + body.row(height, |mut row| { + row.col(|ui| { + let voter = self + .voting_identities + .iter() + .find(|identity| identity.identity.id() == vote.voter_id) + .and_then(|identity| identity.alias.clone()) + .unwrap_or_else(|| crate::model::identity_name::masternode_label(vote.voter_id, None)); + ui.add(Label::new(voter)); + }); + row.col(|ui| { + let dark_mode = ui.style().visuals.dark_mode; + ui.vertical(|ui| { + let status = if missed { + "Missed automatic vote" + } else { + target_outcome_label(scheduled_row.status, scheduled_row.failure) + }; ui.label( - RichText::new(&display_name) + RichText::new(status) .color(DashColors::text_primary(dark_mode)), ); + if let Some(guidance) = failure_guidance { + ui.add(Label::new(guidance).wrap()); + } }); - row.col(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - ui.label( - RichText::new(identifier.to_string(Encoding::Base58)) - .color(DashColors::text_primary(dark_mode)), + }); + row.col(|ui| { + if ui + .add_enabled( + scheduled_vote_remove_enabled(scheduled_row.status), + Button::new("Remove"), + ) + .disabled_tooltip( + "This scheduled vote cannot be removed while its result is being checked.", + ) + .clicked() + { + *action = AppAction::BackendTask(BackendTask::ContestedResourceTask( + scheduled_vote_removal_task(scheduled_row), + )); + } + let dispatch_pending = + self.pending_scheduled_actions.contains_key(&pending_key); + if ui + .add_enabled( + scheduled_row.status == DpnsVoteTargetStatus::Scheduled + && !dispatch_pending, + Button::new("Edit"), + ) + .disabled_tooltip( + "Only scheduled votes that have not started can be edited.", + ) + .clicked() + { + self.open_schedule_editor(scheduled_row); + } + let voter = self + .voting_identities + .iter() + .find(|identity| identity.identity.id() == vote.voter_id) + .cloned(); + let cast_enabled = + scheduled_vote_cast_enabled(scheduled_row.status, dispatch_pending) + && voter.is_some(); + if ui + .add_enabled(cast_enabled, Button::new("Cast now")) + .disabled_tooltip( + "Load this node's voting key and wait for any pending submission to finish before casting.", + ) + .clicked() + && let Some(found) = voter + { + let task = BackendTask::ContestedResourceTask( + ContestedResourceTask::CastScheduledVote( + vote.clone(), + Box::new(found), + ), ); - }); - let dt = DateTime::from_timestamp( - dpns_info.acquired_at as i64 / 1000, - ((dpns_info.acquired_at % 1000) * 1_000_000) as u32, - ) - .map(|dt| dt.to_string()) - .unwrap_or_else(|| "Invalid timestamp".to_string()); - row.col(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - ui.label( - RichText::new(dt).color(DashColors::text_primary(dark_mode)), + let context = BackendTaskContext::for_dispatch_on( + &task, + self.app_context.network(), ); - }); - row.col(|ui| { - let is_node = self.voting_identities.iter() - .any(|node| node.identity.id() == identifier); - if is_node - && ui.small_button("Set node name").clicked() - { - match self.app_context - .set_identity_alias(&identifier, Some(&display_name)) - { - Ok(()) => { - MessageBanner::set_global( - ui.ctx(), - "The node name was saved on this device.", - MessageType::Success, - ); - } - Err(error) => { - MessageBanner::set_global( - ui.ctx(), - "The node name could not be saved. Check available disk space and try again.", - MessageType::Error, - ).with_details(error); - } - } - } - }); + self.pending_scheduled_actions + .insert(pending_key.clone(), context.clone()); + *action = AppAction::BackendTaskWithContext { task, context }; + *show_cast_progress = true; + } }); - } - }); - }); + }); + } + }); } - /// Show the Scheduled Votes table - fn render_table_scheduled_votes(&mut self, ui: &mut Ui) -> AppAction { - let mut action = AppAction::None; - let mut sorted_votes = { - let guard = self.scheduled_votes.lock_recover(); - guard.clone() + fn open_schedule_editor(&mut self, row: &ScheduledDpnsVoteRow) { + let Ok(poll_id) = self.app_context.dpns_vote_poll_id(&row.vote.contested_name) else { + return; }; - // Sort by contested_name or time - sorted_votes.sort_by(|a, b| { - let order = a.0.contested_name.cmp(&b.0.contested_name); - if self.sort_order == SortOrder::Descending { - order.reverse() - } else { - order - } - }); - - egui::ScrollArea::both().show(ui, |ui| { - TableBuilder::new(ui) - .striped(false) - .resizable(true) - .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) - .column(Column::auto().resizable(true)) // ContestedName - .column(Column::auto().resizable(true)) // Voter - .column(Column::auto().resizable(true)) // Choice - .column(Column::auto().resizable(true)) // Time - .column(Column::auto().resizable(true)) // Status - .column(Column::auto().resizable(true)) // Actions - .header(30.0, |mut header| { - header.col(|ui| { - if ui.button("Name").clicked() { - self.toggle_sort(SortColumn::ContestedName); - } - }); - header.col(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - ui.heading( - RichText::new("Voter").color(DashColors::text_primary(dark_mode)), - ); - }); - header.col(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - ui.heading( - RichText::new("Vote Choice").color(DashColors::text_primary(dark_mode)), - ); - }); - header.col(|ui| { - if ui.button("Scheduled Time").clicked() { - self.toggle_sort(SortColumn::EndingTime); - } - }); - header.col(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - ui.heading( - RichText::new("Status").color(DashColors::text_primary(dark_mode)), - ); - }); - header.col(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - ui.heading( - RichText::new("Actions").color(DashColors::text_primary(dark_mode)), - ); - }); - }) - .body(|mut body| { - for vote in sorted_votes.iter_mut() { - body.row(25.0, |mut row| { - // Contested name - row.col(|ui| { - ui.add(Label::new(&vote.0.contested_name)); - }); - // Voter - row.col(|ui| { - ui.add( - Label::new(vote.0.voter_id.to_string(Encoding::Hex)).truncate(), - ); - }); - // Choice - row.col(|ui| { - let display_text = match &vote.0.choice { - ResourceVoteChoice::TowardsIdentity(id) => { - id.to_string(Encoding::Base58) - } - other => other.to_string(), - }; - ui.add(Label::new(display_text)); - }); - // Time - row.col(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - if let LocalResult::Single(dt) = - Utc.timestamp_millis_opt(vote.0.unix_timestamp as i64) - { - let iso = dt.format("%Y-%m-%d %H:%M:%S").to_string(); - let rel_time = HumanTime::from(dt).to_string(); - let relative = if rel_time.contains("seconds") { - "now".to_string() - } else { - rel_time - }; - let text = format!("{} ({})", iso, relative); - ui.label( - RichText::new(text) - .color(DashColors::text_primary(dark_mode)), - ); - } else { - ui.label( - RichText::new("Invalid timestamp") - .color(DashColors::text_primary(dark_mode)), - ); - } - }); - // Status - row.col(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - match vote.1 { - ScheduledVoteCastingStatus::NotStarted => { - ui.label( - RichText::new("Pending") - .color(DashColors::text_primary(dark_mode)), - ); - } - ScheduledVoteCastingStatus::InProgress => { - ui.label( - RichText::new("Casting...") - .color(DashColors::text_primary(dark_mode)), - ); - } - ScheduledVoteCastingStatus::Failed => { - ui.colored_label(Color32::DARK_RED, "Failed"); - } - ScheduledVoteCastingStatus::Completed => { - ui.colored_label(Color32::DARK_GREEN, "Casted"); - } - } - }); - // Actions - row.col(|ui| { - if ui.button("Remove").clicked() { - action = - AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::DeleteScheduledVote( - vote.0.voter_id, - vote.0.contested_name.clone(), - ), - )); - } - // If the user wants to do "Cast Now" from here, they can - // if NotStarted or Failed. If in progress or done, disabled. - let cast_button_enabled = matches!( - vote.1, - ScheduledVoteCastingStatus::NotStarted - | ScheduledVoteCastingStatus::Failed - ) && !self - .scheduled_vote_cast_in_progress; - - let cast_button = if cast_button_enabled { - Button::new("Cast Now") - } else { - Button::new("Cast Now").sense(egui::Sense::hover()) - }; + let key = DpnsVoteTargetKey { + network: self.app_context.network(), + voter_id: row.vote.voter_id, + vote_poll_id: poll_id, + }; + let node_label = self + .voting_identities + .iter() + .find(|identity| identity.identity.id() == row.vote.voter_id) + .and_then(|identity| identity.alias.clone()) + .unwrap_or_else(|| { + crate::model::identity_name::masternode_label(row.vote.voter_id, None) + }); + let mut choices = vec![ + ( + ResourceVoteChoice::Lock, + vote_choice_label(ResourceVoteChoice::Lock, None), + ), + ( + ResourceVoteChoice::Abstain, + vote_choice_label(ResourceVoteChoice::Abstain, None), + ), + ]; + if let Some(candidates) = self.candidate_names.get(&row.vote.contested_name) { + choices.extend(candidates.iter().map(|(candidate_id, name)| { + ( + ResourceVoteChoice::TowardsIdentity(*candidate_id), + vote_choice_label( + ResourceVoteChoice::TowardsIdentity(*candidate_id), + Some(name), + ), + ) + })); + } + if !choices.iter().any(|(choice, _)| *choice == row.vote.choice) { + choices.push((row.vote.choice, vote_choice_label(row.vote.choice, None))); + } + self.scheduled_vote_editor = ScheduledVoteEditor::new( + row.clone(), + key, + node_label, + choices, + self.contest_end_time(&row.vote.contested_name), + ); + } - if ui.add(cast_button).clicked() && cast_button_enabled { - self.scheduled_vote_cast_in_progress = true; - vote.1 = ScheduledVoteCastingStatus::InProgress; + /// The batch timing the confirm step resolves targets with. + fn batch_timing(&self, now_ms: u64) -> Result { + match self.confirm_timing { + ConfirmTiming::Now => Ok(BatchTiming::Now), + ConfirmTiming::BeforeEnd => Ok(BatchTiming::BeforeEnd(self.relative_preset)), + ConfirmTiming::At => { + let at = self + .confirm_schedule + .current_value() + .ok_or(ReviewPlanError::ScheduleIsNotAValidTime)?; + // Each contest's deadline is checked when the plan is composed. + validate_dpns_schedule_time(at, now_ms, None) + .map_err(|_| ReviewPlanError::ScheduleIsNotInTheFuture)?; + Ok(BatchTiming::At(at)) + } + } + } - // Mark in our Arc as well - if let Ok(mut sched_guard) = self.scheduled_votes.lock() - && let Some(t) = sched_guard.iter_mut().find(|(sv, _)| { - sv.voter_id == vote.0.voter_id - && sv.contested_name == vote.0.contested_name - }) - { - t.1 = ScheduledVoteCastingStatus::InProgress; - } - // dispatch the actual cast - let local_ids = - match self.app_context.load_local_voting_identities() { - Ok(ids) => ids, - Err(e) => { - error!("{}", e); - return; - } - }; - if let Some(found) = local_ids - .iter() - .find(|i| i.identity.id() == vote.0.voter_id) - { - action = AppAction::BackendTask( - BackendTask::ContestedResourceTask( - ContestedResourceTask::CastScheduledVote( - vote.0.clone(), - Box::new(found.clone()), - ), - ), - ); - } - } - }); - }); - } - }); - }); + /// The cached display name of a `TowardsIdentity` candidate. + /// + /// A keyed lookup into the refresh-time index — no lock and no allocation, + /// because every render path calls this once per row, every frame. + fn candidate_name(&self, contested_name: &str, choice: ResourceVoteChoice) -> Option<&str> { + let ResourceVoteChoice::TowardsIdentity(candidate_id) = choice else { + return None; + }; + self.candidate_names + .get(contested_name)? + .get(&candidate_id) + .map(String::as_str) + } - action + fn rebuild_candidate_names(&mut self) { + self.candidate_names = + candidate_name_index(&self.active_contests, &self.contested_names.lock_recover()); } - /// For each contested name row, show the possible contestants. This is the old `show_contested_name_details` function. - fn show_contestants_for_contested_name( - &mut self, - ui: &mut Ui, - contested_name: &ContestedName, - is_locked_votes_bold: bool, - max_contestant_votes: u32, - ) { - if let Some(contestants) = &contested_name.contestants { - for contestant in contestants { - let first_6_chars: String = contestant - .id - .to_string(Encoding::Base58) - .chars() - .take(6) - .collect(); - let button_text = format!("{}... - {} votes", first_6_chars, contestant.votes); - - // Bold if highest - let text = if contestant.votes == max_contestant_votes && !is_locked_votes_bold { - RichText::new(button_text) - .strong() - .color(Color32::from_rgb(0, 100, 0)) - } else { - RichText::new(button_text) + fn sync_vote_progress(&mut self) { + let Some(changed) = self.vote_operations.sync_progress(&self.app_context) else { + return; + }; + self.rebuild_scheduled_vote_rows(); + let changed: BTreeMap<_, _> = changed + .into_iter() + .map(|(previous, outcome)| (outcome.target.key.clone(), (previous, outcome))) + .collect(); + for card in &mut self.cards { + let Some(poll) = card.vote_poll_id else { + continue; + }; + for node in &mut card.nodes { + let key = DpnsVoteTargetKey { + network: self.app_context.network(), + voter_id: node.node, + vote_poll_id: poll, }; - - // Check if selected - let is_selected = self.selected_votes.iter().any(|sv| { - sv.contested_name == contested_name.normalized_contested_name - && sv.vote_choice == ResourceVoteChoice::TowardsIdentity(contestant.id) - }); - - let button = if is_selected { - Button::new(text).fill(Color32::from_rgb(0, 150, 255)) - } else { - Button::new(text) + let Some((previous, outcome)) = changed.get(&key) else { + continue; }; - let resp = ui.add(button); - if resp.clicked() { - // Is there already a selection for this contested name? - if let Some(existing_index) = self.selected_votes.iter().position(|sv| { - sv.contested_name == contested_name.normalized_contested_name - }) { - // If the user clicked the same choice, that toggles it off (unselect). - if self.selected_votes[existing_index].vote_choice - == ResourceVoteChoice::TowardsIdentity(contestant.id) - { - // Remove it entirely -> no selection - self.selected_votes.remove(existing_index); - } else { - // Otherwise replace the old choice with TowardsIdentity - self.selected_votes[existing_index].vote_choice = - ResourceVoteChoice::TowardsIdentity(contestant.id); - } - } else { - // No existing selection for this name, so add this new TowardsIdentity - self.selected_votes.push(SelectedVote { - contested_name: contested_name.normalized_contested_name.clone(), - vote_choice: ResourceVoteChoice::TowardsIdentity(contestant.id), - end_time: contested_name.end_time, - }); + let state = if outcome.status == DpnsVoteTargetStatus::Confirmed { + if newly_applied_vote(*previous, outcome) { + node.changes = node.changes.after_applied_vote(node.current.is_some()); } - } + node.current = Some(outcome.target.requested_choice); + DpnsCurrentVoteState::Available(node.current) + } else { + self.vote_state.state(node.node, poll) + }; + node.status = NodeContestStatus::classify( + state, + self.vote_operations.target_status(&key), + node.changes, + ); } + card.placement = place_card(&card.nodes); } } - // --------------------------- - // Bulk scheduling ephemeral UI - // --------------------------- - fn show_bulk_schedule_popup_window(&mut self, ui: &mut Ui) -> AppAction { - let mut action = AppAction::None; + fn rebuild_scheduled_vote_rows(&mut self) { + let rows = self.vote_operations.scheduled_vote_rows(); + self.relative_schedule_labels = rows + .iter() + .filter_map(|row| { + let (operation_id, key) = &row.journal_target; + let at = row.vote.unix_timestamp; + let preset = self + .vote_operations + .operation(*operation_id)? + .outcome(key)? + .relative_schedule_preset_ms?; + let preset = std::time::Duration::from_millis(preset); + Some(((key.clone(), at), preset)) + }) + .collect(); + self.scheduled_groups = group_scheduled_rows(rows.clone()).into(); + *self.scheduled_votes.lock_recover() = rows; + } - let dark_mode = ui.style().visuals.dark_mode; - ui.heading( - RichText::new("Cast or Schedule Votes").color(DashColors::text_primary(dark_mode)), + fn render_voting_identity_load_error(&mut self, ui: &mut Ui) { + ui.colored_label( + DashColors::warning_color(ui.visuals().dark_mode), + "Your nodes could not be loaded from this device. Retry loading before voting.", ); - ui.add_space(10.0); - - // If self.bulk_vote_handling_status is Complete, show completed message - if self.bulk_vote_handling_status == VoteHandlingStatus::Completed { - action |= self.show_bulk_vote_handling_complete(ui); - return action; + if ui.button("Retry loading nodes").clicked() { + self.refresh_on_arrival(); } + } - // If no voting identities are loaded, display a message and return - if self.voting_identities.is_empty() { - ui.add_space(5.0); - ui.colored_label(Color32::DARK_RED, "No masternode identities loaded. Please go to the Identities screen to load your masternodes."); - ui.add_space(10.0); - let dark_mode = ui.style().visuals.dark_mode; + /// The confirm step (VOTE-FR-080): an aggregate of the staged decisions + /// across the node set, the batch timing, and `Adjust nodes`. + fn show_confirm_step(&mut self, ui: &mut Ui) -> AppAction { + let mut action = AppAction::None; + let dark_mode = ui.style().visuals.dark_mode; + + if self.voting_identity_load_error.is_some() { + self.render_voting_identity_load_error(ui); if ComponentStyles::add_secondary_button(ui, "Close", dark_mode).clicked() { - self.show_bulk_schedule_popup = false; + self.confirm_open = false; } return action; } - - // If no votes are selected, display a message and return - if self.selected_votes.is_empty() { - ui.add_space(5.0); - ui.colored_label(Color32::DARK_RED, "No votes selected. Please click the votes you want to cast or schedule in the Active Contests screen."); - ui.add_space(10.0); - let dark_mode = ui.style().visuals.dark_mode; - if ComponentStyles::add_secondary_button(ui, "Close", dark_mode).clicked() { - self.show_bulk_schedule_popup = false; + if self.voting_identities.is_empty() { + let (heading, detail, button) = self.no_voting_nodes_copy(); + ui.colored_label(DashColors::warning_color(dark_mode), heading); + ui.label(detail); + ui.horizontal(|ui| { + if ComponentStyles::add_primary_button(ui, button).clicked() { + self.load_node_requested = true; + self.confirm_open = false; + } + if ComponentStyles::add_secondary_button(ui, "Close", dark_mode).clicked() { + self.confirm_open = false; + } + }); + return action; + } + if self.review_votes().is_empty() { + ui.colored_label( + DashColors::warning_color(dark_mode), + "No decisions are staged. Pick a choice on at least one name, then try again.", + ); + if ComponentStyles::add_secondary_button(ui, "Back to To decide", dark_mode).clicked() { + self.confirm_open = false; } return action; } - egui::ScrollArea::vertical().show(ui, |ui| { - // Show which votes were clicked - ui.group(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - ui.heading( - RichText::new("Selected Votes:").color(DashColors::text_primary(dark_mode)), - ); - ui.separator(); - for sv in &self.selected_votes { - // Convert end_time -> readable - let end_str = if let Some(e) = sv.end_time { - if let LocalResult::Single(dt) = Utc.timestamp_millis_opt(e as i64) { - let iso = dt.format("%Y-%m-%d %H:%M:%S").to_string(); - let rel = HumanTime::from(dt).to_string(); - format!("{} ({})", iso, rel) - } else { - "Invalid timestamp".to_string() - } - } else { - "N/A".to_string() - }; - let display_text = match &sv.vote_choice { - ResourceVoteChoice::TowardsIdentity(id) => id.to_string(Encoding::Base58), - other => other.to_string(), - }; - let dark_mode = ui.style().visuals.dark_mode; - ui.label( - RichText::new(format!( - "{} => {} | Contest ends at {}", - sv.contested_name, display_text, end_str - )) - .color(DashColors::text_primary(dark_mode)), + let plan = self.build_review_plan(); + match &plan { + Ok(plan) => { + ui.heading(confirm_title(plan.decisions.len(), plan.node_count())); + for (decision, nodes) in &plan.decisions { + let choice = vote_choice_label( + decision.choice, + self.candidate_name(&decision.contested_name, decision.choice), ); + let mut row = decision_row(&decision.contested_name, &choice, *nodes); + if let Some(end) = decision.end_time { + row = format!( + "{row} · {ends}", + ends = ends_in_label(time_left(end, now_ms())) + ); + } + ui.label(row); } - }); - - ui.add_space(10.0); + ui.add_space(6.0); + if let Some(line) = confirm_transactions_line(plan.transaction_count()) { + ui.label(line); + } + if plan.recheck_count() > 0 { + ui.label(confirm_recheck_line(plan.recheck_count())); + } + let changes = plan.aggregate.change_count(); + if changes > 0 { + ui.colored_label( + DashColors::warning_color(dark_mode), + confirm_change_warning(changes), + ); + } + if plan.aggregate.ends_soon_now > 0 { + ui.label(ends_soon_now_line(plan.aggregate.ends_soon_now)); + } + let skipped = plan.aggregate.skipped_by_reason(); + if !skipped.is_empty() { + ui.label(RichText::new(skipped_header(plan.aggregate.skipped.len())).strong()); + for (reason, count) in skipped { + ui.label(skipped_reason_line(count, reason)); + } + } + for exclusion in [ + NodeExclusion::NotInMasternodeList, + NodeExclusion::NoVotingKey, + ] { + let count = self + .resolved_nodes + .excluded + .iter() + .filter(|(_, reason)| *reason == exclusion) + .count(); + if count > 0 { + ui.label(excluded_nodes_line(count, exclusion)); + } + } + } + Err(error) => { + ui.colored_label(DashColors::warning_color(dark_mode), error.to_string()); + } + } - // Show each identity + let user pick None / Immediate / Scheduled - let dark_mode = ui.style().visuals.dark_mode; - ui.heading( - RichText::new("Select cast method for each node:") - .color(DashColors::text_primary(dark_mode)), - ); - ui.add_space(10.0); - ui.group(|ui| { + ui.separator(); + ui.horizontal_wrapped(|ui| { + ui.label("When:"); + for timing in ConfirmTiming::ALL { + if ui + .selectable_label(self.confirm_timing == timing, timing.label()) + .clicked() + { + self.confirm_timing = timing; + } + } + }); + match self.confirm_timing { + ConfirmTiming::Now => {} + ConfirmTiming::BeforeEnd => { ui.horizontal(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - ui.label(RichText::new("Set all:").color(DashColors::text_primary(dark_mode))); - - // A ComboBox to pick No Vote / Cast Now / Schedule - ComboBox::from_id_salt("set_all_combo") - .width(120.0) - .selected_text(match self.set_all_option { - VoteOption::NoVote => "No Vote".to_string(), - VoteOption::CastNow => "Cast Now".to_string(), - VoteOption::Scheduled { .. } => "Schedule".to_string(), - }) - .show_ui(ui, |ui| { - if ui - .selectable_label( - matches!(self.set_all_option, VoteOption::NoVote), - "No Vote", - ) - .clicked() - { - self.set_all_option = VoteOption::NoVote; - } - if ui - .selectable_label( - matches!(self.set_all_option, VoteOption::CastNow), - "Cast Now", - ) - .clicked() - { - self.set_all_option = VoteOption::CastNow; - } - if ui - .selectable_label( - matches!(self.set_all_option, VoteOption::Scheduled { .. }), - "Schedule", - ) - .clicked() - { - // Default scheduled values if none set yet - let (d, h, m) = match &self.set_all_option { - VoteOption::Scheduled { - days, - hours, - minutes, - } => (*days, *hours, *minutes), - _ => (0, 0, 0), - }; - self.set_all_option = VoteOption::Scheduled { - days: d, - hours: h, - minutes: m, - }; - } - }); - - // If scheduling, show the days/hours/minutes widgets inline - if let VoteOption::Scheduled { - ref mut days, - ref mut hours, - ref mut minutes, - } = self.set_all_option + let mut minutes = self.relative_preset.as_secs() / 60; + ui.label("Lead time before the end, in minutes:"); + if ui + .add(egui::DragValue::new(&mut minutes).range(1..=7 * 24 * 60)) + .changed() { - let dark_mode = ui.style().visuals.dark_mode; - ui.label( - RichText::new("Schedule In:") - .color(DashColors::text_primary(dark_mode)), - ); - ui.add(egui::DragValue::new(days).prefix("Days: ").range(0..=14)); - ui.add(egui::DragValue::new(hours).prefix("Hours: ").range(0..=23)); - ui.add(egui::DragValue::new(minutes).prefix("Min: ").range(0..=59)); - } - - // Button to apply the "Set all" choice to each identity in bulk_identity_options - if ui.button("Apply to All").clicked() { - for option in &mut self.bulk_identity_options { - *option = self.set_all_option.clone(); - } + self.set_relative_preset(std::time::Duration::from_secs(minutes * 60)); } + ui.label(before_end_phrase(self.relative_preset)); }); - }); - ui.add_space(10.0); - for (i, identity) in self.voting_identities.iter().enumerate() { - ui.group(|ui| { - ui.horizontal(|ui| { - let label = self.app_context.identity_display_label(identity); - let dark_mode = ui.style().visuals.dark_mode; - ui.label( - RichText::new(format!("Identity: {}", label)) - .color(DashColors::text_primary(dark_mode)), - ); - - // This is a hack - // I'm seeing a panic if I load the app in mainnet context where I have no voting identities, - // and then switch to testnet and pressed "Vote". - if self.bulk_identity_options.len() <= i { - let voting_identities = self - .app_context - .load_local_voting_identities() - .unwrap_or_default(); - // Initialize ephemeral bulk-schedule state to hidden - let identity_count = voting_identities.len(); - self.bulk_identity_options = vec![VoteOption::CastNow; identity_count]; - } - - let current_option = &mut self.bulk_identity_options[i]; - ComboBox::from_id_salt(format!("combo_bulk_identity_{}", i)) - .width(120.0) - .selected_text(match current_option { - VoteOption::NoVote => "No Vote".to_string(), - VoteOption::CastNow => "Cast Now".to_string(), - VoteOption::Scheduled { .. } => "Schedule".to_string(), - }) - .show_ui(ui, |ui| { - if ui - .selectable_label( - matches!(current_option, VoteOption::NoVote), - "No Vote", - ) - .clicked() - { - *current_option = VoteOption::NoVote; - } - if ui - .selectable_label( - matches!(current_option, VoteOption::CastNow), - "Cast Now", - ) - .clicked() - { - *current_option = VoteOption::CastNow; - } - if ui - .selectable_label( - matches!(current_option, VoteOption::Scheduled { .. }), - "Schedule", - ) - .clicked() - { - let (d, h, m) = match current_option { - VoteOption::Scheduled { - days, - hours, - minutes, - } => (*days, *hours, *minutes), - _ => (0, 0, 0), - }; - *current_option = VoteOption::Scheduled { - days: d, - hours: h, - minutes: m, - }; - } - }); - - if let VoteOption::Scheduled { - days, - hours, - minutes, - } = current_option - { - let dark_mode = ui.style().visuals.dark_mode; - ui.label( - RichText::new("Schedule In:") - .color(DashColors::text_primary(dark_mode)), - ); - ui.add(egui::DragValue::new(days).prefix("Days: ").range(0..=14)); - ui.add(egui::DragValue::new(hours).prefix("Hours: ").range(0..=23)); - ui.add(egui::DragValue::new(minutes).prefix("Min: ").range(0..=59)); - } - }); - }); - ui.add_space(10.0); + ui.colored_label(DashColors::warning_color(dark_mode), KEEP_RUNNING_MESSAGE); } - }); - - // If any selected votes are scheduled, show a warning - if self - .bulk_identity_options - .iter() - .any(|o| matches!(o, VoteOption::Scheduled { .. })) - { - ui.colored_label(Color32::DARK_RED, "NOTE: Dash Evo Tool must remain running and connected for scheduled votes to execute on time."); - ui.add_space(10.0); - } - - // "Apply Votes" button - if ComponentStyles::add_primary_button(ui, "Apply Votes").clicked() { - action = self.bulk_apply_votes(); - if self.bulk_vote_handling_status == VoteHandlingStatus::CastingVotes { - self.vote_banner.take_and_clear(); - let handle = - MessageBanner::set_global(ui.ctx(), "Casting votes...", MessageType::Info); - handle.with_elapsed(); - self.vote_banner = Some(handle); + ConfirmTiming::At => { + self.confirm_schedule.show(ui); + ui.colored_label(DashColors::warning_color(dark_mode), KEEP_RUNNING_MESSAGE); } } - ui.add_space(5.0); - let dark_mode = ui.style().visuals.dark_mode; - if ComponentStyles::add_secondary_button(ui, "Cancel", dark_mode).clicked() { - self.selected_votes.clear(); - self.show_bulk_schedule_popup = false; - self.bulk_schedule_message = None; - self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; - self.vote_banner.take_and_clear(); - } - - // Handle status - ui.add_space(10.0); - match &self.bulk_vote_handling_status { - VoteHandlingStatus::NotStarted => {} - VoteHandlingStatus::CastingVotes => { - // Elapsed time is shown in the global banner - } - VoteHandlingStatus::SchedulingVotes => { - let dark_mode = ui.style().visuals.dark_mode; - ui.label( - RichText::new("Scheduling votes...").color(DashColors::text_primary(dark_mode)), - ); - } - VoteHandlingStatus::Completed => { - // handled above - } - VoteHandlingStatus::Failed(message) => { - ui.colored_label( - Color32::RED, - format!("Error casting/scheduling votes: {}", message), - ); + egui::CollapsingHeader::new("Adjust nodes") + .default_open(false) + .show(ui, |ui| self.render_adjust_nodes(ui, plan.as_ref().ok())); + + let submitted = plan.as_ref().map_or(0, ReviewPlan::effective_count); + let transactions = plan.as_ref().map_or(0, ReviewPlan::transaction_count); + let rechecks = plan.as_ref().map_or(0, ReviewPlan::recheck_count); + let all_now = plan.as_ref().is_ok_and(|plan| !plan.has_scheduled()); + let submit_disabled_reason = if plan.is_err() { + "These votes cannot be submitted yet. Fix the problem shown above and try again." + } else { + "Nothing can be submitted. Choose at least one node and a vote it has not already cast." + }; + // Holding Enter after opening the sheet must never confirm a vote, + // including when the primary button has keyboard focus. + let repeated_enter = ui.input(|input| { + input.events.iter().any(|event| { + matches!( + event, + egui::Event::Key { + key: egui::Key::Enter, + pressed: true, + repeat: true, + .. + } + ) + }) + }); + let can_submit = submitted > 0 && !repeated_enter; + let (mut submit_clicked, mut cancel_clicked) = ui + .with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let submit_clicked = ComponentStyles::add_primary_button_enabled( + ui, + can_submit, + confirm_button_label(transactions, rechecks, all_now), + ) + .disabled_tooltip(submit_disabled_reason) + .clicked(); + let cancel_clicked = ui + .add(ComponentStyles::secondary_button("Cancel", dark_mode)) + .clicked(); + (submit_clicked, cancel_clicked) + }) + .inner; + // Enter confirms, Esc cancels (VOTE-FR-080) — unless a text field has focus. + if !ui.ctx().egui_wants_keyboard_input() { + ui.input_mut(|input| { + if can_submit && input.consume_key(egui::Modifiers::NONE, egui::Key::Enter) { + submit_clicked = true; + } + if input.consume_key(egui::Modifiers::NONE, egui::Key::Escape) { + cancel_clicked = true; + } + }); + } + if submit_clicked { + action = self.submit_confirmed_votes(); + if matches!(action, AppAction::BackendTask(_)) { + // The confirm step closes at once; the drawer tracks progress + // and the staged decisions clear when the operation reports. + self.confirm_open = false; + self.show_vote_progress(ui.ctx()); } } - + if cancel_clicked { + // Cancel closes the confirm step; staged decisions stay in the tray. + self.confirm_open = false; + self.retry = None; + self.confirm_status = VoteHandlingStatus::NotStarted; + } + if let VoteHandlingStatus::Failed(error) = &self.confirm_status { + ui.colored_label(DashColors::error_color(dark_mode), error.to_string()); + } action } - /// The logic that was in BulkScheduleVoteScreen::schedule_votes - fn bulk_apply_votes(&mut self) -> AppAction { - // Partition immediate vs scheduled - let mut immediate_list = Vec::new(); - let mut scheduled_list = Vec::new(); + /// Change the "before the end" lead time. Nodes set to it under `Adjust + /// nodes` follow, so the header and every node use one lead time. + fn set_relative_preset(&mut self, preset: std::time::Duration) { + self.relative_preset = preset; + for timing in self.node_overrides.values_mut() { + if let NodeTiming::Override(BatchTiming::BeforeEnd(lead)) = timing { + *lead = preset; + } + } + } - for (identity, option) in self - .voting_identities + /// Targets of `operation` placed "before the end" and the lead time they + /// used: nodes following a `When voting is about to end` batch and nodes + /// set to it under `Adjust nodes`. + fn relative_schedule_labels_for( + &self, + operation: &DpnsVoteOperation, + ) -> Option { + let targets: BTreeSet = operation + .targets .iter() - .zip(&self.bulk_identity_options) - { - match option { - VoteOption::NoVote => {} - VoteOption::CastNow => { - immediate_list.push(identity.clone()); - } - VoteOption::Scheduled { - days, - hours, - minutes, - } => { - let now = Utc::now(); - let offset = chrono::Duration::days(*days as i64) - + chrono::Duration::hours(*hours as i64) - + chrono::Duration::minutes(*minutes as i64); - let scheduled_time = (now + offset).timestamp_millis() as u64; - - for sv in &self.selected_votes { - let new_vote = ScheduledDPNSVote { - contested_name: sv.contested_name.clone(), - voter_id: identity.identity.id(), - choice: sv.vote_choice, - unix_timestamp: scheduled_time, - executed_successfully: false, - }; - scheduled_list.push(new_vote); - } - } + .map(|outcome| &outcome.target.key) + .filter(|key| match self.node_overrides.get(&key.voter_id) { + Some(NodeTiming::Override(timing)) => matches!(timing, BatchTiming::BeforeEnd(_)), + Some(NodeTiming::DontUse) => false, + Some(NodeTiming::Batch) | None => self.confirm_timing == ConfirmTiming::BeforeEnd, + }) + .cloned() + .collect(); + (!targets.is_empty()).then_some(RelativeScheduleLabels { + preset: self.relative_preset, + targets, + }) + } + + /// `Adjust nodes`: per-node timing and the full node × name list. + fn render_adjust_nodes(&mut self, ui: &mut Ui, plan: Option<&ReviewPlan>) { + let nodes = self.confirm_nodes(); + for node in &nodes { + let current = self + .node_overrides + .get(&node.voter_id) + .copied() + .unwrap_or(NodeTiming::Batch); + let mut picked = None; + ui.horizontal(|ui| { + ui.label(node_label(node.voter_id, &self.node_labels)); + ComboBox::from_id_salt(("adjust_node", node.voter_id)) + .selected_text(node_timing_label(current)) + .show_ui(ui, |ui| { + for option in [ + NodeTiming::Batch, + NodeTiming::Override(BatchTiming::Now), + NodeTiming::Override(BatchTiming::BeforeEnd(self.relative_preset)), + NodeTiming::DontUse, + ] { + if ui + .selectable_label(current == option, node_timing_label(option)) + .clicked() + { + picked = Some(option); + } + } + }); + }); + if let Some(option) = picked { + self.set_node_timing(node.voter_id, option); } } + let Some(plan) = plan else { + return; + }; + ui.separator(); + egui::Grid::new("adjust_nodes_targets") + .num_columns(4) + .striped(true) + .show(ui, |ui| { + for target in plan.targets() { + ui.label(node_label(target.key.voter_id, &self.node_labels)); + ui.label(format!("{name}.dash", name = target.contested_name)); + ui.label(self.review_choice_line(plan, target)); + let timing = match target.timing { + VoteTiming::Now => "Now".to_owned(), + VoteTiming::Scheduled(at) => format!("{when} UTC", when = utc_minute(at)), + }; + let changes = self + .cards + .iter() + .find(|card| card.vote_poll_id == Some(target.key.vote_poll_id)) + .and_then(|card| { + card.nodes + .iter() + .find(|node| node.node == target.key.voter_id) + }) + .map(|node| node.changes); + ui.label(match changes { + Some(changes) if target.current_choice.is_some() => { + format!("{timing} · {left}", left = changes_left_label(changes)) + } + _ => timing, + }); + ui.end_row(); + } + }); + } - if immediate_list.is_empty() && scheduled_list.is_empty() { - self.bulk_vote_handling_status = VoteHandlingStatus::Failed( - "No votes selected. Please select votes to cast or schedule.".to_string(), - ); - return AppAction::None; + /// One `Adjust nodes` row: the choice the node holds and the requested one. + /// + /// A target only checked again carries no reviewed current choice, so it + /// is worded from the plan instead of being read as a node that never voted. + fn review_choice_line(&self, plan: &ReviewPlan, target: &DpnsVoteTarget) -> String { + let requested = vote_choice_label( + target.requested_choice, + self.candidate_name(&target.contested_name, target.requested_choice), + ); + if plan.aggregate.is_recheck(&target.key) { + return review_recheck_line(&requested); } + let current = review_current_choice_label( + target.current_choice, + target + .current_choice + .and_then(|choice| self.candidate_name(&target.contested_name, choice)), + ); + review_choice_line(¤t, &requested) + } - // 1) If immediate_list is not empty, vote now, possibly scheduling votes as well - if !immediate_list.is_empty() { - let votes_for_all: Vec<(String, ResourceVoteChoice)> = self - .selected_votes - .iter() - .map(|sv| (sv.contested_name.clone(), sv.vote_choice)) - .collect(); - self.bulk_vote_handling_status = VoteHandlingStatus::CastingVotes; - if !scheduled_list.is_empty() { - AppAction::BackendTasks( - vec![ - BackendTask::ContestedResourceTask(ContestedResourceTask::VoteOnDPNSNames( - votes_for_all, - immediate_list, - )), - BackendTask::ContestedResourceTask( - ContestedResourceTask::ScheduleDPNSVotes(scheduled_list), - ), - ], - BackendTasksExecutionMode::Concurrent, - ) - } else { - AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::VoteOnDPNSNames(votes_for_all, immediate_list), - )) - } - } else { - // 2) Otherwise just schedule them - self.bulk_vote_handling_status = VoteHandlingStatus::SchedulingVotes; - AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::ScheduleDPNSVotes(scheduled_list), - )) + /// Record a failed submission and surface it the way the rest of the app + /// surfaces errors: a banner carrying the technical chain in its details. + /// + /// Raised here rather than in the render loop, because `set_global` called + /// every frame would resurrect a banner the user just dismissed. + fn fail_submission(&mut self, error: impl Into) { + let error = error.into(); + self.submission_error_banner.raise_persistent( + self.app_context.egui_ctx(), + error.to_string(), + MessageType::Error, + ); + if let Some(handle) = &self.submission_error_banner { + handle.with_details(&error); } + self.confirm_status = VoteHandlingStatus::Failed(error); } - /// If voting/scheduling is successful, show success message - fn show_bulk_vote_handling_complete(&mut self, ui: &mut Ui) -> AppAction { - let mut action = AppAction::None; + /// Resolve every node × contest target the current review would submit. + /// + /// The confirm step and the submit click share this so the step cannot + /// promise something other than what is sent. + /// + /// # Errors + /// + /// A [`ReviewPlanError`] naming the condition that blocks submission; its + /// `Display` is the sentence the operator reads. + fn build_review_plan(&self) -> Result { + self.build_review_plan_at(Utc::now()) + } - self.selected_votes.clear(); + /// Nodes the confirm step composes with: the retried node alone, else the + /// node set's voting nodes. + fn confirm_nodes(&self) -> Vec { + let included: BTreeSet = self.resolved_nodes.included.iter().copied().collect(); + self.voting_identities + .iter() + .map(|identity| identity.identity.id()) + .filter(|id| match &self.retry { + Some(retry) => *id == retry.voter, + None => included.contains(id), + }) + .map(|voter_id| ComposerNode { + voter_id, + alias: self + .voting_identities + .iter() + .find(|identity| identity.identity.id() == voter_id) + .and_then(|identity| identity.alias.clone()), + }) + .collect() + } - ui.vertical_centered(|ui| { - ui.add_space(20.0); - match &self.bulk_vote_handling_status { - VoteHandlingStatus::Completed => { - // This means DET side was successful, but Platform may have returned errors - if let Some(message) = &self.bulk_schedule_message { - match message.0 { - MessageType::Error => { - let dark_mode = ui.style().visuals.dark_mode; - ui.heading( - RichText::new("❌").color(DashColors::text_primary(dark_mode)), - ); - if message.1.contains("Successes") { - let dark_mode = ui.style().visuals.dark_mode; - ui.heading( - RichText::new("Only some votes succeeded") - .color(DashColors::text_primary(dark_mode)), - ); - } else { - let dark_mode = ui.style().visuals.dark_mode; - ui.heading( - RichText::new("No votes succeeded") - .color(DashColors::text_primary(dark_mode)), - ); - } - ui.add_space(10.0); - let dark_mode = ui.style().visuals.dark_mode; - ui.label( - RichText::new(message.1.clone()) - .color(DashColors::text_primary(dark_mode)), - ); - } - MessageType::Success => { - let dark_mode = ui.style().visuals.dark_mode; - ui.heading( - RichText::new("🎉").color(DashColors::text_primary(dark_mode)), - ); - let dark_mode = ui.style().visuals.dark_mode; - ui.heading( - RichText::new("Successfully casted and scheduled all votes") - .color(DashColors::text_primary(dark_mode)), - ); - } - _ => {} + fn build_review_plan_at(&self, now: DateTime) -> Result { + let now_ms = now.timestamp_millis() as u64; + let decisions = self + .review_votes() + .iter() + .map(|vote| { + let vote_poll_id = self + .app_context + .dpns_vote_poll_id(&vote.contested_name) + .map_err(|error| { + tracing::warn!( + ?error, + contested_name = vote.contested_name, + "Could not build a DPNS vote target" + ); + ReviewPlanError::VotePollUnavailable { + source: Arc::new(error), } - } - } - VoteHandlingStatus::Failed(message) => { - // This means there was a DET-side error, not Platform-side - let dark_mode = ui.style().visuals.dark_mode; - ui.heading(RichText::new("❌").color(DashColors::text_primary(dark_mode))); - ui.heading( - RichText::new("Error casting and scheduling votes (DET-side)") - .color(DashColors::text_primary(dark_mode)), - ); - ui.add_space(10.0); - ui.label(RichText::new(message).color(DashColors::text_primary(dark_mode))); - } - _ => { - // this should not occur - } + })?; + Ok(Decision { + contested_name: vote.contested_name.clone(), + vote_poll_id, + choice: vote.vote_choice, + // The deadline may have been read after the choice was staged. + end_time: self + .contest_end_time(&vote.contested_name) + .or(vote.end_time), + }) + }) + .collect::, ReviewPlanError>>()?; + let network = self.app_context.network(); + let standing = |voter_id: Identifier, vote_poll_id: Identifier| { + let key = DpnsVoteTargetKey { + network, + voter_id, + vote_poll_id, + }; + // Changes left come from the card cache; an uncached contest never + // blocks a vote, since Platform enforces the limit itself. + let changes = self + .cards + .iter() + .find(|card| card.vote_poll_id == Some(vote_poll_id)) + .and_then(|card| card.nodes.iter().find(|node| node.node == voter_id)) + .map_or(ChangesLeft::Unknown, |node| node.changes); + NodeStanding { + state: self.vote_state.state(voter_id, vote_poll_id), + locked: self.vote_operations.target_status(&key).is_some(), + changes, + proof_can_decide: vote_proof_can_decide( + self.vote_state.proved_at(voter_id, vote_poll_id), + now_ms, + ), } + }; + let aggregate = compose( + network, + &decisions, + &self.confirm_nodes(), + standing, + self.batch_timing(now_ms)?, + &self.node_overrides, + now_ms, + )?; + let decisions = decisions + .into_iter() + .map(|decision| { + let nodes = aggregate + .targets + .iter() + .filter(|target| target.key.vote_poll_id == decision.vote_poll_id) + .count(); + (decision, nodes) + }) + .collect(); + Ok(ReviewPlan { + aggregate, + decisions, + }) + } - ui.add_space(20.0); - let dark_mode = ui.style().visuals.dark_mode; - if ComponentStyles::add_primary_button(ui, "Go back to Active Contests").clicked() { - self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; - self.show_bulk_schedule_popup = false; - action = AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::QueryDPNSContests, - )) - } - ui.add_space(5.0); - if ComponentStyles::add_secondary_button(ui, "Go to Scheduled Votes Screen", dark_mode) - .clicked() - { - self.show_bulk_schedule_popup = false; - self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; - action = AppAction::SetMainScreenThenPopScreen( - RootScreenType::RootScreenDPNSScheduledVotes, - ); - } - }); + /// Clone the signing identities of the nodes casting in `plan`. + /// + /// Kept out of [`ReviewPlan`], which the confirm step rebuilds every frame: + /// only the submit click needs owned identities. + fn casting_voters(&self, plan: &ReviewPlan) -> Vec { + let casting: BTreeSet = plan + .targets() + .iter() + .map(|target| target.key.voter_id) + .collect(); + self.voting_identities + .iter() + .filter(|identity| casting.contains(&identity.identity.id())) + .cloned() + .collect() + } - action + fn submit_confirmed_votes(&mut self) -> AppAction { + if self.pending_vote_operation.is_some() { + return AppAction::None; + } + let plan = match self.build_review_plan() { + Ok(plan) => plan, + Err(error) => { + self.fail_submission(error); + return AppAction::None; + } + }; + if plan.aggregate.targets.is_empty() { + let all_no_ops = !plan.aggregate.skipped.is_empty() + && plan + .aggregate + .skipped + .iter() + .all(|skipped| skipped.reason == SkipReason::AlreadyVoted); + self.fail_submission(if all_no_ops { + VoteSubmissionError::AllNoOps + } else { + VoteSubmissionError::NoTargets + }); + return AppAction::None; + } + let voters = self.casting_voters(&plan); + let operation = AppContext::new_dpns_vote_operation(plan.aggregate.targets); + let labels = self.relative_schedule_labels_for(&operation); + self.submission_error_banner.take_and_clear(); + self.confirm_status = VoteHandlingStatus::NotStarted; + self.submitted_retry = self.retry.take(); + self.pending_vote_operation = Some(operation.id); + if self.submitted_retry.is_some() { + // A retried target is not one of the staged decisions, so its + // result must not clear any of them from the tray. + self.submitted_votes.clear(); + self.submitted_cards.clear(); + } else { + self.submitted_votes = self + .selected_votes + .iter() + .cloned() + .map(|vote| (vote.contested_name.clone(), vote)) + .collect(); + self.submitted_cards = self.selected_cards.clone(); + } + AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::SubmitDpnsVoteOperation { + operation, + voters, + replacing_scheduled_key: None, + network: self.app_context.network(), + relative_labels: labels, + }, + )) } } @@ -1759,566 +2587,3005 @@ impl DPNSScreen { // --------------------------- impl ScreenLike for DPNSScreen { fn refresh(&mut self) { - self.scheduled_vote_cast_in_progress = false; - let mut contested_names = self.contested_names.lock_recover(); - let mut dpns_names = self.local_dpns_names.lock_recover(); - let mut scheduled_votes = self.scheduled_votes.lock_recover(); - - match self.dpns_subscreen { - DPNSSubscreen::Active => { - *contested_names = self - .app_context - .ongoing_contested_names() - .unwrap_or_default(); - } - DPNSSubscreen::Past => { - *contested_names = self.app_context.all_contested_names().unwrap_or_default(); - } - DPNSSubscreen::Owned => { - *dpns_names = self.app_context.local_dpns_names().unwrap_or_default(); - } - DPNSSubscreen::ScheduledVotes => { - let new_scheduled = self.app_context.get_scheduled_votes().unwrap_or_default(); - *scheduled_votes = new_scheduled - .iter() - .map(|newv| { - if newv.executed_successfully { - (newv.clone(), ScheduledVoteCastingStatus::Completed) - } else if let Some(existing) = scheduled_votes.iter().find(|(old, _)| { - old.contested_name == newv.contested_name - && old.voter_id == newv.voter_id - }) { - // preserve old status if InProgress/Failed - match existing.1 { - ScheduledVoteCastingStatus::InProgress => { - (newv.clone(), ScheduledVoteCastingStatus::InProgress) - } - ScheduledVoteCastingStatus::Failed => { - (newv.clone(), ScheduledVoteCastingStatus::Failed) - } - _ => (newv.clone(), ScheduledVoteCastingStatus::NotStarted), - } - } else { - (newv.clone(), ScheduledVoteCastingStatus::NotStarted) - } - }) - .collect(); - } + if let Err(error) = self.vote_operations.refresh(&self.app_context) { + tracing::warn!(?error, "Could not refresh cached DPNS vote operations"); + } + self.rebuild_scheduled_vote_rows(); + + self.active_contests = ActiveDpnsContestSnapshot::new( + &self.app_context, + self.app_context + .ongoing_contested_names() + .unwrap_or_default(), + ); + *self.contested_names.lock_recover() = + self.app_context.all_contested_names().unwrap_or_default(); + self.rebuild_candidate_names(); + + let voter_ids = self + .voting_identities + .iter() + .map(|identity| identity.identity.id()) + .collect::>(); + let poll_ids = self.active_contests.vote_poll_ids(); + if let Err(error) = self + .vote_state + .refresh(&self.app_context, &voter_ids, &poll_ids) + { + tracing::warn!(?error, "Could not refresh cached DPNS vote state"); } + self.rebuild_cards(); + self.app_context.recompute_dpns_vote_attention(); } fn refresh_on_arrival(&mut self) { - self.voting_identities = self - .app_context - .load_local_voting_identities() - .unwrap_or_default(); - self.user_identities = self - .app_context - .load_local_user_identities() - .unwrap_or_default(); + // After a failed read the earlier nodes are unknown, so none is new. + let nodes_were_known = self.voting_identity_load_error.is_none(); + let previous_voters: BTreeSet = self + .voting_identities + .iter() + .map(|identity| identity.identity.id()) + .collect(); + match loaded_voting_identities(&self.app_context) { + Ok(identities) => { + self.voting_identities = identities; + self.voting_identity_load_error = None; + } + Err(error) => { + tracing::warn!(?error, "Could not reload local DPNS voting identities"); + self.voting_identities.clear(); + self.voting_identity_load_error = Some(error); + } + } + // A node loaded after decisions were staged never joins them silently. + if nodes_were_known && !self.selected_votes.is_empty() { + for identity in &self.voting_identities { + let id = identity.identity.id(); + if !previous_voters.contains(&id) { + self.late_nodes.insert(id); + self.node_overrides.entry(id).or_insert(NodeTiming::DontUse); + } + } + } self.refresh(); } - fn display_message(&mut self, message: &str, message_type: MessageType) { + fn display_message(&mut self, _message: &str, message_type: MessageType) { // Banner display is handled globally by AppState; this is only for side-effects. if matches!(message_type, MessageType::Error | MessageType::Warning) { self.refresh_banner.take_and_clear(); - self.vote_banner.take_and_clear(); - } - if message.contains("Error casting scheduled vote") { - self.scheduled_vote_cast_in_progress = false; - if let Ok(mut guard) = self.scheduled_votes.lock() { - for vote in guard.iter_mut() { - if vote.1 == ScheduledVoteCastingStatus::InProgress { - vote.1 = ScheduledVoteCastingStatus::Failed; - } + } + } + + fn display_backend_task_error(&mut self, context: &BackendTaskContext, _error: &TaskError) { + if context.is_dpns_contest_refresh() { + self.refreshing_status = RefreshingStatus::NotRefreshing; + self.refresh_banner.take_and_clear(); + } + self.finish_scheduled_dispatch(context); + self.release_pending_on_error = self.pending_vote_operation.is_some_and(|operation_id| { + dpns_operation_id(context, self.app_context.network()) == Some(operation_id) + }); + } + + fn display_task_error(&mut self, error: &TaskError) -> bool { + if let Err(refresh_error) = self.vote_state.reload(&self.app_context) { + tracing::warn!( + ?refresh_error, + "Could not refresh proved DPNS votes after a task error" + ); + } + if self.release_pending_on_error { + self.pending_vote_operation = None; + self.submitted_votes.clear(); + self.submitted_cards.clear(); + self.release_pending_on_error = false; + let retried = self.submitted_retry.take(); + // The confirm step closed when the submission was dispatched and + // AppState banners the error; the decisions stay staged, so the + // operator can confirm them again. + if matches!(error, TaskError::DpnsVoteReviewRequired) { + // A first vote became a change during preflight: reopen the + // confirm on fresh vote state so it shows the change warning. + self.confirm_status = VoteHandlingStatus::NotStarted; + self.retry = retried; + self.confirm_open = !self.review_votes().is_empty(); + } + } + if let Err(refresh_error) = self.vote_operations.refresh(&self.app_context) { + tracing::warn!( + ?refresh_error, + "Could not refresh DPNS voting state after a task error" + ); + } + self.rebuild_scheduled_vote_rows(); + self.rebuild_cards(); + scheduled_vote_sweep_is_quiet(error) + } + + fn display_backend_task_result( + &mut self, + context: &BackendTaskContext, + result: BackendTaskSuccessResult, + ) { + self.finish_scheduled_dispatch(context); + self.display_task_result(result); + } + + fn display_task_result(&mut self, backend_task_success_result: BackendTaskSuccessResult) { + let Some(result) = VotesPanelResult::of(&backend_task_success_result) else { + return; + }; + let current_network = self.app_context.network(); + match result { + // A result for another network is not this panel's to apply. + VotesPanelResult::OperationUpdated { network, .. } + | VotesPanelResult::ScheduledSweepCompleted { network } + if network != current_network => {} + VotesPanelResult::OperationUpdated { operation_id, .. } => { + if let Err(error) = self.vote_state.reload(&self.app_context) { + tracing::warn!( + ?error, + "Could not reload proved DPNS vote state after an operation update" + ); } + let owns_result = self.pending_vote_operation == Some(operation_id); + if owns_result { + self.pending_vote_operation = None; + self.submitted_retry = None; + self.confirm_status = VoteHandlingStatus::NotStarted; + self.selected_votes.retain(|vote| { + self.submitted_votes.get(&vote.contested_name) != Some(vote) + }); + let staged: BTreeSet<&String> = self + .selected_votes + .iter() + .map(|vote| &vote.contested_name) + .collect(); + self.selected_cards.retain(|name| { + !self.submitted_cards.contains(name) || staged.contains(name) + }); + self.submitted_votes.clear(); + self.submitted_cards.clear(); + } + if let Err(error) = self.vote_operations.refresh(&self.app_context) { + tracing::warn!( + ?error, + "Could not refresh scheduled votes after an operation update" + ); + } + self.rebuild_scheduled_vote_rows(); + self.rebuild_cards(); + self.app_context.recompute_dpns_vote_attention(); + } + VotesPanelResult::ScheduledSweepCompleted { .. } => { + self.refresh(); + } + VotesPanelResult::ScheduledVotesInProgress => { + if let Err(error) = self.vote_operations.refresh(&self.app_context) { + tracing::warn!(?error, "Could not refresh scheduled-vote operation state"); + } + self.rebuild_scheduled_vote_rows(); } + VotesPanelResult::ScheduledVotesCleared => { + if let Err(error) = self.vote_operations.refresh(&self.app_context) { + tracing::warn!( + ?error, + "Could not refresh scheduled votes after clearing them" + ); + } + self.rebuild_scheduled_vote_rows(); + } + VotesPanelResult::ContestsRefreshed => { + self.refresh(); + self.refresh_banner.take_and_clear(); + self.refreshing_status = RefreshingStatus::NotRefreshing; + } + } + } + + /// Render the Votes body inside an already laid-out central panel. + /// + /// The Masternodes screen owns the window chrome (top bar, left nav, + /// segment header); this draws the sub-view chips and the active view. + fn ui(&mut self, ui: &mut egui::Ui) -> AppAction { + self.sync_vote_progress(); + let ctx = ui.ctx().clone(); + let ctx = &ctx; + let mut action = AppAction::None; + + // `Review again` from the progress drawer, which lives outside this panel. + if self.pending_vote_operation.is_none() + && let Some(outcome) = self.app_context.take_dpns_vote_review_request() + { + self.view = VotesView::ToDecide; + self.review_failed_target(&outcome); + } + if let Some(label) = self.app_context.take_dpns_votes_name_request() { + self.show_contest(label); } + + ui.horizontal(|ui| { + for view in VotesView::ALL { + if ui.selectable_label(self.view == view, view.label()).clicked() { + self.view = view; + } + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let dark_mode = ui.visuals().dark_mode; + match self.view { + VotesView::Scheduled => { + if ComponentStyles::add_secondary_button( + ui, + "Remove finished votes", + dark_mode, + ) + .clicked() + { + self.scheduled_clear_dialog = Some(( + false, + ConfirmationDialog::new( + "Remove finished votes", + "Remove every finished scheduled vote from this device? Pending votes will stay scheduled.", + ) + .danger_mode(true) + .confirm_text(Some("Remove finished votes")), + )); + } + if ComponentStyles::add_secondary_button(ui, "Remove all", dark_mode) + .clicked() + { + self.scheduled_clear_dialog = Some(( + true, + ConfirmationDialog::new( + "Remove all scheduled votes", + "Remove every scheduled vote from this device? Votes already submitted to Platform cannot be undone.", + ) + .danger_mode(true) + .confirm_text(Some("Remove all scheduled votes")), + )); + } + } + VotesView::ToDecide | VotesView::Voted | VotesView::History => { + let refreshing = self.refreshing_status == RefreshingStatus::Refreshing; + if ui + .add_enabled( + !refreshing, + ComponentStyles::secondary_button("Refresh", dark_mode), + ) + .disabled_tooltip("Contests are already being refreshed.") + .clicked() + { + action = AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::QueryDPNSContests, + )); + } + } + } + }); + }); + ui.add_space(8.0); + + if let Some(error) = self.vote_operations.read_error() { + if self.journal_error_banner.is_none() || self.journal_error_banner.was_evicted() { + self.journal_error_banner.raise_persistent( + ui.ctx(), + JOURNAL_UNAVAILABLE_MESSAGE, + MessageType::Warning, + ); + if let Some(handle) = &self.journal_error_banner { + handle.with_details(error); + } + } + // The banner is dismissible, but the warning has to outlive a + // dismissal for as long as the history is unreliable — so the same + // sentence falls back inline once the banner is gone, and never + // renders twice at once. + if self + .journal_error_banner + .as_ref() + .and_then(BannerHandle::text) + .is_none() + { + ui.label(JOURNAL_UNAVAILABLE_MESSAGE); + } + if ComponentStyles::add_secondary_button(ui, "Retry loading", ui.visuals().dark_mode) + .clicked() + { + self.refresh(); + } + ui.separator(); + } else { + self.journal_error_banner.take_and_clear(); + } + if let Some((clear_all, dialog)) = self.scheduled_clear_dialog.as_mut() + && let Some(status) = dialog.show(ui).inner.dialog_response + { + let clear_all = *clear_all; + self.scheduled_clear_dialog = None; + if status == ConfirmationStatus::Confirmed { + action = AppAction::BackendTask(BackendTask::ContestedResourceTask(if clear_all { + ContestedResourceTask::ClearAllScheduledVotes + } else { + ContestedResourceTask::ClearExecutedScheduledVotes + })); + } + } + if let Some(editor) = self.scheduled_vote_editor.as_mut() { + match editor.show(ui.ctx()) { + EditOutcome::KeepOpen => {} + EditOutcome::Cancel => self.scheduled_vote_editor = None, + EditOutcome::Save(edit) => { + let key = editor.scheduled_key(); + let task = BackendTask::ContestedResourceTask(edit); + let context = + BackendTaskContext::for_dispatch_on(&task, self.app_context.network()); + self.pending_scheduled_actions.insert(key, context.clone()); + action = AppAction::BackendTaskWithContext { task, context }; + self.scheduled_vote_editor = None; + } + } + } + if self.confirm_open { + egui::Window::new("Confirm votes") + .collapsible(false) + .resizable(true) + .vscroll(true) + .show(ui.ctx(), |ui| { + action |= self.show_confirm_step(ui); + }); + } + + if self.voting_identity_load_error.is_some() && !self.confirm_open { + self.render_voting_identity_load_error(ui); + } + match self.view { + VotesView::ToDecide | VotesView::Voted => { + if self.voting_identities.is_empty() && self.voting_identity_load_error.is_none() { + self.render_no_voting_nodes(ui); + } + self.render_needs_attention(ui); + if self.active_contests.is_empty() { + self.render_node_set_chip(ui); + action |= self.render_empty_view(ui); + } else { + self.render_active_contests(ui); + } + } + VotesView::History => { + if self.contested_names.lock_recover().is_empty() { + action |= self.render_empty_view(ui); + } else { + self.render_table_past_contests(ui); + } + } + VotesView::Scheduled => { + if self.scheduled_votes.lock_recover().is_empty() { + action |= self.render_empty_view(ui); + } else { + action |= self.render_table_scheduled_votes(ui); + } + } + } + + if action == AppAction::None + && let Some(task) = self.pending_backend_task.take() + { + action = AppAction::BackendTask(task); + } + if let AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::QueryDPNSContests, + )) = &action + { + self.refresh_banner.take_and_clear(); + let handle = + MessageBanner::set_global(ctx, "Refreshing name contests…", MessageType::Info); + handle.with_elapsed(); + self.refresh_banner = Some(handle); + self.refreshing_status = RefreshingStatus::Refreshing; + } + + if action == AppAction::None + && let Some(preference) = self.pending_preference.take() + { + action = AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::SaveDpnsVotingPreference(preference), + )); + } + action + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::backend_task::contested_names::ScheduledDPNSVote; + use crate::context::connection_status::ConnectionStatus; + use crate::database::test_helpers::create_database_at_path; + use crate::model::user_role::UserRoleCell; + use crate::utils::tasks::TaskManager; + use dash_sdk::dpp::dashcore::Network; + + #[test] + fn review_regression_failed_manual_contest_refresh_can_be_retried() { + let (ctx, _dir) = kv_ctx(); + let mut screen = DPNSScreen::new(&ctx, VotesView::History); + screen.refreshing_status = RefreshingStatus::Refreshing; + let context = BackendTaskContext::from(&BackendTask::ContestedResourceTask( + ContestedResourceTask::QueryDPNSContests, + )); + screen.display_backend_task_error(&context, &TaskError::DpnsCurrentVoteUnavailable); + assert!(screen.refreshing_status == RefreshingStatus::NotRefreshing); + } + + #[test] + fn completed_contest_refresh_reloads_visible_contests_and_votes() { + let (mut screen, _dir) = voting_ui_review_fixture(); + assert!(screen.active_contests.is_empty()); + let voter = screen.voting_identities[0].identity.id(); + let poll = screen.app_context.dpns_vote_poll_id("alpha").unwrap(); + screen + .app_context + .insert_name_contests_as_normalized_names(vec!["alpha".into()]) + .unwrap(); + screen + .app_context + .cache_confirmed_dpns_vote(voter, poll, ResourceVoteChoice::Abstain) + .unwrap(); + screen.refreshing_status = RefreshingStatus::Refreshing; + screen.display_task_result(BackendTaskSuccessResult::RefreshedDpnsContests); + assert!(!screen.active_contests.is_empty()); + assert_eq!( + screen.vote_state.state(voter, poll), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Abstain)) + ); + assert!(screen.refreshing_status == RefreshingStatus::NotRefreshing); + } + + fn offline_ctx() -> (Arc, tempfile::TempDir) { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let data_dir = temp_dir.path().to_path_buf(); + crate::app_dir::ensure_env_file(&data_dir); + let db = Arc::new(create_database_at_path(&data_dir.join("data.db")).expect("db")); + let app_kv = AppContext::open_app_kv(&data_dir).expect("app kv"); + let secret_store = AppContext::open_secret_store(&data_dir).expect("secret store"); + let ctx = AppContext::new( + data_dir, + Network::Regtest, + db, + Arc::new(TaskManager::new()), + Arc::new(ConnectionStatus::new()), + egui::Context::default(), + app_kv, + secret_store, + UserRoleCell::default(), + ) + .expect("offline regtest AppContext::new"); + (ctx, temp_dir) + } + + fn kv_ctx() -> (Arc, tempfile::TempDir) { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let kv = crate::wallet_backend::DetKv::from_store(Arc::new( + crate::wallet_backend::kv_test_support::InMemoryKv::default(), + )); + let ctx = crate::context::test_support::test_app_context_with_kv( + temp_dir.path(), + Arc::new(kv.clone()), + ); + ctx.set_det_kv_override_for_test(kv); + (ctx, temp_dir) + } + + async fn wired_ctx() -> ( + Arc, + tempfile::TempDir, + tokio::sync::mpsc::Receiver, + ) { + let (ctx, temp_dir) = offline_ctx(); + let (tx, events) = tokio::sync::mpsc::channel(32); + ctx.ensure_wallet_backend(crate::utils::egui_mpsc::SenderAsync::new( + tx, + ctx.egui_ctx().clone(), + )) + .await + .expect("wire the wallet backend offline"); + (ctx, temp_dir, events) + } + + /// A masternode identity as the DPNS screen sees it: `voting` decides whether + /// its voter identity — the key the vote submission path needs — is loaded. + fn masternode_identity( + id: u8, + alias: &str, + voting: bool, + network: Network, + ) -> QualifiedIdentity { + use dash_sdk::dpp::identity::Identity; + use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; + use dash_sdk::dpp::version::PlatformVersion; + use dash_sdk::platform::IdentityPublicKey; + + let platform_version = PlatformVersion::latest(); + let identity = + Identity::create_basic_identity(Identifier::from([id; 32]), platform_version) + .expect("identity"); + let associated_voter_identity = voting.then(|| { + let voter = Identity::create_basic_identity( + Identifier::from([id.wrapping_add(100); 32]), + platform_version, + ) + .expect("voter identity"); + ( + voter, + IdentityPublicKey::random_key(0, Some(id as u64), platform_version), + ) + }); + let mut private_keys = + crate::model::qualified_identity::encrypted_key_storage::KeyStorage::default(); + if let Some((_, key)) = &associated_voter_identity { + private_keys.insert_at((crate::model::qualified_identity::PrivateKeyTarget::PrivateKeyOnVoterIdentity, key.id()), ( + crate::model::qualified_identity::qualified_identity_public_key::QualifiedIdentityPublicKey::from(key.clone()), + crate::model::qualified_identity::encrypted_key_storage::PrivateKeyData::InVault, + )); + } + QualifiedIdentity { + identity, + associated_voter_identity, + associated_operator_identity: None, + associated_owner_key_id: None, + identity_type: crate::model::qualified_identity::IdentityType::Masternode, + alias: Some(alias.to_owned()), + private_keys, + dpns_names: vec![], + associated_wallets: std::collections::BTreeMap::new(), + secret_access: None, + wallet_index: None, + top_ups: Default::default(), + status: Default::default(), + network, + } + } + + fn pending_scheduled_key(context: &AppContext) -> DpnsScheduledVoteKey { + DpnsScheduledVoteKey { + network: context.network(), + voter_id: Identifier::from([1; 32]), + contested_name: "pending".to_owned(), + } + } + + /// VOTE-TC-100: no window overlay; staged decisions clear only when this + /// panel's own operation reports, never on another operation's update. + #[test] + fn own_operation_result_clears_staged_decisions_without_an_overlay() { + let (mut screen, _temp_dir) = voting_ui_review_fixture(); + let ctx = Arc::clone(&screen.app_context); + assert!(matches!( + screen.submit_confirmed_votes(), + AppAction::BackendTask(_) + )); + let operation_id = screen.pending_vote_operation.unwrap(); + + screen.display_task_result(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: ctx.network(), + operation_id: DpnsVoteOperationId::from_bytes([8; 16]), + }); + assert_eq!(screen.selected_votes.len(), 1); + assert!(screen.pending_vote_operation.is_some()); + + screen + .pending_scheduled_actions + .insert(pending_scheduled_key(&ctx), BackendTaskContext::Unknown); + screen.display_task_result(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: ctx.network(), + operation_id, + }); + + assert!(screen.selected_votes.is_empty()); + assert!(screen.pending_vote_operation.is_none()); + assert!(matches!( + screen.confirm_status, + VoteHandlingStatus::NotStarted + )); + assert!(!screen.pending_scheduled_actions.is_empty()); + assert!( + !crate::ui::components::progress_overlay::ProgressOverlay::has_global(ctx.egui_ctx()) + ); + } + + #[test] + fn successful_vote_change_reloads_the_new_proved_choice() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let kv = crate::wallet_backend::DetKv::from_store(Arc::new( + crate::wallet_backend::kv_test_support::InMemoryKv::default(), + )); + let ctx = crate::context::test_support::test_app_context_with_kv( + temp_dir.path(), + Arc::new(kv.clone()), + ); + ctx.set_det_kv_override_for_test(kv); + let voter = Identifier::from([1; 32]); + let poll = Identifier::from([2; 32]); + let old_choice = ResourceVoteChoice::TowardsIdentity(Identifier::from([3; 32])); + ctx.cache_confirmed_dpns_vote(voter, poll, old_choice) + .expect("seed old proved choice"); + + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); + screen.vote_state = DpnsVoteStateSnapshot::load(&ctx, &[voter], &[poll]) + .expect("load initial proved choice"); + assert_eq!( + screen.vote_state.state(voter, poll), + DpnsCurrentVoteState::Available(Some(old_choice)) + ); + + ctx.cache_confirmed_dpns_vote(voter, poll, ResourceVoteChoice::Lock) + .expect("cache confirmed vote change"); + screen.display_task_result(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: ctx.network(), + operation_id: DpnsVoteOperationId::from_bytes([7; 16]), + }); + + assert_eq!( + screen.vote_state.state(voter, poll), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + } + + #[test] + fn review_regression_review_choice_names_the_candidate_or_falls_back_to_its_identifier() { + let candidate_id = Identifier::from([42; 32]); + let encoded = candidate_id.to_string(Encoding::Base58); + + let named = vote_choice_label( + ResourceVoteChoice::TowardsIdentity(candidate_id), + Some("alice"), + ); + assert!(named.starts_with("Vote for alice (")); + assert!(named.contains(&encoded)); + + let unresolved = vote_choice_label(ResourceVoteChoice::TowardsIdentity(candidate_id), None); + assert_eq!(unresolved, format!("Vote for {encoded}")); + } + + /// Submission is not blocked when a candidate name cannot be resolved, so + /// the review line has to carry the identifier itself. + #[test] + fn review_sheet_identifies_an_uncached_candidate_by_its_identifier() { + use egui_kittest::kittest::Queryable; + let (mut screen, _dir) = voting_ui_review_fixture(); + let candidate_id = Identifier::from([3; 32]); + let choice = ResourceVoteChoice::TowardsIdentity(candidate_id); + screen.selected_votes[0].vote_choice = choice; + assert!( + screen.candidate_name("alpha", choice).is_none(), + "the fixture must leave the candidate name uncached, or this proves nothing" + ); + let expected = decision_row( + "alpha", + &format!( + "Vote for {handle}", + handle = candidate_id.to_string(Encoding::Base58) + ), + 1, + ); + + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1000.0, 800.0)) + .build_ui(move |ui| { + screen.show_confirm_step(ui); + }); + harness.run(); + + assert!(harness.query_by_label(&expected).is_some()); + for label in [ + "Cast 1 decision with 1 node", + "1 transaction, one per node and name. Voting is free for your nodes.", + "Cast 1 vote", + ] { + assert!( + harness.query_by_label(label).is_some(), + "Missing review detail: {label}" + ); + } + } + + /// Candidate labels are resolved once per refresh, so the render path does a + /// keyed lookup instead of rescanning every contest this install ever cached. + #[test] + fn candidate_labels_come_from_the_refresh_time_index_not_a_per_frame_scan() { + let (ctx, _temp_dir) = kv_ctx(); + ctx.seed_dpns_contest_for_test("alpha", None, false); + let mut screen = DPNSScreen::new(&ctx, VotesView::Scheduled); + let candidate = ResourceVoteChoice::TowardsIdentity(Identifier::from([3; 32])); + assert_eq!(screen.candidate_name("alpha", candidate), Some("alpha")); + + screen.contested_names.lock_recover().clear(); + assert_eq!( + screen.candidate_name("alpha", candidate), + Some("alpha"), + "rendering a row must not depend on scanning the contested-name cache" + ); + + ctx.seed_dpns_contest_for_test("beta", None, false); + assert_eq!( + screen.candidate_name("beta", candidate), + None, + "a contest cached after the last refresh resolves only on the next refresh" + ); + screen.refresh(); + assert_eq!(screen.candidate_name("beta", candidate), Some("beta")); + } + + #[test] + fn activity_choice_uses_the_cached_candidate_name() { + let candidate_id = Identifier::from([42; 32]); + let label = vote_choice_label( + ResourceVoteChoice::TowardsIdentity(candidate_id), + Some("alice"), + ); + + assert_eq!( + label, + vote_choice_label( + ResourceVoteChoice::TowardsIdentity(candidate_id), + Some("alice") + ) + ); + assert!(label.contains(&candidate_id.to_string(Encoding::Base58))); + } + + #[test] + fn absolute_vote_times_are_explicitly_utc() { + let at = Utc.with_ymd_and_hms(2026, 10, 5, 12, 34, 56).unwrap(); + assert!(timestamp_with_relative(at).starts_with("2026-10-05 12:34:56 UTC (")); + } + + #[test] + fn missing_voting_nodes_copy_is_actionable_and_avoids_the_stale_route() { + assert!(NO_VOTING_NODES_DETAIL.contains("masternode")); + assert!(!NO_VOTING_NODES_MESSAGE.contains("Identities screen")); + } + + #[test] + fn scheduled_vote_sweep_error_preserves_unrelated_manual_cast() { + let (ctx, _temp_dir) = offline_ctx(); + let mut screen = DPNSScreen::new(&ctx, VotesView::Scheduled); + let error = TaskError::ScheduledVoteSweepFailed { + network: Network::Regtest, + source: Box::new(TaskError::NoVotingIdentity { + identity_id: "voter-id".to_string(), + }), + }; + + screen + .pending_scheduled_actions + .insert(pending_scheduled_key(&ctx), BackendTaskContext::Unknown); + assert!(screen.display_task_error(&error)); + assert!(!screen.pending_scheduled_actions.is_empty()); + } + + #[test] + fn direct_scheduled_vote_error_remains_available_to_global_handling() { + let (ctx, _temp_dir) = offline_ctx(); + let mut screen = DPNSScreen::new(&ctx, VotesView::Scheduled); + + screen + .pending_scheduled_actions + .insert(pending_scheduled_key(&ctx), BackendTaskContext::Unknown); + assert!(!screen.display_task_error(&TaskError::ScheduledVoteResultUnavailable)); + assert!(!screen.pending_scheduled_actions.is_empty()); + + let sweep_error = TaskError::ScheduledVoteSweepFailed { + network: Network::Regtest, + source: Box::new(TaskError::ScheduledVoteResultUnavailable), + }; + assert!(!screen.display_task_error(&sweep_error)); + + screen + .pending_scheduled_actions + .insert(pending_scheduled_key(&ctx), BackendTaskContext::Unknown); + let exhausted_error = TaskError::ScheduledVoteSweepAllAddressesExhausted { + network: Network::Regtest, + source: Box::new(TaskError::DapiNoAddresses { + source_error: Box::new(dash_sdk::Error::DapiClientError( + dash_sdk::dapi_client::DapiClientError::NoAvailableAddresses, + )), + }), + }; + assert!(!screen.display_task_error(&exhausted_error)); + assert!(!screen.pending_scheduled_actions.is_empty()); + } + + #[test] + fn scheduled_vote_actions_follow_the_journal_status() { + for status in [ + DpnsVoteTargetStatus::Scheduled, + DpnsVoteTargetStatus::Confirmed, + DpnsVoteTargetStatus::Rejected, + DpnsVoteTargetStatus::FailedBeforeSubmission, + DpnsVoteTargetStatus::Cancelled, + DpnsVoteTargetStatus::NotApplied, + ] { + assert!(scheduled_vote_remove_enabled(status), "{status:?}"); + } + for status in [ + DpnsVoteTargetStatus::Queued, + DpnsVoteTargetStatus::Submitting, + DpnsVoteTargetStatus::Confirming, + DpnsVoteTargetStatus::Unconfirmed, + ] { + assert!(!scheduled_vote_remove_enabled(status), "{status:?}"); + } + for status in [ + DpnsVoteTargetStatus::Scheduled, + DpnsVoteTargetStatus::Rejected, + DpnsVoteTargetStatus::FailedBeforeSubmission, + DpnsVoteTargetStatus::Cancelled, + DpnsVoteTargetStatus::NotApplied, + ] { + assert!(scheduled_vote_cast_enabled(status, false), "{status:?}"); + } + for status in [ + DpnsVoteTargetStatus::Queued, + DpnsVoteTargetStatus::Submitting, + DpnsVoteTargetStatus::Confirming, + DpnsVoteTargetStatus::Confirmed, + DpnsVoteTargetStatus::Unconfirmed, + ] { + assert!(!scheduled_vote_cast_enabled(status, false), "{status:?}"); + } + assert!(!scheduled_vote_cast_enabled( + DpnsVoteTargetStatus::Scheduled, + true + )); + } + + #[test] + fn scheduled_vote_removal_dispatches_the_journal_task() { + let operation_id = DpnsVoteOperationId::from_bytes([31; 16]); + let key = DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([32; 32]), + vote_poll_id: Identifier::from([33; 32]), + }; + let vote = ScheduledDPNSVote { + contested_name: "dispatch".to_owned(), + voter_id: key.voter_id, + choice: ResourceVoteChoice::Lock, + unix_timestamp: 42, + executed_successfully: false, + }; + let journal_row = ScheduledDpnsVoteRow { + vote: vote.clone(), + journal_target: (operation_id, key.clone()), + status: DpnsVoteTargetStatus::Scheduled, + failure: None, + }; + assert!(matches!( + scheduled_vote_removal_task(&journal_row), + ContestedResourceTask::CancelScheduledDpnsVote { + operation_id: id, + key: task_key, + } if id == operation_id && task_key == key + )); + } + + /// A failed submission must release the pending submission and keep the + /// staged decisions, so the operator can confirm them again from the tray. + #[test] + fn failed_submission_frees_the_staged_decisions_for_another_confirm() { + let (mut screen, _dir) = voting_ui_review_fixture(); + let staged = screen.selected_votes.clone(); + assert!(matches!( + screen.submit_confirmed_votes(), + AppAction::BackendTask(_) + )); + let operation_id = screen.pending_vote_operation.unwrap(); + screen.confirm_open = false; + let error = TaskError::DpnsCurrentVoteUnavailable; + + screen.display_backend_task_error( + &BackendTaskContext::DpnsVoteOperation { + network: screen.app_context.network(), + operation_id, + }, + &error, + ); + screen.display_task_error(&error); + + assert_eq!(screen.pending_vote_operation, None); + assert_eq!(screen.selected_votes, staged); + assert!(!staged.is_empty()); + assert!(!screen.confirm_open); + screen.open_review_for_node_set(); + assert!( + screen.confirm_open, + "the confirm step must open again once the failed submission is released" + ); + assert!(matches!( + screen.confirm_status, + VoteHandlingStatus::NotStarted + )); + } + + /// An error belonging to a different operation must not release the + /// submission this screen is still waiting on. + #[test] + fn unrelated_error_keeps_the_pending_submission_in_progress() { + let (ctx, _temp_dir) = offline_ctx(); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); + let error = TaskError::DpnsCurrentVoteUnavailable; + screen.pending_vote_operation = Some(DpnsVoteOperationId::from_bytes([11; 16])); + + screen.display_backend_task_error( + &BackendTaskContext::DpnsVoteOperation { + network: ctx.network(), + operation_id: DpnsVoteOperationId::from_bytes([12; 16]), + }, + &error, + ); + screen.display_task_error(&error); + + assert_eq!( + screen.pending_vote_operation, + Some(DpnsVoteOperationId::from_bytes([11; 16])) + ); + } + + /// VOTE-TC-013: a masternode loaded without its voting key must not reach the + /// composer — the actionable "no voting key" state has to come first. This is + /// distinct from having no masternode loaded at all. + #[tokio::test] + async fn a_loaded_masternode_without_a_voting_key_cannot_compose_votes() { + let (ctx, _temp_dir, _events) = wired_ctx().await; + ctx.insert_local_qualified_identity( + &masternode_identity(41, "read-only-node", false, ctx.network()), + &None, + ) + .expect("insert keyless masternode"); + + let screen = DPNSScreen::new(&ctx, VotesView::ToDecide); + + assert!( + !ctx.load_local_voting_identities() + .expect("load voting identities") + .is_empty(), + "the keyless masternode must still be loaded, or this proves nothing" + ); + assert!( + screen.voting_identities.is_empty(), + "a node with no voting key cannot satisfy the submit path" + ); + } + + #[tokio::test] + async fn a_loaded_masternode_with_a_voting_key_can_compose_votes() { + let (ctx, _temp_dir, _events) = wired_ctx().await; + ctx.insert_local_qualified_identity( + &masternode_identity(42, "voting-node", true, ctx.network()), + &None, + ) + .expect("insert voting masternode"); + + let screen = DPNSScreen::new(&ctx, VotesView::ToDecide); + + assert_eq!(screen.voting_identities.len(), 1); + } + + #[test] + fn cards_show_in_flight_and_partial_completion_without_storage_reads() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let store = Arc::new(crate::wallet_backend::kv_test_support::FailingKv::default()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(store.clone())); + ctx.seed_dpns_contest_for_test("alpha", None, false); + let poll = ctx.dpns_vote_poll_id("alpha").unwrap(); + let voter = Identifier::from([1; 32]); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); + screen.cards = vec![VoteCard::new( + Arc::new(ctx.all_contested_names().unwrap().remove(0)), + Some(poll), + vec![NodeContestState { + node: voter, + status: NodeContestStatus::NotVoted, + current: None, + changes: ChangesLeft::Unknown, + }], + )]; + let target = DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: ctx.network(), + voter_id: voter, + vote_poll_id: poll, + }, + voter_alias: None, + contested_name: "alpha".into(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Now, + }; + let key = target.key.clone(); + let mut sibling = target.clone(); + sibling.key.vote_poll_id = ctx.dpns_vote_poll_id("beta").unwrap(); + sibling.contested_name = "beta".into(); + let mut operation = AppContext::new_dpns_vote_operation(vec![target, sibling]); + ctx.insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + store.fail_all_reads(true); + screen.sync_vote_progress(); + assert_eq!(screen.cards[0].nodes[0].status, NodeContestStatus::InFlight); + store.fail_all_reads(false); + ctx.update_dpns_vote_target(operation.id, &key, DpnsVoteTargetStatus::Confirmed, None) + .unwrap(); + store.fail_all_reads(true); + screen.sync_vote_progress(); + assert_eq!( + screen.cards[0].nodes[0].status, + NodeContestStatus::Voted(ResourceVoteChoice::Lock) + ); + assert_eq!( + screen.cards[0].nodes[0].current, + Some(ResourceVoteChoice::Lock) + ); + assert_eq!( + screen + .vote_operations + .operation(operation.id) + .unwrap() + .targets[1] + .status, + DpnsVoteTargetStatus::Queued + ); + } + + /// A vote this device just saw applied leaves a record, so the card must + /// show the new remainder instead of claiming it has none. + #[test] + fn a_vote_confirmed_in_live_progress_updates_changes_left() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let store = Arc::new(crate::wallet_backend::kv_test_support::FailingKv::default()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(store.clone())); + ctx.seed_dpns_contest_for_test("alpha", None, false); + let poll = ctx.dpns_vote_poll_id("alpha").unwrap(); + let voter = Identifier::from([1; 32]); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); + screen.cards = vec![VoteCard::new( + Arc::new(ctx.all_contested_names().unwrap().remove(0)), + Some(poll), + vec![NodeContestState { + node: voter, + status: NodeContestStatus::Voted(ResourceVoteChoice::Abstain), + current: Some(ResourceVoteChoice::Abstain), + changes: ChangesLeft::Known(3), + }], + )]; + let key = DpnsVoteTargetKey { + network: ctx.network(), + voter_id: voter, + vote_poll_id: poll, + }; + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: key.clone(), + voter_alias: None, + contested_name: "alpha".into(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: Some(ResourceVoteChoice::Abstain), + timing: VoteTiming::Now, + }]); + ctx.insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + assert!(ctx.claim_dpns_vote_target(operation.id, &key).unwrap()); + assert!(ctx.mark_dpns_vote_broadcast(operation.id, &key).unwrap()); + store.fail_all_reads(true); + screen.sync_vote_progress(); + assert_eq!(screen.cards[0].nodes[0].status, NodeContestStatus::InFlight); + assert_eq!(screen.cards[0].nodes[0].changes, ChangesLeft::Known(3)); + store.fail_all_reads(false); + ctx.update_dpns_vote_target(operation.id, &key, DpnsVoteTargetStatus::Confirmed, None) + .unwrap(); + store.fail_all_reads(true); + screen.sync_vote_progress(); + let node = screen.cards[0].nodes[0]; + assert_eq!( + node.status, + NodeContestStatus::Voted(ResourceVoteChoice::Lock) + ); + assert_eq!( + node.changes, + ChangesLeft::Known(2), + "the change this device just saw applied must be counted, not unknown" + ); + store.fail_all_reads(false); + assert_eq!( + ctx.dpns_changes_left(voter, poll, DpnsCurrentVoteState::Available(node.current)), + ChangesLeft::Known(4), + "the durable count holds this one vote; the card started from an older count" + ); + } + + #[tokio::test] + async fn entering_votes_reloads_new_voters_without_expanding_staged_choices() { + use crate::model::dpns_voting::operator::MasternodesSegment; + use crate::ui::masternodes::list_screen::MasternodesScreen; + let (ctx, _temp_dir, _events) = wired_ctx().await; + let mut screen = MasternodesScreen::new(&ctx); + screen.select_segment(MasternodesSegment::Nodes); + assert!(screen.votes_mut().voting_identities.is_empty()); + let first = masternode_identity(42, "first-node", true, ctx.network()); + ctx.insert_local_qualified_identity(&first, &None).unwrap(); + screen.select_segment(MasternodesSegment::Votes); + assert_eq!(screen.votes_mut().voting_identities.len(), 1); + screen.votes_mut().selected_votes.push(SelectedVote { + contested_name: "alpha".into(), + vote_choice: ResourceVoteChoice::Lock, + end_time: None, + }); + screen.select_segment(MasternodesSegment::Nodes); + let second = masternode_identity(43, "second-node", true, ctx.network()); + ctx.insert_local_qualified_identity(&second, &None).unwrap(); + screen.select_segment(MasternodesSegment::Votes); + assert_eq!(screen.votes_mut().voting_identities.len(), 2); + assert_eq!( + screen.votes_mut().node_overrides.get(&second.identity.id()), + Some(&NodeTiming::DontUse) + ); + assert!( + !screen + .votes_mut() + .node_overrides + .contains_key(&first.identity.id()) + ); + } + + /// VOTE-FR-080: with Cancel focused, Enter activates Cancel only and + /// casts nothing (any focused widget turns the window's Enter shortcut + /// off); with nothing focused, Enter casts. + #[test] + fn enter_in_the_confirm_never_casts_while_cancel_has_focus() { + use egui_kittest::kittest::Queryable; + let render = |screen: &Arc>| { + let rendering = screen.clone(); + egui_kittest::Harness::builder() + .with_size(egui::vec2(1000.0, 800.0)) + .build_ui(move |ui| { + rendering.lock_recover().show_confirm_step(ui); + }) + }; + let (mut screen, _dir) = voting_ui_review_fixture(); + screen.confirm_open = true; + let screen = Arc::new(Mutex::new(screen)); + + let mut harness = render(&screen); + harness.run(); + harness.get_by_label("Cancel").focus(); + harness.run(); + harness.key_press(egui::Key::Enter); + harness.run(); + { + let screen = screen.lock_recover(); + assert!( + screen.pending_vote_operation.is_none(), + "Enter on Cancel must not cast" + ); + assert!(!screen.confirm_open, "Enter on Cancel cancels"); + } + + screen.lock_recover().confirm_open = true; + let mut harness = render(&screen); + harness.run(); + harness.key_press(egui::Key::Enter); + harness.run_steps(2); // casting shows a spinner, which keeps repainting + assert!( + screen.lock_recover().pending_vote_operation.is_some(), + "Enter with nothing focused casts" + ); + } + + #[tokio::test] + async fn followup_repeated_enter_does_not_submit_confirmation() { + let (screen, _dir) = two_contest_screen().await; + let rendering = screen.clone(); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1400.0, 1200.0)) + .build_ui(move |ui| { + rendering.lock_recover().ui(ui); + }); + harness.run(); + screen.lock_recover().list_focused = true; + for key in [egui::Key::J, egui::Key::L] { + harness.key_press(key); + harness.run(); + } + let enter = |pressed| egui::Event::Key { + key: egui::Key::Enter, + physical_key: None, + pressed, + repeat: false, // egui derives repeat from the held-key state. + modifiers: egui::Modifiers::NONE, + }; + harness.event(enter(true)); + harness.run(); + assert!(screen.lock_recover().confirm_open); + assert!(screen.lock_recover().pending_vote_operation.is_none()); + harness.event(enter(true)); + harness.run_steps(2); + assert!(screen.lock_recover().pending_vote_operation.is_none()); + harness.event(enter(false)); + harness.run_steps(2); + harness.event(enter(true)); + harness.run_steps(2); + assert!( + screen.lock_recover().pending_vote_operation.is_some(), + "a fresh press after release confirms" + ); + } + + fn voting_ui_review_fixture() -> (DPNSScreen, tempfile::TempDir) { + let (ctx, temp_dir) = kv_ctx(); + let voter = masternode_identity(1, "node-one", true, ctx.network()); + let poll = ctx.dpns_vote_poll_id("alpha").unwrap(); + ctx.cache_confirmed_dpns_vote(voter.identity.id(), poll, ResourceVoteChoice::Lock) + .unwrap(); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); + screen.voting_identities = vec![voter.clone()]; + screen.rebuild_cards(); + screen.selected_votes = vec![SelectedVote { + contested_name: "alpha".to_owned(), + vote_choice: ResourceVoteChoice::Abstain, + end_time: None, + }]; + screen.vote_state = + DpnsVoteStateSnapshot::load(&ctx, &[voter.identity.id()], &[poll]).unwrap(); + (screen, temp_dir) + } + + #[test] + fn review_safety_submission_result_preserves_new_staged_decisions() { + let (mut screen, _dir) = voting_ui_review_fixture(); + for name in ["alpha", "beta"] { + screen + .app_context + .seed_dpns_contest_for_test(name, Some(now_ms() + 600_000), false); + } + screen.refresh(); + screen.selected_cards.insert("alpha".to_owned()); + assert!(matches!( + screen.submit_confirmed_votes(), + AppAction::BackendTask(_) + )); + let operation_id = screen.pending_vote_operation.unwrap(); + let new_vote = SelectedVote { + contested_name: "beta".to_owned(), + vote_choice: ResourceVoteChoice::Lock, + end_time: None, + }; + screen.selected_votes.push(new_vote.clone()); + screen.selected_cards.insert("beta".to_owned()); + screen.display_task_result(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: screen.app_context.network(), + operation_id, + }); + assert_eq!(screen.selected_votes, vec![new_vote]); + assert_eq!(screen.selected_cards, BTreeSet::from(["beta".to_owned()])); + assert!(screen.pending_vote_operation.is_none()); + } + + #[test] + fn review_safety_pending_submission_cannot_be_replaced_by_reopening_review() { + let (mut screen, _dir) = voting_ui_review_fixture(); + assert!(matches!( + screen.submit_confirmed_votes(), + AppAction::BackendTask(_) + )); + let operation_id = screen.pending_vote_operation; + screen.confirm_open = false; + screen.open_review_for_node_set(); + assert!(!screen.confirm_open); + assert!(matches!(screen.submit_confirmed_votes(), AppAction::None)); + assert_eq!(screen.pending_vote_operation, operation_id); + } + + #[test] + fn review_safety_submission_result_preserves_changed_staged_choice() { + let (mut screen, _dir) = voting_ui_review_fixture(); + assert!(matches!( + screen.submit_confirmed_votes(), + AppAction::BackendTask(_) + )); + let operation_id = screen.pending_vote_operation.unwrap(); + screen.selected_votes[0].vote_choice = ResourceVoteChoice::Lock; + let revised = screen.selected_votes.clone(); + screen.display_task_result(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: screen.app_context.network(), + operation_id, + }); + assert_eq!(screen.selected_votes, revised); + } + + #[test] + fn voting_ui_unconfirmed_activity_is_reachable_without_active_contests_after_restart() { + use egui_kittest::kittest::Queryable; + let (screen, _dir) = voting_ui_review_fixture(); + let target = screen.build_review_plan().unwrap().aggregate.targets[0].clone(); + let mut operation = AppContext::new_dpns_vote_operation(vec![target]); + operation.targets[0].status = DpnsVoteTargetStatus::Unconfirmed; + screen + .app_context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + let mut reopened = DPNSScreen::new(&screen.app_context, VotesView::ToDecide); + assert!(reopened.active_contests.is_empty()); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1000.0, 1200.0)) + .build_ui(move |ui| { + reopened.ui(ui); + }); + harness.run(); + // VOTE-TC-102: the Needs attention row leads to the drawer's Check again. + assert!( + harness + .query_by_label( + "Votes still being checked: 1. Do not submit the pending votes again." + ) + .is_some() + ); + assert!(harness.query_by_label("Show progress").is_some()); + } + + #[test] + fn additional_scenarios_missed_schedule_is_explained_after_reopening() { + use egui_kittest::kittest::Queryable; + for status in [ + DpnsVoteTargetStatus::Scheduled, + DpnsVoteTargetStatus::Queued, + ] { + let (screen, _dir) = voting_ui_review_fixture(); + let mut target = screen.build_review_plan().unwrap().aggregate.targets[0].clone(); + target.timing = VoteTiming::Scheduled(1); + let mut operation = AppContext::new_dpns_vote_operation(vec![target]); + operation.targets[0].status = status; + screen + .app_context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + let mut reopened = DPNSScreen::new(&screen.app_context, VotesView::Scheduled); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .build_ui(move |ui| { + reopened.ui(ui); + }); + harness.run(); + assert_eq!( + harness.query_by_label("Missed automatic vote").is_some(), + status == DpnsVoteTargetStatus::Scheduled + ); + if status == DpnsVoteTargetStatus::Scheduled { + assert!(harness.query_by_label("The automatic voting time was missed. On the Scheduled tab, use Cast now to vote, Edit to reschedule, or Remove to cancel.").is_some()); + assert!(harness.query_by_label("Cast now").is_some()); + assert!(harness.query_by_label("Edit").is_some()); + } + } + } + + #[test] + fn additional_scenarios_journal_failure_stays_visible_until_refresh_succeeds() { + use egui_kittest::kittest::Queryable; + for fail_at_construction in [true, false] { + let (context, _dir) = kv_ctx(); + let store = Arc::new(crate::wallet_backend::kv_test_support::FailingKv::default()); + context.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store( + store.clone(), + )); + if fail_at_construction { + store.fail_next_gets_containing("det:dpns_vote_operations:v2:", 1); + } + let mut screen = DPNSScreen::new(&context, VotesView::Scheduled); + if !fail_at_construction { + store.fail_next_gets_containing("det:dpns_vote_operations:v2:", 1); + screen.refresh(); + } + let screen = Arc::new(Mutex::new(screen)); + let rendering = screen.clone(); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .build_ui(move |ui| { + // The hosting Masternodes screen renders global banners + // through its island panel. + crate::ui::components::styled::island_central_panel(ui, |ui| { + rendering.lock_recover().ui(ui) + }); + }); + harness.run(); + let message = "Saved voting progress could not be read. The displayed history may be incomplete or out of date. Do not submit votes again until you have retried loading and checked their status."; + assert!(harness.query_by_label(message).is_some()); + screen + .lock_recover() + .journal_error_banner + .as_ref() + .unwrap() + .clone() + .clear(); + harness.run(); + assert!(harness.query_by_label(message).is_some()); + harness.get_by_label("Retry loading").click(); + harness.run(); + assert!(harness.query_by_label(message).is_none()); + } + } + + #[test] + fn voting_ui_scheduled_failure_reason_survives_reopening() { + use crate::model::dpns_voting::DpnsVoteFailure; + use egui_kittest::kittest::Queryable; + for (failure, reason) in [ + ( + DpnsVoteFailure::CurrentVoteUnavailable, + "Current vote could not be verified. On the Scheduled tab, use Cast now to check again or Edit to reschedule.", + ), + ( + DpnsVoteFailure::SubmissionFailed, + "The vote could not be submitted. Check your connection and voting key, then use Cast now or Edit on the Scheduled tab.", + ), + ] { + let (screen, _dir) = voting_ui_review_fixture(); + let mut target = screen.build_review_plan().unwrap().aggregate.targets[0].clone(); + target.timing = VoteTiming::Scheduled(Utc::now().timestamp_millis() as u64); + let mut operation = AppContext::new_dpns_vote_operation(vec![target]); + operation.targets[0].failure = Some(failure); + screen + .app_context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + // The reason lives on the Scheduled tab, which its own copy names. + let mut reopened = DPNSScreen::new(&screen.app_context, VotesView::Scheduled); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .build_ui(move |ui| { + reopened.ui(ui); + }); + harness.run(); + assert!(harness.query_by_label("Not submitted").is_some()); + assert!(harness.query_by_label(reason).is_some()); + } + } + + #[tokio::test] + async fn voting_ui_constructor_keeps_other_voters_when_one_snapshot_read_fails() { + let (context, _dir, _events) = wired_ctx().await; + let store = Arc::new(crate::wallet_backend::kv_test_support::FailingKv::default()); + let kv = crate::wallet_backend::DetKv::from_store(store.clone()); + context.set_det_kv_override_for_test(kv); + for id in [1, 2] { + let voter = masternode_identity(id, &format!("node-{id}"), true, context.network()); + context + .insert_local_qualified_identity(&voter, &None) + .unwrap(); + let poll = context.dpns_vote_poll_id("alpha").unwrap(); + context + .cache_confirmed_dpns_vote(voter.identity.id(), poll, ResourceVoteChoice::Lock) + .unwrap(); + } + context + .insert_name_contests_as_normalized_names(vec!["alpha".into()]) + .unwrap(); + store.fail_next_gets_containing("det:dpns_current_votes:v3:", 1); + let screen = DPNSScreen::new(&context, VotesView::ToDecide); + assert_eq!(screen.voting_identities.len(), 2); + let poll = context.dpns_vote_poll_id("alpha").unwrap(); + assert_eq!( + screen + .vote_state + .state(screen.voting_identities[0].identity.id(), poll), + DpnsCurrentVoteState::Unavailable + ); + assert_eq!( + screen + .vote_state + .state(screen.voting_identities[1].identity.id(), poll), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + } + + #[tokio::test] + async fn voting_ui_task_error_reloads_current_state_and_preserves_valid_confirmations() { + let (context, _dir) = kv_ctx(); + let voter = Identifier::from([1; 32]); + let poll = context.dpns_vote_poll_id("alpha").unwrap(); + let other = context.dpns_vote_poll_id("beta").unwrap(); + context + .seed_proved_dpns_votes_for_test( + voter, + BTreeMap::from([(poll.to_buffer(), ResourceVoteChoice::Lock)]), + ) + .await + .unwrap(); + context + .cache_confirmed_dpns_vote(voter, other, ResourceVoteChoice::Lock) + .unwrap(); + let mut screen = DPNSScreen::new(&context, VotesView::ToDecide); + screen + .vote_state + .refresh(&context, &[voter], &[poll, other]) + .unwrap(); + assert_eq!( + screen.vote_state.state(voter, poll), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + let error = TaskError::DpnsVotePreflightFailed { + source: Arc::new( + context + .fail_proved_dpns_votes_for_test(voter) + .await + .unwrap_err(), + ), + }; + assert_eq!( + context.dpns_current_vote_state(voter, poll).unwrap(), + DpnsCurrentVoteState::Unavailable + ); + screen.display_task_error(&error); + assert_eq!( + screen.vote_state.state(voter, poll), + DpnsCurrentVoteState::Unavailable + ); + assert_eq!( + screen.vote_state.state(voter, other), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + } + + /// VOTE-FR-081: absolute and relative schedules must fall strictly + /// before each contest's end and after now. + #[test] + fn voting_ui_review_rejects_absolute_and_relative_schedules_at_contest_deadline() { + let (mut screen, _dir) = voting_ui_review_fixture(); + let now = Utc::now(); + screen.confirm_timing = ConfirmTiming::At; + screen.confirm_schedule = + UtcScheduleInput::new().with_time(now + chrono::Duration::hours(1)); + let scheduled_at = screen.confirm_schedule.current_value().unwrap(); + for deadline in [scheduled_at - 1, scheduled_at, scheduled_at + 1] { + screen.selected_votes[0].end_time = Some(deadline); + assert_eq!( + screen.build_review_plan_at(now).is_ok(), + deadline > scheduled_at + ); + } + + screen.confirm_timing = ConfirmTiming::BeforeEnd; + screen.relative_preset = std::time::Duration::from_secs(10 * 60); + let now_ms = now.timestamp_millis() as u64; + screen.selected_votes[0].end_time = Some(now_ms + 5 * 60_000); + let plan = screen.build_review_plan_at(now).unwrap(); + assert_eq!( + ( + plan.aggregate.targets[0].timing, + plan.aggregate.ends_soon_now + ), + (VoteTiming::Now, 1), + "ten minutes before an end five minutes away has passed, so it votes now" + ); + let end = now_ms + 60 * 60_000; + screen.selected_votes[0].end_time = Some(end); + assert_eq!( + screen.build_review_plan_at(now).unwrap().aggregate.targets[0].timing, + VoteTiming::Scheduled(end - 10 * 60_000) + ); + + screen.confirm_timing = ConfirmTiming::At; + screen.selected_votes[0].end_time = Some(scheduled_at + 1); + screen.selected_votes.push(SelectedVote { + contested_name: "beta".into(), + vote_choice: ResourceVoteChoice::Abstain, + end_time: Some(scheduled_at), + }); + let Err(error) = screen.build_review_plan_at(now) else { + panic!("the second contest has ended before the schedule"); + }; + assert!(matches!( + error, + ReviewPlanError::Compose(ComposeError::ScheduleOutlastsContest { contested_name }) + if contested_name == "beta" + )); + } + + #[test] + fn voting_ui_absolute_schedule_preserves_the_requested_utc_minute() { + let (mut screen, _temp_dir) = voting_ui_review_fixture(); + let requested = (Utc::now() + chrono::Duration::days(1)) + .date_naive() + .and_hms_opt(18, 30, 0) + .unwrap() + .and_utc(); + screen.confirm_schedule = UtcScheduleInput::new().with_time(requested); + screen.confirm_timing = ConfirmTiming::At; + let plan = screen.build_review_plan().unwrap(); + assert_eq!( + plan.aggregate.targets[0].timing, + VoteTiming::Scheduled(requested.timestamp_millis() as u64) + ); + let delayed = screen + .build_review_plan_at(Utc::now() + chrono::Duration::minutes(20)) + .unwrap(); + assert_eq!( + delayed.aggregate.targets[0].timing, + plan.aggregate.targets[0].timing + ); + } + + #[test] + fn followup_manual_cast_failure_during_bulk_clears_only_its_dispatch() { + let (mut screen, _dir) = voting_ui_review_fixture(); + let voter = screen.voting_identities[0].clone(); + let vote = crate::backend_task::contested_names::ScheduledDPNSVote { + contested_name: "alpha".into(), + voter_id: voter.identity.id(), + choice: ResourceVoteChoice::Abstain, + unix_timestamp: 123, + executed_successfully: false, + }; + let task = BackendTask::ContestedResourceTask(ContestedResourceTask::CastScheduledVote( + vote, + Box::new(voter), + )); + let dispatch = BackendTaskContext::for_dispatch_on(&task, screen.app_context.network()); + let unrelated_dispatch = + BackendTaskContext::for_dispatch_on(&task, screen.app_context.network()); + let key = DpnsScheduledVoteKey { + network: screen.app_context.network(), + voter_id: screen.voting_identities[0].identity.id(), + contested_name: "alpha".into(), + }; + screen + .pending_scheduled_actions + .insert(key.clone(), dispatch.clone()); + let updated = BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: screen.app_context.network(), + operation_id: DpnsVoteOperationId::from_bytes([9; 16]), + }; + screen.display_backend_task_result(&unrelated_dispatch, updated.clone()); + assert!(screen.pending_scheduled_actions.contains_key(&key)); + let sweep = BackendTaskContext::ScheduledVoteSweep { + network: screen.app_context.network(), + }; + screen.display_backend_task_result( + &sweep, + BackendTaskSuccessResult::ScheduledVoteSweepCompleted { + network: screen.app_context.network(), + preserve_eligibility_since_ms: None, + }, + ); + let error = TaskError::ScheduledVoteResultUnavailable; + screen.display_backend_task_error(&sweep, &error); + screen.display_task_error(&error); + assert!(screen.pending_scheduled_actions.contains_key(&key)); + screen.display_backend_task_result(&dispatch, updated); + assert!(screen.pending_scheduled_actions.is_empty()); + screen + .pending_scheduled_actions + .insert(key.clone(), dispatch.clone()); + let bulk_id = DpnsVoteOperationId::from_bytes([13; 16]); + screen.pending_vote_operation = Some(bulk_id); + screen.display_backend_task_error(&dispatch, &error); + screen.display_task_error(&error); + assert!(screen.pending_scheduled_actions.is_empty()); + screen + .pending_scheduled_actions + .insert(key, dispatch.clone()); + assert_eq!(screen.pending_vote_operation, Some(bulk_id)); + screen.reset_for_network_switch(); + assert!(screen.pending_scheduled_actions.is_empty()); + assert!(!screen.finish_scheduled_dispatch(&dispatch)); + } + + #[test] + fn followup_card_refresh_enters_shared_progress_state() { + use egui_kittest::kittest::Queryable; + use std::sync::atomic::{AtomicBool, Ordering}; + let (mut screen, _dir) = voting_ui_review_fixture(); + screen + .app_context + .seed_dpns_contest_for_test("alpha", None, false); + screen.refresh(); + screen.vote_state = DpnsVoteStateSnapshot::default(); + screen.rebuild_cards(); + let refreshed = Arc::new(AtomicBool::new(false)); + let received_refresh = refreshed.clone(); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1000.0, 1200.0)) + .build_ui(move |ui| { + if matches!( + screen.ui(ui), + AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::QueryDPNSContests + )) + ) { + received_refresh.store( + screen.refreshing_status == RefreshingStatus::Refreshing + && screen.refresh_banner.is_some(), + Ordering::Relaxed, + ); + } + }); + harness.run(); + assert!( + harness.query_by_label("alpha.dash").is_some(), + "unavailable state must not hide the contest" + ); + assert!(harness.query_by_label("Refresh voting").is_some()); + assert!( + harness + .query_by_label("Vote state is unavailable for 1 node; it's left out.") + .is_some() + ); + harness.get_by_label("Refresh voting").click(); + harness.run(); + assert!(refreshed.load(Ordering::Relaxed)); + } + + #[tokio::test] + async fn review_fixes_changed_vote_error_reloads_the_review_warning() { + use egui_kittest::kittest::Queryable; + let (mut screen, _dir) = voting_ui_review_fixture(); + let voter = screen.voting_identities[0].identity.id(); + let poll = screen.app_context.dpns_vote_poll_id("alpha").unwrap(); + screen + .app_context + .seed_proved_dpns_votes_for_test(voter, BTreeMap::new()) + .await + .unwrap(); + screen.vote_state.reload(&screen.app_context).unwrap(); + assert!(matches!( + screen.submit_confirmed_votes(), + AppAction::BackendTask(_) + )); + let operation_id = screen.pending_vote_operation.unwrap(); + screen + .app_context + .cache_confirmed_dpns_vote(voter, poll, ResourceVoteChoice::Lock) + .unwrap(); + let error = TaskError::DpnsVoteReviewRequired; + screen.display_backend_task_error( + &BackendTaskContext::DpnsVoteOperation { + network: screen.app_context.network(), + operation_id, + }, + &error, + ); + screen.display_task_error(&error); + assert!(screen.pending_vote_operation.is_none()); + assert!(matches!( + screen.confirm_status, + VoteHandlingStatus::NotStarted + )); + assert!( + screen.confirm_open, + "DPN-005: the confirm reopens with the change warning" + ); + assert_eq!( + screen.build_review_plan().unwrap().aggregate.targets[0].current_choice, + Some(ResourceVoteChoice::Lock) + ); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1000.0, 800.0)) + .build_ui(move |ui| { + screen.show_confirm_step(ui); + }); + harness.run(); + assert!( + harness + .query_by_label( + "1 of these changes an earlier vote. Each node can change its vote 4 times per name." + ) + .is_some() + ); + } + + /// VOTE-TC-089: a contest only some node-set nodes voted on stays in To + /// decide and says how many voted; the Voted view does not list it. + #[tokio::test] + async fn partly_voted_contest_stays_in_to_decide() { + use egui_kittest::kittest::Queryable; + let (ctx, _dir) = kv_ctx(); + ctx.seed_dpns_contest_for_test("alpha", None, false); + let voted = masternode_identity(1, "node-one", true, ctx.network()); + let pending = masternode_identity(2, "node-two", true, ctx.network()); + let poll = ctx.dpns_vote_poll_id("alpha").unwrap(); + ctx.seed_proved_dpns_votes_for_test(pending.identity.id(), BTreeMap::new()) + .await + .unwrap(); + ctx.cache_confirmed_dpns_vote(voted.identity.id(), poll, ResourceVoteChoice::Lock) + .unwrap(); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); + screen.voting_identities = vec![voted.clone(), pending.clone()]; + screen.vote_state = DpnsVoteStateSnapshot::load( + &ctx, + &[voted.identity.id(), pending.identity.id()], + &[poll], + ) + .unwrap(); + screen.rebuild_cards(); + assert_eq!(screen.cards[0].placement, CardPlacement::ToDecide); + + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1200.0, 1200.0)) + .build_ui(move |ui| { + screen.ui(ui); + }); + harness.run(); + assert!(harness.query_by_label("alpha.dash").is_some()); + assert!(harness.query_by_label("Voted with 1 of 2 nodes").is_some()); + assert!( + harness + .query_by_label("1 of your nodes has not voted. 1 of your nodes voted: Lock name.") + .is_some() + ); + } + + /// A request from another screen opens the contest's card, filtered and + /// focused, once. + #[tokio::test] + async fn name_request_shows_that_contest() { + let (screen, _dir) = two_contest_screen().await; + let ctx = screen.lock_recover().app_context.clone(); + ctx.request_dpns_votes_for_name("beta".to_owned()); + let rendering = screen.clone(); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1400.0, 1200.0)) + .build_ui(move |ui| { + rendering.lock_recover().ui(ui); + }); + harness.run(); + let screen = screen.lock_recover(); + assert_eq!(screen.view, VotesView::ToDecide); + assert_eq!(screen.active_filter_term, "beta"); + assert_eq!(screen.focused_card.as_deref(), Some("beta")); + assert!(ctx.take_dpns_votes_name_request().is_none()); + } + + /// Two open contests a single voting node has not voted on yet. + async fn two_contest_screen() -> (Arc>, tempfile::TempDir) { + let (ctx, dir) = kv_ctx(); + ctx.seed_dpns_contest_for_test("alpha", None, false); + ctx.seed_dpns_contest_for_test("beta", None, false); + let node = masternode_identity(1, "node-one", true, ctx.network()); + ctx.seed_proved_dpns_votes_for_test(node.identity.id(), BTreeMap::new()) + .await + .unwrap(); + let polls = [ + ctx.dpns_vote_poll_id("alpha").unwrap(), + ctx.dpns_vote_poll_id("beta").unwrap(), + ]; + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); + screen.voting_identities = vec![node.clone()]; + screen.vote_state = + DpnsVoteStateSnapshot::load(&ctx, &[node.identity.id()], &polls).unwrap(); + screen.rebuild_cards(); + assert_eq!(screen.cards.len(), 2); + (Arc::new(Mutex::new(screen)), dir) + } + + fn staged(screen: &Arc>) -> Vec<(String, ResourceVoteChoice)> { + screen + .lock_recover() + .selected_votes + .iter() + .map(|vote| (vote.contested_name.clone(), vote.vote_choice)) + .collect() + } + + /// VOTE-TC-098: J, 1, J, L, Enter stages both decisions and opens the + /// confirm step; keys do nothing without list focus or in the filter field. + #[tokio::test] + async fn keyboard_flow_stages_decisions_and_opens_confirm() { + use egui_kittest::kittest::Queryable; + let (screen, _dir) = two_contest_screen().await; + let rendering = screen.clone(); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1400.0, 1200.0)) + .build_ui(move |ui| { + rendering.lock_recover().ui(ui); + }); + harness.run(); + + harness.key_press(egui::Key::J); + harness.run(); + assert!(staged(&screen).is_empty(), "no list focus, no shortcut"); + + screen.lock_recover().list_focused = true; + for key in [egui::Key::J, egui::Key::Num1, egui::Key::J, egui::Key::L] { + harness.key_press(key); + harness.run(); + } + let contender = ResourceVoteChoice::TowardsIdentity(Identifier::from([3; 32])); + assert_eq!( + staged(&screen), + vec![ + ("alpha".to_owned(), contender), + ("beta".to_owned(), ResourceVoteChoice::Lock), + ] + ); + + harness + .get_by_role(egui::accesskit::Role::TextInput) + .click(); + harness.run(); + harness.key_press(egui::Key::A); + harness.run(); + assert_eq!( + staged(&screen)[1], + ("beta".to_owned(), ResourceVoteChoice::Lock), + "a focused text field swallows shortcuts" + ); + + screen.lock_recover().list_focused = true; + harness.key_press(egui::Key::Escape); + harness.run(); + screen.lock_recover().list_focused = true; + harness.key_press(egui::Key::Enter); + harness.run(); + assert!(screen.lock_recover().confirm_open); + assert!( + harness + .query_by_label("Cast 2 decisions with 1 node") + .is_some() + ); + } + + /// VOTE-TC-099: with several names selected, the bulk bar stages one + /// decision on each. + #[tokio::test] + async fn bulk_bar_applies_a_decision_to_every_selected_name() { + use egui_kittest::kittest::Queryable; + let (screen, _dir) = two_contest_screen().await; + screen.lock_recover().selected_cards = + BTreeSet::from(["alpha".to_owned(), "beta".to_owned()]); + let rendering = screen.clone(); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1400.0, 1200.0)) + .build_ui(move |ui| { + rendering.lock_recover().ui(ui); + }); + harness.run(); + assert!(harness.query_by_label("2 names selected").is_some()); + harness + .get_by_role_and_label(egui::accesskit::Role::Button, "Abstain") + .click(); + harness.run(); + assert_eq!( + staged(&screen), + vec![ + ("alpha".to_owned(), ResourceVoteChoice::Abstain), + ("beta".to_owned(), ResourceVoteChoice::Abstain), + ] + ); + harness + .get_all_by_role_and_label(egui::accesskit::Role::Button, "Clear") + .next() + .expect("the bulk bar's Clear") + .click(); + harness.run(); + assert!(staged(&screen).is_empty()); + } + + #[tokio::test] + async fn blocker_empty_state_distinguishes_absent_nodes_from_missing_keys() { + use egui_kittest::kittest::Queryable; + for has_node in [false, true] { + let (ctx, _dir, _events) = wired_ctx().await; + if has_node { + ctx.insert_local_qualified_identity( + &masternode_identity(41, "read-only-node", false, ctx.network()), + &None, + ) + .unwrap(); + } + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1000.0, 1200.0)) + .build_ui(move |ui| { + screen.ui(ui); + }); + harness.run(); + let (message, action) = if has_node { + ( + "None of your nodes has a voting key on this device.", + "Add a voting key", + ) + } else { + ("No masternodes are loaded.", "Load a masternode") + }; + assert!( + harness.query_by_label(message).is_some(), + "missing {message}" + ); + assert!(harness.query_by_label(action).is_some(), "missing {action}"); + } + } + + #[test] + fn voting_ui_keyless_users_can_read_cached_active_contests() { + use egui_kittest::kittest::Queryable; + let (context, _dir) = kv_ctx(); + let mut screen = DPNSScreen::new(&context, VotesView::ToDecide); + screen.active_contests = ActiveDpnsContestSnapshot::new( + &context, + vec![ContestedName { + normalized_contested_name: "readable".into(), + contestants: None, + locked_votes: Some(2), + abstain_votes: Some(3), + awarded_to: None, + end_time: None, + state: ContestState::Ongoing, + last_updated: None, + my_votes: BTreeMap::new(), + }], + ); + screen.rebuild_cards(); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1000.0, 1200.0)) + .build_ui(move |ui| { + screen.ui(ui); + }); + harness.run(); + assert!(harness.query_by_label(NO_VOTING_NODES_MESSAGE).is_some()); + assert!(harness.query_by_label("readable.dash").is_some()); + } + + #[test] + fn voting_ui_identity_storage_error_is_not_reported_as_a_missing_key() { + use egui_kittest::kittest::Queryable; + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(crate::wallet_backend::kv_test_support::FailingKv::default()); + let kv = crate::wallet_backend::DetKv::from_store(store.clone()); + let context = crate::context::test_support::test_app_context_with_kv( + dir.path(), + Arc::new(kv.clone()), + ); + context.set_det_kv_override_for_test(kv); + store.fail_all_reads(true); + assert!(loaded_voting_identities(&context).is_err()); + for reviewing in [false, true] { + let mut screen = DPNSScreen::new(&context, VotesView::ToDecide); + assert!(screen.voting_identity_load_error.is_some()); + screen.confirm_open = reviewing; + let mut harness = egui_kittest::Harness::builder().build_ui(move |ui| { + screen.ui(ui); + }); + harness.run(); + assert!(harness.query_by_label("Your nodes could not be loaded from this device. Retry loading before voting.").is_some()); + assert!(harness.query_by_label(NO_VOTING_NODES_MESSAGE).is_none()); + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn voting_ui_retry_keeps_its_node_selection_after_returning_to_the_page() { + let (ctx, _dir, _events) = wired_ctx().await; + let first = masternode_identity(1, "first-node", true, ctx.network()); + let second = masternode_identity(2, "other-node", true, ctx.network()); + ctx.insert_local_qualified_identity(&first, &None).unwrap(); + ctx.insert_local_qualified_identity(&second, &None).unwrap(); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); + screen.selected_votes = vec![SelectedVote { + contested_name: "alpha".into(), + vote_choice: ResourceVoteChoice::Lock, + end_time: None, + }]; + screen + .node_overrides + .insert(second.identity.id(), NodeTiming::DontUse); + screen.refresh_on_arrival(); + assert_eq!( + screen.node_overrides.get(&second.identity.id()), + Some(&NodeTiming::DontUse), + "an operator's per-node choice survives returning to the page" + ); + assert!(!screen.node_overrides.contains_key(&first.identity.id())); + let newly_loaded = masternode_identity(3, "new-node", true, ctx.network()); + ctx.insert_local_qualified_identity(&newly_loaded, &None) + .unwrap(); + screen.refresh_on_arrival(); + assert_eq!( + screen.node_overrides.get(&newly_loaded.identity.id()), + Some(&NodeTiming::DontUse), + "a node loaded after decisions were staged does not join them" + ); + ctx.wallet_backend().unwrap().shutdown().await; + } + + /// A Votes panel with `Lock` staged on `alpha` while only `first-node` is + /// loaded. Both nodes hold `Abstain` there; `late-node` is not loaded yet. + fn panel_with_a_staged_decision( + ctx: &Arc, + ) -> (DPNSScreen, QualifiedIdentity, QualifiedIdentity) { + ctx.seed_dpns_contest_for_test("alpha", None, false); + let poll = ctx.dpns_vote_poll_id("alpha").unwrap(); + let first = masternode_identity(1, "first-node", true, ctx.network()); + let late = masternode_identity(2, "late-node", true, ctx.network()); + for node in [&first, &late] { + ctx.cache_confirmed_dpns_vote(node.identity.id(), poll, ResourceVoteChoice::Abstain) + .unwrap(); + } + ctx.insert_local_qualified_identity(&first, &None).unwrap(); + let mut screen = DPNSScreen::new(ctx, VotesView::ToDecide); + screen.selected_votes = vec![SelectedVote { + contested_name: "alpha".into(), + vote_choice: ResourceVoteChoice::Lock, + end_time: None, + }]; + (screen, first, late) + } + + /// The nodes the confirm step would submit with. + fn casting_nodes(screen: &DPNSScreen) -> BTreeSet { + screen + .build_review_plan() + .expect("review plan") + .targets() + .iter() + .map(|target| target.key.voter_id) + .collect() + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_node_loaded_after_staging_stays_out_of_the_confirm_step_until_included() { + let (ctx, _dir, _events) = wired_ctx().await; + let (mut screen, first, late) = panel_with_a_staged_decision(&ctx); + ctx.insert_local_qualified_identity(&late, &None).unwrap(); + let (first, late) = (first.identity.id(), late.identity.id()); + + screen.refresh_on_arrival(); + assert_eq!(screen.voting_identities.len(), 2); + screen.open_review_for_node_set(); + assert!(screen.confirm_open); + assert_eq!( + casting_nodes(&screen), + BTreeSet::from([first]), + "opening the confirm step must not add the node loaded after staging" + ); + assert_eq!( + screen + .build_review_plan() + .unwrap() + .aggregate + .skipped_by_reason(), + BTreeMap::from([(SkipReason::NotUsed, 1)]), + "the confirm step reports the node as not used" + ); + + screen.confirm_open = false; + screen.open_review_for_node_set(); + assert_eq!( + casting_nodes(&screen), + BTreeSet::from([first]), + "cancelling and opening the confirm step again keeps the node out" + ); + + screen.set_node_timing(late, NodeTiming::Batch); + assert_eq!(casting_nodes(&screen), BTreeSet::from([first, late])); + screen.confirm_open = false; + screen.open_review_for_node_set(); + assert_eq!( + casting_nodes(&screen), + BTreeSet::from([first, late]), + "a node the operator included stays included" + ); + ctx.wallet_backend().unwrap().shutdown().await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_fresh_set_of_decisions_uses_a_node_loaded_during_the_previous_set() { + let (ctx, _dir, _events) = wired_ctx().await; + let (mut screen, first, late) = panel_with_a_staged_decision(&ctx); + ctx.insert_local_qualified_identity(&late, &None).unwrap(); + let (first, late) = (first.identity.id(), late.identity.id()); + screen.refresh_on_arrival(); + screen.open_review_for_node_set(); + assert_eq!(casting_nodes(&screen), BTreeSet::from([first])); + screen.confirm_open = false; + + screen.selected_votes.clear(); + let contest = Arc::clone(&screen.cards[0].contest); + screen.stage_choice(&contest, ResourceVoteChoice::Lock); + screen.open_review_for_node_set(); + assert_eq!( + casting_nodes(&screen), + BTreeSet::from([first, late]), + "decisions staged after the node was loaded include it" + ); + ctx.wallet_backend().unwrap().shutdown().await; + } + + /// Nodes read again after a failed read were loaded before the decisions + /// were staged, so the confirm step leaves none of them out. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn nodes_read_again_after_a_failed_read_stay_in_the_staged_decisions() { + let (ctx, _dir, _events) = wired_ctx().await; + let store = Arc::new(crate::wallet_backend::kv_test_support::FailingKv::default()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(store.clone())); + let (mut screen, first, _late) = panel_with_a_staged_decision(&ctx); + + store.fail_all_reads(true); + screen.refresh_on_arrival(); + assert!(screen.voting_identity_load_error.is_some()); + store.fail_all_reads(false); + screen.refresh_on_arrival(); + assert!(screen.voting_identity_load_error.is_none()); + + screen.open_review_for_node_set(); + assert_eq!( + casting_nodes(&screen), + BTreeSet::from([first.identity.id()]) + ); + ctx.wallet_backend().unwrap().shutdown().await; + } + + #[test] + fn voting_ui_retry_reviews_only_the_failed_node_and_contest() { + let (mut screen, _dir) = voting_ui_review_fixture(); + let operation = AppContext::new_dpns_vote_operation(vec![ + screen + .build_review_plan() + .unwrap() + .aggregate + .targets + .remove(0), + ]); + screen.voting_identities.push(masternode_identity( + 2, + "node-two", + true, + screen.app_context.network(), + )); + screen.selected_votes.push(SelectedVote { + contested_name: "unrelated".into(), + vote_choice: ResourceVoteChoice::Lock, + end_time: None, + }); + let staged = screen.selected_votes.clone(); + screen.review_failed_target(&operation.targets[0]); + let plan = screen.build_review_plan().unwrap(); + assert_eq!(plan.effective_count(), 1); + assert_eq!( + plan.aggregate.targets[0].key, + operation.targets[0].target.key + ); + assert_eq!( + screen.selected_votes, staged, + "reviewing a failed vote again must not discard the staged decisions" + ); + + assert!(matches!( + screen.submit_confirmed_votes(), + AppAction::BackendTask(_) + )); + let operation_id = screen.pending_vote_operation.unwrap(); + screen.display_task_result(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: screen.app_context.network(), + operation_id, + }); + assert!(screen.pending_vote_operation.is_none()); + assert_eq!( + screen.selected_votes, staged, + "the retried vote's result must leave the staged decisions in the tray" + ); + assert_eq!(screen.retry, None); + } + + /// A retried vote that needs another review reopens the confirm step on + /// that same target, not on the unrelated staged decisions. + #[test] + fn a_retry_needing_another_review_reopens_on_the_retried_target() { + let (mut screen, _dir) = voting_ui_review_fixture(); + let operation = AppContext::new_dpns_vote_operation(vec![ + screen + .build_review_plan() + .unwrap() + .aggregate + .targets + .remove(0), + ]); + screen.selected_votes = vec![SelectedVote { + contested_name: "unrelated".into(), + vote_choice: ResourceVoteChoice::Lock, + end_time: None, + }]; + screen.review_failed_target(&operation.targets[0]); + let retried = screen.retry.clone(); + assert!(retried.is_some()); + assert!(matches!( + screen.submit_confirmed_votes(), + AppAction::BackendTask(_) + )); + screen.confirm_open = false; + let error = TaskError::DpnsVoteReviewRequired; + screen.display_backend_task_error( + &BackendTaskContext::DpnsVoteOperation { + network: screen.app_context.network(), + operation_id: screen.pending_vote_operation.unwrap(), + }, + &error, + ); + screen.display_task_error(&error); + + assert!(screen.confirm_open); + assert_eq!(screen.retry, retried); + assert_eq!(screen.selected_votes.len(), 1); + assert_eq!(screen.selected_votes[0].contested_name, "unrelated"); + } + + /// `Review again` must carry the contest's deadline, or "when voting is + /// about to end" has nothing to count back from. + #[test] + fn review_again_schedules_against_the_contest_deadline() { + let (mut screen, _dir) = voting_ui_review_fixture(); + let now = Utc::now(); + let deadline = now.timestamp_millis() as u64 + 60 * 60_000; + screen + .app_context + .seed_dpns_contest_for_test("alpha", Some(deadline), false); + screen.refresh(); + let operation = AppContext::new_dpns_vote_operation(vec![ + screen + .build_review_plan_at(now) + .unwrap() + .aggregate + .targets + .remove(0), + ]); + + screen.review_failed_target(&operation.targets[0]); + screen.confirm_timing = ConfirmTiming::BeforeEnd; + screen.relative_preset = std::time::Duration::from_secs(10 * 60); + let plan = screen.build_review_plan_at(now).unwrap(); + + assert_eq!(plan.decisions[0].0.end_time, Some(deadline)); + assert_eq!( + plan.aggregate.targets[0].timing, + VoteTiming::Scheduled(deadline - 10 * 60_000) + ); + } + + #[test] + fn voting_ui_review_warns_before_using_a_limited_change() { + use egui_kittest::kittest::Queryable; + let (mut screen, _temp_dir) = voting_ui_review_fixture(); + let mut harness = egui_kittest::Harness::builder().build_ui(move |ui| { + screen.show_confirm_step(ui); + }); + harness.run(); + assert!( + harness + .query_by_label( + "1 of these changes an earlier vote. Each node can change its vote 4 times per name." + ) + .is_some() + ); + } + + #[test] + fn voting_ui_no_op_review_does_not_warn_that_a_change_will_be_used() { + use egui_kittest::kittest::Queryable; + let (mut screen, _dir) = voting_ui_review_fixture(); + screen.selected_votes[0].vote_choice = ResourceVoteChoice::Lock; + assert_eq!(screen.build_review_plan().unwrap().effective_count(), 0); + let mut harness = egui_kittest::Harness::builder().build_ui(move |ui| { + screen.show_confirm_step(ui); + }); + harness.run(); + assert!( + harness + .query_by_label( + "1 of these changes an earlier vote. Each node can change its vote 4 times per name." + ) + .is_none() + ); + } + + /// VOTE-TC-101: the drawer names each node and its typed status, and + /// offers only the valid action. + #[test] + fn progress_drawer_identifies_each_node_and_status() { + use egui_kittest::kittest::Queryable; + let (screen, _temp_dir) = voting_ui_review_fixture(); + let plan = screen.build_review_plan().unwrap(); + let mut first = plan.aggregate.targets[0].clone(); + first.voter_alias = Some("node-one".to_owned()); + let mut second = first.clone(); + second.key.voter_id = Identifier::from([2; 32]); + second.voter_alias = None; + let mut third = first.clone(); + third.key.voter_id = Identifier::from([3; 32]); + third.voter_alias = Some("node-three".to_owned()); + let mut operation = AppContext::new_dpns_vote_operation(vec![first, second, third]); + operation.targets[0].status = DpnsVoteTargetStatus::Confirmed; + operation.targets[1].status = DpnsVoteTargetStatus::Rejected; + operation.targets[2].status = DpnsVoteTargetStatus::Unconfirmed; + let context = screen.app_context.clone(); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + context.recompute_dpns_vote_attention(); + let mut state = progress_drawer::DrawerState::new(0); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1000.0, 800.0)) + .build_ui(move |ui| { + progress_drawer::expand(ui.ctx()); + progress_drawer::show(ui.ctx(), &context, &mut state); + }); + harness.run(); + for label in [ + "Casting 3 votes · 2 done · 0 sending · 1 being checked", + "node-one · alpha.dash · Abstain", + "Confirmed", + "02020…202 · alpha.dash · Abstain", + "Rejected", + "Review again", + "Still being checked. Do not submit it again.", + "Check again", + ] { + assert!(harness.query_by_label(label).is_some(), "missing {label}"); + } + } + + #[test] + fn voting_ui_network_switch_discards_staged_choices() { + let (mut screen, _temp_dir) = voting_ui_review_fixture(); + screen.confirm_open = true; + screen.pending_scheduled_actions.insert( + pending_scheduled_key(&screen.app_context), + BackendTaskContext::Unknown, + ); + let new_dir = tempfile::tempdir().unwrap(); + let new_context = crate::context::test_support::test_app_context_for_network( + new_dir.path(), + Network::Regtest, + ); + assert_ne!(screen.app_context.network(), new_context.network()); + // What `MasternodesScreen::reset_for_network_change` does for its panel. + screen.app_context = new_context; + screen.reset_for_network_switch(); + screen.refresh_on_arrival(); + assert!(screen.selected_votes.is_empty()); + assert!(!screen.confirm_open); + assert!(screen.pending_scheduled_actions.is_empty()); + } + + #[test] + fn voting_ui_sweep_completion_refreshes_the_scheduled_row() { + let (mut screen, _temp_dir) = voting_ui_review_fixture(); + screen.view = VotesView::Scheduled; + let mut target = screen + .build_review_plan() + .unwrap() + .aggregate + .targets + .remove(0); + target.timing = VoteTiming::Scheduled(42); + let mut operation = AppContext::new_dpns_vote_operation(vec![target]); + operation.targets[0].status = DpnsVoteTargetStatus::Queued; + screen + .app_context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + screen.refresh(); + assert_eq!( + screen.scheduled_votes.lock_recover()[0].status, + DpnsVoteTargetStatus::Queued + ); + operation.targets[0].status = DpnsVoteTargetStatus::Confirmed; + screen + .app_context + .update_dpns_vote_operation(&operation) + .unwrap(); + screen.display_task_result(BackendTaskSuccessResult::ScheduledVoteSweepCompleted { + network: screen.app_context.network(), + preserve_eligibility_since_ms: None, + }); + assert_eq!( + screen.scheduled_votes.lock_recover()[0].status, + DpnsVoteTargetStatus::Confirmed + ); } - fn display_task_error(&mut self, error: &TaskError) -> bool { - let handled = scheduled_vote_sweep_is_quiet(error); - if matches!( - error, - TaskError::ScheduledVoteRejected { .. } - | TaskError::ScheduledVoteAllAddressesExhausted { .. } - | TaskError::ScheduledVoteResultUnavailable - | TaskError::ScheduledVoteSweepFailed { .. } - | TaskError::ScheduledVoteSweepAllAddressesExhausted { .. } - ) { - self.scheduled_vote_cast_in_progress = false; - if let Ok(mut guard) = self.scheduled_votes.lock() { - for vote in guard.iter_mut() { - if vote.1 == ScheduledVoteCastingStatus::InProgress { - vote.1 = ScheduledVoteCastingStatus::Failed; - } - } - } - } - handled + /// Stage `Lock` on the review fixture's `alpha` contest and give the + /// contest a card, so the tray has nodes to count. Returns the voter and + /// the poll. + fn stage_lock_on_alpha_card(screen: &mut DPNSScreen) -> (Identifier, Identifier) { + let voter = screen.voting_identities[0].identity.id(); + let poll = screen.app_context.dpns_vote_poll_id("alpha").unwrap(); + screen.selected_votes[0].vote_choice = ResourceVoteChoice::Lock; + screen.active_contests = ActiveDpnsContestSnapshot::new( + &screen.app_context, + vec![ContestedName { + normalized_contested_name: "alpha".into(), + contestants: None, + locked_votes: Some(1), + abstain_votes: Some(0), + awarded_to: None, + end_time: None, + state: ContestState::Ongoing, + last_updated: None, + my_votes: BTreeMap::new(), + }], + ); + screen.rebuild_cards(); + (voter, poll) } - fn display_task_result(&mut self, backend_task_success_result: BackendTaskSuccessResult) { - match backend_task_success_result { - // If immediate cast finished, see if we have pending to schedule next - BackendTaskSuccessResult::DPNSVoteResults(results) => { - let errors: Vec = results - .iter() - .filter_map(|(_, _, r)| r.as_ref().err().map(|e| e.to_string())) - .collect(); - let successes: Vec = results - .iter() - .filter_map(|(name, _, r)| r.as_ref().ok().map(|_| name.clone())) - .collect(); - - if !errors.is_empty() { - let errors_string = errors.join("\n\n"); - if !successes.is_empty() { - // partial success - self.bulk_schedule_message = Some(( - MessageType::Error, - format!( - "Successes: {}/{}\n\nErrors:\n\n{:?}", - successes.len(), - successes.len() + errors.len(), - errors_string - ), - )); - } else { - // all failed - self.bulk_schedule_message = - Some((MessageType::Error, format!("Errors:\n\n{}", errors_string))); - } - } else { - // no errors => all success - self.bulk_schedule_message = Some(( - MessageType::Success, - "Votes all cast successfully.".to_string(), - )); - } - - self.vote_banner.take_and_clear(); - self.bulk_vote_handling_status = VoteHandlingStatus::Completed; - } - // If scheduling succeeded - BackendTaskSuccessResult::ScheduledVotes => { - if self.bulk_vote_handling_status == VoteHandlingStatus::SchedulingVotes { - self.vote_banner.take_and_clear(); - self.bulk_vote_handling_status = VoteHandlingStatus::Completed; - } - self.bulk_schedule_message = - Some((MessageType::Success, "Votes scheduled".to_string())); - } - BackendTaskSuccessResult::ScheduledVotesInProgress(votes) => { - // The periodic sweep is about to cast these votes; reflect that - // in the list so the user sees them move before results land. - self.scheduled_vote_cast_in_progress = true; - if let Ok(mut guard) = self.scheduled_votes.lock() { - for vote in &votes { - if let Some((_, status)) = guard.iter_mut().find(|(v, _)| { - v.contested_name == vote.contested_name && v.voter_id == vote.voter_id - }) { - *status = ScheduledVoteCastingStatus::InProgress; - } - } - } - } - BackendTaskSuccessResult::CastScheduledVote(vote) => { - self.scheduled_vote_cast_in_progress = false; - if let Ok(mut guard) = self.scheduled_votes.lock() - && let Some((_, status)) = guard.iter_mut().find(|(v, _)| { - v.contested_name == vote.contested_name && v.voter_id == vote.voter_id - }) - { - *status = ScheduledVoteCastingStatus::Completed; - } - } - BackendTaskSuccessResult::RefreshedDpnsContests - | BackendTaskSuccessResult::RefreshedOwnedDpnsNames => { - self.refresh_banner.take_and_clear(); - self.refreshing_status = RefreshingStatus::NotRefreshing; - } - _ => {} - } + /// Replace the node's proof of `Lock` with one four minutes old: still + /// shown on the card, too old to decide that nothing needs sending. + fn age_lock_proof(screen: &mut DPNSScreen, voter: Identifier, poll: Identifier) { + let four_minutes_ago = now_ms() - 4 * 60_000; + screen + .app_context + .seed_proved_dpns_votes_at_for_test( + voter, + BTreeMap::from([(poll.to_buffer(), ResourceVoteChoice::Lock)]), + four_minutes_ago, + ) + .unwrap(); + screen.vote_state = + DpnsVoteStateSnapshot::load(&screen.app_context, &[voter], &[poll]).unwrap(); + assert_eq!( + screen.vote_state.state(voter, poll), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)), + "the proof is still fresh enough to display" + ); + screen.rebuild_cards(); } - fn ui(&mut self, ui: &mut egui::Ui) -> AppAction { - let ctx = ui.ctx().clone(); - let ctx = &ctx; - let has_identity_that_can_register = !self.user_identities.is_empty(); - let has_active_contests = { - let guard = self.contested_names.lock_recover(); - !guard.is_empty() - }; + /// The cards may show proof far older than a submission may rest on. A + /// node shown on the requested choice by such proof must still be sent to + /// the backend's fresh check instead of being skipped as already voted — + /// and the operator must read it as a vote to check again, not as a first + /// vote or a transaction. + #[test] + fn a_vote_matching_only_stale_proof_is_sent_for_a_fresh_check() { + use egui_kittest::kittest::Queryable; + let (mut screen, _dir) = voting_ui_review_fixture(); + let (voter, poll) = stage_lock_on_alpha_card(&mut screen); + assert_eq!( + screen.build_review_plan().unwrap().effective_count(), + 0, + "control: fresh proof of the same choice is an exact no-op" + ); + assert_eq!( + screen.tray_counts(), + TrayCounts::default(), + "control: the tray offers nothing for a vote proved in place just now" + ); - // Build top-right buttons - let mut right_buttons = match self.dpns_subscreen { - DPNSSubscreen::Active => { - let refresh_button = ( - "Refresh", - DesiredAppAction::BackendTask(Box::new(BackendTask::ContestedResourceTask( - ContestedResourceTask::QueryDPNSContests, - ))), - ); - if has_active_contests { - vec![ - refresh_button, - ( - "Cast/Schedule Votes", - DesiredAppAction::Custom("Vote".to_string()), - ), - ] - } else { - vec![refresh_button] - } - } - DPNSSubscreen::Past => { - let refresh_button = ( - "Refresh", - DesiredAppAction::BackendTask(Box::new(BackendTask::ContestedResourceTask( - ContestedResourceTask::QueryDPNSContests, - ))), - ); - vec![refresh_button] - } - DPNSSubscreen::Owned => { - let refresh_button = ( - "Refresh", - DesiredAppAction::BackendTask(Box::new(BackendTask::IdentityTask( - IdentityTask::RefreshLoadedIdentitiesOwnedDPNSNames, - ))), - ); - vec![refresh_button] - } - DPNSSubscreen::ScheduledVotes => { - vec![ - ( - "Clear All", - DesiredAppAction::BackendTask(Box::new( - BackendTask::ContestedResourceTask( - ContestedResourceTask::ClearAllScheduledVotes, - ), - )), - ), - ( - "Clear Casted", - DesiredAppAction::BackendTask(Box::new( - BackendTask::ContestedResourceTask( - ContestedResourceTask::ClearExecutedScheduledVotes, - ), - )), - ), - ] - } - }; + age_lock_proof(&mut screen, voter, poll); - if has_identity_that_can_register && self.dpns_subscreen != DPNSSubscreen::ScheduledVotes { - // "Register Name" button on the left - right_buttons.insert( - 0, - ( - "Register Name", - DesiredAppAction::AddScreenType(Box::new(ScreenType::RegisterDpnsName( - RegisterDpnsNameSource::Dpns, - ))), - ), + let plan = screen.build_review_plan().unwrap(); + assert_eq!(plan.effective_count(), 1); + assert!(plan.aggregate.skipped.is_empty()); + assert_eq!(plan.aggregate.targets[0].current_choice, None); + + assert_eq!( + plan.transaction_count(), + 0, + "a vote that is only checked again is not a promised transaction" + ); + assert_eq!(plan.recheck_count(), 1); + assert_eq!( + screen.review_choice_line(&plan, &plan.aggregate.targets[0]), + "Current choice: Lock name, as requested. It will be checked again before a vote is sent.", + "the row must show the choice the card shows, not a node that never voted" + ); + assert_eq!( + screen.tray_counts(), + TrayCounts { + transactions: 0, + rechecks: 1, + }, + "the tray keeps the vote submittable without counting a transaction" + ); + + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1000.0, 800.0)) + .build_ui(move |ui| { + screen.show_confirm_step(ui); + }); + harness.run(); + for label in [ + "1 vote is already shown as cast. Dash Evo Tool checks it again first and sends nothing if the node still holds this choice.", + "Check 1 vote", + ] { + assert!( + harness.query_by_label(label).is_some(), + "Missing confirm detail: {label}" ); } + assert!( + harness.query_by_label_contains("transaction").is_none(), + "a batch that sends nothing must not show a transaction sentence" + ); + for label in ["Cast 1 vote", "Cast 0 votes"] { + assert!( + harness.query_by_label(label).is_none(), + "the confirm step must not promise a transaction: {label}" + ); + } + } - // TODO: wire wallet/identity selection consumption for the DPNS page. - let mut action = add_top_panel_with_global_nav( - ui, - &self.app_context, - subdued_everyday_spec("DPNS", RootScreenType::RootScreenDPNSActiveContests), - right_buttons, + /// A node with no changes left is not offered by the tray. The confirm + /// step, which Enter opens regardless of the tray, must agree: stale proof + /// of the staged choice does not turn that node into a vote to check. + #[test] + fn a_node_with_no_changes_left_is_neither_a_vote_nor_a_check() { + let (mut screen, _dir) = voting_ui_review_fixture(); + let (voter, poll) = stage_lock_on_alpha_card(&mut screen); + age_lock_proof(&mut screen, voter, poll); + assert_eq!( + screen.tray_counts(), + TrayCounts { + transactions: 0, + rechecks: 1, + }, + "control: with changes left the node is offered as a check" ); - // If user clicked "Apply Votes" in the top bar - if action == AppAction::Custom("Vote".to_string()) { - // That means the user clicked "Apply Votes" - self.show_bulk_schedule_popup = true; - action = AppAction::None; // clear it out so we don't re-trigger - } + let node = &mut screen.cards[0].nodes[0]; + node.changes = ChangesLeft::Known(0); + node.status = NodeContestStatus::classify( + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)), + None, + node.changes, + ); + assert_eq!( + node.status, + NodeContestStatus::NoChangesLeft(ResourceVoteChoice::Lock) + ); - // Left panel - action |= add_left_panel( - ui, - &self.app_context, - RootScreenType::RootScreenToolsPlatformInfoScreen, - ); - - // Tools area chooser - action |= add_tools_subscreen_chooser_panel(ui, self.app_context.as_ref()); - - // DPNS subscreen chooser - action |= add_dpns_subscreen_chooser_panel(ui, self.app_context.as_ref()); - - // Main panel - action |= island_central_panel(ui, |ui| { - let mut inner_action = AppAction::None; - // Bulk-schedule ephemeral popup - if self.show_bulk_schedule_popup { - egui::Window::new("Voting") - .collapsible(false) - .resizable(true) - .vscroll(true) - .show(ui.ctx(), |ui| { - inner_action |= self.show_bulk_schedule_popup_window(ui); - }); - } + assert_eq!(screen.tray_counts(), TrayCounts::default()); + let plan = screen.build_review_plan().unwrap(); + assert_eq!(plan.effective_count(), 0); + assert_eq!(plan.recheck_count(), 0); + assert_eq!( + plan.aggregate.skipped_by_reason(), + BTreeMap::from([(SkipReason::NoChangesLeft, 1)]) + ); + } - // Render sub-screen - match self.dpns_subscreen { - DPNSSubscreen::Active => { - let has_any = { - let guard = self.contested_names.lock_recover(); - !guard.is_empty() - }; - if has_any { - self.render_table_active_contests(ui); - } else { - inner_action |= self.render_no_active_contests_or_owned_names(ui); - } - } - DPNSSubscreen::Past => { - let has_any = { - let guard = self.contested_names.lock_recover(); - !guard.is_empty() - }; - if has_any { - self.render_table_past_contests(ui); - } else { - inner_action |= self.render_no_active_contests_or_owned_names(ui); - } - } - DPNSSubscreen::Owned => { - let has_any = { - let guard = self.local_dpns_names.lock_recover(); - !guard.is_empty() - }; - if has_any { - self.render_table_local_dpns_names(ui); - } else { - inner_action |= self.render_no_active_contests_or_owned_names(ui); - } - } - DPNSSubscreen::ScheduledVotes => { - let has_any = { - let guard = self.scheduled_votes.lock_recover(); - !guard.is_empty() - }; - if has_any { - inner_action |= self.render_table_scheduled_votes(ui); - } else { - inner_action |= self.render_no_active_contests_or_owned_names(ui); - } - } - } + /// A node set to "when voting is about to end" must use the lead time the + /// confirm step shows, and be labelled with it, after the lead time changes. + #[test] + fn a_node_set_to_before_the_end_follows_a_changed_lead_time() { + let (mut screen, _dir) = voting_ui_review_fixture(); + let voter = screen.voting_identities[0].identity.id(); + let now = Utc::now(); + let end = now.timestamp_millis() as u64 + 24 * 3_600_000; + screen.selected_votes[0].end_time = Some(end); + screen.confirm_timing = ConfirmTiming::Now; + screen.node_overrides.insert( + voter, + NodeTiming::Override(BatchTiming::BeforeEnd(screen.relative_preset)), + ); - // Refreshing indicator is shown via the global banner - // (no inline elapsed rendering needed) - inner_action - }); + let lead = std::time::Duration::from_secs(90 * 60); + assert_ne!(screen.relative_preset, lead); + screen.set_relative_preset(lead); - // Extra handling for actions - match action { - // If refreshing contested names, set self.refreshing = true - AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::QueryDPNSContests, - )) => { - self.refresh_banner.take_and_clear(); - let handle = MessageBanner::set_global( - ctx, - "Refreshing contested names...", - MessageType::Info, - ); - handle.with_elapsed(); - self.refresh_banner = Some(handle); - self.refreshing_status = RefreshingStatus::Refreshing; - } - // If refreshing owned names, set self.refreshing = true - AppAction::BackendTask(BackendTask::IdentityTask( - IdentityTask::RefreshLoadedIdentitiesOwnedDPNSNames, - )) => { - self.refresh_banner.take_and_clear(); - let handle = MessageBanner::set_global( - ctx, - "Refreshing contested names...", - MessageType::Info, - ); - handle.with_elapsed(); - self.refresh_banner = Some(handle); - self.refreshing_status = RefreshingStatus::Refreshing; - } - AppAction::SetMainScreen(_) => { - self.refresh_banner.take_and_clear(); - self.refreshing_status = RefreshingStatus::NotRefreshing; - } - _ => {} - } + assert_eq!( + screen.node_overrides.get(&voter), + Some(&NodeTiming::Override(BatchTiming::BeforeEnd(lead))) + ); + let plan = screen.build_review_plan_at(now).unwrap(); + assert_eq!( + plan.aggregate.targets[0].timing, + VoteTiming::Scheduled(end - 90 * 60_000) + ); + let operation = AppContext::new_dpns_vote_operation(plan.aggregate.targets); + let labels = screen + .relative_schedule_labels_for(&operation) + .expect("the node placed before the end is labelled relative to the end"); + assert_eq!(labels.preset, lead); + assert_eq!( + labels.targets, + BTreeSet::from([operation.targets[0].target.key.clone()]) + ); - // If we have a pending backend task from scheduling (e.g. after immediate votes) - if action == AppAction::None - && let Some(bt) = self.pending_backend_task.take() - { - action = AppAction::BackendTask(bt); - } - action + screen + .node_overrides + .insert(voter, NodeTiming::Override(BatchTiming::Now)); + screen.confirm_timing = ConfirmTiming::BeforeEnd; + assert_eq!( + screen.relative_schedule_labels_for(&operation), + None, + "a node told to vote now is not labelled relative to the end" + ); } -} -#[cfg(test)] -mod tests { - use super::*; - use crate::context::connection_status::ConnectionStatus; - use crate::database::test_helpers::create_database_at_path; - use crate::model::user_role::UserRoleCell; - use crate::utils::tasks::TaskManager; - use dash_sdk::dpp::dashcore::Network; + /// The confirm step must expand every node × contest pair, suppress the + /// targets that already hold the requested choice, and count what it dropped. + #[tokio::test] + async fn review_plan_expands_every_node_and_contest_and_suppresses_no_ops() { + let (ctx, _temp_dir) = kv_ctx(); + let alpha = ctx.dpns_vote_poll_id("alpha").expect("alpha poll id"); + let beta = ctx.dpns_vote_poll_id("beta").expect("beta poll id"); + let first = masternode_identity(1, "node-one", true, ctx.network()); + let second = masternode_identity(2, "node-two", true, ctx.network()); + ctx.seed_proved_dpns_votes_for_test( + first.identity.id(), + std::collections::BTreeMap::from([(alpha.to_buffer(), ResourceVoteChoice::Lock)]), + ) + .await + .expect("seed first node's complete proved votes"); + ctx.seed_proved_dpns_votes_for_test( + second.identity.id(), + std::collections::BTreeMap::from([(beta.to_buffer(), ResourceVoteChoice::Abstain)]), + ) + .await + .expect("seed second node's complete proved votes"); - fn offline_ctx() -> (Arc, tempfile::TempDir) { - let temp_dir = tempfile::tempdir().expect("tempdir"); - let data_dir = temp_dir.path().to_path_buf(); - crate::app_dir::ensure_env_file(&data_dir); - let db = Arc::new(create_database_at_path(&data_dir.join("data.db")).expect("db")); - let app_kv = AppContext::open_app_kv(&data_dir).expect("app kv"); - let secret_store = AppContext::open_secret_store(&data_dir).expect("secret store"); - let ctx = AppContext::new( - data_dir, - Network::Regtest, - db, - Arc::new(TaskManager::new()), - Arc::new(ConnectionStatus::new()), - egui::Context::default(), - app_kv, - secret_store, - UserRoleCell::default(), + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); + screen.voting_identities = vec![first.clone(), second.clone()]; + screen.rebuild_cards(); + screen.relative_preset = std::time::Duration::from_secs(10 * 60); + screen.node_overrides.insert( + second.identity.id(), + NodeTiming::Override(BatchTiming::BeforeEnd(screen.relative_preset)), + ); + let end = now_ms() + 24 * 3_600_000; + screen.selected_votes = vec![ + SelectedVote { + contested_name: "alpha".to_owned(), + vote_choice: ResourceVoteChoice::Lock, + end_time: Some(end), + }, + SelectedVote { + contested_name: "beta".to_owned(), + vote_choice: ResourceVoteChoice::Abstain, + end_time: Some(end), + }, + ]; + screen.vote_state = DpnsVoteStateSnapshot::load( + &ctx, + &[first.identity.id(), second.identity.id()], + &[alpha, beta], ) - .expect("offline regtest AppContext::new"); - (ctx, temp_dir) - } + .expect("load proved vote state"); - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn owned_names_keep_node_alias_action_without_user_aliases() { - use crate::model::qualified_identity::{IdentityStatus, IdentityType}; - use dash_sdk::dpp::{identity::Identity, version::PlatformVersion}; - use egui_kittest::{Harness, kittest::Queryable}; - let (ctx, _dir) = offline_ctx(); - let (sender, _receiver) = tokio::sync::mpsc::channel(32); - ctx.ensure_wallet_backend(crate::utils::egui_mpsc::SenderAsync::new( - sender, - ctx.egui_ctx().clone(), - )) - .await - .unwrap(); - for (byte, identity_type) in [ - (1, IdentityType::User), - (2, IdentityType::Masternode), - (3, IdentityType::Evonode), - ] { - let identity = QualifiedIdentity { - identity: Identity::create_basic_identity( - Identifier::from([byte; 32]), - PlatformVersion::latest(), + let plan = screen.build_review_plan().expect("review plan"); + + assert_eq!(plan.effective_count(), 2); + assert_eq!( + plan.aggregate.skipped_by_reason(), + BTreeMap::from([(SkipReason::AlreadyVoted, 2)]), + "two nodes across two contests, two already as requested" + ); + assert_eq!(plan.node_count(), 2); + assert!(plan.has_scheduled()); + let retained = plan + .targets() + .iter() + .map(|target| { + ( + target.voter_alias.clone(), + target.contested_name.clone(), + target.timing, ) - .unwrap(), - associated_voter_identity: None, - associated_operator_identity: None, - associated_owner_key_id: None, - identity_type, - alias: Some("Original".into()), - private_keys: Default::default(), - dpns_names: vec![DPNSNameInfo { - name: format!("name{byte}"), - acquired_at: 0, - }], - associated_wallets: Default::default(), - secret_access: None, - wallet_index: None, - top_ups: Default::default(), - status: IdentityStatus::Active, - network: Network::Regtest, - }; - ctx.insert_local_qualified_identity(&identity, &None) - .unwrap(); - } - let mut harness = Harness::builder() - .with_size(egui::vec2(1000.0, 500.0)) - .build_ui_state( - |ui, screen: &mut DPNSScreen| screen.render_table_local_dpns_names(ui), - DPNSScreen::new(&ctx, DPNSSubscreen::Owned), - ); - harness.run(); + }) + .collect::>(); assert_eq!( - harness.query_all_by_label("Set node name").count(), - 2, - "only Masternode and Evonode rows offer local naming" + retained, + vec![ + ( + Some("node-two".to_owned()), + "alpha".to_owned(), + VoteTiming::Scheduled(end - 10 * 60_000) + ), + ( + Some("node-one".to_owned()), + "beta".to_owned(), + VoteTiming::Now + ), + ] ); - for index in 0..2 { - harness - .query_all_by_label("Set node name") - .nth(index) - .unwrap() - .click(); - harness.run(); - } - for byte in [2, 3] { - assert_eq!( - ctx.get_identity_alias(&Identifier::from([byte; 32])) - .unwrap(), - Some(format!("name{byte}.dash")) - ); - } + assert_eq!(plan.decisions.len(), 2); + assert!(plan.decisions.iter().all(|(_, nodes)| *nodes == 1)); + } + + /// A review whose every target is a no-op must submit nothing. + #[test] + fn review_plan_reports_an_all_no_op_selection_as_nothing_to_submit() { + let (ctx, _temp_dir) = kv_ctx(); + let alpha = ctx.dpns_vote_poll_id("alpha").expect("alpha poll id"); + let node = masternode_identity(3, "node-three", true, ctx.network()); + ctx.cache_confirmed_dpns_vote(node.identity.id(), alpha, ResourceVoteChoice::Lock) + .expect("seed proved vote"); + + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); + screen.voting_identities = vec![node.clone()]; + screen.rebuild_cards(); + screen.selected_votes = vec![SelectedVote { + contested_name: "alpha".to_owned(), + vote_choice: ResourceVoteChoice::Lock, + end_time: None, + }]; + screen.vote_state = DpnsVoteStateSnapshot::load(&ctx, &[node.identity.id()], &[alpha]) + .expect("load proved vote state"); + + let plan = screen.build_review_plan().expect("review plan"); + + assert_eq!(plan.effective_count(), 0); assert_eq!( - ctx.get_identity_alias(&Identifier::from([1; 32])) - .unwrap() - .as_deref(), - Some("Original") + plan.aggregate.skipped_by_reason(), + BTreeMap::from([(SkipReason::AlreadyVoted, 1)]) ); + assert_eq!(plan.node_count(), 0); } + /// A node that already voted differently keeps its proved choice on the + /// review line, so the operator sees what the vote replaces. #[test] - fn scheduled_vote_sweep_error_is_handled_after_cleanup() { - let (ctx, _temp_dir) = offline_ctx(); - let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::ScheduledVotes); - let error = TaskError::ScheduledVoteSweepFailed { - network: Network::Regtest, - source: Box::new(TaskError::NoVotingIdentity { - identity_id: "voter-id".to_string(), - }), - }; + fn review_plan_carries_the_proved_choice_a_target_replaces() { + let (ctx, _temp_dir) = kv_ctx(); + let alpha = ctx.dpns_vote_poll_id("alpha").expect("alpha poll id"); + let node = masternode_identity(4, "node-four", true, ctx.network()); + ctx.cache_confirmed_dpns_vote(node.identity.id(), alpha, ResourceVoteChoice::Lock) + .expect("seed proved vote"); - screen.scheduled_vote_cast_in_progress = true; - assert!(screen.display_task_error(&error)); - assert!(!screen.scheduled_vote_cast_in_progress); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); + screen.voting_identities = vec![node.clone()]; + screen.rebuild_cards(); + screen.selected_votes = vec![SelectedVote { + contested_name: "alpha".to_owned(), + vote_choice: ResourceVoteChoice::Abstain, + end_time: None, + }]; + screen.vote_state = DpnsVoteStateSnapshot::load(&ctx, &[node.identity.id()], &[alpha]) + .expect("load proved vote state"); + + let plan = screen.build_review_plan().expect("review plan"); + + assert_eq!(plan.effective_count(), 1); + assert_eq!( + plan.targets().first().map(|target| target.current_choice), + Some(Some(ResourceVoteChoice::Lock)) + ); + assert_eq!( + review_current_choice_label(Some(ResourceVoteChoice::Lock), None), + "Lock name" + ); } + /// The composer words its own refusals; the confirm step and the + /// submission banner show them unchanged. #[test] - fn direct_scheduled_vote_error_remains_available_to_global_handling() { - let (ctx, _temp_dir) = offline_ctx(); - let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::ScheduledVotes); + fn composer_refusals_reach_the_operator_word_for_word() { + let ended = ComposeError::VotingEnded { + contested_name: "alpha".to_owned(), + }; + let outlasts = ComposeError::ScheduleOutlastsContest { + contested_name: "alpha".to_owned(), + }; + assert_eq!( + VoteSubmissionError::from(ReviewPlanError::from(ended)).to_string(), + "Voting has ended for alpha.dash. Clear it from your decisions." + ); + assert_eq!( + VoteSubmissionError::from(ReviewPlanError::from(outlasts)).to_string(), + "Choose a future time before the contest ends for alpha.dash." + ); + } - screen.scheduled_vote_cast_in_progress = true; - assert!(!screen.display_task_error(&TaskError::ScheduledVoteResultUnavailable)); - assert!(!screen.scheduled_vote_cast_in_progress); + #[test] + fn review_labels_previous_choices() { + assert_eq!( + review_current_choice_label(Some(ResourceVoteChoice::Abstain), None), + "Abstain" + ); + assert_eq!(review_current_choice_label(None, None), "Not voted yet"); + } - let sweep_error = TaskError::ScheduledVoteSweepFailed { - network: Network::Regtest, - source: Box::new(TaskError::ScheduledVoteResultUnavailable), + /// Removing a scheduled vote must clear its row. The journal cancellation is + /// durable, so the row cannot come back with a Remove button that does nothing. + #[test] + fn removing_a_scheduled_vote_drops_its_row_from_the_table() { + let (ctx, _temp_dir) = kv_ctx(); + let voter_id = Identifier::from([23; 32]); + let key = DpnsVoteTargetKey { + network: ctx.network(), + voter_id, + vote_poll_id: Identifier::from([24; 32]), }; - assert!(!screen.display_task_error(&sweep_error)); + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: key.clone(), + voter_alias: None, + contested_name: "remove-me".to_owned(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Scheduled(42), + }]); + ctx.insert_dpns_vote_operation(&mut operation, None) + .expect("insert scheduled operation"); + let mut screen = DPNSScreen::new(&ctx, VotesView::Scheduled); + assert_eq!(screen.scheduled_votes.lock_recover().len(), 1); - screen.scheduled_vote_cast_in_progress = true; - let exhausted_error = TaskError::ScheduledVoteSweepAllAddressesExhausted { - network: Network::Regtest, - source: Box::new(TaskError::DapiNoAddresses { - source_error: Box::new(dash_sdk::Error::DapiClientError( - dash_sdk::dapi_client::DapiClientError::NoAvailableAddresses, - )), - }), + ctx.cancel_scheduled_dpns_vote_target(operation.id, &key) + .expect("remove the scheduled vote"); + screen.display_task_result(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: ctx.network(), + operation_id: operation.id, + }); + + assert!( + screen.scheduled_votes.lock_recover().is_empty(), + "a removed schedule must not return to the table" + ); + } + + /// VOTE-TC-067: a "before the end" schedule shows its preset next to the + /// absolute UTC time; without a stored label only the absolute time shows. + #[test] + fn relative_schedule_shows_its_preset_and_absolute_time() { + use egui_kittest::kittest::Queryable; + let (ctx, _temp_dir) = kv_ctx(); + let voter_id = Identifier::from([25; 32]); + let key = DpnsVoteTargetKey { + network: ctx.network(), + voter_id, + vote_poll_id: Identifier::from([26; 32]), }; - assert!(!screen.display_task_error(&exhausted_error)); - assert!(!screen.scheduled_vote_cast_in_progress); + let at = 1_900_000_000_000; + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: key.clone(), + voter_alias: None, + contested_name: "later".to_owned(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Scheduled(at), + }]); + operation.targets[0].relative_schedule_preset_ms = Some(6 * 3600 * 1000); + ctx.insert_dpns_vote_operation(&mut operation, None) + .expect("insert scheduled operation"); + let mut screen = DPNSScreen::new(&ctx, VotesView::Scheduled); + let expected = + relative_schedule_label(std::time::Duration::from_secs(6 * 3600), &utc_minute(at)); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1400.0, 800.0)) + .build_ui(move |ui| { + screen.ui(ui); + }); + harness.run(); + assert!( + harness.query_by_label(&expected).is_some(), + "missing {expected}" + ); + } + + #[test] + fn clear_all_result_rebuilds_scheduled_rows_immediately() { + let (ctx, _temp_dir) = kv_ctx(); + let voter_id = Identifier::from([21; 32]); + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: ctx.network(), + voter_id, + vote_poll_id: Identifier::from([22; 32]), + }, + voter_alias: None, + contested_name: "clear-me".to_owned(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Scheduled(42), + }]); + ctx.insert_dpns_vote_operation(&mut operation, None) + .expect("insert scheduled operation"); + let mut screen = DPNSScreen::new(&ctx, VotesView::Scheduled); + assert_eq!(screen.scheduled_votes.lock_recover().len(), 1); + + let outcomes = ctx + .clear_all_scheduled_dpns_votes() + .expect("clear scheduled votes"); + screen.display_task_result(BackendTaskSuccessResult::ScheduledVotesCleared(outcomes)); + + assert!(screen.scheduled_votes.lock_recover().is_empty()); } } diff --git a/src/ui/dpns/dpns_contested_names_screen/scheduled_vote_editor.rs b/src/ui/dpns/dpns_contested_names_screen/scheduled_vote_editor.rs new file mode 100644 index 000000000..ca7ad197c --- /dev/null +++ b/src/ui/dpns/dpns_contested_names_screen/scheduled_vote_editor.rs @@ -0,0 +1,268 @@ +//! Editing a schedule keeps its original target and submits an optimistic update. + +use super::*; +use crate::model::dpns_voting::DpnsScheduledVoteEdit; +use crate::ui::components::modal_chrome::{ModalChromeConfig, modal_chrome}; + +pub(super) struct ScheduledVoteEditor { + original: ScheduledDpnsVoteRow, + key: DpnsVoteTargetKey, + node_label: String, + choices: Vec<(ResourceVoteChoice, String)>, + choice: ResourceVoteChoice, + /// The contest's voting deadline, when the contest list has read it. + end_time: Option, + schedule: UtcScheduleInput, + time_changed: bool, +} + +pub(super) enum EditOutcome { + KeepOpen, + Cancel, + Save(ContestedResourceTask), +} + +impl ScheduledVoteEditor { + pub(super) fn new( + original: ScheduledDpnsVoteRow, + key: DpnsVoteTargetKey, + node_label: String, + choices: Vec<(ResourceVoteChoice, String)>, + end_time: Option, + ) -> Option { + let timestamp = i64::try_from(original.vote.unix_timestamp).ok()?; + let time = DateTime::from_timestamp_millis(timestamp)?; + Some(Self { + choice: original.vote.choice, + original, + key, + node_label, + choices, + end_time, + schedule: UtcScheduleInput::new().with_time(time), + time_changed: false, + }) + } + + pub(super) fn scheduled_key(&self) -> DpnsScheduledVoteKey { + DpnsScheduledVoteKey { + network: self.key.network, + voter_id: self.key.voter_id, + contested_name: self.original.vote.contested_name.clone(), + } + } + + fn task(&self, now_ms: u64) -> Option { + if self.original.status != DpnsVoteTargetStatus::Scheduled { + return None; + } + // A choice-only edit must preserve seconds/milliseconds in an imported schedule. + let timestamp = if self.time_changed { + self.schedule.current_value()? + } else { + self.original.vote.unix_timestamp + }; + // Instant feedback only: the backend re-reads the contest and enforces + // the full edit rules, including the choice, before it stores anything. + validate_dpns_schedule_time(timestamp, now_ms, self.end_time).ok()?; + if !self + .choices + .iter() + .any(|(choice, _)| *choice == self.choice) + { + return None; + } + Some(ContestedResourceTask::EditScheduledDpnsVote( + DpnsScheduledVoteEdit { + operation_id: self.original.journal_target.0, + key: self.key.clone(), + expected_choice: self.original.vote.choice, + expected_timestamp: self.original.vote.unix_timestamp, + choice: self.choice, + unix_timestamp: timestamp, + }, + )) + } + + pub(super) fn show(&mut self, ctx: &egui::Context) -> EditOutcome { + let chrome = modal_chrome( + ctx, + ModalChromeConfig { + title: "Edit scheduled vote".into(), + overlay_id: egui::Id::new("edit_scheduled_vote"), + overlay_order: egui::Order::Middle, + window_order: egui::Order::Foreground, + resizable: false, + show_close_button: true, + blocks_input: true, + inner_margin: 16, + }, + |ui| { + ui.label(format!( + "{node} — {name}.dash", + node = self.node_label, + name = self.original.vote.contested_name, + )); + egui::ComboBox::from_id_salt("edited_vote_choice") + .selected_text( + self.choices + .iter() + .find(|(choice, _)| *choice == self.choice) + .map(|(_, label)| label.as_str()) + .unwrap_or("Choose a vote"), + ) + .show_ui(ui, |ui| { + for (choice, label) in &self.choices { + ui.selectable_value(&mut self.choice, *choice, label); + } + }); + self.time_changed |= self.schedule.show(ui).inner.has_changed(); + ui.label(KEEP_RUNNING_MESSAGE); + let task = self.task(Utc::now().timestamp_millis() as u64); + if task.is_none() { + ui.colored_label(DashColors::warning_color(ui.visuals().dark_mode), + "Choose a future date and time before voting ends. Only votes that have not started can be edited."); + } + ui.horizontal(|ui| { + if ui.button("Cancel").clicked() { + return EditOutcome::Cancel; + } + if ui + .add_enabled(task.is_some(), Button::new("Save changes")) + .clicked() + && let Some(task) = task + { + return EditOutcome::Save(task); + } + EditOutcome::KeepOpen + }) + .inner + }, + ); + if chrome.closed_via_x || ctx.input(|input| input.key_pressed(egui::Key::Escape)) { + EditOutcome::Cancel + } else { + chrome.inner.unwrap_or(EditOutcome::KeepOpen) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::backend_task::contested_names::ScheduledDPNSVote; + + #[test] + fn voting_ui_schedule_edit_preserves_target_and_compares_original_values() { + let key = DpnsVoteTargetKey { + network: dash_sdk::dpp::dashcore::Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([2; 32]), + }; + let row = ScheduledDpnsVoteRow { + failure: None, + vote: ScheduledDPNSVote { + voter_id: key.voter_id, + contested_name: "alice".into(), + choice: ResourceVoteChoice::Lock, + unix_timestamp: 1_900_000_012_345, + executed_successfully: false, + }, + journal_target: (DpnsVoteOperationId::from_bytes([3; 16]), key.clone()), + status: DpnsVoteTargetStatus::Scheduled, + }; + let mut editor = ScheduledVoteEditor::new( + row.clone(), + key.clone(), + "node-one".into(), + vec![ + (ResourceVoteChoice::Lock, "Lock".into()), + (ResourceVoteChoice::Abstain, "Abstain".into()), + ], + None, + ) + .unwrap(); + editor.choice = ResourceVoteChoice::Abstain; + let ContestedResourceTask::EditScheduledDpnsVote(DpnsScheduledVoteEdit { + operation_id, + key: edited_key, + expected_choice, + expected_timestamp, + choice, + unix_timestamp, + }) = editor.task(1).unwrap() + else { + panic!("expected edit"); + }; + assert_eq!(edited_key, key); + assert_eq!(operation_id, row.journal_target.0); + assert_eq!(expected_choice, ResourceVoteChoice::Lock); + assert_eq!(choice, ResourceVoteChoice::Abstain); + assert_eq!(expected_timestamp, row.vote.unix_timestamp); + assert_eq!(unix_timestamp, row.vote.unix_timestamp); + assert!(editor.task(unix_timestamp).is_none()); + editor.original.status = DpnsVoteTargetStatus::Queued; + assert!(editor.task(1).is_none()); + editor.original.status = DpnsVoteTargetStatus::Scheduled; + editor.time_changed = true; + editor.schedule = UtcScheduleInput::new().with_time( + chrono::NaiveDate::from_ymd_opt(2031, 2, 3) + .and_then(|date| date.and_hms_opt(4, 5, 0)) + .expect("valid test instant") + .and_utc(), + ); + let ContestedResourceTask::EditScheduledDpnsVote(DpnsScheduledVoteEdit { + unix_timestamp, + .. + }) = editor.task(1).unwrap() + else { + panic!("expected edit"); + }; + assert_eq!( + unix_timestamp, + crate::model::dpns_vote_schedule::parse_utc_schedule("2031-02-03", 4, 5).unwrap() + ); + } + + /// The backend refuses a time at or after the contest deadline, so the + /// editor must not offer to save one. + #[test] + fn a_time_at_or_after_the_contest_deadline_cannot_be_saved() { + let key = DpnsVoteTargetKey { + network: dash_sdk::dpp::dashcore::Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([2; 32]), + }; + let scheduled_at = 1_900_000_000_000; + let row = ScheduledDpnsVoteRow { + failure: None, + vote: ScheduledDPNSVote { + voter_id: key.voter_id, + contested_name: "alice".into(), + choice: ResourceVoteChoice::Lock, + unix_timestamp: scheduled_at, + executed_successfully: false, + }, + journal_target: (DpnsVoteOperationId::from_bytes([3; 16]), key.clone()), + status: DpnsVoteTargetStatus::Scheduled, + }; + let editor = |end_time| { + ScheduledVoteEditor::new( + row.clone(), + key.clone(), + "node-one".into(), + vec![(ResourceVoteChoice::Lock, "Lock".into())], + end_time, + ) + .unwrap() + }; + + assert!(editor(Some(scheduled_at + 1)).task(1).is_some()); + assert!(editor(Some(scheduled_at)).task(1).is_none()); + assert!(editor(Some(scheduled_at - 1)).task(1).is_none()); + assert!( + editor(None).task(1).is_some(), + "an unread deadline leaves the bound to the backend" + ); + } +} diff --git a/src/ui/dpns/mod.rs b/src/ui/dpns/mod.rs index 49c2ec3c5..1a9f0f7b5 100644 --- a/src/ui/dpns/mod.rs +++ b/src/ui/dpns/mod.rs @@ -1 +1,37 @@ +//! Masternode voting on contested DPNS names (Masternodes ▸ Votes). + +pub mod attention_chip; +pub mod contest_card; +pub mod copy; pub mod dpns_contested_names_screen; +pub mod node_set_picker; +pub mod progress_drawer; + +/// Sub-view of the Masternodes ▸ Votes segment. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum VotesView { + /// Open contests at least one node-set node still has to decide on. + #[default] + ToDecide, + /// Open contests every node-set node has already voted on. + Voted, + /// Scheduled and missed automatic votes. + Scheduled, + /// Finished contests with links to Platform Explorer. + History, +} + +impl VotesView { + /// Every sub-view, in chip order. + pub const ALL: [Self; 4] = [Self::ToDecide, Self::Voted, Self::Scheduled, Self::History]; + + /// The chip label. + pub fn label(self) -> &'static str { + match self { + Self::ToDecide => "To decide", + Self::Voted => "Voted", + Self::Scheduled => "Scheduled", + Self::History => "History", + } + } +} diff --git a/src/ui/dpns/node_set_picker.rs b/src/ui/dpns/node_set_picker.rs new file mode 100644 index 000000000..647916a7c --- /dev/null +++ b/src/ui/dpns/node_set_picker.rs @@ -0,0 +1,158 @@ +//! `Vote with:` node-set chip and popover (VOTE-FR-075, frame V3). + +use crate::model::dpns_voting::operator::{ + ListMembership, NodeExclusion, NodeSet, ResolvedNodeSet, VotingNode, VotingNodeKind, + node_exclusion, +}; +use crate::ui::dpns::contest_card::node_label; +use crate::ui::dpns::copy::{NOT_IN_MASTERNODE_LIST, node_set_chip_label}; +use eframe::egui::{self, RichText, Ui}; +use std::collections::{BTreeMap, BTreeSet}; + +/// Display name of a node set. +pub fn node_set_name(set: &NodeSet) -> &'static str { + match set { + NodeSet::All => "All my nodes", + NodeSet::EvonodesOnly => "Evonodes only", + NodeSet::MasternodesOnly => "Masternodes only", + NodeSet::Custom(_) => "Custom", + } +} + +/// Why a node row is disabled, or a membership note for a usable node. +pub fn node_row_note(node: &VotingNode) -> Option<&'static str> { + match node_exclusion(node) { + Some(NodeExclusion::NoVotingKey) => Some("No voting key is loaded for this node."), + Some(NodeExclusion::NotInMasternodeList) => Some(NOT_IN_MASTERNODE_LIST), + None if node.membership == ListMembership::Unknown => { + Some("Masternode list membership unknown.") + } + None => None, + } +} + +/// What the operator changed in the picker this frame. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct NodeSetPickerResponse { + /// The new set for this session, when it changed. + pub changed: Option, + /// `Save as my default` was clicked for the current set. + pub save_default: bool, +} + +/// Render the chip and, when open, its popover. +pub fn show( + ui: &mut Ui, + set: &NodeSet, + resolved: &ResolvedNodeSet, + nodes: &[VotingNode], +) -> NodeSetPickerResponse { + let mut response = NodeSetPickerResponse::default(); + let chip = ui.button(node_set_chip_label( + node_set_name(set), + resolved.included.len(), + resolved.weight, + )); + egui::Popup::from_toggle_button_response(&chip) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| { + ui.set_min_width(320.0); + ui.label(RichText::new("Vote with").strong()); + for preset in [ + NodeSet::All, + NodeSet::EvonodesOnly, + NodeSet::MasternodesOnly, + ] { + if ui.radio(*set == preset, node_set_name(&preset)).clicked() { + response.changed = Some(preset); + } + } + let custom = matches!(set, NodeSet::Custom(_)); + if ui.radio(custom, "Custom").clicked() && !custom { + response.changed = + Some(NodeSet::Custom(resolved.included.iter().copied().collect())); + } + ui.separator(); + let labels: BTreeMap<_, _> = nodes + .iter() + .filter_map(|node| node.alias.clone().map(|alias| (node.id, alias))) + .collect(); + for node in nodes { + let usable = node_exclusion(node).is_none(); + let mut checked = set.selects(node) && usable; + let kind = match node.kind { + VotingNodeKind::Evonode => "Evonode", + VotingNodeKind::Masternode => "Masternode", + }; + ui.horizontal(|ui| { + let toggled = ui + .add_enabled( + usable, + egui::Checkbox::new( + &mut checked, + format!("{label} · {kind}", label = node_label(node.id, &labels)), + ), + ) + .changed(); + if toggled { + let mut ids: BTreeSet<_> = nodes + .iter() + .filter(|other| set.selects(other) && node_exclusion(other).is_none()) + .map(|other| other.id) + .collect(); + if checked { + ids.insert(node.id); + } else { + ids.remove(&node.id); + } + response.changed = Some(NodeSet::Custom(ids)); + } + if let Some(note) = node_row_note(node) { + ui.label(RichText::new(note).small().weak()); + } + }); + } + ui.separator(); + if ui.button("Save as my default").clicked() { + response.save_default = true; + } + }); + response +} + +#[cfg(test)] +mod tests { + use super::*; + use dash_sdk::platform::Identifier; + + fn node(key: bool, membership: ListMembership) -> VotingNode { + VotingNode { + id: Identifier::from([1; 32]), + kind: VotingNodeKind::Evonode, + has_voting_key: key, + membership, + alias: None, + } + } + + /// VOTE-TC-097: disabled rows carry their reason; unknown membership + /// is a note, never an exclusion (fail open). + #[test] + fn rows_explain_exclusions_and_unknown_membership() { + assert_eq!( + node_row_note(&node(false, ListMembership::Listed)), + Some("No voting key is loaded for this node.") + ); + assert_eq!( + node_row_note(&node(true, ListMembership::NotListed)), + Some("Not in the masternode list. Its votes don't count.") + ); + let unknown = node(true, ListMembership::Unknown); + assert_eq!( + node_row_note(&unknown), + Some("Masternode list membership unknown.") + ); + assert_eq!(node_exclusion(&unknown), None); + assert_eq!(node_row_note(&node(true, ListMembership::Listed)), None); + } +} diff --git a/src/ui/dpns/progress_drawer.rs b/src/ui/dpns/progress_drawer.rs new file mode 100644 index 000000000..fcee0e114 --- /dev/null +++ b/src/ui/dpns/progress_drawer.rs @@ -0,0 +1,318 @@ +//! Vote progress drawer (VOTE-FR-083): bottom-right, collapsible, on every +//! screen. Non-blocking — the rest of the app stays interactive. + +use crate::app::AppAction; +use crate::backend_task::BackendTask; +use crate::backend_task::contested_names::ContestedResourceTask; +use crate::context::AppContext; +use crate::model::dpns_voting::progress::{ + ProgressCounts, ProgressPhase, drawer_operations, progress_counts, progress_phase, +}; +use crate::model::dpns_voting::{DpnsVoteFailure, DpnsVoteOutcome, DpnsVoteTargetStatus}; +use crate::ui::RootScreenType; +use crate::ui::dpns::copy::{drawer_header, progress_row_status}; +use crate::ui::theme::DashColors; +use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use eframe::egui::{self, Align2, Id, RichText, Sense, Ui}; + +const OPEN_ID: &str = "dpns_vote_progress_drawer_open"; + +/// AppState-owned drawer state; survives navigation. Dismissed operations +/// live in `AppContext` so the `Needs attention` row honours them too. +#[derive(Debug, Clone)] +pub struct DrawerState { + /// Settled operations created before this time are not listed. + since_ms: u64, +} + +impl DrawerState { + pub fn new(since_ms: u64) -> Self { + Self { since_ms } + } + + /// Settled operations created before this moment are not listed. + pub fn since_ms(&self) -> u64 { + self.since_ms + } +} + +/// Expand the drawer, e.g. right after a submit. +pub fn expand(ctx: &egui::Context) { + ctx.data_mut(|data| data.insert_temp(Id::new(OPEN_ID), true)); +} + +fn is_open(ctx: &egui::Context) -> bool { + ctx.data(|data| data.get_temp(Id::new(OPEN_ID)).unwrap_or(false)) +} + +/// The action a row offers for an outcome, if any (VOTE-FR-083). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RowAction { + CheckAgain, + ReviewAgain, + AddVotingKey, +} + +impl RowAction { + fn label(self) -> &'static str { + match self { + Self::CheckAgain => "Check again", + Self::ReviewAgain => "Review again", + Self::AddVotingKey => "Add voting key", + } + } +} + +/// The valid action for an outcome: never a resubmit while ambiguous. +pub fn row_action(outcome: &DpnsVoteOutcome) -> Option { + match (outcome.status, outcome.failure) { + (DpnsVoteTargetStatus::Unconfirmed, _) => Some(RowAction::CheckAgain), + (_, Some(DpnsVoteFailure::VotingKeyMissing)) => Some(RowAction::AddVotingKey), + (_, Some(DpnsVoteFailure::VotingEnded)) => None, + (status, _) if status.is_reviewable_failure() => Some(RowAction::ReviewAgain), + _ => None, + } +} + +fn paint_segments(ui: &mut Ui, counts: ProgressCounts) { + let dark_mode = ui.visuals().dark_mode; + let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 6.0), Sense::hover()); + let total = counts.total.max(1) as f32; + let mut x = rect.left(); + for (count, color) in [ + (counts.confirmed, DashColors::success_color(dark_mode)), + (counts.failed, DashColors::error_color(dark_mode)), + (counts.checking, DashColors::warning_color(dark_mode)), + (counts.sending, DashColors::DASH_BLUE), + ] { + if count == 0 { + continue; + } + let width = rect.width() * count as f32 / total; + let segment = egui::Rect::from_min_size(egui::pos2(x, rect.top()), egui::vec2(width, 6.0)); + ui.painter().rect_filled(segment, 2.0, color); + x += width; + } +} + +/// Render the drawer when there is something to show. +pub fn show(ctx: &egui::Context, app_context: &AppContext, state: &mut DrawerState) -> AppAction { + let operations = app_context.dpns_vote_progress(); + let dismissed = app_context.dismissed_dpns_vote_operations(); + let shown = drawer_operations( + operations.iter().map(std::sync::Arc::as_ref), + state.since_ms, + &dismissed, + ); + if shown.is_empty() { + return AppAction::None; + } + let counts = progress_counts(shown.iter().copied()); + let mut open = is_open(ctx); + let mut action = AppAction::None; + egui::Area::new(Id::new("dpns_vote_progress_drawer")) + .anchor(Align2::RIGHT_BOTTOM, egui::vec2(-16.0, -16.0)) + .order(egui::Order::Foreground) + .show(ctx, |ui| { + egui::Frame::window(ui.style()).show(ui, |ui| { + ui.set_width(360.0); + ui.horizontal(|ui| { + ui.label(RichText::new(drawer_header(counts)).strong()); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui + .small_button(if open { "Hide" } else { "Show" }) + .clicked() + { + open = !open; + } + if !counts.in_flight() && ui.small_button("Dismiss").clicked() { + app_context.dismiss_dpns_vote_operations( + shown.iter().map(|operation| operation.id), + ); + } + }); + }); + paint_segments(ui, counts); + if !open { + return; + } + egui::ScrollArea::vertical() + .max_height(260.0) + .show(ui, |ui| { + for outcome in shown + .iter() + .flat_map(|operation| &operation.targets) + .filter(|outcome| progress_phase(outcome).is_some()) + { + ui.horizontal_wrapped(|ui| { + let node = crate::model::identity_name::masternode_label( + outcome.target.key.voter_id, + outcome.target.voter_alias.as_deref(), + ); + let candidate = match outcome.target.requested_choice { + ResourceVoteChoice::TowardsIdentity(id) => app_context + .dpns_candidate_label(&outcome.target.contested_name, id), + _ => None, + }; + ui.label(format!( + "{node} · {name}.dash · {choice}", + name = outcome.target.contested_name, + choice = crate::ui::dpns::copy::vote_choice_label( + outcome.target.requested_choice, + candidate.as_deref(), + ), + )); + let color = match progress_phase(outcome) { + Some(ProgressPhase::Failed) => { + DashColors::error_color(ui.visuals().dark_mode) + } + Some(ProgressPhase::Checking) => { + DashColors::warning_color(ui.visuals().dark_mode) + } + _ => DashColors::text_secondary(ui.visuals().dark_mode), + }; + ui.label( + RichText::new(progress_row_status( + outcome.status, + outcome.failure, + )) + .color(color), + ); + if let Some(row) = row_action(outcome) + && ui.small_button(row.label()).clicked() + { + action = match row { + RowAction::CheckAgain => AppAction::BackendTask( + BackendTask::ContestedResourceTask( + ContestedResourceTask::ReconcileDpnsVoteOperation( + outcome.operation_id, + app_context.network(), + ), + ), + ), + RowAction::ReviewAgain => { + app_context.request_dpns_vote_review(outcome.clone()); + AppAction::SetMainScreenThenGoToMainScreen( + RootScreenType::RootScreenDPNSActiveContests, + ) + } + RowAction::AddVotingKey => { + AppAction::SetMainScreenThenGoToMainScreen( + RootScreenType::RootScreenMasternodes, + ) + } + }; + } + }); + } + }); + }); + }); + ctx.data_mut(|data| data.insert_temp(Id::new(OPEN_ID), open)); + action +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::dpns_voting::{DpnsVoteTarget, DpnsVoteTargetKey, VoteTiming}; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::platform::Identifier; + + fn outcome(status: DpnsVoteTargetStatus, failure: Option) -> DpnsVoteOutcome { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([2; 32]), + }, + voter_alias: None, + contested_name: "alice".to_owned(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Now, + }]); + let mut outcome = operation.targets.remove(0); + outcome.status = status; + outcome.failure = failure; + outcome + } + + #[test] + fn live_progress_drawer_never_reads_persistent_contests() { + let dir = tempfile::tempdir().unwrap(); + let app = crate::context::test_support::test_app_context(dir.path()); + let store = + std::sync::Arc::new(crate::wallet_backend::kv_test_support::FailingKv::default()); + app.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(store.clone())); + app.seed_dpns_contest_for_test("alice", None, false); + app.refresh_dpns_candidate_labels().unwrap(); + assert_eq!( + app.dpns_candidate_label("alice", Identifier::from([3; 32])) + .as_deref(), + Some("alice") + ); + let mut target = outcome(DpnsVoteTargetStatus::Queued, None).target; + target.requested_choice = ResourceVoteChoice::TowardsIdentity(Identifier::from([3; 32])); + target.key.network = app.network; + let mut operation = AppContext::new_dpns_vote_operation(vec![target]); + app.insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + let key = operation.targets[0].target.key.clone(); + let ctx = egui::Context::default(); + let mut state = DrawerState::new(0); + for status in [ + DpnsVoteTargetStatus::Queued, + DpnsVoteTargetStatus::Confirming, + DpnsVoteTargetStatus::Confirmed, + ] { + app.update_dpns_vote_target(operation.id, &key, status, None) + .unwrap(); + for open in [false, true] { + ctx.data_mut(|data| data.insert_temp(Id::new(OPEN_ID), open)); + let reads = store.read_count(); + ctx.run_ui(egui::RawInput::default(), |ui| { + show(ui.ctx(), &app, &mut state); + }) + .drop_without_applying_deltas(); + assert_eq!(store.read_count(), reads, "drawer must use only memory"); + } + } + } + + /// VOTE-FR-044/083: ambiguity offers only Check again; ended voting offers nothing. + #[test] + fn rows_offer_only_the_valid_action() { + use DpnsVoteTargetStatus as S; + assert_eq!( + row_action(&outcome( + S::Unconfirmed, + Some(DpnsVoteFailure::ResultUnconfirmed) + )), + Some(RowAction::CheckAgain) + ); + assert_eq!( + row_action(&outcome( + S::Rejected, + Some(DpnsVoteFailure::PlatformRejected) + )), + Some(RowAction::ReviewAgain) + ); + assert_eq!( + row_action(&outcome( + S::FailedBeforeSubmission, + Some(DpnsVoteFailure::VotingKeyMissing) + )), + Some(RowAction::AddVotingKey) + ); + assert_eq!( + row_action(&outcome( + S::FailedBeforeSubmission, + Some(DpnsVoteFailure::VotingEnded) + )), + None + ); + assert_eq!(row_action(&outcome(S::Confirming, None)), None); + assert_eq!(row_action(&outcome(S::Confirmed, None)), None); + } +} diff --git a/src/ui/identity/add_new_identity_screen/success_screen.rs b/src/ui/identity/add_new_identity_screen/success_screen.rs index fb3e516b2..c1d6e9222 100644 --- a/src/ui/identity/add_new_identity_screen/success_screen.rs +++ b/src/ui/identity/add_new_identity_screen/success_screen.rs @@ -17,7 +17,7 @@ impl AddNewIdentityScreen { AppAction::PopScreenAndRefresh, ), ( - "Register DPNS Name".to_string(), + "Get a username".to_string(), AppAction::Custom("register_dpns".to_string()), ), ], @@ -33,7 +33,6 @@ impl AddNewIdentityScreen { RegisterDpnsNameScreen::new(&self.app_context, RegisterDpnsNameSource::Identities); if let Some(identity_id) = self.successful_qualified_identity_id { screen.select_identity(identity_id); - screen.show_identity_selector = false; } return AppAction::PopThenAddScreenToMainScreen( RootScreenType::RootScreenIdentityHub, diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index 3d89043c6..158cc1e15 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -315,7 +315,7 @@ impl ContactsTabState { return ContactsTabState::Gated { handle: None }; }; - let handle = primary_dpns_handle(&active); + let handle = app_context.main_username(&active); if has_social_profile(profiles, &active) { ContactsTabState::Populated { identity: Box::new(active), @@ -745,16 +745,6 @@ fn section_card(ui: &mut Ui, dark_mode: bool, heading: &str, body: impl FnOnce(& }); } -/// Primary DPNS handle for an identity: the first registered DPNS name, when -/// available. Returns the bare handle without the leading `@`. -fn primary_dpns_handle(identity: &QualifiedIdentity) -> Option { - identity - .dpns_names - .first() - .map(|n| n.name.trim().to_string()) - .filter(|s| !s.is_empty()) -} - /// Detect whether the identity has a DashPay social profile. Reads the hub's /// async profile cache; an entry that is absent (not loaded yet) or holds no /// profile yields `false`, so the gate is shown and the user is not blocked diff --git a/src/ui/identity/home.rs b/src/ui/identity/home.rs index 75863f8b0..f0bf3f734 100644 --- a/src/ui/identity/home.rs +++ b/src/ui/identity/home.rs @@ -28,7 +28,7 @@ use super::identity_hero_card::{HeroIdentityKind, IdentityHeroCard}; use super::onboarding_checklist::{ChecklistAction, ChecklistStep, OnboardingChecklist}; use crate::app::AppAction; use crate::context::AppContext; -use crate::model::contested_name::PendingUsername; +use crate::model::dpns_usernames::UsernameRequest; use crate::model::qualified_identity::QualifiedIdentity; use crate::ui::ScreenType; use crate::ui::identity::register_dpns_name_screen::RegisterDpnsNameSource; @@ -279,7 +279,7 @@ pub fn render( // the onboarding checklist so a pending request is not mistaken for "no // username". Only meaningful when the identity owns no name yet; the cache // read is best-effort, so a failure simply omits the indicator. - let pending_username: Option = + let pending_username: Option = app_context.pending_dpns_username_for_identity(&identity); // A tiny local closure that dispatches via the pure @@ -302,6 +302,10 @@ pub fn render( apply(HomeButton::PickUsernameHero); } + // --- Username requests: pending cards and one-time outcome banners - + ui.add_space(Spacing::SM); + let notices_action = super::username_notices::render(ui, app_context, &identity); + // --- Inline "Set up your social profile" card (no-profile variant) - // // Per wireframe §B.3 this prompt belongs immediately below the compact hero, @@ -378,11 +382,7 @@ pub fn render( if !state.dismissed_checklist { // Extract the primary DPNS handle for the done-subtext ("You are // @{handle}.") — passed into the checklist as optional context. - let primary_handle = identity - .dpns_names - .first() - .map(|n| n.name.trim().to_string()) - .filter(|s| !s.is_empty()); + let primary_handle = app_context.main_username(&identity); let mut checklist = OnboardingChecklist::new(); if let Some(h) = &primary_handle { @@ -393,7 +393,7 @@ pub fn render( } else if let Some(pending) = &pending_username { // Requested but not yet awarded — reflect the pending state instead // of nagging the user to pick a name they already chose. - checklist = checklist.with_pending_username(pending.name.clone()); + checklist = checklist.with_pending_username(pending.label.clone()); } if hero_has_social_profile { checklist = checklist.mark_complete(ChecklistStep::SetDisplayName); @@ -534,6 +534,7 @@ pub fn render( }); } + action |= notices_action; (action, outcome) } @@ -570,15 +571,11 @@ fn build_hero( app_context: &Arc, qi: &QualifiedIdentity, profiles: &mut super::profile_cache::ProfileCache, - pending_username: Option, + pending_username: Option, ) -> IdentityHeroCard { let kind: HeroIdentityKind = qi.identity_type.into(); let balance_dash = format_credits_short(qi.identity.balance()); - let handle = qi - .dpns_names - .first() - .map(|n| n.name.clone()) - .filter(|n| !n.trim().is_empty()); + let handle = app_context.main_username(qi); // Best-effort DashPay display name. The local profile cache was removed in // the platform-wallet migration; the hub loads profiles asynchronously, so diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index a65353072..5a378adb3 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -58,6 +58,11 @@ pub struct IdentityHubScreen { /// Settings-tab state. Held on the hub so edit fields, unsaved drafts, /// and modal state persist across frames. settings_tab: SettingsTab, + /// When a username status refresh was last dispatched (Unix ms). The cadence + /// keys off dispatch time, so a result routed elsewhere never stalls it. + usernames_refreshed_at: Option, + /// The hub was just shown; the next frame applies the arrival refresh rule. + usernames_arriving: bool, /// Identities this screen dispatched an unload for, each retained until its /// own result lands. Neither selection pointer survives that wait: a frame /// can render before the result arrives and reconcile both of them onto the @@ -109,6 +114,32 @@ enum ContactInfoTaskKey { } impl IdentityHubScreen { + /// Refresh username request status when due (USR-FR-021); schedules the next check. + fn username_refresh_action(&mut self, ctx: &egui::Context) -> AppAction { + let arriving = std::mem::take(&mut self.usernames_arriving); + let network = self.app_context.network; + let needs_refresh = self.app_context.username_requests_need_refresh(); + let now = crate::utils::time::now_ms(); + if needs_refresh { + ctx.request_repaint_after(crate::model::dpns_usernames::pending_refresh_interval( + network, + )); + } + if !crate::model::dpns_usernames::username_refresh_due( + now, + self.usernames_refreshed_at, + arriving, + needs_refresh, + network, + ) { + return AppAction::None; + } + self.usernames_refreshed_at = Some(now); + AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::RefreshMyUsernameRequests, + )) + } + /// Whether an avatar result still belongs to an outstanding hub request. pub(crate) fn is_waiting_for_avatar(&self, url: &str) -> bool { self.avatar_cache.is_loading(url) @@ -125,6 +156,8 @@ impl IdentityHubScreen { last_good_landing: HubLanding::Onboarding, home_state: HomeState::default(), settings_tab: SettingsTab::new(), + usernames_refreshed_at: None, + usernames_arriving: true, pending_unloads: BTreeSet::new(), contacts_state: super::contacts::ContactsState::default(), profile_cache: super::profile_cache::ProfileCache::default(), @@ -404,6 +437,7 @@ impl ScreenLike for IdentityHubScreen { fn refresh_on_arrival(&mut self) { self.refresh(); + self.usernames_arriving = true; } fn ui(&mut self, ui: &mut egui::Ui) -> AppAction { @@ -607,6 +641,9 @@ impl ScreenLike for IdentityHubScreen { self.profile_cache.dispatch_pending() }; } + if matches!(action, AppAction::None) { + action = self.username_refresh_action(ctx); + } action } @@ -641,6 +678,13 @@ impl ScreenLike for IdentityHubScreen { } fn display_task_result(&mut self, result: BackendTaskSuccessResult) { + if matches!( + result, + BackendTaskSuccessResult::MyUsernameRequestsRefreshed + | BackendTaskSuccessResult::UsernamePreferencesSaved + ) { + return; + } if let BackendTaskSuccessResult::DashPayAvatar { url, bytes } = result { if self.is_waiting_for_avatar(&url) { self.avatar_cache.store(url, bytes); @@ -744,6 +788,11 @@ impl ScreenLike for IdentityHubScreen { } fn display_task_error(&mut self, error: &TaskError) -> bool { + // The status refresh runs in the background; a failure keeps the stored + // status and retries on the next cadence tick instead of raising a banner. + if matches!(error, TaskError::UsernameRequestRefreshFailed { .. }) { + return true; + } if self.handle_contact_request_error(error) { return matches!( contact_info_read_error_key(error), diff --git a/src/ui/identity/identity_hero_card.rs b/src/ui/identity/identity_hero_card.rs index 99541679d..8e5340c38 100644 --- a/src/ui/identity/identity_hero_card.rs +++ b/src/ui/identity/identity_hero_card.rs @@ -18,7 +18,7 @@ //! This component follows `docs/COMPONENT_DESIGN_PATTERN.md`: private fields + //! builder methods + a response struct implementing [`ComponentResponse`]. -use crate::model::contested_name::PendingUsername; +use crate::model::dpns_usernames::UsernameRequest; use crate::model::qualified_identity::IdentityType; use crate::ui::components::component_trait::ComponentResponse; use crate::ui::components::pill; @@ -185,8 +185,8 @@ pub struct IdentityHeroCard { avatar_decode_ok: bool, /// A DPNS username the identity has requested but not yet been awarded. /// When set and no owned `dpns_handle` exists, the hero shows the requested - /// name with a "Pending" pill instead of the `No username yet` prompt. - pending_username: Option, + /// name with a phase pill instead of the `No username yet` prompt. + pending_username: Option, } impl IdentityHeroCard { @@ -229,8 +229,8 @@ impl IdentityHeroCard { /// Attach a pending DPNS username request (requested but not yet awarded). /// Shown only when the identity has no owned `dpns_handle` — an owned name /// always wins. - pub fn with_pending_username(mut self, pending: PendingUsername) -> Self { - if !pending.name.trim().is_empty() { + pub fn with_pending_username(mut self, pending: UsernameRequest) -> Self { + if !pending.label.trim().is_empty() { self.pending_username = Some(pending); } self @@ -356,7 +356,7 @@ impl IdentityHeroCard { } (None, Some(pending)) => { // Requested but not yet awarded — show the requested - // name with a `Pending` pill so it is not mistaken + // name with a phase pill so it is not mistaken // for "no username requested". self.paint_pending_username_line(ui, dark_mode, pending); } @@ -537,11 +537,11 @@ impl IdentityHeroCard { } /// Paint the pending-username line: the requested `@name` (muted, italic to - /// signal it is not yet final) followed by a shared `Pending` pill whose + /// signal it is not yet final) followed by a shared phase pill whose /// tooltip carries the estimated ready time. - fn paint_pending_username_line(&self, ui: &mut Ui, dark_mode: bool, pending: &PendingUsername) { + fn paint_pending_username_line(&self, ui: &mut Ui, dark_mode: bool, pending: &UsernameRequest) { let name = - crate::model::contested_name::sanitize_pending_username_for_display(&pending.name); + crate::model::contested_name::sanitize_pending_username_for_display(&pending.label); ui.horizontal(|ui| { ui.label( RichText::new(format!("@{name}")) @@ -738,11 +738,19 @@ mod tests { // ─── Pending DPNS username tests ───────────────────────── - fn pending(name: &str) -> PendingUsername { - PendingUsername { - name: name.to_string(), - decided_at: None, - } + fn pending(name: &str) -> UsernameRequest { + let mut request = UsernameRequest::submitted( + "x", + 0, + crate::model::dpns::ContestDurations { + total: std::time::Duration::ZERO, + join: std::time::Duration::ZERO, + }, + None, + ); + request.label = name.to_string(); + request.end = None; + request } #[test] @@ -752,7 +760,7 @@ mod tests { assert!(hero.pending_username.is_none()); } - /// The pending variant renders the requested name with a `Pending` pill and + /// The pending variant renders the requested name with a phase pill and /// suppresses the misleading `No username yet` prompt. #[test] fn hero_pending_variant_shows_pill_not_pick_username_prompt() { @@ -770,9 +778,11 @@ mod tests { assert!( harness - .query_by_label(pill::PENDING_USERNAME_PILL_LABEL) + .query_by_label(crate::ui::identity::username_copy::phase_label( + crate::model::dpns_usernames::RequestPhase::Joinable + )) .is_some(), - "pending hero must render the 'Pending' pill" + "pending hero must render the phase pill" ); assert!( harness.query_by_label("No username yet").is_none(), @@ -780,7 +790,7 @@ mod tests { ); } - /// An owned DPNS name always wins: no `Pending` pill even if a pending + /// An owned DPNS name always wins: no phase pill even if a pending /// request is also attached. #[test] fn hero_owned_handle_wins_over_pending() { @@ -802,7 +812,9 @@ mod tests { ); assert!( harness - .query_by_label(pill::PENDING_USERNAME_PILL_LABEL) + .query_by_label(crate::ui::identity::username_copy::phase_label( + crate::model::dpns_usernames::RequestPhase::Joinable + )) .is_none(), "owned name must suppress the pending pill" ); diff --git a/src/ui/identity/mod.rs b/src/ui/identity/mod.rs index 3bc35d894..c31274ebb 100644 --- a/src/ui/identity/mod.rs +++ b/src/ui/identity/mod.rs @@ -56,6 +56,10 @@ pub mod social_profile_gate_card; pub mod tabs; pub mod top_up_identity_screen; pub mod transfer_screen; +pub mod username_copy; +pub mod username_notices; +pub mod username_request_screen; +pub mod usernames_card; pub mod withdraw_screen; pub use hub_screen::IdentityHubScreen; diff --git a/src/ui/identity/picker.rs b/src/ui/identity/picker.rs index 4bd2e6d2a..cd20c2a3f 100644 --- a/src/ui/identity/picker.rs +++ b/src/ui/identity/picker.rs @@ -108,8 +108,8 @@ pub fn render( identity.identity.id(), profile.and_then(|p| p.display_name_opt()), ); - let mut card = - build_card(identity, name.as_deref()).with_width(card_width); + let mut card = build_card(app_context, identity, name.as_deref()) + .with_width(card_width); if let Some(profile) = profile { card = card.with_avatar_url(&profile.avatar_url); } @@ -182,8 +182,13 @@ enum PickerCell<'a> { Add, } -/// Build a picker card using the same profile name as navigation. -fn build_card(identity: &QualifiedIdentity, display_name: Option<&str>) -> IdentityPickerCard { +/// Build a picker card using the same profile name as navigation and the +/// identity's main username as its handle. +fn build_card( + app_context: &AppContext, + identity: &QualifiedIdentity, + display_name: Option<&str>, +) -> IdentityPickerCard { let id_base58 = identity.identity.id().to_string(Encoding::Base58); // Balance formatting: design-spec §B.14 uses `{amount} DASH` with tabular @@ -209,10 +214,8 @@ fn build_card(identity: &QualifiedIdentity, display_name: Option<&str>) -> Ident if let Some(name) = display_name { card = card.with_display_name(name); } - if let Some(dpns) = identity.dpns_names.first().map(|n| n.name.as_str()) - && !dpns.is_empty() - { - card = card.with_dpns_handle(dpns); + if let Some(dpns) = app_context.main_username(identity) { + card = card.with_dpns_handle(&dpns); } card diff --git a/src/ui/identity/register_dpns_name_screen.rs b/src/ui/identity/register_dpns_name_screen.rs index d56773ca7..b338395b6 100644 --- a/src/ui/identity/register_dpns_name_screen.rs +++ b/src/ui/identity/register_dpns_name_screen.rs @@ -1,686 +1,990 @@ +//! Get a username for one identity: choose a name, consent to a community vote +//! when needed, confirm the payment, and see the result. + use crate::app::AppAction; +use crate::backend_task::error::TaskError; use crate::backend_task::identity::{IdentityTask, RegisterDpnsNameInput}; -use crate::backend_task::{BackendTask, BackendTaskSuccessResult, FeeResult}; +use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult, FeeResult}; use crate::context::AppContext; -use crate::model::dpns::{DpnsNameValidationResult, DpnsRegistrationOutcome, validate_dpns_name}; -use crate::model::fee_estimation::format_credits_as_dash; +use crate::context::connection_status::OverallConnectionState; +use crate::model::dpns::{ + DpnsNameValidationResult, DpnsRegistrationOutcome, contest_durations, suggest_uncontested, + validate_dpns_name, +}; +use crate::model::dpns_usernames::{ + UsernameAvailability, can_register_usernames, dpns_signing_requirement, +}; +use crate::model::fee_estimation::{contest_fee_credits, format_credits_as_dash}; use crate::model::qualified_identity::QualifiedIdentity; +use crate::model::user_role::UserRole; use crate::model::wallet::Wallet; -use crate::ui::components::identity_selector::IdentitySelector; +use crate::ui::components::component_trait::Component; +use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; use crate::ui::components::left_panel::add_left_panel; use crate::ui::components::styled::island_central_panel; use crate::ui::components::top_panel::add_top_panel; use crate::ui::components::wallet_unlock_popup::{ - WalletUnlockPopup, WalletUnlockResult, try_open_wallet_no_password, wallet_needs_unlock, + WalletUnlockPopup, try_open_wallet_no_password, wallet_needs_unlock, }; use crate::ui::components::{ MessageBanner, OptionOverlayExt, OverlayConfig, OverlayHandle, ResultBannerExt, }; use crate::ui::helpers::{TransactionType, add_key_chooser_with_doc_type}; -use crate::ui::theme::{DashColors, ResponseExt}; -use crate::ui::{MessageType, ScreenLike}; +use crate::ui::identity::username_copy::{ + self, AvailabilityRow, Tone, USERNAME_RULES, availability_line, offers_suggestions, +}; +use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; +use crate::ui::{MessageType, RootScreenType, ScreenLike, ScreenType}; use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; -use dash_sdk::dpp::identity::Purpose; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; -use dash_sdk::platform::{Identifier, IdentityPublicKey}; +use dash_sdk::platform::IdentityPublicKey; use eframe::egui::{Context, Frame, Margin}; -use egui::{Color32, RichText, Ui}; -use std::sync::Arc; -use std::sync::RwLock; +use egui::{RichText, Ui}; +use std::sync::{Arc, RwLock}; +use std::time::{Duration, Instant}; use super::get_selected_wallet; -/// Tracks where the user navigated from to reach this screen +/// Wait after the last keystroke before asking the network about a name. +const AVAILABILITY_DEBOUNCE: Duration = Duration::from_millis(400); + +/// Where the user navigated from to reach this screen. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum RegisterDpnsNameSource { + /// The Identities hub, the only place that opens this screen. #[default] - Dpns, Identities, } -#[derive(PartialEq)] -pub enum RegisterDpnsNameStatus { - NotStarted, - WaitingForResult, - Error, - Complete, +/// Where the user is in the flow. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Step { + Choose, + Confirm, + Submitting, + Done(DpnsRegistrationOutcome), +} + +/// Live availability state of the typed label. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Availability { + /// Nothing typed, or the format is invalid. + Idle, + /// Waiting for typing to settle. + Debouncing { label: String, since: Instant }, + /// A check is in flight or answered. + Row { label: String, row: AvailabilityRow }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct RegistrationReview { + label: String, + identity_id: dash_sdk::platform::Identifier, + network: dash_sdk::dpp::dashcore::Network, + needs_vote: bool, + registration_fee: u64, + contest_fee: u64, } pub struct RegisterDpnsNameScreen { - pub show_identity_selector: bool, - pub qualified_identities: Vec, + pub app_context: Arc, + /// The identity the username is for, taken from the app's selected identity. pub selected_qualified_identity: Option, - selected_identity_string: String, - pub selected_key: Option, name_input: String, - register_dpns_name_status: RegisterDpnsNameStatus, - pub app_context: Arc, + availability: Availability, + step: Step, + consent_dialog: Option, + review: Option, + /// Signing key chosen under Advanced; `None` lets the backend pick the default. + selected_key: Option, selected_wallet: Option>>, wallet_unlock_popup: WalletUnlockPopup, wallet_open_attempted: bool, - show_advanced_options: bool, - // Fee result from completed operation completed_fee_result: Option, - registration_outcome: Option, - // Source of navigation to this screen + /// Source of navigation to this screen pub source: RegisterDpnsNameSource, - /// Bucket A overlay-adoption pattern: a button-less full-window block raised - /// when the bounded registration is dispatched and torn down on every - /// terminal result. It replaces the old progress banner and, by blocking the - /// whole window, closes the double-submit hole the banner left open. + /// Full-window block while the registration runs; torn down on every terminal result. op_overlay: Option, + registration_context: Option, + registration_error_handled: bool, + /// Label of the availability check in flight. One check runs at a time, so a + /// failure always belongs to this label. + check_in_flight: Option, } impl RegisterDpnsNameScreen { pub fn new(app_context: &Arc, source: RegisterDpnsNameSource) -> Self { - let qualified_identities: Vec<_> = - app_context.load_local_user_identities().unwrap_or_default(); - - // Seed from the app-scoped selected identity (W2 SYNC); fall back to first. - let selected_qualified_identity = app_context - .selected_identity_id() - .and_then(|id| { - qualified_identities - .iter() - .find(|qi| qi.identity.id() == id) - .cloned() - }) - .or_else(|| qualified_identities.first().cloned()); - - let selected_wallet = if let Some(ref identity) = selected_qualified_identity { - get_selected_wallet(identity, Some(app_context), None) - .or_show_error(app_context.egui_ctx()) - .unwrap_or(None) - } else { - None - }; - - // Auto-select a suitable key for DPNS registration - // Note: MASTER keys cannot be used for document operations, - // only MEDIUM, HIGH, or CRITICAL security levels are allowed - let selected_key = selected_qualified_identity.as_ref().and_then(|identity| { - use dash_sdk::dpp::identity::{KeyType, SecurityLevel}; - identity - .identity - .get_first_public_key_matching( - Purpose::AUTHENTICATION, - [ - SecurityLevel::CRITICAL, - SecurityLevel::HIGH, - SecurityLevel::MEDIUM, - ] - .into(), - KeyType::all_key_types().into(), - false, - ) - .cloned() - }); - - let selected_identity_string = selected_qualified_identity - .as_ref() - .map(|qi| { - qi.identity - .id() - .to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58) - }) - .unwrap_or_default(); - - let show_identity_selector = qualified_identities.len() > 1; - Self { - show_identity_selector, - qualified_identities, - selected_qualified_identity, - selected_identity_string, - selected_key, - name_input: String::new(), - register_dpns_name_status: RegisterDpnsNameStatus::NotStarted, + let mut screen = Self { app_context: app_context.clone(), - selected_wallet, + selected_qualified_identity: None, + name_input: String::new(), + availability: Availability::Idle, + step: Step::Choose, + consent_dialog: None, + review: None, + selected_key: None, + selected_wallet: None, wallet_unlock_popup: WalletUnlockPopup::new(), wallet_open_attempted: false, - show_advanced_options: false, completed_fee_result: None, - registration_outcome: None, source, op_overlay: None, - } + registration_context: None, + registration_error_handled: false, + check_in_flight: None, + }; + screen.reload_identity(); + screen } - pub fn select_identity(&mut self, identity_id: Identifier) { - // Find the qualified identity with the matching identity_id - if let Some(qi) = self - .qualified_identities - .iter() - .find(|qi| qi.identity.id() == identity_id) - { - // Set the selected_qualified_identity to the found identity - self.selected_qualified_identity = Some(qi.clone()); - self.selected_identity_string = qi - .identity - .id() - .to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58); - - // Auto-select a suitable key for DPNS registration - // Note: MASTER keys cannot be used for document operations, - // only MEDIUM, HIGH, or CRITICAL security levels are allowed - use dash_sdk::dpp::identity::{KeyType, SecurityLevel}; - self.selected_key = qi - .identity - .get_first_public_key_matching( - Purpose::AUTHENTICATION, - [ - SecurityLevel::CRITICAL, - SecurityLevel::HIGH, - SecurityLevel::MEDIUM, - ] - .into(), - KeyType::all_key_types().into(), - false, - ) - .cloned(); - - // Update the selected wallet - self.selected_wallet = get_selected_wallet(qi, Some(&self.app_context), None) - .or_show_error(self.app_context.egui_ctx()) - .unwrap_or(None); - self.wallet_open_attempted = false; - } else { - // If not found, you might want to handle this case - // For now, we'll set selected_qualified_identity to None - self.selected_qualified_identity = None; - self.selected_identity_string = String::new(); + /// Get the username for `identity_id` instead of the app's selected identity. + pub fn select_identity(&mut self, identity_id: dash_sdk::platform::Identifier) { + self.load_identity(Some(identity_id)); + } + + /// Re-read the identity so balance and keys stay current (e.g. after a top-up). + fn reload_identity(&mut self) { + let wanted = self + .selected_qualified_identity + .as_ref() + .map(|qi| qi.identity.id()) + .or_else(|| self.app_context.selected_identity_id()); + self.load_identity(wanted); + } + + fn load_identity(&mut self, wanted: Option) { + let identities = self + .app_context + .load_local_user_identities() + .unwrap_or_default(); + let current = self + .selected_qualified_identity + .as_ref() + .map(|qi| qi.identity.id()); + let identity = wanted + .and_then(|id| identities.iter().find(|qi| qi.identity.id() == id).cloned()) + .or_else(|| identities.first().cloned()); + if identity.as_ref().map(|qi| qi.identity.id()) != current { + self.on_label_changed(); self.selected_key = None; - self.selected_wallet = None; + self.selected_wallet = identity.as_ref().and_then(|qi| { + get_selected_wallet(qi, Some(&self.app_context), None) + .or_show_error(self.app_context.egui_ctx()) + .unwrap_or(None) + }); self.wallet_open_attempted = false; } + self.selected_qualified_identity = identity; } - fn render_identity_id_selection(&mut self, ui: &mut egui::Ui) -> AppAction { - let mut action = AppAction::None; + fn identity_label(&self) -> String { + self.selected_qualified_identity + .as_ref() + .map(|qi| self.app_context.identity_display_label(qi)) + .unwrap_or_default() + } - // Identity selector — SYNC: write-back via syncing_global on user pick. - let response = ui.add( - IdentitySelector::new( - "dpns_register_identity_selector", - &mut self.selected_identity_string, - &self.qualified_identities, - ) - .selected_identity(&mut self.selected_qualified_identity) - .unwrap() - .width(300.0) - .label("Identity:") - .other_option(false) - .syncing_global(self.app_context.clone()), - ); + fn label(&self) -> &str { + self.name_input.trim() + } - // Handle identity change - auto-select key and update wallet - if response.changed() { - if let Some(identity) = &self.selected_qualified_identity { - // Auto-select a suitable key for DPNS registration - // Note: MASTER keys cannot be used for document operations, - // only MEDIUM, HIGH, or CRITICAL security levels are allowed - use dash_sdk::dpp::identity::{KeyType, SecurityLevel}; - self.selected_key = identity - .identity - .get_first_public_key_matching( - Purpose::AUTHENTICATION, - [ - SecurityLevel::CRITICAL, - SecurityLevel::HIGH, - SecurityLevel::MEDIUM, - ] - .into(), - KeyType::all_key_types().into(), - false, - ) - .cloned(); - - // Update wallet - self.selected_wallet = get_selected_wallet(identity, Some(&self.app_context), None) - .or_show_error(self.app_context.egui_ctx()) - .unwrap_or(None); - self.wallet_open_attempted = false; - } else { - self.selected_key = None; - self.selected_wallet = None; - self.wallet_open_attempted = false; - } + /// The answered availability for the label currently typed, if any. + fn current_availability(&self) -> Option { + match &self.availability { + Availability::Row { + label, + row: AvailabilityRow::Known(availability), + } if label == self.label() => Some(*availability), + _ => None, } + } - // Key selector (only shown in advanced mode) - if self.show_advanced_options { - ui.add_space(10.0); - if let Some(identity) = &self.selected_qualified_identity { - let key_action = add_key_chooser_with_doc_type( - ui, - &self.app_context, - identity, - &mut self.selected_key, - TransactionType::DocumentAction, - self.app_context - .dpns_contract - .document_type_cloned_for_name("domain") - .ok() - .as_ref(), - ); - if !matches!(key_action, AppAction::None) { - action = key_action; - } - } - } + fn registration_fee(&self) -> u64 { + self.app_context.fee_estimator().estimate_document_batch(2) + } - action + fn contest_fee(&self) -> u64 { + contest_fee_credits(self.app_context.sdk_platform_version()) + } + + /// Restart the debounce after the typed label changed. + fn on_label_changed(&mut self) { + self.review = None; + self.consent_dialog = None; + self.step = Step::Choose; + let label = self.label().to_owned(); + self.availability = if validate_dpns_name(&label) == DpnsNameValidationResult::Valid { + Availability::Debouncing { + label, + since: Instant::now(), + } + } else { + Availability::Idle + }; } - fn register_dpns_name_clicked(&mut self) -> AppAction { - let Some(qualified_identity) = self.selected_qualified_identity.as_ref() else { + /// Dispatch the availability check once typing has settled. + fn poll_debounce(&mut self, ctx: &Context) -> AppAction { + let Availability::Debouncing { label, since } = &self.availability else { return AppAction::None; }; - let Some(_selected_key) = self.selected_key.as_ref() else { + let remaining = AVAILABILITY_DEBOUNCE.saturating_sub(since.elapsed()); + if !remaining.is_zero() || self.check_in_flight.is_some() { + ctx.request_repaint_after(remaining.max(AVAILABILITY_DEBOUNCE / 4)); + return AppAction::None; + } + let label = label.clone(); + self.check_availability(label) + } + + fn check_availability(&mut self, label: String) -> AppAction { + let Some(identity_id) = self + .selected_qualified_identity + .as_ref() + .map(|identity| identity.identity.id()) + else { return AppAction::None; }; - let dpns_name_input = RegisterDpnsNameInput { - qualified_identity: qualified_identity.clone(), - name_input: self.name_input.trim().to_string(), + self.availability = Availability::Row { + label: label.clone(), + row: AvailabilityRow::Checking, }; + self.check_in_flight = Some(label.clone()); + AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::CheckUsernameAvailability { identity_id, label }, + )) + } - AppAction::BackendTask(BackendTask::IdentityTask(IdentityTask::RegisterDpnsName( - dpns_name_input, - ))) + fn payment_review(&self) -> Option { + let availability = self.current_availability()?; + if !availability.allows_registration() { + return None; + } + Some(RegistrationReview { + label: self.label().to_owned(), + identity_id: self.selected_qualified_identity.as_ref()?.identity.id(), + network: self.app_context.network, + needs_vote: availability.needs_vote(), + registration_fee: self.registration_fee(), + contest_fee: if availability.needs_vote() { + self.contest_fee() + } else { + 0 + }, + }) } - /// Dispatch the registration and raise the Bucket A blocking overlay. - /// - /// The overlay is raised only when a real task is produced (an identity and a - /// signing key are selected), so a no-op click never strands a block. The - /// full-window block is the in-progress feedback that replaces the old banner - /// and prevents a second submit while the first is in flight. + fn review_is_current(&self) -> bool { + self.review.is_some() && self.review == self.payment_review() + } + + fn continue_clicked(&mut self) { + let Some(review) = self.payment_review() else { + return; + }; + let needs_vote = review.needs_vote; + self.review = Some(review); + if !needs_vote { + self.step = Step::Confirm; + return; + } + let durations = contest_durations( + self.app_context.network, + self.app_context.sdk_platform_version(), + ); + let lines = username_copy::consent_lines( + self.label(), + durations.total, + durations.join, + self.contest_fee(), + ); + self.consent_dialog = Some( + ConfirmationDialog::new( + username_copy::consent_title(self.label()), + lines.join("\n\n"), + ) + .confirm_text(Some("I understand, continue")) + .cancel_text(Some("Choose another name")), + ); + } + + /// Dispatch the registration and raise the blocking overlay. fn begin_registration(&mut self, ctx: &Context) -> AppAction { - let action = self.register_dpns_name_clicked(); - if matches!(action, AppAction::BackendTask(_)) { - self.register_dpns_name_status = RegisterDpnsNameStatus::WaitingForResult; - self.raise_progress_overlay(ctx); + if self.step != Step::Confirm { + return AppAction::None; } - action + if !self.review_is_current() { + self.on_label_changed(); + return AppAction::None; + } + let Some(review) = &self.review else { + return AppAction::None; + }; + let Some(identity) = self.selected_qualified_identity.as_ref() else { + return AppAction::None; + }; + let task = IdentityTask::RegisterDpnsName(RegisterDpnsNameInput { + qualified_identity: identity.clone(), + name_input: review.label.clone(), + approved_contest_fee: review.contest_fee, + signing_key_id: self.selected_key.as_ref().map(|key| key.id()), + }); + self.step = Step::Submitting; + self.raise_progress_overlay(ctx); + let task = BackendTask::IdentityTask(task); + let context = BackendTaskContext::for_dispatch_on(&task, self.app_context.network()); + self.registration_context = Some(context.clone()); + AppAction::BackendTaskWithContext { task, context } } fn raise_progress_overlay(&mut self, ctx: &Context) { + let title = format!("Registering @{name}.", name = self.label()); self.op_overlay.raise( ctx, - "Registering your username on the network.", - OverlayConfig::default(), + title, + OverlayConfig::default() + .with_description("Keep Dash Evo Tool open until this finishes."), ); } - /// Test seam: run the exact production overlay-raise the Register button uses, - /// so the Bucket A adoption (raise + guaranteed teardown) is exercisable in - /// kittests without funding an identity. Mirrors `force_input_for_test`. + /// Test seam: run the exact production overlay-raise the Pay button uses. #[doc(hidden)] pub fn raise_progress_overlay_for_test(&mut self, ctx: &Context) { self.raise_progress_overlay(ctx); } - pub fn show_success(&mut self, ui: &mut Ui) -> AppAction { - let Some(outcome) = self.registration_outcome else { - return AppAction::None; - }; - let success_message = match outcome { - DpnsRegistrationOutcome::Registered => { - "Your username is registered. You can use it now." - } - DpnsRegistrationOutcome::PendingCommunityVote => { - "Your username request was submitted. Other people can also request this name, so the community will vote on who receives it. Check the Pending label on your identity for updates." - } - }; - let action = crate::ui::helpers::show_success_screen_with_info( - ui, - success_message.to_string(), - vec![ - ("Back".to_string(), AppAction::PopScreenAndRefresh), - ( - "Register another name".to_string(), - AppAction::Custom("register_another".to_string()), - ), - ], - None, - ); - - // Handle the custom action to reset the form - if let AppAction::Custom(ref s) = action - && s == "register_another" - { - self.name_input = String::new(); - self.register_dpns_name_status = RegisterDpnsNameStatus::NotStarted; - self.completed_fee_result = None; - self.registration_outcome = None; - return AppAction::None; - } + /// Test seam: press Pay, dispatching the registration and raising the overlay. + #[doc(hidden)] + pub fn begin_registration_for_test(&mut self, ctx: &Context) -> AppAction { + self.begin_registration(ctx) + } - action + /// Test seam: type `label` as if the user had entered it. + #[doc(hidden)] + pub fn type_label_for_test(&mut self, label: &str) { + self.name_input = label.to_owned(); + self.on_label_changed(); } -} -impl ScreenLike for RegisterDpnsNameScreen { - fn display_message(&mut self, _message: &str, message_type: MessageType) { - // Banner display is handled globally by AppState; this is only for side-effects. - // Tear down the blocking overlay on the error terminal path so a - // failed registration can never hard-lock the window. - if matches!(message_type, MessageType::Error | MessageType::Warning) { - self.op_overlay.take_and_clear(); - self.register_dpns_name_status = RegisterDpnsNameStatus::Error; - } + /// Test seam: the checked label as if the debounce had elapsed. + #[doc(hidden)] + pub fn flush_debounce_for_test(&mut self) -> AppAction { + let label = self.label().to_owned(); + self.check_availability(label) } - fn display_task_result(&mut self, backend_task_success_result: BackendTaskSuccessResult) { - // Tear down the blocking overlay on the success terminal path. - if let BackendTaskSuccessResult::RegisteredDpnsName { - outcome, - fee_result, - } = backend_task_success_result - { - self.op_overlay.take_and_clear(); - self.completed_fee_result = Some(fee_result); - self.registration_outcome = Some(outcome); - self.register_dpns_name_status = RegisterDpnsNameStatus::Complete; - } + /// Test seam: move to the confirm step for the typed label. + #[doc(hidden)] + pub fn open_confirm_for_test(&mut self) { + self.review = self.payment_review(); + self.step = Step::Confirm; } - fn ui(&mut self, ui: &mut egui::Ui) -> AppAction { - let ctx = ui.ctx().clone(); - let ctx = &ctx; - // Build breadcrumbs based on where we came from - let breadcrumbs = match self.source { - RegisterDpnsNameSource::Dpns => vec![ - ( - "DPNS", - AppAction::SetMainScreen( - crate::ui::RootScreenType::RootScreenDPNSActiveContests, - ), - ), - ("Register Name", AppAction::None), - ], - RegisterDpnsNameSource::Identities => vec![ - ("Identities", AppAction::OpenIdentityPicker), - ("Register Name", AppAction::None), - ], - }; + /// Test seam: whether the flow is on the confirm step. + #[doc(hidden)] + pub fn is_confirming_for_test(&self) -> bool { + self.step == Step::Confirm + } - let mut action = add_top_panel(ui, &self.app_context, breadcrumbs, vec![]); + fn render_choose(&mut self, ui: &mut Ui) -> AppAction { + let mut action = AppAction::None; + let dark_mode = ui.style().visuals.dark_mode; + let has_names = self + .selected_qualified_identity + .as_ref() + .is_some_and(|qi| !qi.dpns_names.is_empty()); + ui.heading(if has_names { + "Get another username" + } else { + "Get a username" + }); + ui.label( + RichText::new(format!( + "For {identity}. People will use it to find and pay you. You can't change a username later.", + identity = self.identity_label() + )) + .color(DashColors::text_secondary(dark_mode)), + ); + ui.add_space(12.0); + + ui.label(RichText::new("Username").strong()); + let edit = ui + .horizontal(|ui| { + ui.label("@"); + let response = ui.text_edit_singleline(&mut self.name_input); + ui.label(".dash"); + response + }) + .inner; + if edit.changed() { + self.on_label_changed(); + } + action |= self.poll_debounce(ui.ctx()); + + let label = self.label().to_owned(); + if !label.is_empty() { + ui.add_space(6.0); + render_format_checks(ui, &label, dark_mode); + if let Availability::Row { + label: checked, + row, + } = &self.availability + && checked == &label + { + let row = row.clone(); + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + let (tone, text) = availability_line(&label, &row); + status_line(ui, tone, &text, dark_mode); + if row == AvailabilityRow::CantCheck && ui.button("Try again").clicked() { + action |= self.check_availability(label.clone()); + } + }); + if offers_suggestions(&row) { + let suggestions = suggest_uncontested(&label); + if !suggestions.is_empty() { + ui.horizontal_wrapped(|ui| { + ui.label("Try one without a vote:"); + for suggestion in suggestions { + if ui.button(format!("@{suggestion}")).clicked() { + self.name_input = suggestion; + self.on_label_changed(); + } + } + }); + } + } + } + } - // Use the appropriate left panel highlight based on source - let root_screen = match self.source { - RegisterDpnsNameSource::Dpns => crate::ui::RootScreenType::RootScreenDPNSActiveContests, - RegisterDpnsNameSource::Identities => crate::ui::RootScreenType::RootScreenIdentityHub, - }; - action |= add_left_panel(ui, &self.app_context, root_screen); + ui.add_space(10.0); + egui::CollapsingHeader::new("Username rules") + .default_open(false) + .show(ui, |ui| { + for rule in USERNAME_RULES { + ui.label(format!("• {rule}")); + } + }); - // Don't show the tools/dpns subscreen chooser panels for this screen + ui.add_space(12.0); + ui.horizontal(|ui| { + if ComponentStyles::add_secondary_button(ui, "Cancel", dark_mode).clicked() { + action |= AppAction::PopScreen; + } + let can_continue = self + .current_availability() + .is_some_and(UsernameAvailability::allows_registration); + if ComponentStyles::add_primary_button_enabled(ui, can_continue, "Continue") + .disabled_tooltip("Choose an available username to continue.") + .clicked() + && can_continue + { + self.continue_clicked(); + } + }); + action + } - action |= island_central_panel(ui, |ui| { - let mut inner_action = AppAction::None; + fn render_confirm(&mut self, ui: &mut Ui) -> AppAction { + if self.step == Step::Confirm && !self.review_is_current() { + self.on_label_changed(); + return self.render_choose(ui); + } + let Some(review) = self.review.clone() else { + return AppAction::None; + }; + let mut action = AppAction::None; + let dark_mode = ui.style().visuals.dark_mode; + let Some(identity) = self.selected_qualified_identity.clone() else { + return action; + }; + let name = review.label; + let needs_vote = review.needs_vote; + let registration_fee = review.registration_fee; + let total = registration_fee.saturating_add(review.contest_fee); + let balance = identity.identity.balance(); + + ui.heading("Review and pay"); + ui.add_space(8.0); + Frame::new() + .fill(DashColors::surface(dark_mode)) + .inner_margin(Margin::symmetric(12, 10)) + .corner_radius(6.0) + .show(ui, |ui| { + egui::Grid::new("username_confirm_rows") + .num_columns(2) + .spacing([24.0, 6.0]) + .show(ui, |ui| { + ui.label("Username"); + ui.horizontal(|ui| { + ui.label(RichText::new(format!("@{name}")).strong()); + if needs_vote { + crate::ui::components::pill::accent_pill( + ui, + "Community vote", + DashColors::WARNING_BRIGHT, + None, + ); + } + }); + ui.end_row(); + ui.label("Registration fee"); + ui.label(format!( + "about {fee}", + fee = format_credits_as_dash(registration_fee) + )); + ui.end_row(); + if needs_vote { + ui.label("Community vote fee (not returned)"); + ui.label(format_credits_as_dash(review.contest_fee)); + ui.end_row(); + } + ui.label(RichText::new("Total").strong()); + ui.label(RichText::new(format_credits_as_dash(total)).strong()); + ui.end_row(); + }); + ui.add_space(4.0); + ui.label( + RichText::new(format!( + "Paid from {identity}'s balance · Available {balance}", + identity = self.identity_label(), + balance = format_credits_as_dash(balance) + )) + .color(DashColors::text_secondary(dark_mode)), + ); + }); - egui::ScrollArea::vertical() - .auto_shrink([false; 2]) + if self.app_context.user_role().at_least(UserRole::Power) { + egui::CollapsingHeader::new("Advanced") + .default_open(false) .show(ui, |ui| { - if self.register_dpns_name_status == RegisterDpnsNameStatus::Complete { - inner_action |= self.show_success(ui); - return; + let document_type = self + .app_context + .dpns_contract + .document_type_cloned_for_name("domain") + .ok(); + if self.selected_key.is_none() { + self.selected_key = document_type + .as_ref() + .and_then(|doc_type| identity.document_signing_key(&doc_type.as_ref())) + .cloned(); } + action |= add_key_chooser_with_doc_type( + ui, + &self.app_context, + &identity, + &mut self.selected_key, + TransactionType::DocumentAction, + document_type.as_ref(), + ); + }); + } - ui.horizontal(|ui| { - ui.heading("Register DPNS Name"); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.checkbox(&mut self.show_advanced_options, "Advanced Options"); - }); - }); - ui.add_space(10.0); - - // If no identities loaded, give message - if self.qualified_identities.is_empty() { - ui.colored_label( - egui::Color32::DARK_RED, - "No identities loaded. Please load an identity first.", - ); - return; + if let Some(wallet) = &self.selected_wallet { + if !self.wallet_open_attempted { + if let Err(e) = try_open_wallet_no_password(&self.app_context, wallet) { + MessageBanner::set_global(ui.ctx(), &e, MessageType::Error) + .disable_auto_dismiss(); + } + self.wallet_open_attempted = true; + } + if wallet_needs_unlock(wallet) { + ui.add_space(8.0); + ui.horizontal_wrapped(|ui| { + status_line( + ui, + Tone::Caution, + "Unlock the wallet that holds this identity's keys to continue.", + dark_mode, + ); + if ui.button("Unlock wallet").clicked() { + self.wallet_unlock_popup.open(); + } + }); } + } - // Check if any identity has suitable private keys for DPNS registration - let has_suitable_keys = self.qualified_identities.iter().any(|qi| { - qi.private_keys.identity_public_keys().iter().any(|key_ref| { - let key = &key_ref.1.identity_public_key; - // DPNS registration requires Authentication keys - key.purpose() == Purpose::AUTHENTICATION - }) + let missing = total.saturating_sub(balance); + if missing > 0 { + ui.add_space(8.0); + ui.horizontal_wrapped(|ui| { + status_line( + ui, + Tone::Caution, + &username_copy::low_balance_line(balance, missing), + dark_mode, + ); + if ui.button("Top up").clicked() { + action |= AppAction::AddScreen( + ScreenType::TopUpIdentity(identity.clone()) + .create_screen(&self.app_context), + ); + } }); + } - if !has_suitable_keys { - ui.colored_label( - egui::Color32::DARK_RED, - "No identities with authentication private keys loaded. Please load identity keys to register a DPNS name.", - ); - return; + let synced = + self.app_context.connection_status().overall_state() == OverallConnectionState::Synced; + let locked = self + .selected_wallet + .as_ref() + .is_some_and(wallet_needs_unlock); + let can_pay = synced && missing == 0 && !locked && self.step == Step::Confirm; + let tooltip = if !synced { + "Available after sync finishes." + } else if locked { + "Unlock the wallet to continue." + } else { + "Add funds to this identity to continue." + }; + ui.add_space(12.0); + ui.horizontal(|ui| { + if ComponentStyles::add_secondary_button(ui, "Back", dark_mode).clicked() { + self.step = Step::Choose; } - - // Select the identity to register the name for - ui.heading("1. Select Identity"); - ui.add_space(5.0); - inner_action |= self.render_identity_id_selection(ui); - ui.add_space(5.0); - if let Some(identity) = &self.selected_qualified_identity { - ui.label(format!( - "Identity balance: {balance:.6}", - balance = identity.identity.balance() as f64 * 1e-11 - )); + let pay = ComponentStyles::add_primary_button_enabled( + ui, + can_pay, + username_copy::pay_label(&name, total, needs_vote), + ) + .disabled_tooltip(tooltip); + if pay.clicked() && can_pay { + action |= self.begin_registration(ui.ctx()); } + }); + action + } - ui.add_space(10.0); - ui.separator(); - ui.add_space(10.0); - - if self.selected_wallet.is_some() - && let Some(wallet) = &self.selected_wallet { - if !self.wallet_open_attempted { - if let Err(e) = try_open_wallet_no_password(&self.app_context, wallet) { - MessageBanner::set_global(ui.ctx(), &e, MessageType::Error) - .disable_auto_dismiss(); - } - self.wallet_open_attempted = true; - } - if wallet_needs_unlock(wallet) { - ui.add_space(10.0); - ui.colored_label( - egui::Color32::from_rgb(200, 150, 50), - "Wallet is locked. Please unlock to continue.", - ); - ui.add_space(8.0); - if ui.button("Unlock Wallet").clicked() { - self.wallet_unlock_popup.open(); - } - return; + fn render_done(&mut self, ui: &mut Ui, outcome: DpnsRegistrationOutcome) -> AppAction { + let mut action = AppAction::None; + let dark_mode = ui.style().visuals.dark_mode; + let name = self.label().to_owned(); + ui.vertical_centered(|ui| { + ui.add_space(40.0); + match outcome { + DpnsRegistrationOutcome::Registered => { + ui.heading(username_copy::registered_heading(&name)); + ui.label(username_copy::NAME_REGISTERED_LINE); + } + DpnsRegistrationOutcome::PendingCommunityVote => { + ui.heading(username_copy::request_sent_heading(&name)); + let request = self.selected_qualified_identity.as_ref().and_then(|qi| { + self.app_context + .username_requests_for(&qi.identity.id()) + .into_iter() + .find(|r| r.label == name) + }); + if let Some(request) = request + && let (Some(join_end), Some(end)) = (request.join_end, request.end) + { + ui.label(username_copy::request_schedule_line(join_end, end)); } + ui.label(username_copy::request_uncontested_line(&name)); + ui.label( + RichText::new(username_copy::REQUEST_RESULT_NOTE) + .color(DashColors::text_secondary(dark_mode)), + ); } - - // Input for the name - ui.heading("2. Enter the Name to Register:"); - ui.add_space(5.0); + } + ui.add_space(16.0); ui.horizontal(|ui| { - ui.label("Name (without \".dash\"):"); - ui.text_edit_singleline(&mut self.name_input); + if outcome == DpnsRegistrationOutcome::PendingCommunityVote + && let Some(identity) = &self.selected_qualified_identity + && ComponentStyles::add_secondary_button(ui, "View request status", dark_mode) + .clicked() + { + let status = ScreenType::UsernameRequestStatus { + identity_id: identity.identity.id(), + normalized_label: crate::model::dpns::normalize_dpns_label(&name), + } + .create_screen(&self.app_context); + action = AppAction::PopThenAddScreenToMainScreen( + RootScreenType::RootScreenIdentityHub, + status, + ); + } + if ComponentStyles::add_primary_button(ui, "Go to my identity").clicked() { + action = AppAction::SetMainScreenThenPopScreen( + RootScreenType::RootScreenIdentityHub, + ); + } }); + }); + action + } +} - // Display validation status and cost information - let name = self.name_input.trim(); - if !name.is_empty() { - ui.add_space(10.0); +/// Per-keystroke format checks, each as text plus icon. +fn render_format_checks(ui: &mut Ui, label: &str, dark_mode: bool) { + let validation = validate_dpns_name(label); + let length_ok = !matches!( + validation, + DpnsNameValidationResult::TooShort | DpnsNameValidationResult::TooLong + ); + let chars_ok = !matches!(validation, DpnsNameValidationResult::InvalidCharacter(_)); + let tone = |ok| if ok { Tone::Positive } else { Tone::Negative }; + status_line( + ui, + tone(length_ok), + username_copy::LENGTH_CHECK_LABEL, + dark_mode, + ); + status_line( + ui, + tone(chars_ok), + username_copy::CHARACTERS_CHECK_LABEL, + dark_mode, + ); + if matches!( + validation, + DpnsNameValidationResult::StartsWithHyphen | DpnsNameValidationResult::EndsWithHyphen + ) && let Some(message) = validation.error_message() + { + status_line(ui, Tone::Negative, &message, dark_mode); + } +} - // Validate the name - let validation_result = validate_dpns_name(name); +/// One status line: icon plus text, colored by tone. +pub(crate) fn status_line(ui: &mut Ui, tone: Tone, text: &str, dark_mode: bool) { + let color = match tone { + Tone::Neutral => DashColors::text_secondary(dark_mode), + Tone::Positive => DashColors::success_color(dark_mode), + Tone::Caution => DashColors::warning_color(dark_mode), + Tone::Negative => DashColors::error_color(dark_mode), + }; + ui.label(RichText::new(format!("{} {text}", tone.icon())).color(color)); +} - match validation_result { - DpnsNameValidationResult::Valid => { - ui.colored_label( - egui::Color32::DARK_GREEN, - "Valid name format", - ); +impl ScreenLike for RegisterDpnsNameScreen { + fn display_backend_task_error(&mut self, context: &BackendTaskContext, error: &TaskError) { + self.registration_error_handled = false; + if self.registration_context.as_ref() != Some(context) { + return; + } + self.registration_context = None; + self.op_overlay.take_and_clear(); + if let TaskError::UsernameNoLongerAvailable { availability } = error { + self.step = Step::Choose; + self.availability = Availability::Row { + label: self.label().to_owned(), + row: AvailabilityRow::Known(*availability), + }; + self.registration_error_handled = true; + } else if matches!( + error, + // An unconfirmed request may be paid for: Pay must not come back + // without a fresh availability check and a fresh review. + TaskError::UsernameRegistrationTermsChanged + | TaskError::UsernameRegistrationUnconfirmed { .. } + ) { + self.on_label_changed(); + } else { + self.step = Step::Confirm; + } + } - // Show contested status and cost if valid - if is_contested_name(&name.to_lowercase()) { - ui.colored_label( - egui::Color32::DARK_RED, - "This is a contested name.", - ); - ui.colored_label( - egui::Color32::DARK_RED, - // TODO(platform-4.2-dev-bump): derive from the active platform version's contested_document_vote_resolution_fund_required_amount once PV14 is live on a real network; see /data/artifacts/dash-evo-tool/2026-09-14/platform-4.2-dev-impact.md F4 - "Cost ≈ 0.2006 Dash", - ); - } else { - ui.colored_label( - egui::Color32::DARK_GREEN, - "This is not a contested name.", - ); - } - } - _ => { - if let Some(error_msg) = validation_result.error_message() { - ui.colored_label( - egui::Color32::RED, - error_msg, - ); - } - } + fn display_task_error(&mut self, error: &TaskError) -> bool { + if std::mem::take(&mut self.registration_error_handled) { + return true; + } + if matches!(error, TaskError::UsernameAvailabilityCheckFailed { .. }) + && self.step != Step::Submitting + && let Some(failed) = self.check_in_flight.take() + { + if let Availability::Row { label, row } = &mut self.availability + && *row == AvailabilityRow::Checking + && failed == *label + { + *row = AvailabilityRow::CantCheck; + } + return true; + } + false + } + + fn display_backend_task_result( + &mut self, + context: &BackendTaskContext, + result: BackendTaskSuccessResult, + ) { + if matches!(result, BackendTaskSuccessResult::RegisteredDpnsName { .. }) + && self.registration_context.as_ref() != Some(context) + { + return; + } + self.display_task_result(result); + } + + fn display_task_result(&mut self, result: BackendTaskSuccessResult) { + match result { + BackendTaskSuccessResult::RegisteredDpnsName { + outcome, + fee_result, + } => { + self.op_overlay.take_and_clear(); + self.registration_context = None; + self.completed_fee_result = Some(fee_result); + self.step = Step::Done(outcome); + } + BackendTaskSuccessResult::UsernameAvailability { + label, + availability, + } => { + if self.check_in_flight.as_ref() == Some(&label) { + self.check_in_flight = None; + } + if matches!(&self.availability, Availability::Row { label: current, .. } if *current == label) + { + self.availability = Availability::Row { + label, + row: AvailabilityRow::Known(availability), + }; } } + _ => {} + } + } - ui.add_space(10.0); + fn refresh(&mut self) { + self.reload_identity(); + } - // Fee estimation - let fee_estimator = self.app_context.fee_estimator(); - let estimated_fee = fee_estimator.estimate_document_create(); - let dark_mode = ui.style().visuals.dark_mode; + fn ui(&mut self, ui: &mut egui::Ui) -> AppAction { + let ctx = ui.ctx().clone(); + let identity_label = self.identity_label(); + let breadcrumbs = vec![ + ("Identities", AppAction::OpenIdentityPicker), + (identity_label.as_str(), AppAction::PopScreen), + ("Get a username", AppAction::None), + ]; + let mut action = add_top_panel(ui, &self.app_context, breadcrumbs, vec![]); + action |= add_left_panel(ui, &self.app_context, RootScreenType::RootScreenIdentityHub); - Frame::new() - .fill(DashColors::surface(dark_mode)) - .inner_margin(Margin::symmetric(10, 8)) - .corner_radius(5.0) + action |= island_central_panel(ui, |ui| { + let mut inner = AppAction::None; + egui::ScrollArea::vertical() + .auto_shrink([false; 2]) .show(ui, |ui| { - ui.horizontal(|ui| { - ui.label( - RichText::new("Estimated fee:") - .color(DashColors::text_secondary(dark_mode)) - .size(14.0), + let dark_mode = ui.style().visuals.dark_mode; + if let Step::Done(outcome) = self.step { + inner = self.render_done(ui, outcome); + return; + } + let Some(identity) = &self.selected_qualified_identity else { + status_line( + ui, + Tone::Negative, + "Load or create an identity first, then come back to get a username.", + dark_mode, ); - ui.label( - RichText::new(format_credits_as_dash(estimated_fee)) - .color(DashColors::text_primary(dark_mode)) - .size(14.0), + return; + }; + if !can_register_usernames( + identity, + dpns_signing_requirement(&self.app_context.dpns_contract), + ) { + status_line( + ui, + Tone::Negative, + username_copy::NEEDS_KEY_TO_REGISTER, + dark_mode, ); - }); + return; + } + inner = match self.step.clone() { + Step::Choose => self.render_choose(ui), + Step::Confirm | Step::Submitting => self.render_confirm(ui), + Step::Done(_) => AppAction::None, + }; }); + inner + }); - ui.add_space(10.0); - - // Check if identity has enough balance - let has_enough_balance = self - .selected_qualified_identity - .as_ref() - .map(|id| id.identity.balance() > estimated_fee) - .unwrap_or(false); - - // Register button - let mut new_style = (**ui.style()).clone(); - new_style.spacing.button_padding = egui::vec2(10.0, 5.0); - ui.set_style(new_style); - let name_is_valid = validate_dpns_name(self.name_input.trim()) == DpnsNameValidationResult::Valid; - let button_enabled = self.selected_qualified_identity.is_some() - && self.selected_key.is_some() - && name_is_valid - && has_enough_balance; - - let hover_text = if !has_enough_balance { - format!( - "Insufficient identity balance for fee (need at least {fee})", - fee = format_credits_as_dash(estimated_fee) - ) - } else if !name_is_valid { - "Please enter a valid name".to_string() - } else if self.selected_key.is_none() { - "Please select a signing key".to_string() - } else { - "Register DPNS name".to_string() - }; - - let button = egui::Button::new(RichText::new("Register Name").color(Color32::WHITE)) - .fill(if button_enabled { - DashColors::DASH_BLUE - } else { - Color32::GRAY - }) - .frame(true) - .corner_radius(3.0); - if ui.add_enabled(button_enabled, button) - .clickable_tooltip(&hover_text) - .disabled_tooltip(&hover_text) - .clicked() - { - inner_action = self.begin_registration(ui.ctx()); + if let Some(dialog) = self.consent_dialog.as_mut() { + match dialog.show(ui).inner.dialog_response { + Some(ConfirmationStatus::Confirmed) => { + self.consent_dialog = None; + if self.review_is_current() { + self.step = Step::Confirm; + } else { + self.on_label_changed(); + } + } + Some(ConfirmationStatus::Canceled) => { + self.consent_dialog = None; + self.review = None; + } + None => {} } + } - ui.add_space(10.0); - ui.separator(); - ui.add_space(10.0); - - // DPNS Name Constraints Explanation - ui.heading("DPNS Name Constraints:"); - ui.add_space(5.0); - ui.label(" • Minimum length: 3 characters"); - ui.label(" • Maximum length: 63 characters"); - ui.label(" • Allowed characters: letters (A-Z, case-insensitive), numbers (0-9), and hyphens (-)"); - ui.label(" • Cannot start or end with a hyphen (-)"); - ui.label(" • Names are case-sensitive"); - - ui.add_space(20.0); - - // Contested Names Explanation - ui.heading("Contested Names Info:"); - ui.add_space(5.0); - ui.label(" • To prevent name front-running, some names are contested and require a higher fee to register."); - ui.label(" • Masternodes vote whether or not to award contested names to contestants."); - ui.label(" • Contests last two weeks and new contenders can only join during the first week."); - ui.label(" • Contested names are those that are:"); - ui.label(" • Less than 20 characters long (i.e. “alice”, “quantumexplorer”)"); - ui.label(" • AND"); - ui.label(" • Contain no numbers or only contain the number(s) 0 and/or 1 (i.e. “bob”, “carol01”)"); - }); - inner_action - }); - - // Show wallet unlock popup if open if self.wallet_unlock_popup.is_open() && let Some(wallet) = &self.selected_wallet { - let result = self - .wallet_unlock_popup - .show(ctx, wallet, &self.app_context); - if result == WalletUnlockResult::Unlocked { - // Wallet unlocked successfully - } + self.wallet_unlock_popup + .show(&ctx, wallet, &self.app_context); } action } } -pub fn is_contested_name(name: &str) -> bool { - let length = name.len(); - if length >= 20 { - return false; +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn review_regression_unrelated_error_keeps_paid_registration_blocked() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let mut screen = RegisterDpnsNameScreen::new(&ctx, RegisterDpnsNameSource::Identities); + screen.step = Step::Submitting; + screen.raise_progress_overlay(ctx.egui_ctx()); + screen.display_message("Background refresh failed.", MessageType::Error); + assert_eq!(screen.step, Step::Submitting); + assert!(screen.op_overlay.is_some()); } - for c in name.chars() { - if c.is_ascii_digit() && c != '0' && c != '1' { - return false; - } + + #[test] + fn only_the_matching_registration_dispatch_releases_payment() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let mut screen = RegisterDpnsNameScreen::new(&ctx, RegisterDpnsNameSource::Identities); + let context = BackendTaskContext::for_dispatch(&BackendTask::ContestedResourceTask( + crate::backend_task::contested_names::ContestedResourceTask::QueryDPNSContests, + )); + screen.registration_context = Some(context.clone()); + screen.step = Step::Submitting; + screen.raise_progress_overlay(ctx.egui_ctx()); + let error = TaskError::UsernameNoLongerAvailable { + availability: UsernameAvailability::Locked, + }; + screen.display_backend_task_error(&BackendTaskContext::Unknown, &error); + assert!(!screen.display_task_error(&error)); + assert_eq!(screen.step, Step::Submitting); + assert!(screen.op_overlay.is_some()); + screen.display_backend_task_error(&context, &error); + assert!(screen.display_task_error(&error)); + assert_eq!(screen.step, Step::Choose); + assert!(screen.op_overlay.is_none()); + } + + /// USR-TC-035: on a protocol 14 network the confirm step charges the + /// 0.1 DASH community vote fee and adds it to the registration fee. + #[test] + fn confirm_fees_follow_the_network_protocol_version() { + let dir = tempfile::tempdir().expect("tempdir"); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let pv14 = dash_sdk::dpp::version::PlatformVersion::get(14).expect("PV14"); + ctx.sdk.store(Arc::new( + dash_sdk::SdkBuilder::new_mock() + .with_version(pv14) + .build() + .expect("mock sdk"), + )); + let screen = RegisterDpnsNameScreen::new(&ctx, RegisterDpnsNameSource::Identities); + assert_eq!(screen.contest_fee(), 10_000_000_000); + assert_eq!(format_credits_as_dash(screen.contest_fee()), "0.1 DASH"); } - true } diff --git a/src/ui/identity/settings.rs b/src/ui/identity/settings.rs index 68557fd16..4a0322c8c 100644 --- a/src/ui/identity/settings.rs +++ b/src/ui/identity/settings.rs @@ -1,7 +1,8 @@ //! Identity Hub — Settings tab. //! //! Two-column layout inside the central island: social profile (left) and -//! username + aliases (right), with a full-width `Advanced` expander below. +//! usernames + the device-only name (right), with a full-width `Advanced` +//! expander below. //! See design-spec §B.8 and dev-plan task T11. //! //! ## Backend integration @@ -13,8 +14,6 @@ //! `disabled_tooltip` explaining that the action is coming in a follow-up: //! //! - **Delete social profile** — no `DashPayTask::DeleteProfile` variant. -//! - **Add / remove alias** and **Make primary** — no `IdentityTask::AddAlias` -//! / `RemoveAlias` / `MakePrimaryAlias` variants. //! //! These appear as `Gated(missing_task)` non-interactive rows with the copy //! from design-spec §D (tooltip catalog entry #49). A TODO comment marks each @@ -27,15 +26,14 @@ use crate::backend_task::identity::IdentityTask; use crate::context::AppContext; use crate::model::qualified_identity::{IdentityType, QualifiedIdentity}; use crate::ui::MessageType; +use crate::ui::ScreenType; use crate::ui::components::component_trait::Component; use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; use crate::ui::components::message_banner::MessageBanner; use crate::ui::components::pill; use crate::ui::identity::IDENTITY_REMOVAL_BLOCKED_BY_STORAGE_UPDATE; use crate::ui::identity::identity_hero_card::HeroIdentityKind; -use crate::ui::identity::register_dpns_name_screen::RegisterDpnsNameSource; use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt, Spacing, Typography}; -use crate::ui::{RootScreenType, ScreenType}; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::platform_value::string_encoding::Encoding; use dash_sdk::platform::Identifier; @@ -73,15 +71,9 @@ const TIP_SAVE_NO_CHANGES: &str = "There are no changes to save."; const TIP_SAVE_INVALID: &str = "Fix the highlighted fields before saving."; const TIP_DELETE_PROFILE: &str = "Remove the display name, bio, and avatar from DashPay. Your identity, usernames, and \ balance stay."; -const TIP_PRIMARY_PILL: &str = "Your primary username is what people see by default."; -const TIP_MAKE_PRIMARY: &str = - "Use this username as your main one. Your old primary will become an alias."; -const TIP_REMOVE_ALIAS: &str = "Remove this alias. You will keep your other usernames."; -const TIP_ADD_ALIAS: &str = "Register another DPNS name that points to this identity."; const TIP_ADD_KEY: &str = "Register a new key for this identity. You will choose its purpose and type."; const TIP_MANAGE_KEYS: &str = "View this identity's keys and their security settings."; -const TIP_VIEW_USERNAMES: &str = "Open the complete list of your registered usernames."; const TIP_REFRESH: &str = "Fetch the latest state of this identity from the network."; const TIP_UNLOAD: &str = "Remove this identity from this device and permanently delete the private keys \ stored here. It remains on Dash Platform, but you will need your own backup to use it on this \ @@ -185,6 +177,8 @@ pub struct SettingsTab { /// Track whether we have loaded the cached profile for the current /// identity. Reset on identity change. profile_loaded: bool, + /// Usernames card renderer (holds the open QR code). + usernames_card: super::usernames_card::UsernamesCard, } impl SettingsTab { @@ -228,8 +222,7 @@ impl SettingsTab { // `set_max_width` on the text fields. ui.columns(2, |cols| { action |= self.render_social_profile(&mut cols[0], app_context, &identity); - action |= - self.render_username_and_aliases(&mut cols[1], app_context, &identity); + action |= self.render_usernames(&mut cols[1], app_context, &identity); }); ui.add_space(16.0); @@ -438,147 +431,16 @@ impl SettingsTab { action } - fn render_username_and_aliases( + fn render_usernames( &mut self, ui: &mut Ui, app_context: &Arc, identity: &QualifiedIdentity, ) -> AppAction { - let mut action = AppAction::None; let dark_mode = ui.ctx().global_style().visuals.dark_mode; - username_section_header(ui, identity.identity_type, dark_mode); - - // A DPNS name requested but not yet awarded — surfaced only when the - // identity owns no name yet. Best-effort read; a failure omits it. - let pending_username = app_context.pending_dpns_username_for_identity(identity); - - // Primary DPNS name. If none, show the pending indicator or the CTA card. - let primary = identity.dpns_names.first(); - if let Some(name) = primary { - ui.horizontal(|ui| { - ui.label( - RichText::new(format!("@{}", name.name)) - .monospace() - .color(DashColors::text_primary(dark_mode)), - ); - ui.add_space(4.0); - // Primary pill. - let pill = egui::Button::new(RichText::new("Primary").small()) - .fill(DashColors::DASH_BLUE) - .stroke(egui::Stroke::NONE); - ui.add(pill).info_tooltip(TIP_PRIMARY_PILL); - - ui.add_space(4.0); - if ui - .button("Copy") - .clickable_tooltip(format!("Copy @{} to your clipboard.", name.name)) - .clicked() - { - ui.ctx().copy_text(format!("@{}", name.name)); - } - }); - } else if let Some(pending) = &pending_username { - // Requested but not yet awarded — show the requested name with a - // "Pending" pill instead of the register CTA. - ui.horizontal(|ui| { - let name = crate::model::contested_name::sanitize_pending_username_for_display( - &pending.name, - ); - ui.label( - RichText::new(format!("@{name}")) - .monospace() - .color(DashColors::text_secondary(dark_mode)), - ); - ui.add_space(4.0); - pill::pending_username_pill(ui, pending); - }); - } else { - // Pick-a-username CTA. - egui::Frame::group(ui.style()) - .fill(DashColors::surface(dark_mode)) - .inner_margin(Margin::same(10)) - .corner_radius(egui::CornerRadius::same(6)) - .show(ui, |ui| { - ui.vertical(|ui| { - ui.label( - RichText::new("Pick a username") - .strong() - .color(DashColors::text_primary(dark_mode)), - ); - ui.add_space(6.0); - let reg = ComponentStyles::add_primary_button(ui, "Register a username") - .clickable_tooltip( - "Register a DPNS name and bind it to this identity.", - ); - if reg.clicked() { - action = AppAction::AddScreen( - ScreenType::RegisterDpnsName(RegisterDpnsNameSource::Identities) - .create_screen(app_context), - ); - } - }); - }); - } - - ui.add_space(6.0); - if ComponentStyles::add_secondary_button(ui, "View all usernames", dark_mode) - .clickable_tooltip(TIP_VIEW_USERNAMES) - .clicked() - { - action = usernames_screen_action(); - } - - ui.add_space(12.0); - + let action = self.usernames_card.show(ui, app_context, identity); ui.add_space(12.0); - - // Aliases block. Each secondary DPNS name appears with Make-primary + - // Remove actions; both are GATED because the backend variants do not - // exist yet. - section_heading(ui, "Aliases", dark_mode); - ui.label( - RichText::new("Extra usernames that also point to your identity.") - .small() - .color(DashColors::text_secondary(dark_mode)), - ); - ui.add_space(4.0); - - let aliases: Vec<_> = identity.dpns_names.iter().skip(1).cloned().collect(); - if aliases.is_empty() { - ui.label(RichText::new("No aliases yet.").color(DashColors::text_secondary(dark_mode))); - } else { - for alias in &aliases { - ui.horizontal(|ui| { - ui.label( - RichText::new(format!("@{}", alias.name)) - .monospace() - .color(DashColors::text_primary(dark_mode)), - ); - // TODO(identity-hub): wire once IdentityTask::MakePrimaryAlias exists. - let mp = ui - .add_enabled(false, egui::Button::new("Make primary")) - .disabled_tooltip(format!("{TIP_MAKE_PRIMARY} {GATED_COMING_SOON}")); - let _ = mp; - // TODO(identity-hub): wire once IdentityTask::RemoveAlias exists. - let rm = ui - .add_enabled(false, egui::Button::new("Remove")) - .disabled_tooltip(format!("{TIP_REMOVE_ALIAS} {GATED_COMING_SOON}")); - let _ = rm; - }); - } - } - - ui.add_space(6.0); - - // TODO(identity-hub): "Add an alias" requires IdentityTask::AddAlias, - // which does not exist yet. Render as disabled so Alex sees the - // affordance and learns it is planned. - let add = ui - .add_enabled(false, egui::Button::new("Add an alias")) - .disabled_tooltip(format!("{TIP_ADD_ALIAS} {GATED_COMING_SOON}")); - let _ = add; - action } @@ -1012,10 +874,6 @@ fn keys_screen_type(identity: &QualifiedIdentity) -> ScreenType { ScreenType::Keys(identity.clone()) } -fn usernames_screen_action() -> AppAction { - AppAction::SetMainScreenThenGoToMainScreen(RootScreenType::RootScreenDPNSOwnedNames) -} - // --------------------------------------------------------------------------- // Small layout helpers // --------------------------------------------------------------------------- @@ -1052,7 +910,7 @@ fn section_heading(ui: &mut Ui, text: &str, dark_mode: bool) { fn username_section_header(ui: &mut Ui, identity_type: IdentityType, dark_mode: bool) { let kind = HeroIdentityKind::from(identity_type); ui.horizontal(|ui| { - section_heading(ui, "Username", dark_mode); + section_heading(ui, "Usernames", dark_mode); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { pill::accent_pill( ui, @@ -1154,14 +1012,6 @@ mod tests { )); } - #[test] - fn usernames_action_opens_the_owned_names_screen() { - assert!(matches!( - usernames_screen_action(), - AppAction::SetMainScreenThenGoToMainScreen(RootScreenType::RootScreenDPNSOwnedNames) - )); - } - #[test] fn same_selected_identity_is_replaced_with_refreshed_key_state() { let stale = qualified_identity(); @@ -1199,7 +1049,7 @@ mod tests { .with_size(egui::vec2(900.0, 900.0)) .build_ui(|ui| { tab.render_social_profile(ui, &context, &identity); - tab.render_username_and_aliases(ui, &context, &identity); + tab.render_usernames(ui, &context, &identity); }); harness.run(); assert!(harness.query_by_label("Display name").is_some()); @@ -1454,7 +1304,7 @@ mod tests { }); harness.run(); - let heading = harness.get_by_label("Username").rect().center(); + let heading = harness.get_by_label("Usernames").rect().center(); let badge = harness.get_by_label("User identity").rect().center(); assert!( (heading.y - badge.y).abs() <= 1.0, @@ -1478,8 +1328,7 @@ mod tests { .build_ui(|ui| { let dark = ui.ctx().global_style().visuals.dark_mode; section_heading(ui, "Social profile", dark); - section_heading(ui, "Username", dark); - section_heading(ui, "Aliases", dark); + section_heading(ui, "Usernames", dark); sub_heading(ui, "Advanced", dark); }); harness.run(); @@ -1488,13 +1337,9 @@ mod tests { "Social profile heading must render", ); assert!( - harness.query_by_label("Username").is_some(), + harness.query_by_label("Usernames").is_some(), "Username heading must render", ); - assert!( - harness.query_by_label("Aliases").is_some(), - "Aliases heading must render", - ); assert!( harness.query_by_label("Advanced").is_some(), "Advanced sub-heading must render", diff --git a/src/ui/identity/username_copy.rs b/src/ui/identity/username_copy.rs new file mode 100644 index 000000000..50b74aa5e --- /dev/null +++ b/src/ui/identity/username_copy.rs @@ -0,0 +1,610 @@ +//! User-facing copy for identity usernames. +//! +//! Every string is a complete sentence with named placeholders, so each one +//! stays a single translation unit. Kept free of egui so the copy is unit-testable. + +use std::time::Duration; + +use chrono::{Local, TimeZone}; +use dash_sdk::dpp::identity::TimestampMillis; + +use crate::backend_task::error::USERNAME_AVAILABILITY_CHECK_FAILED; +use crate::model::dpns_usernames::{RequestPhase, TallyStanding, UsernameAvailability}; +use crate::model::fee_estimation::format_credits_as_dash; + +/// Result of the live availability check for the typed label. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AvailabilityRow { + /// The check is running. + Checking, + /// The network answered. + Known(UsernameAvailability), + /// The network could not be reached. + CantCheck, +} + +/// Visual tone of a status line, rendered as text plus icon. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Tone { + /// Neutral progress. + Neutral, + /// Good news. + Positive, + /// Needs attention but allowed. + Caution, + /// Not allowed. + Negative, +} + +impl Tone { + /// Icon shown before the text, so status never depends on color alone. + pub fn icon(self) -> &'static str { + match self { + Self::Neutral => "◌", + Self::Positive => "✓", + Self::Caution => "◷", + Self::Negative => "✗", + } + } +} + +/// Format a timestamp as a local calendar date, for example `Oct 5, 2026`. +pub fn format_date(ms: TimestampMillis) -> String { + local(ms).map_or_else(String::new, |t| t.format("%b %-d, %Y").to_string()) +} + +/// Format a timestamp as a local date and time, for example `Oct 5, 2026, 14:00`. +pub fn format_date_time(ms: TimestampMillis) -> String { + local(ms).map_or_else(String::new, |t| t.format("%b %-d, %Y, %H:%M").to_string()) +} + +fn local(ms: TimestampMillis) -> Option> { + Local.timestamp_millis_opt(i64::try_from(ms).ok()?).single() +} + +/// A contest duration in words: `14 days`, `1 day`, `45 minutes`, `2 hours`. +pub fn format_duration(duration: Duration) -> String { + const MINUTE: u64 = 60; + const HOUR: u64 = 60 * MINUTE; + const DAY: u64 = 24 * HOUR; + let secs = duration.as_secs(); + if secs >= DAY && secs.is_multiple_of(DAY) { + match secs / DAY { + 1 => "1 day".to_owned(), + days => format!("{days} days"), + } + } else if secs >= HOUR && secs.is_multiple_of(HOUR) { + match secs / HOUR { + 1 => "1 hour".to_owned(), + hours => format!("{hours} hours"), + } + } else { + match secs / MINUTE { + 1 => "1 minute".to_owned(), + minutes => format!("{minutes} minutes"), + } + } +} + +/// The single availability line for `name`, with its tone. +pub fn availability_line(name: &str, row: &AvailabilityRow) -> (Tone, String) { + match row { + AvailabilityRow::Checking => (Tone::Neutral, format!("Checking if @{name} is available…")), + AvailabilityRow::CantCheck => ( + Tone::Negative, + USERNAME_AVAILABILITY_CHECK_FAILED.to_owned(), + ), + AvailabilityRow::Known(availability) => match availability { + UsernameAvailability::Available => (Tone::Positive, format!("@{name} is available.")), + UsernameAvailability::NeedsVote => ( + Tone::Caution, + format!("@{name} is available, but it needs a community vote."), + ), + UsernameAvailability::Joinable { + contenders, + join_end, + } => { + let time = format_date_time(*join_end); + let text = if *contenders == 1 { + format!( + "1 other person already asked for @{name}. You can join the vote until {time}." + ) + } else { + format!( + "{contenders} other people already asked for @{name}. You can join the vote until {time}." + ) + }; + (Tone::Caution, text) + } + UsernameAvailability::Taken => ( + Tone::Negative, + format!("@{name} is already taken. Try another name."), + ), + UsernameAvailability::Locked => ( + Tone::Negative, + format!("@{name} can't be registered. A community vote locked this name for good."), + ), + UsernameAvailability::JoinClosed => ( + Tone::Negative, + format!("Others can no longer join the vote for @{name}. Try another name."), + ), + UsernameAvailability::AlreadyRequested => ( + Tone::Caution, + format!( + "You already asked for @{name}. Its status is on your identity's Usernames list." + ), + ), + }, + } +} + +/// Whether suggestions that avoid a vote are offered for this result. +pub fn offers_suggestions(row: &AvailabilityRow) -> bool { + matches!( + row, + AvailabilityRow::Known( + UsernameAvailability::NeedsVote + | UsernameAvailability::Joinable { .. } + | UsernameAvailability::Taken + ) + ) +} + +/// The four username rules, in display order. +pub const USERNAME_RULES: [&str; 4] = [ + "Between 3 and 63 characters.", + "Letters, numbers, and hyphens, with no hyphen at the start or end.", + "Capital letters are treated as lowercase.", + "Names shorter than 20 characters that use only letters, hyphens, 0, and 1 need a community vote. Adding a digit from 2 to 9 avoids the vote.", +]; + +/// Per-keystroke length check under the name field. +pub const LENGTH_CHECK_LABEL: &str = "Between 3 and 63 characters"; + +/// Per-keystroke character check under the name field. +pub const CHARACTERS_CHECK_LABEL: &str = "Only letters, numbers, and hyphens"; + +/// Why an identity without a usable key cannot register a username. +pub const NEEDS_KEY_TO_REGISTER: &str = "Add a key to this identity to register usernames."; + +/// What a registered name gives its owner: the done page and the won banner. +pub const NAME_REGISTERED_LINE: &str = "People can now find and pay you by this name."; + +/// Done-page heading for a name registered right away. +pub fn registered_heading(name: &str) -> String { + format!("You're @{name}") +} + +/// Done-page heading for a request that went to a community vote. +pub fn request_sent_heading(name: &str) -> String { + format!("Your request for @{name} is in") +} + +/// Done-page schedule of a request that went to a community vote. +pub fn request_schedule_line(join_end: TimestampMillis, end: TimestampMillis) -> String { + format!( + "Others can still ask for this name until {join}. The community vote ends around {end}.", + join = format_date_time(join_end), + end = format_date(end) + ) +} + +/// Done-page sentence on how a request nobody contests resolves. +pub fn request_uncontested_line(name: &str) -> String { + format!("If no one else asks and no one votes to lock it, @{name} becomes yours then.") +} + +/// Done-page note that the result arrives without the screen staying open. +pub const REQUEST_RESULT_NOTE: &str = + "We'll show the result on your identity's page. You don't need to keep this screen open."; + +/// Text of the one-time banner for a finished request, if it gets one. +pub fn outcome_banner_line(name: &str, phase: RequestPhase) -> Option { + match phase { + RequestPhase::Won => Some(format!("You're @{name}. {NAME_REGISTERED_LINE}")), + RequestPhase::Lost => Some(format!( + "@{name} went to someone else. You can choose a different username." + )), + RequestPhase::Locked => Some(format!( + "No one can register @{name} anymore. The community vote locked it." + )), + RequestPhase::NoWinner => Some(format!( + "The vote for @{name} ended without a winner. You can choose a different username." + )), + RequestPhase::Joinable | RequestPhase::Voting | RequestPhase::AwaitingOutcome => None, + } +} + +/// First sentence of the Home card for a request that is still open. +pub fn pending_notice_line( + name: &str, + phase: RequestPhase, + end: Option, +) -> String { + match (phase, end) { + (RequestPhase::AwaitingOutcome, _) => { + format!("@{name} is awaiting the voting result. View its status to check the outcome.") + } + (_, Some(end)) => format!( + "@{name} is waiting for a community vote. It ends around {date}.", + date = format_date(end) + ), + (_, None) => format!("@{name} is waiting for a community vote."), + } +} + +/// Usernames-card line under a registered name. +pub fn registered_on_line(at: TimestampMillis) -> String { + format!("Registered on {date}.", date = format_date(at)) +} + +/// Usernames-card line under a request that is still open, when there is +/// something to say about it. +pub fn pending_request_detail( + phase: RequestPhase, + join_end: Option, + end: Option, +) -> Option { + match (phase, join_end, end) { + (RequestPhase::Joinable, Some(join_end), _) => Some(format!( + "Others can ask for this name until {date}. Masternodes can already vote.", + date = format_date(join_end) + )), + (RequestPhase::AwaitingOutcome, _, _) => Some( + "The estimated voting period has ended. View the status to check the outcome." + .to_owned(), + ), + (_, _, Some(end)) => Some(format!( + "Voting ends around {date}.", + date = format_date(end) + )), + _ => None, + } +} + +/// Usernames-card line under a request that ended without the name. +pub fn finished_request_detail(phase: RequestPhase, decided_at: Option) -> String { + match phase { + RequestPhase::Locked => { + "More votes went to locking this name, so no one can register it.".to_owned() + } + RequestPhase::NoWinner => { + "The community vote ended without giving the name to anyone.".to_owned() + } + _ => decided_at.map_or_else( + || "The community vote ended.".to_owned(), + vote_ended_on_line, + ), + } +} + +/// The day a community vote ended. +pub fn vote_ended_on_line(at: TimestampMillis) -> String { + format!( + "The community vote ended on {date}.", + date = format_date(at) + ) +} + +/// Title of the community-vote consent dialog. +pub fn consent_title(name: &str) -> String { + format!("@{name} needs a community vote") +} + +/// Body sentences of the community-vote consent dialog. +pub fn consent_lines(name: &str, total: Duration, join: Duration, fee_credits: u64) -> [String; 5] { + let join_duration = format_duration(join); + let duration = format_duration(total); + let contest_fee = format_credits_as_dash(fee_credits); + [ + format!( + "Anyone can also ask for @{name} during the first {join_duration}. After that, only Dash masternode votes decide." + ), + format!( + "The vote ends after {duration}, even if no one else asks. You'll see the result on your identity's page." + ), + format!( + "The community vote fee is {contest_fee}. It isn't returned, whether you get the name or not." + ), + "If more votes go to locking the name, no one can register it, including you.".to_owned(), + "Until the vote ends, people can't find you by this name.".to_owned(), + ] +} + +/// Primary pay button label. +pub fn pay_label(name: &str, total_credits: u64, needs_vote: bool) -> String { + let total = format_credits_as_dash(total_credits); + if needs_vote { + format!("Pay {total} and request @{name}") + } else { + format!("Pay {total} and get @{name}") + } +} + +/// Low-balance warning on the confirm step. +pub fn low_balance_line(balance_credits: u64, missing_credits: u64) -> String { + let balance = format_credits_as_dash(balance_credits); + let missing = format_credits_as_dash(missing_credits); + format!("This identity has {balance}. Add at least {missing} to continue.") +} + +/// Status word for a request phase, as shown on rows and pages. +pub fn phase_label(phase: RequestPhase) -> &'static str { + match phase { + RequestPhase::Joinable => "Open for other requests", + RequestPhase::Voting => "Waiting for vote", + RequestPhase::AwaitingOutcome => "Awaiting result", + RequestPhase::Won => "Registered", + RequestPhase::Lost => "Went to someone else", + RequestPhase::Locked => "Locked for good", + RequestPhase::NoWinner => "No one got it", + } +} + +/// Timeline sentence for when the request was made. +pub fn requested_at_line(at: TimestampMillis) -> String { + format!("Requested on {date}.", date = format_date(at)) +} + +/// Timeline sentence for the window in which other requests can join. +pub fn joining_timeline_line(end: TimestampMillis, joining: bool) -> String { + if joining { + format!( + "Open for other requests until {date}.", + date = format_date_time(end) + ) + } else { + format!( + "Other requests could join until {date}.", + date = format_date(end) + ) + } +} + +/// Timeline sentence for when the community vote ends. +pub fn voting_timeline_line(end: TimestampMillis, phase: RequestPhase) -> String { + match phase { + RequestPhase::Joinable => format!( + "The community vote will end around {date}.", + date = format_date_time(end) + ), + RequestPhase::Voting => format!( + "The community vote ends around {date}.", + date = format_date_time(end) + ), + RequestPhase::AwaitingOutcome => format!( + "The estimated voting period ended around {date}.", + date = format_date(end) + ), + _ => vote_ended_on_line(end), + } +} + +/// Result sentence on the request timeline. +pub fn request_result_line(phase: RequestPhase) -> &'static str { + match phase { + RequestPhase::Joinable | RequestPhase::Voting => "Result: Not decided yet.", + RequestPhase::AwaitingOutcome => { + "Result: Awaiting confirmation. Refresh to check the outcome." + } + RequestPhase::Won => "Result: The name is yours.", + RequestPhase::Lost => "Result: The name went to someone else.", + RequestPhase::Locked => "Result: The name is locked for good.", + RequestPhase::NoWinner => "Result: No one got the name.", + } +} + +/// Tally row for votes to lock the name, on the read-only request status page. +pub const TALLY_LOCK_LABEL: &str = "Lock, so no one gets it"; + +/// Tally row for abstaining votes, on the read-only request status page. +pub const TALLY_ABSTAIN_LABEL: &str = "Abstain"; + +/// Second sentence of the Home request card. +pub fn standing_line(standing: TallyStanding, others: usize) -> &'static str { + match standing { + TallyStanding::LockAhead => { + "More votes are for locking this name right now. If that holds, no one gets it." + } + _ if others == 0 => "No one else has asked so far.", + TallyStanding::Leading => "You're leading right now.", + TallyStanding::Tied => { + "You're tied with another request. Ties go to the most recent request." + } + TallyStanding::Trailing => "Another request is leading.", + } +} + +/// The fixed "What happens next" rules on the request status page. +pub fn what_happens_next(name: &str) -> [String; 4] { + [ + format!( + "If you still have the most votes when the vote ends, @{name} becomes yours automatically." + ), + "If requests are tied at the end, the most recent request wins.".to_owned(), + format!( + "If more votes go to locking than to any request, no one can ever register @{name}." + ), + "The community vote fee isn't returned in any case.".to_owned(), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + const FORBIDDEN: [&str; 5] = ["DPNS", "contested", "alias", "deposit", "Contest"]; + + fn assert_plain(text: &str) { + for word in FORBIDDEN { + assert!(!text.contains(word), "{text:?} uses {word:?}"); + } + } + + /// The won banner and the done page tell the owner the same thing. + #[test] + fn the_won_banner_repeats_the_done_page_sentence() { + assert_eq!( + outcome_banner_line("ali", RequestPhase::Won).as_deref(), + Some("You're @ali. People can now find and pay you by this name.") + ); + assert_eq!( + NAME_REGISTERED_LINE, + "People can now find and pay you by this name." + ); + assert_eq!(outcome_banner_line("ali", RequestPhase::Voting), None); + } + + /// The card and the request timeline word the end of a vote identically. + #[test] + fn a_finished_vote_reads_the_same_on_the_card_and_the_timeline() { + let ended = format!("The community vote ended on {}.", format_date(0)); + assert_eq!(finished_request_detail(RequestPhase::Lost, Some(0)), ended); + assert_eq!(voting_timeline_line(0, RequestPhase::Lost), ended); + assert_eq!( + finished_request_detail(RequestPhase::Lost, None), + "The community vote ended." + ); + assert_eq!( + pending_request_detail(RequestPhase::Voting, None, None), + None + ); + assert_eq!( + pending_notice_line("ali", RequestPhase::Voting, None), + "@ali is waiting for a community vote." + ); + } + + #[test] + fn availability_rows_cover_every_state() { + // USR-TC-032 + let cases = [ + (AvailabilityRow::Checking, "Checking if @nova is available…"), + ( + AvailabilityRow::Known(UsernameAvailability::Available), + "@nova is available.", + ), + ( + AvailabilityRow::Known(UsernameAvailability::NeedsVote), + "@nova is available, but it needs a community vote.", + ), + ( + AvailabilityRow::Known(UsernameAvailability::Taken), + "@nova is already taken. Try another name.", + ), + ( + AvailabilityRow::Known(UsernameAvailability::Locked), + "@nova can't be registered. A community vote locked this name for good.", + ), + ( + AvailabilityRow::Known(UsernameAvailability::JoinClosed), + "Others can no longer join the vote for @nova. Try another name.", + ), + ( + AvailabilityRow::CantCheck, + "Availability can't be checked right now. Check your internet connection and try again.", + ), + ]; + for (row, expected) in cases { + let (_, text) = availability_line("nova", &row); + assert_eq!(text, expected); + assert_plain(&text); + } + } + + #[test] + fn joinable_row_has_singular_and_plural() { + // USR-TC-033 + let row = |contenders| { + availability_line( + "nova", + &AvailabilityRow::Known(UsernameAvailability::Joinable { + contenders, + join_end: 0, + }), + ) + .1 + }; + assert!(row(1).starts_with("1 other person already asked for @nova.")); + assert!(row(3).starts_with("3 other people already asked for @nova.")); + } + + #[test] + fn consent_uses_network_durations_and_fee() { + // USR-TC-034 + let lines = consent_lines( + "nova", + Duration::from_secs(14 * 86_400), + Duration::from_secs(7 * 86_400), + 20_000_000_000, + ); + assert!(lines[0].contains("during the first 7 days.")); + assert!(lines[1].contains("after 14 days,")); + assert!(lines[2].contains("0.2 DASH. It isn't returned")); + let testnet = consent_lines( + "nova", + Duration::from_secs(90 * 60), + Duration::from_secs(45 * 60), + 10_000_000_000, + ); + assert!(testnet[0].contains("first 45 minutes.")); + assert!(testnet[1].contains("after 90 minutes,")); + assert!(testnet[2].contains("0.1 DASH")); + for line in lines.iter().chain(&testnet) { + assert_plain(line); + } + } + + #[test] + fn rules_are_correct_and_plain() { + // USR-TC-039 + assert_eq!(USERNAME_RULES.len(), 4); + for rule in USERNAME_RULES { + assert_plain(rule); + assert!(!rule.contains("case-sensitive")); + } + } + + #[test] + fn durations_read_naturally() { + assert_eq!(format_duration(Duration::from_secs(86_400)), "1 day"); + assert_eq!(format_duration(Duration::from_secs(2 * 3_600)), "2 hours"); + assert_eq!(format_duration(Duration::from_secs(90 * 60)), "90 minutes"); + } + + #[test] + fn standing_line_matches_home_card_variants() { + // USR-TC-026 + assert_eq!( + standing_line(TallyStanding::Leading, 1), + "You're leading right now." + ); + assert_eq!( + standing_line(TallyStanding::Leading, 0), + "No one else has asked so far." + ); + assert_eq!( + standing_line(TallyStanding::Trailing, 2), + "Another request is leading." + ); + assert_eq!( + standing_line(TallyStanding::Tied, 1), + "You're tied with another request. Ties go to the most recent request." + ); + assert_eq!( + standing_line(TallyStanding::LockAhead, 0), + "More votes are for locking this name right now. If that holds, no one gets it." + ); + } + + #[test] + fn suggestions_only_for_vote_or_taken() { + assert!(offers_suggestions(&AvailabilityRow::Known( + UsernameAvailability::Taken + ))); + assert!(!offers_suggestions(&AvailabilityRow::Known( + UsernameAvailability::Locked + ))); + assert!(!offers_suggestions(&AvailabilityRow::CantCheck)); + } +} diff --git a/src/ui/identity/username_notices.rs b/src/ui/identity/username_notices.rs new file mode 100644 index 000000000..3f1127b37 --- /dev/null +++ b/src/ui/identity/username_notices.rs @@ -0,0 +1,257 @@ +//! Home notices for an identity's username requests: one card per pending +//! request and a one-time banner per finished outcome. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use dash_sdk::dpp::identity::accessors::IdentityGettersV0; +use dash_sdk::platform::Identifier; +use egui::{Frame, Id, Margin, RichText, Ui}; + +use crate::app::AppAction; +use crate::backend_task::BackendTask; +use crate::backend_task::identity::IdentityTask; +use crate::context::AppContext; +use crate::model::dpns_usernames::{RequestPhase, UsernameRequest}; +use crate::model::qualified_identity::QualifiedIdentity; +use crate::ui::ScreenType; +use crate::ui::identity::register_dpns_name_screen::status_line; +use crate::ui::identity::username_copy::{ + Tone, outcome_banner_line, pending_notice_line, phase_label, standing_line, +}; +use crate::ui::identity::usernames_card::register_action_for; +use crate::ui::theme::{ComponentStyles, DashColors}; + +/// Outcome banners shown in this session, so a banner marked seen stays up until dismissed. +const SESSION_BANNERS_ID: &str = "identity_username_outcome_banners"; + +/// Per-session banner state, kept in egui temp data. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +struct SessionBanners { + /// Shown this session; stays up after being recorded as seen. + shown: BTreeSet, + /// Dismissed this session; hidden even before the seen flag is stored. + dismissed: BTreeSet, +} + +/// Text of the one-time banner for a finished request, if it gets one. +pub fn outcome_banner_text(request: &UsernameRequest) -> Option { + outcome_banner_line(&request.label, request.phase) +} + +fn banner_key(identity_id: &Identifier, request: &UsernameRequest) -> String { + format!( + "{identity_id}:{}:{:?}", + request.normalized_label, request.phase + ) +} + +/// Render pending cards and outcome banners for `identity`. +pub fn render( + ui: &mut Ui, + app_context: &Arc, + identity: &QualifiedIdentity, +) -> AppAction { + let mut action = AppAction::None; + let dark_mode = ui.style().visuals.dark_mode; + let identity_id = identity.identity.id(); + let requests = app_context.username_requests_for(&identity_id); + let session_id = Id::new(SESSION_BANNERS_ID); + let mut session: SessionBanners = ui + .ctx() + .data(|data| data.get_temp(session_id)) + .unwrap_or_default(); + let before = session.clone(); + // Outcomes not yet recorded as seen. The mark is re-sent until the store + // confirms it, so a frame whose action is replaced by another dispatch + // (e.g. a profile load) cannot lose it; the context bounds the retries. + let mut unrecorded: Vec = Vec::new(); + + for request in &requests { + let Some(text) = outcome_banner_text(request) else { + continue; + }; + let key = banner_key(&identity_id, request); + let recorded = app_context.username_outcome_seen(&identity_id, request); + if !recorded { + unrecorded.push(request.clone()); + } + if session.dismissed.contains(&key) || (recorded && !session.shown.contains(&key)) { + continue; + } + session.shown.insert(key.clone()); + let tone = if request.phase == RequestPhase::Won { + Tone::Positive + } else { + Tone::Neutral + }; + notice_frame(ui, dark_mode, |ui| { + ui.horizontal_wrapped(|ui| { + status_line(ui, tone, &text, dark_mode); + if matches!(request.phase, RequestPhase::Lost | RequestPhase::NoWinner) + && ui.button("Choose another username").clicked() + { + action = register_action_for(app_context, identity_id); + } + if ui.button("Dismiss").clicked() { + session.shown.remove(&key); + session.dismissed.insert(key.clone()); + } + }); + }); + } + if !unrecorded.is_empty() + && matches!(action, AppAction::None) + && app_context.try_dispatch_username_seen_mark(&identity_id, ui.ctx().cumulative_pass_nr()) + { + action = mark_seen_action(identity_id, unrecorded); + } + if session != before { + ui.ctx() + .data_mut(|data| data.insert_temp(session_id, session)); + } + + for request in requests.iter().filter(|r| r.phase.is_pending()) { + notice_frame(ui, dark_mode, |ui| { + status_line(ui, Tone::Caution, phase_label(request.phase), dark_mode); + let first = pending_notice_line(&request.label, request.phase, request.end); + ui.label(RichText::new(first).strong()); + if request.phase != RequestPhase::AwaitingOutcome { + ui.label(standing_line( + request.tally.standing(), + request.tally.others.len(), + )); + } + if ComponentStyles::add_secondary_button(ui, "View status", dark_mode).clicked() { + action = AppAction::AddScreen( + ScreenType::UsernameRequestStatus { + identity_id, + normalized_label: request.normalized_label.clone(), + } + .create_screen(app_context), + ); + } + }); + } + action +} + +fn mark_seen_action(identity_id: Identifier, requests: Vec) -> AppAction { + AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::MarkUsernameOutcomesSeen { + identity_id, + requests, + }, + )) +} + +fn notice_frame(ui: &mut Ui, dark_mode: bool, add: impl FnOnce(&mut Ui)) { + Frame::new() + .fill(DashColors::surface(dark_mode)) + .inner_margin(Margin::symmetric(12, 10)) + .corner_radius(6.0) + .show(ui, add); + ui.add_space(8.0); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::backend_task::error::TaskError; + use crate::model::dpns::ContestDurations; + use std::time::Duration; + + #[test] + fn banners_exist_only_for_outcomes() { + let mut request = UsernameRequest::submitted( + "ali", + 0, + ContestDurations { + total: Duration::ZERO, + join: Duration::ZERO, + }, + None, + ); + assert!(outcome_banner_text(&request).is_none()); + request.phase = RequestPhase::Won; + assert_eq!( + outcome_banner_text(&request).as_deref(), + Some("You're @ali. People can now find and pay you by this name.") + ); + request.phase = RequestPhase::Locked; + assert_eq!( + outcome_banner_text(&request).as_deref(), + Some("No one can register @ali anymore. The community vote locked it.") + ); + } + + /// A store that keeps failing the "seen" write does not get a new task (or + /// a new error banner) on every frame: the next frame stays quiet, and the + /// retries stop for the session after a few failures. + #[test] + fn failing_seen_store_is_not_retried_every_frame() { + use crate::model::dpns_usernames::{SEEN_MARK_MAX_FAILURES, UsernameRequest}; + use crate::utils::egui_mpsc::SenderAsync; + use crate::wallet_backend::DetKv; + use crate::wallet_backend::kv_test_support::FailingKv; + + let dir = tempfile::tempdir().expect("tempdir"); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let store = Arc::new(FailingKv::default()); + ctx.set_det_kv_override_for_test(DetKv::from_store(store.clone())); + let identity = crate::context::test_support::bare_user_identity( + [0x61; 32].into(), + dash_sdk::dpp::dashcore::Network::Testnet, + ); + let id = identity.identity.id(); + let mut won = UsernameRequest::submitted( + "ali", + 0, + ContestDurations { + total: Duration::ZERO, + join: Duration::ZERO, + }, + None, + ); + won.phase = RequestPhase::Won; + ctx.store_username_requests(&id, vec![won]).expect("store"); + store.fail_next_puts_containing("det:username_outcomes_seen:", usize::MAX); + + let rt = tokio::runtime::Runtime::new().expect("runtime"); + let app_context = ctx.clone(); + let mut harness = egui_kittest::Harness::builder().build_ui_state( + move |ui, last: &mut Option| { + let action = render(ui, &app_context, &identity); + if !matches!(action, AppAction::None) { + *last = Some(action); + } + }, + None, + ); + let mut failures = 0; + for _ in 0..20 { + harness.step(); + let Some(AppAction::BackendTask(task)) = harness.state_mut().take() else { + continue; + }; + let (tx, _rx) = tokio::sync::mpsc::channel(8); + let sender = SenderAsync::new(tx, egui::Context::default()); + let result = rt.block_on(ctx.run_backend_task(task, sender)); + assert!(matches!(result, Err(TaskError::UsernameStorage { .. }))); + failures += 1; + // Right after a failure, the next frame must not dispatch again. + harness.step(); + assert!( + harness.state_mut().take().is_none(), + "a failing store was retried on the very next frame" + ); + // Skip the backoff so the test exercises the session cap. + ctx.username_cache_mut() + .seen_marks + .get_mut(&id) + .expect("attempts") + .expire_backoff_for_test(); + } + assert_eq!(failures, SEEN_MARK_MAX_FAILURES); + } +} diff --git a/src/ui/identity/username_request_screen.rs b/src/ui/identity/username_request_screen.rs new file mode 100644 index 000000000..aa658b09c --- /dev/null +++ b/src/ui/identity/username_request_screen.rs @@ -0,0 +1,321 @@ +//! Request status page: where one username request stands and what happens next. + +use std::sync::Arc; + +use dash_sdk::dpp::identity::accessors::IdentityGettersV0; +use dash_sdk::dpp::platform_value::string_encoding::Encoding; +use dash_sdk::platform::Identifier; +use egui::{RichText, Ui}; + +use crate::app::AppAction; +use crate::backend_task::error::TaskError; +use crate::backend_task::identity::IdentityTask; +use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; +use crate::context::AppContext; +use crate::model::dpns_usernames::{RequestPhase, TallyStanding, UsernameRequest}; +use crate::model::qualified_identity::QualifiedIdentity; +use crate::model::user_role::UserRole; +use crate::ui::components::left_panel::add_left_panel; +use crate::ui::components::styled::island_central_panel; +use crate::ui::components::top_panel::add_top_panel; +use crate::ui::identity::identity_pill::shorten_id; +use crate::ui::identity::register_dpns_name_screen::status_line; +use crate::ui::identity::username_copy::{ + TALLY_ABSTAIN_LABEL, TALLY_LOCK_LABEL, Tone, format_date_time, phase_label, what_happens_next, +}; +use crate::ui::identity::usernames_card::register_action_for; +use crate::ui::theme::{ComponentStyles, DashColors}; +use crate::ui::{RootScreenType, ScreenLike}; + +/// Pushed page showing the status of one of an identity's username requests. +pub struct UsernameRequestScreen { + pub app_context: Arc, + identity_id: Identifier, + normalized_label: String, + refresh_context: Option, + /// Whether a loaded node can vote; computed on arrival, not per frame. + can_vote: bool, + /// The identity's display name; computed on arrival, not per frame. + identity_label: String, +} + +impl UsernameRequestScreen { + pub fn new( + app_context: &Arc, + identity_id: Identifier, + normalized_label: String, + ) -> Self { + let mut screen = Self { + app_context: app_context.clone(), + identity_id, + normalized_label, + refresh_context: None, + can_vote: false, + identity_label: String::new(), + }; + screen.refresh(); + screen + } + + /// The identity this page belongs to. + pub fn identity_id(&self) -> Identifier { + self.identity_id + } + + /// The normalized label of the request shown. + pub fn normalized_label(&self) -> &str { + &self.normalized_label + } + + pub(crate) fn begin_refresh(&mut self) -> AppAction { + if self.refresh_context.is_some() { + return AppAction::None; + } + let task = BackendTask::IdentityTask(IdentityTask::RefreshMyUsernameRequests); + let context = BackendTaskContext::for_dispatch_on(&task, self.app_context.network()); + self.refresh_context = Some(context.clone()); + AppAction::BackendTaskWithContext { task, context } + } + + fn request(&self) -> Option { + self.app_context + .username_requests_for(&self.identity_id) + .into_iter() + .find(|r| r.normalized_label == self.normalized_label) + } + + fn load_identity_label(&self) -> String { + let identity = self + .app_context + .load_local_user_identities() + .unwrap_or_default() + .into_iter() + .find(|qi| qi.identity.id() == self.identity_id); + match identity { + Some(qi) => self.app_context.identity_display_label(&qi), + None => shorten_id(&self.identity_id.to_string(Encoding::Base58)), + } + } + + fn render_timeline(ui: &mut Ui, request: &UsernameRequest, dark_mode: bool) { + let (joining, voting, done) = match request.phase { + RequestPhase::Joinable => (true, false, false), + RequestPhase::Voting => (false, true, false), + RequestPhase::AwaitingOutcome => (false, false, false), + _ => (false, false, true), + }; + if let Some(at) = request.requested_at { + status_line( + ui, + Tone::Positive, + &super::username_copy::requested_at_line(at), + dark_mode, + ); + } + if let Some(join_end) = request.join_end { + let text = super::username_copy::joining_timeline_line(join_end, joining); + let tone = if joining { + Tone::Caution + } else { + Tone::Positive + }; + status_line(ui, tone, &text, dark_mode); + } + if let Some(end) = request.end { + let tone = if done { + Tone::Positive + } else if voting { + Tone::Caution + } else { + Tone::Neutral + }; + let text = super::username_copy::voting_timeline_line(end, request.phase); + status_line(ui, tone, &text, dark_mode); + } + let tone = match request.phase { + RequestPhase::Joinable | RequestPhase::Voting | RequestPhase::AwaitingOutcome => { + Tone::Neutral + } + RequestPhase::Won => Tone::Positive, + RequestPhase::Lost | RequestPhase::Locked | RequestPhase::NoWinner => Tone::Negative, + }; + let result = super::username_copy::request_result_line(request.phase); + status_line(ui, tone, result, dark_mode); + } + + fn render_tally(ui: &mut Ui, request: &UsernameRequest) { + let tally = &request.tally; + let standing = match tally.standing() { + TallyStanding::Leading => "Leading", + TallyStanding::Tied => "Tied", + TallyStanding::Trailing | TallyStanding::LockAhead => "", + }; + let lock_standing = if tally.standing() == TallyStanding::LockAhead { + "Leading" + } else { + "" + }; + egui::Grid::new("username_request_tally") + .num_columns(3) + .spacing([24.0, 4.0]) + .show(ui, |ui| { + ui.label("You"); + ui.label(standing); + ui.label(tally.you.to_string()); + ui.end_row(); + for (id, votes) in &tally.others { + ui.label(format!( + "Other request ({id})", + id = shorten_id(&id.to_string(Encoding::Base58)) + )); + ui.label(""); + ui.label(votes.to_string()); + ui.end_row(); + } + ui.label(TALLY_LOCK_LABEL); + ui.label(lock_standing); + ui.label(tally.lock.to_string()); + ui.end_row(); + ui.label(TALLY_ABSTAIN_LABEL); + ui.label(""); + ui.label(tally.abstain.to_string()); + ui.end_row(); + }); + } + + fn render_body(&mut self, ui: &mut Ui) -> AppAction { + let mut action = AppAction::None; + let dark_mode = ui.style().visuals.dark_mode; + if ui.link("‹ Back to profile").clicked() { + action = AppAction::PopScreen; + } + let Some(request) = self.request() else { + ui.label("This request is no longer listed for this identity."); + return action; + }; + let name = request.label.clone(); + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.heading(format!("Your request for @{name}")); + ui.label(phase_label(request.phase)); + }); + ui.label( + RichText::new(if request.tally.others.is_empty() { + "This name needs a community vote, so Dash masternodes decide who gets it." + } else { + "Other people asked for the same name, so Dash masternodes vote on who gets it." + }) + .color(DashColors::text_secondary(dark_mode)), + ); + ui.add_space(10.0); + Self::render_timeline(ui, &request, dark_mode); + + ui.add_space(12.0); + ui.horizontal(|ui| { + ui.label(RichText::new("How the vote is going").strong()); + let label = if self.refresh_context.is_some() { + "Refreshing…" + } else { + "Refresh status" + }; + if ui + .add_enabled(self.refresh_context.is_none(), egui::Button::new(label)) + .clicked() + { + action = self.begin_refresh(); + } + }); + Self::render_tally(ui, &request); + ui.label( + RichText::new(format!( + "Evonodes count as 4 votes. Votes can change until the vote ends. Last updated {time}.", + time = format_date_time(request.last_updated) + )) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); + + ui.add_space(12.0); + ui.label(RichText::new("What happens next").strong()); + for rule in what_happens_next(&name) { + ui.label(format!("• {rule}")); + } + + ui.add_space(12.0); + ui.horizontal(|ui| { + if ComponentStyles::add_secondary_button(ui, "Get a username without a vote", dark_mode) + .clicked() + { + action = register_action_for(&self.app_context, self.identity_id); + } + if self.can_vote && ui.link("Your nodes can vote on this name").clicked() { + self.app_context + .request_dpns_votes_for_name(self.normalized_label.clone()); + action = AppAction::SetMainScreenThenGoToMainScreen( + RootScreenType::RootScreenDPNSActiveContests, + ); + } + }); + action + } +} + +impl ScreenLike for UsernameRequestScreen { + fn refresh(&mut self) { + self.identity_label = self.load_identity_label(); + self.can_vote = self.app_context.user_role().at_least(UserRole::Power) + && self + .app_context + .load_local_qualified_identities() + .unwrap_or_default() + .iter() + .any(QualifiedIdentity::can_cast_masternode_vote); + } + + fn refresh_on_arrival(&mut self) { + self.refresh(); + } + + fn display_backend_task_error(&mut self, context: &BackendTaskContext, _error: &TaskError) { + if self.refresh_context.as_ref() == Some(context) { + self.refresh_context = None; + } + } + + fn display_backend_task_result( + &mut self, + context: &BackendTaskContext, + result: BackendTaskSuccessResult, + ) { + if self.refresh_context.as_ref() == Some(context) + && matches!( + result, + BackendTaskSuccessResult::MyUsernameRequestsRefreshed + ) + { + self.refresh_context = None; + } + } + + fn ui(&mut self, ui: &mut Ui) -> AppAction { + let identity_label = self.identity_label.clone(); + let name = self + .request() + .map_or_else(|| self.normalized_label.clone(), |r| r.label); + let crumb = format!("@{name}"); + let breadcrumbs = vec![ + ("Identities", AppAction::OpenIdentityPicker), + (identity_label.as_str(), AppAction::PopScreen), + (crumb.as_str(), AppAction::None), + ]; + let mut action = add_top_panel(ui, &self.app_context, breadcrumbs, vec![]); + action |= add_left_panel(ui, &self.app_context, RootScreenType::RootScreenIdentityHub); + action |= island_central_panel(ui, |ui| { + egui::ScrollArea::vertical() + .auto_shrink([false; 2]) + .show(ui, |ui| self.render_body(ui)) + .inner + }); + action + } +} diff --git a/src/ui/identity/usernames_card.rs b/src/ui/identity/usernames_card.rs new file mode 100644 index 000000000..aed0a52bf --- /dev/null +++ b/src/ui/identity/usernames_card.rs @@ -0,0 +1,475 @@ +//! Usernames card: every name an identity owns or asked for, in one list. + +use std::sync::Arc; + +use dash_sdk::dpp::identity::TimestampMillis; +use dash_sdk::dpp::identity::accessors::IdentityGettersV0; +use egui::{ColorImage, RichText, TextureHandle, Ui}; + +use crate::app::AppAction; +use crate::backend_task::BackendTask; +use crate::backend_task::identity::IdentityTask; +use crate::context::AppContext; +use crate::model::dpns::normalize_dpns_label; +use crate::model::dpns_usernames::{ + RequestPhase, UsernameRequest, can_register_usernames, dpns_signing_requirement, +}; +use crate::model::qualified_identity::QualifiedIdentity; +use crate::ui::MessageType; +use crate::ui::ScreenType; +use crate::ui::components::message_banner::MessageBanner; +use crate::ui::identity::funding_common::generate_qr_code_image; +use crate::ui::identity::register_dpns_name_screen::{RegisterDpnsNameSource, status_line}; +use crate::ui::identity::username_copy::{ + NEEDS_KEY_TO_REGISTER, Tone, finished_request_detail, pending_request_detail, phase_label, + registered_on_line, +}; +use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; + +/// One row of the card, in display order. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum UsernameRow { + /// A registered name. + Active { + name: String, + /// Shown as the identity's main name. + is_main: bool, + /// Whether the `Main` badge appears (only with more than one name). + show_main_badge: bool, + acquired_at: TimestampMillis, + }, + /// A request still in its community vote. + Pending(UsernameRequest), + /// A request that ended without the name, kept for 30 days. + Outcome(UsernameRequest), +} + +fn same_name(a: &str, b: &str) -> bool { + normalize_dpns_label(a) == normalize_dpns_label(b) +} + +/// Build the rows: main name, other names, pending requests, then finished outcomes. +pub fn username_rows( + identity: &QualifiedIdentity, + main: Option<&str>, + requests: &[UsernameRequest], +) -> Vec { + // Registered names, plus names won in a vote that the identity's stored + // names have not listed yet (they are re-read in the background). A win the + // stored names listed before and no longer do has left the identity. + let mut names: Vec<(String, TimestampMillis)> = identity + .dpns_names + .iter() + .filter(|n| !n.name.trim().is_empty()) + .map(|n| (n.name.clone(), n.acquired_at)) + .collect(); + for won in requests + .iter() + .filter(|r| r.phase == RequestPhase::Won && !r.reflected_in_owned_names) + { + if !names.iter().any(|(name, _)| same_name(name, &won.label)) { + names.push((won.label.clone(), won.decided_at.unwrap_or(0))); + } + } + let show_main_badge = names.len() > 1; + let mut rows: Vec = Vec::new(); + let main_index = main + .and_then(|main| names.iter().position(|(name, _)| name == main)) + .unwrap_or(0); + for (index, (name, acquired_at)) in names + .iter() + .enumerate() + .filter(|(i, _)| *i == main_index) + .chain(names.iter().enumerate().filter(|(i, _)| *i != main_index)) + { + rows.push(UsernameRow::Active { + name: name.clone(), + is_main: index == main_index, + show_main_badge, + acquired_at: *acquired_at, + }); + } + let owned = |label: &str| names.iter().any(|(name, _)| same_name(name, label)); + rows.extend( + requests + .iter() + .filter(|r| r.phase.is_pending() && !owned(&r.label)) + .cloned() + .map(UsernameRow::Pending), + ); + rows.extend( + requests + .iter() + .filter(|r| { + matches!( + r.phase, + RequestPhase::Lost | RequestPhase::Locked | RequestPhase::NoWinner + ) + }) + .cloned() + .map(UsernameRow::Outcome), + ); + rows +} + +/// Stateful renderer for the Usernames card (holds the open QR code). +#[derive(Default)] +pub struct UsernamesCard { + qr: Option<(String, TextureHandle)>, +} + +impl UsernamesCard { + /// Render the card for `identity`; returns any navigation the user asked for. + pub fn show( + &mut self, + ui: &mut Ui, + app_context: &Arc, + identity: &QualifiedIdentity, + ) -> AppAction { + let mut action = AppAction::None; + let dark_mode = ui.style().visuals.dark_mode; + let identity_id = identity.identity.id(); + let main = app_context.main_username(identity); + let requests = app_context.username_requests_for(&identity_id); + let rows = username_rows(identity, main.as_deref(), &requests); + let can_register = can_register_usernames( + identity, + dpns_signing_requirement(&app_context.dpns_contract), + ); + + if rows.is_empty() { + ui.label( + "This identity has no username yet. A username lets people pay you as @name instead of a long address.", + ); + ui.add_space(6.0); + action |= + get_username_button(ui, app_context, identity, can_register, "Get a username"); + return action; + } + + for row in rows { + ui.add_space(4.0); + match row { + UsernameRow::Active { + name, + is_main, + show_main_badge, + acquired_at, + } => { + ui.horizontal(|ui| { + ui.label(RichText::new(format!("@{name}")).strong()); + if is_main && show_main_badge { + crate::ui::components::pill::accent_pill( + ui, + "Main", + DashColors::DASH_BLUE, + None, + ); + } + ui.menu_button("•••", |ui| { + if ui.button("Copy username").clicked() { + ui.ctx().copy_text(format!("@{name}")); + ui.close(); + } + if ui.button("Show QR code").clicked() { + self.open_qr(ui.ctx(), &name); + ui.close(); + } + if !is_main && ui.button("Show as main").clicked() { + action = AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::SetMainUsername { + identity_id, + name: name.clone(), + }, + )); + ui.close(); + } + }) + .response + .clickable_tooltip(format!("More actions for @{name}")); + }); + if acquired_at > 0 { + ui.label( + RichText::new(registered_on_line(acquired_at)) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); + } + } + UsernameRow::Pending(request) => { + ui.horizontal(|ui| { + ui.label(RichText::new(format!("@{}", request.label)).strong()); + status_line(ui, Tone::Caution, phase_label(request.phase), dark_mode); + if ui.button("View status").clicked() { + action = request_status_action(app_context, identity, &request); + } + }); + if let Some(detail) = + pending_request_detail(request.phase, request.join_end, request.end) + { + ui.label( + RichText::new(detail) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); + } + } + UsernameRow::Outcome(request) => { + ui.horizontal(|ui| { + ui.label(RichText::new(format!("@{}", request.label)).strong()); + status_line(ui, Tone::Negative, phase_label(request.phase), dark_mode); + }); + ui.label( + RichText::new(finished_request_detail(request.phase, request.decided_at)) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); + ui.horizontal(|ui| { + if matches!(request.phase, RequestPhase::Lost | RequestPhase::NoWinner) + && ui.button("Choose another username").clicked() + { + action = register_action(app_context, identity); + } + if ui.button("Dismiss").clicked() { + action = AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::DismissUsernameRequest { + identity_id, + normalized_label: request.normalized_label.clone(), + }, + )); + } + }); + } + } + } + + ui.add_space(10.0); + action |= get_username_button( + ui, + app_context, + identity, + can_register, + "Get another username", + ); + ui.label( + RichText::new("Each username is a separate payment from this identity's balance.") + .small() + .color(DashColors::text_secondary(dark_mode)), + ); + + self.show_qr(ui); + action + } + + fn open_qr(&mut self, ctx: &egui::Context, name: &str) { + let image: ColorImage = match generate_qr_code_image(&format!("{name}.dash")) { + Ok(image) => image, + Err(error) => { + MessageBanner::set_global( + ctx, + "The QR code could not be created. Copy the username instead.", + MessageType::Error, + ) + .with_details(error); + return; + } + }; + let texture = ctx.load_texture("username_qr", image, egui::TextureOptions::NEAREST); + self.qr = Some((name.to_owned(), texture)); + } + + fn show_qr(&mut self, ui: &mut Ui) { + let Some((name, texture)) = &self.qr else { + return; + }; + let mut open = true; + let mut close = false; + egui::Window::new(format!("@{name}")) + .collapsible(false) + .resizable(false) + .open(&mut open) + .show(ui.ctx(), |ui| { + ui.image((texture.id(), egui::vec2(220.0, 220.0))); + if ui.button("Close").clicked() { + close = true; + } + }); + if !open || close { + self.qr = None; + } + } +} + +/// Open "Get a username" for `identity_id`, making it the selected identity. +pub(crate) fn register_action_for( + app_context: &Arc, + identity_id: dash_sdk::platform::Identifier, +) -> AppAction { + app_context.set_selected_identity(Some(identity_id)); + AppAction::AddScreen( + ScreenType::RegisterDpnsName(RegisterDpnsNameSource::Identities).create_screen(app_context), + ) +} + +fn register_action(app_context: &Arc, identity: &QualifiedIdentity) -> AppAction { + register_action_for(app_context, identity.identity.id()) +} + +fn request_status_action( + app_context: &Arc, + identity: &QualifiedIdentity, + request: &UsernameRequest, +) -> AppAction { + AppAction::AddScreen( + ScreenType::UsernameRequestStatus { + identity_id: identity.identity.id(), + normalized_label: request.normalized_label.clone(), + } + .create_screen(app_context), + ) +} + +fn get_username_button( + ui: &mut Ui, + app_context: &Arc, + identity: &QualifiedIdentity, + can_register: bool, + label: &str, +) -> AppAction { + let mut action = AppAction::None; + let reason = NEEDS_KEY_TO_REGISTER; + let clicked = ComponentStyles::add_primary_button_enabled(ui, can_register, label) + .disabled_tooltip(reason) + .clicked(); + if clicked && can_register { + action = register_action(app_context, identity); + } + if !can_register { + ui.horizontal(|ui| { + ui.label(reason); + if ui.link("Add a key").clicked() { + action = AppAction::AddScreen( + ScreenType::Keys(identity.clone()).create_screen(app_context), + ); + } + }); + } + action +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::dpns::ContestDurations; + use crate::model::qualified_identity::DPNSNameInfo; + use std::time::Duration; + + fn identity(names: &[&str]) -> QualifiedIdentity { + let mut identity = crate::context::test_support::bare_user_identity( + [1; 32].into(), + dash_sdk::dpp::dashcore::Network::Testnet, + ); + identity.dpns_names = names + .iter() + .map(|name| DPNSNameInfo { + name: (*name).to_owned(), + acquired_at: 1, + }) + .collect(); + identity + } + + fn request(label: &str, phase: RequestPhase) -> UsernameRequest { + let mut request = UsernameRequest::submitted( + label, + 0, + ContestDurations { + total: Duration::ZERO, + join: Duration::ZERO, + }, + None, + ); + request.phase = phase; + request + } + + fn row_label(row: &UsernameRow) -> String { + match row { + UsernameRow::Active { name, is_main, .. } => { + format!("{name}{}", if *is_main { "*" } else { "" }) + } + UsernameRow::Pending(r) => format!("{}?", r.label), + UsernameRow::Outcome(r) => format!("{}!", r.label), + } + } + + #[test] + fn rows_list_every_state_in_order() { + // USR-TC-020 + let requests = [ + request("ali", RequestPhase::Voting), + request("novak", RequestPhase::Joinable), + request("al", RequestPhase::Lost), + request("aa", RequestPhase::Locked), + ]; + let rows = username_rows(&identity(&["alice", "alice-design"]), None, &requests); + let labels: Vec<_> = rows.iter().map(row_label).collect(); + assert_eq!( + labels, + ["alice*", "alice-design", "ali?", "novak?", "al!", "aa!"] + ); + assert!(matches!( + rows[0], + UsernameRow::Active { + show_main_badge: true, + .. + } + )); + } + + /// A won name is listed while it waits to be read back into the identity's + /// names. Once those names listed it and no longer do, it has left the + /// identity and must not be offered as an owned, shareable username. + #[test] + fn win_that_left_the_identity_is_not_listed_as_owned() { + let mut won = request("carol", RequestPhase::Won); + let waiting = username_rows(&identity(&["alice"]), None, std::slice::from_ref(&won)); + assert_eq!( + waiting.iter().map(row_label).collect::>(), + ["alice*", "carol"] + ); + + won.reflected_in_owned_names = true; + let left = username_rows(&identity(&["alice"]), None, &[won]); + assert_eq!(left.iter().map(row_label).collect::>(), ["alice*"]); + } + + #[test] + fn show_as_main_reorders_and_single_name_has_no_badge() { + // USR-TC-021 + let rows = username_rows(&identity(&["a", "b"]), Some("b"), &[]); + assert_eq!(rows.iter().map(row_label).collect::>(), ["b*", "a"]); + let rows = username_rows(&identity(&["a"]), None, &[]); + assert!(matches!( + rows[0], + UsernameRow::Active { + show_main_badge: false, + .. + } + )); + } + + #[test] + fn owning_a_name_keeps_other_pending_requests() { + // USR-FR-001: an identity owning @a still lists its pending request @b. + let rows = username_rows( + &identity(&["a"]), + None, + &[ + request("b", RequestPhase::Voting), + request("c", RequestPhase::Joinable), + ], + ); + assert_eq!(rows.len(), 3); + } +} diff --git a/src/ui/masternodes/card.rs b/src/ui/masternodes/card.rs index 67559c7da..b8c94d1ee 100644 --- a/src/ui/masternodes/card.rs +++ b/src/ui/masternodes/card.rs @@ -2,7 +2,7 @@ //! `identity_picker_card.rs`'s visual language, adding voter-readiness, //! key-presence, and DPNS-status rows (colour always paired with text, NFR-6). -use crate::model::contested_name::MasternodeContestSummary; +use crate::model::contested_name::{MasternodeContestSummary, MasternodeVoteStateSummary}; use crate::model::fee_estimation::format_credits_as_dash; use crate::model::qualified_identity::{IdentityStatus, IdentityType, MasternodeKeyPresence}; use crate::ui::identity::identity_picker_card::{ @@ -55,11 +55,51 @@ pub fn voter_readiness_label(voting_present: bool) -> &'static str { } } -/// DPNS status line with count-first precedence (§10.1): open contests first -/// (actionable), then a pending scheduled vote, then none. +/// DPNS status line with count-first precedence (§10.1): open contests first, +/// then failed or pending scheduled votes, then none. pub fn dpns_status_line(summary: MasternodeContestSummary) -> String { - if summary.open_contest_count > 0 { - format!("{} contests to vote on", summary.open_contest_count) + if summary.vote_state == MasternodeVoteStateSummary::Unavailable { + if summary.open_contest_count == 0 { + "Voting status unavailable".to_owned() + } else if summary.open_contest_count == 1 { + "Vote state unavailable for 1 active contest".to_owned() + } else { + format!( + "Vote state unavailable for {count} active contests", + count = summary.open_contest_count + ) + } + } else if summary.open_contest_count > 0 { + let single = summary.open_contest_count == 1; + if summary.vote_state == MasternodeVoteStateSummary::Checking { + if single { + "Checking votes for 1 active contest".to_owned() + } else { + format!( + "Checking votes for {count} active contests", + count = summary.open_contest_count + ) + } + } else if summary.needs_vote_count == 0 { + "Votes cast in all active contests".to_owned() + } else if summary.needs_vote_count == 1 { + if single { + "1 active contest · 1 needs a vote".to_owned() + } else { + format!( + "{count} active contests · 1 needs a vote", + count = summary.open_contest_count + ) + } + } else { + format!( + "{contests} active contests · {needs_vote} need votes", + contests = summary.open_contest_count, + needs_vote = summary.needs_vote_count + ) + } + } else if summary.has_failed_scheduled_vote { + "Scheduled vote needs attention".to_string() } else if summary.has_scheduled_vote { "Vote scheduled".to_string() } else { @@ -368,9 +408,44 @@ mod tests { fn tc_fr3_09_dpns_open_contest_count() { let summary = MasternodeContestSummary { open_contest_count: 3, + needs_vote_count: 1, has_scheduled_vote: false, + ..Default::default() }; - assert_eq!(dpns_status_line(summary), "3 contests to vote on"); + assert_eq!( + dpns_status_line(summary), + "3 active contests · 1 needs a vote" + ); + } + + /// A single active contest reads in the singular in every state. + #[test] + fn dpns_status_line_is_singular_for_one_active_contest() { + for (vote_state, needs_vote_count, expected) in [ + ( + MasternodeVoteStateSummary::Unavailable, + 0, + "Vote state unavailable for 1 active contest", + ), + ( + MasternodeVoteStateSummary::Checking, + 0, + "Checking votes for 1 active contest", + ), + ( + MasternodeVoteStateSummary::Ready, + 1, + "1 active contest · 1 needs a vote", + ), + ] { + let summary = MasternodeContestSummary { + open_contest_count: 1, + needs_vote_count, + vote_state, + ..Default::default() + }; + assert_eq!(dpns_status_line(summary), expected, "{vote_state:?}"); + } } #[test] @@ -386,20 +461,74 @@ mod tests { // Both an open contest AND a scheduled vote present → count wins. let summary = MasternodeContestSummary { open_contest_count: 2, + needs_vote_count: 1, has_scheduled_vote: true, + ..Default::default() }; - assert_eq!(dpns_status_line(summary), "2 contests to vote on"); + assert_eq!( + dpns_status_line(summary), + "2 active contests · 1 needs a vote" + ); } #[test] fn dpns_scheduled_shown_only_when_no_open_contests() { let summary = MasternodeContestSummary { open_contest_count: 0, + needs_vote_count: 0, has_scheduled_vote: true, + ..Default::default() }; assert_eq!(dpns_status_line(summary), "Vote scheduled"); } + #[test] + fn terminal_scheduled_failure_needs_attention() { + let summary = MasternodeContestSummary { + has_scheduled_vote: false, + has_failed_scheduled_vote: true, + ..Default::default() + }; + + assert_eq!(dpns_status_line(summary), "Scheduled vote needs attention"); + } + + #[test] + fn dpns_status_reports_checking_instead_of_all_votes_cast() { + let summary = MasternodeContestSummary { + open_contest_count: 3, + vote_state: MasternodeVoteStateSummary::Checking, + ..Default::default() + }; + + assert_eq!( + dpns_status_line(summary), + "Checking votes for 3 active contests" + ); + } + + #[test] + fn dpns_status_reports_unavailable_instead_of_all_votes_cast() { + let summary = MasternodeContestSummary { + open_contest_count: 2, + vote_state: MasternodeVoteStateSummary::Unavailable, + ..Default::default() + }; + + assert_eq!( + dpns_status_line(summary), + "Vote state unavailable for 2 active contests" + ); + } + + #[test] + fn dpns_status_reports_unavailable_when_the_summary_read_failed() { + assert_eq!( + dpns_status_line(MasternodeContestSummary::unavailable()), + "Voting status unavailable" + ); + } + #[test] fn tc_fr3_04_05_badge_label_by_type() { let card = MasternodeCard::new( diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index 09caeccb3..de89449ec 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -6,9 +6,6 @@ use std::sync::Arc; -use chrono::{LocalResult, TimeZone, Utc}; -use chrono_humanize::HumanTime; -use dash_sdk::dpp::identity::TimestampMillis; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; #[cfg(test)] use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; @@ -16,19 +13,16 @@ use dash_sdk::dpp::platform_value::string_encoding::Encoding; use dash_sdk::platform::Identifier; use eframe::egui::{self, Color32, RichText, Ui}; +#[cfg(test)] use std::collections::BTreeMap; -use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; - use crate::app::AppAction; -use crate::backend_task::contested_names::ContestedResourceTask; use crate::backend_task::error::TaskError; use crate::backend_task::identity::{IdentityInputToLoad, IdentityLoadMode, IdentityTask}; -use crate::backend_task::{ - BackendTask, BackendTaskContext, BackendTaskSuccessResult, DPNSVoteOutcome, -}; +use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; use crate::context::AppContext; -use crate::model::contested_name::{ContestedName, MasternodeContestSummary}; +use crate::context::identity_load_registry::{IdentityLoadPhase, IdentityLoadToken}; +use crate::model::dpns_voting::operator::{ListMembership, NodeVoteRow, node_weight, time_left}; use crate::model::fee_estimation::format_credits_as_dash; use crate::model::legacy_recovery::RecoveryItem; use crate::model::qualified_identity::{IdentityType, MasternodeKeyPresence, QualifiedIdentity}; @@ -38,6 +32,9 @@ use crate::ui::components::component_trait::Component; use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; use crate::ui::components::legacy_recovery_section::host_offer; use crate::ui::components::password_input::PasswordInput; +use crate::ui::dpns::copy::{ + NOT_IN_MASTERNODE_LIST, NOT_VOTED_YET, changes_left_label, ends_in_label, voting_weight_label, +}; use crate::ui::identity::identity_picker_card::draw_type_badge; use crate::ui::identity::identity_pill::shorten_id; use crate::ui::identity::keys::key_info_screen::KeyInfoScreen; @@ -50,16 +47,10 @@ use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; use crate::ui::tokens::claim_tokens_screen::ClaimTokensScreen; use crate::ui::tokens::tokens_screen::IdentityTokenBasicInfo; use crate::ui::{MessageType, Screen, ScreenType}; +use crate::utils::time::now_ms; use crate::wallet_backend::IdentityKeyView; use crate::wallet_backend::secret_seam::SecretScheme; -/// §7 copy: shown when the node has no voting key loaded. Entering the key is -/// the only remedy on offer — a voting key held on a separate voter identity -/// that the node's own record does not link to cannot be restored from the -/// previous version's saved data (see issue #942). -const MISSING_VOTER_MESSAGE: &str = - "This node has no voting key loaded. Add its voting private key to cast votes."; - const REMOVE_MASTERNODE_CONFIRMATION: &str = "This removes the node and its voting identity, including their private keys, from this device. To load the node again, you need its ProTxHash and a backup of its private keys."; fn remove_node_action(identity_id: Identifier) -> AppAction { @@ -67,70 +58,6 @@ fn remove_node_action(identity_id: Identifier) -> AppAction { identity_id, })) } -/// §7 copy: shown when the node has a voter identity but no open contests. -const NO_OPEN_CONTESTS_MESSAGE: &str = - "There are no open name contests for this node to vote on right now."; - -/// The collapsible DPNS section header, with the open-contest count (TC-DPNS-02). -fn dpns_section_header(open_contest_count: usize) -> String { - format!("DPNS name contests to vote on ({open_contest_count})") -} - -/// Framing shown once above the per-contest vote controls, so a masternode -/// owner unfamiliar with DPNS contested voting understands what is being -/// decided. -const CONTEST_INTRO_MESSAGE: &str = "Several identities want the same name. Cast this node's vote to help decide who receives it, or to lock the name so no one gets it."; -/// Nudge shown under a contest that still has no vote picked, so the user knows -/// why the Cast votes button stays disabled. -const NO_SELECTION_HINT: &str = - "No vote picked yet. Choose Abstain, Lock, or a candidate above to set this node's vote."; -/// Tooltip on an enabled Cast votes button. -const CAST_ENABLED_HINT: &str = "Submit this node's vote for every name you picked."; -/// Tooltip on a disabled Cast votes button, explaining what unlocks it. -const CAST_DISABLED_HINT: &str = - "Pick Abstain, Lock, or a candidate for at least one name to enable this."; - -/// The full DPNS domain a contest is fighting over: DPNS names register under -/// `.dash`, so append it to the normalized label (shown bare elsewhere) to make -/// clear this is a real domain registration. -fn contest_display_name(normalized_name: &str) -> String { - format!("{normalized_name}.dash") -} - -/// A candidate choice label carrying the candidate's current vote tally, so the -/// voter sees the standing before picking. Phrased to avoid singular/plural -/// verb agreement for later translation. -fn candidate_choice_label(candidate_name: &str, votes: u32) -> String { - format!("Vote for {candidate_name} (votes so far: {votes})") -} - -/// Render data for one open contest, snapshotted before the choice-writing -/// loop so it does not borrow `open_contests` while `vote_selections` mutates. -struct ContestVoteRow { - name: String, - end_time: Option, - /// `(candidate id, candidate name, votes so far)` for each contestant. - candidates: Vec<(dash_sdk::platform::Identifier, String, u32)>, -} - -/// A one-line status for a contest: how many identities are competing and when -/// voting closes. Keeps the deadline absolute (ISO) plus a relative hint, and -/// degrades cleanly when the end time has not loaded yet. -fn contest_status_line(candidate_count: usize, end_time: Option) -> String { - let count = format!("Identities competing for this name: {candidate_count}."); - match end_time { - Some(end_time) => match Utc.timestamp_millis_opt(end_time as i64) { - LocalResult::Single(dt) => { - let iso = dt.format("%Y-%m-%d %H:%M:%S"); - let relative = HumanTime::from(dt); - format!("{count} Voting ends {iso} UTC ({relative}).") - } - _ => format!("{count} The voting deadline is unavailable."), - }, - None => format!("{count} The voting deadline is still loading."), - } -} - /// The fixed top→bottom section order. Actions must precede Keys (TC-FR5-01). pub const SECTION_ORDER: [&str; 5] = ["Header", "Actions", "Keys", "DPNS", "Remove"]; @@ -172,6 +99,8 @@ pub enum DetailOutcome { Back, /// Push a reused screen / navigate. Boxed because `AppAction` is large. Forward(Box), + /// Open Votes with this node as the session's node set (VOTE-FR-076). + VoteWithNode(Identifier), } enum KeyInfoOpenMode { @@ -186,21 +115,24 @@ pub struct MasternodeDetailView { node_id_hex_full: String, node_id_short: String, key_presence: MasternodeKeyPresence, - contest_summary: MasternodeContestSummary, - /// Open contests this node can still vote on (loaded at construction / - /// refresh). Active/open only — scheduled/past history lives on the DPNS - /// Scheduled Votes screen (§10.7). - open_contests: Vec, - /// Per-contest pending vote choice, keyed by normalized contested name. - vote_selections: BTreeMap, - pending_cast: Option, - /// The scoped, in-place "Add voting key" prompt (US-3 / §10.8) — distinct - /// from FR-4's load form. `Some` while the prompt is open. - voter_key_prompt: Option, remove_dialog: Option, + voter_key_prompt: Option, + /// The `Add voting key` merge this view dispatched and has not yet seen + /// finish. Gates Save so a re-click cannot discard the key typed into a + /// prompt the first Save already cleared, and so the wait is visible + /// instead of arriving as an `IdentityLoadInProgress` banner. + /// + /// The token names that one load: a later load of this node, dispatched + /// from anywhere, can never be mistaken for it. `None` when there is + /// nothing to gate — including a node another caller is already loading, + /// whose load owns the record and whose rejection the banner explains. + pending_voter_key_load: Option, /// The offer to restore keys this node left behind in the previous /// version's saved data (issue #889). recovery: LegacyRecoveryState, + /// Open contests with this node's choice, reloaded with stored screen data; + /// `None` when they could not be read. + node_votes: Option>, } #[cfg(test)] @@ -259,6 +191,17 @@ impl MasternodeDetailView { } } +/// The choice cell of a node vote row. +fn node_vote_choice_label(row: &NodeVoteRow) -> String { + match (row.state_known, row.choice) { + (false, _) => "Vote state unavailable".to_owned(), + (true, None) => NOT_VOTED_YET.to_owned(), + (true, Some(choice)) => { + crate::ui::dpns::copy::vote_choice_label(choice, row.contender_name.as_deref()) + } + } +} + impl MasternodeDetailView { pub(crate) fn accepts_recovery_result( &self, @@ -270,16 +213,10 @@ impl MasternodeDetailView { pub fn new(app_context: &Arc, identity: QualifiedIdentity) -> Self { let node_id_hex_full = identity.identity.id().to_string(Encoding::Hex); - let node_id_short = shorten_id(&node_id_hex_full); + let node_id_short = + crate::model::identity_name::masternode_label(identity.identity.id(), None); let key_presence = identity.masternode_key_presence(); - let voter_id = identity - .associated_voter_identity - .as_ref() - .map(|(voter, _)| voter.id()); - let contest_summary = app_context - .masternode_contest_summary(voter_id) - .unwrap_or_default(); - let open_contests = Self::load_open_contests(app_context, voter_id); + let identity_id = identity.identity.id(); let recovery = LegacyRecoveryState::new(app_context, identity.identity.id()); Self { app_context: app_context.clone(), @@ -287,13 +224,44 @@ impl MasternodeDetailView { node_id_hex_full, node_id_short, key_presence, - contest_summary, - open_contests, - vote_selections: BTreeMap::new(), - pending_cast: None, - voter_key_prompt: None, remove_dialog: None, + voter_key_prompt: None, + pending_voter_key_load: None, recovery, + node_votes: app_context + .dpns_node_votes(identity_id) + .inspect_err(|error| { + tracing::debug!(?error, "Could not list this node's votes"); + }) + .ok(), + } + } + + /// The outstanding `Add voting key` merge, so a rebuilt view can keep + /// gating it. Every backend result rebuilds this view; without carrying the + /// gate across, a load still in flight would silently re-offer Save. + pub(crate) fn pending_voter_key_load(&self) -> Option { + self.pending_voter_key_load + } + + /// Adopt the gate of the view this one replaces, for the same node. + pub(crate) fn adopt_pending_voter_key_load(&mut self, token: Option) { + self.pending_voter_key_load = token; + } + + /// Release the gate once the merge's own task reports it finished. Only the + /// phase decides: the load is outstanding from the moment it is dispatched, + /// before its task claims the identity, so neither a result arriving nor the + /// store having changed is a sound proxy. + fn reconcile_voter_key_load(&mut self) { + let Some(token) = self.pending_voter_key_load else { + return; + }; + let phase = self + .app_context + .identity_load_phase(&self.identity.identity.id(), token); + if !phase.is_some_and(IdentityLoadPhase::is_outstanding) { + self.pending_voter_key_load = None; } } @@ -307,9 +275,14 @@ impl MasternodeDetailView { self.recovery.absorb_result(ctx, result) } - /// Refresh stored data while preserving prompts, vote selections, and recovery state. + /// Refresh stored data while preserving prompts and recovery state. pub(crate) fn refresh_from_store(&mut self) { let node_id = self.identity.identity.id(); + self.node_votes = self + .app_context + .dpns_node_votes(node_id) + .inspect_err(|error| tracing::debug!(?error, "Could not reload node votes")) + .ok(); if let Ok(identities) = self.app_context.load_local_masternode_identities() && let Some(identity) = identities .into_iter() @@ -318,7 +291,6 @@ impl MasternodeDetailView { self.key_presence = identity.masternode_key_presence(); self.identity = identity; } - self.refresh_contests(); } /// Re-check recovery on arrival because a pushed Key Info screen may have restored keys. @@ -327,82 +299,18 @@ impl MasternodeDetailView { self.recovery.refresh_on_arrival(); } - fn cast_votes(&mut self, votes: Vec<(String, ResourceVoteChoice)>) -> AppAction { - let task = BackendTask::ContestedResourceTask(ContestedResourceTask::VoteOnDPNSNames( - votes, - vec![self.identity.clone()], - )); - let context = BackendTaskContext::for_dispatch(&task); - self.pending_cast = Some(context.clone()); - AppAction::BackendTaskWithContext { task, context } - } - - /// Retire unchanged, successful selections from this view's latest cast. - pub(crate) fn consume_cast_votes( - &mut self, - context: &BackendTaskContext, - results: &[DPNSVoteOutcome], - ) { - if self.pending_cast.as_ref() != Some(context) { - return; - } - self.pending_cast = None; - for (contested_name, choice, outcome) in results { - if outcome.is_ok() && self.vote_selections.get(contested_name) == Some(choice) { - self.vote_selections.remove(contested_name); - } - } - } - /// End this view's recovery operation when the failure that arrived is that /// operation's own — every error reaches whichever screen is visible. pub(crate) fn absorb_recovery_error(&mut self, context: &BackendTaskContext) { self.recovery.absorb_error(context); } - /// Load the contests this node can still vote on. Empty when the node has no - /// voting key (no voter id) or the read fails. - fn load_open_contests( - app_context: &Arc, - voter_id: Option, - ) -> Vec { - let Some(voter_id) = voter_id else { - return Vec::new(); - }; - app_context - .ongoing_contested_names() - .unwrap_or_default() - .into_iter() - .filter(|contest| contest.is_open_for_voter(&voter_id)) - .collect() - } - - /// Refresh the DPNS contest summary + open-contest list from the store. - fn refresh_contests(&mut self) { - let voter_id = self - .identity - .associated_voter_identity - .as_ref() - .map(|(voter, _)| voter.id()); - self.contest_summary = self - .app_context - .masternode_contest_summary(voter_id) - .unwrap_or_default(); - self.open_contests = Self::load_open_contests(&self.app_context, voter_id); - } - /// Build the network re-fetch dispatched by the detail Refresh button: - /// refresh this node's identity, plus a DPNS contests re-query - /// when the node has a voter identity that can vote. + /// refresh this node's identity. The result refreshes stored identity and vote rows. fn refresh_from_network(&self) -> AppAction { - let mut tasks = vec![BackendTask::IdentityTask(IdentityTask::RefreshIdentity( + let tasks = vec![BackendTask::IdentityTask(IdentityTask::RefreshIdentity( self.identity.clone(), ))]; - if self.identity.associated_voter_identity.is_some() { - tasks.push(BackendTask::ContestedResourceTask( - ContestedResourceTask::QueryDPNSContests, - )); - } AppAction::BackendTasks(tasks, crate::app::BackendTasksExecutionMode::Concurrent) } @@ -475,10 +383,6 @@ impl MasternodeDetailView { } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ComponentStyles::add_toolbar_button(ui, "Refresh", network_accent).clicked() { - // Re-read the local contest cache immediately (optimistic) - // AND dispatch a network re-fetch of this node plus the DPNS - // contests — Refresh must reach the network. - self.refresh_contests(); outcome = DetailOutcome::Forward(Box::new(self.refresh_from_network())); } }); @@ -496,8 +400,8 @@ impl MasternodeDetailView { outcome = DetailOutcome::Forward(Box::new(action)); } ui.add_space(12.0); - if let Some(action) = self.render_dpns_section(ui, dark_mode) { - outcome = DetailOutcome::Forward(Box::new(action)); + if let Some(node) = self.render_dpns_section(ui, dark_mode) { + outcome = DetailOutcome::VoteWithNode(node); } ui.add_space(12.0); if let Some(action) = self.render_remove_section(ui, dark_mode) { @@ -552,6 +456,11 @@ impl MasternodeDetailView { ui.ctx().copy_text(self.node_id_hex_full.clone()); } draw_type_badge(ui, self.badge_label(), dark_mode); + let weight = node_weight(self.identity.identity_type.into()); + ui.label( + RichText::new(voting_weight_label(weight)) + .color(DashColors::text_secondary(dark_mode)), + ); }); let balance = format_credits_as_dash(self.identity.identity.balance()); ui.label( @@ -756,6 +665,11 @@ impl MasternodeDetailView { action = Some(self.open_key_info_with_protection_prompt(&key)); } + if !self.identity.can_cast_masternode_vote() + && let Some(key_action) = self.render_missing_voter(ui, dark_mode) + { + action = Some(key_action); + } if let Some(approved) = self.render_recovery_section(ui) && let Some((task, context)) = self.recovery.restore(approved) { @@ -764,6 +678,96 @@ impl MasternodeDetailView { action } + fn render_missing_voter(&mut self, ui: &mut Ui, dark_mode: bool) -> Option { + let mut action = None; + ui.label( + RichText::new( + "This node has no voting key loaded. Add its voting private key to cast votes.", + ) + .color(DashColors::warning_color(dark_mode)), + ); + + self.reconcile_voter_key_load(); + if self.pending_voter_key_load.is_some() { + // Show the wait rather than re-offering Save: the key that went out + // with the first Save is still being applied. + ui.horizontal(|ui| { + ui.spinner(); + ui.add_enabled(false, egui::Button::new("Adding voting key…")); + }); + return None; + } + + match self.voter_key_prompt.as_mut() { + None => { + if ui.button("Add voting key").clicked() { + // Node context is already bound (`self.identity`) — the + // prompt only asks for the voting key, no ProTxHash re-entry. + self.voter_key_prompt = Some( + PasswordInput::new() + .with_hint_text("Voting private key (WIF or hex)") + .with_monospace(), + ); + } + } + Some(prompt) => { + prompt.show(ui); + ui.horizontal(|ui| { + if ui.button("Cancel").clicked() { + self.voter_key_prompt = None; + } + let has_key = !self + .voter_key_prompt + .as_ref() + .map(PasswordInput::is_empty) + .unwrap_or(true); + if ui.add_enabled(has_key, egui::Button::new("Save")).clicked() { + action = self.submit_voter_key(); + } + }); + } + } + action + } + + /// Close the `Add voting key` prompt, zeroizing the key typed into it. Called + /// when the Masternodes tab is left: the tab is a root screen that outlives + /// navigation, and an unsubmitted key must not. + pub fn clear_secrets(&mut self) { + self.voter_key_prompt = None; + } + + /// Merge a voting key into this node without replacing its other keys. + fn submit_voter_key(&mut self) -> Option { + let voting_key = self.voter_key_prompt.as_mut()?.take_secret(); + self.voter_key_prompt = None; + // Mark the dispatch before the task runs: the merge is outstanding from + // here, and until its task claims the identity nothing else records that. + self.pending_voter_key_load = self + .app_context + .mark_identity_load_submitted(self.identity.identity.id()); + let input = IdentityInputToLoad { + identity_id_input: self.node_id_hex_full.clone(), + identity_type: self.identity.identity_type, + alias_input: self.identity.alias.clone().unwrap_or_default(), + voting_private_key_input: voting_key, + owner_private_key_input: Secret::default(), + payout_address_private_key_input: Secret::default(), + keys_input: vec![], + derive_keys_from_wallets: false, + selected_wallet_seed_hash: None, + encryption_password: None, + // The backend preserves existing keys and their protection tier. + load_mode: IdentityLoadMode::MergeIntoExisting, + // Send the token with the load, so the task claims the record this + // view is waiting on — and so no other load can claim it. + load_token: self.pending_voter_key_load, + }; + Some(AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::LoadIdentity(input), + ))) + } + /// Render the offer at the foot of the keys section, returning the items the /// user approved this frame. fn render_recovery_section(&self, ui: &mut Ui) -> Option> { @@ -844,209 +848,56 @@ impl MasternodeDetailView { AppAction::AddScreen(Screen::KeyInfoScreen(screen.with_masternode_origin())) } - /// Render the collapsible DPNS voting section (collapsed by default, - /// open-contest count in the header). Inline voting reuses the existing - /// `vote_on_dpns_name` backend (locked decision #1 — not a deep-link). - fn render_dpns_section(&mut self, ui: &mut Ui, dark_mode: bool) -> Option { - // When the node has no voter key, the "Add voting key" CTA is - // the primary next step — render it above, outside the collapsed-by- - // default DPNS section, so it is visible without expanding anything. - // The empty DPNS section (no contests possible without a voter) is - // omitted in that state. - if self.identity.associated_voter_identity.is_none() { - return self.render_missing_voter(ui, dark_mode); - } - - let mut action = None; - let header = dpns_section_header(self.contest_summary.open_contest_count); - egui::CollapsingHeader::new(header) - .default_open(false) - .show(ui, |ui| { - if self.open_contests.is_empty() { - ui.label( - RichText::new(NO_OPEN_CONTESTS_MESSAGE) - .color(DashColors::text_secondary(dark_mode)), - ); - } else { - action = self.render_vote_table(ui, dark_mode); - } - }); - action - } - - /// Missing-voter-identity state (US-3 / §10.9): an actionable message plus a - /// scoped in-place `Add voting key` prompt — never the raw error, never - /// FR-4's load form. - fn render_missing_voter(&mut self, ui: &mut Ui, dark_mode: bool) -> Option { - let mut action = None; - ui.label(RichText::new(MISSING_VOTER_MESSAGE).color(DashColors::warning_color(dark_mode))); - - match self.voter_key_prompt.as_mut() { + /// `This node's votes`, its masternode-list status and `Vote with this + /// node` (VOTE-FR-076). Returns the node to vote with when clicked. + fn render_dpns_section(&mut self, ui: &mut Ui, dark_mode: bool) -> Option { + let node = self.identity.identity.id(); + ui.label(RichText::new("This node's votes").strong()); + let membership = match self.app_context.masternode_list_membership(node) { + ListMembership::Listed => "In the masternode list.", + ListMembership::NotListed => NOT_IN_MASTERNODE_LIST, + ListMembership::Unknown => "Masternode list membership unknown.", + }; + ui.label(RichText::new(membership).color(DashColors::text_secondary(dark_mode))); + match &self.node_votes { None => { - if ui.button("Add voting key").clicked() { - // Node context is already bound (`self.identity`) — the - // prompt only asks for the voting key, no ProTxHash re-entry. - self.voter_key_prompt = Some( - PasswordInput::new() - .with_hint_text("Voting private key (WIF or hex)") - .with_monospace(), - ); - } + ui.label("This node's votes could not be read. Refresh to try again."); } - Some(prompt) => { - prompt.show(ui); - ui.horizontal(|ui| { - if ui.button("Cancel").clicked() { - self.voter_key_prompt = None; - } - let has_key = !self - .voter_key_prompt - .as_ref() - .map(PasswordInput::is_empty) - .unwrap_or(true); - if ui.add_enabled(has_key, egui::Button::new("Save")).clicked() { - action = self.submit_voter_key(); - } - }); + Some(rows) if rows.is_empty() => { + ui.label("There are no open name contests right now."); } - } - action - } - - /// Close the `Add voting key` prompt, zeroizing the key typed into it. Called - /// when the Masternodes tab is left: the tab is a root screen that outlives - /// navigation, and an unsubmitted key must not. - pub fn clear_secrets(&mut self) { - self.voter_key_prompt = None; - } - - /// Build the scoped voter-key update: re-load THIS node (context pre-bound) - /// with just the entered voting key, updating its voter identity in place. - /// Distinct from FR-4's load form and exempt from duplicate-ProTxHash - /// rejection (§10.8). - fn submit_voter_key(&mut self) -> Option { - let voting_key = self.voter_key_prompt.as_mut()?.take_secret(); - self.voter_key_prompt = None; - let input = IdentityInputToLoad { - identity_id_input: self.node_id_hex_full.clone(), - identity_type: self.identity.identity_type, - alias_input: self.identity.alias.clone().unwrap_or_default(), - voting_private_key_input: voting_key, - owner_private_key_input: Secret::default(), - payout_address_private_key_input: Secret::default(), - keys_input: vec![], - derive_keys_from_wallets: false, - selected_wallet_seed_hash: None, - encryption_password: None, - // In-place update: merge the new voting key into the already-loaded - // node, preserving its Owner/Payout keys (§10.8). Never overwrite. - load_mode: IdentityLoadMode::MergeIntoExisting, - // This view gates on nothing: the load opens a record of its own rather - // than adopting one another caller is waiting on. - load_token: None, - }; - Some(AppAction::BackendTask(BackendTask::IdentityTask( - IdentityTask::LoadIdentity(input), - ))) - } - - /// Per-contest voting choices + Cast votes, dispatching the existing - /// `VoteOnDPNSNames` backend for the selected choices. - fn render_vote_table(&mut self, ui: &mut Ui, dark_mode: bool) -> Option { - let mut action = None; - // Collect the render data up front so the choice-writing loop does not - // borrow `self.open_contests` while mutating `self.vote_selections`. - let contests: Vec = self - .open_contests - .iter() - .map(|contest| { - let candidates = contest - .contestants - .as_ref() - .map(|list| { - list.iter() - .map(|c| (c.id, c.name.clone(), c.votes)) - .collect() - }) - .unwrap_or_default(); - ContestVoteRow { - name: contest.normalized_contested_name.clone(), - end_time: contest.end_time, - candidates, - } - }) - .collect(); - - ui.label(RichText::new(CONTEST_INTRO_MESSAGE).color(DashColors::text_secondary(dark_mode))); - - for contest in &contests { - ui.separator(); - ui.label( - RichText::new(contest_display_name(&contest.name)) - .strong() - .color(DashColors::text_primary(dark_mode)), - ); - ui.label( - RichText::new(contest_status_line( - contest.candidates.len(), - contest.end_time, - )) - .color(DashColors::text_secondary(dark_mode)), - ); - let selected = self.vote_selections.get(&contest.name).copied(); - ui.horizontal_wrapped(|ui| { - if ui - .selectable_label(selected == Some(ResourceVoteChoice::Abstain), "Abstain") - .clicked() - { - self.vote_selections - .insert(contest.name.clone(), ResourceVoteChoice::Abstain); - } - if ui - .selectable_label(selected == Some(ResourceVoteChoice::Lock), "Lock") - .clicked() - { - self.vote_selections - .insert(contest.name.clone(), ResourceVoteChoice::Lock); - } - // Candidate choices are scoped to THIS contest's contestants. - for (candidate_id, candidate_name, votes) in &contest.candidates { - let choice = ResourceVoteChoice::TowardsIdentity(*candidate_id); - if ui - .selectable_label( - selected == Some(choice), - candidate_choice_label(candidate_name, *votes), - ) - .clicked() - { - self.vote_selections.insert(contest.name.clone(), choice); - } - } - }); - if selected.is_none() { - ui.label( - RichText::new(NO_SELECTION_HINT).color(DashColors::text_secondary(dark_mode)), - ); + Some(rows) => { + let now = now_ms(); + egui::Grid::new(("node_votes", node)) + .num_columns(4) + .striped(true) + .show(ui, |ui| { + for row in rows { + ui.label(format!("{name}.dash", name = row.contested_name)); + ui.label(node_vote_choice_label(row)); + ui.label(if row.choice.is_some() { + changes_left_label(row.changes) + } else { + String::new() + }); + ui.label(match row.end_time { + Some(end) => ends_in_label(time_left(end, now)), + None => String::new(), + }); + ui.end_row(); + } + }); } } - - ui.separator(); - let votes: Vec<(String, ResourceVoteChoice)> = self - .vote_selections - .iter() - .filter(|(name, _)| contests.iter().any(|c| &c.name == *name)) - .map(|(name, choice)| (name.clone(), *choice)) - .collect(); - let has_votes = !votes.is_empty(); - if ui - .add_enabled(has_votes, egui::Button::new("Cast votes")) - .on_hover_text(CAST_ENABLED_HINT) - .on_disabled_hover_text(CAST_DISABLED_HINT) - .clicked() - { - action = Some(self.cast_votes(votes)); - } - action + ui.add_space(6.0); + let can_vote = self.identity.can_cast_masternode_vote(); + ui.add_enabled( + can_vote, + ComponentStyles::secondary_button("Vote with this node", dark_mode), + ) + .disabled_tooltip("Add a voting key to vote with this node.") + .clicked() + .then_some(node) } fn render_remove_section(&mut self, ui: &mut Ui, _dark_mode: bool) -> Option { @@ -1086,6 +937,217 @@ impl MasternodeDetailView { #[cfg(test)] mod tests { use super::*; + use crate::model::secret::Secret; + + /// A masternode with no voting key loaded — the state that puts the + /// `Add voting key` section on screen. Alias is fixed so the merge input's + /// carried alias is assertable. + fn voteless_masternode(ctx: &Arc, byte: u8) -> QualifiedIdentity { + use crate::model::qualified_identity::{IdentityStatus, encrypted_key_storage::KeyStorage}; + use dash_sdk::dpp::identity::Identity; + use dash_sdk::dpp::version::PlatformVersion; + QualifiedIdentity { + identity: Identity::create_basic_identity( + Identifier::from([byte; 32]), + PlatformVersion::latest(), + ) + .unwrap(), + associated_voter_identity: None, + associated_operator_identity: None, + associated_owner_key_id: None, + identity_type: IdentityType::Masternode, + alias: Some("my-node".into()), + private_keys: KeyStorage::default(), + dpns_names: vec![], + associated_wallets: BTreeMap::new(), + secret_access: None, + wallet_index: None, + top_ups: BTreeMap::new(), + status: IdentityStatus::PendingCreation, + network: ctx.network(), + } + } + + #[tokio::test] + async fn blocker_node_detail_refresh_reloads_vote_rows_without_resetting_prompts() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(Arc::new( + crate::wallet_backend::kv_test_support::InMemoryKv::default(), + ))); + let (sender, _events) = tokio::sync::mpsc::channel(16); + ctx.ensure_wallet_backend(crate::utils::egui_mpsc::SenderAsync::new( + sender, + ctx.egui_ctx().clone(), + )) + .await + .unwrap(); + let identity = voteless_masternode(&ctx, 43); + let voter = identity.identity.id(); + ctx.insert_local_qualified_identity(&identity, &None) + .unwrap(); + ctx.seed_dpns_contest_for_test("alice", None, false); + let poll = ctx.dpns_vote_poll_id("alice").unwrap(); + ctx.seed_proved_dpns_votes_for_test(voter, BTreeMap::new()) + .await + .unwrap(); + let mut detail = MasternodeDetailView::new(&ctx, identity); + assert_eq!(detail.node_votes.as_ref().unwrap()[0].choice, None); + detail.set_voter_key_prompt_for_test("test-only-input"); + ctx.seed_proved_dpns_votes_for_test( + voter, + BTreeMap::from([( + poll.to_buffer(), + dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice::Lock, + )]), + ) + .await + .unwrap(); + detail.refresh_from_store(); + assert_eq!( + detail.node_votes.as_ref().unwrap()[0].choice, + Some( + dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice::Lock + ) + ); + assert!(detail.has_voter_key_prompt_for_test()); + } + + #[test] + fn voting_ui_scoped_key_update_merges_into_the_current_node() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let id = Identifier::from([0x47; 32]); + let mut detail = MasternodeDetailView::new(&ctx, voteless_masternode(&ctx, 0x47)); + detail.set_voter_key_prompt_for_test("test-only-input"); + let Some(AppAction::BackendTask(BackendTask::IdentityTask(IdentityTask::LoadIdentity( + input, + )))) = detail.submit_voter_key() + else { + panic!("scoped identity merge"); + }; + assert_eq!(input.identity_id_input, id.to_string(Encoding::Hex)); + assert_eq!(input.load_mode, IdentityLoadMode::MergeIntoExisting); + assert_eq!(input.alias_input, "my-node"); + assert!(!input.voting_private_key_input.is_blank()); + assert!(input.owner_private_key_input.is_blank()); + assert!(input.payout_address_private_key_input.is_blank()); + assert!(input.encryption_password.is_none()); + assert!(!detail.has_voter_key_prompt_for_test()); + assert_eq!( + input.load_token, + detail.pending_voter_key_load(), + "the merge must travel under the token this view gates on", + ); + assert!( + detail.submit_voter_key().is_none(), + "a repeated Save cannot dispatch another load" + ); + } + + /// A second Save, while the first merge is still running, must be refused by + /// a disabled control rather than by discarding the key and reporting + /// `IdentityLoadInProgress`. Save clears the prompt as it dispatches, so an + /// offer to press it again is an offer to lose whatever was typed next. + #[test] + fn a_voting_key_merge_in_flight_gates_a_second_save() { + use egui_kittest::kittest::Queryable; + use std::sync::atomic::{AtomicUsize, Ordering}; + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let mut detail = MasternodeDetailView::new(&ctx, voteless_masternode(&ctx, 0x48)); + + let dispatched = Arc::new(AtomicUsize::new(0)); + let observed = dispatched.clone(); + detail.set_voter_key_prompt_for_test("test-only-input"); + let mut harness = egui_kittest::Harness::builder().build_ui(move |ui| { + if matches!( + detail.render_missing_voter(ui, false), + Some(AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::LoadIdentity(_) + ))) + ) { + observed.fetch_add(1, Ordering::Relaxed); + } + }); + harness.run(); + let position = harness.get_by_label("Save").rect().center(); + harness.get_by_label("Save").click(); + // Stepped, not `run`: the gate's spinner repaints forever by design, so + // `run` would never see the UI settle. One step applies the click and + // dispatches, the next renders the gated section. + harness.step(); + harness.step(); + + assert!( + harness.query_by_label("Save").is_none(), + "the dispatched merge must take Save off screen" + ); + assert!( + harness.query_by_label("Add voting key").is_none(), + "re-offering the prompt invites a submit the backend would reject" + ); + assert!( + harness.query_by_label("Adding voting key…").is_some(), + "the wait must be visible while the merge runs" + ); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { + pos: position, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }); + } + harness.step(); + assert_eq!( + dispatched.load(Ordering::Relaxed), + 1, + "repeated clicks at Save must dispatch only one load" + ); + } + + /// The gate is held by the merge's reported phase, and released by it — + /// never by a guess. A failed merge returns the node to an offer the user + /// can act on, rather than stranding it behind a spinner for the session. + #[test] + fn a_finished_voting_key_merge_releases_the_gate() { + use egui_kittest::kittest::Queryable; + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let node_id = Identifier::from([0x49; 32]); + let mut detail = MasternodeDetailView::new(&ctx, voteless_masternode(&ctx, 0x49)); + detail.set_voter_key_prompt_for_test("test-only-input"); + detail.submit_voter_key().expect("the merge dispatches"); + + let token = detail + .pending_voter_key_load() + .expect("the merge is gated while outstanding"); + let guard = ctx + .begin_identity_load(node_id, Some(token)) + .expect("the task claims the load it was dispatched under"); + detail.reconcile_voter_key_load(); + assert!( + detail.pending_voter_key_load().is_some(), + "a claimed, still-running merge keeps the gate" + ); + + // Dropping the guard without `loaded()` is how a failed load reports. + drop(guard); + detail.reconcile_voter_key_load(); + assert!( + detail.pending_voter_key_load().is_none(), + "a finished merge must release the gate" + ); + + let mut harness = egui_kittest::Harness::builder() + .build_ui(move |ui| _ = detail.render_missing_voter(ui, false)); + harness.run(); + assert!( + harness.query_by_label("Add voting key").is_some(), + "a released gate must let the user try again" + ); + } #[test] fn masternode_removal_dispatches_the_identity_backend_task() { @@ -1129,158 +1191,6 @@ mod tests { ); } - #[test] - fn tc_dpns_02_header_shows_open_contest_count() { - assert_eq!(dpns_section_header(3), "DPNS name contests to vote on (3)"); - assert_eq!(dpns_section_header(0), "DPNS name contests to vote on (0)"); - } - - #[test] - fn contest_name_gets_dash_suffix() { - // The normalized label is shown bare elsewhere; the vote section spells - // out the full `.dash` domain so the user knows it is a registration. - assert_eq!(contest_display_name("det"), "det.dash"); - } - - /// A cast retires only the selections it actually delivered. The view now - /// outlives a backend result, so the votes already on their way must stop - /// re-arming `Cast votes`, while a contest whose vote failed keeps its - /// choice for a corrected retry. - #[test] - fn a_cast_retires_only_the_selections_it_delivered() { - use crate::backend_task::error::TaskError; - use crate::model::qualified_identity::IdentityStatus; - use dash_sdk::dpp::dashcore::Network; - use dash_sdk::dpp::identity::Identity; - use dash_sdk::dpp::version::PlatformVersion; - - let temp_dir = tempfile::tempdir().expect("tempdir"); - let app_context = crate::context::test_support::test_app_context(temp_dir.path()); - let identity = Identity::create_basic_identity( - Identifier::from([0x77; 32]), - PlatformVersion::latest(), - ) - .expect("basic identity"); - let qi = QualifiedIdentity { - identity, - associated_voter_identity: None, - associated_operator_identity: None, - associated_owner_key_id: None, - identity_type: IdentityType::Masternode, - alias: None, - private_keys: Default::default(), - dpns_names: vec![], - associated_wallets: BTreeMap::new(), - secret_access: None, - wallet_index: None, - top_ups: BTreeMap::new(), - status: IdentityStatus::Active, - network: Network::Testnet, - }; - let mut view = MasternodeDetailView::new(&app_context, qi); - view.vote_selections - .insert("delivered".to_string(), ResourceVoteChoice::Abstain); - view.vote_selections - .insert("rejected".to_string(), ResourceVoteChoice::Lock); - view.vote_selections - .insert("changed".to_string(), ResourceVoteChoice::Abstain); - - let AppAction::BackendTaskWithContext { context, .. } = view.cast_votes(vec![ - ("delivered".to_string(), ResourceVoteChoice::Abstain), - ("changed".to_string(), ResourceVoteChoice::Abstain), - ("rejected".to_string(), ResourceVoteChoice::Lock), - ]) else { - panic!("a cast must carry its dispatch context"); - }; - view.vote_selections - .insert("changed".to_string(), ResourceVoteChoice::Lock); - let results = [ - ("delivered".to_string(), ResourceVoteChoice::Abstain, Ok(())), - ("changed".to_string(), ResourceVoteChoice::Abstain, Ok(())), - ( - "rejected".to_string(), - ResourceVoteChoice::Lock, - Err(Arc::new(TaskError::NoIdentitiesFound)), - ), - ]; - view.consume_cast_votes(&BackendTaskContext::Other, &results); - let unrelated = BackendTaskContext::for_dispatch(&BackendTask::None); - view.consume_cast_votes(&unrelated, &results); - assert_eq!( - view.vote_selections.len(), - 3, - "unrelated casts change nothing" - ); - view.consume_cast_votes(&context, &results); - - assert!( - !view.vote_selections.contains_key("delivered"), - "a vote already sent must not stay armed to be sent again", - ); - assert_eq!( - view.vote_selections.get("changed"), - Some(&ResourceVoteChoice::Lock), - "a result for an older choice must preserve the newer selection", - ); - assert_eq!( - view.vote_selections.get("rejected"), - Some(&ResourceVoteChoice::Lock), - "a vote that failed keeps its choice so it can be retried", - ); - - view.vote_selections - .insert("delivered".to_string(), ResourceVoteChoice::Abstain); - let AppAction::BackendTaskWithContext { context: next, .. } = - view.cast_votes(vec![("delivered".to_string(), ResourceVoteChoice::Abstain)]) - else { - panic!("a cast must carry its dispatch context"); - }; - view.consume_cast_votes(&context, &results); - assert!( - view.vote_selections.contains_key("delivered"), - "an older cast cannot retire a new cast's selection" - ); - view.consume_cast_votes(&next, &results); - assert!(!view.vote_selections.contains_key("delivered")); - } - - #[test] - fn candidate_label_carries_current_tally() { - let label = candidate_choice_label("alice", 5); - assert!( - label.contains("Vote for alice"), - "names the candidate: {label}" - ); - assert!(label.contains('5'), "shows the running tally: {label}"); - } - - #[test] - fn status_line_reports_candidate_count() { - let line = contest_status_line(2, None); - assert!( - line.contains("Identities competing for this name: 2."), - "counts contestants: {line}" - ); - assert!( - line.contains("still loading"), - "degrades when the deadline is absent: {line}" - ); - } - - #[test] - fn status_line_renders_absolute_deadline() { - // 2021-01-01T00:00:00Z in milliseconds. - let line = contest_status_line(3, Some(1_609_459_200_000)); - assert!( - line.contains("Identities competing for this name: 3."), - "counts contestants: {line}" - ); - assert!( - line.contains("2021-01-01 00:00:00 UTC"), - "shows the absolute ISO deadline: {line}" - ); - } - #[test] fn protection_tier_label_and_add_gate() { assert_eq!(ProtectionTier::Unprotected.label(), "Keys: unprotected"); diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index 93302e0d4..022114e77 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -12,12 +12,15 @@ use dash_sdk::platform::Identifier; use eframe::egui::{self, RichText}; use crate::app::{AppAction, BackendTasksExecutionMode}; -use crate::backend_task::contested_names::ContestedResourceTask; +use crate::backend_task::contested_names::{ContestedResourceTask, DpnsVotingPreference}; use crate::backend_task::identity::IdentityTask; use crate::backend_task::{BackendTask, BackendTaskSuccessResult}; use crate::context::AppContext; use crate::context::identity_load_registry::{IdentityLoadPhase, IdentityLoadToken}; use crate::model::contested_name::MasternodeContestSummary; +use crate::model::dpns_voting::operator::{ + MasternodesSegment, background_refresh_due, opening_masternodes_segment, +}; use crate::model::masternode_input::decode_identity_id; use crate::model::qualified_identity::{IdentityStatus, IdentityType, MasternodeKeyPresence}; use crate::model::user_role::UserRole; @@ -28,7 +31,8 @@ use crate::ui::components::left_panel::add_left_panel; use crate::ui::components::legacy_recovery_section::completion_message; use crate::ui::components::styled::island_central_panel; use crate::ui::components::top_panel::add_top_panel_with_global_nav_capturing; -use crate::ui::identity::identity_pill::shorten_id; +use crate::ui::dpns::VotesView; +use crate::ui::dpns::dpns_contested_names_screen::DPNSScreen; use crate::ui::identity::picker::compute_column_count; use crate::ui::masternodes::card::{MasternodeCard, card_heading}; use crate::ui::masternodes::detail_screen::{DetailOutcome, MasternodeDetailView}; @@ -38,6 +42,9 @@ use crate::ui::state::masternodes_view::{masternodes_page_nav_spec, node_pill_it use crate::ui::theme::{ComponentStyles, DashColors}; use crate::ui::{MessageType, RootScreenType, ScreenLike}; +/// Arriving on Votes refreshes contests unless one completed this recently. +const VOTES_ARRIVAL_REFRESH_MIN_GAP: std::time::Duration = std::time::Duration::from_secs(60); + /// Minimum horizontal gap between cards in the grid (matches the identity /// picker grid). const GRID_GAP: f32 = 16.0; @@ -105,6 +112,16 @@ pub struct MasternodesScreen { pending_load: Option, /// Identity removals dispatched by this screen whose results have not arrived. pending_removals: BTreeSet, + /// The visible half of the page: Votes or Nodes. + segment: MasternodesSegment, + /// The single voting workspace (Masternodes ▸ Votes). Receives every vote + /// result whether or not its segment is showing. + votes: DPNSScreen, + /// Set when Votes comes into view; the next frame refreshes contests and + /// vote state unless a refresh completed moments ago (VOTE-FR-074). + votes_arrival_refresh: bool, + /// The segment to persist through the backend once no user action is out. + pending_segment_save: Option, } #[cfg(test)] @@ -116,6 +133,14 @@ impl MasternodesScreen { .map(|node| card_heading(node.alias.as_deref(), &node.node_id_short)) .collect() } + + /// Return each card's rendered DPNS status line, in grid order. + pub(crate) fn dpns_status_lines_for_test(&self) -> Vec { + self.nodes + .iter() + .map(|node| crate::ui::masternodes::card::dpns_status_line(node.contest_summary)) + .collect() + } } impl MasternodesScreen { @@ -129,11 +154,77 @@ impl MasternodesScreen { view: MasternodesView::List, pending_load: None, pending_removals: BTreeSet::new(), + segment: opening_masternodes_segment( + 0, + app_context.masternodes_last_segment().unwrap_or_default(), + ), + votes: DPNSScreen::new(app_context, VotesView::ToDecide), + votes_arrival_refresh: false, + pending_segment_save: None, }; screen.reload(); screen } + /// The visible segment. + pub fn segment(&self) -> MasternodesSegment { + self.segment + } + + /// The voting workspace, for routing vote results while this screen is hidden. + pub fn votes_mut(&mut self) -> &mut DPNSScreen { + &mut self.votes + } + + /// Show `segment` and remember it as the last-used one on this network. + pub fn select_segment(&mut self, segment: MasternodesSegment) { + if segment == MasternodesSegment::Votes && self.segment != segment { + self.votes.refresh_on_arrival(); + self.votes_arrival_refresh = true; + } + if segment != self.segment { + self.votes.release_list_focus(); + } + self.segment = segment; + self.pending_segment_save = Some(segment); + } + + /// Open Masternodes ▸ Votes on `view`. + pub fn open_votes(&mut self, view: VotesView) { + self.select_segment(MasternodesSegment::Votes); + self.votes.view = view; + } + + /// Contests needing a decision plus unresolved targets, for the nav badge + /// and the opening segment. + fn attention_count(&self) -> usize { + self.app_context.dpns_vote_attention().badge_count() + } + + fn render_segment_header(&mut self, ui: &mut egui::Ui) { + let attention = self.attention_count(); + ui.horizontal(|ui| { + let votes_label = if attention > 0 { + format!("Votes ({attention})") + } else { + "Votes".to_owned() + }; + for (segment, label) in [ + (MasternodesSegment::Votes, votes_label), + (MasternodesSegment::Nodes, "Nodes".to_owned()), + ] { + if ui + .selectable_label(self.segment == segment, label) + .clicked() + && self.segment != segment + { + self.select_segment(segment); + } + } + }); + ui.add_space(8.0); + } + /// Re-read the loaded masternode/evonode identities and their DPNS contest /// summaries from the local store. A read failure degrades to an empty list /// rather than surfacing a technical error — the empty state is a safe, @@ -144,19 +235,36 @@ impl MasternodesScreen { .load_local_masternode_identities() .unwrap_or_default(); + // Votes are published and cached under the node's own ProTxHash; the + // voter identity only supplies the key that signs them. Resolve every + // node's voter_id up front and fetch all their summaries in one call: + // the contest cache, derived vote-poll ids, operation journal and + // schedule dismissals depend on the contest set, not the node, so an + // operator with a large fleet must not pay for them once per card. + let voter_ids: Vec = identities + .iter() + .filter(|qi| qi.associated_voter_identity.is_some()) + .map(|qi| qi.identity.id()) + .collect(); + let summaries = self + .app_context + .masternode_contest_summaries(&voter_ids) + .unwrap_or_default(); + self.nodes = identities .into_iter() .map(|qi| { let node_id = qi.identity.id(); - let node_id_short = shorten_id(&node_id.to_string(Encoding::Hex)); - let voter_id = qi - .associated_voter_identity - .as_ref() - .map(|(identity, _)| identity.id()); - let contest_summary = self - .app_context - .masternode_contest_summary(voter_id) - .unwrap_or_default(); + let node_id_short = crate::model::identity_name::masternode_label(node_id, None); + let has_voter_id = qi.associated_voter_identity.is_some(); + let contest_summary = if has_voter_id { + summaries + .get(&node_id) + .copied() + .unwrap_or_else(MasternodeContestSummary::unavailable) + } else { + MasternodeContestSummary::default() + }; NodeCardData { node_id, node_id_short, @@ -221,6 +329,14 @@ impl MasternodesScreen { self.view = MasternodesView::List; self.pending_load = None; self.pending_removals.clear(); + self.votes.app_context = self.app_context.clone(); + self.votes.reset_for_network_switch(); + self.segment = opening_masternodes_segment( + 0, + self.app_context + .masternodes_last_segment() + .unwrap_or_default(), + ); self.reload(); } @@ -396,10 +512,17 @@ impl MasternodesScreen { .into_iter() .find(|qi| qi.identity.id() == node_id) { - self.view = MasternodesView::Detail(Box::new(MasternodeDetailView::new( - &self.app_context, - identity, - ))); + // An Add-voting-key merge outstanding on this same node must keep + // gating Save across the rebuild; the fresh view cannot know of it. + let pending_voter_key_load = match &self.view { + MasternodesView::Detail(detail) if detail.node_id() == node_id => { + detail.pending_voter_key_load() + } + _ => None, + }; + let mut detail = Box::new(MasternodeDetailView::new(&self.app_context, identity)); + detail.adopt_pending_voter_key_load(pending_voter_key_load); + self.view = MasternodesView::Detail(detail); } } @@ -420,6 +543,12 @@ impl MasternodesScreen { AppAction::None } DetailOutcome::Forward(action) => *action, + DetailOutcome::VoteWithNode(node) => { + self.view = MasternodesView::List; + self.votes.vote_with_node(node); + self.select_segment(MasternodesSegment::Votes); + AppAction::None + } }; self.capture_removal_dispatch(&action); action @@ -562,6 +691,7 @@ impl ScreenLike for MasternodesScreen { } fn refresh(&mut self) { self.reload(); + self.votes.refresh(); } fn refresh_on_arrival(&mut self) { @@ -570,12 +700,34 @@ impl ScreenLike for MasternodesScreen { if let MasternodesView::Detail(detail) = &mut self.view { detail.refresh_on_arrival(); } + self.votes.refresh_on_arrival(); } fn reset_to_root_view(&mut self) { if !matches!(self.view, MasternodesView::Load(_)) { self.view = MasternodesView::List; } + self.segment = opening_masternodes_segment( + self.attention_count(), + self.app_context + .masternodes_last_segment() + .unwrap_or_default(), + ); + self.votes_arrival_refresh |= self.segment == MasternodesSegment::Votes; + } + + fn display_message(&mut self, message: &str, message_type: MessageType) { + self.votes.display_message(message, message_type); + } + + fn display_backend_task_result( + &mut self, + context: &crate::backend_task::BackendTaskContext, + result: BackendTaskSuccessResult, + ) { + self.votes + .display_backend_task_result(context, result.clone()); + self.apply_node_result(result); } /// Drop every secret the open view holds — the load form's keys and @@ -597,20 +749,102 @@ impl ScreenLike for MasternodesScreen { } } - fn display_backend_task_result( + fn display_task_result(&mut self, result: crate::backend_task::BackendTaskSuccessResult) { + self.votes.display_task_result(result.clone()); + self.apply_node_result(result); + } + + fn display_task_error(&mut self, error: &crate::backend_task::error::TaskError) -> bool { + // A failing load reports `Failed` before its error reaches the UI, so + // settling here re-enables the still-open form's submit button (the Load + // view is untouched, so every entered field survives for correction). + // An error from some other task — a detail-view vote, a refresh — leaves + // this load's phase outstanding and the gate held. The voting panel + // decides whether the global banner is suppressed. + self.reconcile_pending_load(); + self.votes.display_task_error(error) + } + + /// End the open detail view's recovery operation only when the failure is + /// that operation's own. A failed restore returns to its offer so the user + /// can correct a mistyped identity password and press Restore again; any + /// other task's error — which reaches this screen simply because it is + /// visible — must leave a running restore in flight. + fn display_backend_task_error( &mut self, context: &crate::backend_task::BackendTaskContext, - result: BackendTaskSuccessResult, + error: &crate::backend_task::error::TaskError, ) { - if let BackendTaskSuccessResult::DPNSVoteResults(results) = &result - && let MasternodesView::Detail(detail) = &mut self.view + self.votes.display_backend_task_error(context, error); + if let MasternodesView::Detail(detail) = &mut self.view { + detail.absorb_recovery_error(context); + } + } + + fn ui(&mut self, ui: &mut egui::Ui) -> AppAction { + let (mut action, effect) = + add_top_panel_with_global_nav_capturing(ui, &self.app_context, self.nav_spec(), vec![]); + self.apply_nav_effect(effect); + + action |= add_left_panel(ui, &self.app_context, RootScreenType::RootScreenMasternodes); + + let network_accent = + DashColors::network_accent(self.app_context.network, ui.style().visuals.dark_mode); + + action |= island_central_panel(ui, |ui| { + ui.set_min_width(ui.available_width()); + self.render_segment_header(ui); + if self.segment == MasternodesSegment::Votes { + return self.votes.ui(ui); + } + let mut action = AppAction::None; + match self.view { + MasternodesView::Load(_) => action |= self.render_load_view(ui), + MasternodesView::Detail(_) => action |= self.render_detail_view(ui, network_accent), + MasternodesView::List => action |= self.render_list_view(ui, network_accent), + } + action + }); + // Never displace a user action; a refresh deferred here runs next frame. + if action == AppAction::None + && std::mem::take(&mut self.votes_arrival_refresh) + && self.segment == MasternodesSegment::Votes + && background_refresh_due( + self.app_context.dpns_contests_refreshed_at_ms(), + None, + crate::utils::time::now_ms(), + VOTES_ARRIVAL_REFRESH_MIN_GAP, + ) { - detail.consume_cast_votes(context, results); + // A user-visible refresh (VOTE-FR-074): failures reach the banner, + // unlike the timer's background refresh. + action = AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::QueryDPNSContests, + )); } - self.display_task_result(result); + if self.votes.take_load_node_request() { + self.select_segment(MasternodesSegment::Nodes); + if self.pending_load.is_none() { + self.view = MasternodesView::Load(self.new_load_form()); + } + } + if action == AppAction::None + && let Some(segment) = self.pending_segment_save.take() + { + action = AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::SaveDpnsVotingPreference( + DpnsVotingPreference::MasternodesSegment(segment), + ), + )); + } + + action } +} - fn display_task_result(&mut self, result: crate::backend_task::BackendTaskSuccessResult) { +impl MasternodesScreen { + /// Apply a task result to the node list and the open detail view. + fn apply_node_result(&mut self, result: BackendTaskSuccessResult) { match result { // A recovery preview changed nothing in the store, so it is routed // into the open detail view instead of reloading and re-opening it. @@ -687,54 +921,6 @@ impl ScreenLike for MasternodesScreen { detail.refresh_from_store(); } } - - fn display_task_error(&mut self, _error: &crate::backend_task::error::TaskError) -> bool { - // A failing load reports `Failed` before its error reaches the UI, so - // settling here re-enables the still-open form's submit button (the Load - // view is untouched, so every entered field survives for correction). - // An error from some other task — a detail-view vote, a refresh — leaves - // this load's phase outstanding and the gate held. Let the global banner - // render the error (return false). - self.reconcile_pending_load(); - false - } - - /// End the open detail view's recovery operation only when the failure is - /// that operation's own. A failed restore returns to its offer so the user - /// can correct a mistyped identity password and press Restore again; any - /// other task's error — which reaches this screen simply because it is - /// visible — must leave a running restore in flight. - fn display_backend_task_error( - &mut self, - context: &crate::backend_task::BackendTaskContext, - _error: &crate::backend_task::error::TaskError, - ) { - if let MasternodesView::Detail(detail) = &mut self.view { - detail.absorb_recovery_error(context); - } - } - - fn ui(&mut self, ui: &mut egui::Ui) -> AppAction { - let (mut action, effect) = - add_top_panel_with_global_nav_capturing(ui, &self.app_context, self.nav_spec(), vec![]); - self.apply_nav_effect(effect); - - action |= add_left_panel(ui, &self.app_context, RootScreenType::RootScreenMasternodes); - - let network_accent = - DashColors::network_accent(self.app_context.network, ui.style().visuals.dark_mode); - - action |= island_central_panel(ui, |ui| { - ui.set_min_width(ui.available_width()); - match self.view { - MasternodesView::Load(_) => self.render_load_view(ui), - MasternodesView::Detail(_) => self.render_detail_view(ui, network_accent), - MasternodesView::List => self.render_list_view(ui, network_accent), - } - }); - - action - } } #[cfg(test)] @@ -752,6 +938,7 @@ mod tests { use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::identity::Identity; use dash_sdk::dpp::version::PlatformVersion; + use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; use dash_sdk::platform::Identifier; use std::collections::BTreeMap; @@ -807,6 +994,102 @@ mod tests { .expect("seed masternode"); } + /// Seed a masternode carrying an associated voter identity — the state that + /// lets it cast a DPNS vote. Returns the node's own id, which is also the + /// ProTxHash its votes are published and cached under. + fn seed_masternode_with_voter(ctx: &Arc, byte: u8, alias: &str) -> Identifier { + let pv = PlatformVersion::latest(); + let node_id = Identifier::from([byte; 32]); + let voter_identity = + Identity::create_basic_identity(Identifier::from([byte ^ 0xFF; 32]), pv) + .expect("voter identity"); + let voter_key = dash_sdk::platform::IdentityPublicKey::random_key(1, Some(1), pv); + let qi = QualifiedIdentity { + identity: Identity::create_basic_identity(node_id, pv).expect("basic identity"), + associated_voter_identity: Some((voter_identity, voter_key)), + associated_operator_identity: None, + associated_owner_key_id: None, + identity_type: IdentityType::Masternode, + alias: Some(alias.to_owned()), + private_keys: KeyStorage::default(), + dpns_names: vec![], + associated_wallets: BTreeMap::new(), + secret_access: None, + wallet_index: None, + top_ups: BTreeMap::new(), + status: IdentityStatus::PendingCreation, + network: ctx.network(), + }; + ctx.insert_local_qualified_identity(&qi, &None) + .expect("seed masternode with voter"); + node_id + } + + /// A vote a node cast resolves on that node's own card. + /// + /// The card reads the proved-vote cache, which is keyed by the id the vote + /// was published under — the node's ProTxHash, never the separate + /// `associated_voter_identity` record. The vote is written here through the + /// production writer, so this asserts reader/writer agreement rather than + /// restating either side: keying the read on anything else can only miss, + /// and a miss is reported as the permanent "Checking" line. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_cast_vote_resolves_on_the_card_of_the_node_that_cast_it() { + let (ctx, _tmp) = offline_ctx().await; + let node_id = seed_masternode_with_voter(&ctx, 0x55, "voting-node"); + ctx.seed_dpns_contest_for_test("alpha", None, false); + let poll_id = ctx.dpns_vote_poll_id("alpha").expect("DPNS vote poll id"); + ctx.cache_confirmed_dpns_vote(node_id, poll_id, ResourceVoteChoice::Lock) + .expect("cache the confirmed vote"); + + let screen = MasternodesScreen::new(&ctx); + + assert_eq!( + screen.dpns_status_lines_for_test(), + vec!["Votes cast in all active contests".to_string()], + "the card must report the vote this node cast, not stay on \"Checking\"", + ); + + ctx.wallet_backend().expect("backend").shutdown().await; + } + + /// Picking a segment never writes storage from the UI: the choice is + /// persisted through a backend task once no user action is pending. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn segment_choice_is_saved_through_a_backend_task() { + let (ctx, _tmp) = offline_ctx().await; + let mut screen = MasternodesScreen::new(&ctx); + let before = ctx.masternodes_last_segment().unwrap(); + let other = if before == Some(MasternodesSegment::Votes) { + MasternodesSegment::Nodes + } else { + MasternodesSegment::Votes + }; + screen.select_segment(other); + assert_eq!(ctx.masternodes_last_segment().unwrap(), before); + assert_eq!(screen.pending_segment_save, Some(other)); + ctx.wallet_backend().expect("backend").shutdown().await; + } + + /// A node with no voting key can vote in nothing, so its card carries the + /// empty summary instead of a contest count it could never act on. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_node_without_a_voting_key_gets_the_empty_dpns_summary() { + let (ctx, _tmp) = offline_ctx().await; + seed_masternode(&ctx, 0x66, Some("read-only-node")); + ctx.seed_dpns_contest_for_test("alpha", None, false); + + let screen = MasternodesScreen::new(&ctx); + + assert_eq!( + screen.dpns_status_lines_for_test(), + vec!["No open contests".to_string()], + "a node that cannot vote must not be summarised against open contests", + ); + + ctx.wallet_backend().expect("backend").shutdown().await; + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn nodes_are_sorted_case_insensitively_by_display_heading() { let (ctx, _tmp) = offline_ctx().await; @@ -814,7 +1097,8 @@ mod tests { seed_masternode(&ctx, 0x22, Some("alpha")); seed_masternode(&ctx, 0x44, None); - let fallback_heading = shorten_id(&Identifier::from([0x44; 32]).to_string(Encoding::Hex)); + let fallback_heading = + crate::model::identity_name::masternode_label(Identifier::from([0x44; 32]), None); let screen = MasternodesScreen::new(&ctx); assert_eq!( @@ -2033,6 +2317,25 @@ mod tests { ctx.wallet_backend().expect("backend").shutdown().await; } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn voting_ui_leaving_detail_clears_the_scoped_voting_key_prompt() { + let (ctx, _tmp) = offline_ctx().await; + let mut screen = MasternodesScreen::new(&ctx); + let mut detail = MasternodeDetailView::new( + &ctx, + masternode_identity(&ctx, Identifier::from([0x45; 32])), + ); + detail.set_voter_key_prompt_for_test("unsubmitted-test-input"); + assert!(detail.has_voter_key_prompt_for_test()); + screen.view = MasternodesView::Detail(Box::new(detail)); + screen.on_leave(); + let MasternodesView::Detail(detail) = &screen.view else { + panic!("detail"); + }; + assert!(!detail.has_voter_key_prompt_for_test()); + ctx.wallet_backend().expect("backend").shutdown().await; + } + /// SEC — the reported case: the user submits, navigates away while the load /// runs, and the load fails behind their back. The form is kept open for a /// corrected resubmit, so nothing else would ever drop its secrets. Leaving @@ -2061,37 +2364,9 @@ mod tests { ctx.wallet_backend().expect("backend").shutdown().await; } - /// SEC — the detail view's in-place `Add voting key` prompt holds a plaintext - /// WIF too, and lives in the very same root screen. A prompt left filled but - /// unsubmitted must not survive the user leaving the tab. - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn leaving_the_tab_discards_an_unsubmitted_voting_key() { - let (ctx, _tmp) = offline_ctx().await; - seed_masternode(&ctx, 0xc5, None); - let mut screen = MasternodesScreen::new(&ctx); - screen.open_detail(Identifier::from([0xc5; 32])); - - let MasternodesView::Detail(detail) = &mut screen.view else { - panic!("the detail view must be open"); - }; - detail.set_voter_key_prompt_for_test("voter-wif"); - - screen.on_leave(); - - let MasternodesView::Detail(detail) = &screen.view else { - panic!("leaving must not discard the detail view"); - }; - assert!( - !detail.has_voter_key_prompt_for_test(), - "an unsubmitted voting key must not outlive the tab" - ); - - ctx.wallet_backend().expect("backend").shutdown().await; - } - - /// A node with no detail view open and no nodes at all both resolve to "no - /// selection" — the pill falls back to its placeholder rather than naming a - /// node the page is not showing. + /// A screen with no node loaded and no detail view open has nothing to + /// select: the pill falls back to its placeholder rather than naming a node + /// the page is not showing. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn empty_page_offers_no_nodes_on_the_pill() { let (ctx, _tmp) = offline_ctx().await; diff --git a/src/ui/mod.rs b/src/ui/mod.rs index f4b670758..1dd8df378 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -20,7 +20,6 @@ use crate::ui::dashpay::profile_search::ProfileSearchScreen; use crate::ui::dashpay::qr_code_generator::QRCodeGeneratorScreen; use crate::ui::dashpay::send_payment::SendPaymentScreen; use crate::ui::dashpay::{DashPayScreen, DashPaySubscreen}; -use crate::ui::dpns::dpns_contested_names_screen::DPNSScreen; use crate::ui::identity::keys::add_key_screen::AddKeyScreen; use crate::ui::identity::keys::key_info_screen::KeyInfoScreen; use crate::ui::identity::keys::keys_screen::KeysScreen; @@ -50,11 +49,11 @@ use contracts_documents::register_contract_screen::RegisterDataContractScreen; use contracts_documents::update_contract_screen::UpdateDataContractScreen; use dash_sdk::dpp::prelude::IdentityPublicKey; use dash_sdk::platform::Identifier; -use dpns::dpns_contested_names_screen::DPNSSubscreen; use identity::IdentityHubScreen; use identity::add_existing_identity_screen::AddExistingIdentityScreen; use identity::add_new_identity_screen::AddNewIdentityScreen; use identity::register_dpns_name_screen::{RegisterDpnsNameScreen, RegisterDpnsNameSource}; +use identity::username_request_screen::UsernameRequestScreen; use masternodes::MasternodesScreen; use std::fmt; use std::sync::Arc; @@ -132,19 +131,44 @@ pub mod welcome_screen; pub use crate::model::settings::RootScreenType; +/// Where a root route really lands. +/// +/// Voting lives in Masternodes ▸ Votes, but persisted settings and older +/// actions still name the retired DPNS root screens: those open the matching +/// Votes sub-view, and the retired "My usernames" opens the Identities hub. +/// Every other route is returned unchanged with no sub-view. +pub fn resolve_root_screen(root: RootScreenType) -> (RootScreenType, Option) { + match root { + RootScreenType::RootScreenDPNSActiveContests => ( + RootScreenType::RootScreenMasternodes, + Some(dpns::VotesView::ToDecide), + ), + RootScreenType::RootScreenDPNSPastContests => ( + RootScreenType::RootScreenMasternodes, + Some(dpns::VotesView::History), + ), + RootScreenType::RootScreenDPNSScheduledVotes => ( + RootScreenType::RootScreenMasternodes, + Some(dpns::VotesView::Scheduled), + ), + RootScreenType::RootScreenDPNSOwnedNames => (RootScreenType::RootScreenIdentityHub, None), + other => (other, None), + } +} + impl From for ScreenType { fn from(value: RootScreenType) -> Self { match value { - RootScreenType::RootScreenDPNSActiveContests => ScreenType::DPNSActiveContests, - RootScreenType::RootScreenDPNSPastContests => ScreenType::DPNSPastContests, - RootScreenType::RootScreenDPNSOwnedNames => ScreenType::DPNSMyUsernames, + RootScreenType::RootScreenDPNSActiveContests + | RootScreenType::RootScreenDPNSPastContests + | RootScreenType::RootScreenDPNSScheduledVotes => ScreenType::Masternodes, + RootScreenType::RootScreenDPNSOwnedNames => ScreenType::IdentityHub, RootScreenType::RootScreenToolsTransitionVisualizerScreen => { ScreenType::TransitionVisualizer } RootScreenType::RootScreenDocumentQuery => ScreenType::DocumentQuery, RootScreenType::RootScreenNetworkChooser => ScreenType::NetworkChooser, RootScreenType::RootScreenWalletsBalances => ScreenType::WalletsBalances, - RootScreenType::RootScreenDPNSScheduledVotes => ScreenType::ScheduledVotes, RootScreenType::RootScreenToolsProofVisualizerScreen => ScreenType::ProofVisualizer, RootScreenType::RootScreenMyTokenBalances => ScreenType::TokenBalances, RootScreenType::RootScreenTokenSearch => ScreenType::TokenSearch, @@ -171,9 +195,6 @@ impl From for ScreenType { #[derive(Debug, Clone, Default)] pub enum ScreenType { - DPNSActiveContests, - DPNSPastContests, - DPNSMyUsernames, AddNewIdentity, WalletsBalances, ImportMnemonic, @@ -197,10 +218,14 @@ pub enum ScreenType { DocumentQuery, NetworkChooser, RegisterDpnsName(RegisterDpnsNameSource), + /// Status of one of an identity's username requests. + UsernameRequestStatus { + identity_id: Identifier, + normalized_label: String, + }, RegisterContract, UpdateContract, TopUpIdentity(QualifiedIdentity), - ScheduledVotes, AddContracts, ProofVisualizer, DocumentsVisualizer, @@ -275,6 +300,16 @@ impl PartialEq for ScreenType { (KeyInfo(a1, a2, a3), KeyInfo(b1, b2, b3)) => a1 == b1 && a2 == b2 && a3 == b3, (Keys(a), Keys(b)) => a == b, (RegisterDpnsName(a), RegisterDpnsName(b)) => a == b, + ( + UsernameRequestStatus { + identity_id: a1, + normalized_label: a2, + }, + UsernameRequestStatus { + identity_id: b1, + normalized_label: b2, + }, + ) => a1 == b1 && a2 == b2, (TopUpIdentity(a), TopUpIdentity(b)) => a == b, (TransferTokensScreen(a), TransferTokensScreen(b)) => a == b, (MintTokensScreen(a), MintTokensScreen(b)) => a == b, @@ -310,15 +345,6 @@ impl PartialEq for ScreenType { impl ScreenType { pub fn create_screen(&self, app_context: &Arc) -> Screen { match self { - ScreenType::DPNSActiveContests => { - Screen::DPNSScreen(DPNSScreen::new(app_context, DPNSSubscreen::Active)) - } - ScreenType::DPNSPastContests => { - Screen::DPNSScreen(DPNSScreen::new(app_context, DPNSSubscreen::Past)) - } - ScreenType::DPNSMyUsernames => { - Screen::DPNSScreen(DPNSScreen::new(app_context, DPNSSubscreen::Owned)) - } ScreenType::AddNewIdentity => { Screen::AddNewIdentityScreen(AddNewIdentityScreen::new(app_context)) } @@ -342,6 +368,14 @@ impl ScreenType { ScreenType::RegisterDpnsName(source) => { Screen::RegisterDpnsNameScreen(RegisterDpnsNameScreen::new(app_context, *source)) } + ScreenType::UsernameRequestStatus { + identity_id, + normalized_label, + } => Screen::UsernameRequestScreen(UsernameRequestScreen::new( + app_context, + *identity_id, + normalized_label.clone(), + )), ScreenType::RegisterContract => { Screen::RegisterDataContractScreen(RegisterDataContractScreen::new(app_context)) } @@ -381,9 +415,6 @@ impl ScreenType { ScreenType::SingleKeyWalletSendScreen(wallet) => Screen::SingleKeyWalletSendScreen( SingleKeyWalletSendScreen::new(app_context, wallet.clone()), ), - ScreenType::ScheduledVotes => { - Screen::DPNSScreen(DPNSScreen::new(app_context, DPNSSubscreen::ScheduledVotes)) - } ScreenType::AddContracts => { Screen::AddContractsScreen(AddContractsScreen::new(app_context)) } @@ -561,7 +592,6 @@ impl ScreenType { #[allow(clippy::enum_variant_names, clippy::large_enum_variant)] pub enum Screen { - DPNSScreen(DPNSScreen), DocumentQueryScreen(DocumentQueryScreen), AddNewWalletScreen(AddNewWalletScreen), ImportMnemonicScreen(ImportMnemonicScreen), @@ -570,6 +600,7 @@ pub enum Screen { KeyInfoScreen(KeyInfoScreen), KeysScreen(KeysScreen), RegisterDpnsNameScreen(RegisterDpnsNameScreen), + UsernameRequestScreen(UsernameRequestScreen), RegisterDataContractScreen(RegisterDataContractScreen), UpdateDataContractScreen(UpdateDataContractScreen), DocumentActionScreen(DocumentActionScreen), @@ -743,7 +774,6 @@ impl Screen { // The `skip` list must exactly match the explicit match arms above. set_ctx!( set: - DPNSScreen, AddExistingIdentityScreen, KeyInfoScreen, KeysScreen, @@ -753,6 +783,7 @@ impl Screen { AddKeyScreen, DocumentQueryScreen, RegisterDpnsNameScreen, + UsernameRequestScreen, RegisterDataContractScreen, UpdateDataContractScreen, DocumentActionScreen, @@ -918,22 +949,6 @@ impl Screen { screen.key.clone(), screen.private_key_data.clone(), ), - Screen::DPNSScreen(DPNSScreen { - dpns_subscreen: DPNSSubscreen::Active, - .. - }) => ScreenType::DPNSActiveContests, - Screen::DPNSScreen(DPNSScreen { - dpns_subscreen: DPNSSubscreen::Past, - .. - }) => ScreenType::DPNSPastContests, - Screen::DPNSScreen(DPNSScreen { - dpns_subscreen: DPNSSubscreen::Owned, - .. - }) => ScreenType::DPNSMyUsernames, - Screen::DPNSScreen(DPNSScreen { - dpns_subscreen: DPNSSubscreen::ScheduledVotes, - .. - }) => ScreenType::ScheduledVotes, Screen::TransitionVisualizerScreen(_) => ScreenType::TransitionVisualizer, Screen::ContractVisualizerScreen(_) => ScreenType::ContractsVisualizer, Screen::WithdrawalScreen(screen) => { @@ -947,6 +962,10 @@ impl Screen { ScreenType::TopUpIdentity(screen.identity.clone()) } Screen::RegisterDpnsNameScreen(screen) => ScreenType::RegisterDpnsName(screen.source), + Screen::UsernameRequestScreen(screen) => ScreenType::UsernameRequestStatus { + identity_id: screen.identity_id(), + normalized_label: screen.normalized_label().to_owned(), + }, Screen::RegisterDataContractScreen(_) => ScreenType::RegisterContract, Screen::UpdateDataContractScreen(_) => ScreenType::UpdateContract, Screen::DocumentActionScreen(screen) => match screen.action_type { @@ -1080,7 +1099,6 @@ impl Screen { macro_rules! delegate_to_screen { ($self:expr, $screen:ident => $call:expr) => { match $self { - Screen::DPNSScreen($screen) => $call, Screen::DocumentQueryScreen($screen) => $call, Screen::AddNewWalletScreen($screen) => $call, Screen::ImportMnemonicScreen($screen) => $call, @@ -1089,6 +1107,7 @@ macro_rules! delegate_to_screen { Screen::KeyInfoScreen($screen) => $call, Screen::KeysScreen($screen) => $call, Screen::RegisterDpnsNameScreen($screen) => $call, + Screen::UsernameRequestScreen($screen) => $call, Screen::RegisterDataContractScreen($screen) => $call, Screen::UpdateDataContractScreen($screen) => $call, Screen::DocumentActionScreen($screen) => $call, @@ -1204,3 +1223,43 @@ impl ScreenLike for Screen { delegate_to_screen!(self, screen => screen.pop_on_success()) } } + +#[cfg(test)] +mod root_route_tests { + use super::*; + + /// VOTE-TC-082 / VOTE-TC-083 (routing half): retired DPNS routes resolve to + /// Masternodes ▸ Votes sub-views, owned names to the Identities hub. + #[test] + fn retired_dpns_routes_resolve_to_votes_and_the_identity_hub() { + assert_eq!( + resolve_root_screen(RootScreenType::RootScreenDPNSActiveContests), + ( + RootScreenType::RootScreenMasternodes, + Some(dpns::VotesView::ToDecide) + ) + ); + assert_eq!( + resolve_root_screen(RootScreenType::RootScreenDPNSPastContests), + ( + RootScreenType::RootScreenMasternodes, + Some(dpns::VotesView::History) + ) + ); + assert_eq!( + resolve_root_screen(RootScreenType::RootScreenDPNSScheduledVotes), + ( + RootScreenType::RootScreenMasternodes, + Some(dpns::VotesView::Scheduled) + ) + ); + assert_eq!( + resolve_root_screen(RootScreenType::RootScreenDPNSOwnedNames), + (RootScreenType::RootScreenIdentityHub, None) + ); + assert_eq!( + resolve_root_screen(RootScreenType::RootScreenWalletsBalances), + (RootScreenType::RootScreenWalletsBalances, None) + ); + } +} diff --git a/src/ui/state/dpns_contests.rs b/src/ui/state/dpns_contests.rs new file mode 100644 index 000000000..f1e7f7dc6 --- /dev/null +++ b/src/ui/state/dpns_contests.rs @@ -0,0 +1,100 @@ +//! Cached Active-contest data for the DPNS screen. + +use crate::context::AppContext; +use crate::model::contested_name::ContestedName; +use dash_sdk::platform::Identifier; +use std::sync::Arc; + +/// One Active contest with its precomputed Platform vote-poll identifier. +#[derive(Debug, Clone)] +pub struct ActiveDpnsContestView { + pub contest: Arc, + pub vote_poll_id: Option, +} + +/// Immutable render snapshot of the open contests for the Votes panel. +#[derive(Debug, Clone, Default)] +pub struct ActiveDpnsContestSnapshot { + contests: Arc<[ActiveDpnsContestView]>, +} + +impl ActiveDpnsContestSnapshot { + /// Build a snapshot while resolving each contest's vote-poll identifier once. + pub(crate) fn new(app_context: &AppContext, contests: Vec) -> Self { + Self::build(contests, |name| app_context.dpns_vote_poll_id(name).ok()) + } + + pub(crate) fn contests(&self) -> Arc<[ActiveDpnsContestView]> { + Arc::clone(&self.contests) + } + + pub(crate) fn is_empty(&self) -> bool { + self.contests.is_empty() + } + + pub(crate) fn vote_poll_ids(&self) -> Vec { + self.contests + .iter() + .filter_map(|view| view.vote_poll_id) + .collect() + } + + fn build( + contests: Vec, + mut poll_id: impl FnMut(&str) -> Option, + ) -> Self { + let contests = contests + .into_iter() + .map(|contest| { + let vote_poll_id = poll_id(&contest.normalized_contested_name); + ActiveDpnsContestView { + contest: Arc::new(contest), + vote_poll_id, + } + }) + .collect::>(); + Self { + contests: Arc::from(contests), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::contested_name::ContestState; + use dash_sdk::platform::Identifier; + use std::collections::BTreeMap; + + fn contest(name: &str) -> ContestedName { + ContestedName { + normalized_contested_name: name.to_owned(), + contestants: None, + locked_votes: None, + abstain_votes: None, + awarded_to: None, + end_time: None, + state: ContestState::Ongoing, + last_updated: None, + my_votes: BTreeMap::new(), + } + } + + #[test] + fn active_contest_snapshot_computes_each_poll_id_once() { + let mut calls = Vec::new(); + + let snapshot = + ActiveDpnsContestSnapshot::build(vec![contest("alice"), contest("bob")], |name| { + calls.push(name.to_owned()); + Some(Identifier::from([calls.len() as u8; 32])) + }); + + assert_eq!(calls, ["alice", "bob"]); + let contests = snapshot.contests(); + assert_eq!(contests.len(), 2); + assert_eq!(contests[0].contest.normalized_contested_name, "alice"); + assert_eq!(contests[0].vote_poll_id, Some(Identifier::from([1; 32]))); + assert_eq!(contests[1].vote_poll_id, Some(Identifier::from([2; 32]))); + } +} diff --git a/src/ui/state/dpns_vote_cards.rs b/src/ui/state/dpns_vote_cards.rs new file mode 100644 index 000000000..1fc37dd0c --- /dev/null +++ b/src/ui/state/dpns_vote_cards.rs @@ -0,0 +1,444 @@ +//! View-model for the Masternodes ▸ Votes contest cards. +//! +//! Built when contests, proved vote state, the journal or the node set change — +//! never per frame — so the render path only reads it. + +use crate::model::contested_name::ContestedName; +use crate::model::dpns_voting::operator::ChangesLeft; +use crate::model::dpns_voting::{DpnsCurrentVoteState, DpnsVoteTargetStatus}; +use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use dash_sdk::platform::Identifier; +use std::sync::Arc; + +/// Where one node-set node stands on one contest. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NodeContestStatus { + NotVoted, + Voted(ResourceVoteChoice), + /// Proved state could not be read; the node is left out (VOTE-FR-016). + Unavailable, + /// An unresolved operation is sending or checking this node × contest target. + InFlight, + /// A scheduled vote holds this node × contest target. + Scheduled, + /// The node has used all five votes on this contest. + NoChangesLeft(ResourceVoteChoice), +} + +impl NodeContestStatus { + /// Classify one node from its proved state, the status of the operation + /// holding its target lock (if any) and its changes left. + pub fn classify( + state: DpnsCurrentVoteState, + lock: Option, + changes: ChangesLeft, + ) -> Self { + match lock { + Some(DpnsVoteTargetStatus::Scheduled) => return Self::Scheduled, + Some(_) => return Self::InFlight, + None => {} + } + match state { + DpnsCurrentVoteState::Available(None) => Self::NotVoted, + DpnsCurrentVoteState::Available(Some(choice)) if changes.is_exhausted() => { + Self::NoChangesLeft(choice) + } + DpnsCurrentVoteState::Available(Some(choice)) => Self::Voted(choice), + DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable => Self::Unavailable, + } + } + + /// Whether a new decision can be sent with this node now. + pub fn can_submit(self) -> bool { + matches!(self, Self::NotVoted | Self::Voted(_)) + } +} + +/// One node-set node on one contest. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct NodeContestState { + pub node: Identifier, + pub status: NodeContestStatus, + pub current: Option, + pub changes: ChangesLeft, +} + +/// Why no node-set node can vote on a contest. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CantVoteReason { + NoVotingNodes, + VoteStateUnavailable, +} + +/// Which list a card appears in. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CardPlacement { + ToDecide, + Voted, + CantVote(CantVoteReason), +} + +/// Place a card from its nodes: To decide while any node has neither voted +/// nor a vote on its way (the same rule as the attention badge), Voted once +/// every reachable node has voted, is sending, or is scheduled. +pub fn place_card(nodes: &[NodeContestState]) -> CardPlacement { + if nodes.is_empty() { + return CardPlacement::CantVote(CantVoteReason::NoVotingNodes); + } + let any = + |predicate: fn(NodeContestStatus) -> bool| nodes.iter().any(|node| predicate(node.status)); + if any(|status| status == NodeContestStatus::NotVoted) { + CardPlacement::ToDecide + } else if any(|status| status != NodeContestStatus::Unavailable) { + CardPlacement::Voted + } else { + CardPlacement::CantVote(CantVoteReason::VoteStateUnavailable) + } +} + +/// One open contest as the Votes list shows it. +#[derive(Debug, Clone)] +pub struct VoteCard { + pub contest: Arc, + pub vote_poll_id: Option, + pub nodes: Vec, + pub placement: CardPlacement, +} + +impl VoteCard { + /// Build a card; `placement` follows [`place_card`]. + pub fn new( + contest: Arc, + vote_poll_id: Option, + nodes: Vec, + ) -> Self { + let placement = if vote_poll_id.is_some() { + place_card(&nodes) + } else { + CardPlacement::CantVote(CantVoteReason::VoteStateUnavailable) + }; + Self { + contest, + vote_poll_id, + nodes, + placement, + } + } + + /// The contest label (normalized, without `.dash`). + pub fn name(&self) -> &str { + &self.contest.normalized_contested_name + } + + pub fn count(&self, predicate: impl Fn(NodeContestStatus) -> bool) -> usize { + self.nodes + .iter() + .filter(|node| predicate(node.status)) + .count() + } + + /// Nodes that currently hold any vote on this contest. + pub fn voted_count(&self) -> usize { + self.nodes + .iter() + .filter(|node| node.current.is_some()) + .count() + } + + /// Nodes a new decision would be sent with. + pub fn submittable_count(&self) -> usize { + self.count(NodeContestStatus::can_submit) + } + + /// Nodes whose vote is being sent or checked. + pub fn in_flight_count(&self) -> usize { + self.count(|status| status == NodeContestStatus::InFlight) + } + + /// Nodes with a scheduled vote on this contest. + pub fn scheduled_count(&self) -> usize { + self.count(|status| status == NodeContestStatus::Scheduled) + } + + /// The choice every voted node shares, if they agree. + pub fn shared_choice(&self) -> Option { + let mut choices = self.nodes.iter().filter_map(|node| node.current); + let first = choices.next()?; + choices.all(|choice| choice == first).then_some(first) + } + + /// Whether the operator can pick a decision on this card at all. + pub fn accepts_decision(&self) -> bool { + self.submittable_count() > 0 + } +} + +/// A contest-list shortcut (VOTE-FR-082). Each has a visible control: card +/// focus by click, decision pills, the card checkbox, and the tray's Cast. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Shortcut { + Next, + Previous, + /// Vote for the n-th contender (0-based). + Contender(usize), + Lock, + Abstain, + Clear, + ToggleSelected, + Confirm, +} + +/// The shortcut bound to an unmodified key press, if any. +pub fn shortcut_for(key: eframe::egui::Key) -> Option { + use eframe::egui::Key; + Some(match key { + Key::J | Key::ArrowDown => Shortcut::Next, + Key::K | Key::ArrowUp => Shortcut::Previous, + Key::Num1 => Shortcut::Contender(0), + Key::Num2 => Shortcut::Contender(1), + Key::Num3 => Shortcut::Contender(2), + Key::Num4 => Shortcut::Contender(3), + Key::Num5 => Shortcut::Contender(4), + Key::Num6 => Shortcut::Contender(5), + Key::Num7 => Shortcut::Contender(6), + Key::Num8 => Shortcut::Contender(7), + Key::Num9 => Shortcut::Contender(8), + Key::L => Shortcut::Lock, + Key::A => Shortcut::Abstain, + Key::Num0 => Shortcut::Clear, + Key::Space => Shortcut::ToggleSelected, + Key::Enter => Shortcut::Confirm, + _ => return None, + }) +} + +/// The `Shortcuts` popover rows: keys and what they do. +pub const SHORTCUT_HELP: [(&str, &str); 7] = [ + ("J / ↓", "Next name"), + ("K / ↑", "Previous name"), + ("1–9", "Vote for that contender"), + ("L / A", "Lock name / Abstain"), + ("0", "Clear the decision"), + ("Space", "Select for a bulk decision"), + ("Enter", "Review and cast"), +]; + +/// Move focus within `len` listed cards; wraps neither way. +pub fn move_focus(current: Option, len: usize, shortcut: Shortcut) -> Option { + if len == 0 { + return None; + } + Some(match (current, shortcut) { + (None, _) => 0, + (Some(index), Shortcut::Next) => (index + 1).min(len - 1), + (Some(index), Shortcut::Previous) => index.saturating_sub(1), + (Some(index), _) => index.min(len - 1), + }) +} + +/// Order cards by time left; contests without a known deadline go last. +pub fn sort_by_time_left(cards: &mut [VoteCard]) { + cards.sort_by(|a, b| { + a.contest + .end_time + .unwrap_or(u64::MAX) + .cmp(&b.contest.end_time.unwrap_or(u64::MAX)) + .then_with(|| a.name().cmp(b.name())) + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::contested_name::ContestState; + use std::collections::BTreeMap; + + fn contest(name: &str, end_time: Option) -> Arc { + Arc::new(ContestedName { + normalized_contested_name: name.to_owned(), + contestants: None, + locked_votes: None, + abstain_votes: None, + awarded_to: None, + end_time, + state: ContestState::Ongoing, + last_updated: None, + my_votes: BTreeMap::new(), + }) + } + + fn node(byte: u8, status: NodeContestStatus) -> NodeContestState { + let current = match status { + NodeContestStatus::Voted(choice) | NodeContestStatus::NoChangesLeft(choice) => { + Some(choice) + } + _ => None, + }; + NodeContestState { + node: Identifier::from([byte; 32]), + status, + current, + changes: ChangesLeft::Known(4), + } + } + + #[test] + fn classification_puts_locks_first_and_exhaustion_on_voted_nodes() { + let lock = ResourceVoteChoice::Lock; + assert_eq!( + NodeContestStatus::classify( + DpnsCurrentVoteState::Available(None), + Some(DpnsVoteTargetStatus::Unconfirmed), + ChangesLeft::Known(4) + ), + NodeContestStatus::InFlight + ); + assert_eq!( + NodeContestStatus::classify( + DpnsCurrentVoteState::Available(None), + Some(DpnsVoteTargetStatus::Scheduled), + ChangesLeft::Known(4) + ), + NodeContestStatus::Scheduled + ); + assert_eq!( + NodeContestStatus::classify( + DpnsCurrentVoteState::Available(Some(lock)), + None, + ChangesLeft::Known(0) + ), + NodeContestStatus::NoChangesLeft(lock) + ); + assert_eq!( + NodeContestStatus::classify( + DpnsCurrentVoteState::Available(Some(lock)), + None, + ChangesLeft::Unknown + ), + NodeContestStatus::Voted(lock), + "unknown changes never block a change; Platform enforces the limit" + ); + assert_eq!( + NodeContestStatus::classify( + DpnsCurrentVoteState::Checking, + None, + ChangesLeft::Known(4) + ), + NodeContestStatus::Unavailable + ); + } + + /// VOTE-TC-089: a partly voted contest stays in To decide. + #[test] + fn partly_voted_contest_stays_to_decide() { + let lock = ResourceVoteChoice::Lock; + let mut nodes = vec![node(1, NodeContestStatus::NotVoted)]; + nodes.extend((2..=6).map(|byte| node(byte, NodeContestStatus::Voted(lock)))); + let card = VoteCard::new( + contest("alice", Some(1)), + Some(Identifier::from([9; 32])), + nodes, + ); + assert_eq!(card.placement, CardPlacement::ToDecide); + assert_eq!(card.voted_count(), 5); + assert_eq!(card.nodes.len(), 6); + } + + /// VOTE-TC-002: once every node voted the card moves to Voted and stays changeable. + #[test] + fn fully_voted_contest_moves_to_voted_and_accepts_a_change() { + let lock = ResourceVoteChoice::Lock; + let card = VoteCard::new( + contest("alice", Some(1)), + Some(Identifier::from([9; 32])), + vec![ + node(1, NodeContestStatus::Voted(lock)), + node(2, NodeContestStatus::Unavailable), + ], + ); + assert_eq!(card.placement, CardPlacement::Voted); + assert_eq!(card.shared_choice(), Some(lock)); + assert!(card.accepts_decision()); + assert_eq!( + card.submittable_count(), + 1, + "VOTE-TC-007: the unavailable node is left out" + ); + } + + /// VOTE-TC-041: a card whose only node is sending needs no decision and + /// locks that node's choices. + #[test] + fn in_flight_card_needs_no_decision_and_locks_its_nodes() { + let card = VoteCard::new( + contest("alice", Some(1)), + Some(Identifier::from([9; 32])), + vec![node(1, NodeContestStatus::InFlight)], + ); + assert_eq!(card.placement, CardPlacement::Voted); + assert_eq!(card.in_flight_count(), 1); + assert!(!card.accepts_decision()); + } + + #[test] + fn cards_without_usable_nodes_explain_why() { + let none = VoteCard::new(contest("a", None), Some(Identifier::from([9; 32])), vec![]); + assert_eq!( + none.placement, + CardPlacement::CantVote(CantVoteReason::NoVotingNodes) + ); + let unavailable = VoteCard::new( + contest("b", None), + Some(Identifier::from([9; 32])), + vec![node(1, NodeContestStatus::Unavailable)], + ); + assert_eq!( + unavailable.placement, + CardPlacement::CantVote(CantVoteReason::VoteStateUnavailable) + ); + let exhausted = VoteCard::new( + contest("c", None), + Some(Identifier::from([9; 32])), + vec![node( + 1, + NodeContestStatus::NoChangesLeft(ResourceVoteChoice::Abstain), + )], + ); + assert_eq!(exhausted.placement, CardPlacement::Voted); + assert!(!exhausted.accepts_decision()); + } + + /// VOTE-TC-098 (key map half): keys map to shortcuts; focus stays in bounds. + #[test] + fn shortcuts_map_keys_and_bound_focus() { + use eframe::egui::Key; + assert_eq!(shortcut_for(Key::J), Some(Shortcut::Next)); + assert_eq!(shortcut_for(Key::ArrowUp), Some(Shortcut::Previous)); + assert_eq!(shortcut_for(Key::Num2), Some(Shortcut::Contender(1))); + assert_eq!(shortcut_for(Key::L), Some(Shortcut::Lock)); + assert_eq!(shortcut_for(Key::Num0), Some(Shortcut::Clear)); + assert_eq!(shortcut_for(Key::Q), None); + assert_eq!(move_focus(None, 3, Shortcut::Next), Some(0)); + assert_eq!(move_focus(Some(2), 3, Shortcut::Next), Some(2)); + assert_eq!(move_focus(Some(0), 3, Shortcut::Previous), Some(0)); + assert_eq!(move_focus(Some(1), 3, Shortcut::Previous), Some(0)); + assert_eq!(move_focus(Some(1), 0, Shortcut::Next), None); + } + + /// VOTE-TC-088: sorted by time left, unknown deadlines last. + #[test] + fn cards_sort_by_time_left() { + let poll = Some(Identifier::from([9; 32])); + let mut cards = vec![ + VoteCard::new(contest("four-days", Some(4 * 86_400_000)), poll, vec![]), + VoteCard::new(contest("unknown", None), poll, vec![]), + VoteCard::new(contest("twelve-min", Some(720_000)), poll, vec![]), + VoteCard::new(contest("six-hours", Some(21_600_000)), poll, vec![]), + ]; + sort_by_time_left(&mut cards); + assert_eq!( + cards.iter().map(VoteCard::name).collect::>(), + vec!["twelve-min", "six-hours", "four-days", "unknown"] + ); + } +} diff --git a/src/ui/state/dpns_vote_operations.rs b/src/ui/state/dpns_vote_operations.rs new file mode 100644 index 000000000..7cc74bfd7 --- /dev/null +++ b/src/ui/state/dpns_vote_operations.rs @@ -0,0 +1,603 @@ +//! Per-screen DPNS vote-operation snapshot for immediate-mode render paths. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +use crate::backend_task::contested_names::ScheduledDPNSVote; +use crate::backend_task::error::TaskError; +use crate::context::AppContext; +use crate::model::dpns_voting::{ + DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTargetKey, + DpnsVoteTargetStatus, VoteTiming, authoritative_dpns_vote_outcomes, +}; + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct ScheduledDpnsVoteRow { + pub vote: ScheduledDPNSVote, + pub journal_target: (DpnsVoteOperationId, DpnsVoteTargetKey), + pub status: DpnsVoteTargetStatus, + pub failure: Option, +} + +/// Scheduled rows sharing one decision: name × choice × time (VOTE-FR-088). +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct ScheduledDecisionGroup { + pub contested_name: String, + pub choice: dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice, + pub unix_timestamp: u64, + pub rows: Vec, +} + +/// Group scheduled rows by decision, ordered by name then time; rows keep +/// their input order inside a group. +pub(crate) fn group_scheduled_rows(rows: Vec) -> Vec { + let mut groups: Vec = Vec::new(); + let mut indices = BTreeMap::new(); + for row in rows { + let key = ( + row.vote.contested_name.clone(), + row.vote.choice, + row.vote.unix_timestamp, + ); + let index = *indices.entry(key).or_insert_with(|| { + groups.push(ScheduledDecisionGroup { + contested_name: row.vote.contested_name.clone(), + choice: row.vote.choice, + unix_timestamp: row.vote.unix_timestamp, + rows: Vec::new(), + }); + groups.len() - 1 + }); + groups[index].rows.push(row); + } + groups.sort_by(|a, b| { + a.contested_name + .cmp(&b.contested_name) + .then(a.unix_timestamp.cmp(&b.unix_timestamp)) + }); + groups +} + +#[derive(Debug, Clone, Default)] +pub struct DpnsVoteOperationSnapshot { + operations: Vec, + published: Option]>>, + dismissed_schedules: BTreeSet<(DpnsVoteOperationId, DpnsVoteTargetKey)>, + target_statuses: BTreeMap, + loaded: bool, + read_error: Option>, +} + +impl DpnsVoteOperationSnapshot { + pub fn load(app_context: &AppContext) -> Self { + let mut snapshot = Self::default(); + let _ = snapshot.refresh(app_context); + snapshot + } + + pub fn refresh(&mut self, app_context: &AppContext) -> Result<(), Arc> { + let result = (|| { + Ok::<_, TaskError>(( + app_context.dpns_vote_operations()?, + app_context.dismissed_dpns_vote_schedules()?, + )) + })(); + let (operations, dismissals) = result.map_err(|error| { + let error = Arc::new(error); + self.read_error = Some(error.clone()); + error + })?; + self.replace(operations); + self.dismissed_schedules = dismissals; + self.read_error = None; + Ok(()) + } + + /// Adopt backend progress without reading storage on a render frame. + /// + /// Returns each changed outcome with the status it had before, `None` for + /// a target seen for the first time. + pub(crate) fn sync_progress( + &mut self, + app_context: &AppContext, + ) -> Option, DpnsVoteOutcome)>> { + let published = app_context.dpns_vote_progress(); + if self + .published + .as_ref() + .is_some_and(|previous| Arc::ptr_eq(previous, &published)) + { + return None; + } + let previous: BTreeMap<_, _> = self + .operations + .iter() + .flat_map(|operation| { + operation + .targets + .iter() + .map(move |outcome| ((operation.id, &outcome.target.key), outcome)) + }) + .collect(); + let changed = published + .iter() + .flat_map(|operation| operation.targets.iter()) + .filter_map(|outcome| { + let old = previous.get(&(outcome.operation_id, &outcome.target.key)); + old.is_none_or(|old| **old != *outcome) + .then(|| (old.map(|old| old.status), outcome.clone())) + }) + .collect(); + // Keep this snapshot's copy of every operation the publication left as + // it was; only a changed operation is copied. + let mut kept: BTreeMap<_, _> = std::mem::take(&mut self.operations) + .into_iter() + .map(|operation| (operation.id, operation)) + .collect(); + let operations = published + .iter() + .map(|operation| match kept.remove(&operation.id) { + Some(current) if current == **operation => current, + _ => operation.as_ref().clone(), + }) + .collect(); + self.replace(operations); + self.published = Some(published); + Some(changed) + } + + pub(crate) fn read_error(&self) -> Option<&Arc> { + self.read_error.as_ref() + } + + pub fn operations(&self) -> &[DpnsVoteOperation] { + &self.operations + } + + pub fn operation(&self, id: DpnsVoteOperationId) -> Option<&DpnsVoteOperation> { + self.operations.iter().find(|operation| operation.id == id) + } + + pub fn target_status(&self, key: &DpnsVoteTargetKey) -> Option { + self.target_statuses.get(key).copied() + } + + pub fn is_loaded(&self) -> bool { + self.loaded + } + + pub(crate) fn scheduled_vote_rows(&self) -> Vec { + authoritative_dpns_vote_outcomes(&self.operations, |outcome| { + matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + }) + .into_values() + .filter_map(|(operation, outcome)| { + let VoteTiming::Scheduled(timestamp) = outcome.target.timing else { + return None; + }; + Some(ScheduledDpnsVoteRow { + vote: ScheduledDPNSVote { + contested_name: outcome.target.contested_name.clone(), + voter_id: outcome.target.key.voter_id, + choice: outcome.target.requested_choice, + unix_timestamp: timestamp, + executed_successfully: outcome.status == DpnsVoteTargetStatus::Confirmed, + }, + journal_target: (operation.id, outcome.target.key.clone()), + status: outcome.status, + failure: outcome.failure, + }) + }) + .filter(|row| row.status != DpnsVoteTargetStatus::Cancelled) + .filter(|row| !self.dismissed_schedules.contains(&row.journal_target)) + .collect() + } + + fn replace(&mut self, operations: Vec) { + self.target_statuses = operations + .iter() + .flat_map(|operation| &operation.targets) + .filter(|outcome| outcome.status.holds_lock()) + .map(|outcome| (outcome.target.key.clone(), outcome.status)) + .collect(); + self.operations = operations; + self.loaded = true; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::backend_task::contested_names::ScheduledDPNSVote; + use crate::model::dpns_voting::{DpnsVoteTarget, VoteTiming}; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; + use dash_sdk::platform::Identifier; + + #[test] + fn screen_adopts_live_progress_without_reading_storage() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let store = Arc::new(crate::wallet_backend::kv_test_support::FailingKv::default()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(store.clone())); + let mut snapshot = DpnsVoteOperationSnapshot::load(&ctx); + let mut operation = operation(DpnsVoteTargetStatus::Queued); + let key = operation.targets[0].target.key.clone(); + ctx.insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + store.fail_all_reads(true); + assert!(snapshot.sync_progress(&ctx).is_some()); + assert_eq!( + snapshot.target_status(&key), + Some(DpnsVoteTargetStatus::Queued) + ); + assert!(snapshot.sync_progress(&ctx).is_none()); + store.fail_all_reads(false); + ctx.claim_dpns_vote_target(operation.id, &key).unwrap(); + store.fail_all_reads(true); + assert!(snapshot.sync_progress(&ctx).is_some()); + assert_eq!( + snapshot.target_status(&key), + Some(DpnsVoteTargetStatus::Submitting) + ); + assert!(snapshot.read_error().is_none()); + } + + /// Adopting one operation's progress keeps the snapshot's copy of every + /// operation that did not change. + #[test] + fn adopting_progress_copies_only_the_changed_operation() { + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + ctx.set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(Arc::new( + crate::wallet_backend::kv_test_support::InMemoryKv::default(), + ))); + let mut changed = operation(DpnsVoteTargetStatus::Queued); + let mut untouched = operation(DpnsVoteTargetStatus::Queued); + untouched.targets[0].target.key.vote_poll_id = Identifier::from([3; 32]); + let key = changed.targets[0].target.key.clone(); + ctx.insert_dpns_vote_operation(&mut changed, None).unwrap(); + ctx.insert_dpns_vote_operation(&mut untouched, None) + .unwrap(); + let mut snapshot = DpnsVoteOperationSnapshot::default(); + assert!(snapshot.sync_progress(&ctx).is_some()); + let kept = snapshot.operation(untouched.id).unwrap().targets.as_ptr(); + + ctx.claim_dpns_vote_target(changed.id, &key).unwrap(); + let changes = snapshot.sync_progress(&ctx).expect("new progress"); + + assert_eq!(changes.len(), 1); + assert_eq!( + snapshot.operation(changed.id).unwrap().targets[0].status, + DpnsVoteTargetStatus::Submitting + ); + assert_eq!( + snapshot.operation(untouched.id).unwrap().targets.as_ptr(), + kept, + "the unchanged operation is kept, not copied again" + ); + } + + #[test] + fn voting_ui_dismissed_terminal_row_preserves_siblings() { + let mut operation = scheduled_operation( + 10, + DpnsVoteTargetStatus::Confirmed, + ResourceVoteChoice::Lock, + 100, + ); + let dismissed = (operation.id, operation.targets[0].target.key.clone()); + let original = operation.targets[0].clone(); + let mut sibling = original.clone(); + sibling.target.key.vote_poll_id = Identifier::from([12; 32]); + sibling.target.contested_name = "bob".into(); + operation.targets.push(sibling); + let mut snapshot = DpnsVoteOperationSnapshot::default(); + snapshot.replace(vec![operation]); + snapshot.dismissed_schedules.insert(dismissed); + let rows = snapshot.scheduled_vote_rows(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].vote.contested_name, "bob"); + assert_eq!(snapshot.operations()[0].targets[0], original); + } + + fn operation(status: DpnsVoteTargetStatus) -> DpnsVoteOperation { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([2; 32]), + }, + voter_alias: None, + contested_name: "dominguez".to_owned(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Now, + }]); + operation.targets[0].status = status; + operation + } + + #[test] + fn snapshot_indexes_only_lock_holding_targets() { + let live = operation(DpnsVoteTargetStatus::Submitting); + let mut terminal = operation(DpnsVoteTargetStatus::Confirmed); + terminal.targets[0].target.key.vote_poll_id = Identifier::from([3; 32]); + let live_key = live.targets[0].target.key.clone(); + let terminal_key = terminal.targets[0].target.key.clone(); + let mut snapshot = DpnsVoteOperationSnapshot::default(); + + snapshot.replace(vec![live.clone(), terminal.clone()]); + + assert_eq!( + snapshot.target_status(&live_key), + Some(DpnsVoteTargetStatus::Submitting) + ); + assert_eq!(snapshot.target_status(&terminal_key), None); + assert_eq!(snapshot.operation(live.id), Some(&live)); + assert_eq!(snapshot.operations(), &[live, terminal]); + assert!(snapshot.is_loaded()); + } + + /// VOTE-TC-069: one decision on many nodes is one group. + #[test] + fn scheduled_rows_group_by_decision() { + let row = |voter: u8, name: &str, choice, timestamp| ScheduledDpnsVoteRow { + vote: scheduled_vote( + Identifier::from([voter; 32]), + name, + choice, + timestamp, + false, + ), + journal_target: ( + DpnsVoteOperationId::from_bytes([1; 16]), + DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([2; 32]), + }, + ), + status: DpnsVoteTargetStatus::Scheduled, + failure: None, + }; + let lock = ResourceVoteChoice::Lock; + let mut rows: Vec<_> = (0..24).map(|voter| row(voter, "bob", lock, 50)).collect(); + rows.push(row(1, "alice", lock, 90)); + rows.push(row(2, "alice", ResourceVoteChoice::Abstain, 90)); + rows.push(row(3, "alice", lock, 10)); + let groups = group_scheduled_rows(rows); + assert_eq!( + groups + .iter() + .map(|group| ( + group.contested_name.as_str(), + group.unix_timestamp, + group.rows.len() + )) + .collect::>(), + vec![ + ("alice", 10, 1), + ("alice", 90, 1), + ("alice", 90, 1), + ("bob", 50, 24) + ] + ); + } + + /// A schedule that still holds its lock outranks a newer terminal record + /// for the same target, as everywhere else that picks an authority. + #[test] + fn scheduled_rows_prefer_the_lock_holder_over_newer_history() { + let pending = scheduled_operation( + 10, + DpnsVoteTargetStatus::Scheduled, + ResourceVoteChoice::Lock, + 100, + ); + let newer_rejected = scheduled_operation( + 20, + DpnsVoteTargetStatus::Rejected, + ResourceVoteChoice::Abstain, + 200, + ); + let mut snapshot = DpnsVoteOperationSnapshot::default(); + snapshot.replace(vec![pending.clone(), newer_rejected]); + + let rows = snapshot.scheduled_vote_rows(); + + assert_eq!(rows.len(), 1); + assert_eq!(Some(rows[0].journal_target.0), Some(pending.id)); + assert_eq!(rows[0].status, DpnsVoteTargetStatus::Scheduled); + } + + fn scheduled_operation( + created_at: u64, + status: DpnsVoteTargetStatus, + choice: ResourceVoteChoice, + timestamp: u64, + ) -> DpnsVoteOperation { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([7; 32]), + vote_poll_id: Identifier::from([8; 32]), + }, + voter_alias: Some("node-7".to_owned()), + contested_name: "alice".to_owned(), + requested_choice: choice, + current_choice: None, + timing: VoteTiming::Scheduled(timestamp), + }]); + operation.created_at = created_at; + operation.targets[0].status = status; + operation + } + + fn scheduled_vote( + voter_id: Identifier, + name: &str, + choice: ResourceVoteChoice, + timestamp: u64, + executed_successfully: bool, + ) -> ScheduledDPNSVote { + ScheduledDPNSVote { + contested_name: name.to_owned(), + voter_id, + choice, + unix_timestamp: timestamp, + executed_successfully, + } + } + + #[test] + fn scheduled_rows_keep_distinct_polls_and_networks_with_the_same_name() { + let first = scheduled_operation( + 10, + DpnsVoteTargetStatus::Scheduled, + ResourceVoteChoice::Lock, + 100, + ); + let mut second = first.clone(); + second.targets[0].target.key.vote_poll_id = Identifier::from([99; 32]); + let mut third = first.clone(); + third.targets[0].target.key.network = Network::Mainnet; + let mut snapshot = DpnsVoteOperationSnapshot::default(); + snapshot.replace(vec![first, second, third]); + assert_eq!(snapshot.scheduled_vote_rows().len(), 3); + } + + #[test] + fn scheduled_rows_prefer_the_newest_journal_outcome() { + let older = scheduled_operation( + 10, + DpnsVoteTargetStatus::Confirmed, + ResourceVoteChoice::Lock, + 100, + ); + let newer = scheduled_operation( + 20, + DpnsVoteTargetStatus::Rejected, + ResourceVoteChoice::Abstain, + 200, + ); + let expected_id = newer.id; + let expected_key = newer.targets[0].target.key.clone(); + let mut snapshot = DpnsVoteOperationSnapshot::default(); + snapshot.replace(vec![older, newer]); + + let rows = snapshot.scheduled_vote_rows(); + + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].journal_target, (expected_id, expected_key)); + assert_eq!(rows[0].status, DpnsVoteTargetStatus::Rejected); + assert_eq!(rows[0].vote.choice, ResourceVoteChoice::Abstain); + assert_eq!(rows[0].vote.unix_timestamp, 200); + assert!(!rows[0].vote.executed_successfully); + } + + /// Operations stamped in the same millisecond break the tie on the + /// operation id, not on persisted order — the rule every other site uses. + #[test] + fn scheduled_rows_break_created_time_ties_on_the_operation_id() { + let mut first = scheduled_operation( + 10, + DpnsVoteTargetStatus::Rejected, + ResourceVoteChoice::Lock, + 100, + ); + first.id = DpnsVoteOperationId::from_bytes([2; 16]); + let mut second = scheduled_operation( + 10, + DpnsVoteTargetStatus::NotApplied, + ResourceVoteChoice::Abstain, + 200, + ); + second.id = DpnsVoteOperationId::from_bytes([1; 16]); + let expected_id = first.id; + let mut snapshot = DpnsVoteOperationSnapshot::default(); + snapshot.replace(vec![first, second]); + + let rows = snapshot.scheduled_vote_rows(); + + assert_eq!(rows.len(), 1); + assert_eq!(Some(rows[0].journal_target.0), Some(expected_id)); + assert_eq!(rows[0].status, DpnsVoteTargetStatus::Rejected); + assert_eq!(rows[0].vote.unix_timestamp, 100); + } + + /// Removing a scheduled vote cancels its journal target. The row must then + /// disappear instead of returning with a Remove button that does nothing. + #[test] + fn cancelled_scheduled_targets_stop_projecting_a_row() { + let cancelled = scheduled_operation( + 10, + DpnsVoteTargetStatus::Cancelled, + ResourceVoteChoice::Lock, + 100, + ); + let mut snapshot = DpnsVoteOperationSnapshot::default(); + snapshot.replace(vec![cancelled]); + + assert!(snapshot.scheduled_vote_rows().is_empty()); + } + + #[test] + fn cancelled_targets_are_not_shown() { + let cancelled = scheduled_operation( + 10, + DpnsVoteTargetStatus::Cancelled, + ResourceVoteChoice::Lock, + 100, + ); + let mut snapshot = DpnsVoteOperationSnapshot::default(); + snapshot.replace(vec![cancelled]); + + let rows = snapshot.scheduled_vote_rows(); + + assert!(rows.is_empty()); + } + + /// A bulk schedule is one operation with many targets, so cancelling one of + /// them leaves the operation live. Only the cancelled row may disappear. + #[test] + fn cancelling_one_target_keeps_the_other_rows_of_its_operation() { + let mut operation = scheduled_operation( + 10, + DpnsVoteTargetStatus::Cancelled, + ResourceVoteChoice::Lock, + 100, + ); + let mut surviving = operation.targets[0].clone(); + surviving.target.key.vote_poll_id = Identifier::from([12; 32]); + surviving.target.contested_name = "bob".to_owned(); + surviving.status = DpnsVoteTargetStatus::Scheduled; + operation.targets.push(surviving); + let mut snapshot = DpnsVoteOperationSnapshot::default(); + snapshot.replace(vec![operation]); + + let rows = snapshot.scheduled_vote_rows(); + + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].vote.contested_name, "bob"); + assert_eq!(rows[0].status, DpnsVoteTargetStatus::Scheduled); + } + + #[test] + fn scheduled_rows_mark_only_confirmed_votes_as_executed() { + let confirmed = scheduled_operation( + 10, + DpnsVoteTargetStatus::Confirmed, + ResourceVoteChoice::Lock, + 100, + ); + let mut snapshot = DpnsVoteOperationSnapshot::default(); + snapshot.replace(vec![confirmed]); + + let rows = snapshot.scheduled_vote_rows(); + + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].status, DpnsVoteTargetStatus::Confirmed); + assert!(rows[0].vote.executed_successfully); + } +} diff --git a/src/ui/state/dpns_vote_state.rs b/src/ui/state/dpns_vote_state.rs new file mode 100644 index 000000000..f2e9e0e28 --- /dev/null +++ b/src/ui/state/dpns_vote_state.rs @@ -0,0 +1,171 @@ +//! Per-screen cache of proved DPNS vote state for immediate-mode rendering. + +use std::collections::BTreeMap; + +use dash_sdk::platform::Identifier; + +use crate::backend_task::error::TaskError; +use crate::context::AppContext; +use crate::model::dpns_voting::DpnsCurrentVoteState; + +#[derive(Debug, Clone, Default)] +pub struct DpnsVoteStateSnapshot { + states: BTreeMap<(Identifier, Identifier), DpnsCurrentVoteState>, + /// When each available state was proved, Unix ms. + proved_at: BTreeMap<(Identifier, Identifier), u64>, + loaded: bool, +} + +impl DpnsVoteStateSnapshot { + pub fn load( + app_context: &AppContext, + voter_ids: &[Identifier], + vote_poll_ids: &[Identifier], + ) -> Result { + let mut snapshot = Self::default(); + snapshot.refresh(app_context, voter_ids, vote_poll_ids)?; + Ok(snapshot) + } + + /// Publish successful reads and mark failed voter reads unavailable before returning an error. + pub fn refresh( + &mut self, + app_context: &AppContext, + voter_ids: &[Identifier], + vote_poll_ids: &[Identifier], + ) -> Result<(), TaskError> { + self.refresh_voters( + app_context, + voter_ids + .iter() + .map(|voter| (*voter, vote_poll_ids.to_vec())), + ) + } + + pub(crate) fn reload(&mut self, app_context: &AppContext) -> Result<(), TaskError> { + let mut polls_by_voter = BTreeMap::>::new(); + for &(voter_id, vote_poll_id) in self.states.keys() { + polls_by_voter + .entry(voter_id) + .or_default() + .push(vote_poll_id); + } + + self.refresh_voters(app_context, polls_by_voter) + } + + fn refresh_voters( + &mut self, + app_context: &AppContext, + polls_by_voter: impl IntoIterator)>, + ) -> Result<(), TaskError> { + let mut states = BTreeMap::new(); + let mut proved_at = BTreeMap::new(); + let mut first_error = None; + for (voter_id, vote_poll_ids) in polls_by_voter { + let voter_states = match app_context + .dpns_current_vote_states_with_proof_time(voter_id, vote_poll_ids.iter().copied()) + { + Ok(states) => states, + Err(error) => { + first_error.get_or_insert(error); + vote_poll_ids + .into_iter() + .map(|poll| (poll, (DpnsCurrentVoteState::Unavailable, None))) + .collect() + } + }; + for (poll_id, (state, proved)) in voter_states { + states.insert((voter_id, poll_id), state); + if let Some(proved) = proved { + proved_at.insert((voter_id, poll_id), proved); + } + } + } + self.states = states; + self.proved_at = proved_at; + self.loaded = true; + first_error.map_or(Ok(()), Err) + } + + pub fn state(&self, voter_id: Identifier, vote_poll_id: Identifier) -> DpnsCurrentVoteState { + if !self.loaded { + return DpnsCurrentVoteState::Unavailable; + } + self.states + .get(&(voter_id, vote_poll_id)) + .copied() + .unwrap_or(DpnsCurrentVoteState::Unavailable) + } + + /// When the state [`Self::state`] returns was proved, Unix ms; `None` + /// unless it is available. + pub fn proved_at(&self, voter_id: Identifier, vote_poll_id: Identifier) -> Option { + self.proved_at.get(&(voter_id, vote_poll_id)).copied() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn voting_ui_failed_snapshot_read_invalidates_only_the_affected_voter() { + use crate::wallet_backend::{DetKv, kv_test_support::FailingKv}; + use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; + use std::sync::Arc; + + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(FailingKv::default()); + let kv = DetKv::from_store(store.clone()); + let context = crate::context::test_support::test_app_context_with_kv( + dir.path(), + Arc::new(kv.clone()), + ); + context.set_det_kv_override_for_test(kv); + let voters = [Identifier::from([1; 32]), Identifier::from([2; 32])]; + let poll = Identifier::from([3; 32]); + for voter in voters { + context + .cache_confirmed_dpns_vote(voter, poll, ResourceVoteChoice::Lock) + .unwrap(); + } + let mut snapshot = DpnsVoteStateSnapshot::load(&context, &voters, &[poll]).unwrap(); + for reload in [false, true] { + snapshot.refresh(&context, &voters, &[poll]).unwrap(); + store.fail_next_gets_containing("dpns", 1); + let result = if reload { + snapshot.reload(&context) + } else { + snapshot.refresh(&context, &voters, &[poll]) + }; + assert!(result.is_err()); + assert_eq!( + snapshot.state(voters[0], poll), + DpnsCurrentVoteState::Unavailable + ); + assert_eq!( + snapshot.state(voters[1], poll), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + } + } + + #[test] + fn render_lookups_use_only_the_in_memory_snapshot() { + let voter = Identifier::from([1; 32]); + let poll = Identifier::from([2; 32]); + let snapshot = DpnsVoteStateSnapshot { + states: BTreeMap::from([((voter, poll), DpnsCurrentVoteState::Available(None))]), + proved_at: BTreeMap::new(), + loaded: true, + }; + + for _ in 0..120 { + assert_eq!( + snapshot.state(voter, poll), + DpnsCurrentVoteState::Available(None) + ); + } + } +} diff --git a/src/ui/state/mod.rs b/src/ui/state/mod.rs index 120973d14..28ea489b3 100644 --- a/src/ui/state/mod.rs +++ b/src/ui/state/mod.rs @@ -10,6 +10,10 @@ pub mod asset_lock_balance; pub mod avatar_cache; pub mod contacts_view; pub mod derived_key_chooser; +pub mod dpns_contests; +pub mod dpns_vote_cards; +pub mod dpns_vote_operations; +pub mod dpns_vote_state; pub mod global_nav; pub mod hub_selection; pub mod legacy_recovery; diff --git a/src/ui/tools/mod.rs b/src/ui/tools/mod.rs index 52d2b8c0b..68998141b 100644 --- a/src/ui/tools/mod.rs +++ b/src/ui/tools/mod.rs @@ -16,7 +16,6 @@ pub enum ToolsSubscreen { ProofViewer, ContractViewer, GroveSTARK, - DPNS, } impl ToolsSubscreen { @@ -29,7 +28,6 @@ impl ToolsSubscreen { Self::DocumentViewer => "Document deserializer", Self::ContractViewer => "Contract deserializer", Self::GroveSTARK => "ZK Proofs", - Self::DPNS => "DPNS", } } } diff --git a/src/ui/wallets/shielded_tab.rs b/src/ui/wallets/shielded_tab.rs index e68125b91..0bbba9a9c 100644 --- a/src/ui/wallets/shielded_tab.rs +++ b/src/ui/wallets/shielded_tab.rs @@ -949,19 +949,17 @@ mod tests { derive_shielded_indicator( &MigrationState::SucceededWithUnreadableData { identities: 0, - votes: 1, - top_ups: 0, + top_ups: 1, }, false, ), ShieldedIndicator::Verified, - "an unreadable vote row says nothing about shielded data — the drain completed", + "an unreadable top-up row says nothing about shielded data — the drain completed", ); assert_eq!( derive_shielded_indicator( &MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 0, top_ups: 0, }, false, @@ -973,8 +971,7 @@ mod tests { derive_shielded_indicator( &MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 2, - top_ups: 0, + top_ups: 2, }, false, ), diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 574b3edf9..cf070af6d 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -3,3 +3,4 @@ pub mod egui_mpsc; pub(crate) mod file_deletion; pub mod parsers; pub mod tasks; +pub mod time; diff --git a/src/utils/time.rs b/src/utils/time.rs new file mode 100644 index 000000000..e09efcd51 --- /dev/null +++ b/src/utils/time.rs @@ -0,0 +1,15 @@ +//! Wall-clock helpers shared across layers. + +use std::time::{SystemTime, UNIX_EPOCH}; + +/// Milliseconds since the Unix epoch, saturating to `0` on a pre-epoch clock. +/// +/// The single spelling of "now in millis": journal timestamps, schedule +/// deadlines and proved-snapshot freshness are all compared against each other, +/// so they must not drift apart on how a bad clock is handled. +pub fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as u64 +} diff --git a/src/wallet_backend/dashpay.rs b/src/wallet_backend/dashpay.rs index 7d75fa0bc..20bc155ab 100644 --- a/src/wallet_backend/dashpay.rs +++ b/src/wallet_backend/dashpay.rs @@ -2262,7 +2262,7 @@ mod tests { let kv = DetKv::from_store(store.clone()); let timestamps = ProfileTimestamps::default(); let owner = id_from_byte(1); - store.fail_next_puts(2); + store.fail_next_puts_containing("", 2); assert!(timestamps.set(&kv, &owner, (111, 222)).is_err()); // Even while storage is unavailable the view must see the successful write's times. assert_eq!(timestamps.get(&kv, &owner), (111, 222)); @@ -2296,7 +2296,7 @@ mod tests { let timestamps = ProfileTimestamps::default(); let owner = id_from_byte(1); timestamps.set(&kv, &owner, (111, 222)).unwrap(); - store.fail_next_puts(1); + store.fail_next_puts_containing("", 1); assert!(timestamps.set(&kv, &owner, (111, 333)).is_err()); timestamps.initialize(&kv, &owner, 999).unwrap(); assert_eq!(timestamps.get(&kv, &owner), (111, 333)); @@ -2326,9 +2326,9 @@ mod tests { let timestamps = ProfileTimestamps::default(); let owner = id_from_byte(1); timestamps.set(&kv, &owner, (111, 222)).unwrap(); - store.fail_reads(true); + store.fail_all_reads(true); assert!(timestamps.initialize(&kv, &owner, 999).is_err()); - store.fail_reads(false); + store.fail_all_reads(false); assert_eq!(timestamps.get(&kv, &owner), (111, 222)); assert_eq!(store.put_count(), 1); } @@ -2341,7 +2341,7 @@ mod tests { let kv = DetKv::from_store(store.clone()); let timestamps = ProfileTimestamps::default(); let owner = id_from_byte(1); - store.fail_next_puts(1); + store.fail_next_puts_containing("", 1); assert!(timestamps.initialize(&kv, &owner, 111).is_err()); timestamps.initialize(&kv, &owner, 222).unwrap(); assert_eq!(timestamps.get(&kv, &owner), (111, 111)); @@ -2357,7 +2357,7 @@ mod tests { let timestamps = ProfileTimestamps::default(); let owner = id_from_byte(1); let other = id_from_byte(2); - store.fail_next_puts(1); + store.fail_next_puts_containing("", 1); assert!(timestamps.set(&kv, &owner, (111, 222)).is_err()); assert_eq!(timestamps.get(&kv, &other), (0, 0)); timestamps.set(&kv, &owner, (111, 333)).unwrap(); diff --git a/src/wallet_backend/kv.rs b/src/wallet_backend/kv.rs index 829b6064d..2aca15bae 100644 --- a/src/wallet_backend/kv.rs +++ b/src/wallet_backend/kv.rs @@ -221,6 +221,13 @@ fn decode_value(bytes: &[u8]) -> Result } impl DetKv { + #[cfg(test)] + pub(crate) fn failing_store(&self) -> Arc { + Arc::new(super::kv_test_support::FailingKv::from_store( + self.store.clone(), + )) + } + /// Encode and upsert the value bound to `(scope, key)`. pub fn put( &self, diff --git a/src/wallet_backend/kv_test_support.rs b/src/wallet_backend/kv_test_support.rs index e586b515f..efdacf691 100644 --- a/src/wallet_backend/kv_test_support.rs +++ b/src/wallet_backend/kv_test_support.rs @@ -73,6 +73,39 @@ impl KvStore for InMemoryKv { } } +/// A one-shot budget of failures for keys matching a fragment. +/// +/// Only a matching key spends the budget: keys that do not contain the fragment +/// pass through and leave the remaining count untouched, so a test can arm the +/// exact number of failures one keyspace should see without counting the +/// unrelated traffic around it. +#[derive(Default)] +struct CountdownFailure(Mutex>); + +impl CountdownFailure { + /// Arm the next `count` matching keys to fail, discarding any prior arming. + fn arm(&self, key_fragment: &str, count: usize) { + *self.0.lock().unwrap() = Some((key_fragment.to_owned(), count)); + } + + /// Whether `key` fails, spending one failure from the budget when it does. + fn should_fail(&self, key: &str) -> bool { + let mut armed = self.0.lock().unwrap(); + let Some((fragment, remaining)) = armed.as_mut() else { + return false; + }; + if *remaining == 0 || !key.contains(fragment.as_str()) { + return false; + } + *remaining -= 1; + let exhausted = *remaining == 0; + if exhausted { + *armed = None; + } + true + } +} + /// An [`InMemoryKv`] whose reads can be made to fail on demand, counting every /// `put` that reaches the store. /// @@ -81,44 +114,87 @@ impl KvStore for InMemoryKv { /// a value back over a blob you could not read. `put_count` is the assertion /// handle — a caller that "recovers" from a read error by persisting defaults /// shows up as an extra put. -#[derive(Default)] +/// +/// Two independent mechanisms per operation: a blanket `fail_all_*` toggle that +/// fails everything until switched off, and a [`CountdownFailure`] budget that +/// fails a fixed number of keys matching a fragment. pub(crate) struct FailingKv { - inner: InMemoryKv, - fail_reads: AtomicBool, - fail_deletes: AtomicBool, - fail_puts_remaining: AtomicUsize, + inner: std::sync::Arc, + fail_all_reads: AtomicBool, + fail_all_deletes: AtomicBool, puts: AtomicUsize, + reads: AtomicUsize, + get_countdown: CountdownFailure, + put_countdown: CountdownFailure, + delete_countdown: CountdownFailure, +} + +impl Default for FailingKv { + fn default() -> Self { + Self::from_store(std::sync::Arc::new(InMemoryKv::default())) + } } impl FailingKv { - /// Fail the next `count` writes, then resume normal persistence. - pub(crate) fn fail_next_puts(&self, count: usize) { - self.fail_puts_remaining.store(count, Ordering::Relaxed); + pub(crate) fn from_store(inner: std::sync::Arc) -> Self { + Self { + inner, + fail_all_reads: AtomicBool::new(false), + fail_all_deletes: AtomicBool::new(false), + puts: AtomicUsize::new(0), + reads: AtomicUsize::new(0), + get_countdown: CountdownFailure::default(), + put_countdown: CountdownFailure::default(), + delete_countdown: CountdownFailure::default(), + } } /// Make every subsequent `get` fail with [`KvError::LockPoisoned`] (`true`), /// or restore normal reads (`false`). Stored values are never touched, so a /// read armed to fail and then restored still yields the original blob. - pub(crate) fn fail_reads(&self, fail: bool) { - self.fail_reads.store(fail, Ordering::Relaxed); + pub(crate) fn fail_all_reads(&self, fail: bool) { + self.fail_all_reads.store(fail, Ordering::Relaxed); + } + + /// Fail the next `count` reads whose key contains `key_fragment`. + pub(crate) fn fail_next_gets_containing(&self, key_fragment: &str, count: usize) { + self.get_countdown.arm(key_fragment, count); } /// Make every subsequent `delete` fail with [`KvError::LockPoisoned`] /// (`true`), or restore normal deletes (`false`). The stored value is left /// in place, which is what a real failed delete leaves behind. - pub(crate) fn fail_deletes(&self, fail: bool) { - self.fail_deletes.store(fail, Ordering::Relaxed); + pub(crate) fn fail_all_deletes(&self, fail: bool) { + self.fail_all_deletes.store(fail, Ordering::Relaxed); + } + + /// Number of persistent reads, including namespace enumeration. + pub(crate) fn read_count(&self) -> usize { + self.reads.load(Ordering::Relaxed) } /// How many `put` calls have reached the store. pub(crate) fn put_count(&self) -> usize { self.puts.load(Ordering::Relaxed) } + + /// Fail the next `count` writes whose key contains `key_fragment`. + pub(crate) fn fail_next_puts_containing(&self, key_fragment: &str, count: usize) { + self.put_countdown.arm(key_fragment, count); + } + + /// Fail the next `count` deletes whose key contains `key_fragment`. + pub(crate) fn fail_next_deletes_containing(&self, key_fragment: &str, count: usize) { + self.delete_countdown.arm(key_fragment, count); + } } impl KvStore for FailingKv { fn get(&self, scope: &ObjectId, key: &str) -> Result>, KvError> { - if self.fail_reads.load(Ordering::Relaxed) { + self.reads.fetch_add(1, Ordering::Relaxed); + // Blanket first: a read already failing for everything must not spend + // the countdown budget a test armed for one keyspace. + if self.fail_all_reads.load(Ordering::Relaxed) || self.get_countdown.should_fail(key) { return Err(KvError::LockPoisoned); } self.inner.get(scope, key) @@ -128,26 +204,24 @@ impl KvStore for FailingKv { // Counted before delegating: an attempted write is what the assertions // are about, whether or not the store would have accepted it. self.puts.fetch_add(1, Ordering::Relaxed); - if self - .fail_puts_remaining - .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |remaining| { - remaining.checked_sub(1) - }) - .is_ok() - { + if self.put_countdown.should_fail(key) { return Err(KvError::LockPoisoned); } self.inner.put(scope, key, value) } fn delete(&self, scope: &ObjectId, key: &str) -> Result<(), KvError> { - if self.fail_deletes.load(Ordering::Relaxed) { + // Countdown first here, unlike `get`: a blanket-failing delete still + // spends the budget. No test arms both, so the order is only a record + // of which mechanism each caller is actually using. + if self.delete_countdown.should_fail(key) || self.fail_all_deletes.load(Ordering::Relaxed) { return Err(KvError::LockPoisoned); } self.inner.delete(scope, key) } fn list_keys(&self, scope: &ObjectId, prefix: Option<&str>) -> Result, KvError> { + self.reads.fetch_add(1, Ordering::Relaxed); self.inner.list_keys(scope, prefix) } } @@ -311,3 +385,65 @@ impl KvStore for RendezvousKv { self.inner.list_keys(scope, prefix) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unarmed_countdown_never_fails() { + let countdown = CountdownFailure::default(); + + assert!(!countdown.should_fail("det:anything")); + } + + #[test] + fn countdown_fails_exactly_the_armed_number_of_matching_keys() { + let countdown = CountdownFailure::default(); + countdown.arm("votes", 2); + + assert!(countdown.should_fail("det:votes:1")); + assert!(countdown.should_fail("det:votes:2")); + assert!(!countdown.should_fail("det:votes:3")); + } + + #[test] + fn countdown_budget_is_spent_only_by_matching_keys() { + let countdown = CountdownFailure::default(); + countdown.arm("votes", 1); + + assert!(!countdown.should_fail("det:wallets:1")); + assert!(countdown.should_fail("det:votes:1")); + } + + #[test] + fn countdown_armed_with_zero_never_fails() { + let countdown = CountdownFailure::default(); + countdown.arm("votes", 0); + + assert!(!countdown.should_fail("det:votes:1")); + } + + #[test] + fn rearming_countdown_replaces_the_previous_arming() { + let countdown = CountdownFailure::default(); + countdown.arm("votes", 5); + countdown.arm("wallets", 1); + + assert!(!countdown.should_fail("det:votes:1")); + assert!(countdown.should_fail("det:wallets:1")); + } + + #[test] + fn blanket_read_failure_does_not_spend_the_get_countdown() { + let store = FailingKv::default(); + store.fail_next_gets_containing("votes", 1); + store.fail_all_reads(true); + + assert!(store.get(&ObjectId::Global, "det:votes:1").is_err()); + store.fail_all_reads(false); + + assert!(store.get(&ObjectId::Global, "det:votes:1").is_err()); + assert!(store.get(&ObjectId::Global, "det:votes:1").is_ok()); + } +} diff --git a/src/wallet_backend/mod.rs b/src/wallet_backend/mod.rs index 68cd1c875..71891bd2f 100644 --- a/src/wallet_backend/mod.rs +++ b/src/wallet_backend/mod.rs @@ -2467,6 +2467,15 @@ impl WalletBackend { }) } + /// Masternode identity ids in the current deterministic masternode list, + /// each mapped to whether it is an evonode. `None` until the list has synced. + pub async fn masternode_list_membership( + &self, + ) -> Option> { + let summaries = self.inner.pwm.spv().masternode_list_summaries().await?; + Some(membership_from_summaries(summaries)) + } + /// Whether chain sync has not yet reached the tip. pub async fn is_syncing(&self) -> bool { match self.inner.pwm.spv().sync_progress().await { @@ -4738,3 +4747,55 @@ mod tests { ); } } + +/// Key list entries by masternode identity id. The summary holds the +/// proTxHash in wire order; Platform's identity id is the display order +/// (drive-abci parses the RPC hex into the forward-displayed `ProTxHash`). +fn membership_from_summaries( + summaries: impl IntoIterator, +) -> std::collections::BTreeMap { + summaries + .into_iter() + .map(|summary| { + ( + dash_sdk::platform::Identifier::from(summary.pro_tx_hash_display()), + summary.is_evonode, + ) + }) + .collect() +} + +#[cfg(test)] +mod masternode_membership_tests { + use super::*; + use dash_sdk::dpp::dashcore::ProTxHash; + use dash_sdk::dpp::dashcore::hashes::Hash; + use std::str::FromStr; + + const DISPLAY_HEX: &str = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"; + + /// The list key is the id DET loads a masternode under (the explorer / + /// `protx list` hex), which is also how Platform derives the identity id. + #[test] + fn membership_keys_match_the_loaded_masternode_identity_id() { + let loaded = crate::model::masternode_input::decode_identity_id(DISPLAY_HEX).unwrap(); + let platform = ProTxHash::from_str(DISPLAY_HEX).unwrap().to_byte_array(); + assert_eq!(platform, loaded.to_buffer(), "Platform id = RPC hex bytes"); + + let mut wire = loaded.to_buffer(); + wire.reverse(); + let summary = platform_wallet::masternode::MasternodeListSummary { + pro_tx_hash: wire, + service_address: None, + platform_http_port: None, + operator_public_key: [0; 48], + voting_key_id: [0; 20], + platform_node_id: None, + is_valid: true, + is_evonode: true, + has_extended_net_info: false, + }; + let membership = membership_from_summaries([summary]); + assert_eq!(membership.get(&loaded), Some(&true)); + } +} diff --git a/src/wallet_backend/secret_access.rs b/src/wallet_backend/secret_access.rs index 564e1a50e..5d676afab 100644 --- a/src/wallet_backend/secret_access.rs +++ b/src/wallet_backend/secret_access.rs @@ -1268,13 +1268,13 @@ mod tests { assert_eq!(renamed.display_label, "renamed"); assert_eq!(renamed.hint.as_deref(), Some("new hint")); - storage.fail_deletes(true); + storage.fail_all_deletes(true); view.delete(Network::Testnet, &seed_hash) .expect_err("failed sidecar delete"); let after_failed_delete = sa.build_request(&scope, None); assert_eq!(after_failed_delete.display_label, "renamed"); assert_eq!(after_failed_delete.hint.as_deref(), Some("new hint")); - storage.fail_deletes(false); + storage.fail_all_deletes(false); view.delete(Network::Testnet, &seed_hash) .expect("delete metadata"); let deleted = sa.build_request(&scope, None); diff --git a/src/wallet_backend/single_key.rs b/src/wallet_backend/single_key.rs index e607d3517..7c8424fa9 100644 --- a/src/wallet_backend/single_key.rs +++ b/src/wallet_backend/single_key.rs @@ -2984,7 +2984,7 @@ mod tests { network: Network::Testnet, app_kv: Some(&kv), }; - failing.fail_reads(true); + failing.fail_all_reads(true); let error = view .import_wif_if_absent(known_wif(), AliasSource::Preserved(None)) @@ -3020,7 +3020,7 @@ mod tests { network: Network::Testnet, app_kv: Some(&kv), }; - failing.fail_next_puts(1); + failing.fail_next_puts_containing("", 1); let error = view .import_wif_if_absent(known_wif(), AliasSource::Preserved(None)) diff --git a/tests/backend-e2e/dashpay_tasks.rs b/tests/backend-e2e/dashpay_tasks.rs index 2f9f6ed9c..c1ae089f8 100644 --- a/tests/backend-e2e/dashpay_tasks.rs +++ b/tests/backend-e2e/dashpay_tasks.rs @@ -996,6 +996,8 @@ async fn tc_043_reject_contact_request() { dash_evo_tool::backend_task::identity::RegisterDpnsNameInput { qualified_identity: qi_c.clone(), name_input: username_c.clone(), + approved_contest_fee: 0, + signing_key_id: None, }, ), ); diff --git a/tests/backend-e2e/framework/fixtures.rs b/tests/backend-e2e/framework/fixtures.rs index 7b9515bd0..fdfdeeb4b 100644 --- a/tests/backend-e2e/framework/fixtures.rs +++ b/tests/backend-e2e/framework/fixtures.rs @@ -355,6 +355,8 @@ async fn register_dpns_name( let task = BackendTask::IdentityTask(IdentityTask::RegisterDpnsName(RegisterDpnsNameInput { qualified_identity: qi, name_input: name.clone(), + approved_contest_fee: 0, + signing_key_id: None, })); let result = run_task(app_context, task).await.unwrap_or_else(|e| { panic!( diff --git a/tests/backend-e2e/register_dpns.rs b/tests/backend-e2e/register_dpns.rs index 57e6dc8ed..a0bd02314 100644 --- a/tests/backend-e2e/register_dpns.rs +++ b/tests/backend-e2e/register_dpns.rs @@ -44,6 +44,8 @@ async fn test_register_dpns_name() { let task = BackendTask::IdentityTask(IdentityTask::RegisterDpnsName(RegisterDpnsNameInput { qualified_identity: qualified_identity.clone(), name_input: dpns_name.clone(), + approved_contest_fee: 0, + signing_key_id: None, })); let result = run_task(app_context, task) .await diff --git a/tests/kittest/identity_hub_settings.rs b/tests/kittest/identity_hub_settings.rs index 616f57c06..491c270b7 100644 --- a/tests/kittest/identity_hub_settings.rs +++ b/tests/kittest/identity_hub_settings.rs @@ -6,8 +6,8 @@ //! > **Steps**: mount hub, switch to Settings tab. //! > **Expected**: //! > - Section heading `Social profile` present. -//! > - Section heading `Username` present. -//! > - Section heading `Aliases` present. +//! > - Section heading `Usernames` present (the old `Aliases` block is gone; +//! > see `identity_usernames.rs`). //! > - Advanced expander present. //! //! The harness default database has zero identities, so the full populated diff --git a/tests/kittest/identity_hub_switcher.rs b/tests/kittest/identity_hub_switcher.rs index 7df520789..a7aeef334 100644 --- a/tests/kittest/identity_hub_switcher.rs +++ b/tests/kittest/identity_hub_switcher.rs @@ -465,6 +465,34 @@ fn ui_polish_detail_breadcrumb_opens_picker_repeatedly() { }); } +/// The request status page is a pushed screen, so its root crumb has to dismiss +/// it — selecting the hub underneath would leave the page on screen. +#[test] +fn username_request_breadcrumb_dismisses_the_page_and_opens_the_picker() { + with_identity_hub(|mut harness, app_context| { + let identity = seed_identity(&app_context, 1, "Request Alpha"); + app_context.set_selected_identity(Some(identity)); + harness.run_steps(5); + harness + .state_mut() + .screen_stack + .push(dash_evo_tool::ui::Screen::UsernameRequestScreen( + dash_evo_tool::ui::identity::username_request_screen::UsernameRequestScreen::new( + &app_context, + identity, + "a11ce".to_owned(), + ), + )); + harness.run_steps(5); + open_picker(&mut harness); + assert!( + harness.state().screen_stack.is_empty(), + "breadcrumb must dismiss the request status page" + ); + assert!(harness.query_by_label(PICKER_HEADING).is_some()); + }); +} + #[test] fn ui_polish_username_registration_breadcrumb_opens_all_identities() { with_identity_hub(|mut harness, app_context| { diff --git a/tests/kittest/identity_usernames.rs b/tests/kittest/identity_usernames.rs new file mode 100644 index 000000000..b1a0699a9 --- /dev/null +++ b/tests/kittest/identity_usernames.rs @@ -0,0 +1,1196 @@ +//! Kittest coverage for identity usernames (USR-TC-018, 020–027, 029–038). + +use crate::support::{fresh_app_context, with_isolated_data_dir}; +use dash_evo_tool::app::AppAction; +use dash_evo_tool::backend_task::error::TaskError; +use dash_evo_tool::backend_task::identity::IdentityTask; +use dash_evo_tool::backend_task::{BackendTask, BackendTaskSuccessResult}; +use dash_evo_tool::context::AppContext; +use dash_evo_tool::context::connection_status::OverallConnectionState; +use dash_evo_tool::model::dpns::normalize_dpns_label; +use dash_evo_tool::model::dpns_usernames::{ + RequestPhase, RequestTally, UsernameAvailability, UsernameRequest, +}; +use dash_evo_tool::model::fee_estimation::{contest_fee_credits, format_credits_as_dash}; +use dash_evo_tool::model::qualified_identity::encrypted_key_storage::{KeyStorage, PrivateKeyData}; +use dash_evo_tool::model::qualified_identity::qualified_identity_public_key::QualifiedIdentityPublicKey; +use dash_evo_tool::model::qualified_identity::{ + DPNSNameInfo, IdentityStatus, IdentityType, PrivateKeyTarget, QualifiedIdentity, +}; +use dash_evo_tool::model::user_role::UserRole; +use dash_evo_tool::ui::ScreenLike; +use dash_evo_tool::ui::components::ProgressOverlay; +use dash_evo_tool::ui::identity::home::{self, HomeState}; +use dash_evo_tool::ui::identity::profile_cache::ProfileCache; +use dash_evo_tool::ui::identity::register_dpns_name_screen::{ + RegisterDpnsNameScreen, RegisterDpnsNameSource, +}; +use dash_evo_tool::ui::identity::settings::SettingsTab; +use dash_evo_tool::ui::identity::username_request_screen::UsernameRequestScreen; +use dash_evo_tool::utils::egui_mpsc::SenderAsync; +use dash_sdk::dpp::identity::accessors::{IdentityGettersV0, IdentitySettersV0}; +use dash_sdk::dpp::identity::identity_public_key::accessors::v0::{ + IdentityPublicKeyGettersV0, IdentityPublicKeySettersV0, +}; +use dash_sdk::dpp::identity::{Identity, Purpose, SecurityLevel}; +use dash_sdk::dpp::version::PlatformVersion; +use dash_sdk::platform::{Identifier, IdentityPublicKey}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use std::collections::BTreeMap; +use std::sync::Arc; + +/// Seed a selected identity with an authentication key this device can sign with. +pub(crate) fn seed_username_identity( + app_context: &Arc, + byte: u8, + alias: &str, + names: &[&str], + balance: u64, + with_key: bool, +) -> Identifier { + let mut key = + IdentityPublicKey::random_key(1, Some(u64::from(byte)), PlatformVersion::latest()); + key.set_id(1); + key.set_purpose(Purpose::AUTHENTICATION); + key.set_security_level(SecurityLevel::HIGH); + let mut identity = Identity::new_with_id_and_keys( + Identifier::from([byte; 32]), + BTreeMap::from([(key.id(), key.clone())]), + PlatformVersion::latest(), + ) + .expect("identity"); + identity.set_balance(balance); + let id = identity.id(); + let mut private_keys = BTreeMap::new(); + if with_key { + private_keys.insert( + (PrivateKeyTarget::PrivateKeyOnMainIdentity, key.id()), + ( + QualifiedIdentityPublicKey::from(key), + PrivateKeyData::InVault, + ), + ); + } + let qualified = QualifiedIdentity { + identity, + associated_voter_identity: None, + associated_operator_identity: None, + associated_owner_key_id: None, + identity_type: IdentityType::User, + alias: Some(alias.to_owned()), + private_keys: KeyStorage::from(private_keys), + dpns_names: names + .iter() + .map(|name| DPNSNameInfo { + name: (*name).to_owned(), + acquired_at: 0, + }) + .collect(), + associated_wallets: BTreeMap::new(), + secret_access: None, + wallet_index: None, + top_ups: BTreeMap::new(), + status: IdentityStatus::Active, + network: app_context.network(), + }; + app_context + .insert_local_qualified_identity(&qualified, &None) + .expect("seed identity"); + app_context.set_selected_identity(Some(id)); + id +} + +fn mount(screen: RegisterDpnsNameScreen) -> Harness<'static, RegisterDpnsNameScreen> { + let mut harness = Harness::builder() + .with_size(egui::vec2(1280.0, 900.0)) + .build_ui_state( + |ui, screen: &mut RegisterDpnsNameScreen| { + screen.ui(ui); + }, + screen, + ); + harness.run(); + harness +} + +fn answered( + app_context: &Arc, + label: &str, + availability: UsernameAvailability, +) -> RegisterDpnsNameScreen { + let mut screen = RegisterDpnsNameScreen::new(app_context, RegisterDpnsNameSource::Identities); + screen.type_label_for_test(label); + let _ = screen.flush_debounce_for_test(); + screen.display_task_result(BackendTaskSuccessResult::UsernameAvailability { + label: label.to_owned(), + availability, + }); + screen +} + +/// USR-TC-031: opened from an identity, no identity picker; the title names it. +#[test] +fn get_username_names_the_identity_without_a_picker() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + seed_username_identity(&app_context, 0x31, "Alice Novak", &["alice"], 0, true); + let harness = mount(RegisterDpnsNameScreen::new( + &app_context, + RegisterDpnsNameSource::Identities, + )); + assert!( + harness + // A User identity is named by its profile, then its main username; + // the legacy device-only alias is never shown. + .query_by_label_contains("For alice. People will use it to find and pay you.") + .is_some() + ); + assert!(harness.query_by_label("Get another username").is_some()); + assert!(harness.query_by_label("Identity:").is_none()); + assert!(harness.query_by_label_contains("Select Identity").is_none()); + }); +} + +/// USR-TC-032 / 033: the answered row renders alone, with suggestions for a vote. +#[test] +fn availability_row_and_suggestions_render() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + seed_username_identity(&app_context, 0x32, "Alice Novak", &[], 0, true); + let harness = mount(answered( + &app_context, + "nova", + UsernameAvailability::Joinable { + contenders: 1, + join_end: 0, + }, + )); + assert!( + harness + .query_by_label_contains("1 other person already asked for @nova.") + .is_some() + ); + assert!(harness.query_by_label_contains("is available").is_none()); + assert!(harness.query_by_label("Try one without a vote:").is_some()); + assert!(harness.query_by_label("@nova2").is_some()); + }); +} + +/// USR-TC-018: a pay-time re-check that finds the name locked returns to the +/// choose step with the locked row; nothing is dispatched. +#[test] +fn pay_time_recheck_returns_to_choose_with_locked_row() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + seed_username_identity(&app_context, 0x18, "Alice Novak", &[], 0, true); + let mut screen = answered(&app_context, "alice", UsernameAvailability::NeedsVote); + screen.open_confirm_for_test(); + let ctx = egui::Context::default(); + let AppAction::BackendTaskWithContext { context, .. } = + screen.begin_registration_for_test(&ctx) + else { + panic!("expected registration"); + }; + let error = TaskError::UsernameNoLongerAvailable { + availability: UsernameAvailability::Locked, + }; + screen.display_backend_task_error(&context, &error); + let handled = screen.display_task_error(&error); + assert!(handled, "the screen explains the change inline"); + assert!(!ProgressOverlay::has_global(&ctx)); + assert!(!screen.is_confirming_for_test()); + let harness = mount(screen); + assert!( + harness + .query_by_label_contains( + "@alice can't be registered. A community vote locked this name for good." + ) + .is_some() + ); + }); +} + +/// A registration whose outcome could not be confirmed may already be paid for, +/// so the screen must not put the Pay step back with the same review. +#[test] +fn unconfirmed_registration_does_not_return_to_the_pay_step() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + seed_username_identity(&app_context, 0x19, "Alice Novak", &[], 0, true); + let mut screen = answered(&app_context, "alice", UsernameAvailability::NeedsVote); + screen.open_confirm_for_test(); + let ctx = egui::Context::default(); + let AppAction::BackendTaskWithContext { context, .. } = + screen.begin_registration_for_test(&ctx) + else { + panic!("expected registration"); + }; + let error = TaskError::UsernameRegistrationUnconfirmed { + source_error: Box::new(dash_sdk::Error::Generic("no answer".to_owned())), + }; + screen.display_backend_task_error(&context, &error); + assert!( + !screen.display_task_error(&error), + "the warning is shown to the user, not swallowed by the screen" + ); + assert!(!ProgressOverlay::has_global(&ctx)); + assert!(!screen.is_confirming_for_test()); + }); +} + +/// USR-TC-035 / 036 / 037: confirm rows, low balance, and the sync gate. +#[test] +fn confirm_step_shows_fees_low_balance_and_sync_gate() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + seed_username_identity(&app_context, 0x35, "Alice Novak", &[], 0, true); + let mut screen = answered(&app_context, "nova", UsernameAvailability::NeedsVote); + screen.open_confirm_for_test(); + let mut harness = mount(screen); + + let contest_fee = + format_credits_as_dash(contest_fee_credits(app_context.sdk_platform_version())); + assert!( + harness + .query_by_label("Community vote fee (not returned)") + .is_some() + ); + assert!(harness.query_by_label(&contest_fee).is_some()); + let total = format_credits_as_dash( + app_context.fee_estimator().estimate_document_batch(2) + + contest_fee_credits(app_context.sdk_platform_version()), + ); + assert!(harness.query_by_label("Total").is_some()); + assert!( + harness.query_by_label(&total).is_some(), + "total must be registration plus community vote fee ({total})" + ); + assert!(harness.query_by_label("Community vote").is_some()); + assert!( + harness + .query_by_label_contains(&format!( + "This identity has {}. Add at least", + format_credits_as_dash(0) + )) + .is_some() + ); + assert!(harness.query_by_label("Top up").is_some()); + assert!(harness.query_by_label_contains("deposit").is_none()); + + assert_ne!( + app_context.connection_status().overall_state(), + OverallConnectionState::Synced + ); + harness.get_by_label_contains("and request @nova").click(); + harness.run(); + assert!( + harness.state().is_confirming_for_test(), + "an unsynced, underfunded identity must not start paying" + ); + }); +} + +/// USR-FR-005: an identity without a signing key is told how to proceed. +#[test] +fn view_only_identity_is_told_to_add_a_key() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + seed_username_identity(&app_context, 0x05, "Viewer", &[], 0, false); + let harness = mount(RegisterDpnsNameScreen::new( + &app_context, + RegisterDpnsNameSource::Identities, + )); + assert!( + harness + .query_by_label_contains("Add a key to this identity to register usernames.") + .is_some() + ); + }); +} + +fn request(label: &str, phase: RequestPhase) -> UsernameRequest { + let mut request = UsernameRequest::submitted( + label, + dash_evo_tool::utils::time::now_ms().saturating_sub(if phase == RequestPhase::Voting { + 8 * 86_400_000 + } else { + 0 + }), + dash_evo_tool::model::dpns::ContestDurations { + total: std::time::Duration::from_secs(14 * 86_400), + join: std::time::Duration::from_secs(7 * 86_400), + }, + None, + ); + request.phase = phase; + request +} + +/// Settings tab plus the last non-empty action it returned. +type SettingsState = (SettingsTab, Option); + +fn mount_settings(app_context: Arc) -> Harness<'static, SettingsState> { + let mut harness = Harness::builder() + .with_size(egui::vec2(1400.0, 1200.0)) + .build_ui_state( + move |ui, state: &mut SettingsState| { + let action = state + .0 + .render(ui, &app_context, &mut ProfileCache::default()); + if !matches!(action, AppAction::None) { + state.1 = Some(action); + } + }, + (SettingsTab::new(), None), + ); + harness.run(); + harness +} + +/// Run the backend task an action carries, as AppState would. +fn run_action( + rt: &tokio::runtime::Runtime, + app_context: &Arc, + action: Option, +) -> BackendTaskSuccessResult { + let Some(AppAction::BackendTask(task)) = action else { + panic!("expected a backend task, got {action:?}"); + }; + let (tx, _rx) = tokio::sync::mpsc::channel(8); + let sender = SenderAsync::new(tx, egui::Context::default()); + rt.block_on(app_context.run_backend_task(task, sender)) + .expect("task succeeds") +} + +/// USR-TC-020 / 022: every row state renders and no alias stubs remain. +#[test] +fn usernames_card_lists_all_states_without_alias_stubs() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + let id = seed_username_identity( + &app_context, + 0x20, + "Alice Novak", + &["alice", "alice-design"], + 0, + true, + ); + app_context + .store_username_requests( + &id, + vec![ + request("ali", RequestPhase::Voting), + request("novak", RequestPhase::Joinable), + request("al", RequestPhase::Lost), + request("aa", RequestPhase::Locked), + ], + ) + .expect("store requests"); + let harness = mount_settings(app_context); + for label in [ + "@alice", + "@alice-design", + "Main", + "@ali", + "@novak", + "@al", + "@aa", + "Get another username", + ] { + assert!(harness.query_by_label(label).is_some(), "missing {label}"); + } + for text in [ + "Waiting for vote", + "Open for other requests", + "Went to someone else", + "Locked for good", + ] { + assert!( + harness.query_by_label_contains(text).is_some(), + "missing {text}" + ); + } + for stub in [ + "Aliases", + "Make primary", + "Remove", + "Add an alias", + "View all usernames", + ] { + assert!( + harness.query_by_label(stub).is_none(), + "stub {stub} remains" + ); + } + }); +} + +/// USR-TC-023: an identity with no username sees the value line and the CTA. +#[test] +fn usernames_card_empty_state() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + seed_username_identity(&app_context, 0x23, "Alex", &[], 0, true); + let harness = mount_settings(app_context); + assert!( + harness + .query_by_label_contains("This identity has no username yet.") + .is_some() + ); + assert!(harness.query_by_label("Get a username").is_some()); + assert!(harness.query_by_label("Add a key").is_none()); + }); +} + +/// USR-TC-024: a view-only identity gets the reason and an `Add a key` link. +#[test] +fn usernames_card_view_only_offers_add_a_key() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + seed_username_identity(&app_context, 0x24, "Viewer", &[], 0, false); + let harness = mount_settings(app_context); + assert!(harness.query_by_label("Add a key").is_some()); + assert!( + harness + .query_by_label("Add a key to this identity to register usernames.") + .is_some() + ); + }); +} + +fn mount_request( + app_context: &Arc, + id: Identifier, + label: &str, +) -> Harness<'static, UsernameRequestScreen> { + let screen = UsernameRequestScreen::new(app_context, id, label.to_owned()); + let mut harness = Harness::builder() + .with_size(egui::vec2(1280.0, 1200.0)) + .build_ui_state( + |ui, screen: &mut UsernameRequestScreen| { + screen.ui(ui); + }, + screen, + ); + harness.run(); + harness +} + +/// USR-TC-029 / 030: timeline, tally, the four rules, and no voter link for Alex. +#[test] +fn request_status_page_explains_the_vote() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + let id = seed_username_identity(&app_context, 0x29, "Alice Novak", &[], 0, true); + let mut pending = request("ali", RequestPhase::Voting); + pending.tally = RequestTally { + you: 31, + others: vec![(Identifier::from([7; 32]), 18)], + lock: 8, + abstain: 3, + }; + app_context + .store_username_requests(&id, vec![pending]) + .expect("store request"); + let harness = mount_request(&app_context, id, &normalize_dpns_label("ali")); + for text in [ + "Your request for @ali", + "Requested ", + "The community vote ends around", + "Result: Not decided yet.", + "Leading", + "Other request (", + "Lock, so no one gets it", + "Abstain", + "Evonodes count as 4 votes.", + "becomes yours automatically.", + "the most recent request wins.", + "no one can ever register @ali.", + "The community vote fee isn't returned in any case.", + ] { + assert!( + harness.query_by_label_contains(text).is_some(), + "missing {text}" + ); + } + assert!( + harness + .query_by_label("Your nodes can vote on this name") + .is_none() + ); + }); +} + +/// Seed a masternode whose voter identity is loaded, with or without the +/// signing-key reference that lets it cast a vote. +fn seed_voting_node(app_context: &Arc, byte: u8, with_signing_key: bool) { + let pv = PlatformVersion::latest(); + let mut voter = + Identity::create_basic_identity(Identifier::from([byte ^ 0xFF; 32]), pv).expect("voter"); + let voter_key = IdentityPublicKey::random_key(1, Some(u64::from(byte)), pv); + voter.add_public_key(voter_key.clone()); + let mut private_keys = BTreeMap::new(); + if with_signing_key { + private_keys.insert( + (PrivateKeyTarget::PrivateKeyOnVoterIdentity, voter_key.id()), + ( + QualifiedIdentityPublicKey::from(voter_key.clone()), + PrivateKeyData::InVault, + ), + ); + } + let node = QualifiedIdentity { + identity: Identity::create_basic_identity(Identifier::from([byte; 32]), pv).expect("node"), + associated_voter_identity: Some((voter, voter_key)), + associated_operator_identity: None, + associated_owner_key_id: None, + identity_type: IdentityType::Masternode, + alias: Some("Voting node".to_owned()), + private_keys: KeyStorage::from(private_keys), + dpns_names: vec![], + associated_wallets: BTreeMap::new(), + secret_access: None, + wallet_index: None, + top_ups: BTreeMap::new(), + status: IdentityStatus::Active, + network: app_context.network(), + }; + app_context + .insert_local_qualified_identity(&node, &None) + .expect("seed voting node"); +} + +/// USR-TC-030: a Power user with a node that can vote sees the link to vote. +#[test] +fn request_status_page_links_voters() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + let id = seed_username_identity(&app_context, 0x30, "Alice Novak", &[], 0, true); + app_context + .store_username_requests(&id, vec![request("ali", RequestPhase::Voting)]) + .expect("store request"); + seed_voting_node(&app_context, 0x31, true); + app_context.set_user_role(UserRole::Power); + let harness = mount_request(&app_context, id, &normalize_dpns_label("ali")); + assert!( + harness + .query_by_label("Your nodes can vote on this name") + .is_some() + ); + }); +} + +/// A node loaded without its voting key cannot vote on the Votes screen, so +/// the status page must not send its owner there. +#[test] +fn request_status_page_hides_the_voter_link_for_a_node_that_cannot_vote() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + let id = seed_username_identity(&app_context, 0x32, "Alice Novak", &[], 0, true); + app_context + .store_username_requests(&id, vec![request("ali", RequestPhase::Voting)]) + .expect("store request"); + seed_voting_node(&app_context, 0x33, false); + app_context.set_user_role(UserRole::Power); + let harness = mount_request(&app_context, id, &normalize_dpns_label("ali")); + assert!( + harness + .query_by_label("Your nodes can vote on this name") + .is_none() + ); + }); +} + +/// Home tab state plus the last non-empty action it returned. +type HomeHarnessState = (HomeState, ProfileCache, Option); + +fn mount_home(app_context: Arc) -> Harness<'static, HomeHarnessState> { + let mut harness = Harness::builder() + .with_size(egui::vec2(1280.0, 1200.0)) + .build_ui_state( + move |ui, state: &mut HomeHarnessState| { + let (action, _) = home::render(ui, &app_context, &state.0, &mut state.1); + if !matches!(action, AppAction::None) { + state.2 = Some(action); + } + }, + (HomeState::default(), ProfileCache::default(), None), + ); + harness.run(); + harness +} + +/// USR-TC-021: "Show as main" from the row menu saves the choice on this device +/// (no network call) and every label shows it, even over a legacy automatic +/// `{name}.dash` alias written by earlier registrations. +#[test] +fn show_as_main_changes_the_hero_name() { + with_isolated_data_dir(|| { + let (rt, app_context) = fresh_app_context(); + let id = seed_username_identity( + &app_context, + 0x21, + "a-name.dash", + &["a-name", "b-name"], + 0, + true, + ); + let mut settings = mount_settings(app_context.clone()); + settings + .get_all_by_label("•••") + .nth(1) + .expect("menu for @b-name") + .click(); + settings.run(); + settings.get_by_label("Show as main").click(); + settings.run(); + let action = settings.state_mut().1.take(); + assert!( + matches!( + &action, + Some(AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::SetMainUsername { identity_id, name } + ))) if *identity_id == id && name == "b-name" + ), + "expected a local-only SetMainUsername task, got {action:?}" + ); + run_action(&rt, &app_context, action); + + let identity = app_context + .load_local_user_identities() + .expect("identities") + .into_iter() + .find(|qi| qi.identity.id() == id) + .expect("seeded"); + assert_eq!( + app_context.main_username(&identity).as_deref(), + Some("b-name") + ); + let harness = mount_home(app_context); + assert!( + harness + .query_all_by_label_contains("b-name") + .next() + .is_some() + ); + assert!( + harness + .query_all_by_label_contains("a-name") + .next() + .is_none(), + "the legacy automatic alias must not hide the chosen main name" + ); + }); +} + +/// USR-TC-025 / 026: with no registered name, the pending request shows in the +/// header and as a Home card with the standing sentence. +#[test] +fn home_shows_pending_request_header_and_card() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + let id = seed_username_identity(&app_context, 0x25, "Alex", &[], 0, true); + let mut pending = request("ali", RequestPhase::Voting); + pending.tally = RequestTally { + you: 5, + others: vec![(Identifier::from([9; 32]), 2)], + lock: 0, + abstain: 0, + }; + app_context + .store_username_requests(&id, vec![pending]) + .expect("store request"); + let harness = mount_home(app_context); + assert!(harness.query_by_label("@ali").is_some()); + assert!( + harness + .query_all_by_label_contains("Waiting for vote") + .next() + .is_some() + ); + assert!( + harness + .query_by_label_contains("@ali is waiting for a community vote. It ends around") + .is_some() + ); + assert!( + harness + .query_by_label("You're leading right now.") + .is_some() + ); + assert!(harness.query_by_label("View status").is_some()); + }); +} + +#[test] +fn reopening_home_after_username_deadline_does_not_show_open_voting() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + let id = seed_username_identity(&app_context, 0x26, "Alex", &[], 0, true); + let mut expired = request("d1ssh", RequestPhase::Joinable); + expired.join_end = Some(dash_evo_tool::utils::time::now_ms() - 3 * 86_400_000); + expired.end = expired.join_end; + app_context + .store_username_requests(&id, vec![expired]) + .unwrap(); + let harness = mount_home(app_context); + assert!( + harness + .query_all_by_label_contains("Open for other requests") + .next() + .is_none() + ); + assert!(harness.query_by_label_contains("It ends around").is_none()); + assert!( + harness + .query_all_by_label_contains("Awaiting result") + .next() + .is_some() + ); + assert!( + harness + .query_by_label("No one else has asked so far.") + .is_none() + ); + assert!(harness.query_by_label("View status").is_some()); + }); +} + +/// USR-TC-027: an outcome banner shows the first time only. +#[test] +fn outcome_banner_shows_once() { + with_isolated_data_dir(|| { + let (rt, app_context) = fresh_app_context(); + let id = seed_username_identity(&app_context, 0x27, "Alex", &[], 0, true); + app_context + .store_username_requests(&id, vec![request("ali", RequestPhase::Won)]) + .expect("store request"); + let banner = "You're @ali. People can now find and pay you by this name."; + let mut first = mount_home(app_context.clone()); + assert!(first.query_by_label_contains(banner).is_some()); + let mark_seen = first.state_mut().2.take(); + assert!(matches!( + &mark_seen, + Some(AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::MarkUsernameOutcomesSeen { .. } + ))) + )); + run_action(&rt, &app_context, mark_seen); + drop(first); + let second = mount_home(app_context); + assert!(second.query_by_label_contains(banner).is_none()); + }); +} + +/// QA regression (USR-FR-037/038): a network failure during the pay-time +/// re-check lifts the blocking overlay and returns to the confirm step, with +/// the error shown as a banner. +#[test] +fn pay_recheck_network_failure_unblocks_confirm() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + seed_username_identity(&app_context, 0x42, "Alex", &[], 0, true); + let mut screen = answered(&app_context, "alice", UsernameAvailability::NeedsVote); + screen.open_confirm_for_test(); + let ctx = egui::Context::default(); + let AppAction::BackendTaskWithContext { context, .. } = + screen.begin_registration_for_test(&ctx) + else { + panic!("expected registration"); + }; + assert!( + ProgressOverlay::has_global(&ctx), + "precondition: overlay up" + ); + let error = TaskError::UsernameAvailabilityCheckFailed { + source: Box::new(dash_sdk::Error::Generic("timeout".into())), + }; + screen.display_backend_task_error(&context, &error); + let handled = screen.display_task_error(&error); + assert!(!handled, "the banner must tell the user to retry"); + assert!( + !ProgressOverlay::has_global(&ctx), + "the Registering overlay must not stay up after the re-check failed" + ); + assert!(screen.is_confirming_for_test()); + }); +} + +/// QA regression (USR-FR-001): a request won in the vote is listed as an active +/// name before the identity's registered names are re-read. +#[test] +fn won_request_is_listed_on_card() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + let id = seed_username_identity(&app_context, 0x41, "Alex", &[], 0, true); + app_context + .store_username_requests(&id, vec![request("ali", RequestPhase::Won)]) + .expect("store request"); + let harness = mount_settings(app_context); + assert!(harness.query_by_label("@ali").is_some()); + assert!( + harness + .query_by_label_contains("This identity has no username yet.") + .is_none() + ); + }); +} + +/// QA regression: asking again for a name this identity already requested is +/// blocked before any fee, with a clear row instead of "1 other person asked". +#[test] +fn own_request_blocks_a_second_request() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + seed_username_identity(&app_context, 0x43, "Alex", &[], 0, true); + let harness = mount(answered( + &app_context, + "alice", + UsernameAvailability::AlreadyRequested, + )); + assert!( + harness + .query_by_label_contains("You already asked for @alice.") + .is_some() + ); + assert!(harness.query_by_label_contains("other person").is_none()); + assert!(!UsernameAvailability::AlreadyRequested.allows_registration()); + }); +} + +/// QA regression: removing an identity drops its requests, so they stop +/// driving the periodic status refresh. +#[test] +fn removed_identity_requests_stop_counting() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + let id = seed_username_identity(&app_context, 0x44, "Gone", &["gone"], 0, true); + app_context + .store_username_requests(&id, vec![request("ali", RequestPhase::Voting)]) + .expect("store request"); + assert!(app_context.any_pending_username_request()); + app_context + .delete_local_qualified_identity(&id) + .expect("delete identity"); + assert!(!app_context.any_pending_username_request()); + assert!(app_context.username_requests_for(&id).is_empty()); + }); +} + +/// QA regression (PF §3): a lone request wins at the end, so it is "Leading", +/// never "Tied". +#[test] +fn lone_request_is_leading_not_tied() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + let id = seed_username_identity(&app_context, 0x45, "Alex", &[], 0, true); + app_context + .store_username_requests(&id, vec![request("ali", RequestPhase::Voting)]) + .expect("store request"); + let harness = mount_request(&app_context, id, &normalize_dpns_label("ali")); + assert!(harness.query_by_label("Your request for @ali").is_some()); + assert!(harness.query_by_label("Tied").is_none()); + assert!(harness.query_by_label("Leading").is_some()); + }); +} + +/// QA regression (AGENTS.md layering): dismissing an outcome goes through a +/// backend task, which removes the row. +#[test] +fn dismissing_an_outcome_runs_through_the_backend() { + with_isolated_data_dir(|| { + let (rt, app_context) = fresh_app_context(); + let id = seed_username_identity(&app_context, 0x46, "Alex", &[], 0, true); + app_context + .store_username_requests(&id, vec![request("al", RequestPhase::Lost)]) + .expect("store request"); + let mut settings = mount_settings(app_context.clone()); + assert!( + app_context.username_requests_for(&id).len() == 1, + "precondition: outcome stored" + ); + settings.get_by_label("Dismiss").click(); + settings.run(); + assert_eq!( + app_context.username_requests_for(&id).len(), + 1, + "the UI must not write storage itself" + ); + let action = settings.state_mut().1.take(); + run_action(&rt, &app_context, action); + assert!(app_context.username_requests_for(&id).is_empty()); + }); +} + +/// USR-TC-037: with enough balance, only the sync gate holds Pay, and it says so. +#[test] +fn sync_gate_alone_blocks_pay() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + seed_username_identity(&app_context, 0x37, "Alex", &[], 1_000_000_000_000_000, true); + let mut screen = answered(&app_context, "nova", UsernameAvailability::NeedsVote); + screen.open_confirm_for_test(); + let mut harness = mount(screen); + assert!( + harness.query_by_label("Top up").is_none(), + "precondition: balance covers the total" + ); + harness.get_by_label_contains("and request @nova").hover(); + harness.run(); + assert!( + harness + .query_by_label_contains("Available after sync finishes.") + .is_some() + ); + harness.get_by_label_contains("and request @nova").click(); + harness.run(); + assert!(harness.state().is_confirming_for_test()); + }); +} + +/// USR-TC-036: Top up and back keeps the chosen name on the confirm step. +#[test] +fn top_up_returns_with_name_kept() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + let id = seed_username_identity(&app_context, 0x36, "Alex", &[], 185_053_640, true); + let mut screen = answered(&app_context, "nova", UsernameAvailability::NeedsVote); + screen.open_confirm_for_test(); + let mut harness = mount(screen); + harness.get_by_label("Top up").click(); + harness.run(); + app_context + .edit_local_qualified_identity(&id, |identity| { + identity.identity.set_balance(30_000_000_000); + Ok(()) + }) + .unwrap(); + harness.state_mut().refresh(); + harness.run(); + assert!(harness.state().is_confirming_for_test()); + assert_eq!( + harness + .state() + .selected_qualified_identity + .as_ref() + .unwrap() + .identity + .balance(), + 30_000_000_000 + ); + assert!( + harness.query_by_label("Top up").is_none(), + "the updated balance covers the registration" + ); + assert!( + harness + .query_by_label_contains("and request @nova") + .is_some() + ); + }); +} + +/// USR-TC-038: the result page tells a registered name from a request in a vote. +#[test] +fn result_page_distinguishes_registered_from_requested() { + use dash_evo_tool::backend_task::FeeResult; + use dash_evo_tool::model::dpns::DpnsRegistrationOutcome; + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + let id = seed_username_identity(&app_context, 0x38, "Alex", &[], 0, true); + let done = |label: &str, outcome| { + let mut screen = answered(&app_context, label, UsernameAvailability::NeedsVote); + screen.open_confirm_for_test(); + screen.display_task_result(BackendTaskSuccessResult::RegisteredDpnsName { + outcome, + fee_result: FeeResult::estimated_only(1), + }); + mount(screen) + }; + + let registered = done("alex-novak", DpnsRegistrationOutcome::Registered); + assert!(registered.query_by_label("You're @alex-novak").is_some()); + assert!( + registered + .query_by_label("People can now find and pay you by this name.") + .is_some() + ); + assert!(registered.query_by_label_contains("is in").is_none()); + + let mut submitted = request("ali", RequestPhase::Joinable); + submitted.label = "ali".to_owned(); + app_context + .store_username_requests(&id, vec![submitted]) + .expect("store request"); + let requested = done("ali", DpnsRegistrationOutcome::PendingCommunityVote); + assert!( + requested + .query_by_label("Your request for @ali is in") + .is_some() + ); + assert!( + requested + .query_by_label_contains("Others can still ask for this name until") + .is_some() + ); + assert!( + requested + .query_by_label( + "If no one else asks and no one votes to lock it, @ali becomes yours then." + ) + .is_some() + ); + assert!(requested.query_by_label("View request status").is_some()); + assert!(requested.query_by_label_contains("You're @").is_none()); + }); +} + +/// QA regression: when the hub replaces the Home frame's action (e.g. with a +/// profile load), the "seen" mark is sent again on the next frame instead of +/// being lost, so the outcome banner does not return on the next start. +#[test] +fn seen_mark_survives_a_replaced_action() { + with_isolated_data_dir(|| { + let (rt, app_context) = fresh_app_context(); + let id = seed_username_identity(&app_context, 0x51, "Alex", &[], 0, true); + app_context + .store_username_requests(&id, vec![request("ali", RequestPhase::Won)]) + .expect("store request"); + let banner = "You're @ali. People can now find and pay you by this name."; + let is_mark = |action: &Option| { + matches!( + action, + Some(AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::MarkUsernameOutcomesSeen { .. } + ))) + ) + }; + let mut home = mount_home(app_context.clone()); + let replaced = home.state_mut().2.take(); + assert!( + is_mark(&replaced), + "precondition: first frame marks, got {replaced:?}" + ); + + // The hub dropped that action, so the task never starts; the mark is + // sent again once its short start grace (a couple of frames) passes. + let mut retried = None; + for _ in 0..4 { + home.step(); + retried = home.state_mut().2.take(); + if retried.is_some() { + break; + } + } + assert!(is_mark(&retried), "the seen mark was lost, got {retried:?}"); + run_action(&rt, &app_context, retried); + + home.step(); + assert!( + home.state_mut().2.take().is_none(), + "no more marks once stored" + ); + assert!( + home.query_by_label_contains(banner).is_some(), + "the banner stays up this session until dismissed" + ); + drop(home); + let next_start = mount_home(app_context); + assert!(next_start.query_by_label_contains(banner).is_none()); + }); +} + +/// QA regression: identities load with the main username first, so labels that +/// show the first name (identity text, send screen, address picker) show it. +#[test] +fn loaded_identities_list_the_main_username_first() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + let id = seed_username_identity( + &app_context, + 0x52, + "a-name.dash", + &["a-name", "b-name"], + 0, + true, + ); + app_context + .set_main_username(&id, "b-name") + .expect("set main"); + let identity = app_context + .load_local_user_identities() + .expect("identities") + .into_iter() + .find(|qi| qi.identity.id() == id) + .expect("seeded"); + assert_eq!(identity.dpns_names[0].name, "b-name"); + assert_eq!(identity.to_string(), "b-name"); + }); +} + +#[test] +fn changing_reviewed_username_requires_new_consent() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + seed_username_identity(&app_context, 0x61, "Payer", &[], 0, true); + let mut screen = answered(&app_context, "alice-123", UsernameAvailability::Available); + screen.open_confirm_for_test(); + screen.type_label_for_test("alice"); + assert!( + matches!( + screen.begin_registration_for_test(&egui::Context::default()), + AppAction::None + ), + "editing the reviewed name must require availability, vote consent and payment review again" + ); + }); +} + +#[test] +fn changing_identity_invalidates_username_payment_review() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + seed_username_identity(&app_context, 0x62, "First", &[], 0, true); + let mut screen = answered(&app_context, "alice", UsernameAvailability::NeedsVote); + screen.open_confirm_for_test(); + let second = seed_username_identity(&app_context, 0x63, "Second", &[], 0, true); + screen.select_identity(second); + assert!( + matches!( + screen.begin_registration_for_test(&egui::Context::default()), + AppAction::None + ), + "a different payer requires a new review" + ); + }); +} + +#[test] +fn registration_dispatch_uses_the_reviewed_name_and_vote_fee() { + with_isolated_data_dir(|| { + let (_rt, app_context) = fresh_app_context(); + seed_username_identity(&app_context, 0x64, "Payer", &[], 0, true); + let mut screen = answered(&app_context, "Alice", UsernameAvailability::NeedsVote); + screen.open_confirm_for_test(); + let AppAction::BackendTaskWithContext { + task: BackendTask::IdentityTask(IdentityTask::RegisterDpnsName(input)), + .. + } = screen.begin_registration_for_test(&egui::Context::default()) + else { + panic!("expected registration"); + }; + assert_eq!(input.name_input, "Alice"); + assert_eq!( + input.approved_contest_fee, + contest_fee_credits(app_context.sdk_platform_version()) + ); + assert!( + matches!( + screen.begin_registration_for_test(&egui::Context::default()), + AppAction::None + ), + "a second payment cannot be dispatched while submitting" + ); + }); +} diff --git a/tests/kittest/main.rs b/tests/kittest/main.rs index 4cc55e4f0..fd35e4d6f 100644 --- a/tests/kittest/main.rs +++ b/tests/kittest/main.rs @@ -14,6 +14,7 @@ mod identity_hub_onboarding; mod identity_hub_settings; mod identity_hub_switcher; mod identity_selector; +mod identity_usernames; mod import_mnemonic_screen; mod import_single_key; mod info_popup; diff --git a/tests/kittest/masternode_tab.rs b/tests/kittest/masternode_tab.rs index a6c832c59..252224d0c 100644 --- a/tests/kittest/masternode_tab.rs +++ b/tests/kittest/masternode_tab.rs @@ -5,13 +5,14 @@ use crate::support::{mount_app, with_isolated_data_dir}; use dash_evo_tool::app::TaskResult; use dash_evo_tool::backend_task::{BackendTaskContext, BackendTaskSuccessResult}; use dash_evo_tool::context::AppContext; +use dash_evo_tool::model::dpns_voting::operator::MasternodesSegment; use dash_evo_tool::model::qualified_identity::encrypted_key_storage::{KeyStorage, PrivateKeyData}; use dash_evo_tool::model::qualified_identity::qualified_identity_public_key::QualifiedIdentityPublicKey; use dash_evo_tool::model::qualified_identity::{ IdentityStatus, IdentityType, PrivateKeyTarget, QualifiedIdentity, }; use dash_evo_tool::model::user_role::UserRole; -use dash_evo_tool::ui::{RootScreenType, ScreenLike}; +use dash_evo_tool::ui::{RootScreenType, Screen, ScreenLike}; use dash_sdk::dpp::identity::Identity; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; @@ -152,12 +153,18 @@ fn seed_node_with_voter_key(app_context: &Arc, byte: u8, alias: &str .expect("node basic identity"); let node_qi = QualifiedIdentity { identity: node_identity, - associated_voter_identity: Some((voter_identity, voter_key)), + associated_voter_identity: Some((voter_identity, voter_key.clone())), associated_operator_identity: None, associated_owner_key_id: None, identity_type: IdentityType::Masternode, alias: Some(alias.to_string()), - private_keys: KeyStorage::default(), + private_keys: KeyStorage::from(BTreeMap::from([( + (PrivateKeyTarget::PrivateKeyOnVoterIdentity, voter_key.id()), + ( + QualifiedIdentityPublicKey::from(voter_key), + PrivateKeyData::InVault, + ), + )])), dpns_names: vec![], associated_wallets: BTreeMap::new(), secret_access: None, @@ -337,6 +344,325 @@ fn empty_state_renders_canonical_copy() { }); } +/// VOTE-TC-081 — Masternodes carries the `Votes | Nodes` header with Votes +/// listed first; with nothing needing a vote and no history, Nodes opens. +#[test] +fn masternodes_opens_on_nodes_when_nothing_needs_a_vote() { + with_isolated_data_dir(|| { + let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime"); + let _guard = rt.enter(); + + let mut harness = mount_app(RootScreenType::RootScreenIdentityHub); + let app_context = harness.state().current_app_context().clone(); + activate_masternodes_tab(&mut harness, &app_context); + + let votes = harness.get_by_label("Votes"); + let nodes = harness.get_by_label("Nodes"); + assert!( + votes.rect().left() < nodes.rect().left(), + "Votes must be listed before Nodes" + ); + assert!(harness.query_by_label("No masternodes loaded").is_some()); + assert_eq!(masternodes_segment(&mut harness), MasternodesSegment::Nodes); + }); +} + +/// The Votes segment keeps its sub-views reachable: Scheduled opens in place. +#[test] +fn votes_scheduled_view_is_clickable() { + with_isolated_data_dir(|| { + let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime"); + let _guard = rt.enter(); + + let mut harness = mount_app(RootScreenType::RootScreenMasternodes); + harness.run_steps(3); + harness.get_by_label("Votes").click(); + harness.run_steps(3); + + harness.get_by_label("Scheduled").click(); + harness.run_steps(3); + + assert_eq!( + harness.state().selected_main_screen, + RootScreenType::RootScreenMasternodes + ); + assert!(harness.query_by_label("No scheduled votes.").is_some()); + }); +} + +/// VOTE-TC-082 — a persisted retired DPNS route opens the matching Votes view. +#[test] +fn persisted_scheduled_votes_route_opens_votes_scheduled() { + with_isolated_data_dir(|| { + let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime"); + let _guard = rt.enter(); + + let mut harness = mount_app(RootScreenType::RootScreenDPNSScheduledVotes); + harness.run_steps(3); + + assert_eq!( + harness.state().selected_main_screen, + RootScreenType::RootScreenMasternodes + ); + assert_eq!(masternodes_segment(&mut harness), MasternodesSegment::Votes); + assert!(harness.query_by_label("No scheduled votes.").is_some()); + }); +} + +/// VOTE-TC-083 — the retired "My usernames" route opens the Identities hub. +#[test] +fn persisted_owned_names_route_opens_the_identity_hub() { + with_isolated_data_dir(|| { + let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime"); + let _guard = rt.enter(); + + let harness = mount_app(RootScreenType::RootScreenDPNSOwnedNames); + assert_eq!( + harness.state().selected_main_screen, + RootScreenType::RootScreenIdentityHub + ); + }); +} + +fn masternodes_segment( + harness: &mut egui_kittest::Harness<'static, dash_evo_tool::app::AppState>, +) -> MasternodesSegment { + let Screen::MasternodesScreen(screen) = harness + .state_mut() + .main_screens + .get_mut(&RootScreenType::RootScreenMasternodes) + .expect("masternodes screen") + else { + panic!("the Masternodes root must contain the Masternodes screen"); + }; + screen.segment() +} + +/// VOTE-TC-013 — To decide exposes the actionable no-voter-key state; its +/// `Load a masternode` action opens the Nodes load form. +#[test] +fn to_decide_without_a_voting_key_shows_the_load_action() { + with_isolated_data_dir(|| { + let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime"); + let _guard = rt.enter(); + + let mut harness = mount_app(RootScreenType::RootScreenDPNSActiveContests); + let app_context = harness.state().current_app_context().clone(); + app_context + .insert_name_contests_as_normalized_names(vec!["alice".to_owned()]) + .expect("seed active contest"); + let Screen::MasternodesScreen(masternodes) = harness + .state_mut() + .main_screens + .get_mut(&RootScreenType::RootScreenMasternodes) + .expect("masternodes screen") + else { + panic!("the Masternodes root must contain the Masternodes screen"); + }; + masternodes.votes_mut().refresh(); + harness.run_steps(5); + + assert!( + harness + .query_by_label("No masternodes are loaded.") + .is_some(), + "the no-voter-key explanation must render in To decide" + ); + harness.get_by_label("Load a masternode").click(); + harness.run_steps(3); + assert_eq!( + harness.state().selected_main_screen, + RootScreenType::RootScreenMasternodes + ); + assert_eq!(masternodes_segment(&mut harness), MasternodesSegment::Nodes); + assert!( + harness.query_by_label("ProTxHash").is_some(), + "the load form must open" + ); + }); +} + +#[test] +fn blocker_keyless_node_add_voting_key_opens_reimport_form() { + with_isolated_data_dir(|| { + let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime"); + let _guard = rt.enter(); + + let mut harness = mount_app(RootScreenType::RootScreenDPNSActiveContests); + let app_context = harness.state().current_app_context().clone(); + seed_node(&app_context, 93, "keyless", IdentityType::Masternode); + app_context + .insert_name_contests_as_normalized_names(vec!["alice".to_owned()]) + .expect("seed active contest"); + let Screen::MasternodesScreen(masternodes) = harness + .state_mut() + .main_screens + .get_mut(&RootScreenType::RootScreenMasternodes) + .expect("masternodes screen") + else { + panic!("the Masternodes root must contain the Masternodes screen"); + }; + masternodes.votes_mut().refresh(); + harness.run_steps(5); + + assert!( + harness + .query_by_label("None of your nodes has a voting key on this device.") + .is_some(), + "the no-voter-key explanation must render in To decide" + ); + harness.get_by_label("Add a voting key").click(); + harness.run_steps(3); + assert_eq!( + harness.state().selected_main_screen, + RootScreenType::RootScreenMasternodes + ); + assert_eq!(masternodes_segment(&mut harness), MasternodesSegment::Nodes); + assert!( + harness.query_by_label("ProTxHash").is_some(), + "the load form must open" + ); + }); +} + +/// A full result queue must yield to the window event loop while Voting refreshes a large cache. +#[test] +fn voting_refresh_burst_yields_between_frames() { + with_isolated_data_dir(|| { + // Disable backend dispatch before the click; inject equivalent results without network work. + let rt = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap(); + let _guard = rt.enter(); + let mut harness = mount_app(RootScreenType::RootScreenMasternodes); + let context = harness.state().current_app_context().clone(); + rt.block_on(harness.state().subtasks.shutdown_async()) + .unwrap(); + context + .insert_name_contests_as_normalized_names( + (0..985).map(|index| format!("cached{index:04}")).collect(), + ) + .unwrap(); + harness.get_by_label("Votes").click(); + harness.run_steps(3); + assert_eq!(masternodes_segment(&mut harness), MasternodesSegment::Votes); + let sender = harness.state().task_result_sender.clone(); + let mut queued = 0; + while sender.try_send(TaskResult::Refresh).is_ok() { + queued += 1; + } + assert!( + queued >= 192, + "the synthetic burst must fill most of the channel" + ); + let started = Instant::now(); + harness.step(); + let elapsed = started.elapsed(); + let remaining = harness.state().task_result_receiver.len(); + eprintln!( + "Voting985contest refresh burst: frame={elapsed:?}; remaining={remaining}/{queued}" + ); + // Egui may run multiple update passes during one frame; it must still yield with work queued. + assert!( + remaining > 0, + "A frame must yield instead of processing the entire refresh burst; elapsed={elapsed:?}, remaining={remaining}" + ); + assert_eq!( + harness.output().viewport_output[&egui::ViewportId::ROOT].repaint_delay, + Duration::ZERO, + "pending results must schedule another frame" + ); + let mut frames = 1; + let mut longest = elapsed; + while !harness.state().task_result_receiver.is_empty() && frames < 512 { + let started = Instant::now(); + harness.step(); + longest = longest.max(started.elapsed()); + frames += 1; + } + eprintln!("Voting refresh burst completed in {frames} frames; longest frame={longest:?}"); + assert!( + harness.state().task_result_receiver.is_empty(), + "deferred refreshes must eventually be delivered" + ); + rt.block_on(context.wallet_backend().unwrap().shutdown()); + }); +} + +#[test] +fn deferred_backend_results_preserve_success_error_order() { + use dash_evo_tool::backend_task::error::TaskError; + with_isolated_data_dir(|| { + let rt = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap(); + let _guard = rt.enter(); + let mut harness = mount_app(RootScreenType::RootScreenMasternodes); + rt.block_on(harness.state().subtasks.shutdown_async()) + .unwrap(); + let sender = harness.state().task_result_sender.clone(); + for _ in 0..192 { + sender.try_send(TaskResult::Repaint).unwrap(); + } + sender + .try_send(TaskResult::Success { + context: BackendTaskContext::Unknown, + result: Box::new(BackendTaskSuccessResult::Message( + "First result delivered.".to_owned(), + )), + }) + .unwrap(); + let error = TaskError::DpnsCurrentVoteUnavailable; + let error_text = error.to_string(); + sender + .try_send(TaskResult::Error { + context: BackendTaskContext::Unknown, + error, + }) + .unwrap(); + sender.try_send(TaskResult::Refresh).unwrap(); + sender + .try_send(TaskResult::Success { + context: BackendTaskContext::Unknown, + result: Box::new(BackendTaskSuccessResult::Message( + "Last result delivered.".to_owned(), + )), + }) + .unwrap(); + harness.step(); + assert!( + harness.query_by_label("Last result delivered.").is_none(), + "later results must remain queued when a frame yields" + ); + for _ in 0..64 { + harness.step(); + if harness.state().task_result_receiver.is_empty() { + break; + } + } + assert!(harness.state().task_result_receiver.is_empty()); + let first = harness.get_by_label("First result delivered.").rect(); + let error = harness.get_by_label(&error_text).rect(); + let last = harness.get_by_label("Last result delivered.").rect(); + assert!( + first.top() < error.top() && error.top() < last.top(), + "typed success/error results must retain their arrival order across frames" + ); + rt.block_on( + harness + .state() + .current_app_context() + .wallet_backend() + .unwrap() + .shutdown(), + ); + }); +} + /// TC-FR3-01/15, TC-FR7-01, TC-NFR6-01 — with nodes loaded the grid renders one /// card per node (not the empty state), each card is a single accessible click /// target labelled `Open {node}`, the status label pairs with its colour, and @@ -574,13 +900,11 @@ fn detail_view_opens_from_card_with_sections_and_back() { }); } -/// TC-DPNS-01/02/09/10 — the DPNS section is collapsed by default (its body is -/// not rendered), the header carries the open-contest count, and for a node with -/// no voter identity the expanded section shows the actionable missing-voter -/// message with an `Add voting key` action that opens a scoped in-place prompt -/// (not FR-4's load form — no ProTxHash field). +/// VOTE-TC-091: the node detail lists the node's votes and its list status; +/// `Vote with this node` opens Votes ▸ To decide with that node alone and no +/// staged decision. Without a voting key the action is disabled. #[test] -fn dpns_section_missing_voter_scoped_prompt() { +fn detail_vote_with_this_node_opens_votes_for_that_node() { with_isolated_data_dir(|| { let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime"); let _guard = rt.enter(); @@ -588,45 +912,40 @@ fn dpns_section_missing_voter_scoped_prompt() { let mut harness = mount_app(RootScreenType::RootScreenIdentityHub); let app_context = harness.state().current_app_context().clone(); seed_node(&app_context, 0x95, "mn-vote-01", IdentityType::Masternode); + seed_node_with_voter_key(&app_context, 0x96, "mn-vote-02"); activate_masternodes_tab(&mut harness, &app_context); + harness.get_by_label("Open mn-vote-01").click(); harness.run_steps(3); - - // With no voter key the "Add voting key" CTA and its - // actionable message are rendered ABOVE, outside the collapsed-by-default - // DPNS section, so they are visible immediately without expanding - // anything. The empty DPNS header is omitted in this state (no contests - // are possible without a voter). + assert!(harness.query_by_label("This node's votes").is_some()); assert!( harness - .query_by_label("DPNS name contests to vote on (0)") - .is_none(), - "the empty DPNS header must be omitted when the node has no voter key" - ); - assert!( - harness - .query_by_label( - "This node has no voting key loaded. Add its voting private key to cast votes." - ) - .is_some(), - "the actionable missing-voter message must be visible without expanding" + .query_by_label("Masternode list membership unknown.") + .is_some() ); + assert!(harness.query_by_label("DPNS Voting").is_none()); + let keyless = harness.get_by_label("Vote with this node"); assert!( - harness.query_by_label("Add voting key").is_some(), - "missing-voter state must offer an Add voting key action" + keyless.accesskit_node().is_disabled(), + "a key-less node cannot vote" ); - // Click Add voting key → scoped in-place prompt (Save/Cancel), NOT the - // load form (no ProTxHash field) (TC-DPNS-10/11). - harness.get_by_label("Add voting key").click(); + harness.get_by_label("‹ All masternodes").click(); harness.run_steps(3); - assert!( - harness.query_by_label("Save").is_some(), - "scoped voter-key prompt must open with a Save action" + harness.get_by_label("Open mn-vote-02").click(); + harness.run_steps(3); + harness.get_by_label("Vote with this node").click(); + harness.run_steps(3); + assert_eq!( + harness.state().selected_main_screen, + RootScreenType::RootScreenMasternodes ); + assert!(harness.query_by_label("To decide").is_some()); assert!( - harness.query_by_label("ProTxHash").is_none(), - "the scoped prompt must not be FR-4's load form (no ProTxHash re-entry)" + harness + .query_by_label_contains("Vote with: Custom · 1 node") + .is_some(), + "the node-set chip names that single node" ); }); } @@ -850,6 +1169,9 @@ fn remove_flow_deletes_associated_voter_identity() { // Open the node's detail and confirm removal. harness.get_by_label("Open mn-with-voter").click(); harness.run_steps(3); + // A node without a signing key also shows the add-key form above removal. + harness.get_by_label("Remove masternode").scroll_to_me(); + harness.run_steps(3); harness.get_by_label("Remove masternode").click(); harness.run_steps(3); let confirm = harness diff --git a/tests/kittest/migration_banner.rs b/tests/kittest/migration_banner.rs index 976d713e6..6ff7f4b15 100644 --- a/tests/kittest/migration_banner.rs +++ b/tests/kittest/migration_banner.rs @@ -6,11 +6,10 @@ //! needing a full `AppState` harness. use dash_evo_tool::app::{ - MIGRATION_IDENTITIES_ACK_ACTION_ID, MIGRATION_RETRY_ACTION_ID, - MIGRATION_UNREADABLE_ACK_ACTION_ID, MIGRATION_VOTES_ACK_ACTION_ID, + MIGRATION_APP_DATA_ACK_ACTION_ID, MIGRATION_IDENTITIES_ACK_ACTION_ID, + MIGRATION_RETRY_ACTION_ID, MIGRATION_UNREADABLE_ACK_ACTION_ID, migration_failed_with_unreadable_identities_text, migration_running_text, - migration_unreadable_identities_and_votes_text, migration_unreadable_identities_text, - migration_unreadable_votes_text, + migration_unreadable_data_text, migration_unreadable_identities_text, }; use dash_evo_tool::context::migration_status::MigrationStep; use dash_evo_tool::ui::MessageType; @@ -150,13 +149,13 @@ fn tc_a11y_004_failure_banner_uses_icon_and_text() { ); } -/// QA-101 — a migration that drained the wallets but could not read some legacy -/// scheduled votes surfaces a Warning banner naming the recovery action, and +/// QA-101 — a migration that drained the wallets but could not read some +/// balance top-up records surfaces a Warning banner naming what to check, and /// offers NO "Retry now": the drain is done and a corrupt row decodes no better /// on a second pass, so a retry button would be a dead end. #[test] -fn unreadable_votes_banner_warns_without_a_retry_action() { - let text = migration_unreadable_votes_text(2); +fn unreadable_top_ups_banner_warns_without_a_retry_action() { + let text = migration_unreadable_data_text(0, 2); assert!( text.ends_with('.'), "banner copy must be a complete sentence for i18n extraction: `{text}`", @@ -173,7 +172,7 @@ fn unreadable_votes_banner_warns_without_a_retry_action() { assert!( harness.query_by_label(text.as_str()).is_some(), - "the warning banner must render the unreadable-votes copy verbatim", + "the warning banner must render the unreadable top-up copy verbatim", ); assert!( harness.query_by_label("Retry now").is_none(), @@ -183,17 +182,16 @@ fn unreadable_votes_banner_warns_without_a_retry_action() { /// Fix-8 — the warning carries an explicit acknowledgement, and clicking it /// enqueues the ack action id. The app loop drains that id and clears the -/// durable warning record; until then the banner returns on every launch, so a -/// vote whose deadline still matters cannot lose its only notice to a stray -/// dismissal. +/// durable warning record; until then the banner returns on every launch, so +/// the notice cannot be lost to a stray dismissal. #[test] -fn unreadable_votes_banner_acknowledgement_enqueues_action() { - let text = migration_unreadable_votes_text(2); +fn unreadable_top_ups_banner_acknowledgement_enqueues_action() { + let text = migration_unreadable_data_text(0, 2); let mut harness = Harness::builder() .with_size(egui::vec2(600.0, 220.0)) .build_ui(move |ui| { let handle = MessageBanner::set_global(ui.ctx(), text.clone(), MessageType::Warning); - handle.with_action("Got it", MIGRATION_VOTES_ACK_ACTION_ID); + handle.with_action("Got it", MIGRATION_APP_DATA_ACK_ACTION_ID); MessageBanner::show_global(ui); }); harness.run(); @@ -204,7 +202,7 @@ fn unreadable_votes_banner_acknowledgement_enqueues_action() { assert_eq!( MessageBanner::take_action(&harness.ctx).as_deref(), - Some(MIGRATION_VOTES_ACK_ACTION_ID), + Some(MIGRATION_APP_DATA_ACK_ACTION_ID), ); } @@ -213,13 +211,12 @@ fn unreadable_votes_banner_acknowledgement_enqueues_action() { /// screen and no control, which leaves the Everyday User hunting for a flow they /// may never have opened — the repo's error-message rules require a concrete, /// self-serviceable action. The remedy lives behind "Load Identity" on the -/// Identities screen, so all three variants name both, exactly as the vote copy -/// names the Scheduled Votes screen. +/// Identities screen, so all three variants name both. #[test] fn every_unreadable_identity_message_names_where_to_load_them_again() { for text in [ migration_unreadable_identities_text(2), - migration_unreadable_identities_and_votes_text(2, 3), + migration_unreadable_data_text(2, 3), migration_failed_with_unreadable_identities_text(1), ] { assert!( @@ -285,12 +282,10 @@ fn unreadable_identities_banner_acknowledgement_enqueues_action() { /// The combined banner names both problems, so its single "Got it" must enqueue /// the combined acknowledgement — the one that retires BOTH durable records. /// Routing it to either single-signal ack would leave the other half to re-raise -/// on the next launch, as a notice the user has already read. Supersedes the -/// pre-fix coverage that routed this banner's "Got it" to the vote-only ack — -/// that routing no longer matches the combined-ack design this ships. +/// on the next launch, as a notice the user has already read. #[test] fn combined_unreadable_banner_acknowledgement_enqueues_the_combined_action() { - let text = migration_unreadable_identities_and_votes_text(2, 3); + let text = migration_unreadable_data_text(2, 3); let label = text.clone(); let mut harness = Harness::builder() .with_size(egui::vec2(600.0, 260.0)) diff --git a/tests/kittest/register_dpns_name_screen.rs b/tests/kittest/register_dpns_name_screen.rs index 6f000443f..817cfa776 100644 --- a/tests/kittest/register_dpns_name_screen.rs +++ b/tests/kittest/register_dpns_name_screen.rs @@ -3,19 +3,21 @@ //! //! Proves the canonical contract the remaining transaction screens will copy: //! dispatching the registration raises the global blocking overlay, and every -//! terminal result — success (`display_task_result`) or error -//! (`display_message`) — tears it down (the no-hard-lock guarantee). +//! terminal result — success (`display_task_result`) or a matching error +//! (`display_backend_task_error`) — tears it down (the no-hard-lock guarantee). //! //! The screen needs an `Arc`, so each test borrows one from a //! throwaway `AppState` built in an isolated data dir. The overlay raise/teardown //! runs against an independent `egui::Context` the AppState never renders, so the //! app's own SPV block can't perturb the `has_global` assertions. -use crate::support::with_isolated_data_dir; -use dash_evo_tool::app::AppState; -use dash_evo_tool::backend_task::{BackendTaskSuccessResult, FeeResult}; +use crate::support::{fresh_app_context, with_isolated_data_dir}; +use dash_evo_tool::app::{AppAction, AppState}; +use dash_evo_tool::backend_task::error::TaskError; +use dash_evo_tool::backend_task::{BackendTaskContext, BackendTaskSuccessResult, FeeResult}; use dash_evo_tool::context::AppContext; use dash_evo_tool::model::dpns::DpnsRegistrationOutcome; +use dash_evo_tool::model::dpns_usernames::UsernameAvailability; use dash_evo_tool::model::qualified_identity::encrypted_key_storage::KeyStorage; use dash_evo_tool::model::qualified_identity::{IdentityStatus, IdentityType, QualifiedIdentity}; use dash_evo_tool::ui::MessageType; @@ -37,7 +39,7 @@ use std::sync::Arc; fn screen_with_context() -> RegisterDpnsNameScreen { let app_state = AppState::new(egui::Context::default()).expect("AppState builds"); let app_context = app_state.current_app_context().clone(); - RegisterDpnsNameScreen::new(&app_context, RegisterDpnsNameSource::Dpns) + RegisterDpnsNameScreen::new(&app_context, RegisterDpnsNameSource::Identities) } /// Dispatching the registration raises the global blocking overlay. @@ -100,7 +102,6 @@ fn assert_registration_outcome_copy(outcome: DpnsRegistrationOutcome, expected: harness.run(); assert!(harness.query_by_label(expected).is_some()); - assert!(harness.query_by_label("DPNS Name Registered!").is_none()); assert!(harness.query_by_label(wrong).is_none()); }); } @@ -109,8 +110,8 @@ fn assert_registration_outcome_copy(outcome: DpnsRegistrationOutcome, expected: fn dpns_registered_outcome_renders_finalized_copy() { assert_registration_outcome_copy( DpnsRegistrationOutcome::Registered, - "Your username is registered. You can use it now.", - "Your username request was submitted. Other people can also request this name, so the community will vote on who receives it. Check the Pending label on your identity for updates.", + "People can now find and pay you by this name.", + "We'll show the result on your identity's page. You don't need to keep this screen open.", ); } @@ -118,8 +119,8 @@ fn dpns_registered_outcome_renders_finalized_copy() { fn dpns_pending_outcome_renders_voting_copy() { assert_registration_outcome_copy( DpnsRegistrationOutcome::PendingCommunityVote, - "Your username request was submitted. Other people can also request this name, so the community will vote on who receives it. Check the Pending label on your identity for updates.", - "Your username is registered. You can use it now.", + "We'll show the result on your identity's page. You don't need to keep this screen open.", + "People can now find and pay you by this name.", ); } @@ -176,7 +177,7 @@ fn dpns_registration_defaults_to_app_scoped_identity() { app_context.set_selected_identity(Some(second)); - let screen = RegisterDpnsNameScreen::new(&app_context, RegisterDpnsNameSource::Dpns); + let screen = RegisterDpnsNameScreen::new(&app_context, RegisterDpnsNameSource::Identities); assert_eq!( screen @@ -189,24 +190,49 @@ fn dpns_registration_defaults_to_app_scoped_identity() { }); } -/// An error message tears the overlay down (error terminal path): -/// failed registration can never leave the window hard-locked. +/// Only the dispatched registration's error releases the blocking overlay. #[test] -fn dpns_error_message_clears_overlay() { +fn dpns_registration_error_clears_overlay() { with_isolated_data_dir(|| { - let rt = tokio::runtime::Runtime::new().expect("tokio runtime"); - let _guard = rt.enter(); - - let mut screen = screen_with_context(); + let (_rt, app_context) = fresh_app_context(); + let identity_id = seed_identity_for_dpns(&app_context, 0x33, "Alice"); + app_context.set_selected_identity(Some(identity_id)); + let mut screen = + RegisterDpnsNameScreen::new(&app_context, RegisterDpnsNameSource::Identities); + screen.type_label_for_test("alice"); + let _ = screen.flush_debounce_for_test(); + screen.display_task_result(BackendTaskSuccessResult::UsernameAvailability { + label: "alice".to_owned(), + availability: UsernameAvailability::NeedsVote, + }); + screen.open_confirm_for_test(); let ctx = egui::Context::default(); - screen.raise_progress_overlay_for_test(&ctx); + let AppAction::BackendTaskWithContext { context, .. } = + screen.begin_registration_for_test(&ctx) + else { + panic!("expected registration dispatch"); + }; assert!(ProgressOverlay::has_global(&ctx)); - screen.display_message("Registration failed. Try again.", MessageType::Error); + let error = TaskError::UsernameAvailabilityCheckFailed { + source: Box::new(dash_sdk::Error::Generic("timeout".into())), + }; + screen.display_backend_task_error(&BackendTaskContext::Unknown, &error); + assert!(!screen.display_task_error(&error)); + screen.display_message(&error.to_string(), MessageType::Error); + assert!( + ProgressOverlay::has_global(&ctx), + "an unrelated error must not release the pending registration" + ); + + screen.display_backend_task_error(&context, &error); + assert!(!screen.display_task_error(&error)); + screen.display_message(&error.to_string(), MessageType::Error); assert!( !ProgressOverlay::has_global(&ctx), "an error result must tear down the blocking overlay" ); + assert!(screen.is_confirming_for_test()); }); }