From 382efc5c0d0c6fdd5ba27b2e03b314b354cd2d77 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 16 Jul 2026 09:02:15 +0000 Subject: [PATCH 001/194] docs(dpns): design unified voting experience MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Define authoritative vote state, a shared quick and bulk composer, durable operation coordination, safe post-broadcast recovery, and scheduled-vote consolidation before implementation begins. Co-Authored-By: Codex GPT-5 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- .../01-requirements.md | 208 +++++++++++++ .../02-ux-spec.md | 266 ++++++++++++++++ .../03-test-case-spec.md | 89 ++++++ .../04-development-plan.md | 291 ++++++++++++++++++ 4 files changed, 854 insertions(+) create mode 100644 docs/ai-design/2026-07-16-dpns-voting-experience/01-requirements.md create mode 100644 docs/ai-design/2026-07-16-dpns-voting-experience/02-ux-spec.md create mode 100644 docs/ai-design/2026-07-16-dpns-voting-experience/03-test-case-spec.md create mode 100644 docs/ai-design/2026-07-16-dpns-voting-experience/04-development-plan.md 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..3d81a6791 --- /dev/null +++ b/docs/ai-design/2026-07-16-dpns-voting-experience/01-requirements.md @@ -0,0 +1,208 @@ +# DPNS Voting Experience β€” Requirements + +## Status + +Planning specification. No implementation is authorized by this document. + +## Problem statement + +DET exposes DPNS voting through two disconnected experiences: + +- a quick per-node section on the Masternodes detail page; and +- a legacy DPNS bulk dialog for multiple contests, nodes, and schedules. + +Both call the same backend, but neither owns a complete, authoritative model of +the operation. The result is unsafe ambiguity: a vote can be accepted while DET +shows no confirmation, the same choice can immediately be offered again, bulk +results cannot identify the affected node, and a second click can submit another +state transition while the first is unresolved. + +Voting consumes Platform credits and each node may vote only five times on a +contest in total (the initial vote plus up to four changes). Duplicate or +ambiguous submissions therefore have a real cost. + +## Primary persona + +Priya, the power-user masternode operator, manages one or more nodes and expects: + +- current vote state to be accurate; +- quick actions for one node; +- bulk and scheduled operations for many nodes; +- progress that survives navigation and restart; +- 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. It is not an +Everyday User workflow. + +## 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 | +| Legacy bulk workflow is disconnected | Bulk and scheduling live under DPNS while node management lives under Masternodes | Operators can miss existing capabilities or assume they were removed | + +## Product decisions + +1. Masternodes is the primary home for operator voting. +2. DPNS remains the home for name registration, contest discovery, and contest + history, with a route into the shared voting workspace. +3. Quick voting and bulk/scheduled voting use one shared composer and one shared + operation coordinator. +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. + +## Functional requirements + +### Information architecture + +- **VOTE-FR-001** β€” Masternodes provides `Nodes`, `Voting`, and `Scheduled` + views under one operator-focused root. +- **VOTE-FR-002** β€” The DPNS Active Contests page links to the same Voting view; + it does not maintain a second bulk implementation. +- **VOTE-FR-003** β€” A node detail page offers quick voting and an `Open Voting + Center` action pre-filtered to that node. + +### Authoritative state + +- **VOTE-FR-010** β€” DET queries each loaded node's proved Platform votes and + joins them with active contests. +- **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** β€” A change to an existing vote is labeled as a limited vote + change in Review. DET does not claim to know the remaining count. +- **VOTE-FR-016** β€” If current vote state cannot be proved, DET shows it as + unavailable and disables submission for that node instead of assuming + `Not voted`. +- **VOTE-FR-017** β€” Node summaries distinguish active contests from contests + where the node has not voted yet. + +### Vote composition + +- **VOTE-FR-020** β€” Quick voting supports one node across one or more contests. +- **VOTE-FR-021** β€” Bulk voting supports one or more contests across one or more + nodes. +- **VOTE-FR-022** β€” The operator can apply one timing choice to all selected + nodes and override individual nodes. +- **VOTE-FR-023** β€” Timing choices are `Cast now`, `Schedule`, and `Do not use + this node`. +- **VOTE-FR-024** β€” Before submission, a review step lists every target as + node Γ— contest, including current choice, requested choice, and timing. +- **VOTE-FR-025** β€” The review step removes no-op targets and explains why. + +### 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 `Not applied` after definitive + post-broadcast reconciliation. +- **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** β€” Button state derives from the shared coordinator. A click + disables the affected action immediately and shows progress text. +- **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. + +### Confirmation and recovery + +- **VOTE-FR-040** β€” Structured Platform consensus causes are treated as + confirmed 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 and, when available, retried by transition hash through the + Platform SDK. +- **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** β€” A retry becomes available only after authoritative + reconciliation proves the requested change was not applied. + +### 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** β€” Existing scheduled-vote records migrate without losing node, + contest, choice, time, or executed state. +- **VOTE-FR-055** β€” A scheduled target can be edited or cancelled until + execution begins. Once submitting, it follows normal operation locking. + +### Feedback + +- **VOTE-FR-060** β€” One confirmed target shows a concise success banner. +- **VOTE-FR-061** β€” Batch feedback summarizes confirmed, unconfirmed, rejected, + and failed counts and links to per-target details. +- **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. + +## 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. +- **VOTE-NFR-007 Performance** β€” Refresh queries votes once per node, not once + per contest, and bounds cross-node concurrency. +- **VOTE-NFR-008 Network isolation** β€” Drafts, schedules, operations, locks, and + results are network-scoped. +- **VOTE-NFR-009 Secret handling** β€” The coordinator stores identifiers and + choices, never private keys. + +## Platform dependency + +The preferred recovery contract is +[dashpay/platform#4137](https://github.com/dashpay/platform/issues/4137), which +tracks phase-specific, retryable post-broadcast wait errors. The SDK should +expose the transition hash after broadcast so DET can persist it and resume +waiting. + +DET must still support fallback reconciliation by fetching the node's proved +vote for the target poll. Until either method proves the result, the operation +remains unconfirmed and locked against duplicate submission. + +## 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. +- Embedding Platform Explorer. +- Allowing arbitrary cancellation after broadcast. 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..b526819f3 --- /dev/null +++ b/docs/ai-design/2026-07-16-dpns-voting-experience/02-ux-spec.md @@ -0,0 +1,266 @@ +# DPNS Voting Experience β€” UX Specification + +## Experience principle + +Voting is one operator workflow with two entry speeds: + +- **Quick vote** β€” one selected node, usually one or a few contests. +- **Voting Center** β€” many contests, many nodes, immediate and scheduled + targets. + +Both are views over the same draft, authoritative vote state, and operation +coordinator. They must never disagree about current votes or progress. + +## Information architecture + +```text +Masternodes +β”œβ”€β”€ Nodes +β”‚ β”œβ”€β”€ Node cards +β”‚ └── Node detail +β”‚ β”œβ”€β”€ Keys and actions +β”‚ β”œβ”€β”€ Quick voting +β”‚ └── Open Voting Center (filtered to this node) +β”œβ”€β”€ Voting +β”‚ β”œβ”€β”€ Active contests +β”‚ β”œβ”€β”€ Vote composer +β”‚ └── Recent operations +└── Scheduled + β”œβ”€β”€ Upcoming + β”œβ”€β”€ Needs attention + └── Completed + +DPNS +β”œβ”€β”€ Active contests ── β€œVote with masternodes” ──> Masternodes / Voting +β”œβ”€β”€ Past contests +└── My usernames +``` + +The existing DPNS bulk popup is retired after the shared Voting Center is +available. DPNS contest browsing remains; operator actions route to +Masternodes. + +## Shared concepts + +### Current vote + +Every node Γ— contest row shows one of: + +- `Not voted` +- `Current vote: Abstain` +- `Current vote: Lock` +- `Current vote: {candidate}` +- `Checking current vote…` +- `Current vote unavailable` + +An existing vote does not remove the contest. Selecting a different choice is +labeled as a change. + +`Current vote unavailable` disables that node's choice controls and offers +`Refresh vote state`. DET never treats an unavailable query as `Not voted`. + +Node cards summarize both concepts, for example: + +> 3 active contests Β· 1 needs a vote + +When every active contest has a current vote: + +> Votes cast in all active contests + +### Target + +A target is one requested action for one node on one contest. Batch progress +and results are always expressed in targets, never only in aggregate. + +### Operation + +An operation is the reviewed collection of targets submitted together. It owns +progress across screens and process restarts. + +## Journey A β€” Quick vote from a node + +1. Priya opens a node. +2. The DPNS section shows all active contests and the node's current choice. +3. Priya selects a new choice on one or more rows. +4. The primary action becomes `Review 1 vote` or `Review {n} votes`. +5. Review lists current β†’ requested choice for this node. +6. Priya chooses `Cast now` or `Schedule instead`, then confirms. +7. Affected rows become read-only and show `Submitting…` or `Scheduled`. +8. Priya may navigate elsewhere. A global banner links to operation progress. +9. Confirmed rows update their current vote in place; they do not disappear. + +```text +DPNS name contests (3) + +alice.dash +Current vote: Abstain +( Abstain ) ( Lock ) ( Vote for alice ) + +dominguez.dash +Not voted +( Abstain ) ( Lock ) ( Vote for dominguez ) + + [ Review 1 vote ] + [ Open Voting Center ] +``` + +## Journey B β€” Bulk vote or schedule + +The composer is a three-step full-page flow, not a transient popup. Nodes come +first so every later β€œcurrent vote” summary has a defined node scope. + +### Step 1: Nodes and timing + +Priya selects nodes and chooses timing. `Set all` applies timing only; it does +not alter contest choices. + +```text +Voting Center Step 1 of 3: Nodes and timing + +Set all: [ Cast now v ] [ Apply ] + +[x] Eve Mainnet Cast now +[x] Backup Evo Schedule: 2026-07-20 18:00 UTC +[ ] Test Operator Do not use this node + + [ Next: Choose votes ] +``` + +### Step 2: Votes + +Priya selects contests and a requested choice for each contest. Current-state +summaries cover only the nodes selected in Step 1. + +```text +Step 2 of 3: Votes + +[ ] alice.dash Current across selected nodes: Mixed + Abstain | Lock | Vote for alice + +[x] dominguez.dash Current across selected nodes: 1 not voted, 1 Lock + Abstain | Lock | Vote for dominguez + + [ Back ] [ Review 2 targets ] +``` + +### Step 3: Review + +The review expands the cartesian product into exact targets. No-op targets are +removed and explained. + +```text +Step 3 of 3: Review + +Node Contest Current Requested When +Eve Mainnet dominguez.dash Not voted dominguez Now +Backup Evo dominguez.dash Lock dominguez Jul 20 + +2 targets total. Each vote uses Platform credits. + + [ Back ] [ Submit 2 targets ] +``` + +## Journey C β€” Operation progress + +After submit, the review becomes an operation detail page. + +```text +Submitting votes +1 confirmed Β· 1 checking + +βœ“ Eve Mainnet / dominguez.dash + Vote confirmed: dominguez + +… Backup Evo / dominguez.dash + The vote was submitted. DET is checking the result. + + [ Continue in background ] +``` + +Target rows expose technical details only through the standard expandable +details affordance. If a transition hash is available, developer mode may show +and copy it. + +## Journey D β€” Unconfirmed result + +1. Broadcast succeeds. +2. Waiting for the result fails without a structured consensus cause. +3. The target becomes `Unconfirmed`; it is not labeled failed. +4. The exact node Γ— contest target remains locked. +5. DET retries the result wait and/or fetches the proved current vote. +6. If the requested choice appears, the target becomes `Confirmed`. +7. If authoritative reconciliation proves it was not applied, the target + becomes `Not applied` and offers `Submit again`. +8. If Platform remains unavailable, the persistent action is `Check again`. + +Banner copy: + +> The vote was submitted, but DET could not confirm the result yet. DET will +> keep checking. Do not submit it again. + +## Journey E β€” Scheduled vote + +- Scheduled targets appear immediately in `Masternodes > Scheduled`. +- Before execution begins, `Edit schedule` and `Cancel scheduled vote` remain + available. +- At execution time, status changes from `Scheduled` to `Submitting`. +- A confirmed result becomes `Completed`. +- A definite rejection becomes `Needs attention`. +- An ambiguous result becomes `Checking result`; it is never automatically + rebroadcast. + +## Control state + +| Target state | Choice controls | Submit action | Other targets | +|---|---|---|---| +| Draft | Enabled | Enabled when draft has changes | Enabled | +| Current vote unavailable | Disabled for that node | `Refresh vote state` | Enabled | +| Scheduled | Read-only for that target | `Edit schedule` | Enabled | +| Queued / Submitting / Confirming | Disabled | Spinner + status | Enabled | +| Unconfirmed | Disabled | `Check again` | Enabled | +| Confirmed | Enabled for a deliberate change | No draft action | Enabled | +| Rejected / Failed before submission / Not applied | Enabled after correction | `Review again` | Enabled | + +The disabled tooltip names the exact reason, for example: + +> This node's vote for dominguez.dash is still being confirmed. + +## Feedback matrix + +| Outcome | Type | Primary copy | +|---|---|---| +| One confirmed | Success | `Vote cast successfully.` | +| All batch targets confirmed | Success | `{count} votes were cast successfully.` | +| Scheduled | Success | `{count} votes were scheduled.` | +| Partial | Warning | `{confirmed} of {total} votes were confirmed. Review the remaining {remaining}.` | +| Unconfirmed | Warning, persistent | `The vote was submitted, but DET could not confirm the result yet. DET will keep checking. Do not submit it again.` | +| Structured rejection | Error | Typed, user-actionable rejection message | +| Failed before broadcast | Error | `This vote was not submitted. {action}` | +| No-op | Info | `This node already has that vote. Nothing was submitted.` | + +## Navigation and persistence + +- Operation progress is not owned by a screen instance. +- Leaving Masternodes never clears an active operation. +- Returning to any voting entry point reads current operation state and locks + affected targets. +- On startup, DET restores scheduled and unresolved targets before voting + controls become available. +- Switching networks swaps to that network's independent voting workspace. + +## Accessibility and interaction + +- Use styled buttons and semantic status colors with text labels. +- Minimum click targets follow the shared button component. +- `Enter` advances or submits only on the review step. +- `Escape` closes a draft review but cannot cancel a submitted operation. +- Focus moves to the step heading after Back/Next. +- Progress text and spinner are both present; no status is color-only. +- Disabled controls use the standard disabled tooltip policy. + +## Responsive behavior + +- Desktop: contest table and node/timing table use the full island panel. +- Narrow width: target rows become stacked cards showing Node, Contest, Current, + Requested, Timing, and Status. +- Operation progress remains usable without horizontal scrolling. 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..775f44ff3 --- /dev/null +++ b/docs/ai-design/2026-07-16-dpns-voting-experience/03-test-case-spec.md @@ -0,0 +1,89 @@ +# DPNS Voting Experience β€” Test Case Specification + +## 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 | Row shows `Current vote: Lock` | FR-010, FR-011 | +| VOTE-TC-002 | Existing vote remains visible | Node already voted; contest active | Open node detail | Contest remains listed and change controls are available | FR-012 | +| VOTE-TC-003 | Current choice is a no-op | Current vote is Lock | Select Lock and review | Target is removed; nothing can be submitted | FR-013, FR-025 | +| VOTE-TC-004 | Coherent refresh | Contest tally and current vote both changed | Refresh | One snapshot shows both new values | FR-014 | +| VOTE-TC-005 | Vote query is per node | One node, 100 contests | Refresh | Identity-votes query runs once for the node, not 100 times | NFR-007 | +| VOTE-TC-006 | Vote change warning | Node has an existing vote | Select a different choice and review | Review says this uses a limited vote change without inventing a remaining count | FR-015 | +| VOTE-TC-007 | Vote query failure is not `Not voted` | Proved identity-votes query fails | Open voting | State is unavailable; affected submit controls are disabled | FR-016, NFR-004 | +| VOTE-TC-008 | Node summary distinguishes active and unvoted | Three active contests; node voted in two | View node card | Summary says three active and one needs a vote | FR-017 | + +## Quick voting + +| ID | Description | Preconditions | Steps | Expected outcome | Requirements | +|---|---|---|---|---|---| +| VOTE-TC-010 | Quick single vote | Node detail, one draft choice | Review and submit | One target is created for the selected node and contest | FR-020, FR-024 | +| VOTE-TC-011 | Quick multi-contest vote | Node detail, three draft choices | Review | Review shows three exact targets | FR-020, FR-031 | +| VOTE-TC-012 | Quick schedule | Node detail, one draft | Choose Schedule in review | Target appears in Scheduled with the chosen time | FR-023, FR-050 | +| VOTE-TC-013 | Missing voting key | Node lacks voter key | Open voting | Actionable add-key state appears; submit is unavailable | FR-003 | + +## Bulk voting + +| ID | Description | Preconditions | Steps | Expected outcome | Requirements | +|---|---|---|---|---|---| +| VOTE-TC-020 | Multiple contests and nodes | Two contests, three nodes | Select all and review | Six exact targets are listed | FR-021, FR-024 | +| VOTE-TC-021 | Set all timing | Three selected nodes | Apply Schedule to all | All nodes receive the same schedule | FR-022, FR-023 | +| VOTE-TC-022 | Per-node override | Set all Cast now | Override one node to Schedule | Review reflects two Now and one Scheduled target | FR-022 | +| VOTE-TC-023 | DPNS route reuses workspace | DPNS Active Contests visible | Click `Vote with masternodes` | Shared Masternodes Voting view opens; no legacy popup appears | FR-002 | +| VOTE-TC-024 | Node route prefilters | Node detail visible | Click `Open Voting Center` | Voting view opens with only that node selected | FR-003 | +| VOTE-TC-025 | Current summary uses selected nodes | Three nodes loaded; two selected | Open Votes step | `Current across selected nodes` excludes the unselected node | FR-011, FR-021 | + +## Execution correctness + +| 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 | Submit enabled | Double-click Submit | Exactly one operation and one target broadcast are created | FR-034, FR-035 | +| VOTE-TC-041 | Cross-screen duplicate | Target is confirming from quick vote | Open Voting Center | Same node Γ— contest target is disabled with explanation | FR-034, FR-036 | +| VOTE-TC-042 | Unrelated target stays usable | One target confirming | Select another node or contest | Unrelated target remains enabled | Product decision 7 | +| VOTE-TC-043 | Navigation preserves lock | Submit, leave page, return before result | Inspect target | Progress and lock remain active | FR-036 | +| VOTE-TC-044 | Restart preserves lock | Persist unresolved target; restart | Open Voting | Target is restored and reconciled before resubmission is allowed | 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 | Unconfirmed target; definitive reconciliation proves absence | Check again | Status allows reviewed resubmission | 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 | Partial batch | Two confirmed, one unconfirmed, one rejected | Complete batch | Warning shows counts and details map every target | FR-061, FR-062 | + +## Scheduling and migration + +| ID | Description | Preconditions | Steps | Expected outcome | Requirements | +|---|---|---|---|---|---| +| VOTE-TC-060 | Legacy schedule migration | Existing scheduled-vote records | Upgrade | Node, contest, choice, time, and executed state are preserved | 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 | +| 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 | + +## UX, accessibility, and isolation + +| ID | Description | Preconditions | Steps | Expected outcome | Requirements | +|---|---|---|---|---|---| +| VOTE-TC-070 | Progress button state | Target submitting | Inspect action | Disabled styled action shows spinner, text, and tooltip | FR-035, NFR-005 | +| VOTE-TC-071 | Keyboard review | Composer draft ready | Tab, Enter, Escape | Focus order is logical; Enter submits only at review; Escape closes only drafts | NFR-005 | +| VOTE-TC-072 | Network isolation | Testnet target unresolved | Switch Mainnet | Mainnet has no Testnet locks or operation rows | NFR-008 | +| VOTE-TC-073 | No secret persistence | Operation stored | Inspect serialized operation | No private key or WIF bytes are present | NFR-009 | +| VOTE-TC-074 | Complete message units | All new copy | Localization audit | Strings are complete and do not parse technical errors | NFR-006 | +| VOTE-TC-075 | All entry points share one submit path | Quick, bulk, and due-scheduled drafts | Dispatch each | Every path creates a coordinator operation; no legacy direct-broadcast path remains | NFR-001 | +| VOTE-TC-076 | Technical error stays in details | Target rejected or fails | Inspect banner | Primary copy is plain language; typed diagnostic is attached as details | 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..cac053d1f --- /dev/null +++ b/docs/ai-design/2026-07-16-dpns-voting-experience/04-development-plan.md @@ -0,0 +1,291 @@ +# DPNS Voting Experience β€” Development Plan + +## Architecture + +```text +Platform proved queries + β”‚ + β–Ό +DPNS vote-state store ────────┐ + β”‚ +Draft / shared 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 +``` + +Screens never own the authoritative in-progress flag. They render coordinator +state and submit typed drafts. + +## Domain model + +Add `src/model/dpns_voting.rs` with pure, serializable types: + +```rust +struct DpnsVoteTargetKey { + network: Network, + voter_id: Identifier, + vote_poll_id: Identifier, +} + +struct DpnsVoteTarget { + key: DpnsVoteTargetKey, + contested_name: String, + requested_choice: ResourceVoteChoice, + current_choice: Option, + timing: VoteTiming, +} + +struct DpnsVoteOperationId([u8; 16]); + +enum VoteTiming { + Now, + Scheduled(TimestampMillis), +} + +enum DpnsVoteTargetStatus { + Scheduled, + Queued, + Submitting, + Confirming, + Confirmed, + Unconfirmed, + Rejected, + FailedBeforeSubmission, + NotApplied, +} + +struct DpnsVoteOutcome { + operation_id: DpnsVoteOperationId, + target: DpnsVoteTarget, + status: DpnsVoteTargetStatus, + transition_hash: Option<[u8; 32]>, + failure: Option, +} +``` + +Generate `DpnsVoteOperationId` with the project's existing random-number +dependency; no new UUID dependency is required. + +`DpnsVoteFailure` is a pure domain enum, not a wrapper around `TaskError`. +Backend errors are mapped into it structurally. The stored form uses +serde-friendly representations and never serializes `TaskError` or secrets. +Full errors remain in task diagnostics and logs. + +## Data ownership + +### Authoritative current votes + +Add `src/context/dpns_vote_state.rs`. + +- Query `ResourceVote::fetch_many` once per loaded node using its ProTxHash. +- Index results by node + vote-poll ID. +- Persist the latest proved snapshot in the node's identity scope. +- Join vote state with global contest data when building UI view models. +- Stop using `ContestedName::my_votes` as an implied persistent source. Remove + it or populate it only in an explicitly transient joined view. + +This fixes the current false `Not voted` state and supports deliberate changes. + +### Operation journal and locks + +Add `src/context/dpns_vote_operations.rs`. + +- Persist an operation before the first broadcast. +- Maintain target locks keyed by network + node + poll. +- Restore unresolved operations and locks on startup. +- Expose read-only snapshots to every UI surface. +- Release a lock only on Confirmed, Rejected, FailedBeforeSubmission, + NotApplied, or explicit cancellation of a not-yet-submitting schedule. +- Keep Unconfirmed targets locked. + +Use per-object KV records and a network-scoped index, following current DET KV +patterns. + +## Backend tasks + +Replace tuple-heavy vote tasks/results with structured variants: + +```rust +ContestedResourceTask::SubmitDpnsVoteOperation(DpnsVoteOperation) +ContestedResourceTask::ReconcileDpnsVoteOperation(DpnsVoteOperationId) +ContestedResourceTask::DispatchDueDpnsVotes + +BackendTaskContext::DpnsVoteOperation(DpnsVoteOperationId) +BackendTaskSuccessResult::DpnsVoteOperationUpdated(DpnsVoteOperationId) +``` + +The backend persists each target update in the shared coordinator. Task results +carry only the operation ID needed for AppState to request repaint and show a +summary. AppState never delivers raw vote outcomes to whichever screen happens +to be visible. + +## Execution algorithm + +1. Validate the draft against current proved state. +2. Remove exact no-ops. +3. Persist the operation and acquire target locks atomically. +4. Group immediate targets by voter/node. +5. Run different voter groups with a small semaphore. +6. Within each voter group, execute targets sequentially: + - read the current nonce; + - construct and validate the transition; + - persist transition hash when the SDK exposes it; + - broadcast; + - wait for result; + - classify the typed outcome. +7. On cause-less post-broadcast wait failure, mark Unconfirmed and enqueue + reconciliation. Do not rebroadcast. +8. Refresh authoritative vote state after each terminal outcome. + +This replaces the current `join_all` by contest, which can race the same voter +nonce. + +## Reconciliation + +Preferred path: + +1. Resume `waitForStateTransitionResult` by persisted transition hash after + [dashpay/platform#4137](https://github.com/dashpay/platform/issues/4137) + exposes a phase-specific retryable wait error. +2. Independently fetch the proved vote using `VoteQuery` or the per-node votes + query. +3. Confirm when the proved choice matches the request. +4. Keep the target Unconfirmed while neither path is definitive. +5. Permit resubmission only after the Platform contract defines a definitive + negative result. Do not infer safety from a transient query failure. + +The existing generic `PlatformResultUnconfirmed` classification remains useful, +but vote operations convert it into target-level coordinator state instead of a +screen-local banner. + +## Scheduling + +Migrate `ScheduledDPNSVote` into the shared target model: + +- scheduled targets are persisted operations with `VoteTiming::Scheduled`; +- edit and cancel mutate the scheduled target atomically while it still holds + its target lock; +- the due dispatcher moves them to Queued and uses the same executor; +- executed state means Confirmed, not merely outer task success; +- rejected, failed, and unconfirmed outcomes remain inspectable; +- the migration is idempotent and preserves legacy records. + +Do not run immediate casting and schedule persistence as unrelated concurrent +backend tasks. One operation owns both kinds of targets. + +## UI state and components + +### Non-rendering state + +Add `src/ui/state/dpns_vote_workspace.rs` for: + +- draft contest choices; +- selected nodes and timing; +- current composer step; +- validation and no-op explanations; +- conversion to a typed operation request. + +### Shared rendering + +Add `src/ui/components/dpns_vote_composer.rs` implementing the three steps from +the UX specification. + +The compact node-detail controls use the same draft/view-model logic and open +the shared review step. They do not implement a separate submit path. + +### Masternodes views + +Extend the Masternodes root state with: + +- Nodes +- Voting +- Scheduled +- Operation detail + +The root observes coordinator snapshots, so progress survives sub-view changes. + +### DPNS integration + +Replace the legacy bulk popup with `Vote with masternodes`, routing selected +contests into the shared Voting workspace. Keep Active, Past, and My Usernames +contest/name browsing in DPNS. + +## Message handling + +Create one vote-specific formatter over typed target outcomes. It produces: + +- banner summary; +- per-target plain-language status; +- technical details attachment; +- recovery action (`Check again`, `Review again`, or none). + +Never parse error strings. Unconfirmed outcomes never offer an immediate retry. + +## Implementation sequence + +### PR A β€” Authoritative state and typed models + +- Add domain types and vote-state store. +- Query proved votes per node. +- Fix active-contest view models to show current vote and allow changes. +- Update user stories: current vote visibility and vote changes. +- Covers VOTE-TC-001 through VOTE-TC-008. + +### PR B β€” Coordinator and safe executor + +- Add operation journal, locks, structured task context/results. +- Serialize targets per node; bound concurrency across nodes. +- Add post-broadcast unconfirmed classification and reconciliation seam. +- Fix scheduled false-success behavior at the executor boundary. +- Covers VOTE-TC-030 through VOTE-TC-056. + +### PR C β€” Shared Voting Center + +- Add shared composer and Masternodes Voting view. +- Integrate quick node flow. +- Add operation detail/progress. +- Route DPNS Active Contests into the shared workspace. +- Covers VOTE-TC-010 through VOTE-TC-025 and VOTE-TC-070 through VOTE-TC-076. + +### PR D β€” Scheduled consolidation and migration + +- Migrate existing schedules into operation targets. +- Replace legacy scheduled execution/status UI. +- Remove obsolete popup/state code after migration coverage passes. +- Covers VOTE-TC-060 through VOTE-TC-065. + +Each PR is independently testable and must not expose two active submit +implementations for the same stage. + +## Verification + +- Unit tests for draft expansion, no-op removal, status transitions, locks, and + storage migration. +- Backend tests with fake SDK seams for nonce ordering and all result classes. +- Kittest coverage for quick, bulk, navigation, disabled-state, and result UX. +- Backend E2E on Testnet for one-node multi-contest and two-node same-contest + batches. +- Restart test with a persisted Unconfirmed operation. +- Formatter and clippy per repository policy. + +## Documentation updates + +- Revise DPN-005, DPN-006, DPN-007, and MN-003 acceptance criteria. +- Correct the protocol note to five votes total: initial vote plus four changes. +- Add a user story for operation recovery across navigation/restart. +- Replace the previous Masternodes design decision that made scheduled voting + undiscoverable from the operator page. From 36cd3e2b72b101159efc423a3b43c9eaf96fcaf2 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 16 Jul 2026 10:06:57 +0000 Subject: [PATCH 002/194] feat(dpns): unify voting operations and UX MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Load proved current votes, coordinate durable target-level operations, serialize same-node submissions, reconcile ambiguous results without rebroadcasting, and route quick, bulk, and scheduled voting through one reviewed Voting Center. Co-Authored-By: Codex GPT-5 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- .../04-development-plan.md | 26 +- docs/user-stories.md | 26 +- src/app.rs | 114 ++- src/backend_task/contested_names/mod.rs | 505 ++++++++++--- .../query_dpns_contested_resources.rs | 5 + .../contested_names/vote_on_dpns_name.rs | 91 ++- src/backend_task/error.rs | 21 + src/backend_task/mod.rs | 14 +- src/context/contested_names_db.rs | 17 +- src/context/dpns_vote_operations.rs | 326 ++++++++ src/context/dpns_vote_state.rs | 263 +++++++ src/context/mod.rs | 24 + src/model/contested_name.rs | 16 +- src/model/dpns_voting.rs | 290 ++++++++ src/model/mod.rs | 1 + src/ui/dpns/dpns_contested_names_screen.rs | 301 ++++---- src/ui/masternodes/card.rs | 27 +- src/ui/masternodes/detail_screen.rs | 202 +++-- src/ui/masternodes/list_screen.rs | 247 +++++- src/ui/masternodes/mod.rs | 1 + src/ui/masternodes/voting_center.rs | 704 ++++++++++++++++++ src/ui/state/dpns_vote_workspace.rs | 158 ++++ src/ui/state/mod.rs | 1 + tests/kittest/masternode_tab.rs | 30 + 24 files changed, 3037 insertions(+), 373 deletions(-) create mode 100644 src/context/dpns_vote_operations.rs create mode 100644 src/context/dpns_vote_state.rs create mode 100644 src/model/dpns_voting.rs create mode 100644 src/ui/masternodes/voting_center.rs create mode 100644 src/ui/state/dpns_vote_workspace.rs 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 index cac053d1f..c5ee60834 100644 --- 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 @@ -172,6 +172,13 @@ The existing generic `PlatformResultUnconfirmed` classification remains useful, but vote operations convert it into target-level coordinator state instead of a screen-local banner. +At the SDK revision used by DET, exact `Vote::fetch(VoteQuery)` is affected by +[dashpay/platform#4138](https://github.com/dashpay/platform/issues/4138). +Reconciliation therefore uses the proved per-identity range query starting at +the exact poll ID and accepts only an exact-key match. Retaining a signed +transition for wait-only recovery remains dependent on +[dashpay/platform#4137](https://github.com/dashpay/platform/issues/4137). + ## Scheduling Migrate `ScheduledDPNSVote` into the shared target model: @@ -235,9 +242,14 @@ Create one vote-specific formatter over typed target outcomes. It produces: Never parse error strings. Unconfirmed outcomes never offer an immediate retry. -## Implementation sequence +## One-PR implementation workstreams + +This experience ships as one pull request. The workstreams below are logical +commit and review boundaries inside that PR, not independently managed PRs. +They land together so no release can expose two submit paths or a coordinator +without every voting entry point using it. -### PR A β€” Authoritative state and typed models +### Workstream A β€” Authoritative state and typed models - Add domain types and vote-state store. - Query proved votes per node. @@ -245,7 +257,7 @@ Never parse error strings. Unconfirmed outcomes never offer an immediate retry. - Update user stories: current vote visibility and vote changes. - Covers VOTE-TC-001 through VOTE-TC-008. -### PR B β€” Coordinator and safe executor +### Workstream B β€” Coordinator and safe executor - Add operation journal, locks, structured task context/results. - Serialize targets per node; bound concurrency across nodes. @@ -253,7 +265,7 @@ Never parse error strings. Unconfirmed outcomes never offer an immediate retry. - Fix scheduled false-success behavior at the executor boundary. - Covers VOTE-TC-030 through VOTE-TC-056. -### PR C β€” Shared Voting Center +### Workstream C β€” Shared Voting Center - Add shared composer and Masternodes Voting view. - Integrate quick node flow. @@ -261,15 +273,15 @@ Never parse error strings. Unconfirmed outcomes never offer an immediate retry. - Route DPNS Active Contests into the shared workspace. - Covers VOTE-TC-010 through VOTE-TC-025 and VOTE-TC-070 through VOTE-TC-076. -### PR D β€” Scheduled consolidation and migration +### Workstream D β€” Scheduled consolidation and migration - Migrate existing schedules into operation targets. - Replace legacy scheduled execution/status UI. - Remove obsolete popup/state code after migration coverage passes. - Covers VOTE-TC-060 through VOTE-TC-065. -Each PR is independently testable and must not expose two active submit -implementations for the same stage. +Each workstream remains independently testable, but the branch is published and +reviewed as one atomic UX change. ## Verification diff --git a/docs/user-stories.md b/docs/user-stories.md index c2fccf397..13fea7609 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -682,9 +682,11 @@ As a power user, I want to review past DPNS contests so that I can see outcomes As a masternode operator, I want to vote on contested DPNS name registrations so that I can participate in network governance. -- Cast, change, or abstain votes (max 4 vote changes per contest). +- See the node's proved current choice before casting, changing, or abstaining. +- A node may vote five times in total per contest: the initial vote plus up to four changes. +- Choosing the current choice submits nothing. - Evonode/masternode identity required. -- Note: The max 4 vote changes constraint is enforced at the Platform protocol level, not validated in the app UI. +- The vote limit is enforced by Platform; DET does not invent a remaining-change count. ### DPN-006: Schedule votes [Implemented] **Persona:** Priya @@ -693,6 +695,8 @@ As a masternode operator, I want to schedule votes for later execution so that I - Set vote to be cast at a future time. - View and manage scheduled votes. +- Scheduled and immediate votes share the same target locks and result states. +- An ambiguous result remains visible for checking and is never automatically rebroadcast. ### DPN-007: Batch voting across contests [Implemented] **Persona:** Priya @@ -700,6 +704,20 @@ As a masternode operator, I want to schedule votes for later execution so that I 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. - "Set all" option for batch vote assignment. +- Per-node timing overrides and multi-contest selections create exact node Γ— contest targets. +- Immediate and scheduled targets submitted together belong to one operation. + +### DPN-010: 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 credits 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. +- DET reconciles against proved current vote state without rebroadcasting. +- A confirmed match updates the current vote and releases the target lock. ### DPN-008: Set an alias for an owned username [Implemented] **Persona:** Alex, Priya @@ -1492,7 +1510,9 @@ As a masternode operator, I want a card list of my loaded masternodes showing ty 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. - 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. +- Every active contest remains visible with the node's proved current vote, including contests where the node already voted. +- Votes (Abstain, Lock, or a candidate) use the shared durable voting operation path. +- The affected controls disable immediately and show progress until the target is confirmed, rejected, or remains under explicit checking. - A node with no voter identity is told a voting key is required, with a way to add one, instead of a raw error. ### MN-004: Remove a masternode [Implemented] diff --git a/src/app.rs b/src/app.rs index b76cf44ce..8b0d13081 100644 --- a/src/app.rs +++ b/src/app.rs @@ -16,6 +16,7 @@ use crate::context::connection_status::{ConnectionStatus, OverallConnectionState use crate::context::feature_gate::FeatureGate; use crate::context::migration_status::{MigrationState, MigrationStep}; use crate::database::Database; +use crate::model::dpns_voting::DpnsVoteTargetStatus; use crate::model::settings::AppSettings; use crate::ui::components::passphrase_modal; use crate::ui::components::secret_prompt_host::{ActivePrompt, EguiSecretPromptHost, QueuedPrompt}; @@ -2033,19 +2034,106 @@ 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(operation_id) => { + match active_context.dpns_vote_operation(operation_id) { + Ok(Some(operation)) => { + let total = operation.targets.len(); + let confirmed = operation + .targets + .iter() + .filter(|outcome| { + outcome.status == DpnsVoteTargetStatus::Confirmed + }) + .count(); + let scheduled = operation + .targets + .iter() + .filter(|outcome| { + outcome.status == DpnsVoteTargetStatus::Scheduled + }) + .count(); + let unconfirmed = operation + .targets + .iter() + .filter(|outcome| { + outcome.status == DpnsVoteTargetStatus::Unconfirmed + }) + .count(); + let rejected = operation + .targets + .iter() + .filter(|outcome| { + matches!( + outcome.status, + DpnsVoteTargetStatus::Rejected + | DpnsVoteTargetStatus::FailedBeforeSubmission + ) + }) + .count(); + if unconfirmed > 0 { + MessageBanner::set_global( + ctx, + "The vote was submitted, but DET could not confirm the result yet. DET will keep checking. Do not submit it again.", + MessageType::Warning, + ) + .disable_auto_dismiss(); + } else if rejected > 0 { + MessageBanner::set_global( + ctx, + format!( + "{confirmed} of {total} votes were confirmed. Review the remaining {}.", + total.saturating_sub(confirmed) + ), + MessageType::Warning, + ) + .disable_auto_dismiss(); + } else if scheduled == total && total > 0 { + MessageBanner::set_global( + ctx, + format!("{scheduled} votes were scheduled."), + MessageType::Success, + ); + } else if confirmed + scheduled == total + && confirmed > 0 + && scheduled > 0 + { + MessageBanner::set_global( + ctx, + format!( + "{confirmed} votes were cast and {scheduled} votes were scheduled." + ), + MessageType::Success, + ); + } else if confirmed == total && total == 1 { + MessageBanner::set_global( + ctx, + "Vote cast successfully.", + MessageType::Success, + ); + } else if confirmed == total && total > 1 { + MessageBanner::set_global( + ctx, + format!("{confirmed} votes were cast successfully."), + MessageType::Success, + ); + } + } + Ok(None) => { + MessageBanner::set_global( + ctx, + "This node already has that vote. Nothing was submitted.", + MessageType::Info, + ); + } + Err(error) => tracing::warn!( + ?error, + operation_id = %operation_id, + "Could not load DPNS vote operation feedback" + ), + } + self.visible_screen_mut().display_backend_task_result( + &context, + BackendTaskSuccessResult::DpnsVoteOperationUpdated(operation_id), ); self.visible_screen_mut().refresh(); } diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 51d1ca3db..87bb17b7c 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -7,14 +7,22 @@ use crate::app::TaskResult; use crate::backend_task::BackendTaskSuccessResult; use crate::backend_task::error::TaskError; use crate::context::AppContext; +use crate::model::dpns_voting::{ + DpnsCurrentVoteState, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, + DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, +}; use crate::model::qualified_identity::QualifiedIdentity; use crate::model::request_type::RequestType; use dash_sdk::Sdk; 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; use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; @@ -26,8 +34,8 @@ const SCHEDULED_VOTE_MAX_LATENESS_MS: u64 = 120_000; #[derive(Debug, Clone, PartialEq)] pub enum ContestedResourceTask { QueryDPNSContests, - VoteOnDPNSNames(Vec<(String, ResourceVoteChoice)>, Vec), - ScheduleDPNSVotes(Vec), + SubmitDpnsVoteOperation(DpnsVoteOperation, Vec), + ReconcileDpnsVoteOperation(DpnsVoteOperationId), CastScheduledVote(ScheduledDPNSVote, Box), /// Sweep the scheduled-vote table and cast every vote that is now due. /// `preserve_eligibility_since_ms` keeps a vote eligible when its normal @@ -49,6 +57,28 @@ pub struct ScheduledDPNSVote { pub executed_successfully: bool, } +fn classify_vote_attempt( + attempt: &Result, +) -> (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), + ), + Err(_) => ( + DpnsVoteTargetStatus::FailedBeforeSubmission, + Some(DpnsVoteFailure::SubmissionFailed), + ), + } +} + /// 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 @@ -87,65 +117,17 @@ impl AppContext { .query_dpns_contested_resources(sdk, sender) .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::SubmitDpnsVoteOperation(operation, voters) => { + self.execute_dpns_vote_operation(operation, voters, 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], - sdk, - sender, - ) - .await?; - confirm_scheduled_vote_result(result)?; - Ok(BackendTaskSuccessResult::CastScheduledVote(scheduled_vote)) + let operation = self.operation_for_scheduled_vote(&scheduled_vote, &voter)?; + self.execute_dpns_vote_operation(operation, vec![*voter], sdk) + .await } ContestedResourceTask::CastDueScheduledVotes { preserve_eligibility_since_ms, @@ -158,6 +140,7 @@ impl AppContext { }), ContestedResourceTask::ClearAllScheduledVotes => { self.clear_all_scheduled_votes()?; + self.cancel_all_scheduled_dpns_vote_targets()?; Ok(BackendTaskSuccessResult::Refresh) } ContestedResourceTask::ClearExecutedScheduledVotes => { @@ -166,29 +149,319 @@ impl AppContext { } ContestedResourceTask::DeleteScheduledVote(voter_id, contested_name) => { self.delete_scheduled_vote(voter_id.as_slice(), &contested_name)?; + self.cancel_scheduled_dpns_vote_target(voter_id, &contested_name)?; Ok(BackendTaskSuccessResult::Refresh) } } } + 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 { + if let Some(mut operation) = self.dpns_vote_operations()?.into_iter().find(|operation| { + operation.targets.iter().any(|outcome| { + outcome.target.key.voter_id == scheduled_vote.voter_id + && outcome.target.contested_name == scheduled_vote.contested_name + && outcome.status == DpnsVoteTargetStatus::Scheduled + }) + }) { + for outcome in &mut operation.targets { + if outcome.target.key.voter_id == scheduled_vote.voter_id + && outcome.target.contested_name == scheduled_vote.contested_name + && outcome.status == DpnsVoteTargetStatus::Scheduled + { + outcome.status = DpnsVoteTargetStatus::Queued; + } + } + return Ok(operation); + } + + let target = self.dpns_vote_target( + voter, + &scheduled_vote.contested_name, + scheduled_vote.choice, + VoteTiming::Scheduled(scheduled_vote.unix_timestamp), + false, + )?; + let mut operation = DpnsVoteOperation::new(vec![target]); + operation.targets[0].status = DpnsVoteTargetStatus::Queued; + Ok(operation) + } + + async fn execute_dpns_vote_operation( + self: &Arc, + operation: DpnsVoteOperation, + voters: Vec, + sdk: &Sdk, + ) -> Result { + if operation.targets.is_empty() { + return Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated( + operation.id, + )); + } + if self.dpns_vote_operation(operation.id)?.is_some() { + self.update_dpns_vote_operation(&operation)?; + } else { + let scheduled_votes = operation + .targets + .iter() + .filter_map(|outcome| match outcome.target.timing { + VoteTiming::Scheduled(unix_timestamp) => Some(ScheduledDPNSVote { + contested_name: outcome.target.contested_name.clone(), + voter_id: outcome.target.key.voter_id, + choice: outcome.target.requested_choice, + unix_timestamp, + executed_successfully: false, + }), + VoteTiming::Now => None, + }) + .collect::>(); + if !scheduled_votes.is_empty() { + self.insert_scheduled_votes(&scheduled_votes)?; + } + self.insert_dpns_vote_operation(&operation)?; + } + + let voters_by_id: BTreeMap = voters + .into_iter() + .map(|voter| (voter.identity.id(), voter)) + .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()); + } + + const MAX_CONCURRENT_VOTERS: usize = 4; + 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; + async move { + let Some(voter) = voter else { + for target in targets { + app_context.update_dpns_vote_target( + operation_id, + &target.key, + DpnsVoteTargetStatus::FailedBeforeSubmission, + Some(DpnsVoteFailure::SubmissionFailed), + )?; + } + return Ok::<(), TaskError>(()); + }; + + // One voter's targets are deliberately sequential: PutVote + // obtains and consumes the same masternode nonce. + for target in targets { + app_context.update_dpns_vote_target( + operation_id, + &target.key, + DpnsVoteTargetStatus::Submitting, + None, + )?; + let attempt = app_context + .submit_dpns_vote( + &target.contested_name, + target.requested_choice, + &voter, + &sdk, + ) + .await; + let (status, failure) = classify_vote_attempt(&attempt); + match attempt { + Ok(vote_on_dpns_name::DpnsVoteAttempt::Confirmed) => { + app_context.cache_confirmed_dpns_vote( + target.key.voter_id, + target.key.vote_poll_id, + target.requested_choice, + )?; + if matches!(target.timing, VoteTiming::Scheduled(_)) { + app_context.mark_vote_executed( + target.key.voter_id.as_slice(), + target.contested_name.clone(), + )?; + } + } + 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" + ); + } + 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" + ); + } + Err(error) => { + tracing::warn!( + ?error, + voter_id = %target.key.voter_id, + contested_name = %target.contested_name, + "DPNS vote failed before a confirmed submission" + ); + } + } + app_context.update_dpns_vote_target( + operation_id, + &target.key, + status, + failure, + )?; + } + Ok(()) + } + }) + .buffer_unordered(MAX_CONCURRENT_VOTERS) + .collect::>>() + .await + .into_iter() + .collect::, _>>()?; + + Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated( + operation.id, + )) + } + + async fn reconcile_dpns_vote_operation( + &self, + operation_id: DpnsVoteOperationId, + sdk: &Sdk, + ) -> Result { + let Some(operation) = self.dpns_vote_operation(operation_id)? else { + return Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated( + operation_id, + )); + }; + for outcome in operation + .targets + .iter() + .filter(|outcome| outcome.status == DpnsVoteTargetStatus::Unconfirmed) + { + 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) + if votes + .get(&poll_id) + .and_then(Option::as_ref) + .is_some_and(|vote| { + vote.resource_vote_choice() == outcome.target.requested_choice + }) => + { + self.cache_confirmed_dpns_vote( + outcome.target.key.voter_id, + poll_id, + outcome.target.requested_choice, + )?; + self.update_dpns_vote_target( + operation_id, + &outcome.target.key, + DpnsVoteTargetStatus::Confirmed, + None, + )?; + } + Ok(_) => {} + Err(error) => tracing::warn!( + ?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" + ), + } + } + Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated( + operation_id, + )) + } + /// 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`. + /// rest. Emits [`ScheduledVotesInProgress`] before casting; terminal state + /// is persisted in the shared operation journal and legacy executed flag. /// /// [`ScheduledVotesInProgress`]: BackendTaskSuccessResult::ScheduledVotesInProgress - /// [`CastScheduledVote`]: BackendTaskSuccessResult::CastScheduledVote async fn cast_due_scheduled_votes( self: &Arc, sdk: &Sdk, sender: crate::utils::egui_mpsc::SenderAsync, preserve_eligibility_since_ms: Option, ) -> Result { + for operation in self + .dpns_vote_operations()? + .into_iter() + .filter(|operation| { + operation + .targets + .iter() + .any(|outcome| outcome.status == DpnsVoteTargetStatus::Unconfirmed) + }) + { + let result = self + .reconcile_dpns_vote_operation(operation.id, sdk) + .await?; + let _ = sender.send(TaskResult::unattributed_success(result)).await; + } + let now_ms = SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_millis() as u64) @@ -241,34 +514,41 @@ impl AppContext { )) .await; + let mut groups: BTreeMap> = + BTreeMap::new(); 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), - )) - .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); + groups.entry(vote.voter_id).or_default().push((vote, voter)); + } + let results = stream::iter(groups) + .map(|(_, scheduled)| { + let app_context = Arc::clone(self); + let sdk = sdk.clone(); + async move { + let mut results = Vec::with_capacity(scheduled.len()); + for (vote, voter) in scheduled { + let result = match app_context.operation_for_scheduled_vote(&vote, &voter) { + Ok(operation) => app_context + .execute_dpns_vote_operation(operation, vec![voter], &sdk) + .await + .map(|_| ()), + Err(error) => Err(error), + }; + results.push((vote, result)); + } + results } + }) + .buffer_unordered(4) + .collect::>() + .await; + for (vote, result) in results.into_iter().flatten() { + if let Err(error) = result { + tracing::error!( + error = %error, + contested_name = %vote.contested_name, + "Failed to cast a due scheduled vote; leaving it for the next sweep" + ); + first_error.get_or_insert(error); } } if let Some(error) = first_error { @@ -282,19 +562,6 @@ impl AppContext { } } -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); - } - for (_, _, result) in results { - result.map_err(|source| TaskError::ScheduledVoteRejected { source })?; - } - Ok(()) -} - fn scheduled_vote_is_due( scheduled_at_ms: u64, executed_successfully: bool, @@ -311,26 +578,30 @@ fn scheduled_vote_is_due( mod tests { use super::*; + /// VOTE-TC-033: an inner scheduled rejection is never classified as success. #[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)), - )]); - - assert!(matches!( - confirm_scheduled_vote_result(result), - Err(TaskError::ScheduledVoteRejected { .. }) + fn scheduled_inner_rejection_needs_attention() { + let attempt = Ok(vote_on_dpns_name::DpnsVoteAttempt::Rejected( + TaskError::DpnsVoteTargetBusy, )); + assert_eq!( + classify_vote_attempt(&attempt), + ( + DpnsVoteTargetStatus::Rejected, + Some(DpnsVoteFailure::PlatformRejected) + ) + ); } + /// VOTE-TC-034/052: an ambiguous post-broadcast result stays locked. #[test] - fn an_empty_nested_result_is_not_a_successful_scheduled_vote() { - assert!(matches!( - confirm_scheduled_vote_result(BackendTaskSuccessResult::DPNSVoteResults(Vec::new())), - Err(TaskError::ScheduledVoteResultUnavailable) + 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); + assert_eq!(status, DpnsVoteTargetStatus::Unconfirmed); + assert!(status.holds_lock()); } /// Migration extends only eligibility windows that overlap its wait. 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 68bcdb49a..6594867c5 100644 --- a/src/backend_task/contested_names/query_dpns_contested_resources.rs +++ b/src/backend_task/contested_names/query_dpns_contested_resources.rs @@ -212,6 +212,11 @@ impl AppContext { } } + // 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". + self.refresh_dpns_vote_states(sdk).await; + sender .send(TaskResult::unattributed_success( BackendTaskSuccessResult::RefreshedDpnsContests, 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..0ecaa3b80 100644 --- a/src/backend_task/contested_names/vote_on_dpns_name.rs +++ b/src/backend_task/contested_names/vote_on_dpns_name.rs @@ -1,5 +1,3 @@ -use crate::app::TaskResult; -use crate::backend_task::BackendTaskSuccessResult; use crate::backend_task::error::TaskError; use crate::context::AppContext; use crate::model::qualified_identity::QualifiedIdentity; @@ -21,6 +19,13 @@ use dash_sdk::platform::transition::vote::PutVote; use dash_sdk::query_types::ContestedResource; use std::sync::Arc; +#[derive(Debug)] +pub(super) enum DpnsVoteAttempt { + Confirmed, + Unconfirmed(TaskError), + Rejected(TaskError), +} + /// 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` @@ -33,19 +38,13 @@ fn dpns_vote_poll_index_values(normalized_label: &str) -> Vec { } impl AppContext { - pub(super) async fn vote_on_dpns_name( + pub(super) async fn submit_dpns_vote( self: &Arc, name: &str, vote_choice: ResourceVoteChoice, - voters: &[QualifiedIdentity], + qualified_identity: &QualifiedIdentity, sdk: &Sdk, - sender: crate::utils::egui_mpsc::SenderAsync, - ) -> Result { - sender - .send(TaskResult::Refresh) - .await - .map_err(|_| TaskError::InternalSendError)?; - + ) -> Result { let data_contract = self.dpns_contract.as_ref(); let document_type = data_contract .document_type_for_name("domain") @@ -95,37 +94,49 @@ impl AppContext { }); } - 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), - }); + 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)); + + match vote + .put_to_platform_and_wait_for_response( + qualified_identity.identity.id(), + public_key, + sdk, + qualified_identity, + None, + ) + .await + { + Ok(_) => Ok(DpnsVoteAttempt::Confirmed), + Err(error) => { + let unconfirmed = matches!( + &error, + dash_sdk::Error::StateTransitionBroadcastError(broadcast_error) + if broadcast_error.cause.is_none() + ); + let rejected = matches!( + &error, + dash_sdk::Error::StateTransitionBroadcastError(broadcast_error) + if broadcast_error.cause.is_some() + ); + let error = TaskError::from(error); + if unconfirmed { + Ok(DpnsVoteAttempt::Unconfirmed(error)) + } else if rejected { + Ok(DpnsVoteAttempt::Rejected(error)) + } else { + Err(error) + } } } - - Ok(BackendTaskSuccessResult::DPNSVoteResults(vote_results)) } } diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index a11e92e26..237e503ff 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -651,6 +651,27 @@ pub enum TaskError { source: crate::wallet_backend::KvAdapterError, }, + /// A DPNS vote operation or current-vote snapshot could not be persisted. + #[error( + "Could not save DPNS voting progress. Check available disk space and try again." + )] + DpnsVoteOperationStorage { + #[source] + source: crate::wallet_backend::KvAdapterError, + }, + + /// 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, + + /// 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 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.")] diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index e2565b284..1d0afc457 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -13,6 +13,7 @@ use crate::context::AppContext; use crate::context::feature_gate::FeatureGate; use crate::context::identity_load_registry::IdentityLoadToken; use crate::model::masternode_input::decode_identity_id; +use crate::model::dpns_voting::DpnsVoteOperationId; use dash_sdk::dpp::address_funds::PlatformAddress; use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::key_wallet::bip32::DerivationPath; @@ -31,7 +32,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}; @@ -257,6 +257,8 @@ pub enum BackendTaskContext { TokenRewardEstimate(IdentityTokenIdentifier), /// The destructive per-network database clear. ClearNetworkDatabase, + /// One durable DPNS vote operation. + DpnsVoteOperation(DpnsVoteOperationId), /// A known backend task that needs no finer UI correlation. Other, /// An error emitted without an originating backend task. @@ -326,6 +328,13 @@ impl From<&BackendTask> for BackendTaskContext { _ => Self::Other, }, BackendTask::SystemTask(SystemTask::ClearNetworkDatabase) => Self::ClearNetworkDatabase, + BackendTask::ContestedResourceTask(ContestedResourceTask::SubmitDpnsVoteOperation( + operation, + _, + )) => Self::DpnsVoteOperation(operation.id), + BackendTask::ContestedResourceTask( + ContestedResourceTask::ReconcileDpnsVoteOperation(operation_id), + ) => Self::DpnsVoteOperation(*operation_id), _ => Self::Other, } } @@ -368,8 +377,6 @@ pub enum BackendTaskSuccessResult { CoreItem(CoreItem), RegisteredIdentity(QualifiedIdentity, FeeResult), ToppedUpIdentity(QualifiedIdentity, FeeResult), - DPNSVoteResults(Vec<(String, ResourceVoteChoice, Result<(), Arc>)>), - 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. @@ -377,6 +384,7 @@ pub enum BackendTaskSuccessResult { network: Network, preserve_eligibility_since_ms: Option, }, + DpnsVoteOperationUpdated(DpnsVoteOperationId), /// 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), diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 44630a9d9..199fe03bd 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -208,11 +208,23 @@ impl AppContext { return Ok(crate::model::contested_name::MasternodeContestSummary::default()); }; - let open_contest_count = self - .ongoing_contested_names()? + let contests = self.ongoing_contested_names()?; + let open_contest_count = contests .iter() .filter(|contest| contest.is_open_for_voter(&voter_id)) .count(); + let needs_vote_count = contests + .iter() + .filter(|contest| contest.is_open_for_voter(&voter_id)) + .filter(|contest| { + self.dpns_vote_poll_id(&contest.normalized_contested_name) + .ok() + .and_then(|poll_id| self.dpns_current_vote_state(voter_id, poll_id).ok()) + == Some(crate::model::dpns_voting::DpnsCurrentVoteState::Available( + None, + )) + }) + .count(); let has_scheduled_vote = self .get_scheduled_votes()? @@ -221,6 +233,7 @@ impl AppContext { Ok(crate::model::contested_name::MasternodeContestSummary { open_contest_count, + needs_vote_count, has_scheduled_vote, }) } diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs new file mode 100644 index 000000000..79494ac45 --- /dev/null +++ b/src/context/dpns_vote_operations.rs @@ -0,0 +1,326 @@ +//! Durable DPNS vote operation journal and exact-target lock registry. + +use super::AppContext; +use crate::backend_task::error::TaskError; +use crate::model::dpns_voting::{ + DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, + DpnsVoteTargetStatus, VoteTiming, +}; +use crate::wallet_backend::{DetKv, DetScope, KvAdapterError}; +use dash_sdk::platform::Identifier; + +const OPERATION_INDEX_KEY: &str = "det:dpns_vote_operations:v1"; +const OPERATION_KEY_PREFIX: &str = "det:dpns_vote_operation:v1:"; + +fn operation_key(id: DpnsVoteOperationId) -> String { + format!("{OPERATION_KEY_PREFIX}{id}") +} + +fn operation_err(source: KvAdapterError) -> TaskError { + TaskError::DpnsVoteOperationStorage { source } +} + +fn load_operation_ids(kv: &DetKv) -> Result, TaskError> { + kv.get(DetScope::Global, OPERATION_INDEX_KEY) + .map(|ids| ids.unwrap_or_default()) + .map_err(operation_err) +} + +fn load_operations(kv: &DetKv) -> Result, TaskError> { + let mut operations = Vec::new(); + for bytes in load_operation_ids(kv)? { + let id = DpnsVoteOperationId::from_bytes(bytes); + match kv.get(DetScope::Global, &operation_key(id)) { + Ok(Some(operation)) => operations.push(operation), + Ok(None) => {} + Err(error) => { + tracing::warn!( + operation_id = %id, + error = ?error, + "Skipping unreadable DPNS vote operation" + ); + } + } + } + Ok(operations) +} + +fn persist_operation(kv: &DetKv, operation: &DpnsVoteOperation) -> Result<(), TaskError> { + let conflict = load_operations(kv)?.iter().any(|existing| { + existing.id != operation.id + && existing.targets.iter().any(|existing_outcome| { + existing_outcome.status.holds_lock() + && operation.targets.iter().any(|outcome| { + outcome.status.holds_lock() + && outcome.target.key == existing_outcome.target.key + }) + }) + }); + if conflict { + return Err(TaskError::DpnsVoteTargetBusy); + } + + kv.put(DetScope::Global, &operation_key(operation.id), operation) + .map_err(operation_err)?; + let mut ids = load_operation_ids(kv)?; + if !ids.contains(&operation.id.to_bytes()) { + ids.push(operation.id.to_bytes()); + kv.put(DetScope::Global, OPERATION_INDEX_KEY, &ids) + .map_err(operation_err)?; + } + Ok(()) +} + +impl AppContext { + /// Persist a reviewed operation and atomically acquire all unresolved locks. + pub fn insert_dpns_vote_operation( + &self, + operation: &DpnsVoteOperation, + ) -> Result<(), TaskError> { + if operation + .targets + .iter() + .any(|outcome| outcome.target.key.network != self.network) + { + return Err(TaskError::DpnsVoteTargetBusy); + } + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let kv = self.det_kv()?; + let mut existing_operations = load_operations(&kv)?; + for existing in &mut existing_operations { + let mut changed = false; + for existing_outcome in &mut existing.targets { + if existing_outcome.status == DpnsVoteTargetStatus::Scheduled + && operation.targets.iter().any(|new_outcome| { + new_outcome.status == DpnsVoteTargetStatus::Scheduled + && new_outcome.target.key == existing_outcome.target.key + }) + { + existing_outcome.status = DpnsVoteTargetStatus::NotApplied; + changed = true; + } + } + if changed { + kv.put(DetScope::Global, &operation_key(existing.id), existing) + .map_err(operation_err)?; + } + } + persist_operation(&kv, operation) + } + + /// Persist updated target statuses while retaining the original operation ID. + pub fn update_dpns_vote_operation( + &self, + operation: &DpnsVoteOperation, + ) -> Result<(), TaskError> { + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + persist_operation(&self.det_kv()?, operation) + } + + /// Load every operation for this network, including completed history. + pub fn dpns_vote_operations(&self) -> Result, TaskError> { + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let kv = self.det_kv()?; + let mut operations = load_operations(&kv)?; + for legacy in self.get_scheduled_votes()? { + if operations.iter().any(|operation| { + operation.targets.iter().any(|outcome| { + outcome.target.key.voter_id == legacy.voter_id + && outcome.target.contested_name == legacy.contested_name + }) + }) { + continue; + } + let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: self.network, + voter_id: legacy.voter_id, + vote_poll_id: self.dpns_vote_poll_id(&legacy.contested_name)?, + }, + voter_alias: None, + contested_name: legacy.contested_name, + requested_choice: legacy.choice, + current_choice: None, + timing: VoteTiming::Scheduled(legacy.unix_timestamp), + }]); + if legacy.executed_successfully { + operation.targets[0].status = DpnsVoteTargetStatus::Confirmed; + } + persist_operation(&kv, &operation)?; + operations.push(operation); + } + Ok(operations) + } + + /// Load one operation by its stable ID. + pub fn dpns_vote_operation( + &self, + id: DpnsVoteOperationId, + ) -> Result, TaskError> { + self.det_kv()? + .get(DetScope::Global, &operation_key(id)) + .map_err(operation_err) + } + + /// 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. + pub(crate) fn update_dpns_vote_target( + &self, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, + status: DpnsVoteTargetStatus, + failure: Option, + ) -> Result<(), TaskError> { + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let kv = self.det_kv()?; + let Some(mut operation): Option = kv + .get(DetScope::Global, &operation_key(operation_id)) + .map_err(operation_err)? + else { + return Ok(()); + }; + if let Some(outcome) = operation + .targets + .iter_mut() + .find(|outcome| outcome.target.key == *key) + { + outcome.status = status; + outcome.failure = failure; + } + persist_operation(&kv, &operation) + } + + /// Release a not-yet-submitting scheduled target after explicit cancellation. + pub(crate) fn cancel_scheduled_dpns_vote_target( + &self, + voter_id: Identifier, + contested_name: &str, + ) -> Result<(), TaskError> { + let operations = self.dpns_vote_operations()?; + for mut operation in operations { + let mut changed = false; + for outcome in &mut operation.targets { + if outcome.target.key.voter_id == voter_id + && outcome.target.contested_name == contested_name + && outcome.status == DpnsVoteTargetStatus::Scheduled + { + outcome.status = DpnsVoteTargetStatus::NotApplied; + changed = true; + } + } + if changed { + self.update_dpns_vote_operation(&operation)?; + } + } + Ok(()) + } + + /// Release every not-yet-submitting scheduled target on this network. + pub(crate) fn cancel_all_scheduled_dpns_vote_targets(&self) -> Result<(), TaskError> { + let operations = self.dpns_vote_operations()?; + for mut operation in operations { + let mut changed = false; + for outcome in &mut operation.targets { + if outcome.status == DpnsVoteTargetStatus::Scheduled { + outcome.status = DpnsVoteTargetStatus::NotApplied; + changed = true; + } + } + if changed { + self.update_dpns_vote_operation(&operation)?; + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::dpns_voting::{DpnsVoteTarget, VoteTiming}; + use crate::wallet_backend::kv_test_support::InMemoryKv; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; + use dash_sdk::platform::Identifier; + use std::sync::Arc; + + fn kv() -> DetKv { + DetKv::from_store(Arc::new(InMemoryKv::default())) + } + + fn operation(status: DpnsVoteTargetStatus) -> DpnsVoteOperation { + let mut operation = DpnsVoteOperation::new(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 + } + + /// 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, &operation(DpnsVoteTargetStatus::Submitting)).unwrap(); + + let error = persist_operation(&kv, &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, &operation).unwrap(); + + let restored = load_operations(&kv).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, &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, &unrelated).unwrap(); + assert_eq!(load_operations(&kv).unwrap().len(), 2); + } +} diff --git a/src/context/dpns_vote_state.rs b/src/context/dpns_vote_state.rs new file mode 100644 index 000000000..4de03e981 --- /dev/null +++ b/src/context/dpns_vote_state.rs @@ -0,0 +1,263 @@ +//! Proved, per-node DPNS current-vote snapshots. + +use super::AppContext; +use crate::backend_task::error::TaskError; +use crate::model::dpns_voting::DpnsCurrentVoteState; +use crate::wallet_backend::{DetKv, DetScope, KvAdapterError}; +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::identity::accessors::IdentityGettersV0; +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::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 serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::time::{SystemTime, UNIX_EPOCH}; + +const CURRENT_VOTES_KEY: &str = "det:dpns_current_votes:v1"; +const VOTE_QUERY_PAGE_SIZE: u16 = 100; + +#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)] +struct StoredCurrentVotes { + available: bool, + updated_at: u64, + votes: BTreeMap<[u8; 32], ResourceVoteChoice>, +} + +fn vote_state_err(source: KvAdapterError) -> TaskError { + TaskError::DpnsVoteOperationStorage { source } +} + +fn load_snapshot( + kv: &DetKv, + voter_id: &Identifier, +) -> Result, TaskError> { + kv.get(DetScope::Identity(&voter_id.to_buffer()), CURRENT_VOTES_KEY) + .map_err(vote_state_err) +} + +fn save_snapshot( + kv: &DetKv, + voter_id: &Identifier, + snapshot: &StoredCurrentVotes, +) -> Result<(), TaskError> { + kv.put( + DetScope::Identity(&voter_id.to_buffer()), + CURRENT_VOTES_KEY, + snapshot, + ) + .map_err(vote_state_err) +} + +impl AppContext { + /// Build the exact Platform vote-poll ID for one normalized DPNS label. + pub fn dpns_vote_poll_id(&self, name: &str) -> Result { + let document_type = self + .dpns_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", + }); + }; + let normalized_name = convert_to_homograph_safe_chars(name); + ContestedDocumentResourceVotePoll { + index_name: contested_index.name.clone(), + index_values: vec![Value::from("dash"), Value::Text(normalized_name)], + document_type_name: document_type.name().to_owned(), + contract_id: self.dpns_contract.id(), + } + .unique_id() + .map_err(|source| TaskError::SdkError { + source_error: Box::new(dash_sdk::Error::Protocol(source)), + }) + } + + /// Read the latest proved state without performing network I/O in the frame loop. + pub fn dpns_current_vote_state( + &self, + voter_id: Identifier, + vote_poll_id: Identifier, + ) -> Result { + Ok(match load_snapshot(&self.det_kv()?, &voter_id)? { + None => DpnsCurrentVoteState::Checking, + Some(snapshot) if !snapshot.available => DpnsCurrentVoteState::Unavailable, + Some(snapshot) => DpnsCurrentVoteState::Available( + snapshot.votes.get(&vote_poll_id.to_buffer()).copied(), + ), + }) + } + + /// Refresh proved vote state once per loaded masternode, paging only as needed. + pub(crate) async fn refresh_dpns_vote_states(&self, sdk: &Sdk) { + let voters = match self.load_local_masternode_identities() { + Ok(voters) => voters, + Err(error) => { + tracing::warn!(?error, "Could not load nodes for DPNS vote-state refresh"); + return; + } + }; + let kv = match self.det_kv() { + Ok(kv) => kv, + Err(error) => { + tracing::warn!(?error, "Could not open DPNS vote-state storage"); + return; + } + }; + + stream::iter(voters) + .map(|voter| { + let sdk = sdk.clone(); + let kv = kv.clone(); + async move { + let voter_id = voter.identity.id(); + match fetch_votes_for_voter(&sdk, voter_id).await { + Ok(votes) => { + let snapshot = StoredCurrentVotes { + available: true, + updated_at: now_ms(), + votes, + }; + if let Err(error) = save_snapshot(&kv, &voter_id, &snapshot) { + tracing::warn!( + ?error, + voter_id = %voter_id, + "Could not save proved DPNS vote state" + ); + } + } + Err(error) => { + let snapshot = StoredCurrentVotes { + available: false, + updated_at: now_ms(), + votes: BTreeMap::new(), + }; + if let Err(storage_error) = save_snapshot(&kv, &voter_id, &snapshot) { + tracing::warn!( + ?storage_error, + voter_id = %voter_id, + "Could not save unavailable DPNS vote state" + ); + } + tracing::warn!( + ?error, + voter_id = %voter_id, + "Proved DPNS vote-state query was unavailable" + ); + } + } + } + }) + .buffer_unordered(4) + .collect::>() + .await; + } + + /// 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 kv = self.det_kv()?; + let mut snapshot = load_snapshot(&kv, &voter_id)?.unwrap_or_default(); + snapshot.available = true; + snapshot.updated_at = now_ms(); + snapshot.votes.insert(vote_poll_id.to_buffer(), choice); + save_snapshot(&kv, &voter_id, &snapshot) + } +} + +async fn fetch_votes_for_voter( + sdk: &Sdk, + voter_id: Identifier, +) -> Result, dash_sdk::Error> { + 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) +} + +fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as u64 +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::wallet_backend::kv_test_support::InMemoryKv; + use std::sync::Arc; + + fn kv() -> DetKv { + DetKv::from_store(Arc::new(InMemoryKv::default())) + } + + /// 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)]), + }; + save_snapshot(&kv, &voter, &snapshot).unwrap(); + + assert_eq!(load_snapshot(&kv, &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); + } +} diff --git a/src/context/mod.rs b/src/context/mod.rs index 70e215fd4..ab896bf3a 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -1,6 +1,8 @@ pub mod connection_status; mod contested_names_db; mod contract_token_db; +mod dpns_vote_operations; +mod dpns_vote_state; pub mod feature_gate; mod identity_db; pub(crate) mod identity_load_registry; @@ -157,6 +159,8 @@ 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<()>, /// 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>, @@ -171,6 +175,8 @@ pub struct AppContext { /// the hub adopts it on return (forward-courier, mirrors /// `pending_wallet_selection`). pub(crate) pending_identity_selection: Mutex>, + /// One-shot DPNS deep link consumed by the Masternodes Voting Center. + pending_dpns_voting_contests: Mutex>>, /// Cached fee multiplier permille from current epoch (1000 = 1x, 2000 = 2x) /// Updated when epoch info is fetched from Platform fee_multiplier_permille: AtomicU64, @@ -434,11 +440,13 @@ impl AppContext { migration_status: Arc::new(MigrationStatus::new_idle()), migration_run: tokio::sync::Mutex::new(()), contact_request_actions_in_flight: Mutex::new(HashSet::new()), + dpns_vote_operation_guard: Mutex::new(()), pending_wallet_selection: Mutex::new(None), selected_wallet_hash: Mutex::new(selected_wallet_hash), selected_single_key_hash: Mutex::new(selected_single_key_hash), selected_identity_id: Mutex::new(None), pending_identity_selection: Mutex::new(None), + pending_dpns_voting_contests: Mutex::new(None), fee_multiplier_permille: AtomicU64::new( PlatformFeeEstimator::DEFAULT_FEE_MULTIPLIER_PERMILLE, ), @@ -604,6 +612,22 @@ impl AppContext { self.network } + /// Route DPNS contest browsing into the shared Masternodes Voting Center. + pub fn route_to_dpns_voting_center(&self, contested_names: Vec) { + *self + .pending_dpns_voting_contests + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(contested_names); + } + + /// Consume a one-shot DPNS β†’ Masternodes Voting Center deep link. + pub fn take_dpns_voting_center_route(&self) -> Option> { + self.pending_dpns_voting_contests + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + } + pub fn connection_status(&self) -> &ConnectionStatus { &self.connection_status } diff --git a/src/model/contested_name.rs b/src/model/contested_name.rs index f30666b7b..09f72d8c5 100644 --- a/src/model/contested_name.rs +++ b/src/model/contested_name.rs @@ -35,11 +35,9 @@ 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) + /// Whether the contest still accepts this node's initial vote or a change. + pub fn is_open_for_voter(&self, _voter_id: &Identifier) -> bool { + self.state.state_is_votable() } } @@ -51,8 +49,10 @@ impl ContestedName { /// (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 has at least one pending (not-yet-executed) scheduled /// vote, reusing the DPNS Scheduled Votes screen's existing state. pub has_scheduled_vote: bool, @@ -107,14 +107,14 @@ mod tests { } #[test] - fn not_open_when_voter_already_voted() { + fn existing_vote_remains_actionable_while_contest_is_votable() { 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)); + assert!(c.is_open_for_voter(&voter)); } #[test] diff --git a/src/model/dpns_voting.rs b/src/model/dpns_voting.rs new file mode 100644 index 000000000..badbc5383 --- /dev/null +++ b/src/model/dpns_voting.rs @@ -0,0 +1,290 @@ +#[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; + + 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, + } + } + + /// VOTE-TC-003: choosing the proved current vote cannot create a target. + #[test] + fn operation_suppresses_exact_no_ops() { + let operation = DpnsVoteOperation::new(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(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::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 serialized_operation_contains_identifiers_and_choices_only() { + let operation = DpnsVoteOperation::new(vec![target(4, 5, None, ResourceVoteChoice::Lock)]); + let serialized = serde_json::to_string(&operation).expect("serialize operation"); + + assert!(!serialized.contains("private")); + assert!(!serialized.contains("secret")); + assert!(!serialized.contains("wif")); + } +} +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 rand::RngCore; +use serde::{Deserialize, Serialize}; +use std::fmt; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// Proved current vote state for one node Γ— poll. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DpnsCurrentVoteState { + Checking, + Available(Option), + Unavailable, +} + +/// 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 { + /// Generate a random operation identifier without adding a UUID dependency. + pub fn random() -> Self { + let mut bytes = [0; 16]; + rand::rng().fill_bytes(&mut bytes); + Self(bytes) + } + + /// 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, +} + +/// When a target should enter the shared executor. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum VoteTiming { + Now, + Scheduled(TimestampMillis), +} + +/// 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, +} + +/// Persistable, user-meaningful failure category without task diagnostics. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum DpnsVoteFailure { + PlatformRejected, + SubmissionFailed, + CurrentVoteUnavailable, + ResultUnconfirmed, +} + +/// Lifecycle of one target. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum DpnsVoteTargetStatus { + Scheduled, + Queued, + Submitting, + Confirming, + Confirmed, + Unconfirmed, + Rejected, + FailedBeforeSubmission, + NotApplied, +} + +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 + ) + } +} + +/// 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 transition_hash: Option<[u8; 32]>, + pub failure: 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(targets: Vec) -> Self { + let id = DpnsVoteOperationId::random(); + let created_at = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as TimestampMillis; + let original_len = targets.len(); + let targets = targets + .into_iter() + .filter(|target| target.current_choice != Some(target.requested_choice)) + .map(|target| { + let status = match target.timing { + VoteTiming::Now => DpnsVoteTargetStatus::Queued, + VoteTiming::Scheduled(_) => DpnsVoteTargetStatus::Scheduled, + }; + DpnsVoteOutcome { + operation_id: id, + target, + status, + transition_hash: None, + failure: 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()) + } +} diff --git a/src/model/mod.rs b/src/model/mod.rs index 7c1f24ee9..8d1cfabd6 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -5,6 +5,7 @@ pub mod dashpay; pub mod dashpay_derivation; pub(crate) mod data_migration; pub mod dpns; +pub mod dpns_voting; pub mod fee_estimation; pub mod grovestark_prover; pub mod identity_discovery; diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index e244d1786..c97296ccd 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -21,6 +21,10 @@ use crate::backend_task::error::TaskError; use crate::backend_task::identity::IdentityTask; use crate::context::AppContext; use crate::model::contested_name::{ContestState, ContestedName}; +use crate::model::dpns_voting::{ + DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteTarget, DpnsVoteTargetKey, + DpnsVoteTargetStatus, VoteTiming, +}; 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; @@ -1053,6 +1057,20 @@ impl DPNSScreen { }) .body(|mut body| { for vote in sorted_votes.iter_mut() { + let operation_status = self + .app_context + .dpns_vote_poll_id(&vote.0.contested_name) + .ok() + .and_then(|vote_poll_id| { + self.app_context + .dpns_vote_target_status(&DpnsVoteTargetKey { + network: self.app_context.network(), + voter_id: vote.0.voter_id, + vote_poll_id, + }) + .ok() + .flatten() + }); body.row(25.0, |mut row| { // Contested name row.col(|ui| { @@ -1102,6 +1120,25 @@ impl DPNSScreen { // Status row.col(|ui| { let dark_mode = ui.style().visuals.dark_mode; + if matches!( + operation_status, + Some(DpnsVoteTargetStatus::Queued) + | Some(DpnsVoteTargetStatus::Submitting) + | Some(DpnsVoteTargetStatus::Confirming) + ) { + ui.label( + RichText::new("Submitting…") + .color(DashColors::text_primary(dark_mode)), + ); + return; + } + if operation_status == Some(DpnsVoteTargetStatus::Unconfirmed) { + ui.colored_label( + DashColors::warning_color(dark_mode), + "Checking result", + ); + return; + } match vote.1 { ScheduledVoteCastingStatus::NotStarted => { ui.label( @@ -1125,7 +1162,20 @@ impl DPNSScreen { }); // Actions row.col(|ui| { - if ui.button("Remove").clicked() { + let target_is_busy = matches!( + operation_status, + Some(DpnsVoteTargetStatus::Queued) + | Some(DpnsVoteTargetStatus::Submitting) + | Some(DpnsVoteTargetStatus::Confirming) + | Some(DpnsVoteTargetStatus::Unconfirmed) + ); + if ui + .add_enabled(!target_is_busy, Button::new("Remove")) + .disabled_tooltip( + "This scheduled vote cannot be removed while its result is being checked.", + ) + .clicked() + { action = AppAction::BackendTask(BackendTask::ContestedResourceTask( ContestedResourceTask::DeleteScheduledVote( @@ -1140,8 +1190,7 @@ impl DPNSScreen { vote.1, ScheduledVoteCastingStatus::NotStarted | ScheduledVoteCastingStatus::Failed - ) && !self - .scheduled_vote_cast_in_progress; + ) && !target_is_busy; let cast_button = if cast_button_enabled { Button::new("Cast Now") @@ -1538,8 +1587,29 @@ impl DPNSScreen { ui.add_space(10.0); } + let operation_in_progress = matches!( + self.bulk_vote_handling_status, + VoteHandlingStatus::CastingVotes | VoteHandlingStatus::SchedulingVotes + ); + if operation_in_progress { + ui.horizontal(|ui| { + ui.spinner(); + ui.label("Submitting votes…"); + }); + } // "Apply Votes" button - if ComponentStyles::add_primary_button(ui, "Apply Votes").clicked() { + if ComponentStyles::add_primary_button_enabled( + ui, + !operation_in_progress, + if operation_in_progress { + "Submitting votes…" + } else { + "Apply Votes" + }, + ) + .disabled_tooltip("The selected votes are already being submitted.") + .clicked() + { action = self.bulk_apply_votes(); if self.bulk_vote_handling_status == VoteHandlingStatus::CastingVotes { self.vote_banner.take_and_clear(); @@ -1552,7 +1622,14 @@ impl DPNSScreen { ui.add_space(5.0); let dark_mode = ui.style().visuals.dark_mode; - if ComponentStyles::add_secondary_button(ui, "Cancel", dark_mode).clicked() { + if ui + .add_enabled( + !operation_in_progress, + ComponentStyles::secondary_button("Cancel", dark_mode), + ) + .disabled_tooltip("Submitted votes cannot be cancelled.") + .clicked() + { self.selected_votes.clear(); self.show_bulk_schedule_popup = false; self.bulk_schedule_message = None; @@ -1589,19 +1666,19 @@ impl DPNSScreen { /// 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(); - + let mut targets = Vec::new(); + let mut selected_voters = Vec::new(); + let mut has_immediate = false; for (identity, option) in self .voting_identities .iter() .zip(&self.bulk_identity_options) { - match option { - VoteOption::NoVote => {} + let timing = match option { + VoteOption::NoVote => continue, VoteOption::CastNow => { - immediate_list.push(identity.clone()); + has_immediate = true; + VoteTiming::Now } VoteOption::Scheduled { days, @@ -1612,62 +1689,88 @@ impl DPNSScreen { 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); + VoteTiming::Scheduled((now + offset).timestamp_millis() as u64) + } + }; + selected_voters.push(identity.clone()); + for selected_vote in &self.selected_votes { + let voter_id = identity.identity.id(); + let vote_poll_id = match self + .app_context + .dpns_vote_poll_id(&selected_vote.contested_name) + { + Ok(vote_poll_id) => vote_poll_id, + Err(error) => { + self.bulk_vote_handling_status = + VoteHandlingStatus::Failed(error.to_string()); + return AppAction::None; } + }; + let target_key = DpnsVoteTargetKey { + network: self.app_context.network(), + voter_id, + vote_poll_id, + }; + if self + .app_context + .dpns_vote_target_status(&target_key) + .ok() + .flatten() + .is_some() + { + self.bulk_vote_handling_status = VoteHandlingStatus::Failed(format!( + "This node's vote for {} is already in progress. Check its result before submitting again.", + selected_vote.contested_name + )); + return AppAction::None; } + let current_choice = match self + .app_context + .dpns_current_vote_state(voter_id, vote_poll_id) + { + Ok(DpnsCurrentVoteState::Available(choice)) => choice, + Ok(DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable) + | Err(_) => { + self.bulk_vote_handling_status = VoteHandlingStatus::Failed( + "Current vote state is unavailable. Refresh voting before applying votes." + .to_owned(), + ); + return AppAction::None; + } + }; + targets.push(DpnsVoteTarget { + key: target_key, + voter_alias: identity.alias.clone(), + contested_name: selected_vote.contested_name.clone(), + requested_choice: selected_vote.vote_choice, + current_choice, + timing, + }); } } - if immediate_list.is_empty() && scheduled_list.is_empty() { + if targets.is_empty() { self.bulk_vote_handling_status = VoteHandlingStatus::Failed( - "No votes selected. Please select votes to cast or schedule.".to_string(), + "No votes selected. Choose at least one node and contest.".to_owned(), ); return AppAction::None; } - - // 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), - )) + let operation = DpnsVoteOperation::new(targets); + if operation.targets.is_empty() { + self.bulk_vote_handling_status = VoteHandlingStatus::Failed( + "Every selected node already has the requested vote. Nothing will be submitted." + .to_owned(), + ); + return AppAction::None; } + self.bulk_vote_handling_status = if has_immediate { + VoteHandlingStatus::CastingVotes + } else { + VoteHandlingStatus::SchedulingVotes + }; + AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::SubmitDpnsVoteOperation(operation, selected_voters), + )) } /// If voting/scheduling is successful, show success message @@ -1829,22 +1932,12 @@ impl ScreenLike for DPNSScreen { 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_task_error(&mut self, error: &TaskError) -> bool { @@ -1869,54 +1962,10 @@ impl ScreenLike for DPNSScreen { 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(), - )); - } - + BackendTaskSuccessResult::DpnsVoteOperationUpdated(_) => { 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())); + self.refresh(); } BackendTaskSuccessResult::ScheduledVotesInProgress(votes) => { // The periodic sweep is about to cast these votes; reflect that @@ -1932,16 +1981,6 @@ impl ScreenLike for DPNSScreen { } } } - 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(); @@ -1973,7 +2012,7 @@ impl ScreenLike for DPNSScreen { vec![ refresh_button, ( - "Cast/Schedule Votes", + "Vote with masternodes", DesiredAppAction::Custom("Vote".to_string()), ), ] @@ -2044,9 +2083,13 @@ impl ScreenLike for DPNSScreen { // 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 + self.app_context.route_to_dpns_voting_center( + self.selected_votes + .iter() + .map(|vote| vote.contested_name.clone()) + .collect(), + ); + action = AppAction::SetMainScreen(RootScreenType::RootScreenMasternodes); } // Left panel diff --git a/src/ui/masternodes/card.rs b/src/ui/masternodes/card.rs index 67559c7da..c5dcbc7fb 100644 --- a/src/ui/masternodes/card.rs +++ b/src/ui/masternodes/card.rs @@ -59,7 +59,19 @@ pub fn voter_readiness_label(voting_present: bool) -> &'static str { /// (actionable), then a pending scheduled vote, 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.needs_vote_count == 0 { + "Votes cast in all active contests".to_owned() + } else if summary.needs_vote_count == 1 { + format!( + "{} active contests Β· 1 needs a vote", + summary.open_contest_count + ) + } else { + format!( + "{} active contests Β· {} need votes", + summary.open_contest_count, summary.needs_vote_count + ) + } } else if summary.has_scheduled_vote { "Vote scheduled".to_string() } else { @@ -368,9 +380,13 @@ 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, }; - assert_eq!(dpns_status_line(summary), "3 contests to vote on"); + assert_eq!( + dpns_status_line(summary), + "3 active contests Β· 1 needs a vote" + ); } #[test] @@ -386,15 +402,20 @@ 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, }; - 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, }; assert_eq!(dpns_status_line(summary), "Vote scheduled"); diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index f5e3421a4..7274a6b4e 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -24,6 +24,9 @@ use crate::backend_task::contested_names::ContestedResourceTask; use crate::backend_task::identity::{IdentityInputToLoad, IdentityLoadMode, IdentityTask}; use crate::context::AppContext; use crate::model::contested_name::{ContestedName, MasternodeContestSummary}; +use crate::model::dpns_voting::{ + DpnsCurrentVoteState, DpnsVoteTarget, DpnsVoteTargetKey, VoteTiming, +}; use crate::model::fee_estimation::format_credits_as_dash; use crate::model::qualified_identity::{ IdentityType, MasternodeKeyPresence, PrivateKeyTarget, QualifiedIdentity, @@ -91,6 +94,9 @@ fn candidate_choice_label(candidate_name: &str, votes: u32) -> String { struct ContestVoteRow { name: String, end_time: Option, + vote_poll_id: dash_sdk::platform::Identifier, + current_vote: DpnsCurrentVoteState, + locked: bool, /// `(candidate id, candidate name, votes so far)` for each contestant. candidates: Vec<(dash_sdk::platform::Identifier, String, u32)>, } @@ -232,6 +238,11 @@ pub enum DetailOutcome { Back, /// The node was removed β€” return to the list and reload. Removed, + /// Open the shared full-page composer prefiltered to this node. + OpenVotingCenter { + voter_id: dash_sdk::platform::Identifier, + choices: BTreeMap, + }, /// Push a reused screen / navigate. Boxed because `AppAction` is large. Forward(Box), } @@ -250,6 +261,9 @@ pub struct MasternodeDetailView { open_contests: Vec, /// Per-contest pending vote choice, keyed by normalized contested name. vote_selections: BTreeMap, + /// One-shot automatic proved-state refresh for a newly opened detail view. + vote_state_refresh_dispatched: bool, + open_voting_center_requested: 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, @@ -279,7 +293,7 @@ impl MasternodeDetailView { let voter_id = identity .associated_voter_identity .as_ref() - .map(|(voter, _)| voter.id()); + .map(|_| identity.identity.id()); let contest_summary = app_context .masternode_contest_summary(voter_id) .unwrap_or_default(); @@ -293,6 +307,8 @@ impl MasternodeDetailView { contest_summary, open_contests, vote_selections: BTreeMap::new(), + vote_state_refresh_dispatched: false, + open_voting_center_requested: None, voter_key_prompt: None, remove_dialog: None, } @@ -321,7 +337,7 @@ impl MasternodeDetailView { .identity .associated_voter_identity .as_ref() - .map(|(voter, _)| voter.id()); + .map(|_| self.identity.identity.id()); self.contest_summary = self .app_context .masternode_contest_summary(voter_id) @@ -439,6 +455,12 @@ impl MasternodeDetailView { outcome = DetailOutcome::Removed; } }); + if let Some(choices) = self.open_voting_center_requested.take() { + outcome = DetailOutcome::OpenVotingCenter { + voter_id: self.identity.identity.id(), + choices, + }; + } outcome } @@ -820,16 +842,29 @@ impl MasternodeDetailView { ))) } - /// Per-contest voting choices + Cast votes, dispatching the existing - /// `VoteOnDPNSNames` backend for the selected choices. + /// Per-contest choices backed by the shared durable voting coordinator. 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 voter_id = self.identity.identity.id(); let contests: Vec = self .open_contests .iter() - .map(|contest| { + .filter_map(|contest| { + let vote_poll_id = self + .app_context + .dpns_vote_poll_id(&contest.normalized_contested_name) + .ok()?; + let current_vote = self + .app_context + .dpns_current_vote_state(voter_id, vote_poll_id) + .unwrap_or(DpnsCurrentVoteState::Unavailable); + let key = DpnsVoteTargetKey { + network: self.app_context.network(), + voter_id, + vote_poll_id, + }; let candidates = contest .contestants .as_ref() @@ -839,13 +874,31 @@ impl MasternodeDetailView { .collect() }) .unwrap_or_default(); - ContestVoteRow { + Some(ContestVoteRow { name: contest.normalized_contested_name.clone(), end_time: contest.end_time, + vote_poll_id, + current_vote, + locked: self + .app_context + .dpns_vote_target_status(&key) + .ok() + .flatten() + .is_some(), candidates, - } + }) }) .collect(); + if !self.vote_state_refresh_dispatched + && contests + .iter() + .any(|contest| contest.current_vote == DpnsCurrentVoteState::Checking) + { + self.vote_state_refresh_dispatched = true; + action = Some(AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::QueryDPNSContests, + ))); + } ui.label(RichText::new(CONTEST_INTRO_MESSAGE).color(DashColors::text_secondary(dark_mode))); @@ -863,37 +916,73 @@ impl MasternodeDetailView { )) .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); + let current_label = match contest.current_vote { + DpnsCurrentVoteState::Checking => "Checking current vote…".to_owned(), + DpnsCurrentVoteState::Unavailable => "Current vote unavailable".to_owned(), + DpnsCurrentVoteState::Available(None) => "Not voted".to_owned(), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Abstain)) => { + "Current vote: Abstain".to_owned() } - if ui - .selectable_label(selected == Some(ResourceVoteChoice::Lock), "Lock") - .clicked() - { - self.vote_selections - .insert(contest.name.clone(), ResourceVoteChoice::Lock); + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) => { + "Current vote: Lock".to_owned() } - // Candidate choices are scoped to THIS contest's contestants. - for (candidate_id, candidate_name, votes) in &contest.candidates { - let choice = ResourceVoteChoice::TowardsIdentity(*candidate_id); + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::TowardsIdentity(id))) => { + let candidate = contest + .candidates + .iter() + .find(|(candidate_id, _, _)| *candidate_id == id) + .map(|(_, name, _)| name.as_str()) + .unwrap_or("candidate"); + format!("Current vote: {candidate}") + } + }; + ui.label(RichText::new(current_label).color(DashColors::text_secondary(dark_mode))); + let selected = self.vote_selections.get(&contest.name).copied(); + let controls_enabled = + matches!(contest.current_vote, DpnsCurrentVoteState::Available(_)) + && !contest.locked; + ui.add_enabled_ui(controls_enabled, |ui| { + ui.horizontal_wrapped(|ui| { if ui - .selectable_label( - selected == Some(choice), - candidate_choice_label(candidate_name, *votes), - ) + .selectable_label(selected == Some(ResourceVoteChoice::Abstain), "Abstain") .clicked() { - self.vote_selections.insert(contest.name.clone(), choice); + 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() { + if contest.locked { + ui.label( + RichText::new("This node's vote for this name is still being confirmed.") + .color(DashColors::text_secondary(dark_mode)), + ); + } else if matches!(contest.current_vote, DpnsCurrentVoteState::Unavailable) { + ui.label( + RichText::new("Refresh vote state before choosing a vote for this node.") + .color(DashColors::text_secondary(dark_mode)), + ); + } else if selected.is_none() { ui.label( RichText::new(NO_SELECTION_HINT).color(DashColors::text_secondary(dark_mode)), ); @@ -901,22 +990,51 @@ impl MasternodeDetailView { } ui.separator(); - let votes: Vec<(String, ResourceVoteChoice)> = self + let targets: Vec = self .vote_selections .iter() - .filter(|(name, _)| contests.iter().any(|c| &c.name == *name)) - .map(|(name, choice)| (name.clone(), *choice)) + .filter_map(|(name, choice)| { + let contest = contests.iter().find(|contest| &contest.name == name)?; + let DpnsCurrentVoteState::Available(current_choice) = contest.current_vote else { + return None; + }; + if current_choice == Some(*choice) || contest.locked { + return None; + } + Some(DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: self.app_context.network(), + voter_id, + vote_poll_id: contest.vote_poll_id, + }, + voter_alias: self.identity.alias.clone(), + contested_name: name.clone(), + requested_choice: *choice, + current_choice, + timing: VoteTiming::Now, + }) + }) .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) + let has_votes = !targets.is_empty(); + let review_label = if targets.len() == 1 { + "Review 1 vote".to_owned() + } else { + format!("Review {} votes", targets.len()) + }; + if ComponentStyles::add_primary_button_enabled(ui, has_votes, review_label) + .clickable_tooltip(CAST_ENABLED_HINT) + .disabled_tooltip(CAST_DISABLED_HINT) .clicked() { - action = Some(AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::VoteOnDPNSNames(votes, vec![self.identity.clone()]), - ))); + self.open_voting_center_requested = Some( + targets + .into_iter() + .map(|target| (target.contested_name, target.requested_choice)) + .collect(), + ); + } + if ComponentStyles::add_secondary_button(ui, "Open Voting Center", dark_mode).clicked() { + self.open_voting_center_requested = Some(BTreeMap::new()); } action } diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index f658293f1..f33051e66 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -17,6 +17,7 @@ use crate::backend_task::identity::IdentityTask; use crate::context::AppContext; use crate::context::identity_load_registry::{IdentityLoadPhase, IdentityLoadToken}; use crate::model::contested_name::MasternodeContestSummary; +use crate::model::dpns_voting::DpnsVoteTargetStatus; use crate::model::masternode_input::decode_identity_id; use crate::model::qualified_identity::{IdentityStatus, IdentityType, MasternodeKeyPresence}; use crate::model::user_role::UserRole; @@ -29,6 +30,7 @@ use crate::ui::identity::picker::compute_column_count; use crate::ui::masternodes::card::{MasternodeCard, card_heading}; use crate::ui::masternodes::detail_screen::{DetailOutcome, MasternodeDetailView}; use crate::ui::masternodes::load_form::{LoadFormOutcome, MasternodeLoadForm}; +use crate::ui::masternodes::voting_center::{DpnsVotingCenter, VotingCenterOutcome}; use crate::ui::state::global_nav::PageNavSpec; use crate::ui::state::masternodes_view::{masternodes_page_nav_spec, node_pill_item}; use crate::ui::theme::{ComponentStyles, DashColors}; @@ -60,6 +62,10 @@ enum MasternodesView { Load(Box), /// A node's detail / voting view (FR-5). Detail(Box), + /// Shared full-page immediate, bulk, and scheduled composer. + Voting(Box), + /// Shared scheduled-target management. + Scheduled, } /// A load this screen dispatched and has not yet seen finish. The token names @@ -145,7 +151,7 @@ impl MasternodesScreen { let voter_id = qi .associated_voter_identity .as_ref() - .map(|(identity, _)| identity.id()); + .map(|_| qi.identity.id()); let contest_summary = self .app_context .masternode_contest_summary(voter_id) @@ -307,12 +313,98 @@ impl MasternodesScreen { AppAction::None } + /// Operator-level Nodes / Voting / Scheduled navigation. + fn render_voting_navigation(&mut self, ui: &mut egui::Ui) -> AppAction { + let dark_mode = ui.style().visuals.dark_mode; + let action = AppAction::None; + ui.horizontal(|ui| { + if matches!(self.view, MasternodesView::Voting(_)) { + if ComponentStyles::add_secondary_button(ui, "Nodes", dark_mode).clicked() { + self.view = MasternodesView::List; + } + ComponentStyles::add_primary_button(ui, "Voting"); + } else { + if ComponentStyles::add_primary_button(ui, "Nodes").clicked() { + self.view = MasternodesView::List; + } + if ComponentStyles::add_secondary_button(ui, "Voting", dark_mode).clicked() { + self.open_voting_center(None, Vec::new()); + } + } + if matches!(self.view, MasternodesView::Scheduled) { + ComponentStyles::add_primary_button(ui, "Scheduled"); + } else if ComponentStyles::add_secondary_button(ui, "Scheduled", dark_mode).clicked() { + self.view = MasternodesView::Scheduled; + } + }); + ui.separator(); + action + } + + /// Shared target-correlated progress, visible regardless of the active node. + fn render_voting_activity(&self, ui: &mut egui::Ui) -> AppAction { + let Ok(mut operations) = self.app_context.dpns_vote_operations() else { + return AppAction::None; + }; + operations.sort_by_key(|operation| operation.created_at); + let operations = operations + .into_iter() + .rev() + .filter(|operation| !operation.targets.is_empty()) + .take(5) + .collect::>(); + if operations.is_empty() { + return AppAction::None; + } + + let dark_mode = ui.style().visuals.dark_mode; + let mut action = AppAction::None; + ui.add_space(16.0); + ui.heading(RichText::new("Voting activity").color(DashColors::text_primary(dark_mode))); + for operation in operations { + for outcome in &operation.targets { + let voter = outcome.target.voter_alias.clone().unwrap_or_else(|| { + shorten_id(&outcome.target.key.voter_id.to_string(Encoding::Base58)) + }); + let status = match outcome.status { + DpnsVoteTargetStatus::Scheduled => "Scheduled", + DpnsVoteTargetStatus::Queued => "Queued", + DpnsVoteTargetStatus::Submitting => "Submitting", + DpnsVoteTargetStatus::Confirming => "Confirming", + DpnsVoteTargetStatus::Confirmed => "Confirmed", + DpnsVoteTargetStatus::Unconfirmed => "Checking result", + DpnsVoteTargetStatus::Rejected => "Rejected", + DpnsVoteTargetStatus::FailedBeforeSubmission => "Failed before submission", + DpnsVoteTargetStatus::NotApplied => "Not applied", + }; + ui.horizontal_wrapped(|ui| { + ui.label(format!( + "{voter} / {} β€” {status}", + outcome.target.contested_name + )); + if outcome.status == DpnsVoteTargetStatus::Unconfirmed + && ComponentStyles::add_secondary_button(ui, "Check again", dark_mode) + .clicked() + { + action = AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::ReconcileDpnsVoteOperation(operation.id), + )); + } + }); + } + } + action + } + /// The node the page currently operates on β€” the one whose detail view is /// open. The list and load views operate on no single node. fn selected_node_id(&self) -> Option { match &self.view { MasternodesView::Detail(detail) => Some(detail.node_id()), - MasternodesView::List | MasternodesView::Load(_) => None, + MasternodesView::List + | MasternodesView::Load(_) + | MasternodesView::Voting(_) + | MasternodesView::Scheduled => None, } } @@ -384,10 +476,145 @@ impl MasternodesScreen { self.reload(); AppAction::None } + DetailOutcome::OpenVotingCenter { voter_id, choices } => { + self.view = if choices.is_empty() { + MasternodesView::Voting(Box::new(DpnsVotingCenter::new( + &self.app_context, + Some(voter_id), + Vec::new(), + ))) + } else { + MasternodesView::Voting(Box::new(DpnsVotingCenter::for_quick_votes( + &self.app_context, + voter_id, + choices, + ))) + }; + AppAction::None + } DetailOutcome::Forward(action) => *action, } } + fn open_voting_center( + &mut self, + preselected_voter: Option, + preselected_contests: Vec, + ) { + self.view = MasternodesView::Voting(Box::new(DpnsVotingCenter::new( + &self.app_context, + preselected_voter, + preselected_contests, + ))); + } + + fn render_voting_center(&mut self, ui: &mut egui::Ui) -> AppAction { + let outcome = match &mut self.view { + MasternodesView::Voting(center) => center.show(ui), + _ => return AppAction::None, + }; + match outcome { + VotingCenterOutcome::None => AppAction::None, + VotingCenterOutcome::BackToNodes => { + self.view = MasternodesView::List; + AppAction::None + } + VotingCenterOutcome::Action(action) => *action, + } + } + + fn render_scheduled_votes(&mut self, ui: &mut egui::Ui) -> AppAction { + let dark_mode = ui.style().visuals.dark_mode; + let mut action = AppAction::None; + ui.heading("Scheduled votes"); + ui.label( + "Upcoming and unresolved targets use the same operation locks as immediate votes.", + ); + let votes = self.app_context.get_scheduled_votes().unwrap_or_default(); + if votes.is_empty() { + ui.label("No scheduled votes."); + return action; + } + for vote in votes { + let status = self + .app_context + .dpns_vote_poll_id(&vote.contested_name) + .ok() + .and_then(|vote_poll_id| { + self.app_context + .dpns_vote_target_status(&crate::model::dpns_voting::DpnsVoteTargetKey { + network: self.app_context.network(), + voter_id: vote.voter_id, + vote_poll_id, + }) + .ok() + .flatten() + }); + ui.group(|ui| { + ui.label( + RichText::new(format!( + "{}.dash / {}", + vote.contested_name, + vote.voter_id.to_string(Encoding::Base58) + )) + .strong(), + ); + ui.label(format!("Choice: {}", vote.choice)); + ui.label(format!( + "Scheduled time: {} UTC milliseconds", + vote.unix_timestamp + )); + ui.label(match status { + Some(DpnsVoteTargetStatus::Unconfirmed) => "Status: Checking result", + Some( + DpnsVoteTargetStatus::Queued + | DpnsVoteTargetStatus::Submitting + | DpnsVoteTargetStatus::Confirming, + ) => "Status: Submitting", + Some(DpnsVoteTargetStatus::Scheduled) => "Status: Scheduled", + _ if vote.executed_successfully => "Status: Completed", + _ => "Status: Needs attention", + }); + let editable = status == Some(DpnsVoteTargetStatus::Scheduled); + if ComponentStyles::add_secondary_button(ui, "Edit schedule", dark_mode).clicked() + && editable + { + self.view = MasternodesView::Voting(Box::new( + DpnsVotingCenter::for_scheduled_edit(&self.app_context, &vote), + )); + } + if ComponentStyles::add_secondary_button(ui, "Cancel scheduled vote", dark_mode) + .clicked() + && editable + { + action = AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::DeleteScheduledVote( + vote.voter_id, + vote.contested_name.clone(), + ), + )); + } + if status == Some(DpnsVoteTargetStatus::Unconfirmed) + && ComponentStyles::add_secondary_button(ui, "Check again", dark_mode).clicked() + && let Ok(Some(operation)) = + self.app_context.dpns_vote_operations().map(|operations| { + operations.into_iter().find(|operation| { + operation.targets.iter().any(|outcome| { + outcome.target.key.voter_id == vote.voter_id + && outcome.target.contested_name == vote.contested_name + }) + }) + }) + { + action = AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::ReconcileDpnsVoteOperation(operation.id), + )); + } + }); + } + action + } + /// Render the list view: toolbar (`+ Load`, `Refresh`) + empty state or grid. fn render_list_view(&mut self, ui: &mut egui::Ui, network_accent: egui::Color32) -> AppAction { let mut inner = AppAction::None; @@ -514,6 +741,9 @@ impl ScreenLike for MasternodesScreen { fn refresh_on_arrival(&mut self) { self.reload(); self.reconcile_pending_load(); + if let Some(contests) = self.app_context.take_dpns_voting_center_route() { + self.open_voting_center(None, contests); + } } /// Drop every secret the open view holds β€” the load form's keys and @@ -531,7 +761,7 @@ impl ScreenLike for MasternodesScreen { match &mut self.view { MasternodesView::Load(form) => form.clear_secrets(), MasternodesView::Detail(detail) => detail.clear_secrets(), - MasternodesView::List => {} + MasternodesView::List | MasternodesView::Voting(_) | MasternodesView::Scheduled => {} } } @@ -575,11 +805,16 @@ impl ScreenLike for MasternodesScreen { action |= island_central_panel(ui, |ui| { ui.set_min_width(ui.available_width()); + let mut action = self.render_voting_navigation(ui); 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), + MasternodesView::Load(_) => action |= self.render_load_view(ui), + MasternodesView::Detail(_) => action |= self.render_detail_view(ui, network_accent), + MasternodesView::Voting(_) => action |= self.render_voting_center(ui), + MasternodesView::Scheduled => action |= self.render_scheduled_votes(ui), + MasternodesView::List => action |= self.render_list_view(ui, network_accent), } + action |= self.render_voting_activity(ui); + action }); action diff --git a/src/ui/masternodes/mod.rs b/src/ui/masternodes/mod.rs index 89dbc3b52..27d3ed900 100644 --- a/src/ui/masternodes/mod.rs +++ b/src/ui/masternodes/mod.rs @@ -10,6 +10,7 @@ pub mod detail_screen; pub mod list_screen; pub mod load_form; pub mod testnet_fixture; +pub mod voting_center; pub use list_screen::MasternodesScreen; diff --git a/src/ui/masternodes/voting_center.rs b/src/ui/masternodes/voting_center.rs new file mode 100644 index 000000000..bda50bba2 --- /dev/null +++ b/src/ui/masternodes/voting_center.rs @@ -0,0 +1,704 @@ +//! Full-page Nodes β†’ Votes β†’ Review DPNS voting composer. + +use std::collections::BTreeMap; +use std::sync::Arc; + +use chrono::{Duration, Utc}; +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, ComboBox, RichText}; + +use crate::app::AppAction; +use crate::backend_task::BackendTask; +use crate::backend_task::contested_names::{ContestedResourceTask, ScheduledDPNSVote}; +use crate::backend_task::error::TaskError; +use crate::context::AppContext; +use crate::model::contested_name::ContestedName; +use crate::model::dpns_voting::{ + DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, + DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, +}; +use crate::model::qualified_identity::QualifiedIdentity; +use crate::ui::MessageType; +use crate::ui::components::MessageBanner; +use crate::ui::state::dpns_vote_workspace::{ + ComposerKeyAction, DpnsVoteComposerStep, DpnsVoteWorkspace, DraftVoteTiming, +}; +use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; + +pub enum VotingCenterOutcome { + None, + BackToNodes, + Action(Box), +} + +pub struct DpnsVotingCenter { + app_context: Arc, + voters: Vec, + contests: Vec, + workspace: DpnsVoteWorkspace, + submitted_operation: Option, + vote_state_refresh_dispatched: bool, + editing_scheduled_key: Option, + focus_step_heading: bool, +} + +impl DpnsVotingCenter { + pub fn new( + app_context: &Arc, + preselected_voter: Option, + preselected_contests: Vec, + ) -> Self { + let voters = app_context + .load_local_voting_identities() + .unwrap_or_default(); + let mut workspace = DpnsVoteWorkspace::new(voters.iter().map(|voter| voter.identity.id())); + if let Some(voter_id) = preselected_voter { + workspace.prefilter_node(voter_id); + } + let contests = app_context.ongoing_contested_names().unwrap_or_default(); + if !preselected_contests.is_empty() { + for name in preselected_contests { + if contests + .iter() + .any(|contest| contest.normalized_contested_name == name) + { + workspace + .contest_choices + .entry(name) + .or_insert(ResourceVoteChoice::Abstain); + } + } + } + Self { + app_context: Arc::clone(app_context), + voters, + contests, + workspace, + submitted_operation: None, + vote_state_refresh_dispatched: false, + editing_scheduled_key: None, + focus_step_heading: true, + } + } + + pub fn for_scheduled_edit(app_context: &Arc, vote: &ScheduledDPNSVote) -> Self { + let mut center = Self::new( + app_context, + Some(vote.voter_id), + vec![vote.contested_name.clone()], + ); + center + .workspace + .contest_choices + .insert(vote.contested_name.clone(), vote.choice); + let remaining_minutes = vote + .unix_timestamp + .saturating_sub(Utc::now().timestamp_millis() as u64) + / 60_000; + center.workspace.node_timing.insert( + vote.voter_id, + DraftVoteTiming::Scheduled { + days: (remaining_minutes / (24 * 60)) as u32, + hours: ((remaining_minutes / 60) % 24) as u32, + minutes: (remaining_minutes % 60) as u32, + }, + ); + center.editing_scheduled_key = app_context + .dpns_vote_poll_id(&vote.contested_name) + .ok() + .map(|vote_poll_id| DpnsVoteTargetKey { + network: app_context.network(), + voter_id: vote.voter_id, + vote_poll_id, + }); + center + } + + pub fn for_quick_votes( + app_context: &Arc, + voter_id: Identifier, + choices: BTreeMap, + ) -> Self { + let mut center = Self::new( + app_context, + Some(voter_id), + choices.keys().cloned().collect(), + ); + center.workspace.contest_choices = choices; + center.workspace.step = DpnsVoteComposerStep::Review; + center + } + + pub fn show(&mut self, ui: &mut egui::Ui) -> VotingCenterOutcome { + if self.submitted_operation.is_some() { + return self.render_operation(ui); + } + let (enter, escape) = ui.input(|input| { + ( + input.key_pressed(egui::Key::Enter), + input.key_pressed(egui::Key::Escape), + ) + }); + let can_continue = match self.workspace.step { + DpnsVoteComposerStep::Nodes => self.workspace.selected_node_count() > 0, + DpnsVoteComposerStep::Votes => !self.workspace.contest_choices.is_empty(), + DpnsVoteComposerStep::Review => self + .build_operation() + .is_ok_and(|operation| !operation.targets.is_empty()), + }; + match self.workspace.keyboard_action(enter, escape, can_continue) { + ComposerKeyAction::CloseDraft => return VotingCenterOutcome::BackToNodes, + ComposerKeyAction::Advance => { + self.workspace.step = match self.workspace.step { + DpnsVoteComposerStep::Nodes => DpnsVoteComposerStep::Votes, + DpnsVoteComposerStep::Votes | DpnsVoteComposerStep::Review => { + DpnsVoteComposerStep::Review + } + }; + self.focus_step_heading = true; + } + ComposerKeyAction::Submit => { + if let Ok(operation) = self.build_operation() { + return self.submit_operation(operation); + } + } + ComposerKeyAction::None => {} + } + let needs_refresh = self + .selected_current_states() + .iter() + .any(|(_, state)| matches!(state, DpnsCurrentVoteState::Checking)); + if needs_refresh && !self.vote_state_refresh_dispatched { + self.vote_state_refresh_dispatched = true; + return VotingCenterOutcome::Action(Box::new(AppAction::BackendTask( + BackendTask::ContestedResourceTask(ContestedResourceTask::QueryDPNSContests), + ))); + } + + match self.workspace.step { + DpnsVoteComposerStep::Nodes => self.render_nodes(ui), + DpnsVoteComposerStep::Votes => self.render_votes(ui), + DpnsVoteComposerStep::Review => self.render_review(ui), + } + } + + fn render_nodes(&mut self, ui: &mut egui::Ui) -> VotingCenterOutcome { + let dark_mode = ui.style().visuals.dark_mode; + self.step_heading(ui, "Step 1 of 3: Nodes and timing"); + ui.label("Choose which nodes will vote and when each node should submit."); + ui.horizontal_wrapped(|ui| { + ui.label("Set all:"); + timing_combo( + ui, + "voting_center_set_all", + &mut self.workspace.set_all_timing, + ); + if ComponentStyles::add_secondary_button(ui, "Apply", dark_mode).clicked() { + self.workspace.apply_timing_to_all(); + } + }); + ui.separator(); + for voter in &self.voters { + let voter_id = voter.identity.id(); + let alias = voter + .alias + .clone() + .unwrap_or_else(|| voter_id.to_string(Encoding::Base58)); + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new(alias).strong()); + let timing = self + .workspace + .node_timing + .entry(voter_id) + .or_insert(DraftVoteTiming::Excluded); + timing_combo(ui, format!("voting_center_node_{voter_id}"), timing); + render_schedule_offset(ui, timing); + }); + } + ui.separator(); + let enabled = self.workspace.selected_node_count() > 0; + if ComponentStyles::add_primary_button_enabled(ui, enabled, "Next: Choose votes") + .disabled_tooltip("Choose at least one node before continuing.") + .clicked() + { + self.workspace.step = DpnsVoteComposerStep::Votes; + self.focus_step_heading = true; + } + VotingCenterOutcome::None + } + + fn render_votes(&mut self, ui: &mut egui::Ui) -> VotingCenterOutcome { + let dark_mode = ui.style().visuals.dark_mode; + self.step_heading(ui, "Step 2 of 3: Votes"); + ui.label("Choose one requested vote for each contested name."); + for contest in &self.contests { + let name = &contest.normalized_contested_name; + ui.separator(); + ui.label(RichText::new(format!("{name}.dash")).strong()); + let states = self.current_states_for_contest(contest); + ui.label( + RichText::new(current_summary(&states)) + .color(DashColors::text_secondary(dark_mode)), + ); + let vote_poll_id = self.app_context.dpns_vote_poll_id(name).ok(); + let controls_enabled = !states.iter().any(|(voter_id, state, locked)| { + let lock_is_this_edit = vote_poll_id.is_some_and(|vote_poll_id| { + self.editing_scheduled_key.as_ref() + == Some(&DpnsVoteTargetKey { + network: self.app_context.network(), + voter_id: *voter_id, + vote_poll_id, + }) + }); + (*locked && !lock_is_this_edit) + || !matches!(state, DpnsCurrentVoteState::Available(_)) + }); + let selected = self.workspace.contest_choices.get(name).copied(); + ui.add_enabled_ui(controls_enabled, |ui| { + ui.horizontal_wrapped(|ui| { + vote_choice( + ui, + selected, + ResourceVoteChoice::Abstain, + "Abstain", + &mut self.workspace, + name, + ); + vote_choice( + ui, + selected, + ResourceVoteChoice::Lock, + "Lock", + &mut self.workspace, + name, + ); + for candidate in contest.contestants.as_deref().unwrap_or_default() { + vote_choice( + ui, + selected, + ResourceVoteChoice::TowardsIdentity(candidate.id), + &format!("Vote for {}", candidate.name), + &mut self.workspace, + name, + ); + } + }); + }); + if !controls_enabled { + ui.label( + RichText::new( + "This contest is unavailable for at least one selected node. Refresh or wait for the active vote to finish.", + ) + .color(DashColors::text_secondary(dark_mode)), + ); + } + } + ui.separator(); + let mut outcome = VotingCenterOutcome::None; + ui.horizontal(|ui| { + if ComponentStyles::add_secondary_button(ui, "Back", dark_mode).clicked() { + self.workspace.step = DpnsVoteComposerStep::Nodes; + self.focus_step_heading = true; + } + let target_count = + self.workspace.selected_node_count() * self.workspace.contest_choices.len(); + let enabled = target_count > 0; + if ComponentStyles::add_primary_button_enabled( + ui, + enabled, + format!("Review {target_count} targets"), + ) + .disabled_tooltip("Choose at least one contested name before continuing.") + .clicked() + { + self.workspace.step = DpnsVoteComposerStep::Review; + self.focus_step_heading = true; + } + if ComponentStyles::add_secondary_button(ui, "Close Voting Center", dark_mode).clicked() + { + outcome = VotingCenterOutcome::BackToNodes; + } + }); + outcome + } + + fn render_review(&mut self, ui: &mut egui::Ui) -> VotingCenterOutcome { + let dark_mode = ui.style().visuals.dark_mode; + self.step_heading(ui, "Step 3 of 3: Review"); + let operation = match self.build_operation() { + Ok(operation) => operation, + Err(error) => { + MessageBanner::set_global(ui.ctx(), error.to_string(), MessageType::Error) + .with_details(&error); + self.workspace.step = DpnsVoteComposerStep::Votes; + self.focus_step_heading = true; + return VotingCenterOutcome::None; + } + }; + for outcome in &operation.targets { + let voter = outcome + .target + .voter_alias + .as_deref() + .unwrap_or("Unnamed node"); + ui.group(|ui| { + ui.label(RichText::new(format!( + "{voter} / {}.dash", + outcome.target.contested_name + )) + .strong()); + ui.label(format!( + "Current: {}", + choice_label(outcome.target.current_choice) + )); + ui.label(format!( + "Requested: {}", + choice_label(Some(outcome.target.requested_choice)) + )); + ui.label(match outcome.target.timing { + VoteTiming::Now => "When: Cast now".to_owned(), + VoteTiming::Scheduled(timestamp) => { + format!("When: Scheduled for {timestamp} UTC milliseconds") + } + }); + if outcome.target.current_choice.is_some() { + ui.label( + RichText::new( + "This changes an existing vote. Platform permits only a limited number of vote changes.", + ) + .color(DashColors::warning_color(dark_mode)), + ); + } + }); + } + if operation.no_op_count > 0 { + ui.label(format!( + "{} targets already have the requested vote and will not be submitted.", + operation.no_op_count + )); + } + ui.label(format!( + "{} targets total. Each submitted vote uses Platform credits.", + operation.targets.len() + )); + ui.horizontal(|ui| { + if ComponentStyles::add_secondary_button(ui, "Back", dark_mode).clicked() { + self.workspace.step = DpnsVoteComposerStep::Votes; + self.focus_step_heading = true; + } + }); + if operation.targets.is_empty() { + ui.label( + "Every selected node already has the requested vote. Nothing will be submitted.", + ); + return VotingCenterOutcome::None; + } + let target_count = operation.targets.len(); + if ComponentStyles::add_primary_button(ui, format!("Submit {target_count} targets")) + .clicked() + { + return self.submit_operation(operation); + } + VotingCenterOutcome::None + } + + fn render_operation(&mut self, ui: &mut egui::Ui) -> VotingCenterOutcome { + let dark_mode = ui.style().visuals.dark_mode; + let Some(operation_id) = self.submitted_operation else { + return VotingCenterOutcome::None; + }; + ui.heading("Voting operation"); + match self.app_context.dpns_vote_operation(operation_id) { + Ok(Some(operation)) => { + for outcome in &operation.targets { + ui.horizontal_wrapped(|ui| { + ui.label(format!( + "{} / {}.dash β€” {}", + outcome + .target + .voter_alias + .as_deref() + .unwrap_or("Unnamed node"), + outcome.target.contested_name, + status_label(outcome.status) + )); + }); + } + if operation + .targets + .iter() + .any(|outcome| outcome.status == DpnsVoteTargetStatus::Unconfirmed) + && ComponentStyles::add_secondary_button(ui, "Check again", dark_mode).clicked() + { + return VotingCenterOutcome::Action(Box::new(AppAction::BackendTask( + BackendTask::ContestedResourceTask( + ContestedResourceTask::ReconcileDpnsVoteOperation(operation_id), + ), + ))); + } + if ComponentStyles::add_secondary_button(ui, "Continue in background", dark_mode) + .clicked() + { + return VotingCenterOutcome::BackToNodes; + } + } + Ok(None) => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label("Queuing votes…"); + }); + } + Err(error) => { + ui.label(error.to_string()); + } + } + VotingCenterOutcome::None + } + + fn selected_voters(&self) -> Vec { + self.voters + .iter() + .filter(|voter| { + self.workspace + .node_timing + .get(&voter.identity.id()) + .is_some_and(|timing| *timing != DraftVoteTiming::Excluded) + }) + .cloned() + .collect() + } + + fn submit_operation(&mut self, operation: DpnsVoteOperation) -> VotingCenterOutcome { + self.submitted_operation = Some(operation.id); + VotingCenterOutcome::Action(Box::new(AppAction::BackendTask( + BackendTask::ContestedResourceTask(ContestedResourceTask::SubmitDpnsVoteOperation( + operation, + self.selected_voters(), + )), + ))) + } + + fn step_heading(&mut self, ui: &mut egui::Ui, text: &str) { + let response = ui.heading(text); + if std::mem::take(&mut self.focus_step_heading) { + response.request_focus(); + } + } + + fn selected_current_states(&self) -> Vec<(Identifier, DpnsCurrentVoteState)> { + self.contests + .iter() + .flat_map(|contest| { + let poll_id = self + .app_context + .dpns_vote_poll_id(&contest.normalized_contested_name) + .ok(); + self.selected_voters().into_iter().filter_map(move |voter| { + let poll_id = poll_id?; + let voter_id = voter.identity.id(); + Some(( + voter_id, + self.app_context + .dpns_current_vote_state(voter_id, poll_id) + .unwrap_or(DpnsCurrentVoteState::Unavailable), + )) + }) + }) + .collect() + } + + fn current_states_for_contest( + &self, + contest: &ContestedName, + ) -> Vec<(Identifier, DpnsCurrentVoteState, bool)> { + let Ok(vote_poll_id) = self + .app_context + .dpns_vote_poll_id(&contest.normalized_contested_name) + else { + return Vec::new(); + }; + self.selected_voters() + .into_iter() + .map(|voter| { + let voter_id = voter.identity.id(); + let key = DpnsVoteTargetKey { + network: self.app_context.network(), + voter_id, + vote_poll_id, + }; + ( + voter_id, + self.app_context + .dpns_current_vote_state(voter_id, vote_poll_id) + .unwrap_or(DpnsCurrentVoteState::Unavailable), + self.app_context + .dpns_vote_target_status(&key) + .ok() + .flatten() + .is_some(), + ) + }) + .collect() + } + + fn build_operation(&self) -> Result { + let mut targets = Vec::new(); + for voter in self.selected_voters() { + let voter_id = voter.identity.id(); + let draft_timing = self.workspace.node_timing[&voter_id]; + let timing = match draft_timing { + DraftVoteTiming::Excluded => continue, + DraftVoteTiming::Now => VoteTiming::Now, + DraftVoteTiming::Scheduled { + days, + hours, + minutes, + } => VoteTiming::Scheduled( + (Utc::now() + + Duration::days(i64::from(days)) + + Duration::hours(i64::from(hours)) + + Duration::minutes(i64::from(minutes))) + .timestamp_millis() as u64, + ), + }; + for (name, requested_choice) in &self.workspace.contest_choices { + let vote_poll_id = self.app_context.dpns_vote_poll_id(name)?; + let key = DpnsVoteTargetKey { + network: self.app_context.network(), + voter_id, + vote_poll_id, + }; + let existing_status = self.app_context.dpns_vote_target_status(&key)?; + let replacing_schedule = existing_status == Some(DpnsVoteTargetStatus::Scheduled) + && matches!(timing, VoteTiming::Scheduled(_)); + if existing_status.is_some() && !replacing_schedule { + return Err(TaskError::DpnsVoteTargetBusy); + } + let DpnsCurrentVoteState::Available(current_choice) = self + .app_context + .dpns_current_vote_state(voter_id, vote_poll_id)? + else { + return Err(TaskError::DpnsCurrentVoteUnavailable); + }; + targets.push(DpnsVoteTarget { + key, + voter_alias: voter.alias.clone(), + contested_name: name.clone(), + requested_choice: *requested_choice, + current_choice, + timing, + }); + } + } + Ok(DpnsVoteOperation::new(targets)) + } +} + +fn timing_combo(ui: &mut egui::Ui, id: impl Into, timing: &mut DraftVoteTiming) { + ComboBox::from_id_salt(id.into()) + .selected_text(match timing { + DraftVoteTiming::Excluded => "Do not use this node", + DraftVoteTiming::Now => "Cast now", + DraftVoteTiming::Scheduled { .. } => "Schedule", + }) + .show_ui(ui, |ui| { + ui.selectable_value(timing, DraftVoteTiming::Excluded, "Do not use this node"); + ui.selectable_value(timing, DraftVoteTiming::Now, "Cast now"); + if ui + .selectable_label( + matches!(timing, DraftVoteTiming::Scheduled { .. }), + "Schedule", + ) + .clicked() + { + *timing = DraftVoteTiming::Scheduled { + days: 0, + hours: 0, + minutes: 0, + }; + } + }); +} + +fn render_schedule_offset(ui: &mut egui::Ui, timing: &mut DraftVoteTiming) { + if let DraftVoteTiming::Scheduled { + days, + hours, + minutes, + } = timing + { + 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("Minutes: ") + .range(0..=59), + ); + } +} + +fn vote_choice( + ui: &mut egui::Ui, + selected: Option, + choice: ResourceVoteChoice, + label: &str, + workspace: &mut DpnsVoteWorkspace, + name: &str, +) { + if ui + .selectable_label(selected == Some(choice), label) + .clicked() + { + workspace.contest_choices.insert(name.to_owned(), choice); + } +} + +fn current_summary(states: &[(Identifier, DpnsCurrentVoteState, bool)]) -> String { + if states.iter().any(|(_, state, _)| { + matches!( + state, + DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable + ) + }) { + return "Current vote unavailable for at least one selected node".to_owned(); + } + let not_voted = states + .iter() + .filter(|(_, state, _)| *state == DpnsCurrentVoteState::Available(None)) + .count(); + if not_voted == states.len() { + "Current across selected nodes: Not voted".to_owned() + } else if not_voted > 0 { + format!("Current across selected nodes: {not_voted} not voted, others already voted") + } else { + "Current across selected nodes: All already voted".to_owned() + } +} + +fn choice_label(choice: Option) -> String { + match choice { + None => "Not voted".to_owned(), + Some(ResourceVoteChoice::Abstain) => "Abstain".to_owned(), + Some(ResourceVoteChoice::Lock) => "Lock".to_owned(), + Some(ResourceVoteChoice::TowardsIdentity(identity)) => { + format!("Vote for {identity}") + } + } +} + +fn 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 => "Checking result", + DpnsVoteTargetStatus::Rejected => "Rejected", + DpnsVoteTargetStatus::FailedBeforeSubmission => "Failed before submission", + DpnsVoteTargetStatus::NotApplied => "Not applied", + } +} diff --git a/src/ui/state/dpns_vote_workspace.rs b/src/ui/state/dpns_vote_workspace.rs new file mode 100644 index 000000000..1b3170590 --- /dev/null +++ b/src/ui/state/dpns_vote_workspace.rs @@ -0,0 +1,158 @@ +//! Non-rendering state for the shared DPNS Voting Center composer. + +use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use dash_sdk::platform::Identifier; +use std::collections::BTreeMap; + +/// Current step of the full-page voting composer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DpnsVoteComposerStep { + Nodes, + Votes, + Review, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ComposerKeyAction { + None, + Advance, + Submit, + CloseDraft, +} + +/// Per-node timing override in the draft. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DraftVoteTiming { + Excluded, + Now, + Scheduled { days: u32, hours: u32, minutes: u32 }, +} + +/// Shared quick/bulk draft state; renders nothing. +#[derive(Debug, Clone)] +pub struct DpnsVoteWorkspace { + pub step: DpnsVoteComposerStep, + pub node_timing: BTreeMap, + pub contest_choices: BTreeMap, + pub set_all_timing: DraftVoteTiming, +} + +impl DpnsVoteWorkspace { + pub fn new(node_ids: impl IntoIterator) -> Self { + Self { + step: DpnsVoteComposerStep::Nodes, + node_timing: node_ids + .into_iter() + .map(|node_id| (node_id, DraftVoteTiming::Now)) + .collect(), + contest_choices: BTreeMap::new(), + set_all_timing: DraftVoteTiming::Now, + } + } + + /// Restrict the initial draft to one node from a detail-page deep link. + pub fn prefilter_node(&mut self, selected: Identifier) { + for (node_id, timing) in &mut self.node_timing { + *timing = if *node_id == selected { + DraftVoteTiming::Now + } else { + DraftVoteTiming::Excluded + }; + } + } + + pub fn selected_node_count(&self) -> usize { + self.node_timing + .values() + .filter(|timing| **timing != DraftVoteTiming::Excluded) + .count() + } + + pub fn apply_timing_to_all(&mut self) { + for timing in self.node_timing.values_mut() { + *timing = self.set_all_timing; + } + } + + /// Resolve keyboard intent without letting Enter submit before Review. + pub fn keyboard_action( + &self, + enter_pressed: bool, + escape_pressed: bool, + can_continue: bool, + ) -> ComposerKeyAction { + if escape_pressed { + return ComposerKeyAction::CloseDraft; + } + if !enter_pressed || !can_continue { + return ComposerKeyAction::None; + } + match self.step { + DpnsVoteComposerStep::Nodes | DpnsVoteComposerStep::Votes => ComposerKeyAction::Advance, + DpnsVoteComposerStep::Review => ComposerKeyAction::Submit, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// VOTE-TC-021/022: set-all applies timing and an individual override survives. + #[test] + fn set_all_timing_allows_per_node_override() { + let first = Identifier::from([1; 32]); + let second = Identifier::from([2; 32]); + let mut workspace = DpnsVoteWorkspace::new([first, second]); + workspace.set_all_timing = DraftVoteTiming::Scheduled { + days: 1, + hours: 2, + minutes: 3, + }; + workspace.apply_timing_to_all(); + workspace.node_timing.insert(first, DraftVoteTiming::Now); + + assert_eq!(workspace.node_timing[&first], DraftVoteTiming::Now); + assert!(matches!( + workspace.node_timing[&second], + DraftVoteTiming::Scheduled { .. } + )); + } + + /// VOTE-TC-024: a node-detail route selects only that node. + #[test] + fn node_prefilter_excludes_every_other_node() { + let selected = Identifier::from([1; 32]); + let other = Identifier::from([2; 32]); + let mut workspace = DpnsVoteWorkspace::new([selected, other]); + workspace.prefilter_node(selected); + + assert_eq!(workspace.selected_node_count(), 1); + assert_eq!(workspace.node_timing[&selected], DraftVoteTiming::Now); + assert_eq!(workspace.node_timing[&other], DraftVoteTiming::Excluded); + } + + /// VOTE-TC-071: Enter advances drafts but submits only from Review; Escape closes drafts. + #[test] + fn keyboard_actions_respect_composer_step() { + let mut workspace = DpnsVoteWorkspace::new([Identifier::from([1; 32])]); + assert_eq!( + workspace.keyboard_action(true, false, true), + ComposerKeyAction::Advance + ); + workspace.step = DpnsVoteComposerStep::Votes; + assert_eq!( + workspace.keyboard_action(true, false, true), + ComposerKeyAction::Advance + ); + workspace.step = DpnsVoteComposerStep::Review; + assert_eq!( + workspace.keyboard_action(true, false, true), + ComposerKeyAction::Submit + ); + assert_eq!( + workspace.keyboard_action(false, true, true), + ComposerKeyAction::CloseDraft + ); + } +} diff --git a/src/ui/state/mod.rs b/src/ui/state/mod.rs index 791c38c6b..99d73f209 100644 --- a/src/ui/state/mod.rs +++ b/src/ui/state/mod.rs @@ -8,6 +8,7 @@ pub mod account_summary; pub mod avatar_cache; pub mod contacts_view; +pub mod dpns_vote_workspace; pub mod global_nav; pub mod hub_selection; pub mod masternodes_view; diff --git a/tests/kittest/masternode_tab.rs b/tests/kittest/masternode_tab.rs index 3439153cc..e28fc3275 100644 --- a/tests/kittest/masternode_tab.rs +++ b/tests/kittest/masternode_tab.rs @@ -261,6 +261,36 @@ fn empty_state_renders_canonical_copy() { }); } +/// VOTE-TC-023: operator navigation exposes Nodes, Voting, and Scheduled and +/// opens the shared full-page composer. +#[test] +fn voting_navigation_routes_to_shared_workspaces() { + 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::RootScreenIdentities); + let app_context = harness.state().current_app_context().clone(); + activate_masternodes_tab(&mut harness, &app_context); + + assert!(harness.query_by_label("Nodes").is_some()); + assert!(harness.query_by_label("Voting").is_some()); + assert!(harness.query_by_label("Scheduled").is_some()); + + harness.get_by_label("Voting").click(); + harness.run_steps(3); + assert_eq!( + harness.state().selected_main_screen, + RootScreenType::RootScreenMasternodes + ); + assert!( + harness + .query_by_label("Step 1 of 3: Nodes and timing") + .is_some() + ); + }); +} + /// 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 From 0c012cc1e90dcd4cf6e8f9ae9f4bff93fe886a40 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 16 Jul 2026 10:49:27 +0000 Subject: [PATCH 003/194] fix(dpns): harden voting operation recovery MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Serialize nonce-consuming submissions across independent operations, make the operation journal network-qualified and fail-closed, recover interrupted work conservatively, require fresh proved state, and prevent scheduled terminal outcomes from being rebroadcast. Co-Authored-By: Codex GPT-5 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/app.rs | 20 +- src/backend_task/contested_names/mod.rs | 381 +++++++++++++----- src/backend_task/error.rs | 26 ++ src/context/dpns_vote_operations.rs | 508 +++++++++++++++++++++--- src/context/dpns_vote_state.rs | 117 +++++- src/context/mod.rs | 121 +++++- 6 files changed, 1006 insertions(+), 167 deletions(-) diff --git a/src/app.rs b/src/app.rs index 8b0d13081..861f76bde 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2070,23 +2070,31 @@ impl App for AppState { ) }) .count(); + let diagnostics = active_context + .dpns_vote_operation_diagnostics(operation_id); if unconfirmed > 0 { - MessageBanner::set_global( + let handle = MessageBanner::set_global( ctx, "The vote was submitted, but DET could not confirm the result yet. DET will keep checking. Do not submit it again.", MessageType::Warning, - ) - .disable_auto_dismiss(); + ); + if !diagnostics.is_empty() { + handle.with_details(&diagnostics); + } + handle.disable_auto_dismiss(); } else if rejected > 0 { - MessageBanner::set_global( + let handle = MessageBanner::set_global( ctx, format!( "{confirmed} of {total} votes were confirmed. Review the remaining {}.", total.saturating_sub(confirmed) ), MessageType::Warning, - ) - .disable_auto_dismiss(); + ); + if !diagnostics.is_empty() { + handle.with_details(&diagnostics); + } + handle.disable_auto_dismiss(); } else if scheduled == total && total > 0 { MessageBanner::set_global( ctx, diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 87bb17b7c..570a8d027 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -79,6 +79,19 @@ fn classify_vote_attempt( } } +fn classify_reconciled_vote( + observed: Option, + requested: ResourceVoteChoice, +) -> Option { + observed.map(|choice| { + if choice == requested { + DpnsVoteTargetStatus::Confirmed + } else { + DpnsVoteTargetStatus::Rejected + } + }) +} + /// 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 @@ -112,6 +125,7 @@ impl AppContext { sdk: &Sdk, sender: crate::utils::egui_mpsc::SenderAsync, ) -> Result { + self.ensure_dpns_vote_recovery(sdk).await?; match task { ContestedResourceTask::QueryDPNSContests => self .query_dpns_contested_resources(sdk, sender) @@ -155,6 +169,33 @@ impl AppContext { } } + async fn ensure_dpns_vote_recovery(self: &Arc, sdk: &Sdk) -> Result<(), TaskError> { + let mut recovered = self.dpns_vote_recovery.lock().await; + if *recovered { + 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(), sdk) + .await?; + } + } + *recovered = true; + Ok(()) + } + fn dpns_vote_target( &self, voter: &QualifiedIdentity, @@ -197,18 +238,44 @@ impl AppContext { operation.targets.iter().any(|outcome| { outcome.target.key.voter_id == scheduled_vote.voter_id && outcome.target.contested_name == scheduled_vote.contested_name - && outcome.status == DpnsVoteTargetStatus::Scheduled }) }) { + let mut target_queued = false; for outcome in &mut operation.targets { - if outcome.target.key.voter_id == scheduled_vote.voter_id - && outcome.target.contested_name == scheduled_vote.contested_name - && outcome.status == DpnsVoteTargetStatus::Scheduled + if outcome.target.key.voter_id != scheduled_vote.voter_id + || outcome.target.contested_name != scheduled_vote.contested_name { - outcome.status = DpnsVoteTargetStatus::Queued; + continue; + } + match outcome.status { + DpnsVoteTargetStatus::Scheduled => { + outcome.status = DpnsVoteTargetStatus::Queued; + target_queued = true; + } + DpnsVoteTargetStatus::Unconfirmed + | DpnsVoteTargetStatus::Queued + | DpnsVoteTargetStatus::Submitting + | DpnsVoteTargetStatus::Confirming => { + return Err(TaskError::DpnsVoteTargetBusy); + } + DpnsVoteTargetStatus::Confirmed => { + self.mark_vote_executed( + scheduled_vote.voter_id.as_slice(), + scheduled_vote.contested_name.clone(), + )?; + return Ok(operation); + } + DpnsVoteTargetStatus::Rejected + | DpnsVoteTargetStatus::FailedBeforeSubmission + | DpnsVoteTargetStatus::NotApplied => { + // An explicit Cast now action is a deliberate retry and + // may create a new operation below. + } } } - return Ok(operation); + if target_queued { + return Ok(operation); + } } let target = self.dpns_vote_target( @@ -225,7 +292,7 @@ impl AppContext { async fn execute_dpns_vote_operation( self: &Arc, - operation: DpnsVoteOperation, + mut operation: DpnsVoteOperation, voters: Vec, sdk: &Sdk, ) -> Result { @@ -234,8 +301,53 @@ impl AppContext { operation.id, )); } - if self.dpns_vote_operation(operation.id)?.is_some() { - self.update_dpns_vote_operation(&operation)?; + let was_persisted = self.dpns_vote_operation(operation.id)?.is_some(); + 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. + self.refresh_dpns_vote_states(sdk).await; + let queued_keys = operation + .targets + .iter() + .filter(|outcome| outcome.status == DpnsVoteTargetStatus::Queued) + .map(|outcome| outcome.target.key.clone()) + .collect::>(); + for key in queued_keys { + let state = self.dpns_current_vote_state(key.voter_id, key.vote_poll_id)?; + if was_persisted { + self.revalidate_queued_dpns_vote_target(operation.id, &key, state)?; + continue; + } + let Some(outcome) = operation + .targets + .iter_mut() + .find(|outcome| outcome.target.key == key) + else { + continue; + }; + match state { + 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 => { + return Err(TaskError::DpnsCurrentVoteUnavailable); + } + } + } + } + + if was_persisted { + operation = self + .dpns_vote_operation(operation.id)? + .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; } else { let scheduled_votes = operation .targets @@ -251,10 +363,29 @@ impl AppContext { VoteTiming::Now => None, }) .collect::>(); - if !scheduled_votes.is_empty() { - self.insert_scheduled_votes(&scheduled_votes)?; - } self.insert_dpns_vote_operation(&operation)?; + if !scheduled_votes.is_empty() + && let Err(error) = self.insert_scheduled_votes(&scheduled_votes) + { + // The journal is authoritative. The legacy table is a + // compatibility mirror, so its failure cannot turn a durable + // schedule into a reported failure that invites a duplicate. + tracing::warn!( + ?error, + operation_id = %operation.id, + "DPNS vote schedule was journaled but its legacy mirror could not be updated" + ); + } + } + + for outcome in operation.targets.iter().filter(|outcome| { + outcome.status == DpnsVoteTargetStatus::Confirmed + && matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + }) { + self.mark_vote_executed( + outcome.target.key.voter_id.as_slice(), + outcome.target.contested_name.clone(), + )?; } let voters_by_id: BTreeMap = voters @@ -283,25 +414,25 @@ impl AppContext { async move { let Some(voter) = voter else { for target in targets { - app_context.update_dpns_vote_target( - operation_id, - &target.key, - DpnsVoteTargetStatus::FailedBeforeSubmission, - Some(DpnsVoteFailure::SubmissionFailed), - )?; + if app_context.claim_dpns_vote_target(operation_id, &target.key)? { + app_context.update_dpns_vote_target( + operation_id, + &target.key, + DpnsVoteTargetStatus::FailedBeforeSubmission, + Some(DpnsVoteFailure::SubmissionFailed), + )?; + } } return Ok::<(), TaskError>(()); }; // One voter's targets are deliberately sequential: PutVote // obtains and consumes the same masternode nonce. + let _dispatch_guard = app_context.dpns_vote_dispatch.acquire(voter_id).await?; for target in targets { - app_context.update_dpns_vote_target( - operation_id, - &target.key, - DpnsVoteTargetStatus::Submitting, - None, - )?; + if !app_context.claim_dpns_vote_target(operation_id, &target.key)? { + continue; + } let attempt = app_context .submit_dpns_vote( &target.contested_name, @@ -332,6 +463,11 @@ impl AppContext { contested_name = %target.contested_name, "DPNS vote was submitted but remains unconfirmed" ); + app_context.record_dpns_vote_diagnostic( + operation_id, + target.key.clone(), + error, + ); } Ok(vote_on_dpns_name::DpnsVoteAttempt::Rejected(error)) => { tracing::warn!( @@ -340,6 +476,11 @@ impl AppContext { contested_name = %target.contested_name, "Platform rejected a DPNS vote" ); + app_context.record_dpns_vote_diagnostic( + operation_id, + target.key.clone(), + error, + ); } Err(error) => { tracing::warn!( @@ -348,6 +489,11 @@ impl AppContext { contested_name = %target.contested_name, "DPNS vote failed before a confirmed submission" ); + app_context.record_dpns_vote_diagnostic( + operation_id, + target.key.clone(), + error, + ); } } app_context.update_dpns_vote_target( @@ -396,12 +542,13 @@ impl AppContext { }; match ResourceVote::fetch_many(sdk, query).await { Ok(votes) - if votes - .get(&poll_id) - .and_then(Option::as_ref) - .is_some_and(|vote| { - vote.resource_vote_choice() == outcome.target.requested_choice - }) => + if classify_reconciled_vote( + votes + .get(&poll_id) + .and_then(Option::as_ref) + .map(ResourceVoteGettersV0::resource_vote_choice), + outcome.target.requested_choice, + ) == Some(DpnsVoteTargetStatus::Confirmed) => { self.cache_confirmed_dpns_vote( outcome.target.key.voter_id, @@ -414,15 +561,45 @@ impl AppContext { DpnsVoteTargetStatus::Confirmed, None, )?; + if matches!(outcome.target.timing, VoteTiming::Scheduled(_)) { + self.mark_vote_executed( + outcome.target.key.voter_id.as_slice(), + outcome.target.contested_name.clone(), + )?; + } + } + Ok(votes) + if classify_reconciled_vote( + votes + .get(&poll_id) + .and_then(Option::as_ref) + .map(ResourceVoteGettersV0::resource_vote_choice), + outcome.target.requested_choice, + ) == Some(DpnsVoteTargetStatus::Rejected) => + { + self.update_dpns_vote_target( + operation_id, + &outcome.target.key, + DpnsVoteTargetStatus::Rejected, + Some(DpnsVoteFailure::PlatformRejected), + )?; } Ok(_) => {} - Err(error) => tracing::warn!( - ?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" - ), + Err(error) => { + let error = TaskError::from(error); + tracing::warn!( + ?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( + operation_id, + outcome.target.key.clone(), + error, + ); + } } } Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated( @@ -466,19 +643,38 @@ impl AppContext { .duration_since(UNIX_EPOCH) .map(|d| d.as_millis() as u64) .unwrap_or(0); - let due: Vec = self - .get_scheduled_votes()? - .into_iter() - .filter(|vote| { - scheduled_vote_is_due( - vote.unix_timestamp, - vote.executed_successfully, - now_ms, - preserve_eligibility_since_ms, - ) - }) - .collect(); - if due.is_empty() { + let mut due_operations = Vec::new(); + let mut in_progress = Vec::new(); + for mut operation in self.dpns_vote_operations()? { + let mut due = false; + for outcome in &mut operation.targets { + let VoteTiming::Scheduled(scheduled_at) = outcome.target.timing else { + continue; + }; + if outcome.status == DpnsVoteTargetStatus::Scheduled + && scheduled_vote_is_due( + scheduled_at, + false, + now_ms, + preserve_eligibility_since_ms, + ) + { + 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); + } + } + if due_operations.is_empty() { return Ok(BackendTaskSuccessResult::ScheduledVoteSweepCompleted { network: self.network, preserve_eligibility_since_ms, @@ -486,67 +682,37 @@ impl AppContext { } 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 => { - tracing::warn!( - contested_name = %vote.contested_name, - "No local voting identity for a scheduled vote; skipping it" - ); - 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)); - } - // Tell the Scheduled Votes screen which votes are now in flight. - let in_progress = castable.iter().map(|(v, _)| v.clone()).collect(); let _ = sender .send(TaskResult::unattributed_success( BackendTaskSuccessResult::ScheduledVotesInProgress(in_progress), )) .await; - let mut groups: BTreeMap> = - BTreeMap::new(); - for (vote, voter) in castable { - groups.entry(vote.voter_id).or_default().push((vote, voter)); - } - let results = stream::iter(groups) - .map(|(_, scheduled)| { + 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 { - let mut results = Vec::with_capacity(scheduled.len()); - for (vote, voter) in scheduled { - let result = match app_context.operation_for_scheduled_vote(&vote, &voter) { - Ok(operation) => app_context - .execute_dpns_vote_operation(operation, vec![voter], &sdk) - .await - .map(|_| ()), - Err(error) => Err(error), - }; - results.push((vote, result)); - } - results + let result = app_context + .execute_dpns_vote_operation(operation, voters, &sdk) + .await + .map(|_| ()); + (operation_id, result) } }) .buffer_unordered(4) .collect::>() .await; - for (vote, result) in results.into_iter().flatten() { + let mut first_error = None; + for (operation_id, result) in results { if let Err(error) = result { tracing::error!( error = %error, - contested_name = %vote.contested_name, - "Failed to cast a due scheduled vote; leaving it for the next sweep" + operation_id = %operation_id, + "Failed to execute a due DPNS vote operation; leaving it for recovery" ); first_error.get_or_insert(error); } @@ -604,6 +770,35 @@ mod tests { assert!(status.holds_lock()); } + #[test] + fn exact_reconciliation_distinguishes_match_rejection_and_absence() { + assert_eq!( + classify_reconciled_vote(Some(ResourceVoteChoice::Lock), ResourceVoteChoice::Lock), + Some(DpnsVoteTargetStatus::Confirmed) + ); + assert_eq!( + classify_reconciled_vote(Some(ResourceVoteChoice::Abstain), ResourceVoteChoice::Lock), + Some(DpnsVoteTargetStatus::Rejected) + ); + assert_eq!( + classify_reconciled_vote(None, ResourceVoteChoice::Lock), + None, + "an absent exact row remains ambiguous and must not release its lock" + ); + } + + #[test] + fn scheduled_terminal_or_unconfirmed_targets_are_not_due_for_rebroadcast() { + for status in [ + DpnsVoteTargetStatus::Unconfirmed, + DpnsVoteTargetStatus::Rejected, + DpnsVoteTargetStatus::FailedBeforeSubmission, + DpnsVoteTargetStatus::Confirmed, + ] { + assert_ne!(status, DpnsVoteTargetStatus::Scheduled); + } + } + /// Migration extends only eligibility windows that overlap its wait. #[test] fn migration_wait_preserves_only_overlapping_vote_eligibility() { diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 237e503ff..09ae71391 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -660,6 +660,32 @@ pub enum TaskError { source: crate::wallet_backend::KvAdapterError, }, + /// An indexed journal row could not be decoded, so unresolved target locks + /// cannot be reconstructed safely. + #[error( + "Saved DPNS voting progress is unreadable. Restore the saved data or remove the damaged voting record before trying again." + )] + DpnsVoteOperationUnreadable { + #[source] + source: crate::wallet_backend::KvAdapterError, + }, + + /// An operation index referenced a missing row, so target locks are unknown. + #[error( + "Saved DPNS voting progress is incomplete. Restore the saved data or remove the damaged voting record before trying again." + )] + DpnsVoteOperationRecordMissing, + + /// A non-terminal operation was found under a different network namespace. + #[error( + "Saved DPNS 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("DPNS voting is stopping. Wait for DET to finish closing, then 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." diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index 79494ac45..a729267cd 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -3,50 +3,139 @@ use super::AppContext; use crate::backend_task::error::TaskError; use crate::model::dpns_voting::{ - DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, - DpnsVoteTargetStatus, VoteTiming, + DpnsCurrentVoteState, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, + DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, }; use crate::wallet_backend::{DetKv, DetScope, KvAdapterError}; +use dash_sdk::dpp::dashcore::Network; use dash_sdk::platform::Identifier; +use std::sync::Arc; -const OPERATION_INDEX_KEY: &str = "det:dpns_vote_operations:v1"; -const OPERATION_KEY_PREFIX: &str = "det:dpns_vote_operation:v1:"; +const LEGACY_OPERATION_INDEX_KEY: &str = "det:dpns_vote_operations:v1"; +const LEGACY_OPERATION_KEY_PREFIX: &str = "det:dpns_vote_operation:v1:"; +const OPERATION_INDEX_KEY_PREFIX: &str = "det:dpns_vote_operations:v2:"; +const OPERATION_KEY_PREFIX: &str = "det:dpns_vote_operation:v2:"; -fn operation_key(id: DpnsVoteOperationId) -> String { - format!("{OPERATION_KEY_PREFIX}{id}") +fn network_tag(network: Network) -> &'static str { + match network { + Network::Mainnet => "mainnet", + Network::Testnet => "testnet", + Network::Devnet => "devnet", + Network::Regtest => "regtest", + } +} + +fn operation_index_key(network: Network) -> String { + format!("{OPERATION_INDEX_KEY_PREFIX}{}", network_tag(network)) +} + +fn operation_key(network: Network, id: DpnsVoteOperationId) -> String { + format!("{OPERATION_KEY_PREFIX}{}:{id}", network_tag(network)) +} + +fn legacy_operation_key(id: DpnsVoteOperationId) -> String { + format!("{LEGACY_OPERATION_KEY_PREFIX}{id}") } fn operation_err(source: KvAdapterError) -> TaskError { TaskError::DpnsVoteOperationStorage { source } } -fn load_operation_ids(kv: &DetKv) -> Result, TaskError> { - kv.get(DetScope::Global, OPERATION_INDEX_KEY) +fn unreadable_operation_err(source: KvAdapterError) -> TaskError { + TaskError::DpnsVoteOperationUnreadable { source } +} + +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(operation_err) + .map_err(unreadable_operation_err) } -fn load_operations(kv: &DetKv) -> Result, TaskError> { +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 migrate_legacy_operations(kv: &DetKv, network: Network) -> Result<(), TaskError> { + let legacy_ids: Vec<[u8; 16]> = kv + .get(DetScope::Global, LEGACY_OPERATION_INDEX_KEY) + .map_err(unreadable_operation_err)? + .unwrap_or_default(); + if legacy_ids.is_empty() { + return Ok(()); + } + + let mut qualified_ids = load_operation_ids(kv, network)?; + let mut changed = false; + for bytes in legacy_ids { + let id = DpnsVoteOperationId::from_bytes(bytes); + if qualified_ids.contains(&bytes) { + continue; + } + let operation: DpnsVoteOperation = kv + .get(DetScope::Global, &legacy_operation_key(id)) + .map_err(unreadable_operation_err)? + .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; + if !operation_matches_network(&operation, network)? { + continue; + } + kv.put(DetScope::Global, &operation_key(network, id), &operation) + .map_err(operation_err)?; + qualified_ids.push(bytes); + changed = true; + } + if changed { + kv.put( + DetScope::Global, + &operation_index_key(network), + &qualified_ids, + ) + .map_err(operation_err)?; + } + Ok(()) +} + +fn load_operations(kv: &DetKv, network: Network) -> Result, TaskError> { + migrate_legacy_operations(kv, network)?; let mut operations = Vec::new(); - for bytes in load_operation_ids(kv)? { + for bytes in load_operation_ids(kv, network)? { let id = DpnsVoteOperationId::from_bytes(bytes); - match kv.get(DetScope::Global, &operation_key(id)) { - Ok(Some(operation)) => operations.push(operation), - Ok(None) => {} - Err(error) => { - tracing::warn!( - operation_id = %id, - error = ?error, - "Skipping unreadable DPNS vote operation" - ); - } + let operation: DpnsVoteOperation = kv + .get(DetScope::Global, &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 persist_operation(kv: &DetKv, operation: &DpnsVoteOperation) -> Result<(), TaskError> { - let conflict = load_operations(kv)?.iter().any(|existing| { +fn persist_operation( + kv: &DetKv, + network: Network, + operation: &DpnsVoteOperation, +) -> Result<(), TaskError> { + if !operation_matches_network(operation, network)? { + return Err(TaskError::DpnsVoteJournalNetworkMismatch); + } + let conflict = load_operations(kv, network)?.iter().any(|existing| { existing.id != operation.id && existing.targets.iter().any(|existing_outcome| { existing_outcome.status.holds_lock() @@ -60,17 +149,34 @@ fn persist_operation(kv: &DetKv, operation: &DpnsVoteOperation) -> Result<(), Ta return Err(TaskError::DpnsVoteTargetBusy); } - kv.put(DetScope::Global, &operation_key(operation.id), operation) - .map_err(operation_err)?; - let mut ids = load_operation_ids(kv)?; + kv.put( + DetScope::Global, + &operation_key(network, operation.id), + operation, + ) + .map_err(operation_err)?; + let mut ids = load_operation_ids(kv, network)?; if !ids.contains(&operation.id.to_bytes()) { ids.push(operation.id.to_bytes()); - kv.put(DetScope::Global, OPERATION_INDEX_KEY, &ids) + kv.put(DetScope::Global, &operation_index_key(network), &ids) .map_err(operation_err)?; } Ok(()) } +fn write_existing_operation( + kv: &DetKv, + network: Network, + operation: &DpnsVoteOperation, +) -> Result<(), TaskError> { + kv.put( + DetScope::Global, + &operation_key(network, operation.id), + operation, + ) + .map_err(operation_err) +} + impl AppContext { /// Persist a reviewed operation and atomically acquire all unresolved locks. pub fn insert_dpns_vote_operation( @@ -89,8 +195,9 @@ impl AppContext { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); let kv = self.det_kv()?; - let mut existing_operations = load_operations(&kv)?; - for existing in &mut existing_operations { + let mut replaced = Vec::new(); + for mut existing in load_operations(&kv, self.network)? { + let original = existing.clone(); let mut changed = false; for existing_outcome in &mut existing.targets { if existing_outcome.status == DpnsVoteTargetStatus::Scheduled @@ -99,16 +206,27 @@ impl AppContext { && new_outcome.target.key == existing_outcome.target.key }) { - existing_outcome.status = DpnsVoteTargetStatus::NotApplied; changed = true; + existing_outcome.status = DpnsVoteTargetStatus::NotApplied; } } if changed { - kv.put(DetScope::Global, &operation_key(existing.id), existing) - .map_err(operation_err)?; + if let Err(error) = write_existing_operation(&kv, self.network, &existing) { + for previous in replaced { + write_existing_operation(&kv, self.network, &previous)?; + } + return Err(error); + } + replaced.push(original); + } + } + if let Err(error) = persist_operation(&kv, self.network, operation) { + for original in replaced { + write_existing_operation(&kv, self.network, &original)?; } + return Err(error); } - persist_operation(&kv, operation) + Ok(()) } /// Persist updated target statuses while retaining the original operation ID. @@ -120,7 +238,7 @@ impl AppContext { .dpns_vote_operation_guard .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - persist_operation(&self.det_kv()?, operation) + persist_operation(&self.det_kv()?, self.network, operation) } /// Load every operation for this network, including completed history. @@ -130,7 +248,7 @@ impl AppContext { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); let kv = self.det_kv()?; - let mut operations = load_operations(&kv)?; + let mut operations = load_operations(&kv, self.network)?; for legacy in self.get_scheduled_votes()? { if operations.iter().any(|operation| { operation.targets.iter().any(|outcome| { @@ -155,7 +273,7 @@ impl AppContext { if legacy.executed_successfully { operation.targets[0].status = DpnsVoteTargetStatus::Confirmed; } - persist_operation(&kv, &operation)?; + persist_operation(&kv, self.network, &operation)?; operations.push(operation); } Ok(operations) @@ -166,9 +284,21 @@ impl AppContext { &self, id: DpnsVoteOperationId, ) -> Result, TaskError> { - self.det_kv()? - .get(DetScope::Global, &operation_key(id)) - .map_err(operation_err) + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let kv = self.det_kv()?; + migrate_legacy_operations(&kv, self.network)?; + let operation = kv + .get(DetScope::Global, &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. @@ -198,8 +328,8 @@ impl AppContext { .unwrap_or_else(std::sync::PoisonError::into_inner); let kv = self.det_kv()?; let Some(mut operation): Option = kv - .get(DetScope::Global, &operation_key(operation_id)) - .map_err(operation_err)? + .get(DetScope::Global, &operation_key(self.network, operation_id)) + .map_err(unreadable_operation_err)? else { return Ok(()); }; @@ -211,7 +341,140 @@ impl AppContext { outcome.status = status; outcome.failure = failure; } - persist_operation(&kv, &operation) + persist_operation(&kv, self.network, &operation) + } + + /// 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 { + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let kv = self.det_kv()?; + let Some(mut operation): Option = kv + .get(DetScope::Global, &operation_key(self.network, operation_id)) + .map_err(unreadable_operation_err)? + else { + return Ok(false); + }; + let Some(outcome) = operation + .targets + .iter_mut() + .find(|outcome| outcome.target.key == *key) + else { + return Ok(false); + }; + if outcome.status != DpnsVoteTargetStatus::Queued { + return Ok(false); + } + outcome.status = DpnsVoteTargetStatus::Submitting; + outcome.failure = None; + persist_operation(&kv, self.network, &operation)?; + Ok(true) + } + + /// 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 { + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let kv = self.det_kv()?; + let Some(mut operation): Option = kv + .get(DetScope::Global, &operation_key(self.network, operation_id)) + .map_err(unreadable_operation_err)? + else { + return Ok(false); + }; + let Some(outcome) = operation + .targets + .iter_mut() + .find(|outcome| outcome.target.key == *key) + else { + return Ok(false); + }; + if outcome.status != DpnsVoteTargetStatus::Queued { + return Ok(false); + } + match state { + 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 = DpnsVoteTargetStatus::Unconfirmed; + outcome.failure = Some(DpnsVoteFailure::CurrentVoteUnavailable); + } + } + let still_queued = outcome.status == DpnsVoteTargetStatus::Queued; + persist_operation(&kv, self.network, &operation)?; + Ok(still_queued) + } + + /// Convert crash-interrupted transitions into conservative reconciliation. + pub(crate) fn recover_interrupted_dpns_vote_operations(&self) -> Result<(), TaskError> { + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let kv = self.det_kv()?; + for mut operation in load_operations(&kv, self.network)? { + let mut changed = false; + for outcome in &mut operation.targets { + if matches!( + outcome.status, + DpnsVoteTargetStatus::Submitting | DpnsVoteTargetStatus::Confirming + ) { + outcome.status = DpnsVoteTargetStatus::Unconfirmed; + outcome.failure = Some(DpnsVoteFailure::ResultUnconfirmed); + changed = true; + } + } + if changed { + persist_operation(&kv, self.network, &operation)?; + } + } + Ok(()) + } + + pub(crate) fn record_dpns_vote_diagnostic( + &self, + operation_id: DpnsVoteOperationId, + key: DpnsVoteTargetKey, + error: TaskError, + ) { + self.dpns_vote_diagnostics + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert((operation_id, key), Arc::new(error)); + } + + 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() } /// Release a not-yet-submitting scheduled target after explicit cancellation. @@ -266,6 +529,7 @@ mod tests { 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; fn kv() -> DetKv { @@ -293,10 +557,19 @@ mod tests { #[test] fn unresolved_target_rejects_a_competing_operation() { let kv = kv(); - persist_operation(&kv, &operation(DpnsVoteTargetStatus::Submitting)).unwrap(); + persist_operation( + &kv, + Network::Testnet, + &operation(DpnsVoteTargetStatus::Submitting), + ) + .unwrap(); - let error = persist_operation(&kv, &operation(DpnsVoteTargetStatus::Queued)) - .expect_err("the exact target must stay locked"); + let error = persist_operation( + &kv, + Network::Testnet, + &operation(DpnsVoteTargetStatus::Queued), + ) + .expect_err("the exact target must stay locked"); assert!(matches!(error, TaskError::DpnsVoteTargetBusy)); } @@ -305,9 +578,9 @@ mod tests { fn unconfirmed_lock_survives_journal_reload() { let kv = kv(); let operation = operation(DpnsVoteTargetStatus::Unconfirmed); - persist_operation(&kv, &operation).unwrap(); + persist_operation(&kv, Network::Testnet, &operation).unwrap(); - let restored = load_operations(&kv).unwrap(); + let restored = load_operations(&kv, Network::Testnet).unwrap(); assert_eq!(restored, vec![operation]); assert!(restored[0].targets[0].status.holds_lock()); } @@ -316,11 +589,146 @@ mod tests { #[test] fn unrelated_target_can_be_persisted() { let kv = kv(); - persist_operation(&kv, &operation(DpnsVoteTargetStatus::Confirming)).unwrap(); + 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, &unrelated).unwrap(); - assert_eq!(load_operations(&kv).unwrap().len(), 2); + persist_operation(&kv, Network::Testnet, &unrelated).unwrap(); + assert_eq!(load_operations(&kv, Network::Testnet).unwrap().len(), 2); + } + + /// 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(); + 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" + ); + } + + #[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()); + } + + #[test] + fn legacy_journal_migrates_idempotently_into_network_namespace() { + let kv = kv(); + let operation = operation(DpnsVoteTargetStatus::Scheduled); + kv.put( + DetScope::Global, + &legacy_operation_key(operation.id), + &operation, + ) + .unwrap(); + kv.put( + DetScope::Global, + LEGACY_OPERATION_INDEX_KEY, + &vec![operation.id.to_bytes()], + ) + .unwrap(); + + assert_eq!( + load_operations(&kv, Network::Testnet).unwrap(), + vec![operation.clone()] + ); + assert_eq!( + load_operations(&kv, Network::Testnet).unwrap(), + vec![operation], + "repeating migration must not duplicate the operation" + ); + } + + #[test] + fn mismatched_unresolved_legacy_record_fails_closed() { + let kv = kv(); + let operation = operation(DpnsVoteTargetStatus::Unconfirmed); + kv.put( + DetScope::Global, + &legacy_operation_key(operation.id), + &operation, + ) + .unwrap(); + kv.put( + DetScope::Global, + LEGACY_OPERATION_INDEX_KEY, + &vec![operation.id.to_bytes()], + ) + .unwrap(); + + assert!(matches!( + load_operations(&kv, Network::Mainnet), + Err(TaskError::DpnsVoteJournalNetworkMismatch) + )); + } + + #[test] + fn mismatched_terminal_legacy_record_is_safely_ignored() { + let kv = kv(); + let operation = operation(DpnsVoteTargetStatus::Confirmed); + kv.put( + DetScope::Global, + &legacy_operation_key(operation.id), + &operation, + ) + .unwrap(); + kv.put( + DetScope::Global, + LEGACY_OPERATION_INDEX_KEY, + &vec![operation.id.to_bytes()], + ) + .unwrap(); + + assert!(load_operations(&kv, Network::Mainnet).unwrap().is_empty()); + } + + #[test] + fn interrupted_submission_recovers_to_unconfirmed() { + let kv = kv(); + let mut operation = operation(DpnsVoteTargetStatus::Submitting); + persist_operation(&kv, Network::Testnet, &operation).unwrap(); + + for outcome in &mut operation.targets { + if matches!( + outcome.status, + DpnsVoteTargetStatus::Submitting | DpnsVoteTargetStatus::Confirming + ) { + outcome.status = DpnsVoteTargetStatus::Unconfirmed; + outcome.failure = Some(DpnsVoteFailure::ResultUnconfirmed); + } + } + persist_operation(&kv, Network::Testnet, &operation).unwrap(); + + let restored = load_operations(&kv, Network::Testnet).unwrap(); + assert_eq!( + restored[0].targets[0].status, + DpnsVoteTargetStatus::Unconfirmed + ); } } diff --git a/src/context/dpns_vote_state.rs b/src/context/dpns_vote_state.rs index 4de03e981..3116cb3fa 100644 --- a/src/context/dpns_vote_state.rs +++ b/src/context/dpns_vote_state.rs @@ -5,6 +5,7 @@ use crate::backend_task::error::TaskError; use crate::model::dpns_voting::DpnsCurrentVoteState; use crate::wallet_backend::{DetKv, DetScope, KvAdapterError}; use dash_sdk::Sdk; +use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; @@ -21,8 +22,10 @@ use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::time::{SystemTime, UNIX_EPOCH}; -const CURRENT_VOTES_KEY: &str = "det:dpns_current_votes:v1"; +const LEGACY_CURRENT_VOTES_KEY: &str = "det:dpns_current_votes:v1"; +const CURRENT_VOTES_KEY_PREFIX: &str = "det:dpns_current_votes:v2:"; const VOTE_QUERY_PAGE_SIZE: u16 = 100; +const CURRENT_VOTE_MAX_AGE_MS: u64 = 120_000; #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)] struct StoredCurrentVotes { @@ -35,27 +38,70 @@ fn vote_state_err(source: KvAdapterError) -> TaskError { TaskError::DpnsVoteOperationStorage { source } } +fn current_votes_key(network: Network) -> String { + let network = match network { + Network::Mainnet => "mainnet", + Network::Testnet => "testnet", + Network::Devnet => "devnet", + Network::Regtest => "regtest", + }; + format!("{CURRENT_VOTES_KEY_PREFIX}{network}") +} + fn load_snapshot( kv: &DetKv, + network: Network, voter_id: &Identifier, ) -> Result, TaskError> { - kv.get(DetScope::Identity(&voter_id.to_buffer()), CURRENT_VOTES_KEY) - .map_err(vote_state_err) + let scope = DetScope::Identity(&voter_id.to_buffer()); + if let Some(snapshot) = kv + .get(scope, ¤t_votes_key(network)) + .map_err(vote_state_err)? + { + return Ok(Some(snapshot)); + } + let legacy = kv + .get(scope, LEGACY_CURRENT_VOTES_KEY) + .map_err(vote_state_err)?; + if let Some(snapshot) = &legacy { + save_snapshot(kv, network, voter_id, snapshot)?; + } + Ok(legacy) } fn save_snapshot( kv: &DetKv, + network: Network, voter_id: &Identifier, snapshot: &StoredCurrentVotes, ) -> Result<(), TaskError> { kv.put( DetScope::Identity(&voter_id.to_buffer()), - CURRENT_VOTES_KEY, + ¤t_votes_key(network), snapshot, ) .map_err(vote_state_err) } +fn snapshot_vote_state( + snapshot: Option, + vote_poll_id: Identifier, + checked_at_ms: u64, +) -> DpnsCurrentVoteState { + match snapshot { + None => DpnsCurrentVoteState::Checking, + Some(snapshot) + if checked_at_ms.saturating_sub(snapshot.updated_at) > CURRENT_VOTE_MAX_AGE_MS => + { + DpnsCurrentVoteState::Checking + } + Some(snapshot) if !snapshot.available => DpnsCurrentVoteState::Unavailable, + Some(snapshot) => { + DpnsCurrentVoteState::Available(snapshot.votes.get(&vote_poll_id.to_buffer()).copied()) + } + } +} + impl AppContext { /// Build the exact Platform vote-poll ID for one normalized DPNS label. pub fn dpns_vote_poll_id(&self, name: &str) -> Result { @@ -87,13 +133,11 @@ impl AppContext { voter_id: Identifier, vote_poll_id: Identifier, ) -> Result { - Ok(match load_snapshot(&self.det_kv()?, &voter_id)? { - None => DpnsCurrentVoteState::Checking, - Some(snapshot) if !snapshot.available => DpnsCurrentVoteState::Unavailable, - Some(snapshot) => DpnsCurrentVoteState::Available( - snapshot.votes.get(&vote_poll_id.to_buffer()).copied(), - ), - }) + Ok(snapshot_vote_state( + load_snapshot(&self.det_kv()?, self.network, &voter_id)?, + vote_poll_id, + now_ms(), + )) } /// Refresh proved vote state once per loaded masternode, paging only as needed. @@ -117,6 +161,7 @@ impl AppContext { .map(|voter| { let sdk = sdk.clone(); let kv = kv.clone(); + let network = self.network; async move { let voter_id = voter.identity.id(); match fetch_votes_for_voter(&sdk, voter_id).await { @@ -126,7 +171,7 @@ impl AppContext { updated_at: now_ms(), votes, }; - if let Err(error) = save_snapshot(&kv, &voter_id, &snapshot) { + if let Err(error) = save_snapshot(&kv, network, &voter_id, &snapshot) { tracing::warn!( ?error, voter_id = %voter_id, @@ -140,7 +185,9 @@ impl AppContext { updated_at: now_ms(), votes: BTreeMap::new(), }; - if let Err(storage_error) = save_snapshot(&kv, &voter_id, &snapshot) { + if let Err(storage_error) = + save_snapshot(&kv, network, &voter_id, &snapshot) + { tracing::warn!( ?storage_error, voter_id = %voter_id, @@ -169,11 +216,11 @@ impl AppContext { choice: ResourceVoteChoice, ) -> Result<(), TaskError> { let kv = self.det_kv()?; - let mut snapshot = load_snapshot(&kv, &voter_id)?.unwrap_or_default(); + let mut snapshot = load_snapshot(&kv, self.network, &voter_id)?.unwrap_or_default(); snapshot.available = true; snapshot.updated_at = now_ms(); snapshot.votes.insert(vote_poll_id.to_buffer(), choice); - save_snapshot(&kv, &voter_id, &snapshot) + save_snapshot(&kv, self.network, &voter_id, &snapshot) } } @@ -241,9 +288,12 @@ mod tests { updated_at: 3, votes: BTreeMap::from([(poll.to_buffer(), ResourceVoteChoice::Lock)]), }; - save_snapshot(&kv, &voter, &snapshot).unwrap(); + save_snapshot(&kv, Network::Testnet, &voter, &snapshot).unwrap(); - assert_eq!(load_snapshot(&kv, &voter).unwrap(), Some(snapshot)); + assert_eq!( + load_snapshot(&kv, Network::Testnet, &voter).unwrap(), + Some(snapshot) + ); } /// VOTE-TC-007: query failure is represented explicitly, never as no vote. @@ -260,4 +310,37 @@ mod tests { 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(), + }; + 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)]), + }; + + assert_eq!( + snapshot_vote_state(Some(snapshot), poll, CURRENT_VOTE_MAX_AGE_MS + 2), + DpnsCurrentVoteState::Checking + ); + } } diff --git a/src/context/mod.rs b/src/context/mod.rs index ab896bf3a..f91c59f79 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -20,6 +20,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; @@ -49,7 +50,7 @@ use dash_sdk::platform::Identifier; use egui::Context; use migration_status::MigrationStatus; use platform_wallet_storage::secrets::SecretStore; -use std::collections::{BTreeMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::PathBuf; use std::str::FromStr as _; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; @@ -80,6 +81,54 @@ impl Drop for ContactRequestActionClaim<'_> { } } +const MAX_CONCURRENT_DPNS_VOTERS: usize = 4; + +#[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, @@ -161,6 +210,14 @@ pub struct AppContext { contact_request_actions_in_flight: Mutex>, /// Serializes operation journal writes and target-lock acquisition. dpns_vote_operation_guard: Mutex<()>, + /// Serializes all nonce-consuming vote submissions per voter across tasks, + /// while bounding unrelated voters globally. + pub(crate) dpns_vote_dispatch: DpnsVoteDispatchCoordinator, + /// Runs crash recovery exactly once before this context accepts vote work. + pub(crate) dpns_vote_recovery: tokio::sync::Mutex, + /// Full in-process diagnostics keyed to sanitized durable outcomes. + dpns_vote_diagnostics: + Mutex>>, /// 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>, @@ -441,6 +498,9 @@ impl AppContext { migration_run: tokio::sync::Mutex::new(()), contact_request_actions_in_flight: Mutex::new(HashSet::new()), dpns_vote_operation_guard: Mutex::new(()), + dpns_vote_dispatch: DpnsVoteDispatchCoordinator::default(), + dpns_vote_recovery: tokio::sync::Mutex::new(false), + dpns_vote_diagnostics: Mutex::new(BTreeMap::new()), pending_wallet_selection: Mutex::new(None), selected_wallet_hash: Mutex::new(selected_wallet_hash), selected_single_key_hash: Mutex::new(selected_single_key_hash), @@ -1935,4 +1995,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); + } } From ad308095345eb07f5479984d0d79070623ef11b0 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 16 Jul 2026 10:48:14 +0000 Subject: [PATCH 004/194] feat(dpns): preserve voting center route choices MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Carry exact DPNS vote choices through the one-shot operator route so bulk review does not silently replace them with defaults. Co-Authored-By: Codex GPT-5 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/context/mod.rs | 63 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 58 insertions(+), 5 deletions(-) diff --git a/src/context/mod.rs b/src/context/mod.rs index f91c59f79..121389fc0 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -45,6 +45,7 @@ use dash_sdk::dpp::state_transition::batch_transition::methods::StateTransitionC use dash_sdk::dpp::system_data_contracts::{SystemDataContract, load_system_data_contract}; use dash_sdk::dpp::version::PlatformVersion; use dash_sdk::dpp::version::v11::PLATFORM_V11; +use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; use dash_sdk::platform::DataContract; use dash_sdk::platform::Identifier; use egui::Context; @@ -72,6 +73,15 @@ pub(crate) struct ContactRequestActionClaim<'a> { request_id: Identifier, } +/// One-shot navigation into the Masternodes DPNS operator workflow. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DpnsOperatorRoute { + Voting { + choices: BTreeMap, + }, + Scheduled, +} + impl Drop for ContactRequestActionClaim<'_> { fn drop(&mut self) { self.registry @@ -233,7 +243,7 @@ pub struct AppContext { /// `pending_wallet_selection`). pub(crate) pending_identity_selection: Mutex>, /// One-shot DPNS deep link consumed by the Masternodes Voting Center. - pending_dpns_voting_contests: Mutex>>, + pending_dpns_operator_route: Mutex>, /// Cached fee multiplier permille from current epoch (1000 = 1x, 2000 = 2x) /// Updated when epoch info is fetched from Platform fee_multiplier_permille: AtomicU64, @@ -506,7 +516,7 @@ impl AppContext { selected_single_key_hash: Mutex::new(selected_single_key_hash), selected_identity_id: Mutex::new(None), pending_identity_selection: Mutex::new(None), - pending_dpns_voting_contests: Mutex::new(None), + pending_dpns_operator_route: Mutex::new(None), fee_multiplier_permille: AtomicU64::new( PlatformFeeEstimator::DEFAULT_FEE_MULTIPLIER_PERMILLE, ), @@ -674,15 +684,33 @@ impl AppContext { /// Route DPNS contest browsing into the shared Masternodes Voting Center. pub fn route_to_dpns_voting_center(&self, contested_names: Vec) { + self.route_to_dpns_operator(DpnsOperatorRoute::Voting { + choices: contested_names + .into_iter() + .map(|name| (name, ResourceVoteChoice::Abstain)) + .collect(), + }); + } + + /// Route to the shared Masternodes DPNS operator workflow. + pub fn route_to_dpns_operator(&self, route: DpnsOperatorRoute) { *self - .pending_dpns_voting_contests + .pending_dpns_operator_route .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(contested_names); + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(route); } /// Consume a one-shot DPNS β†’ Masternodes Voting Center deep link. pub fn take_dpns_voting_center_route(&self) -> Option> { - self.pending_dpns_voting_contests + match self.take_dpns_operator_route()? { + DpnsOperatorRoute::Voting { choices } => Some(choices.into_keys().collect()), + DpnsOperatorRoute::Scheduled => None, + } + } + + /// Consume a one-shot DPNS operator deep link. + pub fn take_dpns_operator_route(&self) -> Option { + self.pending_dpns_operator_route .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .take() @@ -1593,6 +1621,7 @@ pub(crate) const fn default_platform_version(_network: &Network) -> &'static Pla #[cfg(test)] mod tests { use super::*; + use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; #[test] fn wallet_name_with_spaces_is_url_encoded() { @@ -1604,6 +1633,30 @@ mod tests { assert!(!url.contains(' ')); } + /// VOTE-TC-023: the DPNS deep link preserves each exact selected choice. + #[test] + fn dpns_voting_center_route_preserves_selected_choices() { + let tmp = tempfile::tempdir().expect("tempdir"); + let ctx = crate::context::test_support::test_app_context(tmp.path()); + let candidate = Identifier::from([7; 32]); + let choices = BTreeMap::from([ + ("alice".to_owned(), ResourceVoteChoice::Lock), + ( + "dominguez".to_owned(), + ResourceVoteChoice::TowardsIdentity(candidate), + ), + ]); + + ctx.route_to_dpns_operator(DpnsOperatorRoute::Voting { + choices: choices.clone(), + }); + + assert_eq!( + ctx.take_dpns_operator_route(), + Some(DpnsOperatorRoute::Voting { choices }) + ); + } + // ── FR-6 resolution-layer boundary (B1) ────────────────────────────────── /// Build an offline, wired `AppContext` (no network I/O) so the identity From a3c67c3ca8cb18cb8f953d682c0c68d991385c32 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 16 Jul 2026 11:27:38 +0000 Subject: [PATCH 005/194] fix(dpns): make voting review safe and explicit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Preserve exact routed choices, require explicit node selection, keep healthy targets usable when another node is blocked, render proved-state uncertainty honestly, and consolidate scheduled-vote management under Masternodes with guarded actions and readable review details. Co-Authored-By: Codex GPT-5 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- docs/user-stories.md | 5 +- src/context/contested_names_db.rs | 53 +- src/model/contested_name.rs | 10 + .../dpns_subscreen_chooser_panel.rs | 4 - src/ui/dpns/dpns_contested_names_screen.rs | 21 +- src/ui/masternodes/card.rs | 45 +- src/ui/masternodes/detail_screen.rs | 68 +- src/ui/masternodes/list_screen.rs | 136 +++- src/ui/masternodes/voting_center.rs | 617 ++++++++++++++---- src/ui/state/dpns_vote_workspace.rs | 82 ++- tests/kittest/masternode_tab.rs | 27 + 11 files changed, 859 insertions(+), 209 deletions(-) diff --git a/docs/user-stories.md b/docs/user-stories.md index 13fea7609..e368639f5 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -694,7 +694,8 @@ As a masternode operator, I want to vote on contested DPNS name registrations so As a masternode operator, I want to schedule votes for later execution so that I can plan my voting strategy in advance. - Set vote to be cast at a future time. -- View and manage scheduled votes. +- View and manage scheduled votes under Masternodes β†’ Scheduled; the former DPNS + scheduled-votes entry redirects to this shared operator view. - Scheduled and immediate votes share the same target locks and result states. - An ambiguous result remains visible for checking and is never automatically rebroadcast. @@ -704,6 +705,8 @@ As a masternode operator, I want to schedule votes for later execution so that I 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. - "Set all" option for batch vote assignment. +- Nodes are selected explicitly; "Set all" changes timing only for selected nodes. +- Nodes without a loaded voting key remain visible but cannot be selected. - Per-node timing overrides and multi-contest selections create exact node Γ— contest targets. - Immediate and scheduled targets submitted together belong to one operation. diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 199fe03bd..d3e2a0e0e 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -8,7 +8,10 @@ use super::AppContext; use crate::backend_task::error::TaskError; -use crate::model::contested_name::{ContestState, Contestant, ContestedName}; +use crate::model::contested_name::{ + ContestState, Contestant, ContestedName, MasternodeVoteStateSummary, +}; +use crate::model::dpns_voting::DpnsCurrentVoteState; use crate::wallet_backend::{DetScope, KvAdapterError}; use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::data_contract::document_type::DocumentTypeRef; @@ -75,6 +78,16 @@ fn contest_duration_for_network(network: Network) -> Duration { } } +fn vote_state_summary(states: &[DpnsCurrentVoteState]) -> MasternodeVoteStateSummary { + if states.contains(&DpnsCurrentVoteState::Checking) { + MasternodeVoteStateSummary::Checking + } else if states.contains(&DpnsCurrentVoteState::Unavailable) { + MasternodeVoteStateSummary::Unavailable + } else { + MasternodeVoteStateSummary::Ready + } +} + impl StoredContestedName { fn to_contested_name(&self, network: Network) -> ContestedName { let contest_duration = contest_duration_for_network(network); @@ -213,18 +226,21 @@ impl AppContext { .iter() .filter(|contest| contest.is_open_for_voter(&voter_id)) .count(); - let needs_vote_count = contests + let states = contests .iter() .filter(|contest| contest.is_open_for_voter(&voter_id)) - .filter(|contest| { + .map(|contest| { self.dpns_vote_poll_id(&contest.normalized_contested_name) .ok() .and_then(|poll_id| self.dpns_current_vote_state(voter_id, poll_id).ok()) - == Some(crate::model::dpns_voting::DpnsCurrentVoteState::Available( - None, - )) + .unwrap_or(DpnsCurrentVoteState::Unavailable) }) + .collect::>(); + let needs_vote_count = states + .iter() + .filter(|state| **state == DpnsCurrentVoteState::Available(None)) .count(); + let vote_state = vote_state_summary(&states); let has_scheduled_vote = self .get_scheduled_votes()? @@ -234,6 +250,7 @@ impl AppContext { Ok(crate::model::contested_name::MasternodeContestSummary { open_contest_count, needs_vote_count, + vote_state, has_scheduled_vote, }) } @@ -553,4 +570,28 @@ mod tests { fn contest_key_is_prefixed_with_normalized_name() { assert_eq!(contested_name_key("dash"), "det:contested_name:dash"); } + + #[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 card_summary_does_not_treat_unavailable_as_all_votes_cast() { + assert_eq!( + vote_state_summary(&[ + DpnsCurrentVoteState::Available(None), + DpnsCurrentVoteState::Unavailable, + ]), + MasternodeVoteStateSummary::Unavailable + ); + } } diff --git a/src/model/contested_name.rs b/src/model/contested_name.rs index 09f72d8c5..0b6fb4634 100644 --- a/src/model/contested_name.rs +++ b/src/model/contested_name.rs @@ -47,12 +47,22 @@ impl ContestedName { /// (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). +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub enum MasternodeVoteStateSummary { + #[default] + Ready, + Checking, + Unavailable, +} + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct MasternodeContestSummary { /// 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 every active contest has a proved current-vote state. + 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. pub has_scheduled_vote: bool, diff --git a/src/ui/components/dpns_subscreen_chooser_panel.rs b/src/ui/components/dpns_subscreen_chooser_panel.rs index 38fe91295..c51291031 100644 --- a/src/ui/components/dpns_subscreen_chooser_panel.rs +++ b/src/ui/components/dpns_subscreen_chooser_panel.rs @@ -29,10 +29,6 @@ pub fn add_dpns_subscreen_chooser_panel(ui: &mut Ui, app_context: &AppContext) - DPNSSubscreen::Owned, RootScreenType::RootScreenDPNSOwnedNames, ), - ( - DPNSSubscreen::ScheduledVotes, - RootScreenType::RootScreenDPNSScheduledVotes, - ), ] .into_iter() .map(|(subscreen, target)| { diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index c97296ccd..07b606e8c 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -19,7 +19,7 @@ use crate::backend_task::BackendTask; use crate::backend_task::contested_names::{ContestedResourceTask, ScheduledDPNSVote}; use crate::backend_task::error::TaskError; use crate::backend_task::identity::IdentityTask; -use crate::context::AppContext; +use crate::context::{AppContext, DpnsOperatorRoute}; use crate::model::contested_name::{ContestState, ContestedName}; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteTarget, DpnsVoteTargetKey, @@ -1991,6 +1991,11 @@ impl ScreenLike for DPNSScreen { } fn ui(&mut self, ui: &mut egui::Ui) -> AppAction { + if self.dpns_subscreen == DPNSSubscreen::ScheduledVotes { + self.app_context + .route_to_dpns_operator(DpnsOperatorRoute::Scheduled); + return AppAction::SetMainScreen(RootScreenType::RootScreenMasternodes); + } let ctx = ui.ctx().clone(); let ctx = &ctx; let has_identity_that_can_register = !self.user_identities.is_empty(); @@ -2083,12 +2088,14 @@ impl ScreenLike for DPNSScreen { // If user clicked "Apply Votes" in the top bar if action == AppAction::Custom("Vote".to_string()) { - self.app_context.route_to_dpns_voting_center( - self.selected_votes - .iter() - .map(|vote| vote.contested_name.clone()) - .collect(), - ); + self.app_context + .route_to_dpns_operator(DpnsOperatorRoute::Voting { + choices: self + .selected_votes + .iter() + .map(|vote| (vote.contested_name.clone(), vote.vote_choice)) + .collect(), + }); action = AppAction::SetMainScreen(RootScreenType::RootScreenMasternodes); } diff --git a/src/ui/masternodes/card.rs b/src/ui/masternodes/card.rs index c5dcbc7fb..0147f330b 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::{ @@ -59,7 +59,17 @@ pub fn voter_readiness_label(voting_present: bool) -> &'static str { /// (actionable), then a pending scheduled vote, then none. pub fn dpns_status_line(summary: MasternodeContestSummary) -> String { if summary.open_contest_count > 0 { - if summary.needs_vote_count == 0 { + if summary.vote_state == MasternodeVoteStateSummary::Checking { + format!( + "Checking votes for {} active contests", + summary.open_contest_count + ) + } else if summary.vote_state == MasternodeVoteStateSummary::Unavailable { + format!( + "Vote state unavailable for {} active contests", + 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 { format!( @@ -382,6 +392,7 @@ mod tests { open_contest_count: 3, needs_vote_count: 1, has_scheduled_vote: false, + ..Default::default() }; assert_eq!( dpns_status_line(summary), @@ -404,6 +415,7 @@ mod tests { open_contest_count: 2, needs_vote_count: 1, has_scheduled_vote: true, + ..Default::default() }; assert_eq!( dpns_status_line(summary), @@ -417,10 +429,39 @@ mod tests { open_contest_count: 0, needs_vote_count: 0, has_scheduled_vote: true, + ..Default::default() }; assert_eq!(dpns_status_line(summary), "Vote scheduled"); } + #[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 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 7274a6b4e..f21643f02 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -24,9 +24,7 @@ use crate::backend_task::contested_names::ContestedResourceTask; use crate::backend_task::identity::{IdentityInputToLoad, IdentityLoadMode, IdentityTask}; use crate::context::AppContext; use crate::model::contested_name::{ContestedName, MasternodeContestSummary}; -use crate::model::dpns_voting::{ - DpnsCurrentVoteState, DpnsVoteTarget, DpnsVoteTargetKey, VoteTiming, -}; +use crate::model::dpns_voting::{DpnsCurrentVoteState, DpnsVoteTargetKey}; use crate::model::fee_estimation::format_credits_as_dash; use crate::model::qualified_identity::{ IdentityType, MasternodeKeyPresence, PrivateKeyTarget, QualifiedIdentity, @@ -94,7 +92,6 @@ fn candidate_choice_label(candidate_name: &str, votes: u32) -> String { struct ContestVoteRow { name: String, end_time: Option, - vote_poll_id: dash_sdk::platform::Identifier, current_vote: DpnsCurrentVoteState, locked: bool, /// `(candidate id, candidate name, votes so far)` for each contestant. @@ -877,7 +874,6 @@ impl MasternodeDetailView { Some(ContestVoteRow { name: contest.normalized_contested_name.clone(), end_time: contest.end_time, - vote_poll_id, current_vote, locked: self .app_context @@ -931,8 +927,12 @@ impl MasternodeDetailView { .candidates .iter() .find(|(candidate_id, _, _)| *candidate_id == id) - .map(|(_, name, _)| name.as_str()) - .unwrap_or("candidate"); + .map(|(_, name, _)| { + format!("{name} ({})", shorten_id(&id.to_string(Encoding::Base58))) + }) + .unwrap_or_else(|| { + format!("candidate {}", shorten_id(&id.to_string(Encoding::Base58))) + }); format!("Current vote: {candidate}") } }; @@ -982,6 +982,19 @@ impl MasternodeDetailView { RichText::new("Refresh vote state before choosing a vote for this node.") .color(DashColors::text_secondary(dark_mode)), ); + if ComponentStyles::add_secondary_button(ui, "Refresh vote state", dark_mode) + .clicked() + { + self.vote_state_refresh_dispatched = true; + action = Some(AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::QueryDPNSContests, + ))); + } + } else if matches!(contest.current_vote, DpnsCurrentVoteState::Checking) { + ui.label( + RichText::new("DET is checking this node's current vote.") + .color(DashColors::text_secondary(dark_mode)), + ); } else if selected.is_none() { ui.label( RichText::new(NO_SELECTION_HINT).color(DashColors::text_secondary(dark_mode)), @@ -990,48 +1003,19 @@ impl MasternodeDetailView { } ui.separator(); - let targets: Vec = self - .vote_selections - .iter() - .filter_map(|(name, choice)| { - let contest = contests.iter().find(|contest| &contest.name == name)?; - let DpnsCurrentVoteState::Available(current_choice) = contest.current_vote else { - return None; - }; - if current_choice == Some(*choice) || contest.locked { - return None; - } - Some(DpnsVoteTarget { - key: DpnsVoteTargetKey { - network: self.app_context.network(), - voter_id, - vote_poll_id: contest.vote_poll_id, - }, - voter_alias: self.identity.alias.clone(), - contested_name: name.clone(), - requested_choice: *choice, - current_choice, - timing: VoteTiming::Now, - }) - }) - .collect(); - let has_votes = !targets.is_empty(); - let review_label = if targets.len() == 1 { + let selection_count = self.vote_selections.len(); + let has_selections = selection_count > 0; + let review_label = if selection_count == 1 { "Review 1 vote".to_owned() } else { - format!("Review {} votes", targets.len()) + format!("Review {selection_count} votes") }; - if ComponentStyles::add_primary_button_enabled(ui, has_votes, review_label) + if ComponentStyles::add_primary_button_enabled(ui, has_selections, review_label) .clickable_tooltip(CAST_ENABLED_HINT) .disabled_tooltip(CAST_DISABLED_HINT) .clicked() { - self.open_voting_center_requested = Some( - targets - .into_iter() - .map(|target| (target.contested_name, target.requested_choice)) - .collect(), - ); + self.open_voting_center_requested = Some(self.vote_selections.clone()); } if ComponentStyles::add_secondary_button(ui, "Open Voting Center", dark_mode).clicked() { self.open_voting_center_requested = Some(BTreeMap::new()); diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index f33051e66..9fe61e634 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -5,22 +5,27 @@ use std::sync::Arc; +use chrono::{LocalResult, TimeZone, Utc}; +use chrono_humanize::HumanTime; 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, RichText}; use crate::app::{AppAction, BackendTasksExecutionMode}; use crate::backend_task::BackendTask; -use crate::backend_task::contested_names::ContestedResourceTask; +use crate::backend_task::contested_names::{ContestedResourceTask, ScheduledDPNSVote}; use crate::backend_task::identity::IdentityTask; -use crate::context::AppContext; use crate::context::identity_load_registry::{IdentityLoadPhase, IdentityLoadToken}; +use crate::context::{AppContext, DpnsOperatorRoute}; use crate::model::contested_name::MasternodeContestSummary; use crate::model::dpns_voting::DpnsVoteTargetStatus; use crate::model::masternode_input::decode_identity_id; use crate::model::qualified_identity::{IdentityStatus, IdentityType, MasternodeKeyPresence}; use crate::model::user_role::UserRole; +use crate::ui::components::component_trait::Component; +use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; use crate::ui::components::global_nav_switcher::GlobalNavEffect; use crate::ui::components::left_panel::add_left_panel; use crate::ui::components::styled::island_central_panel; @@ -33,7 +38,7 @@ use crate::ui::masternodes::load_form::{LoadFormOutcome, MasternodeLoadForm}; use crate::ui::masternodes::voting_center::{DpnsVotingCenter, VotingCenterOutcome}; use crate::ui::state::global_nav::PageNavSpec; use crate::ui::state::masternodes_view::{masternodes_page_nav_spec, node_pill_item}; -use crate::ui::theme::{ComponentStyles, DashColors}; +use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; use crate::ui::{RootScreenType, ScreenLike}; /// Minimum horizontal gap between cards in the grid (matches the identity @@ -105,6 +110,7 @@ pub struct MasternodesScreen { /// [`TaskError::IdentityLoadInProgress`](crate::backend_task::error::TaskError::IdentityLoadInProgress) /// instead of racing. pending_load: Option, + pending_schedule_cancellation: Option<(ScheduledDPNSVote, ConfirmationDialog)>, } #[cfg(test)] @@ -128,6 +134,7 @@ impl MasternodesScreen { nodes: Vec::new(), view: MasternodesView::List, pending_load: None, + pending_schedule_cancellation: None, }; screen.reload(); screen @@ -210,6 +217,7 @@ impl MasternodesScreen { pub fn reset_for_network_change(&mut self) { self.view = MasternodesView::List; self.pending_load = None; + self.pending_schedule_cancellation = None; self.reload(); } @@ -342,7 +350,7 @@ impl MasternodesScreen { } /// Shared target-correlated progress, visible regardless of the active node. - fn render_voting_activity(&self, ui: &mut egui::Ui) -> AppAction { + fn render_voting_activity(&mut self, ui: &mut egui::Ui) -> AppAction { let Ok(mut operations) = self.app_context.dpns_vote_operations() else { return AppAction::None; }; @@ -361,7 +369,21 @@ impl MasternodesScreen { let mut action = AppAction::None; ui.add_space(16.0); ui.heading(RichText::new("Voting activity").color(DashColors::text_primary(dark_mode))); + let mut open_operation = None; for operation in operations { + let total = operation.targets.len(); + let complete = operation + .targets + .iter() + .filter(|outcome| !outcome.status.holds_lock()) + .count(); + ui.label( + RichText::new(format!( + "Operation {} Β· {complete} of {total} targets settled", + operation.id + )) + .strong(), + ); for outcome in &operation.targets { let voter = outcome.target.voter_alias.clone().unwrap_or_else(|| { shorten_id(&outcome.target.key.voter_id.to_string(Encoding::Base58)) @@ -379,8 +401,10 @@ impl MasternodesScreen { }; ui.horizontal_wrapped(|ui| { ui.label(format!( - "{voter} / {} β€” {status}", - outcome.target.contested_name + "{voter} / {}.dash β€” {} β†’ {} β€” {status}", + outcome.target.contested_name, + vote_choice_summary(outcome.target.current_choice), + vote_choice_summary(Some(outcome.target.requested_choice)), )); if outcome.status == DpnsVoteTargetStatus::Unconfirmed && ComponentStyles::add_secondary_button(ui, "Check again", dark_mode) @@ -392,6 +416,16 @@ impl MasternodesScreen { } }); } + if ComponentStyles::add_secondary_button(ui, "View operation", dark_mode).clicked() { + open_operation = Some(operation.id); + } + ui.separator(); + } + if let Some(operation_id) = open_operation { + self.view = MasternodesView::Voting(Box::new(DpnsVotingCenter::for_operation( + &self.app_context, + operation_id, + ))); } action } @@ -559,11 +593,11 @@ impl MasternodesScreen { )) .strong(), ); - ui.label(format!("Choice: {}", vote.choice)); ui.label(format!( - "Scheduled time: {} UTC milliseconds", - vote.unix_timestamp + "Choice: {}", + vote_choice_summary(Some(vote.choice)) )); + ui.label(format_scheduled_time(vote.unix_timestamp)); ui.label(match status { Some(DpnsVoteTargetStatus::Unconfirmed) => "Status: Checking result", Some( @@ -576,22 +610,37 @@ impl MasternodesScreen { _ => "Status: Needs attention", }); let editable = status == Some(DpnsVoteTargetStatus::Scheduled); - if ComponentStyles::add_secondary_button(ui, "Edit schedule", dark_mode).clicked() - && editable + let disabled_reason = + "This scheduled vote cannot be changed after submission has started."; + if ui + .add_enabled( + editable, + ComponentStyles::secondary_button("Edit schedule", dark_mode), + ) + .disabled_tooltip(disabled_reason) + .clicked() { self.view = MasternodesView::Voting(Box::new( DpnsVotingCenter::for_scheduled_edit(&self.app_context, &vote), )); } - if ComponentStyles::add_secondary_button(ui, "Cancel scheduled vote", dark_mode) + if ui + .add_enabled( + editable, + ComponentStyles::secondary_button("Cancel scheduled vote", dark_mode), + ) + .disabled_tooltip(disabled_reason) .clicked() - && editable { - action = AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::DeleteScheduledVote( - vote.voter_id, - vote.contested_name.clone(), - ), + let message = format!( + "Cancel the scheduled vote for {}.dash? This removes it before submission.", + vote.contested_name + ); + self.pending_schedule_cancellation = Some(( + vote.clone(), + ConfirmationDialog::new("Cancel scheduled vote", message) + .danger_mode(true) + .confirm_text(Some("Cancel scheduled vote")), )); } if status == Some(DpnsVoteTargetStatus::Unconfirmed) @@ -612,6 +661,21 @@ impl MasternodesScreen { } }); } + if let Some((vote, dialog)) = self.pending_schedule_cancellation.as_mut() { + let result = dialog.show(ui).inner.dialog_response; + if let Some(result) = result { + let vote = vote.clone(); + self.pending_schedule_cancellation = None; + if result == ConfirmationStatus::Confirmed { + action = AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::DeleteScheduledVote( + vote.voter_id, + vote.contested_name, + ), + )); + } + } + } action } @@ -733,6 +797,31 @@ impl MasternodesScreen { } } +fn vote_choice_summary(choice: Option) -> String { + match choice { + None => "Not voted".to_owned(), + Some(ResourceVoteChoice::Abstain) => "Abstain".to_owned(), + Some(ResourceVoteChoice::Lock) => "Lock".to_owned(), + Some(ResourceVoteChoice::TowardsIdentity(identity)) => { + format!( + "Candidate {}", + shorten_id(&identity.to_string(Encoding::Base58)) + ) + } + } +} + +fn format_scheduled_time(timestamp: u64) -> String { + match Utc.timestamp_millis_opt(timestamp as i64) { + LocalResult::Single(date_time) => format!( + "Scheduled time: {} UTC ({})", + date_time.format("%Y-%m-%d %H:%M"), + HumanTime::from(date_time) + ), + _ => "Scheduled time: Unavailable".to_owned(), + } +} + impl ScreenLike for MasternodesScreen { fn refresh(&mut self) { self.reload(); @@ -741,8 +830,15 @@ impl ScreenLike for MasternodesScreen { fn refresh_on_arrival(&mut self) { self.reload(); self.reconcile_pending_load(); - if let Some(contests) = self.app_context.take_dpns_voting_center_route() { - self.open_voting_center(None, contests); + if let Some(route) = self.app_context.take_dpns_operator_route() { + match route { + DpnsOperatorRoute::Voting { choices } => { + self.view = MasternodesView::Voting(Box::new( + DpnsVotingCenter::for_bulk_choices(&self.app_context, choices), + )); + } + DpnsOperatorRoute::Scheduled => self.view = MasternodesView::Scheduled, + } } } diff --git a/src/ui/masternodes/voting_center.rs b/src/ui/masternodes/voting_center.rs index bda50bba2..b483462ee 100644 --- a/src/ui/masternodes/voting_center.rs +++ b/src/ui/masternodes/voting_center.rs @@ -3,7 +3,8 @@ use std::collections::BTreeMap; use std::sync::Arc; -use chrono::{Duration, Utc}; +use chrono::{Duration, LocalResult, TimeZone, Utc}; +use chrono_humanize::HumanTime; 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; @@ -13,16 +14,14 @@ use eframe::egui::{self, ComboBox, RichText}; use crate::app::AppAction; use crate::backend_task::BackendTask; use crate::backend_task::contested_names::{ContestedResourceTask, ScheduledDPNSVote}; -use crate::backend_task::error::TaskError; use crate::context::AppContext; use crate::model::contested_name::ContestedName; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, }; +use crate::model::qualified_identity::PrivateKeyTarget; use crate::model::qualified_identity::QualifiedIdentity; -use crate::ui::MessageType; -use crate::ui::components::MessageBanner; use crate::ui::state::dpns_vote_workspace::{ ComposerKeyAction, DpnsVoteComposerStep, DpnsVoteWorkspace, DraftVoteTiming, }; @@ -45,6 +44,19 @@ pub struct DpnsVotingCenter { focus_step_heading: bool, } +struct ReviewDraft { + operation: DpnsVoteOperation, + exclusions: Vec, +} + +struct ReviewExclusion { + voter: String, + contest: String, + requested_choice: ResourceVoteChoice, + reason: &'static str, + no_op: bool, +} + impl DpnsVotingCenter { pub fn new( app_context: &Arc, @@ -94,17 +106,9 @@ impl DpnsVotingCenter { .workspace .contest_choices .insert(vote.contested_name.clone(), vote.choice); - let remaining_minutes = vote - .unix_timestamp - .saturating_sub(Utc::now().timestamp_millis() as u64) - / 60_000; center.workspace.node_timing.insert( vote.voter_id, - DraftVoteTiming::Scheduled { - days: (remaining_minutes / (24 * 60)) as u32, - hours: ((remaining_minutes / 60) % 24) as u32, - minutes: (remaining_minutes % 60) as u32, - }, + scheduled_offset_from_now(vote.unix_timestamp), ); center.editing_scheduled_key = app_context .dpns_vote_poll_id(&vote.contested_name) @@ -132,6 +136,21 @@ impl DpnsVotingCenter { center } + pub fn for_bulk_choices( + app_context: &Arc, + choices: BTreeMap, + ) -> Self { + let mut center = Self::new(app_context, None, choices.keys().cloned().collect()); + center.workspace.contest_choices = choices; + center + } + + pub fn for_operation(app_context: &Arc, operation_id: DpnsVoteOperationId) -> Self { + let mut center = Self::new(app_context, None, Vec::new()); + center.submitted_operation = Some(operation_id); + center + } + pub fn show(&mut self, ui: &mut egui::Ui) -> VotingCenterOutcome { if self.submitted_operation.is_some() { return self.render_operation(ui); @@ -145,9 +164,7 @@ impl DpnsVotingCenter { let can_continue = match self.workspace.step { DpnsVoteComposerStep::Nodes => self.workspace.selected_node_count() > 0, DpnsVoteComposerStep::Votes => !self.workspace.contest_choices.is_empty(), - DpnsVoteComposerStep::Review => self - .build_operation() - .is_ok_and(|operation| !operation.targets.is_empty()), + DpnsVoteComposerStep::Review => !self.build_review().operation.targets.is_empty(), }; match self.workspace.keyboard_action(enter, escape, can_continue) { ComposerKeyAction::CloseDraft => return VotingCenterOutcome::BackToNodes, @@ -161,9 +178,7 @@ impl DpnsVotingCenter { self.focus_step_heading = true; } ComposerKeyAction::Submit => { - if let Ok(operation) = self.build_operation() { - return self.submit_operation(operation); - } + return self.submit_operation(self.build_review().operation); } ComposerKeyAction::None => {} } @@ -197,7 +212,7 @@ impl DpnsVotingCenter { &mut self.workspace.set_all_timing, ); if ComponentStyles::add_secondary_button(ui, "Apply", dark_mode).clicked() { - self.workspace.apply_timing_to_all(); + self.workspace.apply_timing_to_selected(); } }); ui.separator(); @@ -207,15 +222,33 @@ impl DpnsVotingCenter { .alias .clone() .unwrap_or_else(|| voter_id.to_string(Encoding::Base58)); + let has_voting_key = has_loaded_voting_key(voter); ui.horizontal_wrapped(|ui| { - ui.label(RichText::new(alias).strong()); + let mut selected = self.workspace.is_node_selected(&voter_id); + let checkbox = ui.add_enabled( + has_voting_key, + egui::Checkbox::new(&mut selected, RichText::new(alias).strong()), + ); + if checkbox.changed() { + self.workspace.set_node_selected(voter_id, selected); + } + checkbox + .disabled_tooltip("Load this node's voting private key before selecting it."); let timing = self .workspace .node_timing .entry(voter_id) - .or_insert(DraftVoteTiming::Excluded); - timing_combo(ui, format!("voting_center_node_{voter_id}"), timing); - render_schedule_offset(ui, timing); + .or_insert(DraftVoteTiming::Now); + ui.add_enabled_ui(selected && has_voting_key, |ui| { + timing_combo(ui, format!("voting_center_node_{voter_id}"), timing); + render_schedule_offset(ui, timing); + }); + if !has_voting_key { + ui.label( + RichText::new("Voting key missing") + .color(DashColors::warning_color(dark_mode)), + ); + } }); } ui.separator(); @@ -234,6 +267,7 @@ impl DpnsVotingCenter { let dark_mode = ui.style().visuals.dark_mode; self.step_heading(ui, "Step 2 of 3: Votes"); ui.label("Choose one requested vote for each contested name."); + let mut outcome = VotingCenterOutcome::None; for contest in &self.contests { let name = &contest.normalized_contested_name; ui.separator(); @@ -244,7 +278,7 @@ impl DpnsVotingCenter { .color(DashColors::text_secondary(dark_mode)), ); let vote_poll_id = self.app_context.dpns_vote_poll_id(name).ok(); - let controls_enabled = !states.iter().any(|(voter_id, state, locked)| { + let controls_enabled = states.iter().any(|(voter_id, state, locked)| { let lock_is_this_edit = vote_poll_id.is_some_and(|vote_poll_id| { self.editing_scheduled_key.as_ref() == Some(&DpnsVoteTargetKey { @@ -253,8 +287,8 @@ impl DpnsVotingCenter { vote_poll_id, }) }); - (*locked && !lock_is_this_edit) - || !matches!(state, DpnsCurrentVoteState::Available(_)) + (!*locked || lock_is_this_edit) + && matches!(state, DpnsCurrentVoteState::Available(_)) }); let selected = self.workspace.contest_choices.get(name).copied(); ui.add_enabled_ui(controls_enabled, |ui| { @@ -287,17 +321,41 @@ impl DpnsVotingCenter { } }); }); - if !controls_enabled { + for (voter_id, state, locked) in &states { + let voter = self.voter_label(*voter_id); + let status = match (state, locked) { + (_, true) => "This target already has a voting operation in progress.", + (DpnsCurrentVoteState::Checking, false) => { + "DET is checking this node's current vote." + } + (DpnsCurrentVoteState::Unavailable, false) => { + "This node's current vote is unavailable." + } + _ => continue, + }; ui.label( - RichText::new( - "This contest is unavailable for at least one selected node. Refresh or wait for the active vote to finish.", - ) - .color(DashColors::text_secondary(dark_mode)), + RichText::new(format!("{voter}: {status}")) + .color(DashColors::text_secondary(dark_mode)), ); } + let can_refresh = states.iter().any(|(_, state, locked)| { + !locked + && matches!( + state, + DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable + ) + }); + if can_refresh + && ComponentStyles::add_secondary_button(ui, "Refresh vote state", dark_mode) + .clicked() + { + self.vote_state_refresh_dispatched = true; + outcome = VotingCenterOutcome::Action(Box::new(AppAction::BackendTask( + BackendTask::ContestedResourceTask(ContestedResourceTask::QueryDPNSContests), + ))); + } } ui.separator(); - let mut outcome = VotingCenterOutcome::None; ui.horizontal(|ui| { if ComponentStyles::add_secondary_button(ui, "Back", dark_mode).clicked() { self.workspace.step = DpnsVoteComposerStep::Nodes; @@ -328,22 +386,13 @@ impl DpnsVotingCenter { fn render_review(&mut self, ui: &mut egui::Ui) -> VotingCenterOutcome { let dark_mode = ui.style().visuals.dark_mode; self.step_heading(ui, "Step 3 of 3: Review"); - let operation = match self.build_operation() { - Ok(operation) => operation, - Err(error) => { - MessageBanner::set_global(ui.ctx(), error.to_string(), MessageType::Error) - .with_details(&error); - self.workspace.step = DpnsVoteComposerStep::Votes; - self.focus_step_heading = true; - return VotingCenterOutcome::None; - } - }; - for outcome in &operation.targets { + let review = self.build_review(); + for outcome in &review.operation.targets { let voter = outcome .target .voter_alias - .as_deref() - .unwrap_or("Unnamed node"); + .clone() + .unwrap_or_else(|| shorten_identifier(outcome.target.key.voter_id)); ui.group(|ui| { ui.label(RichText::new(format!( "{voter} / {}.dash", @@ -351,19 +400,17 @@ impl DpnsVotingCenter { )) .strong()); ui.label(format!( - "Current: {}", - choice_label(outcome.target.current_choice) - )); - ui.label(format!( - "Requested: {}", - choice_label(Some(outcome.target.requested_choice)) + "{} β†’ {}", + self.choice_label( + &outcome.target.contested_name, + outcome.target.current_choice + ), + self.choice_label( + &outcome.target.contested_name, + Some(outcome.target.requested_choice) + ) )); - ui.label(match outcome.target.timing { - VoteTiming::Now => "When: Cast now".to_owned(), - VoteTiming::Scheduled(timestamp) => { - format!("When: Scheduled for {timestamp} UTC milliseconds") - } - }); + ui.label(format_timing(outcome.target.timing)); if outcome.target.current_choice.is_some() { ui.label( RichText::new( @@ -374,15 +421,24 @@ impl DpnsVotingCenter { } }); } - if operation.no_op_count > 0 { + if review.operation.no_op_count > 0 { ui.label(format!( "{} targets already have the requested vote and will not be submitted.", - operation.no_op_count + review.operation.no_op_count + )); + } + for exclusion in &review.exclusions { + ui.label(format!( + "{} / {}.dash β†’ {} was excluded. {}", + exclusion.voter, + exclusion.contest, + self.choice_label(&exclusion.contest, Some(exclusion.requested_choice)), + exclusion.reason )); } ui.label(format!( "{} targets total. Each submitted vote uses Platform credits.", - operation.targets.len() + review.operation.targets.len() )); ui.horizontal(|ui| { if ComponentStyles::add_secondary_button(ui, "Back", dark_mode).clicked() { @@ -390,17 +446,25 @@ impl DpnsVotingCenter { self.focus_step_heading = true; } }); - if operation.targets.is_empty() { - ui.label( - "Every selected node already has the requested vote. Nothing will be submitted.", - ); + if review.operation.targets.is_empty() { + if review.operation.no_op_count > 0 + && review.exclusions.iter().all(|exclusion| exclusion.no_op) + { + ui.label( + "Every selected node already has the requested vote. Nothing will be submitted.", + ); + } else { + ui.label( + "No targets are ready to submit. Refresh unavailable vote state or wait for in-progress targets.", + ); + } return VotingCenterOutcome::None; } - let target_count = operation.targets.len(); + let target_count = review.operation.targets.len(); if ComponentStyles::add_primary_button(ui, format!("Submit {target_count} targets")) .clicked() { - return self.submit_operation(operation); + return self.submit_operation(review.operation); } VotingCenterOutcome::None } @@ -414,17 +478,39 @@ impl DpnsVotingCenter { match self.app_context.dpns_vote_operation(operation_id) { Ok(Some(operation)) => { for outcome in &operation.targets { - ui.horizontal_wrapped(|ui| { + ui.group(|ui| { + let voter = outcome + .target + .voter_alias + .clone() + .unwrap_or_else(|| shorten_identifier(outcome.target.key.voter_id)); + ui.label( + RichText::new(format!( + "{voter} / {}.dash", + outcome.target.contested_name + )) + .strong(), + ); ui.label(format!( - "{} / {}.dash β€” {}", - outcome - .target - .voter_alias - .as_deref() - .unwrap_or("Unnamed node"), - outcome.target.contested_name, - status_label(outcome.status) + "{} β†’ {}", + self.choice_label( + &outcome.target.contested_name, + outcome.target.current_choice + ), + self.choice_label( + &outcome.target.contested_name, + Some(outcome.target.requested_choice) + ) )); + ui.label(format_timing(outcome.target.timing)); + ui.label(format!("Status: {}", status_label(outcome.status))); + ui.label(status_explanation(outcome.status)); + if let Some(hash) = outcome.transition_hash { + let hash = hex::encode(hash); + if ui.small_button("Copy transition hash").clicked() { + ui.ctx().copy_text(hash); + } + } }); } if operation @@ -439,6 +525,58 @@ impl DpnsVotingCenter { ), ))); } + if operation.targets.iter().any(|outcome| { + matches!( + outcome.status, + DpnsVoteTargetStatus::Rejected + | DpnsVoteTargetStatus::FailedBeforeSubmission + | DpnsVoteTargetStatus::NotApplied + ) + }) && ComponentStyles::add_secondary_button(ui, "Review again", dark_mode) + .clicked() + { + self.workspace.contest_choices = operation + .targets + .iter() + .filter(|outcome| { + matches!( + outcome.status, + DpnsVoteTargetStatus::Rejected + | DpnsVoteTargetStatus::FailedBeforeSubmission + | DpnsVoteTargetStatus::NotApplied + ) + }) + .map(|outcome| { + ( + outcome.target.contested_name.clone(), + outcome.target.requested_choice, + ) + }) + .collect(); + for outcome in &operation.targets { + if matches!( + outcome.status, + DpnsVoteTargetStatus::Rejected + | DpnsVoteTargetStatus::FailedBeforeSubmission + | DpnsVoteTargetStatus::NotApplied + ) { + self.workspace + .set_node_selected(outcome.target.key.voter_id, true); + self.workspace.node_timing.insert( + outcome.target.key.voter_id, + match outcome.target.timing { + VoteTiming::Now => DraftVoteTiming::Now, + VoteTiming::Scheduled(timestamp) => { + scheduled_offset_from_now(timestamp) + } + }, + ); + } + } + self.workspace.step = DpnsVoteComposerStep::Review; + self.submitted_operation = None; + self.focus_step_heading = true; + } if ComponentStyles::add_secondary_button(ui, "Continue in background", dark_mode) .clicked() { @@ -461,12 +599,8 @@ impl DpnsVotingCenter { fn selected_voters(&self) -> Vec { self.voters .iter() - .filter(|voter| { - self.workspace - .node_timing - .get(&voter.identity.id()) - .is_some_and(|timing| *timing != DraftVoteTiming::Excluded) - }) + .filter(|voter| self.workspace.is_node_selected(&voter.identity.id())) + .filter(|voter| has_loaded_voting_key(voter)) .cloned() .collect() } @@ -518,7 +652,17 @@ impl DpnsVotingCenter { .app_context .dpns_vote_poll_id(&contest.normalized_contested_name) else { - return Vec::new(); + return self + .selected_voters() + .into_iter() + .map(|voter| { + ( + voter.identity.id(), + DpnsCurrentVoteState::Unavailable, + false, + ) + }) + .collect(); }; self.selected_voters() .into_iter() @@ -544,13 +688,13 @@ impl DpnsVotingCenter { .collect() } - fn build_operation(&self) -> Result { + fn build_review(&self) -> ReviewDraft { let mut targets = Vec::new(); + let mut exclusions = Vec::new(); for voter in self.selected_voters() { let voter_id = voter.identity.id(); let draft_timing = self.workspace.node_timing[&voter_id]; let timing = match draft_timing { - DraftVoteTiming::Excluded => continue, DraftVoteTiming::Now => VoteTiming::Now, DraftVoteTiming::Scheduled { days, @@ -565,24 +709,84 @@ impl DpnsVotingCenter { ), }; for (name, requested_choice) in &self.workspace.contest_choices { - let vote_poll_id = self.app_context.dpns_vote_poll_id(name)?; + let vote_poll_id = match self.app_context.dpns_vote_poll_id(name) { + Ok(vote_poll_id) => vote_poll_id, + Err(_) => { + exclusions.push(ReviewExclusion { + voter: self.voter_label(voter_id), + contest: name.clone(), + requested_choice: *requested_choice, + reason: "Refresh this contest before submitting a vote.", + no_op: false, + }); + continue; + } + }; let key = DpnsVoteTargetKey { network: self.app_context.network(), voter_id, vote_poll_id, }; - let existing_status = self.app_context.dpns_vote_target_status(&key)?; + let existing_status = match self.app_context.dpns_vote_target_status(&key) { + Ok(status) => status, + Err(_) => { + exclusions.push(ReviewExclusion { + voter: self.voter_label(voter_id), + contest: name.clone(), + requested_choice: *requested_choice, + reason: "DET could not check whether this target is already in use.", + no_op: false, + }); + continue; + } + }; let replacing_schedule = existing_status == Some(DpnsVoteTargetStatus::Scheduled) && matches!(timing, VoteTiming::Scheduled(_)); if existing_status.is_some() && !replacing_schedule { - return Err(TaskError::DpnsVoteTargetBusy); + exclusions.push(ReviewExclusion { + voter: self.voter_label(voter_id), + contest: name.clone(), + requested_choice: *requested_choice, + reason: "Another voting operation is still using this target.", + no_op: false, + }); + continue; } - let DpnsCurrentVoteState::Available(current_choice) = self + let current_choice = match self .app_context - .dpns_current_vote_state(voter_id, vote_poll_id)? - else { - return Err(TaskError::DpnsCurrentVoteUnavailable); + .dpns_current_vote_state(voter_id, vote_poll_id) + { + Ok(DpnsCurrentVoteState::Available(current_choice)) => current_choice, + Ok(DpnsCurrentVoteState::Checking) => { + exclusions.push(ReviewExclusion { + voter: self.voter_label(voter_id), + contest: name.clone(), + requested_choice: *requested_choice, + reason: "DET is still checking this node's current vote.", + no_op: false, + }); + continue; + } + Ok(DpnsCurrentVoteState::Unavailable) | Err(_) => { + exclusions.push(ReviewExclusion { + voter: self.voter_label(voter_id), + contest: name.clone(), + requested_choice: *requested_choice, + reason: "Refresh this node's vote state before submitting it.", + no_op: false, + }); + continue; + } }; + if current_choice == Some(*requested_choice) { + exclusions.push(ReviewExclusion { + voter: self.voter_label(voter_id), + contest: name.clone(), + requested_choice: *requested_choice, + reason: "This node already has the requested vote, so nothing will be submitted.", + no_op: true, + }); + } targets.push(DpnsVoteTarget { key, voter_alias: voter.alias.clone(), @@ -593,19 +797,38 @@ impl DpnsVotingCenter { }); } } - Ok(DpnsVoteOperation::new(targets)) + ReviewDraft { + operation: DpnsVoteOperation::new(targets), + exclusions, + } + } + + fn voter_label(&self, voter_id: Identifier) -> String { + self.voters + .iter() + .find(|voter| voter.identity.id() == voter_id) + .and_then(|voter| voter.alias.clone()) + .unwrap_or_else(|| shorten_identifier(voter_id)) + } + + fn choice_label(&self, contest_name: &str, choice: Option) -> String { + let contestants = self + .contests + .iter() + .find(|contest| contest.normalized_contested_name == contest_name) + .and_then(|contest| contest.contestants.as_deref()) + .unwrap_or_default(); + choice_label(choice, contestants) } } fn timing_combo(ui: &mut egui::Ui, id: impl Into, timing: &mut DraftVoteTiming) { ComboBox::from_id_salt(id.into()) .selected_text(match timing { - DraftVoteTiming::Excluded => "Do not use this node", DraftVoteTiming::Now => "Cast now", DraftVoteTiming::Scheduled { .. } => "Schedule", }) .show_ui(ui, |ui| { - ui.selectable_value(timing, DraftVoteTiming::Excluded, "Do not use this node"); ui.selectable_value(timing, DraftVoteTiming::Now, "Cast now"); if ui .selectable_label( @@ -657,38 +880,123 @@ fn vote_choice( } fn current_summary(states: &[(Identifier, DpnsCurrentVoteState, bool)]) -> String { - if states.iter().any(|(_, state, _)| { - matches!( - state, - DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable - ) - }) { - return "Current vote unavailable for at least one selected node".to_owned(); + if states.is_empty() { + return "Current vote state is unavailable for selected nodes".to_owned(); } + let checking = states + .iter() + .filter(|(_, state, locked)| !locked && *state == DpnsCurrentVoteState::Checking) + .count(); + let unavailable = states + .iter() + .filter(|(_, state, locked)| !locked && *state == DpnsCurrentVoteState::Unavailable) + .count(); + let busy = states.iter().filter(|(_, _, locked)| *locked).count(); + let available = states + .iter() + .filter(|(_, state, locked)| !locked && matches!(state, DpnsCurrentVoteState::Available(_))) + .count(); let not_voted = states .iter() - .filter(|(_, state, _)| *state == DpnsCurrentVoteState::Available(None)) + .filter(|(_, state, locked)| !locked && *state == DpnsCurrentVoteState::Available(None)) .count(); - if not_voted == states.len() { - "Current across selected nodes: Not voted".to_owned() - } else if not_voted > 0 { - format!("Current across selected nodes: {not_voted} not voted, others already voted") + if available == states.len() && not_voted == states.len() { + return "Current across selected nodes: Not voted".to_owned(); + } + if available == states.len() && not_voted == 0 { + return "Current across selected nodes: All already voted".to_owned(); + } + let mut parts = Vec::new(); + if not_voted > 0 { + parts.push(format!("{not_voted} not voted")); + } + let already_voted = available.saturating_sub(not_voted); + if already_voted > 0 { + parts.push(format!("{already_voted} already voted")); + } + if checking > 0 { + parts.push(format!("{checking} checking")); + } + if unavailable > 0 { + parts.push(format!("{unavailable} unavailable")); + } + if busy > 0 { + parts.push(format!("{busy} in progress")); + } + if parts.is_empty() { + "Current across selected nodes: No usable targets".to_owned() } else { - "Current across selected nodes: All already voted".to_owned() + format!("Current across selected nodes: {}", parts.join(", ")) } } -fn choice_label(choice: Option) -> String { +fn choice_label( + choice: Option, + contestants: &[crate::model::contested_name::Contestant], +) -> String { match choice { None => "Not voted".to_owned(), Some(ResourceVoteChoice::Abstain) => "Abstain".to_owned(), Some(ResourceVoteChoice::Lock) => "Lock".to_owned(), Some(ResourceVoteChoice::TowardsIdentity(identity)) => { - format!("Vote for {identity}") + let short_id = shorten_identifier(identity); + contestants + .iter() + .find(|contestant| contestant.id == identity) + .map(|contestant| format!("{} ({short_id})", contestant.name)) + .unwrap_or_else(|| format!("Candidate {short_id}")) } } } +fn shorten_identifier(identifier: Identifier) -> String { + let encoded = identifier.to_string(Encoding::Base58); + if encoded.chars().count() <= 12 { + return encoded; + } + let first = encoded.chars().take(6).collect::(); + let last = encoded + .chars() + .rev() + .take(4) + .collect::() + .chars() + .rev() + .collect::(); + format!("{first}…{last}") +} + +fn format_timing(timing: VoteTiming) -> String { + match timing { + VoteTiming::Now => "When: Cast now".to_owned(), + VoteTiming::Scheduled(timestamp) => match Utc.timestamp_millis_opt(timestamp as i64) { + LocalResult::Single(date_time) => format!( + "When: {} UTC ({})", + date_time.format("%Y-%m-%d %H:%M"), + HumanTime::from(date_time) + ), + _ => "When: The scheduled time is unavailable.".to_owned(), + }, + } +} + +fn scheduled_offset_from_now(timestamp: u64) -> DraftVoteTiming { + let remaining_minutes = timestamp.saturating_sub(Utc::now().timestamp_millis() as u64) / 60_000; + DraftVoteTiming::Scheduled { + days: (remaining_minutes / (24 * 60)) as u32, + hours: ((remaining_minutes / 60) % 24) as u32, + minutes: (remaining_minutes % 60) as u32, + } +} + +fn has_loaded_voting_key(voter: &QualifiedIdentity) -> bool { + voter + .private_keys + .keys_set() + .iter() + .any(|(target, _)| *target == PrivateKeyTarget::PrivateKeyOnVoterIdentity) +} + fn status_label(status: DpnsVoteTargetStatus) -> &'static str { match status { DpnsVoteTargetStatus::Scheduled => "Scheduled", @@ -702,3 +1010,92 @@ fn status_label(status: DpnsVoteTargetStatus) -> &'static str { DpnsVoteTargetStatus::NotApplied => "Not applied", } } + +fn status_explanation(status: DpnsVoteTargetStatus) -> &'static str { + match status { + DpnsVoteTargetStatus::Scheduled => "DET will submit this vote at the scheduled time.", + DpnsVoteTargetStatus::Queued => "This vote is waiting to be submitted.", + DpnsVoteTargetStatus::Submitting => "DET is submitting this vote.", + DpnsVoteTargetStatus::Confirming => "The vote was submitted and is being confirmed.", + DpnsVoteTargetStatus::Confirmed => "Platform confirmed this vote.", + DpnsVoteTargetStatus::Unconfirmed => { + "The vote was submitted, but DET could not confirm it yet. Do not submit it again." + } + DpnsVoteTargetStatus::Rejected => { + "Platform rejected this vote. Review the choice before trying again." + } + DpnsVoteTargetStatus::FailedBeforeSubmission => { + "This vote was not submitted. Review it before trying again." + } + DpnsVoteTargetStatus::NotApplied => { + "DET proved that this vote was not applied. It is safe to review it again." + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::contested_name::Contestant; + + fn contestant(id: Identifier, name: &str) -> Contestant { + Contestant { + id, + name: name.to_owned(), + info: String::new(), + votes: 0, + created_at: None, + created_at_block_height: None, + created_at_core_block_height: None, + document_id: Identifier::from([9; 32]), + } + } + + #[test] + fn candidate_choice_uses_name_and_short_identifier() { + let candidate = Identifier::from([7; 32]); + let label = choice_label( + Some(ResourceVoteChoice::TowardsIdentity(candidate)), + &[contestant(candidate, "dominguez")], + ); + + assert!(label.starts_with("dominguez (")); + assert!(label.contains('…')); + assert!(!label.contains(&candidate.to_string(Encoding::Base58))); + } + + #[test] + fn current_summary_keeps_healthy_targets_usable() { + let states = [ + ( + Identifier::from([1; 32]), + DpnsCurrentVoteState::Available(None), + false, + ), + ( + Identifier::from([2; 32]), + DpnsCurrentVoteState::Unavailable, + false, + ), + ( + Identifier::from([3; 32]), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)), + false, + ), + ]; + + assert_eq!( + current_summary(&states), + "Current across selected nodes: 1 not voted, 1 already voted, 1 unavailable" + ); + } + + #[test] + fn scheduled_time_is_absolute_and_relative() { + let timestamp = (Utc::now() + Duration::hours(2)).timestamp_millis() as u64; + let label = format_timing(VoteTiming::Scheduled(timestamp)); + + assert!(label.starts_with("When: 20")); + assert!(label.contains(" UTC (")); + } +} diff --git a/src/ui/state/dpns_vote_workspace.rs b/src/ui/state/dpns_vote_workspace.rs index 1b3170590..827d07ab5 100644 --- a/src/ui/state/dpns_vote_workspace.rs +++ b/src/ui/state/dpns_vote_workspace.rs @@ -2,7 +2,7 @@ use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; use dash_sdk::platform::Identifier; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; /// Current step of the full-page voting composer. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -23,7 +23,6 @@ pub enum ComposerKeyAction { /// Per-node timing override in the draft. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DraftVoteTiming { - Excluded, Now, Scheduled { days: u32, hours: u32, minutes: u32 }, } @@ -32,6 +31,7 @@ pub enum DraftVoteTiming { #[derive(Debug, Clone)] pub struct DpnsVoteWorkspace { pub step: DpnsVoteComposerStep, + selected_nodes: BTreeSet, pub node_timing: BTreeMap, pub contest_choices: BTreeMap, pub set_all_timing: DraftVoteTiming, @@ -41,6 +41,7 @@ impl DpnsVoteWorkspace { pub fn new(node_ids: impl IntoIterator) -> Self { Self { step: DpnsVoteComposerStep::Nodes, + selected_nodes: BTreeSet::new(), node_timing: node_ids .into_iter() .map(|node_id| (node_id, DraftVoteTiming::Now)) @@ -52,25 +53,36 @@ impl DpnsVoteWorkspace { /// Restrict the initial draft to one node from a detail-page deep link. pub fn prefilter_node(&mut self, selected: Identifier) { - for (node_id, timing) in &mut self.node_timing { - *timing = if *node_id == selected { - DraftVoteTiming::Now - } else { - DraftVoteTiming::Excluded - }; + self.selected_nodes.clear(); + if let Some(timing) = self.node_timing.get_mut(&selected) { + *timing = DraftVoteTiming::Now; + self.selected_nodes.insert(selected); } } pub fn selected_node_count(&self) -> usize { - self.node_timing - .values() - .filter(|timing| **timing != DraftVoteTiming::Excluded) - .count() + self.selected_nodes.len() } - pub fn apply_timing_to_all(&mut self) { - for timing in self.node_timing.values_mut() { - *timing = self.set_all_timing; + pub fn is_node_selected(&self, node_id: &Identifier) -> bool { + self.selected_nodes.contains(node_id) + } + + pub fn set_node_selected(&mut self, node_id: Identifier, selected: bool) { + if selected { + if self.node_timing.contains_key(&node_id) { + self.selected_nodes.insert(node_id); + } + } else { + self.selected_nodes.remove(&node_id); + } + } + + pub fn apply_timing_to_selected(&mut self) { + for node_id in &self.selected_nodes { + if let Some(timing) = self.node_timing.get_mut(node_id) { + *timing = self.set_all_timing; + } } } @@ -109,7 +121,9 @@ mod tests { hours: 2, minutes: 3, }; - workspace.apply_timing_to_all(); + workspace.set_node_selected(first, true); + workspace.set_node_selected(second, true); + workspace.apply_timing_to_selected(); workspace.node_timing.insert(first, DraftVoteTiming::Now); assert_eq!(workspace.node_timing[&first], DraftVoteTiming::Now); @@ -129,7 +143,41 @@ mod tests { assert_eq!(workspace.selected_node_count(), 1); assert_eq!(workspace.node_timing[&selected], DraftVoteTiming::Now); - assert_eq!(workspace.node_timing[&other], DraftVoteTiming::Excluded); + assert!(!workspace.is_node_selected(&other)); + } + + /// VOTE-TC-020: an unfiltered bulk draft starts with no nodes selected. + #[test] + fn bulk_draft_starts_without_selected_nodes() { + let first = Identifier::from([1; 32]); + let second = Identifier::from([2; 32]); + let workspace = DpnsVoteWorkspace::new([first, second]); + + assert_eq!(workspace.selected_node_count(), 0); + assert!(!workspace.is_node_selected(&first)); + assert!(!workspace.is_node_selected(&second)); + } + + /// VOTE-TC-021: set-all changes timing only for explicitly selected nodes. + #[test] + fn set_all_timing_ignores_unselected_nodes() { + let selected = Identifier::from([1; 32]); + let unselected = Identifier::from([2; 32]); + let mut workspace = DpnsVoteWorkspace::new([selected, unselected]); + workspace.set_node_selected(selected, true); + workspace.set_all_timing = DraftVoteTiming::Scheduled { + days: 1, + hours: 2, + minutes: 3, + }; + + workspace.apply_timing_to_selected(); + + assert!(matches!( + workspace.node_timing[&selected], + DraftVoteTiming::Scheduled { .. } + )); + assert_eq!(workspace.node_timing[&unselected], DraftVoteTiming::Now); } /// VOTE-TC-071: Enter advances drafts but submits only from Review; Escape closes drafts. diff --git a/tests/kittest/masternode_tab.rs b/tests/kittest/masternode_tab.rs index e28fc3275..d6a9caad0 100644 --- a/tests/kittest/masternode_tab.rs +++ b/tests/kittest/masternode_tab.rs @@ -288,6 +288,33 @@ fn voting_navigation_routes_to_shared_workspaces() { .query_by_label("Step 1 of 3: Nodes and timing") .is_some() ); + harness.get_by_label("Next: Choose votes").click(); + harness.run_steps(2); + assert!( + harness + .query_by_label("Step 1 of 3: Nodes and timing") + .is_some(), + "an unfiltered bulk draft must not select every node by default" + ); + }); +} + +/// VOTE-TC-023/075: the retired DPNS scheduled surface redirects to the shared +/// Masternodes scheduled view instead of exposing a second submit path. +#[test] +fn legacy_dpns_scheduled_route_opens_masternodes_scheduled_view() { + 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(5); + + assert_eq!( + harness.state().selected_main_screen, + RootScreenType::RootScreenMasternodes + ); + assert!(harness.query_by_label("Scheduled votes").is_some()); }); } From 0c0eed07289d8145b912382592be4defdf95eba0 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 16 Jul 2026 12:24:49 +0000 Subject: [PATCH 006/194] fix(dpns): make scheduled operations authoritative MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Render and manage scheduled votes from the durable operation journal, retain exact operation correlation for recovery, prevent implicit schedule replacement, report complete mixed outcomes, and preserve explicit unavailable states and target-identifying confirmations. Co-Authored-By: Codex GPT-5 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/app.rs | 203 ++++++++++-------- src/backend_task/contested_names/mod.rs | 55 ++++- src/backend_task/mod.rs | 1 + src/context/dpns_vote_operations.rs | 120 +++++++++-- src/model/contested_name.rs | 10 + src/ui/dpns/dpns_contested_names_screen.rs | 2 +- src/ui/masternodes/card.rs | 22 +- src/ui/masternodes/list_screen.rs | 228 +++++++++++++++------ src/ui/masternodes/voting_center.rs | 153 ++++++++++++-- 9 files changed, 590 insertions(+), 204 deletions(-) diff --git a/src/app.rs b/src/app.rs index 861f76bde..67796b6a3 100644 --- a/src/app.rs +++ b/src/app.rs @@ -16,7 +16,7 @@ use crate::context::connection_status::{ConnectionStatus, OverallConnectionState use crate::context::feature_gate::FeatureGate; use crate::context::migration_status::{MigrationState, MigrationStep}; use crate::database::Database; -use crate::model::dpns_voting::DpnsVoteTargetStatus; +use crate::model::dpns_voting::{DpnsVoteOperation, DpnsVoteTargetStatus}; use crate::model::settings::AppSettings; use crate::ui::components::passphrase_modal; use crate::ui::components::secret_prompt_host::{ActivePrompt, EguiSecretPromptHost, QueuedPrompt}; @@ -131,6 +131,57 @@ fn clear_confirmed_vote_recovery_cutoff( } } +#[derive(Debug, Default, PartialEq, Eq)] +struct DpnsVoteFeedbackCounts { + confirmed: usize, + scheduled: usize, + unconfirmed: usize, + rejected: usize, + failed_before_submission: usize, + not_applied: usize, + in_progress: usize, +} + +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::NotApplied => counts.not_applied += 1, + DpnsVoteTargetStatus::Queued + | DpnsVoteTargetStatus::Submitting + | DpnsVoteTargetStatus::Confirming => counts.in_progress += 1, + } + } + let message = format!( + "Voting results: {} confirmed, {} scheduled, {} unconfirmed, {} rejected, {} failed before submission, {} not applied, and {} still in progress. Open Voting activity to review each target.", + counts.confirmed, + counts.scheduled, + counts.unconfirmed, + counts.rejected, + counts.failed_before_submission, + counts.not_applied, + counts.in_progress, + ); + let needs_attention = + counts.unconfirmed + counts.rejected + counts.failed_before_submission + counts.not_applied + > 0; + let message_type = if needs_attention { + MessageType::Warning + } else if counts.in_progress > 0 { + MessageType::Info + } else { + MessageType::Success + }; + (message, message_type, counts.unconfirmed > 0) +} + /// Action id for the SPV-sync block's "Continue in the background" escape button. /// SPV sync is **unbounded** β€” with no peers it stays Connecting/Syncing forever /// with no terminal signal β€” so a button-less hard block would trap the user @@ -2037,93 +2088,17 @@ impl App for AppState { BackendTaskSuccessResult::DpnsVoteOperationUpdated(operation_id) => { match active_context.dpns_vote_operation(operation_id) { Ok(Some(operation)) => { - let total = operation.targets.len(); - let confirmed = operation - .targets - .iter() - .filter(|outcome| { - outcome.status == DpnsVoteTargetStatus::Confirmed - }) - .count(); - let scheduled = operation - .targets - .iter() - .filter(|outcome| { - outcome.status == DpnsVoteTargetStatus::Scheduled - }) - .count(); - let unconfirmed = operation - .targets - .iter() - .filter(|outcome| { - outcome.status == DpnsVoteTargetStatus::Unconfirmed - }) - .count(); - let rejected = operation - .targets - .iter() - .filter(|outcome| { - matches!( - outcome.status, - DpnsVoteTargetStatus::Rejected - | DpnsVoteTargetStatus::FailedBeforeSubmission - ) - }) - .count(); let diagnostics = active_context .dpns_vote_operation_diagnostics(operation_id); - if unconfirmed > 0 { - let handle = MessageBanner::set_global( - ctx, - "The vote was submitted, but DET could not confirm the result yet. DET will keep checking. Do not submit it again.", - MessageType::Warning, - ); - if !diagnostics.is_empty() { - handle.with_details(&diagnostics); - } - handle.disable_auto_dismiss(); - } else if rejected > 0 { - let handle = MessageBanner::set_global( - ctx, - format!( - "{confirmed} of {total} votes were confirmed. Review the remaining {}.", - total.saturating_sub(confirmed) - ), - MessageType::Warning, - ); - if !diagnostics.is_empty() { - handle.with_details(&diagnostics); - } + 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(); - } else if scheduled == total && total > 0 { - MessageBanner::set_global( - ctx, - format!("{scheduled} votes were scheduled."), - MessageType::Success, - ); - } else if confirmed + scheduled == total - && confirmed > 0 - && scheduled > 0 - { - MessageBanner::set_global( - ctx, - format!( - "{confirmed} votes were cast and {scheduled} votes were scheduled." - ), - MessageType::Success, - ); - } else if confirmed == total && total == 1 { - MessageBanner::set_global( - ctx, - "Vote cast successfully.", - MessageType::Success, - ); - } else if confirmed == total && total > 1 { - MessageBanner::set_global( - ctx, - format!("{confirmed} votes were cast successfully."), - MessageType::Success, - ); } } Ok(None) => { @@ -2546,6 +2521,64 @@ 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 = DpnsVoteOperation::new( + 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 mixed_vote_feedback_counts_every_terminal_category_and_guides_to_details() { + let operation = feedback_operation(&[ + DpnsVoteTargetStatus::Confirmed, + DpnsVoteTargetStatus::Scheduled, + DpnsVoteTargetStatus::Unconfirmed, + DpnsVoteTargetStatus::Rejected, + DpnsVoteTargetStatus::FailedBeforeSubmission, + DpnsVoteTargetStatus::NotApplied, + ]); + + let (message, message_type, keep_visible) = dpns_vote_feedback(&operation); + + assert_eq!(message_type, MessageType::Warning); + assert!(keep_visible); + for phrase in [ + "1 confirmed", + "1 scheduled", + "1 unconfirmed", + "1 rejected", + "1 failed before submission", + "1 not applied", + "Open Voting activity", + ] { + assert!( + message.contains(phrase), + "missing `{phrase}` in `{message}`" + ); + } + } /// A frame owns one migration snapshot even if the task publishes mid-frame. #[test] diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 570a8d027..4182bebc5 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -34,7 +34,11 @@ const SCHEDULED_VOTE_MAX_LATENESS_MS: u64 = 120_000; #[derive(Debug, Clone, PartialEq)] pub enum ContestedResourceTask { QueryDPNSContests, - SubmitDpnsVoteOperation(DpnsVoteOperation, Vec), + SubmitDpnsVoteOperation( + DpnsVoteOperation, + Vec, + Option, + ), ReconcileDpnsVoteOperation(DpnsVoteOperationId), CastScheduledVote(ScheduledDPNSVote, Box), /// Sweep the scheduled-vote table and cast every vote that is now due. @@ -46,6 +50,11 @@ pub enum ContestedResourceTask { ClearAllScheduledVotes, ClearExecutedScheduledVotes, DeleteScheduledVote(Identifier, String), + CancelScheduledDpnsVote { + operation_id: DpnsVoteOperationId, + key: DpnsVoteTargetKey, + contested_name: String, + }, } #[derive(Debug, Clone, PartialEq)] @@ -131,8 +140,12 @@ impl AppContext { .query_dpns_contested_resources(sdk, sender) .await .map(|_| BackendTaskSuccessResult::None), - ContestedResourceTask::SubmitDpnsVoteOperation(operation, voters) => { - self.execute_dpns_vote_operation(operation, voters, sdk) + ContestedResourceTask::SubmitDpnsVoteOperation( + operation, + voters, + replacing_scheduled_key, + ) => { + self.execute_dpns_vote_operation(operation, voters, replacing_scheduled_key, sdk) .await } ContestedResourceTask::ReconcileDpnsVoteOperation(operation_id) => { @@ -140,7 +153,7 @@ impl AppContext { } ContestedResourceTask::CastScheduledVote(scheduled_vote, voter) => { let operation = self.operation_for_scheduled_vote(&scheduled_vote, &voter)?; - self.execute_dpns_vote_operation(operation, vec![*voter], sdk) + self.execute_dpns_vote_operation(operation, vec![*voter], None, sdk) .await } ContestedResourceTask::CastDueScheduledVotes { @@ -153,8 +166,13 @@ impl AppContext { source: Box::new(source), }), ContestedResourceTask::ClearAllScheduledVotes => { - self.clear_all_scheduled_votes()?; self.cancel_all_scheduled_dpns_vote_targets()?; + if let Err(error) = self.clear_all_scheduled_votes() { + tracing::warn!( + ?error, + "Scheduled DPNS votes were cancelled but the legacy mirror could not be cleared" + ); + } Ok(BackendTaskSuccessResult::Refresh) } ContestedResourceTask::ClearExecutedScheduledVotes => { @@ -163,7 +181,25 @@ impl AppContext { } ContestedResourceTask::DeleteScheduledVote(voter_id, contested_name) => { self.delete_scheduled_vote(voter_id.as_slice(), &contested_name)?; - self.cancel_scheduled_dpns_vote_target(voter_id, &contested_name)?; + Ok(BackendTaskSuccessResult::Refresh) + } + ContestedResourceTask::CancelScheduledDpnsVote { + operation_id, + key, + contested_name, + } => { + self.cancel_scheduled_dpns_vote_target(operation_id, &key)?; + if let Err(error) = + self.delete_scheduled_vote(key.voter_id.as_slice(), &contested_name) + { + tracing::warn!( + ?error, + operation_id = %operation_id, + voter_id = %key.voter_id, + contested_name, + "Scheduled DPNS vote was cancelled but the legacy mirror could not be cleared" + ); + } Ok(BackendTaskSuccessResult::Refresh) } } @@ -188,7 +224,7 @@ impl AppContext { if !queued.is_empty() { let voters = self.load_local_voting_identities()?; for operation in queued { - self.execute_dpns_vote_operation(operation, voters.clone(), sdk) + self.execute_dpns_vote_operation(operation, voters.clone(), None, sdk) .await?; } } @@ -294,6 +330,7 @@ impl AppContext { self: &Arc, mut operation: DpnsVoteOperation, voters: Vec, + replacing_scheduled_key: Option, sdk: &Sdk, ) -> Result { if operation.targets.is_empty() { @@ -363,7 +400,7 @@ impl AppContext { VoteTiming::Now => None, }) .collect::>(); - self.insert_dpns_vote_operation(&operation)?; + self.insert_dpns_vote_operation(&operation, replacing_scheduled_key.as_ref())?; if !scheduled_votes.is_empty() && let Err(error) = self.insert_scheduled_votes(&scheduled_votes) { @@ -697,7 +734,7 @@ impl AppContext { let operation_id = operation.id; async move { let result = app_context - .execute_dpns_vote_operation(operation, voters, &sdk) + .execute_dpns_vote_operation(operation, voters, None, &sdk) .await .map(|_| ()); (operation_id, result) diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 1d0afc457..c84c59cf7 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -331,6 +331,7 @@ impl From<&BackendTask> for BackendTaskContext { BackendTask::ContestedResourceTask(ContestedResourceTask::SubmitDpnsVoteOperation( operation, _, + _, )) => Self::DpnsVoteOperation(operation.id), BackendTask::ContestedResourceTask( ContestedResourceTask::ReconcileDpnsVoteOperation(operation_id), diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index a729267cd..1eb1e2653 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -8,7 +8,6 @@ use crate::model::dpns_voting::{ }; use crate::wallet_backend::{DetKv, DetScope, KvAdapterError}; use dash_sdk::dpp::dashcore::Network; -use dash_sdk::platform::Identifier; use std::sync::Arc; const LEGACY_OPERATION_INDEX_KEY: &str = "det:dpns_vote_operations:v1"; @@ -177,11 +176,27 @@ fn write_existing_operation( .map_err(operation_err) } +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(_)) + }) +} + impl AppContext { /// Persist a reviewed operation and atomically acquire all unresolved locks. pub fn insert_dpns_vote_operation( &self, operation: &DpnsVoteOperation, + replacing_scheduled_key: Option<&DpnsVoteTargetKey>, ) -> Result<(), TaskError> { if operation .targets @@ -195,19 +210,46 @@ impl AppContext { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); let kv = self.det_kv()?; + let replacement_is_valid = replacing_scheduled_key.is_none_or(|key| { + operation.targets.iter().any(|outcome| { + outcome.target.key == *key + && outcome.status == DpnsVoteTargetStatus::Scheduled + && matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + }) + }); + if !replacement_is_valid { + return Err(TaskError::DpnsVoteTargetBusy); + } + let mut replaced = Vec::new(); + let mut replacement_found = false; for mut existing in load_operations(&kv, self.network)? { let original = existing.clone(); let mut changed = false; for existing_outcome in &mut existing.targets { - if existing_outcome.status == DpnsVoteTargetStatus::Scheduled + let conflicts = existing_outcome.status.holds_lock() && operation.targets.iter().any(|new_outcome| { - new_outcome.status == DpnsVoteTargetStatus::Scheduled + new_outcome.status.holds_lock() && new_outcome.target.key == existing_outcome.target.key - }) - { + }); + if !conflicts { + continue; + } + let explicitly_replaced = is_authorized_scheduled_replacement( + existing_outcome.status, + &existing_outcome.target.key, + operation, + replacing_scheduled_key, + ); + if explicitly_replaced { changed = true; + replacement_found = true; existing_outcome.status = DpnsVoteTargetStatus::NotApplied; + } else { + for previous in replaced { + write_existing_operation(&kv, self.network, &previous)?; + } + return Err(TaskError::DpnsVoteTargetBusy); } } if changed { @@ -220,6 +262,12 @@ impl AppContext { replaced.push(original); } } + if replacing_scheduled_key.is_some() && !replacement_found { + for original in replaced { + write_existing_operation(&kv, self.network, &original)?; + } + return Err(TaskError::DpnsVoteTargetBusy); + } if let Err(error) = persist_operation(&kv, self.network, operation) { for original in replaced { write_existing_operation(&kv, self.network, &original)?; @@ -480,24 +528,22 @@ impl AppContext { /// Release a not-yet-submitting scheduled target after explicit cancellation. pub(crate) fn cancel_scheduled_dpns_vote_target( &self, - voter_id: Identifier, - contested_name: &str, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, ) -> Result<(), TaskError> { - let operations = self.dpns_vote_operations()?; - for mut operation in operations { - let mut changed = false; - for outcome in &mut operation.targets { - if outcome.target.key.voter_id == voter_id - && outcome.target.contested_name == contested_name - && outcome.status == DpnsVoteTargetStatus::Scheduled - { - outcome.status = DpnsVoteTargetStatus::NotApplied; - changed = true; - } - } - if changed { - self.update_dpns_vote_operation(&operation)?; - } + let Some(mut operation) = self.dpns_vote_operation(operation_id)? else { + return Ok(()); + }; + let Some(outcome) = operation + .targets + .iter_mut() + .find(|outcome| outcome.target.key == *key) + else { + return Ok(()); + }; + if outcome.status == DpnsVoteTargetStatus::Scheduled { + outcome.status = DpnsVoteTargetStatus::NotApplied; + self.update_dpns_vote_operation(&operation)?; } Ok(()) } @@ -602,6 +648,36 @@ mod tests { 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), + )); + } + /// A corrupt indexed row must block lock reconstruction rather than being skipped. #[test] fn unreadable_indexed_operation_fails_closed() { diff --git a/src/model/contested_name.rs b/src/model/contested_name.rs index 0b6fb4634..64ddd24ed 100644 --- a/src/model/contested_name.rs +++ b/src/model/contested_name.rs @@ -68,6 +68,16 @@ pub struct MasternodeContestSummary { pub has_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)] pub struct Contestant { pub id: Identifier, diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 07b606e8c..70b90a618 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -1769,7 +1769,7 @@ impl DPNSScreen { VoteHandlingStatus::SchedulingVotes }; AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::SubmitDpnsVoteOperation(operation, selected_voters), + ContestedResourceTask::SubmitDpnsVoteOperation(operation, selected_voters, None), )) } diff --git a/src/ui/masternodes/card.rs b/src/ui/masternodes/card.rs index 0147f330b..6c232ea11 100644 --- a/src/ui/masternodes/card.rs +++ b/src/ui/masternodes/card.rs @@ -58,15 +58,19 @@ 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. pub fn dpns_status_line(summary: MasternodeContestSummary) -> String { - if summary.open_contest_count > 0 { - if summary.vote_state == MasternodeVoteStateSummary::Checking { + if summary.vote_state == MasternodeVoteStateSummary::Unavailable { + if summary.open_contest_count == 0 { + "DPNS voting status unavailable".to_owned() + } else { format!( - "Checking votes for {} active contests", + "Vote state unavailable for {} active contests", summary.open_contest_count ) - } else if summary.vote_state == MasternodeVoteStateSummary::Unavailable { + } + } else if summary.open_contest_count > 0 { + if summary.vote_state == MasternodeVoteStateSummary::Checking { format!( - "Vote state unavailable for {} active contests", + "Checking votes for {} active contests", summary.open_contest_count ) } else if summary.needs_vote_count == 0 { @@ -462,6 +466,14 @@ mod tests { ); } + #[test] + fn dpns_status_reports_unavailable_when_the_summary_read_failed() { + assert_eq!( + dpns_status_line(MasternodeContestSummary::unavailable()), + "DPNS voting status unavailable" + ); + } + #[test] fn tc_fr3_04_05_badge_label_by_type() { let card = MasternodeCard::new( diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index 9fe61e634..6985c9ec3 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -15,12 +15,14 @@ use eframe::egui::{self, RichText}; use crate::app::{AppAction, BackendTasksExecutionMode}; use crate::backend_task::BackendTask; -use crate::backend_task::contested_names::{ContestedResourceTask, ScheduledDPNSVote}; +use crate::backend_task::contested_names::ContestedResourceTask; use crate::backend_task::identity::IdentityTask; use crate::context::identity_load_registry::{IdentityLoadPhase, IdentityLoadToken}; use crate::context::{AppContext, DpnsOperatorRoute}; use crate::model::contested_name::MasternodeContestSummary; -use crate::model::dpns_voting::DpnsVoteTargetStatus; +use crate::model::dpns_voting::{ + DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTargetStatus, VoteTiming, +}; use crate::model::masternode_input::decode_identity_id; use crate::model::qualified_identity::{IdentityStatus, IdentityType, MasternodeKeyPresence}; use crate::model::user_role::UserRole; @@ -82,6 +84,12 @@ struct PendingLoad { token: IdentityLoadToken, } +#[derive(Clone)] +struct ScheduledJournalTarget { + operation_id: DpnsVoteOperationId, + outcome: DpnsVoteOutcome, +} + /// Root screen for the Masternodes section. pub struct MasternodesScreen { pub app_context: Arc, @@ -110,7 +118,7 @@ pub struct MasternodesScreen { /// [`TaskError::IdentityLoadInProgress`](crate::backend_task::error::TaskError::IdentityLoadInProgress) /// instead of racing. pending_load: Option, - pending_schedule_cancellation: Option<(ScheduledDPNSVote, ConfirmationDialog)>, + pending_schedule_cancellation: Option<(ScheduledJournalTarget, ConfirmationDialog)>, } #[cfg(test)] @@ -162,7 +170,7 @@ impl MasternodesScreen { let contest_summary = self .app_context .masternode_contest_summary(voter_id) - .unwrap_or_default(); + .unwrap_or_else(|_| MasternodeContestSummary::unavailable()); NodeCardData { node_id, node_id_short, @@ -564,52 +572,51 @@ impl MasternodesScreen { ui.label( "Upcoming and unresolved targets use the same operation locks as immediate votes.", ); - let votes = self.app_context.get_scheduled_votes().unwrap_or_default(); - if votes.is_empty() { + let scheduled_targets = match self.app_context.dpns_vote_operations() { + Ok(operations) => scheduled_journal_targets(operations), + Err(error) => { + ui.label("Scheduled votes are unavailable. Refresh this page to try again."); + tracing::warn!(?error, "Could not load journaled DPNS schedules"); + return action; + } + }; + if scheduled_targets.is_empty() { ui.label("No scheduled votes."); return action; } - for vote in votes { - let status = self - .app_context - .dpns_vote_poll_id(&vote.contested_name) - .ok() - .and_then(|vote_poll_id| { - self.app_context - .dpns_vote_target_status(&crate::model::dpns_voting::DpnsVoteTargetKey { - network: self.app_context.network(), - voter_id: vote.voter_id, - vote_poll_id, - }) - .ok() - .flatten() - }); + for scheduled in scheduled_targets { + let target = &scheduled.outcome.target; + let status = scheduled.outcome.status; + let voter = target + .voter_alias + .clone() + .unwrap_or_else(|| shorten_id(&target.key.voter_id.to_string(Encoding::Base58))); + let VoteTiming::Scheduled(scheduled_at) = target.timing else { + continue; + }; ui.group(|ui| { ui.label( - RichText::new(format!( - "{}.dash / {}", - vote.contested_name, - vote.voter_id.to_string(Encoding::Base58) - )) - .strong(), + RichText::new(format!("{}.dash / {}", target.contested_name, voter)).strong(), ); ui.label(format!( "Choice: {}", - vote_choice_summary(Some(vote.choice)) + vote_choice_summary(Some(target.requested_choice)) )); - ui.label(format_scheduled_time(vote.unix_timestamp)); + ui.label(format_scheduled_time(scheduled_at)); ui.label(match status { - Some(DpnsVoteTargetStatus::Unconfirmed) => "Status: Checking result", - Some( - DpnsVoteTargetStatus::Queued - | DpnsVoteTargetStatus::Submitting - | DpnsVoteTargetStatus::Confirming, - ) => "Status: Submitting", - Some(DpnsVoteTargetStatus::Scheduled) => "Status: Scheduled", - _ if vote.executed_successfully => "Status: Completed", - _ => "Status: Needs attention", + DpnsVoteTargetStatus::Unconfirmed => "Status: Checking result", + DpnsVoteTargetStatus::Queued + | DpnsVoteTargetStatus::Submitting + | DpnsVoteTargetStatus::Confirming => "Status: Submitting", + DpnsVoteTargetStatus::Scheduled => "Status: Scheduled", + DpnsVoteTargetStatus::Confirmed => "Status: Completed", + DpnsVoteTargetStatus::Rejected => "Status: Rejected", + DpnsVoteTargetStatus::FailedBeforeSubmission => { + "Status: Failed before submission" + } + DpnsVoteTargetStatus::NotApplied => "Status: Cancelled", }); - let editable = status == Some(DpnsVoteTargetStatus::Scheduled); + let editable = status == DpnsVoteTargetStatus::Scheduled; let disabled_reason = "This scheduled vote cannot be changed after submission has started."; if ui @@ -621,7 +628,7 @@ impl MasternodesScreen { .clicked() { self.view = MasternodesView::Voting(Box::new( - DpnsVotingCenter::for_scheduled_edit(&self.app_context, &vote), + DpnsVotingCenter::for_scheduled_edit(&self.app_context, &scheduled.outcome), )); } if ui @@ -632,46 +639,35 @@ impl MasternodesScreen { .disabled_tooltip(disabled_reason) .clicked() { - let message = format!( - "Cancel the scheduled vote for {}.dash? This removes it before submission.", - vote.contested_name - ); + let message = scheduled_cancel_confirmation(&scheduled.outcome); self.pending_schedule_cancellation = Some(( - vote.clone(), + scheduled.clone(), ConfirmationDialog::new("Cancel scheduled vote", message) .danger_mode(true) .confirm_text(Some("Cancel scheduled vote")), )); } - if status == Some(DpnsVoteTargetStatus::Unconfirmed) + if status == DpnsVoteTargetStatus::Unconfirmed && ComponentStyles::add_secondary_button(ui, "Check again", dark_mode).clicked() - && let Ok(Some(operation)) = - self.app_context.dpns_vote_operations().map(|operations| { - operations.into_iter().find(|operation| { - operation.targets.iter().any(|outcome| { - outcome.target.key.voter_id == vote.voter_id - && outcome.target.contested_name == vote.contested_name - }) - }) - }) { action = AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::ReconcileDpnsVoteOperation(operation.id), + ContestedResourceTask::ReconcileDpnsVoteOperation(scheduled.operation_id), )); } }); } - if let Some((vote, dialog)) = self.pending_schedule_cancellation.as_mut() { + if let Some((scheduled, dialog)) = self.pending_schedule_cancellation.as_mut() { let result = dialog.show(ui).inner.dialog_response; if let Some(result) = result { - let vote = vote.clone(); + let scheduled = scheduled.clone(); self.pending_schedule_cancellation = None; if result == ConfirmationStatus::Confirmed { action = AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::DeleteScheduledVote( - vote.voter_id, - vote.contested_name, - ), + ContestedResourceTask::CancelScheduledDpnsVote { + operation_id: scheduled.operation_id, + key: scheduled.outcome.target.key, + contested_name: scheduled.outcome.target.contested_name, + }, )); } } @@ -797,6 +793,47 @@ impl MasternodesScreen { } } +fn scheduled_journal_targets(operations: Vec) -> Vec { + let mut targets = operations + .into_iter() + .flat_map(|operation| { + operation.targets.into_iter().filter_map(move |outcome| { + matches!(outcome.target.timing, VoteTiming::Scheduled(_)).then_some( + ScheduledJournalTarget { + operation_id: operation.id, + outcome, + }, + ) + }) + }) + .collect::>(); + targets.sort_by_key(|scheduled| match scheduled.outcome.target.timing { + VoteTiming::Scheduled(timestamp) => timestamp, + VoteTiming::Now => u64::MAX, + }); + targets +} + +fn scheduled_cancel_confirmation(outcome: &DpnsVoteOutcome) -> String { + let target = &outcome.target; + let voter = target + .voter_alias + .clone() + .unwrap_or_else(|| shorten_id(&target.key.voter_id.to_string(Encoding::Base58))); + let time = match target.timing { + VoteTiming::Scheduled(timestamp) => format_scheduled_time(timestamp) + .strip_prefix("Scheduled time: ") + .unwrap_or("Unavailable") + .to_owned(), + VoteTiming::Now => "Immediately".to_owned(), + }; + format!( + "Cancel {voter}'s scheduled vote for {}.dash? Choice: {}. Scheduled time: {time}.", + target.contested_name, + vote_choice_summary(Some(target.requested_choice)), + ) +} + fn vote_choice_summary(choice: Option) -> String { match choice { None => "Not voted".to_owned(), @@ -925,6 +962,7 @@ mod tests { use crate::backend_task::identity::IdentityInputToLoad; use crate::context::connection_status::ConnectionStatus; use crate::database::test_helpers::create_database_at_path; + use crate::model::dpns_voting::DpnsVoteTargetKey; use crate::model::qualified_identity::QualifiedIdentity; use crate::model::qualified_identity::encrypted_key_storage::KeyStorage; use crate::utils::egui_mpsc::SenderAsync; @@ -935,6 +973,72 @@ mod tests { use dash_sdk::platform::Identifier; use std::collections::BTreeMap; + fn scheduled_operation( + voter: u8, + poll: u8, + status: DpnsVoteTargetStatus, + alias: Option<&str>, + ) -> DpnsVoteOperation { + let mut operation = + DpnsVoteOperation::new(vec![crate::model::dpns_voting::DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([voter; 32]), + vote_poll_id: Identifier::from([poll; 32]), + }, + voter_alias: alias.map(str::to_owned), + contested_name: "dominguez".to_owned(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Scheduled(1_700_000_000_000), + }]); + operation.targets[0].status = status; + operation + } + + #[test] + fn scheduled_view_items_keep_the_exact_journal_operation_id() { + let historical = + scheduled_operation(1, 2, DpnsVoteTargetStatus::Confirmed, Some("Old Eve")); + let unresolved = scheduled_operation(1, 2, DpnsVoteTargetStatus::Unconfirmed, Some("Eve")); + + let items = scheduled_journal_targets(vec![historical.clone(), unresolved.clone()]); + + assert_eq!(items.len(), 2); + assert_eq!(items[0].operation_id, historical.id); + assert_eq!(items[1].operation_id, unresolved.id); + assert_eq!(items[1].outcome.status, DpnsVoteTargetStatus::Unconfirmed); + } + + #[test] + fn scheduled_cancel_confirmation_identifies_the_complete_target() { + let operation = scheduled_operation(1, 2, DpnsVoteTargetStatus::Scheduled, Some("Eve")); + + let message = scheduled_cancel_confirmation(&operation.targets[0]); + + for phrase in ["Eve", "dominguez.dash", "Lock", "UTC"] { + assert!( + message.contains(phrase), + "missing `{phrase}` in `{message}`" + ); + } + } + + #[test] + fn scheduled_cancel_confirmation_uses_a_short_id_without_an_alias() { + let operation = scheduled_operation(1, 2, DpnsVoteTargetStatus::Scheduled, None); + let full_id = operation.targets[0] + .target + .key + .voter_id + .to_string(Encoding::Base58); + + let message = scheduled_cancel_confirmation(&operation.targets[0]); + + assert!(!message.contains(&full_id)); + assert!(message.contains('…')); + } + /// Build an offline, wallet-backend-wired `AppContext` (no network I/O). async fn offline_ctx() -> (Arc, tempfile::TempDir) { let temp_dir = tempfile::tempdir().expect("tempdir"); diff --git a/src/ui/masternodes/voting_center.rs b/src/ui/masternodes/voting_center.rs index b483462ee..12074c366 100644 --- a/src/ui/masternodes/voting_center.rs +++ b/src/ui/masternodes/voting_center.rs @@ -13,11 +13,11 @@ use eframe::egui::{self, ComboBox, RichText}; use crate::app::AppAction; use crate::backend_task::BackendTask; -use crate::backend_task::contested_names::{ContestedResourceTask, ScheduledDPNSVote}; +use crate::backend_task::contested_names::ContestedResourceTask; use crate::context::AppContext; use crate::model::contested_name::ContestedName; use crate::model::dpns_voting::{ - DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, + DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, }; use crate::model::qualified_identity::PrivateKeyTarget; @@ -41,6 +41,7 @@ pub struct DpnsVotingCenter { submitted_operation: Option, vote_state_refresh_dispatched: bool, editing_scheduled_key: Option, + editing_scheduled_original: Option, focus_step_heading: bool, } @@ -92,32 +93,31 @@ impl DpnsVotingCenter { submitted_operation: None, vote_state_refresh_dispatched: false, editing_scheduled_key: None, + editing_scheduled_original: None, focus_step_heading: true, } } - pub fn for_scheduled_edit(app_context: &Arc, vote: &ScheduledDPNSVote) -> Self { + pub fn for_scheduled_edit(app_context: &Arc, outcome: &DpnsVoteOutcome) -> Self { + let vote = &outcome.target; let mut center = Self::new( app_context, - Some(vote.voter_id), + Some(vote.key.voter_id), vec![vote.contested_name.clone()], ); center .workspace .contest_choices - .insert(vote.contested_name.clone(), vote.choice); - center.workspace.node_timing.insert( - vote.voter_id, - scheduled_offset_from_now(vote.unix_timestamp), - ); - center.editing_scheduled_key = app_context - .dpns_vote_poll_id(&vote.contested_name) - .ok() - .map(|vote_poll_id| DpnsVoteTargetKey { - network: app_context.network(), - voter_id: vote.voter_id, - vote_poll_id, - }); + .insert(vote.contested_name.clone(), vote.requested_choice); + let VoteTiming::Scheduled(timestamp) = vote.timing else { + return center; + }; + center + .workspace + .node_timing + .insert(vote.key.voter_id, scheduled_offset_from_now(timestamp)); + center.editing_scheduled_key = Some(vote.key.clone()); + center.editing_scheduled_original = Some(vote.clone()); center } @@ -410,7 +410,17 @@ impl DpnsVotingCenter { Some(outcome.target.requested_choice) ) )); - ui.label(format_timing(outcome.target.timing)); + if self.editing_scheduled_key.as_ref() == Some(&outcome.target.key) { + if let Some(original) = &self.editing_scheduled_original { + ui.label(scheduled_replacement_summary( + original, + &outcome.target, + |name, choice| self.choice_label(name, choice), + )); + } + } else { + ui.label(format_timing(outcome.target.timing)); + } if outcome.target.current_choice.is_some() { ui.label( RichText::new( @@ -611,6 +621,7 @@ impl DpnsVotingCenter { BackendTask::ContestedResourceTask(ContestedResourceTask::SubmitDpnsVoteOperation( operation, self.selected_voters(), + self.editing_scheduled_key.clone(), )), ))) } @@ -740,8 +751,12 @@ impl DpnsVotingCenter { continue; } }; - let replacing_schedule = existing_status == Some(DpnsVoteTargetStatus::Scheduled) - && matches!(timing, VoteTiming::Scheduled(_)); + let replacing_schedule = is_explicit_schedule_replacement( + self.editing_scheduled_key.as_ref(), + &key, + existing_status, + timing, + ); if existing_status.is_some() && !replacing_schedule { exclusions.push(ReviewExclusion { voter: self.voter_label(voter_id), @@ -980,6 +995,35 @@ fn format_timing(timing: VoteTiming) -> String { } } +fn scheduled_replacement_summary( + original: &DpnsVoteTarget, + replacement: &DpnsVoteTarget, + choice_label: impl Fn(&str, Option) -> String, +) -> String { + format!( + "Replacing scheduled vote: {} at {} β†’ {} at {}.", + choice_label(&original.contested_name, Some(original.requested_choice)), + scheduled_time_label(original.timing), + choice_label( + &replacement.contested_name, + Some(replacement.requested_choice) + ), + scheduled_time_label(replacement.timing), + ) +} + +fn scheduled_time_label(timing: VoteTiming) -> String { + match timing { + VoteTiming::Now => "now".to_owned(), + VoteTiming::Scheduled(timestamp) => match Utc.timestamp_millis_opt(timestamp as i64) { + LocalResult::Single(date_time) => { + format!("{} UTC", date_time.format("%Y-%m-%d %H:%M")) + } + _ => "an unavailable time".to_owned(), + }, + } +} + fn scheduled_offset_from_now(timestamp: u64) -> DraftVoteTiming { let remaining_minutes = timestamp.saturating_sub(Utc::now().timestamp_millis() as u64) / 60_000; DraftVoteTiming::Scheduled { @@ -989,6 +1033,17 @@ fn scheduled_offset_from_now(timestamp: u64) -> DraftVoteTiming { } } +fn is_explicit_schedule_replacement( + editing_key: Option<&DpnsVoteTargetKey>, + target_key: &DpnsVoteTargetKey, + existing_status: Option, + replacement_timing: VoteTiming, +) -> bool { + editing_key == Some(target_key) + && existing_status == Some(DpnsVoteTargetStatus::Scheduled) + && matches!(replacement_timing, VoteTiming::Scheduled(_)) +} + fn has_loaded_voting_key(voter: &QualifiedIdentity) -> bool { voter .private_keys @@ -1098,4 +1153,62 @@ mod tests { assert!(label.starts_with("When: 20")); assert!(label.contains(" UTC (")); } + + #[test] + fn only_the_exact_scheduled_edit_target_can_be_replaced() { + let edited = DpnsVoteTargetKey { + network: dash_sdk::dpp::dashcore::Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([2; 32]), + }; + let other = DpnsVoteTargetKey { + vote_poll_id: Identifier::from([3; 32]), + ..edited.clone() + }; + + assert!(is_explicit_schedule_replacement( + Some(&edited), + &edited, + Some(DpnsVoteTargetStatus::Scheduled), + VoteTiming::Scheduled(10), + )); + assert!(!is_explicit_schedule_replacement( + None, + &edited, + Some(DpnsVoteTargetStatus::Scheduled), + VoteTiming::Scheduled(10), + )); + assert!(!is_explicit_schedule_replacement( + Some(&edited), + &other, + Some(DpnsVoteTargetStatus::Scheduled), + VoteTiming::Scheduled(10), + )); + } + + #[test] + fn scheduled_edit_review_names_the_old_and_new_schedule() { + let original = DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: dash_sdk::dpp::dashcore::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::Scheduled(1_700_000_000_000), + }; + let mut replacement = original.clone(); + replacement.requested_choice = ResourceVoteChoice::Abstain; + replacement.timing = VoteTiming::Scheduled(1_700_003_600_000); + + let summary = scheduled_replacement_summary(&original, &replacement, |_, choice| { + choice_label(choice, &[]) + }); + + assert!(summary.contains("Lock at ")); + assert!(summary.contains("β†’ Abstain at ")); + } } From 64e0962f955c4932b871c7d60d65f5d5aae40b50 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 16 Jul 2026 13:07:03 +0000 Subject: [PATCH 007/194] fix(dpns): close voting operation safety gaps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Durably claim due schedules, preserve ambiguous reconciliation locks, order journal writes before compatibility mirrors, and correlate results and pre-journal failures by network and operation. Co-Authored-By: Codex GPT-5 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/app.rs | 36 +++- src/backend_task/contested_names/mod.rs | 199 ++++++++++++++------- src/backend_task/mod.rs | 39 +++- src/context/dpns_vote_operations.rs | 63 +++++++ src/ui/dpns/dpns_contested_names_screen.rs | 9 +- src/ui/masternodes/list_screen.rs | 20 ++- src/ui/masternodes/voting_center.rs | 69 ++++++- 7 files changed, 350 insertions(+), 85 deletions(-) diff --git a/src/app.rs b/src/app.rs index 67796b6a3..bf5718288 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2085,11 +2085,22 @@ impl App for AppState { MessageType::Success, ); } - BackendTaskSuccessResult::DpnsVoteOperationUpdated(operation_id) => { - match active_context.dpns_vote_operation(operation_id) { - Ok(Some(operation)) => { - let diagnostics = active_context - .dpns_vote_operation_diagnostics(operation_id); + 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 = @@ -2101,22 +2112,31 @@ impl App for AppState { handle.disable_auto_dismiss(); } } - Ok(None) => { + Some(Ok(None)) => { MessageBanner::set_global( ctx, "This node already has that vote. Nothing was submitted.", MessageType::Info, ); } - Err(error) => tracing::warn!( + 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(operation_id), + BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network, + operation_id, + }, ); self.visible_screen_mut().refresh(); } diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 4182bebc5..af3615c5a 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -14,6 +14,7 @@ use crate::model::dpns_voting::{ use crate::model::qualified_identity::QualifiedIdentity; use crate::model::request_type::RequestType; 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; @@ -38,8 +39,9 @@ pub enum ContestedResourceTask { DpnsVoteOperation, Vec, Option, + Network, ), - ReconcileDpnsVoteOperation(DpnsVoteOperationId), + ReconcileDpnsVoteOperation(DpnsVoteOperationId, Network), CastScheduledVote(ScheduledDPNSVote, Box), /// Sweep the scheduled-vote table and cast every vote that is now due. /// `preserve_eligibility_since_ms` keeps a vote eligible when its normal @@ -92,13 +94,15 @@ fn classify_reconciled_vote( observed: Option, requested: ResourceVoteChoice, ) -> Option { - observed.map(|choice| { - if choice == requested { - DpnsVoteTargetStatus::Confirmed - } else { - DpnsVoteTargetStatus::Rejected - } - }) + (observed == Some(requested)).then_some(DpnsVoteTargetStatus::Confirmed) +} + +fn persist_terminal_then_legacy_mirror( + persist_terminal: impl FnOnce() -> Result<(), TaskError>, + update_legacy_mirror: impl FnOnce() -> Result<(), TaskError>, +) -> Result, TaskError> { + persist_terminal()?; + Ok(update_legacy_mirror().err()) } /// Logs a Drive proof-verification failure raised by a contested-resource query. @@ -144,11 +148,12 @@ impl AppContext { operation, voters, replacing_scheduled_key, + _, ) => { self.execute_dpns_vote_operation(operation, voters, replacing_scheduled_key, sdk) .await } - ContestedResourceTask::ReconcileDpnsVoteOperation(operation_id) => { + ContestedResourceTask::ReconcileDpnsVoteOperation(operation_id, _) => { self.reconcile_dpns_vote_operation(operation_id, sdk).await } ContestedResourceTask::CastScheduledVote(scheduled_vote, voter) => { @@ -334,9 +339,10 @@ impl AppContext { sdk: &Sdk, ) -> Result { if operation.targets.is_empty() { - return Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated( - operation.id, - )); + return Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: self.network, + operation_id: operation.id, + }); } let was_persisted = self.dpns_vote_operation(operation.id)?.is_some(); if operation @@ -419,10 +425,18 @@ impl AppContext { outcome.status == DpnsVoteTargetStatus::Confirmed && matches!(outcome.target.timing, VoteTiming::Scheduled(_)) }) { - self.mark_vote_executed( + if let Err(error) = self.mark_vote_executed( outcome.target.key.voter_id.as_slice(), outcome.target.contested_name.clone(), - )?; + ) { + tracing::warn!( + ?error, + operation_id = %operation.id, + voter_id = %outcome.target.key.voter_id, + contested_name = %outcome.target.contested_name, + "Confirmed DPNS vote was journaled but its legacy mirror could not be updated" + ); + } } let voters_by_id: BTreeMap = voters @@ -479,19 +493,12 @@ impl AppContext { ) .await; let (status, failure) = classify_vote_attempt(&attempt); + let confirmed = matches!( + &attempt, + Ok(vote_on_dpns_name::DpnsVoteAttempt::Confirmed) + ); match attempt { Ok(vote_on_dpns_name::DpnsVoteAttempt::Confirmed) => { - app_context.cache_confirmed_dpns_vote( - target.key.voter_id, - target.key.vote_poll_id, - target.requested_choice, - )?; - if matches!(target.timing, VoteTiming::Scheduled(_)) { - app_context.mark_vote_executed( - target.key.voter_id.as_slice(), - target.contested_name.clone(), - )?; - } } Ok(vote_on_dpns_name::DpnsVoteAttempt::Unconfirmed(error)) => { tracing::warn!( @@ -533,12 +540,44 @@ impl AppContext { ); } } - app_context.update_dpns_vote_target( - operation_id, - &target.key, - status, - failure, + let mirror_error = persist_terminal_then_legacy_mirror( + || { + app_context.update_dpns_vote_target( + operation_id, + &target.key, + status, + failure, + ) + }, + || { + if confirmed + && matches!(target.timing, VoteTiming::Scheduled(_)) + { + app_context.mark_vote_executed( + target.key.voter_id.as_slice(), + target.contested_name.clone(), + ) + } else { + Ok(()) + } + }, )?; + if let Some(error) = mirror_error { + tracing::warn!( + ?error, + operation_id = %operation_id, + voter_id = %target.key.voter_id, + contested_name = %target.contested_name, + "DPNS vote reached a terminal journal state but its legacy mirror could not be updated" + ); + } + if confirmed { + app_context.cache_confirmed_dpns_vote( + target.key.voter_id, + target.key.vote_poll_id, + target.requested_choice, + )?; + } } Ok(()) } @@ -549,9 +588,10 @@ impl AppContext { .into_iter() .collect::, _>>()?; - Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated( - operation.id, - )) + Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: self.network, + operation_id: operation.id, + }) } async fn reconcile_dpns_vote_operation( @@ -560,9 +600,10 @@ impl AppContext { sdk: &Sdk, ) -> Result { let Some(operation) = self.dpns_vote_operation(operation_id)? else { - return Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated( + return Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: self.network, operation_id, - )); + }); }; for outcome in operation .targets @@ -587,39 +628,40 @@ impl AppContext { outcome.target.requested_choice, ) == Some(DpnsVoteTargetStatus::Confirmed) => { + let mirror_error = persist_terminal_then_legacy_mirror( + || { + self.update_dpns_vote_target( + operation_id, + &outcome.target.key, + DpnsVoteTargetStatus::Confirmed, + None, + ) + }, + || { + if matches!(outcome.target.timing, VoteTiming::Scheduled(_)) { + self.mark_vote_executed( + outcome.target.key.voter_id.as_slice(), + outcome.target.contested_name.clone(), + ) + } else { + Ok(()) + } + }, + )?; + if let Some(error) = mirror_error { + tracing::warn!( + ?error, + operation_id = %operation_id, + voter_id = %outcome.target.key.voter_id, + contested_name = %outcome.target.contested_name, + "Reconciled DPNS vote reached a terminal journal state but its legacy mirror could not be updated" + ); + } self.cache_confirmed_dpns_vote( outcome.target.key.voter_id, poll_id, outcome.target.requested_choice, )?; - self.update_dpns_vote_target( - operation_id, - &outcome.target.key, - DpnsVoteTargetStatus::Confirmed, - None, - )?; - if matches!(outcome.target.timing, VoteTiming::Scheduled(_)) { - self.mark_vote_executed( - outcome.target.key.voter_id.as_slice(), - outcome.target.contested_name.clone(), - )?; - } - } - Ok(votes) - if classify_reconciled_vote( - votes - .get(&poll_id) - .and_then(Option::as_ref) - .map(ResourceVoteGettersV0::resource_vote_choice), - outcome.target.requested_choice, - ) == Some(DpnsVoteTargetStatus::Rejected) => - { - self.update_dpns_vote_target( - operation_id, - &outcome.target.key, - DpnsVoteTargetStatus::Rejected, - Some(DpnsVoteFailure::PlatformRejected), - )?; } Ok(_) => {} Err(error) => { @@ -639,9 +681,10 @@ impl AppContext { } } } - Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated( + Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: self.network, operation_id, - )) + }) } /// Cast every scheduled vote that is now due, off the UI thread. @@ -695,6 +738,7 @@ impl AppContext { now_ms, preserve_eligibility_since_ms, ) + && self.queue_scheduled_dpns_vote_target(operation.id, &outcome.target.key)? { outcome.status = DpnsVoteTargetStatus::Queued; due = true; @@ -780,6 +824,7 @@ fn scheduled_vote_is_due( #[cfg(test)] mod tests { use super::*; + use std::cell::RefCell; /// VOTE-TC-033: an inner scheduled rejection is never classified as success. #[test] @@ -808,14 +853,15 @@ mod tests { } #[test] - fn exact_reconciliation_distinguishes_match_rejection_and_absence() { + 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), - Some(DpnsVoteTargetStatus::Rejected) + None, + "a mismatched row may predate the submitted transition and remains ambiguous" ); assert_eq!( classify_reconciled_vote(None, ResourceVoteChoice::Lock), @@ -824,6 +870,25 @@ mod tests { ); } + #[test] + fn terminal_journal_write_precedes_best_effort_legacy_mirror() { + let events = RefCell::new(Vec::new()); + let mirror_error = persist_terminal_then_legacy_mirror( + || { + events.borrow_mut().push("journal"); + Ok(()) + }, + || { + events.borrow_mut().push("legacy"); + Err(TaskError::DpnsVoteTargetBusy) + }, + ) + .expect("the authoritative journal write succeeded"); + + assert!(mirror_error.is_some()); + assert_eq!(events.into_inner(), vec!["journal", "legacy"]); + } + #[test] fn scheduled_terminal_or_unconfirmed_targets_are_not_due_for_rebroadcast() { for status in [ diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index c84c59cf7..938db9292 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -258,7 +258,10 @@ pub enum BackendTaskContext { /// The destructive per-network database clear. ClearNetworkDatabase, /// One durable DPNS vote operation. - DpnsVoteOperation(DpnsVoteOperationId), + DpnsVoteOperation { + network: Network, + operation_id: DpnsVoteOperationId, + }, /// A known backend task that needs no finer UI correlation. Other, /// An error emitted without an originating backend task. @@ -332,10 +335,17 @@ impl From<&BackendTask> for BackendTaskContext { operation, _, _, - )) => Self::DpnsVoteOperation(operation.id), + network, + )) => Self::DpnsVoteOperation { + network: *network, + operation_id: operation.id, + }, BackendTask::ContestedResourceTask( - ContestedResourceTask::ReconcileDpnsVoteOperation(operation_id), - ) => Self::DpnsVoteOperation(*operation_id), + ContestedResourceTask::ReconcileDpnsVoteOperation(operation_id, network), + ) => Self::DpnsVoteOperation { + network: *network, + operation_id: *operation_id, + }, _ => Self::Other, } } @@ -385,7 +395,10 @@ pub enum BackendTaskSuccessResult { network: Network, preserve_eligibility_since_ms: Option, }, - DpnsVoteOperationUpdated(DpnsVoteOperationId), + DpnsVoteOperationUpdated { + network: Network, + operation_id: DpnsVoteOperationId, + }, /// 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), @@ -1125,6 +1138,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, + } + ); + } + /// `is_wallet_touching` covers every task family that funnels /// through `WalletBackend` β€” the gate in `run_backend_task` relies /// on it to short-circuit while the cold-start migration is diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index 1eb1e2653..e82210781 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -176,6 +176,33 @@ fn write_existing_operation( .map_err(operation_err) } +fn transition_scheduled_target_to_queued( + kv: &DetKv, + network: Network, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, +) -> Result { + let Some(mut operation): Option = kv + .get(DetScope::Global, &operation_key(network, operation_id)) + .map_err(unreadable_operation_err)? + else { + return Ok(false); + }; + let Some(outcome) = operation + .targets + .iter_mut() + .find(|outcome| outcome.target.key == *key) + else { + return Ok(false); + }; + if outcome.status != DpnsVoteTargetStatus::Scheduled { + return Ok(false); + } + outcome.status = DpnsVoteTargetStatus::Queued; + write_existing_operation(kv, network, &operation)?; + Ok(true) +} + fn is_authorized_scheduled_replacement( existing_status: DpnsVoteTargetStatus, existing_key: &DpnsVoteTargetKey, @@ -192,6 +219,19 @@ fn is_authorized_scheduled_replacement( } impl AppContext { + /// 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 { + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + transition_scheduled_target_to_queued(&self.det_kv()?, self.network, operation_id, key) + } + /// Persist a reviewed operation and atomically acquire all unresolved locks. pub fn insert_dpns_vote_operation( &self, @@ -678,6 +718,29 @@ mod tests { )); } + #[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" + ); + } + /// A corrupt indexed row must block lock reconstruction rather than being skipped. #[test] fn unreadable_indexed_operation_fails_closed() { diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 70b90a618..b9aa6ff34 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -1769,7 +1769,12 @@ impl DPNSScreen { VoteHandlingStatus::SchedulingVotes }; AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::SubmitDpnsVoteOperation(operation, selected_voters, None), + ContestedResourceTask::SubmitDpnsVoteOperation( + operation, + selected_voters, + None, + self.app_context.network(), + ), )) } @@ -1962,7 +1967,7 @@ impl ScreenLike for DPNSScreen { fn display_task_result(&mut self, backend_task_success_result: BackendTaskSuccessResult) { match backend_task_success_result { - BackendTaskSuccessResult::DpnsVoteOperationUpdated(_) => { + BackendTaskSuccessResult::DpnsVoteOperationUpdated { .. } => { self.vote_banner.take_and_clear(); self.bulk_vote_handling_status = VoteHandlingStatus::Completed; self.refresh(); diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index 6985c9ec3..695d28a54 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -419,7 +419,10 @@ impl MasternodesScreen { .clicked() { action = AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::ReconcileDpnsVoteOperation(operation.id), + ContestedResourceTask::ReconcileDpnsVoteOperation( + operation.id, + self.app_context.network(), + ), )); } }); @@ -651,7 +654,10 @@ impl MasternodesScreen { && ComponentStyles::add_secondary_button(ui, "Check again", dark_mode).clicked() { action = AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::ReconcileDpnsVoteOperation(scheduled.operation_id), + ContestedResourceTask::ReconcileDpnsVoteOperation( + scheduled.operation_id, + self.app_context.network(), + ), )); } }); @@ -915,6 +921,16 @@ impl ScreenLike for MasternodesScreen { } } + fn display_backend_task_error( + &mut self, + context: &crate::backend_task::BackendTaskContext, + _error: &crate::backend_task::error::TaskError, + ) { + if let MasternodesView::Voting(center) = &mut self.view { + center.display_backend_task_error(context); + } + } + 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 diff --git a/src/ui/masternodes/voting_center.rs b/src/ui/masternodes/voting_center.rs index 12074c366..ff565b8f9 100644 --- a/src/ui/masternodes/voting_center.rs +++ b/src/ui/masternodes/voting_center.rs @@ -13,6 +13,7 @@ use eframe::egui::{self, ComboBox, RichText}; use crate::app::AppAction; use crate::backend_task::BackendTask; +use crate::backend_task::BackendTaskContext; use crate::backend_task::contested_names::ContestedResourceTask; use crate::context::AppContext; use crate::model::contested_name::ContestedName; @@ -59,6 +60,26 @@ struct ReviewExclusion { } impl DpnsVotingCenter { + pub(crate) fn display_backend_task_error(&mut self, context: &BackendTaskContext) { + let Some(operation_id) = self.submitted_operation else { + return; + }; + if should_return_to_review_after_error( + operation_id, + self.app_context.network(), + context, + self.app_context + .dpns_vote_operation(operation_id) + .ok() + .flatten() + .is_some(), + ) { + self.submitted_operation = None; + self.workspace.step = DpnsVoteComposerStep::Review; + self.focus_step_heading = true; + } + } + pub fn new( app_context: &Arc, preselected_voter: Option, @@ -531,7 +552,10 @@ impl DpnsVotingCenter { { return VotingCenterOutcome::Action(Box::new(AppAction::BackendTask( BackendTask::ContestedResourceTask( - ContestedResourceTask::ReconcileDpnsVoteOperation(operation_id), + ContestedResourceTask::ReconcileDpnsVoteOperation( + operation_id, + self.app_context.network(), + ), ), ))); } @@ -622,6 +646,7 @@ impl DpnsVotingCenter { operation, self.selected_voters(), self.editing_scheduled_key.clone(), + self.app_context.network(), )), ))) } @@ -1044,6 +1069,20 @@ fn is_explicit_schedule_replacement( && matches!(replacement_timing, VoteTiming::Scheduled(_)) } +fn should_return_to_review_after_error( + submitted_operation: DpnsVoteOperationId, + network: dash_sdk::dpp::dashcore::Network, + context: &BackendTaskContext, + operation_was_journaled: bool, +) -> bool { + !operation_was_journaled + && context + == &BackendTaskContext::DpnsVoteOperation { + network, + operation_id: submitted_operation, + } +} + fn has_loaded_voting_key(voter: &QualifiedIdentity) -> bool { voter .private_keys @@ -1211,4 +1250,32 @@ mod tests { assert!(summary.contains("Lock at ")); assert!(summary.contains("β†’ Abstain at ")); } + + #[test] + fn matching_pre_journal_error_returns_the_composer_to_review() { + let operation_id = DpnsVoteOperationId::from_bytes([4; 16]); + let context = BackendTaskContext::DpnsVoteOperation { + network: dash_sdk::dpp::dashcore::Network::Testnet, + operation_id, + }; + + assert!(should_return_to_review_after_error( + operation_id, + dash_sdk::dpp::dashcore::Network::Testnet, + &context, + false, + )); + assert!(!should_return_to_review_after_error( + operation_id, + dash_sdk::dpp::dashcore::Network::Testnet, + &context, + true, + )); + assert!(!should_return_to_review_after_error( + operation_id, + dash_sdk::dpp::dashcore::Network::Mainnet, + &context, + false, + )); + } } From fa0cb10d200fdae8c682c9e05d0ed5a84a1282af Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 16 Jul 2026 13:20:20 +0000 Subject: [PATCH 008/194] fix(dpns): explain empty voting workspace Show a recovery action when no masternodes are available for the shared voting composer. Co-Authored-By: Codex GPT-5 --- src/ui/masternodes/voting_center.rs | 16 ++++++++++++++++ tests/kittest/masternode_tab.rs | 16 ++++++++++++---- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/src/ui/masternodes/voting_center.rs b/src/ui/masternodes/voting_center.rs index ff565b8f9..359d1d7ec 100644 --- a/src/ui/masternodes/voting_center.rs +++ b/src/ui/masternodes/voting_center.rs @@ -225,6 +225,22 @@ impl DpnsVotingCenter { let dark_mode = ui.style().visuals.dark_mode; self.step_heading(ui, "Step 1 of 3: Nodes and timing"); ui.label("Choose which nodes will vote and when each node should submit."); + if self.voters.is_empty() { + ui.separator(); + let go_to_nodes = ui + .vertical_centered(|ui| { + ui.heading("No voting nodes are available"); + ui.label("Load a masternode on the Nodes tab before creating a vote."); + ui.add_space(8.0); + ComponentStyles::add_primary_button_enabled(ui, true, "Go to Nodes").clicked() + }) + .inner; + return if go_to_nodes { + VotingCenterOutcome::BackToNodes + } else { + VotingCenterOutcome::None + }; + } ui.horizontal_wrapped(|ui| { ui.label("Set all:"); timing_combo( diff --git a/tests/kittest/masternode_tab.rs b/tests/kittest/masternode_tab.rs index d6a9caad0..9e93902c8 100644 --- a/tests/kittest/masternode_tab.rs +++ b/tests/kittest/masternode_tab.rs @@ -288,13 +288,21 @@ fn voting_navigation_routes_to_shared_workspaces() { .query_by_label("Step 1 of 3: Nodes and timing") .is_some() ); - harness.get_by_label("Next: Choose votes").click(); - harness.run_steps(2); assert!( harness - .query_by_label("Step 1 of 3: Nodes and timing") + .query_by_label("No voting nodes are available") .is_some(), - "an unfiltered bulk draft must not select every node by default" + "an empty voting workspace must explain why voting cannot start" + ); + assert!( + harness.query_by_label("Go to Nodes").is_some(), + "an empty voting workspace must offer a direct recovery action" + ); + harness.get_by_label("Go to Nodes").click(); + harness.run_steps(2); + assert!( + harness.query_by_label("No masternodes loaded").is_some(), + "the empty-workspace recovery action must return to the Nodes tab" ); }); } From b933f920b114c06eba612ef2951e54ce26bb9e2e Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 16 Jul 2026 16:55:14 +0000 Subject: [PATCH 009/194] fix(dpns): close voting operation review gaps Co-Authored-By: OpenAI GPT-5 Codex --- src/backend_task/contested_names/mod.rs | 3 +- .../contested_names/vote_on_dpns_name.rs | 115 +++++-- src/context/dpns_vote_operations.rs | 301 ++++++++++++------ src/context/dpns_vote_state.rs | 50 ++- src/ui/dpns/dpns_contested_names_screen.rs | 4 +- src/ui/masternodes/list_screen.rs | 11 + src/ui/masternodes/voting_center.rs | 52 ++- 7 files changed, 400 insertions(+), 136 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index af3615c5a..8276da931 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -16,7 +16,6 @@ use crate::model::request_type::RequestType; 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::dpp::voting::votes::resource_vote::ResourceVote; use dash_sdk::dpp::voting::votes::resource_vote::accessors::v0::ResourceVoteGettersV0; @@ -406,7 +405,7 @@ impl AppContext { VoteTiming::Now => None, }) .collect::>(); - self.insert_dpns_vote_operation(&operation, replacing_scheduled_key.as_ref())?; + self.insert_dpns_vote_operation(&mut operation, replacing_scheduled_key.as_ref())?; if !scheduled_votes.is_empty() && let Err(error) = self.insert_scheduled_votes(&scheduled_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 0ecaa3b80..b6a36af31 100644 --- a/src/backend_task/contested_names/vote_on_dpns_name.rs +++ b/src/backend_task/contested_names/vote_on_dpns_name.rs @@ -2,11 +2,18 @@ use crate::backend_task::error::TaskError; use crate::context::AppContext; use crate::model::qualified_identity::QualifiedIdentity; use dash_sdk::Sdk; +use dash_sdk::dpp::consensus::ConsensusError; +use dash_sdk::dpp::consensus::basic::BasicError; use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; +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; @@ -15,7 +22,11 @@ use dash_sdk::dpp::voting::votes::resource_vote::ResourceVote; use dash_sdk::dpp::voting::votes::resource_vote::v0::ResourceVoteV0; 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; @@ -37,6 +48,39 @@ fn dpns_vote_poll_index_values(normalized_label: &str) -> Vec { ] } +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) + } +} + impl AppContext { pub(super) async fn submit_dpns_vote( self: &Arc, @@ -104,38 +148,39 @@ impl AppContext { resource_vote_choice: vote_choice, }; let vote = Vote::ResourceVote(ResourceVote::V0(resource_vote)); - - match vote - .put_to_platform_and_wait_for_response( - qualified_identity.identity.id(), - public_key, - sdk, - qualified_identity, - None, - ) + 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(error) = state_transition.broadcast(sdk, Some(settings)).await { + return Ok(classify_post_broadcast_error(error)); + } + + match Vote::wait_for_response(sdk, state_transition, Some(settings)).await { Ok(_) => Ok(DpnsVoteAttempt::Confirmed), - Err(error) => { - let unconfirmed = matches!( - &error, - dash_sdk::Error::StateTransitionBroadcastError(broadcast_error) - if broadcast_error.cause.is_none() - ); - let rejected = matches!( - &error, - dash_sdk::Error::StateTransitionBroadcastError(broadcast_error) - if broadcast_error.cause.is_some() - ); - let error = TaskError::from(error); - if unconfirmed { - Ok(DpnsVoteAttempt::Unconfirmed(error)) - } else if rejected { - Ok(DpnsVoteAttempt::Rejected(error)) - } else { - Err(error) - } - } + Err(error) => Ok(classify_post_broadcast_error(error)), } } } @@ -180,4 +225,12 @@ mod tests { // Then: the result matches the constant used by the vote poll tests. assert_eq!(normalized, "a11ce"); } + + #[test] + fn non_broadcast_wait_error_is_unconfirmed() { + let attempt = + classify_post_broadcast_error(dash_sdk::Error::Generic("wait failed".to_owned())); + + assert!(matches!(attempt, DpnsVoteAttempt::Unconfirmed(_))); + } } diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index e82210781..4af47959c 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -218,6 +218,88 @@ fn is_authorized_scheduled_replacement( }) } +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; + write_existing_operation(kv, network, &existing)?; + *operation = existing; + return Ok(()); + } + Err(TaskError::DpnsVoteTargetBusy) +} + +fn cancel_scheduled_target( + kv: &DetKv, + network: Network, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, +) -> Result { + let Some(mut operation): Option = kv + .get(DetScope::Global, &operation_key(network, operation_id)) + .map_err(unreadable_operation_err)? + else { + return Ok(false); + }; + let Some(outcome) = operation + .targets + .iter_mut() + .find(|outcome| outcome.target.key == *key) + else { + return Ok(false); + }; + if outcome.status != DpnsVoteTargetStatus::Scheduled { + return Ok(false); + } + outcome.status = DpnsVoteTargetStatus::NotApplied; + write_existing_operation(kv, network, &operation)?; + Ok(true) +} + +fn cancel_all_scheduled_targets(kv: &DetKv, network: Network) -> Result { + let mut cancelled = 0; + for mut operation in load_operations(kv, network)? { + let mut changed = false; + for outcome in &mut operation.targets { + if outcome.status == DpnsVoteTargetStatus::Scheduled { + outcome.status = DpnsVoteTargetStatus::NotApplied; + changed = true; + cancelled += 1; + } + } + if changed { + write_existing_operation(kv, network, &operation)?; + } + } + Ok(cancelled) +} + impl AppContext { /// Durably claim one due scheduled target before any executor can observe it. pub(crate) fn queue_scheduled_dpns_vote_target( @@ -235,7 +317,7 @@ impl AppContext { /// Persist a reviewed operation and atomically acquire all unresolved locks. pub fn insert_dpns_vote_operation( &self, - operation: &DpnsVoteOperation, + operation: &mut DpnsVoteOperation, replacing_scheduled_key: Option<&DpnsVoteTargetKey>, ) -> Result<(), TaskError> { if operation @@ -250,71 +332,10 @@ impl AppContext { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); let kv = self.det_kv()?; - let replacement_is_valid = replacing_scheduled_key.is_none_or(|key| { - operation.targets.iter().any(|outcome| { - outcome.target.key == *key - && outcome.status == DpnsVoteTargetStatus::Scheduled - && matches!(outcome.target.timing, VoteTiming::Scheduled(_)) - }) - }); - if !replacement_is_valid { - return Err(TaskError::DpnsVoteTargetBusy); + if let Some(key) = replacing_scheduled_key { + return replace_scheduled_operation(&kv, self.network, operation, key); } - - let mut replaced = Vec::new(); - let mut replacement_found = false; - for mut existing in load_operations(&kv, self.network)? { - let original = existing.clone(); - let mut changed = false; - for existing_outcome in &mut existing.targets { - let conflicts = existing_outcome.status.holds_lock() - && operation.targets.iter().any(|new_outcome| { - new_outcome.status.holds_lock() - && new_outcome.target.key == existing_outcome.target.key - }); - if !conflicts { - continue; - } - let explicitly_replaced = is_authorized_scheduled_replacement( - existing_outcome.status, - &existing_outcome.target.key, - operation, - replacing_scheduled_key, - ); - if explicitly_replaced { - changed = true; - replacement_found = true; - existing_outcome.status = DpnsVoteTargetStatus::NotApplied; - } else { - for previous in replaced { - write_existing_operation(&kv, self.network, &previous)?; - } - return Err(TaskError::DpnsVoteTargetBusy); - } - } - if changed { - if let Err(error) = write_existing_operation(&kv, self.network, &existing) { - for previous in replaced { - write_existing_operation(&kv, self.network, &previous)?; - } - return Err(error); - } - replaced.push(original); - } - } - if replacing_scheduled_key.is_some() && !replacement_found { - for original in replaced { - write_existing_operation(&kv, self.network, &original)?; - } - return Err(TaskError::DpnsVoteTargetBusy); - } - if let Err(error) = persist_operation(&kv, self.network, operation) { - for original in replaced { - write_existing_operation(&kv, self.network, &original)?; - } - return Err(error); - } - Ok(()) + persist_operation(&kv, self.network, operation) } /// Persist updated target statuses while retaining the original operation ID. @@ -571,38 +592,21 @@ impl AppContext { operation_id: DpnsVoteOperationId, key: &DpnsVoteTargetKey, ) -> Result<(), TaskError> { - let Some(mut operation) = self.dpns_vote_operation(operation_id)? else { - return Ok(()); - }; - let Some(outcome) = operation - .targets - .iter_mut() - .find(|outcome| outcome.target.key == *key) - else { - return Ok(()); - }; - if outcome.status == DpnsVoteTargetStatus::Scheduled { - outcome.status = DpnsVoteTargetStatus::NotApplied; - self.update_dpns_vote_operation(&operation)?; - } + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + cancel_scheduled_target(&self.det_kv()?, self.network, operation_id, key)?; Ok(()) } /// Release every not-yet-submitting scheduled target on this network. pub(crate) fn cancel_all_scheduled_dpns_vote_targets(&self) -> Result<(), TaskError> { - let operations = self.dpns_vote_operations()?; - for mut operation in operations { - let mut changed = false; - for outcome in &mut operation.targets { - if outcome.status == DpnsVoteTargetStatus::Scheduled { - outcome.status = DpnsVoteTargetStatus::NotApplied; - changed = true; - } - } - if changed { - self.update_dpns_vote_operation(&operation)?; - } - } + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + cancel_all_scheduled_targets(&self.det_kv()?, self.network)?; Ok(()) } } @@ -617,6 +621,59 @@ mod tests { 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, + } + + impl CountingKv { + fn reset_puts(&self) { + self.puts.store(0, Ordering::Relaxed); + } + + fn put_count(&self) -> usize { + self.puts.load(Ordering::Relaxed) + } + } + + impl KvStore for CountingKv { + fn get( + &self, + scope: &ObjectId, + key: &str, + ) -> Result>, platform_wallet_storage::KvError> { + 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())) @@ -718,6 +775,29 @@ mod tests { )); } + #[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_puts(); + + 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(); @@ -741,6 +821,43 @@ mod tests { ); } + #[test] + fn cancellation_does_not_overwrite_a_queued_target() { + 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(); + transition_scheduled_target_to_queued(&kv, Network::Testnet, scheduled.id, &key).unwrap(); + + assert!(!cancel_scheduled_target(&kv, Network::Testnet, scheduled.id, &key).unwrap()); + assert_eq!( + load_operations(&kv, Network::Testnet).unwrap()[0].targets[0].status, + DpnsVoteTargetStatus::Queued + ); + } + + #[test] + fn cancel_all_preserves_targets_that_are_already_queued() { + let kv = kv(); + let mut scheduled = operation(DpnsVoteTargetStatus::Scheduled); + scheduled.targets[0].target.timing = VoteTiming::Scheduled(42); + let mut queued = operation(DpnsVoteTargetStatus::Queued); + queued.targets[0].target.key.vote_poll_id = Identifier::from([3; 32]); + persist_operation(&kv, Network::Testnet, &scheduled).unwrap(); + persist_operation(&kv, Network::Testnet, &queued).unwrap(); + + assert_eq!( + cancel_all_scheduled_targets(&kv, Network::Testnet).unwrap(), + 1 + ); + let operations = load_operations(&kv, Network::Testnet).unwrap(); + assert!(operations.iter().any(|operation| { + operation.targets[0].target.key == queued.targets[0].target.key + && operation.targets[0].status == DpnsVoteTargetStatus::Queued + })); + } + /// A corrupt indexed row must block lock reconstruction rather than being skipped. #[test] fn unreadable_indexed_operation_fails_closed() { diff --git a/src/context/dpns_vote_state.rs b/src/context/dpns_vote_state.rs index 3116cb3fa..d036b04ed 100644 --- a/src/context/dpns_vote_state.rs +++ b/src/context/dpns_vote_state.rs @@ -60,13 +60,15 @@ fn load_snapshot( { return Ok(Some(snapshot)); } - let legacy = kv - .get(scope, LEGACY_CURRENT_VOTES_KEY) - .map_err(vote_state_err)?; - if let Some(snapshot) = &legacy { - save_snapshot(kv, network, voter_id, snapshot)?; + if kv + .get::(scope, LEGACY_CURRENT_VOTES_KEY) + .map_err(vote_state_err)? + .is_some() + { + kv.delete(scope, LEGACY_CURRENT_VOTES_KEY) + .map_err(vote_state_err)?; } - Ok(legacy) + Ok(None) } fn save_snapshot( @@ -329,6 +331,42 @@ mod tests { assert_eq!(load_snapshot(&kv, Network::Mainnet, &voter).unwrap(), None); } + #[test] + fn legacy_snapshot_is_discarded_instead_of_assigned_to_a_network() { + let kv = kv(); + let voter = Identifier::from([1; 32]); + let snapshot = StoredCurrentVotes { + available: true, + updated_at: now_ms(), + votes: BTreeMap::new(), + }; + kv.put( + DetScope::Identity(&voter.to_buffer()), + LEGACY_CURRENT_VOTES_KEY, + &snapshot, + ) + .unwrap(); + + assert_eq!(load_snapshot(&kv, Network::Testnet, &voter).unwrap(), None); + assert_eq!(load_snapshot(&kv, Network::Mainnet, &voter).unwrap(), None); + assert!( + kv.get::( + DetScope::Identity(&voter.to_buffer()), + ¤t_votes_key(Network::Testnet), + ) + .unwrap() + .is_none() + ); + assert!( + kv.get::( + DetScope::Identity(&voter.to_buffer()), + LEGACY_CURRENT_VOTES_KEY, + ) + .unwrap() + .is_none() + ); + } + #[test] fn stale_proved_snapshot_cannot_authorize_submission() { let poll = Identifier::from([2; 32]); diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index b9aa6ff34..9cd5355e0 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -12,9 +12,7 @@ use eframe::egui::{self, Button, Color32, 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::app::{AppAction, DesiredAppAction, scheduled_vote_sweep_is_quiet}; use crate::backend_task::BackendTask; use crate::backend_task::contested_names::{ContestedResourceTask, ScheduledDPNSVote}; use crate::backend_task::error::TaskError; diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index 695d28a54..4f671ede9 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -921,6 +921,17 @@ impl ScreenLike for MasternodesScreen { } } + fn display_backend_task_result( + &mut self, + context: &crate::backend_task::BackendTaskContext, + result: crate::backend_task::BackendTaskSuccessResult, + ) { + if let MasternodesView::Voting(center) = &mut self.view { + center.display_backend_task_result(context, &result); + } + self.display_task_result(result); + } + fn display_backend_task_error( &mut self, context: &crate::backend_task::BackendTaskContext, diff --git a/src/ui/masternodes/voting_center.rs b/src/ui/masternodes/voting_center.rs index 359d1d7ec..203b07f8b 100644 --- a/src/ui/masternodes/voting_center.rs +++ b/src/ui/masternodes/voting_center.rs @@ -12,9 +12,8 @@ use dash_sdk::platform::Identifier; use eframe::egui::{self, ComboBox, RichText}; use crate::app::AppAction; -use crate::backend_task::BackendTask; -use crate::backend_task::BackendTaskContext; use crate::backend_task::contested_names::ContestedResourceTask; +use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; use crate::context::AppContext; use crate::model::contested_name::ContestedName; use crate::model::dpns_voting::{ @@ -60,6 +59,15 @@ struct ReviewExclusion { } impl DpnsVotingCenter { + pub(crate) fn display_backend_task_result( + &mut self, + context: &BackendTaskContext, + result: &BackendTaskSuccessResult, + ) { + self.submitted_operation = + updated_submitted_operation(self.submitted_operation, context, result); + } + pub(crate) fn display_backend_task_error(&mut self, context: &BackendTaskContext) { let Some(operation_id) = self.submitted_operation else { return; @@ -1099,6 +1107,27 @@ fn should_return_to_review_after_error( } } +fn updated_submitted_operation( + submitted_operation: Option, + context: &BackendTaskContext, + result: &BackendTaskSuccessResult, +) -> Option { + match (submitted_operation, context, result) { + ( + Some(submitted), + BackendTaskContext::DpnsVoteOperation { + network: submitted_network, + operation_id: submitted_id, + }, + BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: result_network, + operation_id: result_id, + }, + ) if submitted == *submitted_id && submitted_network == result_network => Some(*result_id), + _ => submitted_operation, + } +} + fn has_loaded_voting_key(voter: &QualifiedIdentity) -> bool { voter .private_keys @@ -1294,4 +1323,23 @@ mod tests { false, )); } + + #[test] + fn schedule_replacement_tracks_the_authoritative_operation_id() { + let submitted = DpnsVoteOperationId::from_bytes([4; 16]); + let stored = DpnsVoteOperationId::from_bytes([5; 16]); + let context = BackendTaskContext::DpnsVoteOperation { + network: dash_sdk::dpp::dashcore::Network::Testnet, + operation_id: submitted, + }; + let result = crate::backend_task::BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: dash_sdk::dpp::dashcore::Network::Testnet, + operation_id: stored, + }; + + assert_eq!( + updated_submitted_operation(Some(submitted), &context, &result), + Some(stored) + ); + } } From 05133b601d60a12b33208075d9b46cbb5d4b17d2 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 17 Jul 2026 07:27:33 +0000 Subject: [PATCH 010/194] fix(dpns): always release failed sweep dispatches Keep scheduled vote recovery inside the sweep error boundary so every failure clears the per-network in-progress latch through the typed handler. Co-Authored-By: Codex GPT-5 --- src/backend_task/contested_names/mod.rs | 44 ++++++++++++++++++++----- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 8276da931..8d4fdaeb5 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -104,6 +104,16 @@ fn persist_terminal_then_legacy_mirror( Ok(update_legacy_mirror().err()) } +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 @@ -137,7 +147,6 @@ impl AppContext { sdk: &Sdk, sender: crate::utils::egui_mpsc::SenderAsync, ) -> Result { - self.ensure_dpns_vote_recovery(sdk).await?; match task { ContestedResourceTask::QueryDPNSContests => self .query_dpns_contested_resources(sdk, sender) @@ -162,13 +171,15 @@ impl AppContext { } 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), - }), + } => { + let result = async { + self.ensure_dpns_vote_recovery(sdk).await?; + self.cast_due_scheduled_votes(sdk, sender, preserve_eligibility_since_ms) + .await + } + .await; + wrap_scheduled_vote_sweep_result(self.network, result) + } ContestedResourceTask::ClearAllScheduledVotes => { self.cancel_all_scheduled_dpns_vote_targets()?; if let Err(error) = self.clear_all_scheduled_votes() { @@ -900,6 +911,23 @@ mod tests { } } + #[test] + fn scheduled_sweep_wraps_recovery_failures() { + let error = wrap_scheduled_vote_sweep_result::( + Network::Testnet, + Err(TaskError::DpnsCurrentVoteUnavailable), + ) + .expect_err("a recovery failure must fail the scheduled sweep"); + + assert!(matches!( + error, + TaskError::ScheduledVoteSweepFailed { + network: Network::Testnet, + source, + } if matches!(source.as_ref(), TaskError::DpnsCurrentVoteUnavailable) + )); + } + /// Migration extends only eligibility windows that overlap its wait. #[test] fn migration_wait_preserves_only_overlapping_vote_eligibility() { From 5e0532e1e43567b0524631981018e22408637d0a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 17 Jul 2026 07:31:34 +0000 Subject: [PATCH 011/194] fix(dpns): keep preflight failures retryable Re-drive already queued schedules and restore unavailable scheduled targets before propagating the pre-submission failure. Co-Authored-By: Codex GPT-5 --- src/backend_task/contested_names/mod.rs | 86 +++++++++++++++++++------ src/context/dpns_vote_operations.rs | 24 ++++++- src/model/dpns_voting.rs | 10 +++ 3 files changed, 99 insertions(+), 21 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 8d4fdaeb5..945362ae1 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -9,7 +9,7 @@ use crate::backend_task::error::TaskError; use crate::context::AppContext; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, - DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, unavailable_preflight_outcome, }; use crate::model::qualified_identity::QualifiedIdentity; use crate::model::request_type::RequestType; @@ -355,6 +355,7 @@ impl AppContext { }); } let was_persisted = self.dpns_vote_operation(operation.id)?.is_some(); + let mut preflight_unavailable = false; if operation .targets .iter() @@ -371,8 +372,13 @@ impl AppContext { .collect::>(); for key in queued_keys { let state = self.dpns_current_vote_state(key.voter_id, key.vote_poll_id)?; + let unavailable = matches!( + state, + DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable + ); if was_persisted { self.revalidate_queued_dpns_vote_target(operation.id, &key, state)?; + preflight_unavailable |= unavailable; continue; } let Some(outcome) = operation @@ -391,7 +397,9 @@ impl AppContext { } } DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable => { - return Err(TaskError::DpnsCurrentVoteUnavailable); + (outcome.status, outcome.failure) = + unavailable_preflight_outcome(outcome.target.timing); + preflight_unavailable = true; } } } @@ -598,6 +606,10 @@ impl AppContext { .into_iter() .collect::, _>>()?; + if preflight_unavailable { + return Err(TaskError::DpnsCurrentVoteUnavailable); + } + Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated { network: self.network, operation_id: operation.id, @@ -741,25 +753,28 @@ impl AppContext { let VoteTiming::Scheduled(scheduled_at) = outcome.target.timing else { continue; }; + if !scheduled_target_should_execute( + outcome.status, + scheduled_at, + now_ms, + preserve_eligibility_since_ms, + ) { + continue; + } if outcome.status == DpnsVoteTargetStatus::Scheduled - && scheduled_vote_is_due( - scheduled_at, - false, - now_ms, - preserve_eligibility_since_ms, - ) - && self.queue_scheduled_dpns_vote_target(operation.id, &outcome.target.key)? + && !self.queue_scheduled_dpns_vote_target(operation.id, &outcome.target.key)? { - 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, - }); + 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); @@ -831,6 +846,22 @@ fn scheduled_vote_is_due( && scheduled_at_ms.saturating_add(SCHEDULED_VOTE_MAX_LATENESS_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::*; @@ -928,6 +959,25 @@ mod tests { )); } + #[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, + )); + } + /// Migration extends only eligibility windows that overlap its wait. #[test] fn migration_wait_preserves_only_overlapping_vote_eligibility() { diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index 4af47959c..dac29db49 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -4,7 +4,7 @@ use super::AppContext; use crate::backend_task::error::TaskError; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, - DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, unavailable_preflight_outcome, }; use crate::wallet_backend::{DetKv, DetScope, KvAdapterError}; use dash_sdk::dpp::dashcore::Network; @@ -526,8 +526,8 @@ impl AppContext { } } DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable => { - outcome.status = DpnsVoteTargetStatus::Unconfirmed; - outcome.failure = Some(DpnsVoteFailure::CurrentVoteUnavailable); + (outcome.status, outcome.failure) = + unavailable_preflight_outcome(outcome.target.timing); } } let still_queued = outcome.status == DpnsVoteTargetStatus::Queued; @@ -821,6 +821,24 @@ mod tests { ); } + #[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 kv = kv(); diff --git a/src/model/dpns_voting.rs b/src/model/dpns_voting.rs index badbc5383..69820c7a9 100644 --- a/src/model/dpns_voting.rs +++ b/src/model/dpns_voting.rs @@ -172,6 +172,16 @@ pub enum VoteTiming { Scheduled(TimestampMillis), } +pub(crate) fn unavailable_preflight_outcome( + timing: VoteTiming, +) -> (DpnsVoteTargetStatus, Option) { + let status = match timing { + VoteTiming::Scheduled(_) => DpnsVoteTargetStatus::Scheduled, + VoteTiming::Now => DpnsVoteTargetStatus::FailedBeforeSubmission, + }; + (status, Some(DpnsVoteFailure::CurrentVoteUnavailable)) +} + /// One reviewed node Γ— contest action. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct DpnsVoteTarget { From dd2af6607047de58d9e7ac859e6875d2c87f0ac6 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 17 Jul 2026 07:40:28 +0000 Subject: [PATCH 012/194] fix(dpns): keep voting views authoritative Refresh hidden voting state from correlated results, expose contest refresh, and derive node schedule outcomes from the operation journal. Co-Authored-By: Codex GPT-5 --- src/app.rs | 64 +++++++++++- src/backend_task/error.rs | 12 --- src/context/contested_names_db.rs | 62 +++++++++++- src/model/contested_name.rs | 8 +- src/ui/dpns/dpns_contested_names_screen.rs | 23 +---- src/ui/masternodes/card.rs | 17 +++- src/ui/masternodes/voting_center.rs | 111 +++++++++++++++++++++ 7 files changed, 252 insertions(+), 45 deletions(-) diff --git a/src/app.rs b/src/app.rs index bf5718288..23f2ba5bf 100644 --- a/src/app.rs +++ b/src/app.rs @@ -207,6 +207,17 @@ fn identity_hub_is_visible(selected: RootScreenType, screen_stack_is_empty: bool selected == RootScreenType::RootScreenIdentityHub && screen_stack_is_empty } +fn dpns_result_needs_hidden_masternode_route( + selected: RootScreenType, + screen_stack_is_empty: bool, + result: &BackendTaskSuccessResult, +) -> bool { + matches!( + result, + BackendTaskSuccessResult::DpnsVoteOperationUpdated { .. } + ) && (selected != RootScreenType::RootScreenMasternodes || !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). @@ -361,7 +372,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)); @@ -1826,6 +1837,26 @@ impl AppState { } } + fn route_dpns_vote_result_to_hidden_masternodes( + &mut self, + context: &BackendTaskContext, + result: &BackendTaskSuccessResult, + ) { + if !dpns_result_needs_hidden_masternode_route( + self.selected_main_screen, + self.screen_stack.is_empty(), + result, + ) { + return; + } + if let Some(screen) = self + .main_screens + .get_mut(&RootScreenType::RootScreenMasternodes) + { + screen.display_backend_task_result(context, result.clone()); + } + } + /// 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() @@ -1969,6 +2000,7 @@ impl App for AppState { } => { let unboxed_message = *message; self.route_contact_request_result_to_hidden_hub(&unboxed_message); + self.route_dpns_vote_result_to_hidden_masternodes(&context, &unboxed_message); match unboxed_message { BackendTaskSuccessResult::None => {} BackendTaskSuccessResult::Refresh => { @@ -2894,6 +2926,36 @@ mod contact_request_routing_tests { } } +#[cfg(test)] +mod dpns_result_routing_tests { + use super::*; + use crate::model::dpns_voting::DpnsVoteOperationId; + + #[test] + fn correlated_vote_result_routes_when_masternodes_root_is_hidden() { + let result = BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: Network::Testnet, + operation_id: DpnsVoteOperationId::from_bytes([7; 16]), + }; + + assert!(dpns_result_needs_hidden_masternode_route( + RootScreenType::RootScreenWalletsBalances, + true, + &result, + )); + assert!(dpns_result_needs_hidden_masternode_route( + RootScreenType::RootScreenMasternodes, + false, + &result, + )); + assert!(!dpns_result_needs_hidden_masternode_route( + RootScreenType::RootScreenMasternodes, + true, + &result, + )); + } +} + #[cfg(test)] mod spv_overlay_tests { use super::*; diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 09ae71391..a60df03f9 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -591,18 +591,6 @@ pub enum TaskError { source: crate::wallet_backend::KvAdapterError, }, - /// Platform rejected a scheduled vote inside the otherwise successful - /// per-voter result payload. - #[error("The scheduled vote was not accepted. Wait a moment and try again.")] - ScheduledVoteRejected { - #[source] - source: std::sync::Arc, - }, - - /// The scheduled-vote call returned no per-voter verdict. - #[error("The scheduled vote result could not be confirmed. Wait a moment and try again.")] - ScheduledVoteResultUnavailable, - /// A periodic or post-migration scheduled-vote sweep failed. The network is /// structured context for the app's per-network retry bookkeeping. #[error("Scheduled votes could not be checked. Wait a moment and try again.")] diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index d3e2a0e0e..c3a887b5b 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -11,7 +11,9 @@ use crate::backend_task::error::TaskError; use crate::model::contested_name::{ ContestState, Contestant, ContestedName, MasternodeVoteStateSummary, }; -use crate::model::dpns_voting::DpnsCurrentVoteState; +use crate::model::dpns_voting::{ + DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteTargetStatus, VoteTiming, +}; use crate::wallet_backend::{DetScope, KvAdapterError}; use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::data_contract::document_type::DocumentTypeRef; @@ -34,6 +36,32 @@ 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, +) -> (bool, bool) { + let mut pending = false; + let mut failed = false; + for outcome in operations.iter().flat_map(|operation| &operation.targets) { + if outcome.target.key.voter_id != voter_id + || !matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + { + continue; + } + if matches!( + outcome.status, + DpnsVoteTargetStatus::Rejected + | DpnsVoteTargetStatus::FailedBeforeSubmission + | DpnsVoteTargetStatus::NotApplied + ) { + failed = true; + } else if outcome.status.holds_lock() { + pending = true; + } + } + (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. @@ -242,16 +270,15 @@ impl AppContext { .count(); let vote_state = vote_state_summary(&states); - let has_scheduled_vote = self - .get_scheduled_votes()? - .iter() - .any(|vote| vote.voter_id == voter_id && !vote.executed_successfully); + let (has_scheduled_vote, has_failed_scheduled_vote) = + scheduled_vote_journal_summary(&self.dpns_vote_operations()?, voter_id); Ok(crate::model::contested_name::MasternodeContestSummary { open_contest_count, needs_vote_count, vote_state, has_scheduled_vote, + has_failed_scheduled_vote, }) } @@ -594,4 +621,29 @@ mod tests { MasternodeVoteStateSummary::Unavailable ); } + + #[test] + fn terminal_schedule_failure_is_not_reported_as_pending() { + let voter_id = Identifier::from([7; 32]); + let mut operation = DpnsVoteOperation::new(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::FailedBeforeSubmission; + + assert_eq!( + scheduled_vote_journal_summary(&[operation], voter_id), + (false, true) + ); + } } diff --git a/src/model/contested_name.rs b/src/model/contested_name.rs index 64ddd24ed..0ec6ed1af 100644 --- a/src/model/contested_name.rs +++ b/src/model/contested_name.rs @@ -45,8 +45,8 @@ impl ContestedName { /// /// 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 enum MasternodeVoteStateSummary { #[default] @@ -64,8 +64,10 @@ pub struct MasternodeContestSummary { /// Whether every active contest has a proved current-vote state. 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 { diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 9cd5355e0..09a24f14f 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -1945,12 +1945,7 @@ impl ScreenLike for DPNSScreen { fn display_task_error(&mut self, error: &TaskError) -> bool { let handled = scheduled_vote_sweep_is_quiet(error); - if matches!( - error, - TaskError::ScheduledVoteRejected { .. } - | TaskError::ScheduledVoteResultUnavailable - | TaskError::ScheduledVoteSweepFailed { .. } - ) { + if matches!(error, TaskError::ScheduledVoteSweepFailed { .. }) { self.scheduled_vote_cast_in_progress = false; if let Ok(mut guard) = self.scheduled_votes.lock() { for vote in guard.iter_mut() { @@ -2275,20 +2270,4 @@ mod tests { assert!(screen.display_task_error(&error)); assert!(!screen.scheduled_vote_cast_in_progress); } - - #[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); - - screen.scheduled_vote_cast_in_progress = true; - assert!(!screen.display_task_error(&TaskError::ScheduledVoteResultUnavailable)); - assert!(!screen.scheduled_vote_cast_in_progress); - - let sweep_error = TaskError::ScheduledVoteSweepFailed { - network: Network::Regtest, - source: Box::new(TaskError::ScheduledVoteResultUnavailable), - }; - assert!(!screen.display_task_error(&sweep_error)); - } } diff --git a/src/ui/masternodes/card.rs b/src/ui/masternodes/card.rs index 6c232ea11..6cd753c9b 100644 --- a/src/ui/masternodes/card.rs +++ b/src/ui/masternodes/card.rs @@ -55,8 +55,8 @@ 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.vote_state == MasternodeVoteStateSummary::Unavailable { if summary.open_contest_count == 0 { @@ -86,6 +86,8 @@ pub fn dpns_status_line(summary: MasternodeContestSummary) -> String { summary.open_contest_count, 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 { @@ -438,6 +440,17 @@ mod tests { 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 { diff --git a/src/ui/masternodes/voting_center.rs b/src/ui/masternodes/voting_center.rs index 203b07f8b..bee519488 100644 --- a/src/ui/masternodes/voting_center.rs +++ b/src/ui/masternodes/voting_center.rs @@ -64,6 +64,15 @@ impl DpnsVotingCenter { context: &BackendTaskContext, result: &BackendTaskSuccessResult, ) { + if matches!(result, BackendTaskSuccessResult::RefreshedDpnsContests) { + self.vote_state_refresh_dispatched = false; + match self.app_context.ongoing_contested_names() { + Ok(contests) => self.contests = contests, + Err(error) => { + tracing::warn!(?error, "Could not reload refreshed DPNS contests"); + } + } + } self.submitted_operation = updated_submitted_operation(self.submitted_operation, context, result); } @@ -313,6 +322,16 @@ impl DpnsVotingCenter { self.step_heading(ui, "Step 2 of 3: Votes"); ui.label("Choose one requested vote for each contested name."); let mut outcome = VotingCenterOutcome::None; + if self.contests.is_empty() { + ui.separator(); + ui.label("No active contests are available. Refresh contests to check again."); + if ComponentStyles::add_secondary_button(ui, "Refresh contests", dark_mode).clicked() { + self.vote_state_refresh_dispatched = true; + outcome = VotingCenterOutcome::Action(Box::new(AppAction::BackendTask( + BackendTask::ContestedResourceTask(ContestedResourceTask::QueryDPNSContests), + ))); + } + } for contest in &self.contests { let name = &contest.normalized_contested_name; ui.separator(); @@ -1175,7 +1194,45 @@ fn status_explanation(status: DpnsVoteTargetStatus) -> &'static str { #[cfg(test)] mod tests { use super::*; + 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::model::contested_name::Contestant; + use crate::model::user_role::UserRoleCell; + use crate::utils::egui_mpsc::SenderAsync; + use crate::utils::tasks::TaskManager; + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + use std::cell::{Cell, RefCell}; + use std::rc::Rc; + + async fn offline_ctx() -> (Arc, tempfile::TempDir) { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let data_dir = temp_dir.path().to_path_buf(); + 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 context = AppContext::new( + data_dir, + dash_sdk::dpp::dashcore::Network::Testnet, + db, + Arc::new(TaskManager::new()), + Arc::new(ConnectionStatus::new()), + egui::Context::default(), + app_kv, + secret_store, + UserRoleCell::default(), + ) + .expect("offline AppContext"); + let (sender, _receiver) = tokio::sync::mpsc::channel::(32); + context + .ensure_wallet_backend(SenderAsync::new(sender, context.egui_ctx().clone())) + .await + .expect("wire wallet backend offline"); + (context, temp_dir) + } fn contestant(id: Identifier, name: &str) -> Contestant { Contestant { @@ -1342,4 +1399,58 @@ mod tests { Some(stored) ); } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn refreshed_contests_replace_the_voting_center_snapshot() { + let (context, _temp_dir) = offline_ctx().await; + let mut center = DpnsVotingCenter::new(&context, None, Vec::new()); + assert!(center.contests.is_empty()); + context + .insert_name_contests_as_normalized_names(vec!["dominguez".to_owned()]) + .expect("seed refreshed contest"); + center.vote_state_refresh_dispatched = true; + + center.display_backend_task_result( + &BackendTaskContext::Other, + &BackendTaskSuccessResult::RefreshedDpnsContests, + ); + + assert_eq!(center.contests.len(), 1); + assert_eq!(center.contests[0].normalized_contested_name, "dominguez"); + assert!(!center.vote_state_refresh_dispatched); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn empty_votes_step_offers_a_contest_refresh_action() { + let (context, _temp_dir) = offline_ctx().await; + let center = Rc::new(RefCell::new(DpnsVotingCenter::new( + &context, + None, + Vec::new(), + ))); + let dispatched = Rc::new(Cell::new(false)); + let center_for_ui = Rc::clone(¢er); + let dispatched_for_ui = Rc::clone(&dispatched); + let mut harness = Harness::builder() + .with_size(egui::vec2(700.0, 400.0)) + .build_ui(move |ui| { + if matches!( + center_for_ui.borrow_mut().render_votes(ui), + VotingCenterOutcome::Action(action) + if matches!( + *action, + AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::QueryDPNSContests + )) + ) + ) { + dispatched_for_ui.set(true); + } + }); + + harness.get_by_label("Refresh contests").click(); + harness.run(); + + assert!(dispatched.get()); + } } From d6db6cdbd4e516798a984896944d7ecce35ee4b1 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 17 Jul 2026 07:59:29 +0000 Subject: [PATCH 013/194] fix(dpns): preserve scheduled vote recovery --- src/app.rs | 10 ++ src/backend_task/contested_names/mod.rs | 120 ++++++++++++++++++++---- src/context/contested_names_db.rs | 102 ++++++++++++++++---- src/context/dpns_vote_operations.rs | 72 ++++++++------ src/context/mod.rs | 3 +- src/model/dpns_voting.rs | 10 ++ 6 files changed, 250 insertions(+), 67 deletions(-) diff --git a/src/app.rs b/src/app.rs index 23f2ba5bf..83fc26d1f 100644 --- a/src/app.rs +++ b/src/app.rs @@ -215,6 +215,7 @@ fn dpns_result_needs_hidden_masternode_route( matches!( result, BackendTaskSuccessResult::DpnsVoteOperationUpdated { .. } + | BackendTaskSuccessResult::RefreshedDpnsContests ) && (selected != RootScreenType::RootScreenMasternodes || !screen_stack_is_empty) } @@ -2954,6 +2955,15 @@ mod dpns_result_routing_tests { &result, )); } + + #[test] + fn refreshed_contests_route_when_masternodes_root_is_hidden() { + assert!(dpns_result_needs_hidden_masternode_route( + RootScreenType::RootScreenWalletsBalances, + true, + &BackendTaskSuccessResult::RefreshedDpnsContests, + )); + } } #[cfg(test)] diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 945362ae1..335a81d03 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -9,7 +9,8 @@ use crate::backend_task::error::TaskError; use crate::context::AppContext; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, - DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, unavailable_preflight_outcome, + DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, failed_before_broadcast_outcome, + unavailable_preflight_outcome, }; use crate::model::qualified_identity::QualifiedIdentity; use crate::model::request_type::RequestType; @@ -69,6 +70,7 @@ pub struct ScheduledDPNSVote { fn classify_vote_attempt( attempt: &Result, + timing: VoteTiming, ) -> (DpnsVoteTargetStatus, Option) { match attempt { Ok(vote_on_dpns_name::DpnsVoteAttempt::Confirmed) => { @@ -82,10 +84,7 @@ fn classify_vote_attempt( DpnsVoteTargetStatus::Rejected, Some(DpnsVoteFailure::PlatformRejected), ), - Err(_) => ( - DpnsVoteTargetStatus::FailedBeforeSubmission, - Some(DpnsVoteFailure::SubmissionFailed), - ), + Err(_) => failed_before_broadcast_outcome(timing), } } @@ -147,6 +146,11 @@ impl AppContext { sdk: &Sdk, sender: crate::utils::egui_mpsc::SenderAsync, ) -> Result { + let is_scheduled_sweep = + matches!(&task, ContestedResourceTask::CastDueScheduledVotes { .. }); + if !is_scheduled_sweep { + self.ensure_dpns_vote_recovery(sdk).await?; + } match task { ContestedResourceTask::QueryDPNSContests => self .query_dpns_contested_resources(sdk, sender) @@ -510,11 +514,12 @@ impl AppContext { &sdk, ) .await; - let (status, failure) = classify_vote_attempt(&attempt); + let (status, failure) = classify_vote_attempt(&attempt, target.timing); let confirmed = matches!( &attempt, Ok(vote_on_dpns_name::DpnsVoteAttempt::Confirmed) ); + let mut retryable_scheduled_error = None; match attempt { Ok(vote_on_dpns_name::DpnsVoteAttempt::Confirmed) => { } @@ -551,11 +556,15 @@ impl AppContext { contested_name = %target.contested_name, "DPNS vote failed before a confirmed submission" ); - app_context.record_dpns_vote_diagnostic( - operation_id, - target.key.clone(), - error, - ); + if matches!(target.timing, VoteTiming::Scheduled(_)) { + retryable_scheduled_error = Some(error); + } else { + app_context.record_dpns_vote_diagnostic( + operation_id, + target.key.clone(), + error, + ); + } } } let mirror_error = persist_terminal_then_legacy_mirror( @@ -596,6 +605,9 @@ impl AppContext { target.requested_choice, )?; } + if let Some(error) = retryable_scheduled_error { + return Err(error); + } } Ok(()) } @@ -821,6 +833,20 @@ impl AppContext { "Failed to execute a due DPNS vote operation; leaving it for recovery" ); first_error.get_or_insert(error); + if let Err(recovery_error) = + self.recover_interrupted_dpns_vote_operation(operation_id) + { + tracing::error!( + error = %recovery_error, + operation_id = %operation_id, + "Failed to recover an interrupted DPNS vote operation" + ); + // Let the next contested task retry global recovery after + // storage becomes available again. The targeted attempt is + // preferred because this fallback can see unrelated work. + *self.dpns_vote_recovery.lock().await = false; + first_error.get_or_insert(recovery_error); + } } } if let Some(error) = first_error { @@ -874,7 +900,7 @@ mod tests { TaskError::DpnsVoteTargetBusy, )); assert_eq!( - classify_vote_attempt(&attempt), + classify_vote_attempt(&attempt, VoteTiming::Scheduled(42)), ( DpnsVoteTargetStatus::Rejected, Some(DpnsVoteFailure::PlatformRejected) @@ -888,7 +914,7 @@ mod tests { let attempt = Ok(vote_on_dpns_name::DpnsVoteAttempt::Unconfirmed( TaskError::DpnsVoteTargetBusy, )); - let (status, _) = classify_vote_attempt(&attempt); + let (status, _) = classify_vote_attempt(&attempt, VoteTiming::Scheduled(42)); assert_eq!(status, DpnsVoteTargetStatus::Unconfirmed); assert!(status.holds_lock()); } @@ -942,23 +968,77 @@ mod tests { } } - #[test] - fn scheduled_sweep_wraps_recovery_failures() { - let error = wrap_scheduled_vote_sweep_result::( + #[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, - Err(TaskError::DpnsCurrentVoteUnavailable), + database, + Arc::new(TaskManager::new()), + Arc::new(ConnectionStatus::new()), + egui::Context::default(), + app_kv, + secret_store, + crate::model::user_role::UserRoleCell::default(), ) - .expect_err("a recovery failure must fail the scheduled sweep"); + .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, + }, + &context.sdk(), + sender, + ) + .await + .expect_err("an unwired recovery must fail the scheduled sweep"); assert!(matches!( error, TaskError::ScheduledVoteSweepFailed { network: Network::Testnet, - source, - } if matches!(source.as_ref(), TaskError::DpnsCurrentVoteUnavailable) + .. + } )); } + #[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), + ) + ); + } + #[test] fn queued_schedule_remains_eligible_for_redrive() { let now_ms = 1_000_000; diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index c3a887b5b..e95c0c0f3 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -40,25 +40,37 @@ fn scheduled_vote_journal_summary( operations: &[DpnsVoteOperation], voter_id: Identifier, ) -> (bool, bool) { - let mut pending = false; - let mut failed = false; - for outcome in operations.iter().flat_map(|operation| &operation.targets) { - if outcome.target.key.voter_id != voter_id - || !matches!(outcome.target.timing, VoteTiming::Scheduled(_)) - { - continue; - } - if matches!( + let latest_by_target = operations + .iter() + .flat_map(|operation| { + operation + .targets + .iter() + .map(move |outcome| (operation.created_at, outcome)) + }) + .filter(|(_, outcome)| { + outcome.target.key.voter_id == voter_id + && matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + }) + .fold(BTreeMap::new(), |mut latest, (created_at, outcome)| { + let entry = latest + .entry(&outcome.target.key) + .or_insert((created_at, outcome)); + if created_at >= entry.0 { + *entry = (created_at, outcome); + } + latest + }); + + let pending = latest_by_target + .values() + .any(|(_, outcome)| outcome.status.holds_lock()); + let failed = latest_by_target.values().any(|(_, outcome)| { + matches!( outcome.status, - DpnsVoteTargetStatus::Rejected - | DpnsVoteTargetStatus::FailedBeforeSubmission - | DpnsVoteTargetStatus::NotApplied - ) { - failed = true; - } else if outcome.status.holds_lock() { - pending = true; - } - } + DpnsVoteTargetStatus::Rejected | DpnsVoteTargetStatus::FailedBeforeSubmission + ) + }); (pending, failed) } @@ -646,4 +658,58 @@ mod tests { (false, true) ); } + + #[test] + fn cancelled_schedule_is_not_reported_as_failed() { + let voter_id = Identifier::from([7; 32]); + let mut operation = DpnsVoteOperation::new(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::NotApplied; + + assert_eq!( + scheduled_vote_journal_summary(&[operation], voter_id), + (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 mut failed = DpnsVoteOperation::new(vec![target.clone()]); + failed.created_at = 1; + failed.targets[0].status = DpnsVoteTargetStatus::Rejected; + let mut confirmed = DpnsVoteOperation::new(vec![target]); + confirmed.created_at = 2; + confirmed.targets[0].status = DpnsVoteTargetStatus::Confirmed; + + assert_eq!( + scheduled_vote_journal_summary(&[failed, confirmed], voter_id), + (false, false) + ); + } } diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index dac29db49..d5040ad6a 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -300,6 +300,21 @@ fn cancel_all_scheduled_targets(kv: &DetKv, network: Network) -> Result bool { + let mut changed = false; + for outcome in &mut operation.targets { + if matches!( + outcome.status, + DpnsVoteTargetStatus::Submitting | DpnsVoteTargetStatus::Confirming + ) { + outcome.status = DpnsVoteTargetStatus::Unconfirmed; + outcome.failure = Some(DpnsVoteFailure::ResultUnconfirmed); + changed = true; + } + } + changed +} + impl AppContext { /// Durably claim one due scheduled target before any executor can observe it. pub(crate) fn queue_scheduled_dpns_vote_target( @@ -543,24 +558,35 @@ impl AppContext { .unwrap_or_else(std::sync::PoisonError::into_inner); let kv = self.det_kv()?; for mut operation in load_operations(&kv, self.network)? { - let mut changed = false; - for outcome in &mut operation.targets { - if matches!( - outcome.status, - DpnsVoteTargetStatus::Submitting | DpnsVoteTargetStatus::Confirming - ) { - outcome.status = DpnsVoteTargetStatus::Unconfirmed; - outcome.failure = Some(DpnsVoteFailure::ResultUnconfirmed); - changed = true; - } - } - if changed { + if mark_interrupted_targets_unconfirmed(&mut operation) { persist_operation(&kv, self.network, &operation)?; } } Ok(()) } + /// Conservatively recover one operation after its executor has returned. + pub(crate) fn recover_interrupted_dpns_vote_operation( + &self, + operation_id: DpnsVoteOperationId, + ) -> Result<(), TaskError> { + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let kv = self.det_kv()?; + let Some(mut operation): Option = kv + .get(DetScope::Global, &operation_key(self.network, operation_id)) + .map_err(unreadable_operation_err)? + else { + return Ok(()); + }; + if mark_interrupted_targets_unconfirmed(&mut operation) { + persist_operation(&kv, self.network, &operation)?; + } + Ok(()) + } + pub(crate) fn record_dpns_vote_diagnostic( &self, operation_id: DpnsVoteOperationId, @@ -984,25 +1010,15 @@ mod tests { #[test] fn interrupted_submission_recovers_to_unconfirmed() { - let kv = kv(); let mut operation = operation(DpnsVoteTargetStatus::Submitting); - persist_operation(&kv, Network::Testnet, &operation).unwrap(); - - for outcome in &mut operation.targets { - if matches!( - outcome.status, - DpnsVoteTargetStatus::Submitting | DpnsVoteTargetStatus::Confirming - ) { - outcome.status = DpnsVoteTargetStatus::Unconfirmed; - outcome.failure = Some(DpnsVoteFailure::ResultUnconfirmed); - } - } - persist_operation(&kv, Network::Testnet, &operation).unwrap(); - - let restored = load_operations(&kv, Network::Testnet).unwrap(); + assert!(mark_interrupted_targets_unconfirmed(&mut operation)); assert_eq!( - restored[0].targets[0].status, + operation.targets[0].status, DpnsVoteTargetStatus::Unconfirmed ); + assert_eq!( + operation.targets[0].failure, + Some(DpnsVoteFailure::ResultUnconfirmed) + ); } } diff --git a/src/context/mod.rs b/src/context/mod.rs index 121389fc0..427ec7219 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -223,7 +223,8 @@ pub struct AppContext { /// Serializes all nonce-consuming vote submissions per voter across tasks, /// while bounding unrelated voters globally. pub(crate) dpns_vote_dispatch: DpnsVoteDispatchCoordinator, - /// Runs crash recovery exactly once before this context accepts vote work. + /// Runs crash recovery before this context first accepts vote work. + /// Re-armed only if targeted recovery cannot persist after an executor error. pub(crate) dpns_vote_recovery: tokio::sync::Mutex, /// Full in-process diagnostics keyed to sanitized durable outcomes. dpns_vote_diagnostics: diff --git a/src/model/dpns_voting.rs b/src/model/dpns_voting.rs index 69820c7a9..bd3dd0664 100644 --- a/src/model/dpns_voting.rs +++ b/src/model/dpns_voting.rs @@ -182,6 +182,16 @@ pub(crate) fn unavailable_preflight_outcome( (status, Some(DpnsVoteFailure::CurrentVoteUnavailable)) } +pub(crate) fn failed_before_broadcast_outcome( + timing: VoteTiming, +) -> (DpnsVoteTargetStatus, Option) { + let status = match timing { + VoteTiming::Scheduled(_) => DpnsVoteTargetStatus::Scheduled, + VoteTiming::Now => DpnsVoteTargetStatus::FailedBeforeSubmission, + }; + (status, Some(DpnsVoteFailure::SubmissionFailed)) +} + /// One reviewed node Γ— contest action. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct DpnsVoteTarget { From 4b508782e401435121f696f43794cf1bae415c0e Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 17 Jul 2026 08:06:20 +0000 Subject: [PATCH 014/194] fix(dpns): retry schedules with missing voters --- src/backend_task/contested_names/mod.rs | 30 +++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 335a81d03..be9c9a098 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -88,6 +88,13 @@ fn classify_vote_attempt( } } +fn missing_voter_outcome( + timing: VoteTiming, +) -> (DpnsVoteTargetStatus, Option, bool) { + let (status, failure) = failed_before_broadcast_outcome(timing); + (status, failure, matches!(timing, VoteTiming::Scheduled(_))) +} + fn classify_reconciled_vote( observed: Option, requested: ResourceVoteChoice, @@ -486,16 +493,23 @@ impl AppContext { let operation_id = operation.id; async move { 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, - DpnsVoteTargetStatus::FailedBeforeSubmission, - Some(DpnsVoteFailure::SubmissionFailed), + status, + failure, )?; + scheduled_voter_missing |= retryable; } } + if scheduled_voter_missing { + return Err(TaskError::IdentityNotFoundLocally); + } return Ok::<(), TaskError>(()); }; @@ -1039,6 +1053,18 @@ mod tests { ); } + #[test] + fn scheduled_missing_voter_remains_retryable() { + assert_eq!( + missing_voter_outcome(VoteTiming::Scheduled(42)), + ( + DpnsVoteTargetStatus::Scheduled, + Some(DpnsVoteFailure::SubmissionFailed), + true, + ) + ); + } + #[test] fn queued_schedule_remains_eligible_for_redrive() { let now_ms = 1_000_000; From 2936e6d32f3ce0304b0f7e43e06ead1667399247 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 20 Jul 2026 10:13:48 +0000 Subject: [PATCH 015/194] fix(dpns): bound vote operation journal growth --- src/context/dpns_vote_operations.rs | 354 +++++++++++++++++++++++++--- src/context/identity_db.rs | 1 + src/context/mod.rs | 9 +- 3 files changed, 331 insertions(+), 33 deletions(-) diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index d5040ad6a..b8737c200 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -8,12 +8,20 @@ use crate::model::dpns_voting::{ }; use crate::wallet_backend::{DetKv, DetScope, KvAdapterError}; use dash_sdk::dpp::dashcore::Network; +use std::collections::BTreeMap; use std::sync::Arc; const LEGACY_OPERATION_INDEX_KEY: &str = "det:dpns_vote_operations:v1"; const LEGACY_OPERATION_KEY_PREFIX: &str = "det:dpns_vote_operation:v1:"; const OPERATION_INDEX_KEY_PREFIX: &str = "det:dpns_vote_operations:v2:"; const OPERATION_KEY_PREFIX: &str = "det:dpns_vote_operation:v2:"; +const OPERATION_LOCK_INDEX_KEY_PREFIX: &str = "det:dpns_vote_operation_locks:v2:"; +const OPERATION_LOCK_INDEX_DIRTY_KEY_PREFIX: &str = "det:dpns_vote_operation_locks_dirty:v2:"; +const DPNS_VOTE_DIAGNOSTIC_LIMIT: usize = 256; + +type DpnsVoteLockIndex = BTreeMap; +type DpnsVoteDiagnosticMap = + BTreeMap<(DpnsVoteOperationId, DpnsVoteTargetKey), (u64, Arc)>; fn network_tag(network: Network) -> &'static str { match network { @@ -32,6 +40,21 @@ fn operation_key(network: Network, id: DpnsVoteOperationId) -> String { format!("{OPERATION_KEY_PREFIX}{}:{id}", network_tag(network)) } +fn operation_key_prefix(network: Network) -> String { + format!("{OPERATION_KEY_PREFIX}{}:", network_tag(network)) +} + +fn operation_lock_index_key(network: Network) -> String { + format!("{OPERATION_LOCK_INDEX_KEY_PREFIX}{}", network_tag(network)) +} + +fn operation_lock_index_dirty_key(network: Network) -> String { + format!( + "{OPERATION_LOCK_INDEX_DIRTY_KEY_PREFIX}{}", + network_tag(network) + ) +} + fn legacy_operation_key(id: DpnsVoteOperationId) -> String { format!("{LEGACY_OPERATION_KEY_PREFIX}{id}") } @@ -81,8 +104,10 @@ fn migrate_legacy_operations(kv: &DetKv, network: Network) -> Result<(), TaskErr } let mut qualified_ids = load_operation_ids(kv, network)?; - let mut changed = false; - for bytes in legacy_ids { + let mut qualified_changed = false; + let mut retained_legacy_ids = Vec::new(); + for bytes in &legacy_ids { + let bytes = *bytes; let id = DpnsVoteOperationId::from_bytes(bytes); if qualified_ids.contains(&bytes) { continue; @@ -91,15 +116,26 @@ fn migrate_legacy_operations(kv: &DetKv, network: Network) -> Result<(), TaskErr .get(DetScope::Global, &legacy_operation_key(id)) .map_err(unreadable_operation_err)? .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; - if !operation_matches_network(&operation, network)? { - continue; + match operation_matches_network(&operation, network) { + Ok(false) => continue, + Err(error) => { + retained_legacy_ids.push(bytes); + return Err(error); + } + Ok(true) => {} } + kv.put( + DetScope::Global, + &operation_lock_index_dirty_key(network), + &true, + ) + .map_err(operation_err)?; kv.put(DetScope::Global, &operation_key(network, id), &operation) .map_err(operation_err)?; qualified_ids.push(bytes); - changed = true; + qualified_changed = true; } - if changed { + if qualified_changed { kv.put( DetScope::Global, &operation_index_key(network), @@ -107,11 +143,24 @@ fn migrate_legacy_operations(kv: &DetKv, network: Network) -> Result<(), TaskErr ) .map_err(operation_err)?; } + if retained_legacy_ids.len() != legacy_ids.len() { + kv.put( + DetScope::Global, + LEGACY_OPERATION_INDEX_KEY, + &retained_legacy_ids, + ) + .map_err(operation_err)?; + } + if qualified_changed { + rebuild_lock_index(kv, network)?; + } Ok(()) } -fn load_operations(kv: &DetKv, network: Network) -> Result, TaskError> { - migrate_legacy_operations(kv, network)?; +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); @@ -126,6 +175,75 @@ fn load_operations(kv: &DetKv, network: Network) -> Result Result, TaskError> { + migrate_legacy_operations(kv, network)?; + 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 = kv + .get(DetScope::Global, &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, @@ -134,32 +252,53 @@ fn persist_operation( if !operation_matches_network(operation, network)? { return Err(TaskError::DpnsVoteJournalNetworkMismatch); } - let conflict = load_operations(kv, network)?.iter().any(|existing| { - existing.id != operation.id - && existing.targets.iter().any(|existing_outcome| { - existing_outcome.status.holds_lock() - && operation.targets.iter().any(|outcome| { - outcome.status.holds_lock() - && outcome.target.key == existing_outcome.target.key - }) - }) - }); - if conflict { - return Err(TaskError::DpnsVoteTargetBusy); + let mut locks = load_or_rebuild_lock_index(kv, network)?; + let previous_locks = locks.clone(); + locks.retain(|_, owner| *owner != operation.id); + 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); } + let mut ids = load_operation_ids(kv, network)?; + let new_operation = !ids.contains(&operation.id.to_bytes()); + let locks_changed = locks != previous_locks; + 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)?; - let mut ids = load_operation_ids(kv, network)?; - if !ids.contains(&operation.id.to_bytes()) { + 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)?; + } Ok(()) } @@ -168,12 +307,50 @@ fn write_existing_operation( network: Network, operation: &DpnsVoteOperation, ) -> Result<(), TaskError> { + persist_operation(kv, network, operation) +} + +fn prune_terminal_operations(kv: &DetKv, network: Network) -> Result { + let terminal_ids = load_operations(kv, network)? + .into_iter() + .filter(DpnsVoteOperation::is_complete) + .map(|operation| operation.id) + .collect::>(); + if terminal_ids.is_empty() { + return Ok(0); + } kv.put( DetScope::Global, - &operation_key(network, operation.id), - operation, + &operation_lock_index_dirty_key(network), + &true, ) - .map_err(operation_err) + .map_err(operation_err)?; + for id in &terminal_ids { + kv.delete(DetScope::Global, &operation_key(network, *id)) + .map_err(operation_err)?; + } + rebuild_lock_index(kv, network)?; + Ok(terminal_ids.len()) +} + +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 transition_scheduled_target_to_queued( @@ -593,10 +770,20 @@ impl AppContext { key: DpnsVoteTargetKey, error: TaskError, ) { - self.dpns_vote_diagnostics + 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((operation_id, key), Arc::new(error)); + .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( @@ -608,10 +795,19 @@ impl AppContext { .unwrap_or_else(std::sync::PoisonError::into_inner) .iter() .filter(|((id, _), _)| *id == operation_id) - .map(|(_, error)| Arc::clone(error)) + .map(|(_, (_, error))| Arc::clone(error)) .collect() } + /// Remove lock-releasing operation history when the user clears completed votes. + pub(crate) fn prune_terminal_dpns_vote_operations(&self) -> Result { + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + prune_terminal_operations(&self.det_kv()?, self.network) + } + /// Release a not-yet-submitting scheduled target after explicit cancellation. pub(crate) fn cancel_scheduled_dpns_vote_target( &self, @@ -653,16 +849,22 @@ mod tests { struct CountingKv { inner: InMemoryKv, puts: AtomicUsize, + operation_gets: AtomicUsize, } impl CountingKv { - fn reset_puts(&self) { + 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 { @@ -671,6 +873,9 @@ mod tests { 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) } @@ -812,7 +1017,7 @@ mod tests { let mut replacement = operation(DpnsVoteTargetStatus::Scheduled); replacement.targets[0].target.timing = VoteTiming::Scheduled(84); - store.reset_puts(); + store.reset_counts(); replace_scheduled_operation(&kv, Network::Testnet, &mut replacement, &key).unwrap(); @@ -1006,6 +1211,93 @@ mod tests { .unwrap(); assert!(load_operations(&kv, Network::Mainnet).unwrap().is_empty()); + assert_eq!( + kv.get::>(DetScope::Global, LEGACY_OPERATION_INDEX_KEY) + .unwrap() + .unwrap_or_default(), + Vec::<[u8; 16]>::new(), + "a terminal row for another network must not be scanned again" + ); + } + + #[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 pruning_removes_terminal_records_and_preserves_live_locks() { + let kv = kv(); + let terminal = operation(DpnsVoteTargetStatus::Confirmed); + let live = operation(DpnsVoteTargetStatus::Unconfirmed); + persist_operation(&kv, Network::Testnet, &terminal).unwrap(); + persist_operation(&kv, Network::Testnet, &live).unwrap(); + + assert_eq!(prune_terminal_operations(&kv, Network::Testnet).unwrap(), 1); + assert_eq!( + load_operations_read_only(&kv, Network::Testnet).unwrap(), + vec![live] + ); + assert!( + kv.get::( + DetScope::Global, + &operation_key(Network::Testnet, terminal.id), + ) + .unwrap() + .is_none() + ); + } + + #[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)); } #[test] diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index fc7e6a96b..52f7b0fca 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -1152,6 +1152,7 @@ impl AppContext { } prune_vote_voter_if_empty(&kv, voter)?; } + self.prune_terminal_dpns_vote_operations()?; Ok(()) } diff --git a/src/context/mod.rs b/src/context/mod.rs index 427ec7219..2fe220888 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -62,6 +62,10 @@ use crate::model::user_role::{UserRole, UserRoleCell}; const ANIMATION_REFRESH_TIME: std::time::Duration = std::time::Duration::from_millis(100); +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 @@ -227,8 +231,8 @@ pub struct AppContext { /// Re-armed only if targeted recovery cannot persist after an executor error. pub(crate) dpns_vote_recovery: tokio::sync::Mutex, /// Full in-process diagnostics keyed to sanitized durable outcomes. - dpns_vote_diagnostics: - Mutex>>, + 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>, @@ -512,6 +516,7 @@ impl AppContext { dpns_vote_dispatch: DpnsVoteDispatchCoordinator::default(), dpns_vote_recovery: tokio::sync::Mutex::new(false), 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), From 3a281b7fed9400c9a5b22a18a2fa7f81f020bcf0 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 20 Jul 2026 10:26:20 +0000 Subject: [PATCH 016/194] fix(dpns): cache voting operation views --- src/backend_task/contested_names/mod.rs | 1 + src/context/dpns_vote_operations.rs | 54 ++++++++++- src/ui/dpns/dpns_contested_names_screen.rs | 37 +++++--- src/ui/masternodes/detail_screen.rs | 24 +++-- src/ui/masternodes/list_screen.rs | 37 +++++--- src/ui/masternodes/voting_center.rs | 64 +++++++------ src/ui/state/dpns_vote_operations.rs | 103 +++++++++++++++++++++ src/ui/state/mod.rs | 1 + 8 files changed, 262 insertions(+), 59 deletions(-) create mode 100644 src/ui/state/dpns_vote_operations.rs diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index be9c9a098..d7bbd0fb0 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -236,6 +236,7 @@ impl AppContext { if *recovered { return Ok(()); } + self.migrate_dpns_vote_operations()?; self.recover_interrupted_dpns_vote_operations()?; let queued = self .dpns_vote_operations()? diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index b8737c200..737eacd3b 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -544,6 +544,15 @@ impl AppContext { /// Load every operation for this network, including completed history. pub fn dpns_vote_operations(&self) -> Result, TaskError> { + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + load_operations_read_only(&self.det_kv()?, self.network) + } + + /// Migrate legacy journals and scheduled-vote mirrors before backend recovery. + pub(crate) fn migrate_dpns_vote_operations(&self) -> Result<(), TaskError> { let _guard = self .dpns_vote_operation_guard .lock() @@ -577,7 +586,7 @@ impl AppContext { persist_operation(&kv, self.network, &operation)?; operations.push(operation); } - Ok(operations) + Ok(()) } /// Load one operation by its stable ID. @@ -589,9 +598,8 @@ impl AppContext { .dpns_vote_operation_guard .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; - migrate_legacy_operations(&kv, self.network)?; - let operation = kv + let operation = self + .det_kv()? .get(DetScope::Global, &operation_key(self.network, id)) .map_err(unreadable_operation_err)?; match operation { @@ -1241,6 +1249,44 @@ mod tests { ); } + #[tokio::test] + async fn operation_getter_does_not_migrate_legacy_scheduled_votes() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let store = Arc::new(CountingKv::default()); + let context = crate::context::test_support::test_app_context_with_kv( + temp_dir.path(), + Arc::new(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 + .insert_scheduled_votes(&[crate::backend_task::contested_names::ScheduledDPNSVote { + contested_name: "dominguez".to_owned(), + voter_id: Identifier::from([1; 32]), + choice: ResourceVoteChoice::Lock, + unix_timestamp: 42, + executed_successfully: false, + }]) + .unwrap(); + store.reset_counts(); + + assert!(context.dpns_vote_operations().unwrap().is_empty()); + assert_eq!( + store.put_count(), + 0, + "a named getter must not migrate or write legacy rows" + ); + + context.migrate_dpns_vote_operations().unwrap(); + assert_eq!(context.dpns_vote_operations().unwrap().len(), 1); + } + #[test] fn pruning_removes_terminal_records_and_preserves_live_locks() { let kv = kv(); diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 09a24f14f..3f472bc11 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -31,6 +31,7 @@ use crate::ui::components::tools_subscreen_chooser_panel::add_tools_subscreen_ch use crate::ui::components::top_panel::{add_top_panel_with_global_nav, subdued_everyday_spec}; use crate::ui::components::{BannerHandle, MessageBanner, OptionBannerExt}; use crate::ui::identities::register_dpns_name_screen::RegisterDpnsNameSource; +use crate::ui::state::dpns_vote_operations::DpnsVoteOperationSnapshot; use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; use crate::ui::{BackendTaskSuccessResult, MessageType, RootScreenType, ScreenLike, ScreenType}; @@ -125,6 +126,7 @@ pub struct DPNSScreen { pub selected_votes: Vec, pub app_context: Arc, pending_backend_task: Option, + vote_operations: DpnsVoteOperationSnapshot, /// Sorting sort_column: SortColumn, @@ -182,6 +184,14 @@ impl DPNSScreen { .load_local_voting_identities() .unwrap_or_default(); let user_identities = app_context.load_local_user_identities().unwrap_or_default(); + let vote_operations = + DpnsVoteOperationSnapshot::load(app_context).unwrap_or_else(|error| { + tracing::warn!( + ?error, + "Could not cache DPNS vote operations for the DPNS screen" + ); + DpnsVoteOperationSnapshot::default() + }); // Initialize vote handling pop-up state to hidden let identity_count = voting_identities.len(); @@ -202,6 +212,7 @@ impl DPNSScreen { owned_filter_term: String::new(), scheduled_vote_cast_in_progress: false, pending_backend_task: None, + vote_operations, dpns_subscreen, refreshing_status: RefreshingStatus::NotRefreshing, refresh_banner: None, @@ -1060,14 +1071,12 @@ impl DPNSScreen { .dpns_vote_poll_id(&vote.0.contested_name) .ok() .and_then(|vote_poll_id| { - self.app_context - .dpns_vote_target_status(&DpnsVoteTargetKey { + self.vote_operations + .target_status(&DpnsVoteTargetKey { network: self.app_context.network(), voter_id: vote.0.voter_id, vote_poll_id, }) - .ok() - .flatten() }); body.row(25.0, |mut row| { // Contested name @@ -1709,13 +1718,7 @@ impl DPNSScreen { voter_id, vote_poll_id, }; - if self - .app_context - .dpns_vote_target_status(&target_key) - .ok() - .flatten() - .is_some() - { + if self.vote_operations.target_status(&target_key).is_some() { self.bulk_vote_handling_status = VoteHandlingStatus::Failed(format!( "This node's vote for {} is already in progress. Check its result before submitting again.", selected_vote.contested_name @@ -1876,6 +1879,9 @@ impl DPNSScreen { impl ScreenLike for DPNSScreen { fn refresh(&mut self) { self.scheduled_vote_cast_in_progress = false; + if let Err(error) = self.vote_operations.refresh(&self.app_context) { + tracing::warn!(?error, "Could not refresh cached DPNS vote operations"); + } 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(); @@ -1944,6 +1950,12 @@ impl ScreenLike for DPNSScreen { } fn display_task_error(&mut self, error: &TaskError) -> bool { + 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" + ); + } let handled = scheduled_vote_sweep_is_quiet(error); if matches!(error, TaskError::ScheduledVoteSweepFailed { .. }) { self.scheduled_vote_cast_in_progress = false; @@ -1966,6 +1978,9 @@ impl ScreenLike for DPNSScreen { self.refresh(); } BackendTaskSuccessResult::ScheduledVotesInProgress(votes) => { + if let Err(error) = self.vote_operations.refresh(&self.app_context) { + tracing::warn!(?error, "Could not refresh scheduled-vote operation state"); + } // 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; diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index f21643f02..112b43ab1 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -40,6 +40,7 @@ use crate::ui::masternodes::card::{ PLATFORM_IDENTITY_STATUS_TOOLTIP, platform_identity_status_label, }; use crate::ui::masternodes::{TIP_OWNER_KEY, TIP_PAYOUT_KEY, TIP_VOTING_KEY, key_status_tokens}; +use crate::ui::state::dpns_vote_operations::DpnsVoteOperationSnapshot; use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; use crate::ui::tokens::claim_tokens_screen::ClaimTokensScreen; use crate::ui::tokens::tokens_screen::IdentityTokenBasicInfo; @@ -256,6 +257,7 @@ pub struct MasternodeDetailView { /// refresh). Active/open only β€” scheduled/past history lives on the DPNS /// Scheduled Votes screen (Β§10.7). open_contests: Vec, + vote_operations: DpnsVoteOperationSnapshot, /// Per-contest pending vote choice, keyed by normalized contested name. vote_selections: BTreeMap, /// One-shot automatic proved-state refresh for a newly opened detail view. @@ -283,6 +285,12 @@ impl MasternodeDetailView { } impl MasternodeDetailView { + pub(crate) fn refresh_vote_operations(&mut self) { + if let Err(error) = self.vote_operations.refresh(&self.app_context) { + tracing::warn!(?error, "Could not refresh node-detail voting state"); + } + } + 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); @@ -295,6 +303,14 @@ impl MasternodeDetailView { .masternode_contest_summary(voter_id) .unwrap_or_default(); let open_contests = Self::load_open_contests(app_context, voter_id); + let vote_operations = + DpnsVoteOperationSnapshot::load(app_context).unwrap_or_else(|error| { + tracing::warn!( + ?error, + "Could not cache DPNS operations for the node detail view" + ); + DpnsVoteOperationSnapshot::default() + }); Self { app_context: app_context.clone(), identity, @@ -303,6 +319,7 @@ impl MasternodeDetailView { key_presence, contest_summary, open_contests, + vote_operations, vote_selections: BTreeMap::new(), vote_state_refresh_dispatched: false, open_voting_center_requested: None, @@ -875,12 +892,7 @@ impl MasternodeDetailView { name: contest.normalized_contested_name.clone(), end_time: contest.end_time, current_vote, - locked: self - .app_context - .dpns_vote_target_status(&key) - .ok() - .flatten() - .is_some(), + locked: self.vote_operations.target_status(&key).is_some(), candidates, }) }) diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index 4f671ede9..25cd735c5 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -38,6 +38,7 @@ use crate::ui::masternodes::card::{MasternodeCard, card_heading}; use crate::ui::masternodes::detail_screen::{DetailOutcome, MasternodeDetailView}; use crate::ui::masternodes::load_form::{LoadFormOutcome, MasternodeLoadForm}; use crate::ui::masternodes::voting_center::{DpnsVotingCenter, VotingCenterOutcome}; +use crate::ui::state::dpns_vote_operations::DpnsVoteOperationSnapshot; use crate::ui::state::global_nav::PageNavSpec; use crate::ui::state::masternodes_view::{masternodes_page_nav_spec, node_pill_item}; use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; @@ -96,6 +97,7 @@ pub struct MasternodesScreen { /// Cached card data for the active network, refreshed on arrival, on /// `refresh`, and on the Refresh button. nodes: Vec, + vote_operations: DpnsVoteOperationSnapshot, /// The active sub-view (list / load / detail). view: MasternodesView, /// The load this screen dispatched and has not yet seen finish, identified by @@ -140,6 +142,7 @@ impl MasternodesScreen { let mut screen = Self { app_context: app_context.clone(), nodes: Vec::new(), + vote_operations: DpnsVoteOperationSnapshot::default(), view: MasternodesView::List, pending_load: None, pending_schedule_cancellation: None, @@ -153,6 +156,7 @@ impl MasternodesScreen { /// rather than surfacing a technical error β€” the empty state is a safe, /// meaningful fallback. fn reload(&mut self) { + self.refresh_vote_operations(); let identities = self .app_context .load_local_masternode_identities() @@ -188,6 +192,20 @@ impl MasternodesScreen { }); } + fn refresh_vote_operations(&mut self) { + if let Err(error) = self.vote_operations.refresh(&self.app_context) { + tracing::warn!( + ?error, + "Could not refresh the masternode vote-operation cache" + ); + } + match &mut self.view { + MasternodesView::Detail(detail) => detail.refresh_vote_operations(), + MasternodesView::Voting(center) => center.refresh_vote_operations(), + MasternodesView::List | MasternodesView::Load(_) | MasternodesView::Scheduled => {} + } + } + /// Settle the submitted load against the phase its own task reported, and /// release the gate once that load is finished. The single place this screen /// decides a load is over β€” its result and error callbacks fire only while it @@ -359,9 +377,7 @@ impl MasternodesScreen { /// Shared target-correlated progress, visible regardless of the active node. fn render_voting_activity(&mut self, ui: &mut egui::Ui) -> AppAction { - let Ok(mut operations) = self.app_context.dpns_vote_operations() else { - return AppAction::None; - }; + let mut operations = self.vote_operations.operations().to_vec(); operations.sort_by_key(|operation| operation.created_at); let operations = operations .into_iter() @@ -575,14 +591,12 @@ impl MasternodesScreen { ui.label( "Upcoming and unresolved targets use the same operation locks as immediate votes.", ); - let scheduled_targets = match self.app_context.dpns_vote_operations() { - Ok(operations) => scheduled_journal_targets(operations), - Err(error) => { - ui.label("Scheduled votes are unavailable. Refresh this page to try again."); - tracing::warn!(?error, "Could not load journaled DPNS schedules"); - return action; - } - }; + if !self.vote_operations.is_loaded() { + ui.label("Scheduled votes are unavailable. Refresh this page to try again."); + return action; + } + let scheduled_targets = + scheduled_journal_targets(self.vote_operations.operations().to_vec()); if scheduled_targets.is_empty() { ui.label("No scheduled votes."); return action; @@ -943,6 +957,7 @@ impl ScreenLike for MasternodesScreen { } fn display_task_error(&mut self, _error: &crate::backend_task::error::TaskError) -> bool { + self.refresh_vote_operations(); // 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). diff --git a/src/ui/masternodes/voting_center.rs b/src/ui/masternodes/voting_center.rs index bee519488..591db96bb 100644 --- a/src/ui/masternodes/voting_center.rs +++ b/src/ui/masternodes/voting_center.rs @@ -22,6 +22,7 @@ use crate::model::dpns_voting::{ }; use crate::model::qualified_identity::PrivateKeyTarget; use crate::model::qualified_identity::QualifiedIdentity; +use crate::ui::state::dpns_vote_operations::DpnsVoteOperationSnapshot; use crate::ui::state::dpns_vote_workspace::{ ComposerKeyAction, DpnsVoteComposerStep, DpnsVoteWorkspace, DraftVoteTiming, }; @@ -37,6 +38,7 @@ pub struct DpnsVotingCenter { app_context: Arc, voters: Vec, contests: Vec, + vote_operations: DpnsVoteOperationSnapshot, workspace: DpnsVoteWorkspace, submitted_operation: Option, vote_state_refresh_dispatched: bool, @@ -59,11 +61,18 @@ struct ReviewExclusion { } impl DpnsVotingCenter { + pub(crate) fn refresh_vote_operations(&mut self) { + if let Err(error) = self.vote_operations.refresh(&self.app_context) { + tracing::warn!(?error, "Could not refresh voting-center operation state"); + } + } + pub(crate) fn display_backend_task_result( &mut self, context: &BackendTaskContext, result: &BackendTaskSuccessResult, ) { + self.refresh_vote_operations(); if matches!(result, BackendTaskSuccessResult::RefreshedDpnsContests) { self.vote_state_refresh_dispatched = false; match self.app_context.ongoing_contested_names() { @@ -78,6 +87,7 @@ impl DpnsVotingCenter { } pub(crate) fn display_backend_task_error(&mut self, context: &BackendTaskContext) { + self.refresh_vote_operations(); let Some(operation_id) = self.submitted_operation else { return; }; @@ -85,11 +95,7 @@ impl DpnsVotingCenter { operation_id, self.app_context.network(), context, - self.app_context - .dpns_vote_operation(operation_id) - .ok() - .flatten() - .is_some(), + self.vote_operations.operation(operation_id).is_some(), ) { self.submitted_operation = None; self.workspace.step = DpnsVoteComposerStep::Review; @@ -110,6 +116,14 @@ impl DpnsVotingCenter { workspace.prefilter_node(voter_id); } let contests = app_context.ongoing_contested_names().unwrap_or_default(); + let vote_operations = + DpnsVoteOperationSnapshot::load(app_context).unwrap_or_else(|error| { + tracing::warn!( + ?error, + "Could not cache DPNS vote operations for the voting center" + ); + DpnsVoteOperationSnapshot::default() + }); if !preselected_contests.is_empty() { for name in preselected_contests { if contests @@ -127,6 +141,7 @@ impl DpnsVotingCenter { app_context: Arc::clone(app_context), voters, contests, + vote_operations, workspace, submitted_operation: None, vote_state_refresh_dispatched: false, @@ -549,8 +564,8 @@ impl DpnsVotingCenter { return VotingCenterOutcome::None; }; ui.heading("Voting operation"); - match self.app_context.dpns_vote_operation(operation_id) { - Ok(Some(operation)) => { + match self.vote_operations.operation(operation_id).cloned() { + Some(operation) => { for outcome in &operation.targets { ui.group(|ui| { let voter = outcome @@ -660,14 +675,14 @@ impl DpnsVotingCenter { return VotingCenterOutcome::BackToNodes; } } - Ok(None) => { + None if self.vote_operations.is_loaded() => { ui.horizontal(|ui| { ui.spinner(); ui.label("Queuing votes…"); }); } - Err(error) => { - ui.label(error.to_string()); + None => { + ui.label("This operation could not be loaded. Refresh and try again."); } } VotingCenterOutcome::None @@ -757,11 +772,7 @@ impl DpnsVotingCenter { self.app_context .dpns_current_vote_state(voter_id, vote_poll_id) .unwrap_or(DpnsCurrentVoteState::Unavailable), - self.app_context - .dpns_vote_target_status(&key) - .ok() - .flatten() - .is_some(), + self.vote_operations.target_status(&key).is_some(), ) }) .collect() @@ -806,18 +817,17 @@ impl DpnsVotingCenter { voter_id, vote_poll_id, }; - let existing_status = match self.app_context.dpns_vote_target_status(&key) { - Ok(status) => status, - Err(_) => { - exclusions.push(ReviewExclusion { - voter: self.voter_label(voter_id), - contest: name.clone(), - requested_choice: *requested_choice, - reason: "DET could not check whether this target is already in use.", - no_op: false, - }); - continue; - } + let existing_status = if self.vote_operations.is_loaded() { + self.vote_operations.target_status(&key) + } else { + exclusions.push(ReviewExclusion { + voter: self.voter_label(voter_id), + contest: name.clone(), + requested_choice: *requested_choice, + reason: "DET could not check whether this target is already in use.", + no_op: false, + }); + continue; }; let replacing_schedule = is_explicit_schedule_replacement( self.editing_scheduled_key.as_ref(), diff --git a/src/ui/state/dpns_vote_operations.rs b/src/ui/state/dpns_vote_operations.rs new file mode 100644 index 000000000..46949dce8 --- /dev/null +++ b/src/ui/state/dpns_vote_operations.rs @@ -0,0 +1,103 @@ +//! Per-screen DPNS vote-operation snapshot for immediate-mode render paths. + +use std::collections::BTreeMap; + +use crate::backend_task::error::TaskError; +use crate::context::AppContext; +use crate::model::dpns_voting::{ + DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, DpnsVoteTargetStatus, +}; + +#[derive(Debug, Clone, Default)] +pub struct DpnsVoteOperationSnapshot { + operations: Vec, + target_statuses: BTreeMap, + loaded: bool, +} + +impl DpnsVoteOperationSnapshot { + pub fn load(app_context: &AppContext) -> Result { + let mut snapshot = Self::default(); + snapshot.refresh(app_context)?; + Ok(snapshot) + } + + pub fn refresh(&mut self, app_context: &AppContext) -> Result<(), TaskError> { + self.replace(app_context.dpns_vote_operations()?); + Ok(()) + } + + 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 + } + + 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::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; + + fn operation(status: DpnsVoteTargetStatus) -> DpnsVoteOperation { + let mut operation = DpnsVoteOperation::new(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()); + } +} diff --git a/src/ui/state/mod.rs b/src/ui/state/mod.rs index 99d73f209..31926333e 100644 --- a/src/ui/state/mod.rs +++ b/src/ui/state/mod.rs @@ -8,6 +8,7 @@ pub mod account_summary; pub mod avatar_cache; pub mod contacts_view; +pub mod dpns_vote_operations; pub mod dpns_vote_workspace; pub mod global_nav; pub mod hub_selection; From 14d3aca921b7795aea6e2a682f891861f27dbd42 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 20 Jul 2026 10:34:20 +0000 Subject: [PATCH 017/194] fix(dpns): recover failed direct vote dispatches --- src/backend_task/contested_names/mod.rs | 138 ++++++++++++++++++++---- src/context/mod.rs | 21 ++++ src/wallet_backend/kv_test_support.rs | 22 ++++ 3 files changed, 163 insertions(+), 18 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index d7bbd0fb0..c3dc3f95f 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -169,15 +169,20 @@ impl AppContext { replacing_scheduled_key, _, ) => { - self.execute_dpns_vote_operation(operation, voters, replacing_scheduled_key, sdk) - .await + self.execute_dpns_vote_operation_with_recovery( + operation, + voters, + replacing_scheduled_key, + sdk, + ) + .await } ContestedResourceTask::ReconcileDpnsVoteOperation(operation_id, _) => { self.reconcile_dpns_vote_operation(operation_id, sdk).await } ContestedResourceTask::CastScheduledVote(scheduled_vote, voter) => { let operation = self.operation_for_scheduled_vote(&scheduled_vote, &voter)?; - self.execute_dpns_vote_operation(operation, vec![*voter], None, sdk) + self.execute_dpns_vote_operation_with_recovery(operation, vec![*voter], None, sdk) .await } ContestedResourceTask::CastDueScheduledVotes { @@ -643,6 +648,40 @@ impl AppContext { }) } + async fn execute_dpns_vote_operation_with_recovery( + self: &Arc, + operation: DpnsVoteOperation, + voters: Vec, + replacing_scheduled_key: Option, + sdk: &Sdk, + ) -> Result { + let operation_id = operation.id; + let result = self + .execute_dpns_vote_operation(operation, voters, replacing_scheduled_key, sdk) + .await; + if let Err(error) = &result { + self.recover_failed_dpns_vote_operation(operation_id, error) + .await; + } + result + } + + async fn recover_failed_dpns_vote_operation( + &self, + operation_id: DpnsVoteOperationId, + original_error: &TaskError, + ) { + if let Err(recovery_error) = self.recover_interrupted_dpns_vote_operation(operation_id) { + 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 = false; + } + } + async fn reconcile_dpns_vote_operation( &self, operation_id: DpnsVoteOperationId, @@ -830,7 +869,7 @@ impl AppContext { let operation_id = operation.id; async move { let result = app_context - .execute_dpns_vote_operation(operation, voters, None, &sdk) + .execute_dpns_vote_operation_with_recovery(operation, voters, None, &sdk) .await .map(|_| ()); (operation_id, result) @@ -848,20 +887,6 @@ impl AppContext { "Failed to execute a due DPNS vote operation; leaving it for recovery" ); first_error.get_or_insert(error); - if let Err(recovery_error) = - self.recover_interrupted_dpns_vote_operation(operation_id) - { - tracing::error!( - error = %recovery_error, - operation_id = %operation_id, - "Failed to recover an interrupted DPNS vote operation" - ); - // Let the next contested task retry global recovery after - // storage becomes available again. The targeted attempt is - // preferred because this fallback can see unrelated work. - *self.dpns_vote_recovery.lock().await = false; - first_error.get_or_insert(recovery_error); - } } } if let Some(error) = first_error { @@ -1034,6 +1059,83 @@ mod tests { )); } + #[tokio::test] + async fn direct_dispatch_terminal_write_failure_rearms_global_recovery() { + 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 = DpnsVoteOperation::new(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 = true; + 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, &terminal_error) + .await; + + assert!(!*context.dpns_vote_recovery.lock().await); + assert_eq!( + context + .dpns_vote_operation(operation_id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Submitting + ); + + context + .ensure_dpns_vote_recovery(&context.sdk()) + .await + .expect("the re-armed recovery pass must succeed"); + assert_eq!( + context + .dpns_vote_operation(operation_id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Unconfirmed + ); + } + #[test] fn scheduled_pre_broadcast_failure_remains_retryable() { let attempt = Err(TaskError::DpnsVoteTargetBusy); diff --git a/src/context/mod.rs b/src/context/mod.rs index 2fe220888..a5ca9b05e 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -197,6 +197,8 @@ pub struct AppContext { /// 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 @@ -505,6 +507,8 @@ impl AppContext { animations_disabled: AtomicBool::new(false), cached_settings: RwLock::new(None), app_kv, + #[cfg(test)] + det_kv_override: Mutex::new(None), secret_store, subtasks, token_balance_refresh_in_flight: AtomicBool::new(false), @@ -606,9 +610,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 diff --git a/src/wallet_backend/kv_test_support.rs b/src/wallet_backend/kv_test_support.rs index dbc62f6c0..c9eaa4449 100644 --- a/src/wallet_backend/kv_test_support.rs +++ b/src/wallet_backend/kv_test_support.rs @@ -86,6 +86,7 @@ pub(crate) struct FailingKv { inner: InMemoryKv, fail_reads: AtomicBool, puts: AtomicUsize, + fail_puts: Mutex>, } impl FailingKv { @@ -100,6 +101,11 @@ impl FailingKv { 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.fail_puts.lock().unwrap() = Some((key_fragment.to_owned(), count)); + } } impl KvStore for FailingKv { @@ -114,6 +120,22 @@ 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); + let should_fail = { + let mut failure = self.fail_puts.lock().unwrap(); + let should_fail = failure + .as_ref() + .is_some_and(|(fragment, remaining)| *remaining > 0 && key.contains(fragment)); + if should_fail && let Some((_, remaining)) = failure.as_mut() { + *remaining -= 1; + if *remaining == 0 { + *failure = None; + } + } + should_fail + }; + if should_fail { + return Err(KvError::LockPoisoned); + } self.inner.put(scope, key, value) } From 071cc1691227bdeaeb9420bede9c825dbf4b759c Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 20 Jul 2026 11:32:51 +0000 Subject: [PATCH 018/194] fix(dpns): contextualize vote diagnostics for DAPI exhaustion Co-Authored-By: OpenAI Codex --- src/backend_task/contested_names/mod.rs | 71 +++++++++++++++++++++++-- src/backend_task/mod.rs | 39 -------------- 2 files changed, 66 insertions(+), 44 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index c3dc3f95f..856984b44 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -5,7 +5,7 @@ mod vote_on_dpns_name; use crate::app::TaskResult; use crate::backend_task::BackendTaskSuccessResult; -use crate::backend_task::error::TaskError; +use crate::backend_task::error::{DapiAddressAvailability, TaskError}; use crate::context::AppContext; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, @@ -147,6 +147,17 @@ 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, @@ -550,10 +561,11 @@ impl AppContext { contested_name = %target.contested_name, "DPNS vote was submitted but remains unconfirmed" ); - app_context.record_dpns_vote_diagnostic( + app_context.record_dpns_vote_diagnostic_with_dapi_context( operation_id, target.key.clone(), error, + &sdk, ); } Ok(vote_on_dpns_name::DpnsVoteAttempt::Rejected(error)) => { @@ -563,10 +575,11 @@ impl AppContext { contested_name = %target.contested_name, "Platform rejected a DPNS vote" ); - app_context.record_dpns_vote_diagnostic( + app_context.record_dpns_vote_diagnostic_with_dapi_context( operation_id, target.key.clone(), error, + &sdk, ); } Err(error) => { @@ -579,10 +592,11 @@ impl AppContext { if matches!(target.timing, VoteTiming::Scheduled(_)) { retryable_scheduled_error = Some(error); } else { - app_context.record_dpns_vote_diagnostic( + app_context.record_dpns_vote_diagnostic_with_dapi_context( operation_id, target.key.clone(), error, + &sdk, ); } } @@ -761,10 +775,11 @@ impl AppContext { contested_name = %outcome.target.contested_name, "Could not reconcile an unconfirmed DPNS vote" ); - self.record_dpns_vote_diagnostic( + self.record_dpns_vote_diagnostic_with_dapi_context( operation_id, outcome.target.key.clone(), error, + sdk, ); } } @@ -933,6 +948,52 @@ mod tests { use super::*; use std::cell::RefCell; + 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; + + let status = dash_sdk::dapi_grpc::tonic::Status::unavailable("tcp connect error"); + TaskError::from(SdkError::DapiClientError(DapiClientError::Transport( + TransportError::Grpc(status), + ))) + } + + #[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 { .. }) + )); + } + /// VOTE-TC-033: an inner scheduled rejection is never classified as success. #[test] fn scheduled_inner_rejection_needs_attention() { diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 42fc07eee..db3cd4d2e 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -786,11 +786,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()), @@ -800,17 +795,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)), @@ -1315,29 +1299,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( From 25b89d2114368ddbfd6aa48dbbee5b13191c6aec Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 20 Jul 2026 19:55:34 +0000 Subject: [PATCH 019/194] fix(dpns-voting): address 5 review findings marked resolved but still open PR #901 review threads B, C, D, F, G on the DPNS voting journal were closed as resolved on GitHub, but two independent verification passes against the exact reviewed commit (f69db4eb) confirmed the underlying bugs were still present. Fixes: - B: add a durable Submitting->Confirming phase boundary (mark_dpns_vote_broadcast) so a crash before broadcast recovers to FailedBeforeSubmission/Scheduled instead of permanently locking the target as Unconfirmed. - C: propagate cancel_scheduled_target's race-lost result instead of discarding it; a lost cancellation race now returns TaskError::DpnsScheduledVoteAlreadyStarted and no longer deletes the legacy row. - D: add a terminal DpnsVoteTargetStatus::Cancelled distinct from NotApplied, which is now reserved for proved post-broadcast reconciliation only. - F: MasternodeDetailView's contest reads now degrade to MasternodeContestSummary::unavailable() on failure instead of unwrap_or_default(), matching list_screen's existing fail-safe pattern. - G: classify_broadcast_error distinguishes a broadcast()-call failure (nothing transmitted) from wait_for_response() post-broadcast ambiguity, classifying the former as FailedBeforeSubmission instead of Unconfirmed. Verification: formatting, targeted unit-test suites for the touched modules, and lint (all-features, warnings-as-errors) all passed clean. Co-Authored-By: Codex Sol Co-Authored-By: Claudius the Magnificent --- src/app.rs | 7 +- src/backend_task/contested_names/mod.rs | 29 +++- .../contested_names/vote_on_dpns_name.rs | 49 +++++- src/backend_task/error.rs | 6 + src/context/contested_names_db.rs | 2 +- src/context/dpns_vote_operations.rs | 149 +++++++++++++++--- src/model/dpns_voting.rs | 4 + src/ui/masternodes/detail_screen.rs | 73 ++++++--- src/ui/masternodes/list_screen.rs | 4 +- src/ui/masternodes/voting_center.rs | 9 +- 10 files changed, 286 insertions(+), 46 deletions(-) diff --git a/src/app.rs b/src/app.rs index 4b170b060..4ffe6a302 100644 --- a/src/app.rs +++ b/src/app.rs @@ -197,6 +197,7 @@ struct DpnsVoteFeedbackCounts { unconfirmed: usize, rejected: usize, failed_before_submission: usize, + cancelled: usize, not_applied: usize, in_progress: usize, } @@ -212,6 +213,7 @@ fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, MessageType, bo DpnsVoteTargetStatus::FailedBeforeSubmission => { counts.failed_before_submission += 1; } + DpnsVoteTargetStatus::Cancelled => counts.cancelled += 1, DpnsVoteTargetStatus::NotApplied => counts.not_applied += 1, DpnsVoteTargetStatus::Queued | DpnsVoteTargetStatus::Submitting @@ -219,12 +221,13 @@ fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, MessageType, bo } } let message = format!( - "Voting results: {} confirmed, {} scheduled, {} unconfirmed, {} rejected, {} failed before submission, {} not applied, and {} still in progress. Open Voting activity to review each target.", + "Voting results: {} confirmed, {} scheduled, {} unconfirmed, {} rejected, {} failed before submission, {} cancelled, {} not applied, and {} still in progress. Open Voting activity to review each target.", counts.confirmed, counts.scheduled, counts.unconfirmed, counts.rejected, counts.failed_before_submission, + counts.cancelled, counts.not_applied, counts.in_progress, ); @@ -2813,6 +2816,7 @@ mod migration_banner_tests { DpnsVoteTargetStatus::Unconfirmed, DpnsVoteTargetStatus::Rejected, DpnsVoteTargetStatus::FailedBeforeSubmission, + DpnsVoteTargetStatus::Cancelled, DpnsVoteTargetStatus::NotApplied, ]); @@ -2826,6 +2830,7 @@ mod migration_banner_tests { "1 unconfirmed", "1 rejected", "1 failed before submission", + "1 cancelled", "1 not applied", "Open Voting activity", ] { diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 856984b44..cc04221e1 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -84,7 +84,9 @@ fn classify_vote_attempt( DpnsVoteTargetStatus::Rejected, Some(DpnsVoteFailure::PlatformRejected), ), - Err(_) => failed_before_broadcast_outcome(timing), + Ok(vote_on_dpns_name::DpnsVoteAttempt::FailedBeforeSubmission(_)) | Err(_) => { + failed_before_broadcast_outcome(timing) + } } } @@ -346,6 +348,7 @@ impl AppContext { } DpnsVoteTargetStatus::Rejected | DpnsVoteTargetStatus::FailedBeforeSubmission + | DpnsVoteTargetStatus::Cancelled | DpnsVoteTargetStatus::NotApplied => { // An explicit Cast now action is a deliberate retry and // may create a new operation below. @@ -539,6 +542,8 @@ impl AppContext { } let attempt = app_context .submit_dpns_vote( + operation_id, + &target.key, &target.contested_name, target.requested_choice, &voter, @@ -582,6 +587,26 @@ impl AppContext { &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, @@ -1193,7 +1218,7 @@ mod tests { .unwrap() .targets[0] .status, - DpnsVoteTargetStatus::Unconfirmed + DpnsVoteTargetStatus::FailedBeforeSubmission ); } 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 b6a36af31..5eeaf2882 100644 --- a/src/backend_task/contested_names/vote_on_dpns_name.rs +++ b/src/backend_task/contested_names/vote_on_dpns_name.rs @@ -1,5 +1,6 @@ use crate::backend_task::error::TaskError; use crate::context::AppContext; +use crate::model::dpns_voting::{DpnsVoteOperationId, DpnsVoteTargetKey}; use crate::model::qualified_identity::QualifiedIdentity; use dash_sdk::Sdk; use dash_sdk::dpp::consensus::ConsensusError; @@ -35,6 +36,7 @@ pub(super) enum DpnsVoteAttempt { Confirmed, Unconfirmed(TaskError), Rejected(TaskError), + FailedBeforeSubmission(TaskError), } /// Build `[Value::from("dash"), Value::Text(normalized_label.to_owned())]` for a DPNS vote poll. @@ -81,9 +83,30 @@ fn classify_post_broadcast_error(error: dash_sdk::Error) -> DpnsVoteAttempt { } } +fn classify_broadcast_error(error: dash_sdk::Error) -> DpnsVoteAttempt { + match &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::FailedBeforeSubmission(TaskError::from(error)), + } +} + +fn classify_broadcast_journal_result(result: Result<(), TaskError>) -> Result<(), DpnsVoteAttempt> { + result.map_err(DpnsVoteAttempt::Unconfirmed) +} + impl AppContext { pub(super) async fn submit_dpns_vote( self: &Arc, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, name: &str, vote_choice: ResourceVoteChoice, qualified_identity: &QualifiedIdentity, @@ -175,7 +198,12 @@ impl AppContext { ensure_valid_vote_transition_structure(&state_transition, sdk)?; state_transition.broadcast_request_for_state_transition()?; if let Err(error) = state_transition.broadcast(sdk, Some(settings)).await { - return Ok(classify_post_broadcast_error(error)); + return Ok(classify_broadcast_error(error)); + } + if let Err(attempt) = + classify_broadcast_journal_result(self.mark_dpns_vote_broadcast(operation_id, key)) + { + return Ok(attempt); } match Vote::wait_for_response(sdk, state_transition, Some(settings)).await { @@ -233,4 +261,23 @@ mod tests { assert!(matches!(attempt, DpnsVoteAttempt::Unconfirmed(_))); } + + #[test] + fn broadcast_transport_error_fails_before_submission() { + let attempt = + classify_broadcast_error(dash_sdk::Error::Generic("connection refused".to_owned())); + + assert!(matches!( + attempt, + DpnsVoteAttempt::FailedBeforeSubmission(_) + )); + } + + #[test] + fn journal_failure_after_broadcast_is_unconfirmed() { + let attempt = classify_broadcast_journal_result(Err(TaskError::DpnsVoteTargetBusy)) + .expect_err("a failed journal mark must stop the confirmation wait"); + + assert!(matches!(attempt, DpnsVoteAttempt::Unconfirmed(_))); + } } diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index fd9877951..b8b7a2ac7 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -743,6 +743,12 @@ pub enum TaskError { )] DpnsVoteTargetBusy, + /// 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, + /// 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." diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index e95c0c0f3..bd9256f44 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -676,7 +676,7 @@ mod tests { timing: VoteTiming::Scheduled(42), }, ]); - operation.targets[0].status = DpnsVoteTargetStatus::NotApplied; + operation.targets[0].status = DpnsVoteTargetStatus::Cancelled; assert_eq!( scheduled_vote_journal_summary(&[operation], voter_id), diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index 737eacd3b..5eba99992 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -4,7 +4,8 @@ use super::AppContext; use crate::backend_task::error::TaskError; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, - DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, unavailable_preflight_outcome, + DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, failed_before_broadcast_outcome, + unavailable_preflight_outcome, }; use crate::wallet_backend::{DetKv, DetScope, KvAdapterError}; use dash_sdk::dpp::dashcore::Network; @@ -454,7 +455,8 @@ fn cancel_scheduled_target( if outcome.status != DpnsVoteTargetStatus::Scheduled { return Ok(false); } - outcome.status = DpnsVoteTargetStatus::NotApplied; + outcome.status = DpnsVoteTargetStatus::Cancelled; + outcome.failure = None; write_existing_operation(kv, network, &operation)?; Ok(true) } @@ -465,7 +467,8 @@ fn cancel_all_scheduled_targets(kv: &DetKv, network: Network) -> Result Result bool { +fn recover_interrupted_target_statuses(operation: &mut DpnsVoteOperation) -> bool { let mut changed = false; for outcome in &mut operation.targets { - if matches!( - outcome.status, - DpnsVoteTargetStatus::Submitting | DpnsVoteTargetStatus::Confirming - ) { - outcome.status = DpnsVoteTargetStatus::Unconfirmed; - outcome.failure = Some(DpnsVoteFailure::ResultUnconfirmed); - changed = true; + 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.failure = Some(DpnsVoteFailure::ResultUnconfirmed); + changed = true; + } + _ => {} } } changed } +fn mark_target_broadcast( + kv: &DetKv, + network: Network, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, +) -> Result<(), TaskError> { + let Some(mut operation): Option = kv + .get(DetScope::Global, &operation_key(network, operation_id)) + .map_err(unreadable_operation_err)? + else { + return Ok(()); + }; + let Some(outcome) = operation + .targets + .iter_mut() + .find(|outcome| outcome.target.key == *key) + else { + return Ok(()); + }; + if outcome.status == DpnsVoteTargetStatus::Submitting { + outcome.status = DpnsVoteTargetStatus::Confirming; + write_existing_operation(kv, network, &operation)?; + } + Ok(()) +} + impl AppContext { /// Durably claim one due scheduled target before any executor can observe it. pub(crate) fn queue_scheduled_dpns_vote_target( @@ -686,6 +720,19 @@ impl AppContext { Ok(true) } + /// Record that a target was broadcast before waiting for its result. + pub(crate) fn mark_dpns_vote_broadcast( + &self, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, + ) -> Result<(), TaskError> { + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + mark_target_broadcast(&self.det_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; @@ -735,7 +782,7 @@ impl AppContext { Ok(still_queued) } - /// Convert crash-interrupted transitions into conservative reconciliation. + /// Recover interrupted targets according to their durable broadcast phase. pub(crate) fn recover_interrupted_dpns_vote_operations(&self) -> Result<(), TaskError> { let _guard = self .dpns_vote_operation_guard @@ -743,7 +790,7 @@ impl AppContext { .unwrap_or_else(std::sync::PoisonError::into_inner); let kv = self.det_kv()?; for mut operation in load_operations(&kv, self.network)? { - if mark_interrupted_targets_unconfirmed(&mut operation) { + if recover_interrupted_target_statuses(&mut operation) { persist_operation(&kv, self.network, &operation)?; } } @@ -766,7 +813,7 @@ impl AppContext { else { return Ok(()); }; - if mark_interrupted_targets_unconfirmed(&mut operation) { + if recover_interrupted_target_statuses(&mut operation) { persist_operation(&kv, self.network, &operation)?; } Ok(()) @@ -826,8 +873,11 @@ impl AppContext { .dpns_vote_operation_guard .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - cancel_scheduled_target(&self.det_kv()?, self.network, operation_id, key)?; - Ok(()) + if cancel_scheduled_target(&self.det_kv()?, self.network, operation_id, key)? { + Ok(()) + } else { + Err(TaskError::DpnsScheduledVoteAlreadyStarted) + } } /// Release every not-yet-submitting scheduled target on this network. @@ -1094,6 +1144,22 @@ mod tests { ); } + #[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 kv = kv(); @@ -1109,6 +1175,10 @@ mod tests { 1 ); let operations = load_operations(&kv, Network::Testnet).unwrap(); + assert!(operations.iter().any(|operation| { + operation.targets[0].target.key == scheduled.targets[0].target.key + && operation.targets[0].status == DpnsVoteTargetStatus::Cancelled + })); assert!(operations.iter().any(|operation| { operation.targets[0].target.key == queued.targets[0].target.key && operation.targets[0].status == DpnsVoteTargetStatus::Queued @@ -1347,9 +1417,37 @@ mod tests { } #[test] - fn interrupted_submission_recovers_to_unconfirmed() { + fn interrupted_immediate_submission_recovers_before_submission() { + let mut operation = operation(DpnsVoteTargetStatus::Submitting); + assert!(recover_interrupted_target_statuses(&mut operation)); + 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); - assert!(mark_interrupted_targets_unconfirmed(&mut operation)); + operation.targets[0].target.timing = VoteTiming::Scheduled(42); + + assert!(recover_interrupted_target_statuses(&mut operation)); + 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)); assert_eq!( operation.targets[0].status, DpnsVoteTargetStatus::Unconfirmed @@ -1359,4 +1457,19 @@ mod tests { Some(DpnsVoteFailure::ResultUnconfirmed) ); } + + #[test] + fn successful_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 + ); + } } diff --git a/src/model/dpns_voting.rs b/src/model/dpns_voting.rs index bd3dd0664..3903415a9 100644 --- a/src/model/dpns_voting.rs +++ b/src/model/dpns_voting.rs @@ -74,6 +74,7 @@ mod tests { DpnsVoteTargetStatus::Confirmed, DpnsVoteTargetStatus::Rejected, DpnsVoteTargetStatus::FailedBeforeSubmission, + DpnsVoteTargetStatus::Cancelled, DpnsVoteTargetStatus::NotApplied, ] { assert!(!status.holds_lock(), "{status:?} must release its lock"); @@ -223,7 +224,10 @@ pub enum DpnsVoteTargetStatus { Unconfirmed, Rejected, FailedBeforeSubmission, + /// Reconciliation proved that a submitted vote was not applied. NotApplied, + /// The user cancelled a scheduled vote before it was submitted. + Cancelled, } impl DpnsVoteTargetStatus { diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index 112b43ab1..36daafaef 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -23,7 +23,9 @@ use crate::backend_task::BackendTask; use crate::backend_task::contested_names::ContestedResourceTask; use crate::backend_task::identity::{IdentityInputToLoad, IdentityLoadMode, IdentityTask}; use crate::context::AppContext; -use crate::model::contested_name::{ContestedName, MasternodeContestSummary}; +use crate::model::contested_name::{ + ContestedName, MasternodeContestSummary, MasternodeVoteStateSummary, +}; use crate::model::dpns_voting::{DpnsCurrentVoteState, DpnsVoteTargetKey}; use crate::model::fee_estimation::format_credits_as_dash; use crate::model::qualified_identity::{ @@ -54,10 +56,19 @@ const MISSING_VOTER_MESSAGE: &str = /// Β§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."; +const CONTESTS_UNAVAILABLE_MESSAGE: &str = + "Name contest information is unavailable. Refresh and try again."; /// 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})") +fn dpns_section_header(summary: MasternodeContestSummary) -> String { + if summary.vote_state == MasternodeVoteStateSummary::Unavailable { + CONTESTS_UNAVAILABLE_MESSAGE.to_owned() + } else { + format!( + "DPNS name contests to vote on ({})", + summary.open_contest_count + ) + } } /// Framing shown once above the per-contest vote controls, so a masternode @@ -299,10 +310,10 @@ impl MasternodeDetailView { .associated_voter_identity .as_ref() .map(|_| identity.identity.id()); - let contest_summary = app_context + let mut contest_summary = app_context .masternode_contest_summary(voter_id) - .unwrap_or_default(); - let open_contests = Self::load_open_contests(app_context, voter_id); + .unwrap_or_else(|_| MasternodeContestSummary::unavailable()); + let open_contests = Self::load_open_contests(app_context, voter_id, &mut contest_summary); let vote_operations = DpnsVoteOperationSnapshot::load(app_context).unwrap_or_else(|error| { tracing::warn!( @@ -328,21 +339,25 @@ impl MasternodeDetailView { } } - /// Load the contests this node can still vote on. Empty when the node has no - /// voting key (no voter id) or the read fails. + /// Load the contests this node can still vote on. fn load_open_contests( app_context: &Arc, voter_id: Option, + contest_summary: &mut MasternodeContestSummary, ) -> 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() + match app_context.ongoing_contested_names() { + Ok(contests) => contests + .into_iter() + .filter(|contest| contest.is_open_for_voter(&voter_id)) + .collect(), + Err(_) => { + *contest_summary = MasternodeContestSummary::unavailable(); + Vec::new() + } + } } /// Refresh the DPNS contest summary + open-contest list from the store. @@ -352,11 +367,13 @@ impl MasternodeDetailView { .associated_voter_identity .as_ref() .map(|_| self.identity.identity.id()); - self.contest_summary = self + let mut 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); + .unwrap_or_else(|_| MasternodeContestSummary::unavailable()); + self.open_contests = + Self::load_open_contests(&self.app_context, voter_id, &mut contest_summary); + self.contest_summary = contest_summary; } /// Build the network re-fetch dispatched by the detail Refresh button: @@ -764,11 +781,16 @@ impl MasternodeDetailView { } let mut action = None; - let header = dpns_section_header(self.contest_summary.open_contest_count); + let header = dpns_section_header(self.contest_summary); egui::CollapsingHeader::new(header) .default_open(false) .show(ui, |ui| { - if self.open_contests.is_empty() { + if self.contest_summary.vote_state == MasternodeVoteStateSummary::Unavailable { + ui.label( + RichText::new(CONTESTS_UNAVAILABLE_MESSAGE) + .color(DashColors::warning_color(dark_mode)), + ); + } else if self.open_contests.is_empty() { ui.label( RichText::new(NO_OPEN_CONTESTS_MESSAGE) .color(DashColors::text_secondary(dark_mode)), @@ -1259,8 +1281,17 @@ 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)"); + let mut summary = MasternodeContestSummary::default(); + summary.open_contest_count = 3; + assert_eq!( + dpns_section_header(summary), + "DPNS name contests to vote on (3)" + ); + + assert_eq!( + dpns_section_header(MasternodeContestSummary::unavailable()), + "Name contest information is unavailable. Refresh and try again." + ); } #[test] diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index 25cd735c5..2b1d27e3d 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -421,6 +421,7 @@ impl MasternodesScreen { DpnsVoteTargetStatus::Unconfirmed => "Checking result", DpnsVoteTargetStatus::Rejected => "Rejected", DpnsVoteTargetStatus::FailedBeforeSubmission => "Failed before submission", + DpnsVoteTargetStatus::Cancelled => "Cancelled", DpnsVoteTargetStatus::NotApplied => "Not applied", }; ui.horizontal_wrapped(|ui| { @@ -631,7 +632,8 @@ impl MasternodesScreen { DpnsVoteTargetStatus::FailedBeforeSubmission => { "Status: Failed before submission" } - DpnsVoteTargetStatus::NotApplied => "Status: Cancelled", + DpnsVoteTargetStatus::Cancelled => "Status: Cancelled", + DpnsVoteTargetStatus::NotApplied => "Status: Not applied", }); let editable = status == DpnsVoteTargetStatus::Scheduled; let disabled_reason = diff --git a/src/ui/masternodes/voting_center.rs b/src/ui/masternodes/voting_center.rs index 591db96bb..c2663557d 100644 --- a/src/ui/masternodes/voting_center.rs +++ b/src/ui/masternodes/voting_center.rs @@ -622,6 +622,7 @@ impl DpnsVotingCenter { outcome.status, DpnsVoteTargetStatus::Rejected | DpnsVoteTargetStatus::FailedBeforeSubmission + | DpnsVoteTargetStatus::Cancelled | DpnsVoteTargetStatus::NotApplied ) }) && ComponentStyles::add_secondary_button(ui, "Review again", dark_mode) @@ -635,6 +636,7 @@ impl DpnsVotingCenter { outcome.status, DpnsVoteTargetStatus::Rejected | DpnsVoteTargetStatus::FailedBeforeSubmission + | DpnsVoteTargetStatus::Cancelled | DpnsVoteTargetStatus::NotApplied ) }) @@ -650,6 +652,7 @@ impl DpnsVotingCenter { outcome.status, DpnsVoteTargetStatus::Rejected | DpnsVoteTargetStatus::FailedBeforeSubmission + | DpnsVoteTargetStatus::Cancelled | DpnsVoteTargetStatus::NotApplied ) { self.workspace @@ -1175,6 +1178,7 @@ fn status_label(status: DpnsVoteTargetStatus) -> &'static str { DpnsVoteTargetStatus::Unconfirmed => "Checking result", DpnsVoteTargetStatus::Rejected => "Rejected", DpnsVoteTargetStatus::FailedBeforeSubmission => "Failed before submission", + DpnsVoteTargetStatus::Cancelled => "Cancelled", DpnsVoteTargetStatus::NotApplied => "Not applied", } } @@ -1195,8 +1199,11 @@ fn status_explanation(status: DpnsVoteTargetStatus) -> &'static str { DpnsVoteTargetStatus::FailedBeforeSubmission => { "This vote was not submitted. Review it before trying again." } + DpnsVoteTargetStatus::Cancelled => { + "This scheduled vote was cancelled before it was submitted." + } DpnsVoteTargetStatus::NotApplied => { - "DET proved that this vote was not applied. It is safe to review it again." + "This vote was not applied. You can safely review it and try again." } } } From 79b5c00b4e0d44c2defb967aaf2ac22cb973b21d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 20 Jul 2026 20:37:48 +0000 Subject: [PATCH 020/194] fix(dpns-voting): address remaining PR 901 review findings Co-Authored-By: OpenAI Codex --- src/app.rs | 213 ++++++++++++++++++++---- src/backend_task/contested_names/mod.rs | 89 +++++++++- src/context/dpns_vote_operations.rs | 92 +++++++++- src/context/identity_db.rs | 92 +++++++++- 4 files changed, 432 insertions(+), 54 deletions(-) diff --git a/src/app.rs b/src/app.rs index 4ffe6a302..6f3e87ad8 100644 --- a/src/app.rs +++ b/src/app.rs @@ -220,28 +220,84 @@ fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, MessageType, bo | DpnsVoteTargetStatus::Confirming => counts.in_progress += 1, } } - let message = format!( - "Voting results: {} confirmed, {} scheduled, {} unconfirmed, {} rejected, {} failed before submission, {} cancelled, {} not applied, and {} still in progress. Open Voting activity to review each target.", - counts.confirmed, - counts.scheduled, - counts.unconfirmed, - counts.rejected, - counts.failed_before_submission, - counts.cancelled, - counts.not_applied, - counts.in_progress, - ); - let needs_attention = - counts.unconfirmed + counts.rejected + counts.failed_before_submission + counts.not_applied - > 0; - let message_type = if needs_attention { - MessageType::Warning - } else if counts.in_progress > 0 { - MessageType::Info + if operation.targets.is_empty() { + return ( + "This node already has that vote. Nothing was submitted.".to_owned(), + MessageType::Info, + false, + ); + } + let target_count = operation.targets.len(); + if counts.confirmed == target_count { + let message = if target_count == 1 { + "Vote cast successfully.".to_owned() + } else { + format!("{target_count} votes were cast successfully.") + }; + return (message, MessageType::Success, false); + } + if counts.scheduled == target_count { + return ( + format!("{target_count} votes were scheduled."), + MessageType::Success, + false, + ); + } + if counts.unconfirmed == target_count { + return ( + "The vote was submitted, but DET could not confirm the result yet. DET will keep checking. Do not submit it again.".to_owned(), + MessageType::Warning, + true, + ); + } + if counts.rejected == target_count { + return ( + "The vote was rejected. Review the vote and try again.".to_owned(), + MessageType::Error, + false, + ); + } + if counts.failed_before_submission == target_count { + return ( + "This vote was not submitted. Check your connection and try again.".to_owned(), + MessageType::Error, + false, + ); + } + if counts.not_applied == target_count { + return ( + "The submitted vote was not applied. Review the vote and try again.".to_owned(), + MessageType::Error, + false, + ); + } + if counts.cancelled == target_count { + return ( + "The scheduled vote was cancelled. Nothing was submitted.".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, + ); + } + + let remaining = target_count.saturating_sub(counts.confirmed); + let confirmed = counts.confirmed; + let message = if counts.unconfirmed > 0 { + format!( + "{confirmed} of {target_count} votes were confirmed. Review the remaining {remaining}. The vote was submitted, but DET could not confirm the result yet. DET will keep checking. Do not submit it again.", + ) } else { - MessageType::Success + format!( + "{confirmed} of {target_count} votes were confirmed. Review the remaining {remaining}.", + ) }; - (message, message_type, counts.unconfirmed > 0) + (message, MessageType::Warning, counts.unconfirmed > 0) } /// Action id for the SPV-sync block's "Continue in the background" escape button. @@ -2346,6 +2402,7 @@ impl App for AppState { ) { self.scheduled_vote_recovery_last_attempt.remove(&network); } + self.visible_screen_mut().refresh(); } BackendTaskSuccessResult::NetworkContextCreated { network, @@ -2809,7 +2866,102 @@ mod migration_banner_tests { } #[test] - fn mixed_vote_feedback_counts_every_terminal_category_and_guides_to_details() { + 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, + "2 votes were cast successfully.", + MessageType::Success, + false, + ), + ( + vec![ + DpnsVoteTargetStatus::Confirmed, + DpnsVoteTargetStatus::Confirmed, + ], + 1, + "2 votes were cast successfully.", + 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 DET could not confirm the result yet. DET will keep checking. Do not submit it 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, + "This node already has that 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 + ) + ); + } + } + + #[test] + fn mixed_vote_feedback_reports_partial_result_and_unconfirmed_guidance() { let operation = feedback_operation(&[ DpnsVoteTargetStatus::Confirmed, DpnsVoteTargetStatus::Scheduled, @@ -2824,21 +2976,10 @@ mod migration_banner_tests { assert_eq!(message_type, MessageType::Warning); assert!(keep_visible); - for phrase in [ - "1 confirmed", - "1 scheduled", - "1 unconfirmed", - "1 rejected", - "1 failed before submission", - "1 cancelled", - "1 not applied", - "Open Voting activity", - ] { - assert!( - message.contains(phrase), - "missing `{phrase}` in `{message}`" - ); - } + assert_eq!( + message, + "1 of 7 votes were confirmed. Review the remaining 6. The vote was submitted, but DET could not confirm the result yet. DET will keep checking. Do not submit it again." + ); } /// A frame owns one migration snapshot even if the task publishes mid-frame. diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index cc04221e1..f5cc5d40e 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -315,14 +315,13 @@ impl AppContext { scheduled_vote: &ScheduledDPNSVote, voter: &QualifiedIdentity, ) -> Result { - if let Some(mut operation) = self.dpns_vote_operations()?.into_iter().find(|operation| { + if let Some(operation) = self.dpns_vote_operations()?.into_iter().find(|operation| { operation.targets.iter().any(|outcome| { outcome.target.key.voter_id == scheduled_vote.voter_id && outcome.target.contested_name == scheduled_vote.contested_name }) }) { - let mut target_queued = false; - for outcome in &mut operation.targets { + for outcome in &operation.targets { if outcome.target.key.voter_id != scheduled_vote.voter_id || outcome.target.contested_name != scheduled_vote.contested_name { @@ -330,8 +329,14 @@ impl AppContext { } match outcome.status { DpnsVoteTargetStatus::Scheduled => { - outcome.status = DpnsVoteTargetStatus::Queued; - target_queued = true; + if !self + .queue_scheduled_dpns_vote_target(operation.id, &outcome.target.key)? + { + return Err(TaskError::DpnsVoteTargetBusy); + } + return self + .dpns_vote_operation(operation.id)? + .ok_or(TaskError::DpnsVoteOperationRecordMissing); } DpnsVoteTargetStatus::Unconfirmed | DpnsVoteTargetStatus::Queued @@ -355,9 +360,6 @@ impl AppContext { } } } - if target_queued { - return Ok(operation); - } } let target = self.dpns_vote_target( @@ -971,7 +973,11 @@ fn scheduled_target_should_execute( #[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::cell::RefCell; + use std::collections::BTreeMap; fn dapi_connection_refused_error() -> TaskError { use dash_sdk::Error as SdkError; @@ -984,6 +990,73 @@ mod tests { ))) } + 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, + } + } + + #[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 = DpnsVoteOperation::new(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 vote_diagnostic_contextualizes_exhausted_dapi_addresses() { let temp_dir = tempfile::tempdir().expect("tempdir"); diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index 5eba99992..41be3788a 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -9,7 +9,7 @@ use crate::model::dpns_voting::{ }; use crate::wallet_backend::{DetKv, DetScope, KvAdapterError}; use dash_sdk::dpp::dashcore::Network; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; const LEGACY_OPERATION_INDEX_KEY: &str = "det:dpns_vote_operations:v1"; @@ -311,10 +311,24 @@ fn write_existing_operation( persist_operation(kv, network, operation) } -fn prune_terminal_operations(kv: &DetKv, network: Network) -> Result { +fn prune_terminal_operations( + kv: &DetKv, + network: Network, + removed_scheduled_votes: &BTreeSet<([u8; 32], String)>, +) -> Result { let terminal_ids = load_operations(kv, network)? .into_iter() - .filter(DpnsVoteOperation::is_complete) + .filter(|operation| { + operation.is_complete() + && !operation.targets.is_empty() + && operation.targets.iter().all(|outcome| { + matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + && removed_scheduled_votes.contains(&( + outcome.target.key.voter_id.to_buffer(), + outcome.target.contested_name.clone(), + )) + }) + }) .map(|operation| operation.id) .collect::>(); if terminal_ids.is_empty() { @@ -582,7 +596,18 @@ impl AppContext { .dpns_vote_operation_guard .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - load_operations_read_only(&self.det_kv()?, self.network) + let kv = self.det_kv()?; + 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)?; + } + load_operations_read_only(&kv, self.network) } /// Migrate legacy journals and scheduled-vote mirrors before backend recovery. @@ -855,12 +880,15 @@ impl AppContext { } /// Remove lock-releasing operation history when the user clears completed votes. - pub(crate) fn prune_terminal_dpns_vote_operations(&self) -> Result { + pub(crate) fn prune_terminal_dpns_vote_operations( + &self, + removed_scheduled_votes: &BTreeSet<([u8; 32], String)>, + ) -> Result { let _guard = self .dpns_vote_operation_guard .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - prune_terminal_operations(&self.det_kv()?, self.network) + prune_terminal_operations(&self.det_kv()?, self.network, removed_scheduled_votes) } /// Release a not-yet-submitting scheduled target after explicit cancellation. @@ -1319,6 +1347,46 @@ mod tests { ); } + #[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" + ); + } + #[tokio::test] async fn operation_getter_does_not_migrate_legacy_scheduled_votes() { let temp_dir = tempfile::tempdir().expect("tempdir"); @@ -1360,12 +1428,20 @@ mod tests { #[test] fn pruning_removes_terminal_records_and_preserves_live_locks() { let kv = kv(); - let terminal = operation(DpnsVoteTargetStatus::Confirmed); + let mut terminal = operation(DpnsVoteTargetStatus::Confirmed); + terminal.targets[0].target.timing = VoteTiming::Scheduled(42); let live = operation(DpnsVoteTargetStatus::Unconfirmed); + let removed_scheduled_votes = BTreeSet::from([( + terminal.targets[0].target.key.voter_id.to_buffer(), + terminal.targets[0].target.contested_name.clone(), + )]); persist_operation(&kv, Network::Testnet, &terminal).unwrap(); persist_operation(&kv, Network::Testnet, &live).unwrap(); - assert_eq!(prune_terminal_operations(&kv, Network::Testnet).unwrap(), 1); + assert_eq!( + prune_terminal_operations(&kv, Network::Testnet, &removed_scheduled_votes).unwrap(), + 1 + ); assert_eq!( load_operations_read_only(&kv, Network::Testnet).unwrap(), vec![live] diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index 52f7b0fca..0fa6c242b 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -11,7 +11,7 @@ use dash_sdk::dpp::identity::accessors::IdentityGettersV0; 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::collections::{BTreeMap, BTreeSet}; use std::sync::{Arc, RwLock}; /// Identity blob slot, scoped to [`DetScope::Identity`]. One entry per @@ -1140,19 +1140,21 @@ impl AppContext { pub fn clear_executed_scheduled_votes(&self) -> std::result::Result<(), TaskError> { let kv = self.det_kv()?; let voters = load_scheduled_vote_voters(&kv)?; + let mut removed_scheduled_votes = BTreeSet::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)) if stored.executed_successfully => { kv.delete(scope, &key).map_err(scheduled_vote_err)?; + removed_scheduled_votes.insert((stored.voter_id, stored.contested_name)); } _ => {} } } prune_vote_voter_if_empty(&kv, voter)?; } - self.prune_terminal_dpns_vote_operations()?; + self.prune_terminal_dpns_vote_operations(&removed_scheduled_votes)?; Ok(()) } @@ -1541,6 +1543,92 @@ mod tests { assert_eq!(voters, vec![v1, v2]); } + #[test] + fn clearing_executed_votes_preserves_failed_and_cancelled_journal_records() { + use crate::model::dpns_voting::{ + DpnsVoteOperation, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + }; + + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp_dir.path()); + let kv = empty_kv(); + context.set_det_kv_override_for_test(kv); + let voter = Identifier::from(id(1)); + let cases = [ + ("confirmed", DpnsVoteTargetStatus::Confirmed, true), + ( + "failed", + DpnsVoteTargetStatus::FailedBeforeSubmission, + false, + ), + ("cancelled", DpnsVoteTargetStatus::Cancelled, false), + ]; + let scheduled_votes = cases + .iter() + .enumerate() + .map( + |(index, (name, _, executed_successfully))| ScheduledDPNSVote { + contested_name: (*name).to_owned(), + voter_id: voter, + choice: ResourceVoteChoice::Lock, + unix_timestamp: 42 + index as u64, + executed_successfully: *executed_successfully, + }, + ) + .collect::>(); + context.insert_scheduled_votes(&scheduled_votes).unwrap(); + for (index, (name, status, _)) in cases.iter().enumerate() { + let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + key: DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: voter, + vote_poll_id: Identifier::from([index as u8 + 1; 32]), + }, + voter_alias: None, + contested_name: (*name).to_owned(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Scheduled(42 + index as u64), + }]); + operation.targets[0].status = *status; + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + } + + context.clear_executed_scheduled_votes().unwrap(); + + let mut remaining_legacy_names = context + .get_scheduled_votes() + .unwrap() + .into_iter() + .map(|vote| vote.contested_name) + .collect::>(); + remaining_legacy_names.sort(); + assert_eq!(remaining_legacy_names, vec!["cancelled", "failed"]); + let remaining_operations = context.dpns_vote_operations().unwrap(); + assert_eq!(remaining_operations.len(), 2); + assert!(remaining_operations.iter().any(|operation| { + operation.targets[0].target.contested_name == "failed" + && operation.targets[0].status == DpnsVoteTargetStatus::FailedBeforeSubmission + })); + assert!(remaining_operations.iter().any(|operation| { + operation.targets[0].target.contested_name == "cancelled" + && operation.targets[0].status == DpnsVoteTargetStatus::Cancelled + })); + + context.migrate_dpns_vote_operations().unwrap(); + assert!( + context + .dpns_vote_operations() + .unwrap() + .iter() + .all(|operation| { + operation.targets[0].status != DpnsVoteTargetStatus::Scheduled + }) + ); + } + #[test] fn delete_scheduled_votes_for_voter_drains_scope_and_prunes_index() { let kv = empty_kv(); From 10a30907e735e23fbb5c8982861362a6c680b657 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 21 Jul 2026 01:25:43 +0000 Subject: [PATCH 021/194] fix(dpns-voting): avoid field_reassign_with_default lint error Build a MasternodeContestSummary struct literal directly in the header test instead of default-then-reassign, which the strict-warnings lint gate rejects. Co-Authored-By: Claude Sonnet 5 --- src/ui/masternodes/detail_screen.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index 36daafaef..884ae65e2 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -1281,8 +1281,10 @@ mod tests { #[test] fn tc_dpns_02_header_shows_open_contest_count() { - let mut summary = MasternodeContestSummary::default(); - summary.open_contest_count = 3; + let summary = MasternodeContestSummary { + open_contest_count: 3, + ..Default::default() + }; assert_eq!( dpns_section_header(summary), "DPNS name contests to vote on (3)" From 8335bf948c5a17db2843e5e5486d6b8eb6aa5fdf Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 21 Jul 2026 08:07:02 +0000 Subject: [PATCH 022/194] fix(dpns-voting): move broadcast phase boundary earlier, fix immediate-vote pruning The durable phase-boundary marker crossed into the ambiguous "broadcast may have been sent" state only after broadcast() returned, missing the actual danger window during the RPC call itself (which retries internally). Move the mark-broadcast journal write before the broadcast call, fail closed if it can't be recorded, and reclassify broadcast-call errors: cause-less failures stay retryable (FailedBeforeSubmission), everything past the boundary is Unconfirmed or Rejected. prune_terminal_operations required every target in a complete operation to be Scheduled and legacy-row-cleared, so any immediate- vote-only or mixed operation could never be pruned (regression from this session's earlier legacy-row safeguard). Check per-target instead: immediate targets never needed a legacy row and stay prunable; scheduled targets still require their row confirmed removed. Verified: cargo test vote_on_dpns_name (11 passed), cargo test dpns_vote_operations (26 passed), clippy clean with -D warnings. Co-Authored-By: Codex Sol Co-Authored-By: Claude Opus 4.5 --- .../contested_names/vote_on_dpns_name.rs | 146 ++++++++++++++++-- src/backend_task/error.rs | 7 + src/context/dpns_vote_operations.rs | 108 ++++++++++--- 3 files changed, 229 insertions(+), 32 deletions(-) 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 5eeaf2882..e17832df0 100644 --- a/src/backend_task/contested_names/vote_on_dpns_name.rs +++ b/src/backend_task/contested_names/vote_on_dpns_name.rs @@ -85,21 +85,45 @@ fn classify_post_broadcast_error(error: dash_sdk::Error) -> DpnsVoteAttempt { 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::FailedBeforeSubmission(error) } } - _ => DpnsVoteAttempt::FailedBeforeSubmission(TaskError::from(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)), } } -fn classify_broadcast_journal_result(result: Result<(), TaskError>) -> Result<(), DpnsVoteAttempt> { - result.map_err(DpnsVoteAttempt::Unconfirmed) +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 { @@ -197,11 +221,11 @@ impl AppContext { .map_err(dash_sdk::Error::from)?; ensure_valid_vote_transition_structure(&state_transition, sdk)?; state_transition.broadcast_request_for_state_transition()?; - if let Err(error) = state_transition.broadcast(sdk, Some(settings)).await { - return Ok(classify_broadcast_error(error)); - } - if let Err(attempt) = - classify_broadcast_journal_result(self.mark_dpns_vote_broadcast(operation_id, key)) + 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(attempt); } @@ -263,10 +287,24 @@ mod tests { } #[test] - fn broadcast_transport_error_fails_before_submission() { + fn broadcast_transport_error_after_phase_boundary_is_unconfirmed() { let attempt = classify_broadcast_error(dash_sdk::Error::Generic("connection refused".to_owned())); + assert!(matches!(attempt, DpnsVoteAttempt::Unconfirmed(_))); + } + + #[test] + fn cause_less_broadcast_rejection_fails_before_submission() { + let attempt = classify_broadcast_error( + dash_sdk::error::StateTransitionBroadcastError { + code: 1, + message: "broadcast rejected".to_owned(), + cause: None, + } + .into(), + ); + assert!(matches!( attempt, DpnsVoteAttempt::FailedBeforeSubmission(_) @@ -274,10 +312,92 @@ mod tests { } #[test] - fn journal_failure_after_broadcast_is_unconfirmed() { + fn broadcast_consensus_error_is_rejected() { + let attempt = classify_broadcast_error(dash_sdk::Error::Protocol( + dash_sdk::dpp::ProtocolError::ConsensusError(Box::new(ConsensusError::DefaultError)), + )); + + assert!(matches!(attempt, DpnsVoteAttempt::Rejected(_))); + } + + #[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 stop the confirmation wait"); + .expect_err("a failed journal mark must prevent the broadcast"); - assert!(matches!(attempt, DpnsVoteAttempt::Unconfirmed(_))); + 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 cd06bcb1d..51e039331 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -743,6 +743,13 @@ pub enum TaskError { )] 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." diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index 41be3788a..8cd14f7fc 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -322,8 +322,8 @@ fn prune_terminal_operations( operation.is_complete() && !operation.targets.is_empty() && operation.targets.iter().all(|outcome| { - matches!(outcome.target.timing, VoteTiming::Scheduled(_)) - && removed_scheduled_votes.contains(&( + !matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + || removed_scheduled_votes.contains(&( outcome.target.key.voter_id.to_buffer(), outcome.target.contested_name.clone(), )) @@ -519,25 +519,26 @@ fn mark_target_broadcast( network: Network, operation_id: DpnsVoteOperationId, key: &DpnsVoteTargetKey, -) -> Result<(), TaskError> { +) -> Result { let Some(mut operation): Option = kv .get(DetScope::Global, &operation_key(network, operation_id)) .map_err(unreadable_operation_err)? else { - return Ok(()); + return Ok(false); }; let Some(outcome) = operation .targets .iter_mut() .find(|outcome| outcome.target.key == *key) else { - return Ok(()); + return Ok(false); }; if outcome.status == DpnsVoteTargetStatus::Submitting { outcome.status = DpnsVoteTargetStatus::Confirming; write_existing_operation(kv, network, &operation)?; + return Ok(true); } - Ok(()) + Ok(false) } impl AppContext { @@ -745,12 +746,12 @@ impl AppContext { Ok(true) } - /// Record that a target was broadcast before waiting for its result. + /// Record that a target is entering the ambiguous broadcast phase. pub(crate) fn mark_dpns_vote_broadcast( &self, operation_id: DpnsVoteOperationId, key: &DpnsVoteTargetKey, - ) -> Result<(), TaskError> { + ) -> Result { let _guard = self .dpns_vote_operation_guard .lock() @@ -1426,21 +1427,41 @@ mod tests { } #[test] - fn pruning_removes_terminal_records_and_preserves_live_locks() { + fn pruning_removes_terminal_scheduled_immediate_and_mixed_records() { let kv = kv(); - let mut terminal = operation(DpnsVoteTargetStatus::Confirmed); - terminal.targets[0].target.timing = VoteTiming::Scheduled(42); + 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); - let removed_scheduled_votes = BTreeSet::from([( - terminal.targets[0].target.key.voter_id.to_buffer(), - terminal.targets[0].target.contested_name.clone(), - )]); - persist_operation(&kv, Network::Testnet, &terminal).unwrap(); + let removed_scheduled_votes = BTreeSet::from([ + ( + scheduled.targets[0].target.key.voter_id.to_buffer(), + scheduled.targets[0].target.contested_name.clone(), + ), + ( + mixed.targets[1].target.key.voter_id.to_buffer(), + mixed.targets[1].target.contested_name.clone(), + ), + ]); + 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, &removed_scheduled_votes).unwrap(), - 1 + 3 ); assert_eq!( load_operations_read_only(&kv, Network::Testnet).unwrap(), @@ -1449,7 +1470,23 @@ mod tests { assert!( kv.get::( DetScope::Global, - &operation_key(Network::Testnet, terminal.id), + &operation_key(Network::Testnet, scheduled.id), + ) + .unwrap() + .is_none() + ); + assert!( + kv.get::( + DetScope::Global, + &operation_key(Network::Testnet, immediate.id), + ) + .unwrap() + .is_none() + ); + assert!( + kv.get::( + DetScope::Global, + &operation_key(Network::Testnet, mixed.id), ) .unwrap() .is_none() @@ -1535,7 +1572,7 @@ mod tests { } #[test] - fn successful_broadcast_crosses_the_durable_phase_boundary() { + fn marking_broadcast_crosses_the_durable_phase_boundary() { let kv = kv(); let submitting = operation(DpnsVoteTargetStatus::Submitting); let key = submitting.targets[0].target.key.clone(); @@ -1548,4 +1585,37 @@ mod tests { 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() + ); + } } From 040c51838b53f5d4e29151da2179469af507656e Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 21 Jul 2026 09:32:18 +0000 Subject: [PATCH 023/194] feat(dpns): move voting into active contests --- .../01-requirements.md | 28 +- .../02-ux-spec.md | 339 ++-- .../03-test-case-spec.md | 24 +- .../04-development-plan.md | 48 +- src/app.rs | 32 +- src/context/dpns_vote_state.rs | 92 +- src/context/mod.rs | 72 - src/ui/dpns/dpns_contested_names_screen.rs | 1395 +++++++++------- src/ui/masternodes/detail_screen.rs | 565 +------ src/ui/masternodes/list_screen.rs | 518 +----- src/ui/masternodes/mod.rs | 1 - src/ui/masternodes/voting_center.rs | 1473 ----------------- src/ui/state/dpns_vote_state.rs | 79 + src/ui/state/dpns_vote_workspace.rs | 206 --- src/ui/state/mod.rs | 2 +- tests/kittest/masternode_tab.rs | 99 +- 16 files changed, 1140 insertions(+), 3833 deletions(-) delete mode 100644 src/ui/masternodes/voting_center.rs create mode 100644 src/ui/state/dpns_vote_state.rs delete mode 100644 src/ui/state/dpns_vote_workspace.rs 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 index 3d81a6791..dd8b6b8b4 100644 --- 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 @@ -6,10 +6,8 @@ Planning specification. No implementation is authorized by this document. ## Problem statement -DET exposes DPNS voting through two disconnected experiences: - -- a quick per-node section on the Masternodes detail page; and -- a legacy DPNS bulk dialog for multiple contests, nodes, and schedules. +DET previously exposed DPNS voting through disconnected per-node and bulk +experiences. The adopted design consolidates them on DPNS Active contests. Both call the same backend, but neither owns a complete, authoritative model of the operation. The result is unsafe ambiguity: a vote can be accepted while DET @@ -47,14 +45,15 @@ Everyday User workflow. | 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 | -| Legacy bulk workflow is disconnected | Bulk and scheduling live under DPNS while node management lives under Masternodes | Operators can miss existing capabilities or assume they were removed | +| Voting entry points were disconnected | Per-node and bulk flows used different UI ownership | Operators could miss capabilities or assume they were removed | ## Product decisions -1. Masternodes is the primary home for operator voting. -2. DPNS remains the home for name registration, contest discovery, and contest - history, with a route into the shared voting workspace. -3. Quick voting and bulk/scheduled voting use one shared composer and one shared +1. DPNS Active contests 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. +3. Single and bulk/scheduled voting use one review sheet and one shared operation coordinator. 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 @@ -68,12 +67,11 @@ Everyday User workflow. ### Information architecture -- **VOTE-FR-001** β€” Masternodes provides `Nodes`, `Voting`, and `Scheduled` - views under one operator-focused root. -- **VOTE-FR-002** β€” The DPNS Active Contests page links to the same Voting view; - it does not maintain a second bulk implementation. -- **VOTE-FR-003** β€” A node detail page offers quick voting and an `Open Voting - Center` action pre-filtered to that node. +- **VOTE-FR-001** β€” Masternodes provides only the node list and node detail. +- **VOTE-FR-002** β€” DPNS Active contests owns the single vote composer and + review sheet. +- **VOTE-FR-003** β€” A node detail page offers one `DPNS Voting` action that + navigates plainly to Active contests. ### Authoritative state 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 index b526819f3..dbb6d7357 100644 --- 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 @@ -1,266 +1,143 @@ # DPNS Voting Experience β€” UX Specification -## Experience principle - -Voting is one operator workflow with two entry speeds: - -- **Quick vote** β€” one selected node, usually one or a few contests. -- **Voting Center** β€” many contests, many nodes, immediate and scheduled - targets. - -Both are views over the same draft, authoritative vote state, and operation -coordinator. They must never disagree about current votes or progress. +## Adopted direction (2026-07-21) + +This revision supersedes the earlier three-step Voting Center journeys in this +document. The durable operation coordinator remains the safety model, but the +separate Masternodes `Nodes / Voting / Scheduled` navigation and full-page +wizard are no longer part of the product. The earlier design remains available +in git history as the rejected v2 exploration. + +The accepted direction keeps contest decisions where operators discover them: +DPNS Active contests. A single screen supports one vote, several contests, +several nodes, immediate casting, and scheduling. Masternode detail provides +only a plain `DPNS Voting` link to Active contests and never carries node or +contest preselection. + +## Rationale + +- Contest-first cards let an operator understand the decision before choosing + nodes or timing. +- Read-only tally chips and selectable vote controls have different shapes and + interaction states, removing the old ambiguity where a count looked like a + vote button. +- The review surface starts with the common case: all loaded nodes and cast now. +- Per-node timing remains available without making every operator configure a + matrix. +- Durable typed operations, exact target locks, and recovery messages remain + visible without requiring a separate operation page. ## Information architecture ```text Masternodes -β”œβ”€β”€ Nodes -β”‚ β”œβ”€β”€ Node cards -β”‚ └── Node detail -β”‚ β”œβ”€β”€ Keys and actions -β”‚ β”œβ”€β”€ Quick voting -β”‚ └── Open Voting Center (filtered to this node) -β”œβ”€β”€ Voting -β”‚ β”œβ”€β”€ Active contests -β”‚ β”œβ”€β”€ Vote composer -β”‚ └── Recent operations -└── Scheduled - β”œβ”€β”€ Upcoming - β”œβ”€β”€ Needs attention - └── Completed +β”œβ”€β”€ node list +└── node detail + └── DPNS Voting ──> DPNS / Active contests DPNS -β”œβ”€β”€ Active contests ── β€œVote with masternodes” ──> Masternodes / Voting -β”œβ”€β”€ Past contests -└── My usernames +β”œβ”€β”€ Active contests (all vote composition and recent activity) +β”œβ”€β”€ Past contests (human-readable outcomes) +β”œβ”€β”€ My usernames +└── Scheduled votes (human-readable node, choice, time, status) ``` -The existing DPNS bulk popup is retired after the shared Voting Center is -available. DPNS contest browsing remains; operator actions route to -Masternodes. - -## Shared concepts - -### Current vote - -Every node Γ— contest row shows one of: - -- `Not voted` -- `Current vote: Abstain` -- `Current vote: Lock` -- `Current vote: {candidate}` -- `Checking current vote…` -- `Current vote unavailable` - -An existing vote does not remove the contest. Selecting a different choice is -labeled as a change. - -`Current vote unavailable` disables that node's choice controls and offers -`Refresh vote state`. DET never treats an unavailable query as `Not voted`. - -Node cards summarize both concepts, for example: - -> 3 active contests Β· 1 needs a vote - -When every active contest has a current vote: - -> Votes cast in all active contests - -### Target +## Active contests -A target is one requested action for one node on one contest. Batch progress -and results are always expressed in targets, never only in aggregate. +Contests render as cards, grouped in this order: -### Operation +1. `Needs your vote` +2. `Voted` +3. `Not votable by your nodes` -An operation is the reviewed collection of targets submitted together. It owns -progress across screens and process restarts. - -## Journey A β€” Quick vote from a node - -1. Priya opens a node. -2. The DPNS section shows all active contests and the node's current choice. -3. Priya selects a new choice on one or more rows. -4. The primary action becomes `Review 1 vote` or `Review {n} votes`. -5. Review lists current β†’ requested choice for this node. -6. Priya chooses `Cast now` or `Schedule instead`, then confirms. -7. Affected rows become read-only and show `Submitting…` or `Scheduled`. -8. Priya may navigate elsewhere. A global banner links to operation progress. -9. Confirmed rows update their current vote in place; they do not disappear. +Each group is collapsible. The first group opens by default; the last group is +dimmed and its vote controls are disabled. A filter remains available. ```text -DPNS name contests (3) - -alice.dash -Current vote: Abstain -( Abstain ) ( Lock ) ( Vote for alice ) - -dominguez.dash -Not voted -( Abstain ) ( Lock ) ( Vote for dominguez ) - - [ Review 1 vote ] - [ Open Voting Center ] +β”Œβ”€ Active contests ─────────────────────────────────────────────┐ +β”‚ Filter by name: [________________] β”‚ +β”‚ Each node can change its vote up to four times after its β”‚ +β”‚ initial vote. β”‚ +β”‚ β”‚ +β”‚ β–Ύ Needs your vote (2) β”‚ +β”‚ β”Œβ”€ alice.dash Voting ends in 2d ─┐ β”‚ +β”‚ β”‚ [Lock name] (12 votes) [Abstain] (3 votes) β”‚ β”‚ +β”‚ β”‚ [Vote for Alice] (20 votes) 3MN5mF…s8Qp β”‚ β”‚ +β”‚ β”‚ [Vote for Alyce] (18 votes) 7Yk2aP…d1Rt β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β–Έ Voted (4) β”‚ +β”‚ β–Έ Not votable by your nodes (1) β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ Votes ready to cast: 1 [Review and cast] β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` -## Journey B β€” Bulk vote or schedule - -The composer is a three-step full-page flow, not a transient popup. Nodes come -first so every later β€œcurrent vote” summary has a defined node scope. - -### Step 1: Nodes and timing - -Priya selects nodes and chooses timing. `Set all` applies timing only; it does -not alter contest choices. - -```text -Voting Center Step 1 of 3: Nodes and timing - -Set all: [ Cast now v ] [ Apply ] - -[x] Eve Mainnet Cast now -[x] Backup Evo Schedule: 2026-07-20 18:00 UTC -[ ] Test Operator Do not use this node - - [ Next: Choose votes ] -``` +Parenthesized tally chips are labels, not buttons. `selectable_label` controls +contain an action phrase such as `Vote for Alice`, `Lock name`, or `Abstain`. +Selecting the active choice again removes it from the draft. -### Step 2: Votes +## Review and cast sheet -Priya selects contests and a requested choice for each contest. Current-state -summaries cover only the nodes selected in Step 1. +The sticky tray opens a sheet in the same Active-contests screen. The default +applies the chosen contests to all loaded voting nodes and casts now. ```text -Step 2 of 3: Votes - -[ ] alice.dash Current across selected nodes: Mixed - Abstain | Lock | Vote for alice - -[x] dominguez.dash Current across selected nodes: 1 not voted, 1 Lock - Abstain | Lock | Vote for dominguez - - [ Back ] [ Review 2 targets ] +β”Œβ”€ Review and cast ───────────────────────────────────────┐ +β”‚ Selected votes β”‚ +β”‚ alice.dash β†’ Vote for Alice Β· voting ends in 2d β”‚ +β”‚ β”‚ +β”‚ All my nodes β”‚ +β”‚ Cast timing: [Cast now v] β”‚ +β”‚ β”‚ +β”‚ β–Έ Choose per node (advanced) β”‚ +β”‚ β”‚ +β”‚ [Cancel] [Submit votes] β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` -### Step 3: Review - -The review expands the cartesian product into exact targets. No-op targets are -removed and explained. - -```text -Step 3 of 3: Review - -Node Contest Current Requested When -Eve Mainnet dominguez.dash Not voted dominguez Now -Backup Evo dominguez.dash Lock dominguez Jul 20 - -2 targets total. Each vote uses Platform credits. +Timing choices are `Cast now`, `Schedule`, and `Do not use this node`. +Scheduling exposes the existing day/hour/minute controls and reminds the user +that DET must stay open and connected. The advanced disclosure exposes the +same timing choice for each node. Review removes exact no-op targets, blocks +targets already held by an unresolved operation, and refuses submission when +proved current state is unavailable. - [ Back ] [ Submit 2 targets ] -``` +## Submission and recovery -## Journey C β€” Operation progress +`SubmitDpnsVoteOperation` is the only submit path. Explicit submissions, +manual scheduled casting, and `Check again` show the full-window progress +overlay until a terminal task result or error arrives. -After submit, the review becomes an operation detail page. +Recent voting activity appears below the contest groups and uses typed target +states: ```text -Submitting votes -1 confirmed Β· 1 checking - -βœ“ Eve Mainnet / dominguez.dash - Vote confirmed: dominguez - -… Backup Evo / dominguez.dash - The vote was submitted. DET is checking the result. - - [ Continue in background ] +β”Œβ”€ Recent voting activity ─────────────────────────────────┐ +β”‚ alice.dash β€” Vote for Alice β€” Confirmed β”‚ +β”‚ example.dash β€” Lock name β€” Confirmation is still checked β”‚ +β”‚ This vote may already have been submitted. Do not submit it β”‚ +β”‚ again. [Check again] β”‚ +β”‚ other.dash β€” Abstain β€” Not applied [Review again]β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` -Target rows expose technical details only through the standard expandable -details affordance. If a transition hash is available, developer mode may show -and copy it. - -## Journey D β€” Unconfirmed result - -1. Broadcast succeeds. -2. Waiting for the result fails without a structured consensus cause. -3. The target becomes `Unconfirmed`; it is not labeled failed. -4. The exact node Γ— contest target remains locked. -5. DET retries the result wait and/or fetches the proved current vote. -6. If the requested choice appears, the target becomes `Confirmed`. -7. If authoritative reconciliation proves it was not applied, the target - becomes `Not applied` and offers `Submit again`. -8. If Platform remains unavailable, the persistent action is `Check again`. - -Banner copy: - -> The vote was submitted, but DET could not confirm the result yet. DET will -> keep checking. Do not submit it again. - -## Journey E β€” Scheduled vote - -- Scheduled targets appear immediately in `Masternodes > Scheduled`. -- Before execution begins, `Edit schedule` and `Cancel scheduled vote` remain - available. -- At execution time, status changes from `Scheduled` to `Submitting`. -- A confirmed result becomes `Completed`. -- A definite rejection becomes `Needs attention`. -- An ambiguous result becomes `Checking result`; it is never automatically - rebroadcast. - -## Control state - -| Target state | Choice controls | Submit action | Other targets | -|---|---|---|---| -| Draft | Enabled | Enabled when draft has changes | Enabled | -| Current vote unavailable | Disabled for that node | `Refresh vote state` | Enabled | -| Scheduled | Read-only for that target | `Edit schedule` | Enabled | -| Queued / Submitting / Confirming | Disabled | Spinner + status | Enabled | -| Unconfirmed | Disabled | `Check again` | Enabled | -| Confirmed | Enabled for a deliberate change | No draft action | Enabled | -| Rejected / Failed before submission / Not applied | Enabled after correction | `Review again` | Enabled | - -The disabled tooltip names the exact reason, for example: - -> This node's vote for dominguez.dash is still being confirmed. - -## Feedback matrix - -| Outcome | Type | Primary copy | -|---|---|---| -| One confirmed | Success | `Vote cast successfully.` | -| All batch targets confirmed | Success | `{count} votes were cast successfully.` | -| Scheduled | Success | `{count} votes were scheduled.` | -| Partial | Warning | `{confirmed} of {total} votes were confirmed. Review the remaining {remaining}.` | -| Unconfirmed | Warning, persistent | `The vote was submitted, but DET could not confirm the result yet. DET will keep checking. Do not submit it again.` | -| Structured rejection | Error | Typed, user-actionable rejection message | -| Failed before broadcast | Error | `This vote was not submitted. {action}` | -| No-op | Info | `This node already has that vote. Nothing was submitted.` | - -## Navigation and persistence - -- Operation progress is not owned by a screen instance. -- Leaving Masternodes never clears an active operation. -- Returning to any voting entry point reads current operation state and locks - affected targets. -- On startup, DET restores scheduled and unresolved targets before voting - controls become available. -- Switching networks swaps to that network's independent voting workspace. +`Confirmed`, `Confirming`, `Unconfirmed`, `Rejected`, `Not applied`, and +pre-submission failure are never inferred from strings. Unconfirmed targets +retain their lock and explicitly warn against resubmission. -## Accessibility and interaction +## Scheduled votes and history -- Use styled buttons and semantic status colors with text labels. -- Minimum click targets follow the shared button component. -- `Enter` advances or submits only on the review step. -- `Escape` closes a draft review but cannot cancel a submitted operation. -- Focus moves to the step heading after Back/Next. -- Progress text and spinner are both present; no status is color-only. -- Disabled controls use the standard disabled tooltip policy. +Scheduled votes remain a DPNS sub-screen. Rows show `{name}.dash`, node alias +or shortened Base58 identifier, a human-readable choice, absolute UTC time plus +relative time, typed status, and only valid actions. Past contests describe the +winner or locked outcome in words rather than exposing an unexplained raw ID. -## Responsive behavior +## Accessibility and responsive behavior -- Desktop: contest table and node/timing table use the full island panel. -- Narrow width: target rows become stacked cards showing Node, Contest, Current, - Requested, Timing, and Status. -- Operation progress remains usable without horizontal scrolling. +- Tally chips have no click or keyboard behavior. +- Every selectable control contains the action and target in its label. +- Disabled controls explain what must change before voting is available. +- Cards wrap vote choices before truncating identifiers. +- The review tray remains outside the scrolling card region. +- The advanced matrix starts collapsed and remains keyboard reachable. +- Status is always expressed in text; color is supplementary. 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 index 775f44ff3..ae6235c2f 100644 --- 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 @@ -5,7 +5,7 @@ | ID | Description | Preconditions | Steps | Expected outcome | Requirements | |---|---|---|---|---|---| | VOTE-TC-001 | Current vote loads from Platform | Node has a proved Lock vote | Refresh Voting | Row shows `Current vote: Lock` | FR-010, FR-011 | -| VOTE-TC-002 | Existing vote remains visible | Node already voted; contest active | Open node detail | Contest remains listed and change controls are available | FR-012 | +| VOTE-TC-002 | Existing vote remains visible | Node already voted; contest active | Open Active contests | Contest appears in Voted and change controls are available | FR-012 | | VOTE-TC-003 | Current choice is a no-op | Current vote is Lock | Select Lock and review | Target is removed; nothing can be submitted | FR-013, FR-025 | | VOTE-TC-004 | Coherent refresh | Contest tally and current vote both changed | Refresh | One snapshot shows both new values | FR-014 | | VOTE-TC-005 | Vote query is per node | One node, 100 contests | Refresh | Identity-votes query runs once for the node, not 100 times | NFR-007 | @@ -13,14 +13,14 @@ | VOTE-TC-007 | Vote query failure is not `Not voted` | Proved identity-votes query fails | Open voting | State is unavailable; affected submit controls are disabled | FR-016, NFR-004 | | VOTE-TC-008 | Node summary distinguishes active and unvoted | Three active contests; node voted in two | View node card | Summary says three active and one needs a vote | FR-017 | -## Quick voting +## Single-contest voting | ID | Description | Preconditions | Steps | Expected outcome | Requirements | |---|---|---|---|---|---| -| VOTE-TC-010 | Quick single vote | Node detail, one draft choice | Review and submit | One target is created for the selected node and contest | FR-020, FR-024 | -| VOTE-TC-011 | Quick multi-contest vote | Node detail, three draft choices | Review | Review shows three exact targets | FR-020, FR-031 | -| VOTE-TC-012 | Quick schedule | Node detail, one draft | Choose Schedule in review | Target appears in Scheduled with the chosen time | FR-023, FR-050 | -| VOTE-TC-013 | Missing voting key | Node lacks voter key | Open voting | Actionable add-key state appears; submit is unavailable | FR-003 | +| VOTE-TC-010 | Single vote | Active contests, one draft choice | Review and submit | One target is created per selected loaded node for that contest | FR-020, FR-024 | +| VOTE-TC-011 | Multi-contest vote | Active contests, three draft choices | Review | Review shows the exact node Γ— contest targets | FR-020, FR-031 | +| VOTE-TC-012 | Schedule one choice | Active contests, one draft | Choose Schedule in review | Targets appear in Scheduled with the chosen time | FR-023, FR-050 | +| VOTE-TC-013 | Missing voting key | No loaded node can vote | Open Active contests | Contest appears under Not votable and submit is unavailable | FR-003 | ## Bulk voting @@ -29,9 +29,9 @@ | VOTE-TC-020 | Multiple contests and nodes | Two contests, three nodes | Select all and review | Six exact targets are listed | FR-021, FR-024 | | VOTE-TC-021 | Set all timing | Three selected nodes | Apply Schedule to all | All nodes receive the same schedule | FR-022, FR-023 | | VOTE-TC-022 | Per-node override | Set all Cast now | Override one node to Schedule | Review reflects two Now and one Scheduled target | FR-022 | -| VOTE-TC-023 | DPNS route reuses workspace | DPNS Active Contests visible | Click `Vote with masternodes` | Shared Masternodes Voting view opens; no legacy popup appears | FR-002 | -| VOTE-TC-024 | Node route prefilters | Node detail visible | Click `Open Voting Center` | Voting view opens with only that node selected | FR-003 | -| VOTE-TC-025 | Current summary uses selected nodes | Three nodes loaded; two selected | Open Votes step | `Current across selected nodes` excludes the unselected node | FR-011, FR-021 | +| VOTE-TC-023 | Sticky review tray | Active contests visible | Select a choice | `Votes ready to cast: 1` appears and Review and cast opens in place | FR-002 | +| VOTE-TC-024 | Node navigation is plain | Node detail visible | Click `DPNS Voting` | Active contests opens without a node filter or carried draft | FR-003 | +| VOTE-TC-025 | Advanced node overrides | Three nodes loaded | Open Review and cast, expand advanced choices | All nodes default to Cast now and each can be overridden | FR-011, FR-021 | ## Execution correctness @@ -48,7 +48,7 @@ | ID | Description | Preconditions | Steps | Expected outcome | Requirements | |---|---|---|---|---|---| | VOTE-TC-040 | Double click | Submit enabled | Double-click Submit | Exactly one operation and one target broadcast are created | FR-034, FR-035 | -| VOTE-TC-041 | Cross-screen duplicate | Target is confirming from quick vote | Open Voting Center | Same node Γ— contest target is disabled with explanation | FR-034, FR-036 | +| VOTE-TC-041 | Cross-screen duplicate | Target is confirming | Return to Active contests | Same node Γ— contest target is disabled with explanation | FR-034, FR-036 | | VOTE-TC-042 | Unrelated target stays usable | One target confirming | Select another node or contest | Unrelated target remains enabled | Product decision 7 | | VOTE-TC-043 | Navigation preserves lock | Submit, leave page, return before result | Inspect target | Progress and lock remain active | FR-036 | | VOTE-TC-044 | Restart preserves lock | Persist unresolved target; restart | Open Voting | Target is restored and reconciled before resubmission is allowed | FR-037, NFR-003 | @@ -80,8 +80,8 @@ | ID | Description | Preconditions | Steps | Expected outcome | Requirements | |---|---|---|---|---|---| -| VOTE-TC-070 | Progress button state | Target submitting | Inspect action | Disabled styled action shows spinner, text, and tooltip | FR-035, NFR-005 | -| VOTE-TC-071 | Keyboard review | Composer draft ready | Tab, Enter, Escape | Focus order is logical; Enter submits only at review; Escape closes only drafts | NFR-005 | +| VOTE-TC-070 | Blocking submission feedback | Target submitting | Inspect screen | Full-window progress overlay remains visible until success or error | FR-035, NFR-005 | +| VOTE-TC-071 | Keyboard review | Review sheet open | Tab and activate controls | Focus order is logical and advanced node choices are reachable | NFR-005 | | VOTE-TC-072 | Network isolation | Testnet target unresolved | Switch Mainnet | Mainnet has no Testnet locks or operation rows | NFR-008 | | VOTE-TC-073 | No secret persistence | Operation stored | Inspect serialized operation | No private key or WIF bytes are present | NFR-009 | | VOTE-TC-074 | Complete message units | All new copy | Localization audit | Strings are complete and do not parse technical errors | NFR-006 | 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 index c5ee60834..dd06596a2 100644 --- 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 @@ -198,38 +198,26 @@ backend tasks. One operation owns both kinds of targets. ### Non-rendering state -Add `src/ui/state/dpns_vote_workspace.rs` for: - -- draft contest choices; -- selected nodes and timing; -- current composer step; -- validation and no-op explanations; -- conversion to a typed operation request. +Cache proved current-vote state once when Active contests is built or explicitly +refreshed. Rendering and draft changes read only this in-memory snapshot; they +never perform synchronous KV reads in the egui frame loop. ### Shared rendering -Add `src/ui/components/dpns_vote_composer.rs` implementing the three steps from -the UX specification. - -The compact node-detail controls use the same draft/view-model logic and open -the shared review step. They do not implement a separate submit path. +Active contests owns card grouping, draft choices, the sticky review tray, and +the in-screen `Review and cast` sheet. The sheet expands the draft into typed +node Γ— contest targets and submits one `DpnsVoteOperation`. ### Masternodes views -Extend the Masternodes root state with: - -- Nodes -- Voting -- Scheduled -- Operation detail - -The root observes coordinator snapshots, so progress survives sub-view changes. +Keep the Masternodes root limited to the node list and node detail. Detail has a +single `DPNS Voting` button that opens DPNS Active contests without prefiltering. ### DPNS integration -Replace the legacy bulk popup with `Vote with masternodes`, routing selected -contests into the shared Voting workspace. Keep Active, Past, and My Usernames -contest/name browsing in DPNS. +Replace the legacy table and top-bar trigger with grouped contest cards, a +sticky `Votes ready to cast` tray, and the in-screen review sheet. Keep Active, +Past, My usernames, and Scheduled votes in DPNS. ## Message handling @@ -265,12 +253,12 @@ without every voting entry point using it. - Fix scheduled false-success behavior at the executor boundary. - Covers VOTE-TC-030 through VOTE-TC-056. -### Workstream C β€” Shared Voting Center +### Workstream C β€” Active-contests voting -- Add shared composer and Masternodes Voting view. -- Integrate quick node flow. -- Add operation detail/progress. -- Route DPNS Active Contests into the shared workspace. +- Add grouped contest cards and the review sheet. +- Replace node-detail voting with plain DPNS navigation. +- Add operation progress and recovery to Active contests. +- Remove the Masternodes operator sub-navigation and wizard. - Covers VOTE-TC-010 through VOTE-TC-025 and VOTE-TC-070 through VOTE-TC-076. ### Workstream D β€” Scheduled consolidation and migration @@ -299,5 +287,5 @@ reviewed as one atomic UX change. - Revise DPN-005, DPN-006, DPN-007, and MN-003 acceptance criteria. - Correct the protocol note to five votes total: initial vote plus four changes. - Add a user story for operation recovery across navigation/restart. -- Replace the previous Masternodes design decision that made scheduled voting - undiscoverable from the operator page. +- Document DPNS Active contests as the single voting home and keep Scheduled + votes discoverable in the DPNS sub-navigation. diff --git a/src/app.rs b/src/app.rs index bba79ea9a..b9a4cab2e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -325,7 +325,7 @@ fn identity_hub_is_visible(selected: RootScreenType, screen_stack_is_empty: bool selected == RootScreenType::RootScreenIdentityHub && screen_stack_is_empty } -fn dpns_result_needs_hidden_masternode_route( +fn dpns_result_needs_hidden_active_contests_route( selected: RootScreenType, screen_stack_is_empty: bool, result: &BackendTaskSuccessResult, @@ -334,7 +334,7 @@ fn dpns_result_needs_hidden_masternode_route( result, BackendTaskSuccessResult::DpnsVoteOperationUpdated { .. } | BackendTaskSuccessResult::RefreshedDpnsContests - ) && (selected != RootScreenType::RootScreenMasternodes || !screen_stack_is_empty) + ) && (selected != RootScreenType::RootScreenDPNSActiveContests || !screen_stack_is_empty) } /// Plain, jargon-free descriptions for the SPV-sync block (Everyday-User rule: @@ -2048,12 +2048,12 @@ impl AppState { } } - fn route_dpns_vote_result_to_hidden_masternodes( + fn route_dpns_vote_result_to_hidden_active_contests( &mut self, context: &BackendTaskContext, result: &BackendTaskSuccessResult, ) { - if !dpns_result_needs_hidden_masternode_route( + if !dpns_result_needs_hidden_active_contests_route( self.selected_main_screen, self.screen_stack.is_empty(), result, @@ -2062,9 +2062,10 @@ impl AppState { } if let Some(screen) = self .main_screens - .get_mut(&RootScreenType::RootScreenMasternodes) + .get_mut(&RootScreenType::RootScreenDPNSActiveContests) { screen.display_backend_task_result(context, result.clone()); + screen.refresh(); } } @@ -2216,7 +2217,10 @@ impl App for AppState { } => { let unboxed_message = *message; self.route_contact_request_result_to_hidden_hub(&unboxed_message); - self.route_dpns_vote_result_to_hidden_masternodes(&context, &unboxed_message); + self.route_dpns_vote_result_to_hidden_active_contests( + &context, + &unboxed_message, + ); match unboxed_message { BackendTaskSuccessResult::None => {} BackendTaskSuccessResult::Refresh => { @@ -3340,32 +3344,32 @@ mod dpns_result_routing_tests { use crate::model::dpns_voting::DpnsVoteOperationId; #[test] - fn correlated_vote_result_routes_when_masternodes_root_is_hidden() { + fn correlated_vote_result_routes_when_active_contests_is_hidden() { let result = BackendTaskSuccessResult::DpnsVoteOperationUpdated { network: Network::Testnet, operation_id: DpnsVoteOperationId::from_bytes([7; 16]), }; - assert!(dpns_result_needs_hidden_masternode_route( + assert!(dpns_result_needs_hidden_active_contests_route( RootScreenType::RootScreenWalletsBalances, true, &result, )); - assert!(dpns_result_needs_hidden_masternode_route( - RootScreenType::RootScreenMasternodes, + assert!(dpns_result_needs_hidden_active_contests_route( + RootScreenType::RootScreenDPNSActiveContests, false, &result, )); - assert!(!dpns_result_needs_hidden_masternode_route( - RootScreenType::RootScreenMasternodes, + assert!(!dpns_result_needs_hidden_active_contests_route( + RootScreenType::RootScreenDPNSActiveContests, true, &result, )); } #[test] - fn refreshed_contests_route_when_masternodes_root_is_hidden() { - assert!(dpns_result_needs_hidden_masternode_route( + fn refreshed_contests_route_when_active_contests_is_hidden() { + assert!(dpns_result_needs_hidden_active_contests_route( RootScreenType::RootScreenWalletsBalances, true, &BackendTaskSuccessResult::RefreshedDpnsContests, diff --git a/src/context/dpns_vote_state.rs b/src/context/dpns_vote_state.rs index d036b04ed..7d6bf81fb 100644 --- a/src/context/dpns_vote_state.rs +++ b/src/context/dpns_vote_state.rs @@ -86,7 +86,7 @@ fn save_snapshot( } fn snapshot_vote_state( - snapshot: Option, + snapshot: Option<&StoredCurrentVotes>, vote_poll_id: Identifier, checked_at_ms: u64, ) -> DpnsCurrentVoteState { @@ -135,13 +135,33 @@ impl AppContext { voter_id: Identifier, vote_poll_id: Identifier, ) -> Result { + let snapshot = load_snapshot(&self.det_kv()?, self.network, &voter_id)?; Ok(snapshot_vote_state( - load_snapshot(&self.det_kv()?, self.network, &voter_id)?, + snapshot.as_ref(), vote_poll_id, now_ms(), )) } + /// Read one node's current choices for many polls with a single storage read. + pub fn dpns_current_vote_states( + &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(); + Ok(vote_poll_ids + .into_iter() + .map(|vote_poll_id| { + ( + vote_poll_id, + snapshot_vote_state(snapshot.as_ref(), vote_poll_id, checked_at_ms), + ) + }) + .collect()) + } + /// Refresh proved vote state once per loaded masternode, paging only as needed. pub(crate) async fn refresh_dpns_vote_states(&self, sdk: &Sdk) { let voters = match self.load_local_masternode_identities() { @@ -273,7 +293,38 @@ fn now_ms() -> u64 { 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())) @@ -377,8 +428,43 @@ mod tests { }; assert_eq!( - snapshot_vote_state(Some(snapshot), poll, CURRENT_VOTE_MAX_AGE_MS + 2), + snapshot_vote_state(Some(&snapshot), poll, CURRENT_VOTE_MAX_AGE_MS + 2), DpnsCurrentVoteState::Checking ); } + + #[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(), + }, + ) + .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/mod.rs b/src/context/mod.rs index 85a70aa93..b4ce2dd7d 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -45,7 +45,6 @@ use dash_sdk::dpp::state_transition::batch_transition::methods::StateTransitionC use dash_sdk::dpp::system_data_contracts::{SystemDataContract, load_system_data_contract}; use dash_sdk::dpp::version::PlatformVersion; use dash_sdk::dpp::version::v11::PLATFORM_V11; -use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; use dash_sdk::platform::DataContract; use dash_sdk::platform::Identifier; use egui::Context; @@ -77,15 +76,6 @@ pub(crate) struct ContactRequestActionClaim<'a> { request_id: Identifier, } -/// One-shot navigation into the Masternodes DPNS operator workflow. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum DpnsOperatorRoute { - Voting { - choices: BTreeMap, - }, - Scheduled, -} - impl Drop for ContactRequestActionClaim<'_> { fn drop(&mut self) { self.registry @@ -248,8 +238,6 @@ pub struct AppContext { /// the hub adopts it on return (forward-courier, mirrors /// `pending_wallet_selection`). pub(crate) pending_identity_selection: Mutex>, - /// One-shot DPNS deep link consumed by the Masternodes Voting Center. - pending_dpns_operator_route: Mutex>, /// Cached fee multiplier permille from current epoch (1000 = 1x, 2000 = 2x) /// Updated when epoch info is fetched from Platform fee_multiplier_permille: AtomicU64, @@ -525,7 +513,6 @@ impl AppContext { selected_single_key_hash: Mutex::new(selected_single_key_hash), selected_identity_id: Mutex::new(None), pending_identity_selection: Mutex::new(None), - pending_dpns_operator_route: Mutex::new(None), fee_multiplier_permille: AtomicU64::new( PlatformFeeEstimator::DEFAULT_FEE_MULTIPLIER_PERMILLE, ), @@ -708,40 +695,6 @@ impl AppContext { self.network } - /// Route DPNS contest browsing into the shared Masternodes Voting Center. - pub fn route_to_dpns_voting_center(&self, contested_names: Vec) { - self.route_to_dpns_operator(DpnsOperatorRoute::Voting { - choices: contested_names - .into_iter() - .map(|name| (name, ResourceVoteChoice::Abstain)) - .collect(), - }); - } - - /// Route to the shared Masternodes DPNS operator workflow. - pub fn route_to_dpns_operator(&self, route: DpnsOperatorRoute) { - *self - .pending_dpns_operator_route - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(route); - } - - /// Consume a one-shot DPNS β†’ Masternodes Voting Center deep link. - pub fn take_dpns_voting_center_route(&self) -> Option> { - match self.take_dpns_operator_route()? { - DpnsOperatorRoute::Voting { choices } => Some(choices.into_keys().collect()), - DpnsOperatorRoute::Scheduled => None, - } - } - - /// Consume a one-shot DPNS operator deep link. - pub fn take_dpns_operator_route(&self) -> Option { - self.pending_dpns_operator_route - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .take() - } - pub fn connection_status(&self) -> &ConnectionStatus { &self.connection_status } @@ -1651,7 +1604,6 @@ pub(crate) const fn default_platform_version(_network: &Network) -> &'static Pla #[cfg(test)] mod tests { use super::*; - use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; #[test] fn install_secret_prompt_recovers_poisoned_slot() { @@ -1684,30 +1636,6 @@ mod tests { assert!(!url.contains(' ')); } - /// VOTE-TC-023: the DPNS deep link preserves each exact selected choice. - #[test] - fn dpns_voting_center_route_preserves_selected_choices() { - let tmp = tempfile::tempdir().expect("tempdir"); - let ctx = crate::context::test_support::test_app_context(tmp.path()); - let candidate = Identifier::from([7; 32]); - let choices = BTreeMap::from([ - ("alice".to_owned(), ResourceVoteChoice::Lock), - ( - "dominguez".to_owned(), - ResourceVoteChoice::TowardsIdentity(candidate), - ), - ]); - - ctx.route_to_dpns_operator(DpnsOperatorRoute::Voting { - choices: choices.clone(), - }); - - assert_eq!( - ctx.take_dpns_operator_route(), - Some(DpnsOperatorRoute::Voting { choices }) - ); - } - // ── FR-6 resolution-layer boundary (B1) ────────────────────────────────── /// Build an offline, wired `AppContext` (no network I/O) so the identity diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 108a5a111..1da314bdd 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -10,28 +10,31 @@ use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoic use dash_sdk::platform::Identifier; use eframe::egui::{self, Button, Color32, ComboBox, Label, RichText, Ui}; use egui_extras::{Column, TableBuilder}; -use itertools::Itertools; use crate::app::{AppAction, DesiredAppAction, scheduled_vote_sweep_is_quiet}; -use crate::backend_task::BackendTask; use crate::backend_task::contested_names::{ContestedResourceTask, ScheduledDPNSVote}; use crate::backend_task::error::TaskError; use crate::backend_task::identity::IdentityTask; -use crate::context::{AppContext, DpnsOperatorRoute}; +use crate::backend_task::{BackendTask, BackendTaskContext}; +use crate::context::AppContext; use crate::model::contested_name::{ContestState, ContestedName}; use crate::model::dpns_voting::{ - DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteTarget, DpnsVoteTargetKey, - DpnsVoteTargetStatus, VoteTiming, + DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, + DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, }; use crate::model::qualified_identity::{DPNSNameInfo, QualifiedIdentity}; +use crate::ui::components::component_trait::Component; +use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; 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::progress_overlay::{OptionOverlayExt, OverlayConfig, OverlayHandle}; 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::ui::components::{BannerHandle, MessageBanner, OptionBannerExt}; use crate::ui::identities::register_dpns_name_screen::RegisterDpnsNameSource; use crate::ui::state::dpns_vote_operations::DpnsVoteOperationSnapshot; +use crate::ui::state::dpns_vote_state::DpnsVoteStateSnapshot; use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; use crate::ui::{BackendTaskSuccessResult, MessageType, RootScreenType, ScreenLike, ScreenType}; @@ -44,6 +47,79 @@ pub enum DPNSSubscreen { ScheduledVotes, } +#[derive(Clone, Copy, PartialEq, Eq)] +enum ActiveContestGroup { + NeedsVote, + Voted, + NotVotable, +} + +fn classify_vote_states( + states: impl IntoIterator, +) -> ActiveContestGroup { + let mut has_vote = false; + for state in states { + match state { + DpnsCurrentVoteState::Available(None) => return ActiveContestGroup::NeedsVote, + DpnsCurrentVoteState::Available(Some(_)) => has_vote = true, + DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable => {} + } + } + if has_vote { + ActiveContestGroup::Voted + } else { + ActiveContestGroup::NotVotable + } +} + +fn tally_chip(ui: &mut Ui, votes: u32, dark_mode: bool) { + egui::Frame::new() + .fill(DashColors::surface(dark_mode)) + .corner_radius(egui::CornerRadius::same(255)) + .inner_margin(egui::Margin::symmetric(8, 2)) + .show(ui, |ui| { + ui.label(format!("{votes} votes")); + }); +} + +fn short_identifier(identifier: Identifier) -> String { + let encoded = identifier.to_string(Encoding::Base58); + format!("{}…{}", &encoded[..6], &encoded[encoded.len() - 4..]) +} + +fn vote_choice_label(choice: ResourceVoteChoice) -> String { + match choice { + ResourceVoteChoice::Lock => "Lock name".to_owned(), + ResourceVoteChoice::Abstain => "Abstain".to_owned(), + ResourceVoteChoice::TowardsIdentity(identifier) => { + format!("Vote for {}", short_identifier(identifier)) + } + } +} + +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 => "Confirmation is still being checked", + DpnsVoteTargetStatus::Rejected => "Rejected", + DpnsVoteTargetStatus::FailedBeforeSubmission => "Not submitted", + DpnsVoteTargetStatus::NotApplied => "Not applied", + DpnsVoteTargetStatus::Cancelled => "Cancelled", + } +} + +fn dpns_operation_id(context: &BackendTaskContext) -> Option { + match context { + BackendTaskContext::Dispatched { operation, .. } => dpns_operation_id(operation), + BackendTaskContext::DpnsVoteOperation { operation_id, .. } => Some(*operation_id), + _ => None, + } +} + impl DPNSSubscreen { pub fn display_name(&self) -> &'static str { match self { @@ -98,8 +174,6 @@ pub enum RefreshingStatus { #[derive(Clone, Copy, PartialEq, Eq)] enum SortColumn { ContestedName, - LockedVotes, - AbstainVotes, EndingTime, LastUpdated, AwardedTo, @@ -127,6 +201,11 @@ pub struct DPNSScreen { pub app_context: Arc, pending_backend_task: Option, vote_operations: DpnsVoteOperationSnapshot, + vote_state: DpnsVoteStateSnapshot, + vote_overlay: Option, + pending_vote_operation: Option, + clear_vote_overlay_on_error: bool, + scheduled_clear_dialog: Option<(bool, ConfirmationDialog)>, /// Sorting sort_column: SortColumn, @@ -143,9 +222,7 @@ pub struct DPNSScreen { /// 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, } @@ -192,6 +269,21 @@ impl DPNSScreen { ); DpnsVoteOperationSnapshot::default() }); + let vote_poll_ids = contested_names + .lock_recover() + .iter() + .filter_map(|contest| { + app_context + .dpns_vote_poll_id(&contest.normalized_contested_name) + .ok() + }) + .collect::>(); + let voter_ids = voting_identities + .iter() + .map(|identity| identity.identity.id()) + .collect::>(); + let vote_state = DpnsVoteStateSnapshot::load(app_context, &voter_ids, &vote_poll_ids) + .unwrap_or_default(); // Initialize vote handling pop-up state to hidden let identity_count = voting_identities.len(); @@ -213,6 +305,11 @@ impl DPNSScreen { scheduled_vote_cast_in_progress: false, pending_backend_task: None, vote_operations, + vote_state, + vote_overlay: None, + pending_vote_operation: None, + clear_vote_overlay_on_error: false, + scheduled_clear_dialog: None, dpns_subscreen, refreshing_status: RefreshingStatus::NotRefreshing, refresh_banner: None, @@ -220,9 +317,7 @@ impl DPNSScreen { // 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, } } @@ -248,8 +343,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), @@ -335,7 +428,7 @@ impl DPNSScreen { 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) + RichText::new("Choose votes on the Active contests screen, then use Review and cast to schedule them.").color(text_color) ); } }); @@ -347,331 +440,356 @@ impl DPNSScreen { // Rendering: Active, Past, Owned, Scheduled // --------------------------- - /// Show the Active Contests table - fn render_table_active_contests(&mut self, ui: &mut Ui) { + /// Render active contests as decision cards grouped by what the loaded nodes can do. + fn render_active_contests(&mut self, ui: &mut Ui) { + let dark_mode = ui.style().visuals.dark_mode; 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); }); + ui.label( + RichText::new("Each node can change its vote up to four times after its initial vote.") + .color(DashColors::text_secondary(dark_mode)), + ); + ui.add_space(8.0); - 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 + let filter = self.active_filter_term.to_lowercase(); + let contests = self + .contested_names + .lock_recover() + .iter() + .filter(|contest| { + filter.is_empty() + || contest + .normalized_contested_name .to_lowercase() - .contains(&filter_lc) - }); - } - self.sort_contested_names(&mut cn); - cn - }; + .contains(&filter) + }) + .cloned() + .collect::>(); + let mut groups = [Vec::new(), Vec::new(), Vec::new()]; + for contest in contests { + let index = match self.contest_group(&contest) { + ActiveContestGroup::NeedsVote => 0, + ActiveContestGroup::Voted => 1, + ActiveContestGroup::NotVotable => 2, + }; + groups[index].push(contest); + } - // Space allocation for UI elements is handled by the layout system + egui::ScrollArea::vertical() + .id_salt("active_contest_cards") + .show(ui, |ui| { + self.render_contest_group(ui, "Needs your vote", &groups[0], true, true); + self.render_contest_group(ui, "Voted", &groups[1], false, true); + self.render_contest_group( + ui, + "Not votable by your nodes", + &groups[2], + false, + false, + ); + self.render_voting_activity(ui); + }); - 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)), - ); - }); - }) - .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) - }; + ui.separator(); + ui.horizontal(|ui| { + let count = self.selected_votes.len(); + ui.label( + RichText::new(format!("Votes ready to cast: {count}")) + .strong() + .color(DashColors::text_primary(dark_mode)), + ); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ComponentStyles::add_primary_button_enabled(ui, count > 0, "Review and cast") + .disabled_tooltip("Choose a vote on at least one contest before reviewing it.") + .clicked() + { + self.show_bulk_schedule_popup = true; + } + }); + }); + } - 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); - } - }); + fn contest_group(&self, contest: &ContestedName) -> ActiveContestGroup { + let Ok(poll_id) = self + .app_context + .dpns_vote_poll_id(&contest.normalized_contested_name) + else { + return ActiveContestGroup::NotVotable; + }; + classify_vote_states( + self.voting_identities + .iter() + .map(|identity| self.vote_state.state(identity.identity.id(), poll_id)), + ) + } - // 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) - }; + fn render_contest_group( + &mut self, + ui: &mut Ui, + title: &str, + contests: &[ContestedName], + default_open: bool, + voting_enabled: bool, + ) { + egui::CollapsingHeader::new(format!("{title} ({})", contests.len())) + .default_open(default_open) + .show(ui, |ui| { + if contests.is_empty() { + ui.label("There are no contests in this group."); + } + for contest in contests { + let contest_enabled = + voting_enabled && self.contest_has_available_target(contest); + ui.add_enabled_ui(contest_enabled, |ui| { + self.render_contest_card(ui, contest, contest_enabled); + }); + ui.add_space(8.0); + } + }); + } - // 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 - }); + fn contest_has_available_target(&self, contest: &ContestedName) -> bool { + let Ok(vote_poll_id) = self + .app_context + .dpns_vote_poll_id(&contest.normalized_contested_name) + else { + return false; + }; + self.voting_identities.iter().any(|identity| { + let voter_id = identity.identity.id(); + matches!( + self.vote_state.state(voter_id, vote_poll_id), + DpnsCurrentVoteState::Available(_) + ) && self + .vote_operations + .target_status(&DpnsVoteTargetKey { + network: self.app_context.network(), + voter_id, + vote_poll_id, + }) + .is_none() + }) + } - 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, - }); - } - } - }); + fn render_contest_card(&mut self, ui: &mut Ui, contest: &ContestedName, voting_enabled: bool) { + let dark_mode = ui.style().visuals.dark_mode; + let selected = self + .selected_votes + .iter() + .find(|vote| vote.contested_name == contest.normalized_contested_name) + .map(|vote| vote.vote_choice); + let locked_votes = contest.locked_votes.unwrap_or_default(); + let abstain_votes = contest.abstain_votes.unwrap_or_default(); - // ABSTAIN button - row.col(|ui| { - let abstain_votes = contested_name.abstain_votes.unwrap_or(0); - let label_text = format!("{}", abstain_votes); + egui::Frame::group(ui.style()).show(ui, |ui| { + ui.set_min_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label( + RichText::new(format!("{}.dash", contest.normalized_contested_name)) + .heading() + .strong() + .color(DashColors::text_primary(dark_mode)), + ); + if let Some(end_time) = contest.end_time + && let LocalResult::Single(date_time) = + Utc.timestamp_millis_opt(end_time as i64) + { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label( + RichText::new(format!("Voting ends {}.", HumanTime::from(date_time))) + .color(DashColors::text_secondary(dark_mode)), + ); + }); + } + }); + ui.add_space(6.0); + + ui.horizontal_wrapped(|ui| { + let clicked = ui + .selectable_label(selected == Some(ResourceVoteChoice::Lock), "Lock name") + .on_disabled_hover_text( + "None of your loaded nodes can vote on this contest right now.", + ) + .clicked(); + tally_chip(ui, locked_votes, dark_mode); + if clicked && voting_enabled { + self.set_selected_vote(contest, ResourceVoteChoice::Lock); + } - let is_selected = self.selected_votes.iter().any(|sv| { - sv.contested_name == contested_name.normalized_contested_name - && sv.vote_choice == ResourceVoteChoice::Abstain - }); + let clicked = ui + .selectable_label(selected == Some(ResourceVoteChoice::Abstain), "Abstain") + .clicked(); + tally_chip(ui, abstain_votes, dark_mode); + if clicked && voting_enabled { + self.set_selected_vote(contest, ResourceVoteChoice::Abstain); + } + }); - 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, - }); - } - } - }); + if let Some(contestants) = &contest.contestants { + for contestant in contestants { + ui.horizontal_wrapped(|ui| { + let choice = ResourceVoteChoice::TowardsIdentity(contestant.id); + let clicked = ui + .selectable_label( + selected == Some(choice), + format!("Vote for {}", contestant.name), + ) + .clicked(); + tally_chip(ui, contestant.votes, dark_mode); + ui.label( + RichText::new(short_identifier(contestant.id)) + .monospace() + .color(DashColors::text_secondary(dark_mode)), + ); + if clicked && voting_enabled { + self.set_selected_vote(contest, choice); + } + }); + } + } + }); + } - // 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)), - ); - } - }); + fn set_selected_vote(&mut self, contest: &ContestedName, choice: ResourceVoteChoice) { + if let Some(index) = self + .selected_votes + .iter() + .position(|vote| vote.contested_name == contest.normalized_contested_name) + { + if self.selected_votes[index].vote_choice == choice { + self.selected_votes.remove(index); + } else { + self.selected_votes[index].vote_choice = choice; + } + } else { + self.selected_votes.push(SelectedVote { + contested_name: contest.normalized_contested_name.clone(), + vote_choice: choice, + end_time: contest.end_time, + }); + } + } - // 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)), - ); - } - }); + fn render_voting_activity(&mut self, ui: &mut Ui) { + let mut operations = self.vote_operations.operations().to_vec(); + operations.sort_by_key(|operation| operation.created_at); + let operations = operations + .into_iter() + .rev() + .filter(|operation| !operation.targets.is_empty()) + .take(5) + .collect::>(); + if operations.is_empty() { + return; + } - // Contestants - row.col(|ui| { - self.show_contestants_for_contested_name( - ui, - contested_name, - is_locked_votes_bold, - max_contestant_votes, - ); - }); - }); + let dark_mode = ui.style().visuals.dark_mode; + ui.add_space(12.0); + ui.heading("Recent voting activity"); + for operation in operations { + let settled = operation + .targets + .iter() + .filter(|outcome| !outcome.status.holds_lock()) + .count(); + ui.group(|ui| { + ui.label( + RichText::new(format!( + "{settled} of {} votes settled.", + operation.targets.len() + )) + .strong(), + ); + for outcome in &operation.targets { + ui.horizontal_wrapped(|ui| { + ui.label(format!( + "{}.dash β€” {} β€” {}", + outcome.target.contested_name, + vote_choice_label(outcome.target.requested_choice), + target_status_label(outcome.status), + )); + if outcome.status == DpnsVoteTargetStatus::Unconfirmed + && ComponentStyles::add_secondary_button( + ui, + "Check again", + dark_mode, + ) + .clicked() + { + self.pending_backend_task = Some(BackendTask::ContestedResourceTask( + ContestedResourceTask::ReconcileDpnsVoteOperation( + operation.id, + self.app_context.network(), + ), + )); + self.pending_vote_operation = Some(operation.id); + self.raise_vote_overlay( + ui.ctx(), + "Checking the submitted votes with Platform…", + ); + } + if matches!( + outcome.status, + DpnsVoteTargetStatus::Rejected + | DpnsVoteTargetStatus::FailedBeforeSubmission + | DpnsVoteTargetStatus::NotApplied + ) && ComponentStyles::add_secondary_button( + ui, + "Review again", + dark_mode, + ) + .clicked() + { + self.set_selected_vote_from_outcome(outcome); + self.bulk_identity_options = + vec![VoteOption::CastNow; self.voting_identities.len()]; + self.set_all_option = VoteOption::CastNow; + self.show_bulk_schedule_popup = true; + } + }); + if matches!( + outcome.status, + DpnsVoteTargetStatus::Confirming + | DpnsVoteTargetStatus::Unconfirmed + ) { + ui.label( + RichText::new( + "This vote may already have been submitted. Do not submit it again.", + ) + .color(DashColors::warning_color(dark_mode)), + ); } - }); - }); + } + }); + } + } + + fn set_selected_vote_from_outcome( + &mut self, + outcome: &crate::model::dpns_voting::DpnsVoteOutcome, + ) { + let name = outcome.target.contested_name.clone(); + if let Some(vote) = self + .selected_votes + .iter_mut() + .find(|vote| vote.contested_name == name) + { + vote.vote_choice = outcome.target.requested_choice; + } else { + self.selected_votes.push(SelectedVote { + contested_name: name, + vote_choice: outcome.target.requested_choice, + end_time: None, + }); + } } - /// Show a Past Contests table + fn raise_vote_overlay(&mut self, ctx: &egui::Context, message: &str) { + self.vote_overlay + .raise(ctx, message, OverlayConfig::default()); + } fn render_table_past_contests(&mut self, ui: &mut Ui) { ui.horizontal(|ui| { let dark_mode = ui.style().visuals.dark_mode; @@ -735,7 +853,7 @@ impl DPNSScreen { } }); header.col(|ui| { - if ui.button("Awarded To").clicked() { + if ui.button("Outcome").clicked() { self.toggle_sort(SortColumn::AwardedTo); } }); @@ -826,17 +944,21 @@ 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.clone()) + .unwrap_or_else(|| short_identifier(identifier)); + ui.label(format!("Won by {winner}.")); } ContestState::Locked => { ui.label( - RichText::new("Locked") + RichText::new("Locked; no name was awarded.") .color(DashColors::text_primary(dark_mode)), ); } @@ -1003,6 +1125,7 @@ impl DPNSScreen { /// Show the Scheduled Votes table fn render_table_scheduled_votes(&mut self, ui: &mut Ui) -> AppAction { let mut action = AppAction::None; + let mut show_cast_overlay = false; let mut sorted_votes = { let guard = self.scheduled_votes.lock_recover(); guard.clone() @@ -1081,22 +1204,21 @@ impl DPNSScreen { body.row(25.0, |mut row| { // Contested name row.col(|ui| { - ui.add(Label::new(&vote.0.contested_name)); + ui.add(Label::new(format!("{}.dash", vote.0.contested_name))); }); // Voter row.col(|ui| { - ui.add( - Label::new(vote.0.voter_id.to_string(Encoding::Hex)).truncate(), - ); + let voter = self + .voting_identities + .iter() + .find(|identity| identity.identity.id() == vote.0.voter_id) + .and_then(|identity| identity.alias.clone()) + .unwrap_or_else(|| short_identifier(vote.0.voter_id)); + ui.add(Label::new(voter)); }); // Choice row.col(|ui| { - let display_text = match &vote.0.choice { - ResourceVoteChoice::TowardsIdentity(id) => { - id.to_string(Encoding::Base58) - } - other => other.to_string(), - }; + let display_text = vote_choice_label(vote.0.choice); ui.add(Label::new(display_text)); }); // Time @@ -1200,9 +1322,9 @@ impl DPNSScreen { ) && !target_is_busy; let cast_button = if cast_button_enabled { - Button::new("Cast Now") + Button::new("Cast now") } else { - Button::new("Cast Now").sense(egui::Sense::hover()) + Button::new("Cast now").sense(egui::Sense::hover()) }; if ui.add(cast_button).clicked() && cast_button_enabled { @@ -1231,7 +1353,7 @@ impl DPNSScreen { .iter() .find(|i| i.identity.id() == vote.0.voter_id) { - action = AppAction::BackendTask( + action = AppAction::BackendTask( BackendTask::ContestedResourceTask( ContestedResourceTask::CastScheduledVote( vote.0.clone(), @@ -1239,6 +1361,7 @@ impl DPNSScreen { ), ), ); + show_cast_overlay = true; } } }); @@ -1247,86 +1370,19 @@ impl DPNSScreen { }); }); - action - } - - /// 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) - }; - - // 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 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, - }); - } - } - } + if show_cast_overlay { + self.raise_vote_overlay(ui.ctx(), "Submitting the scheduled vote to Dash Platform…"); } + + action } - // --------------------------- - // Bulk scheduling ephemeral UI - // --------------------------- fn show_bulk_schedule_popup_window(&mut self, ui: &mut Ui) -> AppAction { let mut action = AppAction::None; let dark_mode = ui.style().visuals.dark_mode; ui.heading( - RichText::new("Cast or Schedule Votes").color(DashColors::text_primary(dark_mode)), + RichText::new("Review selected votes").color(DashColors::text_primary(dark_mode)), ); ui.add_space(10.0); @@ -1365,7 +1421,7 @@ impl DPNSScreen { ui.group(|ui| { let dark_mode = ui.style().visuals.dark_mode; ui.heading( - RichText::new("Selected Votes:").color(DashColors::text_primary(dark_mode)), + RichText::new("Selected votes").color(DashColors::text_primary(dark_mode)), ); ui.separator(); for sv in &self.selected_votes { @@ -1400,29 +1456,28 @@ impl DPNSScreen { // 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.heading(RichText::new("All my nodes").color(DashColors::text_primary(dark_mode))); ui.add_space(10.0); ui.group(|ui| { ui.horizontal(|ui| { let dark_mode = ui.style().visuals.dark_mode; - ui.label(RichText::new("Set all:").color(DashColors::text_primary(dark_mode))); + ui.label( + RichText::new("Cast timing:").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::NoVote => "Do not use these nodes".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", + "Do not use these nodes", ) .clicked() { @@ -1431,7 +1486,7 @@ impl DPNSScreen { if ui .selectable_label( matches!(self.set_all_option, VoteOption::CastNow), - "Cast Now", + "Cast now", ) .clicked() { @@ -1470,7 +1525,7 @@ impl DPNSScreen { { let dark_mode = ui.style().visuals.dark_mode; ui.label( - RichText::new("Schedule In:") + RichText::new("Schedule after:") .color(DashColors::text_primary(dark_mode)), ); ui.add(egui::DragValue::new(days).prefix("Days: ").range(0..=14)); @@ -1479,7 +1534,7 @@ impl DPNSScreen { } // Button to apply the "Set all" choice to each identity in bulk_identity_options - if ui.button("Apply to All").clicked() { + if ui.button("Apply to all nodes").clicked() { for option in &mut self.bulk_identity_options { *option = self.set_all_option.clone(); } @@ -1487,103 +1542,115 @@ impl DPNSScreen { }); }); ui.add_space(10.0); - for (i, identity) in self.voting_identities.iter().enumerate() { - ui.group(|ui| { - ui.horizontal(|ui| { - let label = identity - .alias - .clone() - .unwrap_or_else(|| identity.identity.id().to_string(Encoding::Base58)); - 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]; - } + egui::CollapsingHeader::new("Choose per node (advanced)") + .default_open(false) + .show(ui, |ui| { + for (i, identity) in self.voting_identities.iter().enumerate() { + ui.group(|ui| { + ui.horizontal(|ui| { + let label = identity.alias.clone().unwrap_or_else(|| { + identity.identity.id().to_string(Encoding::Base58) + }); + let dark_mode = ui.style().visuals.dark_mode; + ui.label( + RichText::new(format!("Identity: {}", label)) + .color(DashColors::text_primary(dark_mode)), + ); - 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; + // 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]; } - if ui - .selectable_label( - matches!(current_option, VoteOption::Scheduled { .. }), - "Schedule", - ) - .clicked() + + 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 => "Do not use this node".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), + "Do not use this node", + ) + .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 (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, - }; + let dark_mode = ui.style().visuals.dark_mode; + ui.label( + RichText::new("Schedule after:") + .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), + ); } }); - - 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.add_space(10.0); - } }); - // If any selected votes are scheduled, show a warning if self .bulk_identity_options @@ -1611,19 +1678,21 @@ impl DPNSScreen { if operation_in_progress { "Submitting votes…" } else { - "Apply Votes" + "Submit votes" }, ) .disabled_tooltip("The selected votes are already being submitted.") .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); + if matches!( + self.bulk_vote_handling_status, + VoteHandlingStatus::CastingVotes | VoteHandlingStatus::SchedulingVotes + ) { + self.raise_vote_overlay( + ui.ctx(), + "Submitting the selected votes to Dash Platform…", + ); } } @@ -1639,9 +1708,9 @@ impl DPNSScreen { { 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(); + self.vote_overlay.take_and_clear(); + self.pending_vote_operation = None; } // Handle status @@ -1661,10 +1730,7 @@ impl DPNSScreen { // handled above } VoteHandlingStatus::Failed(message) => { - ui.colored_label( - Color32::RED, - format!("Error casting/scheduling votes: {}", message), - ); + ui.colored_label(Color32::RED, message); } } @@ -1708,8 +1774,15 @@ impl DPNSScreen { { Ok(vote_poll_id) => vote_poll_id, Err(error) => { - self.bulk_vote_handling_status = - VoteHandlingStatus::Failed(error.to_string()); + tracing::warn!( + ?error, + contested_name = selected_vote.contested_name, + "Could not build a DPNS vote target" + ); + self.bulk_vote_handling_status = VoteHandlingStatus::Failed( + "This vote could not be prepared. Refresh Active contests and try again." + .to_owned(), + ); return AppAction::None; } }; @@ -1725,13 +1798,9 @@ impl DPNSScreen { )); return AppAction::None; } - let current_choice = match self - .app_context - .dpns_current_vote_state(voter_id, vote_poll_id) - { - Ok(DpnsCurrentVoteState::Available(choice)) => choice, - Ok(DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable) - | Err(_) => { + let current_choice = match self.vote_state.state(voter_id, vote_poll_id) { + DpnsCurrentVoteState::Available(choice) => choice, + DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable => { self.bulk_vote_handling_status = VoteHandlingStatus::Failed( "Current vote state is unavailable. Refresh voting before applying votes." .to_owned(), @@ -1769,6 +1838,7 @@ impl DPNSScreen { } else { VoteHandlingStatus::SchedulingVotes }; + self.pending_vote_operation = Some(operation.id); AppAction::BackendTask(BackendTask::ContestedResourceTask( ContestedResourceTask::SubmitDpnsVoteOperation( operation, @@ -1786,58 +1856,24 @@ impl DPNSScreen { self.selected_votes.clear(); ui.vertical_centered(|ui| { + let dark_mode = ui.style().visuals.dark_mode; 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)), - ); - } - _ => {} - } - } + ui.heading( + RichText::new("The voting operation has been updated.") + .color(DashColors::text_primary(dark_mode)), + ); + ui.label( + "Review the recent voting activity for each confirmed, pending, or failed target.", + ); } 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)") + RichText::new("The votes could not be submitted.") .color(DashColors::text_primary(dark_mode)), ); ui.add_space(10.0); @@ -1927,6 +1963,31 @@ impl ScreenLike for DPNSScreen { .collect(); } } + drop(contested_names); + drop(dpns_names); + drop(scheduled_votes); + + let voter_ids = self + .voting_identities + .iter() + .map(|identity| identity.identity.id()) + .collect::>(); + let poll_ids = self + .contested_names + .lock_recover() + .iter() + .filter_map(|contest| { + self.app_context + .dpns_vote_poll_id(&contest.normalized_contested_name) + .ok() + }) + .collect::>(); + 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"); + } } fn refresh_on_arrival(&mut self) { @@ -1934,6 +1995,8 @@ impl ScreenLike for DPNSScreen { .app_context .load_local_voting_identities() .unwrap_or_default(); + self.bulk_identity_options = vec![VoteOption::CastNow; self.voting_identities.len()]; + self.set_all_option = VoteOption::CastNow; self.user_identities = self .app_context .load_local_user_identities() @@ -1945,11 +2008,22 @@ impl ScreenLike for DPNSScreen { // 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(); } } + fn display_backend_task_error(&mut self, context: &BackendTaskContext, _error: &TaskError) { + self.clear_vote_overlay_on_error = match self.pending_vote_operation { + Some(operation_id) => dpns_operation_id(context) == Some(operation_id), + None => self.vote_overlay.is_some() && dpns_operation_id(context).is_none(), + }; + } + fn display_task_error(&mut self, error: &TaskError) -> bool { + if self.clear_vote_overlay_on_error { + self.vote_overlay.take_and_clear(); + self.pending_vote_operation = None; + self.clear_vote_overlay_on_error = false; + } if let Err(refresh_error) = self.vote_operations.refresh(&self.app_context) { tracing::warn!( ?refresh_error, @@ -1979,10 +2053,19 @@ impl ScreenLike for DPNSScreen { fn display_task_result(&mut self, backend_task_success_result: BackendTaskSuccessResult) { match backend_task_success_result { - BackendTaskSuccessResult::DpnsVoteOperationUpdated { .. } => { - self.vote_banner.take_and_clear(); - self.bulk_vote_handling_status = VoteHandlingStatus::Completed; - self.refresh(); + BackendTaskSuccessResult::DpnsVoteOperationUpdated { operation_id, .. } => { + let owns_result = self.pending_vote_operation == Some(operation_id) + || (self.pending_vote_operation.is_none() && self.vote_overlay.is_some()); + if owns_result { + self.vote_overlay.take_and_clear(); + self.pending_vote_operation = None; + if matches!( + self.bulk_vote_handling_status, + VoteHandlingStatus::CastingVotes | VoteHandlingStatus::SchedulingVotes + ) { + self.bulk_vote_handling_status = VoteHandlingStatus::Completed; + } + } } BackendTaskSuccessResult::ScheduledVotesInProgress(votes) => { if let Err(error) = self.vote_operations.refresh(&self.app_context) { @@ -2011,19 +2094,9 @@ impl ScreenLike for DPNSScreen { } fn ui(&mut self, ui: &mut egui::Ui) -> AppAction { - if self.dpns_subscreen == DPNSSubscreen::ScheduledVotes { - self.app_context - .route_to_dpns_operator(DpnsOperatorRoute::Scheduled); - return AppAction::SetMainScreen(RootScreenType::RootScreenMasternodes); - } 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() - }; - // Build top-right buttons let mut right_buttons = match self.dpns_subscreen { DPNSSubscreen::Active => { @@ -2033,17 +2106,7 @@ impl ScreenLike for DPNSScreen { ContestedResourceTask::QueryDPNSContests, ))), ); - if has_active_contests { - vec![ - refresh_button, - ( - "Vote with masternodes", - DesiredAppAction::Custom("Vote".to_string()), - ), - ] - } else { - vec![refresh_button] - } + vec![refresh_button] } DPNSSubscreen::Past => { let refresh_button = ( @@ -2067,19 +2130,11 @@ impl ScreenLike for DPNSScreen { vec![ ( "Clear All", - DesiredAppAction::BackendTask(Box::new( - BackendTask::ContestedResourceTask( - ContestedResourceTask::ClearAllScheduledVotes, - ), - )), + DesiredAppAction::Custom("Clear all scheduled votes".to_owned()), ), ( - "Clear Casted", - DesiredAppAction::BackendTask(Box::new( - BackendTask::ContestedResourceTask( - ContestedResourceTask::ClearExecutedScheduledVotes, - ), - )), + "Clear Completed", + DesiredAppAction::Custom("Clear completed scheduled votes".to_owned()), ), ] } @@ -2105,18 +2160,28 @@ impl ScreenLike for DPNSScreen { subdued_everyday_spec("DPNS", RootScreenType::RootScreenDPNSActiveContests), right_buttons, ); - - // If user clicked "Apply Votes" in the top bar - if action == AppAction::Custom("Vote".to_string()) { - self.app_context - .route_to_dpns_operator(DpnsOperatorRoute::Voting { - choices: self - .selected_votes - .iter() - .map(|vote| (vote.contested_name.clone(), vote.vote_choice)) - .collect(), - }); - action = AppAction::SetMainScreen(RootScreenType::RootScreenMasternodes); + if action == AppAction::Custom("Clear all scheduled votes".to_owned()) { + self.scheduled_clear_dialog = Some(( + true, + ConfirmationDialog::new( + "Clear all scheduled votes", + "Remove every scheduled vote from this device? Votes already submitted to Platform cannot be undone.", + ) + .danger_mode(true) + .confirm_text(Some("Clear all scheduled votes")), + )); + action = AppAction::None; + } else if action == AppAction::Custom("Clear completed scheduled votes".to_owned()) { + self.scheduled_clear_dialog = Some(( + false, + ConfirmationDialog::new( + "Clear completed scheduled votes", + "Remove every completed scheduled vote from this device? Pending votes will stay scheduled.", + ) + .danger_mode(true) + .confirm_text(Some("Clear completed scheduled votes")), + )); + action = AppAction::None; } // Left panel @@ -2135,9 +2200,23 @@ impl ScreenLike for DPNSScreen { // Main panel action |= island_central_panel(ui, |ui| { let mut inner_action = AppAction::None; + 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 { + inner_action = + AppAction::BackendTask(BackendTask::ContestedResourceTask(if clear_all { + ContestedResourceTask::ClearAllScheduledVotes + } else { + ContestedResourceTask::ClearExecutedScheduledVotes + })); + } + } // Bulk-schedule ephemeral popup if self.show_bulk_schedule_popup { - egui::Window::new("Voting") + egui::Window::new("Review and cast") .collapsible(false) .resizable(true) .vscroll(true) @@ -2154,7 +2233,7 @@ impl ScreenLike for DPNSScreen { !guard.is_empty() }; if has_any { - self.render_table_active_contests(ui); + self.render_active_contests(ui); } else { inner_action |= self.render_no_active_contests_or_owned_names(ui); } @@ -2277,6 +2356,62 @@ mod tests { (ctx, temp_dir) } + #[test] + fn vote_submission_overlay_clears_when_the_operation_finishes() { + let (ctx, _temp_dir) = offline_ctx(); + let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); + + screen.raise_vote_overlay( + ctx.egui_ctx(), + "Submitting the selected votes to Dash Platform…", + ); + screen.pending_vote_operation = Some(DpnsVoteOperationId::from_bytes([7; 16])); + assert!( + crate::ui::components::progress_overlay::ProgressOverlay::has_global(ctx.egui_ctx()) + ); + + screen.display_task_result(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: ctx.network(), + operation_id: DpnsVoteOperationId::from_bytes([8; 16]), + }); + assert!( + crate::ui::components::progress_overlay::ProgressOverlay::has_global(ctx.egui_ctx()) + ); + + screen.display_task_result(BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: ctx.network(), + operation_id: DpnsVoteOperationId::from_bytes([7; 16]), + }); + + assert!( + !crate::ui::components::progress_overlay::ProgressOverlay::has_global(ctx.egui_ctx()) + ); + } + + #[test] + fn active_contest_groups_prioritize_nodes_that_still_need_a_vote() { + assert!(matches!( + classify_vote_states([ + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)), + DpnsCurrentVoteState::Available(None), + ]), + ActiveContestGroup::NeedsVote + )); + assert!(matches!( + classify_vote_states([DpnsCurrentVoteState::Available(Some( + ResourceVoteChoice::Abstain, + ))]), + ActiveContestGroup::Voted + )); + assert!(matches!( + classify_vote_states([ + DpnsCurrentVoteState::Checking, + DpnsCurrentVoteState::Unavailable, + ]), + ActiveContestGroup::NotVotable + )); + } + #[test] fn scheduled_vote_sweep_error_is_handled_after_cleanup() { let (ctx, _temp_dir) = offline_ctx(); diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index 47583ccd0..f8e546071 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; use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dash_sdk::dpp::platform_value::string_encoding::Encoding; @@ -16,25 +13,16 @@ use eframe::egui::{self, Color32, RichText, Ui}; use std::collections::BTreeMap; -use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; - use crate::app::AppAction; use crate::backend_task::BackendTask; -use crate::backend_task::contested_names::ContestedResourceTask; -use crate::backend_task::identity::{IdentityInputToLoad, IdentityLoadMode, IdentityTask}; +use crate::backend_task::identity::IdentityTask; use crate::context::AppContext; -use crate::model::contested_name::{ - ContestedName, MasternodeContestSummary, MasternodeVoteStateSummary, -}; -use crate::model::dpns_voting::{DpnsCurrentVoteState, DpnsVoteTargetKey}; use crate::model::fee_estimation::format_credits_as_dash; use crate::model::qualified_identity::{ IdentityType, MasternodeKeyPresence, PrivateKeyTarget, QualifiedIdentity, }; -use crate::model::secret::Secret; use crate::ui::components::MessageBanner; use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; -use crate::ui::components::password_input::PasswordInput; use crate::ui::identities::keys::key_info_screen::KeyInfoScreen; use crate::ui::identity::identity_picker_card::draw_type_badge; use crate::ui::identity::identity_pill::shorten_id; @@ -42,7 +30,6 @@ use crate::ui::masternodes::card::{ PLATFORM_IDENTITY_STATUS_TOOLTIP, platform_identity_status_label, }; use crate::ui::masternodes::{TIP_OWNER_KEY, TIP_PAYOUT_KEY, TIP_VOTING_KEY, key_status_tokens}; -use crate::ui::state::dpns_vote_operations::DpnsVoteOperationSnapshot; use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; use crate::ui::tokens::claim_tokens_screen::ClaimTokensScreen; use crate::ui::tokens::tokens_screen::IdentityTokenBasicInfo; @@ -50,84 +37,6 @@ use crate::ui::{MessageType, Screen, ScreenType}; use crate::wallet_backend::IdentityKeyView; use crate::wallet_backend::secret_seam::SecretScheme; -/// Β§7 copy: shown when the node has no voting key loaded. -const MISSING_VOTER_MESSAGE: &str = - "This node has no voting key loaded. Add its voting private key to cast votes."; -/// Β§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."; -const CONTESTS_UNAVAILABLE_MESSAGE: &str = - "Name contest information is unavailable. Refresh and try again."; - -/// The collapsible DPNS section header, with the open-contest count (TC-DPNS-02). -fn dpns_section_header(summary: MasternodeContestSummary) -> String { - if summary.vote_state == MasternodeVoteStateSummary::Unavailable { - CONTESTS_UNAVAILABLE_MESSAGE.to_owned() - } else { - format!( - "DPNS name contests to vote on ({})", - summary.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, - current_vote: DpnsCurrentVoteState, - locked: bool, - /// `(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"]; @@ -247,11 +156,6 @@ pub enum DetailOutcome { Back, /// The node was removed β€” return to the list and reload. Removed, - /// Open the shared full-page composer prefiltered to this node. - OpenVotingCenter { - voter_id: dash_sdk::platform::Identifier, - choices: BTreeMap, - }, /// Push a reused screen / navigate. Boxed because `AppAction` is large. Forward(Box), } @@ -268,131 +172,31 @@ 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, - vote_operations: DpnsVoteOperationSnapshot, - /// Per-contest pending vote choice, keyed by normalized contested name. - vote_selections: BTreeMap, - /// One-shot automatic proved-state refresh for a newly opened detail view. - vote_state_refresh_dispatched: bool, - open_voting_center_requested: 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, } -#[cfg(test)] impl MasternodeDetailView { - /// Open the `Add voting key` prompt on a key, as typing into it would. - pub(crate) fn set_voter_key_prompt_for_test(&mut self, value: &str) { - let mut prompt = PasswordInput::new(); - prompt.set_text(value); - self.voter_key_prompt = Some(prompt); - } - - /// Whether the `Add voting key` prompt is open β€” and thus holding a key. - pub(crate) fn has_voter_key_prompt_for_test(&self) -> bool { - self.voter_key_prompt.is_some() - } -} - -impl MasternodeDetailView { - pub(crate) fn refresh_vote_operations(&mut self) { - if let Err(error) = self.vote_operations.refresh(&self.app_context) { - tracing::warn!(?error, "Could not refresh node-detail voting state"); - } - } - 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 key_presence = identity.masternode_key_presence(); - let voter_id = identity - .associated_voter_identity - .as_ref() - .map(|_| identity.identity.id()); - let mut contest_summary = app_context - .masternode_contest_summary(voter_id) - .unwrap_or_else(|_| MasternodeContestSummary::unavailable()); - let open_contests = Self::load_open_contests(app_context, voter_id, &mut contest_summary); - let vote_operations = - DpnsVoteOperationSnapshot::load(app_context).unwrap_or_else(|error| { - tracing::warn!( - ?error, - "Could not cache DPNS operations for the node detail view" - ); - DpnsVoteOperationSnapshot::default() - }); Self { app_context: app_context.clone(), identity, node_id_hex_full, node_id_short, key_presence, - contest_summary, - open_contests, - vote_operations, - vote_selections: BTreeMap::new(), - vote_state_refresh_dispatched: false, - open_voting_center_requested: None, - voter_key_prompt: None, remove_dialog: None, } } - /// Load the contests this node can still vote on. - fn load_open_contests( - app_context: &Arc, - voter_id: Option, - contest_summary: &mut MasternodeContestSummary, - ) -> Vec { - let Some(voter_id) = voter_id else { - return Vec::new(); - }; - match app_context.ongoing_contested_names() { - Ok(contests) => contests - .into_iter() - .filter(|contest| contest.is_open_for_voter(&voter_id)) - .collect(), - Err(_) => { - *contest_summary = MasternodeContestSummary::unavailable(); - Vec::new() - } - } - } - - /// 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(|_| self.identity.identity.id()); - let mut contest_summary = self - .app_context - .masternode_contest_summary(voter_id) - .unwrap_or_else(|_| MasternodeContestSummary::unavailable()); - self.open_contests = - Self::load_open_contests(&self.app_context, voter_id, &mut contest_summary); - self.contest_summary = contest_summary; - } - /// 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. 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) } @@ -462,10 +266,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())); } }); @@ -491,13 +291,6 @@ impl MasternodeDetailView { outcome = DetailOutcome::Removed; } }); - if let Some(choices) = self.open_voting_center_requested.take() { - outcome = DetailOutcome::OpenVotingCenter { - voter_id: self.identity.identity.id(), - choices, - }; - } - outcome } @@ -795,294 +588,12 @@ impl MasternodeDetailView { AppAction::AddScreen(Screen::KeyInfoScreen(screen)) } - /// 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); - egui::CollapsingHeader::new(header) - .default_open(false) - .show(ui, |ui| { - if self.contest_summary.vote_state == MasternodeVoteStateSummary::Unavailable { - ui.label( - RichText::new(CONTESTS_UNAVAILABLE_MESSAGE) - .color(DashColors::warning_color(dark_mode)), - ); - } else 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() { - 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; - } - - /// 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 choices backed by the shared durable voting coordinator. - 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 voter_id = self.identity.identity.id(); - let contests: Vec = self - .open_contests - .iter() - .filter_map(|contest| { - let vote_poll_id = self - .app_context - .dpns_vote_poll_id(&contest.normalized_contested_name) - .ok()?; - let current_vote = self - .app_context - .dpns_current_vote_state(voter_id, vote_poll_id) - .unwrap_or(DpnsCurrentVoteState::Unavailable); - let key = DpnsVoteTargetKey { - network: self.app_context.network(), - voter_id, - vote_poll_id, - }; - let candidates = contest - .contestants - .as_ref() - .map(|list| { - list.iter() - .map(|c| (c.id, c.name.clone(), c.votes)) - .collect() - }) - .unwrap_or_default(); - Some(ContestVoteRow { - name: contest.normalized_contested_name.clone(), - end_time: contest.end_time, - current_vote, - locked: self.vote_operations.target_status(&key).is_some(), - candidates, - }) - }) - .collect(); - if !self.vote_state_refresh_dispatched - && contests - .iter() - .any(|contest| contest.current_vote == DpnsCurrentVoteState::Checking) - { - self.vote_state_refresh_dispatched = true; - action = Some(AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::QueryDPNSContests, - ))); - } - - 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 current_label = match contest.current_vote { - DpnsCurrentVoteState::Checking => "Checking current vote…".to_owned(), - DpnsCurrentVoteState::Unavailable => "Current vote unavailable".to_owned(), - DpnsCurrentVoteState::Available(None) => "Not voted".to_owned(), - DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Abstain)) => { - "Current vote: Abstain".to_owned() - } - DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) => { - "Current vote: Lock".to_owned() - } - DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::TowardsIdentity(id))) => { - let candidate = contest - .candidates - .iter() - .find(|(candidate_id, _, _)| *candidate_id == id) - .map(|(_, name, _)| { - format!("{name} ({})", shorten_id(&id.to_string(Encoding::Base58))) - }) - .unwrap_or_else(|| { - format!("candidate {}", shorten_id(&id.to_string(Encoding::Base58))) - }); - format!("Current vote: {candidate}") - } - }; - ui.label(RichText::new(current_label).color(DashColors::text_secondary(dark_mode))); - let selected = self.vote_selections.get(&contest.name).copied(); - let controls_enabled = - matches!(contest.current_vote, DpnsCurrentVoteState::Available(_)) - && !contest.locked; - ui.add_enabled_ui(controls_enabled, |ui| { - 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 contest.locked { - ui.label( - RichText::new("This node's vote for this name is still being confirmed.") - .color(DashColors::text_secondary(dark_mode)), - ); - } else if matches!(contest.current_vote, DpnsCurrentVoteState::Unavailable) { - ui.label( - RichText::new("Refresh vote state before choosing a vote for this node.") - .color(DashColors::text_secondary(dark_mode)), - ); - if ComponentStyles::add_secondary_button(ui, "Refresh vote state", dark_mode) - .clicked() - { - self.vote_state_refresh_dispatched = true; - action = Some(AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::QueryDPNSContests, - ))); - } - } else if matches!(contest.current_vote, DpnsCurrentVoteState::Checking) { - ui.label( - RichText::new("DET is checking this node's current vote.") - .color(DashColors::text_secondary(dark_mode)), - ); - } else if selected.is_none() { - ui.label( - RichText::new(NO_SELECTION_HINT).color(DashColors::text_secondary(dark_mode)), - ); - } - } - - ui.separator(); - let selection_count = self.vote_selections.len(); - let has_selections = selection_count > 0; - let review_label = if selection_count == 1 { - "Review 1 vote".to_owned() - } else { - format!("Review {selection_count} votes") - }; - if ComponentStyles::add_primary_button_enabled(ui, has_selections, review_label) - .clickable_tooltip(CAST_ENABLED_HINT) - .disabled_tooltip(CAST_DISABLED_HINT) + fn render_dpns_section(&mut self, ui: &mut Ui, _dark_mode: bool) -> Option { + ComponentStyles::add_secondary_button(ui, "DPNS Voting", ui.visuals().dark_mode) .clicked() - { - self.open_voting_center_requested = Some(self.vote_selections.clone()); - } - if ComponentStyles::add_secondary_button(ui, "Open Voting Center", dark_mode).clicked() { - self.open_voting_center_requested = Some(BTreeMap::new()); - } - action + .then(|| { + AppAction::SetMainScreen(crate::ui::RootScreenType::RootScreenDPNSActiveContests) + }) } /// Returns `true` once the node has been removed. @@ -1154,6 +665,7 @@ impl MasternodeDetailView { #[cfg(test)] mod tests { use super::*; + use crate::model::secret::Secret; #[test] fn tc_fr5_01_actions_render_before_keys() { @@ -1307,67 +819,6 @@ mod tests { ); } - #[test] - fn tc_dpns_02_header_shows_open_contest_count() { - let summary = MasternodeContestSummary { - open_contest_count: 3, - ..Default::default() - }; - assert_eq!( - dpns_section_header(summary), - "DPNS name contests to vote on (3)" - ); - - assert_eq!( - dpns_section_header(MasternodeContestSummary::unavailable()), - "Name contest information is unavailable. Refresh and try again." - ); - } - - #[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"); - } - - #[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 bf53383fe..1352cec40 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -5,11 +5,8 @@ use std::sync::Arc; -use chrono::{LocalResult, TimeZone, Utc}; -use chrono_humanize::HumanTime; 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, RichText}; @@ -17,17 +14,12 @@ use crate::app::{AppAction, BackendTasksExecutionMode}; use crate::backend_task::BackendTask; use crate::backend_task::contested_names::ContestedResourceTask; use crate::backend_task::identity::IdentityTask; +use crate::context::AppContext; use crate::context::identity_load_registry::{IdentityLoadPhase, IdentityLoadToken}; -use crate::context::{AppContext, DpnsOperatorRoute}; use crate::model::contested_name::MasternodeContestSummary; -use crate::model::dpns_voting::{ - DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTargetStatus, VoteTiming, -}; use crate::model::masternode_input::decode_identity_id; use crate::model::qualified_identity::{IdentityStatus, IdentityType, MasternodeKeyPresence}; use crate::model::user_role::UserRole; -use crate::ui::components::component_trait::Component; -use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; use crate::ui::components::global_nav_switcher::GlobalNavEffect; use crate::ui::components::left_panel::add_left_panel; use crate::ui::components::styled::island_central_panel; @@ -37,11 +29,9 @@ use crate::ui::identity::picker::compute_column_count; use crate::ui::masternodes::card::{MasternodeCard, card_heading}; use crate::ui::masternodes::detail_screen::{DetailOutcome, MasternodeDetailView}; use crate::ui::masternodes::load_form::{LoadFormOutcome, MasternodeLoadForm}; -use crate::ui::masternodes::voting_center::{DpnsVotingCenter, VotingCenterOutcome}; -use crate::ui::state::dpns_vote_operations::DpnsVoteOperationSnapshot; use crate::ui::state::global_nav::PageNavSpec; use crate::ui::state::masternodes_view::{masternodes_page_nav_spec, node_pill_item}; -use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; +use crate::ui::theme::{ComponentStyles, DashColors}; use crate::ui::{RootScreenType, ScreenLike}; /// Minimum horizontal gap between cards in the grid (matches the identity @@ -70,10 +60,6 @@ enum MasternodesView { Load(Box), /// A node's detail / voting view (FR-5). Detail(Box), - /// Shared full-page immediate, bulk, and scheduled composer. - Voting(Box), - /// Shared scheduled-target management. - Scheduled, } /// A load this screen dispatched and has not yet seen finish. The token names @@ -85,19 +71,12 @@ struct PendingLoad { token: IdentityLoadToken, } -#[derive(Clone)] -struct ScheduledJournalTarget { - operation_id: DpnsVoteOperationId, - outcome: DpnsVoteOutcome, -} - /// Root screen for the Masternodes section. pub struct MasternodesScreen { pub app_context: Arc, /// Cached card data for the active network, refreshed on arrival, on /// `refresh`, and on the Refresh button. nodes: Vec, - vote_operations: DpnsVoteOperationSnapshot, /// The active sub-view (list / load / detail). view: MasternodesView, /// The load this screen dispatched and has not yet seen finish, identified by @@ -120,7 +99,6 @@ pub struct MasternodesScreen { /// [`TaskError::IdentityLoadInProgress`](crate::backend_task::error::TaskError::IdentityLoadInProgress) /// instead of racing. pending_load: Option, - pending_schedule_cancellation: Option<(ScheduledJournalTarget, ConfirmationDialog)>, } #[cfg(test)] @@ -142,10 +120,8 @@ impl MasternodesScreen { let mut screen = Self { app_context: app_context.clone(), nodes: Vec::new(), - vote_operations: DpnsVoteOperationSnapshot::default(), view: MasternodesView::List, pending_load: None, - pending_schedule_cancellation: None, }; screen.reload(); screen @@ -156,7 +132,6 @@ impl MasternodesScreen { /// rather than surfacing a technical error β€” the empty state is a safe, /// meaningful fallback. fn reload(&mut self) { - self.refresh_vote_operations(); let identities = self .app_context .load_local_masternode_identities() @@ -192,20 +167,6 @@ impl MasternodesScreen { }); } - fn refresh_vote_operations(&mut self) { - if let Err(error) = self.vote_operations.refresh(&self.app_context) { - tracing::warn!( - ?error, - "Could not refresh the masternode vote-operation cache" - ); - } - match &mut self.view { - MasternodesView::Detail(detail) => detail.refresh_vote_operations(), - MasternodesView::Voting(center) => center.refresh_vote_operations(), - MasternodesView::List | MasternodesView::Load(_) | MasternodesView::Scheduled => {} - } - } - /// Settle the submitted load against the phase its own task reported, and /// release the gate once that load is finished. The single place this screen /// decides a load is over β€” its result and error callbacks fire only while it @@ -243,7 +204,6 @@ impl MasternodesScreen { pub fn reset_for_network_change(&mut self) { self.view = MasternodesView::List; self.pending_load = None; - self.pending_schedule_cancellation = None; self.reload(); } @@ -347,126 +307,12 @@ impl MasternodesScreen { AppAction::None } - /// Operator-level Nodes / Voting / Scheduled navigation. - fn render_voting_navigation(&mut self, ui: &mut egui::Ui) -> AppAction { - let dark_mode = ui.style().visuals.dark_mode; - let action = AppAction::None; - ui.horizontal(|ui| { - if matches!(self.view, MasternodesView::Voting(_)) { - if ComponentStyles::add_secondary_button(ui, "Nodes", dark_mode).clicked() { - self.view = MasternodesView::List; - } - ComponentStyles::add_primary_button(ui, "Voting"); - } else { - if ComponentStyles::add_primary_button(ui, "Nodes").clicked() { - self.view = MasternodesView::List; - } - if ComponentStyles::add_secondary_button(ui, "Voting", dark_mode).clicked() { - self.open_voting_center(None, Vec::new()); - } - } - if matches!(self.view, MasternodesView::Scheduled) { - ComponentStyles::add_primary_button(ui, "Scheduled"); - } else if ComponentStyles::add_secondary_button(ui, "Scheduled", dark_mode).clicked() { - self.view = MasternodesView::Scheduled; - } - }); - ui.separator(); - action - } - - /// Shared target-correlated progress, visible regardless of the active node. - fn render_voting_activity(&mut self, ui: &mut egui::Ui) -> AppAction { - let mut operations = self.vote_operations.operations().to_vec(); - operations.sort_by_key(|operation| operation.created_at); - let operations = operations - .into_iter() - .rev() - .filter(|operation| !operation.targets.is_empty()) - .take(5) - .collect::>(); - if operations.is_empty() { - return AppAction::None; - } - - let dark_mode = ui.style().visuals.dark_mode; - let mut action = AppAction::None; - ui.add_space(16.0); - ui.heading(RichText::new("Voting activity").color(DashColors::text_primary(dark_mode))); - let mut open_operation = None; - for operation in operations { - let total = operation.targets.len(); - let complete = operation - .targets - .iter() - .filter(|outcome| !outcome.status.holds_lock()) - .count(); - ui.label( - RichText::new(format!( - "Operation {} Β· {complete} of {total} targets settled", - operation.id - )) - .strong(), - ); - for outcome in &operation.targets { - let voter = outcome.target.voter_alias.clone().unwrap_or_else(|| { - shorten_id(&outcome.target.key.voter_id.to_string(Encoding::Base58)) - }); - let status = match outcome.status { - DpnsVoteTargetStatus::Scheduled => "Scheduled", - DpnsVoteTargetStatus::Queued => "Queued", - DpnsVoteTargetStatus::Submitting => "Submitting", - DpnsVoteTargetStatus::Confirming => "Confirming", - DpnsVoteTargetStatus::Confirmed => "Confirmed", - DpnsVoteTargetStatus::Unconfirmed => "Checking result", - DpnsVoteTargetStatus::Rejected => "Rejected", - DpnsVoteTargetStatus::FailedBeforeSubmission => "Failed before submission", - DpnsVoteTargetStatus::Cancelled => "Cancelled", - DpnsVoteTargetStatus::NotApplied => "Not applied", - }; - ui.horizontal_wrapped(|ui| { - ui.label(format!( - "{voter} / {}.dash β€” {} β†’ {} β€” {status}", - outcome.target.contested_name, - vote_choice_summary(outcome.target.current_choice), - vote_choice_summary(Some(outcome.target.requested_choice)), - )); - if outcome.status == DpnsVoteTargetStatus::Unconfirmed - && ComponentStyles::add_secondary_button(ui, "Check again", dark_mode) - .clicked() - { - action = AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::ReconcileDpnsVoteOperation( - operation.id, - self.app_context.network(), - ), - )); - } - }); - } - if ComponentStyles::add_secondary_button(ui, "View operation", dark_mode).clicked() { - open_operation = Some(operation.id); - } - ui.separator(); - } - if let Some(operation_id) = open_operation { - self.view = MasternodesView::Voting(Box::new(DpnsVotingCenter::for_operation( - &self.app_context, - operation_id, - ))); - } - action - } - /// The node the page currently operates on β€” the one whose detail view is /// open. The list and load views operate on no single node. fn selected_node_id(&self) -> Option { match &self.view { MasternodesView::Detail(detail) => Some(detail.node_id()), - MasternodesView::List - | MasternodesView::Load(_) - | MasternodesView::Voting(_) - | MasternodesView::Scheduled => None, + MasternodesView::List | MasternodesView::Load(_) => None, } } @@ -538,165 +384,10 @@ impl MasternodesScreen { self.reload(); AppAction::None } - DetailOutcome::OpenVotingCenter { voter_id, choices } => { - self.view = if choices.is_empty() { - MasternodesView::Voting(Box::new(DpnsVotingCenter::new( - &self.app_context, - Some(voter_id), - Vec::new(), - ))) - } else { - MasternodesView::Voting(Box::new(DpnsVotingCenter::for_quick_votes( - &self.app_context, - voter_id, - choices, - ))) - }; - AppAction::None - } DetailOutcome::Forward(action) => *action, } } - fn open_voting_center( - &mut self, - preselected_voter: Option, - preselected_contests: Vec, - ) { - self.view = MasternodesView::Voting(Box::new(DpnsVotingCenter::new( - &self.app_context, - preselected_voter, - preselected_contests, - ))); - } - - fn render_voting_center(&mut self, ui: &mut egui::Ui) -> AppAction { - let outcome = match &mut self.view { - MasternodesView::Voting(center) => center.show(ui), - _ => return AppAction::None, - }; - match outcome { - VotingCenterOutcome::None => AppAction::None, - VotingCenterOutcome::BackToNodes => { - self.view = MasternodesView::List; - AppAction::None - } - VotingCenterOutcome::Action(action) => *action, - } - } - - fn render_scheduled_votes(&mut self, ui: &mut egui::Ui) -> AppAction { - let dark_mode = ui.style().visuals.dark_mode; - let mut action = AppAction::None; - ui.heading("Scheduled votes"); - ui.label( - "Upcoming and unresolved targets use the same operation locks as immediate votes.", - ); - if !self.vote_operations.is_loaded() { - ui.label("Scheduled votes are unavailable. Refresh this page to try again."); - return action; - } - let scheduled_targets = - scheduled_journal_targets(self.vote_operations.operations().to_vec()); - if scheduled_targets.is_empty() { - ui.label("No scheduled votes."); - return action; - } - for scheduled in scheduled_targets { - let target = &scheduled.outcome.target; - let status = scheduled.outcome.status; - let voter = target - .voter_alias - .clone() - .unwrap_or_else(|| shorten_id(&target.key.voter_id.to_string(Encoding::Base58))); - let VoteTiming::Scheduled(scheduled_at) = target.timing else { - continue; - }; - ui.group(|ui| { - ui.label( - RichText::new(format!("{}.dash / {}", target.contested_name, voter)).strong(), - ); - ui.label(format!( - "Choice: {}", - vote_choice_summary(Some(target.requested_choice)) - )); - ui.label(format_scheduled_time(scheduled_at)); - ui.label(match status { - DpnsVoteTargetStatus::Unconfirmed => "Status: Checking result", - DpnsVoteTargetStatus::Queued - | DpnsVoteTargetStatus::Submitting - | DpnsVoteTargetStatus::Confirming => "Status: Submitting", - DpnsVoteTargetStatus::Scheduled => "Status: Scheduled", - DpnsVoteTargetStatus::Confirmed => "Status: Completed", - DpnsVoteTargetStatus::Rejected => "Status: Rejected", - DpnsVoteTargetStatus::FailedBeforeSubmission => { - "Status: Failed before submission" - } - DpnsVoteTargetStatus::Cancelled => "Status: Cancelled", - DpnsVoteTargetStatus::NotApplied => "Status: Not applied", - }); - let editable = status == DpnsVoteTargetStatus::Scheduled; - let disabled_reason = - "This scheduled vote cannot be changed after submission has started."; - if ui - .add_enabled( - editable, - ComponentStyles::secondary_button("Edit schedule", dark_mode), - ) - .disabled_tooltip(disabled_reason) - .clicked() - { - self.view = MasternodesView::Voting(Box::new( - DpnsVotingCenter::for_scheduled_edit(&self.app_context, &scheduled.outcome), - )); - } - if ui - .add_enabled( - editable, - ComponentStyles::secondary_button("Cancel scheduled vote", dark_mode), - ) - .disabled_tooltip(disabled_reason) - .clicked() - { - let message = scheduled_cancel_confirmation(&scheduled.outcome); - self.pending_schedule_cancellation = Some(( - scheduled.clone(), - ConfirmationDialog::new("Cancel scheduled vote", message) - .danger_mode(true) - .confirm_text(Some("Cancel scheduled vote")), - )); - } - if status == DpnsVoteTargetStatus::Unconfirmed - && ComponentStyles::add_secondary_button(ui, "Check again", dark_mode).clicked() - { - action = AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::ReconcileDpnsVoteOperation( - scheduled.operation_id, - self.app_context.network(), - ), - )); - } - }); - } - if let Some((scheduled, dialog)) = self.pending_schedule_cancellation.as_mut() { - let result = dialog.show(ui).inner.dialog_response; - if let Some(result) = result { - let scheduled = scheduled.clone(); - self.pending_schedule_cancellation = None; - if result == ConfirmationStatus::Confirmed { - action = AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::CancelScheduledDpnsVote { - operation_id: scheduled.operation_id, - key: scheduled.outcome.target.key, - contested_name: scheduled.outcome.target.contested_name, - }, - )); - } - } - } - action - } - /// Render the list view: toolbar (`+ Load`, `Refresh`) + empty state or grid. fn render_list_view(&mut self, ui: &mut egui::Ui, network_accent: egui::Color32) -> AppAction { let mut inner = AppAction::None; @@ -815,72 +506,6 @@ impl MasternodesScreen { } } -fn scheduled_journal_targets(operations: Vec) -> Vec { - let mut targets = operations - .into_iter() - .flat_map(|operation| { - operation.targets.into_iter().filter_map(move |outcome| { - matches!(outcome.target.timing, VoteTiming::Scheduled(_)).then_some( - ScheduledJournalTarget { - operation_id: operation.id, - outcome, - }, - ) - }) - }) - .collect::>(); - targets.sort_by_key(|scheduled| match scheduled.outcome.target.timing { - VoteTiming::Scheduled(timestamp) => timestamp, - VoteTiming::Now => u64::MAX, - }); - targets -} - -fn scheduled_cancel_confirmation(outcome: &DpnsVoteOutcome) -> String { - let target = &outcome.target; - let voter = target - .voter_alias - .clone() - .unwrap_or_else(|| shorten_id(&target.key.voter_id.to_string(Encoding::Base58))); - let time = match target.timing { - VoteTiming::Scheduled(timestamp) => format_scheduled_time(timestamp) - .strip_prefix("Scheduled time: ") - .unwrap_or("Unavailable") - .to_owned(), - VoteTiming::Now => "Immediately".to_owned(), - }; - format!( - "Cancel {voter}'s scheduled vote for {}.dash? Choice: {}. Scheduled time: {time}.", - target.contested_name, - vote_choice_summary(Some(target.requested_choice)), - ) -} - -fn vote_choice_summary(choice: Option) -> String { - match choice { - None => "Not voted".to_owned(), - Some(ResourceVoteChoice::Abstain) => "Abstain".to_owned(), - Some(ResourceVoteChoice::Lock) => "Lock".to_owned(), - Some(ResourceVoteChoice::TowardsIdentity(identity)) => { - format!( - "Candidate {}", - shorten_id(&identity.to_string(Encoding::Base58)) - ) - } - } -} - -fn format_scheduled_time(timestamp: u64) -> String { - match Utc.timestamp_millis_opt(timestamp as i64) { - LocalResult::Single(date_time) => format!( - "Scheduled time: {} UTC ({})", - date_time.format("%Y-%m-%d %H:%M"), - HumanTime::from(date_time) - ), - _ => "Scheduled time: Unavailable".to_owned(), - } -} - impl ScreenLike for MasternodesScreen { fn refresh(&mut self) { self.reload(); @@ -889,16 +514,6 @@ impl ScreenLike for MasternodesScreen { fn refresh_on_arrival(&mut self) { self.reload(); self.reconcile_pending_load(); - if let Some(route) = self.app_context.take_dpns_operator_route() { - match route { - DpnsOperatorRoute::Voting { choices } => { - self.view = MasternodesView::Voting(Box::new( - DpnsVotingCenter::for_bulk_choices(&self.app_context, choices), - )); - } - DpnsOperatorRoute::Scheduled => self.view = MasternodesView::Scheduled, - } - } } fn reset_to_root_view(&mut self) { @@ -921,8 +536,7 @@ impl ScreenLike for MasternodesScreen { fn on_leave(&mut self) { match &mut self.view { MasternodesView::Load(form) => form.clear_secrets(), - MasternodesView::Detail(detail) => detail.clear_secrets(), - MasternodesView::List | MasternodesView::Voting(_) | MasternodesView::Scheduled => {} + MasternodesView::List | MasternodesView::Detail(_) => {} } } @@ -943,29 +557,7 @@ impl ScreenLike for MasternodesScreen { } } - fn display_backend_task_result( - &mut self, - context: &crate::backend_task::BackendTaskContext, - result: crate::backend_task::BackendTaskSuccessResult, - ) { - if let MasternodesView::Voting(center) = &mut self.view { - center.display_backend_task_result(context, &result); - } - self.display_task_result(result); - } - - fn display_backend_task_error( - &mut self, - context: &crate::backend_task::BackendTaskContext, - _error: &crate::backend_task::error::TaskError, - ) { - if let MasternodesView::Voting(center) = &mut self.view { - center.display_backend_task_error(context); - } - } - fn display_task_error(&mut self, _error: &crate::backend_task::error::TaskError) -> bool { - self.refresh_vote_operations(); // 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). @@ -988,15 +580,12 @@ impl ScreenLike for MasternodesScreen { action |= island_central_panel(ui, |ui| { ui.set_min_width(ui.available_width()); - let mut action = self.render_voting_navigation(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::Voting(_) => action |= self.render_voting_center(ui), - MasternodesView::Scheduled => action |= self.render_scheduled_votes(ui), MasternodesView::List => action |= self.render_list_view(ui, network_accent), } - action |= self.render_voting_activity(ui); action }); @@ -1012,7 +601,6 @@ mod tests { use crate::backend_task::identity::IdentityInputToLoad; use crate::context::connection_status::ConnectionStatus; use crate::database::test_helpers::create_database_at_path; - use crate::model::dpns_voting::DpnsVoteTargetKey; use crate::model::qualified_identity::QualifiedIdentity; use crate::model::qualified_identity::encrypted_key_storage::KeyStorage; use crate::utils::egui_mpsc::SenderAsync; @@ -1023,72 +611,6 @@ mod tests { use dash_sdk::platform::Identifier; use std::collections::BTreeMap; - fn scheduled_operation( - voter: u8, - poll: u8, - status: DpnsVoteTargetStatus, - alias: Option<&str>, - ) -> DpnsVoteOperation { - let mut operation = - DpnsVoteOperation::new(vec![crate::model::dpns_voting::DpnsVoteTarget { - key: DpnsVoteTargetKey { - network: Network::Testnet, - voter_id: Identifier::from([voter; 32]), - vote_poll_id: Identifier::from([poll; 32]), - }, - voter_alias: alias.map(str::to_owned), - contested_name: "dominguez".to_owned(), - requested_choice: ResourceVoteChoice::Lock, - current_choice: None, - timing: VoteTiming::Scheduled(1_700_000_000_000), - }]); - operation.targets[0].status = status; - operation - } - - #[test] - fn scheduled_view_items_keep_the_exact_journal_operation_id() { - let historical = - scheduled_operation(1, 2, DpnsVoteTargetStatus::Confirmed, Some("Old Eve")); - let unresolved = scheduled_operation(1, 2, DpnsVoteTargetStatus::Unconfirmed, Some("Eve")); - - let items = scheduled_journal_targets(vec![historical.clone(), unresolved.clone()]); - - assert_eq!(items.len(), 2); - assert_eq!(items[0].operation_id, historical.id); - assert_eq!(items[1].operation_id, unresolved.id); - assert_eq!(items[1].outcome.status, DpnsVoteTargetStatus::Unconfirmed); - } - - #[test] - fn scheduled_cancel_confirmation_identifies_the_complete_target() { - let operation = scheduled_operation(1, 2, DpnsVoteTargetStatus::Scheduled, Some("Eve")); - - let message = scheduled_cancel_confirmation(&operation.targets[0]); - - for phrase in ["Eve", "dominguez.dash", "Lock", "UTC"] { - assert!( - message.contains(phrase), - "missing `{phrase}` in `{message}`" - ); - } - } - - #[test] - fn scheduled_cancel_confirmation_uses_a_short_id_without_an_alias() { - let operation = scheduled_operation(1, 2, DpnsVoteTargetStatus::Scheduled, None); - let full_id = operation.targets[0] - .target - .key - .voter_id - .to_string(Encoding::Base58); - - let message = scheduled_cancel_confirmation(&operation.targets[0]); - - assert!(!message.contains(&full_id)); - assert!(message.contains('…')); - } - /// Build an offline, wallet-backend-wired `AppContext` (no network I/O). async fn offline_ctx() -> (Arc, tempfile::TempDir) { let temp_dir = tempfile::tempdir().expect("tempdir"); @@ -1717,36 +1239,6 @@ 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. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/src/ui/masternodes/mod.rs b/src/ui/masternodes/mod.rs index 27d3ed900..89dbc3b52 100644 --- a/src/ui/masternodes/mod.rs +++ b/src/ui/masternodes/mod.rs @@ -10,7 +10,6 @@ pub mod detail_screen; pub mod list_screen; pub mod load_form; pub mod testnet_fixture; -pub mod voting_center; pub use list_screen::MasternodesScreen; diff --git a/src/ui/masternodes/voting_center.rs b/src/ui/masternodes/voting_center.rs deleted file mode 100644 index c2663557d..000000000 --- a/src/ui/masternodes/voting_center.rs +++ /dev/null @@ -1,1473 +0,0 @@ -//! Full-page Nodes β†’ Votes β†’ Review DPNS voting composer. - -use std::collections::BTreeMap; -use std::sync::Arc; - -use chrono::{Duration, LocalResult, TimeZone, Utc}; -use chrono_humanize::HumanTime; -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, ComboBox, RichText}; - -use crate::app::AppAction; -use crate::backend_task::contested_names::ContestedResourceTask; -use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; -use crate::context::AppContext; -use crate::model::contested_name::ContestedName; -use crate::model::dpns_voting::{ - DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTarget, - DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, -}; -use crate::model::qualified_identity::PrivateKeyTarget; -use crate::model::qualified_identity::QualifiedIdentity; -use crate::ui::state::dpns_vote_operations::DpnsVoteOperationSnapshot; -use crate::ui::state::dpns_vote_workspace::{ - ComposerKeyAction, DpnsVoteComposerStep, DpnsVoteWorkspace, DraftVoteTiming, -}; -use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; - -pub enum VotingCenterOutcome { - None, - BackToNodes, - Action(Box), -} - -pub struct DpnsVotingCenter { - app_context: Arc, - voters: Vec, - contests: Vec, - vote_operations: DpnsVoteOperationSnapshot, - workspace: DpnsVoteWorkspace, - submitted_operation: Option, - vote_state_refresh_dispatched: bool, - editing_scheduled_key: Option, - editing_scheduled_original: Option, - focus_step_heading: bool, -} - -struct ReviewDraft { - operation: DpnsVoteOperation, - exclusions: Vec, -} - -struct ReviewExclusion { - voter: String, - contest: String, - requested_choice: ResourceVoteChoice, - reason: &'static str, - no_op: bool, -} - -impl DpnsVotingCenter { - pub(crate) fn refresh_vote_operations(&mut self) { - if let Err(error) = self.vote_operations.refresh(&self.app_context) { - tracing::warn!(?error, "Could not refresh voting-center operation state"); - } - } - - pub(crate) fn display_backend_task_result( - &mut self, - context: &BackendTaskContext, - result: &BackendTaskSuccessResult, - ) { - self.refresh_vote_operations(); - if matches!(result, BackendTaskSuccessResult::RefreshedDpnsContests) { - self.vote_state_refresh_dispatched = false; - match self.app_context.ongoing_contested_names() { - Ok(contests) => self.contests = contests, - Err(error) => { - tracing::warn!(?error, "Could not reload refreshed DPNS contests"); - } - } - } - self.submitted_operation = - updated_submitted_operation(self.submitted_operation, context, result); - } - - pub(crate) fn display_backend_task_error(&mut self, context: &BackendTaskContext) { - self.refresh_vote_operations(); - let Some(operation_id) = self.submitted_operation else { - return; - }; - if should_return_to_review_after_error( - operation_id, - self.app_context.network(), - context, - self.vote_operations.operation(operation_id).is_some(), - ) { - self.submitted_operation = None; - self.workspace.step = DpnsVoteComposerStep::Review; - self.focus_step_heading = true; - } - } - - pub fn new( - app_context: &Arc, - preselected_voter: Option, - preselected_contests: Vec, - ) -> Self { - let voters = app_context - .load_local_voting_identities() - .unwrap_or_default(); - let mut workspace = DpnsVoteWorkspace::new(voters.iter().map(|voter| voter.identity.id())); - if let Some(voter_id) = preselected_voter { - workspace.prefilter_node(voter_id); - } - let contests = app_context.ongoing_contested_names().unwrap_or_default(); - let vote_operations = - DpnsVoteOperationSnapshot::load(app_context).unwrap_or_else(|error| { - tracing::warn!( - ?error, - "Could not cache DPNS vote operations for the voting center" - ); - DpnsVoteOperationSnapshot::default() - }); - if !preselected_contests.is_empty() { - for name in preselected_contests { - if contests - .iter() - .any(|contest| contest.normalized_contested_name == name) - { - workspace - .contest_choices - .entry(name) - .or_insert(ResourceVoteChoice::Abstain); - } - } - } - Self { - app_context: Arc::clone(app_context), - voters, - contests, - vote_operations, - workspace, - submitted_operation: None, - vote_state_refresh_dispatched: false, - editing_scheduled_key: None, - editing_scheduled_original: None, - focus_step_heading: true, - } - } - - pub fn for_scheduled_edit(app_context: &Arc, outcome: &DpnsVoteOutcome) -> Self { - let vote = &outcome.target; - let mut center = Self::new( - app_context, - Some(vote.key.voter_id), - vec![vote.contested_name.clone()], - ); - center - .workspace - .contest_choices - .insert(vote.contested_name.clone(), vote.requested_choice); - let VoteTiming::Scheduled(timestamp) = vote.timing else { - return center; - }; - center - .workspace - .node_timing - .insert(vote.key.voter_id, scheduled_offset_from_now(timestamp)); - center.editing_scheduled_key = Some(vote.key.clone()); - center.editing_scheduled_original = Some(vote.clone()); - center - } - - pub fn for_quick_votes( - app_context: &Arc, - voter_id: Identifier, - choices: BTreeMap, - ) -> Self { - let mut center = Self::new( - app_context, - Some(voter_id), - choices.keys().cloned().collect(), - ); - center.workspace.contest_choices = choices; - center.workspace.step = DpnsVoteComposerStep::Review; - center - } - - pub fn for_bulk_choices( - app_context: &Arc, - choices: BTreeMap, - ) -> Self { - let mut center = Self::new(app_context, None, choices.keys().cloned().collect()); - center.workspace.contest_choices = choices; - center - } - - pub fn for_operation(app_context: &Arc, operation_id: DpnsVoteOperationId) -> Self { - let mut center = Self::new(app_context, None, Vec::new()); - center.submitted_operation = Some(operation_id); - center - } - - pub fn show(&mut self, ui: &mut egui::Ui) -> VotingCenterOutcome { - if self.submitted_operation.is_some() { - return self.render_operation(ui); - } - let (enter, escape) = ui.input(|input| { - ( - input.key_pressed(egui::Key::Enter), - input.key_pressed(egui::Key::Escape), - ) - }); - let can_continue = match self.workspace.step { - DpnsVoteComposerStep::Nodes => self.workspace.selected_node_count() > 0, - DpnsVoteComposerStep::Votes => !self.workspace.contest_choices.is_empty(), - DpnsVoteComposerStep::Review => !self.build_review().operation.targets.is_empty(), - }; - match self.workspace.keyboard_action(enter, escape, can_continue) { - ComposerKeyAction::CloseDraft => return VotingCenterOutcome::BackToNodes, - ComposerKeyAction::Advance => { - self.workspace.step = match self.workspace.step { - DpnsVoteComposerStep::Nodes => DpnsVoteComposerStep::Votes, - DpnsVoteComposerStep::Votes | DpnsVoteComposerStep::Review => { - DpnsVoteComposerStep::Review - } - }; - self.focus_step_heading = true; - } - ComposerKeyAction::Submit => { - return self.submit_operation(self.build_review().operation); - } - ComposerKeyAction::None => {} - } - let needs_refresh = self - .selected_current_states() - .iter() - .any(|(_, state)| matches!(state, DpnsCurrentVoteState::Checking)); - if needs_refresh && !self.vote_state_refresh_dispatched { - self.vote_state_refresh_dispatched = true; - return VotingCenterOutcome::Action(Box::new(AppAction::BackendTask( - BackendTask::ContestedResourceTask(ContestedResourceTask::QueryDPNSContests), - ))); - } - - match self.workspace.step { - DpnsVoteComposerStep::Nodes => self.render_nodes(ui), - DpnsVoteComposerStep::Votes => self.render_votes(ui), - DpnsVoteComposerStep::Review => self.render_review(ui), - } - } - - fn render_nodes(&mut self, ui: &mut egui::Ui) -> VotingCenterOutcome { - let dark_mode = ui.style().visuals.dark_mode; - self.step_heading(ui, "Step 1 of 3: Nodes and timing"); - ui.label("Choose which nodes will vote and when each node should submit."); - if self.voters.is_empty() { - ui.separator(); - let go_to_nodes = ui - .vertical_centered(|ui| { - ui.heading("No voting nodes are available"); - ui.label("Load a masternode on the Nodes tab before creating a vote."); - ui.add_space(8.0); - ComponentStyles::add_primary_button_enabled(ui, true, "Go to Nodes").clicked() - }) - .inner; - return if go_to_nodes { - VotingCenterOutcome::BackToNodes - } else { - VotingCenterOutcome::None - }; - } - ui.horizontal_wrapped(|ui| { - ui.label("Set all:"); - timing_combo( - ui, - "voting_center_set_all", - &mut self.workspace.set_all_timing, - ); - if ComponentStyles::add_secondary_button(ui, "Apply", dark_mode).clicked() { - self.workspace.apply_timing_to_selected(); - } - }); - ui.separator(); - for voter in &self.voters { - let voter_id = voter.identity.id(); - let alias = voter - .alias - .clone() - .unwrap_or_else(|| voter_id.to_string(Encoding::Base58)); - let has_voting_key = has_loaded_voting_key(voter); - ui.horizontal_wrapped(|ui| { - let mut selected = self.workspace.is_node_selected(&voter_id); - let checkbox = ui.add_enabled( - has_voting_key, - egui::Checkbox::new(&mut selected, RichText::new(alias).strong()), - ); - if checkbox.changed() { - self.workspace.set_node_selected(voter_id, selected); - } - checkbox - .disabled_tooltip("Load this node's voting private key before selecting it."); - let timing = self - .workspace - .node_timing - .entry(voter_id) - .or_insert(DraftVoteTiming::Now); - ui.add_enabled_ui(selected && has_voting_key, |ui| { - timing_combo(ui, format!("voting_center_node_{voter_id}"), timing); - render_schedule_offset(ui, timing); - }); - if !has_voting_key { - ui.label( - RichText::new("Voting key missing") - .color(DashColors::warning_color(dark_mode)), - ); - } - }); - } - ui.separator(); - let enabled = self.workspace.selected_node_count() > 0; - if ComponentStyles::add_primary_button_enabled(ui, enabled, "Next: Choose votes") - .disabled_tooltip("Choose at least one node before continuing.") - .clicked() - { - self.workspace.step = DpnsVoteComposerStep::Votes; - self.focus_step_heading = true; - } - VotingCenterOutcome::None - } - - fn render_votes(&mut self, ui: &mut egui::Ui) -> VotingCenterOutcome { - let dark_mode = ui.style().visuals.dark_mode; - self.step_heading(ui, "Step 2 of 3: Votes"); - ui.label("Choose one requested vote for each contested name."); - let mut outcome = VotingCenterOutcome::None; - if self.contests.is_empty() { - ui.separator(); - ui.label("No active contests are available. Refresh contests to check again."); - if ComponentStyles::add_secondary_button(ui, "Refresh contests", dark_mode).clicked() { - self.vote_state_refresh_dispatched = true; - outcome = VotingCenterOutcome::Action(Box::new(AppAction::BackendTask( - BackendTask::ContestedResourceTask(ContestedResourceTask::QueryDPNSContests), - ))); - } - } - for contest in &self.contests { - let name = &contest.normalized_contested_name; - ui.separator(); - ui.label(RichText::new(format!("{name}.dash")).strong()); - let states = self.current_states_for_contest(contest); - ui.label( - RichText::new(current_summary(&states)) - .color(DashColors::text_secondary(dark_mode)), - ); - let vote_poll_id = self.app_context.dpns_vote_poll_id(name).ok(); - let controls_enabled = states.iter().any(|(voter_id, state, locked)| { - let lock_is_this_edit = vote_poll_id.is_some_and(|vote_poll_id| { - self.editing_scheduled_key.as_ref() - == Some(&DpnsVoteTargetKey { - network: self.app_context.network(), - voter_id: *voter_id, - vote_poll_id, - }) - }); - (!*locked || lock_is_this_edit) - && matches!(state, DpnsCurrentVoteState::Available(_)) - }); - let selected = self.workspace.contest_choices.get(name).copied(); - ui.add_enabled_ui(controls_enabled, |ui| { - ui.horizontal_wrapped(|ui| { - vote_choice( - ui, - selected, - ResourceVoteChoice::Abstain, - "Abstain", - &mut self.workspace, - name, - ); - vote_choice( - ui, - selected, - ResourceVoteChoice::Lock, - "Lock", - &mut self.workspace, - name, - ); - for candidate in contest.contestants.as_deref().unwrap_or_default() { - vote_choice( - ui, - selected, - ResourceVoteChoice::TowardsIdentity(candidate.id), - &format!("Vote for {}", candidate.name), - &mut self.workspace, - name, - ); - } - }); - }); - for (voter_id, state, locked) in &states { - let voter = self.voter_label(*voter_id); - let status = match (state, locked) { - (_, true) => "This target already has a voting operation in progress.", - (DpnsCurrentVoteState::Checking, false) => { - "DET is checking this node's current vote." - } - (DpnsCurrentVoteState::Unavailable, false) => { - "This node's current vote is unavailable." - } - _ => continue, - }; - ui.label( - RichText::new(format!("{voter}: {status}")) - .color(DashColors::text_secondary(dark_mode)), - ); - } - let can_refresh = states.iter().any(|(_, state, locked)| { - !locked - && matches!( - state, - DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable - ) - }); - if can_refresh - && ComponentStyles::add_secondary_button(ui, "Refresh vote state", dark_mode) - .clicked() - { - self.vote_state_refresh_dispatched = true; - outcome = VotingCenterOutcome::Action(Box::new(AppAction::BackendTask( - BackendTask::ContestedResourceTask(ContestedResourceTask::QueryDPNSContests), - ))); - } - } - ui.separator(); - ui.horizontal(|ui| { - if ComponentStyles::add_secondary_button(ui, "Back", dark_mode).clicked() { - self.workspace.step = DpnsVoteComposerStep::Nodes; - self.focus_step_heading = true; - } - let target_count = - self.workspace.selected_node_count() * self.workspace.contest_choices.len(); - let enabled = target_count > 0; - if ComponentStyles::add_primary_button_enabled( - ui, - enabled, - format!("Review {target_count} targets"), - ) - .disabled_tooltip("Choose at least one contested name before continuing.") - .clicked() - { - self.workspace.step = DpnsVoteComposerStep::Review; - self.focus_step_heading = true; - } - if ComponentStyles::add_secondary_button(ui, "Close Voting Center", dark_mode).clicked() - { - outcome = VotingCenterOutcome::BackToNodes; - } - }); - outcome - } - - fn render_review(&mut self, ui: &mut egui::Ui) -> VotingCenterOutcome { - let dark_mode = ui.style().visuals.dark_mode; - self.step_heading(ui, "Step 3 of 3: Review"); - let review = self.build_review(); - for outcome in &review.operation.targets { - let voter = outcome - .target - .voter_alias - .clone() - .unwrap_or_else(|| shorten_identifier(outcome.target.key.voter_id)); - ui.group(|ui| { - ui.label(RichText::new(format!( - "{voter} / {}.dash", - outcome.target.contested_name - )) - .strong()); - ui.label(format!( - "{} β†’ {}", - self.choice_label( - &outcome.target.contested_name, - outcome.target.current_choice - ), - self.choice_label( - &outcome.target.contested_name, - Some(outcome.target.requested_choice) - ) - )); - if self.editing_scheduled_key.as_ref() == Some(&outcome.target.key) { - if let Some(original) = &self.editing_scheduled_original { - ui.label(scheduled_replacement_summary( - original, - &outcome.target, - |name, choice| self.choice_label(name, choice), - )); - } - } else { - ui.label(format_timing(outcome.target.timing)); - } - if outcome.target.current_choice.is_some() { - ui.label( - RichText::new( - "This changes an existing vote. Platform permits only a limited number of vote changes.", - ) - .color(DashColors::warning_color(dark_mode)), - ); - } - }); - } - if review.operation.no_op_count > 0 { - ui.label(format!( - "{} targets already have the requested vote and will not be submitted.", - review.operation.no_op_count - )); - } - for exclusion in &review.exclusions { - ui.label(format!( - "{} / {}.dash β†’ {} was excluded. {}", - exclusion.voter, - exclusion.contest, - self.choice_label(&exclusion.contest, Some(exclusion.requested_choice)), - exclusion.reason - )); - } - ui.label(format!( - "{} targets total. Each submitted vote uses Platform credits.", - review.operation.targets.len() - )); - ui.horizontal(|ui| { - if ComponentStyles::add_secondary_button(ui, "Back", dark_mode).clicked() { - self.workspace.step = DpnsVoteComposerStep::Votes; - self.focus_step_heading = true; - } - }); - if review.operation.targets.is_empty() { - if review.operation.no_op_count > 0 - && review.exclusions.iter().all(|exclusion| exclusion.no_op) - { - ui.label( - "Every selected node already has the requested vote. Nothing will be submitted.", - ); - } else { - ui.label( - "No targets are ready to submit. Refresh unavailable vote state or wait for in-progress targets.", - ); - } - return VotingCenterOutcome::None; - } - let target_count = review.operation.targets.len(); - if ComponentStyles::add_primary_button(ui, format!("Submit {target_count} targets")) - .clicked() - { - return self.submit_operation(review.operation); - } - VotingCenterOutcome::None - } - - fn render_operation(&mut self, ui: &mut egui::Ui) -> VotingCenterOutcome { - let dark_mode = ui.style().visuals.dark_mode; - let Some(operation_id) = self.submitted_operation else { - return VotingCenterOutcome::None; - }; - ui.heading("Voting operation"); - match self.vote_operations.operation(operation_id).cloned() { - Some(operation) => { - for outcome in &operation.targets { - ui.group(|ui| { - let voter = outcome - .target - .voter_alias - .clone() - .unwrap_or_else(|| shorten_identifier(outcome.target.key.voter_id)); - ui.label( - RichText::new(format!( - "{voter} / {}.dash", - outcome.target.contested_name - )) - .strong(), - ); - ui.label(format!( - "{} β†’ {}", - self.choice_label( - &outcome.target.contested_name, - outcome.target.current_choice - ), - self.choice_label( - &outcome.target.contested_name, - Some(outcome.target.requested_choice) - ) - )); - ui.label(format_timing(outcome.target.timing)); - ui.label(format!("Status: {}", status_label(outcome.status))); - ui.label(status_explanation(outcome.status)); - if let Some(hash) = outcome.transition_hash { - let hash = hex::encode(hash); - if ui.small_button("Copy transition hash").clicked() { - ui.ctx().copy_text(hash); - } - } - }); - } - if operation - .targets - .iter() - .any(|outcome| outcome.status == DpnsVoteTargetStatus::Unconfirmed) - && ComponentStyles::add_secondary_button(ui, "Check again", dark_mode).clicked() - { - return VotingCenterOutcome::Action(Box::new(AppAction::BackendTask( - BackendTask::ContestedResourceTask( - ContestedResourceTask::ReconcileDpnsVoteOperation( - operation_id, - self.app_context.network(), - ), - ), - ))); - } - if operation.targets.iter().any(|outcome| { - matches!( - outcome.status, - DpnsVoteTargetStatus::Rejected - | DpnsVoteTargetStatus::FailedBeforeSubmission - | DpnsVoteTargetStatus::Cancelled - | DpnsVoteTargetStatus::NotApplied - ) - }) && ComponentStyles::add_secondary_button(ui, "Review again", dark_mode) - .clicked() - { - self.workspace.contest_choices = operation - .targets - .iter() - .filter(|outcome| { - matches!( - outcome.status, - DpnsVoteTargetStatus::Rejected - | DpnsVoteTargetStatus::FailedBeforeSubmission - | DpnsVoteTargetStatus::Cancelled - | DpnsVoteTargetStatus::NotApplied - ) - }) - .map(|outcome| { - ( - outcome.target.contested_name.clone(), - outcome.target.requested_choice, - ) - }) - .collect(); - for outcome in &operation.targets { - if matches!( - outcome.status, - DpnsVoteTargetStatus::Rejected - | DpnsVoteTargetStatus::FailedBeforeSubmission - | DpnsVoteTargetStatus::Cancelled - | DpnsVoteTargetStatus::NotApplied - ) { - self.workspace - .set_node_selected(outcome.target.key.voter_id, true); - self.workspace.node_timing.insert( - outcome.target.key.voter_id, - match outcome.target.timing { - VoteTiming::Now => DraftVoteTiming::Now, - VoteTiming::Scheduled(timestamp) => { - scheduled_offset_from_now(timestamp) - } - }, - ); - } - } - self.workspace.step = DpnsVoteComposerStep::Review; - self.submitted_operation = None; - self.focus_step_heading = true; - } - if ComponentStyles::add_secondary_button(ui, "Continue in background", dark_mode) - .clicked() - { - return VotingCenterOutcome::BackToNodes; - } - } - None if self.vote_operations.is_loaded() => { - ui.horizontal(|ui| { - ui.spinner(); - ui.label("Queuing votes…"); - }); - } - None => { - ui.label("This operation could not be loaded. Refresh and try again."); - } - } - VotingCenterOutcome::None - } - - fn selected_voters(&self) -> Vec { - self.voters - .iter() - .filter(|voter| self.workspace.is_node_selected(&voter.identity.id())) - .filter(|voter| has_loaded_voting_key(voter)) - .cloned() - .collect() - } - - fn submit_operation(&mut self, operation: DpnsVoteOperation) -> VotingCenterOutcome { - self.submitted_operation = Some(operation.id); - VotingCenterOutcome::Action(Box::new(AppAction::BackendTask( - BackendTask::ContestedResourceTask(ContestedResourceTask::SubmitDpnsVoteOperation( - operation, - self.selected_voters(), - self.editing_scheduled_key.clone(), - self.app_context.network(), - )), - ))) - } - - fn step_heading(&mut self, ui: &mut egui::Ui, text: &str) { - let response = ui.heading(text); - if std::mem::take(&mut self.focus_step_heading) { - response.request_focus(); - } - } - - fn selected_current_states(&self) -> Vec<(Identifier, DpnsCurrentVoteState)> { - self.contests - .iter() - .flat_map(|contest| { - let poll_id = self - .app_context - .dpns_vote_poll_id(&contest.normalized_contested_name) - .ok(); - self.selected_voters().into_iter().filter_map(move |voter| { - let poll_id = poll_id?; - let voter_id = voter.identity.id(); - Some(( - voter_id, - self.app_context - .dpns_current_vote_state(voter_id, poll_id) - .unwrap_or(DpnsCurrentVoteState::Unavailable), - )) - }) - }) - .collect() - } - - fn current_states_for_contest( - &self, - contest: &ContestedName, - ) -> Vec<(Identifier, DpnsCurrentVoteState, bool)> { - let Ok(vote_poll_id) = self - .app_context - .dpns_vote_poll_id(&contest.normalized_contested_name) - else { - return self - .selected_voters() - .into_iter() - .map(|voter| { - ( - voter.identity.id(), - DpnsCurrentVoteState::Unavailable, - false, - ) - }) - .collect(); - }; - self.selected_voters() - .into_iter() - .map(|voter| { - let voter_id = voter.identity.id(); - let key = DpnsVoteTargetKey { - network: self.app_context.network(), - voter_id, - vote_poll_id, - }; - ( - voter_id, - self.app_context - .dpns_current_vote_state(voter_id, vote_poll_id) - .unwrap_or(DpnsCurrentVoteState::Unavailable), - self.vote_operations.target_status(&key).is_some(), - ) - }) - .collect() - } - - fn build_review(&self) -> ReviewDraft { - let mut targets = Vec::new(); - let mut exclusions = Vec::new(); - for voter in self.selected_voters() { - let voter_id = voter.identity.id(); - let draft_timing = self.workspace.node_timing[&voter_id]; - let timing = match draft_timing { - DraftVoteTiming::Now => VoteTiming::Now, - DraftVoteTiming::Scheduled { - days, - hours, - minutes, - } => VoteTiming::Scheduled( - (Utc::now() - + Duration::days(i64::from(days)) - + Duration::hours(i64::from(hours)) - + Duration::minutes(i64::from(minutes))) - .timestamp_millis() as u64, - ), - }; - for (name, requested_choice) in &self.workspace.contest_choices { - let vote_poll_id = match self.app_context.dpns_vote_poll_id(name) { - Ok(vote_poll_id) => vote_poll_id, - Err(_) => { - exclusions.push(ReviewExclusion { - voter: self.voter_label(voter_id), - contest: name.clone(), - requested_choice: *requested_choice, - reason: "Refresh this contest before submitting a vote.", - no_op: false, - }); - continue; - } - }; - let key = DpnsVoteTargetKey { - network: self.app_context.network(), - voter_id, - vote_poll_id, - }; - let existing_status = if self.vote_operations.is_loaded() { - self.vote_operations.target_status(&key) - } else { - exclusions.push(ReviewExclusion { - voter: self.voter_label(voter_id), - contest: name.clone(), - requested_choice: *requested_choice, - reason: "DET could not check whether this target is already in use.", - no_op: false, - }); - continue; - }; - let replacing_schedule = is_explicit_schedule_replacement( - self.editing_scheduled_key.as_ref(), - &key, - existing_status, - timing, - ); - if existing_status.is_some() && !replacing_schedule { - exclusions.push(ReviewExclusion { - voter: self.voter_label(voter_id), - contest: name.clone(), - requested_choice: *requested_choice, - reason: "Another voting operation is still using this target.", - no_op: false, - }); - continue; - } - let current_choice = match self - .app_context - .dpns_current_vote_state(voter_id, vote_poll_id) - { - Ok(DpnsCurrentVoteState::Available(current_choice)) => current_choice, - Ok(DpnsCurrentVoteState::Checking) => { - exclusions.push(ReviewExclusion { - voter: self.voter_label(voter_id), - contest: name.clone(), - requested_choice: *requested_choice, - reason: "DET is still checking this node's current vote.", - no_op: false, - }); - continue; - } - Ok(DpnsCurrentVoteState::Unavailable) | Err(_) => { - exclusions.push(ReviewExclusion { - voter: self.voter_label(voter_id), - contest: name.clone(), - requested_choice: *requested_choice, - reason: "Refresh this node's vote state before submitting it.", - no_op: false, - }); - continue; - } - }; - if current_choice == Some(*requested_choice) { - exclusions.push(ReviewExclusion { - voter: self.voter_label(voter_id), - contest: name.clone(), - requested_choice: *requested_choice, - reason: "This node already has the requested vote, so nothing will be submitted.", - no_op: true, - }); - } - targets.push(DpnsVoteTarget { - key, - voter_alias: voter.alias.clone(), - contested_name: name.clone(), - requested_choice: *requested_choice, - current_choice, - timing, - }); - } - } - ReviewDraft { - operation: DpnsVoteOperation::new(targets), - exclusions, - } - } - - fn voter_label(&self, voter_id: Identifier) -> String { - self.voters - .iter() - .find(|voter| voter.identity.id() == voter_id) - .and_then(|voter| voter.alias.clone()) - .unwrap_or_else(|| shorten_identifier(voter_id)) - } - - fn choice_label(&self, contest_name: &str, choice: Option) -> String { - let contestants = self - .contests - .iter() - .find(|contest| contest.normalized_contested_name == contest_name) - .and_then(|contest| contest.contestants.as_deref()) - .unwrap_or_default(); - choice_label(choice, contestants) - } -} - -fn timing_combo(ui: &mut egui::Ui, id: impl Into, timing: &mut DraftVoteTiming) { - ComboBox::from_id_salt(id.into()) - .selected_text(match timing { - DraftVoteTiming::Now => "Cast now", - DraftVoteTiming::Scheduled { .. } => "Schedule", - }) - .show_ui(ui, |ui| { - ui.selectable_value(timing, DraftVoteTiming::Now, "Cast now"); - if ui - .selectable_label( - matches!(timing, DraftVoteTiming::Scheduled { .. }), - "Schedule", - ) - .clicked() - { - *timing = DraftVoteTiming::Scheduled { - days: 0, - hours: 0, - minutes: 0, - }; - } - }); -} - -fn render_schedule_offset(ui: &mut egui::Ui, timing: &mut DraftVoteTiming) { - if let DraftVoteTiming::Scheduled { - days, - hours, - minutes, - } = timing - { - 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("Minutes: ") - .range(0..=59), - ); - } -} - -fn vote_choice( - ui: &mut egui::Ui, - selected: Option, - choice: ResourceVoteChoice, - label: &str, - workspace: &mut DpnsVoteWorkspace, - name: &str, -) { - if ui - .selectable_label(selected == Some(choice), label) - .clicked() - { - workspace.contest_choices.insert(name.to_owned(), choice); - } -} - -fn current_summary(states: &[(Identifier, DpnsCurrentVoteState, bool)]) -> String { - if states.is_empty() { - return "Current vote state is unavailable for selected nodes".to_owned(); - } - let checking = states - .iter() - .filter(|(_, state, locked)| !locked && *state == DpnsCurrentVoteState::Checking) - .count(); - let unavailable = states - .iter() - .filter(|(_, state, locked)| !locked && *state == DpnsCurrentVoteState::Unavailable) - .count(); - let busy = states.iter().filter(|(_, _, locked)| *locked).count(); - let available = states - .iter() - .filter(|(_, state, locked)| !locked && matches!(state, DpnsCurrentVoteState::Available(_))) - .count(); - let not_voted = states - .iter() - .filter(|(_, state, locked)| !locked && *state == DpnsCurrentVoteState::Available(None)) - .count(); - if available == states.len() && not_voted == states.len() { - return "Current across selected nodes: Not voted".to_owned(); - } - if available == states.len() && not_voted == 0 { - return "Current across selected nodes: All already voted".to_owned(); - } - let mut parts = Vec::new(); - if not_voted > 0 { - parts.push(format!("{not_voted} not voted")); - } - let already_voted = available.saturating_sub(not_voted); - if already_voted > 0 { - parts.push(format!("{already_voted} already voted")); - } - if checking > 0 { - parts.push(format!("{checking} checking")); - } - if unavailable > 0 { - parts.push(format!("{unavailable} unavailable")); - } - if busy > 0 { - parts.push(format!("{busy} in progress")); - } - if parts.is_empty() { - "Current across selected nodes: No usable targets".to_owned() - } else { - format!("Current across selected nodes: {}", parts.join(", ")) - } -} - -fn choice_label( - choice: Option, - contestants: &[crate::model::contested_name::Contestant], -) -> String { - match choice { - None => "Not voted".to_owned(), - Some(ResourceVoteChoice::Abstain) => "Abstain".to_owned(), - Some(ResourceVoteChoice::Lock) => "Lock".to_owned(), - Some(ResourceVoteChoice::TowardsIdentity(identity)) => { - let short_id = shorten_identifier(identity); - contestants - .iter() - .find(|contestant| contestant.id == identity) - .map(|contestant| format!("{} ({short_id})", contestant.name)) - .unwrap_or_else(|| format!("Candidate {short_id}")) - } - } -} - -fn shorten_identifier(identifier: Identifier) -> String { - let encoded = identifier.to_string(Encoding::Base58); - if encoded.chars().count() <= 12 { - return encoded; - } - let first = encoded.chars().take(6).collect::(); - let last = encoded - .chars() - .rev() - .take(4) - .collect::() - .chars() - .rev() - .collect::(); - format!("{first}…{last}") -} - -fn format_timing(timing: VoteTiming) -> String { - match timing { - VoteTiming::Now => "When: Cast now".to_owned(), - VoteTiming::Scheduled(timestamp) => match Utc.timestamp_millis_opt(timestamp as i64) { - LocalResult::Single(date_time) => format!( - "When: {} UTC ({})", - date_time.format("%Y-%m-%d %H:%M"), - HumanTime::from(date_time) - ), - _ => "When: The scheduled time is unavailable.".to_owned(), - }, - } -} - -fn scheduled_replacement_summary( - original: &DpnsVoteTarget, - replacement: &DpnsVoteTarget, - choice_label: impl Fn(&str, Option) -> String, -) -> String { - format!( - "Replacing scheduled vote: {} at {} β†’ {} at {}.", - choice_label(&original.contested_name, Some(original.requested_choice)), - scheduled_time_label(original.timing), - choice_label( - &replacement.contested_name, - Some(replacement.requested_choice) - ), - scheduled_time_label(replacement.timing), - ) -} - -fn scheduled_time_label(timing: VoteTiming) -> String { - match timing { - VoteTiming::Now => "now".to_owned(), - VoteTiming::Scheduled(timestamp) => match Utc.timestamp_millis_opt(timestamp as i64) { - LocalResult::Single(date_time) => { - format!("{} UTC", date_time.format("%Y-%m-%d %H:%M")) - } - _ => "an unavailable time".to_owned(), - }, - } -} - -fn scheduled_offset_from_now(timestamp: u64) -> DraftVoteTiming { - let remaining_minutes = timestamp.saturating_sub(Utc::now().timestamp_millis() as u64) / 60_000; - DraftVoteTiming::Scheduled { - days: (remaining_minutes / (24 * 60)) as u32, - hours: ((remaining_minutes / 60) % 24) as u32, - minutes: (remaining_minutes % 60) as u32, - } -} - -fn is_explicit_schedule_replacement( - editing_key: Option<&DpnsVoteTargetKey>, - target_key: &DpnsVoteTargetKey, - existing_status: Option, - replacement_timing: VoteTiming, -) -> bool { - editing_key == Some(target_key) - && existing_status == Some(DpnsVoteTargetStatus::Scheduled) - && matches!(replacement_timing, VoteTiming::Scheduled(_)) -} - -fn should_return_to_review_after_error( - submitted_operation: DpnsVoteOperationId, - network: dash_sdk::dpp::dashcore::Network, - context: &BackendTaskContext, - operation_was_journaled: bool, -) -> bool { - !operation_was_journaled - && context - == &BackendTaskContext::DpnsVoteOperation { - network, - operation_id: submitted_operation, - } -} - -fn updated_submitted_operation( - submitted_operation: Option, - context: &BackendTaskContext, - result: &BackendTaskSuccessResult, -) -> Option { - match (submitted_operation, context, result) { - ( - Some(submitted), - BackendTaskContext::DpnsVoteOperation { - network: submitted_network, - operation_id: submitted_id, - }, - BackendTaskSuccessResult::DpnsVoteOperationUpdated { - network: result_network, - operation_id: result_id, - }, - ) if submitted == *submitted_id && submitted_network == result_network => Some(*result_id), - _ => submitted_operation, - } -} - -fn has_loaded_voting_key(voter: &QualifiedIdentity) -> bool { - voter - .private_keys - .keys_set() - .iter() - .any(|(target, _)| *target == PrivateKeyTarget::PrivateKeyOnVoterIdentity) -} - -fn 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 => "Checking result", - DpnsVoteTargetStatus::Rejected => "Rejected", - DpnsVoteTargetStatus::FailedBeforeSubmission => "Failed before submission", - DpnsVoteTargetStatus::Cancelled => "Cancelled", - DpnsVoteTargetStatus::NotApplied => "Not applied", - } -} - -fn status_explanation(status: DpnsVoteTargetStatus) -> &'static str { - match status { - DpnsVoteTargetStatus::Scheduled => "DET will submit this vote at the scheduled time.", - DpnsVoteTargetStatus::Queued => "This vote is waiting to be submitted.", - DpnsVoteTargetStatus::Submitting => "DET is submitting this vote.", - DpnsVoteTargetStatus::Confirming => "The vote was submitted and is being confirmed.", - DpnsVoteTargetStatus::Confirmed => "Platform confirmed this vote.", - DpnsVoteTargetStatus::Unconfirmed => { - "The vote was submitted, but DET could not confirm it yet. Do not submit it again." - } - DpnsVoteTargetStatus::Rejected => { - "Platform rejected this vote. Review the choice before trying again." - } - DpnsVoteTargetStatus::FailedBeforeSubmission => { - "This vote was not submitted. Review it before trying again." - } - DpnsVoteTargetStatus::Cancelled => { - "This scheduled vote was cancelled before it was submitted." - } - DpnsVoteTargetStatus::NotApplied => { - "This vote was not applied. You can safely review it and try again." - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - 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::model::contested_name::Contestant; - use crate::model::user_role::UserRoleCell; - use crate::utils::egui_mpsc::SenderAsync; - use crate::utils::tasks::TaskManager; - use egui_kittest::Harness; - use egui_kittest::kittest::Queryable; - use std::cell::{Cell, RefCell}; - use std::rc::Rc; - - async fn offline_ctx() -> (Arc, tempfile::TempDir) { - let temp_dir = tempfile::tempdir().expect("tempdir"); - let data_dir = temp_dir.path().to_path_buf(); - 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 context = AppContext::new( - data_dir, - dash_sdk::dpp::dashcore::Network::Testnet, - db, - Arc::new(TaskManager::new()), - Arc::new(ConnectionStatus::new()), - egui::Context::default(), - app_kv, - secret_store, - UserRoleCell::default(), - ) - .expect("offline AppContext"); - let (sender, _receiver) = tokio::sync::mpsc::channel::(32); - context - .ensure_wallet_backend(SenderAsync::new(sender, context.egui_ctx().clone())) - .await - .expect("wire wallet backend offline"); - (context, temp_dir) - } - - fn contestant(id: Identifier, name: &str) -> Contestant { - Contestant { - id, - name: name.to_owned(), - info: String::new(), - votes: 0, - created_at: None, - created_at_block_height: None, - created_at_core_block_height: None, - document_id: Identifier::from([9; 32]), - } - } - - #[test] - fn candidate_choice_uses_name_and_short_identifier() { - let candidate = Identifier::from([7; 32]); - let label = choice_label( - Some(ResourceVoteChoice::TowardsIdentity(candidate)), - &[contestant(candidate, "dominguez")], - ); - - assert!(label.starts_with("dominguez (")); - assert!(label.contains('…')); - assert!(!label.contains(&candidate.to_string(Encoding::Base58))); - } - - #[test] - fn current_summary_keeps_healthy_targets_usable() { - let states = [ - ( - Identifier::from([1; 32]), - DpnsCurrentVoteState::Available(None), - false, - ), - ( - Identifier::from([2; 32]), - DpnsCurrentVoteState::Unavailable, - false, - ), - ( - Identifier::from([3; 32]), - DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)), - false, - ), - ]; - - assert_eq!( - current_summary(&states), - "Current across selected nodes: 1 not voted, 1 already voted, 1 unavailable" - ); - } - - #[test] - fn scheduled_time_is_absolute_and_relative() { - let timestamp = (Utc::now() + Duration::hours(2)).timestamp_millis() as u64; - let label = format_timing(VoteTiming::Scheduled(timestamp)); - - assert!(label.starts_with("When: 20")); - assert!(label.contains(" UTC (")); - } - - #[test] - fn only_the_exact_scheduled_edit_target_can_be_replaced() { - let edited = DpnsVoteTargetKey { - network: dash_sdk::dpp::dashcore::Network::Testnet, - voter_id: Identifier::from([1; 32]), - vote_poll_id: Identifier::from([2; 32]), - }; - let other = DpnsVoteTargetKey { - vote_poll_id: Identifier::from([3; 32]), - ..edited.clone() - }; - - assert!(is_explicit_schedule_replacement( - Some(&edited), - &edited, - Some(DpnsVoteTargetStatus::Scheduled), - VoteTiming::Scheduled(10), - )); - assert!(!is_explicit_schedule_replacement( - None, - &edited, - Some(DpnsVoteTargetStatus::Scheduled), - VoteTiming::Scheduled(10), - )); - assert!(!is_explicit_schedule_replacement( - Some(&edited), - &other, - Some(DpnsVoteTargetStatus::Scheduled), - VoteTiming::Scheduled(10), - )); - } - - #[test] - fn scheduled_edit_review_names_the_old_and_new_schedule() { - let original = DpnsVoteTarget { - key: DpnsVoteTargetKey { - network: dash_sdk::dpp::dashcore::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::Scheduled(1_700_000_000_000), - }; - let mut replacement = original.clone(); - replacement.requested_choice = ResourceVoteChoice::Abstain; - replacement.timing = VoteTiming::Scheduled(1_700_003_600_000); - - let summary = scheduled_replacement_summary(&original, &replacement, |_, choice| { - choice_label(choice, &[]) - }); - - assert!(summary.contains("Lock at ")); - assert!(summary.contains("β†’ Abstain at ")); - } - - #[test] - fn matching_pre_journal_error_returns_the_composer_to_review() { - let operation_id = DpnsVoteOperationId::from_bytes([4; 16]); - let context = BackendTaskContext::DpnsVoteOperation { - network: dash_sdk::dpp::dashcore::Network::Testnet, - operation_id, - }; - - assert!(should_return_to_review_after_error( - operation_id, - dash_sdk::dpp::dashcore::Network::Testnet, - &context, - false, - )); - assert!(!should_return_to_review_after_error( - operation_id, - dash_sdk::dpp::dashcore::Network::Testnet, - &context, - true, - )); - assert!(!should_return_to_review_after_error( - operation_id, - dash_sdk::dpp::dashcore::Network::Mainnet, - &context, - false, - )); - } - - #[test] - fn schedule_replacement_tracks_the_authoritative_operation_id() { - let submitted = DpnsVoteOperationId::from_bytes([4; 16]); - let stored = DpnsVoteOperationId::from_bytes([5; 16]); - let context = BackendTaskContext::DpnsVoteOperation { - network: dash_sdk::dpp::dashcore::Network::Testnet, - operation_id: submitted, - }; - let result = crate::backend_task::BackendTaskSuccessResult::DpnsVoteOperationUpdated { - network: dash_sdk::dpp::dashcore::Network::Testnet, - operation_id: stored, - }; - - assert_eq!( - updated_submitted_operation(Some(submitted), &context, &result), - Some(stored) - ); - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn refreshed_contests_replace_the_voting_center_snapshot() { - let (context, _temp_dir) = offline_ctx().await; - let mut center = DpnsVotingCenter::new(&context, None, Vec::new()); - assert!(center.contests.is_empty()); - context - .insert_name_contests_as_normalized_names(vec!["dominguez".to_owned()]) - .expect("seed refreshed contest"); - center.vote_state_refresh_dispatched = true; - - center.display_backend_task_result( - &BackendTaskContext::Other, - &BackendTaskSuccessResult::RefreshedDpnsContests, - ); - - assert_eq!(center.contests.len(), 1); - assert_eq!(center.contests[0].normalized_contested_name, "dominguez"); - assert!(!center.vote_state_refresh_dispatched); - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn empty_votes_step_offers_a_contest_refresh_action() { - let (context, _temp_dir) = offline_ctx().await; - let center = Rc::new(RefCell::new(DpnsVotingCenter::new( - &context, - None, - Vec::new(), - ))); - let dispatched = Rc::new(Cell::new(false)); - let center_for_ui = Rc::clone(¢er); - let dispatched_for_ui = Rc::clone(&dispatched); - let mut harness = Harness::builder() - .with_size(egui::vec2(700.0, 400.0)) - .build_ui(move |ui| { - if matches!( - center_for_ui.borrow_mut().render_votes(ui), - VotingCenterOutcome::Action(action) - if matches!( - *action, - AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::QueryDPNSContests - )) - ) - ) { - dispatched_for_ui.set(true); - } - }); - - harness.get_by_label("Refresh contests").click(); - harness.run(); - - assert!(dispatched.get()); - } -} diff --git a/src/ui/state/dpns_vote_state.rs b/src/ui/state/dpns_vote_state.rs new file mode 100644 index 000000000..ce0bbfc62 --- /dev/null +++ b/src/ui/state/dpns_vote_state.rs @@ -0,0 +1,79 @@ +//! 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>, + 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) + } + + pub fn refresh( + &mut self, + app_context: &AppContext, + voter_ids: &[Identifier], + vote_poll_ids: &[Identifier], + ) -> Result<(), TaskError> { + let mut states = BTreeMap::new(); + for voter_id in voter_ids { + states.extend( + app_context + .dpns_current_vote_states(*voter_id, vote_poll_ids.iter().copied())? + .into_iter() + .map(|(poll_id, state)| ((*voter_id, poll_id), state)), + ); + } + self.states = states; + self.loaded = true; + Ok(()) + } + + 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) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[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))]), + loaded: true, + }; + + for _ in 0..120 { + assert_eq!( + snapshot.state(voter, poll), + DpnsCurrentVoteState::Available(None) + ); + } + } +} diff --git a/src/ui/state/dpns_vote_workspace.rs b/src/ui/state/dpns_vote_workspace.rs deleted file mode 100644 index 827d07ab5..000000000 --- a/src/ui/state/dpns_vote_workspace.rs +++ /dev/null @@ -1,206 +0,0 @@ -//! Non-rendering state for the shared DPNS Voting Center composer. - -use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; -use dash_sdk::platform::Identifier; -use std::collections::{BTreeMap, BTreeSet}; - -/// Current step of the full-page voting composer. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum DpnsVoteComposerStep { - Nodes, - Votes, - Review, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ComposerKeyAction { - None, - Advance, - Submit, - CloseDraft, -} - -/// Per-node timing override in the draft. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum DraftVoteTiming { - Now, - Scheduled { days: u32, hours: u32, minutes: u32 }, -} - -/// Shared quick/bulk draft state; renders nothing. -#[derive(Debug, Clone)] -pub struct DpnsVoteWorkspace { - pub step: DpnsVoteComposerStep, - selected_nodes: BTreeSet, - pub node_timing: BTreeMap, - pub contest_choices: BTreeMap, - pub set_all_timing: DraftVoteTiming, -} - -impl DpnsVoteWorkspace { - pub fn new(node_ids: impl IntoIterator) -> Self { - Self { - step: DpnsVoteComposerStep::Nodes, - selected_nodes: BTreeSet::new(), - node_timing: node_ids - .into_iter() - .map(|node_id| (node_id, DraftVoteTiming::Now)) - .collect(), - contest_choices: BTreeMap::new(), - set_all_timing: DraftVoteTiming::Now, - } - } - - /// Restrict the initial draft to one node from a detail-page deep link. - pub fn prefilter_node(&mut self, selected: Identifier) { - self.selected_nodes.clear(); - if let Some(timing) = self.node_timing.get_mut(&selected) { - *timing = DraftVoteTiming::Now; - self.selected_nodes.insert(selected); - } - } - - pub fn selected_node_count(&self) -> usize { - self.selected_nodes.len() - } - - pub fn is_node_selected(&self, node_id: &Identifier) -> bool { - self.selected_nodes.contains(node_id) - } - - pub fn set_node_selected(&mut self, node_id: Identifier, selected: bool) { - if selected { - if self.node_timing.contains_key(&node_id) { - self.selected_nodes.insert(node_id); - } - } else { - self.selected_nodes.remove(&node_id); - } - } - - pub fn apply_timing_to_selected(&mut self) { - for node_id in &self.selected_nodes { - if let Some(timing) = self.node_timing.get_mut(node_id) { - *timing = self.set_all_timing; - } - } - } - - /// Resolve keyboard intent without letting Enter submit before Review. - pub fn keyboard_action( - &self, - enter_pressed: bool, - escape_pressed: bool, - can_continue: bool, - ) -> ComposerKeyAction { - if escape_pressed { - return ComposerKeyAction::CloseDraft; - } - if !enter_pressed || !can_continue { - return ComposerKeyAction::None; - } - match self.step { - DpnsVoteComposerStep::Nodes | DpnsVoteComposerStep::Votes => ComposerKeyAction::Advance, - DpnsVoteComposerStep::Review => ComposerKeyAction::Submit, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// VOTE-TC-021/022: set-all applies timing and an individual override survives. - #[test] - fn set_all_timing_allows_per_node_override() { - let first = Identifier::from([1; 32]); - let second = Identifier::from([2; 32]); - let mut workspace = DpnsVoteWorkspace::new([first, second]); - workspace.set_all_timing = DraftVoteTiming::Scheduled { - days: 1, - hours: 2, - minutes: 3, - }; - workspace.set_node_selected(first, true); - workspace.set_node_selected(second, true); - workspace.apply_timing_to_selected(); - workspace.node_timing.insert(first, DraftVoteTiming::Now); - - assert_eq!(workspace.node_timing[&first], DraftVoteTiming::Now); - assert!(matches!( - workspace.node_timing[&second], - DraftVoteTiming::Scheduled { .. } - )); - } - - /// VOTE-TC-024: a node-detail route selects only that node. - #[test] - fn node_prefilter_excludes_every_other_node() { - let selected = Identifier::from([1; 32]); - let other = Identifier::from([2; 32]); - let mut workspace = DpnsVoteWorkspace::new([selected, other]); - workspace.prefilter_node(selected); - - assert_eq!(workspace.selected_node_count(), 1); - assert_eq!(workspace.node_timing[&selected], DraftVoteTiming::Now); - assert!(!workspace.is_node_selected(&other)); - } - - /// VOTE-TC-020: an unfiltered bulk draft starts with no nodes selected. - #[test] - fn bulk_draft_starts_without_selected_nodes() { - let first = Identifier::from([1; 32]); - let second = Identifier::from([2; 32]); - let workspace = DpnsVoteWorkspace::new([first, second]); - - assert_eq!(workspace.selected_node_count(), 0); - assert!(!workspace.is_node_selected(&first)); - assert!(!workspace.is_node_selected(&second)); - } - - /// VOTE-TC-021: set-all changes timing only for explicitly selected nodes. - #[test] - fn set_all_timing_ignores_unselected_nodes() { - let selected = Identifier::from([1; 32]); - let unselected = Identifier::from([2; 32]); - let mut workspace = DpnsVoteWorkspace::new([selected, unselected]); - workspace.set_node_selected(selected, true); - workspace.set_all_timing = DraftVoteTiming::Scheduled { - days: 1, - hours: 2, - minutes: 3, - }; - - workspace.apply_timing_to_selected(); - - assert!(matches!( - workspace.node_timing[&selected], - DraftVoteTiming::Scheduled { .. } - )); - assert_eq!(workspace.node_timing[&unselected], DraftVoteTiming::Now); - } - - /// VOTE-TC-071: Enter advances drafts but submits only from Review; Escape closes drafts. - #[test] - fn keyboard_actions_respect_composer_step() { - let mut workspace = DpnsVoteWorkspace::new([Identifier::from([1; 32])]); - assert_eq!( - workspace.keyboard_action(true, false, true), - ComposerKeyAction::Advance - ); - workspace.step = DpnsVoteComposerStep::Votes; - assert_eq!( - workspace.keyboard_action(true, false, true), - ComposerKeyAction::Advance - ); - workspace.step = DpnsVoteComposerStep::Review; - assert_eq!( - workspace.keyboard_action(true, false, true), - ComposerKeyAction::Submit - ); - assert_eq!( - workspace.keyboard_action(false, true, true), - ComposerKeyAction::CloseDraft - ); - } -} diff --git a/src/ui/state/mod.rs b/src/ui/state/mod.rs index 31926333e..b744f286f 100644 --- a/src/ui/state/mod.rs +++ b/src/ui/state/mod.rs @@ -9,7 +9,7 @@ pub mod account_summary; pub mod avatar_cache; pub mod contacts_view; pub mod dpns_vote_operations; -pub mod dpns_vote_workspace; +pub mod dpns_vote_state; pub mod global_nav; pub mod hub_selection; pub mod masternodes_view; diff --git a/tests/kittest/masternode_tab.rs b/tests/kittest/masternode_tab.rs index 8a156a611..861aab3be 100644 --- a/tests/kittest/masternode_tab.rs +++ b/tests/kittest/masternode_tab.rs @@ -308,10 +308,10 @@ fn empty_state_renders_canonical_copy() { }); } -/// VOTE-TC-023: operator navigation exposes Nodes, Voting, and Scheduled and -/// opens the shared full-page composer. +/// The Masternodes root contains only its list and detail flow. DPNS owns all +/// voting and scheduled-vote navigation. #[test] -fn voting_navigation_routes_to_shared_workspaces() { +fn masternodes_has_no_operator_voting_subnavigation() { with_isolated_data_dir(|| { let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime"); let _guard = rt.enter(); @@ -320,44 +320,16 @@ fn voting_navigation_routes_to_shared_workspaces() { let app_context = harness.state().current_app_context().clone(); activate_masternodes_tab(&mut harness, &app_context); - assert!(harness.query_by_label("Nodes").is_some()); - assert!(harness.query_by_label("Voting").is_some()); - assert!(harness.query_by_label("Scheduled").is_some()); - - harness.get_by_label("Voting").click(); - harness.run_steps(3); - assert_eq!( - harness.state().selected_main_screen, - RootScreenType::RootScreenMasternodes - ); - assert!( - harness - .query_by_label("Step 1 of 3: Nodes and timing") - .is_some() - ); - assert!( - harness - .query_by_label("No voting nodes are available") - .is_some(), - "an empty voting workspace must explain why voting cannot start" - ); - assert!( - harness.query_by_label("Go to Nodes").is_some(), - "an empty voting workspace must offer a direct recovery action" - ); - harness.get_by_label("Go to Nodes").click(); - harness.run_steps(2); - assert!( - harness.query_by_label("No masternodes loaded").is_some(), - "the empty-workspace recovery action must return to the Nodes tab" - ); + assert!(harness.query_by_label("Nodes").is_none()); + assert!(harness.query_by_label("Voting").is_none()); + assert!(harness.query_by_label("Scheduled").is_none()); + assert!(harness.query_by_label("No masternodes loaded").is_some()); }); } -/// VOTE-TC-023/075: the retired DPNS scheduled surface redirects to the shared -/// Masternodes scheduled view instead of exposing a second submit path. +/// Scheduled votes remain a DPNS subscreen. #[test] -fn legacy_dpns_scheduled_route_opens_masternodes_scheduled_view() { +fn dpns_scheduled_route_stays_in_dpns() { with_isolated_data_dir(|| { let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime"); let _guard = rt.enter(); @@ -367,9 +339,9 @@ fn legacy_dpns_scheduled_route_opens_masternodes_scheduled_view() { assert_eq!( harness.state().selected_main_screen, - RootScreenType::RootScreenMasternodes + RootScreenType::RootScreenDPNSScheduledVotes ); - assert!(harness.query_by_label("Scheduled votes").is_some()); + assert!(harness.query_by_label("No scheduled votes.").is_some()); }); } @@ -610,13 +582,10 @@ 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). +/// The detail screen has one plain route to DPNS voting and no inline voting +/// controls or node-prefilter state. #[test] -fn dpns_section_missing_voter_scoped_prompt() { +fn detail_dpns_voting_button_opens_active_contests() { with_isolated_data_dir(|| { let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime"); let _guard = rt.enter(); @@ -628,42 +597,22 @@ fn dpns_section_missing_voter_scoped_prompt() { 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("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("DPNS Voting").is_some()); 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" - ); - assert!( - harness.query_by_label("Add voting key").is_some(), - "missing-voter state must offer an Add voting key action" + .query_by_label_contains("DPNS name contests to vote on") + .is_none() ); + assert!(harness.query_by_label("Add voting key").is_none()); + assert!(harness.query_by_label_contains("Review ").is_none()); - // 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("DPNS Voting").click(); harness.run_steps(3); - assert!( - harness.query_by_label("Save").is_some(), - "scoped voter-key prompt must open with a Save action" - ); - assert!( - harness.query_by_label("ProTxHash").is_none(), - "the scoped prompt must not be FR-4's load form (no ProTxHash re-entry)" + assert_eq!( + harness.state().selected_main_screen, + RootScreenType::RootScreenDPNSActiveContests ); + assert!(harness.query_by_label("Active contests").is_some()); }); } From 4d0457098a73cc412fb67019885f831f80b7d96f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 21 Jul 2026 10:39:35 +0000 Subject: [PATCH 024/194] docs: update changelog for DPNS voting redesign Masternode detail no longer casts votes inline; voting now lives on the redesigned DPNS Active contests screen (cards, batch, scheduling). Co-Authored-By: Claude Sonnet 5 --- CHANGELOG.md | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4de229b17..ba45ad3b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,15 +24,24 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). 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. + opening a card shows a detail view with Withdraw / Top up / Transfer + actions, key management, a "DPNS Voting" button that opens the DPNS Active + contests screen, 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. + +- **DPNS voting redesigned around the Active contests screen**: casting, + batching, and scheduling DPNS name-contest votes across your masternodes + now happens in one place β€” DPNS β†’ Active contests. Contests are grouped + into Needs your vote / Voted / Not votable by your nodes, with a Review + and cast step for casting now or scheduling later, and your remaining + vote changes shown up front (Platform allows four per contest). The + Masternodes detail screen no longer casts votes inline β€” its "DPNS + Voting" button takes you straight to Active contests instead. - **Wallet/identity indicator on more screens (rollout in progress)**: the wallet and identity picker previously shown only at the top of the Identity From c7e6ac41244d8da968fa74ca686abf5c4383ad71 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 21 Jul 2026 12:04:01 +0000 Subject: [PATCH 025/194] fix(dpns): restore Scheduled-votes nav and rebuild Review-and-cast sheet - Add Scheduled votes as a persistent 4th DPNS nav tab; it was previously reachable only via a one-shot post-schedule-action link. - Rebuild the Review and cast sheet: candidate names instead of raw Base58 IDs, a Cast now / Schedule for later segmented control instead of the legacy per-identity ComboBox, actionable "Open Masternodes" guidance instead of the stale Identities-screen instruction, and a future-time validation warning for scheduling. - Add the Active-contests summary strip and port homograph-safe filter normalization + explanatory tooltip to the Active-contests filter. Co-Authored-By: Claude Sonnet 5 --- .../dpns_subscreen_chooser_panel.rs | 4 + src/ui/dpns/dpns_contested_names_screen.rs | 475 ++++++++++-------- tests/kittest/masternode_tab.rs | 9 +- 3 files changed, 283 insertions(+), 205 deletions(-) diff --git a/src/ui/components/dpns_subscreen_chooser_panel.rs b/src/ui/components/dpns_subscreen_chooser_panel.rs index c51291031..38fe91295 100644 --- a/src/ui/components/dpns_subscreen_chooser_panel.rs +++ b/src/ui/components/dpns_subscreen_chooser_panel.rs @@ -29,6 +29,10 @@ pub fn add_dpns_subscreen_chooser_panel(ui: &mut Ui, app_context: &AppContext) - DPNSSubscreen::Owned, RootScreenType::RootScreenDPNSOwnedNames, ), + ( + DPNSSubscreen::ScheduledVotes, + RootScreenType::RootScreenDPNSScheduledVotes, + ), ] .into_iter() .map(|(subscreen, target)| { diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 1da314bdd..fc915fb7d 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -2,7 +2,7 @@ use crate::wallet_backend::poison::MutexRecover; use std::sync::{Arc, Mutex}; use tracing::error; -use chrono::{DateTime, LocalResult, TimeZone, Utc}; +use chrono::{DateTime, LocalResult, NaiveDate, NaiveTime, TimeZone, Timelike, Utc}; use chrono_humanize::HumanTime; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::platform_value::string_encoding::Encoding; @@ -18,6 +18,7 @@ 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::dpns::normalize_dpns_label; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, @@ -54,6 +55,22 @@ enum ActiveContestGroup { NotVotable, } +const NO_VOTING_NODES_MESSAGE: &str = "No voting-enabled masternodes are loaded. Open the Masternodes tab, load a masternode with its voting key, then try again."; + +fn candidate_choice_label(candidate_name: &str) -> String { + format!("Vote for {candidate_name}") +} + +fn review_vote_choice_label(choice: ResourceVoteChoice, candidate_name: Option<&str>) -> String { + match choice { + ResourceVoteChoice::Lock => "Lock".to_owned(), + ResourceVoteChoice::Abstain => "Abstain".to_owned(), + ResourceVoteChoice::TowardsIdentity(_) => candidate_name + .map(candidate_choice_label) + .unwrap_or_else(|| "Vote for a candidate that is no longer listed.".to_owned()), + } +} + fn classify_vote_states( states: impl IntoIterator, ) -> ActiveContestGroup { @@ -224,6 +241,9 @@ pub struct DPNSScreen { bulk_identity_options: Vec, bulk_vote_handling_status: VoteHandlingStatus, set_all_option: VoteOption, + simple_schedule_date: String, + simple_schedule_hour: u32, + simple_schedule_minute: u32, } impl DPNSScreen { @@ -288,6 +308,7 @@ impl DPNSScreen { // Initialize vote handling pop-up state to hidden let identity_count = voting_identities.len(); let bulk_identity_options = vec![VoteOption::CastNow; identity_count]; + let default_schedule_time = Utc::now() + chrono::Duration::days(1); Self { voting_identities, @@ -319,6 +340,9 @@ impl DPNSScreen { bulk_identity_options, bulk_vote_handling_status: VoteHandlingStatus::NotStarted, set_all_option: VoteOption::CastNow, + simple_schedule_date: default_schedule_time.format("%Y-%m-%d").to_string(), + simple_schedule_hour: default_schedule_time.hour(), + simple_schedule_minute: default_schedule_time.minute(), } } @@ -445,7 +469,10 @@ impl DPNSScreen { let dark_mode = ui.style().visuals.dark_mode; ui.horizontal(|ui| { ui.label(RichText::new("Filter by name:").color(DashColors::text_primary(dark_mode))); - ui.text_edit_singleline(&mut self.active_filter_term); + ui.text_edit_singleline(&mut self.active_filter_term) + .on_hover_text( + "The letters i and l match the digit 1, and the letter o matches 0.", + ); }); ui.label( RichText::new("Each node can change its vote up to four times after its initial vote.") @@ -453,18 +480,11 @@ impl DPNSScreen { ); ui.add_space(8.0); - let filter = self.active_filter_term.to_lowercase(); + let filter = normalize_dpns_label(&self.active_filter_term); let contests = self .contested_names .lock_recover() .iter() - .filter(|contest| { - filter.is_empty() - || contest - .normalized_contested_name - .to_lowercase() - .contains(&filter) - }) .cloned() .collect::>(); let mut groups = [Vec::new(), Vec::new(), Vec::new()]; @@ -477,6 +497,35 @@ impl DPNSScreen { groups[index].push(contest); } + let closes_within_day = groups[0] + .iter() + .filter(|contest| { + contest.end_time.is_some_and(|end_time| { + let remaining = end_time as i64 - Utc::now().timestamp_millis(); + remaining > 0 && remaining <= chrono::Duration::days(1).num_milliseconds() + }) + }) + .count(); + egui::Frame::group(ui.style()).show(ui, |ui| { + ui.label(format!( + "Names still available to your nodes: {available}. Names closing within 24 hours: {closing}.", + available = groups[0].len(), + closing = closes_within_day, + )); + }); + ui.add_space(8.0); + + if !filter.is_empty() { + for group in &mut groups { + group.retain(|contest| { + contest + .normalized_contested_name + .to_lowercase() + .contains(&filter) + }); + } + } + egui::ScrollArea::vertical() .id_salt("active_contest_cards") .show(ui, |ui| { @@ -634,7 +683,7 @@ impl DPNSScreen { let clicked = ui .selectable_label( selected == Some(choice), - format!("Vote for {}", contestant.name), + candidate_choice_label(&contestant.name), ) .clicked(); tally_chip(ui, contestant.votes, dark_mode); @@ -794,31 +843,20 @@ impl DPNSScreen { 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( + "The letters i and l match the digit 1, and the letter o matches 0.", + ); }); 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(); + let filter = normalize_dpns_label(&self.past_filter_term); - cn.retain(|c| { - c.normalized_contested_name - .to_lowercase() - .contains(&filter_lc) - }); + cn.retain(|c| c.normalized_contested_name.to_lowercase().contains(&filter)); } self.sort_contested_names(&mut cn); cn @@ -1377,170 +1415,172 @@ impl DPNSScreen { action } - fn show_bulk_schedule_popup_window(&mut self, ui: &mut Ui) -> AppAction { + fn simple_schedule_option(&self) -> Option { + let date = NaiveDate::parse_from_str(&self.simple_schedule_date, "%Y-%m-%d").ok()?; + let time = + NaiveTime::from_hms_opt(self.simple_schedule_hour, self.simple_schedule_minute, 0)?; + let scheduled_at = DateTime::::from_naive_utc_and_offset(date.and_time(time), Utc); + let seconds = scheduled_at.signed_duration_since(Utc::now()).num_seconds(); + if seconds <= 0 { + return None; + } + let total_minutes = u32::try_from((seconds + 59) / 60).ok()?; + Some(VoteOption::Scheduled { + days: total_minutes / (24 * 60), + hours: total_minutes / 60 % 24, + minutes: total_minutes % 60, + }) + } + + fn apply_all_nodes_option(&mut self, option: VoteOption) { + self.set_all_option = option.clone(); + self.bulk_identity_options.fill(option); + } + + fn review_candidate_name(&self, vote: &SelectedVote) -> Option { + let ResourceVoteChoice::TowardsIdentity(candidate_id) = vote.vote_choice else { + return None; + }; + self.contested_names + .lock_recover() + .iter() + .find(|contest| contest.normalized_contested_name == vote.contested_name) + .and_then(|contest| contest.contestants.as_ref()) + .and_then(|contestants| { + contestants + .iter() + .find(|candidate| candidate.id == candidate_id) + }) + .map(|candidate| candidate.name.clone()) + } + + fn show_review_and_cast_window(&mut self, ui: &mut Ui) -> AppAction { let mut action = AppAction::None; let dark_mode = ui.style().visuals.dark_mode; - ui.heading( - RichText::new("Review selected votes").color(DashColors::text_primary(dark_mode)), - ); - 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 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.colored_label( + DashColors::warning_color(dark_mode), + NO_VOTING_NODES_MESSAGE, + ); 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; - } + ui.horizontal(|ui| { + if ComponentStyles::add_primary_button(ui, "Open Masternodes").clicked() { + action = AppAction::SetMainScreen(RootScreenType::RootScreenMasternodes); + self.show_bulk_schedule_popup = false; + } + if ComponentStyles::add_secondary_button(ui, "Close", dark_mode).clicked() { + self.show_bulk_schedule_popup = 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.colored_label( + DashColors::warning_color(dark_mode), + "No votes are ready to review. Choose at least one vote on Active contests, then try again.", + ); ui.add_space(10.0); - let dark_mode = ui.style().visuals.dark_mode; - if ComponentStyles::add_secondary_button(ui, "Close", dark_mode).clicked() { + if ComponentStyles::add_secondary_button(ui, "Back to Active contests", dark_mode) + .clicked() + { self.show_bulk_schedule_popup = false; } return action; } + let mut simple_schedule_valid = true; 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)), - ); + ui.label(format!( + "Casting on behalf of all my nodes ({count}).", + count = self.voting_identities.len() + )); + ui.separator(); + ui.heading(format!("Votes to cast ({}):", self.selected_votes.len())); + for vote in &self.selected_votes { + let candidate_name = self.review_candidate_name(vote); + let choice = review_vote_choice_label(vote.vote_choice, candidate_name.as_deref()); + ui.label(format!("β€’ {name}.dash β†’ {choice}", name = vote.contested_name)); + } + ui.separator(); + ui.horizontal(|ui| { + ui.label("When:"); + if ui + .selectable_label( + matches!(self.set_all_option, VoteOption::CastNow), + "Cast now", + ) + .clicked() + { + self.apply_all_nodes_option(VoteOption::CastNow); + } + if ui + .selectable_label( + matches!(self.set_all_option, VoteOption::Scheduled { .. }), + "Schedule for later", + ) + .clicked() + && let Some(option) = self.simple_schedule_option() + { + self.apply_all_nodes_option(option); } }); - ui.add_space(10.0); - - // Show each identity + let user pick None / Immediate / Scheduled - let dark_mode = ui.style().visuals.dark_mode; - ui.heading(RichText::new("All my nodes").color(DashColors::text_primary(dark_mode))); - ui.add_space(10.0); - ui.group(|ui| { + if matches!(self.set_all_option, VoteOption::Scheduled { .. }) { + let mut schedule_changed = false; ui.horizontal(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - ui.label( - RichText::new("Cast timing:").color(DashColors::text_primary(dark_mode)), + ui.label("Cast on (UTC):"); + schedule_changed |= ui + .add( + egui::TextEdit::singleline(&mut self.simple_schedule_date) + .desired_width(100.0) + .hint_text("YYYY-MM-DD"), + ) + .changed(); + ui.label("at"); + schedule_changed |= ui + .add( + egui::DragValue::new(&mut self.simple_schedule_hour) + .prefix("Hour: ") + .range(0..=23), + ) + .changed(); + schedule_changed |= ui + .add( + egui::DragValue::new(&mut self.simple_schedule_minute) + .prefix("Minute: ") + .range(0..=59), + ) + .changed(); + }); + simple_schedule_valid = self.simple_schedule_option().is_some(); + if schedule_changed + && let Some(option) = self.simple_schedule_option() + { + self.apply_all_nodes_option(option); + } + if !simple_schedule_valid { + ui.colored_label( + DashColors::warning_color(dark_mode), + "Choose a future date and time before scheduling these votes.", ); + } + ui.colored_label( + DashColors::warning_color(dark_mode), + "Keep Dash Evo Tool running and connected until then, or the scheduled votes will not be cast.", + ); + } - // 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 => "Do not use these nodes".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), - "Do not use these nodes", - ) - .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 dark_mode = ui.style().visuals.dark_mode; - ui.label( - RichText::new("Schedule after:") - .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 nodes").clicked() { - for option in &mut self.bulk_identity_options { - *option = self.set_all_option.clone(); - } - } - }); - }); + ui.separator(); ui.add_space(10.0); egui::CollapsingHeader::new("Choose per node (advanced)") .default_open(false) @@ -1557,18 +1597,9 @@ impl DPNSScreen { .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]; + vec![VoteOption::CastNow; self.voting_identities.len()]; } let current_option = &mut self.bulk_identity_options[i]; @@ -1652,12 +1683,16 @@ impl DPNSScreen { }); }); // If any selected votes are scheduled, show a warning - if self - .bulk_identity_options - .iter() - .any(|o| matches!(o, VoteOption::Scheduled { .. })) + if !matches!(self.set_all_option, VoteOption::Scheduled { .. }) + && self + .bulk_identity_options + .iter() + .any(|option| matches!(option, 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.colored_label( + DashColors::warning_color(ui.style().visuals.dark_mode), + "Keep Dash Evo Tool running and connected until then, or the scheduled votes will not be cast.", + ); ui.add_space(10.0); } @@ -1671,19 +1706,47 @@ impl DPNSScreen { ui.label("Submitting votes…"); }); } - // "Apply Votes" button - if ComponentStyles::add_primary_button_enabled( - ui, - !operation_in_progress, - if operation_in_progress { - "Submitting votes…" - } else { - "Submit votes" - }, - ) - .disabled_tooltip("The selected votes are already being submitted.") - .clicked() - { + let has_immediate = self + .bulk_identity_options + .iter() + .any(|option| matches!(option, VoteOption::CastNow)); + let has_scheduled = self + .bulk_identity_options + .iter() + .any(|option| matches!(option, VoteOption::Scheduled { .. })); + let submit_label = match (has_immediate, has_scheduled) { + (true, false) => "Cast votes", + (false, true) => "Schedule votes", + _ => "Submit votes", + }; + let (submit_clicked, cancel_clicked) = ui + .with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let submit_clicked = ComponentStyles::add_primary_button_enabled( + ui, + !operation_in_progress && simple_schedule_valid, + if operation_in_progress { + "Submitting votes…" + } else { + submit_label + }, + ) + .disabled_tooltip(if operation_in_progress { + "The selected votes are already being submitted." + } else { + "Choose a future date and time before scheduling these votes." + }) + .clicked(); + let cancel_clicked = ui + .add_enabled( + !operation_in_progress, + ComponentStyles::secondary_button("Cancel", dark_mode), + ) + .disabled_tooltip("Submitted votes cannot be cancelled.") + .clicked(); + (submit_clicked, cancel_clicked) + }) + .inner; + if submit_clicked { action = self.bulk_apply_votes(); if matches!( self.bulk_vote_handling_status, @@ -1696,16 +1759,7 @@ impl DPNSScreen { } } - ui.add_space(5.0); - let dark_mode = ui.style().visuals.dark_mode; - if ui - .add_enabled( - !operation_in_progress, - ComponentStyles::secondary_button("Cancel", dark_mode), - ) - .disabled_tooltip("Submitted votes cannot be cancelled.") - .clicked() - { + if cancel_clicked { self.selected_votes.clear(); self.show_bulk_schedule_popup = false; self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; @@ -1737,7 +1791,6 @@ impl DPNSScreen { action } - /// The logic that was in BulkScheduleVoteScreen::schedule_votes fn bulk_apply_votes(&mut self) -> AppAction { let mut targets = Vec::new(); let mut selected_voters = Vec::new(); @@ -2221,7 +2274,7 @@ impl ScreenLike for DPNSScreen { .resizable(true) .vscroll(true) .show(ui.ctx(), |ui| { - inner_action |= self.show_bulk_schedule_popup_window(ui); + inner_action |= self.show_review_and_cast_window(ui); }); } @@ -2412,6 +2465,24 @@ mod tests { )); } + #[test] + fn review_choice_uses_the_candidate_name_instead_of_its_identifier() { + let candidate_id = Identifier::from([42; 32]); + let label = review_vote_choice_label( + ResourceVoteChoice::TowardsIdentity(candidate_id), + Some("alice"), + ); + + assert_eq!(label, "Vote for alice"); + assert!(!label.contains(&candidate_id.to_string(Encoding::Base58))); + } + + #[test] + fn missing_voting_nodes_copy_points_to_the_masternodes_tab() { + assert!(NO_VOTING_NODES_MESSAGE.contains("Masternodes tab")); + assert!(!NO_VOTING_NODES_MESSAGE.contains("Identities screen")); + } + #[test] fn scheduled_vote_sweep_error_is_handled_after_cleanup() { let (ctx, _temp_dir) = offline_ctx(); diff --git a/tests/kittest/masternode_tab.rs b/tests/kittest/masternode_tab.rs index 861aab3be..1ce4e67fa 100644 --- a/tests/kittest/masternode_tab.rs +++ b/tests/kittest/masternode_tab.rs @@ -327,16 +327,19 @@ fn masternodes_has_no_operator_voting_subnavigation() { }); } -/// Scheduled votes remain a DPNS subscreen. +/// Scheduled votes remain reachable from the persistent DPNS subscreen bar. #[test] -fn dpns_scheduled_route_stays_in_dpns() { +fn dpns_scheduled_votes_tab_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::RootScreenDPNSScheduledVotes); + let mut harness = mount_app(RootScreenType::RootScreenDPNSActiveContests); harness.run_steps(5); + harness.get_by_label("Scheduled votes").click(); + harness.run_steps(3); + assert_eq!( harness.state().selected_main_screen, RootScreenType::RootScreenDPNSScheduledVotes From cf61d47503e4936878368d3ae9fd3522496e3813 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 21 Jul 2026 12:49:28 +0000 Subject: [PATCH 026/194] fix(dpns): address active voting review gaps --- CHANGELOG.md | 4 +- .../03-test-case-spec.md | 4 +- docs/user-stories.md | 29 ++- src/ui/dpns/dpns_contested_names_screen.rs | 228 +++++++++++++++--- tests/kittest/masternode_tab.rs | 41 +++- 5 files changed, 257 insertions(+), 49 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ba45ad3b6..0e829af3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,8 +38,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). batching, and scheduling DPNS name-contest votes across your masternodes now happens in one place β€” DPNS β†’ Active contests. Contests are grouped into Needs your vote / Voted / Not votable by your nodes, with a Review - and cast step for casting now or scheduling later, and your remaining - vote changes shown up front (Platform allows four per contest). The + and cast step for casting now or scheduling later, plus a reminder that + Platform allows up to four changes after the initial vote. The Masternodes detail screen no longer casts votes inline β€” its "DPNS Voting" button takes you straight to Active contests instead. 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 index ae6235c2f..3c012dab3 100644 --- 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 @@ -5,7 +5,7 @@ | ID | Description | Preconditions | Steps | Expected outcome | Requirements | |---|---|---|---|---|---| | VOTE-TC-001 | Current vote loads from Platform | Node has a proved Lock vote | Refresh Voting | Row shows `Current vote: Lock` | FR-010, FR-011 | -| VOTE-TC-002 | Existing vote remains visible | Node already voted; contest active | Open Active contests | Contest appears in Voted and change controls are available | FR-012 | +| VOTE-TC-002 | Existing vote remains visible | Node already voted; contest active | Open Active contests | Contest appears in Voted, its proved choice is highlighted, `You voted: {choice}` is visible, and change controls are available | FR-012 | | VOTE-TC-003 | Current choice is a no-op | Current vote is Lock | Select Lock and review | Target is removed; nothing can be submitted | FR-013, FR-025 | | VOTE-TC-004 | Coherent refresh | Contest tally and current vote both changed | Refresh | One snapshot shows both new values | FR-014 | | VOTE-TC-005 | Vote query is per node | One node, 100 contests | Refresh | Identity-votes query runs once for the node, not 100 times | NFR-007 | @@ -20,7 +20,7 @@ | VOTE-TC-010 | Single vote | Active contests, one draft choice | Review and submit | One target is created per selected loaded node for that contest | FR-020, FR-024 | | VOTE-TC-011 | Multi-contest vote | Active contests, three draft choices | Review | Review shows the exact node Γ— contest targets | FR-020, FR-031 | | VOTE-TC-012 | Schedule one choice | Active contests, one draft | Choose Schedule in review | Targets appear in Scheduled with the chosen time | FR-023, FR-050 | -| VOTE-TC-013 | Missing voting key | No loaded node can vote | Open Active contests | Contest appears under Not votable and submit is unavailable | FR-003 | +| VOTE-TC-013 | Missing voting key | No loaded node has a voting key | Open Active contests | An actionable state explains that a voting key is missing, offers `Load a masternode`, and leaves submit unavailable | FR-003 | ## Bulk voting diff --git a/docs/user-stories.md b/docs/user-stories.md index c81b190ee..e81b420cb 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -685,10 +685,11 @@ As a power user, I want to review past DPNS contests so that I can see outcomes As a masternode operator, I want to vote on contested DPNS name registrations so that I can participate in network governance. - See the node's proved current choice before casting, changing, or abstaining. +- Active contests groups cards into Needs your vote, Voted, and Not votable by your nodes; a staged choice takes precedence over the proved highlight until submission. - A node may vote five times in total per contest: the initial vote plus up to four changes. - Choosing the current choice submits nothing. - Evonode/masternode identity required. -- The vote limit is enforced by Platform; DET does not invent a remaining-change count. +- The Active-contests screen explains the four-change limit without inventing a remaining-change count; Platform enforces the limit. ### DPN-006: Schedule votes [Implemented] **Persona:** Priya @@ -696,8 +697,7 @@ As a masternode operator, I want to vote on contested DPNS name registrations so As a masternode operator, I want to schedule votes for later execution so that I can plan my voting strategy in advance. - Set vote to be cast at a future time. -- View and manage scheduled votes under Masternodes β†’ Scheduled; the former DPNS - scheduled-votes entry redirects to this shared operator view. +- View and manage scheduled votes under DPNS β†’ Scheduled votes, which remains available in the persistent DPNS subnavigation. - Scheduled and immediate votes share the same target locks and result states. - An ambiguous result remains visible for checking and is never automatically rebroadcast. @@ -706,9 +706,9 @@ As a masternode operator, I want to schedule votes for later execution so that I 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. -- "Set all" option for batch vote assignment. -- Nodes are selected explicitly; "Set all" changes timing only for selected nodes. -- Nodes without a loaded voting key remain visible but cannot be selected. +- Review and cast defaults to all loaded voting nodes and Cast now. +- The advanced per-node disclosure can set each node to Cast now, Schedule, or Do not use this node. +- When no loaded node has a voting key, Active contests shows an actionable Load a masternode state instead of vote controls. - Per-node timing overrides and multi-contest selections create exact node Γ— contest targets. - Immediate and scheduled targets submitted together belong to one operation. @@ -1515,13 +1515,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 and continue to DPNS voting, so that I can fulfil 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). -- Every active contest remains visible with the node's proved current vote, including contests where the node already voted. -- Votes (Abstain, Lock, or a candidate) use the shared durable voting operation path. -- The affected controls disable immediately and show progress until the target is confirmed, rejected, or remains under explicit checking. -- 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 and node actions. +- A single `DPNS Voting` button opens DPNS β†’ Active contests without carrying a node filter, draft, or other routing state. +- Voting takes place on Active contests through the shared durable voting-operation path. +- When no loaded node has a voting key, Active contests explains what is missing and offers a `Load a masternode` action. ### MN-004: Remove a masternode [Implemented] **Persona:** Priya @@ -1585,10 +1584,10 @@ 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 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 card-list toolbar 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. +- Refresh is a no-op when no node is loaded. DPNS Active contests owns its separate contest refresh action. ### MN-012: Switch wallet/identity from the Masternodes header [Implemented] **Persona:** Priya diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index fc915fb7d..43623aa1c 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -55,7 +55,8 @@ enum ActiveContestGroup { NotVotable, } -const NO_VOTING_NODES_MESSAGE: &str = "No voting-enabled masternodes are loaded. Open the Masternodes tab, load a masternode with its voting key, then try again."; +const NO_VOTING_NODES_MESSAGE: &str = "None of your loaded nodes has a voting key."; +const NO_VOTING_NODES_DETAIL: &str = "Load a masternode with its voting key to cast votes."; fn candidate_choice_label(candidate_name: &str) -> String { format!("Vote for {candidate_name}") @@ -104,14 +105,37 @@ fn short_identifier(identifier: Identifier) -> String { format!("{}…{}", &encoded[..6], &encoded[encoded.len() - 4..]) } -fn vote_choice_label(choice: ResourceVoteChoice) -> String { +fn vote_choice_label(choice: ResourceVoteChoice, candidate_name: Option<&str>) -> String { match choice { - ResourceVoteChoice::Lock => "Lock name".to_owned(), + ResourceVoteChoice::Lock => "Lock".to_owned(), ResourceVoteChoice::Abstain => "Abstain".to_owned(), - ResourceVoteChoice::TowardsIdentity(identifier) => { - format!("Vote for {}", short_identifier(identifier)) + ResourceVoteChoice::TowardsIdentity(identifier) => candidate_name + .map(candidate_choice_label) + .unwrap_or_else(|| format!("Vote for {}", short_identifier(identifier))), + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ProvedVoteSummary { + None, + Choice(ResourceVoteChoice), + Mixed, +} + +fn proved_vote_summary( + states: impl IntoIterator, +) -> ProvedVoteSummary { + let mut proved_choice = None; + for state in states { + let DpnsCurrentVoteState::Available(Some(choice)) = state else { + continue; + }; + if proved_choice.is_some_and(|current| current != choice) { + return ProvedVoteSummary::Mixed; } + proved_choice = Some(choice); } + proved_choice.map_or(ProvedVoteSummary::None, ProvedVoteSummary::Choice) } fn target_status_label(status: DpnsVoteTargetStatus) -> &'static str { @@ -253,7 +277,7 @@ impl DPNSScreen { 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(), + DPNSSubscreen::ScheduledVotes => app_context.all_contested_names().unwrap_or_default(), })); let local_dpns_names = Arc::new(Mutex::new(match dpns_subscreen { @@ -303,7 +327,10 @@ impl DPNSScreen { .map(|identity| identity.identity.id()) .collect::>(); let vote_state = DpnsVoteStateSnapshot::load(app_context, &voter_ids, &vote_poll_ids) - .unwrap_or_default(); + .unwrap_or_else(|error| { + tracing::warn!(?error, "Could not cache proved DPNS vote state"); + DpnsVoteStateSnapshot::default() + }); // Initialize vote handling pop-up state to hidden let identity_count = voting_identities.len(); @@ -382,6 +409,33 @@ impl DPNSScreen { // --------------------------- // Rendering: Empty states // --------------------------- + fn render_no_voting_nodes(&self, ui: &mut Ui) -> AppAction { + let mut action = AppAction::None; + let dark_mode = ui.style().visuals.dark_mode; + ui.vertical_centered(|ui| { + 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( + RichText::new(NO_VOTING_NODES_MESSAGE) + .strong() + .color(DashColors::warning_color(dark_mode)), + ); + ui.label( + RichText::new(NO_VOTING_NODES_DETAIL) + .color(DashColors::text_primary(dark_mode)), + ); + ui.add_space(12.0); + if ComponentStyles::add_primary_button(ui, "Load a masternode").clicked() { + action = AppAction::SetMainScreen(RootScreenType::RootScreenMasternodes); + } + }); + }); + }); + action + } + fn render_no_active_contests_or_owned_names(&mut self, ui: &mut Ui) -> AppAction { let mut app_action = AppAction::None; ui.vertical_centered(|ui| { @@ -529,14 +583,15 @@ impl DPNSScreen { egui::ScrollArea::vertical() .id_salt("active_contest_cards") .show(ui, |ui| { - self.render_contest_group(ui, "Needs your vote", &groups[0], true, true); - self.render_contest_group(ui, "Voted", &groups[1], false, true); + self.render_contest_group(ui, "Needs your vote", &groups[0], true, true, false); + self.render_contest_group(ui, "Voted", &groups[1], false, true, true); self.render_contest_group( ui, "Not votable by your nodes", &groups[2], false, false, + false, ); self.render_voting_activity(ui); }); @@ -581,6 +636,7 @@ impl DPNSScreen { contests: &[ContestedName], default_open: bool, voting_enabled: bool, + show_current_vote: bool, ) { egui::CollapsingHeader::new(format!("{title} ({})", contests.len())) .default_open(default_open) @@ -592,7 +648,7 @@ impl DPNSScreen { let contest_enabled = voting_enabled && self.contest_has_available_target(contest); ui.add_enabled_ui(contest_enabled, |ui| { - self.render_contest_card(ui, contest, contest_enabled); + self.render_contest_card(ui, contest, contest_enabled, show_current_vote); }); ui.add_space(8.0); } @@ -622,13 +678,57 @@ impl DPNSScreen { }) } - fn render_contest_card(&mut self, ui: &mut Ui, contest: &ContestedName, voting_enabled: bool) { + fn proved_vote_for_contest(&self, contest: &ContestedName) -> ProvedVoteSummary { + let Ok(poll_id) = self + .app_context + .dpns_vote_poll_id(&contest.normalized_contested_name) + else { + return ProvedVoteSummary::None; + }; + proved_vote_summary( + self.voting_identities + .iter() + .map(|identity| self.vote_state.state(identity.identity.id(), poll_id)), + ) + } + + fn candidate_name_in_contest( + contest: &ContestedName, + choice: ResourceVoteChoice, + ) -> Option<&str> { + let ResourceVoteChoice::TowardsIdentity(candidate_id) = choice else { + return None; + }; + contest + .contestants + .as_ref()? + .iter() + .find(|candidate| candidate.id == candidate_id) + .map(|candidate| candidate.name.as_str()) + } + + fn render_contest_card( + &mut self, + ui: &mut Ui, + contest: &ContestedName, + voting_enabled: bool, + show_current_vote: bool, + ) { let dark_mode = ui.style().visuals.dark_mode; - let selected = self + let staged = self .selected_votes .iter() .find(|vote| vote.contested_name == contest.normalized_contested_name) .map(|vote| vote.vote_choice); + let proved = if show_current_vote { + self.proved_vote_for_contest(contest) + } else { + ProvedVoteSummary::None + }; + let selected = staged.or(match proved { + ProvedVoteSummary::Choice(choice) => Some(choice), + ProvedVoteSummary::None | ProvedVoteSummary::Mixed => None, + }); let locked_votes = contest.locked_votes.unwrap_or_default(); let abstain_votes = contest.abstain_votes.unwrap_or_default(); @@ -655,6 +755,30 @@ impl DPNSScreen { }); ui.add_space(6.0); + match proved { + ProvedVoteSummary::Choice(choice) => { + let candidate_name = Self::candidate_name_in_contest(contest, choice); + ui.label( + RichText::new(format!( + "You voted: {}.", + vote_choice_label(choice, candidate_name) + )) + .strong() + .color(DashColors::text_primary(dark_mode)), + ); + ui.add_space(4.0); + } + ProvedVoteSummary::Mixed => { + ui.label( + RichText::new("Your loaded nodes have different current votes.") + .strong() + .color(DashColors::text_primary(dark_mode)), + ); + ui.add_space(4.0); + } + ProvedVoteSummary::None => {} + } + ui.horizontal_wrapped(|ui| { let clicked = ui .selectable_label(selected == Some(ResourceVoteChoice::Lock), "Lock name") @@ -756,7 +880,14 @@ impl DPNSScreen { ui.label(format!( "{}.dash β€” {} β€” {}", outcome.target.contested_name, - vote_choice_label(outcome.target.requested_choice), + vote_choice_label( + outcome.target.requested_choice, + self.candidate_name( + &outcome.target.contested_name, + outcome.target.requested_choice, + ) + .as_deref(), + ), target_status_label(outcome.status), )); if outcome.status == DpnsVoteTargetStatus::Unconfirmed @@ -1256,7 +1387,10 @@ impl DPNSScreen { }); // Choice row.col(|ui| { - let display_text = vote_choice_label(vote.0.choice); + let candidate_name = + self.candidate_name(&vote.0.contested_name, vote.0.choice); + let display_text = + vote_choice_label(vote.0.choice, candidate_name.as_deref()); ui.add(Label::new(display_text)); }); // Time @@ -1320,10 +1454,16 @@ impl DPNSScreen { ); } ScheduledVoteCastingStatus::Failed => { - ui.colored_label(Color32::DARK_RED, "Failed"); + ui.colored_label( + DashColors::error_color(dark_mode), + "Failed", + ); } ScheduledVoteCastingStatus::Completed => { - ui.colored_label(Color32::DARK_GREEN, "Casted"); + ui.colored_label( + DashColors::success_color(dark_mode), + "Cast", + ); } } }); @@ -1437,14 +1577,14 @@ impl DPNSScreen { self.bulk_identity_options.fill(option); } - fn review_candidate_name(&self, vote: &SelectedVote) -> Option { - let ResourceVoteChoice::TowardsIdentity(candidate_id) = vote.vote_choice else { + fn candidate_name(&self, contested_name: &str, choice: ResourceVoteChoice) -> Option { + let ResourceVoteChoice::TowardsIdentity(candidate_id) = choice else { return None; }; self.contested_names .lock_recover() .iter() - .find(|contest| contest.normalized_contested_name == vote.contested_name) + .find(|contest| contest.normalized_contested_name == contested_name) .and_then(|contest| contest.contestants.as_ref()) .and_then(|contestants| { contestants @@ -1470,9 +1610,10 @@ impl DPNSScreen { DashColors::warning_color(dark_mode), NO_VOTING_NODES_MESSAGE, ); + ui.label(NO_VOTING_NODES_DETAIL); ui.add_space(10.0); ui.horizontal(|ui| { - if ComponentStyles::add_primary_button(ui, "Open Masternodes").clicked() { + if ComponentStyles::add_primary_button(ui, "Load a masternode").clicked() { action = AppAction::SetMainScreen(RootScreenType::RootScreenMasternodes); self.show_bulk_schedule_popup = false; } @@ -1507,7 +1648,7 @@ impl DPNSScreen { ui.separator(); ui.heading(format!("Votes to cast ({}):", self.selected_votes.len())); for vote in &self.selected_votes { - let candidate_name = self.review_candidate_name(vote); + let candidate_name = self.candidate_name(&vote.contested_name, vote.vote_choice); let choice = review_vote_choice_label(vote.vote_choice, candidate_name.as_deref()); ui.label(format!("β€’ {name}.dash β†’ {choice}", name = vote.contested_name)); } @@ -1924,7 +2065,6 @@ impl DPNSScreen { 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("The votes could not be submitted.") .color(DashColors::text_primary(dark_mode)), @@ -1989,6 +2129,7 @@ impl ScreenLike for DPNSScreen { *dpns_names = self.app_context.local_dpns_names().unwrap_or_default(); } DPNSSubscreen::ScheduledVotes => { + *contested_names = self.app_context.all_contested_names().unwrap_or_default(); let new_scheduled = self.app_context.get_scheduled_votes().unwrap_or_default(); *scheduled_votes = new_scheduled .iter() @@ -2281,11 +2422,10 @@ impl ScreenLike for DPNSScreen { // 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 { + let has_any = !self.contested_names.lock_recover().is_empty(); + if self.voting_identities.is_empty() { + inner_action |= self.render_no_voting_nodes(ui); + } else if has_any { self.render_active_contests(ui); } else { inner_action |= self.render_no_active_contests_or_owned_names(ui); @@ -2478,8 +2618,38 @@ mod tests { } #[test] - fn missing_voting_nodes_copy_points_to_the_masternodes_tab() { - assert!(NO_VOTING_NODES_MESSAGE.contains("Masternodes tab")); + 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 for alice"); + assert!(!label.contains(&candidate_id.to_string(Encoding::Base58))); + } + + #[test] + fn proved_choice_is_highlighted_only_when_loaded_nodes_agree() { + assert_eq!( + proved_vote_summary([ + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Abstain)), + DpnsCurrentVoteState::Checking, + ]), + ProvedVoteSummary::Choice(ResourceVoteChoice::Abstain) + ); + assert_eq!( + proved_vote_summary([ + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Abstain)), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)), + ]), + ProvedVoteSummary::Mixed + ); + } + + #[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")); } diff --git a/tests/kittest/masternode_tab.rs b/tests/kittest/masternode_tab.rs index 1ce4e67fa..3f1362ab2 100644 --- a/tests/kittest/masternode_tab.rs +++ b/tests/kittest/masternode_tab.rs @@ -9,7 +9,7 @@ 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; @@ -348,6 +348,45 @@ fn dpns_scheduled_votes_tab_is_clickable() { }); } +/// VOTE-TC-013 β€” Active contests must expose the actionable no-voter-key state +/// directly; the user cannot open Review and cast without a usable voter. +#[test] +fn active_contests_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 active_screen = harness + .state_mut() + .main_screens + .get_mut(&RootScreenType::RootScreenDPNSActiveContests) + .expect("active contests screen"); + let Screen::DPNSScreen(active_screen) = active_screen else { + panic!("active contests root must contain a DPNS screen"); + }; + active_screen.refresh(); + harness.run_steps(5); + + assert!( + harness + .query_by_label("None of your loaded nodes has a voting key.") + .is_some(), + "the no-voter-key explanation must render on Active contests" + ); + harness.get_by_label("Load a masternode").click(); + harness.run_steps(3); + assert_eq!( + harness.state().selected_main_screen, + RootScreenType::RootScreenMasternodes + ); + }); +} + /// 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 From dd81c468d4223a291da325c56b442d8e1bfe058b Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 21 Jul 2026 13:16:44 +0000 Subject: [PATCH 027/194] fix: refresh proved DPNS vote state after updates Reload the screen's vote-state snapshot from the confirmed vote cache when a voting operation completes, so a changed vote renders immediately instead of showing the pre-change choice until the next full contest refresh. Co-Authored-By: OpenAI Codex --- src/ui/dpns/dpns_contested_names_screen.rs | 44 ++++++++++++++++++++++ src/ui/state/dpns_vote_state.rs | 23 +++++++++++ 2 files changed, 67 insertions(+) diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 43623aa1c..a90ad87c7 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -2248,6 +2248,12 @@ impl ScreenLike for DPNSScreen { fn display_task_result(&mut self, backend_task_success_result: BackendTaskSuccessResult) { match backend_task_success_result { BackendTaskSuccessResult::DpnsVoteOperationUpdated { 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) || (self.pending_vote_operation.is_none() && self.vote_overlay.is_some()); if owns_result { @@ -2581,6 +2587,44 @@ mod tests { ); } + #[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, DPNSSubscreen::Active); + 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 active_contest_groups_prioritize_nodes_that_still_need_a_vote() { assert!(matches!( diff --git a/src/ui/state/dpns_vote_state.rs b/src/ui/state/dpns_vote_state.rs index ce0bbfc62..79fd3a79f 100644 --- a/src/ui/state/dpns_vote_state.rs +++ b/src/ui/state/dpns_vote_state.rs @@ -45,6 +45,29 @@ impl DpnsVoteStateSnapshot { Ok(()) } + 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); + } + + let mut states = BTreeMap::new(); + for (voter_id, vote_poll_ids) in polls_by_voter { + states.extend( + app_context + .dpns_current_vote_states(voter_id, vote_poll_ids)? + .into_iter() + .map(|(poll_id, state)| ((voter_id, poll_id), state)), + ); + } + self.states = states; + self.loaded = true; + Ok(()) + } + pub fn state(&self, voter_id: Identifier, vote_poll_id: Identifier) -> DpnsCurrentVoteState { if !self.loaded { return DpnsCurrentVoteState::Unavailable; From 8ca7635a53ec1d5fb15894776b8c65a2fee450b3 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 22 Jul 2026 07:40:11 +0000 Subject: [PATCH 028/194] fix(dpns-voting): quarantine poisoned legacy rows and unblock stranded Unconfirmed votes - Migrate valid legacy operations while parking foreign-network rows outside the active legacy index so scheduled sweeps keep making progress. - Corroborate a proved-different vote across two reconciliation passes before marking it NotApplied and releasing the target lock. Fixes PR review threads CMT-4 and CMT-5 (findings by claude[bot]). Co-Authored-By: OpenAI Codex --- src/backend_task/contested_names/mod.rs | 172 +++++++++++++++++++----- src/context/dpns_vote_operations.rs | 91 +++++++++++-- 2 files changed, 215 insertions(+), 48 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index f5cc5d40e..6100848eb 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -100,8 +100,17 @@ fn missing_voter_outcome( fn classify_reconciled_vote( observed: Option, requested: ResourceVoteChoice, + previous_observation: Option, ) -> Option { - (observed == Some(requested)).then_some(DpnsVoteTargetStatus::Confirmed) + match observed { + Some(choice) if choice == requested => Some(DpnsVoteTargetStatus::Confirmed), + // Two consecutive identical mismatches filter one stale/racing read while + // releasing the lock promptly once Platform consistently proves another vote. + Some(choice) if previous_observation == Some(choice) => { + Some(DpnsVoteTargetStatus::NotApplied) + } + Some(_) | None => None, + } } fn persist_terminal_then_legacy_mirror( @@ -748,36 +757,35 @@ impl AppContext { order_ascending: true, }; match ResourceVote::fetch_many(sdk, query).await { - Ok(votes) - if classify_reconciled_vote( - votes - .get(&poll_id) - .and_then(Option::as_ref) - .map(ResourceVoteGettersV0::resource_vote_choice), + Ok(votes) => { + let observed = votes + .get(&poll_id) + .and_then(Option::as_ref) + .map(ResourceVoteGettersV0::resource_vote_choice); + let reconciled_status = classify_reconciled_vote( + observed, outcome.target.requested_choice, - ) == Some(DpnsVoteTargetStatus::Confirmed) => - { - let mirror_error = persist_terminal_then_legacy_mirror( - || { - self.update_dpns_vote_target( - operation_id, - &outcome.target.key, - DpnsVoteTargetStatus::Confirmed, - None, - ) - }, - || { - if matches!(outcome.target.timing, VoteTiming::Scheduled(_)) { - self.mark_vote_executed( - outcome.target.key.voter_id.as_slice(), - outcome.target.contested_name.clone(), - ) - } else { - Ok(()) - } - }, - )?; - if let Some(error) = mirror_error { + outcome.target.current_choice, + ); + let status = reconciled_status.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; + } + if matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + && let Err(error) = self.mark_vote_executed( + outcome.target.key.voter_id.as_slice(), + outcome.target.contested_name.clone(), + ) + { tracing::warn!( ?error, operation_id = %operation_id, @@ -792,7 +800,6 @@ impl AppContext { outcome.target.requested_choice, )?; } - Ok(_) => {} Err(error) => { let error = TaskError::from(error); tracing::warn!( @@ -1121,21 +1128,118 @@ mod tests { #[test] fn exact_reconciliation_confirms_only_the_requested_choice() { assert_eq!( - classify_reconciled_vote(Some(ResourceVoteChoice::Lock), ResourceVoteChoice::Lock), + classify_reconciled_vote( + Some(ResourceVoteChoice::Lock), + ResourceVoteChoice::Lock, + None, + ), Some(DpnsVoteTargetStatus::Confirmed) ); assert_eq!( - classify_reconciled_vote(Some(ResourceVoteChoice::Abstain), ResourceVoteChoice::Lock), + classify_reconciled_vote( + Some(ResourceVoteChoice::Abstain), + ResourceVoteChoice::Lock, + None, + ), None, "a mismatched row may predate the submitted transition and remains ambiguous" ); assert_eq!( - classify_reconciled_vote(None, ResourceVoteChoice::Lock), + classify_reconciled_vote( + None, + ResourceVoteChoice::Lock, + Some(ResourceVoteChoice::Abstain), + ), None, "an absent exact row remains ambiguous and must not release its lock" ); } + #[test] + fn proved_different_reconciliation_releases_target_lock_after_corroboration() { + 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 = DpnsVoteOperation::new(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, None) + .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, + persisted.targets[0].target.current_choice, + ) + .expect("the repeated different choice must be proved not applied"); + 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::NotApplied); + assert!(!target.status.holds_lock()); + assert_eq!(context.dpns_vote_target_status(&key).unwrap(), None); + } + #[test] fn terminal_journal_write_precedes_best_effort_legacy_mirror() { let events = RefCell::new(Vec::new()); diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index 8cd14f7fc..efa0398c0 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -9,6 +9,7 @@ use crate::model::dpns_voting::{ }; use crate::wallet_backend::{DetKv, DetScope, KvAdapterError}; 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; @@ -106,7 +107,7 @@ fn migrate_legacy_operations(kv: &DetKv, network: Network) -> Result<(), TaskErr let mut qualified_ids = load_operation_ids(kv, network)?; let mut qualified_changed = false; - let mut retained_legacy_ids = Vec::new(); + let retained_legacy_ids = Vec::<[u8; 16]>::new(); for bytes in &legacy_ids { let bytes = *bytes; let id = DpnsVoteOperationId::from_bytes(bytes); @@ -119,10 +120,8 @@ fn migrate_legacy_operations(kv: &DetKv, network: Network) -> Result<(), TaskErr .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; match operation_matches_network(&operation, network) { Ok(false) => continue, - Err(error) => { - retained_legacy_ids.push(bytes); - return Err(error); - } + Err(TaskError::DpnsVoteJournalNetworkMismatch) => continue, + Err(error) => return Err(error), Ok(true) => {} } kv.put( @@ -505,6 +504,7 @@ fn recover_interrupted_target_statuses(operation: &mut DpnsVoteOperation) -> boo } DpnsVoteTargetStatus::Confirming => { outcome.status = DpnsVoteTargetStatus::Unconfirmed; + outcome.target.current_choice = None; outcome.failure = Some(DpnsVoteFailure::ResultUnconfirmed); changed = true; } @@ -708,11 +708,52 @@ impl AppContext { .find(|outcome| outcome.target.key == *key) { outcome.status = status; + if status == DpnsVoteTargetStatus::Unconfirmed { + outcome.target.current_choice = None; + } outcome.failure = failure; } persist_operation(&kv, self.network, &operation) } + /// Atomically persist one corroborated reconciliation observation. + pub(crate) fn update_dpns_vote_reconciliation( + &self, + operation_id: DpnsVoteOperationId, + key: &DpnsVoteTargetKey, + expected_current_choice: Option, + observed_choice: Option, + status: DpnsVoteTargetStatus, + ) -> Result { + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let kv = self.det_kv()?; + let Some(mut operation): Option = kv + .get(DetScope::Global, &operation_key(self.network, operation_id)) + .map_err(unreadable_operation_err)? + else { + return Ok(false); + }; + let Some(outcome) = operation.targets.iter_mut().find(|outcome| { + outcome.target.key == *key + && outcome.status == DpnsVoteTargetStatus::Unconfirmed + && outcome.target.current_choice == expected_current_choice + }) else { + return Ok(false); + }; + if outcome.target.current_choice == observed_choice && outcome.status == status { + return Ok(true); + } + outcome.target.current_choice = observed_choice; + outcome.status = status; + outcome.failure = (status == DpnsVoteTargetStatus::Unconfirmed) + .then_some(DpnsVoteFailure::ResultUnconfirmed); + persist_operation(&kv, self.network, &operation)?; + Ok(true) + } + /// Atomically claim a queued target before any network or nonce work. pub(crate) fn claim_dpns_vote_target( &self, @@ -1278,26 +1319,48 @@ mod tests { } #[test] - fn mismatched_unresolved_legacy_record_fails_closed() { + fn legacy_migration_quarantines_cross_network_row_without_blocking_siblings() { let kv = kv(); - let operation = operation(DpnsVoteTargetStatus::Unconfirmed); + let mut poisoned = operation(DpnsVoteTargetStatus::Unconfirmed); + poisoned.targets[0].target.key.network = Network::Mainnet; + let mut valid = operation(DpnsVoteTargetStatus::Scheduled); + valid.targets[0].target.key.vote_poll_id = Identifier::from([3; 32]); kv.put( DetScope::Global, - &legacy_operation_key(operation.id), - &operation, + &legacy_operation_key(poisoned.id), + &poisoned, ) .unwrap(); + kv.put(DetScope::Global, &legacy_operation_key(valid.id), &valid) + .unwrap(); kv.put( DetScope::Global, LEGACY_OPERATION_INDEX_KEY, - &vec![operation.id.to_bytes()], + &vec![poisoned.id.to_bytes(), valid.id.to_bytes()], ) .unwrap(); - assert!(matches!( - load_operations(&kv, Network::Mainnet), - Err(TaskError::DpnsVoteJournalNetworkMismatch) - )); + assert_eq!( + load_operations(&kv, Network::Testnet).unwrap(), + vec![valid.clone()] + ); + assert_eq!( + load_operations(&kv, Network::Testnet).unwrap(), + vec![valid], + "a quarantined row must not block or duplicate valid siblings on later sweeps" + ); + assert_eq!( + kv.get::>(DetScope::Global, LEGACY_OPERATION_INDEX_KEY) + .unwrap() + .unwrap_or_default(), + Vec::<[u8; 16]>::new() + ); + assert!( + kv.get::(DetScope::Global, &legacy_operation_key(poisoned.id)) + .unwrap() + .is_some(), + "quarantine must park the foreign record rather than delete it" + ); } #[test] From 76c0ed71f3cf86b476f50702d6b7d0aedd22373b Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 22 Jul 2026 07:53:09 +0000 Subject: [PATCH 029/194] fix(dpns-voting): retain quarantined legacy rows instead of dropping them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit migrate_legacy_operations previously overwrote the legacy index with an always-empty retained list, silently discarding foreign-network rows instead of keeping them for a subsequent correct-network migration pass. πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent Co-Authored-By: Claude GPT-5 Codex --- src/context/dpns_vote_operations.rs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index efa0398c0..2b6777476 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -107,7 +107,7 @@ fn migrate_legacy_operations(kv: &DetKv, network: Network) -> Result<(), TaskErr let mut qualified_ids = load_operation_ids(kv, network)?; let mut qualified_changed = false; - let retained_legacy_ids = Vec::<[u8; 16]>::new(); + let mut retained_legacy_ids = Vec::<[u8; 16]>::new(); for bytes in &legacy_ids { let bytes = *bytes; let id = DpnsVoteOperationId::from_bytes(bytes); @@ -120,7 +120,10 @@ fn migrate_legacy_operations(kv: &DetKv, network: Network) -> Result<(), TaskErr .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; match operation_matches_network(&operation, network) { Ok(false) => continue, - Err(TaskError::DpnsVoteJournalNetworkMismatch) => continue, + Err(TaskError::DpnsVoteJournalNetworkMismatch) => { + retained_legacy_ids.push(bytes); + continue; + } Err(error) => return Err(error), Ok(true) => {} } @@ -1353,7 +1356,8 @@ mod tests { kv.get::>(DetScope::Global, LEGACY_OPERATION_INDEX_KEY) .unwrap() .unwrap_or_default(), - Vec::<[u8; 16]>::new() + vec![poisoned.id.to_bytes()], + "a quarantined row must remain indexed for a correct-network migration pass" ); assert!( kv.get::(DetScope::Global, &legacy_operation_key(poisoned.id)) @@ -1361,6 +1365,18 @@ mod tests { .is_some(), "quarantine must park the foreign record rather than delete it" ); + + assert_eq!( + load_operations(&kv, Network::Mainnet).unwrap(), + vec![poisoned] + ); + assert_eq!( + kv.get::>(DetScope::Global, LEGACY_OPERATION_INDEX_KEY) + .unwrap() + .unwrap_or_default(), + Vec::<[u8; 16]>::new(), + "the legacy index must drop a quarantined row after correct-network migration" + ); } #[test] From 8abca999c21427172ecea234ab18ea659dc8132a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 22 Jul 2026 16:15:47 +0000 Subject: [PATCH 030/194] perf(dpns-voting): batch masternode-card current-vote reads into one storage read per node MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `masternode_contest_summary` called the singular `dpns_current_vote_state` once per open contest, each re-reading the same per-node proved snapshot β€” O(open-contests) KV reads per node on every Masternodes-list refresh, the exact pattern VOTE-NFR-007 / VOTE-TC-005 forbid and that the batched `dpns_current_vote_states` primitive already exists to avoid. Resolve every open contest's vote-poll id up front, then read all states with a single `dpns_current_vote_states` call. A read failure degrades each contest to `Unavailable`, preserving the prior per-contest fallback semantics. Also collapses the duplicated `is_open_for_voter` filter into one pass. Adds a regression test that drives the masternode-card consumer (not just the primitive) and asserts exactly one snapshot read for five open contests. Co-Authored-By: Claude Opus --- src/context/contested_names_db.rs | 114 ++++++++++++++++++++++++++++-- 1 file changed, 108 insertions(+), 6 deletions(-) diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index bd9256f44..715b87dd4 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -262,17 +262,33 @@ impl AppContext { }; let contests = self.ongoing_contested_names()?; - let open_contest_count = contests - .iter() - .filter(|contest| contest.is_open_for_voter(&voter_id)) - .count(); - let states = contests + let open_polls: Vec> = contests .iter() .filter(|contest| contest.is_open_for_voter(&voter_id)) .map(|contest| { self.dpns_vote_poll_id(&contest.normalized_contested_name) .ok() - .and_then(|poll_id| self.dpns_current_vote_state(voter_id, poll_id).ok()) + }) + .collect(); + let open_contest_count = open_polls.len(); + + // 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 = { + let poll_ids: Vec = open_polls.iter().flatten().copied().collect(); + if poll_ids.is_empty() { + BTreeMap::new() + } else { + self.dpns_current_vote_states(voter_id, poll_ids) + .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::>(); @@ -475,7 +491,9 @@ mod tests { use super::*; use crate::wallet_backend::DetKv; 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}; fn empty_kv() -> DetKv { DetKv::from_store(Arc::new(InMemoryKv::default())) @@ -712,4 +730,88 @@ mod tests { (false, false) ); } + + /// Counts reads of the per-node current-vote snapshot key so a test can + /// prove how many snapshot loads a caller performs. The `v2:` prefix is + /// the active snapshot key (`current_votes_key`), one per node. + #[derive(Default)] + struct CurrentVotesReadCounter { + inner: InMemoryKv, + snapshot_reads: AtomicUsize, + } + + impl KvStore for CurrentVotesReadCounter { + fn get(&self, scope: &ObjectId, key: &str) -> Result>, KvError> { + if key.starts_with("det:dpns_current_votes:v2:") { + self.snapshot_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" + ); + } } From f60b7ae21efcb6728674a2cefb0ad011bf68136f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 23 Jul 2026 11:42:18 +0000 Subject: [PATCH 031/194] fix(dpns): surface masternode vote limit Map Platform's typed vote-limit rejection to a dedicated user-facing TaskError while preserving the SDK source for diagnostics. Co-Authored-By: Codex GPT-5.6 --- src/backend_task/error.rs | 80 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 72dd2fa21..3fab2ce33 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1967,6 +1967,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." @@ -2900,6 +2911,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| { @@ -3168,6 +3190,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; @@ -4082,6 +4105,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( From 41196108e4e9abd89f052a129116a1cfee8d1c82 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 27 Jul 2026 08:47:02 +0000 Subject: [PATCH 032/194] fix(dpns): rename misleading is_open_for_voter to reflect contest-level check Rename the voter-scoped-looking helper to is_votable, remove its unused voter parameter, update the sole caller, and replace voter-map-dependent tests with exhaustive contest-state coverage. Co-Authored-By: Codex GPT-5 --- src/context/contested_names_db.rs | 2 +- src/model/contested_name.rs | 52 +++++++------------------------ 2 files changed, 13 insertions(+), 41 deletions(-) diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index d4af4418b..fe82b8c7b 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -356,7 +356,7 @@ impl AppContext { let contests = self.ongoing_contested_names()?; let open_polls: Vec> = contests .iter() - .filter(|contest| contest.is_open_for_voter(&voter_id)) + .filter(|contest| contest.is_votable()) .map(|contest| { self.dpns_vote_poll_id(&contest.normalized_contested_name) .ok() diff --git a/src/model/contested_name.rs b/src/model/contested_name.rs index 102d72769..7c3e2d143 100644 --- a/src/model/contested_name.rs +++ b/src/model/contested_name.rs @@ -39,8 +39,8 @@ pub struct ContestedName { } impl ContestedName { - /// Whether the contest still accepts this node's initial vote or a change. - pub fn is_open_for_voter(&self, _voter_id: &Identifier) -> bool { + /// Whether the contest's state still accepts votes. + pub fn is_votable(&self) -> bool { self.state.state_is_votable() } @@ -247,7 +247,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 { @@ -285,43 +284,16 @@ mod tests { } #[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 existing_vote_remains_actionable_while_contest_is_votable() { - 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)); + 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), + ] { + assert_eq!(contest(state).is_votable(), expected); + } } // ---------------------------------------------------------------- From 9b45fba6c5ebc0110b39508b04b92e0ea3b5951b Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 27 Jul 2026 08:51:43 +0000 Subject: [PATCH 033/194] fix(dpns): route scheduled-vote sweep completion to hidden Active-contests root dpns_result_needs_hidden_active_contests_route() was missing ScheduledVoteSweepCompleted from its matches!, so the general hidden-route dispatcher (route_dpns_vote_result_to_hidden_active_contests, called unconditionally for every Success result) never refreshed a hidden RootScreenDPNSActiveContests after a scheduled-vote sweep completed. A user who navigated away or had a screen pushed on the stack while a sweep was in flight could return to stale, disabled voting controls after a plain PopScreen. Also narrows the sweep-completion branch's direct visible_screen_mut() refresh so it only fires when Active-contests is actually the visible screen (no screen-stack, no other root selected) instead of unconditionally refreshing whatever screen happens to be visible. Adds scheduled_vote_sweep_completion_routes_when_active_contests_is_hidden covering both the hidden and visible cases. Co-Authored-By: Codex Sol --- src/app.rs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/app.rs b/src/app.rs index 2a7275d1e..f1e7ca47b 100644 --- a/src/app.rs +++ b/src/app.rs @@ -384,6 +384,7 @@ fn dpns_result_needs_hidden_active_contests_route( result, BackendTaskSuccessResult::DpnsVoteOperationUpdated { .. } | BackendTaskSuccessResult::RefreshedDpnsContests + | BackendTaskSuccessResult::ScheduledVoteSweepCompleted { .. } ) && (selected != RootScreenType::RootScreenDPNSActiveContests || !screen_stack_is_empty) } @@ -2834,7 +2835,12 @@ impl App for AppState { ) { self.scheduled_vote_recovery_last_attempt.remove(&network); } - self.visible_screen_mut().refresh(); + if self.selected_main_screen + == RootScreenType::RootScreenDPNSActiveContests + && self.screen_stack.is_empty() + { + self.visible_screen_mut().refresh(); + } } BackendTaskSuccessResult::NetworkContextCreated { network, @@ -3814,6 +3820,30 @@ mod dpns_result_routing_tests { &BackendTaskSuccessResult::RefreshedDpnsContests, )); } + + #[test] + fn scheduled_vote_sweep_completion_routes_when_active_contests_is_hidden() { + let result = BackendTaskSuccessResult::ScheduledVoteSweepCompleted { + network: Network::Testnet, + preserve_eligibility_since_ms: None, + }; + + assert!(dpns_result_needs_hidden_active_contests_route( + RootScreenType::RootScreenWalletsBalances, + true, + &result, + )); + assert!(dpns_result_needs_hidden_active_contests_route( + RootScreenType::RootScreenDPNSActiveContests, + false, + &result, + )); + assert!(!dpns_result_needs_hidden_active_contests_route( + RootScreenType::RootScreenDPNSActiveContests, + true, + &result, + )); + } } #[cfg(test)] From 7de526b08cf6a00e68c8412123c8f45673e875b1 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 27 Jul 2026 09:22:21 +0000 Subject: [PATCH 034/194] fix(dpns): guard scheduled-vote journal cleanup and removal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Makes the operation journal authoritative over the legacy scheduled-vote KV mirror for removal, Clear All, and terminal-operation pruning: - remove_scheduled_dpns_vote(): guarded row removal that changes a Scheduled target to Cancelled and persists before touching the mirror, refuses to touch the mirror while a target is Queued/Submitting/ Confirming/Unconfirmed (returns DpnsScheduledVoteAlreadyStarted), and only allows mirror-only deletion when no journal operation still holds the target lock. - clear_all_scheduled_dpns_votes(): guarded Clear All that cancels Scheduled targets, retains mirror rows for anything still in flight, and returns a typed per-target DpnsScheduledVoteClearOutcome instead of unconditionally wiping every mirror row. - insert_dpns_vote_operation_with_scheduled_mirror(): serializes the journal write and the best-effort compatibility-mirror write under the same guard, closing the race where a concurrent Clear All could cancel and prune a schedule before its mirror row ever landed. - prune_terminal_dpns_vote_operations(): now takes no removed-set parameter and derives eligibility from a durable raw-key enumeration of surviving mirror rows instead of an in-memory BTreeSet, so a crash or I/O failure partway through cleanup no longer permanently strands a terminal operation as unprunable. The predicate also no longer treats "not scheduled" as automatic pruning grounds, so immediate-only operations backing Recent voting activity survive a scheduled-only clear. - clear_executed_scheduled_votes(): rewritten around the durable raw-key helper, propagates row-read errors instead of silently treating them as absent, and calls the new no-arg pruning method. - operation_for_scheduled_vote(): prefers the lock-holding operation, falling back to the newest terminal one, instead of first-match. New model types (src/model/dpns_voting.rs): DpnsScheduledVoteKey, DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome. New BackendTaskSuccessResult::ScheduledVotesCleared variant. UI wiring (journal-first Scheduled Votes table, button dispatch, Active contests render cache) is a separate follow-up commit β€” this pass is scoped to the backend_task/context layer only, per the DET module placement policy. Co-Authored-By: Codex Sol --- src/backend_task/contested_names/mod.rs | 126 +++-- src/backend_task/mod.rs | 3 +- src/context/dpns_vote_operations.rs | 591 ++++++++++++++++++++---- src/context/identity_db.rs | 318 +++++++++++-- src/model/dpns_voting.rs | 23 + src/wallet_backend/kv_test_support.rs | 44 ++ 6 files changed, 951 insertions(+), 154 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 6100848eb..fd5c9fec5 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -219,21 +219,20 @@ impl AppContext { wrap_scheduled_vote_sweep_result(self.network, result) } ContestedResourceTask::ClearAllScheduledVotes => { - self.cancel_all_scheduled_dpns_vote_targets()?; - if let Err(error) = self.clear_all_scheduled_votes() { - tracing::warn!( - ?error, - "Scheduled DPNS votes were cancelled but the legacy mirror could not be cleared" - ); - } - 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)?; + let key = DpnsVoteTargetKey { + network: self.network, + voter_id, + vote_poll_id: self.dpns_vote_poll_id(&contested_name)?, + }; + self.remove_scheduled_dpns_vote(None, &key, &contested_name)?; Ok(BackendTaskSuccessResult::Refresh) } ContestedResourceTask::CancelScheduledDpnsVote { @@ -241,18 +240,7 @@ impl AppContext { key, contested_name, } => { - self.cancel_scheduled_dpns_vote_target(operation_id, &key)?; - if let Err(error) = - self.delete_scheduled_vote(key.voter_id.as_slice(), &contested_name) - { - tracing::warn!( - ?error, - operation_id = %operation_id, - voter_id = %key.voter_id, - contested_name, - "Scheduled DPNS vote was cancelled but the legacy mirror could not be cleared" - ); - } + self.cancel_scheduled_dpns_vote_target(operation_id, &key, &contested_name)?; Ok(BackendTaskSuccessResult::Refresh) } } @@ -324,16 +312,16 @@ impl AppContext { scheduled_vote: &ScheduledDPNSVote, voter: &QualifiedIdentity, ) -> Result { - if let Some(operation) = self.dpns_vote_operations()?.into_iter().find(|operation| { - operation.targets.iter().any(|outcome| { - outcome.target.key.voter_id == scheduled_vote.voter_id - && outcome.target.contested_name == scheduled_vote.contested_name - }) - }) { + 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()?; + if let Some(operation) = preferred_operation_for_scheduled_key(&operations, &key)?.cloned() + { for outcome in &operation.targets { - if outcome.target.key.voter_id != scheduled_vote.voter_id - || outcome.target.contested_name != scheduled_vote.contested_name - { + if outcome.target.key != key { continue; } match outcome.status { @@ -466,10 +454,11 @@ impl AppContext { VoteTiming::Now => None, }) .collect::>(); - self.insert_dpns_vote_operation(&mut operation, replacing_scheduled_key.as_ref())?; - if !scheduled_votes.is_empty() - && let Err(error) = self.insert_scheduled_votes(&scheduled_votes) - { + if let Some(error) = self.insert_dpns_vote_operation_with_scheduled_mirror( + &mut operation, + replacing_scheduled_key.as_ref(), + &scheduled_votes, + )? { // The journal is authoritative. The legacy table is a // compatibility mirror, so its failure cannot turn a durable // schedule into a reported failure that invites a duplicate. @@ -949,6 +938,31 @@ impl AppContext { } } +fn preferred_operation_for_scheduled_key<'a>( + operations: &'a [DpnsVoteOperation], + key: &DpnsVoteTargetKey, +) -> Result, TaskError> { + let mut lock_holders = operations.iter().filter(|operation| { + operation + .outcome(key) + .is_some_and(|outcome| outcome.status.holds_lock()) + }); + let lock_holder = lock_holders.next(); + if lock_holders.next().is_some() { + return Err(TaskError::DpnsVoteTargetBusy); + } + Ok(lock_holder.or_else(|| { + operations + .iter() + .filter(|operation| { + operation + .outcome(key) + .is_some_and(|outcome| !outcome.status.holds_lock()) + }) + .max_by_key(|operation| (operation.created_at, operation.id)) + })) +} + fn scheduled_vote_is_due( scheduled_at_ms: u64, executed_successfully: bool, @@ -1064,6 +1078,50 @@ mod tests { 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 = DpnsVoteOperation::new(vec![target.clone()]); + older.created_at = 1; + older.targets[0].status = DpnsVoteTargetStatus::Confirmed; + let mut newer = DpnsVoteOperation::new(vec![target.clone()]); + newer.created_at = 2; + newer.targets[0].status = DpnsVoteTargetStatus::Cancelled; + let mut lock_holder = DpnsVoteOperation::new(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_operation_for_scheduled_key(&operations, &key) + .unwrap() + .unwrap() + .id, + lock_holder.id + ); + + let terminal_operations = vec![older, newer.clone()]; + assert_eq!( + preferred_operation_for_scheduled_key(&terminal_operations, &key) + .unwrap() + .unwrap() + .id, + newer.id + ); + } + #[test] fn vote_diagnostic_contextualizes_exhausted_dapi_addresses() { let temp_dir = tempfile::tempdir().expect("tempdir"); diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 6a0adb1d5..bfcabb7d8 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -12,7 +12,7 @@ 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::DpnsVoteOperationId; +use crate::model::dpns_voting::{DpnsScheduledVoteClearOutcome, DpnsVoteOperationId}; use dash_sdk::dpp::address_funds::PlatformAddress; use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; @@ -511,6 +511,7 @@ pub enum BackendTaskSuccessResult { 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), diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index 2b6777476..da3c05f13 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -1,9 +1,14 @@ //! Durable DPNS vote operation journal and exact-target lock registry. use super::AppContext; +use crate::backend_task::contested_names::ScheduledDPNSVote; use crate::backend_task::error::TaskError; +use crate::context::identity_db::{ + delete_scheduled_vote_in, durable_scheduled_vote_keys, insert_scheduled_votes_in, +}; use crate::model::dpns_voting::{ - DpnsCurrentVoteState, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, + DpnsCurrentVoteState, DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome, + DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, failed_before_broadcast_outcome, unavailable_preflight_outcome, }; @@ -313,22 +318,24 @@ fn write_existing_operation( persist_operation(kv, network, operation) } -fn prune_terminal_operations( - kv: &DetKv, - network: Network, - removed_scheduled_votes: &BTreeSet<([u8; 32], String)>, -) -> Result { +fn prune_terminal_operations(kv: &DetKv, network: Network) -> Result { + let surviving_scheduled_votes = durable_scheduled_vote_keys(kv, network)?; let terminal_ids = load_operations(kv, network)? .into_iter() .filter(|operation| { operation.is_complete() && !operation.targets.is_empty() + && operation + .targets + .iter() + .any(|outcome| matches!(outcome.target.timing, VoteTiming::Scheduled(_))) && operation.targets.iter().all(|outcome| { !matches!(outcome.target.timing, VoteTiming::Scheduled(_)) - || removed_scheduled_votes.contains(&( - outcome.target.key.voter_id.to_buffer(), - outcome.target.contested_name.clone(), - )) + || !surviving_scheduled_votes.contains(&DpnsScheduledVoteKey { + network: outcome.target.key.network, + voter_id: outcome.target.key.voter_id, + contested_name: outcome.target.contested_name.clone(), + }) }) }) .map(|operation| operation.id) @@ -477,25 +484,6 @@ fn cancel_scheduled_target( Ok(true) } -fn cancel_all_scheduled_targets(kv: &DetKv, network: Network) -> Result { - let mut cancelled = 0; - for mut operation in load_operations(kv, network)? { - let mut changed = false; - for outcome in &mut operation.targets { - if outcome.status == DpnsVoteTargetStatus::Scheduled { - outcome.status = DpnsVoteTargetStatus::Cancelled; - outcome.failure = None; - changed = true; - cancelled += 1; - } - } - if changed { - write_existing_operation(kv, network, &operation)?; - } - } - Ok(cancelled) -} - fn recover_interrupted_target_statuses(operation: &mut DpnsVoteOperation) -> bool { let mut changed = false; for outcome in &mut operation.targets { @@ -582,6 +570,33 @@ impl AppContext { persist_operation(&kv, self.network, operation) } + /// Persist an operation and its compatibility mirror under one journal guard. + pub(crate) fn insert_dpns_vote_operation_with_scheduled_mirror( + &self, + operation: &mut DpnsVoteOperation, + replacing_scheduled_key: Option<&DpnsVoteTargetKey>, + scheduled_votes: &[ScheduledDPNSVote], + ) -> Result, TaskError> { + if operation + .targets + .iter() + .any(|outcome| outcome.target.key.network != self.network) + { + return Err(TaskError::DpnsVoteTargetBusy); + } + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let kv = self.det_kv()?; + if let Some(key) = replacing_scheduled_key { + replace_scheduled_operation(&kv, self.network, operation, key)?; + } else { + persist_operation(&kv, self.network, operation)?; + } + Ok(insert_scheduled_votes_in(&kv, scheduled_votes).err()) + } + /// Persist updated target statuses while retaining the original operation ID. pub fn update_dpns_vote_operation( &self, @@ -925,50 +940,239 @@ impl AppContext { } /// Remove lock-releasing operation history when the user clears completed votes. - pub(crate) fn prune_terminal_dpns_vote_operations( - &self, - removed_scheduled_votes: &BTreeSet<([u8; 32], String)>, - ) -> Result { + pub(crate) fn prune_terminal_dpns_vote_operations(&self) -> Result { let _guard = self .dpns_vote_operation_guard .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - prune_terminal_operations(&self.det_kv()?, self.network, removed_scheduled_votes) + prune_terminal_operations(&self.det_kv()?, self.network) } - /// Release a not-yet-submitting scheduled target after explicit cancellation. - pub(crate) fn cancel_scheduled_dpns_vote_target( + /// Remove a schedule only after its authoritative journal state permits it. + pub(crate) fn remove_scheduled_dpns_vote( &self, - operation_id: DpnsVoteOperationId, + expected_operation_id: Option, key: &DpnsVoteTargetKey, + contested_name: &str, ) -> Result<(), TaskError> { let _guard = self .dpns_vote_operation_guard .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - if cancel_scheduled_target(&self.det_kv()?, self.network, operation_id, key)? { - Ok(()) - } else { - Err(TaskError::DpnsScheduledVoteAlreadyStarted) + let kv = self.det_kv()?; + let operations = load_operations(&kv, self.network)?; + let lock_index = load_or_rebuild_lock_index(&kv, self.network)?; + let selected = match expected_operation_id { + Some(operation_id) => operations + .iter() + .find(|operation| operation.id == operation_id) + .and_then(|operation| { + operation + .outcome(key) + .map(|outcome| (operation.id, outcome.status)) + }), + None => { + if let Some(operation_id) = lock_index.get(key) { + let operation = operations + .iter() + .find(|operation| operation.id == *operation_id) + .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; + let outcome = operation + .outcome(key) + .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; + Some((operation.id, outcome.status)) + } else { + operations + .iter() + .filter_map(|operation| { + operation + .outcome(key) + .filter(|outcome| !outcome.status.holds_lock()) + .map(|outcome| (operation.created_at, operation.id, outcome.status)) + }) + .max_by_key(|(created_at, operation_id, _)| (*created_at, *operation_id)) + .map(|(_, operation_id, status)| (operation_id, status)) + } + } + }; + + let journal_is_authoritative = 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); + } + true + } + 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); + } + true + } + None => { + if lock_index.contains_key(key) { + return Err(TaskError::DpnsScheduledVoteAlreadyStarted); + } + false + } + }; + + let voter = key.voter_id.to_buffer(); + if let Err(error) = delete_scheduled_vote_in(&kv, &voter, contested_name) { + if !journal_is_authoritative { + return Err(error); + } + tracing::warn!( + ?error, + expected_operation_id = ?expected_operation_id, + voter_id = %key.voter_id, + contested_name, + "Scheduled DPNS vote journal was updated but its compatibility mirror remains" + ); } + 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, + contested_name: &str, + ) -> Result<(), TaskError> { + self.remove_scheduled_dpns_vote(Some(operation_id), key, contested_name) } - /// Release every not-yet-submitting scheduled target on this network. - pub(crate) fn cancel_all_scheduled_dpns_vote_targets(&self) -> Result<(), TaskError> { + /// Clear removable schedules and report in-flight targets retained for safety. + pub(crate) fn clear_all_scheduled_dpns_votes( + &self, + ) -> Result, TaskError> { let _guard = self .dpns_vote_operation_guard .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - cancel_all_scheduled_targets(&self.det_kv()?, self.network)?; - Ok(()) + let kv = self.det_kv()?; + let mut retained = BTreeSet::new(); + let mut outcomes = BTreeMap::< + DpnsScheduledVoteKey, + ( + Option<(bool, u64, DpnsVoteOperationId)>, + DpnsScheduledVoteClearOutcome, + ), + >::new(); + + for mut operation in load_operations(&kv, self.network)? { + 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 => { + retained.insert(key.clone()); + DpnsScheduledVoteClearDisposition::InFlight(status) + } + _ => DpnsScheduledVoteClearDisposition::Cleared, + }; + let rank = (status.holds_lock(), operation.created_at, operation.id); + let should_replace = outcomes + .get(&key) + .is_none_or(|(existing_rank, _)| existing_rank.is_none_or(|old| rank > old)); + if should_replace { + outcomes.insert( + key.clone(), + ( + Some(rank), + DpnsScheduledVoteClearOutcome { + operation_id: Some(operation.id), + key, + disposition, + }, + ), + ); + } + } + if changed { + write_existing_operation(&kv, self.network, &operation)?; + } + } + + let mirror_keys = durable_scheduled_vote_keys(&kv, self.network)?; + for key in mirror_keys { + let journal_is_authoritative = outcomes.contains_key(&key); + outcomes.entry(key.clone()).or_insert_with(|| { + ( + None, + DpnsScheduledVoteClearOutcome { + operation_id: None, + key: key.clone(), + disposition: DpnsScheduledVoteClearDisposition::Cleared, + }, + ) + }); + if retained.contains(&key) { + continue; + } + let voter = key.voter_id.to_buffer(); + if let Err(error) = delete_scheduled_vote_in(&kv, &voter, &key.contested_name) { + if !journal_is_authoritative { + return Err(error); + } + tracing::warn!( + ?error, + voter_id = %key.voter_id, + contested_name = %key.contested_name, + "Scheduled DPNS vote was cleared in the journal but its compatibility mirror remains" + ); + } + } + + let _surviving_mirror_keys = durable_scheduled_vote_keys(&kv, self.network)?; + prune_terminal_operations(&kv, self.network)?; + Ok(outcomes.into_values().map(|(_, outcome)| outcome).collect()) } } #[cfg(test)] mod tests { use super::*; - use crate::model::dpns_voting::{DpnsVoteTarget, VoteTiming}; - use crate::wallet_backend::kv_test_support::InMemoryKv; + use crate::backend_task::contested_names::ScheduledDPNSVote; + 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; @@ -1058,6 +1262,29 @@ mod tests { 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 + } + + fn scheduled_vote(operation: &DpnsVoteOperation) -> ScheduledDPNSVote { + let target = &operation.targets[0].target; + ScheduledDPNSVote { + contested_name: target.contested_name.clone(), + voter_id: target.key.voter_id, + choice: target.requested_choice, + unix_timestamp: 42, + executed_successfully: false, + } + } + /// VOTE-TC-040/041: one unresolved target cannot be inserted twice. #[test] fn unresolved_target_rejects_a_competing_operation() { @@ -1203,18 +1430,33 @@ mod tests { #[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(); - let mut scheduled = operation(DpnsVoteTargetStatus::Scheduled); - scheduled.targets[0].target.timing = VoteTiming::Scheduled(42); + 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(); - persist_operation(&kv, Network::Testnet, &scheduled).unwrap(); - transition_scheduled_target_to_queued(&kv, Network::Testnet, scheduled.id, &key).unwrap(); + context + .insert_dpns_vote_operation(&mut scheduled, None) + .unwrap(); + context + .insert_scheduled_votes(&[scheduled_vote(&scheduled)]) + .unwrap(); + context + .queue_scheduled_dpns_vote_target(scheduled.id, &key) + .unwrap(); - assert!(!cancel_scheduled_target(&kv, Network::Testnet, scheduled.id, &key).unwrap()); + assert!(matches!( + context + .remove_scheduled_dpns_vote(Some(scheduled.id), &key, "dominguez") + .expect_err("queued targets must not be removed"), + TaskError::DpnsScheduledVoteAlreadyStarted + )); assert_eq!( - load_operations(&kv, Network::Testnet).unwrap()[0].targets[0].status, + context.dpns_vote_operations().unwrap()[0].targets[0].status, DpnsVoteTargetStatus::Queued ); + assert_eq!(context.get_scheduled_votes().unwrap().len(), 1); } #[test] @@ -1235,29 +1477,213 @@ mod tests { #[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(); - let mut scheduled = operation(DpnsVoteTargetStatus::Scheduled); - scheduled.targets[0].target.timing = VoteTiming::Scheduled(42); - let mut queued = operation(DpnsVoteTargetStatus::Queued); - queued.targets[0].target.key.vote_poll_id = Identifier::from([3; 32]); - persist_operation(&kv, Network::Testnet, &scheduled).unwrap(); - persist_operation(&kv, Network::Testnet, &queued).unwrap(); + 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(); + context + .insert_scheduled_votes(&[scheduled_vote(&queued)]) + .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!(context.get_scheduled_votes().unwrap().len(), 1); + assert_eq!(outcomes.len(), 1); + assert_eq!( + outcomes[0].disposition, + DpnsScheduledVoteClearDisposition::InFlight(DpnsVoteTargetStatus::Queued) + ); + } + + #[test] + fn scheduled_removal_persists_cancelled_before_best_effort_mirror_delete() { + 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 + .insert_scheduled_votes(&[scheduled_vote(&scheduled)]) + .unwrap(); + store.fail_next_deletes_containing("cancel-me", 1); + + context + .remove_scheduled_dpns_vote(Some(scheduled.id), &key, "cancel-me") + .unwrap(); + + assert_eq!( + context.dpns_vote_operations().unwrap()[0].targets[0].status, + DpnsVoteTargetStatus::Cancelled + ); + assert_eq!(context.get_scheduled_votes().unwrap().len(), 1); + } + + #[test] + fn stale_terminal_operation_cannot_remove_a_newer_locked_mirror() { + 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(); + context + .insert_scheduled_votes(&[scheduled_vote(¤t)]) + .unwrap(); + + assert!(matches!( + context + .remove_scheduled_dpns_vote(Some(terminal.id), &key, "same-target") + .expect_err("stale terminal history must not remove the current schedule"), + TaskError::DpnsScheduledVoteAlreadyStarted + )); + assert_eq!(context.get_scheduled_votes().unwrap().len(), 1); + 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), + ]; + let mut votes = Vec::new(); + for (index, (name, status)) in cases.into_iter().enumerate() { + let mut operation = scheduled_operation(status, index as u8 + 2, name); + votes.push(scheduled_vote(&operation)); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + } + votes.push(ScheduledDPNSVote { + contested_name: "legacy".to_owned(), + voter_id: Identifier::from([9; 32]), + choice: ResourceVoteChoice::Lock, + unix_timestamp: 42, + executed_successfully: false, + }); + context.insert_scheduled_votes(&votes).unwrap(); + + let outcomes = context.clear_all_scheduled_dpns_votes().unwrap(); + + let remaining_names = context + .get_scheduled_votes() + .unwrap() + .into_iter() + .map(|vote| vote.contested_name) + .collect::>(); assert_eq!( - cancel_all_scheduled_targets(&kv, Network::Testnet).unwrap(), - 1 + remaining_names, + BTreeSet::from([ + "confirming".to_owned(), + "queued".to_owned(), + "submitting".to_owned(), + "unconfirmed".to_owned(), + ]) ); - let operations = load_operations(&kv, Network::Testnet).unwrap(); - assert!(operations.iter().any(|operation| { - operation.targets[0].target.key == scheduled.targets[0].target.key - && operation.targets[0].status == DpnsVoteTargetStatus::Cancelled + assert_eq!(outcomes.len(), 7); + 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", "legacy"] { + assert!(outcomes.iter().any(|outcome| { + outcome.key.contested_name == name + && outcome.disposition == DpnsScheduledVoteClearDisposition::Cleared + })); + } + assert!(outcomes.iter().any(|outcome| { + outcome.key.contested_name == "legacy" && outcome.operation_id.is_none() })); - assert!(operations.iter().any(|operation| { - operation.targets[0].target.key == queued.targets[0].target.key - && operation.targets[0].status == DpnsVoteTargetStatus::Queued + let remaining_operations = context.dpns_vote_operations().unwrap(); + assert_eq!(remaining_operations.len(), 4); + assert!(remaining_operations.iter().all(|operation| { + matches!( + operation.targets[0].status, + DpnsVoteTargetStatus::Queued + | DpnsVoteTargetStatus::Submitting + | DpnsVoteTargetStatus::Confirming + | DpnsVoteTargetStatus::Unconfirmed + ) })); } + #[test] + fn combined_insert_reports_mirror_error_after_persisting_the_journal() { + 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, "mirror-fails"); + let vote = scheduled_vote(&scheduled); + store.fail_next_puts_containing("det:scheduled_vote:", 1); + + let mirror_error = context + .insert_dpns_vote_operation_with_scheduled_mirror(&mut scheduled, None, &[vote]) + .unwrap() + .expect("mirror failure must be returned separately"); + + assert!(matches!( + mirror_error, + TaskError::ScheduledVoteStorage { .. } + )); + assert_eq!( + context.dpns_vote_operations().unwrap(), + vec![scheduled.clone()] + ); + assert!(context.get_scheduled_votes().unwrap().is_empty()); + } + /// A corrupt indexed row must block lock reconstruction rather than being skipped. #[test] fn unreadable_indexed_operation_fails_closed() { @@ -1506,7 +1932,7 @@ mod tests { } #[test] - fn pruning_removes_terminal_scheduled_immediate_and_mixed_records() { + fn pruning_removes_terminal_scheduled_and_mixed_but_retains_immediate_history() { let kv = kv(); let mut scheduled = operation(DpnsVoteTargetStatus::Confirmed); scheduled.targets[0].target.timing = VoteTiming::Scheduled(42); @@ -1523,29 +1949,18 @@ mod tests { mixed_scheduled.target.key.vote_poll_id = Identifier::from([5; 32]); mixed.targets.push(mixed_scheduled); let live = operation(DpnsVoteTargetStatus::Unconfirmed); - let removed_scheduled_votes = BTreeSet::from([ - ( - scheduled.targets[0].target.key.voter_id.to_buffer(), - scheduled.targets[0].target.contested_name.clone(), - ), - ( - mixed.targets[1].target.key.voter_id.to_buffer(), - mixed.targets[1].target.contested_name.clone(), - ), - ]); 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, &removed_scheduled_votes).unwrap(), - 3 - ); - assert_eq!( - load_operations_read_only(&kv, Network::Testnet).unwrap(), - vec![live] - ); + assert_eq!(prune_terminal_operations(&kv, Network::Testnet).unwrap(), 2); + let remaining_ids = load_operations_read_only(&kv, Network::Testnet) + .unwrap() + .into_iter() + .map(|operation| operation.id) + .collect::>(); + assert_eq!(remaining_ids, BTreeSet::from([immediate.id, live.id])); assert!( kv.get::( DetScope::Global, @@ -1560,7 +1975,7 @@ mod tests { &operation_key(Network::Testnet, immediate.id), ) .unwrap() - .is_none() + .is_some() ); assert!( kv.get::( diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index 0fa6c242b..1b92abcd1 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -1,6 +1,7 @@ use super::AppContext; use crate::backend_task::contested_names::ScheduledDPNSVote; use crate::backend_task::error::TaskError; +use crate::model::dpns_voting::DpnsScheduledVoteKey; use crate::model::qualified_identity::{ DPNSNameInfo, IdentityStatus, IdentityType, QualifiedIdentity, }; @@ -456,6 +457,26 @@ fn scheduled_vote_keys( .map_err(scheduled_vote_err) } +/// Enumerate scheduled mirror keys without decoding their stored values. +pub(super) fn durable_scheduled_vote_keys( + kv: &DetKv, + network: Network, +) -> std::result::Result, TaskError> { + let mut keys = BTreeSet::new(); + for voter in load_scheduled_vote_voters(kv)? { + for key in scheduled_vote_keys(kv, &voter)? { + if let Some(contested_name) = key.strip_prefix(SCHEDULED_VOTE_KEY_PREFIX) { + keys.insert(DpnsScheduledVoteKey { + network, + voter_id: Identifier::from(voter), + contested_name: contested_name.to_owned(), + }); + } + } + } + Ok(keys) +} + /// 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( @@ -497,6 +518,37 @@ fn delete_scheduled_votes_for_voter( remove_vote_voter_from_index(kv, voter) } +pub(super) fn insert_scheduled_votes_in( + kv: &DetKv, + scheduled_votes: &[ScheduledDPNSVote], +) -> std::result::Result<(), TaskError> { + 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(()) +} + +pub(super) fn delete_scheduled_vote_in( + kv: &DetKv, + voter: &[u8; 32], + contested_name: &str, +) -> std::result::Result<(), TaskError> { + kv.delete( + DetScope::Identity(voter), + &scheduled_vote_key(contested_name), + ) + .map_err(scheduled_vote_err)?; + prune_vote_voter_if_empty(kv, voter) +} + impl AppContext { /// Insert (or replace) a local qualified identity in the per-network /// wallet k/v store under [`DetScope::Identity`]. Mirrors pre-C7 @@ -1082,19 +1134,7 @@ impl AppContext { &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(()) + insert_scheduled_votes_in(&self.det_kv()?, scheduled_votes) } /// Fetch every scheduled vote queued for this network from the @@ -1140,21 +1180,22 @@ impl AppContext { pub fn clear_executed_scheduled_votes(&self) -> std::result::Result<(), TaskError> { let kv = self.det_kv()?; let voters = load_scheduled_vote_voters(&kv)?; - let mut removed_scheduled_votes = BTreeSet::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)) if stored.executed_successfully => { + match kv + .get::(scope, &key) + .map_err(scheduled_vote_err)? + { + Some(stored) if stored.executed_successfully => { kv.delete(scope, &key).map_err(scheduled_vote_err)?; - removed_scheduled_votes.insert((stored.voter_id, stored.contested_name)); } - _ => {} + Some(_) | None => {} } } prune_vote_voter_if_empty(&kv, voter)?; } - self.prune_terminal_dpns_vote_operations(&removed_scheduled_votes)?; + self.prune_terminal_dpns_vote_operations()?; Ok(()) } @@ -1165,13 +1206,7 @@ impl AppContext { 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) + delete_scheduled_vote_in(&self.det_kv()?, &voter, contested_name) } /// Mark a single scheduled vote as executed so future cast loops skip it. @@ -1223,7 +1258,10 @@ impl AppContext { #[cfg(test)] mod tests { use super::*; - use crate::wallet_backend::kv_test_support::InMemoryKv; + use crate::model::dpns_voting::{ + DpnsVoteOperation, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + }; + use crate::wallet_backend::kv_test_support::{FailingKv, InMemoryKv}; use DetKv; use std::sync::Arc; @@ -1235,6 +1273,42 @@ mod tests { [b; 32] } + fn scheduled_vote( + voter_id: Identifier, + contested_name: &str, + executed_successfully: bool, + ) -> ScheduledDPNSVote { + ScheduledDPNSVote { + contested_name: contested_name.to_owned(), + voter_id, + choice: ResourceVoteChoice::Lock, + unix_timestamp: 42, + executed_successfully, + } + } + + fn scheduled_operation( + voter_id: Identifier, + poll: u8, + contested_name: &str, + status: DpnsVoteTargetStatus, + ) -> DpnsVoteOperation { + let mut operation = DpnsVoteOperation::new(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 @@ -1545,10 +1619,6 @@ mod tests { #[test] fn clearing_executed_votes_preserves_failed_and_cancelled_journal_records() { - use crate::model::dpns_voting::{ - DpnsVoteOperation, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, - }; - let temp_dir = tempfile::tempdir().expect("tempdir"); let context = crate::context::test_support::test_app_context(temp_dir.path()); let kv = empty_kv(); @@ -1680,6 +1750,192 @@ mod tests { assert_eq!(load_scheduled_vote_voters(&kv).unwrap(), vec![voter]); } + #[test] + fn mixed_terminal_operation_is_pruned_only_after_every_scheduled_mirror_is_absent() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp_dir.path()); + let kv = empty_kv(); + context.set_det_kv_override_for_test(kv); + let voter = Identifier::from(id(1)); + let first_vote = scheduled_vote(voter, "first", false); + let second_vote = scheduled_vote(voter, "second", false); + context + .insert_scheduled_votes(&[first_vote, second_vote]) + .unwrap(); + let mut operation = scheduled_operation(voter, 1, "first", DpnsVoteTargetStatus::Confirmed); + operation.targets.push( + scheduled_operation(voter, 2, "second", DpnsVoteTargetStatus::Confirmed) + .targets + .remove(0), + ); + let mut immediate = + scheduled_operation(voter, 3, "immediate", DpnsVoteTargetStatus::Confirmed) + .targets + .remove(0); + immediate.target.timing = VoteTiming::Now; + operation.targets.push(immediate); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + + assert_eq!(context.prune_terminal_dpns_vote_operations().unwrap(), 0); + context + .delete_scheduled_vote(voter.as_slice(), "first") + .unwrap(); + assert_eq!(context.prune_terminal_dpns_vote_operations().unwrap(), 0); + context + .delete_scheduled_vote(voter.as_slice(), "second") + .unwrap(); + assert_eq!(context.prune_terminal_dpns_vote_operations().unwrap(), 1); + assert!(context.dpns_vote_operations().unwrap().is_empty()); + } + + #[test] + fn journal_only_terminal_scheduled_operation_is_prunable() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp_dir.path()); + let kv = empty_kv(); + context.set_det_kv_override_for_test(kv); + let mut operation = scheduled_operation( + Identifier::from(id(1)), + 1, + "journal-only", + DpnsVoteTargetStatus::Confirmed, + ); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + + assert_eq!(context.prune_terminal_dpns_vote_operations().unwrap(), 1); + assert!(context.dpns_vote_operations().unwrap().is_empty()); + } + + #[test] + fn clear_executed_cleanup_recovers_after_voter_index_write_failure() { + 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 voter = Identifier::from(id(1)); + context + .insert_scheduled_votes(&[scheduled_vote(voter, "confirmed", true)]) + .unwrap(); + let mut operation = + scheduled_operation(voter, 1, "confirmed", DpnsVoteTargetStatus::Confirmed); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + store.fail_next_puts_containing(SCHEDULED_VOTE_VOTERS_KEY, 1); + + assert!(context.clear_executed_scheduled_votes().is_err()); + assert_eq!(context.dpns_vote_operations().unwrap(), vec![operation]); + + context.clear_executed_scheduled_votes().unwrap(); + assert!(context.dpns_vote_operations().unwrap().is_empty()); + assert!( + load_scheduled_vote_voters(&context.det_kv().unwrap()) + .unwrap() + .is_empty() + ); + } + + #[test] + fn clear_executed_cleanup_recovers_after_journal_prune_write_failure() { + 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 voter = Identifier::from(id(1)); + context + .insert_scheduled_votes(&[scheduled_vote(voter, "confirmed", true)]) + .unwrap(); + let mut operation = + scheduled_operation(voter, 1, "confirmed", DpnsVoteTargetStatus::Confirmed); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + store.fail_next_puts_containing("dpns_vote_operation_locks_dirty", 1); + + assert!(context.clear_executed_scheduled_votes().is_err()); + assert_eq!(context.dpns_vote_operations().unwrap(), vec![operation]); + + context.clear_executed_scheduled_votes().unwrap(); + assert!(context.dpns_vote_operations().unwrap().is_empty()); + assert!( + load_scheduled_vote_voters(&context.det_kv().unwrap()) + .unwrap() + .is_empty() + ); + } + + #[test] + fn clear_executed_cleanup_fails_closed_on_unreadable_mirror() { + 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 voter = Identifier::from(id(1)); + context + .insert_scheduled_votes(&[scheduled_vote(voter, "unreadable", true)]) + .unwrap(); + let mut operation = + scheduled_operation(voter, 1, "unreadable", DpnsVoteTargetStatus::Confirmed); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + store.fail_next_gets_containing(&scheduled_vote_key("unreadable"), 1); + + assert!(matches!( + context + .clear_executed_scheduled_votes() + .expect_err("an unreadable row must stop cleanup"), + TaskError::ScheduledVoteStorage { .. } + )); + assert_eq!(context.dpns_vote_operations().unwrap(), vec![operation]); + assert_eq!(context.get_scheduled_votes().unwrap().len(), 1); + } + + #[test] + fn pruning_treats_an_unreadable_mirror_key_as_surviving() { + 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 voter = Identifier::from(id(1)); + context + .insert_scheduled_votes(&[scheduled_vote(voter, "unreadable", true)]) + .unwrap(); + let mut operation = + scheduled_operation(voter, 1, "unreadable", DpnsVoteTargetStatus::Confirmed); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + store.fail_next_gets_containing(&scheduled_vote_key("unreadable"), 1); + + assert_eq!(context.prune_terminal_dpns_vote_operations().unwrap(), 0); + assert_eq!(context.dpns_vote_operations().unwrap(), vec![operation]); + assert!( + context.get_scheduled_votes().unwrap().is_empty(), + "the decode-oriented reader should consume and skip the injected row error" + ); + } + // --------------------------------------------------------------- // dashpay private / address_index Identity-scope contracts are // covered in `src/wallet_backend/dashpay.rs`; here we assert the diff --git a/src/model/dpns_voting.rs b/src/model/dpns_voting.rs index 3903415a9..485faead5 100644 --- a/src/model/dpns_voting.rs +++ b/src/model/dpns_voting.rs @@ -166,6 +166,29 @@ pub struct DpnsVoteTargetKey { pub vote_poll_id: Identifier, } +/// Durable identity of one scheduled-vote compatibility mirror row. +#[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 compatibility mirror. +#[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 { diff --git a/src/wallet_backend/kv_test_support.rs b/src/wallet_backend/kv_test_support.rs index c9eaa4449..e17d7ecce 100644 --- a/src/wallet_backend/kv_test_support.rs +++ b/src/wallet_backend/kv_test_support.rs @@ -85,8 +85,10 @@ impl KvStore for InMemoryKv { pub(crate) struct FailingKv { inner: InMemoryKv, fail_reads: AtomicBool, + fail_gets: Mutex>, puts: AtomicUsize, fail_puts: Mutex>, + fail_deletes: Mutex>, } impl FailingKv { @@ -97,6 +99,11 @@ impl FailingKv { self.fail_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.fail_gets.lock().unwrap() = Some((key_fragment.to_owned(), count)); + } + /// How many `put` calls have reached the store. pub(crate) fn put_count(&self) -> usize { self.puts.load(Ordering::Relaxed) @@ -106,6 +113,11 @@ impl FailingKv { pub(crate) fn fail_next_puts_containing(&self, key_fragment: &str, count: usize) { *self.fail_puts.lock().unwrap() = Some((key_fragment.to_owned(), 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.fail_deletes.lock().unwrap() = Some((key_fragment.to_owned(), count)); + } } impl KvStore for FailingKv { @@ -113,6 +125,22 @@ impl KvStore for FailingKv { if self.fail_reads.load(Ordering::Relaxed) { return Err(KvError::LockPoisoned); } + let should_fail = { + let mut failure = self.fail_gets.lock().unwrap(); + let should_fail = failure + .as_ref() + .is_some_and(|(fragment, remaining)| *remaining > 0 && key.contains(fragment)); + if should_fail && let Some((_, remaining)) = failure.as_mut() { + *remaining -= 1; + if *remaining == 0 { + *failure = None; + } + } + should_fail + }; + if should_fail { + return Err(KvError::LockPoisoned); + } self.inner.get(scope, key) } @@ -140,6 +168,22 @@ impl KvStore for FailingKv { } fn delete(&self, scope: &ObjectId, key: &str) -> Result<(), KvError> { + let should_fail = { + let mut failure = self.fail_deletes.lock().unwrap(); + let should_fail = failure + .as_ref() + .is_some_and(|(fragment, remaining)| *remaining > 0 && key.contains(fragment)); + if should_fail && let Some((_, remaining)) = failure.as_mut() { + *remaining -= 1; + if *remaining == 0 { + *failure = None; + } + } + should_fail + }; + if should_fail { + return Err(KvError::LockPoisoned); + } self.inner.delete(scope, key) } From f7f3c6294c752481b8f1aa5ceb75d74a021d2820 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 27 Jul 2026 10:01:58 +0000 Subject: [PATCH 035/194] fix(dpns): make Scheduled Votes journal-first and fix Clear All feedback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Builds on 4058b04b's guarded backend layer to close out the UI-side gaps: - Scheduled Votes table rows are now built from the newest journal outcome per (voter, contested_name) via DpnsVoteOperationSnapshot:: scheduled_vote_rows(), falling back to the legacy mirror row only when no journal pair exists. A journaled-but-unmirrored schedule is no longer invisible, and a terminal journal status (Rejected/ FailedBeforeSubmission/Cancelled) is no longer misdisplayed as Pending. - Row Remove dispatches CancelScheduledDpnsVote (guarded journal cancellation) for journal-backed rows, and DeleteScheduledVote (legacy-only deletion) only for true fallback rows with no journal entry. - Cast-now/Remove availability follows the journal's DpnsVoteTargetStatus instead of the old mirror-derived ScheduledVoteCastingStatus; pending Cast-now clicks are deduplicated locally until the journal catches up. - ScheduledVotesCleared now gets a real result-handling arm: routes through the hidden-Active-contests mechanism when appropriate, shows a success/information MessageBanner summarizing cleared vs. still-in- flight targets, and rebuilds the Scheduled Votes rows immediately instead of silently doing nothing (previously swallowed by a wildcard match arm on both app.rs and the screen's display_task_result). - Active-contests render path now builds an ActiveDpnsContestSnapshot once per construction/refresh (Arc-wrapped contests, poll ID computed once each) instead of cloning every ContestedName and rehashing its poll ID from three separate call sites every egui frame. QA follow-ups from independent review of 4058b04b: - remove_scheduled_dpns_vote(None, ...) β€” the actual production path used by DeleteScheduledVote β€” now has test coverage for both the unlocked (mirror deleted) and locked (refused) cases; the locked case now correctly refuses deletion when a journal lock exists. - Removed the redundant durable mirror-key scan in prune_terminal_operations that computed and immediately discarded a duplicate KV enumeration. Co-Authored-By: Codex Sol --- src/app.rs | 105 +++- src/context/dpns_vote_operations.rs | 87 ++- src/ui/dpns/dpns_contested_names_screen.rs | 655 +++++++++++---------- src/ui/state/dpns_contests.rs | 107 ++++ src/ui/state/dpns_vote_operations.rs | 253 +++++++- src/ui/state/mod.rs | 1 + 6 files changed, 884 insertions(+), 324 deletions(-) create mode 100644 src/ui/state/dpns_contests.rs diff --git a/src/app.rs b/src/app.rs index f1e7ca47b..100d74661 100644 --- a/src/app.rs +++ b/src/app.rs @@ -16,7 +16,10 @@ use crate::context::connection_status::{ConnectionStatus, OverallConnectionState use crate::context::feature_gate::FeatureGate; use crate::context::migration_status::{MigrationState, MigrationStep}; use crate::database::Database; -use crate::model::dpns_voting::{DpnsVoteOperation, DpnsVoteTargetStatus}; +use crate::model::dpns_voting::{ + DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome, DpnsVoteOperation, + DpnsVoteTargetStatus, +}; use crate::model::settings::AppSettings; use crate::ui::components::passphrase_modal; use crate::ui::components::secret_prompt_host::{ActivePrompt, EguiSecretPromptHost, QueuedPrompt}; @@ -350,6 +353,43 @@ fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, MessageType, bo (message, MessageType::Warning, counts.unconfirmed > 0) } +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); + let cleared_message = match cleared { + 0 => "No scheduled votes were removed.".to_owned(), + 1 => "1 scheduled vote was removed.".to_owned(), + count => format!("{count} scheduled votes were removed."), + }; + if in_flight == 0 { + let message_type = if cleared == 0 { + MessageType::Info + } else { + MessageType::Success + }; + return (cleared_message, message_type); + } + let retained_message = if in_flight == 1 { + "1 vote already in progress remains listed. Wait for it to finish before trying again." + } else { + return ( + format!( + "{cleared_message} {in_flight} votes already in progress remain listed. Wait for them to finish before trying again." + ), + MessageType::Info, + ); + }; + ( + format!("{cleared_message} {retained_message}"), + MessageType::Info, + ) +} + /// Action id for the SPV-sync block's "Continue in the background" escape button. /// SPV sync is **unbounded** β€” with no peers it stays Connecting/Syncing forever /// with no terminal signal β€” so a button-less hard block would trap the user @@ -385,6 +425,7 @@ fn dpns_result_needs_hidden_active_contests_route( BackendTaskSuccessResult::DpnsVoteOperationUpdated { .. } | BackendTaskSuccessResult::RefreshedDpnsContests | BackendTaskSuccessResult::ScheduledVoteSweepCompleted { .. } + | BackendTaskSuccessResult::ScheduledVotesCleared(_) ) && (selected != RootScreenType::RootScreenDPNSActiveContests || !screen_stack_is_empty) } @@ -2842,6 +2883,15 @@ impl App for AppState { self.visible_screen_mut().refresh(); } } + 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, context, @@ -3786,7 +3836,10 @@ mod contact_request_routing_tests { #[cfg(test)] mod dpns_result_routing_tests { use super::*; - use crate::model::dpns_voting::DpnsVoteOperationId; + use crate::model::dpns_voting::{ + DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome, DpnsScheduledVoteKey, + DpnsVoteOperationId, + }; #[test] fn correlated_vote_result_routes_when_active_contests_is_hidden() { @@ -3844,6 +3897,54 @@ mod dpns_result_routing_tests { &result, )); } + + #[test] + fn cleared_scheduled_votes_route_when_active_contests_is_hidden() { + assert!(dpns_result_needs_hidden_active_contests_route( + RootScreenType::RootScreenDPNSScheduledVotes, + true, + &BackendTaskSuccessResult::ScheduledVotesCleared(Vec::new()), + )); + } + + #[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), + ( + "1 scheduled vote was removed. 2 votes already in progress remain listed. Wait for them to finish before trying again.".to_owned(), + MessageType::Info, + ) + ); + assert_eq!( + scheduled_vote_clear_feedback(&outcomes[..1]), + ( + "1 scheduled vote was removed.".to_owned(), + MessageType::Success, + ) + ); + } } #[cfg(test)] diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index da3c05f13..c98a7ebfb 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -972,27 +972,19 @@ impl AppContext { .map(|outcome| (operation.id, outcome.status)) }), None => { - if let Some(operation_id) = lock_index.get(key) { - let operation = operations - .iter() - .find(|operation| operation.id == *operation_id) - .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; - let outcome = operation - .outcome(key) - .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; - Some((operation.id, outcome.status)) - } else { - operations - .iter() - .filter_map(|operation| { - operation - .outcome(key) - .filter(|outcome| !outcome.status.holds_lock()) - .map(|outcome| (operation.created_at, operation.id, outcome.status)) - }) - .max_by_key(|(created_at, operation_id, _)| (*created_at, *operation_id)) - .map(|(_, operation_id, status)| (operation_id, status)) + if lock_index.contains_key(key) { + return Err(TaskError::DpnsScheduledVoteAlreadyStarted); } + operations + .iter() + .filter_map(|operation| { + operation + .outcome(key) + .filter(|outcome| !outcome.status.holds_lock()) + .map(|outcome| (operation.created_at, operation.id, outcome.status)) + }) + .max_by_key(|(created_at, operation_id, _)| (*created_at, *operation_id)) + .map(|(_, operation_id, status)| (operation_id, status)) } }; @@ -1159,7 +1151,6 @@ impl AppContext { } } - let _surviving_mirror_keys = durable_scheduled_vote_keys(&kv, self.network)?; prune_terminal_operations(&kv, self.network)?; Ok(outcomes.into_values().map(|(_, outcome)| outcome).collect()) } @@ -1572,6 +1563,60 @@ mod tests { ); } + #[test] + fn legacy_removal_without_expected_operation_deletes_an_unlocked_mirror() { + 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 voter_id = Identifier::from([12; 32]); + let key = DpnsVoteTargetKey { + network: context.network, + voter_id, + vote_poll_id: Identifier::from([13; 32]), + }; + context + .insert_scheduled_votes(&[ScheduledDPNSVote { + contested_name: "legacy-only".to_owned(), + voter_id, + choice: ResourceVoteChoice::Lock, + unix_timestamp: 42, + executed_successfully: false, + }]) + .unwrap(); + + context + .remove_scheduled_dpns_vote(None, &key, "legacy-only") + .unwrap(); + + assert!(context.get_scheduled_votes().unwrap().is_empty()); + } + + #[test] + fn legacy_removal_without_expected_operation_preserves_a_locked_mirror() { + 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, 12, "locked-target"); + let key = scheduled.targets[0].target.key.clone(); + context + .insert_dpns_vote_operation(&mut scheduled, None) + .unwrap(); + context + .insert_scheduled_votes(&[scheduled_vote(&scheduled)]) + .unwrap(); + + assert!(matches!( + context + .remove_scheduled_dpns_vote(None, &key, "locked-target") + .expect_err("a current journal lock must preserve the mirror"), + TaskError::DpnsScheduledVoteAlreadyStarted + )); + assert_eq!(context.get_scheduled_votes().unwrap().len(), 1); + } + #[test] fn clear_all_cancels_pending_and_retains_every_in_flight_target() { let temp_dir = tempfile::tempdir().expect("tempdir"); diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index ba70fb4f4..6297c469c 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -1,6 +1,6 @@ use crate::wallet_backend::poison::MutexRecover; +use std::collections::BTreeSet; use std::sync::{Arc, Mutex}; -use tracing::error; use chrono::{DateTime, LocalResult, NaiveDate, NaiveTime, TimeZone, Timelike, Utc}; use chrono_humanize::HumanTime; @@ -12,7 +12,7 @@ use eframe::egui::{self, Button, Color32, ComboBox, Label, RichText, Ui}; use egui_extras::{Column, TableBuilder}; use crate::app::{AppAction, DesiredAppAction, scheduled_vote_sweep_is_quiet}; -use crate::backend_task::contested_names::{ContestedResourceTask, ScheduledDPNSVote}; +use crate::backend_task::contested_names::ContestedResourceTask; use crate::backend_task::error::TaskError; use crate::backend_task::identity::IdentityTask; use crate::backend_task::{BackendTask, BackendTaskContext}; @@ -20,8 +20,8 @@ use crate::context::AppContext; use crate::model::contested_name::{ContestState, ContestedName}; use crate::model::dpns::normalize_dpns_label; use crate::model::dpns_voting::{ - DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, - DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + DpnsCurrentVoteState, DpnsScheduledVoteKey, DpnsVoteOperation, DpnsVoteOperationId, + DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, }; use crate::model::qualified_identity::{DPNSNameInfo, QualifiedIdentity}; use crate::ui::components::component_trait::Component; @@ -34,7 +34,8 @@ use crate::ui::components::tools_subscreen_chooser_panel::add_tools_subscreen_ch use crate::ui::components::top_panel::{add_top_panel_with_global_nav, subdued_everyday_spec}; use crate::ui::components::{BannerHandle, MessageBanner, OptionBannerExt}; use crate::ui::identities::register_dpns_name_screen::RegisterDpnsNameSource; -use crate::ui::state::dpns_vote_operations::DpnsVoteOperationSnapshot; +use crate::ui::state::dpns_contests::{ActiveDpnsContestSnapshot, ActiveDpnsContestView}; +use crate::ui::state::dpns_vote_operations::{DpnsVoteOperationSnapshot, ScheduledDpnsVoteRow}; use crate::ui::state::dpns_vote_state::DpnsVoteStateSnapshot; use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; use crate::ui::{BackendTaskSuccessResult, MessageType, RootScreenType, ScreenLike, ScreenType}; @@ -153,6 +154,42 @@ fn target_status_label(status: DpnsVoteTargetStatus) -> &'static str { } } +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 + && matches!( + status, + DpnsVoteTargetStatus::Scheduled + | DpnsVoteTargetStatus::Rejected + | DpnsVoteTargetStatus::FailedBeforeSubmission + | DpnsVoteTargetStatus::Cancelled + | DpnsVoteTargetStatus::NotApplied + ) +} + +fn scheduled_vote_removal_task(row: &ScheduledDpnsVoteRow) -> ContestedResourceTask { + match &row.journal_target { + Some((operation_id, key)) => ContestedResourceTask::CancelScheduledDpnsVote { + operation_id: *operation_id, + key: key.clone(), + contested_name: row.vote.contested_name.clone(), + }, + None => ContestedResourceTask::DeleteScheduledVote( + row.vote.voter_id, + row.vote.contested_name.clone(), + ), + } +} + fn dpns_operation_id(context: &BackendTaskContext) -> Option { match context { BackendTaskContext::Dispatched { operation, .. } => dpns_operation_id(operation), @@ -187,15 +224,6 @@ pub enum VoteOption { 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, -} - #[derive(PartialEq)] pub enum VoteHandlingStatus { NotStarted, @@ -235,9 +263,9 @@ pub struct DPNSScreen { voting_identities: Vec, user_identities: Vec, contested_names: Arc>>, + active_contests: ActiveDpnsContestSnapshot, local_dpns_names: Arc>>, - pub scheduled_votes: Arc>>, - pub scheduled_vote_cast_in_progress: bool, + scheduled_votes: Arc>>, pub selected_votes: Vec, pub app_context: Arc, pending_backend_task: Option, @@ -245,6 +273,7 @@ pub struct DPNSScreen { vote_state: DpnsVoteStateSnapshot, vote_overlay: Option, pending_vote_operation: Option, + pending_scheduled_casts: BTreeSet, clear_vote_overlay_on_error: bool, scheduled_clear_dialog: Option<(bool, ConfirmationDialog)>, @@ -272,13 +301,34 @@ pub struct DPNSScreen { impl DPNSScreen { pub fn new(app_context: &Arc, dpns_subscreen: DPNSSubscreen) -> Self { + let vote_operations = + DpnsVoteOperationSnapshot::load(app_context).unwrap_or_else(|error| { + tracing::warn!( + ?error, + "Could not cache DPNS vote operations for the DPNS screen" + ); + DpnsVoteOperationSnapshot::default() + }); + let legacy_scheduled_votes = app_context.get_scheduled_votes().unwrap_or_default(); + let scheduled_votes = Arc::new(Mutex::new( + vote_operations.scheduled_vote_rows(&legacy_scheduled_votes), + )); + // 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::Active => Vec::new(), DPNSSubscreen::Past => app_context.all_contested_names().unwrap_or_default(), DPNSSubscreen::Owned => Vec::new(), DPNSSubscreen::ScheduledVotes => app_context.all_contested_names().unwrap_or_default(), })); + let active_contests = if dpns_subscreen == DPNSSubscreen::Active { + ActiveDpnsContestSnapshot::new( + app_context, + app_context.ongoing_contested_names().unwrap_or_default(), + ) + } else { + ActiveDpnsContestSnapshot::default() + }; let local_dpns_names = Arc::new(Mutex::new(match dpns_subscreen { DPNSSubscreen::Active => Vec::new(), @@ -287,41 +337,11 @@ impl DPNSScreen { 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::>(), - )); - 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 vote_operations = - DpnsVoteOperationSnapshot::load(app_context).unwrap_or_else(|error| { - tracing::warn!( - ?error, - "Could not cache DPNS vote operations for the DPNS screen" - ); - DpnsVoteOperationSnapshot::default() - }); - let vote_poll_ids = contested_names - .lock_recover() - .iter() - .filter_map(|contest| { - app_context - .dpns_vote_poll_id(&contest.normalized_contested_name) - .ok() - }) - .collect::>(); + let vote_poll_ids = active_contests.vote_poll_ids(); let voter_ids = voting_identities .iter() .map(|identity| identity.identity.id()) @@ -341,8 +361,9 @@ impl DPNSScreen { voting_identities, user_identities, contested_names, + active_contests, local_dpns_names, - scheduled_votes: scheduled_votes_with_status, + scheduled_votes, selected_votes: Vec::new(), app_context: app_context.clone(), sort_column: SortColumn::ContestedName, @@ -350,12 +371,12 @@ impl DPNSScreen { 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, vote_operations, vote_state, vote_overlay: None, pending_vote_operation: None, + pending_scheduled_casts: BTreeSet::new(), clear_vote_overlay_on_error: false, scheduled_clear_dialog: None, dpns_subscreen, @@ -535,15 +556,10 @@ impl DPNSScreen { ui.add_space(8.0); let filter = normalize_dpns_label(&self.active_filter_term); - let contests = self - .contested_names - .lock_recover() - .iter() - .cloned() - .collect::>(); + let contests = self.active_contests.contests(); let mut groups = [Vec::new(), Vec::new(), Vec::new()]; - for contest in contests { - let index = match self.contest_group(&contest) { + for contest in contests.iter() { + let index = match self.contest_group(contest.vote_poll_id) { ActiveContestGroup::NeedsVote => 0, ActiveContestGroup::Voted => 1, ActiveContestGroup::NotVotable => 2, @@ -554,7 +570,7 @@ impl DPNSScreen { let closes_within_day = groups[0] .iter() .filter(|contest| { - contest.end_time.is_some_and(|end_time| { + contest.contest.end_time.is_some_and(|end_time| { let remaining = end_time as i64 - Utc::now().timestamp_millis(); remaining > 0 && remaining <= chrono::Duration::days(1).num_milliseconds() }) @@ -573,6 +589,7 @@ impl DPNSScreen { for group in &mut groups { group.retain(|contest| { contest + .contest .normalized_contested_name .to_lowercase() .contains(&filter) @@ -615,11 +632,8 @@ impl DPNSScreen { }); } - fn contest_group(&self, contest: &ContestedName) -> ActiveContestGroup { - let Ok(poll_id) = self - .app_context - .dpns_vote_poll_id(&contest.normalized_contested_name) - else { + fn contest_group(&self, vote_poll_id: Option) -> ActiveContestGroup { + let Some(poll_id) = vote_poll_id else { return ActiveContestGroup::NotVotable; }; classify_vote_states( @@ -633,7 +647,7 @@ impl DPNSScreen { &mut self, ui: &mut Ui, title: &str, - contests: &[ContestedName], + contests: &[&ActiveDpnsContestView], default_open: bool, voting_enabled: bool, show_current_vote: bool, @@ -646,20 +660,23 @@ impl DPNSScreen { } for contest in contests { let contest_enabled = - voting_enabled && self.contest_has_available_target(contest); + voting_enabled && self.contest_has_available_target(contest.vote_poll_id); ui.add_enabled_ui(contest_enabled, |ui| { - self.render_contest_card(ui, contest, contest_enabled, show_current_vote); + self.render_contest_card( + ui, + contest.contest.as_ref(), + contest.vote_poll_id, + contest_enabled, + show_current_vote, + ); }); ui.add_space(8.0); } }); } - fn contest_has_available_target(&self, contest: &ContestedName) -> bool { - let Ok(vote_poll_id) = self - .app_context - .dpns_vote_poll_id(&contest.normalized_contested_name) - else { + fn contest_has_available_target(&self, vote_poll_id: Option) -> bool { + let Some(vote_poll_id) = vote_poll_id else { return false; }; self.voting_identities.iter().any(|identity| { @@ -678,11 +695,8 @@ impl DPNSScreen { }) } - fn proved_vote_for_contest(&self, contest: &ContestedName) -> ProvedVoteSummary { - let Ok(poll_id) = self - .app_context - .dpns_vote_poll_id(&contest.normalized_contested_name) - else { + fn proved_vote_for_contest(&self, vote_poll_id: Option) -> ProvedVoteSummary { + let Some(poll_id) = vote_poll_id else { return ProvedVoteSummary::None; }; proved_vote_summary( @@ -711,6 +725,7 @@ impl DPNSScreen { &mut self, ui: &mut Ui, contest: &ContestedName, + vote_poll_id: Option, voting_enabled: bool, show_current_vote: bool, ) { @@ -721,7 +736,7 @@ impl DPNSScreen { .find(|vote| vote.contested_name == contest.normalized_contested_name) .map(|vote| vote.vote_choice); let proved = if show_current_vote { - self.proved_vote_for_contest(contest) + self.proved_vote_for_contest(vote_poll_id) } else { ProvedVoteSummary::None }; @@ -1300,9 +1315,8 @@ impl DPNSScreen { let guard = self.scheduled_votes.lock_recover(); guard.clone() }; - // Sort by contested_name or time sorted_votes.sort_by(|a, b| { - let order = a.0.contested_name.cmp(&b.0.contested_name); + let order = a.vote.contested_name.cmp(&b.vote.contested_name); if self.sort_order == SortOrder::Descending { order.reverse() } else { @@ -1358,47 +1372,40 @@ impl DPNSScreen { }); }) .body(|mut body| { - for vote in sorted_votes.iter_mut() { - let operation_status = self - .app_context - .dpns_vote_poll_id(&vote.0.contested_name) - .ok() - .and_then(|vote_poll_id| { - self.vote_operations - .target_status(&DpnsVoteTargetKey { - network: self.app_context.network(), - voter_id: vote.0.voter_id, - vote_poll_id, - }) - }); + for scheduled_row in &sorted_votes { + let vote = &scheduled_row.vote; + let pending_key = DpnsScheduledVoteKey { + network: scheduled_row + .journal_target + .as_ref() + .map_or(self.app_context.network(), |(_, key)| key.network), + voter_id: vote.voter_id, + contested_name: vote.contested_name.clone(), + }; body.row(25.0, |mut row| { - // Contested name row.col(|ui| { - ui.add(Label::new(format!("{}.dash", vote.0.contested_name))); + ui.add(Label::new(format!("{}.dash", vote.contested_name))); }); - // Voter row.col(|ui| { let voter = self .voting_identities .iter() - .find(|identity| identity.identity.id() == vote.0.voter_id) + .find(|identity| identity.identity.id() == vote.voter_id) .and_then(|identity| identity.alias.clone()) - .unwrap_or_else(|| short_identifier(vote.0.voter_id)); + .unwrap_or_else(|| short_identifier(vote.voter_id)); ui.add(Label::new(voter)); }); - // Choice row.col(|ui| { let candidate_name = - self.candidate_name(&vote.0.contested_name, vote.0.choice); + self.candidate_name(&vote.contested_name, vote.choice); let display_text = - vote_choice_label(vote.0.choice, candidate_name.as_deref()); + vote_choice_label(vote.choice, candidate_name.as_deref()); 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) + Utc.timestamp_millis_opt(vote.unix_timestamp as i64) { let iso = dt.format("%Y-%m-%d %H:%M:%S").to_string(); let rel_time = HumanTime::from(dt).to_string(); @@ -1419,129 +1426,55 @@ impl DPNSScreen { ); } }); - // Status row.col(|ui| { let dark_mode = ui.style().visuals.dark_mode; - if matches!( - operation_status, - Some(DpnsVoteTargetStatus::Queued) - | Some(DpnsVoteTargetStatus::Submitting) - | Some(DpnsVoteTargetStatus::Confirming) - ) { - ui.label( - RichText::new("Submitting…") - .color(DashColors::text_primary(dark_mode)), - ); - return; - } - if operation_status == Some(DpnsVoteTargetStatus::Unconfirmed) { - ui.colored_label( - DashColors::warning_color(dark_mode), - "Checking result", - ); - return; - } - 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( - DashColors::error_color(dark_mode), - "Failed", - ); - } - ScheduledVoteCastingStatus::Completed => { - ui.colored_label( - DashColors::success_color(dark_mode), - "Cast", - ); - } - } + ui.label( + RichText::new(target_status_label(scheduled_row.status)) + .color(DashColors::text_primary(dark_mode)), + ); }); - // Actions row.col(|ui| { - let target_is_busy = matches!( - operation_status, - Some(DpnsVoteTargetStatus::Queued) - | Some(DpnsVoteTargetStatus::Submitting) - | Some(DpnsVoteTargetStatus::Confirming) - | Some(DpnsVoteTargetStatus::Unconfirmed) - ); + let remove_enabled = + scheduled_vote_remove_enabled(scheduled_row.status); if ui - .add_enabled(!target_is_busy, Button::new("Remove")) + .add_enabled(remove_enabled, Button::new("Remove")) .disabled_tooltip( "This scheduled vote cannot be removed while its result is being checked.", ) .clicked() { - action = - AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::DeleteScheduledVote( - vote.0.voter_id, - vote.0.contested_name.clone(), - ), - )); + action = AppAction::BackendTask( + BackendTask::ContestedResourceTask( + scheduled_vote_removal_task(scheduled_row), + ), + ); } - // 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 - ) && !target_is_busy; - - let cast_button = if cast_button_enabled { - Button::new("Cast now") - } else { - Button::new("Cast now").sense(egui::Sense::hover()) - }; - - if ui.add(cast_button).clicked() && cast_button_enabled { - self.scheduled_vote_cast_in_progress = true; - vote.1 = ScheduledVoteCastingStatus::InProgress; - - // 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 + let cast_button_enabled = scheduled_vote_cast_enabled( + scheduled_row.status, + self.pending_scheduled_casts.contains(&pending_key), + ); + if ui + .add_enabled(cast_button_enabled, Button::new("Cast now")) + .clicked() + && let Some(found) = self + .voting_identities .iter() - .find(|i| i.identity.id() == vote.0.voter_id) - { + .find(|identity| { + identity.identity.id() == vote.voter_id + }) + .cloned() + { + self.pending_scheduled_casts + .insert(pending_key.clone()); action = AppAction::BackendTask( - BackendTask::ContestedResourceTask( - ContestedResourceTask::CastScheduledVote( - vote.0.clone(), - Box::new(found.clone()), - ), + BackendTask::ContestedResourceTask( + ContestedResourceTask::CastScheduledVote( + vote.clone(), + Box::new(found), ), - ); - show_cast_overlay = true; - } + ), + ); + show_cast_overlay = true; } }); }); @@ -1582,6 +1515,19 @@ impl DPNSScreen { let ResourceVoteChoice::TowardsIdentity(candidate_id) = choice else { return None; }; + if let Some(candidate_name) = self + .active_contests + .contest(contested_name) + .and_then(|contest| contest.contestants.as_ref()) + .and_then(|contestants| { + contestants + .iter() + .find(|candidate| candidate.id == candidate_id) + }) + .map(|candidate| candidate.name.clone()) + { + return Some(candidate_name); + } self.contested_names .lock_recover() .iter() @@ -1595,6 +1541,12 @@ impl DPNSScreen { .map(|candidate| candidate.name.clone()) } + fn rebuild_scheduled_vote_rows(&mut self) { + let legacy_votes = self.app_context.get_scheduled_votes().unwrap_or_default(); + *self.scheduled_votes.lock_recover() = + self.vote_operations.scheduled_vote_rows(&legacy_votes); + } + fn show_review_and_cast_window(&mut self, ui: &mut Ui) -> AppAction { let mut action = AppAction::None; @@ -2108,75 +2060,40 @@ impl DPNSScreen { // --------------------------- impl ScreenLike for DPNSScreen { fn refresh(&mut self) { - self.scheduled_vote_cast_in_progress = false; if let Err(error) = self.vote_operations.refresh(&self.app_context) { tracing::warn!(?error, "Could not refresh cached DPNS vote operations"); } - 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(); + self.rebuild_scheduled_vote_rows(); match self.dpns_subscreen { DPNSSubscreen::Active => { - *contested_names = self - .app_context - .ongoing_contested_names() - .unwrap_or_default(); + self.active_contests = ActiveDpnsContestSnapshot::new( + &self.app_context, + self.app_context + .ongoing_contested_names() + .unwrap_or_default(), + ); } DPNSSubscreen::Past => { - *contested_names = self.app_context.all_contested_names().unwrap_or_default(); + *self.contested_names.lock_recover() = + self.app_context.all_contested_names().unwrap_or_default(); } DPNSSubscreen::Owned => { - *dpns_names = self.app_context.local_dpns_names().unwrap_or_default(); + *self.local_dpns_names.lock_recover() = + self.app_context.local_dpns_names().unwrap_or_default(); } DPNSSubscreen::ScheduledVotes => { - *contested_names = self.app_context.all_contested_names().unwrap_or_default(); - 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(); + *self.contested_names.lock_recover() = + self.app_context.all_contested_names().unwrap_or_default(); } } - drop(contested_names); - drop(dpns_names); - drop(scheduled_votes); let voter_ids = self .voting_identities .iter() .map(|identity| identity.identity.id()) .collect::>(); - let poll_ids = self - .contested_names - .lock_recover() - .iter() - .filter_map(|contest| { - self.app_context - .dpns_vote_poll_id(&contest.normalized_contested_name) - .ok() - }) - .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) @@ -2214,6 +2131,7 @@ impl ScreenLike for DPNSScreen { } fn display_task_error(&mut self, error: &TaskError) -> bool { + self.pending_scheduled_casts.clear(); if self.clear_vote_overlay_on_error { self.vote_overlay.take_and_clear(); self.pending_vote_operation = None; @@ -2225,30 +2143,14 @@ impl ScreenLike for DPNSScreen { "Could not refresh DPNS voting state after a task error" ); } - 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 + self.rebuild_scheduled_vote_rows(); + scheduled_vote_sweep_is_quiet(error) } fn display_task_result(&mut self, backend_task_success_result: BackendTaskSuccessResult) { match backend_task_success_result { BackendTaskSuccessResult::DpnsVoteOperationUpdated { operation_id, .. } => { + self.pending_scheduled_casts.clear(); if let Err(error) = self.vote_state.reload(&self.app_context) { tracing::warn!( ?error, @@ -2267,23 +2169,29 @@ impl ScreenLike for DPNSScreen { self.bulk_vote_handling_status = VoteHandlingStatus::Completed; } } + 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(); } - BackendTaskSuccessResult::ScheduledVotesInProgress(votes) => { + BackendTaskSuccessResult::ScheduledVotesInProgress(_) => { if let Err(error) = self.vote_operations.refresh(&self.app_context) { tracing::warn!(?error, "Could not refresh scheduled-vote operation state"); } - // 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; - } - } + self.rebuild_scheduled_vote_rows(); + } + BackendTaskSuccessResult::ScheduledVotesCleared(_) => { + self.pending_scheduled_casts.clear(); + 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(); } BackendTaskSuccessResult::RefreshedDpnsContests | BackendTaskSuccessResult::RefreshedOwnedDpnsNames => { @@ -2429,7 +2337,7 @@ impl ScreenLike for DPNSScreen { // Render sub-screen match self.dpns_subscreen { DPNSSubscreen::Active => { - let has_any = !self.contested_names.lock_recover().is_empty(); + let has_any = !self.active_contests.is_empty(); if self.voting_identities.is_empty() { inner_action |= self.render_no_voting_nodes(ui); } else if has_any { @@ -2528,6 +2436,7 @@ impl ScreenLike for DPNSScreen { #[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; @@ -2556,6 +2465,14 @@ mod tests { (ctx, temp_dir) } + fn pending_scheduled_key(context: &AppContext) -> DpnsScheduledVoteKey { + DpnsScheduledVoteKey { + network: context.network(), + voter_id: Identifier::from([1; 32]), + contested_name: "pending".to_owned(), + } + } + #[test] fn vote_submission_overlay_clears_when_the_operation_finishes() { let (ctx, _temp_dir) = offline_ctx(); @@ -2578,6 +2495,9 @@ mod tests { crate::ui::components::progress_overlay::ProgressOverlay::has_global(ctx.egui_ctx()) ); + screen + .pending_scheduled_casts + .insert(pending_scheduled_key(&ctx)); screen.display_task_result(BackendTaskSuccessResult::DpnsVoteOperationUpdated { network: ctx.network(), operation_id: DpnsVoteOperationId::from_bytes([7; 16]), @@ -2586,6 +2506,7 @@ mod tests { assert!( !crate::ui::components::progress_overlay::ProgressOverlay::has_global(ctx.egui_ctx()) ); + assert!(screen.pending_scheduled_casts.is_empty()); } #[test] @@ -2709,9 +2630,11 @@ mod tests { }), }; - screen.scheduled_vote_cast_in_progress = true; + screen + .pending_scheduled_casts + .insert(pending_scheduled_key(&ctx)); assert!(screen.display_task_error(&error)); - assert!(!screen.scheduled_vote_cast_in_progress); + assert!(screen.pending_scheduled_casts.is_empty()); } #[test] @@ -2719,9 +2642,11 @@ mod tests { let (ctx, _temp_dir) = offline_ctx(); let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::ScheduledVotes); - screen.scheduled_vote_cast_in_progress = true; + screen + .pending_scheduled_casts + .insert(pending_scheduled_key(&ctx)); assert!(!screen.display_task_error(&TaskError::ScheduledVoteResultUnavailable)); - assert!(!screen.scheduled_vote_cast_in_progress); + assert!(screen.pending_scheduled_casts.is_empty()); let sweep_error = TaskError::ScheduledVoteSweepFailed { network: Network::Regtest, @@ -2729,7 +2654,9 @@ mod tests { }; assert!(!screen.display_task_error(&sweep_error)); - screen.scheduled_vote_cast_in_progress = true; + screen + .pending_scheduled_casts + .insert(pending_scheduled_key(&ctx)); let exhausted_error = TaskError::ScheduledVoteSweepAllAddressesExhausted { network: Network::Regtest, source: Box::new(TaskError::DapiNoAddresses { @@ -2739,6 +2666,136 @@ mod tests { }), }; assert!(!screen.display_task_error(&exhausted_error)); - assert!(!screen.scheduled_vote_cast_in_progress); + assert!(screen.pending_scheduled_casts.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_or_legacy_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: Some((operation_id, key.clone())), + status: DpnsVoteTargetStatus::Scheduled, + }; + let legacy_row = ScheduledDpnsVoteRow { + vote, + journal_target: None, + status: DpnsVoteTargetStatus::Scheduled, + }; + + assert!(matches!( + scheduled_vote_removal_task(&journal_row), + ContestedResourceTask::CancelScheduledDpnsVote { + operation_id: id, + key: task_key, + contested_name, + } if id == operation_id && task_key == key && contested_name == "dispatch" + )); + assert!(matches!( + scheduled_vote_removal_task(&legacy_row), + ContestedResourceTask::DeleteScheduledVote(voter_id, contested_name) + if voter_id == Identifier::from([32; 32]) && contested_name == "dispatch" + )); + } + + #[test] + fn clear_all_result_rebuilds_scheduled_rows_immediately() { + 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_id = Identifier::from([21; 32]); + let mut operation = DpnsVoteOperation::new(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"); + ctx.insert_scheduled_votes(&[ScheduledDPNSVote { + contested_name: "clear-me".to_owned(), + voter_id, + choice: ResourceVoteChoice::Lock, + unix_timestamp: 42, + executed_successfully: false, + }]) + .expect("insert compatibility mirror"); + let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::ScheduledVotes); + 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/state/dpns_contests.rs b/src/ui/state/dpns_contests.rs new file mode 100644 index 000000000..aaa49f2b8 --- /dev/null +++ b/src/ui/state/dpns_contests.rs @@ -0,0 +1,107 @@ +//! 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 for the Active contests screen. +#[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() + } + + pub(crate) fn contest(&self, contested_name: &str) -> Option<&ContestedName> { + self.contests + .iter() + .find(|view| view.contest.normalized_contested_name == contested_name) + .map(|view| view.contest.as_ref()) + } + + 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_operations.rs b/src/ui/state/dpns_vote_operations.rs index 46949dce8..0ebcc49a7 100644 --- a/src/ui/state/dpns_vote_operations.rs +++ b/src/ui/state/dpns_vote_operations.rs @@ -1,13 +1,21 @@ //! Per-screen DPNS vote-operation snapshot for immediate-mode render paths. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; +use crate::backend_task::contested_names::ScheduledDPNSVote; use crate::backend_task::error::TaskError; use crate::context::AppContext; use crate::model::dpns_voting::{ - DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, DpnsVoteTargetStatus, + DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, }; +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct ScheduledDpnsVoteRow { + pub vote: ScheduledDPNSVote, + pub journal_target: Option<(DpnsVoteOperationId, DpnsVoteTargetKey)>, + pub status: DpnsVoteTargetStatus, +} + #[derive(Debug, Clone, Default)] pub struct DpnsVoteOperationSnapshot { operations: Vec, @@ -43,6 +51,75 @@ impl DpnsVoteOperationSnapshot { self.loaded } + pub(crate) fn scheduled_vote_rows( + &self, + legacy_votes: &[ScheduledDPNSVote], + ) -> Vec { + let mut journal_rows = BTreeMap::< + (dash_sdk::platform::Identifier, String), + ((u64, usize), ScheduledDpnsVoteRow), + >::new(); + for (operation_index, operation) in self.operations.iter().enumerate() { + for outcome in &operation.targets { + let VoteTiming::Scheduled(timestamp) = outcome.target.timing else { + continue; + }; + let pair = ( + outcome.target.key.voter_id, + outcome.target.contested_name.clone(), + ); + let rank = (operation.created_at, operation_index); + if journal_rows + .get(&pair) + .is_some_and(|(current_rank, _)| *current_rank > rank) + { + continue; + } + journal_rows.insert( + pair, + ( + rank, + 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: Some((operation.id, outcome.target.key.clone())), + status: outcome.status, + }, + ), + ); + } + } + + let journal_pairs = journal_rows.keys().cloned().collect::>(); + let mut rows = journal_rows + .into_values() + .map(|(_, row)| row) + .collect::>(); + rows.extend( + legacy_votes + .iter() + .filter(|vote| { + !journal_pairs.contains(&(vote.voter_id, vote.contested_name.clone())) + }) + .map(|vote| ScheduledDpnsVoteRow { + vote: vote.clone(), + journal_target: None, + status: if vote.executed_successfully { + DpnsVoteTargetStatus::Confirmed + } else { + DpnsVoteTargetStatus::Scheduled + }, + }), + ); + rows + } + fn replace(&mut self, operations: Vec) { self.target_statuses = operations .iter() @@ -58,6 +135,7 @@ impl DpnsVoteOperationSnapshot { #[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; @@ -100,4 +178,175 @@ mod tests { assert_eq!(snapshot.operations(), &[live, terminal]); assert!(snapshot.is_loaded()); } + + fn scheduled_operation( + created_at: u64, + status: DpnsVoteTargetStatus, + choice: ResourceVoteChoice, + timestamp: u64, + ) -> DpnsVoteOperation { + let mut operation = DpnsVoteOperation::new(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 legacy_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_prefer_the_newest_journal_outcome_over_legacy_data() { + 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 legacy = legacy_vote( + Identifier::from([7; 32]), + "alice", + ResourceVoteChoice::Lock, + 999, + true, + ); + let mut snapshot = DpnsVoteOperationSnapshot::default(); + snapshot.replace(vec![older, newer]); + + let rows = snapshot.scheduled_vote_rows(&[legacy]); + + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].journal_target, Some((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); + } + + #[test] + fn scheduled_rows_use_later_persisted_order_when_created_times_match() { + let first = scheduled_operation( + 10, + DpnsVoteTargetStatus::Rejected, + ResourceVoteChoice::Lock, + 100, + ); + let second = scheduled_operation( + 10, + DpnsVoteTargetStatus::Cancelled, + ResourceVoteChoice::Abstain, + 200, + ); + let expected_id = second.id; + let mut snapshot = DpnsVoteOperationSnapshot::default(); + snapshot.replace(vec![first, second]); + + let rows = snapshot.scheduled_vote_rows(&[]); + + assert_eq!(rows.len(), 1); + assert_eq!( + rows[0].journal_target.as_ref().map(|(id, _)| *id), + Some(expected_id) + ); + assert_eq!(rows[0].status, DpnsVoteTargetStatus::Cancelled); + assert_eq!(rows[0].vote.unix_timestamp, 200); + } + + #[test] + fn scheduled_rows_derive_compatibility_execution_only_from_confirmed_status() { + 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); + } + + #[test] + fn scheduled_rows_append_only_unseen_legacy_pairs() { + let journal = scheduled_operation( + 10, + DpnsVoteTargetStatus::Scheduled, + ResourceVoteChoice::Lock, + 100, + ); + let voter_id = journal.targets[0].target.key.voter_id; + let mut snapshot = DpnsVoteOperationSnapshot::default(); + snapshot.replace(vec![journal]); + let legacy = [ + legacy_vote(voter_id, "alice", ResourceVoteChoice::Abstain, 999, true), + legacy_vote( + Identifier::from([9; 32]), + "confirmed-legacy", + ResourceVoteChoice::Lock, + 300, + true, + ), + legacy_vote( + Identifier::from([10; 32]), + "pending-legacy", + ResourceVoteChoice::Abstain, + 400, + false, + ), + ]; + + let rows = snapshot.scheduled_vote_rows(&legacy); + + assert_eq!(rows.len(), 3); + assert!(rows.iter().any(|row| { + row.vote.contested_name == "alice" + && row.status == DpnsVoteTargetStatus::Scheduled + && row.journal_target.is_some() + })); + assert!(rows.iter().any(|row| { + row.vote.contested_name == "confirmed-legacy" + && row.status == DpnsVoteTargetStatus::Confirmed + && row.journal_target.is_none() + })); + assert!(rows.iter().any(|row| { + row.vote.contested_name == "pending-legacy" + && row.status == DpnsVoteTargetStatus::Scheduled + && row.journal_target.is_none() + })); + } } diff --git a/src/ui/state/mod.rs b/src/ui/state/mod.rs index b744f286f..ddaac43e0 100644 --- a/src/ui/state/mod.rs +++ b/src/ui/state/mod.rs @@ -8,6 +8,7 @@ pub mod account_summary; pub mod avatar_cache; pub mod contacts_view; +pub mod dpns_contests; pub mod dpns_vote_operations; pub mod dpns_vote_state; pub mod global_nav; From fcbc1dc41a59945d075756f32ab78fafe7b5a7de Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 27 Jul 2026 11:03:22 +0000 Subject: [PATCH 036/194] fix(dpns): unstick the Review and cast window after a failed submission MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DPNSScreen::display_task_error() cleared the progress overlay and the pending operation id when a vote submission failed, but left bulk_vote_handling_status on CastingVotes/SchedulingVotes. That status is what show_review_and_cast_window() uses as operation_in_progress, and it disables the Submit button *and* the Cancel button; the egui::Window has no close control either. Only display_task_result() ever moved the status out of the in-flight state, so a failed submission left the modal frozen on "Submitting votes…" with no way to retry, cancel, or dismiss it β€” and the state survives navigating away and back, since the screen instance is kept in AppState::main_screens. Reproduces whenever the backend task returns Err after dispatch, e.g. DpnsCurrentVoteUnavailable: the screen's cached proved-vote snapshot is fresh enough to build targets, then the backend's pre-submission refresh_dpns_vote_states() fails against an unreachable DAPI. Move the status to Failed() alongside the existing overlay cleanup, gated on the same clear_vote_overlay_on_error ownership check so an unrelated task error cannot disturb a submission still in flight. The window already renders Failed inline and re-enables both buttons, and TaskError's Display is the user-facing text by convention. Adds failed_submission_releases_the_review_window (covers both in-flight statuses) and unrelated_error_keeps_the_pending_submission_in_progress. Co-Authored-By: Claude Opus 5 --- src/ui/dpns/dpns_contested_names_screen.rs | 76 ++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 6297c469c..58409fbfb 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -2136,6 +2136,16 @@ impl ScreenLike for DPNSScreen { self.vote_overlay.take_and_clear(); self.pending_vote_operation = None; self.clear_vote_overlay_on_error = false; + // The review window disables both Submit and Cancel while a + // submission is in flight, so a failed submission must leave that + // state here. Otherwise the window stays on "Submitting votes…" + // with no way to retry or close it. + if matches!( + self.bulk_vote_handling_status, + VoteHandlingStatus::CastingVotes | VoteHandlingStatus::SchedulingVotes + ) { + self.bulk_vote_handling_status = VoteHandlingStatus::Failed(error.to_string()); + } } if let Err(refresh_error) = self.vote_operations.refresh(&self.app_context) { tracing::warn!( @@ -2754,6 +2764,72 @@ mod tests { )); } + /// A failed submission must release the review window's in-flight state. + /// While it is held, the window disables Submit *and* Cancel and offers no + /// close control, so a stuck status leaves the user with no way out. + #[test] + fn failed_submission_releases_the_review_window() { + let (ctx, _temp_dir) = offline_ctx(); + let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); + let operation_id = DpnsVoteOperationId::from_bytes([11; 16]); + let context = BackendTaskContext::DpnsVoteOperation { + network: ctx.network(), + operation_id, + }; + let error = TaskError::DpnsCurrentVoteUnavailable; + + for in_progress in [ + VoteHandlingStatus::CastingVotes, + VoteHandlingStatus::SchedulingVotes, + ] { + screen.show_bulk_schedule_popup = true; + screen.bulk_vote_handling_status = in_progress; + screen.pending_vote_operation = Some(operation_id); + screen.raise_vote_overlay(ctx.egui_ctx(), "Submitting the selected votes…"); + + screen.display_backend_task_error(&context, &error); + screen.display_task_error(&error); + + assert!( + !crate::ui::components::progress_overlay::ProgressOverlay::has_global( + ctx.egui_ctx() + ) + ); + assert_eq!(screen.pending_vote_operation, None); + assert!( + screen.bulk_vote_handling_status == VoteHandlingStatus::Failed(error.to_string()), + "the review window must leave its in-flight state so Submit and Cancel work again" + ); + } + } + + /// An error belonging to a different operation must not disturb the review + /// window of 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, DPNSSubscreen::Active); + let error = TaskError::DpnsCurrentVoteUnavailable; + screen.show_bulk_schedule_popup = true; + screen.bulk_vote_handling_status = VoteHandlingStatus::CastingVotes; + 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])) + ); + assert!(screen.bulk_vote_handling_status == VoteHandlingStatus::CastingVotes); + } + #[test] fn clear_all_result_rebuilds_scheduled_rows_immediately() { let temp_dir = tempfile::tempdir().expect("tempdir"); From cbb4afa09122f8ac5cf936bcf12fde002ce71f06 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Sat, 1 Aug 2026 09:47:33 +0000 Subject: [PATCH 037/194] fix(dpns): make the vote review honest, Remove final, and keyless nodes blocked Three blocking defects in the unified DPNS voting flow. Review and cast lied about what it would send. It printed one bullet per contest and a raw node count, so a multi-node batch never showed its real node x contest targets, the choice already on chain, the per-target timing, or the targets DpnsVoteOperation::new silently drops as no-ops after Submit. The sheet and the submit click now share one resolved plan, so the sheet cannot promise something other than what is sent: every retained target is listed with node, contest, requested choice, current choice and timing, the skipped no-op count is stated, the headline counts the effective targets, and Submit is disabled when nothing would be submitted. No-op suppression now has a single definition, DpnsVoteTarget::is_no_op, shared by the review and the operation; the operation still receives the unfiltered list so its no_op_count keeps driving the post-submit feedback. Remove on a scheduled vote did not remove it. The cancellation write was durable and correct, but scheduled_vote_rows projected every scheduled-timing outcome back into the table including Cancelled, so the row returned on the next refresh with a second Remove button that did nothing. The projection now honours the cancellation and drops the row, while keeping the target's pair in the legacy-suppression set so a mirror row that outlived a best-effort delete cannot resurrect it. Pruning the journal could not have fixed this: a bulk schedule is one operation with many targets, so removing one row leaves the operation incomplete and unprunable. Clear All keeps its bulk prune. A masternode loaded without its voting key reached the composer and only failed at submit time with NoVotingIdentity, because the gate filtered on identity type alone. The DPNS surfaces now keep only identities that satisfy the submit path (QualifiedIdentity::can_cast_masternode_vote), so a read-only node lands on the actionable "no voting key" state with Load a masternode before any vote is composed. VOTE-FR-024, VOTE-FR-025 and VOTE-TC-013 of the DPNS voting experience design. Co-Authored-By: Claude Opus 5 --- docs/user-stories.md | 4 +- src/model/dpns_voting.rs | 13 +- src/model/qualified_identity/mod.rs | 22 + src/ui/dpns/dpns_contested_names_screen.rs | 626 ++++++++++++++++++--- src/ui/state/dpns_vote_operations.rs | 79 ++- 5 files changed, 649 insertions(+), 95 deletions(-) diff --git a/docs/user-stories.md b/docs/user-stories.md index edd1709f2..9c05f8fdf 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -755,6 +755,7 @@ As a masternode operator, I want to schedule votes for later execution so that I - Set vote to be cast at a future time. - View and manage scheduled votes under DPNS β†’ Scheduled votes, which remains available in the persistent DPNS subnavigation. - Scheduled and immediate votes share the same target locks and result states. +- Removing a scheduled vote takes it off the list for good; it does not come back on the next refresh. - An ambiguous result remains visible for checking and is never automatically rebroadcast. ### DPN-007: Batch voting across contests [Implemented] @@ -764,8 +765,9 @@ As a masternode operator, I want to apply voting choices across multiple contest - Review and cast defaults to all loaded voting nodes and Cast now. - The advanced per-node disclosure can set each node to Cast now, Schedule, or Do not use this node. -- When no loaded node has a voting key, Active contests shows an actionable Load a masternode state instead of vote controls. +- When no loaded node has a voting key, Active contests shows an actionable Load a masternode state instead of vote controls. A masternode loaded without its voting key is not a voting node, so it reaches that state instead of the composer. - Per-node timing overrides and multi-contest selections create exact node Γ— contest targets. +- Review and cast lists each of those targets with its node, contest, requested choice, current choice, and timing, and reports how many targets it skipped because the node already holds the requested choice. - Immediate and scheduled targets submitted together belong to one operation. ### DPN-010: Recover an ambiguous vote result [Implemented] diff --git a/src/model/dpns_voting.rs b/src/model/dpns_voting.rs index 485faead5..3c6c646a7 100644 --- a/src/model/dpns_voting.rs +++ b/src/model/dpns_voting.rs @@ -227,6 +227,17 @@ pub struct DpnsVoteTarget { 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 { @@ -297,7 +308,7 @@ impl DpnsVoteOperation { let original_len = targets.len(); let targets = targets .into_iter() - .filter(|target| target.current_choice != Some(target.requested_choice)) + .filter(|target| !target.is_no_op()) .map(|target| { let status = match target.timing { VoteTiming::Now => DpnsVoteTargetStatus::Queued, diff --git a/src/model/qualified_identity/mod.rs b/src/model/qualified_identity/mod.rs index 56a5161ad..31cf9e4f1 100644 --- a/src/model/qualified_identity/mod.rs +++ b/src/model/qualified_identity/mod.rs @@ -579,6 +579,18 @@ impl QualifiedIdentity { .map_err(|e| format!("Failed to decode QualifiedIdentity: {}", e)) } + /// Whether a masternode vote signed by this identity can reach Platform. + /// + /// True only with a loaded voter identity and its public key β€” the exact + /// precondition the vote submission path enforces. Stricter than + /// [`Self::masternode_key_presence`]'s `voting` flag, which also reports a + /// bare [`Purpose::VOTING`] main key that the vote path cannot sign with. + /// Voting surfaces must gate on this, so a read-only node is refused before + /// the operator composes a vote rather than at submission time. + pub fn can_cast_masternode_vote(&self) -> bool { + self.associated_voter_identity.is_some() + } + /// Which masternode/evonode key roles are loaded for this identity. /// /// Voting presence is signalled by a loaded voter identity @@ -2171,6 +2183,16 @@ 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 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()); + } } #[cfg(test)] diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 58409fbfb..ee2fc9a40 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -190,6 +190,106 @@ fn scheduled_vote_removal_task(row: &ScheduledDpnsVoteRow) -> ContestedResourceT } } +/// 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) -> Vec { + app_context + .load_local_voting_identities() + .unwrap_or_default() + .into_iter() + .filter(QualifiedIdentity::can_cast_masternode_vote) + .collect() +} + +/// One reviewed node Γ— contest line, carrying the timing text the operator chose. +struct ReviewEntry { + target: DpnsVoteTarget, + timing_label: String, +} + +impl ReviewEntry { + fn node_label(&self) -> String { + self.target + .voter_alias + .clone() + .unwrap_or_else(|| short_identifier(self.target.key.voter_id)) + } +} + +/// Exactly what a submit click would send, resolved before the review is shown. +struct ReviewPlan { + entries: Vec, + voters: Vec, +} + +impl ReviewPlan { + /// The targets that will really be submitted, no-op targets removed. + fn effective(&self) -> impl Iterator { + self.entries.iter().filter(|entry| !entry.target.is_no_op()) + } + + fn effective_count(&self) -> usize { + self.effective().count() + } + + fn no_op_count(&self) -> usize { + self.entries.len() - self.effective_count() + } + + fn node_count(&self) -> usize { + self.effective() + .map(|entry| entry.target.key.voter_id) + .collect::>() + .len() + } + + fn has_immediate(&self) -> bool { + self.effective() + .any(|entry| matches!(entry.target.timing, VoteTiming::Now)) + } + + fn has_scheduled(&self) -> bool { + self.effective() + .any(|entry| matches!(entry.target.timing, VoteTiming::Scheduled(_))) + } + + fn changes_an_existing_vote(&self) -> bool { + self.effective() + .any(|entry| entry.target.current_choice.is_some()) + } +} + +fn review_headline(effective_count: usize, node_count: usize) -> String { + format!("Votes to submit ({effective_count}) from your nodes ({node_count}).") +} + +fn review_target_line( + node: &str, + name: &str, + requested: &str, + current: &str, + timing: &str, +) -> String { + format!("β€’ {node} β†’ {name}.dash: {requested}. Current vote: {current}. {timing}.") +} + +fn review_skipped_line(no_op_count: usize) -> String { + format!("Targets skipped because the node already has that choice ({no_op_count}).") +} + +fn review_current_choice_label( + current: Option, + candidate_name: Option<&str>, +) -> String { + match current { + Some(choice) => review_vote_choice_label(choice, candidate_name), + None => "Not voted yet".to_owned(), + } +} + fn dpns_operation_id(context: &BackendTaskContext) -> Option { match context { BackendTaskContext::Dispatched { operation, .. } => dpns_operation_id(operation), @@ -337,9 +437,7 @@ impl DPNSScreen { DPNSSubscreen::ScheduledVotes => Vec::new(), })); - let voting_identities = app_context - .load_local_voting_identities() - .unwrap_or_default(); + let voting_identities = loaded_voting_identities(app_context); let user_identities = app_context.load_local_user_identities().unwrap_or_default(); let vote_poll_ids = active_contests.vote_poll_ids(); let voter_ids = voting_identities @@ -1592,18 +1690,61 @@ impl DPNSScreen { return action; } + self.bulk_identity_options + .resize(self.voting_identities.len(), VoteOption::CastNow); + let plan = self.build_review_plan(); + let mut simple_schedule_valid = true; egui::ScrollArea::vertical().show(ui, |ui| { - ui.label(format!( - "Casting on behalf of all my nodes ({count}).", - count = self.voting_identities.len() - )); - ui.separator(); - ui.heading(format!("Votes to cast ({}):", self.selected_votes.len())); - for vote in &self.selected_votes { - let candidate_name = self.candidate_name(&vote.contested_name, vote.vote_choice); - let choice = review_vote_choice_label(vote.vote_choice, candidate_name.as_deref()); - ui.label(format!("β€’ {name}.dash β†’ {choice}", name = vote.contested_name)); + match &plan { + Ok(plan) => { + ui.heading(review_headline(plan.effective_count(), plan.node_count())); + for entry in plan.effective() { + let candidate_name = self.candidate_name( + &entry.target.contested_name, + entry.target.requested_choice, + ); + let requested = review_vote_choice_label( + entry.target.requested_choice, + candidate_name.as_deref(), + ); + let current_candidate_name = entry + .target + .current_choice + .and_then(|choice| { + self.candidate_name(&entry.target.contested_name, choice) + }); + let current = review_current_choice_label( + entry.target.current_choice, + current_candidate_name.as_deref(), + ); + ui.label(review_target_line( + &entry.node_label(), + &entry.target.contested_name, + &requested, + ¤t, + &entry.timing_label, + )); + } + if plan.no_op_count() > 0 { + ui.label(review_skipped_line(plan.no_op_count())); + } + if plan.changes_an_existing_vote() { + ui.colored_label( + DashColors::warning_color(dark_mode), + "Changing a vote uses one of the node's limited vote changes.", + ); + } + if plan.effective_count() == 0 { + ui.colored_label( + DashColors::warning_color(dark_mode), + "Nothing will be submitted. Choose at least one node and a vote it has not already cast.", + ); + } + } + Err(message) => { + ui.colored_label(DashColors::warning_color(dark_mode), message); + } } ui.separator(); ui.horizontal(|ui| { @@ -1691,11 +1832,6 @@ impl DPNSScreen { .color(DashColors::text_primary(dark_mode)), ); - if self.bulk_identity_options.len() <= i { - self.bulk_identity_options = - vec![VoteOption::CastNow; self.voting_identities.len()]; - } - let current_option = &mut self.bulk_identity_options[i]; ComboBox::from_id_salt(format!("combo_bulk_identity_{}", i)) .width(120.0) @@ -1800,35 +1936,36 @@ impl DPNSScreen { ui.label("Submitting votes…"); }); } - let has_immediate = self - .bulk_identity_options - .iter() - .any(|option| matches!(option, VoteOption::CastNow)); - let has_scheduled = self - .bulk_identity_options - .iter() - .any(|option| matches!(option, VoteOption::Scheduled { .. })); - let submit_label = match (has_immediate, has_scheduled) { - (true, false) => "Cast votes", - (false, true) => "Schedule votes", + let has_submittable = plan.as_ref().is_ok_and(|plan| plan.effective_count() > 0); + let submit_label = match plan + .as_ref() + .map(|plan| (plan.has_immediate(), plan.has_scheduled())) + { + Ok((true, false)) => "Cast votes", + Ok((false, true)) => "Schedule votes", _ => "Submit votes", }; + let submit_disabled_reason = if operation_in_progress { + "The selected votes are already being submitted." + } else if !simple_schedule_valid { + "Choose a future date and time before scheduling these votes." + } else 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." + }; let (submit_clicked, cancel_clicked) = ui .with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let submit_clicked = ComponentStyles::add_primary_button_enabled( ui, - !operation_in_progress && simple_schedule_valid, + !operation_in_progress && simple_schedule_valid && has_submittable, if operation_in_progress { "Submitting votes…" } else { submit_label }, ) - .disabled_tooltip(if operation_in_progress { - "The selected votes are already being submitted." - } else { - "Choose a future date and time before scheduling these votes." - }) + .disabled_tooltip(submit_disabled_reason) .clicked(); let cancel_clicked = ui .add_enabled( @@ -1885,94 +2022,110 @@ impl DPNSScreen { action } - fn bulk_apply_votes(&mut self) -> AppAction { - let mut targets = Vec::new(); - let mut selected_voters = Vec::new(); - let mut has_immediate = false; + /// Resolve every node Γ— contest target the current review would submit. + /// + /// The review sheet and the submit click share this so the sheet cannot + /// promise something other than what is sent. `Err` carries the message the + /// operator sees, and blocks submission. + fn build_review_plan(&self) -> Result { + let mut entries = Vec::new(); + let mut voters = Vec::new(); for (identity, option) in self .voting_identities .iter() .zip(&self.bulk_identity_options) { - let timing = match option { + let (timing, timing_label) = match option { VoteOption::NoVote => continue, - VoteOption::CastNow => { - has_immediate = true; - VoteTiming::Now - } + VoteOption::CastNow => (VoteTiming::Now, "Cast now".to_owned()), 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); - VoteTiming::Scheduled((now + offset).timestamp_millis() as u64) + ( + VoteTiming::Scheduled((Utc::now() + offset).timestamp_millis() as u64), + format!("Scheduled in {days} d {hours} h {minutes} min"), + ) } }; - selected_voters.push(identity.clone()); + voters.push(identity.clone()); for selected_vote in &self.selected_votes { let voter_id = identity.identity.id(); - let vote_poll_id = match self + let vote_poll_id = self .app_context .dpns_vote_poll_id(&selected_vote.contested_name) - { - Ok(vote_poll_id) => vote_poll_id, - Err(error) => { + .map_err(|error| { tracing::warn!( ?error, contested_name = selected_vote.contested_name, "Could not build a DPNS vote target" ); - self.bulk_vote_handling_status = VoteHandlingStatus::Failed( - "This vote could not be prepared. Refresh Active contests and try again." - .to_owned(), - ); - return AppAction::None; - } - }; + "This vote could not be prepared. Refresh Active contests and try again." + .to_owned() + })?; let target_key = DpnsVoteTargetKey { network: self.app_context.network(), voter_id, vote_poll_id, }; if self.vote_operations.target_status(&target_key).is_some() { - self.bulk_vote_handling_status = VoteHandlingStatus::Failed(format!( + return Err(format!( "This node's vote for {} is already in progress. Check its result before submitting again.", selected_vote.contested_name )); - return AppAction::None; } - let current_choice = match self.vote_state.state(voter_id, vote_poll_id) { - DpnsCurrentVoteState::Available(choice) => choice, - DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable => { - self.bulk_vote_handling_status = VoteHandlingStatus::Failed( - "Current vote state is unavailable. Refresh voting before applying votes." - .to_owned(), - ); - return AppAction::None; - } + let DpnsCurrentVoteState::Available(current_choice) = + self.vote_state.state(voter_id, vote_poll_id) + else { + return Err( + "Current vote state is unavailable. Refresh voting before applying votes." + .to_owned(), + ); }; - targets.push(DpnsVoteTarget { - key: target_key, - voter_alias: identity.alias.clone(), - contested_name: selected_vote.contested_name.clone(), - requested_choice: selected_vote.vote_choice, - current_choice, - timing, + entries.push(ReviewEntry { + target: DpnsVoteTarget { + key: target_key, + voter_alias: identity.alias.clone(), + contested_name: selected_vote.contested_name.clone(), + requested_choice: selected_vote.vote_choice, + current_choice, + timing, + }, + timing_label: timing_label.clone(), }); } } + Ok(ReviewPlan { entries, voters }) + } - if targets.is_empty() { + fn bulk_apply_votes(&mut self) -> AppAction { + let plan = match self.build_review_plan() { + Ok(plan) => plan, + Err(message) => { + self.bulk_vote_handling_status = VoteHandlingStatus::Failed(message); + return AppAction::None; + } + }; + let has_immediate = plan.has_immediate(); + let ReviewPlan { + entries, + voters: selected_voters, + } = plan; + + if entries.is_empty() { self.bulk_vote_handling_status = VoteHandlingStatus::Failed( "No votes selected. Choose at least one node and contest.".to_owned(), ); return AppAction::None; } - let operation = DpnsVoteOperation::new(targets); + // No-op targets are handed over unfiltered: the operation counts them, + // and that count drives the post-submit feedback. + let operation = + DpnsVoteOperation::new(entries.into_iter().map(|entry| entry.target).collect()); if operation.targets.is_empty() { self.bulk_vote_handling_status = VoteHandlingStatus::Failed( "Every selected node already has the requested vote. Nothing will be submitted." @@ -2103,10 +2256,7 @@ impl ScreenLike for DPNSScreen { } fn refresh_on_arrival(&mut self) { - self.voting_identities = self - .app_context - .load_local_voting_identities() - .unwrap_or_default(); + self.voting_identities = loaded_voting_identities(&self.app_context); self.bulk_identity_options = vec![VoteOption::CastNow; self.voting_identities.len()]; self.set_all_option = VoteOption::CastNow; self.user_identities = self @@ -2475,6 +2625,64 @@ mod tests { (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) + } + + /// 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::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), + ) + }); + 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: Default::default(), + 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(), @@ -2830,17 +3038,253 @@ mod tests { assert!(screen.bulk_vote_handling_status == VoteHandlingStatus::CastingVotes); } + /// 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. #[test] - fn clear_all_result_rebuilds_scheduled_rows_immediately() { - 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()), + fn a_loaded_masternode_without_a_voting_key_cannot_compose_votes() { + let (ctx, _temp_dir) = kv_ctx(); + ctx.insert_local_qualified_identity( + &masternode_identity(41, "read-only-node", false, ctx.network()), + &None, + ) + .expect("insert keyless masternode"); + + let screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); + + assert!( + !ctx.load_local_voting_identities() + .expect("load voting identities") + .is_empty(), + "the keyless masternode must still be loaded, or this proves nothing" ); - ctx.set_det_kv_override_for_test(kv); + assert!( + screen.voting_identities.is_empty(), + "a node with no voting key cannot satisfy the submit path" + ); + } + + #[test] + fn a_loaded_masternode_with_a_voting_key_can_compose_votes() { + let (ctx, _temp_dir) = kv_ctx(); + ctx.insert_local_qualified_identity( + &masternode_identity(42, "voting-node", true, ctx.network()), + &None, + ) + .expect("insert voting masternode"); + + let screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); + + assert_eq!(screen.voting_identities.len(), 1); + } + + /// The review sheet must expand every node Γ— contest pair, suppress the + /// targets that already hold the requested choice, and count what it dropped. + #[test] + 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.cache_confirmed_dpns_vote(first.identity.id(), alpha, ResourceVoteChoice::Lock) + .expect("seed first node's proved vote"); + ctx.cache_confirmed_dpns_vote(second.identity.id(), beta, ResourceVoteChoice::Abstain) + .expect("seed second node's proved vote"); + + let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); + screen.voting_identities = vec![first.clone(), second.clone()]; + screen.bulk_identity_options = vec![ + VoteOption::CastNow, + VoteOption::Scheduled { + days: 1, + hours: 2, + minutes: 3, + }, + ]; + screen.selected_votes = vec![ + SelectedVote { + contested_name: "alpha".to_owned(), + vote_choice: ResourceVoteChoice::Lock, + end_time: None, + }, + SelectedVote { + contested_name: "beta".to_owned(), + vote_choice: ResourceVoteChoice::Abstain, + end_time: None, + }, + ]; + screen.vote_state = DpnsVoteStateSnapshot::load( + &ctx, + &[first.identity.id(), second.identity.id()], + &[alpha, beta], + ) + .expect("load proved vote state"); + + let plan = screen.build_review_plan().expect("review plan"); + + assert_eq!(plan.entries.len(), 4, "two nodes across two contests"); + assert_eq!(plan.effective_count(), 2); + assert_eq!(plan.no_op_count(), 2); + assert_eq!(plan.node_count(), 2); + assert!(plan.has_immediate()); + assert!(plan.has_scheduled()); + assert!(!plan.changes_an_existing_vote()); + let retained = plan + .effective() + .map(|entry| { + ( + entry.node_label(), + entry.target.contested_name.clone(), + entry.timing_label.clone(), + ) + }) + .collect::>(); + assert_eq!( + retained, + vec![ + ( + "node-one".to_owned(), + "beta".to_owned(), + "Cast now".to_owned() + ), + ( + "node-two".to_owned(), + "alpha".to_owned(), + "Scheduled in 1 d 2 h 3 min".to_owned() + ), + ] + ); + } + + /// 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, DPNSSubscreen::Active); + screen.voting_identities = vec![node.clone()]; + screen.bulk_identity_options = vec![VoteOption::CastNow]; + 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!(plan.no_op_count(), 1); + assert_eq!(plan.node_count(), 0); + } + + /// A node that already voted differently is a vote change, and the review + /// must be able to say so. + #[test] + fn review_plan_flags_a_change_to_an_existing_vote() { + 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"); + + let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); + screen.voting_identities = vec![node.clone()]; + screen.bulk_identity_options = vec![VoteOption::CastNow]; + 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!(plan.changes_an_existing_vote()); + assert_eq!( + plan.effective() + .next() + .map(|entry| entry.target.current_choice), + Some(Some(ResourceVoteChoice::Lock)) + ); + } + + #[test] + fn review_lines_name_the_node_the_contest_the_choices_and_the_timing() { + let line = review_target_line("node-one", "alice", "Lock", "Not voted yet", "Cast now"); + + assert_eq!( + line, + "β€’ node-one β†’ alice.dash: Lock. Current vote: Not voted yet. Cast now." + ); + assert_eq!( + review_headline(6, 3), + "Votes to submit (6) from your nodes (3)." + ); + assert!(review_skipped_line(2).contains("(2)")); + assert_eq!( + review_current_choice_label(Some(ResourceVoteChoice::Abstain), None), + "Abstain" + ); + assert_eq!(review_current_choice_label(None, None), "Not voted yet"); + } + + /// 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]), + }; + let mut operation = DpnsVoteOperation::new(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"); + ctx.insert_scheduled_votes(&[ScheduledDPNSVote { + contested_name: "remove-me".to_owned(), + voter_id, + choice: ResourceVoteChoice::Lock, + unix_timestamp: 42, + executed_successfully: false, + }]) + .expect("insert compatibility mirror"); + let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::ScheduledVotes); + assert_eq!(screen.scheduled_votes.lock_recover().len(), 1); + + ctx.cancel_scheduled_dpns_vote_target(operation.id, &key, "remove-me") + .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" + ); + } + + #[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 = DpnsVoteOperation::new(vec![DpnsVoteTarget { key: DpnsVoteTargetKey { diff --git a/src/ui/state/dpns_vote_operations.rs b/src/ui/state/dpns_vote_operations.rs index 0ebcc49a7..dec12a268 100644 --- a/src/ui/state/dpns_vote_operations.rs +++ b/src/ui/state/dpns_vote_operations.rs @@ -97,9 +97,13 @@ impl DpnsVoteOperationSnapshot { } let journal_pairs = journal_rows.keys().cloned().collect::>(); + // A cancelled target is a dismissed schedule. Its pair stays in + // `journal_pairs` so a mirror row that outlived a best-effort delete + // cannot bring the dismissed schedule back. let mut rows = journal_rows .into_values() .map(|(_, row)| row) + .filter(|row| row.status != DpnsVoteTargetStatus::Cancelled) .collect::>(); rows.extend( legacy_votes @@ -264,7 +268,7 @@ mod tests { ); let second = scheduled_operation( 10, - DpnsVoteTargetStatus::Cancelled, + DpnsVoteTargetStatus::NotApplied, ResourceVoteChoice::Abstain, 200, ); @@ -279,10 +283,81 @@ mod tests { rows[0].journal_target.as_ref().map(|(id, _)| *id), Some(expected_id) ); - assert_eq!(rows[0].status, DpnsVoteTargetStatus::Cancelled); + assert_eq!(rows[0].status, DpnsVoteTargetStatus::NotApplied); assert_eq!(rows[0].vote.unix_timestamp, 200); } + /// 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()); + } + + /// The compatibility-mirror delete is best effort, so a cancelled target + /// must keep suppressing its legacy row even when the mirror survived. + #[test] + fn cancelled_targets_still_suppress_their_legacy_mirror_row() { + let cancelled = scheduled_operation( + 10, + DpnsVoteTargetStatus::Cancelled, + ResourceVoteChoice::Lock, + 100, + ); + let voter_id = cancelled.targets[0].target.key.voter_id; + let mut snapshot = DpnsVoteOperationSnapshot::default(); + snapshot.replace(vec![cancelled]); + let legacy = [ + legacy_vote(voter_id, "alice", ResourceVoteChoice::Lock, 100, false), + legacy_vote( + Identifier::from([11; 32]), + "unrelated", + ResourceVoteChoice::Abstain, + 300, + false, + ), + ]; + + let rows = snapshot.scheduled_vote_rows(&legacy); + + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].vote.contested_name, "unrelated"); + } + + /// 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_derive_compatibility_execution_only_from_confirmed_status() { let confirmed = scheduled_operation( From a9d5a2c43a1bb3ccbd134c9571f0852720aeee47 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Sat, 1 Aug 2026 09:51:09 +0000 Subject: [PATCH 038/194] refactor(dpns): drop the vote-change note from the review sheet The limited-vote-change note belongs to VOTE-FR-015, which is outside the scope of this blocking-fix pass. The review sheet still lists each target's current choice, so the operator sees what a vote replaces; only the extra advisory line and the ReviewPlan predicate behind it are removed. Co-Authored-By: Claude Opus 5 --- src/ui/dpns/dpns_contested_names_screen.rs | 23 +++++++--------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index ee2fc9a40..e9530b777 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -255,11 +255,6 @@ impl ReviewPlan { self.effective() .any(|entry| matches!(entry.target.timing, VoteTiming::Scheduled(_))) } - - fn changes_an_existing_vote(&self) -> bool { - self.effective() - .any(|entry| entry.target.current_choice.is_some()) - } } fn review_headline(effective_count: usize, node_count: usize) -> String { @@ -1729,12 +1724,6 @@ impl DPNSScreen { if plan.no_op_count() > 0 { ui.label(review_skipped_line(plan.no_op_count())); } - if plan.changes_an_existing_vote() { - ui.colored_label( - DashColors::warning_color(dark_mode), - "Changing a vote uses one of the node's limited vote changes.", - ); - } if plan.effective_count() == 0 { ui.colored_label( DashColors::warning_color(dark_mode), @@ -3129,7 +3118,6 @@ mod tests { assert_eq!(plan.node_count(), 2); assert!(plan.has_immediate()); assert!(plan.has_scheduled()); - assert!(!plan.changes_an_existing_vote()); let retained = plan .effective() .map(|entry| { @@ -3184,10 +3172,10 @@ mod tests { assert_eq!(plan.node_count(), 0); } - /// A node that already voted differently is a vote change, and the review - /// must be able to say so. + /// A node that already voted differently keeps its proved choice on the + /// review line, so the operator sees what the vote replaces. #[test] - fn review_plan_flags_a_change_to_an_existing_vote() { + 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()); @@ -3208,13 +3196,16 @@ mod tests { let plan = screen.build_review_plan().expect("review plan"); assert_eq!(plan.effective_count(), 1); - assert!(plan.changes_an_existing_vote()); assert_eq!( plan.effective() .next() .map(|entry| entry.target.current_choice), Some(Some(ResourceVoteChoice::Lock)) ); + assert_eq!( + review_current_choice_label(Some(ResourceVoteChoice::Lock), None), + "Lock" + ); } #[test] From 513af26d055997155e7fa5163fae2ce1e5188c88 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Sat, 1 Aug 2026 10:07:35 +0000 Subject: [PATCH 039/194] chore(deps): bump platform pin to PR #3968 latest tip 762c66cf -> 5931df74 for dash-sdk, rs-sdk-trusted-context-provider, platform-wallet and platform-wallet-storage. Cargo.lock moves only the platform git source revs; no other dependency drifts. Co-Authored-By: Claude Opus 5 --- Cargo.lock | 56 +++++++++++++++++++++++++++--------------------------- Cargo.toml | 8 ++++---- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8f5225dc4..5663efb47 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1877,7 +1877,7 @@ dependencies = [ [[package]] name = "dapi-grpc" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "dash-platform-macros", "futures-core", @@ -1979,7 +1979,7 @@ dependencies = [ [[package]] name = "dash-async" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "thiserror 2.0.18", "tokio", @@ -1989,7 +1989,7 @@ dependencies = [ [[package]] name = "dash-context-provider" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "dash-async", "dpp", @@ -2100,7 +2100,7 @@ dependencies = [ [[package]] name = "dash-platform-macros" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "heck", "quote", @@ -2110,7 +2110,7 @@ dependencies = [ [[package]] name = "dash-sdk" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "arc-swap", "async-trait", @@ -2247,7 +2247,7 @@ dependencies = [ [[package]] name = "dashpay-contract" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "platform-value", "platform-version", @@ -2258,7 +2258,7 @@ dependencies = [ [[package]] name = "data-contracts" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "dashpay-contract", "document-history-contract", @@ -2527,7 +2527,7 @@ dependencies = [ [[package]] name = "document-history-contract" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "platform-value", "platform-version", @@ -2556,7 +2556,7 @@ checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" [[package]] name = "dpns-contract" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "platform-value", "platform-version", @@ -2567,7 +2567,7 @@ dependencies = [ [[package]] name = "dpp" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "anyhow", "async-trait", @@ -2617,7 +2617,7 @@ dependencies = [ [[package]] name = "dpp-json-convertible-derive" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "proc-macro2", "quote", @@ -2627,7 +2627,7 @@ dependencies = [ [[package]] name = "drive" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "bincode 2.0.1", "byteorder", @@ -2652,7 +2652,7 @@ dependencies = [ [[package]] name = "drive-proof-verifier" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "bincode 2.0.1", "dapi-grpc", @@ -5046,7 +5046,7 @@ dependencies = [ [[package]] name = "keyword-search-contract" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "platform-value", "platform-version", @@ -5259,7 +5259,7 @@ dependencies = [ [[package]] name = "masternode-reward-shares-contract" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "platform-value", "platform-version", @@ -6471,7 +6471,7 @@ checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" [[package]] name = "platform-encryption" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "aes", "cbc", @@ -6484,7 +6484,7 @@ dependencies = [ [[package]] name = "platform-serialization" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "bincode 2.0.1", "platform-version", @@ -6493,7 +6493,7 @@ dependencies = [ [[package]] name = "platform-serialization-derive" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "proc-macro2", "quote", @@ -6504,7 +6504,7 @@ dependencies = [ [[package]] name = "platform-value" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "base64 0.22.1", "bincode 2.0.1", @@ -6524,7 +6524,7 @@ dependencies = [ [[package]] name = "platform-version" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "bincode 2.0.1", "grovedb-version 5.0.1", @@ -6535,7 +6535,7 @@ dependencies = [ [[package]] name = "platform-versioning" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "proc-macro2", "quote", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "platform-wallet" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "arc-swap", "async-trait", @@ -6577,7 +6577,7 @@ dependencies = [ [[package]] name = "platform-wallet-storage" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "apple-native-keyring-store", "argon2", @@ -7574,7 +7574,7 @@ dependencies = [ [[package]] name = "rs-dapi-client" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "backon", "chrono", @@ -7600,7 +7600,7 @@ dependencies = [ [[package]] name = "rs-sdk-trusted-context-provider" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "arc-swap", "dash-async", @@ -8842,7 +8842,7 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "token-history-contract" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "platform-value", "platform-version", @@ -9687,7 +9687,7 @@ dependencies = [ [[package]] name = "wallet-utils-contract" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "platform-value", "platform-version", @@ -10943,7 +10943,7 @@ dependencies = [ [[package]] name = "withdrawals-contract" version = "4.1.0" -source = "git+https://github.com/dashpay/platform?rev=762c66cf7716b9b3264868a49e8d29991c643c7e#762c66cf7716b9b3264868a49e8d29991c643c7e" +source = "git+https://github.com/dashpay/platform?rev=5931df745a74aafa92cbcfc410e34319850a8e8a#5931df745a74aafa92cbcfc410e34319850a8e8a" dependencies = [ "num_enum 0.5.11", "platform-value", diff --git a/Cargo.toml b/Cargo.toml index 5b0271230..9fb64ab4f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,7 @@ eframe = { version = "0.35.0", features = ["persistence", "wgpu"] } base64 = "0.22.1" # TODO: GHSA-7gcf-g7xr-8hxj (serde_with <3.21.0) is unfixable from here β€” the 2.x pin lives in # dashcore-rpc-json (dashpay/rust-dashcore, rpc-json/Cargo.toml). Re-check when these pins move. -dash-sdk = { git = "https://github.com/dashpay/platform", rev = "762c66cf7716b9b3264868a49e8d29991c643c7e", features = [ +dash-sdk = { git = "https://github.com/dashpay/platform", rev = "5931df745a74aafa92cbcfc410e34319850a8e8a", features = [ "core_key_wallet", "core_key_wallet_manager", "core_bincode", @@ -30,12 +30,12 @@ dash-sdk = { git = "https://github.com/dashpay/platform", rev = "762c66cf7716b9b "core_spv", "shielded", ] } -rs-sdk-trusted-context-provider = { git = "https://github.com/dashpay/platform", rev = "762c66cf7716b9b3264868a49e8d29991c643c7e" } -platform-wallet = { git = "https://github.com/dashpay/platform", rev = "762c66cf7716b9b3264868a49e8d29991c643c7e", features = [ +rs-sdk-trusted-context-provider = { git = "https://github.com/dashpay/platform", rev = "5931df745a74aafa92cbcfc410e34319850a8e8a" } +platform-wallet = { git = "https://github.com/dashpay/platform", rev = "5931df745a74aafa92cbcfc410e34319850a8e8a", features = [ "serde", "shielded", ] } -platform-wallet-storage = { git = "https://github.com/dashpay/platform", rev = "762c66cf7716b9b3264868a49e8d29991c643c7e", features = [ +platform-wallet-storage = { git = "https://github.com/dashpay/platform", rev = "5931df745a74aafa92cbcfc410e34319850a8e8a", features = [ "shielded", ] } zip32 = "0.2.0" From 28948b13704a7be1a430991d92fbdacf114c0e4a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 8 Sep 2026 14:37:59 +0000 Subject: [PATCH 040/194] fix(dpns): preserve vote proof freshness and ambiguous outcomes Keep mismatched reconciliation outcomes locked, reject superseded refresh publications, and retain typed preflight diagnostics. Track confirmed polls independently from full-voter snapshot freshness. Co-Authored-By: GPT-6 Astra --- src/backend_task/contested_names/mod.rs | 204 ++++--- .../query_dpns_contested_resources.rs | 4 +- src/backend_task/error.rs | 11 + src/context/contested_names_db.rs | 2 +- src/context/dpns_vote_state.rs | 569 +++++++++++++++--- src/context/mod.rs | 3 + src/ui/dpns/dpns_contested_names_screen.rs | 20 +- 7 files changed, 668 insertions(+), 145 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index fd5c9fec5..a9d9764d2 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -100,15 +100,10 @@ fn missing_voter_outcome( fn classify_reconciled_vote( observed: Option, requested: ResourceVoteChoice, - previous_observation: Option, ) -> Option { match observed { Some(choice) if choice == requested => Some(DpnsVoteTargetStatus::Confirmed), - // Two consecutive identical mismatches filter one stale/racing read while - // releasing the lock promptly once Platform consistently proves another vote. - Some(choice) if previous_observation == Some(choice) => { - Some(DpnsVoteTargetStatus::NotApplied) - } + // A different current choice does not establish that this transition cannot apply. Some(_) | None => None, } } @@ -371,6 +366,40 @@ impl AppContext { 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) => { + 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(()) + } + async fn execute_dpns_vote_operation( self: &Arc, mut operation: DpnsVoteOperation, @@ -385,7 +414,7 @@ impl AppContext { }); } let was_persisted = self.dpns_vote_operation(operation.id)?.is_some(); - let mut preflight_unavailable = false; + let mut preflight_error = None; if operation .targets .iter() @@ -393,7 +422,7 @@ impl AppContext { { // A fresh proved snapshot is a submission precondition. This also // prevents a due schedule from replaying a vote already observed. - self.refresh_dpns_vote_states(sdk).await; + let refreshed = self.refresh_dpns_vote_states(sdk).await.map_err(Arc::new); let queued_keys = operation .targets .iter() @@ -401,37 +430,50 @@ impl AppContext { .map(|outcome| outcome.target.key.clone()) .collect::>(); for key in queued_keys { - let state = self.dpns_current_vote_state(key.voter_id, key.vote_poll_id)?; - let unavailable = matches!( - state, - DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable - ); - if was_persisted { - self.revalidate_queued_dpns_vote_target(operation.id, &key, state)?; - preflight_unavailable |= unavailable; - continue; - } - let Some(outcome) = operation - .targets - .iter_mut() - .find(|outcome| outcome.target.key == key) - else { - continue; + 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)), }; - match state { - 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); - preflight_unavailable = true; + let validation = snapshot.and_then(|snapshot| { + snapshot + .with_state(self, key.vote_poll_id, |state| { + matches!(state, DpnsCurrentVoteState::Available(_)).then(|| { + self.revalidate_dpns_vote_preflight( + &mut operation, + was_persisted, + &key, + state, + ) + }) + }) + .map_err(Arc::new) + }); + 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, + )?; + preflight_error.get_or_insert(source); } } @@ -677,8 +719,8 @@ impl AppContext { .into_iter() .collect::, _>>()?; - if preflight_unavailable { - return Err(TaskError::DpnsCurrentVoteUnavailable); + if let Some(source) = preflight_error { + return Err(TaskError::DpnsVotePreflightFailed { source }); } Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated { @@ -751,11 +793,8 @@ impl AppContext { .get(&poll_id) .and_then(Option::as_ref) .map(ResourceVoteGettersV0::resource_vote_choice); - let reconciled_status = classify_reconciled_vote( - observed, - outcome.target.requested_choice, - outcome.target.current_choice, - ); + let reconciled_status = + classify_reconciled_vote(observed, outcome.target.requested_choice); let status = reconciled_status.unwrap_or(DpnsVoteTargetStatus::Unconfirmed); if !self.update_dpns_vote_reconciliation( operation_id, @@ -1157,6 +1196,44 @@ mod tests { )); } + #[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() { @@ -1186,35 +1263,23 @@ mod tests { #[test] fn exact_reconciliation_confirms_only_the_requested_choice() { assert_eq!( - classify_reconciled_vote( - Some(ResourceVoteChoice::Lock), - ResourceVoteChoice::Lock, - None, - ), + classify_reconciled_vote(Some(ResourceVoteChoice::Lock), ResourceVoteChoice::Lock,), Some(DpnsVoteTargetStatus::Confirmed) ); assert_eq!( - classify_reconciled_vote( - Some(ResourceVoteChoice::Abstain), - ResourceVoteChoice::Lock, - None, - ), + 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, - Some(ResourceVoteChoice::Abstain), - ), + classify_reconciled_vote(None, ResourceVoteChoice::Lock,), None, "an absent exact row remains ambiguous and must not release its lock" ); } #[test] - fn proved_different_reconciliation_releases_target_lock_after_corroboration() { + 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( @@ -1260,7 +1325,7 @@ mod tests { ); let observed = Some(ResourceVoteChoice::Abstain); - let first_status = classify_reconciled_vote(observed, ResourceVoteChoice::Lock, None) + let first_status = classify_reconciled_vote(observed, ResourceVoteChoice::Lock) .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); assert!( context @@ -1270,12 +1335,8 @@ mod tests { 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, - persisted.targets[0].target.current_choice, - ) - .expect("the repeated different choice must be proved not applied"); + let second_status = classify_reconciled_vote(observed, ResourceVoteChoice::Lock) + .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); assert!( context .update_dpns_vote_reconciliation( @@ -1293,9 +1354,12 @@ mod tests { .unwrap() .unwrap() .targets[0]; - assert_eq!(target.status, DpnsVoteTargetStatus::NotApplied); - assert!(!target.status.holds_lock()); - assert_eq!(context.dpns_vote_target_status(&key).unwrap(), None); + assert_eq!(target.status, DpnsVoteTargetStatus::Unconfirmed); + assert!(target.status.holds_lock()); + assert_eq!( + context.dpns_vote_target_status(&key).unwrap(), + Some(DpnsVoteTargetStatus::Unconfirmed) + ); } #[test] 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 15085a737..78d9bb40c 100644 --- a/src/backend_task/contested_names/query_dpns_contested_resources.rs +++ b/src/backend_task/contested_names/query_dpns_contested_resources.rs @@ -224,7 +224,9 @@ impl AppContext { // 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". - self.refresh_dpns_vote_states(sdk).await; + if let Err(error) = self.refresh_dpns_vote_states(sdk).await { + tracing::warn!(?error, "Could not refresh DPNS current votes with contests"); + } self.refresh_pending_dpns_usernames()?; sender diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 626b09fb4..522d3121b 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -956,6 +956,17 @@ pub enum TaskError { )] 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, + + /// 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.")] diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 686ad56aa..6dd9239c0 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -916,7 +916,7 @@ mod tests { impl KvStore for CurrentVotesReadCounter { fn get(&self, scope: &ObjectId, key: &str) -> Result>, KvError> { - if key.starts_with("det:dpns_current_votes:v2:") { + if key.starts_with("det:dpns_current_votes:v3:") { self.snapshot_reads.fetch_add(1, Ordering::Relaxed); } self.inner.get(scope, key) diff --git a/src/context/dpns_vote_state.rs b/src/context/dpns_vote_state.rs index ae58a207e..beaf8ef57 100644 --- a/src/context/dpns_vote_state.rs +++ b/src/context/dpns_vote_state.rs @@ -20,10 +20,14 @@ use dash_sdk::platform::{FetchMany, Identifier}; use futures::{StreamExt, stream}; 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}; use std::time::{SystemTime, UNIX_EPOCH}; const LEGACY_CURRENT_VOTES_KEY: &str = "det:dpns_current_votes:v1"; -const CURRENT_VOTES_KEY_PREFIX: &str = "det:dpns_current_votes:v2:"; +const CURRENT_VOTES_KEY_PREFIX: &str = "det:dpns_current_votes:v3:"; const VOTE_QUERY_PAGE_SIZE: u16 = 100; const CURRENT_VOTE_MAX_AGE_MS: u64 = 120_000; @@ -32,6 +36,67 @@ 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>, +} + +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) != Some(&self.generation) { + return Err(TaskError::DpnsVoteStateChanged); + } + Ok(consume(snapshot_vote_state( + Some(&self.snapshot), + poll_id, + now_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 { @@ -60,14 +125,11 @@ fn load_snapshot( { return Ok(Some(snapshot)); } - if kv - .get::(scope, LEGACY_CURRENT_VOTES_KEY) - .map_err(vote_state_err)? - .is_some() - { - kv.delete(scope, LEGACY_CURRENT_VOTES_KEY) - .map_err(vote_state_err)?; - } + // Cached v1/v2 values have no independent per-poll freshness and must be re-proved. + kv.delete(scope, LEGACY_CURRENT_VOTES_KEY) + .map_err(vote_state_err)?; + let previous_key = current_votes_key(network).replace(":v3:", ":v2:"); + kv.delete(scope, &previous_key).map_err(vote_state_err)?; Ok(None) } @@ -90,6 +152,12 @@ fn snapshot_vote_state( vote_poll_id: Identifier, checked_at_ms: u64, ) -> DpnsCurrentVoteState { + 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) <= CURRENT_VOTE_MAX_AGE_MS + { + return DpnsCurrentVoteState::Available(Some(*choice)); + } match snapshot { None => DpnsCurrentVoteState::Checking, Some(snapshot) @@ -105,6 +173,65 @@ fn snapshot_vote_state( } impl AppContext { + #[cfg(test)] + pub(crate) async fn seed_proved_dpns_votes_for_test( + &self, + voter_id: Identifier, + votes: BTreeMap<[u8; 32], ResourceVoteChoice>, + ) -> Result<(), TaskError> { + self.refresh_dpns_vote_state_with(&self.det_kv()?, voter_id, async { Ok(votes) }) + .await + .map(|_| ()) + } + + async fn refresh_dpns_vote_state_with( + &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) + { + return Err(TaskError::DpnsVoteStateChanged); + } + 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, + }; + publications.insert(voter_id, generation); + save_snapshot(kv, self.network, &voter_id, &snapshot)?; + 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 normalized DPNS label. pub fn dpns_vote_poll_id(&self, name: &str) -> Result { let document_type = self @@ -163,71 +290,31 @@ 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) { - let voters = match self.load_local_masternode_identities() { - Ok(voters) => voters, - Err(error) => { - tracing::warn!(?error, "Could not load nodes for DPNS vote-state refresh"); - return; - } - }; - let kv = match self.det_kv() { - Ok(kv) => kv, - Err(error) => { - tracing::warn!(?error, "Could not open DPNS vote-state storage"); - return; - } - }; + pub(crate) async fn refresh_dpns_vote_states( + &self, + sdk: &Sdk, + ) -> Result { + let voters = self.load_local_masternode_identities()?; + let kv = self.det_kv()?; - stream::iter(voters) + Ok(stream::iter(voters) .map(|voter| { let sdk = sdk.clone(); let kv = kv.clone(); - let network = self.network; async move { let voter_id = voter.identity.id(); - match fetch_votes_for_voter(&sdk, voter_id).await { - Ok(votes) => { - let snapshot = StoredCurrentVotes { - available: true, - updated_at: now_ms(), - votes, - }; - if let Err(error) = save_snapshot(&kv, network, &voter_id, &snapshot) { - tracing::warn!( - ?error, - voter_id = %voter_id, - "Could not save proved DPNS vote state" - ); - } - } - Err(error) => { - let snapshot = StoredCurrentVotes { - available: false, - updated_at: now_ms(), - votes: BTreeMap::new(), - }; - if let Err(storage_error) = - save_snapshot(&kv, network, &voter_id, &snapshot) - { - tracing::warn!( - ?storage_error, - voter_id = %voter_id, - "Could not save unavailable DPNS vote state" - ); - } - tracing::warn!( - ?error, - voter_id = %voter_id, - "Proved DPNS vote-state query was unavailable" - ); - } + let result = self.refresh_dpns_vote_state_with( + &kv, voter_id, fetch_votes_for_voter(&sdk, voter_id), + ).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(4) - .collect::>() - .await; + .collect::>() + .await) } /// Update the proved-state cache after a confirmed target. @@ -237,11 +324,24 @@ impl AppContext { 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); + publications.insert( + voter_id, + self.dpns_vote_state_publications.next_generation()?, + ); let kv = self.det_kv()?; let mut snapshot = load_snapshot(&kv, self.network, &voter_id)?.unwrap_or_default(); - snapshot.available = true; - snapshot.updated_at = now_ms(); - snapshot.votes.insert(vote_poll_id.to_buffer(), choice); + let confirmed_at = now_ms(); + snapshot.confirmed.retain(|_, (updated_at, _)| { + confirmed_at.saturating_sub(*updated_at) <= CURRENT_VOTE_MAX_AGE_MS + }); + snapshot + .confirmed + .insert(vote_poll_id.to_buffer(), (confirmed_at, choice)); save_snapshot(&kv, self.network, &voter_id, &snapshot) } } @@ -330,6 +430,336 @@ mod tests { 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 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.refresh_dpns_vote_state_with(&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 + .refresh_dpns_vote_state_with(&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.refresh_dpns_vote_state_with(&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 + .refresh_dpns_vote_state_with(&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::{ + DpnsVoteOperation, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + }; + let key = DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: voter, + vote_poll_id: poll, + }; + let mut operation = DpnsVoteOperation::new(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 + .refresh_dpns_vote_state_with(&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), + DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)) + ); + assert_eq!( + snapshot_vote_state(Some(&snapshot), other, 11), + DpnsCurrentVoteState::Unavailable + ); + assert_eq!( + snapshot_vote_state(Some(&snapshot), poll, 11 + CURRENT_VOTE_MAX_AGE_MS), + DpnsCurrentVoteState::Checking + ); + } + + #[test] + fn v2_snapshot_is_invalidated_without_decoding_a_new_wire_shape() { + let kv = kv(); + let voter = Identifier::from([1; 32]); + let key = "det:dpns_current_votes:v2:testnet"; + let old = ( + true, + now_ms(), + BTreeMap::<[u8; 32], ResourceVoteChoice>::new(), + ); + kv.put(DetScope::Identity(&voter.to_buffer()), key, &old) + .unwrap(); + assert_eq!(load_snapshot(&kv, Network::Testnet, &voter).unwrap(), None); + assert!( + kv.get::<(bool, u64, BTreeMap<[u8; 32], ResourceVoteChoice>)>( + DetScope::Identity(&voter.to_buffer()), + key + ) + .unwrap() + .is_none() + ); + } + + #[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 + .refresh_dpns_vote_state_with(&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() { @@ -340,6 +770,7 @@ mod tests { available: true, updated_at: 3, votes: BTreeMap::from([(poll.to_buffer(), ResourceVoteChoice::Lock)]), + ..Default::default() }; save_snapshot(&kv, Network::Testnet, &voter, &snapshot).unwrap(); @@ -372,6 +803,7 @@ mod tests { available: true, updated_at: now_ms(), votes: BTreeMap::new(), + ..Default::default() }; save_snapshot(&kv, Network::Testnet, &voter, &snapshot).unwrap(); @@ -390,6 +822,7 @@ mod tests { available: true, updated_at: now_ms(), votes: BTreeMap::new(), + ..Default::default() }; kv.put( DetScope::Identity(&voter.to_buffer()), @@ -425,6 +858,7 @@ mod tests { available: true, updated_at: 1, votes: BTreeMap::from([(poll.to_buffer(), ResourceVoteChoice::Lock)]), + ..Default::default() }; assert_eq!( @@ -450,6 +884,7 @@ mod tests { available: true, updated_at: now_ms(), votes: BTreeMap::new(), + ..Default::default() }, ) .expect("seed current-vote snapshot"); diff --git a/src/context/mod.rs b/src/context/mod.rs index ad3758325..0aba0c970 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -236,6 +236,8 @@ pub struct AppContext { contact_request_actions_in_flight: Mutex>, /// Serializes operation journal writes and target-lock acquisition. dpns_vote_operation_guard: 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, @@ -585,6 +587,7 @@ impl AppContext { contact_request_actions_in_flight: Mutex::new(HashSet::new()), dpns_vote_operation_guard: Mutex::new(()), dpns_vote_dispatch: DpnsVoteDispatchCoordinator::default(), + dpns_vote_state_publications: dpns_vote_state::DpnsVoteStatePublications::default(), dpns_vote_recovery: tokio::sync::Mutex::new(false), dpns_vote_diagnostics: Mutex::new(BTreeMap::new()), dpns_vote_diagnostic_sequence: AtomicU64::new(0), diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index ae588875c..1a9be1d5a 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -3085,17 +3085,25 @@ mod tests { /// The review sheet must expand every node Γ— contest pair, suppress the /// targets that already hold the requested choice, and count what it dropped. - #[test] - fn review_plan_expands_every_node_and_contest_and_suppresses_no_ops() { + #[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.cache_confirmed_dpns_vote(first.identity.id(), alpha, ResourceVoteChoice::Lock) - .expect("seed first node's proved vote"); - ctx.cache_confirmed_dpns_vote(second.identity.id(), beta, ResourceVoteChoice::Abstain) - .expect("seed second node's proved vote"); + 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"); let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); screen.voting_identities = vec![first.clone(), second.clone()]; From c5c0e50f4bd3c9cc04ce9d157a8128e899dc0f6f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 8 Sep 2026 14:38:35 +0000 Subject: [PATCH 041/194] fix(dpns): bound vote history and preserve scheduled vote lifecycle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cancel executable journal targets during identity removal and recovery, retain recent completed immediate votes, and add validated in-place schedule edits with optimistic concurrency. Persist dismissed schedule rows separately from their terminal vote outcomes. Co-Authored-By: Codex GPT-6 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- .../contested_names/edit_scheduled_vote.rs | 72 +++ src/backend_task/contested_names/mod.rs | 31 + .../contested_names/vote_on_dpns_name.rs | 23 +- src/backend_task/error.rs | 16 + src/context/dpns_vote_operations.rs | 558 +++++++++++++++++- src/context/identity_db.rs | 182 +++++- src/model/dpns_voting.rs | 82 +++ 7 files changed, 943 insertions(+), 21 deletions(-) create mode 100644 src/backend_task/contested_names/edit_scheduled_vote.rs 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..94f541c20 --- /dev/null +++ b/src/backend_task/contested_names/edit_scheduled_vote.rs @@ -0,0 +1,72 @@ +//! 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 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 = std::time::UNIX_EPOCH + .elapsed() + .unwrap_or_default() + .as_millis() as u64; + 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, mirror_error) = self.edit_scheduled_dpns_vote_target(&edit)?; + if let Some(error) = mirror_error { + tracing::warn!(?error, %operation_id, "DPNS schedule edit was journaled but its compatibility mirror could not be updated"); + } + 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 a9d9764d2..415c3dfac 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -1,3 +1,4 @@ +mod edit_scheduled_vote; mod query_dpns_contested_resources; mod query_dpns_vote_contenders; mod query_ending_times; @@ -57,6 +58,14 @@ pub enum ContestedResourceTask { key: DpnsVoteTargetKey, contested_name: String, }, + EditScheduledDpnsVote { + operation_id: Option, + key: DpnsVoteTargetKey, + expected_choice: ResourceVoteChoice, + expected_timestamp: u64, + choice: ResourceVoteChoice, + unix_timestamp: u64, + }, } #[derive(Debug, Clone, PartialEq)] @@ -238,6 +247,28 @@ impl AppContext { self.cancel_scheduled_dpns_vote_target(operation_id, &key, &contested_name)?; Ok(BackendTaskSuccessResult::Refresh) } + ContestedResourceTask::EditScheduledDpnsVote { + operation_id, + key, + expected_choice, + expected_timestamp, + choice, + unix_timestamp, + } => { + self.edit_scheduled_dpns_vote( + crate::model::dpns_voting::DpnsScheduledVoteEdit { + operation_id, + key, + expected_choice, + expected_timestamp, + choice, + unix_timestamp, + }, + sdk, + sender, + ) + .await + } } } 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 e17832df0..dd3cc1aa1 100644 --- a/src/backend_task/contested_names/vote_on_dpns_name.rs +++ b/src/backend_task/contested_names/vote_on_dpns_name.rs @@ -127,15 +127,12 @@ where } impl AppContext { - pub(super) async fn submit_dpns_vote( - self: &Arc, - operation_id: DpnsVoteOperationId, - key: &DpnsVoteTargetKey, + /// 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, - qualified_identity: &QualifiedIdentity, sdk: &Sdk, - ) -> Result { + ) -> Result { let data_contract = self.dpns_contract.as_ref(); let document_type = data_contract .document_type_for_name("domain") @@ -184,7 +181,19 @@ impl AppContext { name: name.to_owned(), }); } + Ok(vote_poll) + } + 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), diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 522d3121b..f0ace4df3 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -950,6 +950,22 @@ pub enum TaskError { )] 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." diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index c98a7ebfb..03e40323b 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -8,9 +8,9 @@ use crate::context::identity_db::{ }; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome, - DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, - DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, failed_before_broadcast_outcome, - unavailable_preflight_outcome, + DpnsScheduledVoteEdit, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, + DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + failed_before_broadcast_outcome, unavailable_preflight_outcome, }; use crate::wallet_backend::{DetKv, DetScope, KvAdapterError}; use dash_sdk::dpp::dashcore::Network; @@ -25,6 +25,10 @@ const OPERATION_KEY_PREFIX: &str = "det:dpns_vote_operation:v2:"; const OPERATION_LOCK_INDEX_KEY_PREFIX: &str = "det:dpns_vote_operation_locks:v2:"; const OPERATION_LOCK_INDEX_DIRTY_KEY_PREFIX: &str = "det:dpns_vote_operation_locks_dirty:v2:"; const DPNS_VOTE_DIAGNOSTIC_LIMIT: usize = 256; +/// Completed immediate batches retained per network; unresolved work is never capped. +const DPNS_IMMEDIATE_HISTORY_LIMIT: usize = 256; +const SCHEDULE_DISMISSAL_KEY_PREFIX: &str = "det:dpns_vote_schedule_dismissals:v1:"; +const IMMEDIATE_HISTORY_KEY_PREFIX: &str = "det:dpns_vote_immediate_history:v1:"; type DpnsVoteLockIndex = BTreeMap; type DpnsVoteDiagnosticMap = @@ -51,6 +55,47 @@ fn operation_key_prefix(network: Network) -> String { format!("{OPERATION_KEY_PREFIX}{}:", network_tag(network)) } +fn schedule_dismissal_key(network: Network, id: DpnsVoteOperationId) -> String { + format!( + "{SCHEDULE_DISMISSAL_KEY_PREFIX}{}:{id}", + network_tag(network) + ) +} + +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 before clearing their mirrors, under the journal guard. +pub(super) 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(()) +} + fn operation_lock_index_key(network: Network) -> String { format!("{OPERATION_LOCK_INDEX_KEY_PREFIX}{}", network_tag(network)) } @@ -260,6 +305,16 @@ fn persist_operation( if !operation_matches_network(operation, network)? { return Err(TaskError::DpnsVoteJournalNetworkMismatch); } + let immediate_complete = operation.is_complete() + && operation + .targets + .iter() + .all(|outcome| outcome.target.timing == VoteTiming::Now); + let newly_complete = immediate_complete + && kv + .get::(DetScope::Global, &operation_key(network, operation.id)) + .map_err(unreadable_operation_err)? + .is_none_or(|previous| !previous.is_complete()); let mut locks = load_or_rebuild_lock_index(kv, network)?; let previous_locks = locks.clone(); locks.retain(|_, owner| *owner != operation.id); @@ -307,6 +362,16 @@ fn persist_operation( kv.delete(DetScope::Global, &operation_lock_index_dirty_key(network)) .map_err(operation_err)?; } + if immediate_complete + && let Err(error) = + prune_immediate_history(kv, network, newly_complete.then_some(operation.id)) + { + // The submitted result is durable; cleanup failure must not invite a retry. + tracing::warn!( + ?error, + "Completed DPNS immediate history cleanup will retry during recovery" + ); + } Ok(()) } @@ -318,10 +383,11 @@ fn write_existing_operation( persist_operation(kv, network, operation) } -fn prune_terminal_operations(kv: &DetKv, network: Network) -> Result { +pub(super) fn prune_terminal_operations(kv: &DetKv, network: Network) -> Result { let surviving_scheduled_votes = durable_scheduled_vote_keys(kv, network)?; - let terminal_ids = load_operations(kv, network)? - .into_iter() + let operations = load_operations(kv, network)?; + let terminal_ids = operations + .iter() .filter(|operation| { operation.is_complete() && !operation.targets.is_empty() @@ -340,6 +406,71 @@ fn prune_terminal_operations(kv: &DetKv, network: Network) -> Result>(); + let scheduled_count = delete_terminal_operations(kv, network, &terminal_ids)?; + Ok(scheduled_count + prune_immediate_history(kv, network, None)?) +} + +fn prune_immediate_history( + kv: &DetKv, + network: Network, + newly_completed: Option, +) -> Result { + let history_key = format!("{IMMEDIATE_HISTORY_KEY_PREFIX}{}", network_tag(network)); + let mut terminal = load_operations(kv, network)? + .into_iter() + .filter(|operation| { + operation.is_complete() + && operation + .targets + .iter() + .all(|outcome| outcome.target.timing == VoteTiming::Now) + }) + .collect::>(); + terminal.sort_unstable_by_key(|operation| (operation.created_at, operation.id)); + let terminal_ids = terminal + .iter() + .map(|operation| operation.id) + .collect::>(); + let previous: Vec = kv + .get(DetScope::Global, &history_key) + .map_err(unreadable_operation_err)? + .unwrap_or_default(); + 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(DPNS_IMMEDIATE_HISTORY_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) +} + +fn delete_terminal_operations( + kv: &DetKv, + network: Network, + terminal_ids: &[DpnsVoteOperationId], +) -> Result { if terminal_ids.is_empty() { return Ok(0); } @@ -349,14 +480,45 @@ fn prune_terminal_operations(kv: &DetKv, network: Network) -> Result Result<(), TaskError> { + for mut operation in load_operations(kv, network)? { + let mut changed = false; + for outcome in &mut operation.targets { + if outcome.target.key.voter_id == voter_id + && matches!( + outcome.status, + DpnsVoteTargetStatus::Scheduled + | DpnsVoteTargetStatus::Queued + | DpnsVoteTargetStatus::Submitting + ) + { + outcome.status = DpnsVoteTargetStatus::Cancelled; + outcome.failure = None; + changed = true; + } + } + if changed { + persist_operation(kv, network, &operation)?; + } + } + Ok(()) +} + fn insert_diagnostic( diagnostics: &mut DpnsVoteDiagnosticMap, key: (DpnsVoteOperationId, DpnsVoteTargetKey), @@ -484,6 +646,36 @@ fn cancel_scheduled_target( Ok(true) } +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 + .or_else(|| locks.get(&edit.key).copied()) + .ok_or(TaskError::DpnsScheduledVoteNotEditable)?; + if locks.get(&edit.key) != Some(&id) { + return Err(TaskError::DpnsScheduledVoteNotEditable); + } + let operation: DpnsVoteOperation = kv + .get(DetScope::Global, &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) +} + fn recover_interrupted_target_statuses(operation: &mut DpnsVoteOperation) -> bool { let mut changed = false; for outcome in &mut operation.targets { @@ -533,6 +725,62 @@ fn mark_target_broadcast( } impl AppContext { + /// 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 + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + 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/mirror guard without releasing its target lock. + pub(crate) fn edit_scheduled_dpns_vote_target( + &self, + edit: &DpnsScheduledVoteEdit, + ) -> Result<(DpnsVoteOperationId, Option), TaskError> { + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let kv = self.det_kv()?; + let mut operation = operation_for_schedule_edit(&kv, self.network, edit)?; + if edit.unix_timestamp + <= std::time::UNIX_EPOCH + .elapsed() + .unwrap_or_default() + .as_millis() as u64 + { + 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; + outcome.target.timing = VoteTiming::Scheduled(edit.unix_timestamp); + outcome.failure = None; + let mirror = ScheduledDPNSVote { + contested_name: outcome.target.contested_name.clone(), + voter_id: edit.key.voter_id, + choice: edit.choice, + unix_timestamp: edit.unix_timestamp, + executed_successfully: false, + }; + persist_operation(&kv, self.network, &operation)?; + Ok(( + operation.id, + insert_scheduled_votes_in(&kv, &[mirror]).err(), + )) + } + /// Durably claim one due scheduled target before any executor can observe it. pub(crate) fn queue_scheduled_dpns_vote_target( &self, @@ -629,6 +877,27 @@ impl AppContext { load_operations_read_only(&kv, self.network) } + /// Read dismissed schedule rows without changing their recorded vote outcomes. + pub fn dismissed_dpns_vote_schedules( + &self, + ) -> Result, TaskError> { + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let kv = self.det_kv()?; + 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) + } + /// Migrate legacy journals and scheduled-vote mirrors before backend recovery. pub(crate) fn migrate_dpns_vote_operations(&self) -> Result<(), TaskError> { let _guard = self @@ -725,6 +994,9 @@ impl AppContext { .iter_mut() .find(|outcome| outcome.target.key == *key) { + if outcome.status == DpnsVoteTargetStatus::Cancelled { + return Ok(()); + } outcome.status = status; if status == DpnsVoteTargetStatus::Unconfirmed { outcome.target.current_choice = None; @@ -879,6 +1151,7 @@ impl AppContext { persist_operation(&kv, self.network, &operation)?; } } + prune_immediate_history(&kv, self.network, None)?; Ok(()) } @@ -940,6 +1213,7 @@ impl AppContext { } /// 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 .dpns_vote_operation_guard @@ -1015,6 +1289,7 @@ impl AppContext { { return Err(TaskError::DpnsScheduledVoteAlreadyStarted); } + dismiss_scheduled_target(&kv, self.network, operation_id, key)?; true } None => { @@ -1096,7 +1371,15 @@ impl AppContext { retained.insert(key.clone()); DpnsScheduledVoteClearDisposition::InFlight(status) } - _ => DpnsScheduledVoteClearDisposition::Cleared, + _ => { + dismiss_scheduled_target( + &kv, + self.network, + operation.id, + &outcome.target.key, + )?; + DpnsScheduledVoteClearDisposition::Cleared + } }; let rank = (status.holds_lock(), operation.created_at, operation.id); let should_replace = outcomes @@ -2032,6 +2315,265 @@ mod tests { ); } + #[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_immediate_history(&kv, Network::Testnet, None).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"); + let sibling = scheduled_operation(DpnsVoteTargetStatus::Scheduled, 3, "sibling") + .targets + .remove(0); + scheduled.targets.push(sibling); + context + .insert_dpns_vote_operation(&mut scheduled, None) + .unwrap(); + let edit = DpnsScheduledVoteEdit { + operation_id: Some(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 (id, error) = context.edit_scheduled_dpns_vote_target(&edit).unwrap(); + assert_eq!(id, scheduled.id); + assert!(error.is_none()); + let saved = context.dpns_vote_operation(id).unwrap().unwrap(); + assert_eq!(saved.targets[1], scheduled.targets[1]); + 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) + )); + assert_eq!( + context.get_scheduled_votes().unwrap()[0].choice, + ResourceVoteChoice::Abstain + ); + } + + #[test] + fn schedule_edit_mirror_failure_retains_the_committed_edit_and_lock() { + 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 scheduled = scheduled_operation(DpnsVoteTargetStatus::Scheduled, 2, "edit-me"); + context + .insert_dpns_vote_operation(&mut scheduled, None) + .unwrap(); + store.fail_next_puts_containing("det:scheduled_vote:", 1); + let edit = DpnsScheduledVoteEdit { + operation_id: None, + key: scheduled.targets[0].target.key.clone(), + expected_choice: ResourceVoteChoice::Lock, + expected_timestamp: 42, + choice: ResourceVoteChoice::Abstain, + unix_timestamp: u64::MAX - 1, + }; + let (id, error) = context.edit_scheduled_dpns_vote_target(&edit).unwrap(); + assert_eq!(id, scheduled.id); + assert!(error.is_some()); + assert_eq!( + context.dpns_vote_operation(id).unwrap().unwrap().targets[0] + .target + .requested_choice, + edit.choice + ); + assert_eq!( + context.dpns_vote_target_status(&edit.key).unwrap(), + Some(DpnsVoteTargetStatus::Scheduled) + ); + } + + #[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: Some(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 = Some(DpnsVoteOperationId::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) + ); + assert!(context.get_scheduled_votes().unwrap().is_empty()); + } + + #[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()); + for created_at in 0..256 { + 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(), 258); + assert_eq!( + prune_immediate_history(&kv, Network::Testnet, None).unwrap(), + 1 + ); + let remaining = load_operations(&kv, Network::Testnet).unwrap(); + assert_eq!(remaining.len(), 257); + 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 terminal_schedule_dismissal_preserves_outcome_and_survives_mirror_delete_failure() { + 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(); + context + .insert_scheduled_votes(&[scheduled_vote(&completed)]) + .unwrap(); + store.fail_next_deletes_containing("det:scheduled_vote:", 1); + let key = &completed.targets[0].target.key; + context + .remove_scheduled_dpns_vote(Some(completed.id), key, "dismiss-me") + .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())) + ); + assert_eq!(context.get_scheduled_votes().unwrap().len(), 1); + } + #[test] fn diagnostics_evict_the_least_recently_recorded_entry() { let mut diagnostics = BTreeMap::new(); diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index a84775092..a4d74e44f 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -888,10 +888,19 @@ 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)?; + delete_scheduled_votes_for_voter(&kv, &id.to_buffer())?; + } + self.clear_identity_unloaded(&kv, &id.to_buffer())?; self.insert_local_qualified_identity_locked(qualified_identity, wallet_and_identity_id_info) } @@ -1794,6 +1803,14 @@ 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); + super::dpns_vote_operations::cancel_removed_identity_votes(&kv, self.network, *identifier)?; index_remove_identity(&kv, &id)?; purge_identity_scope(&kv, &id)?; let sidecar_cleanup = self.finish_identity_removal_cleanup(&kv, &id, vault_keys)?; @@ -1973,7 +1990,17 @@ impl AppContext { continue; } }; - if let Err(error) = purge_identity_scope(&kv, &id) { + let _vote_guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Err(error) = super::dpns_vote_operations::cancel_removed_identity_votes( + &kv, + self.network, + Identifier::from(id), + ) + .and_then(|()| purge_identity_scope(&kv, &id)) + { tracing::warn!( identity = %Identifier::from(id), %error, @@ -2433,7 +2460,12 @@ impl AppContext { /// Drop every scheduled vote that has already been cast successfully. pub fn clear_executed_scheduled_votes(&self) -> std::result::Result<(), TaskError> { + let _vote_guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); let kv = self.det_kv()?; + super::dpns_vote_operations::dismiss_confirmed_scheduled_targets(&kv, self.network)?; let voters = load_scheduled_vote_voters(&kv)?; for voter in &voters { let scope = DetScope::Identity(voter); @@ -2450,7 +2482,7 @@ impl AppContext { } prune_vote_voter_if_empty(&kv, voter)?; } - self.prune_terminal_dpns_vote_operations()?; + super::dpns_vote_operations::prune_terminal_operations(&kv, self.network)?; Ok(()) } @@ -4406,6 +4438,144 @@ 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 + .insert_scheduled_votes(&[scheduled_vote(staged.id, "removed", false)]) + .unwrap(); + staged + .ctx + .delete_local_qualified_identity(&staged.id) + .unwrap(); + assert!(staged.ctx.get_scheduled_votes().unwrap().is_empty()); + 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(); + 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(); + let mut scheduled = + scheduled_operation(staged.id, 9, "interrupted", DpnsVoteTargetStatus::Scheduled); + staged + .ctx + .insert_dpns_vote_operation(&mut scheduled, None) + .unwrap(); + staged + .ctx + .insert_scheduled_votes(&[scheduled_vote(staged.id, "interrupted", false)]) + .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.get_scheduled_votes().unwrap().is_empty()); + 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; diff --git a/src/model/dpns_voting.rs b/src/model/dpns_voting.rs index 3c6c646a7..7d5e66344 100644 --- a/src/model/dpns_voting.rs +++ b/src/model/dpns_voting.rs @@ -107,6 +107,45 @@ mod tests { assert!(!serialized.contains("secret")); assert!(!serialized.contains("wif")); } + + #[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) + ); + } } use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::identity::TimestampMillis; @@ -166,6 +205,49 @@ pub struct DpnsVoteTargetKey { 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: Option, + 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 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); + } + if unix_timestamp <= now_ms || contest.end_time.is_some_and(|end| unix_timestamp >= end) { + return Err(DpnsScheduleEditValidationError::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(()) +} + /// Durable identity of one scheduled-vote compatibility mirror row. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct DpnsScheduledVoteKey { From 04699b682f84e06824867d931da1702b4b808a31 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 8 Sep 2026 14:56:47 +0000 Subject: [PATCH 042/194] fix(dpns): preserve vote review intent and complete scheduled voting controls Keep absolute UTC times and per-node choices stable, restore scoped voting-key entry and read-only contests, add optimistic schedule editing, and correlate manual task results across navigation. Cache recent activity and surface storage failures distinctly. Validated with 52 focused unit tests, 22 masternode app tests, library clippy and pinned formatting. Co-Authored-By: GPT-6 Astra --- docs/user-stories.md | 7 +- src/app.rs | 136 +++- src/backend_task/mod.rs | 48 +- src/model/dpns_vote_schedule.rs | 25 + src/model/mod.rs | 1 + src/ui/dpns/dpns_contested_names_screen.rs | 767 ++++++++++++++++-- .../scheduled_vote_editor.rs | 240 ++++++ src/ui/masternodes/detail_screen.rs | 138 +++- src/ui/masternodes/list_screen.rs | 22 +- src/ui/mod.rs | 7 +- src/ui/state/dpns_vote_operations.rs | 76 +- tests/kittest/masternode_tab.rs | 22 +- 12 files changed, 1348 insertions(+), 141 deletions(-) create mode 100644 src/model/dpns_vote_schedule.rs create mode 100644 src/ui/dpns/dpns_contested_names_screen/scheduled_vote_editor.rs diff --git a/docs/user-stories.md b/docs/user-stories.md index 6bec75973..9961b2bb2 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -793,7 +793,7 @@ As a masternode operator, I want to vote on contested DPNS name registrations so As a masternode operator, I want to schedule votes for later execution so that I can plan my voting strategy in advance. - Set vote to be cast at a future time. -- View and manage scheduled votes under DPNS β†’ Scheduled votes, which remains available in the persistent DPNS subnavigation. +- View and manage scheduled votes under DPNS β†’ Scheduled votes, which remains available in the persistent DPNS subnavigation. Edit changes the choice or absolute UTC time of a vote that has not started, keeping the same node and contest. An edit is rejected if the schedule changed or began executing while the editor was open. - Scheduled and immediate votes share the same target locks and result states. - Removing a scheduled vote takes it off the list for good; it does not come back on the next refresh. - An ambiguous result remains visible for checking and is never automatically rebroadcast. @@ -804,7 +804,8 @@ As a masternode operator, I want to schedule votes for later execution so that I 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. - Review and cast defaults to all loaded voting nodes and Cast now. -- The advanced per-node disclosure can set each node to Cast now, Schedule, or Do not use this node. +- The advanced per-node disclosure can set each node to Cast now, Schedule after a delay, or Do not use this node. The common UTC picker preserves its absolute timestamp while the review is open. +- Switching networks clears staged votes and open review/edit dialogs; choices from the previous network are never carried into the new one. - When no loaded node has a voting key, Active contests shows an actionable Load a masternode state instead of vote controls. A masternode loaded without its voting key is not a voting node, so it reaches that state instead of the composer. - Per-node timing overrides and multi-contest selections create exact node Γ— contest targets. - Review and cast lists each of those targets with its node, contest, requested choice, current choice, and timing, and reports how many targets it skipped because the node already holds the requested choice. @@ -1716,7 +1717,7 @@ As a masternode operator, I want the Masternodes tab to reset to a clean state w As a masternode operator, I want a Refresh control on the Masternodes tab, so that I can pull the latest node identity 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 one identity refresh per loaded node, or for the single open node on the detail view. -- Refresh is a no-op when no node is loaded. DPNS Active contests owns its separate contest refresh action. +- The card-list Refresh also queries DPNS contests when at least one node is loaded; the detail-view Refresh updates only that node's identity. Refresh is a no-op when no node is loaded. DPNS Active contests also exposes its own contest refresh action. ### MN-012: Switch wallet/identity from the Masternodes header [Implemented] **Persona:** Priya diff --git a/src/app.rs b/src/app.rs index 330c7c79d..6e02df2ba 100644 --- a/src/app.rs +++ b/src/app.rs @@ -475,18 +475,23 @@ fn identity_hub_is_visible(selected: RootScreenType, screen_stack_is_empty: bool selected == RootScreenType::RootScreenIdentityHub && screen_stack_is_empty } -fn dpns_result_needs_hidden_active_contests_route( - selected: RootScreenType, - screen_stack_is_empty: bool, - result: &BackendTaskSuccessResult, -) -> bool { +fn is_dpns_vote_result(result: &BackendTaskSuccessResult) -> bool { matches!( result, BackendTaskSuccessResult::DpnsVoteOperationUpdated { .. } | BackendTaskSuccessResult::RefreshedDpnsContests | BackendTaskSuccessResult::ScheduledVoteSweepCompleted { .. } | BackendTaskSuccessResult::ScheduledVotesCleared(_) - ) && (selected != RootScreenType::RootScreenDPNSActiveContests || !screen_stack_is_empty) + ) +} + +fn dpns_result_needs_hidden_route( + target: RootScreenType, + selected: RootScreenType, + screen_stack_is_empty: bool, + result: &BackendTaskSuccessResult, +) -> bool { + is_dpns_vote_result(result) && (selected != target || !screen_stack_is_empty) } /// Plain, jargon-free descriptions for the SPV-sync block (Everyday-User rule: @@ -2651,24 +2656,48 @@ impl AppState { } } - fn route_dpns_vote_result_to_hidden_active_contests( + fn route_dpns_vote_result_to_hidden_screens( &mut self, context: &BackendTaskContext, result: &BackendTaskSuccessResult, ) { - if !dpns_result_needs_hidden_active_contests_route( - self.selected_main_screen, - self.screen_stack.is_empty(), - result, - ) { + for root in [ + RootScreenType::RootScreenDPNSActiveContests, + RootScreenType::RootScreenDPNSScheduledVotes, + ] { + if dpns_result_needs_hidden_route( + root, + self.selected_main_screen, + self.screen_stack.is_empty(), + result, + ) && let Some(screen) = self.main_screens.get_mut(&root) + { + screen.display_backend_task_result(context, result.clone()); + if matches!(result, BackendTaskSuccessResult::RefreshedDpnsContests) { + screen.refresh(); + } + } + } + } + + fn route_dpns_vote_error_to_hidden_screens( + &mut self, + context: &BackendTaskContext, + error: &TaskError, + ) { + if !context.is_dpns_vote_task() { return; } - if let Some(screen) = self - .main_screens - .get_mut(&RootScreenType::RootScreenDPNSActiveContests) - { - screen.display_backend_task_result(context, result.clone()); - screen.refresh(); + for root in [ + RootScreenType::RootScreenDPNSActiveContests, + RootScreenType::RootScreenDPNSScheduledVotes, + ] { + if (self.selected_main_screen != root || !self.screen_stack.is_empty()) + && let Some(screen) = self.main_screens.get_mut(&root) + { + screen.display_backend_task_error(context, error); + screen.display_task_error(error); + } } } @@ -3049,10 +3078,7 @@ impl App for AppState { let unboxed_message = *message; clear_profile_saving_banner_after_success(ctx, &context, &unboxed_message); self.route_contact_request_result_to_hidden_hub(&unboxed_message); - self.route_dpns_vote_result_to_hidden_active_contests( - &context, - &unboxed_message, - ); + self.route_dpns_vote_result_to_hidden_screens(&context, &unboxed_message); match unboxed_message { BackendTaskSuccessResult::RemovedIdentities { .. } => { deliver_identity_removal_result( @@ -3243,12 +3269,13 @@ impl App for AppState { ) { self.scheduled_vote_recovery_last_attempt.remove(&network); } - if self.selected_main_screen - == RootScreenType::RootScreenDPNSActiveContests - && self.screen_stack.is_empty() - { - self.visible_screen_mut().refresh(); - } + 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); @@ -3344,6 +3371,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); @@ -3367,6 +3395,7 @@ impl App for AppState { &err, ); self.route_contact_request_error_to_hidden_hub(&err); + self.route_dpns_vote_error_to_hidden_screens(&context, &err); let is_database_clear = context == BackendTaskContext::ClearNetworkDatabase; let suppress_stale_error = !is_database_clear && self @@ -4259,6 +4288,33 @@ mod dpns_result_routing_tests { DpnsVoteOperationId, }; + #[test] + fn voting_ui_results_route_to_each_hidden_dpns_screen_only_once() { + let result = BackendTaskSuccessResult::ScheduledVoteSweepCompleted { + network: Network::Testnet, + preserve_eligibility_since_ms: None, + }; + for root in [ + RootScreenType::RootScreenDPNSActiveContests, + RootScreenType::RootScreenDPNSScheduledVotes, + ] { + 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_active_contests_is_hidden() { let result = BackendTaskSuccessResult::DpnsVoteOperationUpdated { @@ -4266,17 +4322,20 @@ mod dpns_result_routing_tests { operation_id: DpnsVoteOperationId::from_bytes([7; 16]), }; - assert!(dpns_result_needs_hidden_active_contests_route( + assert!(dpns_result_needs_hidden_route( + RootScreenType::RootScreenDPNSActiveContests, RootScreenType::RootScreenWalletsBalances, true, &result, )); - assert!(dpns_result_needs_hidden_active_contests_route( + assert!(dpns_result_needs_hidden_route( + RootScreenType::RootScreenDPNSActiveContests, RootScreenType::RootScreenDPNSActiveContests, false, &result, )); - assert!(!dpns_result_needs_hidden_active_contests_route( + assert!(!dpns_result_needs_hidden_route( + RootScreenType::RootScreenDPNSActiveContests, RootScreenType::RootScreenDPNSActiveContests, true, &result, @@ -4285,7 +4344,8 @@ mod dpns_result_routing_tests { #[test] fn refreshed_contests_route_when_active_contests_is_hidden() { - assert!(dpns_result_needs_hidden_active_contests_route( + assert!(dpns_result_needs_hidden_route( + RootScreenType::RootScreenDPNSActiveContests, RootScreenType::RootScreenWalletsBalances, true, &BackendTaskSuccessResult::RefreshedDpnsContests, @@ -4299,17 +4359,20 @@ mod dpns_result_routing_tests { preserve_eligibility_since_ms: None, }; - assert!(dpns_result_needs_hidden_active_contests_route( + assert!(dpns_result_needs_hidden_route( + RootScreenType::RootScreenDPNSActiveContests, RootScreenType::RootScreenWalletsBalances, true, &result, )); - assert!(dpns_result_needs_hidden_active_contests_route( + assert!(dpns_result_needs_hidden_route( + RootScreenType::RootScreenDPNSActiveContests, RootScreenType::RootScreenDPNSActiveContests, false, &result, )); - assert!(!dpns_result_needs_hidden_active_contests_route( + assert!(!dpns_result_needs_hidden_route( + RootScreenType::RootScreenDPNSActiveContests, RootScreenType::RootScreenDPNSActiveContests, true, &result, @@ -4318,7 +4381,8 @@ mod dpns_result_routing_tests { #[test] fn cleared_scheduled_votes_route_when_active_contests_is_hidden() { - assert!(dpns_result_needs_hidden_active_contests_route( + assert!(dpns_result_needs_hidden_route( + RootScreenType::RootScreenDPNSActiveContests, RootScreenType::RootScreenDPNSScheduledVotes, true, &BackendTaskSuccessResult::ScheduledVotesCleared(Vec::new()), diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 88d8f7f6e..362ffd560 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -12,7 +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, DpnsVoteOperationId}; +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; @@ -334,6 +336,10 @@ pub enum BackendTaskContext { }, /// A scheduled-vote sweep for one network. ScheduledVoteSweep { network: Network }, + /// 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. @@ -359,14 +365,24 @@ pub enum BackendTaskContext { } impl BackendTaskContext { - /// The context for `task` about to run on `network`. Identical to - /// `From<&BackendTask>` except that a wallet payment broadcast records the - /// network: the task alone cannot name it β€” a [`Wallet`](crate::model::wallet::Wallet) - /// carries none, and its extended public key cannot tell Devnet or Regtest - /// from Testnet β€” and a late "outcome unknown" error must not be adopted by - /// whichever network happens to be selected when it lands. + /// Bind tasks whose payload omits a network to their originating network, + /// so late wallet and scheduled-vote results cannot affect another context. pub(crate) fn for_task_on(task: &BackendTask, network: Network) -> Self { match task { + BackendTask::ContestedResourceTask(ContestedResourceTask::EditScheduledDpnsVote { + key, + .. + }) => Self::DpnsScheduledVoteEdit { key: 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 } } @@ -397,6 +413,24 @@ impl BackendTaskContext { } } + pub(crate) fn is_dpns_vote_task(&self) -> bool { + matches!( + self.operation(), + Self::DpnsVoteOperation { .. } + | 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, .. } => operation, 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/mod.rs b/src/model/mod.rs index c102ce87d..c463cc310 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -6,6 +6,7 @@ pub mod dashpay; pub mod dashpay_derivation; pub(crate) mod data_migration; pub mod dpns; +pub(crate) mod dpns_vote_schedule; pub mod dpns_voting; pub mod fee_estimation; pub mod grovestark_prover; diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 1a9be1d5a..8a4e21c86 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -1,8 +1,11 @@ +mod scheduled_vote_editor; +use scheduled_vote_editor::{EditOutcome, ScheduledVoteEditor}; + use crate::wallet_backend::poison::MutexRecover; -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::{Arc, Mutex}; -use chrono::{DateTime, LocalResult, NaiveDate, NaiveTime, TimeZone, Timelike, Utc}; +use chrono::{DateTime, LocalResult, TimeZone, Timelike, Utc}; use chrono_humanize::HumanTime; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::platform_value::string_encoding::Encoding; @@ -195,13 +198,12 @@ fn scheduled_vote_removal_task(row: &ScheduledDpnsVoteRow) -> ContestedResourceT /// 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) -> Vec { - app_context - .load_local_voting_identities() - .unwrap_or_default() +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() + .collect()) } /// One reviewed node Γ— contest line, carrying the timing text the operator chose. @@ -285,10 +287,16 @@ fn review_current_choice_label( } } -fn dpns_operation_id(context: &BackendTaskContext) -> Option { +fn dpns_operation_id( + context: &BackendTaskContext, + network: dash_sdk::dpp::dashcore::Network, +) -> Option { match context { - BackendTaskContext::Dispatched { operation, .. } => dpns_operation_id(operation), - BackendTaskContext::DpnsVoteOperation { operation_id, .. } => Some(*operation_id), + BackendTaskContext::Dispatched { operation, .. } => dpns_operation_id(operation, network), + BackendTaskContext::DpnsVoteOperation { + operation_id, + network: origin, + } if *origin == network => Some(*operation_id), _ => None, } } @@ -316,7 +324,13 @@ pub struct SelectedVote { pub enum VoteOption { NoVote, CastNow, - Scheduled { days: u32, hours: u32, minutes: u32 }, + Scheduled { + days: u32, + hours: u32, + minutes: u32, + }, + /// Absolute UTC time, in Unix milliseconds. + ScheduledAt(u64), } #[derive(PartialEq)] @@ -356,6 +370,7 @@ enum SortOrder { /// - Shows scheduled votes listing pub struct DPNSScreen { voting_identities: Vec, + voting_identity_load_error: Option, user_identities: Vec, contested_names: Arc>>, active_contests: ActiveDpnsContestSnapshot, @@ -368,9 +383,10 @@ pub struct DPNSScreen { vote_state: DpnsVoteStateSnapshot, vote_overlay: Option, pending_vote_operation: Option, - pending_scheduled_casts: BTreeSet, + pending_scheduled_actions: BTreeMap, clear_vote_overlay_on_error: bool, scheduled_clear_dialog: Option<(bool, ConfirmationDialog)>, + scheduled_vote_editor: Option, /// Sorting sort_column: SortColumn, @@ -432,7 +448,14 @@ impl DPNSScreen { DPNSSubscreen::ScheduledVotes => Vec::new(), })); - let voting_identities = loaded_voting_identities(app_context); + 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 user_identities = app_context.load_local_user_identities().unwrap_or_default(); let vote_poll_ids = active_contests.vote_poll_ids(); let voter_ids = voting_identities @@ -452,6 +475,7 @@ impl DPNSScreen { Self { voting_identities, + voting_identity_load_error, user_identities, contested_names, active_contests, @@ -469,9 +493,10 @@ impl DPNSScreen { vote_state, vote_overlay: None, pending_vote_operation: None, - pending_scheduled_casts: BTreeSet::new(), + pending_scheduled_actions: BTreeMap::new(), clear_vote_overlay_on_error: false, scheduled_clear_dialog: None, + scheduled_vote_editor: None, dpns_subscreen, refreshing_status: RefreshingStatus::NotRefreshing, refresh_banner: None, @@ -487,6 +512,49 @@ impl DPNSScreen { } } + 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); + if self.pending_vote_operation.is_none() { + self.vote_overlay.take_and_clear(); + } + true + } else { + false + } + } + + pub(crate) fn reset_for_network_switch(&mut self) { + self.selected_votes.clear(); + self.show_bulk_schedule_popup = false; + self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; + self.bulk_identity_options.clear(); + self.set_all_option = VoteOption::CastNow; + self.pending_backend_task = None; + self.pending_vote_operation = None; + self.pending_scheduled_actions.clear(); + self.clear_vote_overlay_on_error = false; + self.scheduled_clear_dialog = None; + self.scheduled_vote_editor = None; + self.vote_overlay.take_and_clear(); + self.refresh_banner.take_and_clear(); + self.refreshing_status = RefreshingStatus::NotRefreshing; + self.voting_identities.clear(); + self.voting_identity_load_error = None; + self.user_identities.clear(); + self.vote_state = DpnsVoteStateSnapshot::default(); + self.vote_operations = DpnsVoteOperationSnapshot::default(); + self.active_contests = ActiveDpnsContestSnapshot::default(); + self.contested_names.lock_recover().clear(); + self.scheduled_votes.lock_recover().clear(); + self.local_dpns_names.lock_recover().clear(); + } + // --------------------------- // Sorting // --------------------------- @@ -699,7 +767,7 @@ impl DPNSScreen { ui, "Not votable by your nodes", &groups[2], - false, + self.voting_identities.is_empty(), false, false, ); @@ -953,15 +1021,27 @@ impl DPNSScreen { } } + fn review_failed_target(&mut self, outcome: &crate::model::dpns_voting::DpnsVoteOutcome) { + self.selected_votes.clear(); + self.set_selected_vote_from_outcome(outcome); + self.bulk_identity_options = self + .voting_identities + .iter() + .map(|voter| { + if voter.identity.id() == outcome.target.key.voter_id { + VoteOption::CastNow + } else { + VoteOption::NoVote + } + }) + .collect(); + self.set_all_option = VoteOption::CastNow; + self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; + self.show_bulk_schedule_popup = true; + } + fn render_voting_activity(&mut self, ui: &mut Ui) { - let mut operations = self.vote_operations.operations().to_vec(); - operations.sort_by_key(|operation| operation.created_at); - let operations = operations - .into_iter() - .rev() - .filter(|operation| !operation.targets.is_empty()) - .take(5) - .collect::>(); + let operations = self.vote_operations.recent_operations(); if operations.is_empty() { return; } @@ -969,7 +1049,7 @@ impl DPNSScreen { let dark_mode = ui.style().visuals.dark_mode; ui.add_space(12.0); ui.heading("Recent voting activity"); - for operation in operations { + for operation in operations.iter() { let settled = operation .targets .iter() @@ -986,7 +1066,8 @@ impl DPNSScreen { for outcome in &operation.targets { ui.horizontal_wrapped(|ui| { ui.label(format!( - "{}.dash β€” {} β€” {}", + "{} β€” {}.dash β€” {} β€” {}", + outcome.target.voter_alias.clone().unwrap_or_else(|| short_identifier(outcome.target.key.voter_id)), outcome.target.contested_name, vote_choice_label( outcome.target.requested_choice, @@ -1030,11 +1111,7 @@ impl DPNSScreen { ) .clicked() { - self.set_selected_vote_from_outcome(outcome); - self.bulk_identity_options = - vec![VoteOption::CastNow; self.voting_identities.len()]; - self.set_all_option = VoteOption::CastNow; - self.show_bulk_schedule_popup = true; + self.review_failed_target(outcome); } }); if matches!( @@ -1542,12 +1619,19 @@ impl DPNSScreen { ), ); } + if ui.add_enabled(scheduled_row.status == DpnsVoteTargetStatus::Scheduled + && !self.pending_scheduled_actions.contains_key(&pending_key), Button::new("Edit")) + .disabled_tooltip("Only scheduled votes that have not started can be edited.") + .clicked() { + self.open_schedule_editor(scheduled_row); + } let cast_button_enabled = scheduled_vote_cast_enabled( scheduled_row.status, - self.pending_scheduled_casts.contains(&pending_key), - ); + self.pending_scheduled_actions.contains_key(&pending_key), + ) && self.voting_identities.iter().any(|identity| identity.identity.id() == vote.voter_id); if ui .add_enabled(cast_button_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) = self .voting_identities @@ -1557,16 +1641,11 @@ impl DPNSScreen { }) .cloned() { - self.pending_scheduled_casts - .insert(pending_key.clone()); - action = AppAction::BackendTask( - BackendTask::ContestedResourceTask( - ContestedResourceTask::CastScheduledVote( - vote.clone(), - Box::new(found), - ), - ), - ); + let task = BackendTask::ContestedResourceTask( + ContestedResourceTask::CastScheduledVote(vote.clone(), Box::new(found))); + let context = BackendTaskContext::for_dispatch_on(&task, self.app_context.network()); + self.pending_scheduled_actions.insert(pending_key.clone(), context.clone()); + action = AppAction::BackendTaskWithContext { task, context }; show_cast_overlay = true; } }); @@ -1582,21 +1661,54 @@ impl DPNSScreen { action } - fn simple_schedule_option(&self) -> Option { - let date = NaiveDate::parse_from_str(&self.simple_schedule_date, "%Y-%m-%d").ok()?; - let time = - NaiveTime::from_hms_opt(self.simple_schedule_hour, self.simple_schedule_minute, 0)?; - let scheduled_at = DateTime::::from_naive_utc_and_offset(date.and_time(time), Utc); - let seconds = scheduled_at.signed_duration_since(Utc::now()).num_seconds(); - if seconds <= 0 { - return None; + 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; + }; + 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(|| short_identifier(row.vote.voter_id)); + let mut choices = vec![ + (ResourceVoteChoice::Lock, "Lock".to_owned()), + (ResourceVoteChoice::Abstain, "Abstain".to_owned()), + ]; + if let Some(contest) = self + .contested_names + .lock_recover() + .iter() + .find(|contest| contest.normalized_contested_name == row.vote.contested_name) + && let Some(candidates) = &contest.contestants + { + choices.extend(candidates.iter().map(|candidate| { + ( + ResourceVoteChoice::TowardsIdentity(candidate.id), + format!("Vote for {}", candidate.name), + ) + })); } - let total_minutes = u32::try_from((seconds + 59) / 60).ok()?; - Some(VoteOption::Scheduled { - days: total_minutes / (24 * 60), - hours: total_minutes / 60 % 24, - minutes: total_minutes % 60, - }) + 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); + } + + fn simple_schedule_option(&self) -> Option { + let timestamp = crate::model::dpns_vote_schedule::parse_utc_schedule( + &self.simple_schedule_date, + self.simple_schedule_hour, + self.simple_schedule_minute, + )?; + (timestamp > Utc::now().timestamp_millis() as u64) + .then_some(VoteOption::ScheduledAt(timestamp)) } fn apply_all_nodes_option(&mut self, option: VoteOption) { @@ -1640,6 +1752,16 @@ impl DPNSScreen { self.vote_operations.scheduled_vote_rows(&legacy_votes); } + 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.", + ); + if ui.button("Retry loading nodes").clicked() { + self.refresh_on_arrival(); + } + } + fn show_review_and_cast_window(&mut self, ui: &mut Ui) -> AppAction { let mut action = AppAction::None; @@ -1650,6 +1772,14 @@ impl DPNSScreen { return action; } + 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; + } + return action; + } + if self.voting_identities.is_empty() { ui.add_space(5.0); ui.colored_label( @@ -1721,6 +1851,10 @@ impl DPNSScreen { &entry.timing_label, )); } + if plan.effective().any(|entry| entry.target.current_choice.is_some()) { + ui.colored_label(DashColors::warning_color(dark_mode), + "Changing an existing vote uses one of that node's four allowed vote changes."); + } if plan.no_op_count() > 0 { ui.label(review_skipped_line(plan.no_op_count())); } @@ -1749,17 +1883,17 @@ impl DPNSScreen { } if ui .selectable_label( - matches!(self.set_all_option, VoteOption::Scheduled { .. }), + matches!(self.set_all_option, VoteOption::ScheduledAt(_)), "Schedule for later", ) .clicked() - && let Some(option) = self.simple_schedule_option() { + let option = self.simple_schedule_option().unwrap_or(VoteOption::ScheduledAt(0)); self.apply_all_nodes_option(option); } }); - if matches!(self.set_all_option, VoteOption::Scheduled { .. }) { + if matches!(self.set_all_option, VoteOption::ScheduledAt(_)) { let mut schedule_changed = false; ui.horizontal(|ui| { ui.label("Cast on (UTC):"); @@ -1790,7 +1924,12 @@ impl DPNSScreen { if schedule_changed && let Some(option) = self.simple_schedule_option() { - self.apply_all_nodes_option(option); + self.set_all_option = option.clone(); + for current in &mut self.bulk_identity_options { + if matches!(current, VoteOption::ScheduledAt(_)) { + *current = option.clone(); + } + } } if !simple_schedule_valid { ui.colored_label( @@ -1827,7 +1966,8 @@ impl DPNSScreen { .selected_text(match current_option { VoteOption::NoVote => "Do not use this node".to_string(), VoteOption::CastNow => "Cast now".to_string(), - VoteOption::Scheduled { .. } => "Schedule".to_string(), + VoteOption::Scheduled { .. } => "Schedule after a delay".to_string(), + VoteOption::ScheduledAt(_) => "At selected UTC time".to_string(), }) .show_ui(ui, |ui| { if ui @@ -1902,7 +2042,7 @@ impl DPNSScreen { }); }); // If any selected votes are scheduled, show a warning - if !matches!(self.set_all_option, VoteOption::Scheduled { .. }) + if !matches!(self.set_all_option, VoteOption::ScheduledAt(_)) && self .bulk_identity_options .iter() @@ -2017,6 +2157,10 @@ impl DPNSScreen { /// promise something other than what is sent. `Err` carries the message the /// operator sees, and blocks submission. fn build_review_plan(&self) -> Result { + self.build_review_plan_at(Utc::now()) + } + + fn build_review_plan_at(&self, now: DateTime) -> Result { let mut entries = Vec::new(); let mut voters = Vec::new(); for (identity, option) in self @@ -2027,6 +2171,20 @@ impl DPNSScreen { let (timing, timing_label) = match option { VoteOption::NoVote => continue, VoteOption::CastNow => (VoteTiming::Now, "Cast now".to_owned()), + VoteOption::ScheduledAt(timestamp) => { + if *timestamp <= now.timestamp_millis() as u64 { + return Err( + "Choose a future date and time before scheduling these votes." + .to_owned(), + ); + } + let date = DateTime::from_timestamp_millis(*timestamp as i64) + .ok_or_else(|| "Choose a valid UTC date and time.".to_owned())?; + ( + VoteTiming::Scheduled(*timestamp), + format!("Scheduled for {} UTC", date.format("%Y-%m-%d %H:%M")), + ) + } VoteOption::Scheduled { days, hours, @@ -2036,7 +2194,7 @@ impl DPNSScreen { + chrono::Duration::hours(*hours as i64) + chrono::Duration::minutes(*minutes as i64); ( - VoteTiming::Scheduled((Utc::now() + offset).timestamp_millis() as u64), + VoteTiming::Scheduled((now + offset).timestamp_millis() as u64), format!("Scheduled in {days} d {hours} h {minutes} min"), ) } @@ -2245,9 +2403,39 @@ impl ScreenLike for DPNSScreen { } fn refresh_on_arrival(&mut self) { - self.voting_identities = loaded_voting_identities(&self.app_context); - self.bulk_identity_options = vec![VoteOption::CastNow; self.voting_identities.len()]; - self.set_all_option = VoteOption::CastNow; + let previous_options = self + .voting_identities + .iter() + .zip(&self.bulk_identity_options) + .map(|(identity, option)| (identity.identity.id(), option.clone())) + .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); + } + } + self.bulk_identity_options = self + .voting_identities + .iter() + .map(|identity| { + previous_options + .get(&identity.identity.id()) + .cloned() + .unwrap_or({ + if self.selected_votes.is_empty() { + VoteOption::CastNow + } else { + VoteOption::NoVote + } + }) + }) + .collect(); self.user_identities = self .app_context .load_local_user_identities() @@ -2264,13 +2452,14 @@ impl ScreenLike for DPNSScreen { fn display_backend_task_error(&mut self, context: &BackendTaskContext, _error: &TaskError) { self.clear_vote_overlay_on_error = match self.pending_vote_operation { - Some(operation_id) => dpns_operation_id(context) == Some(operation_id), - None => self.vote_overlay.is_some() && dpns_operation_id(context).is_none(), + Some(operation_id) => { + dpns_operation_id(context, self.app_context.network()) == Some(operation_id) + } + None => self.finish_scheduled_dispatch(context), }; } fn display_task_error(&mut self, error: &TaskError) -> bool { - self.pending_scheduled_casts.clear(); if self.clear_vote_overlay_on_error { self.vote_overlay.take_and_clear(); self.pending_vote_operation = None; @@ -2296,18 +2485,28 @@ impl ScreenLike for DPNSScreen { 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) { match backend_task_success_result { - BackendTaskSuccessResult::DpnsVoteOperationUpdated { operation_id, .. } => { - self.pending_scheduled_casts.clear(); + BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network, + operation_id, + } if network == self.app_context.network() => { 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) - || (self.pending_vote_operation.is_none() && self.vote_overlay.is_some()); + let owns_result = self.pending_vote_operation == Some(operation_id); if owns_result { self.vote_overlay.take_and_clear(); self.pending_vote_operation = None; @@ -2326,6 +2525,11 @@ impl ScreenLike for DPNSScreen { } self.rebuild_scheduled_vote_rows(); } + BackendTaskSuccessResult::ScheduledVoteSweepCompleted { network, .. } + if network == self.app_context.network() => + { + self.refresh(); + } BackendTaskSuccessResult::ScheduledVotesInProgress(_) => { if let Err(error) = self.vote_operations.refresh(&self.app_context) { tracing::warn!(?error, "Could not refresh scheduled-vote operation state"); @@ -2333,7 +2537,6 @@ impl ScreenLike for DPNSScreen { self.rebuild_scheduled_vote_rows(); } BackendTaskSuccessResult::ScheduledVotesCleared(_) => { - self.pending_scheduled_casts.clear(); if let Err(error) = self.vote_operations.refresh(&self.app_context) { tracing::warn!( ?error, @@ -2472,6 +2675,22 @@ impl ScreenLike for DPNSScreen { })); } } + 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()); + inner_action = AppAction::BackendTaskWithContext { task, context }; + self.scheduled_vote_editor = None; + self.raise_vote_overlay(ui.ctx(), "Saving the scheduled vote…"); + } + } + } // Bulk-schedule ephemeral popup if self.show_bulk_schedule_popup { egui::Window::new("Review and cast") @@ -2483,13 +2702,19 @@ impl ScreenLike for DPNSScreen { }); } + if self.voting_identity_load_error.is_some() && !self.show_bulk_schedule_popup { + self.render_voting_identity_load_error(ui); + } // Render sub-screen match self.dpns_subscreen { DPNSSubscreen::Active => { let has_any = !self.active_contests.is_empty(); - if self.voting_identities.is_empty() { + if self.voting_identities.is_empty() + && self.voting_identity_load_error.is_none() + { inner_action |= self.render_no_voting_nodes(ui); - } else if has_any { + } + if has_any { self.render_active_contests(ui); } else { inner_action |= self.render_no_active_contests_or_owned_names(ui); @@ -2719,8 +2944,8 @@ mod tests { ); screen - .pending_scheduled_casts - .insert(pending_scheduled_key(&ctx)); + .pending_scheduled_actions + .insert(pending_scheduled_key(&ctx), BackendTaskContext::Unknown); screen.display_task_result(BackendTaskSuccessResult::DpnsVoteOperationUpdated { network: ctx.network(), operation_id: DpnsVoteOperationId::from_bytes([7; 16]), @@ -2729,7 +2954,7 @@ mod tests { assert!( !crate::ui::components::progress_overlay::ProgressOverlay::has_global(ctx.egui_ctx()) ); - assert!(screen.pending_scheduled_casts.is_empty()); + assert!(!screen.pending_scheduled_actions.is_empty()); } #[test] @@ -2843,7 +3068,7 @@ mod tests { } #[test] - fn scheduled_vote_sweep_error_is_handled_after_cleanup() { + fn scheduled_vote_sweep_error_preserves_unrelated_manual_cast() { let (ctx, _temp_dir) = offline_ctx(); let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::ScheduledVotes); let error = TaskError::ScheduledVoteSweepFailed { @@ -2854,10 +3079,10 @@ mod tests { }; screen - .pending_scheduled_casts - .insert(pending_scheduled_key(&ctx)); + .pending_scheduled_actions + .insert(pending_scheduled_key(&ctx), BackendTaskContext::Unknown); assert!(screen.display_task_error(&error)); - assert!(screen.pending_scheduled_casts.is_empty()); + assert!(!screen.pending_scheduled_actions.is_empty()); } #[test] @@ -2866,10 +3091,10 @@ mod tests { let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::ScheduledVotes); screen - .pending_scheduled_casts - .insert(pending_scheduled_key(&ctx)); + .pending_scheduled_actions + .insert(pending_scheduled_key(&ctx), BackendTaskContext::Unknown); assert!(!screen.display_task_error(&TaskError::ScheduledVoteResultUnavailable)); - assert!(screen.pending_scheduled_casts.is_empty()); + assert!(!screen.pending_scheduled_actions.is_empty()); let sweep_error = TaskError::ScheduledVoteSweepFailed { network: Network::Regtest, @@ -2878,8 +3103,8 @@ mod tests { assert!(!screen.display_task_error(&sweep_error)); screen - .pending_scheduled_casts - .insert(pending_scheduled_key(&ctx)); + .pending_scheduled_actions + .insert(pending_scheduled_key(&ctx), BackendTaskContext::Unknown); let exhausted_error = TaskError::ScheduledVoteSweepAllAddressesExhausted { network: Network::Regtest, source: Box::new(TaskError::DapiNoAddresses { @@ -2889,7 +3114,7 @@ mod tests { }), }; assert!(!screen.display_task_error(&exhausted_error)); - assert!(screen.pending_scheduled_casts.is_empty()); + assert!(!screen.pending_scheduled_actions.is_empty()); } #[test] @@ -3083,6 +3308,370 @@ mod tests { assert_eq!(screen.voting_identities.len(), 1); } + 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, DPNSSubscreen::Active); + screen.voting_identities = vec![voter.clone()]; + screen.bulk_identity_options = vec![VoteOption::CastNow]; + 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 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.simple_schedule_date = requested.format("%Y-%m-%d").to_string(); + screen.simple_schedule_hour = 18; + screen.simple_schedule_minute = 30; + screen.apply_all_nodes_option(screen.simple_schedule_option().unwrap()); + let plan = screen.build_review_plan().unwrap(); + assert_eq!( + plan.entries[0].target.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.entries[0].target.timing, + plan.entries[0].target.timing + ); + } + + #[test] + fn voting_ui_manual_cast_completes_only_for_its_exact_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()); + screen.raise_vote_overlay(&screen.app_context.egui_ctx().clone(), "Submitting…"); + 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)); + assert!(screen.vote_overlay.is_some()); + 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)); + assert!(screen.vote_overlay.is_some()); + screen.display_backend_task_result(&dispatch, updated); + assert!(screen.pending_scheduled_actions.is_empty()); + assert!(screen.vote_overlay.is_none()); + screen + .pending_scheduled_actions + .insert(key.clone(), dispatch.clone()); + 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()); + screen.reset_for_network_switch(); + assert!(screen.pending_scheduled_actions.is_empty()); + assert!(!screen.finish_scheduled_dispatch(&dispatch)); + } + + #[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, DPNSSubscreen::Active); + 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(), + }], + ); + 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_reads(true); + assert!(loaded_voting_identities(&context).is_err()); + for reviewing in [false, true] { + let mut screen = DPNSScreen::new(&context, DPNSSubscreen::Active); + assert!(screen.voting_identity_load_error.is_some()); + screen.show_bulk_schedule_popup = 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, DPNSSubscreen::Active); + screen.selected_votes = vec![SelectedVote { + contested_name: "alpha".into(), + vote_choice: ResourceVoteChoice::Lock, + end_time: None, + }]; + screen.bulk_identity_options = screen + .voting_identities + .iter() + .map(|identity| { + if identity.identity.id() == first.identity.id() { + VoteOption::CastNow + } else { + VoteOption::NoVote + } + }) + .collect(); + screen.refresh_on_arrival(); + let selected = screen + .voting_identities + .iter() + .zip(&screen.bulk_identity_options) + .filter(|(_, option)| !matches!(option, VoteOption::NoVote)) + .map(|(identity, _)| identity.identity.id()) + .collect::>(); + assert_eq!(selected, vec![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(); + let new_option = screen + .voting_identities + .iter() + .zip(&screen.bulk_identity_options) + .find(|(identity, _)| identity.identity.id() == newly_loaded.identity.id()) + .unwrap() + .1; + assert!(matches!(new_option, VoteOption::NoVote)); + 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 = DpnsVoteOperation::new(vec![ + screen.build_review_plan().unwrap().entries.remove(0).target, + ]); + 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, + }); + screen.review_failed_target(&operation.targets[0]); + let plan = screen.build_review_plan().unwrap(); + assert_eq!(plan.effective_count(), 1); + assert_eq!(plan.entries[0].target.key, operation.targets[0].target.key); + } + + #[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_review_and_cast_window(ui); + }); + harness.run(); + assert!( + harness + .query_by_label( + "Changing an existing vote uses one of that node's four allowed vote changes." + ) + .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_review_and_cast_window(ui); + }); + harness.run(); + assert!( + harness + .query_by_label( + "Changing an existing vote uses one of that node's four allowed vote changes." + ) + .is_none() + ); + } + + #[test] + fn voting_ui_activity_identifies_each_node() { + use egui_kittest::kittest::Queryable; + let (mut screen, _temp_dir) = voting_ui_review_fixture(); + let plan = screen.build_review_plan().unwrap(); + let mut first = plan.entries[0].target.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 = Some("node-two".to_owned()); + let mut operation = DpnsVoteOperation::new(vec![first, second]); + operation.targets[0].status = DpnsVoteTargetStatus::Confirmed; + operation.targets[1].status = DpnsVoteTargetStatus::Rejected; + screen + .app_context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + screen.vote_operations.refresh(&screen.app_context).unwrap(); + let mut harness = egui_kittest::Harness::builder().build_ui(move |ui| { + screen.render_voting_activity(ui); + }); + harness.run(); + assert!( + harness + .query_by_label("node-one β€” alpha.dash β€” Abstain β€” Confirmed") + .is_some() + ); + assert!( + harness + .query_by_label("node-two β€” alpha.dash β€” Abstain β€” Rejected") + .is_some() + ); + } + + #[test] + fn voting_ui_network_switch_discards_staged_choices() { + let (mut screen, _temp_dir) = voting_ui_review_fixture(); + screen.show_bulk_schedule_popup = 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()); + let mut wrapper = crate::ui::Screen::DPNSScreen(screen); + wrapper.change_context(new_context); + wrapper.refresh_on_arrival(); + let crate::ui::Screen::DPNSScreen(screen) = wrapper else { + unreachable!() + }; + assert!(screen.selected_votes.is_empty()); + assert!(!screen.show_bulk_schedule_popup); + 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.dpns_subscreen = DPNSSubscreen::ScheduledVotes; + let mut target = screen.build_review_plan().unwrap().entries.remove(0).target; + target.timing = VoteTiming::Scheduled(42); + let mut operation = DpnsVoteOperation::new(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 + ); + } + /// The review sheet must expand every node Γ— contest pair, suppress the /// targets that already hold the requested choice, and count what it dropped. #[tokio::test] 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..2b400b6f1 --- /dev/null +++ b/src/ui/dpns/dpns_contested_names_screen/scheduled_vote_editor.rs @@ -0,0 +1,240 @@ +//! Editing a schedule keeps its original target and submits an optimistic update. + +use super::*; +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, + date: String, + hour: u32, + minute: u32, + 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)>, + ) -> 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, + date: time.format("%Y-%m-%d").to_string(), + hour: time.hour(), + minute: time.minute(), + 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 { + crate::model::dpns_vote_schedule::parse_utc_schedule( + &self.date, + self.hour, + self.minute, + )? + } else { + self.original.vote.unix_timestamp + }; + if timestamp <= now_ms + || !self + .choices + .iter() + .any(|(choice, _)| *choice == self.choice) + { + return None; + } + Some(ContestedResourceTask::EditScheduledDpnsVote { + operation_id: self.original.journal_target.as_ref().map(|(id, _)| *id), + 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!( + "{} β€” {}.dash", + self.node_label, 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); + } + }); + ui.horizontal(|ui| { + ui.label("Cast on (UTC):"); + self.time_changed |= ui + .add( + egui::TextEdit::singleline(&mut self.date) + .hint_text("YYYY-MM-DD") + .desired_width(100.0), + ) + .changed(); + self.time_changed |= ui + .add( + egui::DragValue::new(&mut self.hour) + .prefix("Hour: ") + .range(0..=23), + ) + .changed(); + self.time_changed |= ui + .add( + egui::DragValue::new(&mut self.minute) + .prefix("Minute: ") + .range(0..=59), + ) + .changed(); + }); + ui.label("Keep Dash Evo Tool running and connected until the scheduled time."); + 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. 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 { + 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: Some((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()), + ], + ) + .unwrap(); + editor.choice = ResourceVoteChoice::Abstain; + let ContestedResourceTask::EditScheduledDpnsVote { + 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.map(|(id, _)| id)); + 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.date = "2031-02-03".into(); + editor.hour = 4; + editor.minute = 5; + let ContestedResourceTask::EditScheduledDpnsVote { 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() + ); + } +} diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index 0f6841f69..71484f635 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -17,16 +17,18 @@ use eframe::egui::{self, Color32, RichText, Ui}; use std::collections::BTreeMap; use crate::app::AppAction; -use crate::backend_task::identity::IdentityTask; +use crate::backend_task::identity::{IdentityInputToLoad, IdentityLoadMode, IdentityTask}; use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; use crate::context::AppContext; use crate::model::fee_estimation::format_credits_as_dash; use crate::model::legacy_recovery::RecoveryItem; use crate::model::qualified_identity::{IdentityType, MasternodeKeyPresence, QualifiedIdentity}; +use crate::model::secret::Secret; use crate::ui::components::MessageBanner; 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::identity::identity_picker_card::draw_type_badge; use crate::ui::identity::identity_pill::shorten_id; use crate::ui::identity::keys::key_info_screen::KeyInfoScreen; @@ -105,6 +107,7 @@ pub struct MasternodeDetailView { node_id_short: String, key_presence: MasternodeKeyPresence, remove_dialog: Option, + voter_key_prompt: Option, /// The offer to restore keys this node left behind in the previous /// version's saved data (issue #889). recovery: LegacyRecoveryState, @@ -112,6 +115,18 @@ pub struct MasternodeDetailView { #[cfg(test)] impl MasternodeDetailView { + /// Open the `Add voting key` prompt on a key, as typing into it would. + pub(crate) fn set_voter_key_prompt_for_test(&mut self, value: &str) { + let mut prompt = PasswordInput::new(); + prompt.set_text(value); + self.voter_key_prompt = Some(prompt); + } + + /// Whether the `Add voting key` prompt is open β€” and thus holding a key. + pub(crate) fn has_voter_key_prompt_for_test(&self) -> bool { + self.voter_key_prompt.is_some() + } + /// Whether a recovery offer is currently on screen for this node. pub(crate) fn has_recovery_offer_for_test(&self) -> bool { self.recovery.has_offer() @@ -158,6 +173,7 @@ impl MasternodeDetailView { node_id_short, key_presence, remove_dialog: None, + voter_key_prompt: None, recovery, } } @@ -538,6 +554,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) = self.recovery.restore(approved) { @@ -546,6 +567,79 @@ 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)), + ); + + 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; + 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, + // The backend creates and owns this load's registry record. + load_token: None, + }; + 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> { @@ -673,6 +767,48 @@ mod tests { use super::*; use crate::model::secret::Secret; + #[test] + fn voting_ui_scoped_key_update_merges_into_the_current_node() { + use crate::model::qualified_identity::{IdentityStatus, encrypted_key_storage::KeyStorage}; + use dash_sdk::dpp::identity::Identity; + use dash_sdk::dpp::version::PlatformVersion; + let dir = tempfile::tempdir().unwrap(); + let ctx = crate::context::test_support::test_app_context(dir.path()); + let id = Identifier::from([0x47; 32]); + let identity = QualifiedIdentity { + identity: Identity::create_basic_identity(id, 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(), + }; + let mut detail = MasternodeDetailView::new(&ctx, identity); + 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()); + } + #[test] fn masternode_removal_dispatches_the_identity_backend_task() { let identity_id = Identifier::from([0x42; 32]); diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index 614f7269d..663acde38 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -582,7 +582,8 @@ impl ScreenLike for MasternodesScreen { fn on_leave(&mut self) { match &mut self.view { MasternodesView::Load(form) => form.clear_secrets(), - MasternodesView::List | MasternodesView::Detail(_) => {} + MasternodesView::Detail(detail) => detail.clear_secrets(), + MasternodesView::List => {} } } @@ -1740,6 +1741,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 diff --git a/src/ui/mod.rs b/src/ui/mod.rs index a0f050936..7941e5789 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -727,6 +727,11 @@ impl Screen { screen.reset_for_context_change(); return; } + Screen::DPNSScreen(screen) => { + screen.app_context = app_context; + screen.reset_for_network_switch(); + return; + } Screen::MasternodesScreen(screen) => { screen.app_context = app_context; // A network switch invalidates any open load form or detail view @@ -742,7 +747,6 @@ impl Screen { // The `skip` list must exactly match the explicit match arms above. set_ctx!( set: - DPNSScreen, AddExistingIdentityScreen, KeyInfoScreen, KeysScreen, @@ -785,6 +789,7 @@ impl Screen { PauseTokensScreen, ResumeTokensScreen; skip: + DPNSScreen, MasternodesScreen, NetworkChooserScreen, AddNewWalletScreen, diff --git a/src/ui/state/dpns_vote_operations.rs b/src/ui/state/dpns_vote_operations.rs index dec12a268..16608a88f 100644 --- a/src/ui/state/dpns_vote_operations.rs +++ b/src/ui/state/dpns_vote_operations.rs @@ -1,6 +1,7 @@ //! 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; @@ -19,6 +20,8 @@ pub(crate) struct ScheduledDpnsVoteRow { #[derive(Debug, Clone, Default)] pub struct DpnsVoteOperationSnapshot { operations: Vec, + recent_operations: Arc<[DpnsVoteOperation]>, + dismissed_schedules: BTreeSet<(DpnsVoteOperationId, DpnsVoteTargetKey)>, target_statuses: BTreeMap, loaded: bool, } @@ -31,7 +34,10 @@ impl DpnsVoteOperationSnapshot { } pub fn refresh(&mut self, app_context: &AppContext) -> Result<(), TaskError> { - self.replace(app_context.dpns_vote_operations()?); + let operations = app_context.dpns_vote_operations()?; + let dismissals = app_context.dismissed_dpns_vote_schedules()?; + self.replace(operations); + self.dismissed_schedules = dismissals; Ok(()) } @@ -39,6 +45,10 @@ impl DpnsVoteOperationSnapshot { &self.operations } + pub(crate) fn recent_operations(&self) -> Arc<[DpnsVoteOperation]> { + Arc::clone(&self.recent_operations) + } + pub fn operation(&self, id: DpnsVoteOperationId) -> Option<&DpnsVoteOperation> { self.operations.iter().find(|operation| operation.id == id) } @@ -104,6 +114,11 @@ impl DpnsVoteOperationSnapshot { .into_values() .map(|(_, row)| row) .filter(|row| row.status != DpnsVoteTargetStatus::Cancelled) + .filter(|row| { + !row.journal_target + .as_ref() + .is_some_and(|key| self.dismissed_schedules.contains(key)) + }) .collect::>(); rows.extend( legacy_votes @@ -131,6 +146,12 @@ impl DpnsVoteOperationSnapshot { .filter(|outcome| outcome.status.holds_lock()) .map(|outcome| (outcome.target.key.clone(), outcome.status)) .collect(); + let mut recent = operations + .iter() + .filter(|operation| !operation.targets.is_empty()) + .collect::>(); + recent.sort_by_key(|operation| operation.created_at); + self.recent_operations = recent.into_iter().rev().take(5).cloned().collect(); self.operations = operations; self.loaded = true; } @@ -145,6 +166,59 @@ mod tests { use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; use dash_sdk::platform::Identifier; + #[test] + fn voting_ui_recent_activity_is_bounded_ordered_and_shared_between_frames() { + let mut snapshot = DpnsVoteOperationSnapshot::default(); + let operations = (0..20) + .map(|created_at| { + let mut operation = operation(DpnsVoteTargetStatus::Confirmed); + operation.created_at = created_at; + operation + }) + .collect(); + snapshot.replace(operations); + let first = snapshot.recent_operations(); + let second = snapshot.recent_operations(); + assert!(Arc::ptr_eq(&first, &second)); + assert_eq!( + first + .iter() + .map(|operation| operation.created_at) + .collect::>(), + vec![19, 18, 17, 16, 15] + ); + assert_eq!(snapshot.operations().len(), 20); + } + + #[test] + fn voting_ui_dismissed_terminal_row_suppresses_its_mirror_and_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(&[legacy_vote( + original.target.key.voter_id, + "alice", + ResourceVoteChoice::Lock, + 100, + true, + )]); + 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 = DpnsVoteOperation::new(vec![DpnsVoteTarget { key: DpnsVoteTargetKey { diff --git a/tests/kittest/masternode_tab.rs b/tests/kittest/masternode_tab.rs index 4527ed1d4..4376c3aa9 100644 --- a/tests/kittest/masternode_tab.rs +++ b/tests/kittest/masternode_tab.rs @@ -314,7 +314,7 @@ fn masternodes_has_no_operator_voting_subnavigation() { let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime"); let _guard = rt.enter(); - let mut harness = mount_app(RootScreenType::RootScreenIdentities); + let mut harness = mount_app(RootScreenType::RootScreenIdentityHub); let app_context = harness.state().current_app_context().clone(); activate_masternodes_tab(&mut harness, &app_context); @@ -643,7 +643,7 @@ fn detail_dpns_voting_button_opens_active_contests() { .query_by_label_contains("DPNS name contests to vote on") .is_none() ); - assert!(harness.query_by_label("Add voting key").is_none()); + assert!(harness.query_by_label("Add voting key").is_some()); assert!(harness.query_by_label_contains("Review ").is_none()); harness.get_by_label("DPNS Voting").click(); @@ -703,6 +703,22 @@ fn masternode_selection_never_leaks_to_app_global_identity() { }); } +/// Drain the asynchronous removal result before asserting the resulting UI/storage state. +fn wait_for_node_removal( + harness: &mut egui_kittest::Harness<'static, dash_evo_tool::app::AppState>, + alias: &str, +) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while harness.query_all_by_label(alias).count() > 0 { + assert!( + std::time::Instant::now() < deadline, + "node removal must finish" + ); + std::thread::sleep(std::time::Duration::from_millis(10)); + harness.run_steps(1); + } +} + /// TC-US4-01/02/06/07 β€” the detail Remove flow: the danger button opens a /// confirmation with the `Remove masternode` verb; confirming deletes only the /// target node (its card disappears) and leaves other nodes intact (isolation). @@ -743,6 +759,7 @@ fn remove_flow_deletes_only_target_node() { .expect("confirm button present"); confirm.click(); harness.run_steps(3); + wait_for_node_removal(&mut harness, "mn-remove-me"); // Only the target node was deleted; the other remains (isolation). let remaining = app_context @@ -808,6 +825,7 @@ fn remove_flow_deletes_associated_voter_identity() { .expect("confirm button present"); confirm.click(); harness.run_steps(3); + wait_for_node_removal(&mut harness, "mn-with-voter"); // Both the node and its voter identity are deleted. assert_eq!( From f0dd759cf980d629ea7b844b193f3ddc57830c9e Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 8 Sep 2026 15:02:37 +0000 Subject: [PATCH 043/194] fix(identity): cancel stale loads and preserve scoped key updates Validate load claims under the identity record lock through final persistence and key protection. Removal invalidates older loads; fresh imports remain supported. Scoped key merges re-read current metadata and keys and revalidate the protection password before sealing. Retry orphaned DPNS dismissal cleanup from the network-owned namespace after partial operation deletion. --- src/backend_task/error.rs | 4 + src/backend_task/identity/load_identity.rs | 380 +++++++++++++++--- .../identity/protect_identity_keys.rs | 3 +- src/context/dpns_vote_operations.rs | 83 +++- src/context/identity_db.rs | 11 + src/context/identity_load_registry.rs | 74 +++- 6 files changed, 504 insertions(+), 51 deletions(-) diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index f0ace4df3..f9a007b9d 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1783,6 +1783,10 @@ pub enum TaskError { )] IdentityLoadInProgress { identity_id: Identifier }, + /// The load was invalidated by removal or a scoped target changed protection. + #[error("This node changed while its key was loading. Open the current node 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( diff --git a/src/backend_task/identity/load_identity.rs b/src/backend_task/identity/load_identity.rs index 5420cd8e3..c9112e364 100644 --- a/src/backend_task/identity/load_identity.rs +++ b/src/backend_task/identity/load_identity.rs @@ -154,6 +154,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); + } _ => {} } @@ -484,38 +487,16 @@ impl AppContext { status: IdentityStatus::Active, network: self.network, }; - // Β§10.8: an in-place update (the "Add voting key" fix-up) merges the - // newly-supplied keys into the already-stored identity's keys instead of - // clobbering them β€” the new voting key is added while the existing - // Owner/Payout keys (which the update leaves blank) survive. - if load_mode == IdentityLoadMode::MergeIntoExisting - && let Some(existing) = existing_stored - { - merge_existing_keys_into(&mut qualified_identity, existing); - } - - // When merging into a Tier-2 node, seal the newly-merged plaintext - // keys Tier-2 under the already-verified password and mark them InVault - // BEFORE the insert, so the fail-closed guard sees no resident plaintext - // on a protected identity β€” the same seal-before-persist add_key_to_identity - // performs. The password was verified up front, before the network fetch. - // - // TODO(#889 review): this seal has no `reject_resident_identity_plaintext` - // preflight, unlike the protect opt-in and the legacy-recovery merge. An - // existing record still carrying resident plaintext from an unfinished - // vault migration is sealed around here, which half-protects the identity - // and then trips the downgrade guard at persist. Out of scope for #889; - // needs its own issue. - if let Some(password) = &merge_seal_password { - self.seal_merged_plaintext_keys(&mut qualified_identity, password)?; - } - - let wallet_info = qualified_identity - .determine_wallet_info() - .map_err(|e| TaskError::WalletInfoDeterminationFailed { detail: e })?; - - // Insert qualified identity into the database - self.insert_local_qualified_identity(&qualified_identity, &wallet_info)?; + // 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) @@ -526,16 +507,6 @@ impl AppContext { .insert(identity_index, qualified_identity.identity.clone()); } - // FR-8: when a load-time password was supplied, seal the just-inserted - // keyless keys Tier-2 through the existing per-identity protect - // envelope. `insert_local_qualified_identity` migrated the resident - // plaintext into the keyless vault, so `protect_identity_keys` - // (validate β†’ fail-closed guard β†’ seal via the secret_seam chokepoint) - // reloads from the DB and seals them β€” one path, no new crypto. - if let Some(password) = encryption_password { - self.protect_identity_keys(qualified_identity.identity.id(), password, None)?; - } - // 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. @@ -544,6 +515,78 @@ impl AppContext { Ok(BackendTaskSuccessResult::LoadedIdentity(qualified_identity)) } + 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> { + 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 let Some(password) = encryption_password { + validate_protection_password(password)?; + } + let wallet_info = if load_mode != IdentityLoadMode::MergeIntoExisting { + let wallet_info = qualified_identity + .determine_wallet_info() + .map_err(|detail| TaskError::WalletInfoDeterminationFailed { detail })?; + self.import_local_qualified_identity_locked(qualified_identity, &wallet_info)?; + wallet_info + } else { + if !self.is_identity_listed(&identity_id)? { + return Err(TaskError::IdentityNotFoundLocally); + } + let existing = self + .get_identity_by_id(&identity_id)? + .ok_or(TaskError::IdentityNotFoundLocally)?; + // 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 }), + } + // This mode is a key fix-up. Its 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; + merge_existing_keys_into(qualified_identity, existing); + if let Some(password) = merge_password { + // TODO(#889 review): reject resident plaintext left by an incomplete + // legacy migration before sealing around it (as the protect path does). + self.seal_merged_plaintext_keys(qualified_identity, password)?; + } + let wallet_info = qualified_identity + .determine_wallet_info() + .map_err(|detail| TaskError::WalletInfoDeterminationFailed { detail })?; + self.write_local_qualified_identity_locked(qualified_identity)?; + wallet_info + }; + if let Some(password) = encryption_password { + let stored = self + .get_identity_by_id(&identity_id)? + .ok_or(TaskError::IdentityNotFoundLocally)?; + self.protect_loaded_identity_keys(&stored, password, None)?; + } + Ok(wallet_info) + } + /// Seal every resident-plaintext key of `qi` Tier-2 under an /// already-verified identity object `password`, marking each `InVault`. /// Called on the in-place merge path when the target node is @@ -807,6 +850,221 @@ mod tests { const M: PrivateKeyTarget = PrivateKeyTarget::PrivateKeyOnMainIdentity; const V: PrivateKeyTarget = PrivateKeyTarget::PrivateKeyOnVoterIdentity; + #[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( @@ -1156,8 +1414,38 @@ mod tests { .verify_identity_object_password(&verify_scope) .await .expect("scripted password verifies"); - ctx.seal_merged_plaintext_keys(&mut existing, &password) - .expect("seal merged plaintext 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!( @@ -1168,10 +1456,6 @@ mod tests { "the merged voting key must be marked InVault after sealing", ); - // ...the at-rest insert now passes the fail-closed guard... - ctx.insert_local_qualified_identity(&existing, &None) - .expect("insert of a Tier-2 node with a sealed new key must succeed"); - // ...and the new key reads back as a Tier-2 (Protected) sealed secret. let backend = ctx.wallet_backend().expect("backend wired"); let view = IdentityKeyView::new(backend.secret_store(), identity_id.to_buffer()); diff --git a/src/backend_task/identity/protect_identity_keys.rs b/src/backend_task/identity/protect_identity_keys.rs index 08b7470f9..2808de10c 100644 --- a/src/backend_task/identity/protect_identity_keys.rs +++ b/src/backend_task/identity/protect_identity_keys.rs @@ -68,7 +68,8 @@ 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. - fn protect_loaded_identity_keys( + /// The caller must hold this identity's record guard through the seal. + pub(super) fn protect_loaded_identity_keys( &self, qi: &QualifiedIdentity, password: &Secret, diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index 03e40323b..e597333b3 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -407,7 +407,9 @@ pub(super) fn prune_terminal_operations(kv: &DetKv, network: Network) -> Result< .map(|operation| operation.id) .collect::>(); let scheduled_count = delete_terminal_operations(kv, network, &terminal_ids)?; - Ok(scheduled_count + prune_immediate_history(kv, network, None)?) + let immediate_count = prune_immediate_history(kv, network, None)?; + prune_orphaned_schedule_dismissals(kv, network)?; + Ok(scheduled_count + immediate_count) } fn prune_immediate_history( @@ -466,6 +468,32 @@ fn prune_immediate_history( Ok(removed) } +/// 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. +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_tag(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::>(); + for key in kv + .list(DetScope::Global, Some(&dismissal_prefix)) + .map_err(unreadable_operation_err)? + { + if key + .strip_prefix(&dismissal_prefix) + .is_some_and(|suffix| !live_suffixes.contains(suffix)) + { + kv.delete(DetScope::Global, &key).map_err(operation_err)?; + } + } + Ok(()) +} + fn delete_terminal_operations( kv: &DetKv, network: Network, @@ -1152,6 +1180,7 @@ impl AppContext { } } prune_immediate_history(&kv, self.network, None)?; + prune_orphaned_schedule_dismissals(&kv, self.network)?; Ok(()) } @@ -2540,6 +2569,58 @@ mod tests { ); } + #[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!(prune_terminal_operations(&kv, Network::Testnet).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 terminal_schedule_dismissal_preserves_outcome_and_survives_mirror_delete_failure() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index a4d74e44f..8ee267331 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -884,6 +884,16 @@ impl AppContext { let _guard = lock .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); + self.import_local_qualified_identity_locked(qualified_identity, wallet_and_identity_id_info) + } + + /// Explicit import, including retirement of an unload marker. The caller + /// must hold this identity's record guard across authorization and this write. + pub(crate) fn import_local_qualified_identity_locked( + &self, + qualified_identity: &QualifiedIdentity, + wallet_and_identity_id_info: &Option<(WalletSeedHash, u32)>, + ) -> std::result::Result<(), TaskError> { // Deliberate: asking for an identity is the one act that means the user // 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 @@ -1812,6 +1822,7 @@ impl AppContext { .unwrap_or_else(std::sync::PoisonError::into_inner); 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)?; let sidecar_cleanup = self.finish_identity_removal_cleanup(&kv, &id, vault_keys)?; // Mirror removal into the upstream unowned scope; wallet-owned identities are unaffected. diff --git a/src/context/identity_load_registry.rs b/src/context/identity_load_registry.rs index c94debb41..8d54dc18c 100644 --- a/src/context/identity_load_registry.rs +++ b/src/context/identity_load_registry.rs @@ -27,6 +27,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. @@ -105,6 +109,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) { @@ -121,7 +145,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 { @@ -170,6 +194,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 @@ -237,6 +275,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( @@ -356,6 +397,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. From 4d0571139f36d8b9d820ea557018463a79a17590 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 8 Sep 2026 15:06:31 +0000 Subject: [PATCH 044/194] docs(dpns): describe reviewed voting and scheduling behavior MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Codex GPT-6 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 91ed52967..a7c586571 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -97,6 +97,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Platform allows up to four changes after the initial vote. The Masternodes detail screen no longer casts votes inline β€” its "DPNS Voting" button takes you straight to Active contests instead. + Review shows each node's current and requested choice and warns when a + change uses the limited allowance; it does not claim a remaining count. + Uncertain results stay visible and blocked from repeat submission. + Scheduled votes retain the selected UTC time and can be edited before + execution starts. Removing a node cancels its unstarted scheduled votes. + Contests remain readable without a voting key, and a missing voting key + can be added from the node's detail page without replacing its other keys. - **Wallet/identity indicator on more screens (rollout in progress)**: the wallet and identity picker previously shown only at the top of the Identity From 5277eebbc2298eabce392583295c0ac598ac3a47 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 9 Sep 2026 08:24:48 +0000 Subject: [PATCH 045/194] fix(dpns): preserve scheduled vote eligibility and validate new schedules MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep explicit retries on the fresh-proof preflight path, reject invalid new schedule times before persistence, and preserve due admissions across slow or failed reconciliation. Ignore dismissed terminal schedules in node summaries while retaining unresolved siblings and historical outcomes. Co-Authored-By: GPT-6 Astra πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/backend_task/contested_names/mod.rs | 403 +++++++++++++++++++++--- src/context/contested_names_db.rs | 111 ++++++- src/model/dpns_voting.rs | 16 +- 3 files changed, 479 insertions(+), 51 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 415c3dfac..30612287e 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -9,9 +9,10 @@ use crate::backend_task::BackendTaskSuccessResult; use crate::backend_task::error::{DapiAddressAvailability, TaskError}; use crate::context::AppContext; use crate::model::dpns_voting::{ - DpnsCurrentVoteState, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, - DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, failed_before_broadcast_outcome, - unavailable_preflight_outcome, + DpnsCurrentVoteState, DpnsScheduleEditValidationError, DpnsVoteFailure, DpnsVoteOperation, + DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + 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; @@ -392,8 +393,15 @@ impl AppContext { VoteTiming::Scheduled(scheduled_vote.unix_timestamp), false, )?; - let mut operation = DpnsVoteOperation::new(vec![target]); - operation.targets[0].status = DpnsVoteTargetStatus::Queued; + // An explicit retry must reach fresh preflight even if the cached + // choice matches. Preflight records an already-satisfied target durably. + let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + current_choice: None, + ..target + }]); + for outcome in &mut operation.targets { + outcome.status = DpnsVoteTargetStatus::Queued; + } Ok(operation) } @@ -431,6 +439,45 @@ impl AppContext { Ok(()) } + fn validate_new_dpns_schedules(&self, targets: &[DpnsVoteTarget]) -> Result<(), TaskError> { + if targets.is_empty() { + return Ok(()); + } + let now_ms = UNIX_EPOCH.elapsed().unwrap_or_default().as_millis() as u64; + // 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(()) + } + async fn execute_dpns_vote_operation( self: &Arc, mut operation: DpnsVoteOperation, @@ -445,6 +492,13 @@ impl AppContext { }); } 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 @@ -513,6 +567,7 @@ impl AppContext { .dpns_vote_operation(operation.id)? .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; } else { + self.validate_new_dpns_schedules(&new_schedules)?; let scheduled_votes = operation .targets .iter() @@ -883,42 +938,30 @@ impl AppContext { }) } - /// 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; terminal state - /// is persisted in the shared operation journal and legacy executed flag. - /// - /// [`ScheduledVotesInProgress`]: BackendTaskSuccessResult::ScheduledVotesInProgress - async fn cast_due_scheduled_votes( - self: &Arc, - sdk: &Sdk, - sender: crate::utils::egui_mpsc::SenderAsync, + /// Preserve durable due targets and catch up after unrelated reconciliation. + async fn prepare_due_scheduled_votes( + &self, + clock: impl Fn() -> u64, preserve_eligibility_since_ms: Option, - ) -> Result { - for operation in self - .dpns_vote_operations()? - .into_iter() - .filter(|operation| { - operation - .targets - .iter() - .any(|outcome| outcome.status == DpnsVoteTargetStatus::Unconfirmed) - }) - { - let result = self - .reconcile_dpns_vote_operation(operation.id, sdk) - .await?; - let _ = sender.send(TaskResult::unattributed_success(result)).await; - } + reconcile: impl std::future::Future>, + ) -> Result<(Vec, Vec), TaskError> { + let started_at = clock(); + let eligibility_cutoff = preserve_eligibility_since_ms.unwrap_or(started_at); + // Persist entry admissions before the await so errors or interruption + // cannot turn an eligible target into a stale schedule on the next sweep. + self.queue_due_scheduled_votes_at(started_at, eligibility_cutoff)?; + let reconciliation = reconcile.await; + // Also admit schedules that became due while reconciliation was waiting. + let admitted = self.queue_due_scheduled_votes_at(clock(), eligibility_cutoff)?; + reconciliation?; + Ok(admitted) + } - let now_ms = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_millis() as u64) - .unwrap_or(0); + fn queue_due_scheduled_votes_at( + &self, + now_ms: u64, + eligibility_cutoff: u64, + ) -> Result<(Vec, Vec), TaskError> { let mut due_operations = Vec::new(); let mut in_progress = Vec::new(); for mut operation in self.dpns_vote_operations()? { @@ -931,7 +974,7 @@ impl AppContext { outcome.status, scheduled_at, now_ms, - preserve_eligibility_since_ms, + Some(eligibility_cutoff), ) { continue; } @@ -954,6 +997,46 @@ impl AppContext { due_operations.push(operation); } } + Ok((due_operations, in_progress)) + } + + /// Reconcile unresolved votes and execute each admitted scheduled operation. + /// 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, + ) -> Result { + let (due_operations, in_progress) = self + .prepare_due_scheduled_votes( + || { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) + }, + preserve_eligibility_since_ms, + async { + for operation in + self.dpns_vote_operations()? + .into_iter() + .filter(|operation| { + operation.targets.iter().any(|outcome| { + outcome.status == DpnsVoteTargetStatus::Unconfirmed + }) + }) + { + let result = self + .reconcile_dpns_vote_operation(operation.id, sdk) + .await?; + let _ = sender.send(TaskResult::unattributed_success(result)).await; + } + + Ok(()) + }, + ) + .await?; if due_operations.is_empty() { return Ok(BackendTaskSuccessResult::ScheduledVoteSweepCompleted { network: self.network, @@ -1105,6 +1188,246 @@ mod tests { } } + fn r2_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) + } + + fn r2_schedule(context: &AppContext, name: &str, timestamp: u64) -> DpnsVoteOperation { + DpnsVoteOperation::new(vec![ + context + .dpns_vote_target( + &qualified_identity(1), + name, + ResourceVoteChoice::Lock, + VoteTiming::Scheduled(timestamp), + false, + ) + .unwrap(), + ]) + } + + #[test] + fn r2_terminal_retry_with_matching_cache_reaches_durable_no_op_preflight() { + let (_temp, context) = r2_context(); + let mut previous = r2_schedule(&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_with_scheduled_mirror(&mut retry, None, &[scheduled]) + .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 r2_sweep_preserves_due_votes_across_slow_reconciliation() { + let (_temp, context) = r2_context(); + let started = 1_000_000; + let clock = std::cell::Cell::new(started); + let mut operation = r2_schedule(&context, "alice", started); + context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + let (due, _) = context + .prepare_due_scheduled_votes(|| clock.get(), None, async { + clock.set(started + SCHEDULED_VOTE_MAX_LATENESS_MS + 1); + Ok(()) + }) + .await + .unwrap(); + assert_eq!( + due.len(), + 1, + "reconciliation must not expire a schedule eligible at sweep entry" + ); + assert_eq!( + context + .dpns_vote_operation(operation.id) + .unwrap() + .unwrap() + .targets[0] + .status, + DpnsVoteTargetStatus::Queued + ); + } + + #[tokio::test] + async fn r2_sweep_reconciliation_failure_retains_durable_due_admission() { + let (_temp, context) = r2_context(); + let started = 1_000_000; + let clock = std::cell::Cell::new(started); + let mut due = r2_schedule(&context, "alice", started); + let mut newly_due = r2_schedule(&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 + .prepare_due_scheduled_votes(|| clock.get(), None, 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" + ); + } + } + + #[tokio::test] + async fn r2_new_schedule_rejects_past_time_before_persistence() { + let (_temp, context) = r2_context(); + let operation = r2_schedule(&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 r2_new_schedule_validates_known_deadline_and_unknown_deadline_policy() { + let now = UNIX_EPOCH.elapsed().unwrap().as_millis() as u64; + 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) = r2_context(); + context.seed_dpns_contest_for_test("alice", deadline, false); + let operation = r2_schedule(&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 r2_new_schedule_rejects_mixed_deadlines_atomically_and_missing_or_closed_contests() { + let now = UNIX_EPOCH.elapsed().unwrap().as_millis() as u64; + let timestamp = now + 60_000; + let (_temp, context) = r2_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 = r2_schedule(&context, "alice", timestamp).targets; + targets.extend(r2_schedule(&context, "bob", timestamp).targets); + let operation = DpnsVoteOperation::new(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()); + assert!(context.get_scheduled_votes().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( + r2_schedule(&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 r2_sweep_preserves_newly_due_but_excludes_already_stale_and_future_targets() { + let (_temp, context) = r2_context(); + let started = 1_000_000; + let finished = started + SCHEDULED_VOTE_MAX_LATENESS_MS * 2; + let clock = std::cell::Cell::new(started); + for (name, timestamp) in [ + ("newlydue", started + 10), + ("stale", started - SCHEDULED_VOTE_MAX_LATENESS_MS - 1), + ("future", finished + 1), + ] { + context + .insert_dpns_vote_operation(&mut r2_schedule(&context, name, timestamp), None) + .unwrap(); + } + let (due, _) = context + .prepare_due_scheduled_votes(|| clock.get(), None, async { + clock.set(finished); + Ok(()) + }) + .await + .unwrap(); + assert_eq!(due.len(), 1); + assert_eq!(due[0].targets[0].target.contested_name, "newlydue"); + } + #[test] fn cast_now_durably_queues_an_existing_scheduled_operation() { let temp_dir = tempfile::tempdir().expect("tempdir"); diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 6dd9239c0..ae10be90c 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -13,7 +13,8 @@ use crate::model::contested_name::{ pending_usernames_in, }; use crate::model::dpns_voting::{ - DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteTargetStatus, VoteTiming, + DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, + DpnsVoteTargetStatus, VoteTiming, }; use crate::model::qualified_identity::QualifiedIdentity; use crate::wallet_backend::{DetScope, KvAdapterError}; @@ -27,7 +28,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 @@ -42,6 +43,7 @@ fn contested_name_key(normalized_name: &str) -> String { fn scheduled_vote_journal_summary( operations: &[DpnsVoteOperation], voter_id: Identifier, + dismissed: &BTreeSet<(DpnsVoteOperationId, DpnsVoteTargetKey)>, ) -> (bool, bool) { let latest_by_target = operations .iter() @@ -72,7 +74,7 @@ fn scheduled_vote_journal_summary( matches!( outcome.status, DpnsVoteTargetStatus::Rejected | DpnsVoteTargetStatus::FailedBeforeSubmission - ) + ) && !dismissed.contains(&(outcome.operation_id, outcome.target.key.clone())) }); (pending, failed) } @@ -337,6 +339,37 @@ impl AppContext { .unwrap_or_default() } + /// 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 = std::time::UNIX_EPOCH.elapsed().unwrap().as_millis() as u64; + 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`); @@ -390,8 +423,11 @@ impl AppContext { .count(); let vote_state = vote_state_summary(&states); - let (has_scheduled_vote, has_failed_scheduled_vote) = - scheduled_vote_journal_summary(&self.dpns_vote_operations()?, voter_id); + let (has_scheduled_vote, has_failed_scheduled_vote) = scheduled_vote_journal_summary( + &self.dpns_vote_operations()?, + voter_id, + &self.dismissed_dpns_vote_schedules()?, + ); Ok(crate::model::contested_name::MasternodeContestSummary { open_contest_count, @@ -826,6 +862,65 @@ mod tests { ); } + #[test] + fn r2_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 = DpnsVoteOperation::new(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( + Some(operation.id), + &operation.targets[0].target.key, + "alice", + ) + .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]); @@ -846,7 +941,7 @@ mod tests { operation.targets[0].status = DpnsVoteTargetStatus::FailedBeforeSubmission; assert_eq!( - scheduled_vote_journal_summary(&[operation], voter_id), + scheduled_vote_journal_summary(&[operation], voter_id, &BTreeSet::new()), (false, true) ); } @@ -871,7 +966,7 @@ mod tests { operation.targets[0].status = DpnsVoteTargetStatus::Cancelled; assert_eq!( - scheduled_vote_journal_summary(&[operation], voter_id), + scheduled_vote_journal_summary(&[operation], voter_id, &BTreeSet::new()), (false, false) ); } @@ -900,7 +995,7 @@ mod tests { confirmed.targets[0].status = DpnsVoteTargetStatus::Confirmed; assert_eq!( - scheduled_vote_journal_summary(&[failed, confirmed], voter_id), + scheduled_vote_journal_summary(&[failed, confirmed], voter_id, &BTreeSet::new()), (false, false) ); } diff --git a/src/model/dpns_voting.rs b/src/model/dpns_voting.rs index 7d5e66344..8bc7c55df 100644 --- a/src/model/dpns_voting.rs +++ b/src/model/dpns_voting.rs @@ -224,6 +224,18 @@ pub enum DpnsScheduleEditValidationError { 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, @@ -234,9 +246,7 @@ pub fn validate_dpns_schedule_edit( if !contest.is_votable() { return Err(DpnsScheduleEditValidationError::Contest); } - if unix_timestamp <= now_ms || contest.end_time.is_some_and(|end| unix_timestamp >= end) { - return Err(DpnsScheduleEditValidationError::Time); - } + validate_dpns_schedule_time(unix_timestamp, now_ms, contest.end_time)?; if let ResourceVoteChoice::TowardsIdentity(id) = choice && !contest .contestants From 010121882be2a148ad6fcd23c9b6cb89c8503bc0 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 9 Sep 2026 08:30:49 +0000 Subject: [PATCH 046/194] docs(dpns): clarify recovery visibility and schedule validation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Codex GPT-6 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 7 ++++++- .../2026-07-16-dpns-voting-experience/02-ux-spec.md | 6 ++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a7c586571..203f98794 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -100,8 +100,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Review shows each node's current and requested choice and warns when a change uses the limited allowance; it does not claim a remaining count. Uncertain results stay visible and blocked from repeat submission. + Unresolved operations remain accessible after a contest closes and are + not displaced by newer completed votes. Failed scheduled attempts retain + an actionable explanation after restarting the app. Scheduled votes retain the selected UTC time and can be edited before - execution starts. Removing a node cancels its unstarted scheduled votes. + execution starts. New schedules must precede the contest's known deadline; + checking older uncertain votes does not discard schedules already due. + Removing a node cancels its unstarted scheduled votes. Contests remain readable without a voting key, and a missing voting key can be added from the node's detail page without replacing its other keys. 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 index dbb6d7357..16e8d4cb1 100644 --- 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 @@ -132,6 +132,12 @@ or shortened Base58 identifier, a human-readable choice, absolute UTC time plus relative time, typed status, and only valid actions. Past contests describe the winner or locked outcome in words rather than exposing an unexplained raw ID. +Unresolved voting operations remain accessible even when no active contests +remain. Completed recent history has a separate limit, so new batches cannot +hide an uncertain result or its check action. A failed scheduled attempt shows +its saved failure reason and an applicable action after navigation or restart. +New schedules and edits reject times at or after a known contest deadline. + ## Accessibility and responsive behavior - Tally chips have no click or keyboard behavior. From b22cc755b37ce758c00ea5e0734d160a319ec05f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 9 Sep 2026 08:31:06 +0000 Subject: [PATCH 047/194] fix(dpns): keep unresolved voting activity and failed state visible --- src/context/dpns_vote_state.rs | 17 ++ src/ui/dpns/dpns_contested_names_screen.rs | 277 +++++++++++++++++- .../scheduled_vote_editor.rs | 1 + src/ui/state/dpns_vote_operations.rs | 48 ++- src/ui/state/dpns_vote_state.rs | 87 +++++- 5 files changed, 398 insertions(+), 32 deletions(-) diff --git a/src/context/dpns_vote_state.rs b/src/context/dpns_vote_state.rs index beaf8ef57..3d10a49c2 100644 --- a/src/context/dpns_vote_state.rs +++ b/src/context/dpns_vote_state.rs @@ -173,6 +173,23 @@ fn snapshot_vote_state( } impl AppContext { + /// 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.refresh_dpns_vote_state_with( + &self.det_kv()?, + voter_id, + std::future::ready(Err(Box::new(dash_sdk::Error::InvalidProvedResponse( + "test proof unavailable".into(), + )))), + ) + .await + .map(|_| ()) + } + #[cfg(test)] pub(crate) async fn seed_proved_dpns_votes_for_test( &self, diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 8a4e21c86..9783933bd 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -23,8 +23,9 @@ use crate::context::AppContext; use crate::model::contested_name::{ContestState, ContestedName}; use crate::model::dpns::normalize_dpns_label; use crate::model::dpns_voting::{ - DpnsCurrentVoteState, DpnsScheduledVoteKey, DpnsVoteOperation, DpnsVoteOperationId, - DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + DpnsCurrentVoteState, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, + DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + validate_dpns_schedule_time, }; use crate::model::qualified_identity::{DPNSNameInfo, QualifiedIdentity}; use crate::ui::components::component_trait::Component; @@ -157,6 +158,35 @@ fn target_status_label(status: DpnsVoteTargetStatus) -> &'static str { } } +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) + } +} + +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. In Scheduled Votes, 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 in Scheduled Votes.", + ), + DpnsVoteFailure::PlatformRejected | DpnsVoteFailure::ResultUnconfirmed => None, + } +} + fn scheduled_vote_remove_enabled(status: DpnsVoteTargetStatus) -> bool { !matches!( status, @@ -462,11 +492,10 @@ impl DPNSScreen { .iter() .map(|identity| identity.identity.id()) .collect::>(); - let vote_state = DpnsVoteStateSnapshot::load(app_context, &voter_ids, &vote_poll_ids) - .unwrap_or_else(|error| { - tracing::warn!(?error, "Could not cache proved DPNS vote state"); - DpnsVoteStateSnapshot::default() - }); + 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(); @@ -1048,7 +1077,7 @@ impl DPNSScreen { let dark_mode = ui.style().visuals.dark_mode; ui.add_space(12.0); - ui.heading("Recent voting activity"); + ui.heading("Voting activity"); for operation in operations.iter() { let settled = operation .targets @@ -1077,7 +1106,7 @@ impl DPNSScreen { ) .as_deref(), ), - target_status_label(outcome.status), + target_outcome_label(outcome.status, outcome.failure), )); if outcome.status == DpnsVoteTargetStatus::Unconfirmed && ComponentStyles::add_secondary_button( @@ -1114,6 +1143,9 @@ impl DPNSScreen { self.review_failed_target(outcome); } }); + if let Some(guidance) = scheduled_failure_guidance(outcome.status, outcome.failure) { + ui.label(guidance); + } if matches!( outcome.status, DpnsVoteTargetStatus::Confirming @@ -1503,7 +1535,7 @@ impl DPNSScreen { .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::initial(280.0).resizable(true)) // Status .column(Column::auto().resizable(true)) // Actions .header(30.0, |mut header| { header.col(|ui| { @@ -1552,7 +1584,8 @@ impl DPNSScreen { voter_id: vote.voter_id, contested_name: vote.contested_name.clone(), }; - body.row(25.0, |mut row| { + let failure_guidance = scheduled_failure_guidance(scheduled_row.status, scheduled_row.failure); + body.row(if failure_guidance.is_some() { 95.0 } else { 25.0 }, |mut row| { row.col(|ui| { ui.add(Label::new(format!("{}.dash", vote.contested_name))); }); @@ -1598,10 +1631,13 @@ impl DPNSScreen { }); row.col(|ui| { let dark_mode = ui.style().visuals.dark_mode; - ui.label( - RichText::new(target_status_label(scheduled_row.status)) - .color(DashColors::text_primary(dark_mode)), - ); + ui.vertical(|ui| { + ui.label(RichText::new(target_outcome_label(scheduled_row.status, scheduled_row.failure)) + .color(DashColors::text_primary(dark_mode))); + if let Some(guidance) = failure_guidance { + ui.add(Label::new(guidance).wrap()); + } + }); }); row.col(|ui| { let remove_enabled = @@ -2201,6 +2237,19 @@ impl DPNSScreen { }; voters.push(identity.clone()); for selected_vote in &self.selected_votes { + if let VoteTiming::Scheduled(timestamp) = timing { + validate_dpns_schedule_time( + timestamp, + now.timestamp_millis() as u64, + selected_vote.end_time, + ) + .map_err(|_| { + format!( + "Choose a future time before the contest ends for {}.dash.", + selected_vote.contested_name + ) + })?; + } let voter_id = identity.identity.id(); let vote_poll_id = self .app_context @@ -2460,6 +2509,12 @@ impl ScreenLike for DPNSScreen { } 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.clear_vote_overlay_on_error { self.vote_overlay.take_and_clear(); self.pending_vote_operation = None; @@ -2718,6 +2773,9 @@ impl ScreenLike for DPNSScreen { self.render_active_contests(ui); } else { inner_action |= self.render_no_active_contests_or_owned_names(ui); + egui::ScrollArea::vertical() + .id_salt("voting_activity_without_contests") + .show(ui, |ui| self.render_voting_activity(ui)); } } DPNSSubscreen::Past => { @@ -3180,11 +3238,13 @@ mod tests { vote: vote.clone(), journal_target: Some((operation_id, key.clone())), status: DpnsVoteTargetStatus::Scheduled, + failure: None, }; let legacy_row = ScheduledDpnsVoteRow { vote, journal_target: None, status: DpnsVoteTargetStatus::Scheduled, + failure: None, }; assert!(matches!( @@ -3327,6 +3387,193 @@ mod tests { (screen, temp_dir) } + #[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().entries[0] + .target + .clone(); + let mut operation = DpnsVoteOperation::new(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, DPNSSubscreen::Active); + 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(); + assert!(harness.query_by_label("Check again").is_some()); + } + + #[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. In Scheduled Votes, 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 in Scheduled Votes.", + ), + ] { + let (screen, _dir) = voting_ui_review_fixture(); + let mut target = screen.build_review_plan().unwrap().entries[0] + .target + .clone(); + target.timing = VoteTiming::Scheduled(Utc::now().timestamp_millis() as u64); + let mut operation = DpnsVoteOperation::new(vec![target]); + operation.targets[0].failure = Some(failure); + screen + .app_context + .insert_dpns_vote_operation(&mut operation, None) + .unwrap(); + for subscreen in [DPNSSubscreen::ScheduledVotes, DPNSSubscreen::Active] { + let scheduled = subscreen == DPNSSubscreen::ScheduledVotes; + let mut reopened = DPNSScreen::new(&screen.app_context, subscreen); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .build_ui(move |ui| { + reopened.ui(ui); + }); + harness.run(); + if scheduled { + 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, DPNSSubscreen::Active); + 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, DPNSSubscreen::Active); + 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)) + ); + } + + #[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(); + let scheduled_at = (now + chrono::Duration::hours(1)).timestamp_millis() as u64; + for option in [ + VoteOption::ScheduledAt(scheduled_at), + VoteOption::Scheduled { + days: 0, + hours: 1, + minutes: 0, + }, + ] { + screen.bulk_identity_options = vec![option]; + 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.selected_votes.push(SelectedVote { + contested_name: "beta".into(), + vote_choice: ResourceVoteChoice::Abstain, + end_time: Some(scheduled_at), + }); + assert!( + screen + .build_review_plan_at(now) + .err() + .expect("the second contest has ended before the schedule") + .contains("beta.dash") + ); + } + #[test] fn voting_ui_absolute_schedule_preserves_the_requested_utc_minute() { let (mut screen, _temp_dir) = voting_ui_review_fixture(); 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 index 2b400b6f1..1452761cb 100644 --- a/src/ui/dpns/dpns_contested_names_screen/scheduled_vote_editor.rs +++ b/src/ui/dpns/dpns_contested_names_screen/scheduled_vote_editor.rs @@ -181,6 +181,7 @@ mod tests { vote_poll_id: Identifier::from([2; 32]), }; let row = ScheduledDpnsVoteRow { + failure: None, vote: ScheduledDPNSVote { voter_id: key.voter_id, contested_name: "alice".into(), diff --git a/src/ui/state/dpns_vote_operations.rs b/src/ui/state/dpns_vote_operations.rs index 16608a88f..16e9d61a4 100644 --- a/src/ui/state/dpns_vote_operations.rs +++ b/src/ui/state/dpns_vote_operations.rs @@ -7,7 +7,8 @@ use crate::backend_task::contested_names::ScheduledDPNSVote; use crate::backend_task::error::TaskError; use crate::context::AppContext; use crate::model::dpns_voting::{ - DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, + DpnsVoteTargetStatus, VoteTiming, }; #[derive(Debug, Clone, PartialEq)] @@ -15,6 +16,7 @@ pub(crate) struct ScheduledDpnsVoteRow { pub vote: ScheduledDPNSVote, pub journal_target: Option<(DpnsVoteOperationId, DpnsVoteTargetKey)>, pub status: DpnsVoteTargetStatus, + pub failure: Option, } #[derive(Debug, Clone, Default)] @@ -100,6 +102,7 @@ impl DpnsVoteOperationSnapshot { }, journal_target: Some((operation.id, outcome.target.key.clone())), status: outcome.status, + failure: outcome.failure, }, ), ); @@ -129,6 +132,7 @@ impl DpnsVoteOperationSnapshot { .map(|vote| ScheduledDpnsVoteRow { vote: vote.clone(), journal_target: None, + failure: None, status: if vote.executed_successfully { DpnsVoteTargetStatus::Confirmed } else { @@ -151,7 +155,25 @@ impl DpnsVoteOperationSnapshot { .filter(|operation| !operation.targets.is_empty()) .collect::>(); recent.sort_by_key(|operation| operation.created_at); - self.recent_operations = recent.into_iter().rev().take(5).cloned().collect(); + // Pending operations must remain reachable even after newer batches complete. + let mut completed_count = 0; + self.recent_operations = recent + .into_iter() + .rev() + .filter(|operation| { + if operation + .targets + .iter() + .any(|outcome| outcome.status.holds_lock()) + { + true + } else { + completed_count += 1; + completed_count <= 5 + } + }) + .cloned() + .collect(); self.operations = operations; self.loaded = true; } @@ -166,6 +188,28 @@ mod tests { use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; use dash_sdk::platform::Identifier; + #[test] + fn voting_ui_unresolved_activity_survives_newer_completed_batches() { + let mut snapshot = DpnsVoteOperationSnapshot::default(); + let mut unresolved = operation(DpnsVoteTargetStatus::Unconfirmed); + unresolved.created_at = 0; + let unresolved_id = unresolved.id; + let mut operations = vec![unresolved]; + for created_at in 1..=8 { + let mut completed = operation(DpnsVoteTargetStatus::Confirmed); + completed.created_at = created_at; + operations.push(completed); + } + snapshot.replace(operations); + let visible = snapshot.recent_operations(); + assert!( + visible + .iter() + .any(|operation| operation.id == unresolved_id) + ); + assert_eq!(visible.len(), 6); + } + #[test] fn voting_ui_recent_activity_is_bounded_ordered_and_shared_between_frames() { let mut snapshot = DpnsVoteOperationSnapshot::default(); diff --git a/src/ui/state/dpns_vote_state.rs b/src/ui/state/dpns_vote_state.rs index 79fd3a79f..e5450b114 100644 --- a/src/ui/state/dpns_vote_state.rs +++ b/src/ui/state/dpns_vote_state.rs @@ -25,24 +25,19 @@ impl DpnsVoteStateSnapshot { 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> { - let mut states = BTreeMap::new(); - for voter_id in voter_ids { - states.extend( - app_context - .dpns_current_vote_states(*voter_id, vote_poll_ids.iter().copied())? - .into_iter() - .map(|(poll_id, state)| ((*voter_id, poll_id), state)), - ); - } - self.states = states; - self.loaded = true; - Ok(()) + 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> { @@ -54,18 +49,38 @@ impl DpnsVoteStateSnapshot { .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 first_error = None; for (voter_id, vote_poll_ids) in polls_by_voter { + let voter_states = match app_context + .dpns_current_vote_states(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)) + .collect() + } + }; states.extend( - app_context - .dpns_current_vote_states(voter_id, vote_poll_ids)? + voter_states .into_iter() .map(|(poll_id, state)| ((voter_id, poll_id), state)), ); } self.states = states; self.loaded = true; - Ok(()) + first_error.map_or(Ok(()), Err) } pub fn state(&self, voter_id: Identifier, vote_poll_id: Identifier) -> DpnsCurrentVoteState { @@ -83,6 +98,48 @@ impl DpnsVoteStateSnapshot { 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]); From 9dc18438e75df17d52d56fc68bfdaffb88b2317d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 9 Sep 2026 15:22:14 +0000 Subject: [PATCH 048/194] fix(dpns): explain missed votes and bound completed history MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep unreadable voting progress visible with a retry action, preserve unresolved locks while retiring completed schedules, and identify mismatched voting keys. Cover recovery, retention failures, key binding, and repeated Save clicks. Co-Authored-By: Codex πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 2 + Cargo.toml | 1 + docs/user-stories.md | 3 + src/backend_task/contested_names/mod.rs | 37 +- src/backend_task/error.rs | 8 +- src/backend_task/identity/load_identity.rs | 90 ++++- src/context/dpns_vote_operations.rs | 371 ++++++++++++++++++++- src/context/identity_db.rs | 4 + src/model/dpns_voting.rs | 16 + src/ui/dpns/dpns_contested_names_screen.rs | 132 +++++++- src/ui/masternodes/detail_screen.rs | 39 +++ src/ui/state/dpns_vote_operations.rs | 27 +- 12 files changed, 686 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 203f98794..d918b00af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -122,6 +122,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- DPNS voting now explains missed automatic schedules and unreadable saved progress, with manual recovery actions. Completed scheduled and mixed voting history is bounded without discarding unresolved votes or restoring removed schedules. Adding another node's voting key gives a key-specific error. + - Identity creation and top-up accounts are saved before payment and restored after restarting the app. Temporary save failures are retried a few times; if saving still fails, the payment stops and the app asks you to try again. diff --git a/Cargo.toml b/Cargo.toml index c5a7e02b2..eea9d5e3f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -129,6 +129,7 @@ cli = ["dep:rmcp", "rmcp/server", "rmcp/macros", "rmcp/client", "rmcp/transport- headless = ["cli", "mcp"] [dev-dependencies] +dash-sdk = { git = "https://github.com/dashpay/platform", rev = "67d4ef3f6340a1e983229b6870ef60cf7573602a", features = ["mocks"] } egui_kittest = { version = "0.35.0", features = ["eframe"] } tokio-shared-rt = "=0.1.0" criterion = "0.5.1" diff --git a/docs/user-stories.md b/docs/user-stories.md index 9961b2bb2..c7c4dfb70 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -797,6 +797,8 @@ As a masternode operator, I want to schedule votes for later execution so that I - Scheduled and immediate votes share the same target locks and result states. - Removing a scheduled vote takes it off the list for good; it does not come back on the next refresh. - An ambiguous result remains visible for checking and is never automatically rebroadcast. +- Votes that miss the normal automatic voting window show guidance to cast manually, edit, or remove them. Already queued votes retain their eligibility. +- 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] **Persona:** Priya @@ -820,6 +822,7 @@ 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. - A confirmed match updates the current vote and releases the target lock. diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 30612287e..fc0c157b8 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -11,8 +11,8 @@ use crate::context::AppContext; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduleEditValidationError, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, - failed_before_broadcast_outcome, unavailable_preflight_outcome, validate_dpns_schedule_edit, - validate_dpns_schedule_time, + dpns_schedule_is_overdue, 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; @@ -29,10 +29,8 @@ use std::collections::BTreeMap; 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 { @@ -1125,7 +1123,7 @@ 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( @@ -1798,6 +1796,31 @@ mod tests { )); } + #[tokio::test] + async fn additional_scenarios_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); + context + .ensure_dpns_vote_recovery(&context.sdk()) + .await + .unwrap(); + assert!(*context.dpns_vote_recovery.lock().await); + } + #[tokio::test] async fn direct_dispatch_terminal_write_failure_rearms_global_recovery() { let temp_dir = tempfile::tempdir().expect("tempdir"); diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index f9a007b9d..daf3b3ae7 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -908,7 +908,7 @@ pub enum TaskError { /// An indexed journal row could not be decoded, so unresolved target locks /// cannot be reconstructed safely. #[error( - "Saved DPNS voting progress is unreadable. Restore the saved data or remove the damaged voting record before trying again." + "Saved DPNS voting progress is unreadable. Restart the app and retry loading. If this continues, restore a backup of the saved data before managing votes." )] DpnsVoteOperationUnreadable { #[source] @@ -917,7 +917,7 @@ pub enum TaskError { /// An operation index referenced a missing row, so target locks are unknown. #[error( - "Saved DPNS voting progress is incomplete. Restore the saved data or remove the damaged voting record before trying again." + "Saved DPNS voting progress is incomplete. Restart the app and retry loading. If this continues, restore a backup of the saved data before managing votes." )] DpnsVoteOperationRecordMissing, @@ -1254,6 +1254,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( diff --git a/src/backend_task/identity/load_identity.rs b/src/backend_task/identity/load_identity.rs index c9112e364..60282e305 100644 --- a/src/backend_task/identity/load_identity.rs +++ b/src/backend_task/identity/load_identity.rs @@ -284,7 +284,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)), }; @@ -850,6 +850,94 @@ 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 = diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations.rs index e597333b3..ee79d8e2d 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations.rs @@ -27,8 +27,10 @@ const OPERATION_LOCK_INDEX_DIRTY_KEY_PREFIX: &str = "det:dpns_vote_operation_loc const DPNS_VOTE_DIAGNOSTIC_LIMIT: usize = 256; /// Completed immediate batches retained per network; unresolved work is never capped. const DPNS_IMMEDIATE_HISTORY_LIMIT: usize = 256; +const DPNS_SCHEDULED_HISTORY_LIMIT: usize = 256; const SCHEDULE_DISMISSAL_KEY_PREFIX: &str = "det:dpns_vote_schedule_dismissals:v1:"; const IMMEDIATE_HISTORY_KEY_PREFIX: &str = "det:dpns_vote_immediate_history:v1:"; +const SCHEDULED_HISTORY_KEY_PREFIX: &str = "det:dpns_vote_scheduled_history:v1:"; type DpnsVoteLockIndex = BTreeMap; type DpnsVoteDiagnosticMap = @@ -305,12 +307,8 @@ fn persist_operation( if !operation_matches_network(operation, network)? { return Err(TaskError::DpnsVoteJournalNetworkMismatch); } - let immediate_complete = operation.is_complete() - && operation - .targets - .iter() - .all(|outcome| outcome.target.timing == VoteTiming::Now); - let newly_complete = immediate_complete + let complete = operation.is_complete(); + let newly_complete = complete && kv .get::(DetScope::Global, &operation_key(network, operation.id)) .map_err(unreadable_operation_err)? @@ -362,14 +360,21 @@ fn persist_operation( kv.delete(DetScope::Global, &operation_lock_index_dirty_key(network)) .map_err(operation_err)?; } - if immediate_complete - && let Err(error) = - prune_immediate_history(kv, network, newly_complete.then_some(operation.id)) + if complete + && let Err(error) = prune_completed_history( + kv, + network, + newly_complete.then_some(operation.id), + operation + .targets + .iter() + .any(|outcome| matches!(outcome.target.timing, VoteTiming::Scheduled(_))), + ) { // The submitted result is durable; cleanup failure must not invite a retry. tracing::warn!( ?error, - "Completed DPNS immediate history cleanup will retry during recovery" + "Completed DPNS voting history cleanup will retry during recovery" ); } Ok(()) @@ -417,15 +422,31 @@ fn prune_immediate_history( network: Network, newly_completed: Option, ) -> Result { - let history_key = format!("{IMMEDIATE_HISTORY_KEY_PREFIX}{}", network_tag(network)); - let mut terminal = load_operations(kv, network)? - .into_iter() + prune_completed_history(kv, network, newly_completed, false) +} + +fn prune_completed_history( + kv: &DetKv, + network: Network, + newly_completed: Option, + scheduled: bool, +) -> Result { + let (prefix, limit) = if scheduled { + (SCHEDULED_HISTORY_KEY_PREFIX, DPNS_SCHEDULED_HISTORY_LIMIT) + } else { + (IMMEDIATE_HISTORY_KEY_PREFIX, DPNS_IMMEDIATE_HISTORY_LIMIT) + }; + let history_key = format!("{prefix}{}", network_tag(network)); + let operations = load_operations(kv, network)?; + let mut terminal = operations + .iter() .filter(|operation| { operation.is_complete() - && operation + && (operation .targets .iter() - .all(|outcome| outcome.target.timing == VoteTiming::Now) + .any(|outcome| matches!(outcome.target.timing, VoteTiming::Scheduled(_))) + == scheduled) }) .collect::>(); terminal.sort_unstable_by_key(|operation| (operation.created_at, operation.id)); @@ -458,7 +479,42 @@ fn prune_immediate_history( kv.put(DetScope::Global, &history_key, &ordered) .map_err(operation_err)?; } - let remove_count = ordered.len().saturating_sub(DPNS_IMMEDIATE_HISTORY_LIMIT); + let remove_count = ordered.len().saturating_sub(limit); + if scheduled && remove_count > 0 { + let removing = ordered[..remove_count] + .iter() + .copied() + .collect::>(); + let surviving_pairs = operations + .iter() + .filter(|operation| !removing.contains(&operation.id)) + .flat_map(|operation| &operation.targets) + .filter(|outcome| matches!(outcome.target.timing, VoteTiming::Scheduled(_))) + .map(|outcome| { + ( + outcome.target.key.voter_id, + outcome.target.contested_name.as_str(), + ) + }) + .collect::>(); + // Remove mirrors before their journals so partial cleanup cannot revive a schedule. + for operation in terminal + .iter() + .filter(|operation| removing.contains(&operation.id)) + { + for outcome in &operation.targets { + let pair = ( + outcome.target.key.voter_id, + outcome.target.contested_name.as_str(), + ); + if matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + && !surviving_pairs.contains(&pair) + { + delete_scheduled_vote_in(kv, &pair.0.to_buffer(), pair.1)?; + } + } + } + } let removed = delete_terminal_operations(kv, network, &ordered[..remove_count])?; if remove_count > 0 { ordered.drain(..remove_count); @@ -870,6 +926,14 @@ impl AppContext { } else { persist_operation(&kv, self.network, operation)?; } + // A repeated terminal update may have been retired by retention. + match kv + .get::(DetScope::Global, &operation_key(self.network, operation.id)) + { + Ok(Some(_)) => {} + Ok(None) => return Ok(None), + Err(error) => return Ok(Some(unreadable_operation_err(error))), + } Ok(insert_scheduled_votes_in(&kv, scheduled_votes).err()) } @@ -1180,6 +1244,7 @@ impl AppContext { } } prune_immediate_history(&kv, self.network, None)?; + prune_completed_history(&kv, self.network, None, true)?; prune_orphaned_schedule_dismissals(&kv, self.network)?; Ok(()) } @@ -2048,6 +2113,16 @@ mod tests { 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, @@ -2060,6 +2135,38 @@ mod tests { 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] @@ -2344,6 +2451,238 @@ mod tests { ); } + #[test] + fn additional_scenarios_retention_read_failure_keeps_durable_insert_successful() { + 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 mut scheduled = scheduled_operation(DpnsVoteTargetStatus::Scheduled, 2, "read-failure"); + let mirror = scheduled_vote(&scheduled); + store.fail_next_gets_containing(OPERATION_KEY_PREFIX, 1); + let mirror_error = context + .insert_dpns_vote_operation_with_scheduled_mirror(&mut scheduled, None, &[mirror]) + .expect("a post-persistence read failure must not invite another submission"); + assert!(mirror_error.is_some()); + assert_eq!( + context.dpns_vote_operation(scheduled.id).unwrap(), + Some(scheduled.clone()) + ); + assert_eq!( + context + .dpns_vote_target_status(&scheduled.targets[0].target.key) + .unwrap(), + Some(DpnsVoteTargetStatus::Scheduled) + ); + assert!(context.get_scheduled_votes().unwrap().is_empty()); + } + + #[test] + fn additional_scenarios_scheduled_and_mixed_history_is_bounded_with_mirrors() { + 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; + for index in 0..258 { + 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)); + } + let mirror = ScheduledDPNSVote { + contested_name: format!("history-{index}"), + voter_id: completed.targets[0].target.key.voter_id, + choice: ResourceVoteChoice::Lock, + unix_timestamp: 42, + executed_successfully: true, + }; + if index == 0 { + oldest = Some(completed.id); + } + context + .insert_dpns_vote_operation_with_scheduled_mirror(&mut completed, None, &[mirror]) + .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() + ); + assert_eq!(context.get_scheduled_votes().unwrap().len(), 256); + context.migrate_dpns_vote_operations().unwrap(); + assert_eq!( + context.dpns_vote_operations().unwrap().len(), + 257, + "pruned mirrors must not migrate back" + ); + assert_eq!( + context + .dpns_vote_target_status(&unresolved.targets[0].target.key) + .unwrap(), + Some(DpnsVoteTargetStatus::Unconfirmed) + ); + } + + #[test] + fn additional_scenarios_scheduled_retention_cleanup_failures_retry_safely() { + for failing_key in [ + "det:scheduled_vote:", + OPERATION_KEY_PREFIX, + SCHEDULE_DISMISSAL_KEY_PREFIX, + ] { + 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.clone()); + let mut oldest = None; + for index in 0..256 { + let mut completed = scheduled_operation( + DpnsVoteTargetStatus::Confirmed, + 2, + &format!("cleanup-{index}"), + ); + completed.created_at = index; + if index == 0 { + oldest = Some(completed.clone()); + dismiss_scheduled_target( + &kv, + Network::Testnet, + completed.id, + &completed.targets[0].target.key, + ) + .unwrap(); + } + context + .insert_dpns_vote_operation_with_scheduled_mirror( + &mut completed.clone(), + None, + &[scheduled_vote(&completed)], + ) + .unwrap(); + } + let mut unresolved = + scheduled_operation(DpnsVoteTargetStatus::Unconfirmed, 3, "pending"); + context + .insert_dpns_vote_operation(&mut unresolved, None) + .unwrap(); + store.fail_next_deletes_containing(failing_key, 1); + let newest = scheduled_operation(DpnsVoteTargetStatus::Confirmed, 2, "newest"); + context + .insert_dpns_vote_operation_with_scheduled_mirror( + &mut newest.clone(), + None, + &[scheduled_vote(&newest)], + ) + .unwrap(); + assert!( + context.dpns_vote_operation(newest.id).unwrap().is_some(), + "cleanup failure must not undo a confirmed result" + ); + context.recover_interrupted_dpns_vote_operations().unwrap(); + let oldest = oldest.unwrap(); + assert_eq!(context.dpns_vote_operations().unwrap().len(), 257); + assert!(context.dpns_vote_operation(oldest.id).unwrap().is_none()); + assert!( + !context + .get_scheduled_votes() + .unwrap() + .iter() + .any(|vote| vote.contested_name == "cleanup-0") + ); + assert!(context.dismissed_dpns_vote_schedules().unwrap().is_empty()); + assert_eq!( + context + .dpns_vote_target_status(&unresolved.targets[0].target.key) + .unwrap(), + Some(DpnsVoteTargetStatus::Unconfirmed) + ); + context + .mark_vote_executed( + oldest.targets[0].target.key.voter_id.as_slice(), + "cleanup-0".to_owned(), + ) + .unwrap(); + context.migrate_dpns_vote_operations().unwrap(); + assert_eq!( + context.dpns_vote_operations().unwrap().len(), + 257, + "late mirror completion must not revive pruned work" + ); + } + } + + #[test] + fn additional_scenarios_retention_preserves_a_newer_schedules_mirror() { + let dir = tempfile::tempdir().unwrap(); + let kv = kv(); + 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 mut old = scheduled_operation(DpnsVoteTargetStatus::Confirmed, 2, "shared"); + old.created_at = 0; + context + .insert_dpns_vote_operation_with_scheduled_mirror( + &mut old.clone(), + None, + &[scheduled_vote(&old)], + ) + .unwrap(); + let mut current = scheduled_operation(DpnsVoteTargetStatus::Scheduled, 2, "shared"); + current.targets[0].target.requested_choice = ResourceVoteChoice::Abstain; + let current_mirror = scheduled_vote(¤t); + context + .insert_dpns_vote_operation_with_scheduled_mirror( + &mut current, + None, + std::slice::from_ref(¤t_mirror), + ) + .unwrap(); + for index in 1..=256 { + let mut completed = scheduled_operation( + DpnsVoteTargetStatus::Confirmed, + 3, + &format!("other-{index}"), + ); + completed.created_at = index; + persist_operation(&kv, Network::Testnet, &completed).unwrap(); + } + assert!(context.dpns_vote_operation(old.id).unwrap().is_none()); + assert_eq!(context.get_scheduled_votes().unwrap(), vec![current_mirror]); + assert_eq!( + context + .dpns_vote_target_status(¤t.targets[0].target.key) + .unwrap(), + Some(DpnsVoteTargetStatus::Scheduled) + ); + } + #[test] fn terminal_immediate_history_is_bounded_without_pruning_unresolved_votes() { let kv = kv(); diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index 8ee267331..1ab23fb1d 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -2513,6 +2513,10 @@ impl AppContext { identity_id: &[u8], contested_name: String, ) -> std::result::Result<(), TaskError> { + let _guard = self + .dpns_vote_operation_guard + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); let voter = voter_buffer(identity_id)?; let key = scheduled_vote_key(&contested_name); let scope = DetScope::Identity(&voter); diff --git a/src/model/dpns_voting.rs b/src/model/dpns_voting.rs index 8bc7c55df..d65d33526 100644 --- a/src/model/dpns_voting.rs +++ b/src/model/dpns_voting.rs @@ -1,3 +1,11 @@ +/// 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 +} + #[cfg(test)] mod tests { use super::*; @@ -5,6 +13,14 @@ mod tests { use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; use dash_sdk::platform::Identifier; + #[test] + fn additional_scenarios_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)); + } + fn target( voter: u8, poll: u8, diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 9783933bd..2f5207dce 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -25,7 +25,7 @@ use crate::model::dpns::normalize_dpns_label; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, - validate_dpns_schedule_time, + dpns_schedule_is_overdue, validate_dpns_schedule_time, }; use crate::model::qualified_identity::{DPNSNameInfo, QualifiedIdentity}; use crate::ui::components::component_trait::Component; @@ -62,6 +62,13 @@ enum ActiveContestGroup { const NO_VOTING_NODES_MESSAGE: &str = "None of your loaded nodes has a voting key."; const NO_VOTING_NODES_DETAIL: &str = "Load a masternode with its voting key to cast votes."; +const JOURNAL_UNAVAILABLE_MESSAGE: &str = "Saved voting progress could not be read. The displayed history may be incomplete or out of date. Retry loading before managing votes."; +const MISSED_SCHEDULE_GUIDANCE: &str = "The automatic voting time was missed. In Scheduled Votes, use Cast now to vote, Edit to reschedule, or Remove to cancel."; + +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 candidate_choice_label(candidate_name: &str) -> String { format!("Vote for {candidate_name}") @@ -429,6 +436,7 @@ pub struct DPNSScreen { pub dpns_subscreen: DPNSSubscreen, refreshing_status: RefreshingStatus, refresh_banner: Option, + journal_error_banner: Option, /// Selected vote handling show_bulk_schedule_popup: bool, @@ -442,14 +450,7 @@ pub struct DPNSScreen { impl DPNSScreen { pub fn new(app_context: &Arc, dpns_subscreen: DPNSSubscreen) -> Self { - let vote_operations = - DpnsVoteOperationSnapshot::load(app_context).unwrap_or_else(|error| { - tracing::warn!( - ?error, - "Could not cache DPNS vote operations for the DPNS screen" - ); - DpnsVoteOperationSnapshot::default() - }); + let vote_operations = DpnsVoteOperationSnapshot::load(app_context); let legacy_scheduled_votes = app_context.get_scheduled_votes().unwrap_or_default(); let scheduled_votes = Arc::new(Mutex::new( vote_operations.scheduled_vote_rows(&legacy_scheduled_votes), @@ -529,6 +530,7 @@ impl DPNSScreen { dpns_subscreen, refreshing_status: RefreshingStatus::NotRefreshing, refresh_banner: None, + journal_error_banner: None, // Vote handling show_bulk_schedule_popup: false, @@ -572,6 +574,7 @@ impl DPNSScreen { self.scheduled_vote_editor = None; self.vote_overlay.take_and_clear(); self.refresh_banner.take_and_clear(); + self.journal_error_banner.take_and_clear(); self.refreshing_status = RefreshingStatus::NotRefreshing; self.voting_identities.clear(); self.voting_identity_load_error = None; @@ -1093,6 +1096,7 @@ impl DPNSScreen { .strong(), ); for outcome in &operation.targets { + let missed = schedule_is_missed(outcome.status, outcome.target.timing, Utc::now().timestamp_millis().max(0) as u64); ui.horizontal_wrapped(|ui| { ui.label(format!( "{} β€” {}.dash β€” {} β€” {}", @@ -1106,7 +1110,7 @@ impl DPNSScreen { ) .as_deref(), ), - target_outcome_label(outcome.status, outcome.failure), + if missed { "Missed automatic vote" } else { target_outcome_label(outcome.status, outcome.failure) }, )); if outcome.status == DpnsVoteTargetStatus::Unconfirmed && ComponentStyles::add_secondary_button( @@ -1146,6 +1150,9 @@ impl DPNSScreen { if let Some(guidance) = scheduled_failure_guidance(outcome.status, outcome.failure) { ui.label(guidance); } + if missed { + ui.label(MISSED_SCHEDULE_GUIDANCE); + } if matches!( outcome.status, DpnsVoteTargetStatus::Confirming @@ -1584,7 +1591,8 @@ impl DPNSScreen { voter_id: vote.voter_id, contested_name: vote.contested_name.clone(), }; - let failure_guidance = scheduled_failure_guidance(scheduled_row.status, scheduled_row.failure); + let missed = schedule_is_missed(scheduled_row.status, VoteTiming::Scheduled(vote.unix_timestamp), Utc::now().timestamp_millis().max(0) as u64); + let failure_guidance = if missed { Some(MISSED_SCHEDULE_GUIDANCE) } else { scheduled_failure_guidance(scheduled_row.status, scheduled_row.failure) }; body.row(if failure_guidance.is_some() { 95.0 } else { 25.0 }, |mut row| { row.col(|ui| { ui.add(Label::new(format!("{}.dash", vote.contested_name))); @@ -1632,7 +1640,7 @@ impl DPNSScreen { row.col(|ui| { let dark_mode = ui.style().visuals.dark_mode; ui.vertical(|ui| { - ui.label(RichText::new(target_outcome_label(scheduled_row.status, scheduled_row.failure)) + ui.label(RichText::new(if missed { "Missed automatic vote" } else { target_outcome_label(scheduled_row.status, scheduled_row.failure) }) .color(DashColors::text_primary(dark_mode))); if let Some(guidance) = failure_guidance { ui.add(Label::new(guidance).wrap()); @@ -2716,6 +2724,27 @@ impl ScreenLike for DPNSScreen { // Main panel action |= island_central_panel(ui, |ui| { let mut inner_action = AppAction::None; + 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(), "Saved voting progress could not be read. Retry loading before managing votes.", MessageType::Warning); + if let Some(handle) = &self.journal_error_banner { + handle.with_details(error); + } + } + 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 { @@ -3411,6 +3440,85 @@ mod tests { assert!(harness.query_by_label("Check again").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().entries[0] + .target + .clone(); + target.timing = VoteTiming::Scheduled(1); + let mut operation = DpnsVoteOperation::new(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, DPNSSubscreen::ScheduledVotes); + 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. In Scheduled Votes, 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, DPNSSubscreen::ScheduledVotes); + 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| { + 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. Retry loading before managing votes."; + 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; diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index 71484f635..46e1254b6 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -807,6 +807,45 @@ mod tests { assert!(input.payout_address_private_key_input.is_blank()); assert!(input.encryption_password.is_none()); assert!(!detail.has_voter_key_prompt_for_test()); + assert!( + detail.submit_voter_key().is_none(), + "a repeated Save cannot dispatch another load" + ); + + use egui_kittest::kittest::Queryable; + use std::sync::atomic::{AtomicUsize, Ordering}; + 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(); + harness.run(); + assert!(harness.query_by_label("Save").is_none()); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { + pos: position, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }); + } + harness.run(); + assert_eq!( + dispatched.load(Ordering::Relaxed), + 1, + "repeated clicks at Save must dispatch only one load" + ); } #[test] diff --git a/src/ui/state/dpns_vote_operations.rs b/src/ui/state/dpns_vote_operations.rs index 16e9d61a4..67b855308 100644 --- a/src/ui/state/dpns_vote_operations.rs +++ b/src/ui/state/dpns_vote_operations.rs @@ -26,23 +26,38 @@ pub struct DpnsVoteOperationSnapshot { dismissed_schedules: BTreeSet<(DpnsVoteOperationId, DpnsVoteTargetKey)>, target_statuses: BTreeMap, loaded: bool, + read_error: Option>, } impl DpnsVoteOperationSnapshot { - pub fn load(app_context: &AppContext) -> Result { + pub fn load(app_context: &AppContext) -> Self { let mut snapshot = Self::default(); - snapshot.refresh(app_context)?; - Ok(snapshot) + let _ = snapshot.refresh(app_context); + snapshot } - pub fn refresh(&mut self, app_context: &AppContext) -> Result<(), TaskError> { - let operations = app_context.dpns_vote_operations()?; - let dismissals = app_context.dismissed_dpns_vote_schedules()?; + 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(()) } + pub(crate) fn read_error(&self) -> Option<&Arc> { + self.read_error.as_ref() + } + pub fn operations(&self) -> &[DpnsVoteOperation] { &self.operations } From 9c50554c1126052b2ed6ec0fa6c0021fcfe27a71 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 10 Sep 2026 09:11:47 +0000 Subject: [PATCH 049/194] fix(dpns): preserve vote intent and fresh preflight review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep exact scheduled retry choices, coordinate successful proof publications, and require renewed review before a first immediate vote becomes a change. Expose unavailable voting state, report mixed success accurately, and keep contest queries independent of vote recovery failures. Co-Authored-By: Codex GPT-6 Astra πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 4 +- docs/user-stories.md | 7 +- src/app.rs | 24 ++ src/backend_task/contested_names/mod.rs | 199 ++++++++++++-- src/backend_task/error.rs | 4 + src/context/dpns_vote_state.rs | 306 ++++++++++++++++++++- src/ui/dpns/dpns_contested_names_screen.rs | 122 +++++++- 7 files changed, 631 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d918b00af..5b73f059a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -92,7 +92,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **DPNS voting redesigned around the Active contests screen**: casting, batching, and scheduling DPNS name-contest votes across your masternodes now happens in one place β€” DPNS β†’ Active contests. Contests are grouped - into Needs your vote / Voted / Not votable by your nodes, with a Review + into Needs your vote / Voted / Vote state unavailable / Not votable by + your nodes, with a Review and cast step for casting now or scheduling later, plus a reminder that Platform allows up to four changes after the initial vote. The Masternodes detail screen no longer casts votes inline β€” its "DPNS @@ -122,6 +123,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- DPNS scheduled retries keep the selected choice, and simultaneous scheduled votes share fresh voting information without losing their due status. If a first vote becomes a vote change before submission, DET asks for another review. Unavailable voting information stays visible with a refresh action, successful mixed batches report both cast and scheduled votes, and contest refresh remains available when saved voting progress cannot be recovered. - DPNS voting now explains missed automatic schedules and unreadable saved progress, with manual recovery actions. Completed scheduled and mixed voting history is bounded without discarding unresolved votes or restoring removed schedules. Adding another node's voting key gives a key-specific error. - Identity creation and top-up accounts are saved before payment and restored diff --git a/docs/user-stories.md b/docs/user-stories.md index c7c4dfb70..4e5da1c6b 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -767,6 +767,7 @@ As a user, I want to see all DPNS usernames I own so that I can manage my regist As a power user, I want to view active DPNS name contests so that I can participate in voting on contested names. - Lists all contests with status and vote counts. +- Contest refresh remains available if saved voting progress cannot be recovered. ### DPN-004: View past name contests [Implemented] **Persona:** Priya @@ -781,11 +782,13 @@ As a power user, I want to review past DPNS contests so that I can see outcomes As a masternode operator, I want to vote on contested DPNS name registrations so that I can participate in network governance. - See the node's proved current choice before casting, changing, or abstaining. -- Active contests groups cards into Needs your vote, Voted, and Not votable by your nodes; a staged choice takes precedence over the proved highlight until submission. +- Active contests groups cards into Needs your vote, Voted, Vote state unavailable, and Not votable by your nodes; a staged choice takes precedence over the proved highlight until submission. +- Unavailable or expired voting information keeps the affected contests visible and offers Refresh voting before enabling their vote controls. - A node may vote five times in total per contest: the initial vote plus up to four changes. - Choosing the current choice submits nothing. - Evonode/masternode identity required. - The Active-contests screen explains the four-change limit without inventing a remaining-change count; Platform enforces the limit. +- If a first immediate vote becomes a change after review, return to review with the current choice and change-limit warning. A matching current choice still submits nothing. ### DPN-006: Schedule votes [Implemented] **Persona:** Priya @@ -798,6 +801,7 @@ As a masternode operator, I want to schedule votes for later execution so that I - Removing a scheduled vote takes it off the list for good; it does not come back on the next refresh. - An ambiguous result remains visible for checking and is never automatically rebroadcast. - Votes that miss the normal automatic voting window show guidance to cast manually, edit, or remove them. Already queued votes retain their eligibility. +- Concurrent scheduled votes use the latest successfully saved voting information without losing their queued eligibility. Cast now retries the selected scheduled choice even when a different immediate vote succeeded afterward. - 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] @@ -812,6 +816,7 @@ As a masternode operator, I want to apply voting choices across multiple contest - Per-node timing overrides and multi-contest selections create exact node Γ— contest targets. - Review and cast lists each of those targets with its node, contest, requested choice, current choice, and timing, and reports how many targets it skipped because the node already holds the requested choice. - Immediate and scheduled targets submitted together belong to one operation. +- A successful mixed batch reports both cast and scheduled counts as success, without a warning about remaining work. ### DPN-010: Recover an ambiguous vote result [Implemented] **Persona:** Priya diff --git a/src/app.rs b/src/app.rs index 6e02df2ba..a7fc59c43 100644 --- a/src/app.rs +++ b/src/app.rs @@ -339,6 +339,17 @@ fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, MessageType, bo 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 ( "The vote was submitted, but DET could not confirm the result yet. DET will keep checking. Do not submit it again.".to_owned(), @@ -3817,6 +3828,19 @@ mod migration_banner_tests { 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 = [ diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index fc0c157b8..1ee9e9da7 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -180,7 +180,7 @@ impl AppContext { ) -> Result { let is_scheduled_sweep = matches!(&task, ContestedResourceTask::CastDueScheduledVotes { .. }); - if !is_scheduled_sweep { + if !is_scheduled_sweep && !matches!(&task, ContestedResourceTask::QueryDPNSContests) { self.ensure_dpns_vote_recovery(sdk).await?; } match task { @@ -366,14 +366,8 @@ impl AppContext { | DpnsVoteTargetStatus::Confirming => { return Err(TaskError::DpnsVoteTargetBusy); } - DpnsVoteTargetStatus::Confirmed => { - self.mark_vote_executed( - scheduled_vote.voter_id.as_slice(), - scheduled_vote.contested_name.clone(), - )?; - return Ok(operation); - } - DpnsVoteTargetStatus::Rejected + DpnsVoteTargetStatus::Confirmed + | DpnsVoteTargetStatus::Rejected | DpnsVoteTargetStatus::FailedBeforeSubmission | DpnsVoteTargetStatus::Cancelled | DpnsVoteTargetStatus::NotApplied => { @@ -423,6 +417,13 @@ impl AppContext { }; 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; @@ -520,20 +521,21 @@ impl AppContext { .and_then(|result| result.as_ref().map_err(Arc::clone)), Err(error) => Err(Arc::clone(error)), }; - let validation = snapshot.and_then(|snapshot| { - snapshot - .with_state(self, key.vote_poll_id, |state| { - matches!(state, DpnsCurrentVoteState::Available(_)).then(|| { - self.revalidate_dpns_vote_preflight( - &mut operation, - was_persisted, - &key, - state, - ) - }) + 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, + ) }) - .map_err(Arc::new) - }); + }, + ); let source = match validation { Ok(Some(result)) => { result?; @@ -1209,6 +1211,159 @@ mod tests { ]) } + #[test] + fn review_fixes_scheduled_retry_keeps_choice_after_different_immediate_success() { + let (_temp, context) = r2_context(); + let mut previous = r2_schedule(&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 = DpnsVoteOperation::new(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 review_fixes_new_immediate_vote_requires_review_when_it_becomes_a_change() { + let (_temp, context) = r2_context(); + let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + timing: VoteTiming::Now, + ..r2_schedule(&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 review_fixes_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 review_fixes_preflight_preserves_matching_noop_and_reviewed_changes() { + let (_temp, context) = r2_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 = DpnsVoteOperation::new(vec![DpnsVoteTarget { + timing: VoteTiming::Now, + current_choice: reviewed, + ..r2_schedule(&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 r2_terminal_retry_with_matching_cache_reaches_durable_no_op_preflight() { let (_temp, context) = r2_context(); diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index daf3b3ae7..c8eb5efcb 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -976,6 +976,10 @@ pub enum TaskError { #[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 { diff --git a/src/context/dpns_vote_state.rs b/src/context/dpns_vote_state.rs index 3d10a49c2..dd44c904c 100644 --- a/src/context/dpns_vote_state.rs +++ b/src/context/dpns_vote_state.rs @@ -42,7 +42,14 @@ struct StoredCurrentVotes { #[derive(Debug, Default)] pub(super) struct DpnsVoteStatePublications { sequence: AtomicU64, - voters: Mutex>, + voters: Mutex>, +} + +#[derive(Debug)] +struct DpnsVoteStatePublication { + generation: u64, + // A failed publication must not authorize fallback to older stored proof. + persisted: Option, } impl DpnsVoteStatePublications { @@ -79,7 +86,11 @@ impl RefreshedDpnsVotes { .voters .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - if publications.get(&self.voter_id) != Some(&self.generation) { + if publications + .get(&self.voter_id) + .map(|entry| entry.generation) + != Some(self.generation) + { return Err(TaskError::DpnsVoteStateChanged); } Ok(consume(snapshot_vote_state( @@ -173,6 +184,42 @@ fn snapshot_vote_state( } 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(), + ))) + } + /// Publish a deterministic proof failure without network I/O. #[cfg(test)] pub(crate) async fn fail_proved_dpns_votes_for_test( @@ -219,10 +266,17 @@ impl AppContext { .unwrap_or_else(std::sync::PoisonError::into_inner); if publications .get(&voter_id) - .is_some_and(|published| *published > generation) + .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() @@ -236,8 +290,14 @@ impl AppContext { votes: result.as_ref().cloned().unwrap_or_default(), confirmed, }; - publications.insert(voter_id, generation); 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)); @@ -346,9 +406,13 @@ impl AppContext { .voters .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); + let generation = self.dpns_vote_state_publications.next_generation()?; publications.insert( voter_id, - self.dpns_vote_state_publications.next_generation()?, + DpnsVoteStatePublication { + generation, + persisted: None, + }, ); let kv = self.det_kv()?; let mut snapshot = load_snapshot(&kv, self.network, &voter_id)?.unwrap_or_default(); @@ -359,7 +423,15 @@ impl AppContext { snapshot .confirmed .insert(vote_poll_id.to_buffer(), (confirmed_at, choice)); - save_snapshot(&kv, self.network, &voter_id, &snapshot) + save_snapshot(&kv, self.network, &voter_id, &snapshot)?; + publications.insert( + voter_id, + DpnsVoteStatePublication { + generation, + persisted: Some(snapshot), + }, + ); + Ok(()) } } @@ -456,6 +528,228 @@ mod tests { )) } + #[tokio::test] + async fn review_fixes_overlapping_refreshes_keep_both_due_targets_admitted() { + use crate::model::dpns_voting::{ + DpnsVoteOperation, 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| { + DpnsVoteOperation::new(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 + .refresh_dpns_vote_state_with(&kv, voter, async { Ok(BTreeMap::new()) }) + .await + .unwrap(); + published_tx.send(()).unwrap(); + snapshot + }; + let second = async { + published_rx.await.unwrap(); + context + .refresh_dpns_vote_state_with(&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 + .refresh_dpns_vote_state_with(&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.refresh_dpns_vote_state_with(&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 + .refresh_dpns_vote_state_with(&kv, voter, async { Ok(BTreeMap::new()) }) + .await + .unwrap(); + assert!( + context + .refresh_dpns_vote_state_with(&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 + .refresh_dpns_vote_state_with(&kv, voter, async { Ok(BTreeMap::new()) }) + .await + .unwrap(); + store.fail_next_gets_containing("det:dpns_current_votes:", 1); + assert!( + context + .refresh_dpns_vote_state_with(&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(); diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 2f5207dce..94445b71a 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -57,6 +57,7 @@ pub enum DPNSSubscreen { enum ActiveContestGroup { NeedsVote, Voted, + VoteStateUnavailable, NotVotable, } @@ -88,15 +89,20 @@ fn classify_vote_states( states: impl IntoIterator, ) -> ActiveContestGroup { let mut has_vote = false; + let mut has_unavailable_state = false; for state in states { match state { DpnsCurrentVoteState::Available(None) => return ActiveContestGroup::NeedsVote, DpnsCurrentVoteState::Available(Some(_)) => has_vote = true, - DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable => {} + DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable => { + has_unavailable_state = true; + } } } if has_vote { ActiveContestGroup::Voted + } else if has_unavailable_state { + ActiveContestGroup::VoteStateUnavailable } else { ActiveContestGroup::NotVotable } @@ -750,12 +756,13 @@ impl DPNSScreen { let filter = normalize_dpns_label(&self.active_filter_term); let contests = self.active_contests.contests(); - let mut groups = [Vec::new(), Vec::new(), Vec::new()]; + let mut groups = [Vec::new(), Vec::new(), Vec::new(), Vec::new()]; for contest in contests.iter() { let index = match self.contest_group(contest.vote_poll_id) { ActiveContestGroup::NeedsVote => 0, ActiveContestGroup::Voted => 1, - ActiveContestGroup::NotVotable => 2, + ActiveContestGroup::VoteStateUnavailable => 2, + ActiveContestGroup::NotVotable => 3, }; groups[index].push(contest); } @@ -795,10 +802,21 @@ impl DPNSScreen { .show(ui, |ui| { self.render_contest_group(ui, "Needs your vote", &groups[0], true, true, false); self.render_contest_group(ui, "Voted", &groups[1], false, true, true); + if !groups[2].is_empty() { + ui.label("Current votes are unavailable or out of date. Refresh voting to check these nodes."); + if ui.button("Refresh voting").clicked() { + self.pending_backend_task = Some(BackendTask::ContestedResourceTask( + ContestedResourceTask::QueryDPNSContests, + )); + } + self.render_contest_group( + ui, "Vote state unavailable", &groups[2], true, false, false, + ); + } self.render_contest_group( ui, "Not votable by your nodes", - &groups[2], + &groups[3], self.voting_identities.is_empty(), false, false, @@ -3102,7 +3120,7 @@ mod tests { DpnsCurrentVoteState::Checking, DpnsCurrentVoteState::Unavailable, ]), - ActiveContestGroup::NotVotable + ActiveContestGroup::VoteStateUnavailable )); } @@ -3774,6 +3792,100 @@ mod tests { assert!(!screen.finish_scheduled_dispatch(&dispatch)); } + #[test] + fn review_fixes_unavailable_contests_offer_a_visible_refresh_action() { + 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(); + 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(true, 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( + "Current votes are unavailable or out of date. Refresh voting to check these nodes." + ).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.bulk_apply_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.bulk_vote_handling_status, + VoteHandlingStatus::Failed(_) + )); + assert_eq!( + screen.build_review_plan().unwrap().entries[0] + .target + .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_review_and_cast_window(ui); + }); + harness.run(); + assert!( + harness + .query_by_label( + "Changing an existing vote uses one of that node's four allowed vote changes." + ) + .is_some() + ); + } + #[test] fn voting_ui_keyless_users_can_read_cached_active_contests() { use egui_kittest::kittest::Queryable; From ed34bc6e9cfba4bfa3e4c6e2a5e412bb4aadc798 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 14 Sep 2026 15:08:27 +0000 Subject: [PATCH 050/194] docs(dpns): fix duplicate story ID and close design-doc drift - Renumber the duplicate DPN-010 user story to the next free ID. - Add the missing 'Vote state unavailable' card group to the UX spec, matching shipped behavior. - Add the missing Cancelled variant to the DpnsVoteTargetStatus enum documented in the requirements and development-plan docs. - Correct the development-plan's stale task-variant name to describe the actual dispatch mechanism (CastDueScheduledVotes). - Update the requirements doc's stale 'planning only' status header to reflect that the feature shipped in PR #901. - Add FR/TC traceability for three later-landed, CHANGELOG-headline behaviors that previously had none: journal-read-failure retry, missed-schedule guidance, and the voting-key-mismatch error. Co-Authored-By: Claude Sonnet 5 --- .../01-requirements.md | 20 +++++++++++++++++-- .../02-ux-spec.md | 5 ++++- .../03-test-case-spec.md | 3 +++ .../04-development-plan.md | 11 +++++++++- docs/user-stories.md | 2 +- 5 files changed, 36 insertions(+), 5 deletions(-) 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 index dd8b6b8b4..389c67f6a 100644 --- 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 @@ -2,7 +2,12 @@ ## Status -Planning specification. No implementation is authorized by this document. +Implemented in PR [#901](https://github.com/dashpay/dash-evo-tool/pull/901) +(`feat(dpns): unify safe masternode voting operations`); see +`docs/user-stories.md` (DPN series) and `CHANGELOG.md` for the shipped, +user-visible behavior. The requirements below are kept as the original +planning record β€” later-landed behavior may extend them without this +document being updated in lockstep. ## Problem statement @@ -114,7 +119,8 @@ Everyday User workflow. - **VOTE-FR-032** β€” Target statuses are `Scheduled`, `Queued`, `Submitting`, `Confirming`, `Confirmed`, `Unconfirmed`, `Rejected`, and `Failed before submission`, plus `Not applied` after definitive - post-broadcast reconciliation. + post-broadcast reconciliation and `Cancelled` when the user cancels a + scheduled target before it is submitted (see VOTE-FR-055). - **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 @@ -140,6 +146,10 @@ Everyday User workflow. ambiguous. It offers `Check again`. - **VOTE-FR-045** β€” A retry becomes available only after authoritative reconciliation proves the requested change was not applied. +- **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 @@ -155,6 +165,9 @@ Everyday User workflow. contest, choice, time, or executed state. - **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 Votes as a missed automatic vote, with + `Cast now`, `Edit`, and `Remove` actions. ### Feedback @@ -165,6 +178,9 @@ Everyday User workflow. - **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. ## Non-functional requirements 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 index 16e8d4cb1..45125ae25 100644 --- 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 @@ -48,7 +48,9 @@ Contests render as cards, grouped in this order: 1. `Needs your vote` 2. `Voted` -3. `Not votable by your nodes` +3. `Vote state unavailable` β€” contests whose proved current vote state could + not be read; hidden when empty, with a `Refresh voting` action above it +4. `Not votable by your nodes` Each group is collapsible. The first group opens by default; the last group is dimmed and its vote controls are disabled. A filter remains available. @@ -66,6 +68,7 @@ dimmed and its vote controls are disabled. A filter remains available. β”‚ β”‚ [Vote for Alyce] (18 votes) 7Yk2aP…d1Rt β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β–Έ Voted (4) β”‚ +β”‚ β–Έ Vote state unavailable (1) [Refresh voting] β”‚ β”‚ β–Έ Not votable by your nodes (1) β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Votes ready to cast: 1 [Review and cast] β”‚ 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 index 3c012dab3..ee5eee8d3 100644 --- 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 @@ -21,6 +21,7 @@ | VOTE-TC-011 | Multi-contest vote | Active contests, three draft choices | Review | Review shows the exact node Γ— contest targets | FR-020, FR-031 | | VOTE-TC-012 | Schedule one choice | Active contests, one draft | Choose Schedule in review | Targets appear in Scheduled with the chosen time | FR-023, FR-050 | | VOTE-TC-013 | Missing voting key | No loaded node has a voting key | Open Active contests | An actionable state explains that a voting key is missing, offers `Load a masternode`, and leaves submit unavailable | FR-003 | +| VOTE-TC-014 | Voting key does not match node | Load a masternode with a voting private key belonging to a different node's voter identity | Submit the load | Load is rejected with `This voting key could not be matched to the selected node. Check that node's voting private key and try again.`; the node's existing keys and associated voter identity are unchanged | FR-065 | ## Bulk voting @@ -64,6 +65,7 @@ | VOTE-TC-054 | Reconcile to safe retry | Unconfirmed target; definitive reconciliation proves absence | Check again | Status allows reviewed resubmission | 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 | Partial batch | Two confirmed, one unconfirmed, one rejected | Complete batch | Warning shows counts and details map every target | FR-061, FR-062 | +| VOTE-TC-057 | Journal read failure stays visible until retried | Saved vote-operation progress cannot be read | Open Scheduled Votes, 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 migration @@ -75,6 +77,7 @@ | 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 | Scheduled target's due time is more than 120 seconds in the past and it has not executed | Reopen Scheduled Votes | Row shows `Missed automatic vote` with `Cast now`, `Edit`, and `Remove` actions | FR-056 | ## UX, accessibility, and isolation 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 index dd06596a2..301bd20ab 100644 --- 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 @@ -66,6 +66,8 @@ enum DpnsVoteTargetStatus { Rejected, FailedBeforeSubmission, NotApplied, + // The user cancelled a scheduled target before it was submitted. + Cancelled, } struct DpnsVoteOutcome { @@ -122,7 +124,7 @@ Replace tuple-heavy vote tasks/results with structured variants: ```rust ContestedResourceTask::SubmitDpnsVoteOperation(DpnsVoteOperation) ContestedResourceTask::ReconcileDpnsVoteOperation(DpnsVoteOperationId) -ContestedResourceTask::DispatchDueDpnsVotes +ContestedResourceTask::CastDueScheduledVotes { preserve_eligibility_since_ms: Option } BackendTaskContext::DpnsVoteOperation(DpnsVoteOperationId) BackendTaskSuccessResult::DpnsVoteOperationUpdated(DpnsVoteOperationId) @@ -133,6 +135,13 @@ carry only the operation ID needed for AppState to request repaint and show a summary. AppState never delivers raw vote outcomes to whichever screen happens to be visible. +As built, due-schedule dispatch is its own sweep rather than a side effect of +contest querying: `AppState::update()` in `app.rs` dispatches +`CastDueScheduledVotes` on a ~60s timer (tightened to a recovery backoff after +a deferred sweep), and `cast_due_scheduled_votes()` in +`src/backend_task/contested_names/mod.rs` loads due targets, casts them, and +persists results off the UI thread. + ## Execution algorithm 1. Validate the draft against current proved state. diff --git a/docs/user-stories.md b/docs/user-stories.md index 4e5da1c6b..2ed08b6df 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -818,7 +818,7 @@ As a masternode operator, I want to apply voting choices across multiple contest - Immediate and scheduled targets submitted together belong to one operation. - A successful mixed batch reports both cast and scheduled counts as success, without a warning about remaining work. -### DPN-010: Recover an ambiguous vote result [Implemented] +### DPN-011: Recover an ambiguous vote result [Implemented] **Persona:** Priya As a masternode operator, I want DET to keep checking a submitted vote whose From a504b8a0f583e599a5fa8c62130b6c7bda3ed7e8 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 14 Sep 2026 15:09:13 +0000 Subject: [PATCH 051/194] fix(app): route every DPNS result to hidden screens and fix vote copy is_dpns_vote_result omitted ScheduledVotesInProgress and RefreshedOwnedDpnsNames, both of which DPNSScreen::display_task_result handles. Hidden-screen routing runs before the result match in AppState::update, so those two were delivered to the visible screen only: refreshing on My usernames and navigating away before the result landed left refreshing_status on Refreshing, turning the empty-state Refresh button into a permanent no-op. Both variants are now routed, and a guard test reads the handler's own source and fails if the routed set and the handled set drift apart again. The non-auto-dismissing vote-result banner said "DET could not confirm the result yet. DET will keep checking". The product name is now spelled out, matching the rest of the voting flow. An all-no-op submit reported "This node already has that vote" even when every one of a bulk submit's targets was skipped. It now picks singular or plural copy from no_op_count, and the Ok(None) branch - which is where an all-no-op submit actually lands, since execute_dpns_vote_operation returns without persisting an operation - uses the plural form. The mixed-outcome message no longer bakes a count-dependent verb into one template ("1 of 7 votes were confirmed"); confirmed count, remaining count and unconfirmed guidance each pick a complete sentence that matches their count. The matching copy fixes in dpns_contested_names_screen.rs land in a separate commit. scheduled_vote_clear_feedback no longer returns out of the else arm of a let binding; the retained-votes branch mirrors the three-arm match shape used just above it. route_dpns_vote_error_to_hidden_screens open-coded the visibility condition that dpns_result_needs_hidden_route already had tests for. Both now call a shared dpns_screen_is_hidden helper. Co-Authored-By: Claude Sonnet 5 --- src/app.rs | 270 +++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 239 insertions(+), 31 deletions(-) diff --git a/src/app.rs b/src/app.rs index a7fc59c43..59bd097d3 100644 --- a/src/app.rs +++ b/src/app.rs @@ -298,6 +298,28 @@ struct DpnsVoteFeedbackCounts { 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. +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." + ), + } +} + fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, MessageType, bool) { let mut counts = DpnsVoteFeedbackCounts::default(); for outcome in &operation.targets { @@ -317,11 +339,11 @@ fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, MessageType, bo } } if operation.targets.is_empty() { - return ( - "This node already has that vote. Nothing was submitted.".to_owned(), - MessageType::Info, - false, - ); + 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 counts.confirmed == target_count { @@ -352,7 +374,7 @@ fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, MessageType, bo } if counts.unconfirmed == target_count { return ( - "The vote was submitted, but DET could not confirm the result yet. DET will keep checking. Do not submit it again.".to_owned(), + dpns_unconfirmed_guidance(counts.unconfirmed), MessageType::Warning, true, ); @@ -394,16 +416,20 @@ fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, MessageType, bo } let remaining = target_count.saturating_sub(counts.confirmed); - let confirmed = counts.confirmed; - let message = if counts.unconfirmed > 0 { - format!( - "{confirmed} of {target_count} votes were confirmed. Review the remaining {remaining}. The vote was submitted, but DET could not confirm the result yet. DET will keep checking. Do not submit it again.", - ) - } else { - format!( - "{confirmed} of {target_count} votes were confirmed. Review the remaining {remaining}.", - ) + let confirmed_sentence = match counts.confirmed { + 0 => format!("None of the {target_count} votes were confirmed."), + 1 => format!("1 of the {target_count} votes was confirmed."), + confirmed => format!("{confirmed} of the {target_count} votes were confirmed."), }; + let review_sentence = match remaining { + 1 => "Review the remaining vote.".to_owned(), + remaining => format!("Review the remaining {remaining} votes."), + }; + let mut message = format!("{confirmed_sentence} {review_sentence}"); + if counts.unconfirmed > 0 { + message.push(' '); + message.push_str(&dpns_unconfirmed_guidance(counts.unconfirmed)); + } (message, MessageType::Warning, counts.unconfirmed > 0) } @@ -428,15 +454,14 @@ fn scheduled_vote_clear_feedback( }; return (cleared_message, message_type); } - let retained_message = if in_flight == 1 { - "1 vote already in progress remains listed. Wait for it to finish before trying again." - } else { - return ( - format!( - "{cleared_message} {in_flight} votes already in progress remain listed. Wait for them to finish before trying again." - ), - MessageType::Info, - ); + let retained_message = match in_flight { + 1 => { + "1 vote already in progress remains listed. Wait for it to finish before trying again." + .to_owned() + } + count => format!( + "{count} votes already in progress remain listed. Wait for them to finish before trying again." + ), }; ( format!("{cleared_message} {retained_message}"), @@ -486,23 +511,41 @@ fn identity_hub_is_visible(selected: RootScreenType, screen_stack_is_empty: bool selected == RootScreenType::RootScreenIdentityHub && screen_stack_is_empty } +/// Every result `DPNSScreen::display_task_result` acts on, so that a DPNS root +/// screen receives it even while hidden. Dropping a variant here without +/// dropping its handler arm strands the screen in the state that result would +/// have cleared. `dpns_result_routing_tests` reads the handler's source and +/// fails if the two sets drift apart. fn is_dpns_vote_result(result: &BackendTaskSuccessResult) -> bool { matches!( result, BackendTaskSuccessResult::DpnsVoteOperationUpdated { .. } | BackendTaskSuccessResult::RefreshedDpnsContests + | BackendTaskSuccessResult::RefreshedOwnedDpnsNames | BackendTaskSuccessResult::ScheduledVoteSweepCompleted { .. } | BackendTaskSuccessResult::ScheduledVotesCleared(_) + | BackendTaskSuccessResult::ScheduledVotesInProgress(_) ) } +/// 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 { - is_dpns_vote_result(result) && (selected != target || !screen_stack_is_empty) + is_dpns_vote_result(result) && dpns_screen_is_hidden(target, selected, screen_stack_is_empty) } /// Plain, jargon-free descriptions for the SPV-sync block (Everyday-User rule: @@ -2703,8 +2746,11 @@ impl AppState { RootScreenType::RootScreenDPNSActiveContests, RootScreenType::RootScreenDPNSScheduledVotes, ] { - if (self.selected_main_screen != root || !self.screen_stack.is_empty()) - && let Some(screen) = self.main_screens.get_mut(&root) + if dpns_screen_is_hidden( + root, + self.selected_main_screen, + self.screen_stack.is_empty(), + ) && let Some(screen) = self.main_screens.get_mut(&root) { screen.display_backend_task_error(context, error); screen.display_task_error(error); @@ -3240,10 +3286,13 @@ impl App for AppState { 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, - "This node already has that vote. Nothing was submitted.", + DPNS_ALL_VOTES_ALREADY_CAST, MessageType::Info, ); } @@ -3894,7 +3943,17 @@ mod migration_banner_tests { ( vec![DpnsVoteTargetStatus::Unconfirmed], 0, - "The vote was submitted, but DET could not confirm the result yet. DET will keep checking. Do not submit it again.", + "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, ), @@ -3915,7 +3974,14 @@ mod migration_banner_tests { ( Vec::new(), 1, - "This node already has that vote. Nothing was submitted.", + "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, ), @@ -3954,7 +4020,42 @@ mod migration_banner_tests { assert!(keep_visible); assert_eq!( message, - "1 of 7 votes were confirmed. Review the remaining 6. The vote was submitted, but DET could not confirm the result yet. DET will keep checking. Do not submit it again." + "1 of the 7 votes was confirmed. Review the remaining 6 votes. The vote was submitted, but the result could not be confirmed yet. Dash Evo Tool will keep checking. Do not submit it again." + ); + } + + /// Counts drive which sentence is built, so no single template has to carry + /// a verb that is only correct for one of them. + #[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, + "2 of the 3 votes were confirmed. Review the remaining vote." + ); + } + + #[test] + fn vote_feedback_reports_no_confirmations_without_a_leading_zero() { + let operation = feedback_operation(&[ + DpnsVoteTargetStatus::Rejected, + DpnsVoteTargetStatus::NotApplied, + ]); + + let (message, _, _) = dpns_vote_feedback(&operation); + + assert_eq!( + message, + "None of the 2 votes were confirmed. Review the remaining 2 votes." ); } @@ -4413,6 +4514,113 @@ mod dpns_result_routing_tests { )); } + /// The DPNS screen's own source, read at compile time so the guard below + /// tracks the handler instead of a hand-copied list of variant names. + const DPNS_SCREEN_SOURCE: &str = include_str!("ui/dpns/dpns_contested_names_screen.rs"); + + /// Result variant names `DPNSScreen::display_task_result` matches on. + fn variants_the_dpns_screen_handles() -> Vec { + const MARKER: &str = "BackendTaskSuccessResult::"; + let start = DPNS_SCREEN_SOURCE + .find("fn display_task_result(") + .expect("DPNSScreen::display_task_result was renamed; update this guard"); + let handler = &DPNS_SCREEN_SOURCE[start..]; + let end = handler[1..] + .find("\n fn ") + .map_or(handler.len(), |offset| offset + 1); + let handler = &handler[..end]; + + let mut variants: Vec = Vec::new(); + for (index, _) in handler.match_indices(MARKER) { + let name: String = handler[index + MARKER.len()..] + .chars() + .take_while(|character| character.is_alphanumeric() || *character == '_') + .collect(); + if !name.is_empty() && !variants.contains(&name) { + variants.push(name); + } + } + assert!( + !variants.is_empty(), + "no handled variants found; the guard no longer locates DPNSScreen::display_task_result" + ); + variants + } + + fn sample_result(variant: &str) -> BackendTaskSuccessResult { + match variant { + "DpnsVoteOperationUpdated" => BackendTaskSuccessResult::DpnsVoteOperationUpdated { + network: Network::Testnet, + operation_id: DpnsVoteOperationId::from_bytes([5; 16]), + }, + "ScheduledVoteSweepCompleted" => { + BackendTaskSuccessResult::ScheduledVoteSweepCompleted { + network: Network::Testnet, + preserve_eligibility_since_ms: None, + } + } + "ScheduledVotesInProgress" => { + BackendTaskSuccessResult::ScheduledVotesInProgress(Vec::new()) + } + "ScheduledVotesCleared" => BackendTaskSuccessResult::ScheduledVotesCleared(Vec::new()), + "RefreshedDpnsContests" => BackendTaskSuccessResult::RefreshedDpnsContests, + "RefreshedOwnedDpnsNames" => BackendTaskSuccessResult::RefreshedOwnedDpnsNames, + unknown => panic!( + "DPNSScreen::display_task_result now handles {unknown}; add a sample here and route it in is_dpns_vote_result" + ), + } + } + + /// A result the DPNS screen acts on but `is_dpns_vote_result` rejects is + /// dropped whenever that screen is hidden, so the two sets must agree. + #[test] + fn every_result_the_dpns_screen_handles_is_routed_to_hidden_screens() { + for variant in variants_the_dpns_screen_handles() { + assert!( + is_dpns_vote_result(&sample_result(&variant)), + "DPNSScreen::display_task_result handles {variant} but is_dpns_vote_result drops it while the screen is hidden" + ); + } + } + + /// Refresh on My usernames, navigate away, come back: without routing, the + /// screen never clears `RefreshingStatus::Refreshing` and its Refresh + /// button stays inert. + #[test] + fn refreshed_owned_names_route_when_the_dpns_screen_is_hidden() { + assert!(dpns_result_needs_hidden_route( + RootScreenType::RootScreenDPNSActiveContests, + RootScreenType::RootScreenWalletsBalances, + true, + &BackendTaskSuccessResult::RefreshedOwnedDpnsNames, + )); + } + + #[test] + fn scheduled_votes_in_progress_route_when_the_dpns_screen_is_hidden() { + assert!(dpns_result_needs_hidden_route( + RootScreenType::RootScreenDPNSScheduledVotes, + 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 a_dpns_screen_is_hidden_behind_another_root_screen_or_a_modal() { + let target = RootScreenType::RootScreenDPNSActiveContests; + + 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 { From e9b7f383c57174310cd3384d64b9f3867c7c9e8f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 14 Sep 2026 15:03:52 +0000 Subject: [PATCH 052/194] fix(dpns): give vote reconciliation a negative terminal verdict An Unconfirmed target held its exact (network, voter, poll) lock forever: classify_reconciled_vote could only ever return Confirmed, every other observation collapsed back to Unconfirmed, and DpnsVoteTargetStatus::NotApplied was never assigned anywhere in production. A lost broadcast therefore wedged the target for good -- no cancel, no clear-all and no retention pass could release it, and the journal record grew without bound. Reconciliation now reaches NotApplied once the vote poll is proved closed. A merely different current choice still proves nothing (it may predate the submitted transition), so the existing ambiguity rule is unchanged; a decided or expired contest is authoritative, because no transition can apply to it. The Unconfirmed phase is now bounded by the contest window instead of being unbounded, the lock is released, and the operation becomes prunable. - add DpnsVotePollAvailability and dpns_vote_poll_availability to the DPNS voting model; an uncached contest stays MayAccept, since absence of evidence is not evidence of closure - derive availability per target in reconcile_dpns_vote_operation from the cached contests, matching on the normalized name the way dpns_vote_poll_id does - extract with_target/TargetUpdate in the journal, collapsing seven copies of the load-find-check-mutate-persist prologue and deciding the missing-record, missing-target and cancelled-target policies in one place - add AppContext::journal_guard/journal, replacing the guard boilerplate that was written out by hand at twenty call sites - drop the write_existing_operation and prune_immediate_history forwarders, and replace the prune_completed_history bool parameter with a HistoryKind enum - split the journal into keys.rs, retention.rs and transitions.rs; the facade, migration and lock-index protocol stay in mod.rs - name the tests after the behaviour they assert rather than the review round Co-Authored-By: Claude Sonnet 5 --- src/backend_task/contested_names/mod.rs | 340 +++++++-- src/context/dpns_vote_operations/keys.rs | 72 ++ .../mod.rs} | 712 +++--------------- src/context/dpns_vote_operations/retention.rs | 256 +++++++ .../dpns_vote_operations/transitions.rs | 127 ++++ src/model/dpns_voting.rs | 38 +- 6 files changed, 902 insertions(+), 643 deletions(-) create mode 100644 src/context/dpns_vote_operations/keys.rs rename src/context/{dpns_vote_operations.rs => dpns_vote_operations/mod.rs} (81%) create mode 100644 src/context/dpns_vote_operations/retention.rs create mode 100644 src/context/dpns_vote_operations/transitions.rs diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 1ee9e9da7..8920a4444 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -10,15 +10,17 @@ use crate::backend_task::error::{DapiAddressAvailability, TaskError}; use crate::context::AppContext; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduleEditValidationError, DpnsVoteFailure, DpnsVoteOperation, - DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, - dpns_schedule_is_overdue, failed_before_broadcast_outcome, unavailable_preflight_outcome, - validate_dpns_schedule_edit, validate_dpns_schedule_time, + DpnsVoteOperationId, DpnsVotePollAvailability, DpnsVoteTarget, DpnsVoteTargetKey, + DpnsVoteTargetStatus, VoteTiming, dpns_schedule_is_overdue, 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 dash_sdk::Sdk; use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; +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::votes::resource_vote::ResourceVote; use dash_sdk::dpp::voting::votes::resource_vote::accessors::v0::ResourceVoteGettersV0; @@ -105,14 +107,22 @@ fn missing_voter_outcome( (status, failure, matches!(timing, VoteTiming::Scheduled(_))) } +/// Decide whether one reconciliation observation is terminal. +/// +/// Returns `None` while the outcome stays ambiguous, which keeps the target +/// locked. A current choice that differs from `requested` is not by itself +/// evidence against the submitted transition β€” it may simply predate it β€” so it +/// only becomes terminal once `availability` proves the poll can no longer +/// accept anything. fn classify_reconciled_vote( observed: Option, requested: ResourceVoteChoice, + availability: DpnsVotePollAvailability, ) -> Option { - match observed { - Some(choice) if choice == requested => Some(DpnsVoteTargetStatus::Confirmed), - // A different current choice does not establish that this transition cannot apply. - Some(_) | None => None, + match (observed, availability) { + (Some(choice), _) if choice == requested => Some(DpnsVoteTargetStatus::Confirmed), + (_, DpnsVotePollAvailability::ProvedClosed) => Some(DpnsVoteTargetStatus::NotApplied), + (_, DpnsVotePollAvailability::MayAccept) => None, } } @@ -860,11 +870,23 @@ impl AppContext { operation_id, }); }; + // TODO: a wedged target is only released once its contest closes. Restore + // the operator-driven "stop waiting and vote again" escape so one can also + // be abandoned mid-contest; that needs a control in the DPNS contests screen. + let contests = self + .all_contested_names()? + .into_iter() + .map(|contest| (contest.normalized_contested_name.clone(), contest)) + .collect::>(); + let now_ms = UNIX_EPOCH.elapsed().unwrap_or_default().as_millis() as u64; for outcome in operation .targets .iter() .filter(|outcome| outcome.status == DpnsVoteTargetStatus::Unconfirmed) { + // Targets may carry the label the operator typed; contests are keyed normalized. + let normalized = convert_to_homograph_safe_chars(&outcome.target.contested_name); + let availability = dpns_vote_poll_availability(contests.get(&normalized), now_ms); let poll_id = outcome.target.key.vote_poll_id; let query = ContestedResourceVotesGivenByIdentityQuery { identity_id: outcome.target.key.voter_id, @@ -879,9 +901,12 @@ impl AppContext { .get(&poll_id) .and_then(Option::as_ref) .map(ResourceVoteGettersV0::resource_vote_choice); - let reconciled_status = - classify_reconciled_vote(observed, outcome.target.requested_choice); - let status = reconciled_status.unwrap_or(DpnsVoteTargetStatus::Unconfirmed); + let status = classify_reconciled_vote( + observed, + outcome.target.requested_choice, + availability, + ) + .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); if !self.update_dpns_vote_reconciliation( operation_id, &outcome.target.key, @@ -1188,7 +1213,7 @@ mod tests { } } - fn r2_context() -> (tempfile::TempDir, Arc) { + 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( @@ -1197,7 +1222,11 @@ mod tests { (temp, context) } - fn r2_schedule(context: &AppContext, name: &str, timestamp: u64) -> DpnsVoteOperation { + fn scheduled_operation_for( + context: &AppContext, + name: &str, + timestamp: u64, + ) -> DpnsVoteOperation { DpnsVoteOperation::new(vec![ context .dpns_vote_target( @@ -1212,9 +1241,9 @@ mod tests { } #[test] - fn review_fixes_scheduled_retry_keeps_choice_after_different_immediate_success() { - let (_temp, context) = r2_context(); - let mut previous = r2_schedule(&context, "alice", 42); + 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 @@ -1251,11 +1280,13 @@ mod tests { } #[test] - fn review_fixes_new_immediate_vote_requires_review_when_it_becomes_a_change() { - let (_temp, context) = r2_context(); + fn new_immediate_vote_requires_review_when_it_becomes_a_change() { + let (_temp, context) = vote_context(); let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { timing: VoteTiming::Now, - ..r2_schedule(&context, "alice", 42).targets[0].target.clone() + ..scheduled_operation_for(&context, "alice", 42).targets[0] + .target + .clone() }]); let key = operation.targets[0].target.key.clone(); assert!( @@ -1274,7 +1305,7 @@ mod tests { } #[tokio::test] - async fn review_fixes_contest_query_does_not_require_readable_vote_journal() { + 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; @@ -1331,8 +1362,8 @@ mod tests { } #[test] - fn review_fixes_preflight_preserves_matching_noop_and_reviewed_changes() { - let (_temp, context) = r2_context(); + fn preflight_preserves_matching_noop_and_reviewed_changes() { + let (_temp, context) = vote_context(); for (reviewed, observed, expected_status) in [ ( None, @@ -1349,7 +1380,9 @@ mod tests { let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { timing: VoteTiming::Now, current_choice: reviewed, - ..r2_schedule(&context, "alice", 42).targets[0].target.clone() + ..scheduled_operation_for(&context, "alice", 42).targets[0] + .target + .clone() }]); let key = operation.targets[0].target.key.clone(); context @@ -1365,9 +1398,9 @@ mod tests { } #[test] - fn r2_terminal_retry_with_matching_cache_reaches_durable_no_op_preflight() { - let (_temp, context) = r2_context(); - let mut previous = r2_schedule(&context, "alice", 42); + 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) @@ -1418,11 +1451,11 @@ mod tests { } #[tokio::test] - async fn r2_sweep_preserves_due_votes_across_slow_reconciliation() { - let (_temp, context) = r2_context(); + async fn sweep_preserves_due_votes_across_slow_reconciliation() { + let (_temp, context) = vote_context(); let started = 1_000_000; let clock = std::cell::Cell::new(started); - let mut operation = r2_schedule(&context, "alice", started); + let mut operation = scheduled_operation_for(&context, "alice", started); context .insert_dpns_vote_operation(&mut operation, None) .unwrap(); @@ -1450,12 +1483,12 @@ mod tests { } #[tokio::test] - async fn r2_sweep_reconciliation_failure_retains_durable_due_admission() { - let (_temp, context) = r2_context(); + 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 = r2_schedule(&context, "alice", started); - let mut newly_due = r2_schedule(&context, "bob", started + 10); + 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) @@ -1477,9 +1510,9 @@ mod tests { } #[tokio::test] - async fn r2_new_schedule_rejects_past_time_before_persistence() { - let (_temp, context) = r2_context(); - let operation = r2_schedule(&context, "alice", 1); + 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; @@ -1491,7 +1524,7 @@ mod tests { } #[tokio::test] - async fn r2_new_schedule_validates_known_deadline_and_unknown_deadline_policy() { + async fn new_schedule_validates_known_deadline_and_unknown_deadline_policy() { let now = UNIX_EPOCH.elapsed().unwrap().as_millis() as u64; let end = now + 120_000; for (timestamp, deadline, expected_valid) in [ @@ -1500,9 +1533,9 @@ mod tests { (end + 1, Some(end), false), (end, None, true), ] { - let (_temp, context) = r2_context(); + let (_temp, context) = vote_context(); context.seed_dpns_contest_for_test("alice", deadline, false); - let operation = r2_schedule(&context, "alice", timestamp); + let operation = scheduled_operation_for(&context, "alice", timestamp); let result = context .execute_dpns_vote_operation(operation, vec![], None, &context.sdk()) .await; @@ -1520,14 +1553,14 @@ mod tests { } #[tokio::test] - async fn r2_new_schedule_rejects_mixed_deadlines_atomically_and_missing_or_closed_contests() { + async fn new_schedule_rejects_mixed_deadlines_atomically_and_missing_or_closed_contests() { let now = UNIX_EPOCH.elapsed().unwrap().as_millis() as u64; let timestamp = now + 60_000; - let (_temp, context) = r2_context(); + 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 = r2_schedule(&context, "alice", timestamp).targets; - targets.extend(r2_schedule(&context, "bob", timestamp).targets); + let mut targets = scheduled_operation_for(&context, "alice", timestamp).targets; + targets.extend(scheduled_operation_for(&context, "bob", timestamp).targets); let operation = DpnsVoteOperation::new(targets.into_iter().map(|o| o.target).collect()); let result = context .execute_dpns_vote_operation(operation, vec![], None, &context.sdk()) @@ -1544,7 +1577,7 @@ mod tests { } let result = context .execute_dpns_vote_operation( - r2_schedule(&context, name, timestamp), + scheduled_operation_for(&context, name, timestamp), vec![], None, &context.sdk(), @@ -1556,8 +1589,8 @@ mod tests { } #[tokio::test] - async fn r2_sweep_preserves_newly_due_but_excludes_already_stale_and_future_targets() { - let (_temp, context) = r2_context(); + 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); @@ -1567,7 +1600,10 @@ mod tests { ("future", finished + 1), ] { context - .insert_dpns_vote_operation(&mut r2_schedule(&context, name, timestamp), None) + .insert_dpns_vote_operation( + &mut scheduled_operation_for(&context, name, timestamp), + None, + ) .unwrap(); } let (due, _) = context @@ -1770,21 +1806,209 @@ mod tests { #[test] fn exact_reconciliation_confirms_only_the_requested_choice() { assert_eq!( - classify_reconciled_vote(Some(ResourceVoteChoice::Lock), ResourceVoteChoice::Lock,), + classify_reconciled_vote( + Some(ResourceVoteChoice::Lock), + ResourceVoteChoice::Lock, + DpnsVotePollAvailability::MayAccept, + ), Some(DpnsVoteTargetStatus::Confirmed) ); assert_eq!( - classify_reconciled_vote(Some(ResourceVoteChoice::Abstain), ResourceVoteChoice::Lock,), + classify_reconciled_vote( + Some(ResourceVoteChoice::Abstain), + ResourceVoteChoice::Lock, + DpnsVotePollAvailability::MayAccept, + ), None, "a mismatched row may predate the submitted transition and remains ambiguous" ); assert_eq!( - classify_reconciled_vote(None, ResourceVoteChoice::Lock,), + classify_reconciled_vote( + None, + ResourceVoteChoice::Lock, + DpnsVotePollAvailability::MayAccept, + ), None, "an absent exact row remains ambiguous and must not release its lock" ); } + /// A closed poll is the terminal evidence that ambiguity alone never supplies. + #[test] + fn a_closed_poll_turns_an_unreconcilable_vote_into_a_terminal_verdict() { + assert_eq!( + classify_reconciled_vote( + Some(ResourceVoteChoice::Abstain), + ResourceVoteChoice::Lock, + DpnsVotePollAvailability::ProvedClosed, + ), + Some(DpnsVoteTargetStatus::NotApplied), + "a decided contest can no longer accept the submitted transition" + ); + assert_eq!( + classify_reconciled_vote( + None, + ResourceVoteChoice::Lock, + DpnsVotePollAvailability::ProvedClosed, + ), + Some(DpnsVoteTargetStatus::NotApplied), + "an absent row on a closed poll proves the vote never applied" + ); + assert_eq!( + classify_reconciled_vote( + Some(ResourceVoteChoice::Lock), + ResourceVoteChoice::Lock, + DpnsVotePollAvailability::ProvedClosed, + ), + Some(DpnsVoteTargetStatus::Confirmed), + "a vote that did apply stays confirmed after the contest closes" + ); + assert!(!DpnsVoteTargetStatus::NotApplied.holds_lock()); + } + + #[test] + fn poll_availability_is_proved_only_by_a_cached_decided_or_expired_contest() { + let (_temp, context) = vote_context(); + assert_eq!( + dpns_vote_poll_availability(None, 1_000), + DpnsVotePollAvailability::MayAccept, + "an uncached contest is unknown, not closed" + ); + + for (end_time, closed, now_ms, expected) in [ + ( + Some(2_000), + false, + 1_000, + DpnsVotePollAvailability::MayAccept, + ), + (None, false, 1_000, DpnsVotePollAvailability::MayAccept), + ( + Some(1_000), + false, + 1_000, + DpnsVotePollAvailability::ProvedClosed, + ), + ( + Some(2_000), + true, + 1_000, + 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(), now_ms), + expected, + "end_time {end_time:?}, closed {closed}, now {now_ms}" + ); + } + } + + /// An unreconcilable target must not hold its lock past the contest it belongs to. + #[tokio::test] + async fn an_unreconcilable_vote_releases_its_lock_once_the_contest_closes() { + let (_temp, context) = vote_context(); + let key = DpnsVoteTargetKey { + network: Network::Testnet, + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([2; 32]), + }; + let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + key: key.clone(), + voter_alias: None, + contested_name: "dominguez".to_owned(), + requested_choice: ResourceVoteChoice::Abstain, + current_choice: Some(ResourceVoteChoice::Lock), + timing: VoteTiming::Now, + }]); + operation.targets[0].status = DpnsVoteTargetStatus::Confirming; + let operation_id = operation.id; + context + .insert_dpns_vote_operation(&mut operation, None) + .expect("persist confirming operation"); + // The broadcast was lost: the node keeps proving its previous choice. + context + .update_dpns_vote_target( + operation_id, + &key, + DpnsVoteTargetStatus::Unconfirmed, + Some(DpnsVoteFailure::ResultUnconfirmed), + ) + .expect("persist unconfirmed operation"); + + let observed = Some(ResourceVoteChoice::Lock); + let mut expected_current = None; + for round in 0..3 { + let status = classify_reconciled_vote( + observed, + ResourceVoteChoice::Abstain, + DpnsVotePollAvailability::MayAccept, + ) + .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); + assert!( + context + .update_dpns_vote_reconciliation( + operation_id, + &key, + expected_current, + observed, + status, + ) + .expect("persist observation") + ); + expected_current = observed; + assert_eq!( + context.dpns_vote_target_status(&key).unwrap(), + Some(DpnsVoteTargetStatus::Unconfirmed), + "round {round}: an open contest keeps the ambiguous target locked" + ); + } + + let terminal = classify_reconciled_vote( + observed, + ResourceVoteChoice::Abstain, + DpnsVotePollAvailability::ProvedClosed, + ) + .expect("a closed poll must reach a terminal verdict"); + assert_eq!(terminal, DpnsVoteTargetStatus::NotApplied); + assert!( + context + .update_dpns_vote_reconciliation( + operation_id, + &key, + expected_current, + observed, + terminal, + ) + .expect("persist terminal verdict") + ); + + assert_eq!( + context.dpns_vote_target_status(&key).unwrap(), + None, + "the exact voter x poll lock must be released" + ); + let persisted = context.dpns_vote_operation(operation_id).unwrap().unwrap(); + assert_eq!( + persisted.targets[0].status, + DpnsVoteTargetStatus::NotApplied + ); + assert!( + persisted.is_complete(), + "a terminal operation must become prunable instead of growing the journal forever" + ); + + let mut retry = DpnsVoteOperation::new(vec![DpnsVoteTarget { + current_choice: None, + ..persisted.targets[0].target.clone() + }]); + context + .insert_dpns_vote_operation(&mut retry, None) + .expect("a released target must accept a fresh operation"); + } + #[test] fn repeated_mismatches_keep_an_ambiguous_vote_locked() { let temp_dir = tempfile::tempdir().expect("tempdir"); @@ -1832,8 +2056,12 @@ mod tests { ); let observed = Some(ResourceVoteChoice::Abstain); - let first_status = classify_reconciled_vote(observed, ResourceVoteChoice::Lock) - .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); + let first_status = classify_reconciled_vote( + observed, + ResourceVoteChoice::Lock, + DpnsVotePollAvailability::MayAccept, + ) + .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); assert!( context .update_dpns_vote_reconciliation(operation_id, &key, None, observed, first_status,) @@ -1842,8 +2070,12 @@ mod tests { 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); + let second_status = classify_reconciled_vote( + observed, + ResourceVoteChoice::Lock, + DpnsVotePollAvailability::MayAccept, + ) + .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); assert!( context .update_dpns_vote_reconciliation( @@ -1952,7 +2184,7 @@ mod tests { } #[tokio::test] - async fn additional_scenarios_failed_migration_retries_in_the_same_process() { + 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()); diff --git a/src/context/dpns_vote_operations/keys.rs b/src/context/dpns_vote_operations/keys.rs new file mode 100644 index 000000000..2f83ad3a5 --- /dev/null +++ b/src/context/dpns_vote_operations/keys.rs @@ -0,0 +1,72 @@ +//! Key schema for the DPNS vote journal's k/v namespaces. +//! +//! Every key the journal owns is built here so the on-disk layout, including +//! the v1 names still read by migration, has one definition. + +use crate::backend_task::error::TaskError; +use crate::model::dpns_voting::DpnsVoteOperationId; +use crate::wallet_backend::KvAdapterError; +use dash_sdk::dpp::dashcore::Network; + +pub(super) const LEGACY_OPERATION_INDEX_KEY: &str = "det:dpns_vote_operations:v1"; +pub(super) const LEGACY_OPERATION_KEY_PREFIX: &str = "det:dpns_vote_operation:v1:"; +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 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 network_tag(network: Network) -> &'static str { + match network { + Network::Mainnet => "mainnet", + Network::Testnet => "testnet", + Network::Devnet => "devnet", + Network::Regtest => "regtest", + } +} + +pub(super) fn operation_index_key(network: Network) -> String { + format!("{OPERATION_INDEX_KEY_PREFIX}{}", network_tag(network)) +} + +pub(super) fn operation_key(network: Network, id: DpnsVoteOperationId) -> String { + format!("{OPERATION_KEY_PREFIX}{}:{id}", network_tag(network)) +} + +pub(super) fn operation_key_prefix(network: Network) -> String { + format!("{OPERATION_KEY_PREFIX}{}:", network_tag(network)) +} + +pub(super) fn schedule_dismissal_key(network: Network, id: DpnsVoteOperationId) -> String { + format!( + "{SCHEDULE_DISMISSAL_KEY_PREFIX}{}:{id}", + network_tag(network) + ) +} + +pub(super) fn operation_lock_index_key(network: Network) -> String { + format!("{OPERATION_LOCK_INDEX_KEY_PREFIX}{}", network_tag(network)) +} + +pub(super) fn operation_lock_index_dirty_key(network: Network) -> String { + format!( + "{OPERATION_LOCK_INDEX_DIRTY_KEY_PREFIX}{}", + network_tag(network) + ) +} + +pub(super) fn legacy_operation_key(id: DpnsVoteOperationId) -> String { + format!("{LEGACY_OPERATION_KEY_PREFIX}{id}") +} + +pub(super) fn operation_err(source: KvAdapterError) -> TaskError { + TaskError::DpnsVoteOperationStorage { source } +} + +pub(super) fn unreadable_operation_err(source: KvAdapterError) -> TaskError { + TaskError::DpnsVoteOperationUnreadable { source } +} diff --git a/src/context/dpns_vote_operations.rs b/src/context/dpns_vote_operations/mod.rs similarity index 81% rename from src/context/dpns_vote_operations.rs rename to src/context/dpns_vote_operations/mod.rs index ee79d8e2d..f88c60c96 100644 --- a/src/context/dpns_vote_operations.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -1,5 +1,15 @@ //! Durable DPNS vote operation journal and exact-target lock registry. +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::contested_names::ScheduledDPNSVote; use crate::backend_task::error::TaskError; @@ -10,117 +20,20 @@ use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome, DpnsScheduledVoteEdit, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, - failed_before_broadcast_outcome, unavailable_preflight_outcome, + unavailable_preflight_outcome, }; -use crate::wallet_backend::{DetKv, DetScope, KvAdapterError}; +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 LEGACY_OPERATION_INDEX_KEY: &str = "det:dpns_vote_operations:v1"; -const LEGACY_OPERATION_KEY_PREFIX: &str = "det:dpns_vote_operation:v1:"; -const OPERATION_INDEX_KEY_PREFIX: &str = "det:dpns_vote_operations:v2:"; -const OPERATION_KEY_PREFIX: &str = "det:dpns_vote_operation:v2:"; -const OPERATION_LOCK_INDEX_KEY_PREFIX: &str = "det:dpns_vote_operation_locks:v2:"; -const OPERATION_LOCK_INDEX_DIRTY_KEY_PREFIX: &str = "det:dpns_vote_operation_locks_dirty:v2:"; const DPNS_VOTE_DIAGNOSTIC_LIMIT: usize = 256; -/// Completed immediate batches retained per network; unresolved work is never capped. -const DPNS_IMMEDIATE_HISTORY_LIMIT: usize = 256; -const DPNS_SCHEDULED_HISTORY_LIMIT: usize = 256; -const SCHEDULE_DISMISSAL_KEY_PREFIX: &str = "det:dpns_vote_schedule_dismissals:v1:"; -const IMMEDIATE_HISTORY_KEY_PREFIX: &str = "det:dpns_vote_immediate_history:v1:"; -const SCHEDULED_HISTORY_KEY_PREFIX: &str = "det:dpns_vote_scheduled_history:v1:"; type DpnsVoteLockIndex = BTreeMap; type DpnsVoteDiagnosticMap = BTreeMap<(DpnsVoteOperationId, DpnsVoteTargetKey), (u64, Arc)>; -fn network_tag(network: Network) -> &'static str { - match network { - Network::Mainnet => "mainnet", - Network::Testnet => "testnet", - Network::Devnet => "devnet", - Network::Regtest => "regtest", - } -} - -fn operation_index_key(network: Network) -> String { - format!("{OPERATION_INDEX_KEY_PREFIX}{}", network_tag(network)) -} - -fn operation_key(network: Network, id: DpnsVoteOperationId) -> String { - format!("{OPERATION_KEY_PREFIX}{}:{id}", network_tag(network)) -} - -fn operation_key_prefix(network: Network) -> String { - format!("{OPERATION_KEY_PREFIX}{}:", network_tag(network)) -} - -fn schedule_dismissal_key(network: Network, id: DpnsVoteOperationId) -> String { - format!( - "{SCHEDULE_DISMISSAL_KEY_PREFIX}{}:{id}", - network_tag(network) - ) -} - -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 before clearing their mirrors, under the journal guard. -pub(super) 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(()) -} - -fn operation_lock_index_key(network: Network) -> String { - format!("{OPERATION_LOCK_INDEX_KEY_PREFIX}{}", network_tag(network)) -} - -fn operation_lock_index_dirty_key(network: Network) -> String { - format!( - "{OPERATION_LOCK_INDEX_DIRTY_KEY_PREFIX}{}", - network_tag(network) - ) -} - -fn legacy_operation_key(id: DpnsVoteOperationId) -> String { - format!("{LEGACY_OPERATION_KEY_PREFIX}{id}") -} - -fn operation_err(source: KvAdapterError) -> TaskError { - TaskError::DpnsVoteOperationStorage { source } -} - -fn unreadable_operation_err(source: KvAdapterError) -> TaskError { - TaskError::DpnsVoteOperationUnreadable { source } -} - fn load_operation_ids(kv: &DetKv, network: Network) -> Result, TaskError> { kv.get(DetScope::Global, &operation_index_key(network)) .map(|ids| ids.unwrap_or_default()) @@ -365,10 +278,7 @@ fn persist_operation( kv, network, newly_complete.then_some(operation.id), - operation - .targets - .iter() - .any(|outcome| matches!(outcome.target.timing, VoteTiming::Scheduled(_))), + HistoryKind::of(operation), ) { // The submitted result is durable; cleanup failure must not invite a retry. @@ -380,200 +290,6 @@ fn persist_operation( Ok(()) } -fn write_existing_operation( - kv: &DetKv, - network: Network, - operation: &DpnsVoteOperation, -) -> Result<(), TaskError> { - persist_operation(kv, network, operation) -} - -pub(super) fn prune_terminal_operations(kv: &DetKv, network: Network) -> Result { - let surviving_scheduled_votes = durable_scheduled_vote_keys(kv, network)?; - let operations = load_operations(kv, network)?; - let terminal_ids = operations - .iter() - .filter(|operation| { - operation.is_complete() - && !operation.targets.is_empty() - && operation - .targets - .iter() - .any(|outcome| matches!(outcome.target.timing, VoteTiming::Scheduled(_))) - && operation.targets.iter().all(|outcome| { - !matches!(outcome.target.timing, VoteTiming::Scheduled(_)) - || !surviving_scheduled_votes.contains(&DpnsScheduledVoteKey { - network: outcome.target.key.network, - voter_id: outcome.target.key.voter_id, - contested_name: outcome.target.contested_name.clone(), - }) - }) - }) - .map(|operation| operation.id) - .collect::>(); - let scheduled_count = delete_terminal_operations(kv, network, &terminal_ids)?; - let immediate_count = prune_immediate_history(kv, network, None)?; - prune_orphaned_schedule_dismissals(kv, network)?; - Ok(scheduled_count + immediate_count) -} - -fn prune_immediate_history( - kv: &DetKv, - network: Network, - newly_completed: Option, -) -> Result { - prune_completed_history(kv, network, newly_completed, false) -} - -fn prune_completed_history( - kv: &DetKv, - network: Network, - newly_completed: Option, - scheduled: bool, -) -> Result { - let (prefix, limit) = if scheduled { - (SCHEDULED_HISTORY_KEY_PREFIX, DPNS_SCHEDULED_HISTORY_LIMIT) - } else { - (IMMEDIATE_HISTORY_KEY_PREFIX, DPNS_IMMEDIATE_HISTORY_LIMIT) - }; - let history_key = format!("{prefix}{}", network_tag(network)); - let operations = load_operations(kv, network)?; - let mut terminal = operations - .iter() - .filter(|operation| { - operation.is_complete() - && (operation - .targets - .iter() - .any(|outcome| matches!(outcome.target.timing, VoteTiming::Scheduled(_))) - == scheduled) - }) - .collect::>(); - terminal.sort_unstable_by_key(|operation| (operation.created_at, operation.id)); - let terminal_ids = terminal - .iter() - .map(|operation| operation.id) - .collect::>(); - let previous: Vec = kv - .get(DetScope::Global, &history_key) - .map_err(unreadable_operation_err)? - .unwrap_or_default(); - 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); - if scheduled && remove_count > 0 { - let removing = ordered[..remove_count] - .iter() - .copied() - .collect::>(); - let surviving_pairs = operations - .iter() - .filter(|operation| !removing.contains(&operation.id)) - .flat_map(|operation| &operation.targets) - .filter(|outcome| matches!(outcome.target.timing, VoteTiming::Scheduled(_))) - .map(|outcome| { - ( - outcome.target.key.voter_id, - outcome.target.contested_name.as_str(), - ) - }) - .collect::>(); - // Remove mirrors before their journals so partial cleanup cannot revive a schedule. - for operation in terminal - .iter() - .filter(|operation| removing.contains(&operation.id)) - { - for outcome in &operation.targets { - let pair = ( - outcome.target.key.voter_id, - outcome.target.contested_name.as_str(), - ); - if matches!(outcome.target.timing, VoteTiming::Scheduled(_)) - && !surviving_pairs.contains(&pair) - { - delete_scheduled_vote_in(kv, &pair.0.to_buffer(), pair.1)?; - } - } - } - } - 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) -} - -/// 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. -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_tag(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::>(); - for key in kv - .list(DetScope::Global, Some(&dismissal_prefix)) - .map_err(unreadable_operation_err)? - { - if key - .strip_prefix(&dismissal_prefix) - .is_some_and(|suffix| !live_suffixes.contains(suffix)) - { - kv.delete(DetScope::Global, &key).map_err(operation_err)?; - } - } - Ok(()) -} - -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 { - 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()) -} - /// Cancel executable votes before their voter is delisted, while the caller owns the journal guard. pub(super) fn cancel_removed_identity_votes( kv: &DetKv, @@ -623,33 +339,6 @@ fn insert_diagnostic( } } -fn transition_scheduled_target_to_queued( - kv: &DetKv, - network: Network, - operation_id: DpnsVoteOperationId, - key: &DpnsVoteTargetKey, -) -> Result { - let Some(mut operation): Option = kv - .get(DetScope::Global, &operation_key(network, operation_id)) - .map_err(unreadable_operation_err)? - else { - return Ok(false); - }; - let Some(outcome) = operation - .targets - .iter_mut() - .find(|outcome| outcome.target.key == *key) - else { - return Ok(false); - }; - if outcome.status != DpnsVoteTargetStatus::Scheduled { - return Ok(false); - } - outcome.status = DpnsVoteTargetStatus::Queued; - write_existing_operation(kv, network, &operation)?; - Ok(true) -} - fn is_authorized_scheduled_replacement( existing_status: DpnsVoteTargetStatus, existing_key: &DpnsVoteTargetKey, @@ -695,41 +384,13 @@ fn replace_scheduled_operation( } *outcome = replacement; outcome.operation_id = existing.id; - write_existing_operation(kv, network, &existing)?; + persist_operation(kv, network, &existing)?; *operation = existing; return Ok(()); } Err(TaskError::DpnsVoteTargetBusy) } -fn cancel_scheduled_target( - kv: &DetKv, - network: Network, - operation_id: DpnsVoteOperationId, - key: &DpnsVoteTargetKey, -) -> Result { - let Some(mut operation): Option = kv - .get(DetScope::Global, &operation_key(network, operation_id)) - .map_err(unreadable_operation_err)? - else { - return Ok(false); - }; - let Some(outcome) = operation - .targets - .iter_mut() - .find(|outcome| outcome.target.key == *key) - else { - return Ok(false); - }; - if outcome.status != DpnsVoteTargetStatus::Scheduled { - return Ok(false); - } - outcome.status = DpnsVoteTargetStatus::Cancelled; - outcome.failure = None; - write_existing_operation(kv, network, &operation)?; - Ok(true) -} - fn operation_for_schedule_edit( kv: &DetKv, network: Network, @@ -760,64 +421,35 @@ fn operation_for_schedule_edit( Ok(operation) } -fn recover_interrupted_target_statuses(operation: &mut DpnsVoteOperation) -> bool { - let mut changed = false; - for outcome in &mut operation.targets { - 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; - } - _ => {} - } +impl AppContext { + /// Take the process-wide journal guard, recovering from a poisoned lock. + /// + /// Every read and write of the operation journal, its lock index and its + /// compatibility mirror 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) } - changed -} -fn mark_target_broadcast( - kv: &DetKv, - network: Network, - operation_id: DpnsVoteOperationId, - key: &DpnsVoteTargetKey, -) -> Result { - let Some(mut operation): Option = kv - .get(DetScope::Global, &operation_key(network, operation_id)) - .map_err(unreadable_operation_err)? - else { - return Ok(false); - }; - let Some(outcome) = operation - .targets - .iter_mut() - .find(|outcome| outcome.target.key == *key) - else { - return Ok(false); - }; - if outcome.status == DpnsVoteTargetStatus::Submitting { - outcome.status = DpnsVoteTargetStatus::Confirming; - write_existing_operation(kv, network, &operation)?; - return Ok(true); + /// 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()?)) } - Ok(false) -} -impl AppContext { /// 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 - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); + let _guard = self.journal_guard(); operation_for_schedule_edit(&self.det_kv()?, self.network, edit)? .outcome(&edit.key) .map(|outcome| outcome.target.clone()) @@ -829,11 +461,7 @@ impl AppContext { &self, edit: &DpnsScheduledVoteEdit, ) -> Result<(DpnsVoteOperationId, Option), TaskError> { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; + let (_guard, kv) = self.journal()?; let mut operation = operation_for_schedule_edit(&kv, self.network, edit)?; if edit.unix_timestamp <= std::time::UNIX_EPOCH @@ -871,10 +499,7 @@ impl AppContext { operation_id: DpnsVoteOperationId, key: &DpnsVoteTargetKey, ) -> Result { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); + let _guard = self.journal_guard(); transition_scheduled_target_to_queued(&self.det_kv()?, self.network, operation_id, key) } @@ -891,11 +516,7 @@ impl AppContext { { return Err(TaskError::DpnsVoteTargetBusy); } - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; + let (_guard, kv) = self.journal()?; if let Some(key) = replacing_scheduled_key { return replace_scheduled_operation(&kv, self.network, operation, key); } @@ -916,11 +537,7 @@ impl AppContext { { return Err(TaskError::DpnsVoteTargetBusy); } - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; + let (_guard, kv) = self.journal()?; if let Some(key) = replacing_scheduled_key { replace_scheduled_operation(&kv, self.network, operation, key)?; } else { @@ -942,20 +559,13 @@ impl AppContext { &self, operation: &DpnsVoteOperation, ) -> Result<(), TaskError> { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); + let _guard = self.journal_guard(); persist_operation(&self.det_kv()?, self.network, operation) } /// Load every operation for this network, including completed history. pub fn dpns_vote_operations(&self) -> Result, TaskError> { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; + let (_guard, kv) = self.journal()?; if kv .get::( DetScope::Global, @@ -973,11 +583,7 @@ impl AppContext { pub fn dismissed_dpns_vote_schedules( &self, ) -> Result, TaskError> { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; + 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); @@ -992,11 +598,7 @@ impl AppContext { /// Migrate legacy journals and scheduled-vote mirrors before backend recovery. pub(crate) fn migrate_dpns_vote_operations(&self) -> Result<(), TaskError> { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; + let (_guard, kv) = self.journal()?; let mut operations = load_operations(&kv, self.network)?; for legacy in self.get_scheduled_votes()? { if operations.iter().any(|operation| { @@ -1033,10 +635,7 @@ impl AppContext { &self, id: DpnsVoteOperationId, ) -> Result, TaskError> { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); + let _guard = self.journal_guard(); let operation = self .det_kv()? .get(DetScope::Global, &operation_key(self.network, id)) @@ -1063,6 +662,9 @@ impl AppContext { } /// 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, @@ -1070,35 +672,26 @@ impl AppContext { status: DpnsVoteTargetStatus, failure: Option, ) -> Result<(), TaskError> { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; - let Some(mut operation): Option = kv - .get(DetScope::Global, &operation_key(self.network, operation_id)) - .map_err(unreadable_operation_err)? - else { - return Ok(()); - }; - if let Some(outcome) = operation - .targets - .iter_mut() - .find(|outcome| outcome.target.key == *key) - { + let (_guard, kv) = self.journal()?; + with_target(&kv, self.network, operation_id, key, |outcome| { if outcome.status == DpnsVoteTargetStatus::Cancelled { - return Ok(()); + return TargetUpdate::Skip(()); } outcome.status = status; if status == DpnsVoteTargetStatus::Unconfirmed { outcome.target.current_choice = None; } outcome.failure = failure; - } - persist_operation(&kv, self.network, &operation) + 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, @@ -1107,33 +700,25 @@ impl AppContext { observed_choice: Option, status: DpnsVoteTargetStatus, ) -> Result { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; - let Some(mut operation): Option = kv - .get(DetScope::Global, &operation_key(self.network, operation_id)) - .map_err(unreadable_operation_err)? - else { - return Ok(false); - }; - let Some(outcome) = operation.targets.iter_mut().find(|outcome| { - outcome.target.key == *key - && outcome.status == DpnsVoteTargetStatus::Unconfirmed - && outcome.target.current_choice == expected_current_choice - }) else { - return Ok(false); - }; - if outcome.target.current_choice == observed_choice && outcome.status == status { - return Ok(true); - } - outcome.target.current_choice = observed_choice; - outcome.status = status; - outcome.failure = (status == DpnsVoteTargetStatus::Unconfirmed) - .then_some(DpnsVoteFailure::ResultUnconfirmed); - persist_operation(&kv, self.network, &operation)?; - Ok(true) + let (_guard, kv) = self.journal()?; + 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. @@ -1142,31 +727,18 @@ impl AppContext { operation_id: DpnsVoteOperationId, key: &DpnsVoteTargetKey, ) -> Result { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; - let Some(mut operation): Option = kv - .get(DetScope::Global, &operation_key(self.network, operation_id)) - .map_err(unreadable_operation_err)? - else { - return Ok(false); - }; - let Some(outcome) = operation - .targets - .iter_mut() - .find(|outcome| outcome.target.key == *key) - else { - return Ok(false); - }; - if outcome.status != DpnsVoteTargetStatus::Queued { - return Ok(false); - } - outcome.status = DpnsVoteTargetStatus::Submitting; - outcome.failure = None; - persist_operation(&kv, self.network, &operation)?; - Ok(true) + let (_guard, kv) = self.journal()?; + 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. @@ -1175,10 +747,7 @@ impl AppContext { operation_id: DpnsVoteOperationId, key: &DpnsVoteTargetKey, ) -> Result { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); + let _guard = self.journal_guard(); mark_target_broadcast(&self.det_kv()?, self.network, operation_id, key) } @@ -1192,59 +761,41 @@ impl AppContext { key: &DpnsVoteTargetKey, state: DpnsCurrentVoteState, ) -> Result { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; - let Some(mut operation): Option = kv - .get(DetScope::Global, &operation_key(self.network, operation_id)) - .map_err(unreadable_operation_err)? - else { - return Ok(false); - }; - let Some(outcome) = operation - .targets - .iter_mut() - .find(|outcome| outcome.target.key == *key) - else { - return Ok(false); - }; - if outcome.status != DpnsVoteTargetStatus::Queued { - return Ok(false); - } - match state { - DpnsCurrentVoteState::Available(current) => { - outcome.target.current_choice = current; - if current == Some(outcome.target.requested_choice) { - outcome.status = DpnsVoteTargetStatus::Confirmed; - outcome.failure = None; + let (_guard, kv) = self.journal()?; + Ok( + with_target(&kv, self.network, operation_id, key, |outcome| { + if outcome.status != DpnsVoteTargetStatus::Queued { + return TargetUpdate::Skip(false); } - } - DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable => { - (outcome.status, outcome.failure) = - unavailable_preflight_outcome(outcome.target.timing); - } - } - let still_queued = outcome.status == DpnsVoteTargetStatus::Queued; - persist_operation(&kv, self.network, &operation)?; - Ok(still_queued) + match state { + 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. pub(crate) fn recover_interrupted_dpns_vote_operations(&self) -> Result<(), TaskError> { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; + let (_guard, kv) = self.journal()?; for mut operation in load_operations(&kv, self.network)? { if recover_interrupted_target_statuses(&mut operation) { persist_operation(&kv, self.network, &operation)?; } } - prune_immediate_history(&kv, self.network, None)?; - prune_completed_history(&kv, self.network, None, true)?; + 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(()) } @@ -1254,11 +805,7 @@ impl AppContext { &self, operation_id: DpnsVoteOperationId, ) -> Result<(), TaskError> { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; + let (_guard, kv) = self.journal()?; let Some(mut operation): Option = kv .get(DetScope::Global, &operation_key(self.network, operation_id)) .map_err(unreadable_operation_err)? @@ -1309,10 +856,7 @@ impl AppContext { /// 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 - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); + let _guard = self.journal_guard(); prune_terminal_operations(&self.det_kv()?, self.network) } @@ -1323,11 +867,7 @@ impl AppContext { key: &DpnsVoteTargetKey, contested_name: &str, ) -> Result<(), TaskError> { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; + 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 = match expected_operation_id { @@ -1424,11 +964,7 @@ impl AppContext { pub(crate) fn clear_all_scheduled_dpns_votes( &self, ) -> Result, TaskError> { - let _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; + let (_guard, kv) = self.journal()?; let mut retained = BTreeSet::new(); let mut outcomes = BTreeMap::< DpnsScheduledVoteKey, @@ -1494,7 +1030,7 @@ impl AppContext { } } if changed { - write_existing_operation(&kv, self.network, &operation)?; + persist_operation(&kv, self.network, &operation)?; } } @@ -2452,7 +1988,7 @@ mod tests { } #[test] - fn additional_scenarios_retention_read_failure_keeps_durable_insert_successful() { + fn retention_read_failure_keeps_durable_insert_successful() { let dir = tempfile::tempdir().unwrap(); let store = Arc::new(FailingKv::default()); let kv = DetKv::from_store(store.clone()); @@ -2482,7 +2018,7 @@ mod tests { } #[test] - fn additional_scenarios_scheduled_and_mixed_history_is_bounded_with_mirrors() { + fn scheduled_and_mixed_history_is_bounded_with_mirrors() { let dir = tempfile::tempdir().unwrap(); let context = crate::context::test_support::test_app_context_with_kv(dir.path(), Arc::new(kv())); @@ -2545,7 +2081,7 @@ mod tests { } #[test] - fn additional_scenarios_scheduled_retention_cleanup_failures_retry_safely() { + fn scheduled_retention_cleanup_failures_retry_safely() { for failing_key in [ "det:scheduled_vote:", OPERATION_KEY_PREFIX, @@ -2637,7 +2173,7 @@ mod tests { } #[test] - fn additional_scenarios_retention_preserves_a_newer_schedules_mirror() { + fn retention_preserves_a_newer_schedules_mirror() { let dir = tempfile::tempdir().unwrap(); let kv = kv(); let context = crate::context::test_support::test_app_context_with_kv( @@ -2731,7 +2267,7 @@ mod tests { .unwrap() .is_some() ); - prune_immediate_history(&kv, Network::Testnet, None).unwrap(); + 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)); @@ -2894,7 +2430,7 @@ mod tests { persist_operation(&kv, Network::Testnet, &newest).unwrap(); assert_eq!(load_operations(&kv, Network::Testnet).unwrap().len(), 258); assert_eq!( - prune_immediate_history(&kv, Network::Testnet, None).unwrap(), + prune_completed_history(&kv, Network::Testnet, None, HistoryKind::Immediate).unwrap(), 1 ); let remaining = load_operations(&kv, Network::Testnet).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..fac35951a --- /dev/null +++ b/src/context/dpns_vote_operations/retention.rs @@ -0,0 +1,256 @@ +//! Retention for completed vote batches and their dismissal sidecars. +//! +//! 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::context::identity_db::{delete_scheduled_vote_in, durable_scheduled_vote_keys}; +use crate::model::dpns_voting::{ + DpnsScheduledVoteKey, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, + DpnsVoteTargetStatus, VoteTiming, +}; +use crate::wallet_backend::{DetKv, DetScope}; +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; + +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 before clearing their mirrors, 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. +/// +/// Scheduled batches are capped separately because retiring one must also drop +/// the compatibility mirror rows that back it. +#[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 surviving_scheduled_votes = durable_scheduled_vote_keys(kv, network)?; + let operations = load_operations(kv, network)?; + let terminal_ids = operations + .iter() + .filter(|operation| { + operation.is_complete() + && !operation.targets.is_empty() + && operation + .targets + .iter() + .any(|outcome| matches!(outcome.target.timing, VoteTiming::Scheduled(_))) + && operation.targets.iter().all(|outcome| { + !matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + || !surviving_scheduled_votes.contains(&DpnsScheduledVoteKey { + network: outcome.target.key.network, + voter_id: outcome.target.key.voter_id, + contested_name: outcome.target.contested_name.clone(), + }) + }) + }) + .map(|operation| operation.id) + .collect::>(); + let scheduled_count = delete_terminal_operations(kv, network, &terminal_ids)?; + 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_tag(network)); + 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 previous: Vec = kv + .get(DetScope::Global, &history_key) + .map_err(unreadable_operation_err)? + .unwrap_or_default(); + 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); + if kind == HistoryKind::Scheduled && remove_count > 0 { + let removing = ordered[..remove_count] + .iter() + .copied() + .collect::>(); + let surviving_pairs = operations + .iter() + .filter(|operation| !removing.contains(&operation.id)) + .flat_map(|operation| &operation.targets) + .filter(|outcome| matches!(outcome.target.timing, VoteTiming::Scheduled(_))) + .map(|outcome| { + ( + outcome.target.key.voter_id, + outcome.target.contested_name.as_str(), + ) + }) + .collect::>(); + // Remove mirrors before their journals so partial cleanup cannot revive a schedule. + for operation in terminal + .iter() + .filter(|operation| removing.contains(&operation.id)) + { + for outcome in &operation.targets { + let pair = ( + outcome.target.key.voter_id, + outcome.target.contested_name.as_str(), + ); + if matches!(outcome.target.timing, VoteTiming::Scheduled(_)) + && !surviving_pairs.contains(&pair) + { + delete_scheduled_vote_in(kv, &pair.0.to_buffer(), pair.1)?; + } + } + } + } + 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) +} + +/// 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_tag(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::>(); + for key in kv + .list(DetScope::Global, Some(&dismissal_prefix)) + .map_err(unreadable_operation_err)? + { + if key + .strip_prefix(&dismissal_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 { + 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..68813252a --- /dev/null +++ b/src/context/dpns_vote_operations/transitions.rs @@ -0,0 +1,127 @@ +//! 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::persist_operation; +use crate::backend_task::error::TaskError; +use crate::model::dpns_voting::{ + DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTargetKey, + DpnsVoteTargetStatus, failed_before_broadcast_outcome, +}; +use crate::wallet_backend::{DetKv, DetScope}; +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 = kv + .get(DetScope::Global, &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) -> bool { + let mut changed = false; + for outcome in &mut operation.targets { + 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 +} + +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/model/dpns_voting.rs b/src/model/dpns_voting.rs index d65d33526..e794aaec9 100644 --- a/src/model/dpns_voting.rs +++ b/src/model/dpns_voting.rs @@ -14,7 +14,7 @@ mod tests { use dash_sdk::platform::Identifier; #[test] - fn additional_scenarios_automatic_window_boundary_and_overflow() { + 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)); @@ -180,6 +180,42 @@ pub enum DpnsCurrentVoteState { 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 is decided or its deadline has passed. + ProvedClosed, +} + +/// Classify a poll from its cached contest, if DET has one. +/// +/// `now_ms` is the current wall clock in Unix milliseconds, matched against the +/// contest deadline. Returns [`DpnsVotePollAvailability::MayAccept`] for a +/// contest DET has never cached. +pub fn dpns_vote_poll_availability( + contest: Option<&crate::model::contested_name::ContestedName>, + now_ms: u64, +) -> DpnsVotePollAvailability { + let Some(contest) = contest else { + return DpnsVotePollAvailability::MayAccept; + }; + let decided = !contest.is_votable(); + let expired = contest.end_time.is_some_and(|end| end <= now_ms); + if decided || expired { + 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]); From 6df93f3bb81d7e9536f7b6271922f17f684d96ce Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 14 Sep 2026 15:00:31 +0000 Subject: [PATCH 053/194] fix(dpns): unify the authoritative-operation rule across the vote journal Re-applies the authoritative-operation unification onto the journal's split module layout, landing each piece in the module that now owns the concern: key builders in keys.rs, the retention cap and its new prune fast path in retention.rs, the rank call sites in the journal facade. "Which operation currently speaks for this target" was written four times with three different tie-break rules. The node-card summary (scheduled_vote_journal_summary) omitted the (created_at, operation_id) tie-break the other three apply, so two operations stamped inside the same millisecond -- routine when a bulk review commits -- made it disagree with the Scheduled Votes screen about which operation is authoritative, with the winner decided by journal iteration order. model/dpns_voting.rs now owns the rule as dpns_vote_authority_rank ("lock holder first, then newest by (created_at, id)") plus authoritative_dpns_vote_outcome and dpns_vote_lock_holders built on it. All four sites call it: preferred_outcome_for_scheduled_key, remove_scheduled_dpns_vote, clear_all_scheduled_dpns_votes and scheduled_vote_journal_summary. The summary now also lets a lock holder outrank a newer terminal record, matching the other three. Covered by a test that seeds two same-millisecond operations and asserts all four sites name the same one. Also in this change: - Vote polls are built in one place. dpns_vote_poll() now backs both dpns_vote_poll_id and checked_dpns_vote_poll, so the poll DET locks and journals cannot drift from the poll it votes on. - Proved vote-state queries moved out of context/ into backend_task/contested_names/refresh_vote_states.rs; no context/ module performs SDK network I/O any more. - One network_prefix (the documented wallet-backend storage token, byte identical to the journal's former private network_tag) and one now_ms() (new utils::time) replace a duplicated network match and every spelling of "now in millis", including the one the reconciliation verdict added. - Superseded current-vote keys are named in LEGACY_CURRENT_VOTES_KEY_PREFIXES instead of being manufactured by string-replacing the version segment. - MAX_CONCURRENT_DPNS_VOTERS is the single per-voter concurrency bound. - Masternode-card summaries read node-independent state once for the whole fleet via masternode_contest_summaries. - Completing writes no longer rescan the whole journal: prune_completed_history records completion order and defers reconciliation and eviction until the retention cap is exceeded by DPNS_HISTORY_PRUNE_SLACK. Recovery still reconciles unconditionally. Co-Authored-By: Claude Sonnet 5 --- .../contested_names/edit_scheduled_vote.rs | 6 +- src/backend_task/contested_names/mod.rs | 154 +++++------- .../contested_names/refresh_vote_states.rs | 82 +++++++ .../contested_names/vote_on_dpns_name.rs | 68 +----- src/context/contested_names_db.rs | 226 ++++++++++++------ src/context/dpns_vote_operations/keys.rs | 26 +- src/context/dpns_vote_operations/mod.rs | 139 ++++++++--- src/context/dpns_vote_operations/retention.rs | 40 +++- src/context/dpns_vote_state.rs | 174 +++----------- src/context/mod.rs | 6 +- src/model/dpns_voting.rs | 136 ++++++++++- src/utils/mod.rs | 1 + src/utils/time.rs | 15 ++ 13 files changed, 649 insertions(+), 424 deletions(-) create mode 100644 src/backend_task/contested_names/refresh_vote_states.rs create mode 100644 src/utils/time.rs diff --git a/src/backend_task/contested_names/edit_scheduled_vote.rs b/src/backend_task/contested_names/edit_scheduled_vote.rs index 94f541c20..dddf26c15 100644 --- a/src/backend_task/contested_names/edit_scheduled_vote.rs +++ b/src/backend_task/contested_names/edit_scheduled_vote.rs @@ -6,6 +6,7 @@ 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 { @@ -45,10 +46,7 @@ impl AppContext { .ok_or_else(|| TaskError::VotePollNotFound { name: target.contested_name.clone(), })?; - let now_ms = std::time::UNIX_EPOCH - .elapsed() - .unwrap_or_default() - .as_millis() as u64; + 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, diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 8920a4444..9f64665dc 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -2,21 +2,24 @@ 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::{DapiAddressAvailability, TaskError}; -use crate::context::AppContext; +use crate::context::{AppContext, MAX_CONCURRENT_DPNS_VOTERS}; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduleEditValidationError, DpnsVoteFailure, DpnsVoteOperation, - DpnsVoteOperationId, DpnsVotePollAvailability, DpnsVoteTarget, DpnsVoteTargetKey, - DpnsVoteTargetStatus, VoteTiming, dpns_schedule_is_overdue, dpns_vote_poll_availability, + 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; @@ -29,7 +32,6 @@ use dash_sdk::platform::{FetchMany, Identifier}; use futures::{StreamExt, stream}; use std::collections::BTreeMap; use std::sync::Arc; -use std::time::{SystemTime, UNIX_EPOCH}; #[cfg(test)] use crate::model::dpns_voting::SCHEDULED_VOTE_MAX_LATENESS_MS; @@ -353,37 +355,32 @@ impl AppContext { vote_poll_id: self.dpns_vote_poll_id(&scheduled_vote.contested_name)?, }; let operations = self.dpns_vote_operations()?; - if let Some(operation) = preferred_operation_for_scheduled_key(&operations, &key)?.cloned() - { - for outcome in &operation.targets { - if outcome.target.key != key { - continue; - } - match outcome.status { - DpnsVoteTargetStatus::Scheduled => { - if !self - .queue_scheduled_dpns_vote_target(operation.id, &outcome.target.key)? - { - return Err(TaskError::DpnsVoteTargetBusy); - } - return self - .dpns_vote_operation(operation.id)? - .ok_or(TaskError::DpnsVoteOperationRecordMissing); - } - DpnsVoteTargetStatus::Unconfirmed - | DpnsVoteTargetStatus::Queued - | DpnsVoteTargetStatus::Submitting - | DpnsVoteTargetStatus::Confirming => { + if let Some(outcome) = preferred_outcome_for_scheduled_key(&operations, &key)?.cloned() { + match outcome.status { + DpnsVoteTargetStatus::Scheduled => { + if !self.queue_scheduled_dpns_vote_target( + outcome.operation_id, + &outcome.target.key, + )? { 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. - } + return self + .dpns_vote_operation(outcome.operation_id)? + .ok_or(TaskError::DpnsVoteOperationRecordMissing); + } + 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. } } } @@ -452,7 +449,7 @@ impl AppContext { if targets.is_empty() { return Ok(()); } - let now_ms = UNIX_EPOCH.elapsed().unwrap_or_default().as_millis() as u64; + 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 { @@ -642,7 +639,6 @@ impl AppContext { .push(outcome.target.clone()); } - const MAX_CONCURRENT_VOTERS: usize = 4; stream::iter(groups) .map(|(voter_id, targets)| { let app_context = Arc::clone(self); @@ -809,7 +805,7 @@ impl AppContext { Ok(()) } }) - .buffer_unordered(MAX_CONCURRENT_VOTERS) + .buffer_unordered(MAX_CONCURRENT_DPNS_VOTERS) .collect::>>() .await .into_iter() @@ -878,7 +874,7 @@ impl AppContext { .into_iter() .map(|contest| (contest.normalized_contested_name.clone(), contest)) .collect::>(); - let now_ms = UNIX_EPOCH.elapsed().unwrap_or_default().as_millis() as u64; + let now_ms = now_ms(); for outcome in operation .targets .iter() @@ -1034,33 +1030,25 @@ impl AppContext { preserve_eligibility_since_ms: Option, ) -> Result { let (due_operations, in_progress) = self - .prepare_due_scheduled_votes( - || { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_millis() as u64) - .unwrap_or(0) - }, - preserve_eligibility_since_ms, - async { - for operation in - self.dpns_vote_operations()? - .into_iter() - .filter(|operation| { - operation.targets.iter().any(|outcome| { - outcome.status == DpnsVoteTargetStatus::Unconfirmed - }) - }) - { - let result = self - .reconcile_dpns_vote_operation(operation.id, sdk) - .await?; - let _ = sender.send(TaskResult::unattributed_success(result)).await; - } + .prepare_due_scheduled_votes(now_ms, preserve_eligibility_since_ms, async { + for operation in self + .dpns_vote_operations()? + .into_iter() + .filter(|operation| { + operation + .targets + .iter() + .any(|outcome| outcome.status == DpnsVoteTargetStatus::Unconfirmed) + }) + { + let result = self + .reconcile_dpns_vote_operation(operation.id, sdk) + .await?; + let _ = sender.send(TaskResult::unattributed_success(result)).await; + } - Ok(()) - }, - ) + Ok(()) + }) .await?; if due_operations.is_empty() { return Ok(BackendTaskSuccessResult::ScheduledVoteSweepCompleted { @@ -1091,7 +1079,7 @@ impl AppContext { (operation_id, result) } }) - .buffer_unordered(4) + .buffer_unordered(MAX_CONCURRENT_DPNS_VOTERS) .collect::>() .await; let mut first_error = None; @@ -1116,29 +1104,15 @@ impl AppContext { } } -fn preferred_operation_for_scheduled_key<'a>( +/// 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: &DpnsVoteTargetKey, -) -> Result, TaskError> { - let mut lock_holders = operations.iter().filter(|operation| { - operation - .outcome(key) - .is_some_and(|outcome| outcome.status.holds_lock()) - }); - let lock_holder = lock_holders.next(); - if lock_holders.next().is_some() { + key: &'a DpnsVoteTargetKey, +) -> Result, TaskError> { + if dpns_vote_lock_holders(operations, key).nth(1).is_some() { return Err(TaskError::DpnsVoteTargetBusy); } - Ok(lock_holder.or_else(|| { - operations - .iter() - .filter(|operation| { - operation - .outcome(key) - .is_some_and(|outcome| !outcome.status.holds_lock()) - }) - .max_by_key(|operation| (operation.created_at, operation.id)) - })) + Ok(authoritative_dpns_vote_outcome(operations, key)) } fn scheduled_vote_is_due( @@ -1525,7 +1499,7 @@ mod tests { #[tokio::test] async fn new_schedule_validates_known_deadline_and_unknown_deadline_policy() { - let now = UNIX_EPOCH.elapsed().unwrap().as_millis() as u64; + let now = now_ms(); let end = now + 120_000; for (timestamp, deadline, expected_valid) in [ (end - 1, Some(end), true), @@ -1554,7 +1528,7 @@ mod tests { #[tokio::test] async fn new_schedule_rejects_mixed_deadlines_atomically_and_missing_or_closed_contests() { - let now = UNIX_EPOCH.elapsed().unwrap().as_millis() as u64; + 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); @@ -1687,19 +1661,19 @@ mod tests { let operations = vec![older.clone(), lock_holder.clone(), newer.clone()]; assert_eq!( - preferred_operation_for_scheduled_key(&operations, &key) + preferred_outcome_for_scheduled_key(&operations, &key) .unwrap() .unwrap() - .id, + .operation_id, lock_holder.id ); let terminal_operations = vec![older, newer.clone()]; assert_eq!( - preferred_operation_for_scheduled_key(&terminal_operations, &key) + preferred_outcome_for_scheduled_key(&terminal_operations, &key) .unwrap() .unwrap() - .id, + .operation_id, newer.id ); } 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..d175f7a85 --- /dev/null +++ b/src/backend_task/contested_names/refresh_vote_states.rs @@ -0,0 +1,82 @@ +//! 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; +use std::sync::Arc; + +const VOTE_QUERY_PAGE_SIZE: u16 = 100; + +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()?; + let kv = self.det_kv()?; + + Ok(stream::iter(voters) + .map(|voter| { + let sdk = sdk.clone(); + let kv = kv.clone(); + async move { + let voter_id = voter.identity.id(); + let result = self.publish_dpns_vote_state( + &kv, voter_id, fetch_votes_for_voter(&sdk, voter_id), + ).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 dd3cc1aa1..7b07f8c09 100644 --- a/src/backend_task/contested_names/vote_on_dpns_name.rs +++ b/src/backend_task/contested_names/vote_on_dpns_name.rs @@ -1,12 +1,10 @@ use crate::backend_task::error::TaskError; use crate::context::AppContext; -use crate::model::dpns_voting::{DpnsVoteOperationId, DpnsVoteTargetKey}; +use crate::model::dpns_voting::{DpnsVoteOperationId, DpnsVoteTargetKey, dpns_vote_poll}; use crate::model::qualified_identity::QualifiedIdentity; use dash_sdk::Sdk; use dash_sdk::dpp::consensus::ConsensusError; use dash_sdk::dpp::consensus::basic::BasicError; -use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; -use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; use dash_sdk::dpp::identifier::MasternodeIdentifiers; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::identity::hash::IdentityPublicKeyHashMethodsV0; @@ -39,17 +37,6 @@ pub(super) enum DpnsVoteAttempt { FailedBeforeSubmission(TaskError), } -/// 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()), - ] -} - fn ensure_valid_vote_transition_structure( state_transition: &StateTransition, sdk: &Sdk, @@ -133,33 +120,15 @@ impl AppContext { name: &str, sdk: &Sdk, ) -> Result { - 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", - }); - }; - + 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 @@ -250,33 +219,6 @@ impl AppContext { 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"; - - // 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())); - } - #[test] fn convert_to_homograph_safe_chars_maps_alice_to_a11ce() { // Given: the canonical DPNS homograph substitutions (i/l β†’ 1, o β†’ 0). diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index ae10be90c..f156bc43b 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -14,9 +14,10 @@ use crate::model::contested_name::{ }; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, - DpnsVoteTargetStatus, VoteTiming, + DpnsVoteTargetStatus, VoteTiming, dpns_vote_authority_rank, }; 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; @@ -45,7 +46,7 @@ fn scheduled_vote_journal_summary( voter_id: Identifier, dismissed: &BTreeSet<(DpnsVoteOperationId, DpnsVoteTargetKey)>, ) -> (bool, bool) { - let latest_by_target = operations + let authoritative_by_target = operations .iter() .flat_map(|operation| { operation @@ -57,20 +58,25 @@ fn scheduled_vote_journal_summary( outcome.target.key.voter_id == voter_id && matches!(outcome.target.timing, VoteTiming::Scheduled(_)) }) - .fold(BTreeMap::new(), |mut latest, (created_at, outcome)| { - let entry = latest - .entry(&outcome.target.key) - .or_insert((created_at, outcome)); - if created_at >= entry.0 { - *entry = (created_at, outcome); - } - latest - }); + .fold( + BTreeMap::new(), + |mut authoritative, (created_at, outcome)| { + let rank = + dpns_vote_authority_rank(created_at, outcome.operation_id, outcome.status); + let entry = authoritative + .entry(&outcome.target.key) + .or_insert((rank, outcome)); + if rank >= entry.0 { + *entry = (rank, outcome); + } + authoritative + }, + ); - let pending = latest_by_target + let pending = authoritative_by_target .values() .any(|(_, outcome)| outcome.status.holds_lock()); - let failed = latest_by_target.values().any(|(_, outcome)| { + let failed = authoritative_by_target.values().any(|(_, outcome)| { matches!( outcome.status, DpnsVoteTargetStatus::Rejected | DpnsVoteTargetStatus::FailedBeforeSubmission @@ -147,13 +153,7 @@ 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), - ); + let elapsed = Duration::from_millis(now_ms().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 { @@ -224,10 +224,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)) @@ -270,10 +267,7 @@ impl AppContext { &self, identity_id: &Identifier, ) -> std::result::Result, TaskError> { - let now_ms = std::time::UNIX_EPOCH - .elapsed() - .unwrap_or_default() - .as_millis() as u64; + let now_ms = now_ms(); Ok(self .pending_dpns_usernames .read() @@ -291,10 +285,7 @@ impl AppContext { &self, identity_ids: &[Identifier], ) -> std::result::Result, TaskError> { - let now_ms = std::time::UNIX_EPOCH - .elapsed() - .unwrap_or_default() - .as_millis() as u64; + let now_ms = now_ms(); let pending = self .pending_dpns_usernames .read() @@ -347,7 +338,7 @@ impl AppContext { end_time: Option, closed: bool, ) { - let now = std::time::UNIX_EPOCH.elapsed().unwrap().as_millis() as u64; + let now = now_ms(); let stored = StoredContestedName { normalized_contested_name: name.into(), end_time, @@ -385,6 +376,29 @@ 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()) + } + + /// 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 contests = self.ongoing_contested_names()?; let open_polls: Vec> = contests @@ -396,46 +410,48 @@ impl AppContext { }) .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()?; - // 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 = { - let poll_ids: Vec = open_polls.iter().flatten().copied().collect(); - if poll_ids.is_empty() { - BTreeMap::new() - } else { - self.dpns_current_vote_states(voter_id, poll_ids) - .unwrap_or_default() - } - }; - let states = open_polls + Ok(voter_ids .iter() - .map(|poll| { - poll.and_then(|poll_id| poll_states.get(&poll_id).copied()) - .unwrap_or(DpnsCurrentVoteState::Unavailable) + .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::>(); - let needs_vote_count = states - .iter() - .filter(|state| **state == DpnsCurrentVoteState::Available(None)) - .count(); - let vote_state = vote_state_summary(&states); - - let (has_scheduled_vote, has_failed_scheduled_vote) = scheduled_vote_journal_summary( - &self.dpns_vote_operations()?, - voter_id, - &self.dismissed_dpns_vote_schedules()?, - ); - - Ok(crate::model::contested_name::MasternodeContestSummary { - open_contest_count, - needs_vote_count, - vote_state, - has_scheduled_vote, - has_failed_scheduled_vote, - }) + .collect()) } /// Apply a batch of newly-seen normalized names. New names are stored @@ -1000,13 +1016,15 @@ mod tests { ); } - /// Counts reads of the per-node current-vote snapshot key so a test can - /// prove how many snapshot loads a caller performs. The `v2:` prefix is - /// the active snapshot key (`current_votes_key`), one per node. + /// 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 { @@ -1014,6 +1032,11 @@ mod tests { 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) } @@ -1084,6 +1107,63 @@ mod tests { ); } + /// 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 = + DpnsVoteOperation::new(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() + ); + } + // ---------------------------------------------------------------- // Bridge: a stored contest decodes into a detectable pending username. // ---------------------------------------------------------------- diff --git a/src/context/dpns_vote_operations/keys.rs b/src/context/dpns_vote_operations/keys.rs index 2f83ad3a5..ffd4dbc0a 100644 --- a/src/context/dpns_vote_operations/keys.rs +++ b/src/context/dpns_vote_operations/keys.rs @@ -5,7 +5,7 @@ use crate::backend_task::error::TaskError; use crate::model::dpns_voting::DpnsVoteOperationId; -use crate::wallet_backend::KvAdapterError; +use crate::wallet_backend::{KvAdapterError, network_prefix}; use dash_sdk::dpp::dashcore::Network; pub(super) const LEGACY_OPERATION_INDEX_KEY: &str = "det:dpns_vote_operations:v1"; @@ -20,42 +20,36 @@ pub(super) const SCHEDULE_DISMISSAL_KEY_PREFIX: &str = "det:dpns_vote_schedule_d 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 network_tag(network: Network) -> &'static str { - match network { - Network::Mainnet => "mainnet", - Network::Testnet => "testnet", - Network::Devnet => "devnet", - Network::Regtest => "regtest", - } -} - pub(super) fn operation_index_key(network: Network) -> String { - format!("{OPERATION_INDEX_KEY_PREFIX}{}", network_tag(network)) + format!("{OPERATION_INDEX_KEY_PREFIX}{}", network_prefix(network)) } pub(super) fn operation_key(network: Network, id: DpnsVoteOperationId) -> String { - format!("{OPERATION_KEY_PREFIX}{}:{id}", network_tag(network)) + format!("{OPERATION_KEY_PREFIX}{}:{id}", network_prefix(network)) } pub(super) fn operation_key_prefix(network: Network) -> String { - format!("{OPERATION_KEY_PREFIX}{}:", network_tag(network)) + 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_tag(network) + network_prefix(network) ) } pub(super) fn operation_lock_index_key(network: Network) -> String { - format!("{OPERATION_LOCK_INDEX_KEY_PREFIX}{}", network_tag(network)) + 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_tag(network) + network_prefix(network) ) } diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index f88c60c96..aa6286aae 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -18,10 +18,12 @@ use crate::context::identity_db::{ }; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome, - DpnsScheduledVoteEdit, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, - DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + DpnsScheduledVoteEdit, DpnsScheduledVoteKey, DpnsVoteAuthorityRank, DpnsVoteFailure, + DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, + DpnsVoteTargetStatus, VoteTiming, authoritative_dpns_vote_outcome, dpns_vote_authority_rank, 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; @@ -463,12 +465,7 @@ impl AppContext { ) -> Result<(DpnsVoteOperationId, Option), TaskError> { let (_guard, kv) = self.journal()?; let mut operation = operation_for_schedule_edit(&kv, self.network, edit)?; - if edit.unix_timestamp - <= std::time::UNIX_EPOCH - .elapsed() - .unwrap_or_default() - .as_millis() as u64 - { + if edit.unix_timestamp <= now_ms() { return Err(TaskError::DpnsScheduledVoteInvalidTime); } let outcome = operation @@ -883,16 +880,8 @@ impl AppContext { if lock_index.contains_key(key) { return Err(TaskError::DpnsScheduledVoteAlreadyStarted); } - operations - .iter() - .filter_map(|operation| { - operation - .outcome(key) - .filter(|outcome| !outcome.status.holds_lock()) - .map(|outcome| (operation.created_at, operation.id, outcome.status)) - }) - .max_by_key(|(created_at, operation_id, _)| (*created_at, *operation_id)) - .map(|(_, operation_id, status)| (operation_id, status)) + authoritative_dpns_vote_outcome(&operations, key) + .map(|outcome| (outcome.operation_id, outcome.status)) } }; @@ -968,10 +957,7 @@ impl AppContext { let mut retained = BTreeSet::new(); let mut outcomes = BTreeMap::< DpnsScheduledVoteKey, - ( - Option<(bool, u64, DpnsVoteOperationId)>, - DpnsScheduledVoteClearOutcome, - ), + (Option, DpnsScheduledVoteClearOutcome), >::new(); for mut operation in load_operations(&kv, self.network)? { @@ -1011,7 +997,7 @@ impl AppContext { DpnsScheduledVoteClearDisposition::Cleared } }; - let rank = (status.holds_lock(), operation.created_at, operation.id); + let rank = dpns_vote_authority_rank(operation.created_at, operation.id, status); let should_replace = outcomes .get(&key) .is_none_or(|(existing_rank, _)| existing_rank.is_none_or(|old| rank > old)); @@ -1189,6 +1175,88 @@ mod tests { } } + /// 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(None, &key, "alice") + .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" + ); + } + /// VOTE-TC-040/041: one unresolved target cannot be inserted twice. #[test] fn unresolved_target_rejects_a_competing_operation() { @@ -2024,7 +2092,9 @@ mod tests { 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; - for index in 0..258 { + // 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, @@ -2096,7 +2166,9 @@ mod tests { ); context.set_det_kv_override_for_test(kv.clone()); let mut oldest = None; - for index in 0..256 { + // Fill the history to the prune threshold so the `newest` write below + // is the one that prunes, and meets the injected cleanup failure. + for index in 0..(DPNS_SCHEDULED_HISTORY_LIMIT + DPNS_HISTORY_PRUNE_SLACK) as u64 { let mut completed = scheduled_operation( DpnsVoteTargetStatus::Confirmed, 2, @@ -2200,7 +2272,7 @@ mod tests { std::slice::from_ref(¤t_mirror), ) .unwrap(); - for index in 1..=256 { + for index in 1..=(DPNS_SCHEDULED_HISTORY_LIMIT + DPNS_HISTORY_PRUNE_SLACK) as u64 { let mut completed = scheduled_operation( DpnsVoteTargetStatus::Confirmed, 3, @@ -2418,7 +2490,10 @@ mod tests { fn immediate_history_delete_failure_is_retried_without_losing_unresolved_locks() { let store = Arc::new(FailingKv::default()); let kv = DetKv::from_store(store.clone()); - for created_at in 0..256 { + // 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(); @@ -2428,13 +2503,17 @@ mod tests { 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(), 258); + 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(), - 1 + DPNS_HISTORY_PRUNE_SLACK + 1 ); let remaining = load_operations(&kv, Network::Testnet).unwrap(); - assert_eq!(remaining.len(), 257); + 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) diff --git a/src/context/dpns_vote_operations/retention.rs b/src/context/dpns_vote_operations/retention.rs index fac35951a..3aef4cdca 100644 --- a/src/context/dpns_vote_operations/retention.rs +++ b/src/context/dpns_vote_operations/retention.rs @@ -11,13 +11,20 @@ use crate::model::dpns_voting::{ DpnsScheduledVoteKey, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, }; -use crate::wallet_backend::{DetKv, DetScope}; +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, @@ -121,7 +128,27 @@ pub(super) fn prune_completed_history( kind: HistoryKind, ) -> Result { let (prefix, limit) = kind.key_prefix_and_limit(); - let history_key = format!("{prefix}{}", network_tag(network)); + 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() @@ -132,10 +159,6 @@ pub(super) fn prune_completed_history( .iter() .map(|operation| operation.id) .collect::>(); - let previous: Vec = kv - .get(DetScope::Global, &history_key) - .map_err(unreadable_operation_err)? - .unwrap_or_default(); let mut ordered = terminal .iter() .map(|operation| operation.id) @@ -210,7 +233,10 @@ pub(super) fn prune_orphaned_schedule_dismissals( network: Network, ) -> Result<(), TaskError> { let operation_prefix = operation_key_prefix(network); - let dismissal_prefix = format!("{SCHEDULE_DISMISSAL_KEY_PREFIX}{}:", network_tag(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)? diff --git a/src/context/dpns_vote_state.rs b/src/context/dpns_vote_state.rs index dd44c904c..42dc07361 100644 --- a/src/context/dpns_vote_state.rs +++ b/src/context/dpns_vote_state.rs @@ -2,33 +2,25 @@ use super::AppContext; use crate::backend_task::error::TaskError; -use crate::model::dpns_voting::DpnsCurrentVoteState; -use crate::wallet_backend::{DetKv, DetScope, KvAdapterError}; -use dash_sdk::Sdk; +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::data_contract::accessors::v0::DataContractV0Getters; -use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; -use dash_sdk::dpp::identity::accessors::IdentityGettersV0; -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::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 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}; -use std::time::{SystemTime, UNIX_EPOCH}; +/// v1 predates network qualification, so it is one key rather than a prefix. const LEGACY_CURRENT_VOTES_KEY: &str = "det:dpns_current_votes:v1"; const CURRENT_VOTES_KEY_PREFIX: &str = "det:dpns_current_votes:v3:"; -const VOTE_QUERY_PAGE_SIZE: u16 = 100; +/// Superseded per-network prefixes, deleted on the first read that misses. +/// Bumping [`CURRENT_VOTES_KEY_PREFIX`] means adding the retired value here. +const LEGACY_CURRENT_VOTES_KEY_PREFIXES: [&str; 1] = ["det:dpns_current_votes:v2:"]; const CURRENT_VOTE_MAX_AGE_MS: u64 = 120_000; #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -115,13 +107,7 @@ fn vote_state_err(source: KvAdapterError) -> TaskError { } fn current_votes_key(network: Network) -> String { - let network = match network { - Network::Mainnet => "mainnet", - Network::Testnet => "testnet", - Network::Devnet => "devnet", - Network::Regtest => "regtest", - }; - format!("{CURRENT_VOTES_KEY_PREFIX}{network}") + format!("{CURRENT_VOTES_KEY_PREFIX}{}", network_prefix(network)) } fn load_snapshot( @@ -136,11 +122,13 @@ fn load_snapshot( { return Ok(Some(snapshot)); } - // Cached v1/v2 values have no independent per-poll freshness and must be re-proved. + // Superseded values have no independent per-poll freshness and must be re-proved. kv.delete(scope, LEGACY_CURRENT_VOTES_KEY) .map_err(vote_state_err)?; - let previous_key = current_votes_key(network).replace(":v3:", ":v2:"); - kv.delete(scope, &previous_key).map_err(vote_state_err)?; + for prefix in LEGACY_CURRENT_VOTES_KEY_PREFIXES { + kv.delete(scope, &format!("{prefix}{}", network_prefix(network))) + .map_err(vote_state_err)?; + } Ok(None) } @@ -226,7 +214,7 @@ impl AppContext { &self, voter_id: Identifier, ) -> Result<(), TaskError> { - self.refresh_dpns_vote_state_with( + self.publish_dpns_vote_state( &self.det_kv()?, voter_id, std::future::ready(Err(Box::new(dash_sdk::Error::InvalidProvedResponse( @@ -243,12 +231,14 @@ impl AppContext { voter_id: Identifier, votes: BTreeMap<[u8; 32], ResourceVoteChoice>, ) -> Result<(), TaskError> { - self.refresh_dpns_vote_state_with(&self.det_kv()?, voter_id, async { Ok(votes) }) + self.publish_dpns_vote_state(&self.det_kv()?, voter_id, async { Ok(votes) }) .await .map(|_| ()) } - async fn refresh_dpns_vote_state_with( + /// 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, @@ -309,28 +299,13 @@ impl AppContext { }) } - /// Build the exact Platform vote-poll ID for one normalized DPNS label. + /// Build the exact Platform vote-poll ID for one DPNS label. pub fn dpns_vote_poll_id(&self, name: &str) -> Result { - let document_type = self - .dpns_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", - }); - }; - let normalized_name = convert_to_homograph_safe_chars(name); - ContestedDocumentResourceVotePoll { - index_name: contested_index.name.clone(), - index_values: vec![Value::from("dash"), Value::Text(normalized_name)], - document_type_name: document_type.name().to_owned(), - contract_id: self.dpns_contract.id(), - } - .unique_id() - .map_err(|source| TaskError::SdkError { - source_error: Box::new(dash_sdk::Error::Protocol(source)), - }) + 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 without performing network I/O in the frame loop. @@ -366,34 +341,6 @@ impl AppContext { .collect()) } - /// 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()?; - let kv = self.det_kv()?; - - Ok(stream::iter(voters) - .map(|voter| { - let sdk = sdk.clone(); - let kv = kv.clone(); - async move { - let voter_id = voter.identity.id(); - let result = self.refresh_dpns_vote_state_with( - &kv, voter_id, fetch_votes_for_voter(&sdk, voter_id), - ).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(4) - .collect::>() - .await) - } - /// Update the proved-state cache after a confirmed target. pub(crate) fn cache_confirmed_dpns_vote( &self, @@ -435,49 +382,6 @@ impl AppContext { } } -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) -} - -fn now_ms() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_millis() as u64 -} - #[cfg(test)] mod tests { use super::*; @@ -561,7 +465,7 @@ mod tests { let (published_tx, published_rx) = tokio::sync::oneshot::channel(); let first = async { let snapshot = context - .refresh_dpns_vote_state_with(&kv, voter, async { Ok(BTreeMap::new()) }) + .publish_dpns_vote_state(&kv, voter, async { Ok(BTreeMap::new()) }) .await .unwrap(); published_tx.send(()).unwrap(); @@ -570,7 +474,7 @@ mod tests { let second = async { published_rx.await.unwrap(); context - .refresh_dpns_vote_state_with(&kv, voter, async { Ok(BTreeMap::new()) }) + .publish_dpns_vote_state(&kv, voter, async { Ok(BTreeMap::new()) }) .await .unwrap() }; @@ -608,7 +512,7 @@ mod tests { let voter = Identifier::from([1; 32]); let poll = Identifier::from([2; 32]); let older = context - .refresh_dpns_vote_state_with(&kv, voter, async { Ok(BTreeMap::new()) }) + .publish_dpns_vote_state(&kv, voter, async { Ok(BTreeMap::new()) }) .await .unwrap(); context @@ -644,7 +548,7 @@ mod tests { 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.refresh_dpns_vote_state_with(&kv, voter, async { + let older = context.publish_dpns_vote_state(&kv, voter, async { started_tx.send(()).unwrap(); finish_rx.await.unwrap(); Ok(BTreeMap::new()) @@ -693,12 +597,12 @@ mod tests { let voter = Identifier::from([1; 32]); let poll = Identifier::from([2; 32]); let older = context - .refresh_dpns_vote_state_with(&kv, voter, async { Ok(BTreeMap::new()) }) + .publish_dpns_vote_state(&kv, voter, async { Ok(BTreeMap::new()) }) .await .unwrap(); assert!( context - .refresh_dpns_vote_state_with(&kv, voter, async { Err(connection_error()) }) + .publish_dpns_vote_state(&kv, voter, async { Err(connection_error()) }) .await .is_err() ); @@ -732,13 +636,13 @@ mod tests { let voter = Identifier::from([1; 32]); let poll = Identifier::from([2; 32]); let older = context - .refresh_dpns_vote_state_with(&kv, voter, async { Ok(BTreeMap::new()) }) + .publish_dpns_vote_state(&kv, voter, async { Ok(BTreeMap::new()) }) .await .unwrap(); store.fail_next_gets_containing("det:dpns_current_votes:", 1); assert!( context - .refresh_dpns_vote_state_with(&kv, voter, async { Err(connection_error()) }) + .publish_dpns_vote_state(&kv, voter, async { Err(connection_error()) }) .await .is_err() ); @@ -760,7 +664,7 @@ mod tests { 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.refresh_dpns_vote_state_with(&kv, voter, async { + let older = context.publish_dpns_vote_state(&kv, voter, async { started_tx.send(()).unwrap(); finish_rx.await.unwrap(); Ok(BTreeMap::from([( @@ -771,7 +675,7 @@ mod tests { let newer = async { started_rx.await.unwrap(); let result = context - .refresh_dpns_vote_state_with(&kv, voter, async { + .publish_dpns_vote_state(&kv, voter, async { Ok(BTreeMap::from([( poll.to_buffer(), ResourceVoteChoice::Lock, @@ -803,7 +707,7 @@ mod tests { 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.refresh_dpns_vote_state_with(&kv, voter, async { + let refresh = context.publish_dpns_vote_state(&kv, voter, async { started_tx.send(()).unwrap(); finish_rx.await.unwrap(); Err(connection_error()) @@ -832,7 +736,7 @@ mod tests { let voter = Identifier::from([1; 32]); let poll = Identifier::from([2; 32]); let result = context - .refresh_dpns_vote_state_with(&kv, voter, async { Ok(BTreeMap::new()) }) + .publish_dpns_vote_state(&kv, voter, async { Ok(BTreeMap::new()) }) .await .unwrap(); context @@ -885,7 +789,7 @@ mod tests { .unwrap(); assert!( context - .refresh_dpns_vote_state_with(&kv, voter, async { Err(connection_error()) }) + .publish_dpns_vote_state(&kv, voter, async { Err(connection_error()) }) .await .is_err() ); @@ -988,7 +892,7 @@ mod tests { context.set_det_kv_override_for_test(kv.clone()); let voter = Identifier::from([1; 32]); let error = context - .refresh_dpns_vote_state_with(&kv, voter, async { Err(connection_error()) }) + .publish_dpns_vote_state(&kv, voter, async { Err(connection_error()) }) .await .unwrap_err(); assert!(error.contains_dapi_reachability_failure()); diff --git a/src/context/mod.rs b/src/context/mod.rs index c53c01ed6..a295fa9d6 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -3,6 +3,7 @@ mod contested_names_db; mod contract_token_db; mod dpns_vote_operations; mod dpns_vote_state; +pub(crate) use dpns_vote_state::DpnsVoteRefreshResults; pub mod feature_gate; mod identity_db; #[cfg(test)] @@ -91,7 +92,10 @@ impl Drop for ContactRequestActionClaim<'_> { } } -const MAX_CONCURRENT_DPNS_VOTERS: usize = 4; +/// 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; #[derive(Debug)] pub(crate) struct DpnsVoteDispatchCoordinator { diff --git a/src/model/dpns_voting.rs b/src/model/dpns_voting.rs index e794aaec9..459297c45 100644 --- a/src/model/dpns_voting.rs +++ b/src/model/dpns_voting.rs @@ -41,6 +41,33 @@ mod tests { } } + #[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() { @@ -163,14 +190,21 @@ mod tests { ); } } +use crate::backend_task::error::TaskError; +use crate::utils::time::now_ms; 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 rand::RngCore; use serde::{Deserialize, Serialize}; use std::fmt; -use std::time::{SystemTime, UNIX_EPOCH}; /// Proved current vote state for one node Γ— poll. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -445,10 +479,7 @@ impl DpnsVoteOperation { /// Build an operation while removing targets that match proved current state. pub fn new(targets: Vec) -> Self { let id = DpnsVoteOperationId::random(); - let created_at = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_millis() as TimestampMillis; + let created_at = now_ms(); let original_len = targets.len(); let targets = targets .into_iter() @@ -490,3 +521,98 @@ impl DpnsVoteOperation { .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()), + ] +} + +/// 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 +/// +/// [`TaskError::DataContractNotFound`] when the contract carries no `domain` +/// document type, and [`TaskError::ContractSchemaMismatch`] when that document +/// type declares no contested index. +pub fn dpns_vote_poll( + dpns_contract: &DataContract, + name: &str, +) -> Result { + let document_type = dpns_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", + }); + }; + 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) +} + +/// The outcome that currently speaks for `key`, by [`dpns_vote_authority_rank`]. +/// +/// Returns `None` when no operation in `operations` targets `key`. +pub fn authoritative_dpns_vote_outcome<'a>( + operations: &'a [DpnsVoteOperation], + key: &DpnsVoteTargetKey, +) -> Option<&'a DpnsVoteOutcome> { + operations + .iter() + .filter_map(|operation| { + operation + .outcome(key) + .map(|outcome| (operation.created_at, outcome)) + }) + .max_by_key(|(created_at, outcome)| { + dpns_vote_authority_rank(*created_at, outcome.operation_id, outcome.status) + }) + .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()) + }) +} diff --git a/src/utils/mod.rs b/src/utils/mod.rs index d81e1a8bf..339b76d81 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -1,3 +1,4 @@ pub mod egui_mpsc; 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 +} From b397392c98169e588f48ed20315577695e7d51ee Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 14 Sep 2026 15:06:16 +0000 Subject: [PATCH 054/194] fix(dpns): disclose the vote recipient and stop the per-frame contest scan Review-and-cast could ask the operator to approve a candidate vote whose target identity appeared nowhere on the sheet: `review_vote_choice_label` discarded the identifier and rendered "Vote for a candidate that is no longer listed." whenever the name was not cached, while submission stayed enabled. Delete that function and use `vote_choice_label`, which already falls back to the candidate's Base58 handle, so one label function serves every surface and cannot drift again. Candidate labels are now resolved once per refresh into a `BTreeMap>` on the screen. The render path did a mutex-locked linear scan of the entire historical contested-name cache once per row per frame, in the Scheduled Votes table, the Voting activity list and the review sheet alike; it is now one keyed lookup with no lock and no allocation. The schedule editor reads the same index instead of locking the cache. Also in this pass: - `build_review_plan{,_at}` returns a typed `ReviewPlanError` and `VoteHandlingStatus::Failed` carries a `VoteSubmissionError`, replacing `Result<_, String>` and the stringified `TaskError`. Failures raise a `BannerHandle` with the error's details attached, at the transition point rather than per frame, and the raw `Color32::RED` label is gone. - Extract the duplicated UTC schedule picker into a `UtcScheduleInput` component used by both the review sheet and the schedule editor, and catalogue it in the components README. - Replace `render_contest_group`'s three positional bools with `ContestGroupPresentation`, and key the groups by `ActiveContestGroup` instead of hand-mapped array indices. - Promote the repeated "choose a future date" and "keep Dash Evo Tool running" sentences to constants, collapsing three wordings of the latter into one, and give the journal-failure banner and its inline fallback a single sentence that never renders twice at once. - Convert the remaining positional format arguments in user-facing copy to named placeholders, and share one `{absolute} ({relative})` timestamp helper between the two tables. - Reword the skipped-votes line and the post-submit sheet for the Everyday User persona: no "target" or "operation", and the heading no longer claims votes were cast when the batch was scheduled-only. Co-Authored-By: Claude Sonnet 5 --- docs/user-stories.md | 1 + src/ui/components/README.md | 1 + src/ui/components/mod.rs | 1 + src/ui/components/utc_schedule_input.rs | 202 +++++ src/ui/dpns/dpns_contested_names_screen.rs | 733 ++++++++++++------ .../scheduled_vote_editor.rs | 55 +- src/ui/state/dpns_contests.rs | 7 - 7 files changed, 701 insertions(+), 299 deletions(-) create mode 100644 src/ui/components/utc_schedule_input.rs diff --git a/docs/user-stories.md b/docs/user-stories.md index 2ed08b6df..4cfda2210 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -815,6 +815,7 @@ As a masternode operator, I want to apply voting choices across multiple contest - When no loaded node has a voting key, Active contests shows an actionable Load a masternode state instead of vote controls. A masternode loaded without its voting key is not a voting node, so it reaches that state instead of the composer. - Per-node timing overrides and multi-contest selections create exact node Γ— contest targets. - Review and cast lists each of those targets with its node, contest, requested choice, current choice, and timing, and reports how many targets it skipped because the node already holds the requested choice. +- A vote for a candidate always identifies that candidate on the review line β€” by name when one is cached, otherwise by the candidate's identifier. Submission is never gated on a resolvable name, so the sheet never approves a vote whose recipient it did not show. - Immediate and scheduled targets submitted together belong to one operation. - A successful mixed batch reports both cast and scheduled counts as success, without a warning about remaining work. diff --git a/src/ui/components/README.md b/src/ui/components/README.md index 1ef52121b..60f0c7e1e 100644 --- a/src/ui/components/README.md +++ b/src/ui/components/README.md @@ -17,6 +17,7 @@ Concise catalog of all reusable UI components. Consult before creating new UI el | `AddressInput` | `address_input.rs` | `ValidatedAddress` | Unified address with autocomplete, type detection (Core/Platform/Shielded/Identity), DPNS resolution. GitHub-style tag search (`type:core\|platform\|…`, `wallet:name`; unrecognized tokens are free text). Rows render `[wallet pill] address (name) [type pill] balance`; when no explicit hint is set the placeholder is a live `type:…|… wallet:…|…` legend | | `PasswordInput` | `password_input.rs` | N/A (security) | Masked input with hold-to-reveal, zeroizes on drop. NOT ComponentResponse | | `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/mod.rs b/src/ui/components/mod.rs index 1209b90b1..191996977 100644 --- a/src/ui/components/mod.rs +++ b/src/ui/components/mod.rs @@ -27,6 +27,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/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/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 94445b71a..54d1212fd 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -5,7 +5,7 @@ use crate::wallet_backend::poison::MutexRecover; use std::collections::{BTreeMap, BTreeSet}; use std::sync::{Arc, Mutex}; -use chrono::{DateTime, LocalResult, TimeZone, Timelike, Utc}; +use chrono::{DateTime, LocalResult, TimeZone, Utc}; use chrono_humanize::HumanTime; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::platform_value::string_encoding::Encoding; @@ -28,7 +28,7 @@ use crate::model::dpns_voting::{ dpns_schedule_is_overdue, validate_dpns_schedule_time, }; use crate::model::qualified_identity::{DPNSNameInfo, QualifiedIdentity}; -use crate::ui::components::component_trait::Component; +use crate::ui::components::component_trait::{Component, ComponentResponse}; use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; use crate::ui::components::dpns_subscreen_chooser_panel::add_dpns_subscreen_chooser_panel; use crate::ui::components::left_panel::add_left_panel; @@ -36,6 +36,7 @@ use crate::ui::components::progress_overlay::{OptionOverlayExt, OverlayConfig, O 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::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::state::dpns_contests::{ActiveDpnsContestSnapshot, ActiveDpnsContestView}; @@ -53,7 +54,10 @@ pub enum DPNSSubscreen { ScheduledVotes, } -#[derive(Clone, Copy, PartialEq, Eq)] +/// Active contests bucketed by what the loaded nodes can do with them. +/// +/// Declaration order is display order: the derived `Ord` keys the render map. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] enum ActiveContestGroup { NeedsVote, Voted, @@ -61,10 +65,83 @@ enum ActiveContestGroup { NotVotable, } +/// How one contest group renders. Named fields so a callsite cannot transpose +/// "this group is expanded" with "this group accepts votes". +#[derive(Clone, Copy)] +struct ContestGroupPresentation { + default_open: bool, + voting_enabled: bool, + show_current_vote: bool, +} + +impl ActiveContestGroup { + /// Every group, in the order the screen stacks them. + const ALL: [Self; 4] = [ + Self::NeedsVote, + Self::Voted, + Self::VoteStateUnavailable, + Self::NotVotable, + ]; + + fn title(self) -> &'static str { + match self { + Self::NeedsVote => "Needs your vote", + Self::Voted => "Voted", + Self::VoteStateUnavailable => "Vote state unavailable", + Self::NotVotable => "Not votable by your nodes", + } + } + + /// `no_voting_nodes` opens the un-votable group only when it is all the + /// operator has to look at. + fn presentation(self, no_voting_nodes: bool) -> ContestGroupPresentation { + match self { + Self::NeedsVote => ContestGroupPresentation { + default_open: true, + voting_enabled: true, + show_current_vote: false, + }, + Self::Voted => ContestGroupPresentation { + default_open: false, + voting_enabled: true, + show_current_vote: true, + }, + Self::VoteStateUnavailable => ContestGroupPresentation { + default_open: true, + voting_enabled: false, + show_current_vote: false, + }, + Self::NotVotable => ContestGroupPresentation { + default_open: no_voting_nodes, + voting_enabled: false, + show_current_vote: false, + }, + } + } +} + const NO_VOTING_NODES_MESSAGE: &str = "None of your loaded nodes has a voting key."; const NO_VOTING_NODES_DETAIL: &str = "Load a masternode with its voting key to cast votes."; const JOURNAL_UNAVAILABLE_MESSAGE: &str = "Saved voting progress could not be read. The displayed history may be incomplete or out of date. Retry loading before managing votes."; const MISSED_SCHEDULE_GUIDANCE: &str = "The automatic voting time was missed. In Scheduled Votes, 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 (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"), + ) +} fn schedule_is_missed(status: DpnsVoteTargetStatus, timing: VoteTiming, now_ms: u64) -> bool { status == DpnsVoteTargetStatus::Scheduled @@ -75,16 +152,6 @@ fn candidate_choice_label(candidate_name: &str) -> String { format!("Vote for {candidate_name}") } -fn review_vote_choice_label(choice: ResourceVoteChoice, candidate_name: Option<&str>) -> String { - match choice { - ResourceVoteChoice::Lock => "Lock".to_owned(), - ResourceVoteChoice::Abstain => "Abstain".to_owned(), - ResourceVoteChoice::TowardsIdentity(_) => candidate_name - .map(candidate_choice_label) - .unwrap_or_else(|| "Vote for a candidate that is no longer listed.".to_owned()), - } -} - fn classify_vote_states( states: impl IntoIterator, ) -> ActiveContestGroup { @@ -120,17 +187,58 @@ fn tally_chip(ui: &mut Ui, votes: u32, dark_mode: bool) { fn short_identifier(identifier: Identifier) -> String { let encoded = identifier.to_string(Encoding::Base58); - format!("{}…{}", &encoded[..6], &encoded[encoded.len() - 4..]) + format!( + "{head}…{tail}", + head = &encoded[..6], + tail = &encoded[encoded.len() - 4..], + ) } +/// Name a vote choice for the operator. +/// +/// A `TowardsIdentity` choice falls back to the candidate's Base58 handle when +/// no name is cached: every surface that shows a vote β€” including the +/// review-and-cast sheet, which submission does not gate on a resolvable name β€” +/// must disclose which identity the vote goes to. fn vote_choice_label(choice: ResourceVoteChoice, candidate_name: Option<&str>) -> String { match choice { ResourceVoteChoice::Lock => "Lock".to_owned(), ResourceVoteChoice::Abstain => "Abstain".to_owned(), ResourceVoteChoice::TowardsIdentity(identifier) => candidate_name .map(candidate_choice_label) - .unwrap_or_else(|| format!("Vote for {}", short_identifier(identifier))), + .unwrap_or_else(|| format!("Vote for {handle}", handle = short_identifier(identifier))), + } +} + +/// 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 } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -317,7 +425,12 @@ fn review_target_line( } fn review_skipped_line(no_op_count: usize) -> String { - format!("Targets skipped because the node already has that choice ({no_op_count}).") + match no_op_count { + 1 => "1 vote is already cast as requested and will be skipped.".to_owned(), + skipped_count => { + format!("{skipped_count} votes are already cast as requested and will be skipped.") + } + } } fn review_current_choice_label( @@ -325,11 +438,58 @@ fn review_current_choice_label( candidate_name: Option<&str>, ) -> String { match current { - Some(choice) => review_vote_choice_label(choice, candidate_name), + 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("Choose a future time before the contest ends for {contested_name}.dash.")] + ScheduleOutlastsContest { contested_name: String }, + #[error("This vote could not be prepared. Refresh Active contests and try again.")] + VotePollUnavailable { + #[source] + source: Arc, + }, + #[error( + "This node's vote for {contested_name} is already in progress. Check its result before submitting again." + )] + VoteAlreadyInProgress { contested_name: String }, + #[error("Current vote state is unavailable. Refresh voting before applying votes.")] + CurrentVoteUnavailable, +} + +/// 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, + /// A dispatched submission came back as a failure. + /// + /// Fieldless on purpose: `display_task_error` only borrows the `TaskError`, + /// and the alternative β€” stashing its rendered sentence β€” is the very thing + /// a typed error exists to avoid. The specific failure still reaches the + /// user in full, through the global banner AppState raises for every failed + /// task with the technical chain in its details. + #[error( + "The votes could not be submitted. Check your connection and voting key, then review and submit them again." + )] + TaskFailed, +} + fn dpns_operation_id( context: &BackendTaskContext, network: dash_sdk::dpp::dashcore::Network, @@ -376,13 +536,12 @@ pub enum VoteOption { ScheduledAt(u64), } -#[derive(PartialEq)] pub enum VoteHandlingStatus { NotStarted, CastingVotes, SchedulingVotes, Completed, - Failed(String), + Failed(VoteSubmissionError), } #[derive(PartialEq)] @@ -417,6 +576,9 @@ pub struct DPNSScreen { user_identities: Vec, contested_names: Arc>>, 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, local_dpns_names: Arc>>, scheduled_votes: Arc>>, pub selected_votes: Vec, @@ -448,10 +610,11 @@ pub struct DPNSScreen { show_bulk_schedule_popup: bool, bulk_identity_options: Vec, bulk_vote_handling_status: VoteHandlingStatus, + submission_error_banner: Option, set_all_option: VoteOption, - simple_schedule_date: String, - simple_schedule_hour: u32, - simple_schedule_minute: u32, + /// Eagerly built, unlike most components: its default is the construction + /// time plus a day, and the read-only accessors below must see it. + simple_schedule: UtcScheduleInput, } impl DPNSScreen { @@ -478,6 +641,9 @@ impl DPNSScreen { ActiveDpnsContestSnapshot::default() }; + let candidate_names = + candidate_name_index(&active_contests, &contested_names.lock_recover()); + let local_dpns_names = Arc::new(Mutex::new(match dpns_subscreen { DPNSSubscreen::Active => Vec::new(), DPNSSubscreen::Past => Vec::new(), @@ -515,6 +681,7 @@ impl DPNSScreen { user_identities, contested_names, active_contests, + candidate_names, local_dpns_names, scheduled_votes, selected_votes: Vec::new(), @@ -542,10 +709,9 @@ impl DPNSScreen { show_bulk_schedule_popup: false, bulk_identity_options, bulk_vote_handling_status: VoteHandlingStatus::NotStarted, + submission_error_banner: None, set_all_option: VoteOption::CastNow, - simple_schedule_date: default_schedule_time.format("%Y-%m-%d").to_string(), - simple_schedule_hour: default_schedule_time.hour(), - simple_schedule_minute: default_schedule_time.minute(), + simple_schedule: UtcScheduleInput::new().with_time(default_schedule_time), } } @@ -581,6 +747,7 @@ impl DPNSScreen { self.vote_overlay.take_and_clear(); 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; @@ -588,6 +755,7 @@ impl DPNSScreen { 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.local_dpns_names.lock_recover().clear(); @@ -756,18 +924,21 @@ impl DPNSScreen { let filter = normalize_dpns_label(&self.active_filter_term); let contests = self.active_contests.contests(); - let mut groups = [Vec::new(), Vec::new(), Vec::new(), Vec::new()]; + let mut groups = BTreeMap::>::new(); for contest in contests.iter() { - let index = match self.contest_group(contest.vote_poll_id) { - ActiveContestGroup::NeedsVote => 0, - ActiveContestGroup::Voted => 1, - ActiveContestGroup::VoteStateUnavailable => 2, - ActiveContestGroup::NotVotable => 3, - }; - groups[index].push(contest); + groups + .entry(self.contest_group(contest.vote_poll_id)) + .or_default() + .push(contest); } - let closes_within_day = groups[0] + // Counted before the filter is applied: the summary describes the whole + // set of names still open to the operator, not the current search. + let still_open = groups + .get(&ActiveContestGroup::NeedsVote) + .map_or(&[][..], Vec::as_slice); + let available = still_open.len(); + let closing = still_open .iter() .filter(|contest| { contest.contest.end_time.is_some_and(|end_time| { @@ -779,14 +950,12 @@ impl DPNSScreen { egui::Frame::group(ui.style()).show(ui, |ui| { ui.label(format!( "Names still available to your nodes: {available}. Names closing within 24 hours: {closing}.", - available = groups[0].len(), - closing = closes_within_day, )); }); ui.add_space(8.0); if !filter.is_empty() { - for group in &mut groups { + for group in groups.values_mut() { group.retain(|contest| { contest .contest @@ -797,30 +966,30 @@ impl DPNSScreen { } } + let no_voting_nodes = self.voting_identities.is_empty(); egui::ScrollArea::vertical() .id_salt("active_contest_cards") .show(ui, |ui| { - self.render_contest_group(ui, "Needs your vote", &groups[0], true, true, false); - self.render_contest_group(ui, "Voted", &groups[1], false, true, true); - if !groups[2].is_empty() { - ui.label("Current votes are unavailable or out of date. Refresh voting to check these nodes."); - if ui.button("Refresh voting").clicked() { - self.pending_backend_task = Some(BackendTask::ContestedResourceTask( - ContestedResourceTask::QueryDPNSContests, - )); + for group in ActiveContestGroup::ALL { + let contests = groups.get(&group).map_or(&[][..], Vec::as_slice); + if group == ActiveContestGroup::VoteStateUnavailable { + if contests.is_empty() { + continue; + } + ui.label("Current votes are unavailable or out of date. Refresh voting to check these nodes."); + if ui.button("Refresh voting").clicked() { + self.pending_backend_task = Some(BackendTask::ContestedResourceTask( + ContestedResourceTask::QueryDPNSContests, + )); + } } self.render_contest_group( - ui, "Vote state unavailable", &groups[2], true, false, false, + ui, + group.title(), + contests, + group.presentation(no_voting_nodes), ); } - self.render_contest_group( - ui, - "Not votable by your nodes", - &groups[3], - self.voting_identities.is_empty(), - false, - false, - ); self.render_voting_activity(ui); }); @@ -859,26 +1028,24 @@ impl DPNSScreen { ui: &mut Ui, title: &str, contests: &[&ActiveDpnsContestView], - default_open: bool, - voting_enabled: bool, - show_current_vote: bool, + presentation: ContestGroupPresentation, ) { - egui::CollapsingHeader::new(format!("{title} ({})", contests.len())) - .default_open(default_open) + egui::CollapsingHeader::new(format!("{title} ({count})", count = contests.len())) + .default_open(presentation.default_open) .show(ui, |ui| { if contests.is_empty() { ui.label("There are no contests in this group."); } for contest in contests { - let contest_enabled = - voting_enabled && self.contest_has_available_target(contest.vote_poll_id); - ui.add_enabled_ui(contest_enabled, |ui| { + let mut card = presentation; + card.voting_enabled = presentation.voting_enabled + && self.contest_has_available_target(contest.vote_poll_id); + ui.add_enabled_ui(card.voting_enabled, |ui| { self.render_contest_card( ui, contest.contest.as_ref(), contest.vote_poll_id, - contest_enabled, - show_current_vote, + card, ); }); ui.add_space(8.0); @@ -937,9 +1104,13 @@ impl DPNSScreen { ui: &mut Ui, contest: &ContestedName, vote_poll_id: Option, - voting_enabled: bool, - show_current_vote: bool, + presentation: ContestGroupPresentation, ) { + let ContestGroupPresentation { + voting_enabled, + show_current_vote, + .. + } = presentation; let dark_mode = ui.style().visuals.dark_mode; let staged = self .selected_votes @@ -962,10 +1133,13 @@ impl DPNSScreen { ui.set_min_width(ui.available_width()); ui.horizontal(|ui| { ui.label( - RichText::new(format!("{}.dash", contest.normalized_contested_name)) - .heading() - .strong() - .color(DashColors::text_primary(dark_mode)), + RichText::new(format!( + "{name}.dash", + name = contest.normalized_contested_name + )) + .heading() + .strong() + .color(DashColors::text_primary(dark_mode)), ); if let Some(end_time) = contest.end_time && let LocalResult::Single(date_time) = @@ -973,8 +1147,11 @@ impl DPNSScreen { { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.label( - RichText::new(format!("Voting ends {}.", HumanTime::from(date_time))) - .color(DashColors::text_secondary(dark_mode)), + RichText::new(format!( + "Voting ends {when}.", + when = HumanTime::from(date_time) + )) + .color(DashColors::text_secondary(dark_mode)), ); }); } @@ -1117,18 +1294,17 @@ impl DPNSScreen { let missed = schedule_is_missed(outcome.status, outcome.target.timing, Utc::now().timestamp_millis().max(0) as u64); ui.horizontal_wrapped(|ui| { ui.label(format!( - "{} β€” {}.dash β€” {} β€” {}", - outcome.target.voter_alias.clone().unwrap_or_else(|| short_identifier(outcome.target.key.voter_id)), - outcome.target.contested_name, - vote_choice_label( + "{node} β€” {name}.dash β€” {choice} β€” {status}", + node = outcome.target.voter_alias.clone().unwrap_or_else(|| short_identifier(outcome.target.key.voter_id)), + name = outcome.target.contested_name, + choice = vote_choice_label( outcome.target.requested_choice, self.candidate_name( &outcome.target.contested_name, outcome.target.requested_choice, - ) - .as_deref(), + ), ), - if missed { "Missed automatic vote" } else { target_outcome_label(outcome.status, outcome.failure) }, + status = if missed { "Missed automatic vote" } else { target_outcome_label(outcome.status, outcome.failure) }, )); if outcome.status == DpnsVoteTargetStatus::Unconfirmed && ComponentStyles::add_secondary_button( @@ -1287,10 +1463,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 { @@ -1468,7 +1642,7 @@ impl DPNSScreen { let display_name = if name_for_alias.ends_with(".dash") { name_for_alias.clone() } else { - format!("{}.dash", name_for_alias) + format!("{name}.dash", name = name_for_alias) }; body.row(25.0, |mut row| { row.col(|ui| { @@ -1503,7 +1677,7 @@ impl DPNSScreen { let alias_with_suffix = if name_for_alias.ends_with(".dash") { name_for_alias.clone() } else { - format!("{}.dash", name_for_alias) + format!("{name}.dash", name = name_for_alias) }; if let Err(e) = self .app_context @@ -1613,7 +1787,10 @@ impl DPNSScreen { let failure_guidance = if missed { Some(MISSED_SCHEDULE_GUIDANCE) } else { scheduled_failure_guidance(scheduled_row.status, scheduled_row.failure) }; body.row(if failure_guidance.is_some() { 95.0 } else { 25.0 }, |mut row| { row.col(|ui| { - ui.add(Label::new(format!("{}.dash", vote.contested_name))); + ui.add(Label::new(format!( + "{name}.dash", + name = vote.contested_name + ))); }); row.col(|ui| { let voter = self @@ -1627,25 +1804,15 @@ impl DPNSScreen { row.col(|ui| { let candidate_name = self.candidate_name(&vote.contested_name, vote.choice); - let display_text = - vote_choice_label(vote.choice, candidate_name.as_deref()); - ui.add(Label::new(display_text)); + ui.add(Label::new(vote_choice_label(vote.choice, candidate_name))); }); row.col(|ui| { let dark_mode = ui.style().visuals.dark_mode; if let LocalResult::Single(dt) = Utc.timestamp_millis_opt(vote.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) + RichText::new(timestamp_with_relative(dt)) .color(DashColors::text_primary(dark_mode)), ); } else { @@ -1742,17 +1909,11 @@ impl DPNSScreen { (ResourceVoteChoice::Lock, "Lock".to_owned()), (ResourceVoteChoice::Abstain, "Abstain".to_owned()), ]; - if let Some(contest) = self - .contested_names - .lock_recover() - .iter() - .find(|contest| contest.normalized_contested_name == row.vote.contested_name) - && let Some(candidates) = &contest.contestants - { - choices.extend(candidates.iter().map(|candidate| { + if let Some(candidates) = self.candidate_names.get(&row.vote.contested_name) { + choices.extend(candidates.iter().map(|(candidate_id, name)| { ( - ResourceVoteChoice::TowardsIdentity(candidate.id), - format!("Vote for {}", candidate.name), + ResourceVoteChoice::TowardsIdentity(*candidate_id), + candidate_choice_label(name), ) })); } @@ -1764,11 +1925,7 @@ impl DPNSScreen { } fn simple_schedule_option(&self) -> Option { - let timestamp = crate::model::dpns_vote_schedule::parse_utc_schedule( - &self.simple_schedule_date, - self.simple_schedule_hour, - self.simple_schedule_minute, - )?; + let timestamp = self.simple_schedule.current_value()?; (timestamp > Utc::now().timestamp_millis() as u64) .then_some(VoteOption::ScheduledAt(timestamp)) } @@ -1778,34 +1935,23 @@ impl DPNSScreen { self.bulk_identity_options.fill(option); } - fn candidate_name(&self, contested_name: &str, choice: ResourceVoteChoice) -> Option { + /// 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; }; - if let Some(candidate_name) = self - .active_contests - .contest(contested_name) - .and_then(|contest| contest.contestants.as_ref()) - .and_then(|contestants| { - contestants - .iter() - .find(|candidate| candidate.id == candidate_id) - }) - .map(|candidate| candidate.name.clone()) - { - return Some(candidate_name); - } - self.contested_names - .lock_recover() - .iter() - .find(|contest| contest.normalized_contested_name == contested_name) - .and_then(|contest| contest.contestants.as_ref()) - .and_then(|contestants| { - contestants - .iter() - .find(|candidate| candidate.id == candidate_id) - }) - .map(|candidate| candidate.name.clone()) + self.candidate_names + .get(contested_name)? + .get(&candidate_id) + .map(String::as_str) + } + + fn rebuild_candidate_names(&mut self) { + self.candidate_names = + candidate_name_index(&self.active_contests, &self.contested_names.lock_recover()); } fn rebuild_scheduled_vote_rows(&mut self) { @@ -1829,7 +1975,10 @@ impl DPNSScreen { let dark_mode = ui.style().visuals.dark_mode; - if self.bulk_vote_handling_status == VoteHandlingStatus::Completed { + if matches!( + self.bulk_vote_handling_status, + VoteHandlingStatus::Completed + ) { action |= self.show_bulk_vote_handling_complete(ui); return action; } @@ -1887,23 +2036,18 @@ impl DPNSScreen { Ok(plan) => { ui.heading(review_headline(plan.effective_count(), plan.node_count())); for entry in plan.effective() { - let candidate_name = self.candidate_name( - &entry.target.contested_name, - entry.target.requested_choice, - ); - let requested = review_vote_choice_label( + let requested = vote_choice_label( entry.target.requested_choice, - candidate_name.as_deref(), + self.candidate_name( + &entry.target.contested_name, + entry.target.requested_choice, + ), ); - let current_candidate_name = entry - .target - .current_choice - .and_then(|choice| { - self.candidate_name(&entry.target.contested_name, choice) - }); let current = review_current_choice_label( entry.target.current_choice, - current_candidate_name.as_deref(), + entry.target.current_choice.and_then(|choice| { + self.candidate_name(&entry.target.contested_name, choice) + }), ); ui.label(review_target_line( &entry.node_label(), @@ -1927,8 +2071,8 @@ impl DPNSScreen { ); } } - Err(message) => { - ui.colored_label(DashColors::warning_color(dark_mode), message); + Err(error) => { + ui.colored_label(DashColors::warning_color(dark_mode), error.to_string()); } } ui.separator(); @@ -1956,32 +2100,7 @@ impl DPNSScreen { }); if matches!(self.set_all_option, VoteOption::ScheduledAt(_)) { - let mut schedule_changed = false; - ui.horizontal(|ui| { - ui.label("Cast on (UTC):"); - schedule_changed |= ui - .add( - egui::TextEdit::singleline(&mut self.simple_schedule_date) - .desired_width(100.0) - .hint_text("YYYY-MM-DD"), - ) - .changed(); - ui.label("at"); - schedule_changed |= ui - .add( - egui::DragValue::new(&mut self.simple_schedule_hour) - .prefix("Hour: ") - .range(0..=23), - ) - .changed(); - schedule_changed |= ui - .add( - egui::DragValue::new(&mut self.simple_schedule_minute) - .prefix("Minute: ") - .range(0..=59), - ) - .changed(); - }); + let schedule_changed = self.simple_schedule.show(ui).inner.has_changed(); simple_schedule_valid = self.simple_schedule_option().is_some(); if schedule_changed && let Some(option) = self.simple_schedule_option() @@ -1996,13 +2115,10 @@ impl DPNSScreen { if !simple_schedule_valid { ui.colored_label( DashColors::warning_color(dark_mode), - "Choose a future date and time before scheduling these votes.", + SCHEDULE_IN_FUTURE_MESSAGE, ); } - ui.colored_label( - DashColors::warning_color(dark_mode), - "Keep Dash Evo Tool running and connected until then, or the scheduled votes will not be cast.", - ); + ui.colored_label(DashColors::warning_color(dark_mode), KEEP_RUNNING_MESSAGE); } ui.separator(); @@ -2013,17 +2129,17 @@ impl DPNSScreen { for (i, identity) in self.voting_identities.iter().enumerate() { ui.group(|ui| { ui.horizontal(|ui| { - let label = identity.alias.clone().unwrap_or_else(|| { + let identity_label = identity.alias.clone().unwrap_or_else(|| { identity.identity.id().to_string(Encoding::Base58) }); let dark_mode = ui.style().visuals.dark_mode; ui.label( - RichText::new(format!("Identity: {}", label)) + RichText::new(format!("Identity: {identity_label}")) .color(DashColors::text_primary(dark_mode)), ); let current_option = &mut self.bulk_identity_options[i]; - ComboBox::from_id_salt(format!("combo_bulk_identity_{}", i)) + ComboBox::from_id_salt(format!("combo_bulk_identity_{i}")) .width(120.0) .selected_text(match current_option { VoteOption::NoVote => "Do not use this node".to_string(), @@ -2112,7 +2228,7 @@ impl DPNSScreen { { ui.colored_label( DashColors::warning_color(ui.style().visuals.dark_mode), - "Keep Dash Evo Tool running and connected until then, or the scheduled votes will not be cast.", + KEEP_RUNNING_MESSAGE, ); ui.add_space(10.0); } @@ -2139,7 +2255,7 @@ impl DPNSScreen { let submit_disabled_reason = if operation_in_progress { "The selected votes are already being submitted." } else if !simple_schedule_valid { - "Choose a future date and time before scheduling these votes." + SCHEDULE_IN_FUTURE_MESSAGE } else if plan.is_err() { "These votes cannot be submitted yet. Fix the problem shown above and try again." } else { @@ -2205,24 +2321,46 @@ impl DPNSScreen { VoteHandlingStatus::Completed => { // handled above } - VoteHandlingStatus::Failed(message) => { - ui.colored_label(Color32::RED, message); + VoteHandlingStatus::Failed(error) => { + ui.colored_label(DashColors::error_color(dark_mode), error.to_string()); } } action } + /// 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.bulk_vote_handling_status = VoteHandlingStatus::Failed(error); + } + /// Resolve every node Γ— contest target the current review would submit. /// /// The review sheet and the submit click share this so the sheet cannot - /// promise something other than what is sent. `Err` carries the message the - /// operator sees, and blocks submission. - fn build_review_plan(&self) -> Result { + /// 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()) } - fn build_review_plan_at(&self, now: DateTime) -> Result { + fn build_review_plan_at(&self, now: DateTime) -> Result { let mut entries = Vec::new(); let mut voters = Vec::new(); for (identity, option) in self @@ -2235,16 +2373,16 @@ impl DPNSScreen { VoteOption::CastNow => (VoteTiming::Now, "Cast now".to_owned()), VoteOption::ScheduledAt(timestamp) => { if *timestamp <= now.timestamp_millis() as u64 { - return Err( - "Choose a future date and time before scheduling these votes." - .to_owned(), - ); + return Err(ReviewPlanError::ScheduleIsNotInTheFuture); } let date = DateTime::from_timestamp_millis(*timestamp as i64) - .ok_or_else(|| "Choose a valid UTC date and time.".to_owned())?; + .ok_or(ReviewPlanError::ScheduleIsNotAValidTime)?; ( VoteTiming::Scheduled(*timestamp), - format!("Scheduled for {} UTC", date.format("%Y-%m-%d %H:%M")), + format!( + "Scheduled for {when} UTC", + when = date.format("%Y-%m-%d %H:%M"), + ), ) } VoteOption::Scheduled { @@ -2269,11 +2407,8 @@ impl DPNSScreen { now.timestamp_millis() as u64, selected_vote.end_time, ) - .map_err(|_| { - format!( - "Choose a future time before the contest ends for {}.dash.", - selected_vote.contested_name - ) + .map_err(|_| ReviewPlanError::ScheduleOutlastsContest { + contested_name: selected_vote.contested_name.clone(), })?; } let voter_id = identity.identity.id(); @@ -2286,8 +2421,9 @@ impl DPNSScreen { contested_name = selected_vote.contested_name, "Could not build a DPNS vote target" ); - "This vote could not be prepared. Refresh Active contests and try again." - .to_owned() + ReviewPlanError::VotePollUnavailable { + source: Arc::new(error), + } })?; let target_key = DpnsVoteTargetKey { network: self.app_context.network(), @@ -2295,18 +2431,14 @@ impl DPNSScreen { vote_poll_id, }; if self.vote_operations.target_status(&target_key).is_some() { - return Err(format!( - "This node's vote for {} is already in progress. Check its result before submitting again.", - selected_vote.contested_name - )); + return Err(ReviewPlanError::VoteAlreadyInProgress { + contested_name: selected_vote.contested_name.clone(), + }); } let DpnsCurrentVoteState::Available(current_choice) = self.vote_state.state(voter_id, vote_poll_id) else { - return Err( - "Current vote state is unavailable. Refresh voting before applying votes." - .to_owned(), - ); + return Err(ReviewPlanError::CurrentVoteUnavailable); }; entries.push(ReviewEntry { target: DpnsVoteTarget { @@ -2327,8 +2459,8 @@ impl DPNSScreen { fn bulk_apply_votes(&mut self) -> AppAction { let plan = match self.build_review_plan() { Ok(plan) => plan, - Err(message) => { - self.bulk_vote_handling_status = VoteHandlingStatus::Failed(message); + Err(error) => { + self.fail_submission(error); return AppAction::None; } }; @@ -2339,9 +2471,7 @@ impl DPNSScreen { } = plan; if entries.is_empty() { - self.bulk_vote_handling_status = VoteHandlingStatus::Failed( - "No votes selected. Choose at least one node and contest.".to_owned(), - ); + self.fail_submission(VoteSubmissionError::NoTargets); return AppAction::None; } // No-op targets are handed over unfiltered: the operation counts them, @@ -2349,12 +2479,10 @@ impl DPNSScreen { let operation = DpnsVoteOperation::new(entries.into_iter().map(|entry| entry.target).collect()); if operation.targets.is_empty() { - self.bulk_vote_handling_status = VoteHandlingStatus::Failed( - "Every selected node already has the requested vote. Nothing will be submitted." - .to_owned(), - ); + self.fail_submission(VoteSubmissionError::AllNoOps); return AppAction::None; } + self.submission_error_banner.take_and_clear(); self.bulk_vote_handling_status = if has_immediate { VoteHandlingStatus::CastingVotes } else { @@ -2383,14 +2511,14 @@ impl DPNSScreen { match &self.bulk_vote_handling_status { VoteHandlingStatus::Completed => { ui.heading( - RichText::new("The voting operation has been updated.") + RichText::new("Your votes have been submitted or scheduled as requested.") .color(DashColors::text_primary(dark_mode)), ); ui.label( - "Review the recent voting activity for each confirmed, pending, or failed target.", + "Check the recent voting activity to see which votes were confirmed, are still pending, or failed.", ); } - VoteHandlingStatus::Failed(message) => { + VoteHandlingStatus::Failed(error) => { // This means there was a DET-side error, not Platform-side let dark_mode = ui.style().visuals.dark_mode; ui.heading( @@ -2398,7 +2526,10 @@ impl DPNSScreen { .color(DashColors::text_primary(dark_mode)), ); ui.add_space(10.0); - ui.label(RichText::new(message).color(DashColors::text_primary(dark_mode))); + ui.label( + RichText::new(error.to_string()) + .color(DashColors::text_primary(dark_mode)), + ); } _ => { // this should not occur @@ -2462,6 +2593,7 @@ impl ScreenLike for DPNSScreen { self.app_context.all_contested_names().unwrap_or_default(); } } + self.rebuild_candidate_names(); let voter_ids = self .voting_identities @@ -2553,7 +2685,10 @@ impl ScreenLike for DPNSScreen { self.bulk_vote_handling_status, VoteHandlingStatus::CastingVotes | VoteHandlingStatus::SchedulingVotes ) { - self.bulk_vote_handling_status = VoteHandlingStatus::Failed(error.to_string()); + // AppState banners the borrowed `TaskError` itself, so the + // window only has to leave its in-flight state. + self.bulk_vote_handling_status = + VoteHandlingStatus::Failed(VoteSubmissionError::TaskFailed); } } if let Err(refresh_error) = self.vote_operations.refresh(&self.app_context) { @@ -2744,12 +2879,27 @@ impl ScreenLike for DPNSScreen { let mut inner_action = AppAction::None; 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(), "Saved voting progress could not be read. Retry loading before managing votes.", MessageType::Warning); + 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); } } - ui.label(JOURNAL_UNAVAILABLE_MESSAGE); + // 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", @@ -3124,16 +3274,82 @@ mod tests { )); } + /// The review sheet is the last surface an operator reads before a + /// masternode vote is submitted, and a vote change is budgeted, so the sheet + /// must always disclose which identity the vote goes to β€” by name when one + /// is cached, by its copyable handle when none is. #[test] - fn review_choice_uses_the_candidate_name_instead_of_its_identifier() { + fn review_choice_names_the_candidate_or_falls_back_to_its_identifier() { let candidate_id = Identifier::from([42; 32]); - let label = review_vote_choice_label( + let encoded = candidate_id.to_string(Encoding::Base58); + + let named = vote_choice_label( ResourceVoteChoice::TowardsIdentity(candidate_id), Some("alice"), ); + assert_eq!(named, "Vote for alice"); + assert!(!named.contains(&encoded)); - assert_eq!(label, "Vote for alice"); - assert!(!label.contains(&candidate_id.to_string(Encoding::Base58))); + let unresolved = vote_choice_label(ResourceVoteChoice::TowardsIdentity(candidate_id), None); + assert_eq!( + unresolved, + format!("Vote for {}", short_identifier(candidate_id)) + ); + } + + /// 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 = format!( + "β€’ node-one β†’ alpha.dash: Vote for {handle}. Current vote: Lock. Cast now.", + handle = short_identifier(candidate_id), + ); + + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1000.0, 800.0)) + .build_ui(move |ui| { + screen.show_review_and_cast_window(ui); + }); + harness.run(); + + assert!(harness.query_by_label(&expected).is_some()); + } + + /// 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, DPNSSubscreen::ScheduledVotes); + 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] @@ -3341,9 +3557,15 @@ mod tests { ) ); assert_eq!(screen.pending_vote_operation, None); + let VoteHandlingStatus::Failed(failure) = &screen.bulk_vote_handling_status else { + panic!( + "the review window must leave its in-flight state so Submit and Cancel work again" + ); + }; + assert!(matches!(failure, VoteSubmissionError::TaskFailed)); assert!( - screen.bulk_vote_handling_status == VoteHandlingStatus::Failed(error.to_string()), - "the review window must leave its in-flight state so Submit and Cancel work again" + failure.to_string().contains("review and submit them again"), + "the window must name a recovery step the operator can take" ); } } @@ -3372,7 +3594,10 @@ mod tests { screen.pending_vote_operation, Some(DpnsVoteOperationId::from_bytes([11; 16])) ); - assert!(screen.bulk_vote_handling_status == VoteHandlingStatus::CastingVotes); + assert!(matches!( + screen.bulk_vote_handling_status, + VoteHandlingStatus::CastingVotes + )); } /// VOTE-TC-013: a masternode loaded without its voting key must not reach the @@ -3691,13 +3916,13 @@ mod tests { vote_choice: ResourceVoteChoice::Abstain, end_time: Some(scheduled_at), }); - assert!( - screen - .build_review_plan_at(now) - .err() - .expect("the second contest has ended before the schedule") - .contains("beta.dash") - ); + let Err(error) = screen.build_review_plan_at(now) else { + panic!("the second contest has ended before the schedule"); + }; + assert!(matches!( + error, + ReviewPlanError::ScheduleOutlastsContest { contested_name } if contested_name == "beta" + )); } #[test] @@ -3708,10 +3933,9 @@ mod tests { .and_hms_opt(18, 30, 0) .unwrap() .and_utc(); - screen.simple_schedule_date = requested.format("%Y-%m-%d").to_string(); - screen.simple_schedule_hour = 18; - screen.simple_schedule_minute = 30; - screen.apply_all_nodes_option(screen.simple_schedule_option().unwrap()); + screen.simple_schedule = UtcScheduleInput::new().with_time(requested); + let option = screen.simple_schedule_option().unwrap(); + screen.apply_all_nodes_option(option); let plan = screen.build_review_plan().unwrap(); assert_eq!( plan.entries[0].target.timing, @@ -4300,7 +4524,14 @@ mod tests { review_headline(6, 3), "Votes to submit (6) from your nodes (3)." ); - assert!(review_skipped_line(2).contains("(2)")); + assert_eq!( + review_skipped_line(1), + "1 vote is already cast as requested and will be skipped." + ); + assert_eq!( + review_skipped_line(2), + "2 votes are already cast as requested and will be skipped." + ); assert_eq!( review_current_choice_label(Some(ResourceVoteChoice::Abstain), None), "Abstain" 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 index 1452761cb..3ac1fb4d1 100644 --- a/src/ui/dpns/dpns_contested_names_screen/scheduled_vote_editor.rs +++ b/src/ui/dpns/dpns_contested_names_screen/scheduled_vote_editor.rs @@ -9,9 +9,7 @@ pub(super) struct ScheduledVoteEditor { node_label: String, choices: Vec<(ResourceVoteChoice, String)>, choice: ResourceVoteChoice, - date: String, - hour: u32, - minute: u32, + schedule: UtcScheduleInput, time_changed: bool, } @@ -36,9 +34,7 @@ impl ScheduledVoteEditor { key, node_label, choices, - date: time.format("%Y-%m-%d").to_string(), - hour: time.hour(), - minute: time.minute(), + schedule: UtcScheduleInput::new().with_time(time), time_changed: false, }) } @@ -57,11 +53,7 @@ impl ScheduledVoteEditor { } // A choice-only edit must preserve seconds/milliseconds in an imported schedule. let timestamp = if self.time_changed { - crate::model::dpns_vote_schedule::parse_utc_schedule( - &self.date, - self.hour, - self.minute, - )? + self.schedule.current_value()? } else { self.original.vote.unix_timestamp }; @@ -98,8 +90,9 @@ impl ScheduledVoteEditor { }, |ui| { ui.label(format!( - "{} β€” {}.dash", - self.node_label, self.original.vote.contested_name + "{node} β€” {name}.dash", + node = self.node_label, + name = self.original.vote.contested_name, )); egui::ComboBox::from_id_salt("edited_vote_choice") .selected_text( @@ -114,31 +107,8 @@ impl ScheduledVoteEditor { ui.selectable_value(&mut self.choice, *choice, label); } }); - ui.horizontal(|ui| { - ui.label("Cast on (UTC):"); - self.time_changed |= ui - .add( - egui::TextEdit::singleline(&mut self.date) - .hint_text("YYYY-MM-DD") - .desired_width(100.0), - ) - .changed(); - self.time_changed |= ui - .add( - egui::DragValue::new(&mut self.hour) - .prefix("Hour: ") - .range(0..=23), - ) - .changed(); - self.time_changed |= ui - .add( - egui::DragValue::new(&mut self.minute) - .prefix("Minute: ") - .range(0..=59), - ) - .changed(); - }); - ui.label("Keep Dash Evo Tool running and connected until the scheduled time."); + 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), @@ -225,9 +195,12 @@ mod tests { assert!(editor.task(1).is_none()); editor.original.status = DpnsVoteTargetStatus::Scheduled; editor.time_changed = true; - editor.date = "2031-02-03".into(); - editor.hour = 4; - editor.minute = 5; + 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 { unix_timestamp, .. } = editor.task(1).unwrap() else { diff --git a/src/ui/state/dpns_contests.rs b/src/ui/state/dpns_contests.rs index aaa49f2b8..60c886133 100644 --- a/src/ui/state/dpns_contests.rs +++ b/src/ui/state/dpns_contests.rs @@ -39,13 +39,6 @@ impl ActiveDpnsContestSnapshot { .collect() } - pub(crate) fn contest(&self, contested_name: &str) -> Option<&ContestedName> { - self.contests - .iter() - .find(|view| view.contest.normalized_contested_name == contested_name) - .map(|view| view.contest.as_ref()) - } - fn build( contests: Vec, mut poll_id: impl FnMut(&str) -> Option, From 1c985fa4db38ad41db9265e98d1ee09518452550 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 14 Sep 2026 15:03:39 +0000 Subject: [PATCH 055/194] fix(masternodes): correct the DPNS card contract and gate the voting-key merge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three fixes on the Masternodes list and detail screens. Corrected the `masternode_contest_summary` doc contract. It claimed `voter_id` is the node's `associated_voter_identity` id. Platform records masternode votes under the node's ProTxHash β€” Drive stores them at `votes_identities_path / voter_pro_tx_hash` β€” and every producer in this codebase already keys on it: `refresh_dpns_vote_states` writes the proved-vote snapshot under `voter.identity.id()`, `dpns_vote_target` builds `DpnsVoteTargetKey` from it, and `MasternodeVoteTransition` is signed against it, with the voter identity supplying only the signing key. The call site was right and the doc was wrong; keying the read on the voter identity would have missed a cache nothing writes and stranded every card on "Checking votes for N active contests". Rewrote the `voter_id` expression in `reload()` as an explicit presence check. `.map(|_| qi.identity.id())` discarded its binding and read as a transformation of the voter identity when it is really "if a voting key is loaded, use the node's own id". Behaviour is unchanged; a comment now records why. Covered both with tests that drive the production writer (`cache_confirmed_dpns_vote`), so they assert reader/writer agreement rather than restating either side. Gated the "Add voting key" merge while it is in flight, mirroring the load form's `PendingLoad`. Save clears the prompt as it dispatches, so re-offering the button invited a second submit that discarded the newly typed key and surfaced `IdentityLoadInProgress` instead of a disabled control. The merge now travels under a registry token β€” it previously sent none, leaving its own load unobservable β€” the button becomes a spinner while the phase is outstanding, and the gate is carried across the view rebuild that every backend result triggers. Restored a test doc comment whose first line was removed with an adjacent test, leaving a fragment starting mid-sentence. Co-Authored-By: Claude Sonnet 5 --- src/context/contested_names_db.rs | 7 +- src/ui/masternodes/detail_screen.rs | 169 +++++++++++++++++++++++++--- src/ui/masternodes/list_screen.rs | 114 +++++++++++++++++-- 3 files changed, 266 insertions(+), 24 deletions(-) diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index f156bc43b..465c39429 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -363,8 +363,11 @@ impl AppContext { /// 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). diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index 46e1254b6..195648965 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -20,6 +20,7 @@ use crate::app::AppAction; use crate::backend_task::identity::{IdentityInputToLoad, IdentityLoadMode, IdentityTask}; use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; use crate::context::AppContext; +use crate::context::identity_load_registry::{IdentityLoadPhase, IdentityLoadToken}; use crate::model::fee_estimation::format_credits_as_dash; use crate::model::legacy_recovery::RecoveryItem; use crate::model::qualified_identity::{IdentityType, MasternodeKeyPresence, QualifiedIdentity}; @@ -108,6 +109,16 @@ pub struct MasternodeDetailView { key_presence: MasternodeKeyPresence, 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, @@ -174,10 +185,39 @@ impl MasternodeDetailView { key_presence, remove_dialog: None, voter_key_prompt: None, + pending_voter_key_load: None, recovery, } } + /// 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; + } + } + /// Route a finished backend task into this node's recovery offer, reporting /// whether this node's own restore finished. pub(crate) fn absorb_recovery_result( @@ -576,6 +616,17 @@ impl MasternodeDetailView { .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() { @@ -619,6 +670,11 @@ impl MasternodeDetailView { 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, @@ -632,8 +688,9 @@ impl MasternodeDetailView { encryption_password: None, // The backend preserves existing keys and their protection tier. load_mode: IdentityLoadMode::MergeIntoExisting, - // The backend creates and owns this load's registry record. - load_token: None, + // 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), @@ -767,16 +824,19 @@ mod tests { use super::*; use crate::model::secret::Secret; - #[test] - fn voting_ui_scoped_key_update_merges_into_the_current_node() { + /// 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; - let dir = tempfile::tempdir().unwrap(); - let ctx = crate::context::test_support::test_app_context(dir.path()); - let id = Identifier::from([0x47; 32]); - let identity = QualifiedIdentity { - identity: Identity::create_basic_identity(id, PlatformVersion::latest()).unwrap(), + 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, @@ -790,8 +850,15 @@ mod tests { top_ups: BTreeMap::new(), status: IdentityStatus::PendingCreation, network: ctx.network(), - }; - let mut detail = MasternodeDetailView::new(&ctx, identity); + } + } + + #[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, @@ -807,13 +874,29 @@ mod tests { 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"); @@ -830,8 +913,24 @@ mod tests { harness.run(); let position = harness.get_by_label("Save").rect().center(); harness.get_by_label("Save").click(); - harness.run(); - assert!(harness.query_by_label("Save").is_none()); + // 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, @@ -840,7 +939,7 @@ mod tests { modifiers: egui::Modifiers::NONE, }); } - harness.run(); + harness.step(); assert_eq!( dispatched.load(Ordering::Relaxed), 1, @@ -848,6 +947,48 @@ mod tests { ); } + /// 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() { let identity_id = Identifier::from([0x42; 32]); diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index 663acde38..6fd5b8cf0 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -116,6 +116,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 { @@ -149,10 +157,12 @@ impl MasternodesScreen { .map(|qi| { let node_id = qi.identity.id(); let node_id_short = shorten_id(&node_id.to_string(Encoding::Hex)); + // Votes are published and cached under the node's own ProTxHash; + // the voter identity only supplies the key that signs them. let voter_id = qi .associated_voter_identity - .as_ref() - .map(|_| qi.identity.id()); + .is_some() + .then(|| qi.identity.id()); let contest_summary = self .app_context .masternode_contest_summary(voter_id) @@ -396,10 +406,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); } } @@ -734,6 +751,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; @@ -789,6 +807,84 @@ 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; + } + + /// 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; @@ -1787,8 +1883,10 @@ mod tests { ctx.wallet_backend().expect("backend").shutdown().await; } - /// 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; From 4c0d80ccd401a091ada031003b1ee3b54168870c Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 14 Sep 2026 15:44:11 +0000 Subject: [PATCH 056/194] refactor(dpns): move dpns_voting test module to the bottom of the file Hoist the module's imports above the items and move #[cfg(test)] mod tests from the top of the file to the bottom, matching the layout of every other module in model/. No behavioral change. --- src/model/dpns_voting.rs | 385 ++++++++++++++++++++------------------- 1 file changed, 193 insertions(+), 192 deletions(-) diff --git a/src/model/dpns_voting.rs b/src/model/dpns_voting.rs index 459297c45..eb10ad862 100644 --- a/src/model/dpns_voting.rs +++ b/src/model/dpns_voting.rs @@ -1,195 +1,3 @@ -/// 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 -} - -#[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 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)); - } - - 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(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(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 serialized_operation_contains_identifiers_and_choices_only() { - let operation = DpnsVoteOperation::new(vec![target(4, 5, None, ResourceVoteChoice::Lock)]); - let serialized = serde_json::to_string(&operation).expect("serialize operation"); - - assert!(!serialized.contains("private")); - assert!(!serialized.contains("secret")); - assert!(!serialized.contains("wif")); - } - - #[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) - ); - } -} use crate::backend_task::error::TaskError; use crate::utils::time::now_ms; use dash_sdk::dpp::dashcore::Network; @@ -206,6 +14,14 @@ use rand::RngCore; use serde::{Deserialize, Serialize}; use std::fmt; +/// 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 { @@ -616,3 +432,188 @@ pub fn dpns_vote_lock_holders<'a>( .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 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)); + } + + 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(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(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 serialized_operation_contains_identifiers_and_choices_only() { + let operation = DpnsVoteOperation::new(vec![target(4, 5, None, ResourceVoteChoice::Lock)]); + let serialized = serde_json::to_string(&operation).expect("serialize operation"); + + assert!(!serialized.contains("private")); + assert!(!serialized.contains("secret")); + assert!(!serialized.contains("wif")); + } + + #[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) + ); + } +} From 1cf916446e71aaa53578057ed8bd0bad49cff6b5 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 14 Sep 2026 14:45:49 +0000 Subject: [PATCH 057/194] fix(dpns): dedupe kv test-support latch and fix doc placement - contested_name.rs: move the "Per-node DPNS voting summary" doc block from MasternodeVoteStateSummary back onto MasternodeContestSummary, where it belongs; document the enum and each of its three variants; reword the vote_state field doc as a three-state statement instead of a yes/no one. - model/dpns_voting.rs: move the #[cfg(test)] mod tests block from the top of the file to the bottom and hoist the imports above the items, matching the layout of every other module in model/. - wallet_backend/kv_test_support.rs: extract CountdownFailure(Mutex>) with arm()/should_fail(), replacing three copies of the same 13-line latch in FailingKv::get/put/delete. Rename the blanket toggles and their fields to fail_all_reads/fail_all_deletes so no method name collides with a different field's name. Evaluation order is preserved exactly, including the get-vs-delete asymmetry, now documented at both sites. Call sites updated in context/settings_db.rs, context/identity_db.rs and ui/dpns/dpns_contested_names_screen.rs. - Add contract tests for the extracted latch: budget spent only by matching keys, exact armed count, zero-count arming, re-arming replaces the previous arming, and a blanket read failure leaving the get countdown unspent. Co-Authored-By: Claude Sonnet 5 --- src/context/identity_db.rs | 4 +- src/context/settings_db.rs | 18 +-- src/model/contested_name.rs | 19 ++- src/ui/dpns/dpns_contested_names_screen.rs | 2 +- src/wallet_backend/kv_test_support.rs | 175 ++++++++++++++------- 5 files changed, 141 insertions(+), 77 deletions(-) diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index b2120a0d3..61fc27796 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -5164,7 +5164,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); @@ -5172,7 +5172,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") diff --git a/src/context/settings_db.rs b/src/context/settings_db.rs index 96635350c..d85952298 100644 --- a/src/context/settings_db.rs +++ b/src/context/settings_db.rs @@ -493,7 +493,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(); @@ -508,7 +508,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!( @@ -545,7 +545,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, @@ -554,7 +554,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!( @@ -628,7 +628,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); @@ -639,7 +639,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)); @@ -663,7 +663,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); @@ -736,7 +736,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(); @@ -753,7 +753,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/model/contested_name.rs b/src/model/contested_name.rs index 7c3e2d143..ca8cd8141 100644 --- a/src/model/contested_name.rs +++ b/src/model/contested_name.rs @@ -193,27 +193,32 @@ pub fn approximate_time_until(decided_at_ms: TimestampMillis, now_ms: u64) -> Op }) } -/// 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 failed or pending scheduled votes, then no open -/// contests (requirements Β§10.1). +/// 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 failed or pending scheduled votes, then no open +/// contests (requirements Β§10.1). #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct MasternodeContestSummary { /// 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 every active contest has a proved current-vote state. + /// 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 in the authoritative operation journal. diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 54d1212fd..9a97573ee 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -4150,7 +4150,7 @@ mod tests { Arc::new(kv.clone()), ); context.set_det_kv_override_for_test(kv); - store.fail_reads(true); + store.fail_all_reads(true); assert!(loaded_voting_identities(&context).is_err()); for reviewing in [false, true] { let mut screen = DPNSScreen::new(&context, DPNSSubscreen::Active); diff --git a/src/wallet_backend/kv_test_support.rs b/src/wallet_backend/kv_test_support.rs index 9a1063bc0..c0dabcdf1 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,34 +114,38 @@ 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. +/// +/// 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. #[derive(Default)] pub(crate) struct FailingKv { inner: InMemoryKv, - fail_reads: AtomicBool, - fail_gets: Mutex>, + fail_all_reads: AtomicBool, fail_all_deletes: AtomicBool, puts: AtomicUsize, - fail_puts: Mutex>, - fail_deletes: Mutex>, + get_countdown: CountdownFailure, + put_countdown: CountdownFailure, + delete_countdown: CountdownFailure, } impl FailingKv { /// 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.fail_gets.lock().unwrap() = Some((key_fragment.to_owned(), count)); + 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) { + pub(crate) fn fail_all_deletes(&self, fail: bool) { self.fail_all_deletes.store(fail, Ordering::Relaxed); } @@ -119,34 +156,20 @@ impl FailingKv { /// Fail the next `count` writes whose key contains `key_fragment`. pub(crate) fn fail_next_puts_containing(&self, key_fragment: &str, count: usize) { - *self.fail_puts.lock().unwrap() = Some((key_fragment.to_owned(), count)); + 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.fail_deletes.lock().unwrap() = Some((key_fragment.to_owned(), count)); + 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) { - return Err(KvError::LockPoisoned); - } - let should_fail = { - let mut failure = self.fail_gets.lock().unwrap(); - let should_fail = failure - .as_ref() - .is_some_and(|(fragment, remaining)| *remaining > 0 && key.contains(fragment)); - if should_fail && let Some((_, remaining)) = failure.as_mut() { - *remaining -= 1; - if *remaining == 0 { - *failure = None; - } - } - should_fail - }; - if should_fail { + // 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) @@ -156,43 +179,17 @@ 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); - let should_fail = { - let mut failure = self.fail_puts.lock().unwrap(); - let should_fail = failure - .as_ref() - .is_some_and(|(fragment, remaining)| *remaining > 0 && key.contains(fragment)); - if should_fail && let Some((_, remaining)) = failure.as_mut() { - *remaining -= 1; - if *remaining == 0 { - *failure = None; - } - } - should_fail - }; - if should_fail { + 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> { - let should_fail = { - let mut failure = self.fail_deletes.lock().unwrap(); - let should_fail = failure - .as_ref() - .is_some_and(|(fragment, remaining)| *remaining > 0 && key.contains(fragment)); - if should_fail && let Some((_, remaining)) = failure.as_mut() { - *remaining -= 1; - if *remaining == 0 { - *failure = None; - } - } - should_fail - }; - if should_fail { - return Err(KvError::LockPoisoned); - } - if self.fail_all_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) @@ -362,3 +359,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()); + } +} From 39edf1f6b63b8084bcbc90a6d44c1c3b662cba9d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 14 Sep 2026 15:47:28 +0000 Subject: [PATCH 058/194] perf(masternodes): batch the DPNS contest summary read in reload() Resolve every node's voter_id up front and call masternode_contest_summaries() once instead of looping the single-node wrapper, so an operator with many nodes pays for the shared contest cache, vote-poll ids, journal and schedule-dismissal reads once per reload instead of once per node. --- src/ui/masternodes/list_screen.rs | 35 ++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index 6fd5b8cf0..a5e79ef76 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -152,21 +152,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)); - // Votes are published and cached under the node's own ProTxHash; - // the voter identity only supplies the key that signs them. - let voter_id = qi - .associated_voter_identity - .is_some() - .then(|| qi.identity.id()); - let contest_summary = self - .app_context - .masternode_contest_summary(voter_id) - .unwrap_or_else(|_| MasternodeContestSummary::unavailable()); + 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, From 6ae22e6f32b693a0c82507f4181df15488eadaaf Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 14 Sep 2026 15:50:32 +0000 Subject: [PATCH 059/194] test(dpns): drop the review-round prefix from one contested_names_db test --- src/context/contested_names_db.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 465c39429..6f051e46d 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -882,7 +882,7 @@ mod tests { } #[test] - fn r2_dismissed_failure_does_not_hide_unresolved_sibling() { + 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()); From 237b37bad4a2ebd68bd3d036eadf5ffeb41d044d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 17 Sep 2026 14:30:43 +0000 Subject: [PATCH 060/194] fix(dpns-voting): update RNG usage for rand 0.10 API The v1.0-dev merge bumped the direct `rand` dependency to 0.10, which removed `RngCore` from the crate root and renamed the old ext trait. `DpnsVoteOperationId::random()` still used the rand 0.9 import path, breaking the build. Replace the trait-based fill with `rand::random()`, matching the rest of the repo's rand 0.10 usage, and add a test asserting generated operation ids are distinct and never all-zero. Co-Authored-By: Claude Sonnet 5 --- src/model/dpns_voting.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/model/dpns_voting.rs b/src/model/dpns_voting.rs index eb10ad862..3bec03bbb 100644 --- a/src/model/dpns_voting.rs +++ b/src/model/dpns_voting.rs @@ -10,7 +10,6 @@ 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 rand::RngCore; use serde::{Deserialize, Serialize}; use std::fmt; @@ -73,9 +72,7 @@ pub struct DpnsVoteOperationId([u8; 16]); impl DpnsVoteOperationId { /// Generate a random operation identifier without adding a UUID dependency. pub fn random() -> Self { - let mut bytes = [0; 16]; - rand::rng().fill_bytes(&mut bytes); - Self(bytes) + Self(rand::random()) } /// Return the stable persisted byte representation. @@ -448,6 +445,17 @@ mod tests { assert!(!dpns_schedule_is_overdue(u64::MAX, u64::MAX)); } + #[test] + fn operation_ids_are_random_and_distinct() { + let ids: std::collections::BTreeSet<_> = + (0..64).map(|_| DpnsVoteOperationId::random()).collect(); + assert_eq!(ids.len(), 64, "identifiers must not repeat"); + assert!( + !ids.contains(&DpnsVoteOperationId::from_bytes([0; 16])), + "identifiers must not be all-zero" + ); + } + fn target( voter: u8, poll: u8, From c0074617663e04f0b137858042826d7685d1bbd4 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 17 Sep 2026 14:59:52 +0000 Subject: [PATCH 061/194] fix(dpns): clarify the vote decision before confirmation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Highlight the contested name and selected decision, explain Lock and Abstain, and show the previous vote, voting node, and timing separately. πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 3 ++ src/ui/dpns/dpns_contested_names_screen.rs | 61 +++++++++++++--------- 2 files changed, 39 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b7d4bccdc..ff3d80d0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -123,6 +123,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- DPNS vote confirmation now highlights the name and chosen vote in separate + blocks, explains Lock and Abstain, and separates the previous vote and timing. + - DPNS scheduled retries keep the selected choice, and simultaneous scheduled votes share fresh voting information without losing their due status. If a first vote becomes a vote change before submission, DET asks for another review. Unavailable voting information stays visible with a refresh action, successful mixed batches report both cast and scheduled votes, and contest refresh remains available when saved voting progress cannot be recovered. - DPNS voting now explains missed automatic schedules and unreadable saved progress, with manual recovery actions. Completed scheduled and mixed voting history is bounded without discarding unresolved votes or restoring removed schedules. Adding another node's voting key gives a key-specific error. diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 9a97573ee..ffa3de5b1 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -414,16 +414,6 @@ fn review_headline(effective_count: usize, node_count: usize) -> String { format!("Votes to submit ({effective_count}) from your nodes ({node_count}).") } -fn review_target_line( - node: &str, - name: &str, - requested: &str, - current: &str, - timing: &str, -) -> String { - format!("β€’ {node} β†’ {name}.dash: {requested}. Current vote: {current}. {timing}.") -} - fn review_skipped_line(no_op_count: usize) -> String { match no_op_count { 1 => "1 vote is already cast as requested and will be skipped.".to_owned(), @@ -2049,13 +2039,29 @@ impl DPNSScreen { self.candidate_name(&entry.target.contested_name, choice) }), ); - ui.label(review_target_line( - &entry.node_label(), - &entry.target.contested_name, - &requested, - ¤t, - &entry.timing_label, - )); + ui.group(|ui| { + ui.set_width(ui.available_width()); + ui.heading(format!("{name}.dash", name = entry.target.contested_name)); + let decision = match entry.target.requested_choice { + ResourceVoteChoice::Lock => "Your vote: Lock this name".to_owned(), + ResourceVoteChoice::Abstain => "Your vote: Abstain".to_owned(), + ResourceVoteChoice::TowardsIdentity(_) => format!("Your vote: {requested}"), + }; + ui.label(RichText::new(decision).strong()); + match entry.target.requested_choice { + ResourceVoteChoice::Lock => { + ui.label("You are voting to prevent any contestant from receiving this name."); + } + ResourceVoteChoice::Abstain => { + ui.label("You are voting without supporting a contestant or locking this name."); + } + ResourceVoteChoice::TowardsIdentity(_) => {} + } + ui.label(format!("Voting node: {node}", node = entry.node_label())); + ui.label(format!("Previous vote: {current}")); + ui.label(format!("When: {timing}", timing = entry.timing_label)); + }); + ui.add_space(8.0); } if plan.effective().any(|entry| entry.target.current_choice.is_some()) { ui.colored_label(DashColors::warning_color(dark_mode), @@ -3311,7 +3317,7 @@ mod tests { "the fixture must leave the candidate name uncached, or this proves nothing" ); let expected = format!( - "β€’ node-one β†’ alpha.dash: Vote for {handle}. Current vote: Lock. Cast now.", + "Your vote: Vote for {handle}", handle = short_identifier(candidate_id), ); @@ -3323,6 +3329,17 @@ mod tests { harness.run(); assert!(harness.query_by_label(&expected).is_some()); + for label in [ + "alpha.dash", + "Voting node: node-one", + "Previous vote: Lock", + "When: Cast now", + ] { + 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 @@ -4513,13 +4530,7 @@ mod tests { } #[test] - fn review_lines_name_the_node_the_contest_the_choices_and_the_timing() { - let line = review_target_line("node-one", "alice", "Lock", "Not voted yet", "Cast now"); - - assert_eq!( - line, - "β€’ node-one β†’ alice.dash: Lock. Current vote: Not voted yet. Cast now." - ); + fn review_summary_counts_votes_and_labels_previous_choices() { assert_eq!( review_headline(6, 3), "Votes to submit (6) from your nodes (3)." From d9bda1588a825cf7580cf1b7f9732cfff84a39c6 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 23 Sep 2026 06:23:18 +0000 Subject: [PATCH 062/194] test(mcp): use the fragment-based put-failure helper after base merge The base branch added a network-switch test calling FailingKv::fail_next_puts, which this branch replaced with fail_next_puts_containing. An empty fragment matches every key, preserving the original fail-all-writes semantics. Co-Authored-By: Claude Opus 5.5 --- src/mcp/tools/network.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 { From 76f2350af1c31836c4b501f04156508f8780f5a8 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 16:18:44 +0000 Subject: [PATCH 063/194] docs(dpns): redesign voting for operators and move usernames to identities Update the #901 voting requirements, UX spec, test cases and development plan for the operator-convenience redesign (Masternodes > Votes, node sets, aggregate confirm, non-blocking progress, attention chip), and add the identity-side usernames redesign with platform facts and wireframes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HNezqoMYJNU57odApsxVUH --- .../01-requirements.md | 253 ++++-- .../02-ux-spec.md | 284 +++--- .../03-test-case-spec.md | 122 ++- .../04-development-plan.md | 480 +++++----- .../01-requirements.md | 208 +++++ .../02-ux-spec.md | 78 ++ .../03-test-case-spec.md | 56 ++ .../platform-facts.md | 114 +++ .../wireframes.html | 817 ++++++++++++++++++ docs/user-stories.md | 202 +++-- 10 files changed, 2026 insertions(+), 588 deletions(-) create mode 100644 docs/ai-design/2026-10-01-usernames-redesign/01-requirements.md create mode 100644 docs/ai-design/2026-10-01-usernames-redesign/02-ux-spec.md create mode 100644 docs/ai-design/2026-10-01-usernames-redesign/03-test-case-spec.md create mode 100644 docs/ai-design/2026-10-01-usernames-redesign/platform-facts.md create mode 100644 docs/ai-design/2026-10-01-usernames-redesign/wireframes.html 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 index 389c67f6a..175ce988f 100644 --- 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 @@ -3,40 +3,55 @@ ## Status Implemented in PR [#901](https://github.com/dashpay/dash-evo-tool/pull/901) -(`feat(dpns): unify safe masternode voting operations`); see -`docs/user-stories.md` (DPN series) and `CHANGELOG.md` for the shipped, -user-visible behavior. The requirements below are kept as the original -planning record β€” later-landed behavior may extend them without this -document being updated in lockstep. +(`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. -## Problem statement +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. -DET previously exposed DPNS voting through disconnected per-node and bulk -experiences. The adopted design consolidates them on DPNS Active contests. +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). -Both call the same backend, but neither owns a complete, authoritative model of -the operation. The result is unsafe ambiguity: a vote can be accepted while DET -shows no confirmation, the same choice can immediately be offered again, bulk -results cannot identify the affected node, and a second click can submit another -state transition while the first is unresolved. +## Problem statement -Voting consumes Platform credits and each node may vote only five times on a -contest in total (the initial vote plus up to four changes). Duplicate or -ambiguous submissions therefore have a real cost. +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, manages one or more nodes and expects: +Priya, the power-user masternode operator, runs 1–40 nodes (often several on +one voting key) and expects: - current vote state to be accurate; -- quick actions for one node; +- 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; +- 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. It is not an -Everyday User workflow. +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 @@ -51,37 +66,73 @@ Everyday User workflow. | 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. -2. Masternode detail links plainly to Active contests without carrying a node - filter or draft. -3. Single and bulk/scheduled voting use one review sheet and one shared - operation coordinator. +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. + 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. -- **VOTE-FR-002** β€” DPNS Active contests owns the single vote composer and - review sheet. -- **VOTE-FR-003** β€” A node detail page offers one `DPNS Voting` action that - navigates plainly to Active contests. +- ~~**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. +- **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. + 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 @@ -90,26 +141,66 @@ Everyday User workflow. create a state transition. - **VOTE-FR-014** β€” Refresh updates contests, tallies, and node vote state as one coherent snapshot. -- **VOTE-FR-015** β€” A change to an existing vote is labeled as a limited vote - change in Review. DET does not claim to know the remaining count. +- **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 disables submission for that node instead of assuming - `Not voted`. + 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 node voted outside Dash Evo Tool.` + A node with 0 left is skipped with the reason `no changes left (5 of 5 votes + 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** β€” Quick voting supports one node across one or more contests. -- **VOTE-FR-021** β€” Bulk voting supports one or more contests across one or more +- **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** β€” The operator can apply one timing choice to all selected - nodes and override individual nodes. -- **VOTE-FR-023** β€” Timing choices are `Cast now`, `Schedule`, and `Do not use - this node`. -- **VOTE-FR-024** β€” Before submission, a review step lists every target as - node Γ— contest, including current choice, requested choice, and timing. -- **VOTE-FR-025** β€” The review step removes no-op targets and explains why. +- **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. +- **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`. +- **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.`; + - 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`. + - Enter confirms and Esc cancels. +- **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`. ### Operation lifecycle @@ -125,11 +216,25 @@ Everyday User workflow. 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** β€” Button state derives from the shared coordinator. A click - disables the affected action immediately and shows progress text. +- **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. +- **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`). 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 or Scheduled. +- **VOTE-FR-087** **[New]** β€” Targets not yet submitted when their contest's + voting ends become `Failed before submission` with the reason `Not cast. Voting + ended.` ### Confirmation and recovery @@ -166,14 +271,22 @@ Everyday User workflow. - **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 Votes as a missed automatic vote, with + 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}`. Times at or after the deadline are 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. ### Feedback - **VOTE-FR-060** β€” One confirmed target shows a concise success banner. -- **VOTE-FR-061** β€” Batch feedback summarizes confirmed, unconfirmed, rejected, - and failed counts and links to per-target details. +- **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 `…; {k} are + still being checked.`). - **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 @@ -181,6 +294,11 @@ Everyday User workflow. - **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 @@ -193,30 +311,35 @@ Everyday User workflow. - **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. + 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. -- **VOTE-NFR-008 Network isolation** β€” Drafts, schedules, operations, locks, and - results are network-scoped. + 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), which -tracks phase-specific, retryable post-broadcast wait errors. The SDK should -expose the transition hash after broadcast so DET can persist it and resume -waiting. +[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. -DET must still support fallback reconciliation by fetching the node's proved -vote for the target poll. Until either method proves the result, the operation -remains unconfirmed and locked against duplicate submission. +**[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. +- ~~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 index 45125ae25..17c6eefe4 100644 --- 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 @@ -1,152 +1,164 @@ # DPNS Voting Experience β€” UX Specification -## Adopted direction (2026-07-21) +## Adopted direction (revised 2026-10-01) -This revision supersedes the earlier three-step Voting Center journeys in this -document. The durable operation coordinator remains the safety model, but the -separate Masternodes `Nodes / Voting / Scheduled` navigation and full-page -wizard are no longer part of the product. The earlier design remains available -in git history as the rejected v2 exploration. +This revision supersedes the 2026-07-21 "DPNS β–Έ Active contests" placement. The +durable operation coordinator remains the safety model. What changed: -The accepted direction keeps contest decisions where operators discover them: -DPNS Active contests. A single screen supports one vote, several contests, -several nodes, immediate casting, and scheduling. Masternode detail provides -only a plain `DPNS Voting` link to Active contests and never carries node or -contest preselection. +- 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 -- Contest-first cards let an operator understand the decision before choosing - nodes or timing. -- Read-only tally chips and selectable vote controls have different shapes and - interaction states, removing the old ambiguity where a count looked like a - vote button. -- The review surface starts with the common case: all loaded nodes and cast now. -- Per-node timing remains available without making every operator configure a - matrix. -- Durable typed operations, exact target locks, and recovery messages remain - visible without requiring a separate operation page. +- 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 -Masternodes -β”œβ”€β”€ node list -└── node detail - └── DPNS Voting ──> DPNS / Active contests - -DPNS -β”œβ”€β”€ Active contests (all vote composition and recent activity) -β”œβ”€β”€ Past contests (human-readable outcomes) -β”œβ”€β”€ My usernames -└── Scheduled votes (human-readable node, choice, time, status) -``` - -## Active contests - -Contests render as cards, grouped in this order: - -1. `Needs your vote` -2. `Voted` -3. `Vote state unavailable` β€” contests whose proved current vote state could - not be read; hidden when empty, with a `Refresh voting` action above it -4. `Not votable by your nodes` - -Each group is collapsible. The first group opens by default; the last group is -dimmed and its vote controls are disabled. A filter remains available. - -```text -β”Œβ”€ Active contests ─────────────────────────────────────────────┐ -β”‚ Filter by name: [________________] β”‚ -β”‚ Each node can change its vote up to four times after its β”‚ -β”‚ initial vote. β”‚ -β”‚ β”‚ -β”‚ β–Ύ Needs your vote (2) β”‚ -β”‚ β”Œβ”€ alice.dash Voting ends in 2d ─┐ β”‚ -β”‚ β”‚ [Lock name] (12 votes) [Abstain] (3 votes) β”‚ β”‚ -β”‚ β”‚ [Vote for Alice] (20 votes) 3MN5mF…s8Qp β”‚ β”‚ -β”‚ β”‚ [Vote for Alyce] (18 votes) 7Yk2aP…d1Rt β”‚ β”‚ -β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ -β”‚ β–Έ Voted (4) β”‚ -β”‚ β–Έ Vote state unavailable (1) [Refresh voting] β”‚ -β”‚ β–Έ Not votable by your nodes (1) β”‚ -β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ -β”‚ Votes ready to cast: 1 [Review and cast] β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ -``` - -Parenthesized tally chips are labels, not buttons. `selectable_label` controls -contain an action phrase such as `Vote for Alice`, `Lock name`, or `Abstain`. -Selecting the active choice again removes it from the draft. - -## Review and cast sheet - -The sticky tray opens a sheet in the same Active-contests screen. The default -applies the chosen contests to all loaded voting nodes and casts now. - -```text -β”Œβ”€ Review and cast ───────────────────────────────────────┐ -β”‚ Selected votes β”‚ -β”‚ alice.dash β†’ Vote for Alice Β· voting ends in 2d β”‚ -β”‚ β”‚ -β”‚ All my nodes β”‚ -β”‚ Cast timing: [Cast now v] β”‚ -β”‚ β”‚ -β”‚ β–Έ Choose per node (advanced) β”‚ -β”‚ β”‚ -β”‚ [Cancel] [Submit votes] β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ -``` - -Timing choices are `Cast now`, `Schedule`, and `Do not use this node`. -Scheduling exposes the existing day/hour/minute controls and reminds the user -that DET must stay open and connected. The advanced disclosure exposes the -same timing choice for each node. Review removes exact no-op targets, blocks -targets already held by an unresolved operation, and refuses submission when -proved current state is unavailable. - -## Submission and recovery - -`SubmitDpnsVoteOperation` is the only submit path. Explicit submissions, -manual scheduled casting, and `Check again` show the full-window progress -overlay until a terminal task result or error arrives. - -Recent voting activity appears below the contest groups and uses typed target -states: - -```text -β”Œβ”€ Recent voting activity ─────────────────────────────────┐ -β”‚ alice.dash β€” Vote for Alice β€” Confirmed β”‚ -β”‚ example.dash β€” Lock name β€” Confirmation is still checked β”‚ -β”‚ This vote may already have been submitted. Do not submit it β”‚ -β”‚ again. [Check again] β”‚ -β”‚ other.dash β€” Abstain β€” Not applied [Review again]β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +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). ``` -`Confirmed`, `Confirming`, `Unconfirmed`, `Rejected`, `Not applied`, and -pre-submission failure are never inferred from strings. Unconfirmed targets -retain their lock and explicitly warn against resubmission. - -## Scheduled votes and history - -Scheduled votes remain a DPNS sub-screen. Rows show `{name}.dash`, node alias -or shortened Base58 identifier, a human-readable choice, absolute UTC time plus -relative time, typed status, and only valid actions. Past contests describe the -winner or locked outcome in words rather than exposing an unexplained raw ID. - -Unresolved voting operations remain accessible even when no active contests -remain. Completed recent history has a separate limit, so new batches cannot -hide an uncertain result or its check action. A failed scheduled attempt shows -its saved failure reason and an applicable action after navigation or restart. -New schedules and edits reject times at or after a known contest deadline. +## Votes β–Έ To decide (frame V1) + +Header row: sub-view chips Β· node-set chip `Vote with: All my nodes Β· 24 nodes Β· +51 votes β–Ύ` Β· `Find a name` (homoglyph tooltip: `Search ignores look-alike +characters the way usernames do, so o matches 0 and l matches 1.`). + +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}` (1–9) Β· `Lock name` (L) Β· + `Abstain` (A). The node line reads `Your nodes: 19 not voted Β· 4 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 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): `Needs attention: 1 vote +from mn-12 on dashfan.dash is still being checked. Don't submit it again. +1 scheduled vote was missed.` [Show]. + +## 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]. + +## 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.` +- `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: `Done` Β· `Sending` Β· `Being checked` + `This vote may + already have been submitted. Don't submit it again.` [Check again] Β· + `Not applied` + `Platform shows a different vote.` [Review again] Β· + `Not cast` + reason. +- Collapsed state: a chip `Casting 44 votes Β· 33 done` above the network chip. +- 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` + `Dash Evo Tool wasn't + running at that time. Voting is still open for {time}.` [Cast now] [Edit] + [Remove] Β· `Not cast` + saved reason + valid action Β· `Cast with {n} nodes`. +- 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 Β· Outcome (`Went to {name} ({short_id})` [Copy ID] Β· `Locked for +good, no one can register it`) Β· `Your nodes voted` (`Vote for Zed (24 nodes, +51 votes)` / `Your nodes didn't vote.`). + +## Empty and gate states (frame V5) + +| State | Copy | Action | +|---|---|---| +| No nodes loaded | `Load a masternode with its voting key to vote on name contests.` (contests shown read-only; choice tooltip `Load a masternode with a voting key to vote.`) | 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 couldn't be read, so this history may be incomplete. Votes that are still being checked stay protected from resubmission.` | 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]. The `This node's votes` +table shows Name Β· Vote Β· Changes left Β· Voting ends, with the footer `Changes +left are 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 chips have no click or keyboard behavior. -- Every selectable control contains the action and target in its label. -- Disabled controls explain what must change before voting is available. -- Cards wrap vote choices before truncating identifiers. -- The review tray remains outside the scrolling card region. -- The advanced matrix starts collapsed and remains keyboard reachable. -- Status is always expressed in text; color is supplementary. +- 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 becomes a bottom sheet; + 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 index ee5eee8d3..3edc42aa4 100644 --- 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 @@ -1,40 +1,38 @@ # DPNS Voting Experience β€” Test Case Specification -## 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 | Row shows `Current vote: Lock` | FR-010, FR-011 | -| VOTE-TC-002 | Existing vote remains visible | Node already voted; contest active | Open Active contests | Contest appears in Voted, its proved choice is highlighted, `You voted: {choice}` is visible, and change controls are available | FR-012 | -| VOTE-TC-003 | Current choice is a no-op | Current vote is Lock | Select Lock and review | Target is removed; nothing can be submitted | FR-013, FR-025 | -| VOTE-TC-004 | Coherent refresh | Contest tally and current vote both changed | Refresh | One snapshot shows both new values | FR-014 | -| VOTE-TC-005 | Vote query is per node | One node, 100 contests | Refresh | Identity-votes query runs once for the node, not 100 times | NFR-007 | -| VOTE-TC-006 | Vote change warning | Node has an existing vote | Select a different choice and review | Review says this uses a limited vote change without inventing a remaining count | FR-015 | -| VOTE-TC-007 | Vote query failure is not `Not voted` | Proved identity-votes query fails | Open voting | State is unavailable; affected submit controls are disabled | FR-016, NFR-004 | -| VOTE-TC-008 | Node summary distinguishes active and unvoted | Three active contests; node voted in two | View node card | Summary says three active and one needs a vote | FR-017 | +Stream V. Revised 2026-10-01. Markers as in `01-requirements.md`. Level: U = unit, +K = kittest, B = backend test with fake SDK seam. -## Single-contest voting +## Authoritative state | ID | Description | Preconditions | Steps | Expected outcome | Requirements | |---|---|---|---|---|---| -| VOTE-TC-010 | Single vote | Active contests, one draft choice | Review and submit | One target is created per selected loaded node for that contest | FR-020, FR-024 | -| VOTE-TC-011 | Multi-contest vote | Active contests, three draft choices | Review | Review shows the exact node Γ— contest targets | FR-020, FR-031 | -| VOTE-TC-012 | Schedule one choice | Active contests, one draft | Choose Schedule in review | Targets appear in Scheduled with the chosen time | FR-023, FR-050 | -| VOTE-TC-013 | Missing voting key | No loaded node has a voting key | Open Active contests | An actionable state explains that a voting key is missing, offers `Load a masternode`, and leaves submit unavailable | FR-003 | -| VOTE-TC-014 | Voting key does not match node | Load a masternode with a voting private key belonging to a different node's voter identity | Submit the load | Load is rejected with `This voting key could not be matched to the selected node. Check that node's voting private key and try again.`; the node's existing keys and associated voter identity are unchanged | FR-065 | +| 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 | -## Bulk voting +## Composition | ID | Description | Preconditions | Steps | Expected outcome | Requirements | |---|---|---|---|---|---| -| VOTE-TC-020 | Multiple contests and nodes | Two contests, three nodes | Select all and review | Six exact targets are listed | FR-021, FR-024 | -| VOTE-TC-021 | Set all timing | Three selected nodes | Apply Schedule to all | All nodes receive the same schedule | FR-022, FR-023 | -| VOTE-TC-022 | Per-node override | Set all Cast now | Override one node to Schedule | Review reflects two Now and one Scheduled target | FR-022 | -| VOTE-TC-023 | Sticky review tray | Active contests visible | Select a choice | `Votes ready to cast: 1` appears and Review and cast opens in place | FR-002 | -| VOTE-TC-024 | Node navigation is plain | Node detail visible | Click `DPNS Voting` | Active contests opens without a node filter or carried draft | FR-003 | -| VOTE-TC-025 | Advanced node overrides | Three nodes loaded | Open Review and cast, expand advanced choices | All nodes default to Cast now and each can be overridden | FR-011, FR-021 | - -## Execution correctness +| 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 | |---|---|---|---|---|---| @@ -48,11 +46,11 @@ | ID | Description | Preconditions | Steps | Expected outcome | Requirements | |---|---|---|---|---|---| -| VOTE-TC-040 | Double click | Submit enabled | Double-click Submit | Exactly one operation and one target broadcast are created | FR-034, FR-035 | -| VOTE-TC-041 | Cross-screen duplicate | Target is confirming | Return to Active contests | Same node Γ— contest target is disabled with explanation | FR-034, FR-036 | -| VOTE-TC-042 | Unrelated target stays usable | One target confirming | Select another node or contest | Unrelated target remains enabled | Product decision 7 | -| VOTE-TC-043 | Navigation preserves lock | Submit, leave page, return before result | Inspect target | Progress and lock remain active | FR-036 | -| VOTE-TC-044 | Restart preserves lock | Persist unresolved target; restart | Open Voting | Target is restored and reconciled before resubmission is allowed | FR-037, NFR-003 | +| 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 @@ -64,8 +62,8 @@ | 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 | Unconfirmed target; definitive reconciliation proves absence | Check again | Status allows reviewed resubmission | 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 | Partial batch | Two confirmed, one unconfirmed, one rejected | Complete batch | Warning shows counts and details map every target | FR-061, FR-062 | -| VOTE-TC-057 | Journal read failure stays visible until retried | Saved vote-operation progress cannot be read | Open Scheduled Votes, 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 | +| 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 migration @@ -73,20 +71,54 @@ |---|---|---|---|---|---| | VOTE-TC-060 | Legacy schedule migration | Existing scheduled-vote records | Upgrade | Node, contest, choice, time, and executed state are preserved | 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 | +| 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 | Scheduled target's due time is more than 120 seconds in the past and it has not executed | Reopen Scheduled Votes | Row shows `Missed automatic vote` with `Cast now`, `Edit`, and `Remove` actions | FR-056 | +| 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 node voted outside Dash Evo Tool.` | FR-078 | U | +| VOTE-TC-096 | Out of changes skipped | Journal 5 votes | Confirm | Node under Skipped with `no changes left (5 of 5 votes 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 opens drawer / Scheduled | FR-084 | K | +| VOTE-TC-103 | Contest ends mid-batch | Queued targets past end | Execute | `Failed before submission` + `Not cast. 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 | Preconditions | Steps | Expected outcome | Requirements | -|---|---|---|---|---|---| -| VOTE-TC-070 | Blocking submission feedback | Target submitting | Inspect screen | Full-window progress overlay remains visible until success or error | FR-035, NFR-005 | -| VOTE-TC-071 | Keyboard review | Review sheet open | Tab and activate controls | Focus order is logical and advanced node choices are reachable | NFR-005 | -| VOTE-TC-072 | Network isolation | Testnet target unresolved | Switch Mainnet | Mainnet has no Testnet locks or operation rows | NFR-008 | -| VOTE-TC-073 | No secret persistence | Operation stored | Inspect serialized operation | No private key or WIF bytes are present | NFR-009 | -| VOTE-TC-074 | Complete message units | All new copy | Localization audit | Strings are complete and do not parse technical errors | NFR-006 | -| VOTE-TC-075 | All entry points share one submit path | Quick, bulk, and due-scheduled drafts | Dispatch each | Every path creates a coordinator operation; no legacy direct-broadcast path remains | NFR-001 | -| VOTE-TC-076 | Technical error stays in details | Target rejected or fails | Inspect banner | Primary copy is plain language; typed diagnostic is attached as details | FR-063 | +| 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 index 301bd20ab..dc7ca8483 100644 --- 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 @@ -1,5 +1,11 @@ # 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 @@ -8,7 +14,7 @@ Platform proved queries β–Ό DPNS vote-state store ────────┐ β”‚ -Draft / shared composer ──> Vote operation coordinator +Draft / node set / composer ──> Vote operation coordinator β”‚ β”œβ”€ durable operation journal β”œβ”€ target lock registry @@ -24,277 +30,219 @@ Draft / shared composer ──> Vote operation coordinator reconciliation service β”‚ β–Ό - shared operation/result views + 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 - -Add `src/model/dpns_voting.rs` with pure, serializable types: - -```rust -struct DpnsVoteTargetKey { - network: Network, - voter_id: Identifier, - vote_poll_id: Identifier, -} - -struct DpnsVoteTarget { - key: DpnsVoteTargetKey, - contested_name: String, - requested_choice: ResourceVoteChoice, - current_choice: Option, - timing: VoteTiming, -} - -struct DpnsVoteOperationId([u8; 16]); - -enum VoteTiming { - Now, - Scheduled(TimestampMillis), -} - -enum DpnsVoteTargetStatus { - Scheduled, - Queued, - Submitting, - Confirming, - Confirmed, - Unconfirmed, - Rejected, - FailedBeforeSubmission, - NotApplied, - // The user cancelled a scheduled target before it was submitted. - Cancelled, -} - -struct DpnsVoteOutcome { - operation_id: DpnsVoteOperationId, - target: DpnsVoteTarget, - status: DpnsVoteTargetStatus, - transition_hash: Option<[u8; 32]>, - failure: Option, -} -``` - -Generate `DpnsVoteOperationId` with the project's existing random-number -dependency; no new UUID dependency is required. - -`DpnsVoteFailure` is a pure domain enum, not a wrapper around `TaskError`. -Backend errors are mapped into it structurally. The stored form uses -serde-friendly representations and never serializes `TaskError` or secrets. -Full errors remain in task diagnostics and logs. - -## Data ownership - -### Authoritative current votes - -Add `src/context/dpns_vote_state.rs`. - -- Query `ResourceVote::fetch_many` once per loaded node using its ProTxHash. -- Index results by node + vote-poll ID. -- Persist the latest proved snapshot in the node's identity scope. -- Join vote state with global contest data when building UI view models. -- Stop using `ContestedName::my_votes` as an implied persistent source. Remove - it or populate it only in an explicitly transient joined view. - -This fixes the current false `Not voted` state and supports deliberate changes. - -### Operation journal and locks - -Add `src/context/dpns_vote_operations.rs`. - -- Persist an operation before the first broadcast. -- Maintain target locks keyed by network + node + poll. -- Restore unresolved operations and locks on startup. -- Expose read-only snapshots to every UI surface. -- Release a lock only on Confirmed, Rejected, FailedBeforeSubmission, - NotApplied, or explicit cancellation of a not-yet-submitting schedule. -- Keep Unconfirmed targets locked. - -Use per-object KV records and a network-scoped index, following current DET KV -patterns. - -## Backend tasks - -Replace tuple-heavy vote tasks/results with structured variants: - -```rust -ContestedResourceTask::SubmitDpnsVoteOperation(DpnsVoteOperation) -ContestedResourceTask::ReconcileDpnsVoteOperation(DpnsVoteOperationId) -ContestedResourceTask::CastDueScheduledVotes { preserve_eligibility_since_ms: Option } - -BackendTaskContext::DpnsVoteOperation(DpnsVoteOperationId) -BackendTaskSuccessResult::DpnsVoteOperationUpdated(DpnsVoteOperationId) -``` - -The backend persists each target update in the shared coordinator. Task results -carry only the operation ID needed for AppState to request repaint and show a -summary. AppState never delivers raw vote outcomes to whichever screen happens -to be visible. - -As built, due-schedule dispatch is its own sweep rather than a side effect of -contest querying: `AppState::update()` in `app.rs` dispatches -`CastDueScheduledVotes` on a ~60s timer (tightened to a recovery backoff after -a deferred sweep), and `cast_due_scheduled_votes()` in -`src/backend_task/contested_names/mod.rs` loads due targets, casts them, and -persists results off the UI thread. - -## Execution algorithm - -1. Validate the draft against current proved state. -2. Remove exact no-ops. -3. Persist the operation and acquire target locks atomically. -4. Group immediate targets by voter/node. -5. Run different voter groups with a small semaphore. -6. Within each voter group, execute targets sequentially: - - read the current nonce; - - construct and validate the transition; - - persist transition hash when the SDK exposes it; - - broadcast; - - wait for result; - - classify the typed outcome. -7. On cause-less post-broadcast wait failure, mark Unconfirmed and enqueue - reconciliation. Do not rebroadcast. -8. Refresh authoritative vote state after each terminal outcome. - -This replaces the current `join_all` by contest, which can race the same voter -nonce. - -## Reconciliation - -Preferred path: - -1. Resume `waitForStateTransitionResult` by persisted transition hash after - [dashpay/platform#4137](https://github.com/dashpay/platform/issues/4137) - exposes a phase-specific retryable wait error. -2. Independently fetch the proved vote using `VoteQuery` or the per-node votes - query. -3. Confirm when the proved choice matches the request. -4. Keep the target Unconfirmed while neither path is definitive. -5. Permit resubmission only after the Platform contract defines a definitive - negative result. Do not infer safety from a transient query failure. - -The existing generic `PlatformResultUnconfirmed` classification remains useful, -but vote operations convert it into target-level coordinator state instead of a -screen-local banner. - -At the SDK revision used by DET, exact `Vote::fetch(VoteQuery)` is affected by -[dashpay/platform#4138](https://github.com/dashpay/platform/issues/4138). -Reconciliation therefore uses the proved per-identity range query starting at -the exact poll ID and accepts only an exact-key match. Retaining a signed -transition for wait-only recovery remains dependent on -[dashpay/platform#4137](https://github.com/dashpay/platform/issues/4137). - -## Scheduling - -Migrate `ScheduledDPNSVote` into the shared target model: - -- scheduled targets are persisted operations with `VoteTiming::Scheduled`; -- edit and cancel mutate the scheduled target atomically while it still holds - its target lock; -- the due dispatcher moves them to Queued and uses the same executor; -- executed state means Confirmed, not merely outer task success; -- rejected, failed, and unconfirmed outcomes remain inspectable; -- the migration is idempotent and preserves legacy records. - -Do not run immediate casting and schedule persistence as unrelated concurrent -backend tasks. One operation owns both kinds of targets. - -## UI state and components - -### Non-rendering state - -Cache proved current-vote state once when Active contests is built or explicitly -refreshed. Rendering and draft changes read only this in-memory snapshot; they -never perform synchronous KV reads in the egui frame loop. - -### Shared rendering - -Active contests owns card grouping, draft choices, the sticky review tray, and -the in-screen `Review and cast` sheet. The sheet expands the draft into typed -node Γ— contest targets and submits one `DpnsVoteOperation`. - -### Masternodes views - -Keep the Masternodes root limited to the node list and node detail. Detail has a -single `DPNS Voting` button that opens DPNS Active contests without prefiltering. - -### DPNS integration - -Replace the legacy table and top-bar trigger with grouped contest cards, a -sticky `Votes ready to cast` tray, and the in-screen review sheet. Keep Active, -Past, My usernames, and Scheduled votes in DPNS. - -## Message handling - -Create one vote-specific formatter over typed target outcomes. It produces: - -- banner summary; -- per-target plain-language status; -- technical details attachment; -- recovery action (`Check again`, `Review again`, or none). - -Never parse error strings. Unconfirmed outcomes never offer an immediate retry. - -## One-PR implementation workstreams - -This experience ships as one pull request. The workstreams below are logical -commit and review boundaries inside that PR, not independently managed PRs. -They land together so no release can expose two submit paths or a coordinator -without every voting entry point using it. - -### Workstream A β€” Authoritative state and typed models - -- Add domain types and vote-state store. -- Query proved votes per node. -- Fix active-contest view models to show current vote and allow changes. -- Update user stories: current vote visibility and vote changes. -- Covers VOTE-TC-001 through VOTE-TC-008. - -### Workstream B β€” Coordinator and safe executor - -- Add operation journal, locks, structured task context/results. -- Serialize targets per node; bound concurrency across nodes. -- Add post-broadcast unconfirmed classification and reconciliation seam. -- Fix scheduled false-success behavior at the executor boundary. -- Covers VOTE-TC-030 through VOTE-TC-056. - -### Workstream C β€” Active-contests voting - -- Add grouped contest cards and the review sheet. -- Replace node-detail voting with plain DPNS navigation. -- Add operation progress and recovery to Active contests. -- Remove the Masternodes operator sub-navigation and wizard. -- Covers VOTE-TC-010 through VOTE-TC-025 and VOTE-TC-070 through VOTE-TC-076. - -### Workstream D β€” Scheduled consolidation and migration - -- Migrate existing schedules into operation targets. -- Replace legacy scheduled execution/status UI. -- Remove obsolete popup/state code after migration coverage passes. -- Covers VOTE-TC-060 through VOTE-TC-065. - -Each workstream remains independently testable, but the branch is published and -reviewed as one atomic UX change. +## Domain model (built in #901) + +`src/model/dpns_voting.rs` holds the pure, serializable types: + +- `DpnsVoteTargetKey { network, voter_id, vote_poll_id }` +- `DpnsVoteTarget { key, 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, transition_hash, failure }` +- `DpnsVoteFailure`: a pure domain enum, mapped structurally from backend + errors. It never serializes `TaskError` or secrets. + +2026-10-01 additions (pure, same module): + +- `NodeSet { All, EvonodesOnly, MasternodesOnly, Custom(BTreeSet) }` + plus resolution against the loaded nodes, producing excluded nodes with typed + reasons (`NoVotingKey`, `NoChangesLeft`, `NotInMasternodeList`, + `VoteStateUnavailable`). +- `ChangesLeft { Known(u8), Unknown }`, computed from journal counts and proved + state (VOTE-FR-078). +- `node_weight(node_type) -> u32` (1 or 4) and `influence(tally, node_set_weight) + -> Option` (VOTE-FR-077). +- `relative_schedule(end_time, preset) -> Result` + (VOTE-FR-081). +- `FailureReason::VotingEnded` for VOTE-FR-087. + +## Data ownership (built in #901) + +- `src/context/dpns_vote_state.rs`: proved votes per node via + `ResourceVote::fetch_many` keyed by proTxHash (not the SDK stub). Indexed by + node + poll and persisted per node scope. +- `src/context/dpns_vote_operations.rs`: 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(id)`. The due-schedule sweep +runs on a timer of about 60 s in `AppState::update()`. + +## Execution algorithm (unchanged) + +1. Validate against proved state. +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: nonce β†’ + build β†’ persist hash β†’ broadcast β†’ wait β†’ classify. +6. A cause-less wait failure becomes Unconfirmed and is reconciled, never + rebroadcast. +7. Refresh vote state after each terminal outcome. + +2026-10-01: before dispatching a queued target, re-check the contest end time. +If voting has ended, mark it `FailedBeforeSubmission(VotingEnded)`. + +## Reconciliation (unchanged) + +Resume by transition hash when dashpay/platform#4137 lands. Meanwhile use the +proved per-identity range query starting at the exact poll ID (#4138 +workaround). Confirm only on an exact match, and stay Unconfirmed otherwise. + +## 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: aggregate `Your nodes voted` with weight. + +### 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.rs` (+ NodeSet, ChangesLeft, influence, relative schedule) | **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.rs`, new `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 tests for draft expansion, no-op removal, status transitions, locks, and - storage migration. -- Backend tests with fake SDK seams for nonce ordering and all result classes. -- Kittest coverage for quick, bulk, navigation, disabled-state, and result UX. -- Backend E2E on Testnet for one-node multi-contest and two-node same-contest - batches. -- Restart test with a persisted Unconfirmed operation. -- Formatter and clippy per repository policy. +- 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 - -- Revise DPN-005, DPN-006, DPN-007, and MN-003 acceptance criteria. -- Correct the protocol note to five votes total: initial vote plus four changes. -- Add a user story for operation recovery across navigation/restart. -- Document DPNS Active contests as the single voting home and keep Scheduled - votes discoverable in the DPNS sub-navigation. +- `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..68204db8f --- /dev/null +++ b/docs/ai-design/2026-10-01-usernames-redesign/01-requirements.md @@ -0,0 +1,208 @@ +# 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; + - finished outcomes from the last 30 days: `Went to someone else`, + `Locked for good`. + - **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 `@{name} Β· Waiting for vote` + when the identity has no active name. +- **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.` +- **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): + - uses `get_non_resolved_dpns_contests_for_identity` + `get_contested_dpns_vote_state`; + - returns per identity a `Vec`; + - persists it and replaces the single-`Option` pending API. + - **AC:** an identity owning a name still reports its pending requests. A + finished contest yields Won/Lost/Locked. +- **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. 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`. 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.` + - `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, return to U4 with that row; nothing is spent. +- **USR-FR-038** β€” Progress: UX-001 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`). + +### 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..429e23f74 --- /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.` +- Overlay only during registration (UX-001). 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..2bb771b90 --- /dev/null +++ b/docs/ai-design/2026-10-01-usernames-redesign/03-test-case-spec.md @@ -0,0 +1,56 @@ +# 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 | Phases Won / Lost / Locked with dates | FR-020 | B | +| USR-TC-018 | Re-check on pay | Check said NeedsVote; at pay time Locked | Registration not dispatched; U4 shows locked row | FR-037 | B+K | + +## 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} Β· Waiting for vote` | 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..46ef0ab38 --- /dev/null +++ b/docs/ai-design/2026-10-01-usernames-redesign/platform-facts.md @@ -0,0 +1,114 @@ +# DPNS usernames & contested-resource voting β€” platform facts + +Source: dashpay/platform @ `9f7ed16935bd540e4c2a542688800d2953f9f67a` (DET pin). Paths are relative to +`/home/ubuntu/.cargo/git/checkouts/platform-7a21f318038a582f/9f7ed16/packages/`. +`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 + +1. `src/ui/identity/register_dpns_name_screen.rs:539` hard-codes "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` lives in `ui/` (`register_dpns_name_screen.rs:678`) β€” duplicates 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..dbfd53701 --- /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 UX-001 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/user-stories.md b/docs/user-stories.md index 75c7d83af..7d3587803 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -769,121 +769,170 @@ As a user, I want to remove an identity from this device from the identity's own ## DPNS (DPN) -### DPN-001: Register a DPNS username [Implemented] +### DPN-001: Register a username [Gap] **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 Β· 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. +- While registration runs, a full-window blocking overlay (UX-001) prevents a duplicate submission. +- Completion distinguishes a username registered for immediate use from a request submitted for a community vote. -### DPN-002: View owned usernames [Implemented] +### DPN-002: View my usernames [Gap] **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). +- 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 [Gap] **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] +### DPN-004: View past name contests [Gap] **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 my nodes' votes with their total weight. -### DPN-005: Vote on contested names [Implemented] +### DPN-005: Vote on contested names [Gap] **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. -- See the node's proved current choice before casting, changing, or abstaining. -- Active contests groups cards into Needs your vote, Voted, Vote state unavailable, and Not votable by your nodes; a staged choice takes precedence over the proved highlight until submission. -- Unavailable or expired voting information keeps the affected contests visible and offers Refresh voting before enabling their vote controls. -- A node may vote five times in total per contest: the initial vote plus up to four changes. -- Choosing the current choice submits nothing. -- Evonode/masternode identity required. -- The Active-contests screen explains the four-change limit without inventing a remaining-change count; Platform enforces the limit. -- If a first immediate vote becomes a change after review, return to review with the current choice and change-limit warning. A matching current choice still submits nothing. +- 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. +- 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] +### DPN-006: Schedule votes [Gap] **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 under DPNS β†’ Scheduled votes, which remains available in the persistent DPNS subnavigation. Edit changes the choice or absolute UTC time of a vote that has not started, keeping the same node and contest. An edit is rejected if the schedule changed or began executing while the editor was open. -- Scheduled and immediate votes share the same target locks and result states. -- Removing a scheduled vote takes it off the list for good; it does not come back on the next refresh. -- An ambiguous result remains visible for checking and is never automatically rebroadcast. -- Votes that miss the normal automatic voting window show guidance to cast manually, edit, or remove them. Already queued votes retain their eligibility. -- Concurrent scheduled votes use the latest successfully saved voting information without losing their queued eligibility. Cast now retries the selected scheduled choice even when a different immediate vote succeeded afterward. +- 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 [Gap] **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. -- Review and cast defaults to all loaded voting nodes and Cast now. -- The advanced per-node disclosure can set each node to Cast now, Schedule after a delay, or Do not use this node. The common UTC picker preserves its absolute timestamp while the review is open. -- Switching networks clears staged votes and open review/edit dialogs; choices from the previous network are never carried into the new one. -- When no loaded node has a voting key, Active contests shows an actionable Load a masternode state instead of vote controls. A masternode loaded without its voting key is not a voting node, so it reaches that state instead of the composer. -- Per-node timing overrides and multi-contest selections create exact node Γ— contest targets. -- Review and cast lists each of those targets with its node, contest, requested choice, current choice, and timing, and reports how many targets it skipped because the node already holds the requested choice. -- A vote for a candidate always identifies that candidate on the review line β€” by name when one is cached, otherwise by the candidate's identifier. Submission is never gated on a resolvable name, so the sheet never approves a vote whose recipient it did not show. -- Immediate and scheduled targets submitted together belong to one operation. -- A successful mixed batch reports both cast and scheduled counts as success, without a warning about remaining work. +- 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 always identifies that requester, by name or by identifier. +- Switching networks clears drafts and open dialogs. +- A successful mixed batch reports cast and scheduled counts. + +### DPN-008: Choose which username is shown [Gap] +**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. +- 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. + +### DPN-009: Scheduled votes preserved across an app 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. + +- 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. + +### DPN-010: See a pending username request [Gap] +**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 I have already chosen. + +- The header subtitle reads `@name Β· Waiting for vote` when the identity has no active name. 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 credits by submitting -the same vote again. +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. +- 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-008: Set an alias for an owned username [Implemented] -**Persona:** Alex, Priya +### DPN-012: Follow my username request to a result [Gap] +**Persona:** Alex -As a user, I want to assign a friendly alias to an identity behind a username I own so that I can recognise it more easily in lists. +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. -- Alias set from the "My usernames" table. -- Alias persists and is applied to the underlying identity. +- 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) are announced once with a banner and stay in Profile for 30 days. +- Power users whose nodes can vote on the contest get a link to Masternodes β–Έ Votes for that name. -### DPN-009: Scheduled votes preserved across an app upgrade [Implemented] +### DPN-013: Know from anywhere that a vote is needed [Gap] **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 the app to tell me when my nodes have contests to decide so that I never miss a deadline. -- 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. +- 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-010: See a pending username registration [Implemented] -**Persona:** Alex +### DPN-014: See my voting weight and remaining changes [Gap] +**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 [Gap] +**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 [Gap] +**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 [Gap] +**Persona:** Alex, Priya -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, 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. -- 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. +- 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". --- @@ -1677,15 +1726,15 @@ As a masternode operator, I want a card list of my loaded masternodes showing ty - An empty state explains what a masternode identity is for and offers a primary "Load a masternode" action when none are loaded. - The Masternodes tab and its nav entry are visible only at the Detailed view interface mode or above; dropping below Detailed view while the tab is active falls back to the Identities screen. -### MN-003: Open a masternode and vote [Implemented] +### MN-003: Open a masternode and vote [Gap] **Persona:** Priya -As a masternode operator, I want to open a node and continue to DPNS voting, 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 the keys summary and node actions. -- A single `DPNS Voting` button opens DPNS β†’ Active contests without carrying a node filter, draft, or other routing state. -- Voting takes place on Active contests through the shared durable voting-operation path. -- When no loaded node has a voting key, Active contests explains what is missing and offers a `Load a masternode` action. +- 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 @@ -1751,10 +1800,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 node identity 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 one identity refresh per loaded node, or for the single open node on the detail view. -- The card-list Refresh also queries DPNS contests when at least one node is loaded; the detail-view Refresh updates only that node's identity. Refresh is a no-op when no node is loaded. DPNS Active contests also exposes its own contest refresh action. +- 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. +- [Gap] 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 From 47249d446465b6cac1009cad66ae53ee35fbbde9 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 16:29:32 +0000 Subject: [PATCH 064/194] feat(dpns): contest timing, contested rule and vote fee in model Move the contested-name rule into model/dpns.rs, delegating to the bundled DPNS contract's contested-index field matches, and add contest durations, the urgency window and vote-free suggestions. Read the community vote fee from the protocol version instead of the hard-coded 0.2006 literal. Co-Authored-By: Claude Opus 5.5 --- src/context/contested_names_db.rs | 30 ++- src/model/dpns.rs | 191 +++++++++++++++++++ src/model/fee_estimation.rs | 20 ++ src/ui/identity/register_dpns_name_screen.rs | 24 +-- 4 files changed, 230 insertions(+), 35 deletions(-) diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 6f051e46d..16ed07013 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -114,21 +114,6 @@ 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 - } else { - NON_MAINNET_CONTEST_DURATION - } -} - fn vote_state_summary(states: &[DpnsCurrentVoteState]) -> MasternodeVoteStateSummary { if states.contains(&DpnsCurrentVoteState::Checking) { MasternodeVoteStateSummary::Checking @@ -141,7 +126,11 @@ fn vote_state_summary(states: &[DpnsCurrentVoteState]) -> MasternodeVoteStateSum 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 @@ -154,9 +143,7 @@ impl StoredContestedName { ContestState::WonBy(id) } else if let Some(created_at) = latest_created_at { let elapsed = Duration::from_millis(now_ms().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 { + if elapsed <= join_window { ContestState::Joinable } else { ContestState::Ongoing @@ -200,6 +187,11 @@ fn contest_err(source: KvAdapterError) -> TaskError { } 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() + } + /// 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()?; diff --git a/src/model/dpns.rs b/src/model/dpns.rs index 7853480ae..6422f51fe 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,118 @@ 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 digit from 2 to 9, which 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"; @@ -269,6 +391,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/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/ui/identity/register_dpns_name_screen.rs b/src/ui/identity/register_dpns_name_screen.rs index d8267a4a6..466ca549d 100644 --- a/src/ui/identity/register_dpns_name_screen.rs +++ b/src/ui/identity/register_dpns_name_screen.rs @@ -528,15 +528,20 @@ impl ScreenLike for RegisterDpnsNameScreen { ); // Show contested status and cost if valid - if is_contested_name(&name.to_lowercase()) { + if crate::model::dpns::is_contested_label(name) { ui.colored_label( egui::Color32::DARK_RED, "This is a contested name.", ); + let contest_fee = crate::model::fee_estimation::contest_fee_credits( + self.app_context.sdk_platform_version(), + ); 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", + format!( + "Community vote fee: {fee} DASH", + fee = format_credits_as_dash(contest_fee) + ), ); } else { ui.colored_label( @@ -674,16 +679,3 @@ impl ScreenLike for RegisterDpnsNameScreen { action } } - -pub fn is_contested_name(name: &str) -> bool { - let length = name.len(); - if length >= 20 { - return false; - } - for c in name.chars() { - if c.is_ascii_digit() && c != '0' && c != '1' { - return false; - } - } - true -} From 201e3f5ef56a393fbc328a69ffa8552ebc68bca8 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 16:38:20 +0000 Subject: [PATCH 065/194] feat(identity): username availability and request status ops Add CheckUsernameAvailability and RefreshMyUsernameRequests backend ops. Availability combines the registered-name lookup with the proved contest state, so contested, joinable and locked names are never reported as free. Request status is derived from one scan of running contests for all identities, with outcomes read per name once a contest leaves that set. Pending requests are stored as a list per identity alongside the local main-name choice and seen-outcome flags, replacing the single pending username snapshot. Registration re-checks availability before any fee is spent and records contested submissions immediately. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/error.rs | 24 + src/backend_task/identity/dpns_usernames.rs | 267 ++++++++ src/backend_task/identity/mod.rs | 12 + .../identity/register_dpns_name.rs | 20 + src/backend_task/mod.rs | 9 + src/context/contested_names_db.rs | 419 ++++++++---- src/context/mod.rs | 7 +- src/model/contested_name.rs | 233 +------ src/model/dpns_usernames.rs | 639 ++++++++++++++++++ src/model/mod.rs | 1 + src/ui/components/pill.rs | 37 +- src/ui/identity/home.rs | 8 +- src/ui/identity/identity_hero_card.rs | 29 +- src/ui/identity/settings.rs | 2 +- 14 files changed, 1308 insertions(+), 399 deletions(-) create mode 100644 src/backend_task/identity/dpns_usernames.rs create mode 100644 src/model/dpns_usernames.rs diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 177832f0c..155fb07fa 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1958,6 +1958,30 @@ 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( + "Availability can't be checked right now. Check your internet connection and try again." + )] + 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, + }, + + /// 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 { diff --git a/src/backend_task/identity/dpns_usernames.rs b/src/backend_task/identity/dpns_usernames.rs new file mode 100644 index 000000000..d175cdd62 --- /dev/null +++ b/src/backend_task/identity/dpns_usernames.rs @@ -0,0 +1,267 @@ +//! 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, UsernameAvailability, UsernameRequest, + classify_availability, merge_requests, username_request_from_contest, +}; +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. + pub(crate) async fn username_availability( + &self, + sdk: &Sdk, + 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( + label, + awarded, + contest.as_ref(), + now_ms(), + self.username_contest_durations(sdk), + )) + } + + pub(super) async fn check_username_availability( + &self, + sdk: &Sdk, + label: String, + ) -> Result { + let availability = self.username_availability(sdk, &label).await?; + Ok(BackendTaskSuccessResult::UsernameAvailability { + label, + availability, + }) + } + + async fn dpns_domain_exists(&self, sdk: &Sdk, normalized: &str) -> Result { + let 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: "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, + }; + let documents = Document::fetch_many(sdk, query) + .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. + /// + /// One scan of running contests serves all identities. Requests that left + /// the running set are re-read individually to learn their outcome. + pub(super) async fn refresh_my_username_requests( + &self, + sdk: &Sdk, + ) -> Result { + let identity_ids: Vec = self + .load_local_user_identities()? + .iter() + .map(|identity| identity.identity.id()) + .collect(); + let running = sdk + .get_contested_non_resolved_usernames(None) + .await + .map_err(|source| TaskError::UsernameRequestRefreshFailed { + source: Box::new(source), + })?; + let durations = self.username_contest_durations(sdk); + let now = now_ms(); + let snapshots: BTreeMap<&String, (ContestSnapshot, u64)> = running + .iter() + .map(|(name, info)| { + ( + name, + (self.contest_snapshot(sdk, &info.contenders), info.end_time), + ) + }) + .collect(); + + for identity_id in identity_ids { + let previous = self.username_requests_for(&identity_id); + let mut fresh: Vec = snapshots + .iter() + .filter_map(|(name, (snapshot, end))| { + username_request_from_contest( + identity_id, + name, + snapshot, + Some(*end), + now, + durations, + ) + }) + .collect(); + for old in previous.iter().filter(|old| { + old.phase.is_pending() && !snapshots.contains_key(&old.normalized_label) + }) { + match sdk + .get_contested_dpns_vote_state(&old.normalized_label, None) + .await + { + Ok(contenders) => { + let snapshot = self.contest_snapshot(sdk, &contenders); + if snapshot.winner.is_some() + && let Some(outcome) = username_request_from_contest( + identity_id, + &old.normalized_label, + &snapshot, + old.end, + now, + durations, + ) + { + fresh.push(outcome); + } + } + Err(error) => tracing::debug!( + name = %old.normalized_label, + ?error, + "Username request outcome could not be read; keeping the stored status" + ), + } + } + let merged = merge_requests(&previous, fresh, now); + if merged != previous { + self.store_username_requests(&identity_id, merged)?; + } + } + Ok(BackendTaskSuccessResult::MyUsernameRequestsRefreshed) + } + + /// Record a just-submitted contested request so the hub shows it at once. + pub(super) fn record_submitted_username_request( + &self, + sdk: &Sdk, + identity_id: &Identifier, + label: &str, + ) -> Result<(), TaskError> { + let now = now_ms(); + let submitted = + UsernameRequest::submitted(label, now, self.username_contest_durations(sdk)); + let previous = self.username_requests_for(identity_id); + let merged = merge_requests(&previous, vec![submitted], now); + self.store_username_requests(identity_id, merged) + } +} diff --git a/src/backend_task/identity/mod.rs b/src/backend_task/identity/mod.rs index 2d21fd3f5..54189051f 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; @@ -546,6 +547,13 @@ pub enum IdentityTask { }, RefreshIdentity(QualifiedIdentity), RefreshLoadedIdentitiesOwnedDPNSNames, + /// Check whether a username label can be requested right now. + CheckUsernameAvailability { + /// The bare label, as typed. + label: String, + }, + /// Refresh the community-vote requests of every loaded identity. + RefreshMyUsernameRequests, } /// Returns the default key specifications for a new identity. @@ -951,6 +959,10 @@ impl AppContext { IdentityTask::RefreshLoadedIdentitiesOwnedDPNSNames => { Ok(self.refresh_loaded_identities_dpns_names(sender).await?) } + IdentityTask::CheckUsernameAvailability { label } => { + self.check_username_availability(sdk, label).await + } + IdentityTask::RefreshMyUsernameRequests => self.refresh_my_username_requests(sdk).await, IdentityTask::ProtectIdentityKeys { identity_id, password, diff --git a/src/backend_task/identity/register_dpns_name.rs b/src/backend_task/identity/register_dpns_name.rs index a129b6f8b..344e8dc46 100644 --- a/src/backend_task/identity/register_dpns_name.rs +++ b/src/backend_task/identity/register_dpns_name.rs @@ -48,6 +48,13 @@ impl AppContext { return Err(TaskError::InvalidDpnsName { validation }); } + // 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, &input.name_input).await?; + if !availability.allows_registration() { + return Err(TaskError::UsernameNoLongerAvailable { availability }); + } + let mut rng = StdRng::from_entropy(); let dpns_contract = self.dpns_contract.clone(); @@ -272,6 +279,19 @@ impl AppContext { self.update_local_qualified_identity(&qualified_identity)?; + if outcome == crate::model::dpns::DpnsRegistrationOutcome::PendingCommunityVote + && let Err(error) = self.record_submitted_username_request( + sdk, + &qualified_identity.identity.id(), + &input.name_input, + ) + { + tracing::warn!( + ?error, + "Submitted username request could not be stored locally" + ); + } + let fee_result = FeeResult::new(estimated_fee, actual_fee); Ok(BackendTaskSuccessResult::RegisteredDpnsName { outcome, diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index b1baa8af8..79db0e56a 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -1041,6 +1041,15 @@ 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, + // Broadcast results BroadcastedStateTransition, diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 16ed07013..90f03a8a1 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -9,9 +9,9 @@ use super::AppContext; use crate::backend_task::error::TaskError; use crate::model::contested_name::{ - ContestState, Contestant, ContestedName, MasternodeVoteStateSummary, PendingUsername, - pending_usernames_in, + ContestState, Contestant, ContestedName, MasternodeVoteStateSummary, }; +use crate::model::dpns_usernames::UsernameRequest; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, dpns_vote_authority_rank, @@ -239,87 +239,199 @@ 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 cache = UsernameCache::default(); + for key in kv + .list(DetScope::Global, Some(USERNAME_REQUESTS_KEY_PREFIX)) + .map_err(contest_err)? + { + let Some(id) = identity_from_key(&key, USERNAME_REQUESTS_KEY_PREFIX) else { + continue; + }; + match kv.get::>(DetScope::Global, &key) { + Ok(Some(requests)) => { + cache.requests.insert(id, requests); + } + Ok(None) => {} + Err(error) => { + tracing::warn!(key = %key, ?error, "Skipping unreadable username request list") + } + } + } + for key in kv + .list(DetScope::Global, Some(MAIN_USERNAME_KEY_PREFIX)) + .map_err(contest_err)? + { + if let Some(id) = identity_from_key(&key, MAIN_USERNAME_KEY_PREFIX) + && let Ok(Some(name)) = kv.get::(DetScope::Global, &key) + { + cache.main.insert(id, name); + } + } + for key in kv + .list(DetScope::Global, Some(SEEN_OUTCOMES_KEY_PREFIX)) + .map_err(contest_err)? + { + if let Some(id) = identity_from_key(&key, SEEN_OUTCOMES_KEY_PREFIX) + && let Ok(Some(seen)) = kv.get::>(DetScope::Global, &key) + { + cache.seen.insert(id, seen); + } + } + *self.username_cache_mut() = 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 = now_ms(); - 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) + } + + 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 { + self.username_cache() + .requests .get(identity_id) - .filter(|pending| pending.decided_at.is_none_or(|end| end > now_ms)) - .cloned()) + .cloned() + .unwrap_or_default() } - /// Map each of `identity_ids` to its pending DPNS username request, if any. - /// - /// Reads only the frame-safe snapshot. Identities with nothing pending are - /// omitted. - pub fn pending_dpns_usernames( + /// Persist `requests` as the full request list of `identity_id`. + pub(crate) fn store_username_requests( &self, - identity_ids: &[Identifier], - ) -> std::result::Result, TaskError> { - let now_ms = now_ms(); - 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, + requests: Vec, + ) -> Result<(), TaskError> { + let key = identity_key(USERNAME_REQUESTS_KEY_PREFIX, identity_id); + let kv = self.det_kv()?; + if requests.is_empty() { + kv.delete(DetScope::Global, &key).map_err(contest_err)?; + self.username_cache_mut().requests.remove(identity_id); + } else { + kv.put(DetScope::Global, &key, &requests) + .map_err(contest_err)?; + self.username_cache_mut() + .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_cache() + .requests + .get(&identity.identity.id())? + .iter() + .find(|request| request.phase.is_pending()) + .cloned() } - /// 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) + } + + /// 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> { + self.det_kv()? + .put( + DetScope::Global, + &identity_key(MAIN_USERNAME_KEY_PREFIX, identity_id), + &name.to_owned(), + ) + .map_err(contest_err)?; + self.username_cache_mut() + .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))) + } + + /// Record that the outcome banner for `request` was shown. + pub fn mark_username_outcome_seen( + &self, + identity_id: &Identifier, + request: &UsernameRequest, + ) -> Result<(), TaskError> { + let mut seen = self + .username_cache() + .seen + .get(identity_id) + .cloned() + .unwrap_or_default(); + if !seen.insert(outcome_key(request)) { + return Ok(()); + } + self.det_kv()? + .put( + DetScope::Global, + &identity_key(SEEN_OUTCOMES_KEY_PREFIX, identity_id), + &seen, + ) + .map_err(contest_err)?; + self.username_cache_mut().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> { + let mut requests = self.username_requests_for(identity_id); + requests.retain(|r| r.phase.is_pending() || r.normalized_label != normalized_label); + self.store_username_requests(identity_id, requests) } /// Seed a current contest through the persisted shape for backend contract tests. @@ -625,6 +737,40 @@ 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>, + main: HashMap, + seen: 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 @@ -636,7 +782,7 @@ 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::qualified_identity::encrypted_key_storage::KeyStorage; use crate::model::qualified_identity::{ DPNSNameInfo, IdentityStatus, IdentityType, QualifiedIdentity, @@ -691,46 +837,92 @@ 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, + } + } + #[test] - fn pending_dpns_usernames_for_identities_omits_owned_identity() { + 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, " "); - { - 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, - }, - ); - pending.insert( - unowned.identity.id(), - PendingUsername { - name: "bob".to_string(), - decided_at: None, - }, - ); + for identity in [&owned, &unowned] { + context + .store_username_requests( + &identity.identity.id(), + vec![ + request("lost", RequestPhase::Lost), + request("b0b", RequestPhase::Voting), + ], + ) + .expect("store"); } - - let pending = context.pending_dpns_usernames_for_identities(&[owned, unowned]); - - assert!( - !pending.contains_key(&Identifier::from([1; 32])), - "an awarded DPNS name must suppress the stale pending indicator" - ); + assert!(context.pending_dpns_username_for_identity(&owned).is_none()); 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" + 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_outcome_seen(&id, &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 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")); } // ---------------------------------------------------------------- @@ -1158,39 +1350,4 @@ mod tests { voters.len() ); } - - // ---------------------------------------------------------------- - // Bridge: a stored contest decodes into a detectable pending username. - // ---------------------------------------------------------------- - - #[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)); - } - - #[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() - }; - 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()); - } } diff --git a/src/context/mod.rs b/src/context/mod.rs index e43a830eb..9061ba9a1 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -195,9 +195,8 @@ 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, /// 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 @@ -565,7 +564,7 @@ impl AppContext { identity_record_locks: Mutex::new(HashMap::new()), animations_disabled: AtomicBool::new(false), cached_settings: RwLock::new(None), - pending_dpns_usernames: RwLock::new(HashMap::new()), + pending_dpns_usernames: RwLock::new(Default::default()), app_kv, #[cfg(test)] det_kv_override: Mutex::new(None), diff --git a/src/model/contested_name.rs b/src/model/contested_name.rs index ca8cd8141..6720f0452 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; @@ -43,99 +42,6 @@ impl ContestedName { pub fn is_votable(&self) -> bool { self.state.state_is_votable() } - - /// 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); - } - } - 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. @@ -267,27 +173,6 @@ 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 contest_is_votable_only_in_open_states() { for (state, expected) in [ @@ -301,122 +186,6 @@ mod tests { } } - // ---------------------------------------------------------------- - // 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, - ] { - 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)); - } - } - - #[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, - ] { - let c = contest_with(state, vec![contestant(me, "det1")]); - assert!(c.pending_username_for(&Identifier::from(me)).is_none()); - } - } - - #[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_usernames.rs b/src/model/dpns_usernames.rs new file mode 100644 index 000000000..8a6989423 --- /dev/null +++ b/src/model/dpns_usernames.rs @@ -0,0 +1,639 @@ +//! 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}; + +/// How long a finished request stays listed on the identity. +pub const OUTCOME_RETENTION: Duration = Duration::from_secs(30 * 24 * 60 * 60); + +/// 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, +} + +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 { .. }) + } +} + +/// 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 `label` can be requested. +/// +/// `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`. +pub fn classify_availability( + label: &str, + awarded: bool, + contest: Option<&ContestSnapshot>, + now: TimestampMillis, + durations: ContestDurations, +) -> UsernameAvailability { + if awarded { + return UsernameAvailability::Taken; + } + if let Some(contest) = contest { + 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, +} + +impl RequestPhase { + /// Whether the vote is still running. + pub fn is_pending(self) -> bool { + matches!(self, Self::Joinable | Self::Voting) + } +} + +/// 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, +} + +/// Whether the requester leads the tally. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TallyStanding { + /// More votes than any other request and than lock. + Leading, + /// Level with the strongest other choice. + Tied, + /// Another request or lock has more votes. + Trailing, +} + +impl RequestTally { + /// The requester's standing against the strongest other request or lock. + pub fn standing(&self) -> TallyStanding { + let best_other = self + .others + .iter() + .map(|(_, votes)| *votes) + .chain(std::iter::once(self.lock)) + .max() + .unwrap_or(0); + match self.you.cmp(&best_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)] +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, +} + +impl UsernameRequest { + /// A request just submitted at `now`, before the network reports its contest. + pub fn submitted(label: &str, now: TimestampMillis, durations: ContestDurations) -> Self { + Self { + label: label.to_owned(), + normalized_label: super::dpns::normalize_dpns_label(label), + phase: RequestPhase::Joinable, + requested_at: Some(now), + join_end: Some(now.saturating_add(duration_ms(durations.join))), + end: Some(now.saturating_add(duration_ms(durations.total))), + decided_at: None, + tally: RequestTally::default(), + last_updated: now, + } + } +} + +/// 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. `label` is the fallback 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 phase = match contest.winner { + Some(ContestWinner::Identity(winner)) if winner == identity_id => RequestPhase::Won, + Some(ContestWinner::Locked) => RequestPhase::Locked, + Some(_) => RequestPhase::Lost, + None => { + mine?; + let start = contest.started_at(); + let join_end = start.map(|s| s.saturating_add(duration_ms(durations.join))); + if join_end.is_some_and(|end| now < end) { + RequestPhase::Joinable + } else { + RequestPhase::Voting + } + } + }; + let start = contest.started_at(); + 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: start.map(|s| s.saturating_add(duration_ms(durations.join))), + end: end_time.or_else(|| start.map(|s| s.saturating_add(duration_ms(durations.total)))), + decided_at: contest.decided_at, + tally, + last_updated: now, + }) +} + +/// Combine a fresh read with what was stored before. +/// +/// 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. +pub fn merge_requests( + previous: &[UsernameRequest], + fresh: Vec, + now: TimestampMillis, +) -> 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.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)); + } + 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()); + } + } + let retention = duration_ms(OUTCOME_RETENTION); + merged.retain(|r| { + r.phase.is_pending() + || 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 available_when_nothing_exists_and_label_is_uncontested() { + // USR-TC-010 + assert_eq!( + classify_availability("alice2", false, None, 0, durations()), + UsernameAvailability::Available + ); + } + + #[test] + fn contested_label_without_contest_needs_vote() { + // USR-TC-011 + assert_eq!( + classify_availability("alice", false, None, 0, durations()), + UsernameAvailability::NeedsVote + ); + assert_eq!( + classify_availability( + "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( + "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( + "alice", + false, + Some(&contest), + 1_000 + 45 * MINUTE, + durations() + ), + UsernameAvailability::JoinClosed + ); + } + + #[test] + fn awarded_name_is_taken() { + // USR-TC-014 + assert_eq!( + classify_availability("alice", true, None, 0, durations()), + UsernameAvailability::Taken + ); + assert_eq!( + classify_availability("alice2", true, None, 0, durations()), + UsernameAvailability::Taken + ); + } + + #[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("alice", false, Some(&contest), 0, durations()), + UsernameAvailability::Locked + ); + } + + #[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, + ] { + 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))) + ); + } + + #[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, + }; + assert_eq!(tally(0, vec![], 0).standing(), TallyStanding::Tied); + assert_eq!(tally(5, vec![5], 0).standing(), TallyStanding::Tied); + assert_eq!(tally(5, vec![1], 6).standing(), TallyStanding::Trailing); + } + + 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, + } + } + + #[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) + .into_iter() + .map(|r| r.normalized_label) + .collect(); + assert_eq!(labels, ["b", "c", "recent"]); + } + + #[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); + 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/mod.rs b/src/model/mod.rs index cb1165442..818255d44 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -7,6 +7,7 @@ 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; diff --git a/src/ui/components/pill.rs b/src/ui/components/pill.rs index a64312a3f..1bd35d0da 100644 --- a/src/ui/components/pill.rs +++ b/src/ui/components/pill.rs @@ -6,7 +6,8 @@ //! 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, @@ -50,7 +51,7 @@ 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 /// 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, @@ -64,13 +65,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 +85,26 @@ 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, + }, + ); + 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 +117,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"), @@ -122,10 +130,7 @@ mod tests { #[test] fn pending_pill_renders_the_pending_label() { - let pending = PendingUsername { - name: "det1".to_string(), - decided_at: None, - }; + let pending = waiting(None); let mut harness = Harness::builder().build_ui(move |ui| { pending_username_pill(ui, &pending); }); diff --git a/src/ui/identity/home.rs b/src/ui/identity/home.rs index b3aaf306d..ad7b056c6 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 @@ -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); @@ -570,7 +570,7 @@ 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()); diff --git a/src/ui/identity/identity_hero_card.rs b/src/ui/identity/identity_hero_card.rs index 534c1d189..11b479da8 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; @@ -186,7 +186,7 @@ pub struct IdentityHeroCard { /// 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, + 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 @@ -539,9 +539,9 @@ 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 /// 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}")) @@ -724,11 +724,18 @@ 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, + }, + ); + request.label = name.to_string(); + request.end = None; + request } #[test] diff --git a/src/ui/identity/settings.rs b/src/ui/identity/settings.rs index 65475d4e8..f8d83d7af 100644 --- a/src/ui/identity/settings.rs +++ b/src/ui/identity/settings.rs @@ -496,7 +496,7 @@ impl SettingsTab { // "Pending" pill instead of the register CTA. ui.horizontal(|ui| { let name = crate::model::contested_name::sanitize_pending_username_for_display( - &pending.name, + &pending.label, ); ui.label( RichText::new(format!("@{name}")) From c9cba79b420e063defef5ce1d0eb24c690ea2e8e Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 16:45:19 +0000 Subject: [PATCH 066/194] =?UTF-8?q?feat(dpns):=20move=20voting=20into=20Ma?= =?UTF-8?q?sternodes=20=E2=96=B8=20Votes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Voting now lives in one panel hosted by the Masternodes screen behind a `Votes | Nodes` header (Votes first; opens on Votes while anything needs a vote, otherwise the last-used segment). Sub-views are To decide, Voted, Scheduled and History. Tools β–Έ DPNS and the DPNS sub-screen chooser are gone; persisted DPNS routes resolve to the matching Votes view and "My usernames" to the Identities hub. Hidden-screen routing now delivers every vote result and error to the panel while Masternodes is not visible. Adds the operator model (node sets, vote weight, changes left, influence, relative schedule, attention summary), per-network voting preferences, masternode-list membership from the SPV list, and a durable per-node Γ— poll count of applied votes that survives journal pruning. Co-Authored-By: Claude Opus 5.5 --- src/app.rs | 203 ++-- .../query_dpns_contested_resources.rs | 3 + src/backend_task/error.rs | 11 + src/context/dpns_vote_attention.rs | 294 ++++++ src/context/dpns_vote_operations/counts.rs | 191 ++++ src/context/dpns_vote_operations/mod.rs | 86 +- src/context/dpns_vote_preferences.rs | 110 ++ src/context/mod.rs | 10 + .../{dpns_voting.rs => dpns_voting/mod.rs} | 5 + src/model/dpns_voting/operator.rs | 645 ++++++++++++ .../dpns_subscreen_chooser_panel.rs | 48 - src/ui/components/left_panel.rs | 9 - src/ui/components/mod.rs | 1 - src/ui/components/styled.rs | 4 - .../tools_subscreen_chooser_panel.rs | 24 +- src/ui/dpns/dpns_contested_names_screen.rs | 945 ++++++------------ src/ui/dpns/mod.rs | 31 + src/ui/masternodes/list_screen.rs | 216 +++- src/ui/mod.rs | 115 ++- src/ui/tools/mod.rs | 2 - src/wallet_backend/mod.rs | 22 + tests/kittest/masternode_tab.rs | 108 +- 22 files changed, 2137 insertions(+), 946 deletions(-) create mode 100644 src/context/dpns_vote_attention.rs create mode 100644 src/context/dpns_vote_operations/counts.rs create mode 100644 src/context/dpns_vote_preferences.rs rename src/model/{dpns_voting.rs => dpns_voting/mod.rs} (99%) create mode 100644 src/model/dpns_voting/operator.rs delete mode 100644 src/ui/components/dpns_subscreen_chooser_panel.rs diff --git a/src/app.rs b/src/app.rs index 9e5b66bee..c89db9708 100644 --- a/src/app.rs +++ b/src/app.rs @@ -28,7 +28,6 @@ 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::identity::identity_pill::shorten_id; use crate::ui::network_chooser_screen::{NetworkChooserScreen, chooser_network_label}; use crate::ui::theme::ThemeMode; @@ -551,8 +550,11 @@ fn identity_hub_is_visible(selected: RootScreenType, screen_stack_is_empty: bool selected == RootScreenType::RootScreenIdentityHub && screen_stack_is_empty } -/// Every result `DPNSScreen::display_task_result` acts on, so that a DPNS root -/// screen receives it even while hidden. Dropping a variant here without +/// The root screen hosting the voting workspace (Masternodes β–Έ Votes). +const VOTING_ROOT_SCREEN: RootScreenType = RootScreenType::RootScreenMasternodes; + +/// Every result `DPNSScreen::display_task_result` acts on, so that the voting +/// panel receives it even while its root screen is hidden. Dropping a variant here without /// dropping its handler arm strands the screen in the state that result would /// have cleared. `dpns_result_routing_tests` reads the handler's source and /// fails if the two sets drift apart. @@ -561,7 +563,6 @@ fn is_dpns_vote_result(result: &BackendTaskSuccessResult) -> bool { result, BackendTaskSuccessResult::DpnsVoteOperationUpdated { .. } | BackendTaskSuccessResult::RefreshedDpnsContests - | BackendTaskSuccessResult::RefreshedOwnedDpnsNames | BackendTaskSuccessResult::ScheduledVoteSweepCompleted { .. } | BackendTaskSuccessResult::ScheduledVotesCleared(_) | BackendTaskSuccessResult::ScheduledVotesInProgress(_) @@ -2052,11 +2053,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); @@ -2080,22 +2076,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), @@ -2283,12 +2263,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. @@ -2762,26 +2749,24 @@ impl AppState { } } + /// 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, ) { - for root in [ - RootScreenType::RootScreenDPNSActiveContests, - RootScreenType::RootScreenDPNSScheduledVotes, - ] { - if dpns_result_needs_hidden_route( - root, - self.selected_main_screen, - self.screen_stack.is_empty(), - result, - ) && let Some(screen) = self.main_screens.get_mut(&root) - { - screen.display_backend_task_result(context, result.clone()); - if matches!(result, BackendTaskSuccessResult::RefreshedDpnsContests) { - screen.refresh(); - } + 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()); + if matches!(result, BackendTaskSuccessResult::RefreshedDpnsContests) { + votes.refresh(); } } } @@ -2794,19 +2779,15 @@ impl AppState { if !context.is_dpns_vote_task() { return; } - for root in [ - RootScreenType::RootScreenDPNSActiveContests, - RootScreenType::RootScreenDPNSScheduledVotes, - ] { - if dpns_screen_is_hidden( - root, - self.selected_main_screen, - self.screen_stack.is_empty(), - ) && let Some(screen) = self.main_screens.get_mut(&root) - { - screen.display_backend_task_error(context, error); - screen.display_task_error(error); - } + 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); } } @@ -2833,6 +2814,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; } @@ -2840,11 +2822,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 @@ -4477,63 +4475,60 @@ mod dpns_result_routing_tests { }; #[test] - fn voting_ui_results_route_to_each_hidden_dpns_screen_only_once() { + fn voting_ui_results_route_to_the_hidden_voting_panel_only_once() { let result = BackendTaskSuccessResult::ScheduledVoteSweepCompleted { network: Network::Testnet, preserve_eligibility_since_ms: None, }; - for root in [ - RootScreenType::RootScreenDPNSActiveContests, - RootScreenType::RootScreenDPNSScheduledVotes, - ] { - 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 - )); - } + 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_active_contests_is_hidden() { + 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( - RootScreenType::RootScreenDPNSActiveContests, + VOTING_ROOT_SCREEN, RootScreenType::RootScreenWalletsBalances, true, &result, )); assert!(dpns_result_needs_hidden_route( - RootScreenType::RootScreenDPNSActiveContests, - RootScreenType::RootScreenDPNSActiveContests, + VOTING_ROOT_SCREEN, + VOTING_ROOT_SCREEN, false, &result, )); assert!(!dpns_result_needs_hidden_route( - RootScreenType::RootScreenDPNSActiveContests, - RootScreenType::RootScreenDPNSActiveContests, + VOTING_ROOT_SCREEN, + VOTING_ROOT_SCREEN, true, &result, )); } #[test] - fn refreshed_contests_route_when_active_contests_is_hidden() { + fn refreshed_contests_route_when_masternodes_is_hidden() { assert!(dpns_result_needs_hidden_route( - RootScreenType::RootScreenDPNSActiveContests, + VOTING_ROOT_SCREEN, RootScreenType::RootScreenWalletsBalances, true, &BackendTaskSuccessResult::RefreshedDpnsContests, @@ -4541,37 +4536,37 @@ mod dpns_result_routing_tests { } #[test] - fn scheduled_vote_sweep_completion_routes_when_active_contests_is_hidden() { + 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( - RootScreenType::RootScreenDPNSActiveContests, + VOTING_ROOT_SCREEN, RootScreenType::RootScreenWalletsBalances, true, &result, )); assert!(dpns_result_needs_hidden_route( - RootScreenType::RootScreenDPNSActiveContests, - RootScreenType::RootScreenDPNSActiveContests, + VOTING_ROOT_SCREEN, + VOTING_ROOT_SCREEN, false, &result, )); assert!(!dpns_result_needs_hidden_route( - RootScreenType::RootScreenDPNSActiveContests, - RootScreenType::RootScreenDPNSActiveContests, + VOTING_ROOT_SCREEN, + VOTING_ROOT_SCREEN, true, &result, )); } #[test] - fn cleared_scheduled_votes_route_when_active_contests_is_hidden() { + fn cleared_scheduled_votes_route_when_masternodes_is_hidden() { assert!(dpns_result_needs_hidden_route( - RootScreenType::RootScreenDPNSActiveContests, - RootScreenType::RootScreenDPNSScheduledVotes, + VOTING_ROOT_SCREEN, + RootScreenType::RootScreenIdentityHub, true, &BackendTaskSuccessResult::ScheduledVotesCleared(Vec::new()), )); @@ -4627,7 +4622,6 @@ mod dpns_result_routing_tests { } "ScheduledVotesCleared" => BackendTaskSuccessResult::ScheduledVotesCleared(Vec::new()), "RefreshedDpnsContests" => BackendTaskSuccessResult::RefreshedDpnsContests, - "RefreshedOwnedDpnsNames" => BackendTaskSuccessResult::RefreshedOwnedDpnsNames, unknown => panic!( "DPNSScreen::display_task_result now handles {unknown}; add a sample here and route it in is_dpns_vote_result" ), @@ -4646,23 +4640,10 @@ mod dpns_result_routing_tests { } } - /// Refresh on My usernames, navigate away, come back: without routing, the - /// screen never clears `RefreshingStatus::Refreshing` and its Refresh - /// button stays inert. - #[test] - fn refreshed_owned_names_route_when_the_dpns_screen_is_hidden() { - assert!(dpns_result_needs_hidden_route( - RootScreenType::RootScreenDPNSActiveContests, - RootScreenType::RootScreenWalletsBalances, - true, - &BackendTaskSuccessResult::RefreshedOwnedDpnsNames, - )); - } - #[test] - fn scheduled_votes_in_progress_route_when_the_dpns_screen_is_hidden() { + fn scheduled_votes_in_progress_route_when_masternodes_is_hidden() { assert!(dpns_result_needs_hidden_route( - RootScreenType::RootScreenDPNSScheduledVotes, + VOTING_ROOT_SCREEN, RootScreenType::RootScreenWalletsBalances, true, &BackendTaskSuccessResult::ScheduledVotesInProgress(Vec::new()), @@ -4672,8 +4653,8 @@ mod dpns_result_routing_tests { /// The visibility rule both `route_dpns_vote_result_to_hidden_screens` and /// `route_dpns_vote_error_to_hidden_screens` route on. #[test] - fn a_dpns_screen_is_hidden_behind_another_root_screen_or_a_modal() { - let target = RootScreenType::RootScreenDPNSActiveContests; + 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)); 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 78d9bb40c..84714d4a8 100644 --- a/src/backend_task/contested_names/query_dpns_contested_resources.rs +++ b/src/backend_task/contested_names/query_dpns_contested_resources.rs @@ -227,6 +227,9 @@ impl AppContext { if let Err(error) = self.refresh_dpns_vote_states(sdk).await { tracing::warn!(?error, "Could not refresh DPNS current votes with contests"); } + self.refresh_masternode_list_membership().await; + self.forget_closed_dpns_vote_counts(); + self.recompute_dpns_vote_attention(); self.refresh_pending_dpns_usernames()?; sender diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 177832f0c..58a8e0d59 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -862,6 +862,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 diff --git a/src/context/dpns_vote_attention.rs b/src/context/dpns_vote_attention.rs new file mode 100644 index 000000000..51b4c51fd --- /dev/null +++ b/src/context/dpns_vote_attention.rs @@ -0,0 +1,294 @@ +//! 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, VotingNode, VotingNodeKind, + changes_left, contest_needs_decision, +}; +use crate::model::dpns_voting::{ + DpnsCurrentVoteState, DpnsVoteOperation, DpnsVotePollAvailability, DpnsVoteTargetKey, + DpnsVoteTargetStatus, authoritative_dpns_vote_outcome, dpns_vote_lock_holders, + dpns_vote_poll_availability, +}; +use crate::model::qualified_identity::IdentityType; +use crate::utils::time::now_ms; +use dash_sdk::dpp::identity::accessors::IdentityGettersV0; +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 { + let keys: BTreeSet<&DpnsVoteTargetKey> = operations + .iter() + .flat_map(|operation| operation.targets.iter().map(|outcome| &outcome.target.key)) + .collect(); + keys.into_iter() + .filter(|key| { + authoritative_dpns_vote_outcome(operations, key) + .is_some_and(|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), + ) + } + + /// 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 now = now_ms(); + let closed: BTreeSet = self + .all_contested_names() + .unwrap_or_default() + .iter() + .filter(|contest| { + dpns_vote_poll_availability(Some(contest), now) + == 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, + } + } + + /// 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()? + .into_iter() + .map(|identity| { + let id = identity.identity.id(); + VotingNode { + id, + kind: if identity.identity_type == IdentityType::Evonode { + VotingNodeKind::Evonode + } else { + VotingNodeKind::Masternode + }, + has_voting_key: identity.can_cast_masternode_vote(), + membership: self.masternode_list_membership(id), + } + }) + .collect()) + } + + /// 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 { + match self.compute_dpns_vote_attention() { + 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) -> Result { + let resolved = self + .saved_dpns_node_set() + .unwrap_or_default() + .resolve(&self.dpns_voting_nodes()?); + 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 operations = self.dpns_vote_operations()?; + let polls: Vec = contests.iter().map(|(_, _, poll)| *poll).collect(); + let mut states = BTreeMap::new(); + for voter in &resolved.included { + let voter_states = self + .dpns_current_vote_states(*voter, polls.iter().copied()) + .unwrap_or_default(); + states.insert(*voter, voter_states); + } + + let network = self.network(); + let attention: Vec = contests + .into_iter() + .map(|(name, end_time, poll)| { + let needs_decision = + contest_needs_decision(resolved.included.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(); + Ok(AttentionSummary::new( + &attention, + unresolved_target_count(&operations), + )) + } +} + +#[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 = DpnsVoteOperation::new(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 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..f70e7fd93 --- /dev/null +++ b/src/context/dpns_vote_operations/counts.rs @@ -0,0 +1,191 @@ +//! 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, 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:"; + +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)) +} + +/// 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 one spent vote for `key`. Callers hold the journal guard and bump +/// before persisting the transition: a crash in between over-counts, which +/// understates changes left instead of overstating them. +pub(super) fn bump_vote_count(kv: &DetKv, key: &DpnsVoteTargetKey) -> Result<(), TaskError> { + 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) +} + +/// 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 prefix = count_key_prefix(network); + let suffixes: Vec = closed_polls.iter().map(|poll| format!(":{poll}")).collect(); + let mut removed = 0; + 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 += 1; + } + } + Ok(removed) +} + +#[cfg(test)] +mod tests { + use super::*; + 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 = DpnsVoteOperation::new(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 _ in 0..3 { + bump_vote_count(&kv, &key(2)).unwrap(); + } + bump_vote_count(&kv, &key(3)).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!( + 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/mod.rs b/src/context/dpns_vote_operations/mod.rs index aa6286aae..8697f50fc 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -1,5 +1,6 @@ //! Durable DPNS vote operation journal and exact-target lock registry. +mod counts; mod keys; mod retention; mod transitions; @@ -223,10 +224,21 @@ fn persist_operation( return Err(TaskError::DpnsVoteJournalNetworkMismatch); } let complete = operation.is_complete(); - let newly_complete = complete - && kv - .get::(DetScope::Global, &operation_key(network, operation.id)) + // 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 { + kv.get::(DetScope::Global, &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)?; let previous_locks = locks.clone(); @@ -245,6 +257,10 @@ fn persist_operation( locks.insert(outcome.target.key.clone(), operation.id); } + for key in counts::newly_spent_targets(previous.as_ref(), operation) { + counts::bump_vote_count(kv, key)?; + } + let mut ids = load_operation_ids(kv, network)?; let new_operation = !ids.contains(&operation.id.to_bytes()); let locks_changed = locks != previous_locks; @@ -627,6 +643,26 @@ impl AppContext { Ok(()) } + /// 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, @@ -1900,6 +1936,50 @@ mod tests { ); } + /// 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" + ); + } + #[test] fn persisted_lock_index_avoids_full_journal_reads_on_transition() { let store = Arc::new(CountingKv::default()); 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/mod.rs b/src/context/mod.rs index e43a830eb..dada70a72 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -1,7 +1,9 @@ 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; pub(crate) use dpns_vote_state::DpnsVoteRefreshResults; pub mod feature_gate; @@ -198,6 +200,12 @@ pub struct AppContext { /// Frame-safe pending DPNS names rebuilt after the contest cache changes. pending_dpns_usernames: 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>>>, /// 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 @@ -566,6 +574,8 @@ impl AppContext { animations_disabled: AtomicBool::new(false), cached_settings: RwLock::new(None), pending_dpns_usernames: RwLock::new(HashMap::new()), + dpns_vote_attention: RwLock::new(Default::default()), + masternode_list_membership: RwLock::new(None), app_kv, #[cfg(test)] det_kv_override: Mutex::new(None), diff --git a/src/model/dpns_voting.rs b/src/model/dpns_voting/mod.rs similarity index 99% rename from src/model/dpns_voting.rs rename to src/model/dpns_voting/mod.rs index 3bec03bbb..b5e787d2a 100644 --- a/src/model/dpns_voting.rs +++ b/src/model/dpns_voting/mod.rs @@ -13,6 +13,8 @@ use dash_sdk::platform::Identifier; use serde::{Deserialize, Serialize}; use std::fmt; +pub mod operator; + /// Grace period for admitting a scheduled vote to automatic execution. pub const SCHEDULED_VOTE_MAX_LATENESS_MS: u64 = 120_000; @@ -236,6 +238,9 @@ pub enum DpnsVoteFailure { SubmissionFailed, CurrentVoteUnavailable, ResultUnconfirmed, + /// The contest closed before the target was submitted. Appended last: + /// journal records are positionally encoded. + VotingEnded, } /// Lifecycle of one target. diff --git a/src/model/dpns_voting/operator.rs b/src/model/dpns_voting/operator.rs new file mode 100644 index 000000000..f70dc566e --- /dev/null +++ b/src/model/dpns_voting/operator.rs @@ -0,0 +1,645 @@ +//! 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 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, +} + +/// 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 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 + } +} + +/// 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 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, +} + +/// 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 ranked.len() > 1 && top_votes == runner_up && lock_votes <= top_votes { + return Some(Influence::Tied); + } + 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 }) +} + +/// 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) +} + +/// 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), + } +} + +/// 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)>, +} + +impl AttentionSummary { + /// Build the summary from open contests and the unresolved-target count. + pub fn new(contests: &[ContestAttention], unresolved: 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(), + } + } + + /// 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, + } + } + + 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. + #[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 + }) + ); + } + + /// 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(&[(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) + ); + } + + #[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, + ); + assert_eq!(summary.needs_decision, 4); + 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/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/left_panel.rs b/src/ui/components/left_panel.rs index 979d9ed69..92316a85d 100644 --- a/src/ui/components/left_panel.rs +++ b/src/ui/components/left_panel.rs @@ -189,15 +189,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, }; diff --git a/src/ui/components/mod.rs b/src/ui/components/mod.rs index 6a7cbff8a..c3c26806e 100644 --- a/src/ui/components/mod.rs +++ b/src/ui/components/mod.rs @@ -7,7 +7,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; 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/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index ffa3de5b1..bed59c329 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -11,13 +11,12 @@ 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 crate::app::{AppAction, DesiredAppAction, scheduled_vote_sweep_is_quiet}; +use crate::app::{AppAction, scheduled_vote_sweep_is_quiet}; use crate::backend_task::contested_names::ContestedResourceTask; 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}; @@ -27,32 +26,19 @@ use crate::model::dpns_voting::{ DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, dpns_schedule_is_overdue, validate_dpns_schedule_time, }; -use crate::model::qualified_identity::{DPNSNameInfo, QualifiedIdentity}; +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::dpns_subscreen_chooser_panel::add_dpns_subscreen_chooser_panel; -use crate::ui::components::left_panel::add_left_panel; use crate::ui::components::progress_overlay::{OptionOverlayExt, OverlayConfig, OverlayHandle}; -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::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::state::dpns_contests::{ActiveDpnsContestSnapshot, ActiveDpnsContestView}; use crate::ui::state::dpns_vote_operations::{DpnsVoteOperationSnapshot, ScheduledDpnsVoteRow}; 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}; -/// Which DPNS sub-screen is currently showing. -#[derive(PartialEq)] -pub enum DPNSSubscreen { - Active, - Past, - Owned, - ScheduledVotes, -} +pub use super::VotesView; /// Active contests bucketed by what the loaded nodes can do with them. /// @@ -88,7 +74,15 @@ impl ActiveContestGroup { Self::NeedsVote => "Needs your vote", Self::Voted => "Voted", Self::VoteStateUnavailable => "Vote state unavailable", - Self::NotVotable => "Not votable by your nodes", + Self::NotVotable => "Can't vote with your nodes", + } + } + + /// The Votes sub-view that lists this group. + fn view(self) -> VotesView { + match self { + Self::Voted => VotesView::Voted, + Self::NeedsVote | Self::VoteStateUnavailable | Self::NotVotable => VotesView::ToDecide, } } @@ -120,10 +114,12 @@ impl ActiveContestGroup { } } +const NO_OPEN_CONTESTS_MESSAGE: &str = + "There are no open name contests right now. New contests appear here automatically."; const NO_VOTING_NODES_MESSAGE: &str = "None of your loaded nodes has a voting key."; const NO_VOTING_NODES_DETAIL: &str = "Load a masternode with its voting key to cast votes."; const JOURNAL_UNAVAILABLE_MESSAGE: &str = "Saved voting progress could not be read. The displayed history may be incomplete or out of date. Retry loading before managing votes."; -const MISSED_SCHEDULE_GUIDANCE: &str = "The automatic voting time was missed. In Scheduled Votes, use Cast now to vote, Edit to reschedule, or Remove to cancel."; +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."; @@ -299,12 +295,14 @@ fn scheduled_failure_guidance( } match failure? { DpnsVoteFailure::CurrentVoteUnavailable => Some( - "Current vote could not be verified. In Scheduled Votes, use Cast now to check again or Edit to reschedule.", + "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 in Scheduled Votes.", + "The vote could not be submitted. Check your connection and voting key, then use Cast now or Edit on the Scheduled tab.", ), - DpnsVoteFailure::PlatformRejected | DpnsVoteFailure::ResultUnconfirmed => None, + DpnsVoteFailure::PlatformRejected + | DpnsVoteFailure::ResultUnconfirmed + | DpnsVoteFailure::VotingEnded => None, } } @@ -445,7 +443,7 @@ pub enum ReviewPlanError { ScheduleIsNotAValidTime, #[error("Choose a future time before the contest ends for {contested_name}.dash.")] ScheduleOutlastsContest { contested_name: String }, - #[error("This vote could not be prepared. Refresh Active contests and try again.")] + #[error("This vote could not be prepared. Refresh the contests and try again.")] VotePollUnavailable { #[source] source: Arc, @@ -494,17 +492,6 @@ fn dpns_operation_id( } } -impl DPNSSubscreen { - pub fn display_name(&self) -> &'static str { - match self { - Self::Active => "Active contests", - Self::Past => "Past contests", - Self::Owned => "My usernames", - Self::ScheduledVotes => "Scheduled votes", - } - } -} - /// Minimal object for storing the user’s currently selected vote on a single contested name. #[derive(Clone, Debug, PartialEq)] pub struct SelectedVote { @@ -555,21 +542,18 @@ 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, voting_identity_load_error: Option, - user_identities: Vec, contested_names: Arc>>, 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, - local_dpns_names: Arc>>, scheduled_votes: Arc>>, pub selected_votes: Vec, pub app_context: Arc, @@ -588,10 +572,9 @@ pub struct DPNSScreen { 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, @@ -605,42 +588,31 @@ pub struct DPNSScreen { /// Eagerly built, unlike most components: its default is the construction /// time plus a day, and the read-only accessors below must see it. simple_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, } impl DPNSScreen { - pub fn new(app_context: &Arc, dpns_subscreen: DPNSSubscreen) -> Self { + pub fn new(app_context: &Arc, view: VotesView) -> Self { let vote_operations = DpnsVoteOperationSnapshot::load(app_context); let legacy_scheduled_votes = app_context.get_scheduled_votes().unwrap_or_default(); let scheduled_votes = Arc::new(Mutex::new( vote_operations.scheduled_vote_rows(&legacy_scheduled_votes), )); - // Load contested names, local dpns, scheduled, etc.: - let contested_names = Arc::new(Mutex::new(match dpns_subscreen { - DPNSSubscreen::Active => Vec::new(), - DPNSSubscreen::Past => app_context.all_contested_names().unwrap_or_default(), - DPNSSubscreen::Owned => Vec::new(), - DPNSSubscreen::ScheduledVotes => app_context.all_contested_names().unwrap_or_default(), - })); - let active_contests = if dpns_subscreen == DPNSSubscreen::Active { - ActiveDpnsContestSnapshot::new( - app_context, - app_context.ongoing_contested_names().unwrap_or_default(), - ) - } else { - ActiveDpnsContestSnapshot::default() - }; + // 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 candidate_names = candidate_name_index(&active_contests, &contested_names.lock_recover()); - 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 (voting_identities, voting_identity_load_error) = match loaded_voting_identities(app_context) { Ok(identities) => (identities, None), @@ -649,7 +621,6 @@ impl DPNSScreen { (Vec::new(), Some(error)) } }; - let user_identities = app_context.load_local_user_identities().unwrap_or_default(); let vote_poll_ids = active_contests.vote_poll_ids(); let voter_ids = voting_identities .iter() @@ -668,11 +639,9 @@ impl DPNSScreen { Self { voting_identities, voting_identity_load_error, - user_identities, contested_names, active_contests, candidate_names, - local_dpns_names, scheduled_votes, selected_votes: Vec::new(), app_context: app_context.clone(), @@ -680,7 +649,6 @@ impl DPNSScreen { sort_order: SortOrder::Ascending, active_filter_term: String::new(), past_filter_term: String::new(), - owned_filter_term: String::new(), pending_backend_task: None, vote_operations, vote_state, @@ -690,7 +658,7 @@ impl DPNSScreen { clear_vote_overlay_on_error: false, scheduled_clear_dialog: None, scheduled_vote_editor: None, - dpns_subscreen, + view, refreshing_status: RefreshingStatus::NotRefreshing, refresh_banner: None, journal_error_banner: None, @@ -702,9 +670,15 @@ impl DPNSScreen { submission_error_banner: None, set_all_option: VoteOption::CastNow, simple_schedule: UtcScheduleInput::new().with_time(default_schedule_time), + load_node_requested: false, } } + /// 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 @@ -741,14 +715,12 @@ impl DPNSScreen { self.refreshing_status = RefreshingStatus::NotRefreshing; self.voting_identities.clear(); self.voting_identity_load_error = None; - self.user_identities.clear(); 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.local_dpns_names.lock_recover().clear(); } // --------------------------- @@ -787,8 +759,8 @@ impl DPNSScreen { // --------------------------- // Rendering: Empty states // --------------------------- - fn render_no_voting_nodes(&self, ui: &mut Ui) -> AppAction { - let mut action = AppAction::None; + fn render_no_voting_nodes(&mut self, ui: &mut Ui) -> AppAction { + let action = AppAction::None; let dark_mode = ui.style().visuals.dark_mode; ui.vertical_centered(|ui| { ui.add_space(24.0); @@ -806,7 +778,7 @@ impl DPNSScreen { ); ui.add_space(12.0); if ComponentStyles::add_primary_button(ui, "Load a masternode").clicked() { - action = AppAction::SetMainScreen(RootScreenType::RootScreenMasternodes); + self.load_node_requested = true; } }); }); @@ -814,86 +786,48 @@ impl DPNSScreen { action } - fn render_no_active_contests_or_owned_names(&mut self, ui: &mut Ui) -> AppAction { + 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); - match self.dpns_subscreen { - DPNSSubscreen::Active => { - ui.label( - egui::RichText::new("No active contests at the moment.") - .heading() - .strong() - .color(Color32::GRAY), - ); - } - 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.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))); } - ui.add_space(10.0); - - 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))); + 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() + { + self.refreshing_status = RefreshingStatus::Refreshing; + 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("Choose votes on the Active contests screen, then use Review and cast to schedule them.").color(text_color) - ); } }); - app_action } // --------------------------- - // Rendering: Active, Past, Owned, Scheduled + // Rendering: To decide, Voted, Scheduled, History // --------------------------- /// Render active contests as decision cards grouped by what the loaded nodes can do. @@ -957,10 +891,14 @@ impl DPNSScreen { } let no_voting_nodes = self.voting_identities.is_empty(); + let view = self.view; egui::ScrollArea::vertical() .id_salt("active_contest_cards") .show(ui, |ui| { - for group in ActiveContestGroup::ALL { + for group in ActiveContestGroup::ALL + .into_iter() + .filter(|group| group.view() == view) + { let contests = groups.get(&group).map_or(&[][..], Vec::as_slice); if group == ActiveContestGroup::VoteStateUnavailable { if contests.is_empty() { @@ -1545,159 +1483,6 @@ impl DPNSScreen { }); } - /// 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 - } - } - _ => std::cmp::Ordering::Equal, - }); - - // 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().resizable(true)) // Actions - .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| { - let dark_mode = ui.style().visuals.dark_mode; - ui.label( - RichText::new("Actions").color(DashColors::text_primary(dark_mode)), - ); - }); - }) - .body(|mut body| { - for (identifier, dpns_info) in filtered_names { - let name_for_alias = dpns_info.name.clone(); - // Display name with .dash suffix - let display_name = if name_for_alias.ends_with(".dash") { - name_for_alias.clone() - } else { - format!("{name}.dash", name = name_for_alias) - }; - body.row(25.0, |mut row| { - row.col(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - ui.label( - RichText::new(&display_name) - .color(DashColors::text_primary(dark_mode)), - ); - }); - 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)), - ); - }); - 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)), - ); - }); - row.col(|ui| { - if ui.small_button("Set Alias").clicked() { - // Append .dash suffix for DPNS names - let alias_with_suffix = if name_for_alias.ends_with(".dash") { - name_for_alias.clone() - } else { - format!("{name}.dash", name = name_for_alias) - }; - if let Err(e) = self - .app_context - .set_identity_alias(&identifier, Some(&alias_with_suffix)) - { - MessageBanner::set_global( - ui.ctx(), - "The alias could not be saved. Check available disk space and try again.", - MessageType::Error, - ) - .with_details(e); - } else { - MessageBanner::set_global( - ui.ctx(), - format!( - "Alias set to '{alias}' for identity {identity_id}", - alias = alias_with_suffix, - identity_id = identifier.to_string(Encoding::Base58) - ), - MessageType::Success, - ); - } - } - }); - }); - } - }); - }); - } - /// Show the Scheduled Votes table fn render_table_scheduled_votes(&mut self, ui: &mut Ui) -> AppAction { let mut action = AppAction::None; @@ -1991,7 +1776,7 @@ impl DPNSScreen { ui.add_space(10.0); ui.horizontal(|ui| { if ComponentStyles::add_primary_button(ui, "Load a masternode").clicked() { - action = AppAction::SetMainScreen(RootScreenType::RootScreenMasternodes); + self.load_node_requested = true; self.show_bulk_schedule_popup = false; } if ComponentStyles::add_secondary_button(ui, "Close", dark_mode).clicked() { @@ -2005,12 +1790,10 @@ impl DPNSScreen { ui.add_space(5.0); ui.colored_label( DashColors::warning_color(dark_mode), - "No votes are ready to review. Choose at least one vote on Active contests, then try again.", + "No votes are ready to review. Choose at least one vote in To decide, then try again.", ); ui.add_space(10.0); - if ComponentStyles::add_secondary_button(ui, "Back to Active contests", dark_mode) - .clicked() - { + if ComponentStyles::add_secondary_button(ui, "Back to To decide", dark_mode).clicked() { self.show_bulk_schedule_popup = false; } return action; @@ -2544,7 +2327,7 @@ impl DPNSScreen { 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() { + if ComponentStyles::add_primary_button(ui, "Back to To decide").clicked() { self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; self.show_bulk_schedule_popup = false; action = AppAction::BackendTask(BackendTask::ContestedResourceTask( @@ -2552,14 +2335,12 @@ impl DPNSScreen { )) } ui.add_space(5.0); - if ComponentStyles::add_secondary_button(ui, "Go to Scheduled Votes Screen", dark_mode) + if ComponentStyles::add_secondary_button(ui, "Show scheduled votes", dark_mode) .clicked() { self.show_bulk_schedule_popup = false; self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; - action = AppAction::SetMainScreenThenPopScreen( - RootScreenType::RootScreenDPNSScheduledVotes, - ); + self.view = VotesView::Scheduled; } }); @@ -2577,28 +2358,14 @@ impl ScreenLike for DPNSScreen { } self.rebuild_scheduled_vote_rows(); - match self.dpns_subscreen { - DPNSSubscreen::Active => { - self.active_contests = ActiveDpnsContestSnapshot::new( - &self.app_context, - self.app_context - .ongoing_contested_names() - .unwrap_or_default(), - ); - } - DPNSSubscreen::Past => { - *self.contested_names.lock_recover() = - self.app_context.all_contested_names().unwrap_or_default(); - } - DPNSSubscreen::Owned => { - *self.local_dpns_names.lock_recover() = - self.app_context.local_dpns_names().unwrap_or_default(); - } - DPNSSubscreen::ScheduledVotes => { - *self.contested_names.lock_recover() = - self.app_context.all_contested_names().unwrap_or_default(); - } - } + 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 @@ -2649,10 +2416,6 @@ impl ScreenLike for DPNSScreen { }) }) .collect(); - self.user_identities = self - .app_context - .load_local_user_identities() - .unwrap_or_default(); self.refresh(); } @@ -2767,8 +2530,7 @@ impl ScreenLike for DPNSScreen { } self.rebuild_scheduled_vote_rows(); } - BackendTaskSuccessResult::RefreshedDpnsContests - | BackendTaskSuccessResult::RefreshedOwnedDpnsNames => { + BackendTaskSuccessResult::RefreshedDpnsContests => { self.refresh_banner.take_and_clear(); self.refreshing_status = RefreshingStatus::NotRefreshing; } @@ -2776,293 +2538,196 @@ impl ScreenLike for DPNSScreen { } } + /// 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 { let ctx = ui.ctx().clone(); let ctx = &ctx; - let has_identity_that_can_register = !self.user_identities.is_empty(); - // 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, - ))), - ); - 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::Custom("Clear all scheduled votes".to_owned()), - ), - ( - "Clear Completed", - DesiredAppAction::Custom("Clear completed scheduled votes".to_owned()), - ), - ] - } - }; - - 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, - ))), - ), - ); - } - - // 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, - ); - if action == AppAction::Custom("Clear all scheduled votes".to_owned()) { - self.scheduled_clear_dialog = Some(( - true, - ConfirmationDialog::new( - "Clear all scheduled votes", - "Remove every scheduled vote from this device? Votes already submitted to Platform cannot be undone.", - ) - .danger_mode(true) - .confirm_text(Some("Clear all scheduled votes")), - )); - action = AppAction::None; - } else if action == AppAction::Custom("Clear completed scheduled votes".to_owned()) { - self.scheduled_clear_dialog = Some(( - false, - ConfirmationDialog::new( - "Clear completed scheduled votes", - "Remove every completed scheduled vote from this device? Pending votes will stay scheduled.", - ) - .danger_mode(true) - .confirm_text(Some("Clear completed scheduled votes")), - )); - action = AppAction::None; - } - - // Left panel - action |= add_left_panel( - ui, - &self.app_context, - RootScreenType::RootScreenToolsPlatformInfoScreen, - ); + let mut action = AppAction::None; - // 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; - 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); - } + ui.horizontal(|ui| { + for view in VotesView::ALL { + if ui.selectable_label(self.view == view, view.label()).clicked() { + self.view = view; } - // 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); + } + 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, + )); + } + } } - if ComponentStyles::add_secondary_button( - ui, - "Retry loading", - ui.visuals().dark_mode, - ) - .clicked() - { - self.refresh(); + }); + }); + 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); } - 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 + // 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() { - let clear_all = *clear_all; - self.scheduled_clear_dialog = None; - if status == ConfirmationStatus::Confirmed { - inner_action = - AppAction::BackendTask(BackendTask::ContestedResourceTask(if clear_all { - ContestedResourceTask::ClearAllScheduledVotes - } else { - ContestedResourceTask::ClearExecutedScheduledVotes - })); - } + ui.label(JOURNAL_UNAVAILABLE_MESSAGE); } - 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()); - inner_action = AppAction::BackendTaskWithContext { task, context }; - self.scheduled_vote_editor = None; - self.raise_vote_overlay(ui.ctx(), "Saving the scheduled vote…"); - } - } + if ComponentStyles::add_secondary_button(ui, "Retry loading", ui.visuals().dark_mode) + .clicked() + { + self.refresh(); } - // Bulk-schedule ephemeral popup - if self.show_bulk_schedule_popup { - egui::Window::new("Review and cast") - .collapsible(false) - .resizable(true) - .vscroll(true) - .show(ui.ctx(), |ui| { - inner_action |= self.show_review_and_cast_window(ui); - }); + 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 self.voting_identity_load_error.is_some() && !self.show_bulk_schedule_popup { - self.render_voting_identity_load_error(ui); + } + 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; + self.raise_vote_overlay(ui.ctx(), "Saving the scheduled vote…"); + } } - // Render sub-screen - match self.dpns_subscreen { - DPNSSubscreen::Active => { - let has_any = !self.active_contests.is_empty(); - if self.voting_identities.is_empty() - && self.voting_identity_load_error.is_none() - { - inner_action |= self.render_no_voting_nodes(ui); - } - if has_any { - self.render_active_contests(ui); - } else { - inner_action |= self.render_no_active_contests_or_owned_names(ui); - egui::ScrollArea::vertical() - .id_salt("voting_activity_without_contests") - .show(ui, |ui| self.render_voting_activity(ui)); - } + } + if self.show_bulk_schedule_popup { + egui::Window::new("Review and cast") + .collapsible(false) + .resizable(true) + .vscroll(true) + .show(ui.ctx(), |ui| { + action |= self.show_review_and_cast_window(ui); + }); + } + + if self.voting_identity_load_error.is_some() && !self.show_bulk_schedule_popup { + 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() { + action |= self.render_no_voting_nodes(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); - } + if self.active_contests.is_empty() { + action |= self.render_empty_view(ui); + egui::ScrollArea::vertical() + .id_salt("voting_activity_without_contests") + .show(ui, |ui| self.render_voting_activity(ui)); + } else { + self.render_active_contests(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); - } + } + VotesView::History => { + if self.contested_names.lock_recover().is_empty() { + action |= self.render_empty_view(ui); + } else { + self.render_table_past_contests(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); - } + } + VotesView::Scheduled => { + if self.scheduled_votes.lock_recover().is_empty() { + action |= self.render_empty_view(ui); + } else { + action |= self.render_table_scheduled_votes(ui); } } + } - // Refreshing indicator is shown via the global banner - // (no inline elapsed rendering needed) - inner_action - }); - - // 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; - } - _ => {} + 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 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() + && let Some(task) = self.pending_backend_task.take() { - action = AppAction::BackendTask(bt); + action = AppAction::BackendTask(task); } action } @@ -3185,7 +2850,7 @@ mod tests { #[test] fn vote_submission_overlay_clears_when_the_operation_finishes() { let (ctx, _temp_dir) = offline_ctx(); - let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); screen.raise_vote_overlay( ctx.egui_ctx(), @@ -3235,7 +2900,7 @@ mod tests { ctx.cache_confirmed_dpns_vote(voter, poll, old_choice) .expect("seed old proved choice"); - let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); screen.vote_state = DpnsVoteStateSnapshot::load(&ctx, &[voter], &[poll]) .expect("load initial proved choice"); assert_eq!( @@ -3348,7 +3013,7 @@ mod tests { 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, DPNSSubscreen::ScheduledVotes); + 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")); @@ -3408,7 +3073,7 @@ mod tests { #[test] fn scheduled_vote_sweep_error_preserves_unrelated_manual_cast() { let (ctx, _temp_dir) = offline_ctx(); - let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::ScheduledVotes); + let mut screen = DPNSScreen::new(&ctx, VotesView::Scheduled); let error = TaskError::ScheduledVoteSweepFailed { network: Network::Regtest, source: Box::new(TaskError::NoVotingIdentity { @@ -3426,7 +3091,7 @@ mod tests { #[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); + let mut screen = DPNSScreen::new(&ctx, VotesView::Scheduled); screen .pending_scheduled_actions @@ -3548,7 +3213,7 @@ mod tests { #[test] fn failed_submission_releases_the_review_window() { let (ctx, _temp_dir) = offline_ctx(); - let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); let operation_id = DpnsVoteOperationId::from_bytes([11; 16]); let context = BackendTaskContext::DpnsVoteOperation { network: ctx.network(), @@ -3592,7 +3257,7 @@ mod tests { #[test] fn unrelated_error_keeps_the_pending_submission_in_progress() { let (ctx, _temp_dir) = offline_ctx(); - let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); let error = TaskError::DpnsCurrentVoteUnavailable; screen.show_bulk_schedule_popup = true; screen.bulk_vote_handling_status = VoteHandlingStatus::CastingVotes; @@ -3629,7 +3294,7 @@ mod tests { ) .expect("insert keyless masternode"); - let screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); + let screen = DPNSScreen::new(&ctx, VotesView::ToDecide); assert!( !ctx.load_local_voting_identities() @@ -3652,7 +3317,7 @@ mod tests { ) .expect("insert voting masternode"); - let screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); + let screen = DPNSScreen::new(&ctx, VotesView::ToDecide); assert_eq!(screen.voting_identities.len(), 1); } @@ -3663,7 +3328,7 @@ mod tests { 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, DPNSSubscreen::Active); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); screen.voting_identities = vec![voter.clone()]; screen.bulk_identity_options = vec![VoteOption::CastNow]; screen.selected_votes = vec![SelectedVote { @@ -3689,7 +3354,7 @@ mod tests { .app_context .insert_dpns_vote_operation(&mut operation, None) .unwrap(); - let mut reopened = DPNSScreen::new(&screen.app_context, DPNSSubscreen::Active); + 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)) @@ -3718,7 +3383,7 @@ mod tests { .app_context .insert_dpns_vote_operation(&mut operation, None) .unwrap(); - let mut reopened = DPNSScreen::new(&screen.app_context, DPNSSubscreen::ScheduledVotes); + 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| { @@ -3730,7 +3395,7 @@ mod tests { status == DpnsVoteTargetStatus::Scheduled ); if status == DpnsVoteTargetStatus::Scheduled { - assert!(harness.query_by_label("The automatic voting time was missed. In Scheduled Votes, use Cast now to vote, Edit to reschedule, or Remove to cancel.").is_some()); + 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()); } @@ -3749,7 +3414,7 @@ mod tests { if fail_at_construction { store.fail_next_gets_containing("det:dpns_vote_operations:v2:", 1); } - let mut screen = DPNSScreen::new(&context, DPNSSubscreen::ScheduledVotes); + 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(); @@ -3759,7 +3424,11 @@ mod tests { let mut harness = egui_kittest::Harness::builder() .with_size(egui::vec2(1600.0, 1200.0)) .build_ui(move |ui| { - rendering.lock_recover().ui(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. Retry loading before managing votes."; @@ -3786,11 +3455,11 @@ mod tests { for (failure, reason) in [ ( DpnsVoteFailure::CurrentVoteUnavailable, - "Current vote could not be verified. In Scheduled Votes, use Cast now to check again or Edit to reschedule.", + "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 in Scheduled Votes.", + "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(); @@ -3804,8 +3473,8 @@ mod tests { .app_context .insert_dpns_vote_operation(&mut operation, None) .unwrap(); - for subscreen in [DPNSSubscreen::ScheduledVotes, DPNSSubscreen::Active] { - let scheduled = subscreen == DPNSSubscreen::ScheduledVotes; + for subscreen in [VotesView::Scheduled, VotesView::ToDecide] { + let scheduled = subscreen == VotesView::Scheduled; let mut reopened = DPNSScreen::new(&screen.app_context, subscreen); let mut harness = egui_kittest::Harness::builder() .with_size(egui::vec2(1600.0, 1200.0)) @@ -3841,7 +3510,7 @@ mod tests { .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, DPNSSubscreen::Active); + 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!( @@ -3874,7 +3543,7 @@ mod tests { context .cache_confirmed_dpns_vote(voter, other, ResourceVoteChoice::Lock) .unwrap(); - let mut screen = DPNSScreen::new(&context, DPNSSubscreen::Active); + let mut screen = DPNSScreen::new(&context, VotesView::ToDecide); screen .vote_state .refresh(&context, &[voter], &[poll, other]) @@ -4131,7 +3800,7 @@ mod tests { 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, DPNSSubscreen::Active); + let mut screen = DPNSScreen::new(&context, VotesView::ToDecide); screen.active_contests = ActiveDpnsContestSnapshot::new( &context, vec![ContestedName { @@ -4170,7 +3839,7 @@ mod tests { store.fail_all_reads(true); assert!(loaded_voting_identities(&context).is_err()); for reviewing in [false, true] { - let mut screen = DPNSScreen::new(&context, DPNSSubscreen::Active); + let mut screen = DPNSScreen::new(&context, VotesView::ToDecide); assert!(screen.voting_identity_load_error.is_some()); screen.show_bulk_schedule_popup = reviewing; let mut harness = egui_kittest::Harness::builder().build_ui(move |ui| { @@ -4189,7 +3858,7 @@ mod tests { 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, DPNSSubscreen::Active); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); screen.selected_votes = vec![SelectedVote { contested_name: "alpha".into(), vote_choice: ResourceVoteChoice::Lock, @@ -4337,12 +4006,10 @@ mod tests { Network::Regtest, ); assert_ne!(screen.app_context.network(), new_context.network()); - let mut wrapper = crate::ui::Screen::DPNSScreen(screen); - wrapper.change_context(new_context); - wrapper.refresh_on_arrival(); - let crate::ui::Screen::DPNSScreen(screen) = wrapper else { - unreachable!() - }; + // 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.show_bulk_schedule_popup); assert!(screen.pending_scheduled_actions.is_empty()); @@ -4351,7 +4018,7 @@ mod tests { #[test] fn voting_ui_sweep_completion_refreshes_the_scheduled_row() { let (mut screen, _temp_dir) = voting_ui_review_fixture(); - screen.dpns_subscreen = DPNSSubscreen::ScheduledVotes; + screen.view = VotesView::Scheduled; let mut target = screen.build_review_plan().unwrap().entries.remove(0).target; target.timing = VoteTiming::Scheduled(42); let mut operation = DpnsVoteOperation::new(vec![target]); @@ -4402,7 +4069,7 @@ mod tests { .await .expect("seed second node's complete proved votes"); - let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); screen.voting_identities = vec![first.clone(), second.clone()]; screen.bulk_identity_options = vec![ VoteOption::CastNow, @@ -4475,7 +4142,7 @@ mod tests { ctx.cache_confirmed_dpns_vote(node.identity.id(), alpha, ResourceVoteChoice::Lock) .expect("seed proved vote"); - let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); screen.voting_identities = vec![node.clone()]; screen.bulk_identity_options = vec![VoteOption::CastNow]; screen.selected_votes = vec![SelectedVote { @@ -4503,7 +4170,7 @@ mod tests { ctx.cache_confirmed_dpns_vote(node.identity.id(), alpha, ResourceVoteChoice::Lock) .expect("seed proved vote"); - let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::Active); + let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); screen.voting_identities = vec![node.clone()]; screen.bulk_identity_options = vec![VoteOption::CastNow]; screen.selected_votes = vec![SelectedVote { @@ -4579,7 +4246,7 @@ mod tests { executed_successfully: false, }]) .expect("insert compatibility mirror"); - let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::ScheduledVotes); + let mut screen = DPNSScreen::new(&ctx, VotesView::Scheduled); assert_eq!(screen.scheduled_votes.lock_recover().len(), 1); ctx.cancel_scheduled_dpns_vote_target(operation.id, &key, "remove-me") @@ -4621,7 +4288,7 @@ mod tests { executed_successfully: false, }]) .expect("insert compatibility mirror"); - let mut screen = DPNSScreen::new(&ctx, DPNSSubscreen::ScheduledVotes); + let mut screen = DPNSScreen::new(&ctx, VotesView::Scheduled); assert_eq!(screen.scheduled_votes.lock_recover().len(), 1); let outcomes = ctx diff --git a/src/ui/dpns/mod.rs b/src/ui/dpns/mod.rs index 49c2ec3c5..e78f28a00 100644 --- a/src/ui/dpns/mod.rs +++ b/src/ui/dpns/mod.rs @@ -1 +1,32 @@ +//! Masternode voting on contested DPNS names (Masternodes β–Έ Votes). + pub mod dpns_contested_names_screen; + +/// 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 and how the operator's nodes voted. + 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/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index 87b233238..eb6d7d033 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -18,6 +18,7 @@ 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, 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,6 +29,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::dpns::VotesView; +use crate::ui::dpns::dpns_contested_names_screen::DPNSScreen; use crate::ui::identity::identity_pill::shorten_id; use crate::ui::identity::picker::compute_column_count; use crate::ui::masternodes::card::{MasternodeCard, card_heading}; @@ -105,6 +108,11 @@ 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, } #[cfg(test)] @@ -137,11 +145,70 @@ 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), }; 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) { + self.segment = segment; + if let Err(error) = self.app_context.set_masternodes_last_segment(segment) { + tracing::debug!(?error, "Could not remember the Masternodes 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, @@ -246,6 +313,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(); } @@ -594,6 +669,7 @@ impl ScreenLike for MasternodesScreen { } fn refresh(&mut self) { self.reload(); + self.votes.refresh(); } fn refresh_on_arrival(&mut self) { @@ -602,12 +678,33 @@ 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(), + ); + } + + 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 @@ -630,6 +727,75 @@ impl ScreenLike for MasternodesScreen { } 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, + error: &crate::backend_task::error::TaskError, + ) { + 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 + }); + 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()); + } + } + + action + } +} + +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. @@ -706,56 +872,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()); - 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 - }); - - action - } } #[cfg(test)] diff --git a/src/ui/mod.rs b/src/ui/mod.rs index a9cf8a8cf..b6d3f4dbf 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,7 +49,6 @@ 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; @@ -132,19 +130,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 +194,6 @@ impl From for ScreenType { #[derive(Debug, Clone, Default)] pub enum ScreenType { - DPNSActiveContests, - DPNSPastContests, - DPNSMyUsernames, AddNewIdentity, WalletsBalances, ImportMnemonic, @@ -200,7 +220,6 @@ pub enum ScreenType { RegisterContract, UpdateContract, TopUpIdentity(QualifiedIdentity), - ScheduledVotes, AddContracts, ProofVisualizer, DocumentsVisualizer, @@ -310,15 +329,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)) } @@ -381,9 +391,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 +568,6 @@ impl ScreenType { #[allow(clippy::enum_variant_names, clippy::large_enum_variant)] pub enum Screen { - DPNSScreen(DPNSScreen), DocumentQueryScreen(DocumentQueryScreen), AddNewWalletScreen(AddNewWalletScreen), ImportMnemonicScreen(ImportMnemonicScreen), @@ -727,11 +733,6 @@ impl Screen { screen.reset_for_context_change(); return; } - Screen::DPNSScreen(screen) => { - screen.app_context = app_context; - screen.reset_for_network_switch(); - return; - } Screen::MasternodesScreen(screen) => { screen.app_context = app_context; // A network switch invalidates any open load form or detail view @@ -789,7 +790,6 @@ impl Screen { PauseTokensScreen, ResumeTokensScreen; skip: - DPNSScreen, MasternodesScreen, NetworkChooserScreen, AddNewWalletScreen, @@ -922,22 +922,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) => { @@ -1084,7 +1068,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, @@ -1208,3 +1191,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/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/wallet_backend/mod.rs b/src/wallet_backend/mod.rs index 0f8815d36..b96e90d60 100644 --- a/src/wallet_backend/mod.rs +++ b/src/wallet_backend/mod.rs @@ -2419,6 +2419,28 @@ impl WalletBackend { }) } + /// ProTxHashes in the current deterministic masternode list, each mapped + /// to whether it is an evonode. `None` until the list has synced. + /// + /// Keys are the masternode identity ids: Platform derives them from the + /// wire-order `pro_tx_hash` bytes unchanged (`to_byte_array`). + pub async fn masternode_list_membership( + &self, + ) -> Option> { + let summaries = self.inner.pwm.spv().masternode_list_summaries().await?; + Some( + summaries + .into_iter() + .map(|summary| { + ( + dash_sdk::platform::Identifier::from(summary.pro_tx_hash), + summary.is_evonode, + ) + }) + .collect(), + ) + } + /// Whether chain sync has not yet reached the tip. pub async fn is_syncing(&self) -> bool { match self.inner.pwm.spv().sync_progress().await { diff --git a/tests/kittest/masternode_tab.rs b/tests/kittest/masternode_tab.rs index a5f07421a..153c6a72a 100644 --- a/tests/kittest/masternode_tab.rs +++ b/tests/kittest/masternode_tab.rs @@ -5,6 +5,7 @@ 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::{ @@ -337,10 +338,10 @@ fn empty_state_renders_canonical_copy() { }); } -/// The Masternodes root contains only its list and detail flow. DPNS owns all -/// voting and scheduled-vote navigation. +/// 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_has_no_operator_voting_subnavigation() { +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(); @@ -349,38 +350,92 @@ fn masternodes_has_no_operator_voting_subnavigation() { let app_context = harness.state().current_app_context().clone(); activate_masternodes_tab(&mut harness, &app_context); - assert!(harness.query_by_label("Nodes").is_none()); - assert!(harness.query_by_label("Voting").is_none()); - assert!(harness.query_by_label("Scheduled").is_none()); + 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); }); } -/// Scheduled votes remain reachable from the persistent DPNS subscreen bar. +/// The Votes segment keeps its sub-views reachable: Scheduled opens in place. #[test] -fn dpns_scheduled_votes_tab_is_clickable() { +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::RootScreenDPNSActiveContests); - harness.run_steps(5); + 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(); - harness.get_by_label("Scheduled votes").click(); + let mut harness = mount_app(RootScreenType::RootScreenDPNSScheduledVotes); harness.run_steps(3); assert_eq!( harness.state().selected_main_screen, - RootScreenType::RootScreenDPNSScheduledVotes + RootScreenType::RootScreenMasternodes ); + assert_eq!(masternodes_segment(&mut harness), MasternodesSegment::Votes); assert!(harness.query_by_label("No scheduled votes.").is_some()); }); } -/// VOTE-TC-013 β€” Active contests must expose the actionable no-voter-key state -/// directly; the user cannot open Review and cast without a usable voter. +/// VOTE-TC-083 β€” the retired "My usernames" route opens the Identities hub. #[test] -fn active_contests_without_a_voting_key_shows_the_load_action() { +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(); @@ -390,22 +445,22 @@ fn active_contests_without_a_voting_key_shows_the_load_action() { app_context .insert_name_contests_as_normalized_names(vec!["alice".to_owned()]) .expect("seed active contest"); - let active_screen = harness + let Screen::MasternodesScreen(masternodes) = harness .state_mut() .main_screens - .get_mut(&RootScreenType::RootScreenDPNSActiveContests) - .expect("active contests screen"); - let Screen::DPNSScreen(active_screen) = active_screen else { - panic!("active contests root must contain a DPNS screen"); + .get_mut(&RootScreenType::RootScreenMasternodes) + .expect("masternodes screen") + else { + panic!("the Masternodes root must contain the Masternodes screen"); }; - active_screen.refresh(); + masternodes.votes_mut().refresh(); harness.run_steps(5); assert!( harness .query_by_label("None of your loaded nodes has a voting key.") .is_some(), - "the no-voter-key explanation must render on Active contests" + "the no-voter-key explanation must render in To decide" ); harness.get_by_label("Load a masternode").click(); harness.run_steps(3); @@ -413,6 +468,11 @@ fn active_contests_without_a_voting_key_shows_the_load_action() { 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" + ); }); } @@ -681,9 +741,9 @@ fn detail_dpns_voting_button_opens_active_contests() { harness.run_steps(3); assert_eq!( harness.state().selected_main_screen, - RootScreenType::RootScreenDPNSActiveContests + RootScreenType::RootScreenMasternodes ); - assert!(harness.query_by_label("Active contests").is_some()); + assert!(harness.query_by_label("To decide").is_some()); }); } From d4e7a130e5fc0a583ffe379318508c4e095c7b37 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 16:50:55 +0000 Subject: [PATCH 067/194] feat(identity): rework username registration flow Open the flow from an identity with no identity picker. Check availability live with a 400 ms debounce and show exactly one status line, suggest names that avoid a community vote, and keep the username rules in a collapsed disclosure. Contested names go through a consent dialog with network durations and the community vote fee, then a confirm step with fee rows, low-balance top-up and a sync gate. A pay-time availability change returns to the choose step with nothing spent. Co-Authored-By: Claude Opus 5.5 --- src/model/dpns_usernames.rs | 12 + .../add_new_identity_screen/success_screen.rs | 1 - src/ui/identity/mod.rs | 1 + src/ui/identity/register_dpns_name_screen.rs | 1220 +++++++++-------- src/ui/identity/username_copy.rs | 375 +++++ tests/kittest/identity_usernames.rs | 254 ++++ tests/kittest/main.rs | 1 + tests/kittest/register_dpns_name_screen.rs | 9 +- 8 files changed, 1332 insertions(+), 541 deletions(-) create mode 100644 src/ui/identity/username_copy.rs create mode 100644 tests/kittest/identity_usernames.rs diff --git a/src/model/dpns_usernames.rs b/src/model/dpns_usernames.rs index 8a6989423..8487d8d81 100644 --- a/src/model/dpns_usernames.rs +++ b/src/model/dpns_usernames.rs @@ -10,10 +10,22 @@ 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); +/// Whether this device holds a key that can sign username registrations for `identity`. +pub fn can_register_usernames(identity: &QualifiedIdentity) -> bool { + use dash_sdk::dpp::identity::Purpose; + use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; + identity + .private_keys + .identity_public_keys() + .iter() + .any(|(_, key)| key.identity_public_key.purpose() == Purpose::AUTHENTICATION) +} + /// Whether a username can be requested right now, and on what terms. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum UsernameAvailability { 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..395a1dcda 100644 --- a/src/ui/identity/add_new_identity_screen/success_screen.rs +++ b/src/ui/identity/add_new_identity_screen/success_screen.rs @@ -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/mod.rs b/src/ui/identity/mod.rs index 3bc35d894..cb14cfbff 100644 --- a/src/ui/identity/mod.rs +++ b/src/ui/identity/mod.rs @@ -56,6 +56,7 @@ 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 withdraw_screen; pub use hub_screen::IdentityHubScreen; diff --git a/src/ui/identity/register_dpns_name_screen.rs b/src/ui/identity/register_dpns_name_screen.rs index 466ca549d..b442213f3 100644 --- a/src/ui/identity/register_dpns_name_screen.rs +++ b/src/ui/identity/register_dpns_name_screen.rs @@ -1,36 +1,52 @@ +//! 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::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}; +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::identity_pill::display_label; +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::dpp::platform_value::string_encoding::Encoding; 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; +/// Wait after the last keystroke before asking the network about a name. +const AVAILABILITY_DEBOUNCE: Duration = Duration::from_millis(400); + /// Tracks where the user navigated from to reach this screen #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum RegisterDpnsNameSource { @@ -39,641 +55,775 @@ pub enum RegisterDpnsNameSource { 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 }, } 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, 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, } 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, + 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, - } + }; + 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(); + /// 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)); + } - // 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(); - self.selected_key = None; - self.selected_wallet = None; + /// 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.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| { + display_label( + qi.alias.as_deref(), + None, + self.app_context.main_username(qi).as_deref(), + &qi.identity.id().to_string(Encoding::Base58), + ) + }) + .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()) } - fn register_dpns_name_clicked(&mut self) -> AppAction { - let Some(qualified_identity) = self.selected_qualified_identity.as_ref() else { - return AppAction::None; + fn total_fee(&self, needs_vote: bool) -> u64 { + self.registration_fee() + if needs_vote { self.contest_fee() } else { 0 } + } + + /// Restart the debounce after the typed label changed. + fn on_label_changed(&mut self) { + let label = self.label().to_owned(); + self.availability = if validate_dpns_name(&label) == DpnsNameValidationResult::Valid { + Availability::Debouncing { + label, + since: Instant::now(), + } + } else { + Availability::Idle }; - let Some(_selected_key) = self.selected_key.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 dpns_name_input = RegisterDpnsNameInput { - qualified_identity: qualified_identity.clone(), - name_input: self.name_input.trim().to_string(), + let remaining = AVAILABILITY_DEBOUNCE.saturating_sub(since.elapsed()); + if !remaining.is_zero() { + ctx.request_repaint_after(remaining); + return AppAction::None; + } + let label = label.clone(); + self.check_availability(label) + } + + fn check_availability(&mut self, label: String) -> AppAction { + self.availability = Availability::Row { + label: label.clone(), + row: AvailabilityRow::Checking, }; + AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::CheckUsernameAvailability { label }, + )) + } - AppAction::BackendTask(BackendTask::IdentityTask(IdentityTask::RegisterDpnsName( - dpns_name_input, - ))) + fn continue_clicked(&mut self) { + let Some(availability) = self.current_availability() else { + return; + }; + if !availability.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 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. + /// 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); - } - action + let Some(identity) = self.selected_qualified_identity.as_ref() else { + return AppAction::None; + }; + let task = IdentityTask::RegisterDpnsName(RegisterDpnsNameInput { + qualified_identity: identity.clone(), + name_input: self.label().to_owned(), + }); + self.step = Step::Submitting; + self.raise_progress_overlay(ctx); + AppAction::BackendTask(BackendTask::IdentityTask(task)) } 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." + /// 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(); + } + + /// 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) + } + + /// Test seam: move to the confirm step for the typed label. + #[doc(hidden)] + pub fn open_confirm_for_test(&mut self) { + self.step = Step::Confirm; + } + + /// Test seam: whether the flow is on the confirm step. + #[doc(hidden)] + pub fn is_confirming_for_test(&self) -> bool { + self.step == Step::Confirm + } + + 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(); + } + } + }); + } + } } - 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." + } + + 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}")); + } + }); + + 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 + } + + fn render_confirm(&mut self, ui: &mut Ui) -> AppAction { + 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 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, - ); + let name = self.label().to_owned(); + let needs_vote = self + .current_availability() + .is_some_and(UsernameAvailability::needs_vote); + let registration_fee = self.registration_fee(); + let total = self.total_fee(needs_vote); + 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!( + "{fee}", + fee = format_credits_as_dash(self.contest_fee()) + )); + ui.end_row(); + } + ui.label(RichText::new("Total").strong()); + ui.label( + RichText::new(format!( + "{total}", + total = 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)), + ); + }); - // 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; + if self.app_context.user_role().at_least(UserRole::Power) { + egui::CollapsingHeader::new("Advanced") + .default_open(false) + .show(ui, |ui| { + let key = self + .app_context + .dpns_contract + .document_type_for_name("domain") + .ok() + .and_then(|document_type| identity.document_signing_key(&document_type)) + .map(|key| key.id()); + match key { + Some(id) => ui.label(format!("Signing key: Authentication key {id}")), + None => ui.label("No signing key is available for this identity."), + }; + }); } + 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(); + } + }); + } + } + + 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), + ); + } + }); + } + + 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; + } + 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 + } + + 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(format!("You're @{name}")); + ui.label("People can now find and pay you by this name."); + } + DpnsRegistrationOutcome::PendingCommunityVote => { + ui.heading(format!("Your request for @{name} is in")); + 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(format!( + "Others can still ask for this name until {join}. The community vote ends around {end}.", + join = username_copy::format_date_time(join_end), + end = username_copy::format_date(end) + )); + } + ui.label(format!( + "If no one else asks and no one votes to lock it, @{name} becomes yours then." + )); + ui.label( + RichText::new( + "We'll show the result on your identity's page. You don't need to keep this screen open.", + ) + .color(DashColors::text_secondary(dark_mode)), + ); + } + } + ui.add_space(16.0); + ui.horizontal(|ui| { + if outcome == DpnsRegistrationOutcome::PendingCommunityVote + && ComponentStyles::add_secondary_button(ui, "View request status", dark_mode) + .clicked() + { + action = AppAction::SetMainScreenThenPopScreen( + RootScreenType::RootScreenIdentityHub, + ); + } + if ComponentStyles::add_primary_button(ui, "Go to my identity").clicked() { + action = AppAction::SetMainScreenThenPopScreen( + RootScreenType::RootScreenIdentityHub, + ); + } + }); + }); action } } +/// 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), + "Between 3 and 63 characters", + dark_mode, + ); + status_line( + ui, + tone(chars_ok), + "Only letters, numbers, and hyphens", + dark_mode, + ); + if matches!( + validation, + DpnsNameValidationResult::StartsWithHyphen | DpnsNameValidationResult::EndsWithHyphen + ) && let Some(message) = validation.error_message() + { + status_line(ui, Tone::Negative, &message, dark_mode); + } +} + +/// 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)); +} + 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. + // Banners are shown by AppState; this only unblocks the flow after a failure. if matches!(message_type, MessageType::Error | MessageType::Warning) { self.op_overlay.take_and_clear(); - self.register_dpns_name_status = RegisterDpnsNameStatus::Error; + if self.step == Step::Submitting { + self.step = Step::Confirm; + } } } - 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; + fn display_task_error(&mut self, error: &TaskError) -> bool { + match error { + TaskError::UsernameAvailabilityCheckFailed { .. } => { + if let Availability::Row { row, .. } = &mut self.availability + && *row == AvailabilityRow::Checking + { + *row = AvailabilityRow::CantCheck; + } + // The inline row explains the failure; no banner needed. + true + } + TaskError::UsernameNoLongerAvailable { availability } => { + self.op_overlay.take_and_clear(); + self.step = Step::Choose; + self.availability = Availability::Row { + label: self.label().to_owned(), + row: AvailabilityRow::Known(*availability), + }; + true + } + _ => false, + } + } + + fn display_task_result(&mut self, result: BackendTaskSuccessResult) { + match result { + BackendTaskSuccessResult::RegisteredDpnsName { + outcome, + fee_result, + } => { + self.op_overlay.take_and_clear(); + self.completed_fee_result = Some(fee_result); + self.step = Step::Done(outcome); + } + BackendTaskSuccessResult::UsernameAvailability { + label, + availability, + } => { + if matches!(&self.availability, Availability::Row { label: current, .. } if *current == label) + { + self.availability = Availability::Row { + label, + row: AvailabilityRow::Known(availability), + }; + } + } + _ => {} } } + fn refresh_on_arrival(&mut self) { + self.reload_identity(); + } + 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 identity_label = self.identity_label(); let breadcrumbs = match self.source { RegisterDpnsNameSource::Dpns => vec![ ( "DPNS", - AppAction::SetMainScreen( - crate::ui::RootScreenType::RootScreenDPNSActiveContests, - ), + AppAction::SetMainScreen(RootScreenType::RootScreenDPNSActiveContests), ), - ("Register Name", AppAction::None), + ("Get a username", AppAction::None), ], RegisterDpnsNameSource::Identities => vec![ ( "Identities", - AppAction::SetMainScreen(crate::ui::RootScreenType::RootScreenIdentityHub), + AppAction::SetMainScreen(RootScreenType::RootScreenIdentityHub), ), - ("Register Name", AppAction::None), + (identity_label.as_str(), AppAction::PopScreen), + ("Get a username", AppAction::None), ], }; - let mut action = add_top_panel(ui, &self.app_context, breadcrumbs, vec![]); - - // 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, + RegisterDpnsNameSource::Dpns => RootScreenType::RootScreenDPNSActiveContests, + RegisterDpnsNameSource::Identities => RootScreenType::RootScreenIdentityHub, }; action |= add_left_panel(ui, &self.app_context, root_screen); - // Don't show the tools/dpns subscreen chooser panels for this screen - action |= island_central_panel(ui, |ui| { - let mut inner_action = AppAction::None; - + let mut inner = AppAction::None; egui::ScrollArea::vertical() .auto_shrink([false; 2]) .show(ui, |ui| { - if self.register_dpns_name_status == RegisterDpnsNameStatus::Complete { - inner_action |= self.show_success(ui); + let dark_mode = ui.style().visuals.dark_mode; + if let Step::Done(outcome) = self.step { + inner = self.render_done(ui, outcome); return; } - - 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; - } - - // 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 - }) - }); - - 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; - } - - // 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 - )); - } - - 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.", + 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.add_space(8.0); - if ui.button("Unlock Wallet").clicked() { - self.wallet_unlock_popup.open(); - } return; - } - } - - // Input for the name - ui.heading("2. Enter the Name to Register:"); - ui.add_space(5.0); - ui.horizontal(|ui| { - ui.label("Name (without \".dash\"):"); - ui.text_edit_singleline(&mut self.name_input); - }); - - // Display validation status and cost information - let name = self.name_input.trim(); - if !name.is_empty() { - ui.add_space(10.0); - - // Validate the name - let validation_result = validate_dpns_name(name); - - match validation_result { - DpnsNameValidationResult::Valid => { - ui.colored_label( - egui::Color32::DARK_GREEN, - "Valid name format", + }; + if !can_register_usernames(identity) { + status_line( + ui, + Tone::Negative, + "Add a key to this identity to register usernames.", + dark_mode, ); - - // Show contested status and cost if valid - if crate::model::dpns::is_contested_label(name) { - ui.colored_label( - egui::Color32::DARK_RED, - "This is a contested name.", - ); - let contest_fee = crate::model::fee_estimation::contest_fee_credits( - self.app_context.sdk_platform_version(), - ); - ui.colored_label( - egui::Color32::DARK_RED, - format!( - "Community vote fee: {fee} DASH", - fee = format_credits_as_dash(contest_fee) - ), - ); - } 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, - ); - } + return; } - } - } - - ui.add_space(10.0); - - // 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; - - Frame::new() - .fill(DashColors::surface(dark_mode)) - .inner_margin(Margin::symmetric(10, 8)) - .corner_radius(5.0) - .show(ui, |ui| { - ui.horizontal(|ui| { - ui.label( - RichText::new("Estimated fee:") - .color(DashColors::text_secondary(dark_mode)) - .size(14.0), - ); - ui.label( - RichText::new(format_credits_as_dash(estimated_fee)) - .color(DashColors::text_primary(dark_mode)) - .size(14.0), - ); - }); + 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; + self.step = Step::Confirm; + } + Some(ConfirmationStatus::Canceled) => self.consent_dialog = 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 diff --git a/src/ui/identity/username_copy.rs b/src/ui/identity/username_copy.rs new file mode 100644 index 000000000..2fd7639e9 --- /dev/null +++ b/src/ui/identity/username_copy.rs @@ -0,0 +1,375 @@ +//! 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::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, + "Availability can't be checked right now. Check your internet connection and try again." + .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."), + ), + }, + } +} + +/// 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.", +]; + +/// 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::Won => "Registered", + RequestPhase::Lost => "Went to someone else", + RequestPhase::Locked => "Locked for good", + } +} + +/// Second sentence of the Home request card. +pub fn standing_line(standing: TallyStanding, others: usize) -> &'static str { + if others == 0 { + "No one else has asked so far." + } else { + match standing { + TallyStanding::Leading => "You're leading right now.", + TallyStanding::Tied | 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:?}"); + } + } + + #[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::Tied, 0), + "No one else has asked so far." + ); + assert_eq!( + standing_line(TallyStanding::Trailing, 2), + "Another request is leading." + ); + } + + #[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/tests/kittest/identity_usernames.rs b/tests/kittest/identity_usernames.rs new file mode 100644 index 000000000..733590f99 --- /dev/null +++ b/tests/kittest/identity_usernames.rs @@ -0,0 +1,254 @@ +//! Kittest coverage for identity usernames (USR-TC-018, 031–038). + +use crate::support::{fresh_app_context, with_isolated_data_dir}; +use dash_evo_tool::backend_task::BackendTaskSuccessResult; +use dash_evo_tool::backend_task::error::TaskError; +use dash_evo_tool::context::AppContext; +use dash_evo_tool::context::connection_status::OverallConnectionState; +use dash_evo_tool::model::dpns_usernames::UsernameAvailability; +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::ui::ScreenLike; +use dash_evo_tool::ui::components::ProgressOverlay; +use dash_evo_tool::ui::identity::register_dpns_name_screen::{ + RegisterDpnsNameScreen, RegisterDpnsNameSource, +}; +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 + .query_by_label_contains("For Alice Novak. 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(); + screen.raise_progress_overlay_for_test(&ctx); + let handled = screen.display_task_error(&TaskError::UsernameNoLongerAvailable { + availability: UsernameAvailability::Locked, + }); + 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() + ); + }); +} + +/// 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(&format!("{contest_fee}")).is_some()); + 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() + ); + }); +} 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/register_dpns_name_screen.rs b/tests/kittest/register_dpns_name_screen.rs index 5b573a856..e9b26307c 100644 --- a/tests/kittest/register_dpns_name_screen.rs +++ b/tests/kittest/register_dpns_name_screen.rs @@ -100,7 +100,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 +108,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 +117,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.", ); } From 1d511d60f9959f0bb6586f287e22f2493b67510f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 16:51:48 +0000 Subject: [PATCH 068/194] style(identity): drop redundant format calls in username confirm rows Co-Authored-By: Claude Opus 5.5 --- src/ui/identity/register_dpns_name_screen.rs | 13 ++----------- tests/kittest/identity_usernames.rs | 2 +- 2 files changed, 3 insertions(+), 12 deletions(-) diff --git a/src/ui/identity/register_dpns_name_screen.rs b/src/ui/identity/register_dpns_name_screen.rs index b442213f3..fbe4cf6ed 100644 --- a/src/ui/identity/register_dpns_name_screen.rs +++ b/src/ui/identity/register_dpns_name_screen.rs @@ -458,20 +458,11 @@ impl RegisterDpnsNameScreen { ui.end_row(); if needs_vote { ui.label("Community vote fee (not returned)"); - ui.label(format!( - "{fee}", - fee = format_credits_as_dash(self.contest_fee()) - )); + ui.label(format_credits_as_dash(self.contest_fee())); ui.end_row(); } ui.label(RichText::new("Total").strong()); - ui.label( - RichText::new(format!( - "{total}", - total = format_credits_as_dash(total) - )) - .strong(), - ); + ui.label(RichText::new(format_credits_as_dash(total)).strong()); ui.end_row(); }); ui.add_space(4.0); diff --git a/tests/kittest/identity_usernames.rs b/tests/kittest/identity_usernames.rs index 733590f99..f5f8266dc 100644 --- a/tests/kittest/identity_usernames.rs +++ b/tests/kittest/identity_usernames.rs @@ -209,7 +209,7 @@ fn confirm_step_shows_fees_low_balance_and_sync_gate() { .query_by_label("Community vote fee (not returned)") .is_some() ); - assert!(harness.query_by_label(&format!("{contest_fee}")).is_some()); + assert!(harness.query_by_label(&contest_fee).is_some()); assert!(harness.query_by_label("Community vote").is_some()); assert!( harness From b31455080b7a63adc7375d4b030fab545dfda39d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 16:52:29 +0000 Subject: [PATCH 069/194] feat(dpns): signal votes needed from every screen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A top-bar chip shows "{n} names need your vote" (amber with the soonest deadline inside the urgency window) and a second chip while votes are still being checked; both open Masternodes β–Έ Votes and hide below the Power role or without a voting node. The Masternodes nav item carries a badge of contests needing a decision plus unresolved targets. A background refresh of contests and node vote state runs every 30 min on mainnet and 3 min elsewhere while voting nodes are loaded, and on arriving at Votes; its failures are logged, never bannered. The attention summary is recomputed on refresh and on coordinator updates. Contest durations and the urgency window use a local stand-in for the shared model::dpns helpers until the usernames stream lands them. Co-Authored-By: Claude Opus 5.5 --- src/app.rs | 38 ++++ src/backend_task/contested_names/mod.rs | 17 +- .../query_dpns_contested_resources.rs | 14 ++ src/backend_task/mod.rs | 3 + src/context/dpns_vote_attention.rs | 18 ++ src/context/mod.rs | 3 + src/model/dpns_voting/contest_timing.rs | 76 ++++++++ src/model/dpns_voting/mod.rs | 1 + src/model/dpns_voting/operator.rs | 92 +++++++++- src/ui/components/left_panel.rs | 34 ++++ src/ui/components/top_panel.rs | 3 + src/ui/dpns/attention_chip.rs | 173 ++++++++++++++++++ src/ui/dpns/copy.rs | 100 ++++++++++ src/ui/dpns/dpns_contested_names_screen.rs | 2 + src/ui/dpns/mod.rs | 2 + src/ui/masternodes/list_screen.rs | 33 +++- 16 files changed, 605 insertions(+), 4 deletions(-) create mode 100644 src/model/dpns_voting/contest_timing.rs create mode 100644 src/ui/dpns/attention_chip.rs create mode 100644 src/ui/dpns/copy.rs diff --git a/src/app.rs b/src/app.rs index c89db9708..3b154d2a6 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1414,6 +1414,8 @@ pub struct AppState { scheduled_vote_sweep_deferred_since_ms: BTreeMap, /// Networks with a scheduled-vote sweep currently running. scheduled_vote_sweeps_in_progress: BTreeSet, + /// Unix ms of the last background contest refresh dispatched per network. + dpns_background_refresh_dispatched_at_ms: BTreeMap, /// Last recovery-sweep attempt per network, used to throttle retries while /// retaining the original eligibility cutoff. scheduled_vote_recovery_last_attempt: BTreeMap, @@ -1949,6 +1951,7 @@ impl AppState { last_scheduled_vote_check: Instant::now(), scheduled_vote_sweep_deferred_since_ms: BTreeMap::new(), scheduled_vote_sweeps_in_progress: BTreeSet::new(), + dpns_background_refresh_dispatched_at_ms: BTreeMap::new(), scheduled_vote_recovery_last_attempt: BTreeMap::new(), last_repaint_request: Instant::now(), subtasks, @@ -3479,6 +3482,14 @@ 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 on its own cadence; the + // voting panel's Refresh is where failures are reported. + tracing::debug!(?error, ?network, "Background contest refresh failed"); + } TaskResult::Error { context, error: @@ -3640,6 +3651,33 @@ impl App for AppState { } } + // 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(); + if 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_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 diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 9f64665dc..64d8d8d52 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -39,6 +39,9 @@ use crate::model::dpns_voting::SCHEDULED_VOTE_MAX_LATENESS_MS; #[derive(Debug, Clone, PartialEq)] pub enum ContestedResourceTask { QueryDPNSContests, + /// The same contest + vote-state refresh, run by the background timer: + /// partial failures are logged instead of reported to the user. + RefreshContestsInBackground, SubmitDpnsVoteOperation( DpnsVoteOperation, Vec, @@ -192,12 +195,22 @@ impl AppContext { ) -> Result { let is_scheduled_sweep = matches!(&task, ContestedResourceTask::CastDueScheduledVotes { .. }); - if !is_scheduled_sweep && !matches!(&task, ContestedResourceTask::QueryDPNSContests) { + if !is_scheduled_sweep + && !matches!( + &task, + ContestedResourceTask::QueryDPNSContests + | ContestedResourceTask::RefreshContestsInBackground + ) + { 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::RefreshContestsInBackground => self + .query_dpns_contested_resources(sdk, sender, true) .await .map(|_| BackendTaskSuccessResult::None), ContestedResourceTask::SubmitDpnsVoteOperation( 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 84714d4a8..a2b26ed29 100644 --- a/src/backend_task/contested_names/query_dpns_contested_resources.rs +++ b/src/backend_task/contested_names/query_dpns_contested_resources.rs @@ -14,10 +14,17 @@ use std::sync::Arc; use tokio::sync::{OwnedSemaphorePermit, Semaphore}; 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 @@ -144,6 +151,9 @@ impl AppContext { ); } } + Err(e) if quiet => { + tracing::debug!(error = ?e, "Background refresh could not query contest end times"); + } Err(e) => { tracing::error!("Error querying dpns end times: {}", e); let result = contextualize_dapi_task_result( @@ -195,6 +205,9 @@ impl AppContext { ); } } + Err(e) if quiet => { + tracing::debug!(error = ?e, %name, "Background refresh could not query contenders"); + } Err(e) => { tracing::error!("Error querying dpns vote contenders for {}: {}", name, e); let result = contextualize_dapi_task_result( @@ -230,6 +243,7 @@ impl AppContext { self.refresh_masternode_list_membership().await; self.forget_closed_dpns_vote_counts(); self.recompute_dpns_vote_attention(); + self.mark_dpns_contests_refreshed(); self.refresh_pending_dpns_usernames()?; sender diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index b1baa8af8..4315531bd 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -339,6 +339,9 @@ pub enum BackendTaskContext { }, /// 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 single schedule action, before its journal operation is resolved. DpnsScheduledVote { key: DpnsScheduledVoteKey }, /// An optimistic edit of one durable scheduled target. diff --git a/src/context/dpns_vote_attention.rs b/src/context/dpns_vote_attention.rs index 51b4c51fd..54eab22a8 100644 --- a/src/context/dpns_vote_attention.rs +++ b/src/context/dpns_vote_attention.rs @@ -47,6 +47,23 @@ impl AppContext { ) } + /// 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, @@ -229,6 +246,7 @@ impl AppContext { Ok(AttentionSummary::new( &attention, unresolved_target_count(&operations), + resolved.included.len(), )) } } diff --git a/src/context/mod.rs b/src/context/mod.rs index dada70a72..fd56a7771 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -206,6 +206,8 @@ pub struct AppContext { /// Current masternode-list membership (ProTxHash β†’ is evonode); `None` /// until the SPV masternode list is available. masternode_list_membership: RwLock>>>, + /// 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 @@ -576,6 +578,7 @@ impl AppContext { pending_dpns_usernames: RwLock::new(HashMap::new()), dpns_vote_attention: RwLock::new(Default::default()), masternode_list_membership: RwLock::new(None), + dpns_contests_refreshed_at_ms: std::sync::atomic::AtomicU64::new(0), app_kv, #[cfg(test)] det_kv_override: Mutex::new(None), diff --git a/src/model/dpns_voting/contest_timing.rs b/src/model/dpns_voting/contest_timing.rs new file mode 100644 index 000000000..c9a8b1da0 --- /dev/null +++ b/src/model/dpns_voting/contest_timing.rs @@ -0,0 +1,76 @@ +//! Contest durations and the urgency window per network. +//! +//! TODO(stream-u): stand-in for `model::dpns::{contest_durations, urgency_window}`, +//! which the usernames stream owns. Signatures match the agreed API; delete this +//! module and switch the imports once that lands. + +use dash_sdk::dpp::dashcore::Network; +use dash_sdk::dpp::version::PlatformVersion; +use std::time::Duration; + +/// Contest timing for a network at a protocol version. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ContestDurations { + pub total: Duration, + pub join: Duration, +} + +/// Mainnet 14 d / 7 d; any other network 90 min / 45 min, read from the +/// protocol version. +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, join) = match network { + Network::Mainnet => ( + voting.default_vote_poll_time_duration_mainnet_ms, + joining.allow_other_contenders_time_mainnet_ms, + ), + _ => ( + voting.default_vote_poll_time_duration_test_network_ms, + joining.allow_other_contenders_time_testing_ms, + ), + }; + ContestDurations { + total: Duration::from_millis(total), + join: Duration::from_millis(join), + } +} + +/// How close to its deadline a contest counts as urgent: 24 h on mainnet, +/// 30 min elsewhere. +pub fn urgency_window(network: Network) -> Duration { + match network { + Network::Mainnet => Duration::from_secs(24 * 60 * 60), + _ => Duration::from_secs(30 * 60), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// VOTE-FR-085: durations come from the protocol version, never literals. + #[test] + fn durations_follow_the_network() { + let pv = PlatformVersion::latest(); + assert_eq!( + contest_durations(Network::Mainnet, pv), + ContestDurations { + total: Duration::from_secs(14 * 24 * 3600), + join: Duration::from_secs(7 * 24 * 3600), + } + ); + assert_eq!( + contest_durations(Network::Testnet, pv), + ContestDurations { + total: Duration::from_secs(90 * 60), + join: Duration::from_secs(45 * 60), + } + ); + assert_eq!( + urgency_window(Network::Mainnet), + Duration::from_secs(86_400) + ); + assert_eq!(urgency_window(Network::Devnet), Duration::from_secs(1_800)); + } +} diff --git a/src/model/dpns_voting/mod.rs b/src/model/dpns_voting/mod.rs index b5e787d2a..4faa6e4af 100644 --- a/src/model/dpns_voting/mod.rs +++ b/src/model/dpns_voting/mod.rs @@ -13,6 +13,7 @@ use dash_sdk::platform::Identifier; use serde::{Deserialize, Serialize}; use std::fmt; +pub mod contest_timing; pub mod operator; /// Grace period for admitting a scheduled vote to automatic execution. diff --git a/src/model/dpns_voting/operator.rs b/src/model/dpns_voting/operator.rs index f70dc566e..e3d2afe86 100644 --- a/src/model/dpns_voting/operator.rs +++ b/src/model/dpns_voting/operator.rs @@ -223,6 +223,32 @@ pub fn influence( .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 { @@ -250,6 +276,22 @@ pub fn relative_schedule( 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 { @@ -293,11 +335,13 @@ pub struct AttentionSummary { 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) -> Self { + 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)); @@ -310,6 +354,7 @@ impl AttentionSummary { .take(ATTENTION_TOOLTIP_NAMES) .map(|contest| (contest.name.clone(), contest.end_time)) .collect(), + voting_nodes, } } @@ -573,6 +618,49 @@ mod tests { ); } + #[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 = ( @@ -615,8 +703,10 @@ mod tests { 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)); diff --git a/src/ui/components/left_panel.rs b/src/ui/components/left_panel.rs index 92316a85d..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, @@ -207,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/top_panel.rs b/src/ui/components/top_panel.rs index 2e4975b71..aec35277f 100644 --- a/src/ui/components/top_panel.rs +++ b/src/ui/components/top_panel.rs @@ -304,6 +304,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/dpns/attention_chip.rs b/src/ui/dpns/attention_chip.rs new file mode 100644 index 000000000..a8a428b26 --- /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_voting::contest_timing::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/copy.rs b/src/ui/dpns/copy.rs new file mode 100644 index 000000000..054fab11e --- /dev/null +++ b/src/ui/dpns/copy.rs @@ -0,0 +1,100 @@ +//! User-facing sentences for the voting workspace. +//! +//! Each function returns one complete translation unit with its plural pair, +//! so no caller concatenates fragments. + +use crate::model::dpns_voting::operator::TimeLeft; + +/// 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."), + } +} + +#[cfg(test)] +mod tests { + 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 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 bed59c329..37335ac9f 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -2380,6 +2380,7 @@ impl ScreenLike for DPNSScreen { { tracing::warn!(?error, "Could not refresh cached DPNS vote state"); } + self.app_context.recompute_dpns_vote_attention(); } fn refresh_on_arrival(&mut self) { @@ -2509,6 +2510,7 @@ impl ScreenLike for DPNSScreen { ); } self.rebuild_scheduled_vote_rows(); + self.app_context.recompute_dpns_vote_attention(); } BackendTaskSuccessResult::ScheduledVoteSweepCompleted { network, .. } if network == self.app_context.network() => diff --git a/src/ui/dpns/mod.rs b/src/ui/dpns/mod.rs index e78f28a00..0f22e405c 100644 --- a/src/ui/dpns/mod.rs +++ b/src/ui/dpns/mod.rs @@ -1,5 +1,7 @@ //! Masternode voting on contested DPNS names (Masternodes β–Έ Votes). +pub mod attention_chip; +pub mod copy; pub mod dpns_contested_names_screen; /// Sub-view of the Masternodes β–Έ Votes segment. diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index eb6d7d033..ef1e97d00 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -18,7 +18,9 @@ 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, opening_masternodes_segment}; +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; @@ -41,6 +43,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; @@ -113,6 +118,9 @@ pub struct MasternodesScreen { /// 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, } #[cfg(test)] @@ -150,6 +158,7 @@ impl MasternodesScreen { app_context.masternodes_last_segment().unwrap_or_default(), ), votes: DPNSScreen::new(app_context, VotesView::ToDecide), + votes_arrival_refresh: false, }; screen.reload(); screen @@ -167,6 +176,8 @@ impl MasternodesScreen { /// Show `segment` and remember it as the last-used one on this network. pub fn select_segment(&mut self, segment: MasternodesSegment) { + self.votes_arrival_refresh |= + segment == MasternodesSegment::Votes && self.segment != segment; self.segment = segment; if let Err(error) = self.app_context.set_masternodes_last_segment(segment) { tracing::debug!(?error, "Could not remember the Masternodes segment"); @@ -691,6 +702,7 @@ impl ScreenLike for MasternodesScreen { .masternodes_last_segment() .unwrap_or_default(), ); + self.votes_arrival_refresh |= self.segment == MasternodesSegment::Votes; } fn display_message(&mut self, message: &str, message_type: MessageType) { @@ -782,6 +794,25 @@ impl ScreenLike for MasternodesScreen { } 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, + ) + { + let network = self.app_context.network; + action = AppAction::BackendTaskWithContext { + task: BackendTask::ContestedResourceTask( + ContestedResourceTask::RefreshContestsInBackground, + ), + context: crate::backend_task::BackendTaskContext::DpnsBackgroundRefresh { network }, + }; + } if self.votes.take_load_node_request() { self.select_segment(MasternodesSegment::Nodes); if self.pending_load.is_none() { From 53ccd3fb5f0740584a6c9ecc0402ae8456521a7c Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:00:37 +0000 Subject: [PATCH 070/194] feat(identity): usernames card and request status page Replace the Settings tab's username and Aliases block with one Usernames card: main name, other names, pending requests and recent outcomes, each with its own actions (copy, QR code, show as main, view status, dismiss, choose another). Remove the disabled alias stubs and the jump to the DPNS owned-names screen. Add a request status page with the timeline, a read-only weighted tally, and the rules for what happens next. Co-Authored-By: Claude Opus 5.5 --- src/context/contested_names_db.rs | 2 +- src/ui/identity/mod.rs | 2 + src/ui/identity/settings.rs | 181 +------- src/ui/identity/username_request_screen.rs | 324 +++++++++++++++ src/ui/identity/usernames_card.rs | 457 +++++++++++++++++++++ src/ui/mod.rs | 31 ++ tests/kittest/identity_hub_settings.rs | 4 +- tests/kittest/identity_usernames.rs | 228 +++++++++- 8 files changed, 1059 insertions(+), 170 deletions(-) create mode 100644 src/ui/identity/username_request_screen.rs create mode 100644 src/ui/identity/usernames_card.rs diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 90f03a8a1..908624c70 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -309,7 +309,7 @@ impl AppContext { } /// Persist `requests` as the full request list of `identity_id`. - pub(crate) fn store_username_requests( + pub fn store_username_requests( &self, identity_id: &Identifier, requests: Vec, diff --git a/src/ui/identity/mod.rs b/src/ui/identity/mod.rs index cb14cfbff..6571a97b2 100644 --- a/src/ui/identity/mod.rs +++ b/src/ui/identity/mod.rs @@ -57,6 +57,8 @@ pub mod tabs; pub mod top_up_identity_screen; pub mod transfer_screen; pub mod username_copy; +pub mod username_request_screen; +pub mod usernames_card; pub mod withdraw_screen; pub use hub_screen::IdentityHubScreen; diff --git a/src/ui/identity/settings.rs b/src/ui/identity/settings.rs index f8d83d7af..9d0bdafc5 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 \ @@ -199,6 +191,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 { @@ -242,8 +236,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); @@ -451,149 +444,17 @@ 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.label, - ); - 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(); - } - + let mut action = self.usernames_card.show(ui, app_context, identity); ui.add_space(12.0); - action |= self.render_local_alias(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 } @@ -1066,10 +927,6 @@ fn keys_screen_type(identity: &QualifiedIdentity) -> ScreenType { ScreenType::Keys(identity.clone()) } -fn usernames_screen_action() -> AppAction { - AppAction::SetMainScreenThenGoToMainScreen(RootScreenType::RootScreenDPNSOwnedNames) -} - // --------------------------------------------------------------------------- // Small layout helpers // --------------------------------------------------------------------------- @@ -1106,7 +963,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, @@ -1208,14 +1065,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(); @@ -1340,7 +1189,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, @@ -1364,8 +1213,8 @@ 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); + section_heading(ui, "Name on this device", dark); sub_heading(ui, "Advanced", dark); }); harness.run(); @@ -1374,12 +1223,12 @@ 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", + harness.query_by_label("Name on this device").is_some(), + "device-name heading must render", ); assert!( harness.query_by_label("Advanced").is_some(), diff --git a/src/ui/identity/username_request_screen.rs b/src/ui/identity/username_request_screen.rs new file mode 100644 index 000000000..d529a6dd6 --- /dev/null +++ b/src/ui/identity/username_request_screen.rs @@ -0,0 +1,324 @@ +//! 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::identity::IdentityTask; +use crate::backend_task::{BackendTask, BackendTaskSuccessResult}; +use crate::context::AppContext; +use crate::model::dpns_usernames::{RequestPhase, TallyStanding, UsernameRequest}; +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::{display_label, shorten_id}; +use crate::ui::identity::register_dpns_name_screen::{RegisterDpnsNameSource, status_line}; +use crate::ui::identity::username_copy::{ + Tone, format_date, format_date_time, phase_label, what_happens_next, +}; +use crate::ui::theme::{ComponentStyles, DashColors}; +use crate::ui::{MessageType, RootScreenType, ScreenLike, ScreenType}; + +/// 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, + refreshing: bool, + /// 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, + refreshing: false, + 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 + } + + 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) => display_label( + qi.alias.as_deref(), + None, + self.app_context.main_username(&qi).as_deref(), + &qi.identity.id().to_string(Encoding::Base58), + ), + 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), + _ => (false, false, true), + }; + if let Some(at) = request.requested_at { + status_line( + ui, + Tone::Positive, + &format!("Requested {}", format_date(at)), + dark_mode, + ); + } + if let Some(join_end) = request.join_end { + let text = if joining { + format!( + "Open for other requests until {}", + format_date_time(join_end) + ) + } else { + format!("Open for other requests. Ended {}.", format_date(join_end)) + }; + let tone = if joining { + Tone::Caution + } else { + Tone::Positive + }; + status_line(ui, tone, &text, dark_mode); + } + if let Some(end) = request.end { + let (tone, text) = if done { + ( + Tone::Positive, + format!("Community vote ended {}.", format_date(end)), + ) + } else if voting { + ( + Tone::Caution, + format!("Community vote. Ends around {}.", format_date_time(end)), + ) + } else { + ( + Tone::Neutral, + format!("Community vote until {}", format_date_time(end)), + ) + }; + status_line(ui, tone, &text, dark_mode); + } + let (tone, result) = match request.phase { + RequestPhase::Joinable | RequestPhase::Voting => { + (Tone::Neutral, "Result: Not decided yet.") + } + RequestPhase::Won => (Tone::Positive, "Result: The name is yours."), + RequestPhase::Lost => (Tone::Negative, "Result: The name went to someone else."), + RequestPhase::Locked => (Tone::Negative, "Result: The name is locked for good."), + }; + 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 => "", + }; + 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("Lock, so no one gets it"); + ui.label(""); + ui.label(tally.lock.to_string()); + ui.end_row(); + ui.label("Abstain"); + 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.refreshing { + "Refreshing…" + } else { + "Refresh status" + }; + if ui + .add_enabled(!self.refreshing, egui::Button::new(label)) + .clicked() + { + self.refreshing = true; + action = AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::RefreshMyUsernameRequests, + )); + } + }); + 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 = AppAction::AddScreen( + ScreenType::RegisterDpnsName(RegisterDpnsNameSource::Identities) + .create_screen(&self.app_context), + ); + } + if self.can_vote && ui.link("Your nodes can vote on this name").clicked() { + // TODO(stream-v): open Masternodes β–Έ Votes filtered to this name once Stream V exposes the route. + 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(|qi| qi.associated_voter_identity.is_some()); + } + + fn refresh_on_arrival(&mut self) { + self.refresh(); + } + + fn display_message(&mut self, _message: &str, message_type: MessageType) { + if matches!(message_type, MessageType::Error | MessageType::Warning) { + self.refreshing = false; + } + } + + fn display_task_result(&mut self, result: BackendTaskSuccessResult) { + if matches!( + result, + BackendTaskSuccessResult::MyUsernameRequestsRefreshed + ) { + self.refreshing = false; + } + } + + 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::SetMainScreen(RootScreenType::RootScreenIdentityHub), + ), + (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..f505130a9 --- /dev/null +++ b/src/ui/identity/usernames_card.rs @@ -0,0 +1,457 @@ +//! 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::context::AppContext; +use crate::model::dpns_usernames::{RequestPhase, UsernameRequest, can_register_usernames}; +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::{Tone, format_date, phase_label}; +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), +} + +/// Build the rows: main name, other names, pending requests, then finished outcomes. +pub fn username_rows( + identity: &QualifiedIdentity, + main: Option<&str>, + requests: &[UsernameRequest], +) -> Vec { + let names: Vec<_> = identity + .dpns_names + .iter() + .filter(|n| !n.name.trim().is_empty()) + .collect(); + let show_main_badge = names.len() > 1; + let mut rows: Vec = Vec::new(); + let main_index = main + .and_then(|main| names.iter().position(|n| n.name == main)) + .unwrap_or(0); + for (index, name) in names + .iter() + .enumerate() + .filter(|(i, _)| *i == main_index) + .chain(names.iter().enumerate().filter(|(i, _)| *i != main_index)) + { + rows.push(UsernameRow::Active { + name: name.name.clone(), + is_main: index == main_index, + show_main_badge, + acquired_at: name.acquired_at, + }); + } + let owned = |label: &str| names.iter().any(|n| n.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)) + .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); + + 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() { + if let Err(error) = app_context.set_main_username(&identity_id, &name) { + MessageBanner::set_global( + ui.ctx(), + "This choice could not be saved on your device. Try again in a moment.", + MessageType::Error, + ) + .with_details(error); + } + ui.close(); + } + }) + .response + .clickable_tooltip(format!("More actions for @{name}")); + }); + if acquired_at > 0 { + ui.label( + RichText::new(format!("Registered on {}.", format_date(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); + } + }); + let detail = match (request.phase, request.join_end, request.end) { + (RequestPhase::Joinable, Some(join_end), _) => format!( + "Others can ask for this name until {}. Voting starts after that.", + format_date(join_end) + ), + (_, _, Some(end)) => { + format!("Voting ends around {}.", format_date(end)) + } + _ => String::new(), + }; + if !detail.is_empty() { + 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); + }); + let detail = match request.phase { + RequestPhase::Locked => { + "More votes went to locking this name, so no one can register it." + .to_owned() + } + _ => request.decided_at.map_or_else( + || "The community vote ended.".to_owned(), + |at| format!("The community vote ended on {}.", format_date(at)), + ), + }; + ui.label( + RichText::new(detail) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); + ui.horizontal(|ui| { + if request.phase == RequestPhase::Lost + && ui.button("Choose another username").clicked() + { + action = register_action(app_context, identity); + } + if ui.button("Dismiss").clicked() + && let Err(error) = app_context + .dismiss_username_request(&identity_id, &request.normalized_label) + { + MessageBanner::set_global( + ui.ctx(), + "This row could not be dismissed. Try again in a moment.", + MessageType::Error, + ) + .with_details(error); + } + }); + } + } + } + + 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; + } + } +} + +fn register_action(app_context: &Arc, identity: &QualifiedIdentity) -> AppAction { + app_context.set_selected_identity(Some(identity.identity.id())); + AppAction::AddScreen( + ScreenType::RegisterDpnsName(RegisterDpnsNameSource::Identities).create_screen(app_context), + ) +} + +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 = "Add a key to this identity to register usernames."; + 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 { + use crate::model::qualified_identity::encrypted_key_storage::KeyStorage; + use crate::model::qualified_identity::{IdentityStatus, IdentityType}; + use dash_sdk::dpp::identity::Identity; + use dash_sdk::dpp::version::PlatformVersion; + let mut identity = QualifiedIdentity { + identity: Identity::create_basic_identity([1; 32].into(), 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: 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, + }, + ); + 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, + .. + } + )); + } + + #[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/mod.rs b/src/ui/mod.rs index a9cf8a8cf..5bb0f7c8b 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -55,6 +55,7 @@ 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; @@ -197,6 +198,11 @@ 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), @@ -275,6 +281,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, @@ -342,6 +358,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)) } @@ -570,6 +594,7 @@ pub enum Screen { KeyInfoScreen(KeyInfoScreen), KeysScreen(KeysScreen), RegisterDpnsNameScreen(RegisterDpnsNameScreen), + UsernameRequestScreen(UsernameRequestScreen), RegisterDataContractScreen(RegisterDataContractScreen), UpdateDataContractScreen(UpdateDataContractScreen), DocumentActionScreen(DocumentActionScreen), @@ -756,6 +781,7 @@ impl Screen { AddKeyScreen, DocumentQueryScreen, RegisterDpnsNameScreen, + UsernameRequestScreen, RegisterDataContractScreen, UpdateDataContractScreen, DocumentActionScreen, @@ -951,6 +977,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 { @@ -1093,6 +1123,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, 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_usernames.rs b/tests/kittest/identity_usernames.rs index f5f8266dc..aa2023af8 100644 --- a/tests/kittest/identity_usernames.rs +++ b/tests/kittest/identity_usernames.rs @@ -5,18 +5,25 @@ use dash_evo_tool::backend_task::BackendTaskSuccessResult; use dash_evo_tool::backend_task::error::TaskError; use dash_evo_tool::context::AppContext; use dash_evo_tool::context::connection_status::OverallConnectionState; -use dash_evo_tool::model::dpns_usernames::UsernameAvailability; +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::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_sdk::dpp::identity::accessors::{IdentityGettersV0, IdentitySettersV0}; use dash_sdk::dpp::identity::identity_public_key::accessors::v0::{ IdentityPublicKeyGettersV0, IdentityPublicKeySettersV0, @@ -252,3 +259,222 @@ fn view_only_identity_is_told_to_add_a_key() { ); }); } + +fn request(label: &str, phase: RequestPhase) -> UsernameRequest { + let mut request = UsernameRequest::submitted( + label, + 1_700_000_000_000, + dash_evo_tool::model::dpns::ContestDurations { + total: std::time::Duration::from_secs(14 * 86_400), + join: std::time::Duration::from_secs(7 * 86_400), + }, + ); + request.phase = phase; + request +} + +fn mount_settings(app_context: Arc) -> Harness<'static, SettingsTab> { + let mut harness = Harness::builder() + .with_size(egui::vec2(1400.0, 1200.0)) + .build_ui_state( + move |ui, tab: &mut SettingsTab| { + tab.render(ui, &app_context, &mut ProfileCache::default()); + }, + SettingsTab::new(), + ); + harness.run(); + harness +} + +/// 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 ", + "Community vote. Ends around", + "Result: Not decided yet.", + "Leading", + "Other request (", + "Lock, so no one gets it", + "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() + ); + }); +} + +/// USR-TC-030: a Power user with a voting node 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"); + let mut node = app_context + .load_local_user_identities() + .expect("identities") + .into_iter() + .find(|qi| qi.identity.id() == id) + .expect("seeded"); + let voter = Identity::create_basic_identity( + Identifier::from([0x31; 32]), + PlatformVersion::latest(), + ) + .expect("voter"); + let key = IdentityPublicKey::random_key(9, Some(9), PlatformVersion::latest()); + node.associated_voter_identity = Some((voter, key)); + app_context + .update_local_qualified_identity(&node) + .expect("store node"); + 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() + ); + }); +} From 5643f16abb9d44be7e8cea1b5ecee16ed34778c4 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:07:02 +0000 Subject: [PATCH 071/194] feat(dpns): contest cards with weighted tallies and a node set MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit To decide and Voted now render one card per open contest, sorted by time left: a weighted tally with the evonode hint, an influence or tie line from the node set's weight, decision pills with key hints, the node line ("Your nodes: 19 not voted Β· 4 voted Abstain Β· mn-07 has no changes left"), "Voted with {n} of {total} nodes" for partly voted contests, and an inline Refresh voting when a node's state is unproved. Contests no node can vote on collapse into "Can't vote with your nodes". The "Vote with:" chip picks All / Evonodes only / Masternodes only / Custom; key-less and unlisted nodes show their reason and cannot be picked, unknown list membership fails open. "Save as my default" persists per network and feeds the attention badge. A pure composer (model/dpns_voting/composer.rs) turns staged decisions Γ— node set into targets with typed skip reasons; the confirm step adopts it next. The tray reads "{d} decisions ready Β· {t} transactions" and opens the review with exactly the node-set nodes. Co-Authored-By: Claude Opus 5.5 --- src/context/dpns_vote_attention.rs | 1 + src/model/dpns_voting/composer.rs | 449 +++++++++++ src/model/dpns_voting/mod.rs | 1 + src/model/dpns_voting/operator.rs | 3 + src/ui/dpns/contest_card.rs | 487 ++++++++++++ src/ui/dpns/copy.rs | 156 ++++ src/ui/dpns/dpns_contested_names_screen.rs | 849 +++++++++------------ src/ui/dpns/mod.rs | 2 + src/ui/dpns/node_set_picker.rs | 160 ++++ src/ui/state/dpns_vote_cards.rs | 364 +++++++++ src/ui/state/mod.rs | 1 + 11 files changed, 2006 insertions(+), 467 deletions(-) create mode 100644 src/model/dpns_voting/composer.rs create mode 100644 src/ui/dpns/contest_card.rs create mode 100644 src/ui/dpns/node_set_picker.rs create mode 100644 src/ui/state/dpns_vote_cards.rs diff --git a/src/context/dpns_vote_attention.rs b/src/context/dpns_vote_attention.rs index 54eab22a8..97991957c 100644 --- a/src/context/dpns_vote_attention.rs +++ b/src/context/dpns_vote_attention.rs @@ -141,6 +141,7 @@ impl AppContext { }, has_voting_key: identity.can_cast_masternode_vote(), membership: self.masternode_list_membership(id), + alias: identity.alias.clone(), } }) .collect()) diff --git a/src/model/dpns_voting/composer.rs b/src/model/dpns_voting/composer.rs new file mode 100644 index 000000000..765f2691c --- /dev/null +++ b/src/model/dpns_voting/composer.rs @@ -0,0 +1,449 @@ +//! 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, DpnsScheduleEditValidationError, 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, +} + +/// 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, +} + +/// 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. Remove it from your decisions.")] + VotingEnded { contested_name: String }, +} + +/// Exactly what a confirm click sends. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct AggregatePlan { + pub targets: Vec, + pub skipped: Vec, +} + +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() + } + + /// 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 + } +} + +fn resolve_timing( + timing: BatchTiming, + decision: &Decision, + now_ms: u64, +) -> Result { + let outlasts = || ComposeError::ScheduleOutlastsContest { + contested_name: decision.contested_name.clone(), + }; + match timing { + BatchTiming::Now => Ok(VoteTiming::Now), + BatchTiming::BeforeEnd(preset) => { + let end = decision.end_time.ok_or_else(outlasts)?; + relative_schedule(end, preset, now_ms) + .map(VoteTiming::Scheduled) + .map_err(|_: DpnsScheduleEditValidationError| outlasts()) + } + BatchTiming::At(at) => validate_dpns_schedule_time(at, now_ms, decision.end_time) + .map(|()| VoteTiming::Scheduled(at)) + .map_err(|_| outlasts()), + } +} + +/// 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(), + }); + } + 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)) => timing, + Some(NodeTiming::Batch) | None => batch, + }; + 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; + }; + if current == Some(decision.choice) { + plan.skipped.push(skip(SkipReason::AlreadyVoted)); + continue; + } + if current.is_some() && standing.changes.is_exhausted() { + plan.skipped.push(skip(SkipReason::NoChangesLeft)); + continue; + } + plan.targets.push(DpnsVoteTarget { + key: DpnsVoteTargetKey { + network, + voter_id: node.voter_id, + vote_poll_id: decision.vote_poll_id, + }, + voter_alias: node.alias.clone(), + contested_name: decision.contested_name.clone(), + requested_choice: decision.choice, + current_choice: current, + timing: resolve_timing(timing, decision, now_ms)?, + }); + } + } + 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), + } + } + + /// VOTE-TC-090: 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.node_count(), 3); + assert_eq!(plan.change_count(), 0); + assert!(plan.all_now()); + assert!(plan.skipped.is_empty()); + } + + /// VOTE-TC-091/093/007/041: 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-094/095: "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()); + } + + /// VOTE-TC-095 (rejection half): 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::BeforeEnd(Duration::from_secs(600))), + outlasts + ); + assert_eq!(compose_at(BatchTiming::At(5 * MIN)), outlasts); + assert!(compose_at(BatchTiming::At(4 * MIN)).is_ok()); + } + + /// VOTE-TC-104 (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 index 4faa6e4af..bcc7b2437 100644 --- a/src/model/dpns_voting/mod.rs +++ b/src/model/dpns_voting/mod.rs @@ -13,6 +13,7 @@ use dash_sdk::platform::Identifier; use serde::{Deserialize, Serialize}; use std::fmt; +pub mod composer; pub mod contest_timing; pub mod operator; diff --git a/src/model/dpns_voting/operator.rs b/src/model/dpns_voting/operator.rs index e3d2afe86..6c7bdff1b 100644 --- a/src/model/dpns_voting/operator.rs +++ b/src/model/dpns_voting/operator.rs @@ -76,6 +76,8 @@ pub struct VotingNode { 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. @@ -381,6 +383,7 @@ mod tests { kind, has_voting_key: key, membership, + alias: None, } } diff --git a/src/ui/dpns/contest_card.rs b/src/ui/dpns/contest_card.rs new file mode 100644 index 000000000..feaa1ee53 --- /dev/null +++ b/src/ui/dpns/contest_card.rs @@ -0,0 +1,487 @@ +//! 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_voting::contest_timing::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), + format!("Vote for {name}", name = 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 { + match choice { + ResourceVoteChoice::Lock => "Lock".to_owned(), + ResourceVoteChoice::Abstain => "Abstain".to_owned(), + ResourceVoteChoice::TowardsIdentity(id) => card + .contest + .contestants + .iter() + .flatten() + .find(|contender| contender.id == id) + .map(|contender| format!("for {name}", name = contender.name)) + .unwrap_or_else(|| "for another identity".to_owned()), + } +} + +/// 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 { + labels.get(&node).cloned().unwrap_or_else(|| { + let encoded = + node.to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58); + format!("{head}…", head = &encoded[..6]) + }) +} + +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, + 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)) + }; + 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); + }); + }); + 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| { + ( + format!("Vote for {name}", name = 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::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 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!["Vote for alice", "Lock name", "Abstain"]); + } + + #[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("Your nodes: 2 not voted Β· 1 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 index 054fab11e..f57edf30d 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -62,6 +62,129 @@ pub fn deadline_line(name: &str, time_left: Option) -> String { } } +/// `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 { + let margin_votes = if margin == 1 { + "1 vote".to_owned() + } else { + format!("{margin} votes") + }; + match weight { + 1 => format!("{leader} leads by {margin_votes}. Your 1 vote can change who leads."), + 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."; + +/// 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 { + format!("{count} not voted") +} + +/// One part of the node line: nodes that voted `choice`. +pub fn voted_part(count: usize, choice_label: &str) -> String { + format!("{count} 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 sending".to_owned(), + count => format!("{count} sending"), + } +} + +/// One part of the node line: nodes with a scheduled vote. +pub fn scheduled_part(count: usize) -> String { + format!("{count} scheduled") +} + +/// The node line under a card's choices, from its parts. +pub fn node_line(parts: &[String]) -> String { + format!("Your nodes: {parts}", parts = 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). +pub fn tray_label(decisions: usize, transactions: usize) -> String { + let decisions = match decisions { + 1 => "1 decision ready".to_owned(), + count => format!("{count} decisions ready"), + }; + match transactions { + 1 => format!("{decisions} Β· 1 transaction, one per node and name"), + count => format!("{decisions} Β· {count} transactions, one per node and name"), + } +} + +/// Node-set chip (VOTE-FR-075). +pub fn node_set_chip_label(set_name: &str, nodes: usize, weight: u32) -> String { + let nodes = match nodes { + 1 => "1 node".to_owned(), + count => format!("{count} nodes"), + }; + let votes = match weight { + 1 => "1 vote".to_owned(), + weight => format!("{weight} votes"), + }; + format!("Vote with: {set_name} Β· {nodes} Β· {votes}") +} + #[cfg(test)] mod tests { use super::*; @@ -88,6 +211,39 @@ mod tests { 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()]), + ]), + "Your nodes: 19 not voted Β· 4 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!( + 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." + ); + } + #[test] fn deadlines_read_naturally() { assert_eq!(ends_in_label(Some(TimeLeft::Days(1))), "Ends in 1 day"); diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 37335ac9f..0b5517cfd 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -21,18 +21,27 @@ use crate::backend_task::{BackendTask, BackendTaskContext}; use crate::context::AppContext; use crate::model::contested_name::{ContestState, ContestedName}; use crate::model::dpns::normalize_dpns_label; +use crate::model::dpns_voting::contest_timing::{contest_durations, urgency_window}; +use crate::model::dpns_voting::operator::{NodeSet, ResolvedNodeSet, VotingNode, VotingNodeKind}; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, dpns_schedule_is_overdue, validate_dpns_schedule_time, }; +use crate::model::qualified_identity::IdentityType; 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::progress_overlay::{OptionOverlayExt, OverlayConfig, OverlayHandle}; use crate::ui::components::utc_schedule_input::UtcScheduleInput; use crate::ui::components::{BannerHandle, MessageBanner, OptionBannerExt}; -use crate::ui::state::dpns_contests::{ActiveDpnsContestSnapshot, ActiveDpnsContestView}; +use crate::ui::dpns::contest_card::{CardEvent, CardView}; +use crate::ui::dpns::copy::tray_label; +use crate::ui::dpns::node_set_picker; +use crate::ui::state::dpns_contests::ActiveDpnsContestSnapshot; +use crate::ui::state::dpns_vote_cards::{ + CantVoteReason, CardPlacement, NodeContestState, NodeContestStatus, VoteCard, sort_by_time_left, +}; use crate::ui::state::dpns_vote_operations::{DpnsVoteOperationSnapshot, ScheduledDpnsVoteRow}; use crate::ui::state::dpns_vote_state::DpnsVoteStateSnapshot; use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; @@ -40,82 +49,9 @@ use crate::ui::{BackendTaskSuccessResult, MessageType, ScreenLike}; pub use super::VotesView; -/// Active contests bucketed by what the loaded nodes can do with them. -/// -/// Declaration order is display order: the derived `Ord` keys the render map. -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -enum ActiveContestGroup { - NeedsVote, - Voted, - VoteStateUnavailable, - NotVotable, -} - -/// How one contest group renders. Named fields so a callsite cannot transpose -/// "this group is expanded" with "this group accepts votes". -#[derive(Clone, Copy)] -struct ContestGroupPresentation { - default_open: bool, - voting_enabled: bool, - show_current_vote: bool, -} - -impl ActiveContestGroup { - /// Every group, in the order the screen stacks them. - const ALL: [Self; 4] = [ - Self::NeedsVote, - Self::Voted, - Self::VoteStateUnavailable, - Self::NotVotable, - ]; - - fn title(self) -> &'static str { - match self { - Self::NeedsVote => "Needs your vote", - Self::Voted => "Voted", - Self::VoteStateUnavailable => "Vote state unavailable", - Self::NotVotable => "Can't vote with your nodes", - } - } - - /// The Votes sub-view that lists this group. - fn view(self) -> VotesView { - match self { - Self::Voted => VotesView::Voted, - Self::NeedsVote | Self::VoteStateUnavailable | Self::NotVotable => VotesView::ToDecide, - } - } - - /// `no_voting_nodes` opens the un-votable group only when it is all the - /// operator has to look at. - fn presentation(self, no_voting_nodes: bool) -> ContestGroupPresentation { - match self { - Self::NeedsVote => ContestGroupPresentation { - default_open: true, - voting_enabled: true, - show_current_vote: false, - }, - Self::Voted => ContestGroupPresentation { - default_open: false, - voting_enabled: true, - show_current_vote: true, - }, - Self::VoteStateUnavailable => ContestGroupPresentation { - default_open: true, - voting_enabled: false, - show_current_vote: false, - }, - Self::NotVotable => ContestGroupPresentation { - default_open: no_voting_nodes, - voting_enabled: false, - show_current_vote: false, - }, - } - } -} - 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 = "None of your loaded nodes has a voting key."; const NO_VOTING_NODES_DETAIL: &str = "Load a masternode with its voting key to cast votes."; const JOURNAL_UNAVAILABLE_MESSAGE: &str = "Saved voting progress could not be read. The displayed history may be incomplete or out of date. Retry loading before managing votes."; @@ -148,39 +84,6 @@ fn candidate_choice_label(candidate_name: &str) -> String { format!("Vote for {candidate_name}") } -fn classify_vote_states( - states: impl IntoIterator, -) -> ActiveContestGroup { - let mut has_vote = false; - let mut has_unavailable_state = false; - for state in states { - match state { - DpnsCurrentVoteState::Available(None) => return ActiveContestGroup::NeedsVote, - DpnsCurrentVoteState::Available(Some(_)) => has_vote = true, - DpnsCurrentVoteState::Checking | DpnsCurrentVoteState::Unavailable => { - has_unavailable_state = true; - } - } - } - if has_vote { - ActiveContestGroup::Voted - } else if has_unavailable_state { - ActiveContestGroup::VoteStateUnavailable - } else { - ActiveContestGroup::NotVotable - } -} - -fn tally_chip(ui: &mut Ui, votes: u32, dark_mode: bool) { - egui::Frame::new() - .fill(DashColors::surface(dark_mode)) - .corner_radius(egui::CornerRadius::same(255)) - .inner_margin(egui::Margin::symmetric(8, 2)) - .show(ui, |ui| { - ui.label(format!("{votes} votes")); - }); -} - fn short_identifier(identifier: Identifier) -> String { let encoded = identifier.to_string(Encoding::Base58); format!( @@ -237,29 +140,6 @@ fn candidate_name_index( index } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ProvedVoteSummary { - None, - Choice(ResourceVoteChoice), - Mixed, -} - -fn proved_vote_summary( - states: impl IntoIterator, -) -> ProvedVoteSummary { - let mut proved_choice = None; - for state in states { - let DpnsCurrentVoteState::Available(Some(choice)) = state else { - continue; - }; - if proved_choice.is_some_and(|current| current != choice) { - return ProvedVoteSummary::Mixed; - } - proved_choice = Some(choice); - } - proved_choice.map_or(ProvedVoteSummary::None, ProvedVoteSummary::Choice) -} - fn target_status_label(status: DpnsVoteTargetStatus) -> &'static str { match status { DpnsVoteTargetStatus::Scheduled => "Scheduled", @@ -591,6 +471,19 @@ pub struct DPNSScreen { /// Set when the operator asks to load a node; the hosting Masternodes /// screen consumes it and opens its load form. load_node_requested: bool, + + /// 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, + /// Cards ticked for a bulk decision, by contest name. + selected_cards: BTreeSet, + focused_card: Option, } impl DPNSScreen { @@ -636,7 +529,7 @@ impl DPNSScreen { let bulk_identity_options = vec![VoteOption::CastNow; identity_count]; let default_schedule_time = Utc::now() + chrono::Duration::days(1); - Self { + let mut screen = Self { voting_identities, voting_identity_load_error, contested_names, @@ -671,7 +564,17 @@ impl DPNSScreen { set_all_option: VoteOption::CastNow, simple_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(), + selected_cards: BTreeSet::new(), + focused_card: None, + }; + screen.rebuild_cards(); + screen } /// Consume a pending "load a masternode" request from this panel. @@ -721,6 +624,12 @@ impl DPNSScreen { self.candidate_names.clear(); self.contested_names.lock_recover().clear(); self.scheduled_votes.lock_recover().clear(); + 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; } // --------------------------- @@ -830,330 +739,334 @@ impl DPNSScreen { // Rendering: To decide, Voted, Scheduled, History // --------------------------- - /// Render active contests as decision cards grouped by what the loaded nodes can do. - fn render_active_contests(&mut self, ui: &mut Ui) { - let dark_mode = ui.style().visuals.dark_mode; - ui.horizontal(|ui| { - ui.label(RichText::new("Filter by name:").color(DashColors::text_primary(dark_mode))); - ui.text_edit_singleline(&mut self.active_filter_term) - .on_hover_text( - "The letters i and l match the digit 1, and the letter o matches 0.", + /// 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| { + let id = identity.identity.id(); + VotingNode { + id, + kind: if identity.identity_type == IdentityType::Evonode { + VotingNodeKind::Evonode + } else { + VotingNodeKind::Masternode + }, + has_voting_key: true, + membership: self.app_context.masternode_list_membership(id), + alias: identity.alias.clone(), + } + }) + .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)), ); - }); - ui.label( - RichText::new("Each node can change its vote up to four times after its initial vote.") - .color(DashColors::text_secondary(dark_mode)), - ); - ui.add_space(8.0); + } + Err(error) => tracing::debug!(?error, "Could not list key-less nodes for the node set"), + } + nodes + } - let filter = normalize_dpns_label(&self.active_filter_term); - let contests = self.active_contests.contests(); - let mut groups = BTreeMap::>::new(); - for contest in contests.iter() { - groups - .entry(self.contest_group(contest.vote_poll_id)) - .or_default() - .push(contest); + /// 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())); + } - // Counted before the filter is applied: the summary describes the whole - // set of names still open to the operator, not the current search. - let still_open = groups - .get(&ActiveContestGroup::NeedsVote) - .map_or(&[][..], Vec::as_slice); - let available = still_open.len(); - let closing = still_open + /// Votes a staged decision would send: submittable nodes not already on it. + fn transaction_count(&self) -> usize { + self.selected_votes .iter() - .filter(|contest| { - contest.contest.end_time.is_some_and(|end_time| { - let remaining = end_time as i64 - Utc::now().timestamp_millis(); - remaining > 0 && remaining <= chrono::Duration::days(1).num_milliseconds() - }) + .filter_map(|vote| { + let card = self + .cards + .iter() + .find(|card| card.name() == vote.contested_name)?; + Some( + card.nodes + .iter() + .filter(|node| node.status.can_submit()) + .filter(|node| node.current != Some(vote.vote_choice)) + .count(), + ) }) - .count(); - egui::Frame::group(ui.style()).show(ui, |ui| { - ui.label(format!( - "Names still available to your nodes: {available}. Names closing within 24 hours: {closing}.", - )); - }); - ui.add_space(8.0); + .sum() + } - if !filter.is_empty() { - for group in groups.values_mut() { - group.retain(|contest| { - contest - .contest - .normalized_contested_name - .to_lowercase() - .contains(&filter) - }); - } - } + fn apply_node_set(&mut self, node_set: NodeSet) { + self.node_set = node_set; + self.rebuild_cards(); + } - let no_voting_nodes = self.voting_identities.is_empty(); - let view = self.view; - egui::ScrollArea::vertical() - .id_salt("active_contest_cards") - .show(ui, |ui| { - for group in ActiveContestGroup::ALL - .into_iter() - .filter(|group| group.view() == view) - { - let contests = groups.get(&group).map_or(&[][..], Vec::as_slice); - if group == ActiveContestGroup::VoteStateUnavailable { - if contests.is_empty() { - continue; + /// 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| { + if !self.voting_nodes.is_empty() { + let picked = node_set_picker::show( + ui, + &self.node_set, + &self.resolved_nodes, + &self.voting_nodes, + ); + if picked.save_default { + match self.app_context.save_dpns_node_set(&self.node_set) { + Ok(()) => { + self.app_context.recompute_dpns_vote_attention(); } - ui.label("Current votes are unavailable or out of date. Refresh voting to check these nodes."); - if ui.button("Refresh voting").clicked() { - self.pending_backend_task = Some(BackendTask::ContestedResourceTask( - ContestedResourceTask::QueryDPNSContests, - )); + Err(error) => { + MessageBanner::set_global( + ui.ctx(), + error.to_string(), + MessageType::Error, + ) + .with_details(&error); } } - self.render_contest_group( - ui, - group.title(), - contests, - group.presentation(no_voting_nodes), - ); } - self.render_voting_activity(ui); - }); - - ui.separator(); - ui.horizontal(|ui| { - let count = self.selected_votes.len(); - ui.label( - RichText::new(format!("Votes ready to cast: {count}")) - .strong() - .color(DashColors::text_primary(dark_mode)), - ); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ComponentStyles::add_primary_button_enabled(ui, count > 0, "Review and cast") - .disabled_tooltip("Choose a vote on at least one contest before reviewing it.") - .clicked() - { - self.show_bulk_schedule_popup = true; + if let Some(node_set) = picked.changed { + self.apply_node_set(node_set); } + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add( + egui::TextEdit::singleline(&mut self.active_filter_term) + .hint_text("Filter by name") + .desired_width(180.0), + ) + .on_hover_text( + "The letters i and l match the digit 1, and the letter o matches 0.", + ); }); }); - } + ui.add_space(8.0); - fn contest_group(&self, vote_poll_id: Option) -> ActiveContestGroup { - let Some(poll_id) = vote_poll_id else { - return ActiveContestGroup::NotVotable; - }; - classify_vote_states( - self.voting_identities + 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() - .map(|identity| self.vote_state.state(identity.identity.id(), poll_id)), - ) - } + .enumerate() + .filter(|(_, card)| matches_filter(card)) + .filter(|(_, card)| { + card.placement == CardPlacement::CantVote(CantVoteReason::NoVotingNodes) + }) + .map(|(index, _)| index) + .collect() + } else { + Vec::new() + }; - fn render_contest_group( - &mut self, - ui: &mut Ui, - title: &str, - contests: &[&ActiveDpnsContestView], - presentation: ContestGroupPresentation, - ) { - egui::CollapsingHeader::new(format!("{title} ({count})", count = contests.len())) - .default_open(presentation.default_open) + let mut events: Vec<(usize, CardEvent)> = Vec::new(); + egui::ScrollArea::vertical() + .id_salt("active_contest_cards") + .max_height(ui.available_height() - 48.0) .show(ui, |ui| { - if contests.is_empty() { - ui.label("There are no contests in this group."); + 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))); } - for contest in contests { - let mut card = presentation; - card.voting_enabled = presentation.voting_enabled - && self.contest_has_available_target(contest.vote_poll_id); - ui.add_enabled_ui(card.voting_enabled, |ui| { - self.render_contest_card( - ui, - contest.contest.as_ref(), - contest.vote_poll_id, - card, - ); - }); + 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()), + 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); } - }); - } - - fn contest_has_available_target(&self, vote_poll_id: Option) -> bool { - let Some(vote_poll_id) = vote_poll_id else { - return false; - }; - self.voting_identities.iter().any(|identity| { - let voter_id = identity.identity.id(); - matches!( - self.vote_state.state(voter_id, vote_poll_id), - DpnsCurrentVoteState::Available(_) - ) && self - .vote_operations - .target_status(&DpnsVoteTargetKey { - network: self.app_context.network(), - voter_id, - vote_poll_id, - }) - .is_none() - }) - } - - fn proved_vote_for_contest(&self, vote_poll_id: Option) -> ProvedVoteSummary { - let Some(poll_id) = vote_poll_id else { - return ProvedVoteSummary::None; - }; - proved_vote_summary( - self.voting_identities - .iter() - .map(|identity| self.vote_state.state(identity.identity.id(), poll_id)), - ) - } - - fn candidate_name_in_contest( - contest: &ContestedName, - choice: ResourceVoteChoice, - ) -> Option<&str> { - let ResourceVoteChoice::TowardsIdentity(candidate_id) = choice else { - return None; - }; - contest - .contestants - .as_ref()? - .iter() - .find(|candidate| candidate.id == candidate_id) - .map(|candidate| candidate.name.as_str()) - } - - fn render_contest_card( - &mut self, - ui: &mut Ui, - contest: &ContestedName, - vote_poll_id: Option, - presentation: ContestGroupPresentation, - ) { - let ContestGroupPresentation { - voting_enabled, - show_current_vote, - .. - } = presentation; - let dark_mode = ui.style().visuals.dark_mode; - let staged = self - .selected_votes - .iter() - .find(|vote| vote.contested_name == contest.normalized_contested_name) - .map(|vote| vote.vote_choice); - let proved = if show_current_vote { - self.proved_vote_for_contest(vote_poll_id) - } else { - ProvedVoteSummary::None - }; - let selected = staged.or(match proved { - ProvedVoteSummary::Choice(choice) => Some(choice), - ProvedVoteSummary::None | ProvedVoteSummary::Mixed => None, - }); - let locked_votes = contest.locked_votes.unwrap_or_default(); - let abstain_votes = contest.abstain_votes.unwrap_or_default(); - - egui::Frame::group(ui.style()).show(ui, |ui| { - ui.set_min_width(ui.available_width()); - ui.horizontal(|ui| { - ui.label( - RichText::new(format!( - "{name}.dash", - name = contest.normalized_contested_name + if !cant_vote.is_empty() { + egui::CollapsingHeader::new(format!( + "Can't vote with your nodes ({count})", + count = cant_vote.len() )) - .heading() - .strong() - .color(DashColors::text_primary(dark_mode)), - ); - if let Some(end_time) = contest.end_time - && let LocalResult::Single(date_time) = - Utc.timestamp_millis_opt(end_time as i64) - { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + .default_open(!has_voting_nodes) + .show(ui, |ui| { ui.label( - RichText::new(format!( - "Voting ends {when}.", - when = HumanTime::from(date_time) - )) - .color(DashColors::text_secondary(dark_mode)), + RichText::new(CANT_VOTE_REASON) + .color(DashColors::text_secondary(dark_mode)), ); + for index in &cant_vote { + render(ui, *index, &mut events); + } }); } + self.render_voting_activity(ui); }); - ui.add_space(6.0); - match proved { - ProvedVoteSummary::Choice(choice) => { - let candidate_name = Self::candidate_name_in_contest(contest, choice); - ui.label( - RichText::new(format!( - "You voted: {}.", - vote_choice_label(choice, candidate_name) - )) - .strong() - .color(DashColors::text_primary(dark_mode)), - ); - ui.add_space(4.0); + 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); } - ProvedVoteSummary::Mixed => { - ui.label( - RichText::new("Your loaded nodes have different current votes.") - .strong() - .color(DashColors::text_primary(dark_mode)), - ); - ui.add_space(4.0); + CardEvent::ToggleSelected => { + if !self.selected_cards.remove(&name) { + self.selected_cards.insert(name.clone()); + } + } + CardEvent::RefreshVoting => { + self.pending_backend_task = Some(BackendTask::ContestedResourceTask( + ContestedResourceTask::QueryDPNSContests, + )); } - ProvedVoteSummary::None => {} } + self.focused_card = Some(name); + } + + self.render_tray(ui); + } - ui.horizontal_wrapped(|ui| { - let clicked = ui - .selectable_label(selected == Some(ResourceVoteChoice::Lock), "Lock name") - .on_disabled_hover_text( - "None of your loaded nodes can vote on this contest right now.", + /// 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 transactions = self.transaction_count(); + ui.separator(); + ui.horizontal(|ui| { + ui.label(RichText::new(tray_label(decisions, transactions)).strong()); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ComponentStyles::add_primary_button_enabled(ui, transactions > 0, "Cast") + .disabled_tooltip( + "Your nodes already hold these choices. Pick a different decision.", ) - .clicked(); - tally_chip(ui, locked_votes, dark_mode); - if clicked && voting_enabled { - self.set_selected_vote(contest, ResourceVoteChoice::Lock); + .clicked() + { + self.open_review_for_node_set(); } - - let clicked = ui - .selectable_label(selected == Some(ResourceVoteChoice::Abstain), "Abstain") - .clicked(); - tally_chip(ui, abstain_votes, dark_mode); - if clicked && voting_enabled { - self.set_selected_vote(contest, ResourceVoteChoice::Abstain); + if ui.button("Clear").clicked() { + self.selected_votes.clear(); } }); + }); + } - if let Some(contestants) = &contest.contestants { - for contestant in contestants { - ui.horizontal_wrapped(|ui| { - let choice = ResourceVoteChoice::TowardsIdentity(contestant.id); - let clicked = ui - .selectable_label( - selected == Some(choice), - candidate_choice_label(&contestant.name), - ) - .clicked(); - tally_chip(ui, contestant.votes, dark_mode); - ui.label( - RichText::new(short_identifier(contestant.id)) - .monospace() - .color(DashColors::text_secondary(dark_mode)), - ); - if clicked && voting_enabled { - self.set_selected_vote(contest, choice); - } - }); + /// Open the review with exactly the node-set nodes selected. + fn open_review_for_node_set(&mut self) { + let included: BTreeSet = self.resolved_nodes.included.iter().copied().collect(); + self.bulk_identity_options = self + .voting_identities + .iter() + .map(|identity| { + if included.contains(&identity.identity.id()) { + VoteOption::CastNow + } else { + VoteOption::NoVote } - } - }); + }) + .collect(); + self.set_all_option = VoteOption::CastNow; + self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; + self.show_bulk_schedule_popup = true; } fn set_selected_vote(&mut self, contest: &ContestedName, choice: ResourceVoteChoice) { @@ -2380,6 +2293,7 @@ impl ScreenLike for DPNSScreen { { tracing::warn!(?error, "Could not refresh cached DPNS vote state"); } + self.rebuild_cards(); self.app_context.recompute_dpns_vote_attention(); } @@ -2468,6 +2382,7 @@ impl ScreenLike for DPNSScreen { ); } self.rebuild_scheduled_vote_rows(); + self.rebuild_cards(); scheduled_vote_sweep_is_quiet(error) } @@ -2510,6 +2425,7 @@ impl ScreenLike for DPNSScreen { ); } self.rebuild_scheduled_vote_rows(); + self.rebuild_cards(); self.app_context.recompute_dpns_vote_attention(); } BackendTaskSuccessResult::ScheduledVoteSweepCompleted { network, .. } @@ -2923,34 +2839,6 @@ mod tests { ); } - #[test] - fn active_contest_groups_prioritize_nodes_that_still_need_a_vote() { - assert!(matches!( - classify_vote_states([ - DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)), - DpnsCurrentVoteState::Available(None), - ]), - ActiveContestGroup::NeedsVote - )); - assert!(matches!( - classify_vote_states([DpnsCurrentVoteState::Available(Some( - ResourceVoteChoice::Abstain, - ))]), - ActiveContestGroup::Voted - )); - assert!(matches!( - classify_vote_states([ - DpnsCurrentVoteState::Checking, - DpnsCurrentVoteState::Unavailable, - ]), - ActiveContestGroup::VoteStateUnavailable - )); - } - - /// The review sheet is the last surface an operator reads before a - /// masternode vote is submitted, and a vote change is budgeted, so the sheet - /// must always disclose which identity the vote goes to β€” by name when one - /// is cached, by its copyable handle when none is. #[test] fn review_choice_names_the_candidate_or_falls_back_to_its_identifier() { let candidate_id = Identifier::from([42; 32]); @@ -3048,24 +2936,6 @@ mod tests { assert!(!label.contains(&candidate_id.to_string(Encoding::Base58))); } - #[test] - fn proved_choice_is_highlighted_only_when_loaded_nodes_agree() { - assert_eq!( - proved_vote_summary([ - DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Abstain)), - DpnsCurrentVoteState::Checking, - ]), - ProvedVoteSummary::Choice(ResourceVoteChoice::Abstain) - ); - assert_eq!( - proved_vote_summary([ - DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Abstain)), - DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)), - ]), - ProvedVoteSummary::Mixed - ); - } - #[test] fn missing_voting_nodes_copy_is_actionable_and_avoids_the_stale_route() { assert!(NO_VOTING_NODES_DETAIL.contains("masternode")); @@ -3714,6 +3584,7 @@ mod tests { .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() @@ -3734,9 +3605,11 @@ mod tests { "unavailable state must not hide the contest" ); assert!(harness.query_by_label("Refresh voting").is_some()); - assert!(harness.query_by_label( - "Current votes are unavailable or out of date. Refresh voting to check these nodes." - ).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)); @@ -3798,6 +3671,47 @@ mod tests { ); } + /// 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("Your nodes: 1 not voted Β· 1 voted Lock") + .is_some() + ); + } + #[test] fn voting_ui_keyless_users_can_read_cached_active_contests() { use egui_kittest::kittest::Queryable; @@ -3817,6 +3731,7 @@ mod tests { 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| { diff --git a/src/ui/dpns/mod.rs b/src/ui/dpns/mod.rs index 0f22e405c..ae6f6208c 100644 --- a/src/ui/dpns/mod.rs +++ b/src/ui/dpns/mod.rs @@ -1,8 +1,10 @@ //! 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; /// Sub-view of the Masternodes β–Έ Votes segment. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] diff --git a/src/ui/dpns/node_set_picker.rs b/src/ui/dpns/node_set_picker.rs new file mode 100644 index 000000000..af1314474 --- /dev/null +++ b/src/ui/dpns/node_set_picker.rs @@ -0,0 +1,160 @@ +//! `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::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 the masternode list. Its votes don't count.") + } + 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-096/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/state/dpns_vote_cards.rs b/src/ui/state/dpns_vote_cards.rs new file mode 100644 index 000000000..fbc36902a --- /dev/null +++ b/src/ui/state/dpns_vote_cards.rs @@ -0,0 +1,364 @@ +//! 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 + } +} + +/// 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 leaves To decide (it + /// needs no decision) and takes no new decision for that node. + #[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-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/mod.rs b/src/ui/state/mod.rs index 2d151ac4f..28ea489b3 100644 --- a/src/ui/state/mod.rs +++ b/src/ui/state/mod.rs @@ -11,6 +11,7 @@ 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; From 2c8f44b9504f7a08be1330624fb55ca956c432bf Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:08:51 +0000 Subject: [PATCH 072/194] feat(identity): home request cards, outcome banners and main name Show each pending username request as a Home card with its standing, and each finished outcome as a one-time banner tracked by a local seen flag. Refresh request status from the Identities hub on arrival when it is older than five minutes, and periodically while a request is pending (15 minutes on mainnet, 2 on testing networks); a failed background refresh keeps the stored status without a banner. Every place that shows an identity's username reads the device-local main-name choice, and the pending pill reads Waiting for vote. The registration result links straight to the new request status page. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/identity/dpns_usernames.rs | 3 + src/context/contested_names_db.rs | 9 + src/model/dpns_usernames.rs | 91 ++++++++++ src/ui/components/global_nav_switcher.rs | 17 +- src/ui/components/pill.rs | 2 +- src/ui/dashpay/profile_screen.rs | 8 +- src/ui/identity/contacts.rs | 12 +- src/ui/identity/home.rs | 17 +- src/ui/identity/hub_screen.rs | 62 ++++++- src/ui/identity/mod.rs | 1 + src/ui/identity/picker.rs | 10 +- src/ui/identity/register_dpns_name_screen.rs | 9 +- src/ui/identity/username_notices.rs | 177 +++++++++++++++++++ tests/kittest/identity_usernames.rs | 106 +++++++++++ 14 files changed, 482 insertions(+), 42 deletions(-) create mode 100644 src/ui/identity/username_notices.rs diff --git a/src/backend_task/identity/dpns_usernames.rs b/src/backend_task/identity/dpns_usernames.rs index d175cdd62..2e10330a4 100644 --- a/src/backend_task/identity/dpns_usernames.rs +++ b/src/backend_task/identity/dpns_usernames.rs @@ -180,6 +180,9 @@ impl AppContext { .iter() .map(|identity| identity.identity.id()) .collect(); + if identity_ids.is_empty() { + return Ok(BackendTaskSuccessResult::MyUsernameRequestsRefreshed); + } let running = sdk .get_contested_non_resolved_usernames(None) .await diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 908624c70..0bc9d2b9f 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -308,6 +308,15 @@ impl AppContext { .unwrap_or_default() } + /// 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()) + } + /// Persist `requests` as the full request list of `identity_id`. pub fn store_username_requests( &self, diff --git a/src/model/dpns_usernames.rs b/src/model/dpns_usernames.rs index 8487d8d81..07d5dbb6c 100644 --- a/src/model/dpns_usernames.rs +++ b/src/model/dpns_usernames.rs @@ -15,6 +15,41 @@ 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))) +} + /// Whether this device holds a key that can sign username registrations for `identity`. pub fn can_register_usernames(identity: &QualifiedIdentity) -> bool { use dash_sdk::dpp::identity::Purpose; @@ -417,6 +452,62 @@ mod tests { } } + #[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 diff --git a/src/ui/components/global_nav_switcher.rs b/src/ui/components/global_nav_switcher.rs index e06dc6ea3..c6cd6eb25 100644 --- a/src/ui/components/global_nav_switcher.rs +++ b/src/ui/components/global_nav_switcher.rs @@ -122,12 +122,12 @@ fn gather_wallets(app_context: &Arc) -> Vec<(WalletSeedHash, String) /// Identity display label (Local nickname β†’ DPNS β†’ short id). The switcher /// reads no social profile, so the display-name tier is empty. -fn identity_label(qi: &QualifiedIdentity) -> String { - let dpns = qi.dpns_names.first().map(|n| n.name.as_str()); +fn identity_label(app_context: &AppContext, qi: &QualifiedIdentity) -> String { + let dpns = app_context.main_username(qi); display_label( qi.alias.as_deref(), None, - dpns, + dpns.as_deref(), &qi.identity.id().to_string(Encoding::Base58), ) } @@ -510,9 +510,9 @@ fn render_app_global_identity_pill( return; }; - let label = identity_label(active_qi); + let label = identity_label(app_context, 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 { @@ -551,7 +551,7 @@ fn render_app_global_identity_pill( }; for qi in &data.scoped { - let row = identity_label(qi); + let row = identity_label(app_context, qi); if !filter.is_empty() && !row.to_lowercase().contains(&filter) { continue; } @@ -573,7 +573,10 @@ fn render_app_global_identity_pill( for qi in &data.no_wallet { let id = qi.identity.id(); let is_active = data.active_id == Some(id); - if ui.selectable_label(is_active, identity_label(qi)).clicked() { + if ui + .selectable_label(is_active, identity_label(app_context, qi)) + .clicked() + { *effect = GlobalNavEffect::SelectIdentity(id); ui.close(); } diff --git a/src/ui/components/pill.rs b/src/ui/components/pill.rs index 1bd35d0da..1517a50ba 100644 --- a/src/ui/components/pill.rs +++ b/src/ui/components/pill.rs @@ -14,7 +14,7 @@ use eframe::egui::{ }; /// Label shown on the DPNS pending-registration pill. -pub const PENDING_USERNAME_PILL_LABEL: &str = "Pending"; +pub const PENDING_USERNAME_PILL_LABEL: &str = "Waiting for vote"; /// 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 diff --git a/src/ui/dashpay/profile_screen.rs b/src/ui/dashpay/profile_screen.rs index c7c096444..6915d5ace 100644 --- a/src/ui/dashpay/profile_screen.rs +++ b/src/ui/dashpay/profile_screen.rs @@ -801,14 +801,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/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 ad7b056c6..aca9a110f 100644 --- a/src/ui/identity/home.rs +++ b/src/ui/identity/home.rs @@ -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 { @@ -534,6 +534,7 @@ pub fn render( }); } + action |= notices_action; (action, outcome) } @@ -574,11 +575,7 @@ fn build_hero( ) -> 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 8c4d51ccc..9045dd74f 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -58,6 +58,12 @@ 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 username request status was last refreshed (Unix ms). + usernames_refreshed_at: Option, + /// A username refresh is in flight. + usernames_refreshing: bool, + /// 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 @@ -107,6 +113,36 @@ 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); + if self.usernames_refreshing { + return AppAction::None; + } + let network = self.app_context.network; + let any_pending = self.app_context.any_pending_username_request(); + let now = crate::utils::time::now_ms(); + if any_pending { + 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, + any_pending, + network, + ) { + return AppAction::None; + } + self.usernames_refreshed_at = Some(now); + self.usernames_refreshing = true; + AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::RefreshMyUsernameRequests, + )) + } + /// Construct a new hub screen. Follows the project convention: constructors /// handle errors internally via `MessageBanner` and return `Self`. The /// scaffold has nothing to fail on yet. @@ -118,6 +154,9 @@ impl IdentityHubScreen { last_good_landing: HubLanding::Onboarding, home_state: HomeState::default(), settings_tab: SettingsTab::new(), + usernames_refreshed_at: None, + usernames_refreshing: false, + usernames_arriving: true, pending_unloads: BTreeSet::new(), contacts_state: super::contacts::ContactsState::default(), profile_cache: super::profile_cache::ProfileCache::default(), @@ -380,6 +419,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 { @@ -521,6 +561,10 @@ impl ScreenLike for IdentityHubScreen { // migration, so profiles resolve asynchronously via the backend). action |= self.profile_cache.dispatch_pending(); + if matches!(action, AppAction::None) { + action = self.username_refresh_action(ctx); + } + self.prepare_contact_info_dialog(); if let Some((dialog, key)) = &mut self.contact_info_overwrite_dialog { let key = *key; @@ -552,12 +596,22 @@ impl ScreenLike for IdentityHubScreen { action } - fn display_message(&mut self, _message: &str, _message_type: MessageType) { + fn display_message(&mut self, _message: &str, message_type: MessageType) { + if matches!(message_type, MessageType::Error | MessageType::Warning) { + self.usernames_refreshing = false; + } // AppState sets the global banner centrally; the hub itself owns no // in-flight task banners. Sub-tab content overrides its own lifecycle. } fn display_task_result(&mut self, result: BackendTaskSuccessResult) { + if matches!( + result, + BackendTaskSuccessResult::MyUsernameRequestsRefreshed + ) { + self.usernames_refreshing = false; + return; + } // Feed an async DashPay profile load back into the cache the tabs read. self.profile_cache.record_result(&result); @@ -670,6 +724,12 @@ 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 { .. }) { + self.usernames_refreshing = false; + return true; + } if self.handle_contact_request_error(error) { return matches!( contact_info_read_error_key(error), diff --git a/src/ui/identity/mod.rs b/src/ui/identity/mod.rs index 6571a97b2..c31274ebb 100644 --- a/src/ui/identity/mod.rs +++ b/src/ui/identity/mod.rs @@ -57,6 +57,7 @@ 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; diff --git a/src/ui/identity/picker.rs b/src/ui/identity/picker.rs index 7649b018f..697b48a5c 100644 --- a/src/ui/identity/picker.rs +++ b/src/ui/identity/picker.rs @@ -97,7 +97,7 @@ pub fn render( } match cell { PickerCell::Identity(identity) => { - let card = build_card(identity); + let card = build_card(app_context, identity); let response = card.show(ui); if response.clicked { captured_selection = Some(response.identity_id.clone()); @@ -155,7 +155,7 @@ enum PickerCell<'a> { /// display-name so users who have labelled their identities still see a /// familiar heading. When a real social-profile display name becomes /// available upstream, wiring it into this function is a one-line change. -fn build_card(identity: &QualifiedIdentity) -> IdentityPickerCard { +fn build_card(app_context: &AppContext, identity: &QualifiedIdentity) -> IdentityPickerCard { let id_base58 = identity.identity.id().to_string(Encoding::Base58); // Balance formatting: design-spec Β§B.14 uses `{amount} DASH` with tabular @@ -182,10 +182,8 @@ fn build_card(identity: &QualifiedIdentity) -> IdentityPickerCard { if let Some(alias) = identity.alias.as_deref().filter(|s| !s.trim().is_empty()) { card = card.with_display_name(alias); } - 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 fbe4cf6ed..7f42f4a37 100644 --- a/src/ui/identity/register_dpns_name_screen.rs +++ b/src/ui/identity/register_dpns_name_screen.rs @@ -611,11 +611,18 @@ impl RegisterDpnsNameScreen { ui.add_space(16.0); ui.horizontal(|ui| { if outcome == DpnsRegistrationOutcome::PendingCommunityVote + && let Some(identity) = &self.selected_qualified_identity && ComponentStyles::add_secondary_button(ui, "View request status", dark_mode) .clicked() { - action = AppAction::SetMainScreenThenPopScreen( + 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() { diff --git a/src/ui/identity/username_notices.rs b/src/ui/identity/username_notices.rs new file mode 100644 index 000000000..97c7b85be --- /dev/null +++ b/src/ui/identity/username_notices.rs @@ -0,0 +1,177 @@ +//! 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::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::{RegisterDpnsNameSource, status_line}; +use crate::ui::identity::username_copy::{Tone, format_date, phase_label, standing_line}; +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"; + +/// Text of the one-time banner for a finished request, if it gets one. +pub fn outcome_banner_text(request: &UsernameRequest) -> Option { + let name = &request.label; + match request.phase { + RequestPhase::Won => Some(format!( + "You're @{name}. People can now find and pay you by this name." + )), + 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::Joinable | RequestPhase::Voting => None, + } +} + +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: BTreeSet = ui + .ctx() + .data(|data| data.get_temp(session_id)) + .unwrap_or_default(); + let mut session_changed = false; + + for request in &requests { + let Some(text) = outcome_banner_text(request) else { + continue; + }; + let key = banner_key(&identity_id, request); + if !session.contains(&key) { + if app_context.username_outcome_seen(&identity_id, request) { + continue; + } + if let Err(error) = app_context.mark_username_outcome_seen(&identity_id, request) { + tracing::debug!( + ?error, + "Username outcome banner could not be marked as seen" + ); + } + session.insert(key.clone()); + session_changed = true; + } + 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 request.phase == RequestPhase::Lost + && ui.button("Choose another username").clicked() + { + action = AppAction::AddScreen( + ScreenType::RegisterDpnsName(RegisterDpnsNameSource::Identities) + .create_screen(app_context), + ); + } + if ui.button("Dismiss").clicked() { + session.remove(&key); + session_changed = true; + } + }); + }); + } + if session_changed { + 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 name = &request.label; + let first = match request.end { + 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."), + }; + ui.label(RichText::new(first).strong()); + 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 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::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, + }, + ); + 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.") + ); + } +} diff --git a/tests/kittest/identity_usernames.rs b/tests/kittest/identity_usernames.rs index aa2023af8..ebca08851 100644 --- a/tests/kittest/identity_usernames.rs +++ b/tests/kittest/identity_usernames.rs @@ -18,6 +18,7 @@ use dash_evo_tool::model::qualified_identity::{ 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, @@ -478,3 +479,108 @@ fn request_status_page_links_voters() { ); }); } + +fn mount_home(app_context: Arc) -> Harness<'static, (HomeState, ProfileCache)> { + let mut harness = Harness::builder() + .with_size(egui::vec2(1280.0, 1200.0)) + .build_ui_state( + move |ui, state: &mut (HomeState, ProfileCache)| { + let _ = home::render(ui, &app_context, &state.0, &mut state.1); + }, + (HomeState::default(), ProfileCache::default()), + ); + harness.run(); + harness +} + +/// USR-TC-021: "Show as main" changes the shown name locally, with no backend task. +#[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", "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!( + 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() + ); + }); +} + +/// 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()); + }); +} + +/// 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 first = mount_home(app_context.clone()); + assert!(first.query_by_label_contains(banner).is_some()); + drop(first); + let second = mount_home(app_context); + assert!(second.query_by_label_contains(banner).is_none()); + }); +} From 26424f5d985b171badadb7b3565b43b2fb31eca9 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:12:45 +0000 Subject: [PATCH 073/194] feat(identity): signing key choice for usernames and user stories Let Power users choose the signing key under Advanced on the confirm step; the backend accepts only an enabled authentication key strong enough for DPNS documents. Mark DPN-001, 002, 008, 010, 012 and 016 as implemented. Co-Authored-By: Claude Opus 5.5 --- docs/user-stories.md | 12 ++-- src/backend_task/identity/mod.rs | 2 + .../identity/register_dpns_name.rs | 56 ++++++++++++++++++- src/ui/identity/register_dpns_name_screen.rs | 33 ++++++++--- tests/backend-e2e/dashpay_tasks.rs | 1 + tests/backend-e2e/framework/fixtures.rs | 1 + tests/backend-e2e/register_dpns.rs | 1 + 7 files changed, 88 insertions(+), 18 deletions(-) diff --git a/docs/user-stories.md b/docs/user-stories.md index 7d3587803..ff14f8c84 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -769,7 +769,7 @@ As a user, I want to remove an identity from this device from the identity's own ## DPNS (DPN) -### DPN-001: Register a username [Gap] +### DPN-001: Register a username [Implemented] **Persona:** Alex, Priya 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. @@ -781,7 +781,7 @@ As a user, I want to register a username for one of my identities so that others - While registration runs, a full-window blocking overlay (UX-001) prevents a duplicate submission. - Completion distinguishes a username registered for immediate use from a request submitted for a community vote. -### DPN-002: View my usernames [Gap] +### DPN-002: View my usernames [Implemented] **Persona:** Alex, Priya 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. @@ -842,7 +842,7 @@ As a masternode operator, I want to choose which nodes vote and decide many cont - Switching networks clears drafts and open dialogs. - A successful mixed batch reports cast and scheduled counts. -### DPN-008: Choose which username is shown [Gap] +### DPN-008: 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. @@ -861,7 +861,7 @@ As a masternode operator, I want my previously scheduled DPNS votes to survive a - 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. -### DPN-010: See a pending username request [Gap] +### 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 I have already chosen. @@ -881,7 +881,7 @@ As a masternode operator, I want DET to keep checking a submitted vote whose res - 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 [Gap] +### 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. @@ -917,7 +917,7 @@ As a masternode operator, I want votes to go out in the background with per-node - 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 [Gap] +### 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. diff --git a/src/backend_task/identity/mod.rs b/src/backend_task/identity/mod.rs index 54189051f..1b648d729 100644 --- a/src/backend_task/identity/mod.rs +++ b/src/backend_task/identity/mod.rs @@ -451,6 +451,8 @@ impl PartialEq for IdentityTopUpInfo { pub struct RegisterDpnsNameInput { pub qualified_identity: QualifiedIdentity, pub name_input: String, + /// Authentication key to sign with; `None` picks the identity's default document key. + pub signing_key_id: Option, } #[derive(Debug, Clone, PartialEq)] diff --git a/src/backend_task/identity/register_dpns_name.rs b/src/backend_task/identity/register_dpns_name.rs index 344e8dc46..3051c67d7 100644 --- a/src/backend_task/identity/register_dpns_name.rs +++ b/src/backend_task/identity/register_dpns_name.rs @@ -28,6 +28,20 @@ use dash_sdk::{ use super::{BackendTaskSuccessResult, RegisterDpnsNameInput}; +/// Whether `key` may sign documents of `document_type`: an enabled authentication +/// key at least as strong as the type requires, and never a master key. +fn can_sign_documents( + key: &dash_sdk::platform::IdentityPublicKey, + document_type: &dash_sdk::dpp::data_contract::document_type::DocumentTypeRef, +) -> 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() <= document_type.security_level_requirement() +} + fn rebrand_dpns_domain_conflict(error: TaskError) -> TaskError { match error { TaskError::PlatformEntryConflict { source_error } => { @@ -159,9 +173,15 @@ impl AppContext { ) .map_err(|error| SdkError::Protocol(*error))?; - let public_key = qualified_identity - .document_signing_key(&preorder_document_type) - .ok_or(TaskError::NoDocumentSigningKey)?; + let public_key = match input.signing_key_id { + Some(key_id) => qualified_identity + .identity + .get_public_key_by_id(key_id) + .filter(|key| can_sign_documents(key, &preorder_document_type)) + .filter(|key| can_sign_documents(key, &domain_document_type)), + 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); @@ -303,6 +323,36 @@ impl AppContext { #[cfg(test)] mod tests { use super::*; + + #[test] + fn chosen_signing_key_must_suit_dpns_documents() { + use dash_sdk::dpp::data_contracts::SystemDataContract; + use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; + use dash_sdk::dpp::identity::{Purpose, SecurityLevel}; + use dash_sdk::dpp::system_data_contracts::load_system_data_contract; + use dash_sdk::dpp::version::PlatformVersion; + let pv = PlatformVersion::latest(); + let contract = load_system_data_contract(SystemDataContract::DPNS, pv).expect("DPNS"); + let domain = contract.document_type_for_name("domain").expect("domain"); + let key = |purpose, level| { + let mut key = dash_sdk::platform::IdentityPublicKey::random_key(1, Some(1), pv); + key.set_purpose(purpose); + key.set_security_level(level); + key + }; + assert!(can_sign_documents( + &key(Purpose::AUTHENTICATION, SecurityLevel::HIGH), + &domain + )); + assert!(!can_sign_documents( + &key(Purpose::AUTHENTICATION, SecurityLevel::MASTER), + &domain + )); + assert!(!can_sign_documents( + &key(Purpose::TRANSFER, SecurityLevel::CRITICAL), + &domain + )); + } use dash_sdk::dpp::consensus::ConsensusError::StateError as ConsensusStateError; use dash_sdk::dpp::consensus::state::state_error::StateError; diff --git a/src/ui/identity/register_dpns_name_screen.rs b/src/ui/identity/register_dpns_name_screen.rs index 7f42f4a37..b56651fa0 100644 --- a/src/ui/identity/register_dpns_name_screen.rs +++ b/src/ui/identity/register_dpns_name_screen.rs @@ -27,6 +27,7 @@ use crate::ui::components::wallet_unlock_popup::{ use crate::ui::components::{ MessageBanner, OptionOverlayExt, OverlayConfig, OverlayHandle, ResultBannerExt, }; +use crate::ui::helpers::{TransactionType, add_key_chooser_with_doc_type}; use crate::ui::identity::identity_pill::display_label; use crate::ui::identity::username_copy::{ self, AvailabilityRow, Tone, USERNAME_RULES, availability_line, offers_suggestions, @@ -37,6 +38,7 @@ use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dash_sdk::dpp::platform_value::string_encoding::Encoding; +use dash_sdk::platform::IdentityPublicKey; use eframe::egui::{Context, Frame, Margin}; use egui::{RichText, Ui}; use std::sync::{Arc, RwLock}; @@ -83,6 +85,8 @@ pub struct RegisterDpnsNameScreen { availability: Availability, step: Step, consent_dialog: 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, @@ -102,6 +106,7 @@ impl RegisterDpnsNameScreen { availability: Availability::Idle, step: Step::Choose, consent_dialog: None, + selected_key: None, selected_wallet: None, wallet_unlock_popup: WalletUnlockPopup::new(), wallet_open_attempted: false, @@ -141,6 +146,7 @@ impl RegisterDpnsNameScreen { .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.selected_key = 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()) @@ -265,6 +271,7 @@ impl RegisterDpnsNameScreen { let task = IdentityTask::RegisterDpnsName(RegisterDpnsNameInput { qualified_identity: identity.clone(), name_input: self.label().to_owned(), + signing_key_id: self.selected_key.as_ref().map(|key| key.id()), }); self.step = Step::Submitting; self.raise_progress_overlay(ctx); @@ -480,17 +487,25 @@ impl RegisterDpnsNameScreen { egui::CollapsingHeader::new("Advanced") .default_open(false) .show(ui, |ui| { - let key = self + let document_type = self .app_context .dpns_contract - .document_type_for_name("domain") - .ok() - .and_then(|document_type| identity.document_signing_key(&document_type)) - .map(|key| key.id()); - match key { - Some(id) => ui.label(format!("Signing key: Authentication key {id}")), - None => ui.label("No signing key is available for this identity."), - }; + .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(), + ); }); } diff --git a/tests/backend-e2e/dashpay_tasks.rs b/tests/backend-e2e/dashpay_tasks.rs index 72b9a88ad..13f21fc10 100644 --- a/tests/backend-e2e/dashpay_tasks.rs +++ b/tests/backend-e2e/dashpay_tasks.rs @@ -991,6 +991,7 @@ async fn tc_043_reject_contact_request() { dash_evo_tool::backend_task::identity::RegisterDpnsNameInput { qualified_identity: qi_c.clone(), name_input: username_c.clone(), + signing_key_id: None, }, ), ); diff --git a/tests/backend-e2e/framework/fixtures.rs b/tests/backend-e2e/framework/fixtures.rs index 1f6c89fbc..ab5aa35bb 100644 --- a/tests/backend-e2e/framework/fixtures.rs +++ b/tests/backend-e2e/framework/fixtures.rs @@ -356,6 +356,7 @@ async fn register_dpns_name( let task = BackendTask::IdentityTask(IdentityTask::RegisterDpnsName(RegisterDpnsNameInput { qualified_identity: qi, name_input: name.clone(), + 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 5dab6cca2..009a86327 100644 --- a/tests/backend-e2e/register_dpns.rs +++ b/tests/backend-e2e/register_dpns.rs @@ -44,6 +44,7 @@ async fn test_register_dpns_name() { let task = BackendTask::IdentityTask(IdentityTask::RegisterDpnsName(RegisterDpnsNameInput { qualified_identity: qualified_identity.clone(), name_input: dpns_name.clone(), + signing_key_id: None, })); let result = run_task(app_context, task) .await From e77b50d532d187f1ac3524de6cf6f9aea8acef7b Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:22:28 +0000 Subject: [PATCH 074/194] feat(dpns): aggregate confirm step for staged votes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The per-target review sheet becomes one confirm step (VOTE-FR-080): "Cast {d} decisions with {n} nodes", a decision list, the transaction line, the change warning once per batch, and "Skipped: {s} votes" with typed reasons. Timing is Now / When voting is about to end (editable lead time, VOTE-FR-081) / At a specific time; "Adjust nodes" sets per-node timing or "Don't use this node" and lists every node Γ— name with current β†’ requested choice and changes left. Enter confirms, Esc cancels; staged decisions survive a cancel. Targets come from the pure composer: unproved, in-progress and out-of-changes nodes are skipped with a reason instead of blocking the whole batch; locked targets still never get a second operation, and the batch time is validated against every contest's deadline. A node loaded after decisions were staged stays out of them. A "before the end" schedule records its preset in a side map keyed by target and absolute time; Scheduled shows "6 hours before the end Β· {UTC}" and falls back to the absolute time when no label exists. Co-Authored-By: Claude Opus 5.5 --- src/context/dpns_vote_preferences.rs | 70 +- src/model/dpns_voting/composer.rs | 28 +- src/ui/dpns/copy.rs | 146 ++- src/ui/dpns/dpns_contested_names_screen.rs | 1205 ++++++++++---------- 4 files changed, 845 insertions(+), 604 deletions(-) diff --git a/src/context/dpns_vote_preferences.rs b/src/context/dpns_vote_preferences.rs index e0d49d2b2..6d4c7af17 100644 --- a/src/context/dpns_vote_preferences.rs +++ b/src/context/dpns_vote_preferences.rs @@ -1,16 +1,20 @@ //! Per-network operator preferences for masternode voting: the last-used -//! Masternodes segment and the saved node set. +//! Masternodes segment, the saved node set, and the display label of +//! relative ("before the end") schedules. //! //! 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::DpnsVoteTargetKey; use crate::model::dpns_voting::operator::{MasternodesSegment, NodeSet}; use crate::wallet_backend::DetScope; use dash_sdk::dpp::dashcore::Network; +use dash_sdk::dpp::identity::TimestampMillis; use serde::Serialize; use serde::de::DeserializeOwned; +use std::time::Duration; fn segment_key(network: Network) -> String { format!("{network}:dpns_voting:masternodes_segment") @@ -20,6 +24,22 @@ fn node_set_key(network: Network) -> String { format!("{network}:dpns_voting:node_set") } +/// Keyed by the absolute time too: an edit to another time orphans the label, +/// and the row falls back to the absolute time alone. The target is hashed to +/// fit the store's key-length limit. +fn relative_label_key(key: &DpnsVoteTargetKey, scheduled_at: TimestampMillis) -> String { + use dash_sdk::dpp::dashcore::hashes::{Hash, sha256}; + let mut preimage = Vec::with_capacity(72); + preimage.extend_from_slice(key.voter_id.as_bytes()); + preimage.extend_from_slice(key.vote_poll_id.as_bytes()); + preimage.extend_from_slice(&scheduled_at.to_be_bytes()); + format!( + "{network}:dpns_voting:relative:{digest}", + network = key.network, + digest = sha256::Hash::hash(&preimage), + ) +} + impl AppContext { fn voting_preference(&self, key: &str) -> Result, TaskError> { self.app_kv().get(DetScope::Global, key).map_err(|source| { @@ -61,6 +81,32 @@ impl AppContext { pub fn save_dpns_node_set(&self, node_set: &NodeSet) -> Result<(), TaskError> { self.put_voting_preference(&node_set_key(self.network()), node_set) } + + /// Remember that the target scheduled at `scheduled_at` was picked as + /// `preset` before its contest's end (VOTE-FR-081). Display only: the + /// absolute time in the journal stays authoritative. + pub fn save_dpns_relative_schedule_label( + &self, + key: &DpnsVoteTargetKey, + scheduled_at: TimestampMillis, + preset: Duration, + ) -> Result<(), TaskError> { + let preset_ms = u64::try_from(preset.as_millis()).unwrap_or(u64::MAX); + self.put_voting_preference(&relative_label_key(key, scheduled_at), &preset_ms) + } + + /// The relative preset a scheduled target was picked with, if recorded. + pub fn dpns_relative_schedule_label( + &self, + key: &DpnsVoteTargetKey, + scheduled_at: TimestampMillis, + ) -> Option { + self.voting_preference::(&relative_label_key(key, scheduled_at)) + .inspect_err(|error| tracing::debug!(?error, "Relative schedule label unreadable")) + .ok() + .flatten() + .map(Duration::from_millis) + } } #[cfg(test)] @@ -69,6 +115,28 @@ mod tests { use dash_sdk::platform::Identifier; use std::collections::BTreeSet; + /// VOTE-TC-094 (label half): the label is bound to the exact time; a + /// different time reads no label, so the row shows the absolute time only. + #[test] + fn relative_label_is_bound_to_its_absolute_time() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let context = crate::context::test_support::test_app_context(temp_dir.path()); + let key = DpnsVoteTargetKey { + network: context.network(), + voter_id: Identifier::from([1; 32]), + vote_poll_id: Identifier::from([2; 32]), + }; + let six_hours = Duration::from_secs(6 * 3600); + context + .save_dpns_relative_schedule_label(&key, 1_000, six_hours) + .expect("save label"); + assert_eq!( + context.dpns_relative_schedule_label(&key, 1_000), + Some(six_hours) + ); + assert_eq!(context.dpns_relative_schedule_label(&key, 2_000), None); + } + #[test] fn keys_are_network_scoped() { assert_ne!(segment_key(Network::Mainnet), segment_key(Network::Testnet)); diff --git a/src/model/dpns_voting/composer.rs b/src/model/dpns_voting/composer.rs index 765f2691c..a30ff9cb6 100644 --- a/src/model/dpns_voting/composer.rs +++ b/src/model/dpns_voting/composer.rs @@ -179,6 +179,8 @@ pub fn compose( contested_name: decision.contested_name.clone(), }); } + // The batch timing 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, @@ -190,8 +192,8 @@ pub fn compose( plan.skipped.push(skip(SkipReason::NotUsed)); continue; } - Some(NodeTiming::Override(timing)) => timing, - Some(NodeTiming::Batch) | None => batch, + Some(NodeTiming::Override(timing)) => Some(timing), + Some(NodeTiming::Batch) | None => None, }; let standing = standing(node.voter_id, decision.vote_poll_id); if standing.locked { @@ -220,7 +222,10 @@ pub fn compose( contested_name: decision.contested_name.clone(), requested_choice: decision.choice, current_choice: current, - timing: resolve_timing(timing, decision, now_ms)?, + timing: match timing { + Some(timing) => resolve_timing(timing, decision, now_ms)?, + None => batch_timing, + }, }); } } @@ -425,6 +430,23 @@ mod tests { ); 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-TC-104 (compose half): a decision whose voting ended is refused. diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index f57edf30d..bc42b6e50 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -3,7 +3,8 @@ //! Each function returns one complete translation unit with its plural pair, //! so no caller concatenates fragments. -use crate::model::dpns_voting::operator::TimeLeft; +use crate::model::dpns_voting::composer::SkipReason; +use crate::model::dpns_voting::operator::{ChangesLeft, TimeLeft}; /// A remaining time as a phrase, e.g. `3 hours`. pub fn time_left_phrase(time_left: TimeLeft) -> String { @@ -185,6 +186,112 @@ pub fn node_set_chip_label(set_name: &str, nodes: usize, weight: u32) -> String format!("Vote with: {set_name} Β· {nodes} Β· {votes}") } +/// 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). +pub fn confirm_transactions_line(transactions: usize) -> String { + match transactions { + 1 => "1 transaction, one per node and name. Voting is free for your nodes.".to_owned(), + count => { + format!("{count} transactions, one per node and name. Voting is free for your nodes.") + } + } +} + +/// 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"), + } +} + +/// One skipped-reason line, e.g. `2 votes: no changes left (5 of 5 votes used)`. +pub fn skipped_reason_line(count: usize, reason: SkipReason) -> String { + let votes = match count { + 1 => "1 vote".to_owned(), + count => format!("{count} votes"), + }; + let reason = match reason { + SkipReason::AlreadyVoted => "the node already voted this way", + SkipReason::NoChangesLeft => "no changes left (5 of 5 votes used)", + SkipReason::VoteStateUnavailable => { + "vote state is unavailable; refresh voting to include it" + } + SkipReason::AlreadyInProgress => "an earlier vote on this name is still being sent", + SkipReason::NotUsed => "you chose not to use the node", + }; + format!("{votes}: {reason}") +} + +/// Confirm primary button (VOTE-FR-080). +pub fn confirm_button_label(transactions: usize, all_now: bool) -> String { + match (transactions, all_now) { + (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, 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(1) => "1 change left, counted on this device".to_owned(), + ChangesLeft::Known(left) => format!("{left} changes left, counted on this device"), + ChangesLeft::Unknown => { + "Changes left unknown. This node voted outside Dash Evo Tool.".to_owned() + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -244,6 +351,43 @@ mod tests { ); } + /// VOTE-TC-090/091 (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), + "72 transactions, one per node and name. Voting is free for your nodes." + ); + 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), + "1 vote: no changes left (5 of 5 votes used)" + ); + assert_eq!(confirm_button_label(72, true), "Cast 72 votes"); + assert_eq!(confirm_button_label(1, 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 changes left, counted on this device" + ); + assert_eq!( + changes_left_label(ChangesLeft::Unknown), + "Changes left unknown. This node voted outside Dash Evo Tool." + ); + } + #[test] fn deadlines_read_naturally() { assert_eq!(ends_in_label(Some(TimeLeft::Days(1))), "Ends in 1 day"); diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 0b5517cfd..83b52fcd0 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -21,12 +21,19 @@ use crate::backend_task::{BackendTask, BackendTaskContext}; use crate::context::AppContext; use crate::model::contested_name::{ContestState, ContestedName}; use crate::model::dpns::normalize_dpns_label; +use crate::model::dpns_voting::composer::{ + AggregatePlan, BatchTiming, ComposeError, ComposerNode, Decision, NodeStanding, NodeTiming, + SkipReason, compose, +}; use crate::model::dpns_voting::contest_timing::{contest_durations, urgency_window}; -use crate::model::dpns_voting::operator::{NodeSet, ResolvedNodeSet, VotingNode, VotingNodeKind}; +use crate::model::dpns_voting::operator::{ + ChangesLeft, NodeSet, ResolvedNodeSet, VotingNode, VotingNodeKind, relative_schedule_preset, + time_left, +}; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, - dpns_schedule_is_overdue, validate_dpns_schedule_time, + dpns_schedule_is_overdue, }; use crate::model::qualified_identity::IdentityType; use crate::model::qualified_identity::QualifiedIdentity; @@ -35,8 +42,14 @@ use crate::ui::components::confirmation_dialog::{ConfirmationDialog, Confirmatio use crate::ui::components::progress_overlay::{OptionOverlayExt, OverlayConfig, OverlayHandle}; use crate::ui::components::utc_schedule_input::UtcScheduleInput; use crate::ui::components::{BannerHandle, MessageBanner, OptionBannerExt}; +use crate::ui::dpns::contest_card::node_label; use crate::ui::dpns::contest_card::{CardEvent, CardView}; use crate::ui::dpns::copy::tray_label; +use crate::ui::dpns::copy::{ + 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, + skipped_header, skipped_reason_line, +}; use crate::ui::dpns::node_set_picker; use crate::ui::state::dpns_contests::ActiveDpnsContestSnapshot; use crate::ui::state::dpns_vote_cards::{ @@ -46,6 +59,7 @@ use crate::ui::state::dpns_vote_operations::{DpnsVoteOperationSnapshot, Schedule use crate::ui::state::dpns_vote_state::DpnsVoteStateSnapshot; use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; use crate::ui::{BackendTaskSuccessResult, MessageType, ScreenLike}; +use crate::utils::time::now_ms; pub use super::VotesView; @@ -235,72 +249,80 @@ fn loaded_voting_identities(app_context: &AppContext) -> Result String { - self.target - .voter_alias - .clone() - .unwrap_or_else(|| short_identifier(self.target.key.voter_id)) - } -} - -/// Exactly what a submit click would send, resolved before the review is shown. +/// Exactly what a confirm click would send, resolved before the confirm step +/// is shown. struct ReviewPlan { - entries: Vec, + aggregate: AggregatePlan, + /// One line per staged decision: name, choice, and the nodes casting it. + decisions: Vec<(Decision, usize)>, voters: Vec, } impl ReviewPlan { - /// The targets that will really be submitted, no-op targets removed. - fn effective(&self) -> impl Iterator { - self.entries.iter().filter(|entry| !entry.target.is_no_op()) + /// The targets that will really be submitted. + fn targets(&self) -> &[DpnsVoteTarget] { + &self.aggregate.targets } fn effective_count(&self) -> usize { - self.effective().count() - } - - fn no_op_count(&self) -> usize { - self.entries.len() - self.effective_count() + self.aggregate.targets.len() } fn node_count(&self) -> usize { - self.effective() - .map(|entry| entry.target.key.voter_id) - .collect::>() - .len() + self.aggregate.node_count() } fn has_immediate(&self) -> bool { - self.effective() - .any(|entry| matches!(entry.target.timing, VoteTiming::Now)) + self.targets() + .iter() + .any(|target| matches!(target.timing, VoteTiming::Now)) } fn has_scheduled(&self) -> bool { - self.effective() - .any(|entry| matches!(entry.target.timing, VoteTiming::Scheduled(_))) + self.targets() + .iter() + .any(|target| matches!(target.timing, VoteTiming::Scheduled(_))) } } -fn review_headline(effective_count: usize, node_count: usize) -> String { - format!("Votes to submit ({effective_count}) from your nodes ({node_count}).") +/// 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, } -fn review_skipped_line(no_op_count: usize) -> String { - match no_op_count { - 1 => "1 vote is already cast as requested and will be skipped.".to_owned(), - skipped_count => { - format!("{skipped_count} votes are already cast as requested and will be skipped.") +impl ConfirmTiming { + const ALL: [Self; 3] = [Self::Now, Self::BeforeEnd, Self::At]; + + fn label(self) -> &'static str { + match self { + 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>, @@ -328,12 +350,19 @@ pub enum ReviewPlanError { #[source] source: Arc, }, - #[error( - "This node's vote for {contested_name} is already in progress. Check its result before submitting again." - )] - VoteAlreadyInProgress { contested_name: String }, - #[error("Current vote state is unavailable. Refresh voting before applying votes.")] - CurrentVoteUnavailable, + #[error("Voting has ended for {contested_name}.dash. Clear it from your decisions.")] + VotingEnded { contested_name: String }, +} + +impl From for ReviewPlanError { + fn from(error: ComposeError) -> Self { + match error { + ComposeError::ScheduleOutlastsContest { contested_name } => { + Self::ScheduleOutlastsContest { contested_name } + } + ComposeError::VotingEnded { contested_name } => Self::VotingEnded { contested_name }, + } + } } /// Why a submit click produced nothing to send. @@ -380,19 +409,6 @@ pub struct SelectedVote { pub end_time: Option, } -#[derive(Clone)] -pub enum VoteOption { - NoVote, - CastNow, - Scheduled { - days: u32, - hours: u32, - minutes: u32, - }, - /// Absolute UTC time, in Unix milliseconds. - ScheduledAt(u64), -} - pub enum VoteHandlingStatus { NotStarted, CastingVotes, @@ -461,10 +477,15 @@ pub struct DPNSScreen { /// Selected vote handling show_bulk_schedule_popup: bool, - bulk_identity_options: Vec, + /// Per-node overrides under `Adjust nodes`; absent means "same as above". + node_overrides: BTreeMap, + /// Set by `Review again`: the confirm step covers only this node. + retry_voter: Option, bulk_vote_handling_status: VoteHandlingStatus, submission_error_banner: Option, - set_all_option: VoteOption, + 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. simple_schedule: UtcScheduleInput, @@ -481,6 +502,9 @@ pub struct DPNSScreen { 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>, /// Cards ticked for a bulk decision, by contest name. selected_cards: BTreeSet, focused_card: Option, @@ -525,8 +549,6 @@ impl DPNSScreen { } // Initialize vote handling pop-up state to hidden - let identity_count = voting_identities.len(); - let bulk_identity_options = vec![VoteOption::CastNow; identity_count]; let default_schedule_time = Utc::now() + chrono::Duration::days(1); let mut screen = Self { @@ -558,10 +580,12 @@ impl DPNSScreen { // Vote handling show_bulk_schedule_popup: false, - bulk_identity_options, + node_overrides: BTreeMap::new(), + retry_voter: None, bulk_vote_handling_status: VoteHandlingStatus::NotStarted, submission_error_banner: None, - set_all_option: VoteOption::CastNow, + confirm_timing: ConfirmTiming::Now, + relative_preset: relative_schedule_preset(app_context.network()), simple_schedule: UtcScheduleInput::new().with_time(default_schedule_time), load_node_requested: false, node_set: NodeSet::All, @@ -570,10 +594,12 @@ impl DPNSScreen { resolved_nodes: ResolvedNodeSet::default(), node_labels: BTreeMap::new(), cards: Vec::new(), + relative_schedule_labels: BTreeMap::new(), selected_cards: BTreeSet::new(), focused_card: None, }; screen.rebuild_cards(); + screen.rebuild_scheduled_vote_rows(); screen } @@ -603,8 +629,10 @@ impl DPNSScreen { self.selected_votes.clear(); self.show_bulk_schedule_popup = false; self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; - self.bulk_identity_options.clear(); - self.set_all_option = VoteOption::CastNow; + self.node_overrides.clear(); + self.retry_voter = None; + self.confirm_timing = ConfirmTiming::Now; + self.relative_preset = relative_schedule_preset(self.app_context.network()); self.pending_backend_task = None; self.pending_vote_operation = None; self.pending_scheduled_actions.clear(); @@ -1050,21 +1078,10 @@ impl DPNSScreen { }); } - /// Open the review with exactly the node-set nodes selected. + /// Open the confirm step for the staged decisions across the node set. fn open_review_for_node_set(&mut self) { - let included: BTreeSet = self.resolved_nodes.included.iter().copied().collect(); - self.bulk_identity_options = self - .voting_identities - .iter() - .map(|identity| { - if included.contains(&identity.identity.id()) { - VoteOption::CastNow - } else { - VoteOption::NoVote - } - }) - .collect(); - self.set_all_option = VoteOption::CastNow; + self.retry_voter = None; + self.node_overrides.clear(); self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; self.show_bulk_schedule_popup = true; } @@ -1092,18 +1109,9 @@ impl DPNSScreen { fn review_failed_target(&mut self, outcome: &crate::model::dpns_voting::DpnsVoteOutcome) { self.selected_votes.clear(); self.set_selected_vote_from_outcome(outcome); - self.bulk_identity_options = self - .voting_identities - .iter() - .map(|voter| { - if voter.identity.id() == outcome.target.key.voter_id { - VoteOption::CastNow - } else { - VoteOption::NoVote - } - }) - .collect(); - self.set_all_option = VoteOption::CastNow; + self.retry_voter = Some(outcome.target.key.voter_id); + self.node_overrides.clear(); + self.confirm_timing = ConfirmTiming::Now; self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; self.show_bulk_schedule_popup = true; } @@ -1496,7 +1504,19 @@ impl DPNSScreen { }); row.col(|ui| { let dark_mode = ui.style().visuals.dark_mode; - if let LocalResult::Single(dt) = + let preset = scheduled_row.journal_target.as_ref().and_then(|(_, key)| { + self.relative_schedule_labels + .get(&(key.clone(), vote.unix_timestamp)) + }); + if let Some(preset) = preset { + ui.label( + RichText::new(relative_schedule_label( + *preset, + &utc_minute(vote.unix_timestamp), + )) + .color(DashColors::text_primary(dark_mode)), + ); + } else if let LocalResult::Single(dt) = Utc.timestamp_millis_opt(vote.unix_timestamp as i64) { ui.label( @@ -1612,15 +1632,22 @@ impl DPNSScreen { ScheduledVoteEditor::new(row.clone(), key, node_label, choices); } - fn simple_schedule_option(&self) -> Option { - let timestamp = self.simple_schedule.current_value()?; - (timestamp > Utc::now().timestamp_millis() as u64) - .then_some(VoteOption::ScheduledAt(timestamp)) - } - - fn apply_all_nodes_option(&mut self, option: VoteOption) { - self.set_all_option = option.clone(); - self.bulk_identity_options.fill(option); + /// 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 + .simple_schedule + .current_value() + .ok_or(ReviewPlanError::ScheduleIsNotAValidTime)?; + if at <= now_ms { + return Err(ReviewPlanError::ScheduleIsNotInTheFuture); + } + Ok(BatchTiming::At(at)) + } + } } /// The cached display name of a `TowardsIdentity` candidate. @@ -1644,8 +1671,17 @@ impl DPNSScreen { fn rebuild_scheduled_vote_rows(&mut self) { let legacy_votes = self.app_context.get_scheduled_votes().unwrap_or_default(); - *self.scheduled_votes.lock_recover() = - self.vote_operations.scheduled_vote_rows(&legacy_votes); + let rows = self.vote_operations.scheduled_vote_rows(&legacy_votes); + self.relative_schedule_labels = rows + .iter() + .filter_map(|row| { + let (_, key) = row.journal_target.as_ref()?; + let at = row.vote.unix_timestamp; + let preset = self.app_context.dpns_relative_schedule_label(key, at)?; + Some(((key.clone(), at), preset)) + }) + .collect(); + *self.scheduled_votes.lock_recover() = rows; } fn render_voting_identity_load_error(&mut self, ui: &mut Ui) { @@ -1658,19 +1694,18 @@ impl DPNSScreen { } } + /// The confirm step (VOTE-FR-080): an aggregate of the staged decisions + /// across the node set, the batch timing, and `Adjust nodes`. fn show_review_and_cast_window(&mut self, ui: &mut Ui) -> AppAction { let mut action = AppAction::None; - let dark_mode = ui.style().visuals.dark_mode; if matches!( self.bulk_vote_handling_status, VoteHandlingStatus::Completed ) { - action |= self.show_bulk_vote_handling_complete(ui); - return action; + return self.show_bulk_vote_handling_complete(ui); } - 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() { @@ -1678,15 +1713,12 @@ impl DPNSScreen { } return action; } - if self.voting_identities.is_empty() { - ui.add_space(5.0); ui.colored_label( DashColors::warning_color(dark_mode), NO_VOTING_NODES_MESSAGE, ); ui.label(NO_VOTING_NODES_DETAIL); - ui.add_space(10.0); ui.horizontal(|ui| { if ComponentStyles::add_primary_button(ui, "Load a masternode").clicked() { self.load_node_requested = true; @@ -1698,243 +1730,95 @@ impl DPNSScreen { }); return action; } - if self.selected_votes.is_empty() { - ui.add_space(5.0); ui.colored_label( DashColors::warning_color(dark_mode), - "No votes are ready to review. Choose at least one vote in To decide, then try again.", + "No decisions are staged. Pick a choice on at least one name, then try again.", ); - ui.add_space(10.0); if ComponentStyles::add_secondary_button(ui, "Back to To decide", dark_mode).clicked() { self.show_bulk_schedule_popup = false; } return action; } - self.bulk_identity_options - .resize(self.voting_identities.len(), VoteOption::CastNow); let plan = self.build_review_plan(); - - let mut simple_schedule_valid = true; - egui::ScrollArea::vertical().show(ui, |ui| { - match &plan { - Ok(plan) => { - ui.heading(review_headline(plan.effective_count(), plan.node_count())); - for entry in plan.effective() { - let requested = vote_choice_label( - entry.target.requested_choice, - self.candidate_name( - &entry.target.contested_name, - entry.target.requested_choice, - ), - ); - let current = review_current_choice_label( - entry.target.current_choice, - entry.target.current_choice.and_then(|choice| { - self.candidate_name(&entry.target.contested_name, choice) - }), - ); - ui.group(|ui| { - ui.set_width(ui.available_width()); - ui.heading(format!("{name}.dash", name = entry.target.contested_name)); - let decision = match entry.target.requested_choice { - ResourceVoteChoice::Lock => "Your vote: Lock this name".to_owned(), - ResourceVoteChoice::Abstain => "Your vote: Abstain".to_owned(), - ResourceVoteChoice::TowardsIdentity(_) => format!("Your vote: {requested}"), - }; - ui.label(RichText::new(decision).strong()); - match entry.target.requested_choice { - ResourceVoteChoice::Lock => { - ui.label("You are voting to prevent any contestant from receiving this name."); - } - ResourceVoteChoice::Abstain => { - ui.label("You are voting without supporting a contestant or locking this name."); - } - ResourceVoteChoice::TowardsIdentity(_) => {} - } - ui.label(format!("Voting node: {node}", node = entry.node_label())); - ui.label(format!("Previous vote: {current}")); - ui.label(format!("When: {timing}", timing = entry.timing_label)); - }); - ui.add_space(8.0); - } - if plan.effective().any(|entry| entry.target.current_choice.is_some()) { - ui.colored_label(DashColors::warning_color(dark_mode), - "Changing an existing vote uses one of that node's four allowed vote changes."); - } - if plan.no_op_count() > 0 { - ui.label(review_skipped_line(plan.no_op_count())); - } - if plan.effective_count() == 0 { - ui.colored_label( - DashColors::warning_color(dark_mode), - "Nothing will be submitted. Choose at least one node and a vote it has not already cast.", + 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); } - Err(error) => { - ui.colored_label(DashColors::warning_color(dark_mode), error.to_string()); + ui.add_space(6.0); + ui.label(confirm_transactions_line(plan.effective_count())); + let changes = plan.aggregate.change_count(); + if changes > 0 { + ui.colored_label( + DashColors::warning_color(dark_mode), + confirm_change_warning(changes), + ); } - } - ui.separator(); - ui.horizontal(|ui| { - ui.label("When:"); - if ui - .selectable_label( - matches!(self.set_all_option, VoteOption::CastNow), - "Cast now", - ) - .clicked() - { - self.apply_all_nodes_option(VoteOption::CastNow); + 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)); + } } + } + Err(error) => { + ui.colored_label(DashColors::warning_color(dark_mode), error.to_string()); + } + } + + ui.separator(); + ui.horizontal_wrapped(|ui| { + ui.label("When:"); + for timing in ConfirmTiming::ALL { if ui - .selectable_label( - matches!(self.set_all_option, VoteOption::ScheduledAt(_)), - "Schedule for later", - ) + .selectable_label(self.confirm_timing == timing, timing.label()) .clicked() { - let option = self.simple_schedule_option().unwrap_or(VoteOption::ScheduledAt(0)); - self.apply_all_nodes_option(option); + self.confirm_timing = timing; } - }); - - if matches!(self.set_all_option, VoteOption::ScheduledAt(_)) { - let schedule_changed = self.simple_schedule.show(ui).inner.has_changed(); - simple_schedule_valid = self.simple_schedule_option().is_some(); - if schedule_changed - && let Some(option) = self.simple_schedule_option() - { - self.set_all_option = option.clone(); - for current in &mut self.bulk_identity_options { - if matches!(current, VoteOption::ScheduledAt(_)) { - *current = option.clone(); - } - } - } - if !simple_schedule_valid { - ui.colored_label( - DashColors::warning_color(dark_mode), - SCHEDULE_IN_FUTURE_MESSAGE, - ); - } - ui.colored_label(DashColors::warning_color(dark_mode), KEEP_RUNNING_MESSAGE); } - - ui.separator(); - ui.add_space(10.0); - egui::CollapsingHeader::new("Choose per node (advanced)") - .default_open(false) - .show(ui, |ui| { - for (i, identity) in self.voting_identities.iter().enumerate() { - ui.group(|ui| { - ui.horizontal(|ui| { - let identity_label = identity.alias.clone().unwrap_or_else(|| { - identity.identity.id().to_string(Encoding::Base58) - }); - let dark_mode = ui.style().visuals.dark_mode; - ui.label( - RichText::new(format!("Identity: {identity_label}")) - .color(DashColors::text_primary(dark_mode)), - ); - - 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 => "Do not use this node".to_string(), - VoteOption::CastNow => "Cast now".to_string(), - VoteOption::Scheduled { .. } => "Schedule after a delay".to_string(), - VoteOption::ScheduledAt(_) => "At selected UTC time".to_string(), - }) - .show_ui(ui, |ui| { - if ui - .selectable_label( - matches!(current_option, VoteOption::NoVote), - "Do not use this node", - ) - .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 after:") - .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); + }); + match self.confirm_timing { + ConfirmTiming::Now => {} + ConfirmTiming::BeforeEnd => { + ui.horizontal(|ui| { + 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() + { + self.relative_preset = std::time::Duration::from_secs(minutes * 60); } + ui.label(before_end_phrase(self.relative_preset)); }); - }); - // If any selected votes are scheduled, show a warning - if !matches!(self.set_all_option, VoteOption::ScheduledAt(_)) - && self - .bulk_identity_options - .iter() - .any(|option| matches!(option, VoteOption::Scheduled { .. })) - { - ui.colored_label( - DashColors::warning_color(ui.style().visuals.dark_mode), - KEEP_RUNNING_MESSAGE, - ); - ui.add_space(10.0); + ui.colored_label(DashColors::warning_color(dark_mode), KEEP_RUNNING_MESSAGE); + } + ConfirmTiming::At => { + self.simple_schedule.show(ui); + ui.colored_label(DashColors::warning_color(dark_mode), KEEP_RUNNING_MESSAGE); + } } + egui::CollapsingHeader::new("Adjust nodes") + .default_open(false) + .show(ui, |ui| self.render_adjust_nodes(ui, plan.as_ref().ok())); + let operation_in_progress = matches!( self.bulk_vote_handling_status, VoteHandlingStatus::CastingVotes | VoteHandlingStatus::SchedulingVotes @@ -1945,33 +1829,25 @@ impl DPNSScreen { ui.label("Submitting votes…"); }); } - let has_submittable = plan.as_ref().is_ok_and(|plan| plan.effective_count() > 0); - let submit_label = match plan - .as_ref() - .map(|plan| (plan.has_immediate(), plan.has_scheduled())) - { - Ok((true, false)) => "Cast votes", - Ok((false, true)) => "Schedule votes", - _ => "Submit votes", - }; + let transactions = plan.as_ref().map_or(0, ReviewPlan::effective_count); + let all_now = plan.as_ref().is_ok_and(|plan| !plan.has_scheduled()); let submit_disabled_reason = if operation_in_progress { "The selected votes are already being submitted." - } else if !simple_schedule_valid { - SCHEDULE_IN_FUTURE_MESSAGE } else 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." }; - let (submit_clicked, cancel_clicked) = ui + let can_submit = !operation_in_progress && transactions > 0; + 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, - !operation_in_progress && simple_schedule_valid && has_submittable, + can_submit, if operation_in_progress { - "Submitting votes…" + "Submitting votes…".to_owned() } else { - submit_label + confirm_button_label(transactions, all_now) }, ) .disabled_tooltip(submit_disabled_reason) @@ -1986,6 +1862,19 @@ impl DPNSScreen { (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 !operation_in_progress + && input.consume_key(egui::Modifiers::NONE, egui::Key::Escape) + { + cancel_clicked = true; + } + }); + } if submit_clicked { action = self.bulk_apply_votes(); if matches!( @@ -1998,39 +1887,99 @@ impl DPNSScreen { ); } } - if cancel_clicked { - self.selected_votes.clear(); + // Cancel closes the confirm step; staged decisions stay in the tray. self.show_bulk_schedule_popup = false; + self.retry_voter = None; self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; - self.vote_overlay.take_and_clear(); - self.pending_vote_operation = None; } - - // 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(error) => { - ui.colored_label(DashColors::error_color(dark_mode), error.to_string()); - } + if let VoteHandlingStatus::Failed(error) = &self.bulk_vote_handling_status { + ui.colored_label(DashColors::error_color(dark_mode), error.to_string()); } - action } + /// `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); + 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() + { + if option == NodeTiming::Batch { + self.node_overrides.remove(&node.voter_id); + } else { + self.node_overrides.insert(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)); + let requested = vote_choice_label( + target.requested_choice, + self.candidate_name(&target.contested_name, target.requested_choice), + ); + let current = review_current_choice_label( + target.current_choice, + target + .current_choice + .and_then(|choice| self.candidate_name(&target.contested_name, choice)), + ); + ui.label(format!("{current} β†’ {requested}")); + 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(); + } + }); + } + /// 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. /// @@ -2062,100 +2011,112 @@ impl DPNSScreen { self.build_review_plan_at(Utc::now()) } + /// 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_voter { + Some(voter) => *id == 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() + } + fn build_review_plan_at(&self, now: DateTime) -> Result { - let mut entries = Vec::new(); - let mut voters = Vec::new(); - for (identity, option) in self - .voting_identities + let now_ms = now.timestamp_millis() as u64; + let decisions = self + .selected_votes .iter() - .zip(&self.bulk_identity_options) - { - let (timing, timing_label) = match option { - VoteOption::NoVote => continue, - VoteOption::CastNow => (VoteTiming::Now, "Cast now".to_owned()), - VoteOption::ScheduledAt(timestamp) => { - if *timestamp <= now.timestamp_millis() as u64 { - return Err(ReviewPlanError::ScheduleIsNotInTheFuture); - } - let date = DateTime::from_timestamp_millis(*timestamp as i64) - .ok_or(ReviewPlanError::ScheduleIsNotAValidTime)?; - ( - VoteTiming::Scheduled(*timestamp), - format!( - "Scheduled for {when} UTC", - when = date.format("%Y-%m-%d %H:%M"), - ), - ) - } - VoteOption::Scheduled { - days, - hours, - minutes, - } => { - let offset = chrono::Duration::days(*days as i64) - + chrono::Duration::hours(*hours as i64) - + chrono::Duration::minutes(*minutes as i64); - ( - VoteTiming::Scheduled((now + offset).timestamp_millis() as u64), - format!("Scheduled in {days} d {hours} h {minutes} min"), - ) - } - }; - voters.push(identity.clone()); - for selected_vote in &self.selected_votes { - if let VoteTiming::Scheduled(timestamp) = timing { - validate_dpns_schedule_time( - timestamp, - now.timestamp_millis() as u64, - selected_vote.end_time, - ) - .map_err(|_| ReviewPlanError::ScheduleOutlastsContest { - contested_name: selected_vote.contested_name.clone(), - })?; - } - let voter_id = identity.identity.id(); + .map(|vote| { let vote_poll_id = self .app_context - .dpns_vote_poll_id(&selected_vote.contested_name) + .dpns_vote_poll_id(&vote.contested_name) .map_err(|error| { tracing::warn!( ?error, - contested_name = selected_vote.contested_name, + contested_name = vote.contested_name, "Could not build a DPNS vote target" ); ReviewPlanError::VotePollUnavailable { source: Arc::new(error), } })?; - let target_key = DpnsVoteTargetKey { - network: self.app_context.network(), - voter_id, + Ok(Decision { + contested_name: vote.contested_name.clone(), vote_poll_id, - }; - if self.vote_operations.target_status(&target_key).is_some() { - return Err(ReviewPlanError::VoteAlreadyInProgress { - contested_name: selected_vote.contested_name.clone(), - }); - } - let DpnsCurrentVoteState::Available(current_choice) = - self.vote_state.state(voter_id, vote_poll_id) - else { - return Err(ReviewPlanError::CurrentVoteUnavailable); - }; - entries.push(ReviewEntry { - target: DpnsVoteTarget { - key: target_key, - voter_alias: identity.alias.clone(), - contested_name: selected_vote.contested_name.clone(), - requested_choice: selected_vote.vote_choice, - current_choice, - timing, - }, - timing_label: timing_label.clone(), - }); + choice: vote.vote_choice, + end_time: 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, } - } - Ok(ReviewPlan { entries, voters }) + }; + let aggregate = compose( + network, + &decisions, + &self.confirm_nodes(), + standing, + self.batch_timing(now_ms)?, + &self.node_overrides, + now_ms, + )?; + let casting: BTreeSet = aggregate + .targets + .iter() + .map(|target| target.key.voter_id) + .collect(); + let voters = self + .voting_identities + .iter() + .filter(|identity| casting.contains(&identity.identity.id())) + .cloned() + .collect(); + 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, + voters, + }) } fn bulk_apply_votes(&mut self) -> AppAction { @@ -2167,22 +2128,37 @@ impl DPNSScreen { } }; let has_immediate = plan.has_immediate(); - let ReviewPlan { - entries, - voters: selected_voters, - } = plan; - - if entries.is_empty() { - self.fail_submission(VoteSubmissionError::NoTargets); + 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; } - // No-op targets are handed over unfiltered: the operation counts them, - // and that count drives the post-submit feedback. - let operation = - DpnsVoteOperation::new(entries.into_iter().map(|entry| entry.target).collect()); - if operation.targets.is_empty() { - self.fail_submission(VoteSubmissionError::AllNoOps); - return AppAction::None; + let operation = DpnsVoteOperation::new(plan.aggregate.targets); + if self.confirm_timing == ConfirmTiming::BeforeEnd { + for outcome in &operation.targets { + if let VoteTiming::Scheduled(at) = outcome.target.timing + && !self + .node_overrides + .contains_key(&outcome.target.key.voter_id) + && let Err(error) = self.app_context.save_dpns_relative_schedule_label( + &outcome.target.key, + at, + self.relative_preset, + ) + { + // Display only: the row falls back to the absolute time. + tracing::debug!(?error, "Could not save a relative schedule label"); + } + } } self.submission_error_banner.take_and_clear(); self.bulk_vote_handling_status = if has_immediate { @@ -2190,11 +2166,12 @@ impl DPNSScreen { } else { VoteHandlingStatus::SchedulingVotes }; + self.retry_voter = None; self.pending_vote_operation = Some(operation.id); AppAction::BackendTask(BackendTask::ContestedResourceTask( ContestedResourceTask::SubmitDpnsVoteOperation( operation, - selected_voters, + plan.voters, None, self.app_context.network(), ), @@ -2298,12 +2275,11 @@ impl ScreenLike for DPNSScreen { } fn refresh_on_arrival(&mut self) { - let previous_options = self + let previous_voters: BTreeSet = self .voting_identities .iter() - .zip(&self.bulk_identity_options) - .map(|(identity, option)| (identity.identity.id(), option.clone())) - .collect::>(); + .map(|identity| identity.identity.id()) + .collect(); match loaded_voting_identities(&self.app_context) { Ok(identities) => { self.voting_identities = identities; @@ -2315,22 +2291,15 @@ impl ScreenLike for DPNSScreen { self.voting_identity_load_error = Some(error); } } - self.bulk_identity_options = self - .voting_identities - .iter() - .map(|identity| { - previous_options - .get(&identity.identity.id()) - .cloned() - .unwrap_or({ - if self.selected_votes.is_empty() { - VoteOption::CastNow - } else { - VoteOption::NoVote - } - }) - }) - .collect(); + // A node loaded after decisions were staged never joins them silently. + if !self.selected_votes.is_empty() { + for identity in &self.voting_identities { + let id = identity.identity.id(); + if !previous_voters.contains(&id) { + self.node_overrides.entry(id).or_insert(NodeTiming::DontUse); + } + } + } self.refresh(); } @@ -2588,7 +2557,7 @@ impl ScreenLike for DPNSScreen { } } if self.show_bulk_schedule_popup { - egui::Window::new("Review and cast") + egui::Window::new("Confirm votes") .collapsible(false) .resizable(true) .vscroll(true) @@ -2871,9 +2840,10 @@ mod tests { screen.candidate_name("alpha", choice).is_none(), "the fixture must leave the candidate name uncached, or this proves nothing" ); - let expected = format!( - "Your vote: Vote for {handle}", - handle = short_identifier(candidate_id), + let expected = decision_row( + "alpha", + &format!("Vote for {handle}", handle = short_identifier(candidate_id)), + 1, ); let mut harness = egui_kittest::Harness::builder() @@ -2885,10 +2855,9 @@ mod tests { assert!(harness.query_by_label(&expected).is_some()); for label in [ - "alpha.dash", - "Voting node: node-one", - "Previous vote: Lock", - "When: Cast now", + "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(), @@ -3202,7 +3171,7 @@ mod tests { .unwrap(); let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); screen.voting_identities = vec![voter.clone()]; - screen.bulk_identity_options = vec![VoteOption::CastNow]; + screen.rebuild_cards(); screen.selected_votes = vec![SelectedVote { contested_name: "alpha".to_owned(), vote_choice: ResourceVoteChoice::Abstain, @@ -3217,9 +3186,7 @@ mod tests { 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().entries[0] - .target - .clone(); + let target = screen.build_review_plan().unwrap().aggregate.targets[0].clone(); let mut operation = DpnsVoteOperation::new(vec![target]); operation.targets[0].status = DpnsVoteTargetStatus::Unconfirmed; screen @@ -3245,9 +3212,7 @@ mod tests { DpnsVoteTargetStatus::Queued, ] { let (screen, _dir) = voting_ui_review_fixture(); - let mut target = screen.build_review_plan().unwrap().entries[0] - .target - .clone(); + let mut target = screen.build_review_plan().unwrap().aggregate.targets[0].clone(); target.timing = VoteTiming::Scheduled(1); let mut operation = DpnsVoteOperation::new(vec![target]); operation.targets[0].status = status; @@ -3335,9 +3300,7 @@ mod tests { ), ] { let (screen, _dir) = voting_ui_review_fixture(); - let mut target = screen.build_review_plan().unwrap().entries[0] - .target - .clone(); + 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 = DpnsVoteOperation::new(vec![target]); operation.targets[0].failure = Some(failure); @@ -3447,28 +3410,41 @@ mod tests { ); } + /// VOTE-TC-095: 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(); - let scheduled_at = (now + chrono::Duration::hours(1)).timestamp_millis() as u64; - for option in [ - VoteOption::ScheduledAt(scheduled_at), - VoteOption::Scheduled { - days: 0, - hours: 1, - minutes: 0, - }, - ] { - screen.bulk_identity_options = vec![option]; - 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::At; + screen.simple_schedule = + UtcScheduleInput::new().with_time(now + chrono::Duration::hours(1)); + let scheduled_at = screen.simple_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); + assert!( + screen.build_review_plan_at(now).is_err(), + "ten minutes before an end five minutes away is in the past" + ); + 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, @@ -3492,19 +3468,18 @@ mod tests { .unwrap() .and_utc(); screen.simple_schedule = UtcScheduleInput::new().with_time(requested); - let option = screen.simple_schedule_option().unwrap(); - screen.apply_all_nodes_option(option); + screen.confirm_timing = ConfirmTiming::At; let plan = screen.build_review_plan().unwrap(); assert_eq!( - plan.entries[0].target.timing, + 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.entries[0].target.timing, - plan.entries[0].target.timing + delayed.aggregate.targets[0].timing, + plan.aggregate.targets[0].timing ); } @@ -3651,9 +3626,7 @@ mod tests { VoteHandlingStatus::Failed(_) )); assert_eq!( - screen.build_review_plan().unwrap().entries[0] - .target - .current_choice, + screen.build_review_plan().unwrap().aggregate.targets[0].current_choice, Some(ResourceVoteChoice::Lock) ); let mut harness = egui_kittest::Harness::builder() @@ -3665,7 +3638,7 @@ mod tests { assert!( harness .query_by_label( - "Changing an existing vote uses one of that node's four allowed vote changes." + "1 of these changes an earlier vote. Each node can change its vote 4 times per name." ) .is_some() ); @@ -3781,38 +3754,25 @@ mod tests { vote_choice: ResourceVoteChoice::Lock, end_time: None, }]; - screen.bulk_identity_options = screen - .voting_identities - .iter() - .map(|identity| { - if identity.identity.id() == first.identity.id() { - VoteOption::CastNow - } else { - VoteOption::NoVote - } - }) - .collect(); + screen + .node_overrides + .insert(second.identity.id(), NodeTiming::DontUse); screen.refresh_on_arrival(); - let selected = screen - .voting_identities - .iter() - .zip(&screen.bulk_identity_options) - .filter(|(_, option)| !matches!(option, VoteOption::NoVote)) - .map(|(identity, _)| identity.identity.id()) - .collect::>(); - assert_eq!(selected, vec![first.identity.id()]); + 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(); - let new_option = screen - .voting_identities - .iter() - .zip(&screen.bulk_identity_options) - .find(|(identity, _)| identity.identity.id() == newly_loaded.identity.id()) - .unwrap() - .1; - assert!(matches!(new_option, VoteOption::NoVote)); + 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; } @@ -3820,7 +3780,12 @@ mod tests { fn voting_ui_retry_reviews_only_the_failed_node_and_contest() { let (mut screen, _dir) = voting_ui_review_fixture(); let operation = DpnsVoteOperation::new(vec![ - screen.build_review_plan().unwrap().entries.remove(0).target, + screen + .build_review_plan() + .unwrap() + .aggregate + .targets + .remove(0), ]); screen.voting_identities.push(masternode_identity( 2, @@ -3836,7 +3801,10 @@ mod tests { screen.review_failed_target(&operation.targets[0]); let plan = screen.build_review_plan().unwrap(); assert_eq!(plan.effective_count(), 1); - assert_eq!(plan.entries[0].target.key, operation.targets[0].target.key); + assert_eq!( + plan.aggregate.targets[0].key, + operation.targets[0].target.key + ); } #[test] @@ -3850,7 +3818,7 @@ mod tests { assert!( harness .query_by_label( - "Changing an existing vote uses one of that node's four allowed vote changes." + "1 of these changes an earlier vote. Each node can change its vote 4 times per name." ) .is_some() ); @@ -3869,7 +3837,7 @@ mod tests { assert!( harness .query_by_label( - "Changing an existing vote uses one of that node's four allowed vote changes." + "1 of these changes an earlier vote. Each node can change its vote 4 times per name." ) .is_none() ); @@ -3880,7 +3848,7 @@ mod tests { use egui_kittest::kittest::Queryable; let (mut screen, _temp_dir) = voting_ui_review_fixture(); let plan = screen.build_review_plan().unwrap(); - let mut first = plan.entries[0].target.clone(); + 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]); @@ -3936,7 +3904,12 @@ mod tests { 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().entries.remove(0).target; + let mut target = screen + .build_review_plan() + .unwrap() + .aggregate + .targets + .remove(0); target.timing = VoteTiming::Scheduled(42); let mut operation = DpnsVoteOperation::new(vec![target]); operation.targets[0].status = DpnsVoteTargetStatus::Queued; @@ -3988,24 +3961,23 @@ mod tests { let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); screen.voting_identities = vec![first.clone(), second.clone()]; - screen.bulk_identity_options = vec![ - VoteOption::CastNow, - VoteOption::Scheduled { - days: 1, - hours: 2, - minutes: 3, - }, - ]; + 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: None, + end_time: Some(end), }, SelectedVote { contested_name: "beta".to_owned(), vote_choice: ResourceVoteChoice::Abstain, - end_time: None, + end_time: Some(end), }, ]; screen.vote_state = DpnsVoteStateSnapshot::load( @@ -4017,19 +3989,23 @@ mod tests { let plan = screen.build_review_plan().expect("review plan"); - assert_eq!(plan.entries.len(), 4, "two nodes across two contests"); assert_eq!(plan.effective_count(), 2); - assert_eq!(plan.no_op_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_immediate()); assert!(plan.has_scheduled()); let retained = plan - .effective() - .map(|entry| { + .targets() + .iter() + .map(|target| { ( - entry.node_label(), - entry.target.contested_name.clone(), - entry.timing_label.clone(), + target.voter_alias.clone(), + target.contested_name.clone(), + target.timing, ) }) .collect::>(); @@ -4037,17 +4013,19 @@ mod tests { retained, vec![ ( - "node-one".to_owned(), - "beta".to_owned(), - "Cast now".to_owned() + Some("node-two".to_owned()), + "alpha".to_owned(), + VoteTiming::Scheduled(end - 10 * 60_000) ), ( - "node-two".to_owned(), - "alpha".to_owned(), - "Scheduled in 1 d 2 h 3 min".to_owned() + Some("node-one".to_owned()), + "beta".to_owned(), + VoteTiming::Now ), ] ); + 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. @@ -4061,7 +4039,7 @@ mod tests { let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); screen.voting_identities = vec![node.clone()]; - screen.bulk_identity_options = vec![VoteOption::CastNow]; + screen.rebuild_cards(); screen.selected_votes = vec![SelectedVote { contested_name: "alpha".to_owned(), vote_choice: ResourceVoteChoice::Lock, @@ -4073,7 +4051,10 @@ mod tests { let plan = screen.build_review_plan().expect("review plan"); assert_eq!(plan.effective_count(), 0); - assert_eq!(plan.no_op_count(), 1); + assert_eq!( + plan.aggregate.skipped_by_reason(), + BTreeMap::from([(SkipReason::AlreadyVoted, 1)]) + ); assert_eq!(plan.node_count(), 0); } @@ -4089,7 +4070,7 @@ mod tests { let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); screen.voting_identities = vec![node.clone()]; - screen.bulk_identity_options = vec![VoteOption::CastNow]; + screen.rebuild_cards(); screen.selected_votes = vec![SelectedVote { contested_name: "alpha".to_owned(), vote_choice: ResourceVoteChoice::Abstain, @@ -4102,9 +4083,7 @@ mod tests { assert_eq!(plan.effective_count(), 1); assert_eq!( - plan.effective() - .next() - .map(|entry| entry.target.current_choice), + plan.targets().first().map(|target| target.current_choice), Some(Some(ResourceVoteChoice::Lock)) ); assert_eq!( @@ -4114,19 +4093,7 @@ mod tests { } #[test] - fn review_summary_counts_votes_and_labels_previous_choices() { - assert_eq!( - review_headline(6, 3), - "Votes to submit (6) from your nodes (3)." - ); - assert_eq!( - review_skipped_line(1), - "1 vote is already cast as requested and will be skipped." - ); - assert_eq!( - review_skipped_line(2), - "2 votes are already cast as requested and will be skipped." - ); + fn review_labels_previous_choices() { assert_eq!( review_current_choice_label(Some(ResourceVoteChoice::Abstain), None), "Abstain" @@ -4179,6 +4146,46 @@ mod tests { ); } + /// VOTE-TC-094: 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]), + }; + let at = 1_900_000_000_000; + let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + key: key.clone(), + voter_alias: None, + contested_name: "later".to_owned(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, + timing: VoteTiming::Scheduled(at), + }]); + ctx.insert_dpns_vote_operation(&mut operation, None) + .expect("insert scheduled operation"); + ctx.save_dpns_relative_schedule_label(&key, at, std::time::Duration::from_secs(6 * 3600)) + .expect("save label"); + 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(); From fac41fcc0f363770ced73e99af512dec9025190e Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:36:21 +0000 Subject: [PATCH 075/194] feat(dpns): non-blocking vote progress drawer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Voting progress leaves the full-window overlay (VOTE-FR-035) for a collapsible bottom-right drawer that follows the operator across screens: "Casting {t} votes Β· {done} done Β· {sending} sending Β· {checking} being checked", a segmented bar, and per node Γ— name rows with typed status and only the valid action β€” Check again while a result is ambiguous, Review again after a definitive failure, Add voting key when the node's key was missing. The confirm step closes on submit; staged decisions clear when the operation reports. Votes gains a "Needs attention" row for unconfirmed, failed or missed targets, linking to the drawer or Scheduled. The executor fails a target whose contest closed before it was sent with "Not cast. Voting ended." (terminal, including schedules), and a missing voter is recorded as VotingKeyMissing. Batch feedback reads "{n} nodes voted on {d} names." with the still-being-checked count and do-not-resubmit guidance. The attention summary is re-derived from local state once a minute so newly loaded nodes reach the chip, badge and background refresh. Co-Authored-By: Claude Opus 5.5 --- src/app.rs | 94 +++++- src/backend_task/contested_names/mod.rs | 91 ++++- src/context/dpns_vote_attention.rs | 57 +++- src/context/mod.rs | 6 + src/model/dpns_voting/mod.rs | 3 + src/model/dpns_voting/progress.rs | 267 +++++++++++++++ src/ui/dpns/copy.rs | 121 +++++++ src/ui/dpns/dpns_contested_names_screen.rs | 371 +++++++-------------- src/ui/dpns/mod.rs | 1 + src/ui/dpns/progress_drawer.rs | 290 ++++++++++++++++ src/ui/state/dpns_vote_operations.rs | 75 ----- 11 files changed, 1041 insertions(+), 335 deletions(-) create mode 100644 src/model/dpns_voting/progress.rs create mode 100644 src/ui/dpns/progress_drawer.rs diff --git a/src/app.rs b/src/app.rs index 3b154d2a6..0c3cc9800 100644 --- a/src/app.rs +++ b/src/app.rs @@ -305,6 +305,9 @@ 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); + fn unix_time_ms() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) @@ -385,13 +388,40 @@ fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, MessageType, bo return (message.to_owned(), MessageType::Info, false); } let target_count = operation.targets.len(); - if counts.confirmed == target_count { - let message = if target_count == 1 { - "Vote cast successfully.".to_owned() + 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 { - format!("{target_count} votes were cast successfully.") + MessageType::Warning }; - return (message, MessageType::Success, false); + return ( + crate::ui::dpns::copy::batch_voted_line(nodes, names, checking), + message_type, + checking > 0, + ); } if counts.scheduled == target_count { return ( @@ -1416,6 +1446,11 @@ pub struct AppState { scheduled_vote_sweeps_in_progress: BTreeSet, /// Unix ms of the last background contest refresh dispatched per network. dpns_background_refresh_dispatched_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, @@ -1952,6 +1987,8 @@ impl AppState { scheduled_vote_sweep_deferred_since_ms: BTreeMap::new(), scheduled_vote_sweeps_in_progress: BTreeSet::new(), dpns_background_refresh_dispatched_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, @@ -3651,6 +3688,22 @@ 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() @@ -3763,6 +3816,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, @@ -4005,7 +4067,7 @@ mod migration_banner_tests { DpnsVoteTargetStatus::Confirmed, ], 0, - "2 votes were cast successfully.", + "1 node voted on 2 names.", MessageType::Success, false, ), @@ -4015,7 +4077,7 @@ mod migration_banner_tests { DpnsVoteTargetStatus::Confirmed, ], 1, - "2 votes were cast successfully.", + "1 node voted on 2 names.", MessageType::Success, false, ), @@ -4125,6 +4187,24 @@ mod migration_banner_tests { /// Counts drive which sentence is built, so no single template has to carry /// a verb that is only correct for one of them. + /// VOTE-TC-101: 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, + "1 node voted on 2 names; 1 is still being checked. Dash Evo Tool will keep checking. Do not submit it again." + ); + } + #[test] fn mixed_vote_feedback_matches_its_verbs_to_the_counts() { let operation = feedback_operation(&[ diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 64d8d8d52..c319be5eb 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -9,6 +9,7 @@ use crate::app::TaskResult; use crate::backend_task::BackendTaskSuccessResult; use crate::backend_task::error::{DapiAddressAvailability, TaskError}; use crate::context::{AppContext, MAX_CONCURRENT_DPNS_VOTERS}; +use crate::model::contested_name::ContestedName; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduleEditValidationError, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVotePollAvailability, DpnsVoteTarget, @@ -105,11 +106,33 @@ fn classify_vote_attempt( } } +/// The outcome of a target whose contest closed before it was sent +/// (VOTE-FR-087), or `None` while the contest may still accept votes. +/// +/// Terminal for scheduled targets too: a closed poll can never accept the +/// vote, so retrying it would only fail again. +fn voting_ended_outcome( + contest: Option<&ContestedName>, + now_ms: u64, +) -> Option<(DpnsVoteTargetStatus, Option)> { + (dpns_vote_poll_availability(contest, now_ms) == DpnsVotePollAvailability::ProvedClosed) + .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, failure) = failed_before_broadcast_outcome(timing); - (status, failure, matches!(timing, VoteTiming::Scheduled(_))) + let (status, _) = failed_before_broadcast_outcome(timing); + ( + status, + Some(DpnsVoteFailure::VotingKeyMissing), + matches!(timing, VoteTiming::Scheduled(_)), + ) } /// Decide whether one reconciliation observation is terminal. @@ -640,6 +663,21 @@ impl AppContext { .into_iter() .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 @@ -658,6 +696,7 @@ impl AppContext { 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 { let Some(voter) = voter else { let mut scheduled_voter_missing = false; @@ -687,6 +726,22 @@ impl AppContext { 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, @@ -2292,16 +2347,46 @@ mod tests { ); } + /// VOTE-TC-104 (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) + )) + ); + } + #[test] fn scheduled_missing_voter_remains_retryable() { assert_eq!( missing_voter_outcome(VoteTiming::Scheduled(42)), ( DpnsVoteTargetStatus::Scheduled, - Some(DpnsVoteFailure::SubmissionFailed), + Some(DpnsVoteFailure::VotingKeyMissing), true, ) ); + assert_eq!( + missing_voter_outcome(VoteTiming::Now), + ( + DpnsVoteTargetStatus::FailedBeforeSubmission, + Some(DpnsVoteFailure::VotingKeyMissing), + false, + ) + ); } #[test] diff --git a/src/context/dpns_vote_attention.rs b/src/context/dpns_vote_attention.rs index 97991957c..21744679c 100644 --- a/src/context/dpns_vote_attention.rs +++ b/src/context/dpns_vote_attention.rs @@ -11,9 +11,9 @@ use crate::model::dpns_voting::operator::{ changes_left, contest_needs_decision, }; use crate::model::dpns_voting::{ - DpnsCurrentVoteState, DpnsVoteOperation, DpnsVotePollAvailability, DpnsVoteTargetKey, - DpnsVoteTargetStatus, authoritative_dpns_vote_outcome, dpns_vote_lock_holders, - dpns_vote_poll_availability, + DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOutcome, DpnsVotePollAvailability, + DpnsVoteTargetKey, DpnsVoteTargetStatus, authoritative_dpns_vote_outcome, + dpns_vote_lock_holders, dpns_vote_poll_availability, }; use crate::model::qualified_identity::IdentityType; use crate::utils::time::now_ms; @@ -47,6 +47,34 @@ impl AppContext { ) } + /// Journal operations as of the last recompute, for the progress drawer + /// (cheap; safe to call every frame). + pub fn dpns_vote_progress(&self) -> Arc<[DpnsVoteOperation]> { + 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() + } + /// Record that a contest + vote-state refresh just completed. pub(crate) fn mark_dpns_contests_refreshed(&self) { self.dpns_contests_refreshed_at_ms @@ -175,7 +203,18 @@ impl AppContext { /// Storage failures keep the previous summary rather than signalling /// nothing. pub fn recompute_dpns_vote_attention(&self) -> Arc { - match self.compute_dpns_vote_attention() { + 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(); + } + }; + *self + .dpns_vote_progress + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::from(operations.as_slice()); + match self.compute_dpns_vote_attention(&operations) { Ok(summary) => { let summary = Arc::new(summary); *self @@ -191,7 +230,10 @@ impl AppContext { } } - fn compute_dpns_vote_attention(&self) -> Result { + fn compute_dpns_vote_attention( + &self, + operations: &[DpnsVoteOperation], + ) -> Result { let resolved = self .saved_dpns_node_set() .unwrap_or_default() @@ -208,7 +250,6 @@ impl AppContext { Some((contest.normalized_contested_name, contest.end_time, poll)) }) .collect(); - let operations = self.dpns_vote_operations()?; let polls: Vec = contests.iter().map(|(_, _, poll)| *poll).collect(); let mut states = BTreeMap::new(); for voter in &resolved.included { @@ -234,7 +275,7 @@ impl AppContext { voter_id: *voter, vote_poll_id: poll, }; - let locked = dpns_vote_lock_holders(&operations, &key).next().is_some(); + let locked = dpns_vote_lock_holders(operations, &key).next().is_some(); (state, locked, self.dpns_changes_left(*voter, poll, state)) })); ContestAttention { @@ -246,7 +287,7 @@ impl AppContext { .collect(); Ok(AttentionSummary::new( &attention, - unresolved_target_count(&operations), + unresolved_target_count(operations), resolved.included.len(), )) } diff --git a/src/context/mod.rs b/src/context/mod.rs index fd56a7771..3896d88e7 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -206,6 +206,10 @@ pub struct AppContext { /// Current masternode-list membership (ProTxHash β†’ is evonode); `None` /// until the SPV masternode list is available. masternode_list_membership: RwLock>>>, + /// Journal operations as of the last attention recompute (progress drawer). + dpns_vote_progress: RwLock>, + /// A `Review again` request from the progress drawer for the voting panel. + dpns_vote_review_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`. @@ -579,6 +583,8 @@ impl AppContext { 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), app_kv, #[cfg(test)] det_kv_override: Mutex::new(None), diff --git a/src/model/dpns_voting/mod.rs b/src/model/dpns_voting/mod.rs index bcc7b2437..86e56691a 100644 --- a/src/model/dpns_voting/mod.rs +++ b/src/model/dpns_voting/mod.rs @@ -16,6 +16,7 @@ use std::fmt; pub mod composer; pub mod contest_timing; 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; @@ -243,6 +244,8 @@ pub enum DpnsVoteFailure { /// 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. diff --git a/src/model/dpns_voting/progress.rs b/src/model/dpns_voting/progress.rs new file mode 100644 index 000000000..08583156f --- /dev/null +++ b/src/model/dpns_voting/progress.rs @@ -0,0 +1,267 @@ +//! 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, + 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 +} + +/// Operations the drawer lists: anything still in flight, plus settled +/// operations created since `since_ms` that the operator has not dismissed. +pub fn drawer_operations<'a>( + operations: &'a [DpnsVoteOperation], + since_ms: u64, + dismissed: &BTreeSet, +) -> Vec<&'a DpnsVoteOperation> { + operations + .iter() + .filter(|operation| { + let counts = progress_counts([*operation]); + if counts.total == 0 { + return false; + } + counts.in_flight() + || (operation.created_at >= since_ms && !dismissed.contains(&operation.id)) + }) + .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. +/// +/// Failed targets count only from operations created since `since_ms`, so a +/// stale failure from an earlier session does not nag forever; unconfirmed +/// and missed targets still hold their lock and always count. +pub fn needs_attention( + operations: &[DpnsVoteOperation], + since_ms: u64, + now_ms: u64, +) -> NeedsAttention { + let mut attention = NeedsAttention::default(); + for operation in operations { + for outcome in &operation.targets { + 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 operation.created_at >= since_ms + && 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( + 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(), + ); + operation.created_at = created_at; + 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-098: 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(1, &[(S::Confirmed, NOW)]); + let recent_settled = operation(100, &[(S::Confirmed, NOW)]); + let dismissed_settled = operation(100, &[(S::Rejected, NOW)]); + let schedule_only = operation(100, &[(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-099: 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, 1_000 + 121_000); + assert_eq!( + attention, + NeedsAttention { + checking: 1, + failed: 1, + missed_schedules: 1, + } + ); + assert!(needs_attention(&[], 0, 0).is_empty()); + } +} diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index bc42b6e50..97eb24ab0 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -5,6 +5,8 @@ use crate::model::dpns_voting::composer::SkipReason; use crate::model::dpns_voting::operator::{ChangesLeft, TimeLeft}; +use crate::model::dpns_voting::progress::{NeedsAttention, ProgressCounts}; +use crate::model::dpns_voting::{DpnsVoteFailure, DpnsVoteTargetStatus}; /// A remaining time as a phrase, e.g. `3 hours`. pub fn time_left_phrase(time_left: TimeLeft) -> String { @@ -186,6 +188,85 @@ pub fn node_set_chip_label(set_name: &str, nodes: usize, weight: u32) -> String format!("Vote with: {set_name} Β· {nodes} Β· {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 { + let voted = 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"), + }; + match checking { + 0 => format!("{voted}."), + 1 => format!( + "{voted}; 1 is still being checked. Dash Evo Tool will keep checking. Do not submit it again." + ), + checking => format!( + "{voted}; {checking} are still being checked. Dash Evo Tool will keep checking. Do not submit them again." + ), + } +} + +/// Drawer header (VOTE-FR-083). +pub fn drawer_header(counts: ProgressCounts) -> String { + let casting = match counts.total { + 1 => "Casting 1 vote".to_owned(), + total => format!("Casting {total} votes"), + }; + format!( + "{casting} Β· {done} done Β· {sending} sending Β· {checking} being checked", + done = counts.done(), + sending = counts.sending, + checking = counts.checking, + ) +} + +/// Drawer row status (VOTE-FR-083/087). +pub fn progress_row_status( + status: DpnsVoteTargetStatus, + failure: Option, +) -> &'static str { + match (status, failure) { + (_, Some(DpnsVoteFailure::VotingEnded)) => "Not cast. Voting ended.", + (_, Some(DpnsVoteFailure::VotingKeyMissing)) => "Not cast. The voting key is not loaded.", + ( + DpnsVoteTargetStatus::Queued + | DpnsVoteTargetStatus::Submitting + | DpnsVoteTargetStatus::Confirming, + _, + ) => "Sending…", + (DpnsVoteTargetStatus::Unconfirmed, _) => "Still being checked. Don't submit it again.", + (DpnsVoteTargetStatus::Confirmed, _) => "Voted", + (DpnsVoteTargetStatus::Rejected, _) => "Rejected by Platform", + (DpnsVoteTargetStatus::NotApplied, _) => "Not applied", + (DpnsVoteTargetStatus::FailedBeforeSubmission, _) => "Not sent", + (DpnsVoteTargetStatus::Scheduled, _) => "Scheduled", + (DpnsVoteTargetStatus::Cancelled, _) => "Cancelled", + } +} + +/// `Needs attention` summary (VOTE-FR-084). +pub fn needs_attention_line(attention: NeedsAttention) -> String { + let mut parts = Vec::new(); + match attention.checking { + 0 => {} + 1 => parts.push("1 vote is still being checked".to_owned()), + count => parts.push(format!("{count} votes are still being checked")), + } + match attention.failed { + 0 => {} + 1 => parts.push("1 vote was not cast".to_owned()), + count => parts.push(format!("{count} votes were not cast")), + } + match attention.missed_schedules { + 0 => {} + 1 => parts.push("1 scheduled vote was missed".to_owned()), + count => parts.push(format!("{count} scheduled votes were missed")), + } + format!("Needs attention: {parts}.", parts = parts.join(" Β· ")) +} + /// Confirm title (VOTE-FR-080). pub fn confirm_title(decisions: usize, nodes: usize) -> String { match (decisions, nodes) { @@ -388,6 +469,46 @@ mod tests { ); } + /// VOTE-TC-101: 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), + "2 nodes voted on 1 name; 1 is still being checked. Dash Evo Tool will keep checking. Do not submit it again." + ); + } + + /// VOTE-TC-098/099/104 (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 cast. Voting ended." + ); + assert_eq!( + needs_attention_line(NeedsAttention { + checking: 1, + failed: 0, + missed_schedules: 2, + }), + "Needs attention: 1 vote is still being checked Β· 2 scheduled votes were missed." + ); + } + #[test] fn deadlines_read_naturally() { assert_eq!(ends_in_label(Some(TimeLeft::Days(1))), "Ends in 1 day"); diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 83b52fcd0..fb314cb64 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -30,6 +30,7 @@ use crate::model::dpns_voting::operator::{ ChangesLeft, NodeSet, ResolvedNodeSet, VotingNode, VotingNodeKind, relative_schedule_preset, time_left, }; +use crate::model::dpns_voting::progress::needs_attention; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, @@ -39,11 +40,11 @@ use crate::model::qualified_identity::IdentityType; 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::progress_overlay::{OptionOverlayExt, OverlayConfig, OverlayHandle}; use crate::ui::components::utc_schedule_input::UtcScheduleInput; use crate::ui::components::{BannerHandle, MessageBanner, OptionBannerExt}; 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::tray_label; use crate::ui::dpns::copy::{ before_end_phrase, changes_left_label, confirm_button_label, confirm_change_warning, @@ -51,6 +52,7 @@ use crate::ui::dpns::copy::{ skipped_header, skipped_reason_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, VoteCard, sort_by_time_left, @@ -194,6 +196,9 @@ fn scheduled_failure_guidance( 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, @@ -413,7 +418,6 @@ pub enum VoteHandlingStatus { NotStarted, CastingVotes, SchedulingVotes, - Completed, Failed(VoteSubmissionError), } @@ -456,10 +460,11 @@ pub struct DPNSScreen { pending_backend_task: Option, vote_operations: DpnsVoteOperationSnapshot, vote_state: DpnsVoteStateSnapshot, - vote_overlay: Option, pending_vote_operation: Option, pending_scheduled_actions: BTreeMap, - clear_vote_overlay_on_error: bool, + /// 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, @@ -505,6 +510,8 @@ pub struct DPNSScreen { /// "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, @@ -567,10 +574,10 @@ impl DPNSScreen { pending_backend_task: None, vote_operations, vote_state, - vote_overlay: None, pending_vote_operation: None, pending_scheduled_actions: BTreeMap::new(), - clear_vote_overlay_on_error: false, + release_pending_on_error: false, + session_started_ms: now_ms(), scheduled_clear_dialog: None, scheduled_vote_editor: None, view, @@ -616,9 +623,6 @@ impl DPNSScreen { .map(|(key, _)| key.clone()); if let Some(key) = key { self.pending_scheduled_actions.remove(&key); - if self.pending_vote_operation.is_none() { - self.vote_overlay.take_and_clear(); - } true } else { false @@ -636,10 +640,9 @@ impl DPNSScreen { self.pending_backend_task = None; self.pending_vote_operation = None; self.pending_scheduled_actions.clear(); - self.clear_vote_overlay_on_error = false; + self.release_pending_on_error = false; self.scheduled_clear_dialog = None; self.scheduled_vote_editor = None; - self.vote_overlay.take_and_clear(); self.refresh_banner.take_and_clear(); self.journal_error_banner.take_and_clear(); self.submission_error_banner.take_and_clear(); @@ -1025,7 +1028,6 @@ impl DPNSScreen { } }); } - self.render_voting_activity(ui); }); for (index, event) in events { @@ -1116,101 +1118,38 @@ impl DPNSScreen { self.show_bulk_schedule_popup = true; } - fn render_voting_activity(&mut self, ui: &mut Ui) { - let operations = self.vote_operations.recent_operations(); - if operations.is_empty() { + /// `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, + now_ms(), + ); + if attention.is_empty() { return; } - - let dark_mode = ui.style().visuals.dark_mode; - ui.add_space(12.0); - ui.heading("Voting activity"); - for operation in operations.iter() { - let settled = operation - .targets - .iter() - .filter(|outcome| !outcome.status.holds_lock()) - .count(); - ui.group(|ui| { - ui.label( - RichText::new(format!( - "{settled} of {} votes settled.", - operation.targets.len() - )) - .strong(), - ); - for outcome in &operation.targets { - let missed = schedule_is_missed(outcome.status, outcome.target.timing, Utc::now().timestamp_millis().max(0) as u64); - ui.horizontal_wrapped(|ui| { - ui.label(format!( - "{node} β€” {name}.dash β€” {choice} β€” {status}", - node = outcome.target.voter_alias.clone().unwrap_or_else(|| short_identifier(outcome.target.key.voter_id)), - name = outcome.target.contested_name, - choice = vote_choice_label( - outcome.target.requested_choice, - self.candidate_name( - &outcome.target.contested_name, - outcome.target.requested_choice, - ), - ), - status = if missed { "Missed automatic vote" } else { target_outcome_label(outcome.status, outcome.failure) }, - )); - if outcome.status == DpnsVoteTargetStatus::Unconfirmed - && ComponentStyles::add_secondary_button( - ui, - "Check again", - dark_mode, - ) - .clicked() - { - self.pending_backend_task = Some(BackendTask::ContestedResourceTask( - ContestedResourceTask::ReconcileDpnsVoteOperation( - operation.id, - self.app_context.network(), - ), - )); - self.pending_vote_operation = Some(operation.id); - self.raise_vote_overlay( - ui.ctx(), - "Checking the submitted votes with Platform…", - ); - } - if matches!( - outcome.status, - DpnsVoteTargetStatus::Rejected - | DpnsVoteTargetStatus::FailedBeforeSubmission - | DpnsVoteTargetStatus::NotApplied - ) && ComponentStyles::add_secondary_button( - ui, - "Review again", - dark_mode, - ) - .clicked() - { - self.review_failed_target(outcome); - } - }); - if let Some(guidance) = scheduled_failure_guidance(outcome.status, outcome.failure) { - ui.label(guidance); - } - if missed { - ui.label(MISSED_SCHEDULE_GUIDANCE); - } - if matches!( - outcome.status, - DpnsVoteTargetStatus::Confirming - | DpnsVoteTargetStatus::Unconfirmed - ) { - ui.label( - RichText::new( - "This vote may already have been submitted. Do not submit it again.", - ) + 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); } fn set_selected_vote_from_outcome( @@ -1233,9 +1172,10 @@ impl DPNSScreen { } } - fn raise_vote_overlay(&mut self, ctx: &egui::Context, message: &str) { - self.vote_overlay - .raise(ctx, message, OverlayConfig::default()); + /// 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| { @@ -1592,7 +1532,7 @@ impl DPNSScreen { }); if show_cast_overlay { - self.raise_vote_overlay(ui.ctx(), "Submitting the scheduled vote to Dash Platform…"); + self.show_vote_progress(ui.ctx()); } action @@ -1700,12 +1640,6 @@ impl DPNSScreen { let mut action = AppAction::None; let dark_mode = ui.style().visuals.dark_mode; - if matches!( - self.bulk_vote_handling_status, - VoteHandlingStatus::Completed - ) { - return self.show_bulk_vote_handling_complete(ui); - } 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() { @@ -1881,10 +1815,10 @@ impl DPNSScreen { self.bulk_vote_handling_status, VoteHandlingStatus::CastingVotes | VoteHandlingStatus::SchedulingVotes ) { - self.raise_vote_overlay( - ui.ctx(), - "Submitting the selected votes to Dash Platform…", - ); + // The confirm step closes at once; the drawer tracks progress + // and the staged decisions clear when the operation reports. + self.show_bulk_schedule_popup = false; + self.show_vote_progress(ui.ctx()); } } if cancel_clicked { @@ -2177,65 +2111,6 @@ impl DPNSScreen { ), )) } - - /// 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; - - self.selected_votes.clear(); - - ui.vertical_centered(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - ui.add_space(20.0); - match &self.bulk_vote_handling_status { - VoteHandlingStatus::Completed => { - ui.heading( - RichText::new("Your votes have been submitted or scheduled as requested.") - .color(DashColors::text_primary(dark_mode)), - ); - ui.label( - "Check the recent voting activity to see which votes were confirmed, are still pending, or failed.", - ); - } - VoteHandlingStatus::Failed(error) => { - // This means there was a DET-side error, not Platform-side - let dark_mode = ui.style().visuals.dark_mode; - ui.heading( - RichText::new("The votes could not be submitted.") - .color(DashColors::text_primary(dark_mode)), - ); - ui.add_space(10.0); - ui.label( - RichText::new(error.to_string()) - .color(DashColors::text_primary(dark_mode)), - ); - } - _ => { - // this should not occur - } - } - - ui.add_space(20.0); - let dark_mode = ui.style().visuals.dark_mode; - if ComponentStyles::add_primary_button(ui, "Back to To decide").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, "Show scheduled votes", dark_mode) - .clicked() - { - self.show_bulk_schedule_popup = false; - self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; - self.view = VotesView::Scheduled; - } - }); - - action - } } // --------------------------- @@ -2311,7 +2186,7 @@ impl ScreenLike for DPNSScreen { } fn display_backend_task_error(&mut self, context: &BackendTaskContext, _error: &TaskError) { - self.clear_vote_overlay_on_error = match self.pending_vote_operation { + self.release_pending_on_error = match self.pending_vote_operation { Some(operation_id) => { dpns_operation_id(context, self.app_context.network()) == Some(operation_id) } @@ -2326,10 +2201,9 @@ impl ScreenLike for DPNSScreen { "Could not refresh proved DPNS votes after a task error" ); } - if self.clear_vote_overlay_on_error { - self.vote_overlay.take_and_clear(); + if self.release_pending_on_error { self.pending_vote_operation = None; - self.clear_vote_overlay_on_error = false; + self.release_pending_on_error = false; // The review window disables both Submit and Cancel while a // submission is in flight, so a failed submission must leave that // state here. Otherwise the window stays on "Submitting votes…" @@ -2378,13 +2252,14 @@ impl ScreenLike for DPNSScreen { } let owns_result = self.pending_vote_operation == Some(operation_id); if owns_result { - self.vote_overlay.take_and_clear(); self.pending_vote_operation = None; if matches!( self.bulk_vote_handling_status, VoteHandlingStatus::CastingVotes | VoteHandlingStatus::SchedulingVotes ) { - self.bulk_vote_handling_status = VoteHandlingStatus::Completed; + self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; + self.selected_votes.clear(); + self.selected_cards.clear(); } } if let Err(error) = self.vote_operations.refresh(&self.app_context) { @@ -2434,6 +2309,12 @@ impl ScreenLike for DPNSScreen { let ctx = &ctx; let mut action = AppAction::None; + // `Review again` from the progress drawer, which lives outside this panel. + if let Some(outcome) = self.app_context.take_dpns_vote_review_request() { + self.view = VotesView::ToDecide; + self.review_failed_target(&outcome); + } + ui.horizontal(|ui| { for view in VotesView::ALL { if ui.selectable_label(self.view == view, view.label()).clicked() { @@ -2552,7 +2433,6 @@ impl ScreenLike for DPNSScreen { self.pending_scheduled_actions.insert(key, context.clone()); action = AppAction::BackendTaskWithContext { task, context }; self.scheduled_vote_editor = None; - self.raise_vote_overlay(ui.ctx(), "Saving the scheduled vote…"); } } } @@ -2574,11 +2454,9 @@ impl ScreenLike for DPNSScreen { if self.voting_identities.is_empty() && self.voting_identity_load_error.is_none() { action |= self.render_no_voting_nodes(ui); } + self.render_needs_attention(ui); if self.active_contests.is_empty() { action |= self.render_empty_view(ui); - egui::ScrollArea::vertical() - .id_salt("voting_activity_without_contests") - .show(ui, |ui| self.render_voting_activity(ui)); } else { self.render_active_contests(ui); } @@ -2734,27 +2612,26 @@ mod tests { } } + /// VOTE-FR-035: no window overlay; staged decisions clear only when this + /// panel's own operation reports, never on another operation's update. #[test] - fn vote_submission_overlay_clears_when_the_operation_finishes() { + fn own_operation_result_clears_staged_decisions_without_an_overlay() { let (ctx, _temp_dir) = offline_ctx(); let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); - - screen.raise_vote_overlay( - ctx.egui_ctx(), - "Submitting the selected votes to Dash Platform…", - ); + screen.selected_votes = vec![SelectedVote { + contested_name: "alpha".to_owned(), + vote_choice: ResourceVoteChoice::Lock, + end_time: None, + }]; + screen.bulk_vote_handling_status = VoteHandlingStatus::CastingVotes; screen.pending_vote_operation = Some(DpnsVoteOperationId::from_bytes([7; 16])); - assert!( - crate::ui::components::progress_overlay::ProgressOverlay::has_global(ctx.egui_ctx()) - ); screen.display_task_result(BackendTaskSuccessResult::DpnsVoteOperationUpdated { network: ctx.network(), operation_id: DpnsVoteOperationId::from_bytes([8; 16]), }); - assert!( - crate::ui::components::progress_overlay::ProgressOverlay::has_global(ctx.egui_ctx()) - ); + assert_eq!(screen.selected_votes.len(), 1); + assert!(screen.pending_vote_operation.is_some()); screen .pending_scheduled_actions @@ -2764,10 +2641,16 @@ mod tests { operation_id: DpnsVoteOperationId::from_bytes([7; 16]), }); + assert!(screen.selected_votes.is_empty()); + assert!(screen.pending_vote_operation.is_none()); + assert!(matches!( + screen.bulk_vote_handling_status, + VoteHandlingStatus::NotStarted + )); + assert!(!screen.pending_scheduled_actions.is_empty()); assert!( !crate::ui::components::progress_overlay::ProgressOverlay::has_global(ctx.egui_ctx()) ); - assert!(!screen.pending_scheduled_actions.is_empty()); } #[test] @@ -3069,16 +2952,10 @@ mod tests { screen.show_bulk_schedule_popup = true; screen.bulk_vote_handling_status = in_progress; screen.pending_vote_operation = Some(operation_id); - screen.raise_vote_overlay(ctx.egui_ctx(), "Submitting the selected votes…"); screen.display_backend_task_error(&context, &error); screen.display_task_error(&error); - assert!( - !crate::ui::components::progress_overlay::ProgressOverlay::has_global( - ctx.egui_ctx() - ) - ); assert_eq!(screen.pending_vote_operation, None); let VoteHandlingStatus::Failed(failure) = &screen.bulk_vote_handling_status else { panic!( @@ -3201,7 +3078,13 @@ mod tests { reopened.ui(ui); }); harness.run(); - assert!(harness.query_by_label("Check again").is_some()); + // VOTE-TC-099: the Needs attention row leads to the drawer's Check again. + assert!( + harness + .query_by_label("Needs attention: 1 vote is still being checked.") + .is_some() + ); + assert!(harness.query_by_label("Show progress").is_some()); } #[test] @@ -3308,20 +3191,16 @@ mod tests { .app_context .insert_dpns_vote_operation(&mut operation, None) .unwrap(); - for subscreen in [VotesView::Scheduled, VotesView::ToDecide] { - let scheduled = subscreen == VotesView::Scheduled; - let mut reopened = DPNSScreen::new(&screen.app_context, subscreen); - let mut harness = egui_kittest::Harness::builder() - .with_size(egui::vec2(1600.0, 1200.0)) - .build_ui(move |ui| { - reopened.ui(ui); - }); - harness.run(); - if scheduled { - assert!(harness.query_by_label("Not submitted").is_some()); - } - assert!(harness.query_by_label(reason).is_some()); - } + // 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()); } } @@ -3509,14 +3388,12 @@ mod tests { screen .pending_scheduled_actions .insert(key.clone(), dispatch.clone()); - screen.raise_vote_overlay(&screen.app_context.egui_ctx().clone(), "Submitting…"); 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)); - assert!(screen.vote_overlay.is_some()); let sweep = BackendTaskContext::ScheduledVoteSweep { network: screen.app_context.network(), }; @@ -3531,10 +3408,8 @@ mod tests { screen.display_backend_task_error(&sweep, &error); screen.display_task_error(&error); assert!(screen.pending_scheduled_actions.contains_key(&key)); - assert!(screen.vote_overlay.is_some()); screen.display_backend_task_result(&dispatch, updated); assert!(screen.pending_scheduled_actions.is_empty()); - assert!(screen.vote_overlay.is_none()); screen .pending_scheduled_actions .insert(key.clone(), dispatch.clone()); @@ -3843,38 +3718,50 @@ mod tests { ); } + /// VOTE-TC-098: the drawer names each node and its typed status, and + /// offers only the valid action. #[test] - fn voting_ui_activity_identifies_each_node() { + fn progress_drawer_identifies_each_node_and_status() { use egui_kittest::kittest::Queryable; - let (mut screen, _temp_dir) = voting_ui_review_fixture(); + 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 = Some("node-two".to_owned()); - let mut operation = DpnsVoteOperation::new(vec![first, second]); + let mut third = first.clone(); + third.key.voter_id = Identifier::from([3; 32]); + third.voter_alias = Some("node-three".to_owned()); + let mut operation = DpnsVoteOperation::new(vec![first, second, third]); operation.targets[0].status = DpnsVoteTargetStatus::Confirmed; operation.targets[1].status = DpnsVoteTargetStatus::Rejected; - screen - .app_context + operation.targets[2].status = DpnsVoteTargetStatus::Unconfirmed; + let context = screen.app_context.clone(); + context .insert_dpns_vote_operation(&mut operation, None) .unwrap(); - screen.vote_operations.refresh(&screen.app_context).unwrap(); - let mut harness = egui_kittest::Harness::builder().build_ui(move |ui| { - screen.render_voting_activity(ui); - }); + 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(); - assert!( - harness - .query_by_label("node-one β€” alpha.dash β€” Abstain β€” Confirmed") - .is_some() - ); - assert!( - harness - .query_by_label("node-two β€” alpha.dash β€” Abstain β€” Rejected") - .is_some() - ); + for label in [ + "Casting 3 votes Β· 2 done Β· 0 sending Β· 1 being checked", + "node-one Β· alpha.dash Β· Abstain", + "Voted", + "node-two Β· alpha.dash Β· Abstain", + "Rejected by Platform", + "Review again", + "Still being checked. Don't submit it again.", + "Check again", + ] { + assert!(harness.query_by_label(label).is_some(), "missing {label}"); + } } #[test] diff --git a/src/ui/dpns/mod.rs b/src/ui/dpns/mod.rs index ae6f6208c..d9036cfef 100644 --- a/src/ui/dpns/mod.rs +++ b/src/ui/dpns/mod.rs @@ -5,6 +5,7 @@ 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)] diff --git a/src/ui/dpns/progress_drawer.rs b/src/ui/dpns/progress_drawer.rs new file mode 100644 index 000000000..f44e546d5 --- /dev/null +++ b/src/ui/dpns/progress_drawer.rs @@ -0,0 +1,290 @@ +//! 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, DpnsVoteOperationId, 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::platform_value::string_encoding::Encoding; +use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use eframe::egui::{self, Align2, Id, RichText, Sense, Ui}; +use std::collections::BTreeSet; + +const OPEN_ID: &str = "dpns_vote_progress_drawer_open"; + +/// AppState-owned drawer state; survives navigation. +#[derive(Debug, Clone)] +pub struct DrawerState { + /// Settled operations created before this time are not listed. + since_ms: u64, + dismissed: BTreeSet, +} + +impl DrawerState { + pub fn new(since_ms: u64) -> Self { + Self { + since_ms, + dismissed: BTreeSet::new(), + } + } + + /// 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, + ( + DpnsVoteTargetStatus::Rejected + | DpnsVoteTargetStatus::FailedBeforeSubmission + | DpnsVoteTargetStatus::NotApplied, + _, + ) => Some(RowAction::ReviewAgain), + _ => None, + } +} + +fn choice_label(choice: ResourceVoteChoice) -> String { + match choice { + ResourceVoteChoice::Lock => "Lock".to_owned(), + ResourceVoteChoice::Abstain => "Abstain".to_owned(), + ResourceVoteChoice::TowardsIdentity(id) => { + let encoded = id.to_string(Encoding::Base58); + format!("Vote for {head}…", head = &encoded[..6]) + } + } +} + +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 shown = drawer_operations(&operations, state.since_ms, &state.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() { + state + .dismissed + .extend(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 = + outcome.target.voter_alias.clone().unwrap_or_else(|| { + let encoded = + outcome.target.key.voter_id.to_string(Encoding::Base58); + format!("{head}…", head = &encoded[..6]) + }); + ui.label(format!( + "{node} Β· {name}.dash Β· {choice}", + name = outcome.target.contested_name, + choice = choice_label(outcome.target.requested_choice), + )); + 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::{ + DpnsVoteOperation, DpnsVoteTarget, DpnsVoteTargetKey, VoteTiming, + }; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::platform::Identifier; + + fn outcome(status: DpnsVoteTargetStatus, failure: Option) -> DpnsVoteOutcome { + let mut operation = DpnsVoteOperation::new(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 + } + + /// 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/state/dpns_vote_operations.rs b/src/ui/state/dpns_vote_operations.rs index 67b855308..80a11809e 100644 --- a/src/ui/state/dpns_vote_operations.rs +++ b/src/ui/state/dpns_vote_operations.rs @@ -22,7 +22,6 @@ pub(crate) struct ScheduledDpnsVoteRow { #[derive(Debug, Clone, Default)] pub struct DpnsVoteOperationSnapshot { operations: Vec, - recent_operations: Arc<[DpnsVoteOperation]>, dismissed_schedules: BTreeSet<(DpnsVoteOperationId, DpnsVoteTargetKey)>, target_statuses: BTreeMap, loaded: bool, @@ -62,10 +61,6 @@ impl DpnsVoteOperationSnapshot { &self.operations } - pub(crate) fn recent_operations(&self) -> Arc<[DpnsVoteOperation]> { - Arc::clone(&self.recent_operations) - } - pub fn operation(&self, id: DpnsVoteOperationId) -> Option<&DpnsVoteOperation> { self.operations.iter().find(|operation| operation.id == id) } @@ -165,30 +160,6 @@ impl DpnsVoteOperationSnapshot { .filter(|outcome| outcome.status.holds_lock()) .map(|outcome| (outcome.target.key.clone(), outcome.status)) .collect(); - let mut recent = operations - .iter() - .filter(|operation| !operation.targets.is_empty()) - .collect::>(); - recent.sort_by_key(|operation| operation.created_at); - // Pending operations must remain reachable even after newer batches complete. - let mut completed_count = 0; - self.recent_operations = recent - .into_iter() - .rev() - .filter(|operation| { - if operation - .targets - .iter() - .any(|outcome| outcome.status.holds_lock()) - { - true - } else { - completed_count += 1; - completed_count <= 5 - } - }) - .cloned() - .collect(); self.operations = operations; self.loaded = true; } @@ -203,52 +174,6 @@ mod tests { use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; use dash_sdk::platform::Identifier; - #[test] - fn voting_ui_unresolved_activity_survives_newer_completed_batches() { - let mut snapshot = DpnsVoteOperationSnapshot::default(); - let mut unresolved = operation(DpnsVoteTargetStatus::Unconfirmed); - unresolved.created_at = 0; - let unresolved_id = unresolved.id; - let mut operations = vec![unresolved]; - for created_at in 1..=8 { - let mut completed = operation(DpnsVoteTargetStatus::Confirmed); - completed.created_at = created_at; - operations.push(completed); - } - snapshot.replace(operations); - let visible = snapshot.recent_operations(); - assert!( - visible - .iter() - .any(|operation| operation.id == unresolved_id) - ); - assert_eq!(visible.len(), 6); - } - - #[test] - fn voting_ui_recent_activity_is_bounded_ordered_and_shared_between_frames() { - let mut snapshot = DpnsVoteOperationSnapshot::default(); - let operations = (0..20) - .map(|created_at| { - let mut operation = operation(DpnsVoteTargetStatus::Confirmed); - operation.created_at = created_at; - operation - }) - .collect(); - snapshot.replace(operations); - let first = snapshot.recent_operations(); - let second = snapshot.recent_operations(); - assert!(Arc::ptr_eq(&first, &second)); - assert_eq!( - first - .iter() - .map(|operation| operation.created_at) - .collect::>(), - vec![19, 18, 17, 16, 15] - ); - assert_eq!(snapshot.operations().len(), 20); - } - #[test] fn voting_ui_dismissed_terminal_row_suppresses_its_mirror_and_preserves_siblings() { let mut operation = scheduled_operation( From b1402b927fc47a5a6b5a039c75b693b096383b24 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:45:18 +0000 Subject: [PATCH 076/194] feat(dpns): keyboard shortcuts and bulk decisions in Votes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While the contest list has focus β€” and never while a text field does (VOTE-NFR-010) β€” J/K or ↓/↑ move card focus, 1–9 vote for contender n, L locks, A abstains, 0 clears, Space selects and Enter opens the confirm step. Every key has a visible equivalent, listed in a Shortcuts popover. Selecting two or more names shows a bulk bar: Lock name Β· Abstain Β· Clear (VOTE-FR-082). Test-case references in voting tests now match the spec's IDs, and the changes-left label reads "{n} of 4 changes left, counted on this device". Co-Authored-By: Claude Opus 5.5 --- src/app.rs | 2 +- src/backend_task/contested_names/mod.rs | 2 +- src/context/dpns_vote_preferences.rs | 2 +- src/model/dpns_voting/composer.rs | 10 +- src/model/dpns_voting/progress.rs | 4 +- src/ui/dpns/contest_card.rs | 7 +- src/ui/dpns/copy.rs | 11 +- src/ui/dpns/dpns_contested_names_screen.rs | 339 ++++++++++++++++++++- src/ui/dpns/node_set_picker.rs | 2 +- src/ui/state/dpns_vote_cards.rs | 84 ++++- 10 files changed, 428 insertions(+), 35 deletions(-) diff --git a/src/app.rs b/src/app.rs index 0c3cc9800..7c2bbd7a9 100644 --- a/src/app.rs +++ b/src/app.rs @@ -4187,7 +4187,7 @@ mod migration_banner_tests { /// Counts drive which sentence is built, so no single template has to carry /// a verb that is only correct for one of them. - /// VOTE-TC-101: confirmed plus still-checking targets read as nodes Γ— names + /// 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() { diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index c319be5eb..b51b81d33 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -2347,7 +2347,7 @@ mod tests { ); } - /// VOTE-TC-104 (executor half): a target whose contest closed before it + /// 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() { diff --git a/src/context/dpns_vote_preferences.rs b/src/context/dpns_vote_preferences.rs index 6d4c7af17..24f70bb8d 100644 --- a/src/context/dpns_vote_preferences.rs +++ b/src/context/dpns_vote_preferences.rs @@ -115,7 +115,7 @@ mod tests { use dash_sdk::platform::Identifier; use std::collections::BTreeSet; - /// VOTE-TC-094 (label half): the label is bound to the exact time; a + /// VOTE-TC-067 (label half): the label is bound to the exact time; a /// different time reads no label, so the row shows the absolute time only. #[test] fn relative_label_is_bound_to_its_absolute_time() { diff --git a/src/model/dpns_voting/composer.rs b/src/model/dpns_voting/composer.rs index a30ff9cb6..f73a77efa 100644 --- a/src/model/dpns_voting/composer.rs +++ b/src/model/dpns_voting/composer.rs @@ -269,7 +269,7 @@ mod tests { } } - /// VOTE-TC-090: two decisions Γ— three nodes give six targets, one per node and name. + /// 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; @@ -293,7 +293,7 @@ mod tests { assert!(plan.skipped.is_empty()); } - /// VOTE-TC-091/093/007/041: every exclusion becomes a typed skip. + /// VOTE-TC-003/007/041/096: every exclusion becomes a typed skip. #[test] fn exclusions_are_skipped_with_reasons() { let lock = ResourceVoteChoice::Lock; @@ -365,7 +365,7 @@ mod tests { assert_eq!(plan.targets.len(), 1); } - /// VOTE-TC-094/095: "about to end" resolves per contest; per-node overrides win. + /// 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; @@ -406,7 +406,7 @@ mod tests { assert!(!plan.all_now()); } - /// VOTE-TC-095 (rejection half): a time at or after the deadline is refused. + /// VOTE-FR-081: a time at or after the deadline is refused. #[test] fn schedules_outside_the_window_are_rejected() { let lock = ResourceVoteChoice::Lock; @@ -449,7 +449,7 @@ mod tests { ); } - /// VOTE-TC-104 (compose half): a decision whose voting ended is refused. + /// VOTE-TC-103 (compose half): a decision whose voting ended is refused. #[test] fn ended_contests_are_refused() { let result = compose( diff --git a/src/model/dpns_voting/progress.rs b/src/model/dpns_voting/progress.rs index 08583156f..203a2b5e3 100644 --- a/src/model/dpns_voting/progress.rs +++ b/src/model/dpns_voting/progress.rs @@ -184,7 +184,7 @@ mod tests { use DpnsVoteTargetStatus as S; const NOW: VoteTiming = VoteTiming::Now; - /// VOTE-TC-098: the drawer header counts done, sending and checking. + /// VOTE-TC-101: the drawer header counts done, sending and checking. #[test] fn counts_group_targets_by_phase_and_skip_schedules() { let op = operation( @@ -238,7 +238,7 @@ mod tests { assert_eq!(shown, vec![old_in_flight.id, recent_settled.id]); } - /// VOTE-TC-099: unconfirmed, failed and missed targets need attention. + /// VOTE-TC-102: unconfirmed, failed and missed targets need attention. #[test] fn needs_attention_counts_each_kind() { let operations = vec![ diff --git a/src/ui/dpns/contest_card.rs b/src/ui/dpns/contest_card.rs index feaa1ee53..08b80d716 100644 --- a/src/ui/dpns/contest_card.rs +++ b/src/ui/dpns/contest_card.rs @@ -154,6 +154,8 @@ pub struct CardView<'a> { 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, @@ -172,7 +174,7 @@ impl CardView<'_> { } else { egui::Stroke::new(1.0, DashColors::border_light(dark_mode)) }; - egui::Frame::group(ui.style()) + let frame = egui::Frame::group(ui.style()) .stroke(stroke) .show(ui, |ui| { ui.set_min_width(ui.available_width()); @@ -181,6 +183,9 @@ impl CardView<'_> { self.show_decision(&mut columns[1], &mut events); }); }); + if self.scroll_into_view { + ui.scroll_to_rect(frame.response.rect, None); + } events } diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index 97eb24ab0..c896941d4 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -365,8 +365,7 @@ pub fn decision_row(name: &str, choice: &str, nodes: usize) -> String { /// Changes-left cell under `Adjust nodes` (VOTE-FR-078). pub fn changes_left_label(changes: ChangesLeft) -> String { match changes { - ChangesLeft::Known(1) => "1 change left, counted on this device".to_owned(), - ChangesLeft::Known(left) => format!("{left} changes left, counted on this device"), + ChangesLeft::Known(left) => format!("{left} of 4 changes left, counted on this device"), ChangesLeft::Unknown => { "Changes left unknown. This node voted outside Dash Evo Tool.".to_owned() } @@ -432,7 +431,7 @@ mod tests { ); } - /// VOTE-TC-090/091 (copy half): the confirm lines follow VOTE-FR-080. + /// 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"); @@ -461,7 +460,7 @@ mod tests { ); assert_eq!( changes_left_label(ChangesLeft::Known(3)), - "3 changes left, counted on this device" + "3 of 4 changes left, counted on this device" ); assert_eq!( changes_left_label(ChangesLeft::Unknown), @@ -469,7 +468,7 @@ mod tests { ); } - /// VOTE-TC-101: the batch banner counts nodes and names. + /// 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."); @@ -479,7 +478,7 @@ mod tests { ); } - /// VOTE-TC-098/099/104 (copy half). + /// VOTE-TC-101/102/103 (copy half). #[test] fn drawer_and_attention_copy() { assert_eq!( diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index fb314cb64..9dc97424d 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -55,7 +55,8 @@ 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, VoteCard, sort_by_time_left, + CantVoteReason, CardPlacement, NodeContestState, NodeContestStatus, SHORTCUT_HELP, Shortcut, + VoteCard, move_focus, shortcut_for, sort_by_time_left, }; use crate::ui::state::dpns_vote_operations::{DpnsVoteOperationSnapshot, ScheduledDpnsVoteRow}; use crate::ui::state::dpns_vote_state::DpnsVoteStateSnapshot; @@ -515,6 +516,8 @@ pub struct DPNSScreen { /// 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 { @@ -604,6 +607,7 @@ impl DPNSScreen { relative_schedule_labels: BTreeMap::new(), selected_cards: BTreeSet::new(), focused_card: None, + list_focused: false, }; screen.rebuild_cards(); screen.rebuild_scheduled_vote_rows(); @@ -922,14 +926,34 @@ impl DPNSScreen { } } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.add( - egui::TextEdit::singleline(&mut self.active_filter_term) - .hint_text("Filter by name") - .desired_width(180.0), - ) - .on_hover_text( - "The letters i and l match the digit 1, and the letter o matches 0.", - ); + 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( + "The letters i and l match the digit 1, and the letter o matches 0.", + ); + if filter.has_focus() { + self.list_focused = false; + } }); }); ui.add_space(8.0); @@ -974,8 +998,11 @@ impl DPNSScreen { Vec::new() }; + let scroll_to = self.handle_shortcuts(ui, &listed); + self.render_bulk_bar(ui); + let mut events: Vec<(usize, CardEvent)> = Vec::new(); - egui::ScrollArea::vertical() + let list = egui::ScrollArea::vertical() .id_salt("active_contest_cards") .max_height(ui.available_height() - 48.0) .show(ui, |ui| { @@ -998,6 +1025,7 @@ impl DPNSScreen { 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, @@ -1030,6 +1058,19 @@ impl DPNSScreen { } }); + // 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 { @@ -1054,6 +1095,149 @@ impl DPNSScreen { self.render_tray(ui); } + /// 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 => self.selected_votes.push(SelectedVote { + contested_name: contest.normalized_contested_name.clone(), + vote_choice: choice, + end_time: contest.end_time, + }), + } + } + + fn clear_choice(&mut self, contested_name: &str) { + self.selected_votes + .retain(|vote| vote.contested_name != contested_name); + } + + /// 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.show_bulk_schedule_popup + || 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 + } + + /// 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), + } + } + } + /// 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(); @@ -2612,7 +2796,7 @@ mod tests { } } - /// VOTE-FR-035: no window overlay; staged decisions clear only when this + /// 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() { @@ -3078,7 +3262,7 @@ mod tests { reopened.ui(ui); }); harness.run(); - // VOTE-TC-099: the Needs attention row leads to the drawer's Check again. + // VOTE-TC-102: the Needs attention row leads to the drawer's Check again. assert!( harness .query_by_label("Needs attention: 1 vote is still being checked.") @@ -3289,7 +3473,7 @@ mod tests { ); } - /// VOTE-TC-095: absolute and relative schedules must fall strictly + /// 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() { @@ -3560,6 +3744,131 @@ mod tests { ); } + /// 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().show_bulk_schedule_popup); + 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()); + } + #[test] fn voting_ui_keyless_users_can_read_cached_active_contests() { use egui_kittest::kittest::Queryable; @@ -3718,7 +4027,7 @@ mod tests { ); } - /// VOTE-TC-098: the drawer names each node and its typed status, and + /// 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() { @@ -4033,7 +4342,7 @@ mod tests { ); } - /// VOTE-TC-094: a "before the end" schedule shows its preset next to the + /// 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() { diff --git a/src/ui/dpns/node_set_picker.rs b/src/ui/dpns/node_set_picker.rs index af1314474..6996ebc27 100644 --- a/src/ui/dpns/node_set_picker.rs +++ b/src/ui/dpns/node_set_picker.rs @@ -137,7 +137,7 @@ mod tests { } } - /// VOTE-TC-096/097: disabled rows carry their reason; unknown membership + /// 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() { diff --git a/src/ui/state/dpns_vote_cards.rs b/src/ui/state/dpns_vote_cards.rs index fbc36902a..1fc37dd0c 100644 --- a/src/ui/state/dpns_vote_cards.rs +++ b/src/ui/state/dpns_vote_cards.rs @@ -173,6 +173,69 @@ impl VoteCard { } } +/// 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| { @@ -303,8 +366,8 @@ mod tests { ); } - /// VOTE-TC-041: a card whose only node is sending leaves To decide (it - /// needs no decision) and takes no new decision for that node. + /// 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( @@ -345,6 +408,23 @@ mod tests { 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() { From 9821f104ae3862b8f47d1b2bc7f569e15b1ba10b Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:46:55 +0000 Subject: [PATCH 077/194] fix(identity): close username QA gaps before and after payment - Detect the identity's own running request (AlreadyRequested) so a second request is blocked before the preorder fee is spent. - After the documents are broadcast, re-reads and local saves are best-effort: registration always reports success and records the request, so Pay is never re-enabled for a paid name. Joined requests take the contest's real join and vote dates. - A pay-time re-check network failure lifts the overlay and returns to the confirm step with a banner; availability checks run one at a time so a late failure never marks the wrong label. - Stop writing an automatic {name}.dash alias, and ignore legacy ones in labels, so Show as main applies to pill, switcher, picker and pages. - Won names are listed at once and the identity's names are re-read after a won vote; NoWinner is its own outcome; standing follows Platform rules (lone request leads, ties go to the latest request, lock can lead). - Username writes (main name, dismiss, seen banners) go through backend tasks; updates are atomic so a refresh never drops a just-recorded request; removing an identity clears its username records. - The hub refresh cadence keys off dispatch time and never stalls; local storage problems in the background refresh are logged, not bannered. - The signing gate matches Platform key rules (enabled, non-master, strong enough for DPNS documents). Co-Authored-By: Claude Opus 5.5 --- src/backend_task/error.rs | 9 + src/backend_task/identity/dpns_usernames.rs | 150 ++++++-- src/backend_task/identity/mod.rs | 33 +- .../refresh_loaded_identities_dpns_names.rs | 109 +++--- .../identity/register_dpns_name.rs | 355 +++++++++++------- src/backend_task/mod.rs | 2 + src/context/contested_names_db.rs | 153 +++++--- src/context/identity_db.rs | 7 + src/model/dpns_usernames.rs | 260 +++++++++++-- src/ui/components/address_input.rs | 1 + src/ui/components/global_nav_switcher.rs | 28 +- src/ui/components/pill.rs | 1 + src/ui/identity/hub_screen.rs | 18 +- src/ui/identity/identity_hero_card.rs | 1 + src/ui/identity/picker.rs | 2 +- src/ui/identity/register_dpns_name_screen.rs | 55 ++- src/ui/identity/username_copy.rs | 32 +- src/ui/identity/username_notices.rs | 46 ++- src/ui/identity/username_request_screen.rs | 22 +- src/ui/identity/usernames_card.rs | 94 +++-- tests/kittest/identity_usernames.rs | 298 ++++++++++++++- 21 files changed, 1257 insertions(+), 419 deletions(-) diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 155fb07fa..787807227 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1973,6 +1973,15 @@ pub enum TaskError { availability: crate::model::dpns_usernames::UsernameAvailability, }, + /// 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." diff --git a/src/backend_task/identity/dpns_usernames.rs b/src/backend_task/identity/dpns_usernames.rs index 2e10330a4..241ef6bb0 100644 --- a/src/backend_task/identity/dpns_usernames.rs +++ b/src/backend_task/identity/dpns_usernames.rs @@ -20,9 +20,10 @@ use crate::model::dpns::{ normalize_dpns_label, validate_dpns_name, }; use crate::model::dpns_usernames::{ - ContenderTally, ContestSnapshot, ContestWinner, UsernameAvailability, UsernameRequest, - classify_availability, merge_requests, username_request_from_contest, + ContenderTally, ContestSnapshot, ContestWinner, RequestPhase, UsernameAvailability, + UsernameRequest, classify_availability, merge_requests, username_request_from_contest, }; +use crate::model::qualified_identity::QualifiedIdentity; use crate::utils::time::now_ms; fn availability_error(source: SdkError) -> TaskError { @@ -39,9 +40,13 @@ impl AppContext { /// 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); @@ -60,6 +65,7 @@ impl AppContext { None }; Ok(classify_availability( + requester, label, awarded, contest.as_ref(), @@ -71,9 +77,10 @@ impl AppContext { pub(super) async fn check_username_availability( &self, sdk: &Sdk, + identity_id: Identifier, label: String, ) -> Result { - let availability = self.username_availability(sdk, &label).await?; + let availability = self.username_availability(sdk, identity_id, &label).await?; Ok(BackendTaskSuccessResult::UsernameAvailability { label, availability, @@ -169,20 +176,29 @@ impl AppContext { /// Refresh the username requests of every loaded identity. /// - /// One scan of running contests serves all identities. Requests that left - /// the running set are re-read individually to learn their outcome. + /// One scan of running contests serves all identities. Requests missing + /// from the scan are re-read individually, for their outcome or running + /// tally. Only the network scan fails the task; local storage problems are + /// logged so a background refresh never raises a banner. pub(super) async fn refresh_my_username_requests( &self, sdk: &Sdk, ) -> Result { - let identity_ids: Vec = self - .load_local_user_identities()? - .iter() - .map(|identity| identity.identity.id()) - .collect(); - if identity_ids.is_empty() { + let identities = match self.load_local_user_identities() { + Ok(identities) => identities, + Err(error) => { + tracing::debug!( + ?error, + "Username requests not refreshed: identities unavailable" + ); + return Ok(BackendTaskSuccessResult::MyUsernameRequestsRefreshed); + } + }; + if identities.is_empty() { return Ok(BackendTaskSuccessResult::MyUsernameRequestsRefreshed); } + // 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 = sdk .get_contested_non_resolved_usernames(None) .await @@ -201,7 +217,8 @@ impl AppContext { }) .collect(); - for identity_id in identity_ids { + for mut identity in identities { + let identity_id = identity.identity.id(); let previous = self.username_requests_for(&identity_id); let mut fresh: Vec = snapshots .iter() @@ -223,21 +240,14 @@ impl AppContext { .get_contested_dpns_vote_state(&old.normalized_label, None) .await { - Ok(contenders) => { - let snapshot = self.contest_snapshot(sdk, &contenders); - if snapshot.winner.is_some() - && let Some(outcome) = username_request_from_contest( - identity_id, - &old.normalized_label, - &snapshot, - old.end, - now, - durations, - ) - { - fresh.push(outcome); - } - } + Ok(contenders) => fresh.extend(username_request_from_contest( + identity_id, + &old.normalized_label, + &self.contest_snapshot(sdk, &contenders), + old.end, + now, + durations, + )), Err(error) => tracing::debug!( name = %old.normalized_label, ?error, @@ -245,26 +255,96 @@ impl AppContext { ), } } - let merged = merge_requests(&previous, fresh, now); - if merged != previous { - self.store_username_requests(&identity_id, merged)?; + let newly_won = fresh.iter().any(|request| { + request.phase == RequestPhase::Won + && !previous.iter().any(|old| { + old.normalized_label == request.normalized_label + && old.phase == RequestPhase::Won + }) + }); + if let Err(error) = self.update_username_requests(&identity_id, |current| { + merge_requests(current, fresh, now) + }) { + tracing::warn!(?error, %identity_id, "Username requests could not be stored"); + } + if newly_won { + self.record_won_usernames(sdk, &mut identity).await; } } Ok(BackendTaskSuccessResult::MyUsernameRequestsRefreshed) } + /// Re-read the registered names of an identity that just won a vote, so the + /// won name is listed and shown at once. + async fn record_won_usernames(&self, sdk: &Sdk, identity: &mut QualifiedIdentity) { + match self + .fetch_owned_dpns_names(sdk, identity.identity.id()) + .await + { + Ok(names) => { + identity.dpns_names = names; + if let Err(error) = self.update_local_qualified_identity(identity) { + tracing::warn!(?error, "Won username could not be saved on the identity"); + } + } + Err(error) => { + tracing::debug!( + ?error, + "Registered names could not be re-read after a won vote" + ) + } + } + } + /// 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)); - let previous = self.username_requests_for(identity_id); - let merged = merge_requests(&previous, vec![submitted], now); - self.store_username_requests(identity_id, merged) + let submitted = UsernameRequest::submitted( + label, + now, + self.username_contest_durations(sdk), + joined_until, + ); + self.update_username_requests(identity_id, |current| { + merge_requests(current, vec![submitted], now) + }) + } + + /// 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.mark_username_outcomes_seen(&identity_id, &requests)?; + Ok(BackendTaskSuccessResult::UsernamePreferencesSaved) } } diff --git a/src/backend_task/identity/mod.rs b/src/backend_task/identity/mod.rs index 1b648d729..66597bd62 100644 --- a/src/backend_task/identity/mod.rs +++ b/src/backend_task/identity/mod.rs @@ -551,11 +551,28 @@ pub enum IdentityTask { 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. @@ -961,10 +978,22 @@ impl AppContext { IdentityTask::RefreshLoadedIdentitiesOwnedDPNSNames => { Ok(self.refresh_loaded_identities_dpns_names(sender).await?) } - IdentityTask::CheckUsernameAvailability { label } => { - self.check_username_availability(sdk, label).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/refresh_loaded_identities_dpns_names.rs b/src/backend_task/identity/refresh_loaded_identities_dpns_names.rs index d977c07b0..c5083cbf7 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( @@ -19,65 +19,9 @@ 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; - - if qualified_identity.alias.is_none() && !qualified_identity.dpns_names.is_empty() { - let dpns_name = &qualified_identity.dpns_names[0].name; - qualified_identity.alias = Some(format!("{}.dash", dpns_name)); - } - + qualified_identity.dpns_names = self + .fetch_owned_dpns_names(&sdk, qualified_identity.identity.id()) + .await?; self.update_local_qualified_identity(&qualified_identity)?; } @@ -88,4 +32,49 @@ impl AppContext { Ok(BackendTaskSuccessResult::RefreshedOwnedDpnsNames) } + + /// 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 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 documents = + Document::fetch_many(sdk, query) + .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()) + } } diff --git a/src/backend_task/identity/register_dpns_name.rs b/src/backend_task/identity/register_dpns_name.rs index 3051c67d7..4103244da 100644 --- a/src/backend_task/identity/register_dpns_name.rs +++ b/src/backend_task/identity/register_dpns_name.rs @@ -16,31 +16,19 @@ use dash_sdk::{ data_contract::{ accessors::v0::DataContractV0Getters, document_type::accessors::DocumentTypeV0Getters, }, - document::{DocumentV0, DocumentV0Getters}, + document::DocumentV0, identity::accessors::IdentityGettersV0, - platform_value::{Bytes32, Value}, + platform_value::Bytes32, util::{hash::hash_double, strings::convert_to_homograph_safe_chars}, }, - drive::query::{SelectProjection, WhereClause, WhereOperator}, platform::Fetch, - platform::{Document, DocumentQuery, FetchMany, transition::put_document::PutDocument}, + platform::{Document, transition::put_document::PutDocument}, }; use super::{BackendTaskSuccessResult, RegisterDpnsNameInput}; - -/// Whether `key` may sign documents of `document_type`: an enabled authentication -/// key at least as strong as the type requires, and never a master key. -fn can_sign_documents( - key: &dash_sdk::platform::IdentityPublicKey, - document_type: &dash_sdk::dpp::data_contract::document_type::DocumentTypeRef, -) -> 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() <= document_type.security_level_requirement() -} +use crate::model::dpns_usernames::{ + UsernameAvailability, dpns_signing_requirement, key_can_sign_documents, +}; fn rebrand_dpns_domain_conflict(error: TaskError) -> TaskError { match error { @@ -64,15 +52,25 @@ impl AppContext { // 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, &input.name_input).await?; + let availability = self + .username_availability( + sdk, + input.qualified_identity.identity.id(), + &input.name_input, + ) + .await?; if !availability.allows_registration() { return Err(TaskError::UsernameNoLongerAvailable { availability }); } + let joined_until = match availability { + UsernameAvailability::Joinable { join_end, .. } => Some(join_end), + _ => None, + }; 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 @@ -177,8 +175,9 @@ impl AppContext { Some(key_id) => qualified_identity .identity .get_public_key_by_id(key_id) - .filter(|key| can_sign_documents(key, &preorder_document_type)) - .filter(|key| can_sign_documents(key, &domain_document_type)), + .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)?; @@ -215,108 +214,101 @@ impl AppContext { .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, - }; - - 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; - - if qualified_identity.alias.is_none() { - qualified_identity.alias = Some(format!("{name}.dash", name = input.name_input)); - } - - let refreshed_identity = dash_sdk::platform::Identity::fetch_by_identifier( - sdk, - qualified_identity.identity.id(), - ) - .await? - .ok_or(TaskError::IdentityNotFound)?; - - let balance_after = refreshed_identity.balance(); - let actual_fee = balance_before.saturating_sub(balance_after); + Ok(self + .finish_username_registration( + sdk, + qualified_identity, + &input.name_input, + outcome, + joined_until, + balance_before, + estimated_fee, + ) + .await) + } - 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, + mut identity: crate::model::qualified_identity::QualifiedIdentity, + name: &str, + outcome: crate::model::dpns::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 == crate::model::dpns::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; - - self.update_local_qualified_identity(&qualified_identity)?; + match self.fetch_owned_dpns_names(sdk, identity_id).await { + Ok(names) => identity.dpns_names = names, + Err(error) => { + tracing::warn!( + ?error, + "Registered names could not be re-read after registration" + ); + if outcome == crate::model::dpns::DpnsRegistrationOutcome::Registered + && !identity.dpns_names.iter().any(|known| known.name == name) + { + identity.dpns_names.push(DPNSNameInfo { + name: name.to_owned(), + acquired_at: crate::utils::time::now_ms(), + }); + } + } + } - if outcome == crate::model::dpns::DpnsRegistrationOutcome::PendingCommunityVote - && let Err(error) = self.record_submitted_username_request( - sdk, - &qualified_identity.identity.id(), - &input.name_input, - ) + 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()); + identity.identity = refreshed_identity; + 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) + } + }; + + if let Err(error) = self.update_local_qualified_identity(&identity) { tracing::warn!( ?error, - "Submitted username request could not be stored locally" + "Identity could not be saved locally after username registration" ); } - let fee_result = FeeResult::new(estimated_fee, actual_fee); - Ok(BackendTaskSuccessResult::RegisteredDpnsName { + BackendTaskSuccessResult::RegisteredDpnsName { outcome, fee_result, - }) + } } } @@ -325,33 +317,16 @@ mod tests { use super::*; #[test] - fn chosen_signing_key_must_suit_dpns_documents() { + fn dpns_registration_needs_a_high_or_critical_key() { use dash_sdk::dpp::data_contracts::SystemDataContract; - use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; - use dash_sdk::dpp::identity::{Purpose, SecurityLevel}; + use dash_sdk::dpp::identity::SecurityLevel; use dash_sdk::dpp::system_data_contracts::load_system_data_contract; - use dash_sdk::dpp::version::PlatformVersion; - let pv = PlatformVersion::latest(); - let contract = load_system_data_contract(SystemDataContract::DPNS, pv).expect("DPNS"); - let domain = contract.document_type_for_name("domain").expect("domain"); - let key = |purpose, level| { - let mut key = dash_sdk::platform::IdentityPublicKey::random_key(1, Some(1), pv); - key.set_purpose(purpose); - key.set_security_level(level); - key - }; - assert!(can_sign_documents( - &key(Purpose::AUTHENTICATION, SecurityLevel::HIGH), - &domain - )); - assert!(!can_sign_documents( - &key(Purpose::AUTHENTICATION, SecurityLevel::MASTER), - &domain - )); - assert!(!can_sign_documents( - &key(Purpose::TRANSFER, SecurityLevel::CRITICAL), - &domain - )); + let contract = load_system_data_contract( + SystemDataContract::DPNS, + dash_sdk::dpp::version::PlatformVersion::latest(), + ) + .expect("DPNS"); + assert_eq!(dpns_signing_requirement(&contract), SecurityLevel::HIGH); } use dash_sdk::dpp::consensus::ConsensusError::StateError as ConsensusStateError; use dash_sdk::dpp::consensus::state::state_error::StateError; @@ -396,4 +371,114 @@ 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 { + use crate::model::qualified_identity::encrypted_key_storage::KeyStorage; + use crate::model::qualified_identity::{IdentityStatus, IdentityType, QualifiedIdentity}; + QualifiedIdentity { + identity: dash_sdk::platform::Identity::create_basic_identity( + [byte; 32].into(), + 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: dash_sdk::dpp::dashcore::Network::Testnet, + } + } + + /// 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::DpnsRegistrationOutcome; + 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(); + + 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 { .. } + )); + } + + /// 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(), + 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/mod.rs b/src/backend_task/mod.rs index 79db0e56a..acd5b1eb7 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -1049,6 +1049,8 @@ pub enum BackendTaskSuccessResult { }, /// 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, diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 0bc9d2b9f..a3ec11e18 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -186,6 +186,10 @@ 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 { @@ -248,7 +252,7 @@ impl AppContext { let mut cache = UsernameCache::default(); for key in kv .list(DetScope::Global, Some(USERNAME_REQUESTS_KEY_PREFIX)) - .map_err(contest_err)? + .map_err(username_err)? { let Some(id) = identity_from_key(&key, USERNAME_REQUESTS_KEY_PREFIX) else { continue; @@ -265,7 +269,7 @@ impl AppContext { } for key in kv .list(DetScope::Global, Some(MAIN_USERNAME_KEY_PREFIX)) - .map_err(contest_err)? + .map_err(username_err)? { if let Some(id) = identity_from_key(&key, MAIN_USERNAME_KEY_PREFIX) && let Ok(Some(name)) = kv.get::(DetScope::Global, &key) @@ -275,7 +279,7 @@ impl AppContext { } for key in kv .list(DetScope::Global, Some(SEEN_OUTCOMES_KEY_PREFIX)) - .map_err(contest_err)? + .map_err(username_err)? { if let Some(id) = identity_from_key(&key, SEEN_OUTCOMES_KEY_PREFIX) && let Ok(Some(seen)) = kv.get::>(DetScope::Global, &key) @@ -293,6 +297,8 @@ impl AppContext { .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. fn username_cache_mut(&self) -> std::sync::RwLockWriteGuard<'_, UsernameCache> { self.pending_dpns_usernames .write() @@ -323,17 +329,33 @@ impl AppContext { identity_id: &Identifier, requests: Vec, ) -> Result<(), TaskError> { - let key = identity_key(USERNAME_REQUESTS_KEY_PREFIX, identity_id); + self.update_username_requests(identity_id, |_| requests) + } + + /// Replace the request list of `identity_id` with `update(current list)`. + /// + /// 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_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 = cache.requests.get(identity_id).cloned().unwrap_or_default(); + let requests = update(¤t); + if requests == current { + return Ok(()); + } if requests.is_empty() { - kv.delete(DetScope::Global, &key).map_err(contest_err)?; - self.username_cache_mut().requests.remove(identity_id); + kv.delete(DetScope::Global, &key).map_err(username_err)?; + cache.requests.remove(identity_id); } else { kv.put(DetScope::Global, &key, &requests) - .map_err(contest_err)?; - self.username_cache_mut() - .requests - .insert(*identity_id, requests); + .map_err(username_err)?; + cache.requests.insert(*identity_id, requests); } Ok(()) } @@ -381,16 +403,15 @@ impl AppContext { /// 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> { - self.det_kv()? - .put( - DetScope::Global, - &identity_key(MAIN_USERNAME_KEY_PREFIX, identity_id), - &name.to_owned(), - ) - .map_err(contest_err)?; - self.username_cache_mut() - .main - .insert(*identity_id, name.to_owned()); + 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(()) } @@ -406,29 +427,27 @@ impl AppContext { .is_some_and(|seen| seen.contains(&outcome_key(request))) } - /// Record that the outcome banner for `request` was shown. - pub fn mark_username_outcome_seen( + /// Record that the outcome banners for `requests` were shown. + pub fn mark_username_outcomes_seen( &self, identity_id: &Identifier, - request: &UsernameRequest, + requests: &[UsernameRequest], ) -> Result<(), TaskError> { - let mut seen = self - .username_cache() - .seen - .get(identity_id) - .cloned() - .unwrap_or_default(); - if !seen.insert(outcome_key(request)) { + 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(()); } - self.det_kv()? - .put( - DetScope::Global, - &identity_key(SEEN_OUTCOMES_KEY_PREFIX, identity_id), - &seen, - ) - .map_err(contest_err)?; - self.username_cache_mut().seen.insert(*identity_id, seen); + kv.put( + DetScope::Global, + &identity_key(SEEN_OUTCOMES_KEY_PREFIX, identity_id), + &seen, + ) + .map_err(username_err)?; + cache.seen.insert(*identity_id, seen); Ok(()) } @@ -438,9 +457,35 @@ impl AppContext { identity_id: &Identifier, normalized_label: &str, ) -> Result<(), TaskError> { - let mut requests = self.username_requests_for(identity_id); - requests.retain(|r| r.phase.is_pending() || r.normalized_label != normalized_label); - self.store_username_requests(identity_id, requests) + 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(); + for prefix in [ + USERNAME_REQUESTS_KEY_PREFIX, + MAIN_USERNAME_KEY_PREFIX, + SEEN_OUTCOMES_KEY_PREFIX, + ] { + kv.delete(DetScope::Global, &identity_key(prefix, identity_id)) + .map_err(username_err)?; + } + cache.requests.remove(identity_id); + cache.main.remove(identity_id); + cache.seen.remove(identity_id); + Ok(()) } /// Seed a current contest through the persisted shape for backend contract tests. @@ -907,7 +952,9 @@ mod tests { context .store_username_requests(&id, vec![won.clone()]) .expect("store"); - context.mark_username_outcome_seen(&id, &won).expect("seen"); + 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"); @@ -922,6 +969,28 @@ mod tests { 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"); diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index 8a4cd8606..008ad46b6 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -1709,6 +1709,13 @@ impl AppContext { index_remove_identity(&kv, &id)?; self.invalidate_identity_load(*identifier); purge_identity_scope(&kv, &id)?; + if let Err(error) = self.forget_identity_usernames(&kv, identifier) { + tracing::warn!( + identity_id = %identifier, + ?error, + "Removed identity's username records could not be cleared" + ); + } let sidecar_cleanup = self.finish_identity_removal_cleanup(&kv, &id, vault_keys)?; // Mirror removal into the upstream unowned scope; wallet-owned identities are unaffected. if let Ok(backend) = self.wallet_backend() diff --git a/src/model/dpns_usernames.rs b/src/model/dpns_usernames.rs index 07d5dbb6c..c140efbca 100644 --- a/src/model/dpns_usernames.rs +++ b/src/model/dpns_usernames.rs @@ -50,15 +50,58 @@ pub fn username_refresh_due( || (any_pending && elapsed >= duration_ms(pending_refresh_interval(network))) } -/// Whether this device holds a key that can sign username registrations for `identity`. -pub fn can_register_usernames(identity: &QualifiedIdentity) -> bool { - use dash_sdk::dpp::identity::Purpose; +/// 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.identity_public_key.purpose() == Purpose::AUTHENTICATION) + .any(|(_, key)| key_can_sign_documents(&key.identity_public_key, required)) +} + +/// The device-only name the user chose, ignoring a legacy automatic copy of a +/// username (`{name}.dash`), which would otherwise hide the chosen main username. +pub fn user_alias(identity: &QualifiedIdentity) -> Option<&str> { + let alias = identity.alias.as_deref()?.trim(); + let automatic = identity.dpns_names.iter().any(|name| { + alias + .strip_suffix(".dash") + .is_some_and(|stem| stem.eq_ignore_ascii_case(name.name.trim())) + }); + (!alias.is_empty() && !automatic).then_some(alias) } /// Whether a username can be requested right now, and on what terms. @@ -81,6 +124,8 @@ pub enum UsernameAvailability { 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 { @@ -144,12 +189,14 @@ impl ContestSnapshot { } } -/// Decide whether `label` can be requested. +/// 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`. +/// 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>, @@ -160,6 +207,14 @@ pub fn classify_availability( 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, @@ -205,6 +260,8 @@ pub enum RequestPhase { Lost, /// The vote locked the name for everyone. Locked, + /// The vote ended and no one got the name. + NoWinner, } impl RequestPhase { @@ -227,31 +284,35 @@ pub struct RequestTally { pub abstain: u32, } -/// Whether the requester leads the tally. +/// What would happen to the requester if the vote ended now (PF Β§3). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TallyStanding { - /// More votes than any other request and than lock. + /// 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 choice. + /// Level with the strongest other request; ties go to the most recent request. Tied, - /// Another request or lock has more votes. + /// 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 against the strongest other request or lock. + /// The requester's standing under Platform's resolution rules. pub fn standing(&self) -> TallyStanding { - let best_other = self - .others - .iter() - .map(|(_, votes)| *votes) - .chain(std::iter::once(self.lock)) - .max() - .unwrap_or(0); - match self.you.cmp(&best_other) { - std::cmp::Ordering::Greater => TallyStanding::Leading, - std::cmp::Ordering::Equal => TallyStanding::Tied, - std::cmp::Ordering::Less => TallyStanding::Trailing, + 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, + }, } } } @@ -281,14 +342,25 @@ pub struct UsernameRequest { impl UsernameRequest { /// A request just submitted at `now`, before the network reports its contest. - pub fn submitted(label: &str, now: TimestampMillis, durations: ContestDurations) -> Self { + /// + /// `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(now.saturating_add(duration_ms(durations.join))), - end: Some(now.saturating_add(duration_ms(durations.total))), + 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, @@ -316,7 +388,8 @@ pub fn username_request_from_contest( let phase = match contest.winner { Some(ContestWinner::Identity(winner)) if winner == identity_id => RequestPhase::Won, Some(ContestWinner::Locked) => RequestPhase::Locked, - Some(_) => RequestPhase::Lost, + Some(ContestWinner::NoWinner) => RequestPhase::NoWinner, + Some(ContestWinner::Identity(_)) => RequestPhase::Lost, None => { mine?; let start = contest.started_at(); @@ -512,7 +585,7 @@ mod tests { fn available_when_nothing_exists_and_label_is_uncontested() { // USR-TC-010 assert_eq!( - classify_availability("alice2", false, None, 0, durations()), + classify_availability(id(9), "alice2", false, None, 0, durations()), UsernameAvailability::Available ); } @@ -521,11 +594,12 @@ mod tests { fn contested_label_without_contest_needs_vote() { // USR-TC-011 assert_eq!( - classify_availability("alice", false, None, 0, durations()), + classify_availability(id(9), "alice", false, None, 0, durations()), UsernameAvailability::NeedsVote ); assert_eq!( classify_availability( + id(9), "alice", false, Some(&ContestSnapshot::default()), @@ -542,6 +616,7 @@ mod tests { let contest = running(vec![contender(1, 0, 1_000), contender(2, 0, 5_000)]); assert_eq!( classify_availability( + id(9), "alice", false, Some(&contest), @@ -561,6 +636,7 @@ mod tests { let contest = running(vec![contender(1, 0, 1_000)]); assert_eq!( classify_availability( + id(9), "alice", false, Some(&contest), @@ -575,15 +651,115 @@ mod tests { fn awarded_name_is_taken() { // USR-TC-014 assert_eq!( - classify_availability("alice", true, None, 0, durations()), + classify_availability(id(9), "alice", true, None, 0, durations()), UsernameAvailability::Taken ); assert_eq!( - classify_availability("alice2", true, None, 0, durations()), + 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 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. @@ -592,7 +768,7 @@ mod tests { ..Default::default() }; assert_eq!( - classify_availability("alice", false, Some(&contest), 0, durations()), + classify_availability(id(9), "alice", false, Some(&contest), 0, durations()), UsernameAvailability::Locked ); } @@ -679,6 +855,10 @@ mod tests { phase(ContestWinner::Locked), Some((RequestPhase::Locked, Some(7_000))) ); + assert_eq!( + phase(ContestWinner::NoWinner), + Some((RequestPhase::NoWinner, Some(7_000))) + ); } #[test] @@ -689,9 +869,23 @@ mod tests { lock, abstain: 0, }; - assert_eq!(tally(0, vec![], 0).standing(), TallyStanding::Tied); + // 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![1], 6).standing(), TallyStanding::Trailing); + 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 { diff --git a/src/ui/components/address_input.rs b/src/ui/components/address_input.rs index cb2d53502..4e01dc36e 100644 --- a/src/ui/components/address_input.rs +++ b/src/ui/components/address_input.rs @@ -604,6 +604,7 @@ impl AddressInput { for qi in identities { let id = qi.identity.id(); let id_str = id.to_string(Encoding::Base58); + // TODO(usernames): use AppContext::main_username once this component can reach the context. let dpns_name = qi.dpns_names.first().map(|n| n.name.clone()); let name_label = dpns_name.clone().or_else(|| qi.alias.clone()); self.all_entries.push(AddressEntry { diff --git a/src/ui/components/global_nav_switcher.rs b/src/ui/components/global_nav_switcher.rs index c6cd6eb25..a94b668e5 100644 --- a/src/ui/components/global_nav_switcher.rs +++ b/src/ui/components/global_nav_switcher.rs @@ -125,7 +125,7 @@ fn gather_wallets(app_context: &Arc) -> Vec<(WalletSeedHash, String) fn identity_label(app_context: &AppContext, qi: &QualifiedIdentity) -> String { let dpns = app_context.main_username(qi); display_label( - qi.alias.as_deref(), + crate::model::dpns_usernames::user_alias(qi), None, dpns.as_deref(), &qi.identity.id().to_string(Encoding::Base58), @@ -517,18 +517,26 @@ fn render_app_global_identity_pill( if let PillConsumption::Unwired { tooltip } = consumption { // Subdued, non-interactive: the value shows dimmed with no caret. - IdentityPill::new(active_qi.alias.as_deref(), dpns.as_deref(), &id_b58) - .with_avatar(kind, monogram_initial(&label)) - .with_mode(BreadcrumbPillMode::Subdued) - .with_tooltip(tooltip.clone()) - .show(ui); + IdentityPill::new( + crate::model::dpns_usernames::user_alias(active_qi), + dpns.as_deref(), + &id_b58, + ) + .with_avatar(kind, monogram_initial(&label)) + .with_mode(BreadcrumbPillMode::Subdued) + .with_tooltip(tooltip.clone()) + .show(ui); return; } - let resp = IdentityPill::new(active_qi.alias.as_deref(), dpns.as_deref(), &id_b58) - .with_avatar(kind, monogram_initial(&label)) - .with_tooltip(tt_identity(&data.active_wallet_name)) - .show(ui); + let resp = IdentityPill::new( + crate::model::dpns_usernames::user_alias(active_qi), + dpns.as_deref(), + &id_b58, + ) + .with_avatar(kind, monogram_initial(&label)) + .with_tooltip(tt_identity(&data.active_wallet_name)) + .show(ui); if let Some(anchor) = resp.response.clone() { let popup_id = ui.make_persistent_id("global_nav_identity_switcher"); diff --git a/src/ui/components/pill.rs b/src/ui/components/pill.rs index 1517a50ba..cfffe5bf1 100644 --- a/src/ui/components/pill.rs +++ b/src/ui/components/pill.rs @@ -93,6 +93,7 @@ mod tests { total: std::time::Duration::ZERO, join: std::time::Duration::ZERO, }, + None, ); request.end = end; request diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index 9045dd74f..7d1359232 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -58,10 +58,9 @@ 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 username request status was last refreshed (Unix ms). + /// 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, - /// A username refresh is in flight. - usernames_refreshing: bool, /// 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 @@ -116,9 +115,6 @@ 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); - if self.usernames_refreshing { - return AppAction::None; - } let network = self.app_context.network; let any_pending = self.app_context.any_pending_username_request(); let now = crate::utils::time::now_ms(); @@ -137,7 +133,6 @@ impl IdentityHubScreen { return AppAction::None; } self.usernames_refreshed_at = Some(now); - self.usernames_refreshing = true; AppAction::BackendTask(BackendTask::IdentityTask( IdentityTask::RefreshMyUsernameRequests, )) @@ -155,7 +150,6 @@ impl IdentityHubScreen { home_state: HomeState::default(), settings_tab: SettingsTab::new(), usernames_refreshed_at: None, - usernames_refreshing: false, usernames_arriving: true, pending_unloads: BTreeSet::new(), contacts_state: super::contacts::ContactsState::default(), @@ -596,10 +590,7 @@ impl ScreenLike for IdentityHubScreen { action } - fn display_message(&mut self, _message: &str, message_type: MessageType) { - if matches!(message_type, MessageType::Error | MessageType::Warning) { - self.usernames_refreshing = false; - } + fn display_message(&mut self, _message: &str, _message_type: MessageType) { // AppState sets the global banner centrally; the hub itself owns no // in-flight task banners. Sub-tab content overrides its own lifecycle. } @@ -608,8 +599,8 @@ impl ScreenLike for IdentityHubScreen { if matches!( result, BackendTaskSuccessResult::MyUsernameRequestsRefreshed + | BackendTaskSuccessResult::UsernamePreferencesSaved ) { - self.usernames_refreshing = false; return; } // Feed an async DashPay profile load back into the cache the tabs read. @@ -727,7 +718,6 @@ impl ScreenLike for IdentityHubScreen { // 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 { .. }) { - self.usernames_refreshing = false; return true; } if self.handle_contact_request_error(error) { diff --git a/src/ui/identity/identity_hero_card.rs b/src/ui/identity/identity_hero_card.rs index 11b479da8..802c04dd9 100644 --- a/src/ui/identity/identity_hero_card.rs +++ b/src/ui/identity/identity_hero_card.rs @@ -732,6 +732,7 @@ mod tests { total: std::time::Duration::ZERO, join: std::time::Duration::ZERO, }, + None, ); request.label = name.to_string(); request.end = None; diff --git a/src/ui/identity/picker.rs b/src/ui/identity/picker.rs index 697b48a5c..216f27bdc 100644 --- a/src/ui/identity/picker.rs +++ b/src/ui/identity/picker.rs @@ -179,7 +179,7 @@ fn build_card(app_context: &AppContext, identity: &QualifiedIdentity) -> Identit ); // Heading priority: local alias β†’ DPNS β†’ shortened id. - if let Some(alias) = identity.alias.as_deref().filter(|s| !s.trim().is_empty()) { + if let Some(alias) = crate::model::dpns_usernames::user_alias(identity) { card = card.with_display_name(alias); } if let Some(dpns) = app_context.main_username(identity) { diff --git a/src/ui/identity/register_dpns_name_screen.rs b/src/ui/identity/register_dpns_name_screen.rs index b56651fa0..12a7061e4 100644 --- a/src/ui/identity/register_dpns_name_screen.rs +++ b/src/ui/identity/register_dpns_name_screen.rs @@ -11,7 +11,9 @@ use crate::model::dpns::{ DpnsNameValidationResult, DpnsRegistrationOutcome, contest_durations, suggest_uncontested, validate_dpns_name, }; -use crate::model::dpns_usernames::{UsernameAvailability, can_register_usernames}; +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; @@ -95,6 +97,9 @@ pub struct RegisterDpnsNameScreen { pub source: RegisterDpnsNameSource, /// Full-window block while the registration runs; torn down on every terminal result. op_overlay: Option, + /// 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 { @@ -113,6 +118,7 @@ impl RegisterDpnsNameScreen { completed_fee_result: None, source, op_overlay: None, + check_in_flight: None, }; screen.reload_identity(); screen @@ -162,7 +168,7 @@ impl RegisterDpnsNameScreen { .as_ref() .map(|qi| { display_label( - qi.alias.as_deref(), + crate::model::dpns_usernames::user_alias(qi), None, self.app_context.main_username(qi).as_deref(), &qi.identity.id().to_string(Encoding::Base58), @@ -217,8 +223,8 @@ impl RegisterDpnsNameScreen { return AppAction::None; }; let remaining = AVAILABILITY_DEBOUNCE.saturating_sub(since.elapsed()); - if !remaining.is_zero() { - ctx.request_repaint_after(remaining); + 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(); @@ -226,12 +232,20 @@ impl RegisterDpnsNameScreen { } 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; + }; self.availability = Availability::Row { label: label.clone(), row: AvailabilityRow::Checking, }; + self.check_in_flight = Some(label.clone()); AppAction::BackendTask(BackendTask::IdentityTask( - IdentityTask::CheckUsernameAvailability { label }, + IdentityTask::CheckUsernameAvailability { identity_id, label }, )) } @@ -294,6 +308,12 @@ impl RegisterDpnsNameScreen { self.raise_progress_overlay(ctx); } + /// 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) + } + /// Test seam: type `label` as if the user had entered it. #[doc(hidden)] pub fn type_label_for_test(&mut self, label: &str) { @@ -696,6 +716,12 @@ impl ScreenLike for RegisterDpnsNameScreen { fn display_message(&mut self, _message: &str, message_type: MessageType) { // Banners are shown by AppState; this only unblocks the flow after a failure. if matches!(message_type, MessageType::Error | MessageType::Warning) { + if self.check_in_flight.take().is_some() + && let Availability::Row { row, .. } = &mut self.availability + && *row == AvailabilityRow::Checking + { + *row = AvailabilityRow::CantCheck; + } self.op_overlay.take_and_clear(); if self.step == Step::Submitting { self.step = Step::Confirm; @@ -705,9 +731,18 @@ impl ScreenLike for RegisterDpnsNameScreen { fn display_task_error(&mut self, error: &TaskError) -> bool { match error { + TaskError::UsernameAvailabilityCheckFailed { .. } if self.step == Step::Submitting => { + // The pay-time re-check failed before anything was spent: unblock + // the confirm step and let the banner ask the user to retry. + self.op_overlay.take_and_clear(); + self.step = Step::Confirm; + false + } TaskError::UsernameAvailabilityCheckFailed { .. } => { - if let Availability::Row { row, .. } = &mut self.availability + let failed = self.check_in_flight.take(); + if let Availability::Row { label, row } = &mut self.availability && *row == AvailabilityRow::Checking + && failed.as_ref() == Some(label) { *row = AvailabilityRow::CantCheck; } @@ -741,6 +776,9 @@ impl ScreenLike for RegisterDpnsNameScreen { 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 { @@ -803,7 +841,10 @@ impl ScreenLike for RegisterDpnsNameScreen { ); return; }; - if !can_register_usernames(identity) { + if !can_register_usernames( + identity, + dpns_signing_requirement(&self.app_context.dpns_contract), + ) { status_line( ui, Tone::Negative, diff --git a/src/ui/identity/username_copy.rs b/src/ui/identity/username_copy.rs index 2fd7639e9..765409c00 100644 --- a/src/ui/identity/username_copy.rs +++ b/src/ui/identity/username_copy.rs @@ -133,6 +133,12 @@ pub fn availability_line(name: &str, row: &AvailabilityRow) -> (Tone, String) { 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." + ), + ), }, } } @@ -207,18 +213,22 @@ pub fn phase_label(phase: RequestPhase) -> &'static str { RequestPhase::Won => "Registered", RequestPhase::Lost => "Went to someone else", RequestPhase::Locked => "Locked for good", + RequestPhase::NoWinner => "No one got it", } } /// Second sentence of the Home request card. pub fn standing_line(standing: TallyStanding, others: usize) -> &'static str { - if others == 0 { - "No one else has asked so far." - } else { - match standing { - TallyStanding::Leading => "You're leading right now.", - TallyStanding::Tied | TallyStanding::Trailing => "Another request is leading.", + 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.", } } @@ -353,13 +363,21 @@ mod tests { "You're leading right now." ); assert_eq!( - standing_line(TallyStanding::Tied, 0), + 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] diff --git a/src/ui/identity/username_notices.rs b/src/ui/identity/username_notices.rs index 97c7b85be..19baaf807 100644 --- a/src/ui/identity/username_notices.rs +++ b/src/ui/identity/username_notices.rs @@ -9,12 +9,15 @@ 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::{RegisterDpnsNameSource, status_line}; +use crate::ui::identity::register_dpns_name_screen::status_line; use crate::ui::identity::username_copy::{Tone, format_date, 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. @@ -33,6 +36,9 @@ pub fn outcome_banner_text(request: &UsernameRequest) -> Option { 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 => None, } } @@ -60,6 +66,9 @@ pub fn render( .data(|data| data.get_temp(session_id)) .unwrap_or_default(); let mut session_changed = false; + // Outcomes shown for the first time this frame; recorded as seen through a + // backend task so each banner appears once, across restarts too. + let mut newly_shown: Vec = Vec::new(); for request in &requests { let Some(text) = outcome_banner_text(request) else { @@ -70,14 +79,7 @@ pub fn render( if app_context.username_outcome_seen(&identity_id, request) { continue; } - if let Err(error) = app_context.mark_username_outcome_seen(&identity_id, request) { - tracing::debug!( - ?error, - "Username outcome banner could not be marked as seen" - ); - } - session.insert(key.clone()); - session_changed = true; + newly_shown.push(request.clone()); } let tone = if request.phase == RequestPhase::Won { Tone::Positive @@ -87,21 +89,27 @@ pub fn render( notice_frame(ui, dark_mode, |ui| { ui.horizontal_wrapped(|ui| { status_line(ui, tone, &text, dark_mode); - if request.phase == RequestPhase::Lost + if matches!(request.phase, RequestPhase::Lost | RequestPhase::NoWinner) && ui.button("Choose another username").clicked() { - action = AppAction::AddScreen( - ScreenType::RegisterDpnsName(RegisterDpnsNameSource::Identities) - .create_screen(app_context), - ); + action = register_action_for(app_context, identity_id); } if ui.button("Dismiss").clicked() { session.remove(&key); session_changed = true; + if newly_shown.last() == Some(request) { + newly_shown.pop(); + action = mark_seen_action(identity_id, vec![request.clone()]); + } } }); }); } + if !newly_shown.is_empty() && matches!(action, AppAction::None) { + session.extend(newly_shown.iter().map(|r| banner_key(&identity_id, r))); + session_changed = true; + action = mark_seen_action(identity_id, newly_shown); + } if session_changed { ui.ctx() .data_mut(|data| data.insert_temp(session_id, session)); @@ -137,6 +145,15 @@ pub fn render( 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)) @@ -161,6 +178,7 @@ mod tests { total: Duration::ZERO, join: Duration::ZERO, }, + None, ); assert!(outcome_banner_text(&request).is_none()); request.phase = RequestPhase::Won; diff --git a/src/ui/identity/username_request_screen.rs b/src/ui/identity/username_request_screen.rs index d529a6dd6..214ba48af 100644 --- a/src/ui/identity/username_request_screen.rs +++ b/src/ui/identity/username_request_screen.rs @@ -17,12 +17,13 @@ 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::{display_label, shorten_id}; -use crate::ui::identity::register_dpns_name_screen::{RegisterDpnsNameSource, status_line}; +use crate::ui::identity::register_dpns_name_screen::status_line; use crate::ui::identity::username_copy::{ Tone, format_date, 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::{MessageType, RootScreenType, ScreenLike, ScreenType}; +use crate::ui::{MessageType, RootScreenType, ScreenLike}; /// Pushed page showing the status of one of an identity's username requests. pub struct UsernameRequestScreen { @@ -80,7 +81,7 @@ impl UsernameRequestScreen { .find(|qi| qi.identity.id() == self.identity_id); match identity { Some(qi) => display_label( - qi.alias.as_deref(), + crate::model::dpns_usernames::user_alias(&qi), None, self.app_context.main_username(&qi).as_deref(), &qi.identity.id().to_string(Encoding::Base58), @@ -145,6 +146,7 @@ impl UsernameRequestScreen { RequestPhase::Won => (Tone::Positive, "Result: The name is yours."), RequestPhase::Lost => (Tone::Negative, "Result: The name went to someone else."), RequestPhase::Locked => (Tone::Negative, "Result: The name is locked for good."), + RequestPhase::NoWinner => (Tone::Negative, "Result: No one got the name."), }; status_line(ui, tone, result, dark_mode); } @@ -154,7 +156,12 @@ impl UsernameRequestScreen { let standing = match tally.standing() { TallyStanding::Leading => "Leading", TallyStanding::Tied => "Tied", - TallyStanding::Trailing => "", + TallyStanding::Trailing | TallyStanding::LockAhead => "", + }; + let lock_standing = if tally.standing() == TallyStanding::LockAhead { + "Leading" + } else { + "" }; egui::Grid::new("username_request_tally") .num_columns(3) @@ -174,7 +181,7 @@ impl UsernameRequestScreen { ui.end_row(); } ui.label("Lock, so no one gets it"); - ui.label(""); + ui.label(lock_standing); ui.label(tally.lock.to_string()); ui.end_row(); ui.label("Abstain"); @@ -250,10 +257,7 @@ impl UsernameRequestScreen { if ComponentStyles::add_secondary_button(ui, "Get a username without a vote", dark_mode) .clicked() { - action = AppAction::AddScreen( - ScreenType::RegisterDpnsName(RegisterDpnsNameSource::Identities) - .create_screen(&self.app_context), - ); + action = register_action_for(&self.app_context, self.identity_id); } if self.can_vote && ui.link("Your nodes can vote on this name").clicked() { // TODO(stream-v): open Masternodes β–Έ Votes filtered to this name once Stream V exposes the route. diff --git a/src/ui/identity/usernames_card.rs b/src/ui/identity/usernames_card.rs index f505130a9..6bc8ec0e9 100644 --- a/src/ui/identity/usernames_card.rs +++ b/src/ui/identity/usernames_card.rs @@ -7,8 +7,13 @@ 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_usernames::{RequestPhase, UsernameRequest, can_register_usernames}; +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; @@ -36,36 +41,48 @@ pub enum UsernameRow { 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 { - let names: Vec<_> = identity + // Registered names, plus names won in a vote that the identity's stored + // names do not list yet (they are re-read in the background). + 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) { + 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(|n| n.name == main)) + .and_then(|main| names.iter().position(|(name, _)| name == main)) .unwrap_or(0); - for (index, name) in names + 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.name.clone(), + name: name.clone(), is_main: index == main_index, show_main_badge, - acquired_at: name.acquired_at, + acquired_at: *acquired_at, }); } - let owned = |label: &str| names.iter().any(|n| n.name == label); + let owned = |label: &str| names.iter().any(|(name, _)| same_name(name, label)); rows.extend( requests .iter() @@ -76,7 +93,12 @@ pub fn username_rows( rows.extend( requests .iter() - .filter(|r| matches!(r.phase, RequestPhase::Lost | RequestPhase::Locked)) + .filter(|r| { + matches!( + r.phase, + RequestPhase::Lost | RequestPhase::Locked | RequestPhase::NoWinner + ) + }) .cloned() .map(UsernameRow::Outcome), ); @@ -103,7 +125,10 @@ impl UsernamesCard { 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); + let can_register = can_register_usernames( + identity, + dpns_signing_requirement(&app_context.dpns_contract), + ); if rows.is_empty() { ui.label( @@ -144,14 +169,12 @@ impl UsernamesCard { ui.close(); } if !is_main && ui.button("Show as main").clicked() { - if let Err(error) = app_context.set_main_username(&identity_id, &name) { - MessageBanner::set_global( - ui.ctx(), - "This choice could not be saved on your device. Try again in a moment.", - MessageType::Error, - ) - .with_details(error); - } + action = AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::SetMainUsername { + identity_id, + name: name.clone(), + }, + )); ui.close(); } }) @@ -176,7 +199,7 @@ impl UsernamesCard { }); let detail = match (request.phase, request.join_end, request.end) { (RequestPhase::Joinable, Some(join_end), _) => format!( - "Others can ask for this name until {}. Voting starts after that.", + "Others can ask for this name until {}. Masternodes can already vote.", format_date(join_end) ), (_, _, Some(end)) => { @@ -202,6 +225,9 @@ impl UsernamesCard { "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() + } _ => request.decided_at.map_or_else( || "The community vote ended.".to_owned(), |at| format!("The community vote ended on {}.", format_date(at)), @@ -213,21 +239,18 @@ impl UsernamesCard { .color(DashColors::text_secondary(dark_mode)), ); ui.horizontal(|ui| { - if request.phase == RequestPhase::Lost + 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() - && let Err(error) = app_context - .dismiss_username_request(&identity_id, &request.normalized_label) - { - MessageBanner::set_global( - ui.ctx(), - "This row could not be dismissed. Try again in a moment.", - MessageType::Error, - ) - .with_details(error); + if ui.button("Dismiss").clicked() { + action = AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::DismissUsernameRequest { + identity_id, + normalized_label: request.normalized_label.clone(), + }, + )); } }); } @@ -291,13 +314,21 @@ impl UsernamesCard { } } -fn register_action(app_context: &Arc, identity: &QualifiedIdentity) -> AppAction { - app_context.set_selected_identity(Some(identity.identity.id())); +/// 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, @@ -387,6 +418,7 @@ mod tests { total: Duration::ZERO, join: Duration::ZERO, }, + None, ); request.phase = phase; request diff --git a/tests/kittest/identity_usernames.rs b/tests/kittest/identity_usernames.rs index ebca08851..ab6faddda 100644 --- a/tests/kittest/identity_usernames.rs +++ b/tests/kittest/identity_usernames.rs @@ -1,8 +1,10 @@ -//! Kittest coverage for identity usernames (USR-TC-018, 031–038). +//! 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::backend_task::BackendTaskSuccessResult; +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; @@ -25,6 +27,7 @@ use dash_evo_tool::ui::identity::register_dpns_name_screen::{ }; 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, @@ -218,6 +221,15 @@ fn confirm_step_shows_fees_low_balance_and_sync_gate() { .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 @@ -269,24 +281,48 @@ fn request(label: &str, phase: RequestPhase) -> UsernameRequest { total: std::time::Duration::from_secs(14 * 86_400), join: std::time::Duration::from_secs(7 * 86_400), }, + None, ); request.phase = phase; request } -fn mount_settings(app_context: Arc) -> Harness<'static, SettingsTab> { +/// 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, tab: &mut SettingsTab| { - tab.render(ui, &app_context, &mut ProfileCache::default()); + 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(), + (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() { @@ -480,28 +516,61 @@ fn request_status_page_links_voters() { }); } -fn mount_home(app_context: Arc) -> Harness<'static, (HomeState, ProfileCache)> { +/// 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 (HomeState, ProfileCache)| { - let _ = home::render(ui, &app_context, &state.0, &mut state.1); + 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()), + (HomeState::default(), ProfileCache::default(), None), ); harness.run(); harness } -/// USR-TC-021: "Show as main" changes the shown name locally, with no backend task. +/// 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", "b-name"], 0, true); - app_context - .set_main_username(&id, "b-name") - .expect("set main"); + 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") @@ -523,7 +592,8 @@ fn show_as_main_changes_the_hero_name() { harness .query_all_by_label_contains("a-name") .next() - .is_none() + .is_none(), + "the legacy automatic alias must not hide the chosen main name" ); }); } @@ -571,16 +641,206 @@ fn home_shows_pending_request_header_and_card() { #[test] fn outcome_banner_shows_once() { with_isolated_data_dir(|| { - let (_rt, app_context) = fresh_app_context(); + 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 first = mount_home(app_context.clone()); + 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(); + screen.begin_registration_for_test(&ctx); + assert!( + ProgressOverlay::has_global(&ctx), + "precondition: overlay up" + ); + let handled = screen.display_task_error(&TaskError::UsernameAvailabilityCheckFailed { + source: Box::new(dash_sdk::Error::Generic("timeout".into())), + }); + 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(); + seed_username_identity(&app_context, 0x36, "Alex", &[], 0, 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(); + harness.state_mut().refresh_on_arrival(); + harness.run(); + assert!(harness.state().is_confirming_for_test()); + assert!( + harness + .query_by_label_contains("and request @nova") + .is_some() + ); + }); +} From db87d63a7275947b86631674821c1804b08e9436 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:51:06 +0000 Subject: [PATCH 078/194] feat(masternodes): node votes and "Vote with this node" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The node detail replaces its plain "DPNS Voting" route with "This node's votes" (VOTE-FR-076): every open contest with the node's proved choice, changes left counted on this device, and time left, plus the node's masternode-list status. "Vote with this node" opens Votes β–Έ To decide with that node as the session's node set and no staged decision carried over; it is disabled while the node has no voting key. The node-set chip now also shows when no contest is open. Co-Authored-By: Claude Opus 5.5 --- src/context/dpns_vote_attention.rs | 97 +++++++++++++++++++++- src/model/dpns_voting/operator.rs | 15 ++++ src/ui/dpns/dpns_contested_names_screen.rs | 62 ++++++++------ src/ui/masternodes/detail_screen.rs | 93 +++++++++++++++++++-- src/ui/masternodes/list_screen.rs | 6 ++ tests/kittest/masternode_tab.rs | 36 +++++--- 6 files changed, 263 insertions(+), 46 deletions(-) diff --git a/src/context/dpns_vote_attention.rs b/src/context/dpns_vote_attention.rs index 21744679c..c32898d82 100644 --- a/src/context/dpns_vote_attention.rs +++ b/src/context/dpns_vote_attention.rs @@ -7,8 +7,8 @@ use super::AppContext; use crate::backend_task::error::TaskError; use crate::model::dpns_voting::operator::{ - AttentionSummary, ChangesLeft, ContestAttention, ListMembership, VotingNode, VotingNodeKind, - changes_left, contest_needs_decision, + AttentionSummary, ChangesLeft, ContestAttention, ListMembership, NodeVoteRow, VotingNode, + VotingNodeKind, changes_left, contest_needs_decision, }; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOutcome, DpnsVotePollAvailability, @@ -18,6 +18,7 @@ use crate::model::dpns_voting::{ use crate::model::qualified_identity::IdentityType; 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; @@ -175,6 +176,58 @@ impl AppContext { .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, @@ -332,6 +385,46 @@ mod tests { assert_eq!(unresolved_target_count(&[]), 0); } + /// 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" + ); + } + #[test] fn membership_is_unknown_until_the_list_is_available() { let temp_dir = tempfile::tempdir().expect("tempdir"); diff --git a/src/model/dpns_voting/operator.rs b/src/model/dpns_voting/operator.rs index 6c7bdff1b..d8529e930 100644 --- a/src/model/dpns_voting/operator.rs +++ b/src/model/dpns_voting/operator.rs @@ -152,6 +152,21 @@ pub fn node_exclusion(node: &VotingNode) -> Option { } } +/// 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 { diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 9dc97424d..9c10626c6 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -890,41 +890,50 @@ impl DPNSScreen { .sum() } + /// 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 { + match self.app_context.save_dpns_node_set(&self.node_set) { + Ok(()) => { + self.app_context.recompute_dpns_vote_attention(); + } + Err(error) => { + MessageBanner::set_global(ui.ctx(), error.to_string(), MessageType::Error) + .with_details(&error); + } + } + } + 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| { - if !self.voting_nodes.is_empty() { - let picked = node_set_picker::show( - ui, - &self.node_set, - &self.resolved_nodes, - &self.voting_nodes, - ); - if picked.save_default { - match self.app_context.save_dpns_node_set(&self.node_set) { - Ok(()) => { - self.app_context.recompute_dpns_vote_attention(); - } - Err(error) => { - MessageBanner::set_global( - ui.ctx(), - error.to_string(), - MessageType::Error, - ) - .with_details(&error); - } - } - } - if let Some(node_set) = picked.changed { - self.apply_node_set(node_set); - } - } + 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) @@ -2640,6 +2649,7 @@ impl ScreenLike for DPNSScreen { } 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); diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index cd585dc19..93c7e09fa 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -22,6 +22,7 @@ use crate::backend_task::identity::{IdentityInputToLoad, IdentityLoadMode, Ident use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; use crate::context::AppContext; use crate::context::identity_load_registry::{IdentityLoadPhase, IdentityLoadToken}; +use crate::model::dpns_voting::operator::{ListMembership, NodeVoteRow, 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}; @@ -31,6 +32,7 @@ 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::{changes_left_label, ends_in_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; @@ -43,6 +45,7 @@ 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; @@ -94,6 +97,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 { @@ -123,6 +128,9 @@ pub struct MasternodeDetailView { /// 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, read when the view is built; + /// `None` when they could not be read. + node_votes: Option>, } #[cfg(test)] @@ -181,6 +189,24 @@ impl MasternodeDetailView { } } +/// The choice cell of a node vote row. +fn node_vote_choice_label(row: &NodeVoteRow) -> String { + use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; + match (row.state_known, row.choice) { + (false, _) => "Vote state unavailable".to_owned(), + (true, None) => "Not voted yet".to_owned(), + (true, Some(ResourceVoteChoice::Lock)) => "Lock".to_owned(), + (true, Some(ResourceVoteChoice::Abstain)) => "Abstain".to_owned(), + (true, Some(ResourceVoteChoice::TowardsIdentity(id))) => match &row.contender_name { + Some(name) => format!("Vote for {name}"), + None => format!( + "Vote for {id}", + id = shorten_id(&id.to_string(Encoding::Base58)) + ), + }, + } +} + impl MasternodeDetailView { pub(crate) fn accepts_recovery_result( &self, @@ -194,6 +220,7 @@ impl MasternodeDetailView { let node_id_hex_full = identity.identity.id().to_string(Encoding::Hex); let node_id_short = shorten_id(&node_id_hex_full); let key_presence = identity.masternode_key_presence(); + let identity_id = identity.identity.id(); let recovery = LegacyRecoveryState::new(app_context, identity.identity.id()); Self { app_context: app_context.clone(), @@ -205,6 +232,12 @@ impl MasternodeDetailView { 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(), } } @@ -367,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) { @@ -810,12 +843,56 @@ impl MasternodeDetailView { AppAction::AddScreen(Screen::KeyInfoScreen(screen)) } - fn render_dpns_section(&mut self, ui: &mut Ui, _dark_mode: bool) -> Option { - ComponentStyles::add_secondary_button(ui, "DPNS Voting", ui.visuals().dark_mode) - .clicked() - .then(|| { - AppAction::SetMainScreen(crate::ui::RootScreenType::RootScreenDPNSActiveContests) - }) + /// `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 the masternode list. Its votes don't count.", + ListMembership::Unknown => "Masternode list membership unknown.", + }; + ui.label(RichText::new(membership).color(DashColors::text_secondary(dark_mode))); + match &self.node_votes { + None => { + ui.label("This node's votes could not be read. Refresh to try again."); + } + Some(rows) if rows.is_empty() => { + ui.label("There are no open name contests right now."); + } + 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.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 { diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index ef1e97d00..bc6eddb3b 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -538,6 +538,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 diff --git a/tests/kittest/masternode_tab.rs b/tests/kittest/masternode_tab.rs index 153c6a72a..f1f29189c 100644 --- a/tests/kittest/masternode_tab.rs +++ b/tests/kittest/masternode_tab.rs @@ -713,10 +713,11 @@ fn detail_view_opens_from_card_with_sections_and_back() { }); } -/// The detail screen has one plain route to DPNS voting and no inline voting -/// controls or node-prefilter state. +/// 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 detail_dpns_voting_button_opens_active_contests() { +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(); @@ -724,26 +725,41 @@ fn detail_dpns_voting_button_opens_active_contests() { 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); - - assert!(harness.query_by_label("DPNS Voting").is_some()); + assert!(harness.query_by_label("This node's votes").is_some()); assert!( harness - .query_by_label_contains("DPNS name contests to vote on") - .is_none() + .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!( + keyless.accesskit_node().is_disabled(), + "a key-less node cannot vote" ); - assert!(harness.query_by_label("Add voting key").is_some()); - assert!(harness.query_by_label_contains("Review ").is_none()); - harness.get_by_label("DPNS Voting").click(); + harness.get_by_label("β€Ή All masternodes").click(); + harness.run_steps(3); + 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_contains("Vote with: Custom Β· 1 node") + .is_some(), + "the node-set chip names that single node" + ); }); } From 6aba4a5abca0638d14bfd5fc81a6d41226af9571 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:55:32 +0000 Subject: [PATCH 079/194] feat(dpns): group scheduled votes by decision MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Scheduled view lists one row per name Γ— choice Γ— time instead of one row per node (VOTE-FR-088). Each group keeps its relative-time label and expands to "{n} nodes" with each node's status, guidance and the Remove / Edit / Cast now actions; groups with a failure or a missed schedule open by default. Co-Authored-By: Claude Opus 5.5 --- src/ui/dpns/copy.rs | 8 + src/ui/dpns/dpns_contested_names_screen.rs | 385 +++++++++++---------- src/ui/state/dpns_vote_operations.rs | 75 ++++ 3 files changed, 284 insertions(+), 184 deletions(-) diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index c896941d4..24641062c 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -267,6 +267,14 @@ pub fn needs_attention_line(attention: NeedsAttention) -> String { format!("Needs attention: {parts}.", parts = parts.join(" Β· ")) } +/// 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) { diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 9c10626c6..5e69031cd 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -49,7 +49,7 @@ use crate::ui::dpns::copy::tray_label; use crate::ui::dpns::copy::{ 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, - skipped_header, skipped_reason_line, + scheduled_nodes_label, skipped_header, skipped_reason_line, }; use crate::ui::dpns::node_set_picker; use crate::ui::dpns::progress_drawer; @@ -58,7 +58,9 @@ use crate::ui::state::dpns_vote_cards::{ CantVoteReason, CardPlacement, NodeContestState, NodeContestStatus, SHORTCUT_HELP, Shortcut, VoteCard, move_focus, shortcut_for, sort_by_time_left, }; -use crate::ui::state::dpns_vote_operations::{DpnsVoteOperationSnapshot, ScheduledDpnsVoteRow}; +use crate::ui::state::dpns_vote_operations::{ + DpnsVoteOperationSnapshot, ScheduledDpnsVoteRow, group_scheduled_rows, +}; use crate::ui::state::dpns_vote_state::DpnsVoteStateSnapshot; use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; use crate::ui::{BackendTaskSuccessResult, MessageType, ScreenLike}; @@ -1538,199 +1540,214 @@ impl DPNSScreen { } /// Show the Scheduled Votes table + /// 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. fn render_table_scheduled_votes(&mut self, ui: &mut Ui) -> AppAction { let mut action = AppAction::None; - let mut show_cast_overlay = false; - let mut sorted_votes = { - let guard = self.scheduled_votes.lock_recover(); - guard.clone() - }; - sorted_votes.sort_by(|a, b| { - let order = a.vote.contested_name.cmp(&b.vote.contested_name); - if self.sort_order == SortOrder::Descending { - order.reverse() - } else { - order - } - }); - + let mut show_cast_progress = false; + let rows = self.scheduled_votes.lock_recover().clone(); + let mut groups = group_scheduled_rows(rows); + if self.sort_order == SortOrder::Descending { + groups.reverse(); + } + let now = Utc::now().timestamp_millis().max(0) as u64; 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::initial(280.0).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 scheduled_row in &sorted_votes { - let vote = &scheduled_row.vote; - let pending_key = DpnsScheduledVoteKey { - network: scheduled_row - .journal_target - .as_ref() - .map_or(self.app_context.network(), |(_, key)| key.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), Utc::now().timestamp_millis().max(0) as u64); - let failure_guidance = if missed { Some(MISSED_SCHEDULE_GUIDANCE) } else { scheduled_failure_guidance(scheduled_row.status, scheduled_row.failure) }; - body.row(if failure_guidance.is_some() { 95.0 } else { 25.0 }, |mut row| { - row.col(|ui| { - ui.add(Label::new(format!( - "{name}.dash", - name = vote.contested_name - ))); - }); - 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(|| short_identifier(vote.voter_id)); - ui.add(Label::new(voter)); - }); - row.col(|ui| { - let candidate_name = - self.candidate_name(&vote.contested_name, vote.choice); - ui.add(Label::new(vote_choice_label(vote.choice, candidate_name))); - }); - row.col(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - let preset = scheduled_row.journal_target.as_ref().and_then(|(_, key)| { - self.relative_schedule_labels - .get(&(key.clone(), vote.unix_timestamp)) - }); - if let Some(preset) = preset { - ui.label( - RichText::new(relative_schedule_label( - *preset, - &utc_minute(vote.unix_timestamp), - )) - .color(DashColors::text_primary(dark_mode)), - ); - } else if let LocalResult::Single(dt) = - Utc.timestamp_millis_opt(vote.unix_timestamp as i64) - { - ui.label( - RichText::new(timestamp_with_relative(dt)) - .color(DashColors::text_primary(dark_mode)), - ); - } else { - ui.label( - RichText::new("Invalid timestamp") - .color(DashColors::text_primary(dark_mode)), - ); - } - }); - row.col(|ui| { - let dark_mode = ui.style().visuals.dark_mode; - ui.vertical(|ui| { - ui.label(RichText::new(if missed { "Missed automatic vote" } else { target_outcome_label(scheduled_row.status, scheduled_row.failure) }) - .color(DashColors::text_primary(dark_mode))); - if let Some(guidance) = failure_guidance { - ui.add(Label::new(guidance).wrap()); - } - }); - }); - row.col(|ui| { - let remove_enabled = - scheduled_vote_remove_enabled(scheduled_row.status); - if ui - .add_enabled(remove_enabled, 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), - ), - ); - } - if ui.add_enabled(scheduled_row.status == DpnsVoteTargetStatus::Scheduled - && !self.pending_scheduled_actions.contains_key(&pending_key), Button::new("Edit")) - .disabled_tooltip("Only scheduled votes that have not started can be edited.") - .clicked() { - self.open_schedule_editor(scheduled_row); - } - let cast_button_enabled = scheduled_vote_cast_enabled( - scheduled_row.status, - self.pending_scheduled_actions.contains_key(&pending_key), - ) && self.voting_identities.iter().any(|identity| identity.identity.id() == vote.voter_id); - if ui - .add_enabled(cast_button_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) = self - .voting_identities - .iter() - .find(|identity| { - identity.identity.id() == vote.voter_id - }) - .cloned() - { - let task = BackendTask::ContestedResourceTask( - ContestedResourceTask::CastScheduledVote(vote.clone(), Box::new(found))); - let context = BackendTaskContext::for_dispatch_on(&task, self.app_context.network()); - self.pending_scheduled_actions.insert(pending_key.clone(), context.clone()); - action = AppAction::BackendTaskWithContext { task, context }; - show_cast_overlay = true; - } - }); - }); + 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.as_ref()?; + 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); + } }); - - if show_cast_overlay { + if show_cast_progress { self.show_vote_progress(ui.ctx()); } - action } + /// 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 + .as_ref() + .map_or(self.app_context.network(), |(_, key)| key.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(|| short_identifier(vote.voter_id)); + 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(status) + .color(DashColors::text_primary(dark_mode)), + ); + if let Some(guidance) = failure_guidance { + ui.add(Label::new(guidance).wrap()); + } + }); + }); + 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 context = BackendTaskContext::for_dispatch_on( + &task, + self.app_context.network(), + ); + self.pending_scheduled_actions + .insert(pending_key.clone(), context.clone()); + *action = AppAction::BackendTaskWithContext { task, context }; + *show_cast_progress = true; + } + }); + }); + } + }); + } + 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; diff --git a/src/ui/state/dpns_vote_operations.rs b/src/ui/state/dpns_vote_operations.rs index 80a11809e..4935a022e 100644 --- a/src/ui/state/dpns_vote_operations.rs +++ b/src/ui/state/dpns_vote_operations.rs @@ -19,6 +19,42 @@ pub(crate) struct ScheduledDpnsVoteRow { 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(); + for row in rows { + match groups.iter_mut().find(|group| { + group.contested_name == row.vote.contested_name + && group.choice == row.vote.choice + && group.unix_timestamp == row.vote.unix_timestamp + }) { + Some(group) => group.rows.push(row), + None => groups.push(ScheduledDecisionGroup { + contested_name: row.vote.contested_name.clone(), + choice: row.vote.choice, + unix_timestamp: row.vote.unix_timestamp, + rows: vec![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, @@ -241,6 +277,45 @@ mod tests { 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: legacy_vote( + Identifier::from([voter; 32]), + name, + choice, + timestamp, + false, + ), + journal_target: None, + 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) + ] + ); + } + fn scheduled_operation( created_at: u64, status: DpnsVoteTargetStatus, From ad3bbdeeb11652b1518449663a303b9191608f05 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:06:16 +0000 Subject: [PATCH 080/194] feat(dpns): history shows how your nodes voted MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Votes β–Έ History adds "Your nodes voted": every loaded node's proved choice on the finished contest, tallied by choice with vote weight (e.g. "Lock (2 nodes, 5 votes)"), or "Your nodes didn't vote." The cell stays blank when no node's vote is known on this device. Outcomes read "Went to {name} ({id})" with Copy ID, or "Locked for good, no one can register it" (VOTE-FR-087). The confirm step lists set nodes that cannot vote (not in the masternode list, no voting key), and the node detail shows its voting weight. User stories DPN-003/004/006/007/013/014/015 and MN-003 are implemented; DPN-005 stays a gap until preflight hands a first vote that became a change back to the confirm step. Co-Authored-By: Claude Opus 5.5 --- docs/user-stories.md | 16 +- src/backend_task/contested_names/mod.rs | 3 + src/model/dpns_voting/operator.rs | 62 ++++++- src/ui/dpns/copy.rs | 73 +++++++- src/ui/dpns/dpns_contested_names_screen.rs | 186 +++++++++++++++++++-- src/ui/masternodes/detail_screen.rs | 14 +- 6 files changed, 331 insertions(+), 23 deletions(-) diff --git a/docs/user-stories.md b/docs/user-stories.md index 7d3587803..53cf90755 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -790,7 +790,7 @@ As a user, I want to see each identity's usernames and their state so that I kno - 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: See name contests my nodes can vote on [Gap] +### DPN-003: See name contests my nodes can vote on [Implemented] **Persona:** Priya 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. @@ -800,7 +800,7 @@ As a masternode operator, I want to see the name contests that need a decision f - Contest refresh remains available if saved voting progress cannot be recovered. - Tools no longer has a DPNS entry. -### DPN-004: View past name contests [Gap] +### DPN-004: View past name contests [Implemented] **Persona:** Priya As a power user, I want to review past contests so that I can see outcomes and how my nodes voted. @@ -819,7 +819,7 @@ As a masternode operator, I want to make one decision per contest and have all m - 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 [Gap] +### DPN-006: Schedule votes [Implemented] **Persona:** Priya As a masternode operator, I want to schedule votes so that they are cast before the deadline without my watching. @@ -830,7 +830,7 @@ As a masternode operator, I want to schedule votes so that they are cast before - 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: Vote with many nodes and contests at once [Gap] +### DPN-007: Vote with many nodes and contests at once [Implemented] **Persona:** Priya 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. @@ -891,7 +891,7 @@ As a user waiting for a community vote, I want to see how my request is doing an - Outcomes (won, went to someone else, locked) are announced once with a banner and stay in Profile for 30 days. - Power users whose nodes can vote on the contest get a link to Masternodes β–Έ Votes for that name. -### DPN-013: Know from anywhere that a vote is needed [Gap] +### 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. @@ -900,7 +900,7 @@ As a masternode operator, I want the app to tell me when my nodes have contests - 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 [Gap] +### 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. @@ -908,7 +908,7 @@ As a masternode operator, I want to see how much my votes matter and how many ch - 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 [Gap] +### 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. @@ -1726,7 +1726,7 @@ As a masternode operator, I want a card list of my loaded masternodes showing ty - An empty state explains what a masternode identity is for and offers a primary "Load a masternode" action when none are loaded. - The Masternodes tab and its nav entry are visible only at the Detailed view interface mode or above; dropping below Detailed view while the tab is active falls back to the Identities screen. -### MN-003: Open a masternode and vote [Gap] +### MN-003: Open a masternode and vote [Implemented] **Persona:** Priya 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. diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index b51b81d33..dff0554fb 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -726,6 +726,9 @@ impl AppContext { if !app_context.claim_dpns_vote_target(operation_id, &target.key)? { continue; } + // TODO(DPN-005): re-read the proved current choice here and, when a + // first vote has become a change, hand the batch back to the confirm + // step with the change warning instead of submitting. if let Some((status, failure)) = voting_ended_outcome(contests.get(&target.contested_name), now_ms()) { diff --git a/src/model/dpns_voting/operator.rs b/src/model/dpns_voting/operator.rs index d8529e930..600870bfd 100644 --- a/src/model/dpns_voting/operator.rs +++ b/src/model/dpns_voting/operator.rs @@ -152,13 +152,43 @@ pub fn node_exclusion(node: &VotingNode) -> Option { } } +/// 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, VOTE-FR-087). +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, + 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. @@ -536,6 +566,34 @@ mod tests { } /// 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]); diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index 24641062c..d1745ef5f 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -4,7 +4,7 @@ //! so no caller concatenates fragments. use crate::model::dpns_voting::composer::SkipReason; -use crate::model::dpns_voting::operator::{ChangesLeft, TimeLeft}; +use crate::model::dpns_voting::operator::{ChangesLeft, NodeExclusion, TimeLeft}; use crate::model::dpns_voting::progress::{NeedsAttention, ProgressCounts}; use crate::model::dpns_voting::{DpnsVoteFailure, DpnsVoteTargetStatus}; @@ -267,6 +267,38 @@ pub fn needs_attention_line(attention: NeedsAttention) -> String { format!("Needs attention: {parts}.", parts = parts.join(" Β· ")) } +/// One part of the History `Your nodes voted` cell, e.g. +/// `Vote for Zed (24 nodes, 51 votes)`. +pub fn nodes_voted_part(choice: &str, nodes: usize, votes: u32) -> String { + match (nodes, votes) { + (1, 1) => format!("{choice} (1 node, 1 vote)"), + (1, votes) => format!("{choice} (1 node, {votes} votes)"), + (nodes, votes) => format!("{choice} ({nodes} nodes, {votes} votes)"), + } +} + +/// 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 (VOTE-FR-087). +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"; + +/// History cell when none of your nodes voted on a finished contest. +pub const NODES_DID_NOT_VOTE: &str = "Your nodes didn't vote."; + /// Expander label of a scheduled decision's node list (VOTE-FR-088). pub fn scheduled_nodes_label(nodes: usize) -> String { match nodes { @@ -314,6 +346,25 @@ pub fn skipped_header(count: usize) -> String { } } +/// 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 skipped-reason line, e.g. `2 votes: no changes left (5 of 5 votes used)`. pub fn skipped_reason_line(count: usize, reason: SkipReason) -> String { let votes = match count { @@ -382,6 +433,26 @@ pub fn changes_left_label(changes: ChangesLeft) -> String { #[cfg(test)] mod tests { + /// 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!( + nodes_voted_part("Vote for Zed", 24, 51), + "Vote for Zed (24 nodes, 51 votes)" + ); + assert_eq!(nodes_voted_part("Lock", 1, 1), "Lock (1 node, 1 vote)"); + assert_eq!(nodes_voted_part("Lock", 1, 4), "Lock (1 node, 4 votes)"); + 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). diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 5e69031cd..1befcf29b 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -26,9 +26,10 @@ use crate::model::dpns_voting::composer::{ SkipReason, compose, }; use crate::model::dpns_voting::contest_timing::{contest_durations, urgency_window}; +use crate::model::dpns_voting::operator::NodeExclusion; use crate::model::dpns_voting::operator::{ - ChangesLeft, NodeSet, ResolvedNodeSet, VotingNode, VotingNodeKind, relative_schedule_preset, - time_left, + ChangesLeft, ChoiceTally, NodeSet, ResolvedNodeSet, VotingNode, VotingNodeKind, + relative_schedule_preset, tally_node_choices, time_left, }; use crate::model::dpns_voting::progress::needs_attention; use crate::model::dpns_voting::{ @@ -44,12 +45,14 @@ use crate::ui::components::utc_schedule_input::UtcScheduleInput; use crate::ui::components::{BannerHandle, MessageBanner, OptionBannerExt}; use crate::ui::dpns::contest_card::node_label; use crate::ui::dpns::contest_card::{CardEvent, CardView}; +use crate::ui::dpns::copy::excluded_nodes_line; use crate::ui::dpns::copy::needs_attention_line; use crate::ui::dpns::copy::tray_label; use crate::ui::dpns::copy::{ - 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, + LOCKED_FOR_GOOD, NODES_DID_NOT_VOTE, before_end_phrase, changes_left_label, + confirm_button_label, confirm_change_warning, confirm_title, confirm_transactions_line, + decision_row, ends_in_label, nodes_voted_part, relative_schedule_label, scheduled_nodes_label, + skipped_header, skipped_reason_line, went_to_label, }; use crate::ui::dpns::node_set_picker; use crate::ui::dpns::progress_drawer; @@ -518,6 +521,9 @@ pub struct DPNSScreen { /// Cards ticked for a bulk decision, by contest name. selected_cards: BTreeSet, focused_card: Option, + /// History `Your nodes voted` per finished contest; absent when no node's + /// vote is known on this device. + history_votes: BTreeMap>, /// Whether the contest list has keyboard focus for shortcuts. list_focused: bool, } @@ -609,6 +615,7 @@ impl DPNSScreen { relative_schedule_labels: BTreeMap::new(), selected_cards: BTreeSet::new(), focused_card: None, + history_votes: BTreeMap::new(), list_focused: false, }; screen.rebuild_cards(); @@ -667,6 +674,8 @@ impl DPNSScreen { self.cards.clear(); self.selected_cards.clear(); self.focused_card = None; + self.list_focused = false; + self.history_votes.clear(); } // --------------------------- @@ -811,6 +820,87 @@ impl DPNSScreen { /// 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. + /// Every loaded node's proved choice on each finished contest, tallied. + /// A contest is listed only when at least one node's vote is known. + fn collect_history_votes(&self) -> BTreeMap> { + let finished: Vec<(String, Identifier)> = self + .contested_names + .lock_recover() + .iter() + .filter(|contest| contest.awarded_to.is_some() || contest.state == ContestState::Locked) + .filter_map(|contest| { + let poll = self + .app_context + .dpns_vote_poll_id(&contest.normalized_contested_name) + .ok()?; + Some((contest.normalized_contested_name.clone(), poll)) + }) + .collect(); + if finished.is_empty() { + return BTreeMap::new(); + } + let states: Vec<(VotingNodeKind, BTreeMap)> = self + .voting_nodes + .iter() + .filter_map(|node| { + let states = self + .app_context + .dpns_current_vote_states(node.id, finished.iter().map(|(_, poll)| *poll)) + .inspect_err(|error| { + tracing::debug!( + ?error, + "Could not read a node's votes on finished contests" + ); + }) + .ok()?; + Some((node.kind, states)) + }) + .collect(); + finished + .into_iter() + .filter_map(|(name, poll)| { + let known: Vec<(VotingNodeKind, Option)> = states + .iter() + .filter_map(|(kind, states)| match states.get(&poll) { + Some(DpnsCurrentVoteState::Available(choice)) => Some((*kind, *choice)), + _ => None, + }) + .collect(); + if known.is_empty() { + return None; + } + let tallies = tally_node_choices( + known + .into_iter() + .filter_map(|(kind, choice)| choice.map(|choice| (kind, choice))), + ); + Some((name, tallies)) + }) + .collect() + } + + /// The History `Your nodes voted` cell; empty when nothing is known. + fn history_votes_cell(&self, contested_name: &str) -> String { + match self.history_votes.get(contested_name) { + None => String::new(), + Some(tallies) if tallies.is_empty() => NODES_DID_NOT_VOTE.to_owned(), + Some(tallies) => tallies + .iter() + .map(|tally| { + nodes_voted_part( + &vote_choice_label( + tally.choice, + self.candidate_name(contested_name, tally.choice), + ), + tally.nodes, + tally.weight, + ) + }) + .collect::>() + .join("; "), + } + } + pub(crate) fn rebuild_cards(&mut self) { let network = self.app_context.network(); if self.node_set_network != Some(network) { @@ -867,6 +957,7 @@ impl DPNSScreen { .collect(); sort_by_time_left(&mut cards); self.cards = cards; + self.history_votes = self.collect_history_votes(); let names: BTreeSet<&str> = self.cards.iter().map(VoteCard::name).collect(); self.selected_cards .retain(|name| names.contains(name.as_str())); @@ -1407,6 +1498,7 @@ impl DPNSScreen { .column(Column::auto().resizable(true)) // Ended Time .column(Column::auto().resizable(true)) // Last Updated .column(Column::auto().resizable(true)) // Awarded To + .column(Column::remainder()) // Your nodes voted .header(30.0, |mut header| { header.col(|ui| { if ui.button("Name").clicked() { @@ -1428,6 +1520,9 @@ impl DPNSScreen { self.toggle_sort(SortColumn::AwardedTo); } }); + header.col(|ui| { + ui.label(RichText::new("Your nodes voted").strong()); + }); }) .body(|mut body| { for contested_name in &contested_names { @@ -1521,25 +1616,37 @@ impl DPNSScreen { .iter() .find(|contestant| contestant.id == identifier) }) - .map(|contestant| contestant.name.clone()) - .unwrap_or_else(|| short_identifier(identifier)); - ui.label(format!("Won by {winner}.")); + .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; no name was awarded.") + RichText::new(LOCKED_FOR_GOOD) .color(DashColors::text_primary(dark_mode)), ); } } }); + row.col(|ui| { + ui.label( + self.history_votes_cell( + &contested_name.normalized_contested_name, + ), + ); + }); }); } }); }); } - /// Show the Scheduled Votes table /// 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. @@ -1919,6 +2026,20 @@ impl DPNSScreen { 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()); @@ -3771,6 +3892,51 @@ mod tests { ); } + /// VOTE-FR-087 (History): `Your nodes voted` tallies proved choices with + /// weight, says when no node voted, and stays blank when nothing is known. + #[tokio::test] + async fn history_cell_tallies_node_votes() { + let (ctx, _dir) = kv_ctx(); + let mut evonode = masternode_identity(1, "evo", true, ctx.network()); + evonode.identity_type = crate::model::qualified_identity::IdentityType::Evonode; + let masternode = masternode_identity(2, "mn", true, ctx.network()); + let finished = |name: &str| ContestedName { + normalized_contested_name: name.to_owned(), + contestants: None, + locked_votes: None, + abstain_votes: None, + awarded_to: None, + end_time: Some(1), + state: ContestState::Locked, + last_updated: None, + my_votes: BTreeMap::new(), + }; + let voted = ctx.dpns_vote_poll_id("voted").unwrap(); + ctx.seed_proved_dpns_votes_for_test( + evonode.identity.id(), + BTreeMap::from([(voted.to_buffer(), ResourceVoteChoice::Lock)]), + ) + .await + .unwrap(); + ctx.seed_proved_dpns_votes_for_test( + masternode.identity.id(), + BTreeMap::from([(voted.to_buffer(), ResourceVoteChoice::Lock)]), + ) + .await + .unwrap(); + let mut screen = DPNSScreen::new(&ctx, VotesView::History); + *screen.contested_names.lock_recover() = + vec![finished("voted"), finished("skipped"), finished("unknown")]; + screen.voting_identities = vec![evonode, masternode]; + screen.rebuild_cards(); + assert_eq!( + screen.history_votes_cell("voted"), + "Lock (2 nodes, 5 votes)" + ); + assert_eq!(screen.history_votes_cell("skipped"), NODES_DID_NOT_VOTE); + assert_eq!(screen.history_votes_cell("absent"), ""); + } + /// 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(); diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index 93c7e09fa..c447b3648 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -22,7 +22,9 @@ use crate::backend_task::identity::{IdentityInputToLoad, IdentityLoadMode, Ident use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; use crate::context::AppContext; use crate::context::identity_load_registry::{IdentityLoadPhase, IdentityLoadToken}; -use crate::model::dpns_voting::operator::{ListMembership, NodeVoteRow, time_left}; +use crate::model::dpns_voting::operator::{ + EVONODE_VOTE_WEIGHT, ListMembership, MASTERNODE_VOTE_WEIGHT, NodeVoteRow, 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}; @@ -32,7 +34,7 @@ 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::{changes_left_label, ends_in_label}; +use crate::ui::dpns::copy::{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; @@ -456,6 +458,14 @@ impl MasternodeDetailView { ui.ctx().copy_text(self.node_id_hex_full.clone()); } draw_type_badge(ui, self.badge_label(), dark_mode); + let weight = match self.identity.identity_type { + IdentityType::Evonode => EVONODE_VOTE_WEIGHT, + _ => MASTERNODE_VOTE_WEIGHT, + }; + 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( From 6bccd91d93d4c3b854a30e4a43faa46209b1bfaa Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:09:49 +0000 Subject: [PATCH 081/194] feat(dpns): open Votes on one contest from other screens MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AppContext::request_dpns_votes_for_name(label), paired with SetMainScreenThenGoToMainScreen(RootScreenDPNSActiveContests), opens Masternodes β–Έ Votes on the view holding that contest's card, with the filter set to the label and the card focused. The username request status page uses it for its link to the voting panel. Co-Authored-By: Claude Opus 5.5 --- src/context/dpns_vote_attention.rs | 18 ++++++++++ src/context/mod.rs | 3 ++ src/ui/dpns/dpns_contested_names_screen.rs | 41 ++++++++++++++++++++++ 3 files changed, 62 insertions(+) diff --git a/src/context/dpns_vote_attention.rs b/src/context/dpns_vote_attention.rs index c32898d82..5874ca4fa 100644 --- a/src/context/dpns_vote_attention.rs +++ b/src/context/dpns_vote_attention.rs @@ -76,6 +76,24 @@ impl AppContext { .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); + } + + /// 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 diff --git a/src/context/mod.rs b/src/context/mod.rs index 3896d88e7..4d59c968e 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -210,6 +210,8 @@ pub struct AppContext { dpns_vote_progress: RwLock>, /// A `Review again` request from the progress drawer for the voting panel. dpns_vote_review_request: std::sync::Mutex>, + /// 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`. @@ -585,6 +587,7 @@ impl AppContext { 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), app_kv, #[cfg(test)] det_kv_override: Mutex::new(None), diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 1befcf29b..b25f209d5 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -983,6 +983,23 @@ impl DPNSScreen { .sum() } + /// 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; + } + /// 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) { @@ -2645,6 +2662,9 @@ impl ScreenLike for DPNSScreen { 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 { @@ -3937,6 +3957,27 @@ mod tests { assert_eq!(screen.history_votes_cell("absent"), ""); } + /// 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(); From 303571a47913b7e3a497ad9216dd4bfd97a7d9d1 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:10:10 +0000 Subject: [PATCH 082/194] docs(identity): mark DPN-017 implemented and name the filtered votes route Co-Authored-By: Claude Opus 5.5 --- docs/user-stories.md | 2 +- src/ui/identity/username_request_screen.rs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/user-stories.md b/docs/user-stories.md index ff14f8c84..bee0ca36a 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -925,7 +925,7 @@ As a user, I want suggestions that need no vote so that I can get a working user - 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 [Gap] +### 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. diff --git a/src/ui/identity/username_request_screen.rs b/src/ui/identity/username_request_screen.rs index 214ba48af..6747ef6af 100644 --- a/src/ui/identity/username_request_screen.rs +++ b/src/ui/identity/username_request_screen.rs @@ -260,7 +260,8 @@ impl UsernameRequestScreen { action = register_action_for(&self.app_context, self.identity_id); } if self.can_vote && ui.link("Your nodes can vote on this name").clicked() { - // TODO(stream-v): open Masternodes β–Έ Votes filtered to this name once Stream V exposes the route. + // TODO(stream-v): after redesign/pr901-voting merges, call + // `app_context.request_dpns_votes_for_name(self.normalized_label.clone())` first. action = AppAction::SetMainScreenThenGoToMainScreen( RootScreenType::RootScreenDPNSActiveContests, ); From 8929336b058ec9c1adecddd1a34d626f6f1d7872 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:32:13 +0000 Subject: [PATCH 083/194] fix(masternodes): key list membership by the masternode identity id The SPV masternode list holds each proTxHash in wire order, but Platform derives masternode identity ids from the display order: drive-abci parses Core's RPC hex into `ProTxHash`, which is forward-displayed, so the hex bytes are the id. Keying membership by the wire bytes made every loaded node read "not in the masternode list" once the list synced, which left no node able to vote. Membership now keys by `pro_tx_hash_display()`, and a test pins it to the id DET loads a masternode under. Co-Authored-By: Claude Opus 5.5 --- src/wallet_backend/mod.rs | 71 ++++++++++++++++++++++++++++++--------- 1 file changed, 55 insertions(+), 16 deletions(-) diff --git a/src/wallet_backend/mod.rs b/src/wallet_backend/mod.rs index 9e0908e05..7eebd50f6 100644 --- a/src/wallet_backend/mod.rs +++ b/src/wallet_backend/mod.rs @@ -2455,26 +2455,13 @@ impl WalletBackend { }) } - /// ProTxHashes in the current deterministic masternode list, each mapped - /// to whether it is an evonode. `None` until the list has synced. - /// - /// Keys are the masternode identity ids: Platform derives them from the - /// wire-order `pro_tx_hash` bytes unchanged (`to_byte_array`). + /// 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( - summaries - .into_iter() - .map(|summary| { - ( - dash_sdk::platform::Identifier::from(summary.pro_tx_hash), - summary.is_evonode, - ) - }) - .collect(), - ) + Some(membership_from_summaries(summaries)) } /// Whether chain sync has not yet reached the tip. @@ -4748,3 +4735,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)); + } +} From 93a501265b5d87cf8a4ad4dcba47b5dd937dbcfe Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:33:36 +0000 Subject: [PATCH 084/194] fix(identity): keep outcome banners once-only and show the main name everywhere - Re-send the outcome seen mark on every Home frame until the store confirms it, so a frame whose action the hub replaces (profile load) no longer loses it and the banner does not return on the next start. - Treat any legacy {label}.dash alias as the automatic copy older versions wrote, including for requests later lost. - Load identities with the main username first, and use it in the identity Display, send screen and address picker. - Tests: USR-TC-035 at protocol 14 (0.1 DASH fee and total), USR-TC-038 result variants, replaced-action seen mark, legacy alias, main-name order. Co-Authored-By: Claude Opus 5.5 --- src/context/contested_names_db.rs | 15 +++ src/context/identity_db.rs | 1 + src/model/dpns_usernames.rs | 49 ++++++- src/model/qualified_identity/mod.rs | 2 +- src/ui/components/address_input.rs | 2 +- src/ui/identity/register_dpns_name_screen.rs | 28 ++++ src/ui/identity/username_notices.rs | 48 ++++--- src/ui/wallets/send_screen.rs | 14 +- tests/kittest/identity_usernames.rs | 131 +++++++++++++++++++ 9 files changed, 254 insertions(+), 36 deletions(-) diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index a3ec11e18..6545f64da 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -401,6 +401,21 @@ impl AppContext { 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()?; diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index 008ad46b6..6de7d4678 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -1510,6 +1510,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) } diff --git a/src/model/dpns_usernames.rs b/src/model/dpns_usernames.rs index c140efbca..0ef51493a 100644 --- a/src/model/dpns_usernames.rs +++ b/src/model/dpns_usernames.rs @@ -93,13 +93,13 @@ pub fn can_register_usernames( } /// The device-only name the user chose, ignoring a legacy automatic copy of a -/// username (`{name}.dash`), which would otherwise hide the chosen main username. +/// username. Earlier versions wrote `{name}.dash` into the alias at registration, +/// including for requests later lost, so any alias of that exact form is treated +/// as automatic and never hides the chosen main username. pub fn user_alias(identity: &QualifiedIdentity) -> Option<&str> { let alias = identity.alias.as_deref()?.trim(); - let automatic = identity.dpns_names.iter().any(|name| { - alias - .strip_suffix(".dash") - .is_some_and(|stem| stem.eq_ignore_ascii_case(name.name.trim())) + let automatic = alias.strip_suffix(".dash").is_some_and(|stem| { + super::dpns::validate_dpns_name(stem) == super::dpns::DpnsNameValidationResult::Valid }); (!alias.is_empty() && !automatic).then_some(alias) } @@ -723,6 +723,45 @@ mod tests { assert_eq!(opened.join_end, Some(5_000 + 45 * MINUTE)); } + #[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!(user_alias(&identity), None); + assert_eq!(identity.to_string(), "bob"); + identity.alias = Some("Alice Novak".to_owned()); + assert_eq!(user_alias(&identity), Some("Alice Novak")); + identity.alias = Some(" ".to_owned()); + assert_eq!(user_alias(&identity), None); + } + #[test] fn signing_gate_matches_platform_key_rules() { use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; diff --git a/src/model/qualified_identity/mod.rs b/src/model/qualified_identity/mod.rs index b15fab90e..92553b3e2 100644 --- a/src/model/qualified_identity/mod.rs +++ b/src/model/qualified_identity/mod.rs @@ -343,7 +343,7 @@ impl Decode for QualifiedIdentity { impl Display for QualifiedIdentity { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - if let Some(alias) = &self.alias { + if let Some(alias) = crate::model::dpns_usernames::user_alias(self) { write!(f, "{}", alias) } else if !self.dpns_names.is_empty() { write!(f, "{}", self.dpns_names[0].name) diff --git a/src/ui/components/address_input.rs b/src/ui/components/address_input.rs index 4e01dc36e..4c567afca 100644 --- a/src/ui/components/address_input.rs +++ b/src/ui/components/address_input.rs @@ -604,7 +604,7 @@ impl AddressInput { for qi in identities { let id = qi.identity.id(); let id_str = id.to_string(Encoding::Base58); - // TODO(usernames): use AppContext::main_username once this component can reach the context. + // Loaded identities list their main username first. let dpns_name = qi.dpns_names.first().map(|n| n.name.clone()); let name_label = dpns_name.clone().or_else(|| qi.alias.clone()); self.all_entries.push(AddressEntry { diff --git a/src/ui/identity/register_dpns_name_screen.rs b/src/ui/identity/register_dpns_name_screen.rs index 12a7061e4..119fd1bf0 100644 --- a/src/ui/identity/register_dpns_name_screen.rs +++ b/src/ui/identity/register_dpns_name_screen.rs @@ -883,3 +883,31 @@ impl ScreenLike for RegisterDpnsNameScreen { action } } + +#[cfg(test)] +mod tests { + use super::*; + + /// 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"); + assert_eq!( + screen.total_fee(true), + screen.registration_fee() + 10_000_000_000 + ); + assert_eq!(screen.total_fee(false), screen.registration_fee()); + } +} diff --git a/src/ui/identity/username_notices.rs b/src/ui/identity/username_notices.rs index 19baaf807..21806310e 100644 --- a/src/ui/identity/username_notices.rs +++ b/src/ui/identity/username_notices.rs @@ -23,6 +23,15 @@ 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 { let name = &request.label; @@ -61,26 +70,29 @@ pub fn render( 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: BTreeSet = ui + let mut session: SessionBanners = ui .ctx() .data(|data| data.get_temp(session_id)) .unwrap_or_default(); - let mut session_changed = false; - // Outcomes shown for the first time this frame; recorded as seen through a - // backend task so each banner appears once, across restarts too. - let mut newly_shown: Vec = Vec::new(); + let before = session.clone(); + // Outcomes not yet recorded as seen. The mark is re-sent on every frame + // until the store confirms it, so a frame whose action is replaced by + // another dispatch (e.g. a profile load) cannot lose it; the task is idempotent. + 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); - if !session.contains(&key) { - if app_context.username_outcome_seen(&identity_id, request) { - continue; - } - newly_shown.push(request.clone()); + 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 { @@ -95,22 +107,16 @@ pub fn render( action = register_action_for(app_context, identity_id); } if ui.button("Dismiss").clicked() { - session.remove(&key); - session_changed = true; - if newly_shown.last() == Some(request) { - newly_shown.pop(); - action = mark_seen_action(identity_id, vec![request.clone()]); - } + session.shown.remove(&key); + session.dismissed.insert(key.clone()); } }); }); } - if !newly_shown.is_empty() && matches!(action, AppAction::None) { - session.extend(newly_shown.iter().map(|r| banner_key(&identity_id, r))); - session_changed = true; - action = mark_seen_action(identity_id, newly_shown); + if !unrecorded.is_empty() && matches!(action, AppAction::None) { + action = mark_seen_action(identity_id, unrecorded); } - if session_changed { + if session != before { ui.ctx() .data_mut(|data| data.insert_temp(session_id, session)); } diff --git a/src/ui/wallets/send_screen.rs b/src/ui/wallets/send_screen.rs index a4891990b..32b239f85 100644 --- a/src/ui/wallets/send_screen.rs +++ b/src/ui/wallets/send_screen.rs @@ -2217,10 +2217,9 @@ impl WalletSendScreen { .selected_identity .as_ref() .map(|qi| { - let name = qi - .dpns_names - .first() - .map(|n| n.name.clone()) + let name = self + .app_context + .main_username(qi) .or_else(|| qi.alias.clone()) .unwrap_or_else(|| { let id_str = qi.identity.id().to_string( @@ -2236,16 +2235,15 @@ impl WalletSendScreen { }) .unwrap_or_else(|| "Select identity".to_string()); + let app_context = self.app_context.clone(); egui::ComboBox::from_id_salt("identity_source_selector") .selected_text(¤t_label) .width(ui.available_width() - 20.0) .show_ui(ui, |ui| { for identity in &identities { let label = { - let name = identity - .dpns_names - .first() - .map(|n| n.name.clone()) + let name = app_context + .main_username(identity) .or_else(|| identity.alias.clone()) .unwrap_or_else(|| { let id_str = identity.identity.id().to_string( diff --git a/tests/kittest/identity_usernames.rs b/tests/kittest/identity_usernames.rs index ab6faddda..35468f6e8 100644 --- a/tests/kittest/identity_usernames.rs +++ b/tests/kittest/identity_usernames.rs @@ -844,3 +844,134 @@ fn top_up_returns_with_name_kept() { ); }); } + +/// 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; the next frame must send it again. + home.step(); + let retried = home.state_mut().2.take(); + 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"); + }); +} From 05621ed072717e1699c1e21e704cbfb8bcbac9b0 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:34:08 +0000 Subject: [PATCH 085/194] fix(dpns): tie lines for Lock ties and empty contests A card no longer reads "leads by 0 votes" when Lock name matches the single top request. It shows "Lock name is tied with the leading request. If still tied at the end, the request wins.", matching Platform, where Lock needs strictly more votes than the top request. A contest with no votes yet shows no tie line. Co-Authored-By: Claude Opus 5.5 --- src/model/dpns_voting/operator.rs | 31 +++++++++++++++++++++++++++++++ src/ui/dpns/contest_card.rs | 3 +++ src/ui/dpns/copy.rs | 4 ++++ 3 files changed, 38 insertions(+) diff --git a/src/model/dpns_voting/operator.rs b/src/model/dpns_voting/operator.rs index 600870bfd..a7069a3c9 100644 --- a/src/model/dpns_voting/operator.rs +++ b/src/model/dpns_voting/operator.rs @@ -237,6 +237,9 @@ pub enum Influence { }, /// 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. @@ -254,9 +257,15 @@ pub fn influence( 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 { @@ -635,6 +644,18 @@ mod tests { ); } + /// 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() { @@ -643,6 +664,16 @@ mod tests { (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, diff --git a/src/ui/dpns/contest_card.rs b/src/ui/dpns/contest_card.rs index f7a5e7f7c..550d3f8eb 100644 --- a/src/ui/dpns/contest_card.rs +++ b/src/ui/dpns/contest_card.rs @@ -287,6 +287,9 @@ impl CardView<'_> { 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 diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index d1745ef5f..b09692fa8 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -99,6 +99,10 @@ pub fn influence_line(leader: &str, margin: u32, weight: u32) -> String { /// 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."; From e082ff590ac91a80a1754be6ad04df61b6c77d80 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:37:33 +0000 Subject: [PATCH 086/194] fix(dpns): clear "not cast" once a vote is recast or dismissed The Needs attention row counted every failed target from this session, even after the same node and name were recast successfully or the batch was dismissed in the progress drawer, so it pointed at a drawer that showed nothing. A failure now counts only while it is the latest outcome for its target and its operation is not dismissed. Dismissed operations live in AppContext so the drawer and the row agree. Co-Authored-By: Claude Opus 5.5 --- src/context/dpns_vote_attention.rs | 22 +++++++++++ src/context/mod.rs | 5 +++ src/model/dpns_voting/progress.rs | 43 ++++++++++++++++++---- src/ui/dpns/dpns_contested_names_screen.rs | 1 + src/ui/dpns/progress_drawer.rs | 23 +++++------- 5 files changed, 72 insertions(+), 22 deletions(-) diff --git a/src/context/dpns_vote_attention.rs b/src/context/dpns_vote_attention.rs index 5874ca4fa..e6e49ef23 100644 --- a/src/context/dpns_vote_attention.rs +++ b/src/context/dpns_vote_attention.rs @@ -86,6 +86,28 @@ impl AppContext { .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 diff --git a/src/context/mod.rs b/src/context/mod.rs index 689eca962..2414f8b92 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -210,6 +210,10 @@ pub struct AppContext { 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. @@ -588,6 +592,7 @@ impl AppContext { 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), diff --git a/src/model/dpns_voting/progress.rs b/src/model/dpns_voting/progress.rs index 203a2b5e3..530a7afa6 100644 --- a/src/model/dpns_voting/progress.rs +++ b/src/model/dpns_voting/progress.rs @@ -2,10 +2,10 @@ //! (VOTE-FR-083/084). Pure: callers pass journal operations and the clock. use super::{ - DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTargetStatus, VoteTiming, - dpns_schedule_is_overdue, + DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTargetKey, + DpnsVoteTargetStatus, VoteTiming, dpns_schedule_is_overdue, }; -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; /// Where one sent target stands, as the drawer groups it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -114,14 +114,23 @@ impl NeedsAttention { /// Targets that need the operator: unconfirmed, failed, or schedules missed. /// -/// Failed targets count only from operations created since `since_ms`, so a -/// stale failure from an earlier session does not nag forever; unconfirmed -/// and missed targets still hold their lock and always count. +/// A failure counts only while it is the latest outcome for its target, its +/// operation was created 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 latest: BTreeMap<&DpnsVoteTargetKey, u64> = BTreeMap::new(); + for operation in operations { + for outcome in &operation.targets { + let at = latest.entry(&outcome.target.key).or_default(); + *at = (*at).max(operation.created_at); + } + } let mut attention = NeedsAttention::default(); for operation in operations { for outcome in &operation.targets { @@ -133,6 +142,8 @@ pub fn needs_attention( attention.missed_schedules += 1; } _ if operation.created_at >= since_ms + && !dismissed.contains(&operation.id) + && latest.get(&outcome.target.key) == Some(&operation.created_at) && progress_phase(outcome) == Some(ProgressPhase::Failed) => { attention.failed += 1; @@ -253,7 +264,7 @@ mod tests { ), operation(1, &[(S::Rejected, NOW)]), ]; - let attention = needs_attention(&operations, 50, 1_000 + 121_000); + let attention = needs_attention(&operations, 50, &BTreeSet::new(), 1_000 + 121_000); assert_eq!( attention, NeedsAttention { @@ -262,6 +273,22 @@ mod tests { missed_schedules: 1, } ); - assert!(needs_attention(&[], 0, 0).is_empty()); + 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(&[failed.clone()], 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); } } diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index e800df10a..72b4d6dad 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -1427,6 +1427,7 @@ impl DPNSScreen { 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() { diff --git a/src/ui/dpns/progress_drawer.rs b/src/ui/dpns/progress_drawer.rs index f44e546d5..bfef25b9f 100644 --- a/src/ui/dpns/progress_drawer.rs +++ b/src/ui/dpns/progress_drawer.rs @@ -8,33 +8,27 @@ use crate::context::AppContext; use crate::model::dpns_voting::progress::{ ProgressCounts, ProgressPhase, drawer_operations, progress_counts, progress_phase, }; -use crate::model::dpns_voting::{ - DpnsVoteFailure, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTargetStatus, -}; +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::platform_value::string_encoding::Encoding; use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; use eframe::egui::{self, Align2, Id, RichText, Sense, Ui}; -use std::collections::BTreeSet; const OPEN_ID: &str = "dpns_vote_progress_drawer_open"; -/// AppState-owned drawer state; survives navigation. +/// 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, - dismissed: BTreeSet, } impl DrawerState { pub fn new(since_ms: u64) -> Self { - Self { - since_ms, - dismissed: BTreeSet::new(), - } + Self { since_ms } } /// Settled operations created before this moment are not listed. @@ -121,7 +115,8 @@ fn paint_segments(ui: &mut Ui, counts: ProgressCounts) { /// 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 shown = drawer_operations(&operations, state.since_ms, &state.dismissed); + let dismissed = app_context.dismissed_dpns_vote_operations(); + let shown = drawer_operations(&operations, state.since_ms, &dismissed); if shown.is_empty() { return AppAction::None; } @@ -144,9 +139,9 @@ pub fn show(ctx: &egui::Context, app_context: &AppContext, state: &mut DrawerSta open = !open; } if !counts.in_flight() && ui.small_button("Dismiss").clicked() { - state - .dismissed - .extend(shown.iter().map(|operation| operation.id)); + app_context.dismiss_dpns_vote_operations( + shown.iter().map(|operation| operation.id), + ); } }); }); From 2ac5b0d55a557299dd6ca66a4fb8c31d2896bf88 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:41:10 +0000 Subject: [PATCH 087/194] fix(identity): bound outcome seen-mark retries Allow one seen-mark write in flight per identity. A dispatch that never starts (its action replaced) is resent after two frames; a failed write backs off 5 s per failure and stops after three failures for the session, so a broken store no longer spawns a task and an error banner every frame. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/identity/dpns_usernames.rs | 5 +- src/context/contested_names_db.rs | 32 ++++++- src/model/dpns_usernames.rs | 91 ++++++++++++++++++ src/ui/identity/username_notices.rs | 100 +++++++++++++++++++- tests/kittest/identity_usernames.rs | 13 ++- 5 files changed, 230 insertions(+), 11 deletions(-) diff --git a/src/backend_task/identity/dpns_usernames.rs b/src/backend_task/identity/dpns_usernames.rs index 241ef6bb0..fd38064df 100644 --- a/src/backend_task/identity/dpns_usernames.rs +++ b/src/backend_task/identity/dpns_usernames.rs @@ -344,7 +344,10 @@ impl AppContext { identity_id: Identifier, requests: Vec, ) -> Result { - self.mark_username_outcomes_seen(&identity_id, &requests)?; + 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) } } diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 6545f64da..312cffb61 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -11,7 +11,7 @@ use crate::backend_task::error::TaskError; use crate::model::contested_name::{ ContestState, Contestant, ContestedName, MasternodeVoteStateSummary, }; -use crate::model::dpns_usernames::UsernameRequest; +use crate::model::dpns_usernames::{SeenMarkAttempts, UsernameRequest}; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, dpns_vote_authority_rank, @@ -287,7 +287,9 @@ impl AppContext { cache.seen.insert(id, seen); } } - *self.username_cache_mut() = cache; + let mut current = self.username_cache_mut(); + cache.seen_marks = std::mem::take(&mut current.seen_marks); + *current = cache; Ok(()) } @@ -299,7 +301,7 @@ impl AppContext { /// Write guard over the username snapshot. Every username write holds it /// across its read-modify-write and store update, so writers never interleave. - fn username_cache_mut(&self) -> std::sync::RwLockWriteGuard<'_, UsernameCache> { + pub(crate) fn username_cache_mut(&self) -> std::sync::RwLockWriteGuard<'_, UsernameCache> { self.pending_dpns_usernames .write() .unwrap_or_else(std::sync::PoisonError::into_inner) @@ -442,6 +444,28 @@ impl AppContext { .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, @@ -819,6 +843,8 @@ pub(crate) struct UsernameCache { requests: HashMap>, 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 { diff --git a/src/model/dpns_usernames.rs b/src/model/dpns_usernames.rs index 0ef51493a..3292c4966 100644 --- a/src/model/dpns_usernames.rs +++ b/src/model/dpns_usernames.rs @@ -50,6 +50,71 @@ pub fn username_refresh_due( || (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( @@ -723,6 +788,32 @@ mod tests { 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, diff --git a/src/ui/identity/username_notices.rs b/src/ui/identity/username_notices.rs index 21806310e..8f342c8d8 100644 --- a/src/ui/identity/username_notices.rs +++ b/src/ui/identity/username_notices.rs @@ -75,9 +75,9 @@ pub fn render( .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 on every frame - // until the store confirms it, so a frame whose action is replaced by - // another dispatch (e.g. a profile load) cannot lose it; the task is idempotent. + // 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 { @@ -113,7 +113,10 @@ pub fn render( }); }); } - if !unrecorded.is_empty() && matches!(action, AppAction::None) { + 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 { @@ -172,6 +175,7 @@ fn notice_frame(ui: &mut Ui, dark_mode: bool, add: impl FnOnce(&mut Ui)) { #[cfg(test)] mod tests { use super::*; + use crate::backend_task::error::TaskError; use crate::model::dpns::ContestDurations; use std::time::Duration; @@ -198,4 +202,92 @@ mod tests { 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::model::qualified_identity::encrypted_key_storage::KeyStorage; + use crate::model::qualified_identity::{IdentityStatus, IdentityType}; + 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 = QualifiedIdentity { + identity: dash_sdk::dpp::identity::Identity::create_basic_identity( + [0x61; 32].into(), + 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: 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/tests/kittest/identity_usernames.rs b/tests/kittest/identity_usernames.rs index 35468f6e8..9c68c44c0 100644 --- a/tests/kittest/identity_usernames.rs +++ b/tests/kittest/identity_usernames.rs @@ -927,9 +927,16 @@ fn seen_mark_survives_a_replaced_action() { "precondition: first frame marks, got {replaced:?}" ); - // The hub dropped that action; the next frame must send it again. - home.step(); - let retried = home.state_mut().2.take(); + // 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); From 1efeac0d1fb46a62b51bbe4b4c681a49a044e19a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:42:37 +0000 Subject: [PATCH 088/194] feat(dpns): vote now on contests already inside the lead time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "When voting is about to end" no longer rejects the whole batch when one contest ends sooner than the lead time. Such contests are voted now, and the confirm step says so: "{n} of these votes will be sent now because voting ends soon." Every other contest is still scheduled at end βˆ’ lead time. Absolute times at or after a deadline are still refused. VOTE-FR-081 and the UX spec describe the fallback. Also clears a clippy lint in the needs-attention test. Co-Authored-By: Claude Opus 5.5 --- .../01-requirements.md | 6 +- .../02-ux-spec.md | 3 +- src/model/dpns_voting/composer.rs | 67 ++++++++++++++----- src/model/dpns_voting/progress.rs | 5 +- src/ui/dpns/copy.rs | 6 ++ src/ui/dpns/dpns_contested_names_screen.rs | 16 +++-- 6 files changed, 81 insertions(+), 22 deletions(-) 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 index 175ce988f..43bb4ef3f 100644 --- 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 @@ -276,7 +276,11 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. - **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}`. Times at or after the deadline are rejected (existing rule). + Β· {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.` Every other contest is + scheduled as above. 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. 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 index 17c6eefe4..360012fa0 100644 --- 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 @@ -94,7 +94,8 @@ 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.` + 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). diff --git a/src/model/dpns_voting/composer.rs b/src/model/dpns_voting/composer.rs index f73a77efa..49ca93a70 100644 --- a/src/model/dpns_voting/composer.rs +++ b/src/model/dpns_voting/composer.rs @@ -6,8 +6,8 @@ use super::operator::{ChangesLeft, relative_schedule}; use super::{ - DpnsCurrentVoteState, DpnsScheduleEditValidationError, DpnsVoteTarget, DpnsVoteTargetKey, - VoteTiming, validate_dpns_schedule_time, + DpnsCurrentVoteState, DpnsVoteTarget, DpnsVoteTargetKey, VoteTiming, + validate_dpns_schedule_time, }; use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::identity::TimestampMillis; @@ -95,6 +95,9 @@ pub enum ComposeError { pub struct AggregatePlan { pub targets: Vec, pub skipped: Vec, + /// Targets asked to vote "when voting is about to end" whose contest is + /// already inside the lead time, so they are sent now. + pub ends_soon_now: usize, } impl AggregatePlan { @@ -132,24 +135,27 @@ impl AggregatePlan { } } +/// Resolve a timing for one decision. "Before the end" on a contest already +/// inside the lead time votes now; the flag reports that fallback. fn resolve_timing( timing: BatchTiming, decision: &Decision, now_ms: u64, -) -> Result { +) -> Result<(VoteTiming, bool), ComposeError> { let outlasts = || ComposeError::ScheduleOutlastsContest { contested_name: decision.contested_name.clone(), }; match timing { - BatchTiming::Now => Ok(VoteTiming::Now), + BatchTiming::Now => Ok((VoteTiming::Now, false)), BatchTiming::BeforeEnd(preset) => { let end = decision.end_time.ok_or_else(outlasts)?; - relative_schedule(end, preset, now_ms) - .map(VoteTiming::Scheduled) - .map_err(|_: DpnsScheduleEditValidationError| outlasts()) + Ok(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(|()| VoteTiming::Scheduled(at)) + .map(|()| (VoteTiming::Scheduled(at), false)) .map_err(|_| outlasts()), } } @@ -222,9 +228,13 @@ pub fn compose( contested_name: decision.contested_name.clone(), requested_choice: decision.choice, current_choice: current, - timing: match timing { - Some(timing) => resolve_timing(timing, decision, now_ms)?, - None => batch_timing, + timing: { + let (timing, ends_soon) = match timing { + Some(timing) => resolve_timing(timing, decision, now_ms)?, + None => batch_timing, + }; + plan.ends_soon_now += usize::from(ends_soon); + timing }, }); } @@ -424,10 +434,6 @@ mod tests { let outlasts = Err(ComposeError::ScheduleOutlastsContest { contested_name: "alice".to_owned(), }); - assert_eq!( - compose_at(BatchTiming::BeforeEnd(Duration::from_secs(600))), - outlasts - ); assert_eq!(compose_at(BatchTiming::At(5 * MIN)), outlasts); assert!(compose_at(BatchTiming::At(4 * MIN)).is_ok()); @@ -449,6 +455,37 @@ mod tests { ); } + /// 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); + } + /// VOTE-TC-103 (compose half): a decision whose voting ended is refused. #[test] fn ended_contests_are_refused() { diff --git a/src/model/dpns_voting/progress.rs b/src/model/dpns_voting/progress.rs index 530a7afa6..404a5a440 100644 --- a/src/model/dpns_voting/progress.rs +++ b/src/model/dpns_voting/progress.rs @@ -283,7 +283,10 @@ mod tests { let failed = operation(100, &[(S::FailedBeforeSubmission, NOW)]); let recast = operation(200, &[(S::Confirmed, NOW)]); let none = BTreeSet::new(); - assert_eq!(needs_attention(&[failed.clone()], 0, &none, 300).failed, 1); + 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 diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index b09692fa8..dc24e4c1f 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -350,6 +350,12 @@ pub fn skipped_header(count: usize) -> String { } } +/// 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) { diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 72b4d6dad..7b1b226c4 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -45,7 +45,6 @@ use crate::ui::components::utc_schedule_input::UtcScheduleInput; use crate::ui::components::{BannerHandle, MessageBanner, OptionBannerExt}; use crate::ui::dpns::contest_card::node_label; use crate::ui::dpns::contest_card::{CardEvent, CardView}; -use crate::ui::dpns::copy::excluded_nodes_line; use crate::ui::dpns::copy::needs_attention_line; use crate::ui::dpns::copy::tray_label; use crate::ui::dpns::copy::{ @@ -54,6 +53,7 @@ use crate::ui::dpns::copy::{ decision_row, ends_in_label, nodes_voted_part, relative_schedule_label, scheduled_nodes_label, skipped_header, skipped_reason_line, went_to_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; @@ -2037,6 +2037,9 @@ impl DPNSScreen { 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()); @@ -3664,9 +3667,14 @@ mod tests { 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); - assert!( - screen.build_review_plan_at(now).is_err(), - "ten minutes before an end five minutes away is in the past" + 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); From e076952a68570c4059c9d44f7b9bca130a84a208 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:49:15 +0000 Subject: [PATCH 089/194] refactor(dpns): persist voting preferences through backend tasks The voting UI wrote the KV store itself in three places: the remembered Masternodes segment, "Save as my default" for the node set, and the relative-schedule labels saved on submit. They now go through the backend. The new ContestedResourceTask::SaveDpnsVotingPreference handles the segment and the node set; the screens queue it and send it when no user action is pending. SubmitDpnsVoteOperation carries the labels, and the backend stores them before it runs the operation. Label writes stay display-only and never block a vote. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/contested_names/mod.rs | 86 ++++++++++++++++++++++ src/backend_task/mod.rs | 1 + src/ui/dpns/dpns_contested_names_screen.rs | 51 +++++++------ src/ui/masternodes/list_screen.rs | 36 ++++++++- 4 files changed, 144 insertions(+), 30 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index dff0554fb..802dd3c54 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -40,14 +40,19 @@ use crate::model::dpns_voting::SCHEDULED_VOTE_MAX_LATENESS_MS; #[derive(Debug, Clone, PartialEq)] pub enum ContestedResourceTask { QueryDPNSContests, + /// 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, + /// The last field records the relative preset of "before the end" + /// targets for display (VOTE-FR-081). SubmitDpnsVoteOperation( DpnsVoteOperation, Vec, Option, Network, + Option, ), ReconcileDpnsVoteOperation(DpnsVoteOperationId, Network), CastScheduledVote(ScheduledDPNSVote, Box), @@ -111,6 +116,42 @@ fn classify_vote_attempt( /// /// Terminal for scheduled targets too: a closed poll can never accept the /// vote, so retrying it would only fail again. +/// 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, +} + +impl AppContext { + /// Record the relative preset of each listed scheduled target. Display + /// only, so failures are logged and never block the vote. + fn save_relative_schedule_labels( + &self, + operation: &DpnsVoteOperation, + labels: &RelativeScheduleLabels, + ) { + for outcome in &operation.targets { + if let VoteTiming::Scheduled(at) = outcome.target.timing + && labels.targets.contains(&outcome.target.key) + && let Err(error) = + self.save_dpns_relative_schedule_label(&outcome.target.key, at, labels.preset) + { + tracing::debug!(?error, "Could not save a relative schedule label"); + } + } + } +} + fn voting_ended_outcome( contest: Option<&ContestedName>, now_ms: u64, @@ -236,12 +277,28 @@ impl AppContext { .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( operation, voters, replacing_scheduled_key, _, + labels, ) => { + if let Some(labels) = labels { + self.save_relative_schedule_labels(&operation, &labels); + } self.execute_dpns_vote_operation_with_recovery( operation, voters, @@ -1554,6 +1611,35 @@ mod tests { } } + /// 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(), + }; + context.save_relative_schedule_labels(&operation, &labels); + let alice = &operation.targets[0].target.key; + let bob = &operation.targets[1].target.key; + assert_eq!( + context.dpns_relative_schedule_label(alice, 9_000), + Some(preset) + ); + assert_eq!(context.dpns_relative_schedule_label(bob, 9_000), None); + } + #[tokio::test] async fn new_schedule_rejects_past_time_before_persistence() { let (_temp, context) = vote_context(); diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 472b07c07..c1e68a07e 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -631,6 +631,7 @@ impl From<&BackendTask> for BackendTaskContext { _, _, network, + _, )) => Self::DpnsVoteOperation { network: *network, operation_id: operation.id, diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 7b1b226c4..6a3ad8ca1 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -16,6 +16,7 @@ use egui_extras::{Column, TableBuilder}; 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::{BackendTask, BackendTaskContext}; use crate::context::AppContext; @@ -464,6 +465,8 @@ pub struct DPNSScreen { 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, @@ -583,6 +586,7 @@ impl DPNSScreen { active_filter_term: String::new(), past_filter_term: String::new(), pending_backend_task: None, + pending_preference: None, vote_operations, vote_state, pending_vote_operation: None, @@ -651,6 +655,7 @@ impl DPNSScreen { 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.pending_scheduled_actions.clear(); self.release_pending_on_error = false; @@ -1024,15 +1029,7 @@ impl DPNSScreen { let picked = node_set_picker::show(ui, &self.node_set, &self.resolved_nodes, &self.voting_nodes); if picked.save_default { - match self.app_context.save_dpns_node_set(&self.node_set) { - Ok(()) => { - self.app_context.recompute_dpns_vote_attention(); - } - Err(error) => { - MessageBanner::set_global(ui.ctx(), error.to_string(), MessageType::Error) - .with_details(&error); - } - } + self.pending_preference = Some(DpnsVotingPreference::NodeSet(self.node_set.clone())); } if let Some(node_set) = picked.changed { self.apply_node_set(node_set); @@ -2429,23 +2426,17 @@ impl DPNSScreen { return AppAction::None; } let operation = DpnsVoteOperation::new(plan.aggregate.targets); - if self.confirm_timing == ConfirmTiming::BeforeEnd { - for outcome in &operation.targets { - if let VoteTiming::Scheduled(at) = outcome.target.timing - && !self - .node_overrides - .contains_key(&outcome.target.key.voter_id) - && let Err(error) = self.app_context.save_dpns_relative_schedule_label( - &outcome.target.key, - at, - self.relative_preset, - ) - { - // Display only: the row falls back to the absolute time. - tracing::debug!(?error, "Could not save a relative schedule label"); - } - } - } + let labels = + (self.confirm_timing == ConfirmTiming::BeforeEnd).then(|| RelativeScheduleLabels { + preset: self.relative_preset, + targets: operation + .targets + .iter() + .map(|outcome| &outcome.target.key) + .filter(|key| !self.node_overrides.contains_key(&key.voter_id)) + .cloned() + .collect(), + }); self.submission_error_banner.take_and_clear(); self.bulk_vote_handling_status = if has_immediate { VoteHandlingStatus::CastingVotes @@ -2460,6 +2451,7 @@ impl DPNSScreen { plan.voters, None, self.app_context.network(), + labels, ), )) } @@ -2850,6 +2842,13 @@ impl ScreenLike for DPNSScreen { { action = AppAction::BackendTask(task); } + if action == AppAction::None + && let Some(preference) = self.pending_preference.take() + { + action = AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::SaveDpnsVotingPreference(preference), + )); + } action } } diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index bc6eddb3b..a78e8b41d 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -12,7 +12,7 @@ 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; @@ -121,6 +121,8 @@ pub struct MasternodesScreen { /// 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)] @@ -159,6 +161,7 @@ impl MasternodesScreen { ), votes: DPNSScreen::new(app_context, VotesView::ToDecide), votes_arrival_refresh: false, + pending_segment_save: None, }; screen.reload(); screen @@ -179,9 +182,7 @@ impl MasternodesScreen { self.votes_arrival_refresh |= segment == MasternodesSegment::Votes && self.segment != segment; self.segment = segment; - if let Err(error) = self.app_context.set_masternodes_last_segment(segment) { - tracing::debug!(?error, "Could not remember the Masternodes segment"); - } + self.pending_segment_save = Some(segment); } /// Open Masternodes β–Έ Votes on `view`. @@ -825,6 +826,15 @@ impl ScreenLike for MasternodesScreen { 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 } @@ -1041,6 +1051,24 @@ mod tests { 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)] From ebcb70f30846b095fd4f331810a8aadd6f41e87a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:53:23 +0000 Subject: [PATCH 090/194] fix(dpns): reopen the confirm when preflight finds a vote change Preflight already refuses a first vote that has become a change since the review (DpnsVoteReviewRequired), but after the confirm started closing on submit nothing reopened it. The staged decisions stayed put and the warning only showed on the next Cast. The confirm now reopens on fresh vote state with the change warning, ready to cast again. DPN-005 is implemented. Co-Authored-By: Claude Opus 5.5 --- docs/user-stories.md | 2 +- src/backend_task/contested_names/mod.rs | 3 --- src/ui/dpns/dpns_contested_names_screen.rs | 13 +++++++++++-- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/user-stories.md b/docs/user-stories.md index c8fcde9a7..951dea17c 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -820,7 +820,7 @@ As a power user, I want to review past contests so that I can see outcomes and h - Votes β–Έ History lists finished contests with the outcome in words (went to a named requester with a copyable identifier, or locked for good), and my nodes' votes with their total weight. -### DPN-005: Vote on contested names [Gap] +### DPN-005: Vote on contested names [Implemented] **Persona:** Priya 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. diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 802dd3c54..85b70f6c4 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -783,9 +783,6 @@ impl AppContext { if !app_context.claim_dpns_vote_target(operation_id, &target.key)? { continue; } - // TODO(DPN-005): re-read the proved current choice here and, when a - // first vote has become a change, hand the batch back to the confirm - // step with the change warning instead of submitting. if let Some((status, failure)) = voting_ended_outcome(contests.get(&target.contested_name), now_ms()) { diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 6a3ad8ca1..82b10bd16 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -2552,7 +2552,12 @@ impl ScreenLike for DPNSScreen { // submission is in flight, so a failed submission must leave that // state here. Otherwise the window stays on "Submitting votes…" // with no way to retry or close it. - if matches!( + 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.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; + self.show_bulk_schedule_popup = !self.selected_votes.is_empty(); + } else if matches!( self.bulk_vote_handling_status, VoteHandlingStatus::CastingVotes | VoteHandlingStatus::SchedulingVotes ) { @@ -3858,8 +3863,12 @@ mod tests { assert!(screen.pending_vote_operation.is_none()); assert!(matches!( screen.bulk_vote_handling_status, - VoteHandlingStatus::Failed(_) + VoteHandlingStatus::NotStarted )); + assert!( + screen.show_bulk_schedule_popup, + "DPN-005: the confirm reopens with the change warning" + ); assert_eq!( screen.build_review_plan().unwrap().aggregate.targets[0].current_choice, Some(ResourceVoteChoice::Lock) From ea5f95a18295b5e7415aed4fa71ddc389645e215 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:01:45 +0000 Subject: [PATCH 091/194] fix(dpns): QA follow-ups for executor coverage, wording and refresh - An executor test drives a queued target on a contest that closed after review. The target is claimed and fails before submission as VotingEnded, and nothing is sent. Removing the check turns the test red. - A lead time under a minute reads "Less than a minute before the end" instead of "0 minutes before the end". - Opening Votes refreshes contests the way the Refresh button does, so a failure reaches the banner instead of only the log (VOTE-FR-074). - Saving a voting preference no longer waits on vote recovery, so it works offline. A test covers the task. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/contested_names/mod.rs | 110 ++++++++++++++++++++++++ src/ui/dpns/copy.rs | 5 ++ src/ui/masternodes/list_screen.rs | 12 ++- 3 files changed, 120 insertions(+), 7 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 85b70f6c4..c5fae909f 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -264,6 +264,7 @@ impl AppContext { &task, ContestedResourceTask::QueryDPNSContests | ContestedResourceTask::RefreshContestsInBackground + | ContestedResourceTask::SaveDpnsVotingPreference(_) ) { self.ensure_dpns_vote_recovery(sdk).await?; @@ -1608,6 +1609,32 @@ mod tests { } } + /// 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] @@ -2455,6 +2482,89 @@ mod tests { ); } + /// 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 = DpnsVoteOperation::new(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!( diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index dc24e4c1f..2aa8c5b95 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -407,6 +407,7 @@ pub fn confirm_button_label(transactions: usize, all_now: bool) -> String { 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(), @@ -451,6 +452,10 @@ mod tests { 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!( nodes_voted_part("Vote for Zed", 24, 51), "Vote for Zed (24 nodes, 51 votes)" diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index a78e8b41d..2dd704998 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -812,13 +812,11 @@ impl ScreenLike for MasternodesScreen { VOTES_ARRIVAL_REFRESH_MIN_GAP, ) { - let network = self.app_context.network; - action = AppAction::BackendTaskWithContext { - task: BackendTask::ContestedResourceTask( - ContestedResourceTask::RefreshContestsInBackground, - ), - context: crate::backend_task::BackendTaskContext::DpnsBackgroundRefresh { network }, - }; + // A user-visible refresh (VOTE-FR-074): failures reach the banner, + // unlike the timer's background refresh. + action = AppAction::BackendTask(BackendTask::ContestedResourceTask( + ContestedResourceTask::QueryDPNSContests, + )); } if self.votes.take_load_node_request() { self.select_segment(MasternodesSegment::Nodes); From b0a8fd0088dc1aac3dac0c197f4b83ec63f03fd9 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:07:48 +0000 Subject: [PATCH 092/194] test(dpns): pin Enter in the confirm; drop list focus on segment switch QA suspected that Enter cast the votes while Cancel had focus. It does not. egui's `egui_wants_keyboard_input()` is true for any focused widget, so the confirm's Enter shortcut stays off and Enter only activates the focused button. A test pins both sides: Enter on a focused Cancel cancels and casts nothing, and Enter with nothing focused casts (VOTE-FR-080). Leaving the Votes segment now drops the contest list's keyboard focus, so single-key shortcuts need a click in the list again (VOTE-NFR-010). Co-Authored-By: Claude Opus 5.5 --- src/ui/dpns/dpns_contested_names_screen.rs | 49 ++++++++++++++++++++++ src/ui/masternodes/list_screen.rs | 3 ++ 2 files changed, 52 insertions(+) diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 82b10bd16..9a4883544 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -1005,6 +1005,11 @@ impl DPNSScreen { self.list_focused = true; } + /// 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; + } + /// 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) { @@ -3400,6 +3405,50 @@ mod tests { assert_eq!(screen.voting_identities.len(), 1); } + /// 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_review_and_cast_window(ui); + }) + }; + let (mut screen, _dir) = voting_ui_review_fixture(); + screen.show_bulk_schedule_popup = 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.show_bulk_schedule_popup, "Enter on Cancel cancels"); + } + + screen.lock_recover().show_bulk_schedule_popup = 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" + ); + } + fn voting_ui_review_fixture() -> (DPNSScreen, tempfile::TempDir) { let (ctx, temp_dir) = kv_ctx(); let voter = masternode_identity(1, "node-one", true, ctx.network()); diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index 2dd704998..8c517f30b 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -181,6 +181,9 @@ impl MasternodesScreen { pub fn select_segment(&mut self, segment: MasternodesSegment) { self.votes_arrival_refresh |= segment == MasternodesSegment::Votes && self.segment != segment; + if segment != self.segment { + self.votes.release_list_focus(); + } self.segment = segment; self.pending_segment_save = Some(segment); } From 61c674ca2caf1eb7818effe37a61497df1b901ce Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:37:52 +0000 Subject: [PATCH 093/194] fix(dpns): do not treat an unknown contest as closed An Unknown contest skeleton (contenders never loaded) was classified as ProvedClosed because the check used `!is_votable()`. That failed queued votes as VotingEnded and could release the lock of an unconfirmed vote during reconciliation. Only a won or locked contest, or a passed deadline, now proves closure. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HNezqoMYJNU57odApsxVUH --- src/backend_task/contested_names/mod.rs | 32 +++++++++++++++++++++++++ src/model/contested_name.rs | 20 ++++++++++++++++ src/model/dpns_voting/mod.rs | 4 ++-- 3 files changed, 54 insertions(+), 2 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index c5fae909f..627b01b15 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -2482,6 +2482,38 @@ mod tests { ); } + /// 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), 5_000); + 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, availability), + None, + "observed {observed:?}: the unresolved target stays locked" + ); + } + } + /// 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). diff --git a/src/model/contested_name.rs b/src/model/contested_name.rs index b8a9d2d65..bac538c89 100644 --- a/src/model/contested_name.rs +++ b/src/model/contested_name.rs @@ -22,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)] @@ -175,6 +182,19 @@ mod tests { } } + #[test] + 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), + ] { + assert_eq!(state.is_decided(), expected, "{state:?}"); + } + } + // ---------------------------------------------------------------- // ETA humanization. // ---------------------------------------------------------------- diff --git a/src/model/dpns_voting/mod.rs b/src/model/dpns_voting/mod.rs index f6a4880c0..65fbb187a 100644 --- a/src/model/dpns_voting/mod.rs +++ b/src/model/dpns_voting/mod.rs @@ -52,7 +52,7 @@ pub enum DpnsVotePollAvailability { /// /// `now_ms` is the current wall clock in Unix milliseconds, matched against the /// contest deadline. Returns [`DpnsVotePollAvailability::MayAccept`] for a -/// contest DET has never cached. +/// contest DET has never cached or whose state is still unknown. pub fn dpns_vote_poll_availability( contest: Option<&crate::model::contested_name::ContestedName>, now_ms: u64, @@ -60,7 +60,7 @@ pub fn dpns_vote_poll_availability( let Some(contest) = contest else { return DpnsVotePollAvailability::MayAccept; }; - let decided = !contest.is_votable(); + let decided = contest.state.is_decided(); let expired = contest.end_time.is_some_and(|end| end <= now_ms); if decided || expired { DpnsVotePollAvailability::ProvedClosed From 8774488b47a27f69487e0b4e0174485eac55f58b Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:39:31 +0000 Subject: [PATCH 094/194] fix(dpns): use singular and plural vote feedback sentences A single scheduled vote read "1 votes were scheduled.", and batches that all failed the same way used singular copy. Each outcome now has a complete singular and plural sentence. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HNezqoMYJNU57odApsxVUH --- src/app.rs | 91 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 66 insertions(+), 25 deletions(-) diff --git a/src/app.rs b/src/app.rs index 788c67fcc..c5c838477 100644 --- a/src/app.rs +++ b/src/app.rs @@ -423,12 +423,14 @@ fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, MessageType, bo checking > 0, ); } + let single = target_count == 1; if counts.scheduled == target_count { - return ( - format!("{target_count} votes were scheduled."), - MessageType::Success, - false, - ); + 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 ( @@ -449,32 +451,36 @@ fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, MessageType, bo ); } if counts.rejected == target_count { - return ( - "The vote was rejected. Review the vote and try again.".to_owned(), - MessageType::Error, - false, - ); + 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 { - return ( - "This vote was not submitted. Check your connection and try again.".to_owned(), - MessageType::Error, - false, - ); + let message = 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." + }; + return (message.to_owned(), MessageType::Error, false); } if counts.not_applied == target_count { - return ( - "The submitted vote was not applied. Review the vote and try again.".to_owned(), - MessageType::Error, - false, - ); + 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 { - return ( - "The scheduled vote was cancelled. Nothing was submitted.".to_owned(), - MessageType::Info, - false, - ); + 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 ( @@ -4259,6 +4265,41 @@ mod migration_banner_tests { } } + /// 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(&[ From 6fb00e12a177a9dfdcfe59783e3a9359720a81de Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:39:31 +0000 Subject: [PATCH 095/194] fix(masternodes): singular status line for one active contest The node card rendered "1 active contests" in the unavailable, checking, and needs-a-vote states. Each now has a singular sentence. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HNezqoMYJNU57odApsxVUH --- src/ui/masternodes/card.rs | 57 ++++++++++++++++++++++++++++++++------ 1 file changed, 49 insertions(+), 8 deletions(-) diff --git a/src/ui/masternodes/card.rs b/src/ui/masternodes/card.rs index 6cd753c9b..0cc81b1df 100644 --- a/src/ui/masternodes/card.rs +++ b/src/ui/masternodes/card.rs @@ -61,6 +61,8 @@ pub fn dpns_status_line(summary: MasternodeContestSummary) -> String { if summary.vote_state == MasternodeVoteStateSummary::Unavailable { if summary.open_contest_count == 0 { "DPNS 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 {} active contests", @@ -68,18 +70,27 @@ pub fn dpns_status_line(summary: MasternodeContestSummary) -> String { ) } } else if summary.open_contest_count > 0 { + let single = summary.open_contest_count == 1; if summary.vote_state == MasternodeVoteStateSummary::Checking { - format!( - "Checking votes for {} active contests", - summary.open_contest_count - ) + if single { + "Checking votes for 1 active contest".to_owned() + } else { + format!( + "Checking votes for {} active contests", + 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 { - format!( - "{} active contests Β· 1 needs a vote", - summary.open_contest_count - ) + if single { + "1 active contest Β· 1 needs a vote".to_owned() + } else { + format!( + "{} active contests Β· 1 needs a vote", + summary.open_contest_count + ) + } } else { format!( "{} active contests Β· {} need votes", @@ -406,6 +417,36 @@ mod tests { ); } + /// 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] fn tc_fr3_10_dpns_no_open_contests() { assert_eq!( From 8b170942bcbdd142c210313af71f069db7058ccc Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:42:29 +0000 Subject: [PATCH 096/194] refactor(dpns): drop dead transition_hash and pin the journal key set DpnsVoteOutcome.transition_hash was never written or read. The journal format has not shipped on v1.0-dev yet, so removing the field now avoids carrying a dead slot in every bincode record forever. The secret-absence test checked substrings no field could produce. It now asserts the exact set of serialized keys at every depth, so any new persisted field fails the test whatever it is called. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HNezqoMYJNU57odApsxVUH --- .../04-development-plan.md | 2 +- src/model/dpns_voting/mod.rs | 53 ++++++++++++++++--- 2 files changed, 47 insertions(+), 8 deletions(-) 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 index dc7ca8483..8b81d79a3 100644 --- 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 @@ -46,7 +46,7 @@ state and submit typed drafts. - `VoteTiming { Now, Scheduled(TimestampMillis) }` - `DpnsVoteTargetStatus`: Scheduled, Queued, Submitting, Confirming, Confirmed, Unconfirmed, Rejected, FailedBeforeSubmission, NotApplied, Cancelled -- `DpnsVoteOutcome { operation_id, target, status, transition_hash, failure }` +- `DpnsVoteOutcome { operation_id, target, status, failure }` - `DpnsVoteFailure`: a pure domain enum, mapped structurally from backend errors. It never serializes `TaskError` or secrets. diff --git a/src/model/dpns_voting/mod.rs b/src/model/dpns_voting/mod.rs index 65fbb187a..51f2bcaca 100644 --- a/src/model/dpns_voting/mod.rs +++ b/src/model/dpns_voting/mod.rs @@ -284,7 +284,6 @@ pub struct DpnsVoteOutcome { pub operation_id: DpnsVoteOperationId, pub target: DpnsVoteTarget, pub status: DpnsVoteTargetStatus, - pub transition_hash: Option<[u8; 32]>, pub failure: Option, } @@ -315,7 +314,6 @@ impl DpnsVoteOperation { operation_id: id, target, status, - transition_hash: None, failure: None, } }) @@ -587,12 +585,53 @@ mod tests { /// VOTE-TC-073: the durable operation shape contains no signing material. #[test] fn serialized_operation_contains_identifiers_and_choices_only() { - let operation = DpnsVoteOperation::new(vec![target(4, 5, None, ResourceVoteChoice::Lock)]); - let serialized = serde_json::to_string(&operation).expect("serialize operation"); + 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)); + } + _ => {} + } + } - assert!(!serialized.contains("private")); - assert!(!serialized.contains("secret")); - assert!(!serialized.contains("wif")); + let operation = DpnsVoteOperation::new(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] From 5ceed0bcc1493c1e11bffdcc798c3f8e391d25e9 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:42:50 +0000 Subject: [PATCH 097/194] refactor(dpns): derive vote confirmation from the classified status The executor classified each attempt twice, once through classify_vote_attempt and again with a separate matches!. It now reads `confirmed` from the computed status so there is one source of truth. Also re-attaches the voting_ended_outcome doc comment to its function. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HNezqoMYJNU57odApsxVUH --- src/backend_task/contested_names/mod.rs | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 627b01b15..3a12404c8 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -111,11 +111,6 @@ fn classify_vote_attempt( } } -/// The outcome of a target whose contest closed before it was sent -/// (VOTE-FR-087), or `None` while the contest may still accept votes. -/// -/// Terminal for scheduled targets too: a closed poll can never accept the -/// vote, so retrying it would only fail again. /// A voting preference the UI asks the backend to persist. #[derive(Debug, Clone, PartialEq)] pub enum DpnsVotingPreference { @@ -152,6 +147,11 @@ impl AppContext { } } +/// The outcome of a target whose contest closed before it was sent +/// (VOTE-FR-087), or `None` while the contest may still accept votes. +/// +/// Terminal for scheduled targets too: a closed poll can never accept the +/// vote, so retrying it would only fail again. fn voting_ended_outcome( contest: Option<&ContestedName>, now_ms: u64, @@ -811,14 +811,11 @@ impl AppContext { ) .await; let (status, failure) = classify_vote_attempt(&attempt, target.timing); - let confirmed = matches!( - &attempt, - Ok(vote_on_dpns_name::DpnsVoteAttempt::Confirmed) - ); + let confirmed = status == DpnsVoteTargetStatus::Confirmed; let mut retryable_scheduled_error = None; match attempt { - Ok(vote_on_dpns_name::DpnsVoteAttempt::Confirmed) => { - } + // 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, From 604acc42de848d186f062e31c3ad46b3c97d1ed1 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:43:12 +0000 Subject: [PATCH 098/194] refactor(dpns): name the SubmitDpnsVoteOperation fields The variant carried five positional fields, so the Option slots (replacing scheduled key, relative labels) could be swapped silently. Named fields match the sibling CancelScheduledDpnsVote and EditScheduledDpnsVote variants. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HNezqoMYJNU57odApsxVUH --- src/backend_task/contested_names/mod.rs | 30 ++++++++++++---------- src/backend_task/mod.rs | 12 ++++----- src/ui/dpns/dpns_contested_names_screen.rs | 12 ++++----- 3 files changed, 27 insertions(+), 27 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 3a12404c8..275d00af1 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -45,15 +45,17 @@ pub enum ContestedResourceTask { /// The same contest + vote-state refresh, run by the background timer: /// partial failures are logged instead of reported to the user. RefreshContestsInBackground, - /// The last field records the relative preset of "before the end" - /// targets for display (VOTE-FR-081). - SubmitDpnsVoteOperation( - DpnsVoteOperation, - Vec, - Option, - Network, - Option, - ), + /// 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. @@ -290,14 +292,14 @@ impl AppContext { } Ok(BackendTaskSuccessResult::None) } - ContestedResourceTask::SubmitDpnsVoteOperation( + ContestedResourceTask::SubmitDpnsVoteOperation { operation, voters, replacing_scheduled_key, - _, - labels, - ) => { - if let Some(labels) = labels { + network: _, + relative_labels, + } => { + if let Some(labels) = relative_labels { self.save_relative_schedule_labels(&operation, &labels); } self.execute_dpns_vote_operation_with_recovery( diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 94ce4049f..44b942213 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -629,13 +629,11 @@ impl From<&BackendTask> for BackendTaskContext { identity_index: *identity_index, }, BackendTask::SystemTask(SystemTask::ClearNetworkDatabase) => Self::ClearNetworkDatabase, - BackendTask::ContestedResourceTask(ContestedResourceTask::SubmitDpnsVoteOperation( - operation, - _, - _, - network, - _, - )) => Self::DpnsVoteOperation { + BackendTask::ContestedResourceTask( + ContestedResourceTask::SubmitDpnsVoteOperation { + operation, network, .. + }, + ) => Self::DpnsVoteOperation { network: *network, operation_id: operation.id, }, diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 9a4883544..8721fbbf5 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -2451,13 +2451,13 @@ impl DPNSScreen { self.retry_voter = None; self.pending_vote_operation = Some(operation.id); AppAction::BackendTask(BackendTask::ContestedResourceTask( - ContestedResourceTask::SubmitDpnsVoteOperation( + ContestedResourceTask::SubmitDpnsVoteOperation { operation, - plan.voters, - None, - self.app_context.network(), - labels, - ), + voters: plan.voters, + replacing_scheduled_key: None, + network: self.app_context.network(), + relative_labels: labels, + }, )) } } From 7f14b27792b78aefa1c65a52e169d9b305ef85f8 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:45:30 +0000 Subject: [PATCH 099/194] perf(dpns): detect lock-index changes without cloning the index persist_operation cloned the whole lock index on every target transition just to compare it afterwards. Only the operation's own entries are removed and reinserted, so comparing the keys it owned before and after gives the same signal at the cost of that operation's keys alone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HNezqoMYJNU57odApsxVUH --- src/context/dpns_vote_operations/mod.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index 8697f50fc..c42965d24 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -241,8 +241,17 @@ fn persist_operation( .as_ref() .is_none_or(|previous| !previous.is_complete()); let mut locks = load_or_rebuild_lock_index(kv, network)?; - let previous_locks = locks.clone(); - locks.retain(|_, owner| *owner != operation.id); + // 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() @@ -255,6 +264,7 @@ fn persist_operation( 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) { @@ -263,7 +273,7 @@ fn persist_operation( let mut ids = load_operation_ids(kv, network)?; let new_operation = !ids.contains(&operation.id.to_bytes()); - let locks_changed = locks != previous_locks; + let locks_changed = previously_owned != now_owned; if new_operation || locks_changed { kv.put( DetScope::Global, From 8d8f4622e8f2f2a2342e8d7c6edabbdd12455625 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:49:16 +0000 Subject: [PATCH 100/194] fix(dpns): rank scheduled rows by the shared vote authority rule Scheduled Votes picked a target's row by (created_at, persisted order), while the backend and node cards use dpns_vote_authority_rank (lock holder, created_at, operation id). On a same-millisecond tie the screen could show a different result and offer different actions than the backend would act on. The projection now uses the shared rank, and the cross-consumer regression covers the Scheduled Votes rows too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HNezqoMYJNU57odApsxVUH --- src/context/dpns_vote_operations/mod.rs | 12 ++++++ src/ui/state/dpns_vote_operations.rs | 56 ++++++++++++++++++++----- 2 files changed, 57 insertions(+), 11 deletions(-) diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index c42965d24..510136090 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -1301,6 +1301,18 @@ mod tests { .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| row.journal_target.as_ref().map(|(id, _)| *id)) + .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. diff --git a/src/ui/state/dpns_vote_operations.rs b/src/ui/state/dpns_vote_operations.rs index 4935a022e..3956acc4e 100644 --- a/src/ui/state/dpns_vote_operations.rs +++ b/src/ui/state/dpns_vote_operations.rs @@ -7,8 +7,8 @@ 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, DpnsVoteTargetKey, - DpnsVoteTargetStatus, VoteTiming, + DpnsVoteAuthorityRank, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, + DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, dpns_vote_authority_rank, }; #[derive(Debug, Clone, PartialEq)] @@ -115,9 +115,9 @@ impl DpnsVoteOperationSnapshot { ) -> Vec { let mut journal_rows = BTreeMap::< (dash_sdk::platform::Identifier, String), - ((u64, usize), ScheduledDpnsVoteRow), + (DpnsVoteAuthorityRank, ScheduledDpnsVoteRow), >::new(); - for (operation_index, operation) in self.operations.iter().enumerate() { + for operation in &self.operations { for outcome in &operation.targets { let VoteTiming::Scheduled(timestamp) = outcome.target.timing else { continue; @@ -126,7 +126,8 @@ impl DpnsVoteOperationSnapshot { outcome.target.key.voter_id, outcome.target.contested_name.clone(), ); - let rank = (operation.created_at, operation_index); + let rank = + dpns_vote_authority_rank(operation.created_at, operation.id, outcome.status); if journal_rows .get(&pair) .is_some_and(|(current_rank, _)| *current_rank > rank) @@ -316,6 +317,35 @@ mod tests { ); } + /// 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!( + rows[0].journal_target.as_ref().map(|(id, _)| *id), + Some(pending.id) + ); + assert_eq!(rows[0].status, DpnsVoteTargetStatus::Scheduled); + } + fn scheduled_operation( created_at: u64, status: DpnsVoteTargetStatus, @@ -391,21 +421,25 @@ mod tests { 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_use_later_persisted_order_when_created_times_match() { - let first = scheduled_operation( + fn scheduled_rows_break_created_time_ties_on_the_operation_id() { + let mut first = scheduled_operation( 10, DpnsVoteTargetStatus::Rejected, ResourceVoteChoice::Lock, 100, ); - let second = scheduled_operation( + first.id = DpnsVoteOperationId::from_bytes([2; 16]); + let mut second = scheduled_operation( 10, DpnsVoteTargetStatus::NotApplied, ResourceVoteChoice::Abstain, 200, ); - let expected_id = second.id; + second.id = DpnsVoteOperationId::from_bytes([1; 16]); + let expected_id = first.id; let mut snapshot = DpnsVoteOperationSnapshot::default(); snapshot.replace(vec![first, second]); @@ -416,8 +450,8 @@ mod tests { rows[0].journal_target.as_ref().map(|(id, _)| *id), Some(expected_id) ); - assert_eq!(rows[0].status, DpnsVoteTargetStatus::NotApplied); - assert_eq!(rows[0].vote.unix_timestamp, 200); + 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 From 668d89c7754a3fa78a75230ab86c0630ab9c91ae Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:50:48 +0000 Subject: [PATCH 101/194] refactor(dpns): name the reviewable-failure lifecycle on the status The Rejected | FailedBeforeSubmission | NotApplied set was spelled out separately in the progress drawer and the Scheduled tab cast gate. DpnsVoteTargetStatus::is_reviewable_failure now owns that definition, next to holds_lock, with an exhaustive match so a new status forces a decision. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HNezqoMYJNU57odApsxVUH --- src/model/dpns_voting/mod.rs | 38 ++++++++++++++++++++++ src/ui/dpns/dpns_contested_names_screen.rs | 13 +++----- src/ui/dpns/progress_drawer.rs | 7 +--- 3 files changed, 44 insertions(+), 14 deletions(-) diff --git a/src/model/dpns_voting/mod.rs b/src/model/dpns_voting/mod.rs index 51f2bcaca..bb34abc92 100644 --- a/src/model/dpns_voting/mod.rs +++ b/src/model/dpns_voting/mod.rs @@ -276,6 +276,21 @@ impl DpnsVoteTargetStatus { | 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. @@ -583,6 +598,29 @@ mod tests { } /// 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) { diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 8721fbbf5..9763e343a 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -224,14 +224,11 @@ fn scheduled_vote_remove_enabled(status: DpnsVoteTargetStatus) -> bool { fn scheduled_vote_cast_enabled(status: DpnsVoteTargetStatus, dispatch_pending: bool) -> bool { !dispatch_pending - && matches!( - status, - DpnsVoteTargetStatus::Scheduled - | DpnsVoteTargetStatus::Rejected - | DpnsVoteTargetStatus::FailedBeforeSubmission - | DpnsVoteTargetStatus::Cancelled - | DpnsVoteTargetStatus::NotApplied - ) + && (status.is_reviewable_failure() + || matches!( + status, + DpnsVoteTargetStatus::Scheduled | DpnsVoteTargetStatus::Cancelled + )) } fn scheduled_vote_removal_task(row: &ScheduledDpnsVoteRow) -> ContestedResourceTask { diff --git a/src/ui/dpns/progress_drawer.rs b/src/ui/dpns/progress_drawer.rs index bfef25b9f..2ce68a4e0 100644 --- a/src/ui/dpns/progress_drawer.rs +++ b/src/ui/dpns/progress_drawer.rs @@ -70,12 +70,7 @@ pub fn row_action(outcome: &DpnsVoteOutcome) -> Option { (DpnsVoteTargetStatus::Unconfirmed, _) => Some(RowAction::CheckAgain), (_, Some(DpnsVoteFailure::VotingKeyMissing)) => Some(RowAction::AddVotingKey), (_, Some(DpnsVoteFailure::VotingEnded)) => None, - ( - DpnsVoteTargetStatus::Rejected - | DpnsVoteTargetStatus::FailedBeforeSubmission - | DpnsVoteTargetStatus::NotApplied, - _, - ) => Some(RowAction::ReviewAgain), + (status, _) if status.is_reviewable_failure() => Some(RowAction::ReviewAgain), _ => None, } } From ac884e2950705770b92cdf06597a92f6a19e9df7 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:52:04 +0000 Subject: [PATCH 102/194] perf(dpns): clone voter identities only when submitting The review sheet rebuilds ReviewPlan every frame, and each rebuild cloned a full QualifiedIdentity per casting node although rendering needs only the targets. The plan no longer carries voters; the submit click resolves and clones them once. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HNezqoMYJNU57odApsxVUH --- src/ui/dpns/dpns_contested_names_screen.rs | 33 +++++++++++++--------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 9763e343a..0433ab9aa 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -264,7 +264,6 @@ struct ReviewPlan { aggregate: AggregatePlan, /// One line per staged decision: name, choice, and the nodes casting it. decisions: Vec<(Decision, usize)>, - voters: Vec, } impl ReviewPlan { @@ -2375,17 +2374,6 @@ impl DPNSScreen { &self.node_overrides, now_ms, )?; - let casting: BTreeSet = aggregate - .targets - .iter() - .map(|target| target.key.voter_id) - .collect(); - let voters = self - .voting_identities - .iter() - .filter(|identity| casting.contains(&identity.identity.id())) - .cloned() - .collect(); let decisions = decisions .into_iter() .map(|decision| { @@ -2400,10 +2388,26 @@ impl DPNSScreen { Ok(ReviewPlan { aggregate, decisions, - voters, }) } + /// Clone the signing identities of the nodes casting in `plan`. + /// + /// Kept out of [`ReviewPlan`], which the review sheet 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() + } + fn bulk_apply_votes(&mut self) -> AppAction { let plan = match self.build_review_plan() { Ok(plan) => plan, @@ -2427,6 +2431,7 @@ impl DPNSScreen { }); return AppAction::None; } + let voters = self.casting_voters(&plan); let operation = DpnsVoteOperation::new(plan.aggregate.targets); let labels = (self.confirm_timing == ConfirmTiming::BeforeEnd).then(|| RelativeScheduleLabels { @@ -2450,7 +2455,7 @@ impl DPNSScreen { AppAction::BackendTask(BackendTask::ContestedResourceTask( ContestedResourceTask::SubmitDpnsVoteOperation { operation, - voters: plan.voters, + voters, replacing_scheduled_key: None, network: self.app_context.network(), relative_labels: labels, From 2768f70396b6f9240a4d0be18e441bcd702adb0b Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:53:51 +0000 Subject: [PATCH 103/194] perf(dpns): scope submission preflight to the operation's voters Every operation with queued targets refreshed proved vote state for all loaded masternodes, so a scheduled sweep of M operations over N nodes made M x N voter queries and unrelated slow nodes delayed each submission. Preflight now refreshes only the operation's queued voters; the all-nodes refresh stays for contest refreshes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HNezqoMYJNU57odApsxVUH --- src/backend_task/contested_names/mod.rs | 55 ++++++++++++++++++- .../contested_names/refresh_vote_states.rs | 38 +++++++++++-- 2 files changed, 88 insertions(+), 5 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 275d00af1..90bedc78a 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -609,13 +609,17 @@ impl AppContext { { // A fresh proved snapshot is a submission precondition. This also // prevents a due schedule from replaying a vote already observed. - let refreshed = self.refresh_dpns_vote_states(sdk).await.map_err(Arc::new); 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 @@ -2513,6 +2517,55 @@ mod tests { } } + /// 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). diff --git a/src/backend_task/contested_names/refresh_vote_states.rs b/src/backend_task/contested_names/refresh_vote_states.rs index d175f7a85..2a7b18834 100644 --- a/src/backend_task/contested_names/refresh_vote_states.rs +++ b/src/backend_task/contested_names/refresh_vote_states.rs @@ -10,7 +10,7 @@ use dash_sdk::dpp::voting::votes::resource_vote::accessors::v0::ResourceVoteGett 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; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; const VOTE_QUERY_PAGE_SIZE: u16 = 100; @@ -21,15 +21,45 @@ impl AppContext { &self, sdk: &Sdk, ) -> Result { - let voters = self.load_local_masternode_identities()?; + 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| { + .map(|voter_id| { let sdk = sdk.clone(); let kv = kv.clone(); async move { - let voter_id = voter.identity.id(); let result = self.publish_dpns_vote_state( &kv, voter_id, fetch_votes_for_voter(&sdk, voter_id), ).await.map_err(Arc::new); From ab99fa5c22cfa39b2624190a072f04a2448f40d5 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:57:01 +0000 Subject: [PATCH 104/194] docs(dpns): note deferred shared preflight concurrency bound Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HNezqoMYJNU57odApsxVUH --- src/backend_task/contested_names/refresh_vote_states.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/backend_task/contested_names/refresh_vote_states.rs b/src/backend_task/contested_names/refresh_vote_states.rs index 2a7b18834..91ea5560b 100644 --- a/src/backend_task/contested_names/refresh_vote_states.rs +++ b/src/backend_task/contested_names/refresh_vote_states.rs @@ -34,6 +34,9 @@ impl AppContext { /// 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. + /// + /// TODO(dpns-voting): concurrent preflights each bound their own fan-out; + /// a shared concurrency limit across callers is deferred (PR #901 review). pub(crate) async fn refresh_dpns_vote_states_for( &self, sdk: &Sdk, From 4f121ce00df234b36707e844f6709c6a191c12b0 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 2 Oct 2026 08:43:52 +0000 Subject: [PATCH 105/194] docs(dpns): align voting and username documentation with current UI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Describe Masternodes voting, identity usernames, journal storage and reconciliation accurately, and reconcile the user stories. Co-Authored-By: Codex πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 38 +++++++---- .../04-development-plan.md | 67 +++++++++++-------- docs/user-stories.md | 6 +- 3 files changed, 65 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bf859bd5..de82ad7bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -139,10 +139,11 @@ 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; + 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, a "DPNS Voting" button that opens the DPNS Active - contests screen, and β€” for evonodes only β€” a link to claim token rewards. + 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 @@ -150,17 +151,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). evonode from *Identities β†’ Load Existing Identity β†’ Show Advanced Options*, which no longer offers those identity types. -- **DPNS voting redesigned around the Active contests screen**: casting, - batching, and scheduling DPNS name-contest votes across your masternodes - now happens in one place β€” DPNS β†’ Active contests. Contests are grouped - into Needs your vote / Voted / Vote state unavailable / Not votable by - your nodes, with a Review - and cast step for casting now or scheduling later, plus a reminder that - Platform allows up to four changes after the initial vote. The - Masternodes detail screen no longer casts votes inline β€” its "DPNS - Voting" button takes you straight to Active contests instead. - Review shows each node's current and requested choice and warns when a - change uses the limited allowance; it does not claim a remaining count. +- **Username voting in Masternodes β†’ Votes**: decide name contests across + your masternodes in one place, with To decide / Voted / Scheduled / History + views, node-set selection, bulk choices, and one confirmation for the batch. + Cards show weighted tallies and your nodes' influence. 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. + Review shows each node's current and requested choice and remaining vote + changes, or Unknown when the local history cannot establish the count. + Cast now, choose a UTC time, or schedule shortly before voting ends. + A progress drawer lets you keep working while votes are sent. Uncertain results stay visible and blocked from repeat submission. Unresolved operations remain accessible after a contest closes and are not displaced by newer completed votes. Failed scheduled attempts retain @@ -172,6 +172,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Contests remain readable without a voting key, and a missing voting key can be added from the node's detail page without replacing its other keys. +- **Usernames in Identities**: check a name's availability, request it, and + follow its status without opening the voting screen. Names that need a + community vote show the non-refundable fee before payment; availability + is checked again before registration. Request status shows the timeline, + tally, and outcome, and suggests alternatives that need no vote. + Profile β†’ Usernames lists your names and requests, with a "Show as main" + choice for the username displayed when no profile display name is set. + The former DPNS tool entry is removed; old voting shortcuts open + Masternodes β†’ Votes, and old username shortcuts open Identities. + - **Wallet/identity indicator on more screens (rollout in progress)**: the wallet and identity picker previously shown only at the top of the Identity Hub now also appears at the top of the Identities, DashPay, DPNS, and 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 index 8b81d79a3..a46f1d58f 100644 --- 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 @@ -38,10 +38,12 @@ state and submit typed drafts. ## Domain model (built in #901) -`src/model/dpns_voting.rs` holds the pure, serializable types: +`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, contested_name, requested_choice, current_choice, timing }` +- `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, @@ -50,26 +52,28 @@ state and submit typed drafts. - `DpnsVoteFailure`: a pure domain enum, mapped structurally from backend errors. It never serializes `TaskError` or secrets. -2026-10-01 additions (pure, same module): +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`, `NoChangesLeft`, `NotInMasternodeList`, - `VoteStateUnavailable`). + 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(node_type) -> u32` (1 or 4) and `influence(tally, node_set_weight) - -> Option` (VOTE-FR-077). -- `relative_schedule(end_time, preset) -> Result` +- `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). -- `FailureReason::VotingEnded` for VOTE-FR-087. +- `DpnsVoteFailure::VotingEnded` in `mod.rs` for VOTE-FR-087. ## Data ownership (built in #901) -- `src/context/dpns_vote_state.rs`: proved votes per node via - `ResourceVote::fetch_many` keyed by proTxHash (not the SDK stub). Indexed by - node + poll and persisted per node scope. -- `src/context/dpns_vote_operations.rs`: journal and target locks. Persists +- `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. @@ -78,29 +82,34 @@ state and submit typed drafts. `ContestedResourceTask::SubmitDpnsVoteOperation`, `ReconcileDpnsVoteOperation`, `CastDueScheduledVotes { … }`; -`BackendTaskSuccessResult::DpnsVoteOperationUpdated(id)`. The due-schedule sweep +`BackendTaskSuccessResult::DpnsVoteOperationUpdated { network, operation_id }`. +The due-schedule sweep runs on a timer of about 60 s in `AppState::update()`. -## Execution algorithm (unchanged) +## Execution algorithm -1. Validate against proved state. +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: nonce β†’ - build β†’ persist hash β†’ broadcast β†’ wait β†’ classify. -6. A cause-less wait failure becomes Unconfirmed and is reconciled, never - rebroadcast. -7. Refresh vote state after each terminal outcome. - -2026-10-01: before dispatching a queued target, re-check the contest end time. +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 mirror terminal outcomes to legacy schedules. + +Before dispatching a queued target, re-check the contest end time. If voting has ended, mark it `FailedBeforeSubmission(VotingEnded)`. -## Reconciliation (unchanged) +## Reconciliation -Resume by transition hash when dashpay/platform#4137 lands. Meanwhile use the -proved per-identity range query starting at the exact poll ID (#4138 -workaround). Confirm only on an exact match, and stay Unconfirmed otherwise. +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 proved closed contest with no match +marks it NotApplied; while the contest can still accept votes, a missing or +different choice remains Unconfirmed. Transition-based recovery is a future +integration tracked by dashpay/platform#4137. ## Scheduling (built in #901) @@ -197,9 +206,9 @@ see below) for countdowns, presets and the chip. |---|---|---|---| | `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.rs` (+ NodeSet, ChangesLeft, influence, relative schedule) | **V** | β€” | | +| `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.rs`, new `dpns_vote_attention.rs` | **V** | β€” | | +| `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. | diff --git a/docs/user-stories.md b/docs/user-stories.md index bcca1a77b..613b71b2c 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -864,7 +864,7 @@ As a masternode operator, I want to choose which nodes vote and decide many cont - 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 always identifies that requester, by name or by identifier. +- 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. @@ -875,7 +875,7 @@ As a user, I want my identity's Display name to identify it throughout the app s - Change Display name in the identity profile. - Lists and navigation use Display name, then the main username (DPN-018), then a shortened identity ID. -- My usernames lists registered names without assigning local identity aliases. +- Profile β†’ Usernames lists registered names without assigning local identity aliases. ### DPN-009: Scheduled votes preserved across an app upgrade [Implemented] **Persona:** Priya @@ -1832,7 +1832,7 @@ As a masternode operator, I want a Refresh control on the Masternodes tab, so th - 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. -- [Gap] A background refresh keeps contest and vote state current while voting nodes are loaded (see DPN-013). +- 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 From 26ed875396a28d680da2c1a7c30979c5ace53635 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 2 Oct 2026 09:01:51 +0000 Subject: [PATCH 106/194] docs(dpns): document registration and voting review fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Codex πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index de82ad7bb..46d145e1e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -194,6 +194,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- Returning from a successful identity top-up refreshes the balance on + "Get a username" without clearing the chosen name or payment review. +- Username registration stays blocked while its payment is in progress, + even when an unrelated background task fails. Username updates preserve + concurrent changes to the identity's keys. +- Vote choices show identity handles to distinguish similar names. + "Cast now" leaves other nodes' queued votes untouched, and failed contest + refreshes can be retried. + - DPNS vote confirmation now highlights the name and chosen vote in separate blocks, explains Lock and Abstain, and separates the previous vote and timing. From 718bf6b7acf902720a0ae15cca6a58ca684db76a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 2 Oct 2026 09:11:31 +0000 Subject: [PATCH 107/194] fix(dpns): preserve registration and vote state across concurrent tasks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Correlate paid registration results, reload balances after top-ups, and merge username updates into current identity records. Restrict Cast now and failure recovery to selected targets, require voting key references, and restore manual refresh after errors. Share candidate handles and statuses, bound concurrent proof refreshes, and remove migrations for unreleased storage formats. Co-Authored-By: Codex GPT-6 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/app.rs | 31 ++- src/backend_task/contested_names/mod.rs | 78 ++++++- .../contested_names/refresh_vote_states.rs | 13 +- src/backend_task/error.rs | 14 +- src/backend_task/identity/dpns_usernames.rs | 14 +- .../identity/register_dpns_name.rs | 85 ++++++-- src/backend_task/mod.rs | 10 + src/context/dpns_vote_operations/keys.rs | 9 +- src/context/dpns_vote_operations/mod.rs | 197 ++---------------- .../dpns_vote_operations/transitions.rs | 8 +- src/context/dpns_vote_state.rs | 85 +------- src/context/mod.rs | 2 + src/model/qualified_identity/mod.rs | 38 +++- src/ui/dpns/contest_card.rs | 64 ++++-- src/ui/dpns/copy.rs | 92 +++++--- src/ui/dpns/dpns_contested_names_screen.rs | 99 +++++---- src/ui/dpns/progress_drawer.rs | 59 ++++-- src/ui/identity/register_dpns_name_screen.rs | 130 ++++++++---- src/ui/masternodes/card.rs | 21 +- src/ui/masternodes/detail_screen.rs | 13 +- tests/kittest/identity_usernames.rs | 48 ++++- tests/kittest/masternode_tab.rs | 13 +- 22 files changed, 602 insertions(+), 521 deletions(-) diff --git a/src/app.rs b/src/app.rs index c5c838477..39de8bf34 100644 --- a/src/app.rs +++ b/src/app.rs @@ -490,17 +490,32 @@ fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, MessageType, bo ); } - let remaining = target_count.saturating_sub(counts.confirmed); + let reviewable = counts.rejected + counts.failed_before_submission + counts.not_applied; let confirmed_sentence = match counts.confirmed { 0 => format!("None of the {target_count} votes were confirmed."), 1 => format!("1 of the {target_count} votes was confirmed."), confirmed => format!("{confirmed} of the {target_count} votes were confirmed."), }; - let review_sentence = match remaining { - 1 => "Review the remaining vote.".to_owned(), - remaining => format!("Review the remaining {remaining} votes."), + let review_sentence = match reviewable { + 0 => String::new(), + 1 => "Review the failed vote.".to_owned(), + count => format!("Review the {count} failed votes."), }; - let mut message = format!("{confirmed_sentence} {review_sentence}"); + let mut message = confirmed_sentence; + if !review_sentence.is_empty() { + message.push(' '); + message.push_str(&review_sentence); + } + if counts.scheduled > 0 { + message.push_str(&format!( + " Votes scheduled: {scheduled}.", + scheduled = counts.scheduled + )); + } + if counts.in_progress > 0 { + message + .push_str(" Voting is still in progress. Wait for the result before submitting again."); + } if counts.unconfirmed > 0 { message.push(' '); message.push_str(&dpns_unconfirmed_guidance(counts.unconfirmed)); @@ -4318,7 +4333,7 @@ mod migration_banner_tests { assert!(keep_visible); assert_eq!( message, - "1 of the 7 votes was confirmed. Review the remaining 6 votes. The vote was submitted, but the result could not be confirmed yet. Dash Evo Tool will keep checking. Do not submit it again." + "1 of the 7 votes was confirmed. Review the 3 failed votes. Votes scheduled: 1. The vote was submitted, but the result could not be confirmed yet. Dash Evo Tool will keep checking. Do not submit it again." ); } @@ -4356,7 +4371,7 @@ mod migration_banner_tests { assert!(!keep_visible); assert_eq!( message, - "2 of the 3 votes were confirmed. Review the remaining vote." + "2 of the 3 votes were confirmed. Review the failed vote." ); } @@ -4371,7 +4386,7 @@ mod migration_banner_tests { assert_eq!( message, - "None of the 2 votes were confirmed. Review the remaining 2 votes." + "None of the 2 votes were confirmed. Review the 2 failed votes." ); } diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 90bedc78a..8f3c24231 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -31,7 +31,7 @@ use dash_sdk::dpp::voting::votes::resource_vote::accessors::v0::ResourceVoteGett 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; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; #[cfg(test)] @@ -460,9 +460,11 @@ impl AppContext { )? { return Err(TaskError::DpnsVoteTargetBusy); } - return self + let mut operation = self .dpns_vote_operation(outcome.operation_id)? - .ok_or(TaskError::DpnsVoteOperationRecordMissing); + .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; + operation.targets.retain(|target| target.target.key == key); + return Ok(operation); } DpnsVoteTargetStatus::Unconfirmed | DpnsVoteTargetStatus::Queued @@ -593,6 +595,11 @@ impl AppContext { 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 @@ -673,6 +680,9 @@ impl AppContext { 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)?; let scheduled_votes = operation @@ -958,11 +968,16 @@ impl AppContext { sdk: &Sdk, ) -> Result { let operation_id = operation.id; + let keys = operation + .targets + .iter() + .map(|outcome| outcome.target.key.clone()) + .collect(); let result = self .execute_dpns_vote_operation(operation, voters, replacing_scheduled_key, sdk) .await; if let Err(error) = &result { - self.recover_failed_dpns_vote_operation(operation_id, error) + self.recover_failed_dpns_vote_operation(operation_id, &keys, error) .await; } result @@ -971,9 +986,12 @@ impl AppContext { async fn recover_failed_dpns_vote_operation( &self, operation_id: DpnsVoteOperationId, + keys: &BTreeSet, original_error: &TaskError, ) { - if let Err(recovery_error) = self.recover_interrupted_dpns_vote_operation(operation_id) { + if let Err(recovery_error) = + self.recover_interrupted_dpns_vote_operation(operation_id, keys) + { tracing::error!( error = %recovery_error, original_error = %original_error, @@ -1279,7 +1297,7 @@ mod tests { use dash_sdk::dpp::identity::Identity; use dash_sdk::dpp::version::PlatformVersion; use std::cell::RefCell; - use std::collections::BTreeMap; + use std::collections::{BTreeMap, BTreeSet}; fn dapi_connection_refused_error() -> TaskError { use dash_sdk::Error as SdkError; @@ -1343,6 +1361,48 @@ mod tests { ]) } + #[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 = DpnsVoteOperation::new(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, + &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(); @@ -2414,7 +2474,11 @@ mod tests { ) .expect_err("terminal operation write must fail"); context - .recover_failed_dpns_vote_operation(operation_id, &terminal_error) + .recover_failed_dpns_vote_operation( + operation_id, + &BTreeSet::from([target_key.clone()]), + &terminal_error, + ) .await; assert!(!*context.dpns_vote_recovery.lock().await); diff --git a/src/backend_task/contested_names/refresh_vote_states.rs b/src/backend_task/contested_names/refresh_vote_states.rs index 91ea5560b..954a4177e 100644 --- a/src/backend_task/contested_names/refresh_vote_states.rs +++ b/src/backend_task/contested_names/refresh_vote_states.rs @@ -34,9 +34,6 @@ impl AppContext { /// 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. - /// - /// TODO(dpns-voting): concurrent preflights each bound their own fan-out; - /// a shared concurrency limit across callers is deferred (PR #901 review). pub(crate) async fn refresh_dpns_vote_states_for( &self, sdk: &Sdk, @@ -63,9 +60,13 @@ impl AppContext { let sdk = sdk.clone(); let kv = kv.clone(); async move { - let result = self.publish_dpns_vote_state( - &kv, voter_id, fetch_votes_for_voter(&sdk, voter_id), - ).await.map_err(Arc::new); + 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"); } diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index de6df51d2..5054c0a04 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1086,7 +1086,7 @@ 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, @@ -1094,7 +1094,7 @@ pub enum TaskError { /// A DPNS vote operation or current-vote snapshot could not be persisted. #[error( - "Could not save DPNS voting progress. Check available disk space and try again." + "Could not save voting progress. Check available disk space and try again." )] DpnsVoteOperationStorage { #[source] @@ -1104,7 +1104,7 @@ pub enum TaskError { /// An indexed journal row could not be decoded, so unresolved target locks /// cannot be reconstructed safely. #[error( - "Saved DPNS voting progress is unreadable. Restart the app and retry loading. If this continues, restore a backup of the saved data before managing votes." + "Saved voting progress is unreadable. Restart the app and try loading your votes again." )] DpnsVoteOperationUnreadable { #[source] @@ -1113,18 +1113,18 @@ pub enum TaskError { /// An operation index referenced a missing row, so target locks are unknown. #[error( - "Saved DPNS voting progress is incomplete. Restart the app and retry loading. If this continues, restore a backup of the saved data before managing votes." + "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 DPNS voting progress belongs to another network. Switch back to that network or resolve the pending vote there." + "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("DPNS voting is stopping. Wait for DET to finish closing, then try again.")] + #[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. @@ -2014,7 +2014,7 @@ pub enum TaskError { IdentityLoadInProgress { identity_id: Identifier }, /// The load was invalidated by removal or a scoped target changed protection. - #[error("This node changed while its key was loading. Open the current node and try again.")] + #[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 diff --git a/src/backend_task/identity/dpns_usernames.rs b/src/backend_task/identity/dpns_usernames.rs index fd38064df..e89a098e0 100644 --- a/src/backend_task/identity/dpns_usernames.rs +++ b/src/backend_task/identity/dpns_usernames.rs @@ -217,7 +217,7 @@ impl AppContext { }) .collect(); - for mut identity in identities { + for identity in identities { let identity_id = identity.identity.id(); let previous = self.username_requests_for(&identity_id); let mut fresh: Vec = snapshots @@ -268,7 +268,7 @@ impl AppContext { tracing::warn!(?error, %identity_id, "Username requests could not be stored"); } if newly_won { - self.record_won_usernames(sdk, &mut identity).await; + self.record_won_usernames(sdk, &identity).await; } } Ok(BackendTaskSuccessResult::MyUsernameRequestsRefreshed) @@ -276,14 +276,18 @@ impl AppContext { /// Re-read the registered names of an identity that just won a vote, so the /// won name is listed and shown at once. - async fn record_won_usernames(&self, sdk: &Sdk, identity: &mut QualifiedIdentity) { + async fn record_won_usernames(&self, sdk: &Sdk, identity: &QualifiedIdentity) { match self .fetch_owned_dpns_names(sdk, identity.identity.id()) .await { Ok(names) => { - identity.dpns_names = names; - if let Err(error) = self.update_local_qualified_identity(identity) { + if let Err(error) = + self.edit_local_qualified_identity(&identity.identity.id(), |fresh| { + fresh.dpns_names = names; + Ok(()) + }) + { tracing::warn!(?error, "Won username could not be saved on the identity"); } } diff --git a/src/backend_task/identity/register_dpns_name.rs b/src/backend_task/identity/register_dpns_name.rs index 549a0f83a..ebc9396df 100644 --- a/src/backend_task/identity/register_dpns_name.rs +++ b/src/backend_task/identity/register_dpns_name.rs @@ -17,7 +17,7 @@ use dash_sdk::{ accessors::v0::DataContractV0Getters, document_type::accessors::DocumentTypeV0Getters, }, document::DocumentV0, - identity::accessors::IdentityGettersV0, + identity::accessors::{IdentityGettersV0, IdentitySettersV0}, platform_value::Bytes32, util::{hash::hash_double, strings::convert_to_homograph_safe_chars}, }, @@ -239,7 +239,7 @@ impl AppContext { async fn finish_username_registration( &self, sdk: &Sdk, - mut identity: crate::model::qualified_identity::QualifiedIdentity, + identity: crate::model::qualified_identity::QualifiedIdentity, name: &str, outcome: crate::model::dpns::DpnsRegistrationOutcome, joined_until: Option, @@ -259,34 +259,24 @@ impl AppContext { ); } - match self.fetch_owned_dpns_names(sdk, identity_id).await { - Ok(names) => identity.dpns_names = names, + 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" ); - if outcome == crate::model::dpns::DpnsRegistrationOutcome::Registered - && !identity.dpns_names.iter().any(|known| known.name == name) - { - identity.dpns_names.push(DPNSNameInfo { - name: name.to_owned(), - acquired_at: crate::utils::time::now_ms(), - }); - } + None } - } - - // Name an unnamed node after its main username, never a pending request. - let main_username = self.main_username(&identity); - identity.initialize_node_alias(None, main_username.as_deref()); + }; + 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()); - identity.identity = refreshed_identity; + refreshed_balance = Some(refreshed_identity.balance()); if actual_fee != estimated_fee { tracing::warn!( estimated_fee, @@ -302,7 +292,24 @@ impl AppContext { } }; - if let Err(error) = self.update_local_qualified_identity(&identity) { + if let Err(error) = self.edit_local_qualified_identity(&identity_id, |fresh| { + if let Some(names) = refreshed_names { + fresh.dpns_names = names; + } else if outcome == crate::model::dpns::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" @@ -402,6 +409,45 @@ mod tests { } } + #[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", + crate::model::dpns::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")); + } + /// 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. @@ -418,6 +464,7 @@ mod tests { 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( diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 44b942213..8ac288420 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -350,6 +350,8 @@ pub enum BackendTaskContext { /// 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. @@ -456,6 +458,7 @@ impl BackendTaskContext { matches!( self.operation(), Self::DpnsVoteOperation { .. } + | Self::DpnsContestRefresh | Self::DpnsScheduledVote { .. } | Self::DpnsScheduledVoteEdit { .. } | Self::ScheduledVoteSweep { .. } @@ -478,6 +481,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(_)) } @@ -643,6 +650,9 @@ impl From<&BackendTask> for BackendTaskContext { network: *network, operation_id: *operation_id, }, + BackendTask::ContestedResourceTask(ContestedResourceTask::QueryDPNSContests) => { + Self::DpnsContestRefresh + } BackendTask::MigrationTask(MigrationTask::RestoreFromPreviousVersion) => { Self::RestoreFromPreviousVersion } diff --git a/src/context/dpns_vote_operations/keys.rs b/src/context/dpns_vote_operations/keys.rs index ffd4dbc0a..c80e03de0 100644 --- a/src/context/dpns_vote_operations/keys.rs +++ b/src/context/dpns_vote_operations/keys.rs @@ -1,15 +1,12 @@ //! Key schema for the DPNS vote journal's k/v namespaces. //! -//! Every key the journal owns is built here so the on-disk layout, including -//! the v1 names still read by migration, has one definition. +//! 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 LEGACY_OPERATION_INDEX_KEY: &str = "det:dpns_vote_operations:v1"; -pub(super) const LEGACY_OPERATION_KEY_PREFIX: &str = "det:dpns_vote_operation:v1:"; 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:"; @@ -53,10 +50,6 @@ pub(super) fn operation_lock_index_dirty_key(network: Network) -> String { ) } -pub(super) fn legacy_operation_key(id: DpnsVoteOperationId) -> String { - format!("{LEGACY_OPERATION_KEY_PREFIX}{id}") -} - pub(super) fn operation_err(source: KvAdapterError) -> TaskError { TaskError::DpnsVoteOperationStorage { source } } diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index 510136090..b9d089c4b 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -64,70 +64,6 @@ fn operation_matches_network( Ok(false) } -fn migrate_legacy_operations(kv: &DetKv, network: Network) -> Result<(), TaskError> { - let legacy_ids: Vec<[u8; 16]> = kv - .get(DetScope::Global, LEGACY_OPERATION_INDEX_KEY) - .map_err(unreadable_operation_err)? - .unwrap_or_default(); - if legacy_ids.is_empty() { - return Ok(()); - } - - let mut qualified_ids = load_operation_ids(kv, network)?; - let mut qualified_changed = false; - let mut retained_legacy_ids = Vec::<[u8; 16]>::new(); - for bytes in &legacy_ids { - let bytes = *bytes; - let id = DpnsVoteOperationId::from_bytes(bytes); - if qualified_ids.contains(&bytes) { - continue; - } - let operation: DpnsVoteOperation = kv - .get(DetScope::Global, &legacy_operation_key(id)) - .map_err(unreadable_operation_err)? - .ok_or(TaskError::DpnsVoteOperationRecordMissing)?; - match operation_matches_network(&operation, network) { - Ok(false) => continue, - Err(TaskError::DpnsVoteJournalNetworkMismatch) => { - retained_legacy_ids.push(bytes); - continue; - } - Err(error) => return Err(error), - Ok(true) => {} - } - kv.put( - DetScope::Global, - &operation_lock_index_dirty_key(network), - &true, - ) - .map_err(operation_err)?; - kv.put(DetScope::Global, &operation_key(network, id), &operation) - .map_err(operation_err)?; - qualified_ids.push(bytes); - qualified_changed = true; - } - if qualified_changed { - kv.put( - DetScope::Global, - &operation_index_key(network), - &qualified_ids, - ) - .map_err(operation_err)?; - } - if retained_legacy_ids.len() != legacy_ids.len() { - kv.put( - DetScope::Global, - LEGACY_OPERATION_INDEX_KEY, - &retained_legacy_ids, - ) - .map_err(operation_err)?; - } - if qualified_changed { - rebuild_lock_index(kv, network)?; - } - Ok(()) -} - fn load_operations_read_only( kv: &DetKv, network: Network, @@ -147,7 +83,6 @@ fn load_operations_read_only( } fn load_operations(kv: &DetKv, network: Network) -> Result, TaskError> { - migrate_legacy_operations(kv, network)?; load_or_rebuild_lock_index(kv, network)?; load_operations_read_only(kv, network) } @@ -619,7 +554,7 @@ impl AppContext { Ok(dismissed) } - /// Migrate legacy journals and scheduled-vote mirrors before backend recovery. + /// Import stored scheduled votes before backend recovery. pub(crate) fn migrate_dpns_vote_operations(&self) -> Result<(), TaskError> { let (_guard, kv) = self.journal()?; let mut operations = load_operations(&kv, self.network)?; @@ -833,7 +768,7 @@ impl AppContext { pub(crate) fn recover_interrupted_dpns_vote_operations(&self) -> Result<(), TaskError> { let (_guard, kv) = self.journal()?; for mut operation in load_operations(&kv, self.network)? { - if recover_interrupted_target_statuses(&mut operation) { + if recover_interrupted_target_statuses(&mut operation, |_| true) { persist_operation(&kv, self.network, &operation)?; } } @@ -847,6 +782,7 @@ impl AppContext { pub(crate) fn recover_interrupted_dpns_vote_operation( &self, operation_id: DpnsVoteOperationId, + keys: &BTreeSet, ) -> Result<(), TaskError> { let (_guard, kv) = self.journal()?; let Some(mut operation): Option = kv @@ -855,7 +791,7 @@ impl AppContext { else { return Ok(()); }; - if recover_interrupted_target_statuses(&mut operation) { + if recover_interrupted_target_statuses(&mut operation, |key| keys.contains(key)) { persist_operation(&kv, self.network, &operation)?; } Ok(()) @@ -1845,119 +1781,6 @@ mod tests { assert!(load_operations(&kv, Network::Mainnet).unwrap().is_empty()); } - #[test] - fn legacy_journal_migrates_idempotently_into_network_namespace() { - let kv = kv(); - let operation = operation(DpnsVoteTargetStatus::Scheduled); - kv.put( - DetScope::Global, - &legacy_operation_key(operation.id), - &operation, - ) - .unwrap(); - kv.put( - DetScope::Global, - LEGACY_OPERATION_INDEX_KEY, - &vec![operation.id.to_bytes()], - ) - .unwrap(); - - assert_eq!( - load_operations(&kv, Network::Testnet).unwrap(), - vec![operation.clone()] - ); - assert_eq!( - load_operations(&kv, Network::Testnet).unwrap(), - vec![operation], - "repeating migration must not duplicate the operation" - ); - } - - #[test] - fn legacy_migration_quarantines_cross_network_row_without_blocking_siblings() { - let kv = kv(); - let mut poisoned = operation(DpnsVoteTargetStatus::Unconfirmed); - poisoned.targets[0].target.key.network = Network::Mainnet; - let mut valid = operation(DpnsVoteTargetStatus::Scheduled); - valid.targets[0].target.key.vote_poll_id = Identifier::from([3; 32]); - kv.put( - DetScope::Global, - &legacy_operation_key(poisoned.id), - &poisoned, - ) - .unwrap(); - kv.put(DetScope::Global, &legacy_operation_key(valid.id), &valid) - .unwrap(); - kv.put( - DetScope::Global, - LEGACY_OPERATION_INDEX_KEY, - &vec![poisoned.id.to_bytes(), valid.id.to_bytes()], - ) - .unwrap(); - - assert_eq!( - load_operations(&kv, Network::Testnet).unwrap(), - vec![valid.clone()] - ); - assert_eq!( - load_operations(&kv, Network::Testnet).unwrap(), - vec![valid], - "a quarantined row must not block or duplicate valid siblings on later sweeps" - ); - assert_eq!( - kv.get::>(DetScope::Global, LEGACY_OPERATION_INDEX_KEY) - .unwrap() - .unwrap_or_default(), - vec![poisoned.id.to_bytes()], - "a quarantined row must remain indexed for a correct-network migration pass" - ); - assert!( - kv.get::(DetScope::Global, &legacy_operation_key(poisoned.id)) - .unwrap() - .is_some(), - "quarantine must park the foreign record rather than delete it" - ); - - assert_eq!( - load_operations(&kv, Network::Mainnet).unwrap(), - vec![poisoned] - ); - assert_eq!( - kv.get::>(DetScope::Global, LEGACY_OPERATION_INDEX_KEY) - .unwrap() - .unwrap_or_default(), - Vec::<[u8; 16]>::new(), - "the legacy index must drop a quarantined row after correct-network migration" - ); - } - - #[test] - fn mismatched_terminal_legacy_record_is_safely_ignored() { - let kv = kv(); - let operation = operation(DpnsVoteTargetStatus::Confirmed); - kv.put( - DetScope::Global, - &legacy_operation_key(operation.id), - &operation, - ) - .unwrap(); - kv.put( - DetScope::Global, - LEGACY_OPERATION_INDEX_KEY, - &vec![operation.id.to_bytes()], - ) - .unwrap(); - - assert!(load_operations(&kv, Network::Mainnet).unwrap().is_empty()); - assert_eq!( - kv.get::>(DetScope::Global, LEGACY_OPERATION_INDEX_KEY) - .unwrap() - .unwrap_or_default(), - Vec::<[u8; 16]>::new(), - "a terminal row for another network must not be scanned again" - ); - } - /// VOTE-FR-078: the durable count advances once per vote Platform applied, /// and survives pruning of the operation that spent it. #[test] @@ -2750,7 +2573,9 @@ mod tests { #[test] fn interrupted_immediate_submission_recovers_before_submission() { let mut operation = operation(DpnsVoteTargetStatus::Submitting); - assert!(recover_interrupted_target_statuses(&mut operation)); + assert!(recover_interrupted_target_statuses(&mut operation, |_| { + true + })); assert_eq!( operation.targets[0].status, DpnsVoteTargetStatus::FailedBeforeSubmission @@ -2766,7 +2591,9 @@ mod tests { let mut operation = operation(DpnsVoteTargetStatus::Submitting); operation.targets[0].target.timing = VoteTiming::Scheduled(42); - assert!(recover_interrupted_target_statuses(&mut operation)); + assert!(recover_interrupted_target_statuses(&mut operation, |_| { + true + })); assert_eq!(operation.targets[0].status, DpnsVoteTargetStatus::Scheduled); assert_eq!( operation.targets[0].failure, @@ -2778,7 +2605,9 @@ mod tests { fn interrupted_confirmation_recovers_to_unconfirmed() { let mut operation = operation(DpnsVoteTargetStatus::Confirming); - assert!(recover_interrupted_target_statuses(&mut operation)); + assert!(recover_interrupted_target_statuses(&mut operation, |_| { + true + })); assert_eq!( operation.targets[0].status, DpnsVoteTargetStatus::Unconfirmed diff --git a/src/context/dpns_vote_operations/transitions.rs b/src/context/dpns_vote_operations/transitions.rs index 68813252a..cce5dd6e1 100644 --- a/src/context/dpns_vote_operations/transitions.rs +++ b/src/context/dpns_vote_operations/transitions.rs @@ -89,9 +89,15 @@ pub(super) fn cancel_scheduled_target( .unwrap_or(false)) } -pub(super) fn recover_interrupted_target_statuses(operation: &mut DpnsVoteOperation) -> bool { +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) = diff --git a/src/context/dpns_vote_state.rs b/src/context/dpns_vote_state.rs index 42dc07361..add96c81a 100644 --- a/src/context/dpns_vote_state.rs +++ b/src/context/dpns_vote_state.rs @@ -15,12 +15,7 @@ use std::sync::Arc; use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; -/// v1 predates network qualification, so it is one key rather than a prefix. -const LEGACY_CURRENT_VOTES_KEY: &str = "det:dpns_current_votes:v1"; const CURRENT_VOTES_KEY_PREFIX: &str = "det:dpns_current_votes:v3:"; -/// Superseded per-network prefixes, deleted on the first read that misses. -/// Bumping [`CURRENT_VOTES_KEY_PREFIX`] means adding the retired value here. -const LEGACY_CURRENT_VOTES_KEY_PREFIXES: [&str; 1] = ["det:dpns_current_votes:v2:"]; const CURRENT_VOTE_MAX_AGE_MS: u64 = 120_000; #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -115,21 +110,11 @@ fn load_snapshot( network: Network, voter_id: &Identifier, ) -> Result, TaskError> { - let scope = DetScope::Identity(&voter_id.to_buffer()); - if let Some(snapshot) = kv - .get(scope, ¤t_votes_key(network)) - .map_err(vote_state_err)? - { - return Ok(Some(snapshot)); - } - // Superseded values have no independent per-poll freshness and must be re-proved. - kv.delete(scope, LEGACY_CURRENT_VOTES_KEY) - .map_err(vote_state_err)?; - for prefix in LEGACY_CURRENT_VOTES_KEY_PREFIXES { - kv.delete(scope, &format!("{prefix}{}", network_prefix(network))) - .map_err(vote_state_err)?; - } - Ok(None) + kv.get( + DetScope::Identity(&voter_id.to_buffer()), + ¤t_votes_key(network), + ) + .map_err(vote_state_err) } fn save_snapshot( @@ -861,29 +846,6 @@ mod tests { ); } - #[test] - fn v2_snapshot_is_invalidated_without_decoding_a_new_wire_shape() { - let kv = kv(); - let voter = Identifier::from([1; 32]); - let key = "det:dpns_current_votes:v2:testnet"; - let old = ( - true, - now_ms(), - BTreeMap::<[u8; 32], ResourceVoteChoice>::new(), - ); - kv.put(DetScope::Identity(&voter.to_buffer()), key, &old) - .unwrap(); - assert_eq!(load_snapshot(&kv, Network::Testnet, &voter).unwrap(), None); - assert!( - kv.get::<(bool, u64, BTreeMap<[u8; 32], ResourceVoteChoice>)>( - DetScope::Identity(&voter.to_buffer()), - key - ) - .unwrap() - .is_none() - ); - } - #[tokio::test] async fn failed_refresh_preserves_its_typed_network_cause() { let temp = tempfile::tempdir().unwrap(); @@ -1029,43 +991,6 @@ mod tests { assert_eq!(load_snapshot(&kv, Network::Mainnet, &voter).unwrap(), None); } - #[test] - fn legacy_snapshot_is_discarded_instead_of_assigned_to_a_network() { - let kv = kv(); - let voter = Identifier::from([1; 32]); - let snapshot = StoredCurrentVotes { - available: true, - updated_at: now_ms(), - votes: BTreeMap::new(), - ..Default::default() - }; - kv.put( - DetScope::Identity(&voter.to_buffer()), - LEGACY_CURRENT_VOTES_KEY, - &snapshot, - ) - .unwrap(); - - assert_eq!(load_snapshot(&kv, Network::Testnet, &voter).unwrap(), None); - assert_eq!(load_snapshot(&kv, Network::Mainnet, &voter).unwrap(), None); - assert!( - kv.get::( - DetScope::Identity(&voter.to_buffer()), - ¤t_votes_key(Network::Testnet), - ) - .unwrap() - .is_none() - ); - assert!( - kv.get::( - DetScope::Identity(&voter.to_buffer()), - LEGACY_CURRENT_VOTES_KEY, - ) - .unwrap() - .is_none() - ); - } - #[test] fn stale_proved_snapshot_cannot_authorize_submission() { let poll = Identifier::from([2; 32]); diff --git a/src/context/mod.rs b/src/context/mod.rs index 24e894392..177c0ee53 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -264,6 +264,7 @@ pub struct AppContext { /// 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. /// Re-armed only if targeted recovery cannot persist after an executor error. pub(crate) dpns_vote_recovery: tokio::sync::Mutex, @@ -609,6 +610,7 @@ impl AppContext { contact_request_actions_in_flight: Mutex::new(HashSet::new()), dpns_vote_operation_guard: Mutex::new(()), 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(false), dpns_vote_diagnostics: Mutex::new(BTreeMap::new()), diff --git a/src/model/qualified_identity/mod.rs b/src/model/qualified_identity/mod.rs index a5d31a5b6..48f85d83c 100644 --- a/src/model/qualified_identity/mod.rs +++ b/src/model/qualified_identity/mod.rs @@ -606,16 +606,12 @@ impl QualifiedIdentity { .map_err(|e| format!("Failed to decode QualifiedIdentity: {}", e)) } - /// Whether a masternode vote signed by this identity can reach Platform. - /// - /// True only with a loaded voter identity and its public key β€” the exact - /// precondition the vote submission path enforces. Stricter than - /// [`Self::masternode_key_presence`]'s `voting` flag, which also reports a - /// bare [`Purpose::VOTING`] main key that the vote path cannot sign with. - /// Voting surfaces must gate on this, so a read-only node is refused before - /// the operator composes a vote rather than at submission time. + /// 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.is_some() + 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. @@ -2422,10 +2418,30 @@ mod masternode_key_presence_tests { /// 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 only_a_loaded_voter_identity_can_cast_a_masternode_vote() { - assert!(qi_with(true, &[]).can_cast_masternode_vote()); + 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()); } } diff --git a/src/ui/dpns/contest_card.rs b/src/ui/dpns/contest_card.rs index 550d3f8eb..ab97b42a1 100644 --- a/src/ui/dpns/contest_card.rs +++ b/src/ui/dpns/contest_card.rs @@ -34,7 +34,10 @@ pub fn card_choices(card: &VoteCard) -> Vec<(ResourceVoteChoice, String)> { .map(|contender| { ( ResourceVoteChoice::TowardsIdentity(contender.id), - format!("Vote for {name}", name = contender.name), + copy::vote_choice_label( + ResourceVoteChoice::TowardsIdentity(contender.id), + Some(&contender.name), + ), ) }) .collect(); @@ -45,18 +48,14 @@ pub fn card_choices(card: &VoteCard) -> Vec<(ResourceVoteChoice, String)> { /// Short label of a choice for node lines and summaries. pub fn choice_short_label(card: &VoteCard, choice: ResourceVoteChoice) -> String { - match choice { - ResourceVoteChoice::Lock => "Lock".to_owned(), - ResourceVoteChoice::Abstain => "Abstain".to_owned(), - ResourceVoteChoice::TowardsIdentity(id) => card - .contest - .contestants - .iter() - .flatten() - .find(|contender| contender.id == id) - .map(|contender| format!("for {name}", name = contender.name)) - .unwrap_or_else(|| "for another identity".to_owned()), - } + 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. @@ -114,7 +113,7 @@ pub fn node_label(node: Identifier, labels: &BTreeMap) -> St labels.get(&node).cloned().unwrap_or_else(|| { let encoded = node.to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58); - format!("{head}…", head = &encoded[..6]) + crate::model::identity_name::shorten_id(&encoded) }) } @@ -235,7 +234,10 @@ impl CardView<'_> { .flatten() .map(|contender| { ( - format!("Vote for {name}", name = contender.name), + copy::vote_choice_label( + ResourceVoteChoice::TowardsIdentity(contender.id), + Some(&contender.name), + ), contender.votes, ) }) @@ -345,6 +347,11 @@ impl CardView<'_> { 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)); } @@ -441,7 +448,30 @@ mod tests { 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!["Vote for alice", "Lock name", "Abstain"]); + 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] @@ -456,7 +486,7 @@ mod tests { let labels = BTreeMap::from([(Identifier::from([4; 32]), "mn-07".to_owned())]); assert_eq!( card_node_line(&card, &labels).as_deref(), - Some("Your nodes: 2 not voted Β· 1 voted Abstain Β· mn-07 has no changes left") + Some("Your nodes: 2 not voted Β· 1 voted: Abstain Β· mn-07 has no changes left") ); } diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index 2aa8c5b95..fec347bbb 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -1,13 +1,49 @@ //! User-facing sentences for the voting workspace. //! -//! Each function returns one complete translation unit with its plural pair, -//! so no caller concatenates fragments. +//! 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::{DpnsVoteFailure, DpnsVoteTargetStatus}; +/// 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 = crate::model::identity_name::shorten_id( + &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 { @@ -83,15 +119,16 @@ pub fn requests_label(contenders: usize) -> String { /// Influence line (VOTE-FR-077). pub fn influence_line(leader: &str, margin: u32, weight: u32) -> String { - let margin_votes = if margin == 1 { - "1 vote".to_owned() - } else { - format!("{margin} votes") - }; - match weight { - 1 => format!("{leader} leads by {margin_votes}. Your 1 vote can change who leads."), - weight => { - format!("{leader} leads by {margin_votes}. Your {weight} votes can change who leads.") + 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.") } } } @@ -113,7 +150,7 @@ pub fn not_voted_part(count: usize) -> String { /// One part of the node line: nodes that voted `choice`. pub fn voted_part(count: usize, choice_label: &str) -> String { - format!("{count} voted {choice_label}") + format!("{count} voted: {choice_label}") } /// One part of the node line: nodes out of changes, named when few. @@ -232,21 +269,14 @@ pub fn progress_row_status( failure: Option, ) -> &'static str { match (status, failure) { - (_, Some(DpnsVoteFailure::VotingEnded)) => "Not cast. Voting ended.", - (_, Some(DpnsVoteFailure::VotingKeyMissing)) => "Not cast. The voting key is not loaded.", - ( - DpnsVoteTargetStatus::Queued - | DpnsVoteTargetStatus::Submitting - | DpnsVoteTargetStatus::Confirming, - _, - ) => "Sending…", - (DpnsVoteTargetStatus::Unconfirmed, _) => "Still being checked. Don't submit it again.", - (DpnsVoteTargetStatus::Confirmed, _) => "Voted", - (DpnsVoteTargetStatus::Rejected, _) => "Rejected by Platform", - (DpnsVoteTargetStatus::NotApplied, _) => "Not applied", - (DpnsVoteTargetStatus::FailedBeforeSubmission, _) => "Not sent", - (DpnsVoteTargetStatus::Scheduled, _) => "Scheduled", - (DpnsVoteTargetStatus::Cancelled, _) => "Cancelled", + (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), } } @@ -260,8 +290,8 @@ pub fn needs_attention_line(attention: NeedsAttention) -> String { } match attention.failed { 0 => {} - 1 => parts.push("1 vote was not cast".to_owned()), - count => parts.push(format!("{count} votes were not cast")), + 1 => parts.push("1 vote failed".to_owned()), + count => parts.push(format!("{count} votes failed")), } match attention.missed_schedules { 0 => {} @@ -505,7 +535,7 @@ mod tests { voted_part(4, "Abstain"), no_changes_part(&["mn-07".to_owned()]), ]), - "Your nodes: 19 not voted Β· 4 voted Abstain Β· mn-07 has no changes left" + "Your nodes: 19 not voted Β· 4 voted: Abstain Β· mn-07 has no changes left" ); assert_eq!( change_warning_line(4), @@ -590,7 +620,7 @@ mod tests { DpnsVoteTargetStatus::FailedBeforeSubmission, Some(DpnsVoteFailure::VotingEnded) ), - "Not cast. Voting ended." + "Not submitted. Voting ended." ); assert_eq!( needs_attention_line(NeedsAttention { diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 0433ab9aa..319ebb27a 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -103,34 +103,11 @@ fn schedule_is_missed(status: DpnsVoteTargetStatus, timing: VoteTiming, now_ms: && matches!(timing, VoteTiming::Scheduled(timestamp) if dpns_schedule_is_overdue(timestamp, now_ms)) } -fn candidate_choice_label(candidate_name: &str) -> String { - format!("Vote for {candidate_name}") -} - fn short_identifier(identifier: Identifier) -> String { - let encoded = identifier.to_string(Encoding::Base58); - format!( - "{head}…{tail}", - head = &encoded[..6], - tail = &encoded[encoded.len() - 4..], - ) + crate::model::identity_name::shorten_id(&identifier.to_string(Encoding::Base58)) } -/// Name a vote choice for the operator. -/// -/// A `TowardsIdentity` choice falls back to the candidate's Base58 handle when -/// no name is cached: every surface that shows a vote β€” including the -/// review-and-cast sheet, which submission does not gate on a resolvable name β€” -/// must disclose which identity the vote goes to. -fn vote_choice_label(choice: ResourceVoteChoice, candidate_name: Option<&str>) -> String { - match choice { - ResourceVoteChoice::Lock => "Lock".to_owned(), - ResourceVoteChoice::Abstain => "Abstain".to_owned(), - ResourceVoteChoice::TowardsIdentity(identifier) => candidate_name - .map(candidate_choice_label) - .unwrap_or_else(|| format!("Vote for {handle}", handle = short_identifier(identifier))), - } -} +use super::copy::{target_status_label, vote_choice_label}; /// Candidate display names resolved once per refresh: contest β†’ candidate β†’ name. /// @@ -163,21 +140,6 @@ fn candidate_name_index( index } -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 => "Confirmation is still being checked", - DpnsVoteTargetStatus::Rejected => "Rejected", - DpnsVoteTargetStatus::FailedBeforeSubmission => "Not submitted", - DpnsVoteTargetStatus::NotApplied => "Not applied", - DpnsVoteTargetStatus::Cancelled => "Cancelled", - } -} - fn target_outcome_label( status: DpnsVoteTargetStatus, failure: Option, @@ -1894,7 +1856,10 @@ impl DPNSScreen { choices.extend(candidates.iter().map(|(candidate_id, name)| { ( ResourceVoteChoice::TowardsIdentity(*candidate_id), - candidate_choice_label(name), + vote_choice_label( + ResourceVoteChoice::TowardsIdentity(*candidate_id), + Some(name), + ), ) })); } @@ -2537,6 +2502,10 @@ impl ScreenLike for DPNSScreen { } 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.release_pending_on_error = match self.pending_vote_operation { Some(operation_id) => { dpns_operation_id(context, self.app_context.network()) == Some(operation_id) @@ -2875,6 +2844,18 @@ mod tests { 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); + } + fn offline_ctx() -> (Arc, tempfile::TempDir) { let temp_dir = tempfile::tempdir().expect("tempdir"); let data_dir = temp_dir.path().to_path_buf(); @@ -2935,6 +2916,7 @@ mod tests { 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; @@ -2953,6 +2935,14 @@ mod tests { 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, @@ -2960,7 +2950,7 @@ mod tests { associated_owner_key_id: None, identity_type: crate::model::qualified_identity::IdentityType::Masternode, alias: Some(alias.to_owned()), - private_keys: Default::default(), + private_keys, dpns_names: vec![], associated_wallets: std::collections::BTreeMap::new(), secret_access: None, @@ -3059,7 +3049,7 @@ mod tests { } #[test] - fn review_choice_names_the_candidate_or_falls_back_to_its_identifier() { + 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); @@ -3067,7 +3057,8 @@ mod tests { ResourceVoteChoice::TowardsIdentity(candidate_id), Some("alice"), ); - assert_eq!(named, "Vote for alice"); + assert!(named.starts_with("Vote for alice (")); + assert!(named.contains(&crate::model::identity_name::shorten_id(&encoded))); assert!(!named.contains(&encoded)); let unresolved = vote_choice_label(ResourceVoteChoice::TowardsIdentity(candidate_id), None); @@ -3151,7 +3142,13 @@ mod tests { Some("alice"), ); - assert_eq!(label, "Vote for alice"); + assert_eq!( + label, + vote_choice_label( + ResourceVoteChoice::TowardsIdentity(candidate_id), + Some("alice") + ) + ); assert!(!label.contains(&candidate_id.to_string(Encoding::Base58))); } @@ -3975,7 +3972,7 @@ mod tests { assert!(harness.query_by_label("Voted with 1 of 2 nodes").is_some()); assert!( harness - .query_by_label("Your nodes: 1 not voted Β· 1 voted Lock") + .query_by_label("Your nodes: 1 not voted Β· 1 voted: Lock name") .is_some() ); } @@ -4019,7 +4016,7 @@ mod tests { screen.rebuild_cards(); assert_eq!( screen.history_votes_cell("voted"), - "Lock (2 nodes, 5 votes)" + "Lock name (2 nodes, 5 votes)" ); assert_eq!(screen.history_votes_cell("skipped"), NODES_DID_NOT_VOTE); assert_eq!(screen.history_votes_cell("absent"), ""); @@ -4364,11 +4361,11 @@ mod tests { for label in [ "Casting 3 votes Β· 2 done Β· 0 sending Β· 1 being checked", "node-one Β· alpha.dash Β· Abstain", - "Voted", + "Confirmed", "node-two Β· alpha.dash Β· Abstain", - "Rejected by Platform", + "Rejected", "Review again", - "Still being checked. Don't submit it again.", + "Still being checked. Do not submit it again.", "Check again", ] { assert!(harness.query_by_label(label).is_some(), "missing {label}"); @@ -4586,7 +4583,7 @@ mod tests { ); assert_eq!( review_current_choice_label(Some(ResourceVoteChoice::Lock), None), - "Lock" + "Lock name" ); } diff --git a/src/ui/dpns/progress_drawer.rs b/src/ui/dpns/progress_drawer.rs index 2ce68a4e0..325f19999 100644 --- a/src/ui/dpns/progress_drawer.rs +++ b/src/ui/dpns/progress_drawer.rs @@ -14,7 +14,10 @@ use crate::ui::dpns::copy::{drawer_header, progress_row_status}; use crate::ui::theme::DashColors; 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, Align2, Id, RichText, Sense, Ui}; +use std::collections::BTreeMap; +use std::sync::Arc; const OPEN_ID: &str = "dpns_vote_progress_drawer_open"; @@ -24,11 +27,17 @@ const OPEN_ID: &str = "dpns_vote_progress_drawer_open"; pub struct DrawerState { /// Settled operations created before this time are not listed. since_ms: u64, + operations: Option>, + candidates: BTreeMap<(String, Identifier), String>, } impl DrawerState { pub fn new(since_ms: u64) -> Self { - Self { since_ms } + Self { + since_ms, + operations: None, + candidates: BTreeMap::new(), + } } /// Settled operations created before this moment are not listed. @@ -75,17 +84,6 @@ pub fn row_action(outcome: &DpnsVoteOutcome) -> Option { } } -fn choice_label(choice: ResourceVoteChoice) -> String { - match choice { - ResourceVoteChoice::Lock => "Lock".to_owned(), - ResourceVoteChoice::Abstain => "Abstain".to_owned(), - ResourceVoteChoice::TowardsIdentity(id) => { - let encoded = id.to_string(Encoding::Base58); - format!("Vote for {head}…", head = &encoded[..6]) - } - } -} - 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()); @@ -116,6 +114,30 @@ pub fn show(ctx: &egui::Context, app_context: &AppContext, state: &mut DrawerSta return AppAction::None; } let counts = progress_counts(shown.iter().copied()); + if !state + .operations + .as_ref() + .is_some_and(|previous| Arc::ptr_eq(previous, &operations)) + { + state.candidates = app_context + .all_contested_names() + .unwrap_or_default() + .into_iter() + .flat_map(|contest| { + contest + .contestants + .unwrap_or_default() + .into_iter() + .map(move |candidate| { + ( + (contest.normalized_contested_name.clone(), candidate.id), + candidate.name, + ) + }) + }) + .collect(); + state.operations = Some(Arc::clone(&operations)); + } let mut open = is_open(ctx); let mut action = AppAction::None; egui::Area::new(Id::new("dpns_vote_progress_drawer")) @@ -157,12 +179,21 @@ pub fn show(ctx: &egui::Context, app_context: &AppContext, state: &mut DrawerSta outcome.target.voter_alias.clone().unwrap_or_else(|| { let encoded = outcome.target.key.voter_id.to_string(Encoding::Base58); - format!("{head}…", head = &encoded[..6]) + crate::model::identity_name::shorten_id(&encoded) }); ui.label(format!( "{node} Β· {name}.dash Β· {choice}", name = outcome.target.contested_name, - choice = choice_label(outcome.target.requested_choice), + choice = crate::ui::dpns::copy::vote_choice_label( + outcome.target.requested_choice, + match outcome.target.requested_choice { + ResourceVoteChoice::TowardsIdentity(id) => state + .candidates + .get(&(outcome.target.contested_name.clone(), id)) + .map(String::as_str), + _ => None, + }, + ), )); let color = match progress_phase(outcome) { Some(ProgressPhase::Failed) => { diff --git a/src/ui/identity/register_dpns_name_screen.rs b/src/ui/identity/register_dpns_name_screen.rs index 3885abf55..1c0fe1aa2 100644 --- a/src/ui/identity/register_dpns_name_screen.rs +++ b/src/ui/identity/register_dpns_name_screen.rs @@ -4,7 +4,7 @@ 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::context::connection_status::OverallConnectionState; use crate::model::dpns::{ @@ -95,6 +95,8 @@ pub struct RegisterDpnsNameScreen { pub source: RegisterDpnsNameSource, /// 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, @@ -116,6 +118,8 @@ impl RegisterDpnsNameScreen { completed_fee_result: None, source, op_overlay: None, + registration_context: None, + registration_error_handled: false, check_in_flight: None, }; screen.reload_identity(); @@ -280,7 +284,10 @@ impl RegisterDpnsNameScreen { }); self.step = Step::Submitting; self.raise_progress_overlay(ctx); - AppAction::BackendTask(BackendTask::IdentityTask(task)) + 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) { @@ -704,53 +711,55 @@ pub(crate) fn status_line(ui: &mut Ui, tone: Tone, text: &str, dark_mode: bool) } impl ScreenLike for RegisterDpnsNameScreen { - fn display_message(&mut self, _message: &str, message_type: MessageType) { - // Banners are shown by AppState; this only unblocks the flow after a failure. - if matches!(message_type, MessageType::Error | MessageType::Warning) { - if self.check_in_flight.take().is_some() - && let Availability::Row { row, .. } = &mut self.availability + 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 { + self.step = Step::Confirm; + } + } + + 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; } - self.op_overlay.take_and_clear(); - if self.step == Step::Submitting { - self.step = Step::Confirm; - } + return true; } + false } - fn display_task_error(&mut self, error: &TaskError) -> bool { - match error { - TaskError::UsernameAvailabilityCheckFailed { .. } if self.step == Step::Submitting => { - // The pay-time re-check failed before anything was spent: unblock - // the confirm step and let the banner ask the user to retry. - self.op_overlay.take_and_clear(); - self.step = Step::Confirm; - false - } - TaskError::UsernameAvailabilityCheckFailed { .. } => { - let failed = self.check_in_flight.take(); - if let Availability::Row { label, row } = &mut self.availability - && *row == AvailabilityRow::Checking - && failed.as_ref() == Some(label) - { - *row = AvailabilityRow::CantCheck; - } - // The inline row explains the failure; no banner needed. - true - } - TaskError::UsernameNoLongerAvailable { availability } => { - self.op_overlay.take_and_clear(); - self.step = Step::Choose; - self.availability = Availability::Row { - label: self.label().to_owned(), - row: AvailabilityRow::Known(*availability), - }; - 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) { @@ -760,6 +769,7 @@ impl ScreenLike for RegisterDpnsNameScreen { fee_result, } => { self.op_overlay.take_and_clear(); + self.registration_context = None; self.completed_fee_result = Some(fee_result); self.step = Step::Done(outcome); } @@ -782,7 +792,7 @@ impl ScreenLike for RegisterDpnsNameScreen { } } - fn refresh_on_arrival(&mut self) { + fn refresh(&mut self) { self.reload_identity(); } @@ -876,6 +886,42 @@ impl ScreenLike for RegisterDpnsNameScreen { 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()); + } + + #[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] diff --git a/src/ui/masternodes/card.rs b/src/ui/masternodes/card.rs index 0cc81b1df..b8c94d1ee 100644 --- a/src/ui/masternodes/card.rs +++ b/src/ui/masternodes/card.rs @@ -60,13 +60,13 @@ pub fn voter_readiness_label(voting_present: bool) -> &'static str { pub fn dpns_status_line(summary: MasternodeContestSummary) -> String { if summary.vote_state == MasternodeVoteStateSummary::Unavailable { if summary.open_contest_count == 0 { - "DPNS voting status unavailable".to_owned() + "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 {} active contests", - summary.open_contest_count + "Vote state unavailable for {count} active contests", + count = summary.open_contest_count ) } } else if summary.open_contest_count > 0 { @@ -76,8 +76,8 @@ pub fn dpns_status_line(summary: MasternodeContestSummary) -> String { "Checking votes for 1 active contest".to_owned() } else { format!( - "Checking votes for {} active contests", - summary.open_contest_count + "Checking votes for {count} active contests", + count = summary.open_contest_count ) } } else if summary.needs_vote_count == 0 { @@ -87,14 +87,15 @@ pub fn dpns_status_line(summary: MasternodeContestSummary) -> String { "1 active contest Β· 1 needs a vote".to_owned() } else { format!( - "{} active contests Β· 1 needs a vote", - summary.open_contest_count + "{count} active contests Β· 1 needs a vote", + count = summary.open_contest_count ) } } else { format!( - "{} active contests Β· {} need votes", - summary.open_contest_count, summary.needs_vote_count + "{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 { @@ -524,7 +525,7 @@ mod tests { fn dpns_status_reports_unavailable_when_the_summary_read_failed() { assert_eq!( dpns_status_line(MasternodeContestSummary::unavailable()), - "DPNS voting status unavailable" + "Voting status unavailable" ); } diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index 74ecd4ee7..0e61c416a 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -193,19 +193,12 @@ impl MasternodeDetailView { /// The choice cell of a node vote row. fn node_vote_choice_label(row: &NodeVoteRow) -> String { - use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; match (row.state_known, row.choice) { (false, _) => "Vote state unavailable".to_owned(), (true, None) => "Not voted yet".to_owned(), - (true, Some(ResourceVoteChoice::Lock)) => "Lock".to_owned(), - (true, Some(ResourceVoteChoice::Abstain)) => "Abstain".to_owned(), - (true, Some(ResourceVoteChoice::TowardsIdentity(id))) => match &row.contender_name { - Some(name) => format!("Vote for {name}"), - None => format!( - "Vote for {id}", - id = shorten_id(&id.to_string(Encoding::Base58)) - ), - }, + (true, Some(choice)) => { + crate::ui::dpns::copy::vote_choice_label(choice, row.contender_name.as_deref()) + } } } diff --git a/tests/kittest/identity_usernames.rs b/tests/kittest/identity_usernames.rs index 5a57ea710..4240f6e4a 100644 --- a/tests/kittest/identity_usernames.rs +++ b/tests/kittest/identity_usernames.rs @@ -187,10 +187,16 @@ fn pay_time_recheck_returns_to_choose_with_locked_row() { let mut screen = answered(&app_context, "alice", UsernameAvailability::NeedsVote); screen.open_confirm_for_test(); let ctx = egui::Context::default(); - screen.raise_progress_overlay_for_test(&ctx); - let handled = screen.display_task_error(&TaskError::UsernameNoLongerAvailable { + 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()); @@ -676,14 +682,20 @@ fn pay_recheck_network_failure_unblocks_confirm() { let mut screen = answered(&app_context, "alice", UsernameAvailability::NeedsVote); screen.open_confirm_for_test(); let ctx = egui::Context::default(); - screen.begin_registration_for_test(&ctx); + let AppAction::BackendTaskWithContext { context, .. } = + screen.begin_registration_for_test(&ctx) + else { + panic!("expected registration"); + }; assert!( ProgressOverlay::has_global(&ctx), "precondition: overlay up" ); - let handled = screen.display_task_error(&TaskError::UsernameAvailabilityCheckFailed { + 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), @@ -830,15 +842,35 @@ fn sync_gate_alone_blocks_pay() { fn top_up_returns_with_name_kept() { with_isolated_data_dir(|| { let (_rt, app_context) = fresh_app_context(); - seed_username_identity(&app_context, 0x36, "Alex", &[], 0, true); + 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(); - harness.state_mut().refresh_on_arrival(); + 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") diff --git a/tests/kittest/masternode_tab.rs b/tests/kittest/masternode_tab.rs index 4ca92edff..b03a87507 100644 --- a/tests/kittest/masternode_tab.rs +++ b/tests/kittest/masternode_tab.rs @@ -153,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, @@ -982,6 +988,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 From 9e67385a653edec6532d986abf41729d9de7ce39 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 2 Oct 2026 10:04:40 +0000 Subject: [PATCH 108/194] test(dpns): route registration errors through dispatch context MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Exercise the registration dispatch and typed error callbacks used by AppState. Check that unrelated errors retain the overlay and matching errors release it and return to confirmation. πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- tests/kittest/register_dpns_name_screen.rs | 47 +++++++++++++++------- 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/tests/kittest/register_dpns_name_screen.rs b/tests/kittest/register_dpns_name_screen.rs index e458793e5..ace3fd03c 100644 --- a/tests/kittest/register_dpns_name_screen.rs +++ b/tests/kittest/register_dpns_name_screen.rs @@ -3,17 +3,18 @@ //! //! 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::qualified_identity::encrypted_key_storage::KeyStorage; @@ -188,24 +189,42 @@ 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::Dpns); + screen.type_label_for_test("alice"); 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()); }); } From eb94b0a754530dcea4d2b79f21b9a504ed5ebd7a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 2 Oct 2026 12:17:31 +0000 Subject: [PATCH 109/194] fix(dpns): preserve identity edits and isolate vote recovery MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep ambiguous broadcasts pending, protect confirmation from held Enter, and clear scheduled-row failures independently of bulk submissions. Share refresh progress, phase and choice labels, and complete voting copy. Co-Authored-By: Codex GPT-6 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 8 + .../02-ux-plan.md | 2 +- docs/ux-design-patterns.md | 2 +- src/app.rs | 213 +---------- src/backend_task/contested_names/mod.rs | 129 ++++++- .../contested_names/vote_on_dpns_name.rs | 9 +- .../refresh_loaded_identities_dpns_names.rs | 88 ++++- src/context/mod.rs | 15 +- src/ui/components/pill.rs | 36 +- src/ui/dpns/contest_card.rs | 4 +- src/ui/dpns/copy.rs | 348 +++++++++++++----- src/ui/dpns/dpns_contested_names_screen.rs | 120 ++++-- src/ui/identity/identity_hero_card.rs | 20 +- src/ui/identity/username_copy.rs | 47 +++ src/ui/identity/username_request_screen.rs | 50 +-- tests/kittest/identity_usernames.rs | 4 +- 16 files changed, 691 insertions(+), 404 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 72b08e2ff..f3058acc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -194,6 +194,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- Refreshing owned usernames preserves concurrent identity alias and key edits. +- Ambiguous vote broadcasts remain locked while their results are checked. Failed recovery + retries only affected targets and cannot release another active voter's claim. +- Holding Enter cannot submit the vote confirmation. Scheduled vote errors release their + own controls during bulk submissions, and card refreshes show the shared progress state. +- Username request badges reflect the joining and voting phases consistently, and voting + choices and feedback use shared labels and complete translation-ready sentences. + - Returning from a successful identity top-up refreshes the balance on "Get a username" without clearing the chosen name or payment review. - Username registration stays blocked while its payment is in progress, 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/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 a99d41620..2ca61f1c8 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, @@ -17,10 +20,7 @@ use crate::context::connection_status::{ConnectionStatus, OverallConnectionState use crate::context::feature_gate::FeatureGate; use crate::context::migration_status::{MigrationState, MigrationStep}; use crate::database::Database; -use crate::model::dpns_voting::{ - DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome, DpnsVoteOperation, - DpnsVoteTargetStatus, -}; +use crate::model::dpns_voting::{DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome}; use crate::model::settings::AppSettings; use crate::model::wallet::{TransactionConfirmation, TransactionStatus}; use crate::ui::components::passphrase_modal; @@ -328,201 +328,6 @@ fn clear_confirmed_vote_recovery_cutoff( } } -#[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. -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." - ), - } -} - -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 ( - crate::ui::dpns::copy::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 = 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." - }; - return (message.to_owned(), MessageType::Error, 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, - ); - } - - let reviewable = counts.rejected + counts.failed_before_submission + counts.not_applied; - let confirmed_sentence = match counts.confirmed { - 0 => format!("None of the {target_count} votes were confirmed."), - 1 => format!("1 of the {target_count} votes was confirmed."), - confirmed => format!("{confirmed} of the {target_count} votes were confirmed."), - }; - let review_sentence = match reviewable { - 0 => String::new(), - 1 => "Review the failed vote.".to_owned(), - count => format!("Review the {count} failed votes."), - }; - let mut message = confirmed_sentence; - if !review_sentence.is_empty() { - message.push(' '); - message.push_str(&review_sentence); - } - if counts.scheduled > 0 { - message.push_str(&format!( - " Votes scheduled: {scheduled}.", - scheduled = counts.scheduled - )); - } - if counts.in_progress > 0 { - message - .push_str(" Voting is still in progress. Wait for the result before submitting again."); - } - if counts.unconfirmed > 0 { - message.push(' '); - message.push_str(&dpns_unconfirmed_guidance(counts.unconfirmed)); - } - (message, MessageType::Warning, counts.unconfirmed > 0) -} - fn scheduled_vote_clear_feedback( outcomes: &[DpnsScheduledVoteClearOutcome], ) -> (String, MessageType) { @@ -4343,7 +4148,7 @@ mod migration_banner_tests { assert!(keep_visible); assert_eq!( message, - "1 of the 7 votes was confirmed. Review the 3 failed votes. Votes scheduled: 1. The vote was submitted, but the result could not be confirmed yet. Dash Evo Tool will keep checking. Do not submit it again." + "Vote results: 1 confirmed, 1 scheduled, 3 needing review, 1 cancelled, 0 in progress, and 1 still being checked. Review failed votes before retrying. Wait for votes in progress or still being checked; do not submit those votes again." ); } @@ -4363,7 +4168,7 @@ mod migration_banner_tests { assert!(keep_visible); assert_eq!( message, - "1 node voted on 2 names; 1 is still being checked. Dash Evo Tool will keep checking. Do not submit it again." + "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." ); } @@ -4381,12 +4186,12 @@ mod migration_banner_tests { assert!(!keep_visible); assert_eq!( message, - "2 of the 3 votes were confirmed. Review the failed vote." + "Vote results: 2 confirmed, 0 scheduled, 1 needing review, 0 cancelled, 0 in progress, and 0 still being checked. Review failed votes before retrying. Wait for votes in progress or still being checked; do not submit those votes again." ); } #[test] - fn vote_feedback_reports_no_confirmations_without_a_leading_zero() { + fn vote_feedback_reports_mixed_failures_without_confirmations() { let operation = feedback_operation(&[ DpnsVoteTargetStatus::Rejected, DpnsVoteTargetStatus::NotApplied, @@ -4396,7 +4201,7 @@ mod migration_banner_tests { assert_eq!( message, - "None of the 2 votes were confirmed. Review the 2 failed votes." + "Vote results: 0 confirmed, 0 scheduled, 2 needing review, 0 cancelled, 0 in progress, and 0 still being checked. Review failed votes before retrying. Wait for votes in progress or still being checked; do not submit those votes again." ); } diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 8f3c24231..ceefe0912 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -381,7 +381,12 @@ impl AppContext { async fn ensure_dpns_vote_recovery(self: &Arc, sdk: &Sdk) -> Result<(), TaskError> { let mut recovered = self.dpns_vote_recovery.lock().await; - if *recovered { + 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.migrate_dpns_vote_operations()?; @@ -403,7 +408,7 @@ impl AppContext { .await?; } } - *recovered = true; + recovered.initialized = true; Ok(()) } @@ -772,6 +777,8 @@ impl AppContext { 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 { @@ -795,7 +802,6 @@ impl AppContext { // One voter's targets are deliberately sequential: PutVote // obtains and consumes the same masternode nonce. - let _dispatch_guard = app_context.dpns_vote_dispatch.acquire(voter_id).await?; for target in targets { if !app_context.claim_dpns_vote_target(operation_id, &target.key)? { continue; @@ -983,14 +989,35 @@ impl AppContext { result } + /// 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_interrupted_dpns_vote_operation(operation_id, keys) + if let Err(recovery_error) = self + .recover_idle_dpns_vote_targets(operation_id, keys) + .await { tracing::error!( error = %recovery_error, @@ -998,7 +1025,13 @@ impl AppContext { operation_id = %operation_id, "Failed to persist recovery for an interrupted DPNS vote operation" ); - *self.dpns_vote_recovery.lock().await = false; + self.dpns_vote_recovery + .lock() + .await + .pending + .entry(operation_id) + .or_default() + .extend(keys.iter().cloned()); } } @@ -2418,16 +2451,16 @@ mod tests { .await .is_err() ); - assert!(!*context.dpns_vote_recovery.lock().await); + assert!(!context.dpns_vote_recovery.lock().await.initialized); context .ensure_dpns_vote_recovery(&context.sdk()) .await .unwrap(); - assert!(*context.dpns_vote_recovery.lock().await); + assert!(context.dpns_vote_recovery.lock().await.initialized); } #[tokio::test] - async fn direct_dispatch_terminal_write_failure_rearms_global_recovery() { + 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( @@ -2462,7 +2495,44 @@ mod tests { context .insert_dpns_vote_operation(&mut operation, None) .expect("persist in-flight operation"); - *context.dpns_vote_recovery.lock().await = true; + context.dpns_vote_recovery.lock().await.initialized = true; + let mut live = operation.clone(); + live.id = DpnsVoteOperation::new(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 @@ -2481,7 +2551,6 @@ mod tests { ) .await; - assert!(!*context.dpns_vote_recovery.lock().await); assert_eq!( context .dpns_vote_operation(operation_id) @@ -2492,10 +2561,40 @@ mod tests { DpnsVoteTargetStatus::Submitting ); - context - .ensure_dpns_vote_recovery(&context.sdk()) - .await - .expect("the re-armed recovery pass must succeed"); + 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) 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 7b07f8c09..24a6d055e 100644 --- a/src/backend_task/contested_names/vote_on_dpns_name.rs +++ b/src/backend_task/contested_names/vote_on_dpns_name.rs @@ -81,7 +81,7 @@ fn classify_broadcast_error(error: dash_sdk::Error) -> DpnsVoteAttempt { if rejected { DpnsVoteAttempt::Rejected(error) } else { - DpnsVoteAttempt::FailedBeforeSubmission(error) + DpnsVoteAttempt::Unconfirmed(error) } } _ => DpnsVoteAttempt::Unconfirmed(TaskError::from(error)), @@ -246,7 +246,7 @@ mod tests { } #[test] - fn cause_less_broadcast_rejection_fails_before_submission() { + fn followup_cause_less_broadcast_error_remains_unconfirmed() { let attempt = classify_broadcast_error( dash_sdk::error::StateTransitionBroadcastError { code: 1, @@ -256,10 +256,7 @@ mod tests { .into(), ); - assert!(matches!( - attempt, - DpnsVoteAttempt::FailedBeforeSubmission(_) - )); + assert!(matches!(attempt, DpnsVoteAttempt::Unconfirmed(_))); } #[test] 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 e71e926d2..e27336395 100644 --- a/src/backend_task/identity/refresh_loaded_identities_dpns_names.rs +++ b/src/backend_task/identity/refresh_loaded_identities_dpns_names.rs @@ -18,13 +18,11 @@ impl AppContext { let sdk = self.sdk.load().as_ref().clone(); - for mut qualified_identity in qualified_identities { - qualified_identity.dpns_names = self + for qualified_identity in qualified_identities { + let names = self .fetch_owned_dpns_names(&sdk, qualified_identity.identity.id()) .await?; - let main_username = self.main_username(&qualified_identity); - qualified_identity.initialize_node_alias(None, main_username.as_deref()); - self.update_local_qualified_identity(&qualified_identity)?; + self.finish_owned_names_refresh(qualified_identity, names)?; } sender @@ -35,6 +33,20 @@ impl AppContext { Ok(BackendTaskSuccessResult::RefreshedOwnedDpnsNames) } + 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, @@ -80,3 +92,69 @@ impl AppContext { .collect()) } } + +#[cfg(test)] +mod tests { + use super::*; + fn bare_identity(byte: u8) -> crate::model::qualified_identity::QualifiedIdentity { + use crate::model::qualified_identity::encrypted_key_storage::KeyStorage; + use crate::model::qualified_identity::{IdentityStatus, IdentityType, QualifiedIdentity}; + QualifiedIdentity { + identity: dash_sdk::platform::Identity::create_basic_identity( + [byte; 32].into(), + 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: 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")); + } +} diff --git a/src/context/mod.rs b/src/context/mod.rs index 177c0ee53..f4fd9fe93 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -102,6 +102,16 @@ impl Drop for ContactRequestActionClaim<'_> { /// 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>>>, @@ -266,8 +276,7 @@ pub struct AppContext { 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. - /// Re-armed only if targeted recovery cannot persist after an executor error. - pub(crate) dpns_vote_recovery: tokio::sync::Mutex, + 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, @@ -612,7 +621,7 @@ impl AppContext { 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(false), + 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), diff --git a/src/ui/components/pill.rs b/src/ui/components/pill.rs index cfffe5bf1..ff33460a1 100644 --- a/src/ui/components/pill.rs +++ b/src/ui/components/pill.rs @@ -13,9 +13,6 @@ 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 = "Waiting for vote"; - /// 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`]. @@ -48,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: &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), ) @@ -130,17 +127,22 @@ mod tests { } #[test] - fn pending_pill_renders_the_pending_label() { - let pending = waiting(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/dpns/contest_card.rs b/src/ui/dpns/contest_card.rs index ab97b42a1..072db08c6 100644 --- a/src/ui/dpns/contest_card.rs +++ b/src/ui/dpns/contest_card.rs @@ -486,7 +486,9 @@ mod tests { let labels = BTreeMap::from([(Identifier::from([4; 32]), "mn-07".to_owned())]); assert_eq!( card_node_line(&card, &labels).as_deref(), - Some("Your nodes: 2 not voted Β· 1 voted: Abstain Β· mn-07 has no changes left") + Some( + "2 of your nodes have not voted. 1 of your nodes voted: Abstain. mn-07 has no changes left." + ) ); } diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index fec347bbb..272262dec 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -5,7 +5,9 @@ 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::{DpnsVoteFailure, DpnsVoteTargetStatus}; +use crate::model::dpns_voting::{DpnsVoteFailure, DpnsVoteOperation, DpnsVoteTargetStatus}; +use crate::ui::MessageType; +use std::collections::BTreeSet; /// Candidate choice with an identity handle, including when its name is unavailable. pub fn vote_choice_label( @@ -145,39 +147,48 @@ 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 { - format!("{count} not voted") + 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 { - format!("{count} voted: {choice_label}") + 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] => 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 sending".to_owned(), - count => format!("{count} sending"), + 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 { - format!("{count} scheduled") + 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 { - format!("Your nodes: {parts}", parts = parts.join(" Β· ")) + parts.join(" ") } /// Shown when picking a decision changes earlier votes (VOTE-FR-015). @@ -206,61 +217,61 @@ pub fn sending_with_label(count: usize) -> String { /// Tray summary (VOTE-FR-086). pub fn tray_label(decisions: usize, transactions: usize) -> String { - let decisions = match decisions { - 1 => "1 decision ready".to_owned(), - count => format!("{count} decisions ready"), - }; - match transactions { - 1 => format!("{decisions} Β· 1 transaction, one per node and name"), - count => format!("{decisions} Β· {count} transactions, one per node and name"), + match (decisions, transactions) { + (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" + ), } } /// Node-set chip (VOTE-FR-075). pub fn node_set_chip_label(set_name: &str, nodes: usize, weight: u32) -> String { - let nodes = match nodes { - 1 => "1 node".to_owned(), - count => format!("{count} nodes"), - }; - let votes = match weight { - 1 => "1 vote".to_owned(), - weight => format!("{weight} votes"), - }; - format!("Vote with: {set_name} Β· {nodes} Β· {votes}") + 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 { - let voted = 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"), - }; - match checking { - 0 => format!("{voted}."), - 1 => format!( - "{voted}; 1 is still being checked. Dash Evo Tool will keep checking. Do not submit it again." - ), - checking => format!( - "{voted}; {checking} are still being checked. Dash Evo Tool will keep checking. Do not submit them again." - ), + 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 casting = match counts.total { - 1 => "Casting 1 vote".to_owned(), - total => format!("Casting {total} votes"), - }; - format!( - "{casting} Β· {done} done Β· {sending} sending Β· {checking} being checked", - done = counts.done(), - sending = counts.sending, - checking = counts.checking, - ) + 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). @@ -282,23 +293,14 @@ pub fn progress_row_status( /// `Needs attention` summary (VOTE-FR-084). pub fn needs_attention_line(attention: NeedsAttention) -> String { - let mut parts = Vec::new(); - match attention.checking { - 0 => {} - 1 => parts.push("1 vote is still being checked".to_owned()), - count => parts.push(format!("{count} votes are still being checked")), - } - match attention.failed { - 0 => {} - 1 => parts.push("1 vote failed".to_owned()), - count => parts.push(format!("{count} votes failed")), - } - match attention.missed_schedules { - 0 => {} - 1 => parts.push("1 scheduled vote was missed".to_owned()), - count => parts.push(format!("{count} scheduled votes were missed")), - } - format!("Needs attention: {parts}.", parts = parts.join(" Β· ")) + let NeedsAttention { + checking, + failed, + missed_schedules, + } = attention; + format!( + "Votes still being checked: {checking}. Failed votes: {failed}. Missed scheduled votes: {missed_schedules}." + ) } /// One part of the History `Your nodes voted` cell, e.g. @@ -407,20 +409,21 @@ pub fn excluded_nodes_line(count: usize, exclusion: NodeExclusion) -> String { /// One skipped-reason line, e.g. `2 votes: no changes left (5 of 5 votes used)`. pub fn skipped_reason_line(count: usize, reason: SkipReason) -> String { - let votes = match count { - 1 => "1 vote".to_owned(), - count => format!("{count} votes"), - }; - let reason = match reason { - SkipReason::AlreadyVoted => "the node already voted this way", - SkipReason::NoChangesLeft => "no changes left (5 of 5 votes used)", - SkipReason::VoteStateUnavailable => { - "vote state is unavailable; refresh voting to include it" + 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 (5 of 5 votes 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::AlreadyInProgress => "an earlier vote on this name is still being sent", - SkipReason::NotUsed => "you chose not to use the node", - }; - format!("{votes}: {reason}") + SkipReason::NotUsed => format!("Votes skipped: {count}. You chose not to use these nodes."), + } } /// Confirm primary button (VOTE-FR-080). @@ -472,6 +475,183 @@ pub fn changes_left_label(changes: ChangesLeft) -> String { } } +#[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." + ), + } +} + +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 = 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." + }; + return (message.to_owned(), MessageType::Error, 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, + ); + } + + let reviewable = counts.rejected + counts.failed_before_submission + counts.not_applied; + let DpnsVoteFeedbackCounts { + confirmed, + scheduled, + cancelled, + in_progress, + unconfirmed, + .. + } = counts; + let message = format!( + "Vote results: {confirmed} confirmed, {scheduled} scheduled, {reviewable} needing review, {cancelled} cancelled, {in_progress} in progress, and {unconfirmed} still being checked. Review failed votes before retrying. Wait for votes in progress or still being checked; do not submit those votes again." + ); + (message, MessageType::Warning, unconfirmed > 0) +} + #[cfg(test)] mod tests { /// History outcome and node-vote wording (frame V4). @@ -535,7 +715,7 @@ mod tests { voted_part(4, "Abstain"), no_changes_part(&["mn-07".to_owned()]), ]), - "Your nodes: 19 not voted Β· 4 voted: Abstain Β· mn-07 has no changes left" + "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), @@ -570,7 +750,7 @@ mod tests { assert_eq!(skipped_header(2), "Skipped: 2 votes"); assert_eq!( skipped_reason_line(1, SkipReason::NoChangesLeft), - "1 vote: no changes left (5 of 5 votes used)" + "Votes skipped: 1. The selected nodes have no changes left (5 of 5 votes used)." ); assert_eq!(confirm_button_label(72, true), "Cast 72 votes"); assert_eq!(confirm_button_label(1, false), "Schedule 1 vote"); @@ -598,7 +778,7 @@ mod tests { assert_eq!(batch_voted_line(24, 3, 0), "24 nodes voted on 3 names."); assert_eq!( batch_voted_line(2, 1, 1), - "2 nodes voted on 1 name; 1 is still being checked. Dash Evo Tool will keep checking. Do not submit it again." + "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." ); } @@ -628,7 +808,7 @@ mod tests { failed: 0, missed_schedules: 2, }), - "Needs attention: 1 vote is still being checked Β· 2 scheduled votes were missed." + "Votes still being checked: 1. Failed votes: 0. Missed scheduled votes: 2." ); } diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 319ebb27a..8db2da6a5 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -734,7 +734,6 @@ impl DPNSScreen { .disabled_tooltip("Contests are already being refreshed.") .clicked() { - self.refreshing_status = RefreshingStatus::Refreshing; app_action = AppAction::BackendTask(BackendTask::ContestedResourceTask( ContestedResourceTask::QueryDPNSContests, )); @@ -1162,11 +1161,14 @@ impl DPNSScreen { self.selected_cards.insert(name.clone()); } } - CardEvent::RefreshVoting => { + CardEvent::RefreshVoting + if self.refreshing_status != RefreshingStatus::Refreshing => + { self.pending_backend_task = Some(BackendTask::ContestedResourceTask( ContestedResourceTask::QueryDPNSContests, )); } + CardEvent::RefreshVoting => {} } self.focused_card = Some(name); } @@ -1849,8 +1851,14 @@ impl DPNSScreen { .and_then(|identity| identity.alias.clone()) .unwrap_or_else(|| short_identifier(row.vote.voter_id)); let mut choices = vec![ - (ResourceVoteChoice::Lock, "Lock".to_owned()), - (ResourceVoteChoice::Abstain, "Abstain".to_owned()), + ( + 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)| { @@ -2087,7 +2095,22 @@ impl DPNSScreen { } else { "Nothing can be submitted. Choose at least one node and a vote it has not already cast." }; - let can_submit = !operation_in_progress && transactions > 0; + // 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 = !operation_in_progress && transactions > 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( @@ -2203,7 +2226,9 @@ impl DPNSScreen { .current_choice .and_then(|choice| self.candidate_name(&target.contested_name, choice)), ); - ui.label(format!("{current} β†’ {requested}")); + ui.label(format!( + "Current choice: {current}. Requested choice: {requested}." + )); let timing = match target.timing { VoteTiming::Now => "Now".to_owned(), VoteTiming::Scheduled(at) => format!("{when} UTC", when = utc_minute(at)), @@ -2506,12 +2531,10 @@ impl ScreenLike for DPNSScreen { self.refreshing_status = RefreshingStatus::NotRefreshing; self.refresh_banner.take_and_clear(); } - self.release_pending_on_error = match self.pending_vote_operation { - Some(operation_id) => { - dpns_operation_id(context, self.app_context.network()) == Some(operation_id) - } - None => self.finish_scheduled_dispatch(context), - }; + 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 { @@ -2806,6 +2829,11 @@ impl ScreenLike for DPNSScreen { } } + 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 @@ -2818,11 +2846,6 @@ impl ScreenLike for DPNSScreen { self.refreshing_status = RefreshingStatus::Refreshing; } - if action == AppAction::None - && let Some(task) = self.pending_backend_task.take() - { - action = AppAction::BackendTask(task); - } if action == AppAction::None && let Some(preference) = self.pending_preference.take() { @@ -3448,6 +3471,45 @@ mod tests { ); } + #[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().show_bulk_schedule_popup); + 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()); @@ -3489,7 +3551,9 @@ mod tests { // VOTE-TC-102: the Needs attention row leads to the drawer's Check again. assert!( harness - .query_by_label("Needs attention: 1 vote is still being checked.") + .query_by_label( + "Votes still being checked: 1. Failed votes: 0. Missed scheduled votes: 0." + ) .is_some() ); assert!(harness.query_by_label("Show progress").is_some()); @@ -3776,7 +3840,7 @@ mod tests { } #[test] - fn voting_ui_manual_cast_completes_only_for_its_exact_dispatch() { + 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 { @@ -3826,19 +3890,27 @@ mod tests { 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.bulk_vote_handling_status = VoteHandlingStatus::CastingVotes; 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)); + assert!(matches!( + screen.bulk_vote_handling_status, + VoteHandlingStatus::CastingVotes + )); screen.reset_for_network_switch(); assert!(screen.pending_scheduled_actions.is_empty()); assert!(!screen.finish_scheduled_dispatch(&dispatch)); } #[test] - fn review_fixes_unavailable_contests_offer_a_visible_refresh_action() { + 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(); @@ -3859,7 +3931,11 @@ mod tests { ContestedResourceTask::QueryDPNSContests )) ) { - received_refresh.store(true, Ordering::Relaxed); + received_refresh.store( + screen.refreshing_status == RefreshingStatus::Refreshing + && screen.refresh_banner.is_some(), + Ordering::Relaxed, + ); } }); harness.run(); @@ -3972,7 +4048,7 @@ mod tests { assert!(harness.query_by_label("Voted with 1 of 2 nodes").is_some()); assert!( harness - .query_by_label("Your nodes: 1 not voted Β· 1 voted: Lock name") + .query_by_label("1 of your nodes has not voted. 1 of your nodes voted: Lock name.") .is_some() ); } diff --git a/src/ui/identity/identity_hero_card.rs b/src/ui/identity/identity_hero_card.rs index 218222a08..8e5340c38 100644 --- a/src/ui/identity/identity_hero_card.rs +++ b/src/ui/identity/identity_hero_card.rs @@ -185,7 +185,7 @@ 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. + /// name with a phase pill instead of the `No username yet` prompt. pending_username: Option, } @@ -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,7 +537,7 @@ 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: &UsernameRequest) { let name = @@ -760,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() { @@ -778,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(), @@ -788,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() { @@ -810,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/username_copy.rs b/src/ui/identity/username_copy.rs index 765409c00..2b83dd117 100644 --- a/src/ui/identity/username_copy.rs +++ b/src/ui/identity/username_copy.rs @@ -217,6 +217,53 @@ pub fn phase_label(phase: RequestPhase) -> &'static str { } } +/// Complete timeline sentences for the request status page. +pub fn requested_at_line(at: TimestampMillis) -> String { + format!("Requested on {date}.", date = format_date(at)) +} + +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) + ) + } +} + +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) + ), + _ => format!( + "The community vote ended on {date}.", + date = format_date(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::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.", + } +} + /// Second sentence of the Home request card. pub fn standing_line(standing: TallyStanding, others: usize) -> &'static str { match standing { diff --git a/src/ui/identity/username_request_screen.rs b/src/ui/identity/username_request_screen.rs index 8d502f5dc..1637f8d36 100644 --- a/src/ui/identity/username_request_screen.rs +++ b/src/ui/identity/username_request_screen.rs @@ -18,9 +18,7 @@ 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::{ - Tone, format_date, format_date_time, phase_label, what_happens_next, -}; +use crate::ui::identity::username_copy::{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::{MessageType, RootScreenType, ScreenLike}; @@ -95,19 +93,12 @@ impl UsernameRequestScreen { status_line( ui, Tone::Positive, - &format!("Requested {}", format_date(at)), + &super::username_copy::requested_at_line(at), dark_mode, ); } if let Some(join_end) = request.join_end { - let text = if joining { - format!( - "Open for other requests until {}", - format_date_time(join_end) - ) - } else { - format!("Open for other requests. Ended {}.", format_date(join_end)) - }; + let text = super::username_copy::joining_timeline_line(join_end, joining); let tone = if joining { Tone::Caution } else { @@ -116,33 +107,22 @@ impl UsernameRequestScreen { status_line(ui, tone, &text, dark_mode); } if let Some(end) = request.end { - let (tone, text) = if done { - ( - Tone::Positive, - format!("Community vote ended {}.", format_date(end)), - ) + let tone = if done { + Tone::Positive } else if voting { - ( - Tone::Caution, - format!("Community vote. Ends around {}.", format_date_time(end)), - ) + Tone::Caution } else { - ( - Tone::Neutral, - format!("Community vote until {}", format_date_time(end)), - ) + Tone::Neutral }; + let text = super::username_copy::voting_timeline_line(end, request.phase); status_line(ui, tone, &text, dark_mode); } - let (tone, result) = match request.phase { - RequestPhase::Joinable | RequestPhase::Voting => { - (Tone::Neutral, "Result: Not decided yet.") - } - RequestPhase::Won => (Tone::Positive, "Result: The name is yours."), - RequestPhase::Lost => (Tone::Negative, "Result: The name went to someone else."), - RequestPhase::Locked => (Tone::Negative, "Result: The name is locked for good."), - RequestPhase::NoWinner => (Tone::Negative, "Result: No one got the name."), + let tone = match request.phase { + RequestPhase::Joinable | RequestPhase::Voting => 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); } @@ -175,11 +155,11 @@ impl UsernameRequestScreen { ui.label(votes.to_string()); ui.end_row(); } - ui.label("Lock, so no one gets it"); + ui.label(crate::ui::dpns::copy::vote_choice_label(dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice::Lock, None)); ui.label(lock_standing); ui.label(tally.lock.to_string()); ui.end_row(); - ui.label("Abstain"); + ui.label(crate::ui::dpns::copy::vote_choice_label(dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice::Abstain, None)); ui.label(""); ui.label(tally.abstain.to_string()); ui.end_row(); diff --git a/tests/kittest/identity_usernames.rs b/tests/kittest/identity_usernames.rs index 4240f6e4a..aa67411bf 100644 --- a/tests/kittest/identity_usernames.rs +++ b/tests/kittest/identity_usernames.rs @@ -465,11 +465,11 @@ fn request_status_page_explains_the_vote() { for text in [ "Your request for @ali", "Requested ", - "Community vote. Ends around", + "The community vote ends around", "Result: Not decided yet.", "Leading", "Other request (", - "Lock, so no one gets it", + "Lock name", "Evonodes count as 4 votes.", "becomes yours automatically.", "the most recent request wins.", From 8cc95c646217c94b17a4b91d897ba12290e43fc2 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 2 Oct 2026 15:08:54 +0000 Subject: [PATCH 110/194] fix(dpns): address voting review blockers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Distinguish missing nodes and voting keys, refresh node vote rows, retain partial bulk results and scheduled retries, and align change-limit copy. Bound relative schedule metadata to journal ownership without changing existing binary vote records or uncertain safety locks. Co-Authored-By: Codex GPT-6 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 5 + .../01-requirements.md | 3 +- .../03-test-case-spec.md | 2 +- .../wireframes.html | 2 +- src/backend_task/contested_names/mod.rs | 179 +++++++++++++--- src/context/dpns_vote_operations/keys.rs | 7 + src/context/dpns_vote_operations/mod.rs | 202 ++++++++++++++++-- src/context/dpns_vote_operations/retention.rs | 28 ++- .../dpns_vote_operations/transitions.rs | 10 +- src/context/dpns_vote_preferences.rs | 70 +----- src/model/dpns_voting/mod.rs | 5 + src/ui/dpns/copy.rs | 13 +- src/ui/dpns/dpns_contested_names_screen.rs | 85 ++++++-- src/ui/masternodes/detail_screen.rs | 55 ++++- tests/kittest/masternode_tab.rs | 45 +++- 15 files changed, 557 insertions(+), 154 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e3f53dd9..d9a896731 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -194,6 +194,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- Votes distinguishes missing nodes from missing voting keys, and node detail refresh reloads cached votes. +- Bulk voting reports confirmed and failed targets together while scheduled preflight failures remain retryable. +- Relative schedule labels follow vote journal retention and clear when the scheduled time changes. +- Exhausted voting limits consistently describe four changes after the initial vote. + - Refreshing owned usernames preserves concurrent identity alias and key edits. - Ambiguous vote broadcasts remain locked while their results are checked. Failed recovery retries only affected targets and cannot release another active voter's claim. 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 index 43bb4ef3f..9881d3414 100644 --- 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 @@ -158,7 +158,7 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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 node voted outside Dash Evo Tool.` - A node with 0 left is skipped with the reason `no changes left (5 of 5 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 @@ -195,6 +195,7 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. - the timing selector and `Adjust nodes`; - primary `Cast {t} votes` / `Schedule {t} votes`. - 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 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 index 3edc42aa4..f6ebad9a5 100644 --- 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 @@ -100,7 +100,7 @@ K = kittest, B = backend test with fake SDK seam. | 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 node voted outside Dash Evo Tool.` | FR-078 | U | -| VOTE-TC-096 | Out of changes skipped | Journal 5 votes | Confirm | Node under Skipped with `no changes left (5 of 5 votes used)`; not submitted | FR-078, FR-025 | B | +| 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 | diff --git a/docs/ai-design/2026-10-01-usernames-redesign/wireframes.html b/docs/ai-design/2026-10-01-usernames-redesign/wireframes.html index dbfd53701..cf464e8a1 100644 --- a/docs/ai-design/2026-10-01-usernames-redesign/wireframes.html +++ b/docs/ai-design/2026-10-01-usernames-redesign/wireframes.html @@ -703,7 +703,7 @@

Your request for @nova is i

44 transactions, one per node and name. Voting is free for your nodes.

Skipped: 4 votes -
  • mn-07 on alice.dash: no changes left (5 of 5 votes used).
  • 3 nodes on cooltoken.dash: vote state unavailable. Refresh voting to include them.
+
  • mn-07 on alice.dash: no changes left (4 of 4 changes used).
  • 3 nodes on cooltoken.dash: vote state unavailable. Refresh voting to include them.
When

"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.

diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index ceefe0912..b813ae981 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -129,22 +129,17 @@ pub struct RelativeScheduleLabels { pub targets: std::collections::BTreeSet, } -impl AppContext { - /// Record the relative preset of each listed scheduled target. Display - /// only, so failures are logged and never block the vote. - fn save_relative_schedule_labels( - &self, - operation: &DpnsVoteOperation, - labels: &RelativeScheduleLabels, - ) { - for outcome in &operation.targets { - if let VoteTiming::Scheduled(at) = outcome.target.timing - && labels.targets.contains(&outcome.target.key) - && let Err(error) = - self.save_dpns_relative_schedule_label(&outcome.target.key, at, labels.preset) - { - tracing::debug!(?error, "Could not save a relative schedule label"); - } +/// 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); } } } @@ -293,14 +288,14 @@ impl AppContext { Ok(BackendTaskSuccessResult::None) } ContestedResourceTask::SubmitDpnsVoteOperation { - operation, + mut operation, voters, replacing_scheduled_key, network: _, relative_labels, } => { if let Some(labels) = relative_labels { - self.save_relative_schedule_labels(&operation, &labels); + set_relative_schedule_labels(&mut operation, &labels); } self.execute_dpns_vote_operation_with_recovery( operation, @@ -677,7 +672,14 @@ impl AppContext { &key, DpnsCurrentVoteState::Unavailable, )?; - preflight_error.get_or_insert(source); + // 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); + } } } @@ -1394,6 +1396,123 @@ mod tests { ]) } + #[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 = DpnsVoteOperation::new(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("1 confirmed") && message.contains("1 needing review"), + "{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(Some(operation.id), &key, "alice") + .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 [ @@ -1750,14 +1869,20 @@ mod tests { .map(|outcome| outcome.target.key.clone()) .collect(), }; - context.save_relative_schedule_labels(&operation, &labels); - let alice = &operation.targets[0].target.key; - let bob = &operation.targets[1].target.key; - assert_eq!( - context.dpns_relative_schedule_label(alice, 9_000), - Some(preset) - ); - assert_eq!(context.dpns_relative_schedule_label(bob, 9_000), None); + 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] diff --git a/src/context/dpns_vote_operations/keys.rs b/src/context/dpns_vote_operations/keys.rs index c80e03de0..e12f7de09 100644 --- a/src/context/dpns_vote_operations/keys.rs +++ b/src/context/dpns_vote_operations/keys.rs @@ -13,6 +13,8 @@ pub(super) const OPERATION_LOCK_INDEX_KEY_PREFIX: &str = "det:dpns_vote_operatio 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 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:"; @@ -57,3 +59,8 @@ pub(super) fn operation_err(source: KvAdapterError) -> TaskError { 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) +} diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index b9d089c4b..e1a479135 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -37,6 +37,58 @@ type DpnsVoteLockIndex = BTreeMap; type DpnsVoteDiagnosticMap = BTreeMap<(DpnsVoteOperationId, DpnsVoteTargetKey), (u64, Arc)>; +type RelativeSchedulePresets = 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"), + } + Ok(Some(operation)) +} + +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()) @@ -71,8 +123,7 @@ fn load_operations_read_only( let mut operations = Vec::new(); for bytes in load_operation_ids(kv, network)? { let id = DpnsVoteOperationId::from_bytes(bytes); - let operation: DpnsVoteOperation = kv - .get(DetScope::Global, &operation_key(network, id)) + 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)? { @@ -100,8 +151,7 @@ fn rebuild_lock_index(kv: &DetKv, network: Network) -> Result(DetScope::Global, &operation_key(network, operation.id)) + load_operation(kv, &operation_key(network, operation.id)) .map_err(unreadable_operation_err)? } else { None @@ -236,6 +286,7 @@ fn persist_operation( 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, @@ -370,8 +421,7 @@ fn operation_for_schedule_edit( if locks.get(&edit.key) != Some(&id) { return Err(TaskError::DpnsScheduledVoteNotEditable); } - let operation: DpnsVoteOperation = kv - .get(DetScope::Global, &operation_key(network, id)) + 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| { @@ -435,6 +485,9 @@ impl AppContext { .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; let mirror = ScheduledDPNSVote { @@ -502,9 +555,7 @@ impl AppContext { persist_operation(&kv, self.network, operation)?; } // A repeated terminal update may have been retired by retention. - match kv - .get::(DetScope::Global, &operation_key(self.network, operation.id)) - { + match load_operation(&kv, &operation_key(self.network, operation.id)) { Ok(Some(_)) => {} Ok(None) => return Ok(None), Err(error) => return Ok(Some(unreadable_operation_err(error))), @@ -614,9 +665,7 @@ impl AppContext { id: DpnsVoteOperationId, ) -> Result, TaskError> { let _guard = self.journal_guard(); - let operation = self - .det_kv()? - .get(DetScope::Global, &operation_key(self.network, id)) + 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)? => { @@ -785,9 +834,9 @@ impl AppContext { keys: &BTreeSet, ) -> Result<(), TaskError> { let (_guard, kv) = self.journal()?; - let Some(mut operation): Option = kv - .get(DetScope::Global, &operation_key(self.network, operation_id)) - .map_err(unreadable_operation_err)? + let Some(mut operation): Option = + load_operation(&kv, &operation_key(self.network, operation_id)) + .map_err(unreadable_operation_err)? else { return Ok(()); }; @@ -1767,6 +1816,98 @@ mod tests { 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(); @@ -2081,6 +2222,7 @@ mod tests { "det:scheduled_vote:", OPERATION_KEY_PREFIX, SCHEDULE_DISMISSAL_KEY_PREFIX, + RELATIVE_LABEL_KEY_PREFIX, ] { let dir = tempfile::tempdir().unwrap(); let store = Arc::new(FailingKv::default()); @@ -2100,6 +2242,7 @@ mod tests { &format!("cleanup-{index}"), ); completed.created_at = index; + completed.targets[0].relative_schedule_preset_ms = Some(600_000); if index == 0 { oldest = Some(completed.clone()); dismiss_scheduled_target( @@ -2277,10 +2420,14 @@ mod tests { 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(); @@ -2288,15 +2435,36 @@ mod tests { operation_id: Some(scheduled.id), key: scheduled.targets[0].target.key.clone(), expected_choice: ResourceVoteChoice::Lock, - expected_timestamp: 42, + 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, error) = context.edit_scheduled_dpns_vote_target(&edit).unwrap(); assert_eq!(id, scheduled.id); assert!(error.is_none()); 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 diff --git a/src/context/dpns_vote_operations/retention.rs b/src/context/dpns_vote_operations/retention.rs index 3aef4cdca..d67a5ab18 100644 --- a/src/context/dpns_vote_operations/retention.rs +++ b/src/context/dpns_vote_operations/retention.rs @@ -1,4 +1,4 @@ -//! Retention for completed vote batches and their dismissal sidecars. +//! 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. @@ -225,6 +225,7 @@ pub(super) fn prune_completed_history( 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. @@ -243,15 +244,18 @@ pub(super) fn prune_orphaned_schedule_dismissals( .into_iter() .filter_map(|key| key.strip_prefix(&operation_prefix).map(str::to_owned)) .collect::>(); - for key in kv - .list(DetScope::Global, Some(&dismissal_prefix)) - .map_err(unreadable_operation_err)? - { - if key - .strip_prefix(&dismissal_prefix) - .is_some_and(|suffix| !live_suffixes.contains(suffix)) + let relative_prefix = format!("{RELATIVE_LABEL_KEY_PREFIX}{}:", network_prefix(network)); + for prefix in [dismissal_prefix, relative_prefix] { + for key in kv + .list(DetScope::Global, Some(&prefix)) + .map_err(unreadable_operation_err)? { - kv.delete(DetScope::Global, &key).map_err(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(()) @@ -272,6 +276,12 @@ pub(super) fn delete_terminal_operations( ) .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, &operation_key(network, *id)) .map_err(operation_err)?; kv.delete(DetScope::Global, &schedule_dismissal_key(network, *id)) diff --git a/src/context/dpns_vote_operations/transitions.rs b/src/context/dpns_vote_operations/transitions.rs index cce5dd6e1..a10e89dee 100644 --- a/src/context/dpns_vote_operations/transitions.rs +++ b/src/context/dpns_vote_operations/transitions.rs @@ -4,13 +4,13 @@ //! status untouched, so a target can only ever advance along one path. use super::keys::*; -use super::persist_operation; +use super::{load_operation, persist_operation}; use crate::backend_task::error::TaskError; use crate::model::dpns_voting::{ DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTargetKey, DpnsVoteTargetStatus, failed_before_broadcast_outcome, }; -use crate::wallet_backend::{DetKv, DetScope}; +use crate::wallet_backend::DetKv; use dash_sdk::dpp::dashcore::Network; /// What [`with_target`] should do once its mutator has inspected an outcome. @@ -34,9 +34,9 @@ pub(super) fn with_target( key: &DpnsVoteTargetKey, mutate: impl FnOnce(&mut DpnsVoteOutcome) -> TargetUpdate, ) -> Result, TaskError> { - let Some(mut operation): Option = kv - .get(DetScope::Global, &operation_key(network, operation_id)) - .map_err(unreadable_operation_err)? + let Some(mut operation): Option = + load_operation(kv, &operation_key(network, operation_id)) + .map_err(unreadable_operation_err)? else { return Ok(None); }; diff --git a/src/context/dpns_vote_preferences.rs b/src/context/dpns_vote_preferences.rs index 24f70bb8d..e0d49d2b2 100644 --- a/src/context/dpns_vote_preferences.rs +++ b/src/context/dpns_vote_preferences.rs @@ -1,20 +1,16 @@ //! Per-network operator preferences for masternode voting: the last-used -//! Masternodes segment, the saved node set, and the display label of -//! relative ("before the end") schedules. +//! 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::DpnsVoteTargetKey; use crate::model::dpns_voting::operator::{MasternodesSegment, NodeSet}; use crate::wallet_backend::DetScope; use dash_sdk::dpp::dashcore::Network; -use dash_sdk::dpp::identity::TimestampMillis; use serde::Serialize; use serde::de::DeserializeOwned; -use std::time::Duration; fn segment_key(network: Network) -> String { format!("{network}:dpns_voting:masternodes_segment") @@ -24,22 +20,6 @@ fn node_set_key(network: Network) -> String { format!("{network}:dpns_voting:node_set") } -/// Keyed by the absolute time too: an edit to another time orphans the label, -/// and the row falls back to the absolute time alone. The target is hashed to -/// fit the store's key-length limit. -fn relative_label_key(key: &DpnsVoteTargetKey, scheduled_at: TimestampMillis) -> String { - use dash_sdk::dpp::dashcore::hashes::{Hash, sha256}; - let mut preimage = Vec::with_capacity(72); - preimage.extend_from_slice(key.voter_id.as_bytes()); - preimage.extend_from_slice(key.vote_poll_id.as_bytes()); - preimage.extend_from_slice(&scheduled_at.to_be_bytes()); - format!( - "{network}:dpns_voting:relative:{digest}", - network = key.network, - digest = sha256::Hash::hash(&preimage), - ) -} - impl AppContext { fn voting_preference(&self, key: &str) -> Result, TaskError> { self.app_kv().get(DetScope::Global, key).map_err(|source| { @@ -81,32 +61,6 @@ impl AppContext { pub fn save_dpns_node_set(&self, node_set: &NodeSet) -> Result<(), TaskError> { self.put_voting_preference(&node_set_key(self.network()), node_set) } - - /// Remember that the target scheduled at `scheduled_at` was picked as - /// `preset` before its contest's end (VOTE-FR-081). Display only: the - /// absolute time in the journal stays authoritative. - pub fn save_dpns_relative_schedule_label( - &self, - key: &DpnsVoteTargetKey, - scheduled_at: TimestampMillis, - preset: Duration, - ) -> Result<(), TaskError> { - let preset_ms = u64::try_from(preset.as_millis()).unwrap_or(u64::MAX); - self.put_voting_preference(&relative_label_key(key, scheduled_at), &preset_ms) - } - - /// The relative preset a scheduled target was picked with, if recorded. - pub fn dpns_relative_schedule_label( - &self, - key: &DpnsVoteTargetKey, - scheduled_at: TimestampMillis, - ) -> Option { - self.voting_preference::(&relative_label_key(key, scheduled_at)) - .inspect_err(|error| tracing::debug!(?error, "Relative schedule label unreadable")) - .ok() - .flatten() - .map(Duration::from_millis) - } } #[cfg(test)] @@ -115,28 +69,6 @@ mod tests { use dash_sdk::platform::Identifier; use std::collections::BTreeSet; - /// VOTE-TC-067 (label half): the label is bound to the exact time; a - /// different time reads no label, so the row shows the absolute time only. - #[test] - fn relative_label_is_bound_to_its_absolute_time() { - let temp_dir = tempfile::tempdir().expect("tempdir"); - let context = crate::context::test_support::test_app_context(temp_dir.path()); - let key = DpnsVoteTargetKey { - network: context.network(), - voter_id: Identifier::from([1; 32]), - vote_poll_id: Identifier::from([2; 32]), - }; - let six_hours = Duration::from_secs(6 * 3600); - context - .save_dpns_relative_schedule_label(&key, 1_000, six_hours) - .expect("save label"); - assert_eq!( - context.dpns_relative_schedule_label(&key, 1_000), - Some(six_hours) - ); - assert_eq!(context.dpns_relative_schedule_label(&key, 2_000), None); - } - #[test] fn keys_are_network_scoped() { assert_ne!(segment_key(Network::Mainnet), segment_key(Network::Testnet)); diff --git a/src/model/dpns_voting/mod.rs b/src/model/dpns_voting/mod.rs index bb34abc92..0f06fc938 100644 --- a/src/model/dpns_voting/mod.rs +++ b/src/model/dpns_voting/mod.rs @@ -300,6 +300,10 @@ pub struct DpnsVoteOutcome { 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, } /// Reviewed voting batch stored before its first broadcast. @@ -330,6 +334,7 @@ impl DpnsVoteOperation { target, status, failure: None, + relative_schedule_preset_ms: None, } }) .collect::>(); diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index 272262dec..08d3859de 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -407,14 +407,14 @@ pub fn excluded_nodes_line(count: usize, exclusion: NodeExclusion) -> String { } } -/// One skipped-reason line, e.g. `2 votes: no changes left (5 of 5 votes used)`. +/// One skipped-reason line, e.g. `2 votes: no changes left (4 of 4 changes used)`. 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 (5 of 5 votes used)." + "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." @@ -654,6 +654,13 @@ pub(crate) fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, Mess #[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() { @@ -750,7 +757,7 @@ mod tests { 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 (5 of 5 votes used)." + "Votes skipped: 1. The selected nodes have no changes left (4 of 4 changes used)." ); assert_eq!(confirm_button_label(72, true), "Cast 72 votes"); assert_eq!(confirm_button_label(1, false), "Schedule 1 vote"); diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 8db2da6a5..9e534170c 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -75,7 +75,7 @@ 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 = "None of your loaded nodes has a voting key."; +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 JOURNAL_UNAVAILABLE_MESSAGE: &str = "Saved voting progress could not be read. The displayed history may be incomplete or out of date. Retry loading before managing 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."; @@ -677,7 +677,24 @@ impl DPNSScreen { // --------------------------- // Rendering: Empty states // --------------------------- + 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) -> AppAction { + let (heading, detail, button) = self.no_voting_nodes_copy(); let action = AppAction::None; let dark_mode = ui.style().visuals.dark_mode; ui.vertical_centered(|ui| { @@ -686,16 +703,13 @@ impl DPNSScreen { ui.set_max_width(520.0); ui.vertical_centered(|ui| { ui.label( - RichText::new(NO_VOTING_NODES_MESSAGE) + RichText::new(heading) .strong() .color(DashColors::warning_color(dark_mode)), ); - ui.label( - RichText::new(NO_VOTING_NODES_DETAIL) - .color(DashColors::text_primary(dark_mode)), - ); + ui.label(RichText::new(detail).color(DashColors::text_primary(dark_mode))); ui.add_space(12.0); - if ComponentStyles::add_primary_button(ui, "Load a masternode").clicked() { + if ComponentStyles::add_primary_button(ui, button).clicked() { self.load_node_requested = true; } }); @@ -1921,9 +1935,14 @@ impl DPNSScreen { self.relative_schedule_labels = rows .iter() .filter_map(|row| { - let (_, key) = row.journal_target.as_ref()?; + let (operation_id, key) = row.journal_target.as_ref()?; let at = row.vote.unix_timestamp; - let preset = self.app_context.dpns_relative_schedule_label(key, at)?; + 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(); @@ -1954,13 +1973,11 @@ impl DPNSScreen { return action; } if self.voting_identities.is_empty() { - ui.colored_label( - DashColors::warning_color(dark_mode), - NO_VOTING_NODES_MESSAGE, - ); - ui.label(NO_VOTING_NODES_DETAIL); + 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, "Load a masternode").clicked() { + if ComponentStyles::add_primary_button(ui, button).clicked() { self.load_node_requested = true; self.show_bulk_schedule_popup = false; } @@ -4244,6 +4261,41 @@ mod tests { 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; @@ -4738,10 +4790,9 @@ mod tests { 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"); - ctx.save_dpns_relative_schedule_label(&key, at, std::time::Duration::from_secs(6 * 3600)) - .expect("save label"); let mut screen = DPNSScreen::new(&ctx, VotesView::Scheduled); let expected = relative_schedule_label(std::time::Duration::from_secs(6 * 3600), &utc_minute(at)); diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index 0e61c416a..a38eb38d7 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -130,7 +130,7 @@ pub struct MasternodeDetailView { /// 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, read when the view is built; + /// Open contests with this node's choice, reloaded with stored screen data; /// `None` when they could not be read. node_votes: Option>, } @@ -277,6 +277,11 @@ impl MasternodeDetailView { /// 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() @@ -300,8 +305,7 @@ impl MasternodeDetailView { } /// 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 tasks = vec![BackendTask::IdentityTask(IdentityTask::RefreshIdentity( self.identity.clone(), @@ -966,6 +970,51 @@ mod tests { } } + #[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(); diff --git a/tests/kittest/masternode_tab.rs b/tests/kittest/masternode_tab.rs index b03a87507..a5355bf66 100644 --- a/tests/kittest/masternode_tab.rs +++ b/tests/kittest/masternode_tab.rs @@ -464,7 +464,7 @@ fn to_decide_without_a_voting_key_shows_the_load_action() { assert!( harness - .query_by_label("None of your loaded nodes has a voting key.") + .query_by_label("No masternodes are loaded.") .is_some(), "the no-voter-key explanation must render in To decide" ); @@ -482,6 +482,49 @@ fn to_decide_without_a_voting_key_shows_the_load_action() { }); } +#[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" + ); + }); +} + /// 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 From 9e3ffdb668022aea6adced392db824f7d01ce901 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 2 Oct 2026 15:30:26 +0000 Subject: [PATCH 111/194] fix(ui): keep voting refresh bursts from starving frames MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bound backend-result work per update and coalesce adjacent cache refreshes. Flush refreshes before typed results and repaint while queued work remains, preserving result order and eventual delivery. Reproduce the Voting stall with 985 synthetic cached contests and a full result channel; verify bounded frames and interleaved success/error delivery. Co-Authored-By: Codex GPT-6 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 2 + src/app.rs | 26 +++++- tests/kittest/masternode_tab.rs | 138 ++++++++++++++++++++++++++++++++ 3 files changed, 163 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d9a896731..9b7cb256f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -194,6 +194,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- Large voting refresh bursts yield between frames so the window remains responsive while queued results are delivered. + - Votes distinguishes missing nodes from missing voting keys, and node detail refresh reloads cached votes. - Bulk voting reports confirmed and failed targets together while scheduled preflight failures remain retryable. - Relative schedule labels follow vote journal retention and clear when the scheduled time changes. diff --git a/src/app.rs b/src/app.rs index 2ca61f1c8..7c838a3f5 100644 --- a/src/app.rs +++ b/src/app.rs @@ -3103,8 +3103,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); @@ -3547,7 +3560,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 @@ -3556,6 +3569,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. diff --git a/tests/kittest/masternode_tab.rs b/tests/kittest/masternode_tab.rs index a5355bf66..252224d0c 100644 --- a/tests/kittest/masternode_tab.rs +++ b/tests/kittest/masternode_tab.rs @@ -525,6 +525,144 @@ fn blocker_keyless_node_add_voting_key_opens_reimport_form() { }); } +/// 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 From 4902efdc254b2cc239513100e1a1d0df0195f666 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 5 Oct 2026 07:43:01 +0000 Subject: [PATCH 112/194] fix(dpns): refresh voting state and align review feedback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reload visible voting snapshots after refresh, rank attention outcomes consistently, and recognize reconciled scheduled failures. Use honest voting-history warnings, complete Clear-All messages, and shared hexadecimal masternode labels. Remove overlay cross-references from current username feature docs. Cover resident plaintext protection during scoped identity merges and remove the stale TODO. Co-Authored-By: Codex πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 4 + .../01-requirements.md | 2 +- .../02-ux-spec.md | 2 +- .../wireframes.html | 2 +- docs/user-stories.md | 2 +- src/app.rs | 59 ++++-------- src/backend_task/identity/load_identity.rs | 84 ++++++++++++++++- src/context/contested_names_db.rs | 43 ++++++--- src/model/dpns_voting/progress.rs | 49 ++++++++-- src/model/identity_name.rs | 12 ++- src/ui/dpns/contest_card.rs | 16 +++- src/ui/dpns/copy.rs | 92 +++++++++++++++++-- src/ui/dpns/dpns_contested_names_screen.rs | 35 ++++++- src/ui/dpns/progress_drawer.rs | 11 +-- src/ui/masternodes/detail_screen.rs | 3 +- src/ui/masternodes/list_screen.rs | 6 +- 16 files changed, 327 insertions(+), 95 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b7cb256f..00a10887d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -159,6 +159,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). refresh every 30 minutes on Mainnet and every 3 minutes on other networks. Review shows each node's current and requested choice and remaining vote changes, or Unknown when the local history cannot establish the count. + Refresh updates the visible contests and vote state. Unnamed nodes use the + same shortened ProTxHash throughout voting and progress views. Attention + summaries reflect authoritative vote outcomes and warn against resubmitting + votes whose results are still uncertain. Cast now, choose a UTC time, or schedule shortly before voting ends. A progress drawer lets you keep working while votes are sent. Uncertain results stay visible and blocked from repeat submission. 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 index 68204db8f..483257006 100644 --- a/docs/ai-design/2026-10-01-usernames-redesign/01-requirements.md +++ b/docs/ai-design/2026-10-01-usernames-redesign/01-requirements.md @@ -161,7 +161,7 @@ Scope: identity-side usernames. Voting is Stream V in - 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, return to U4 with that row; nothing is spent. -- **USR-FR-038** β€” Progress: UX-001 overlay `Registering @{name}.` `Keep Dash +- **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 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 index 429e23f74..019f36b60 100644 --- 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 @@ -49,7 +49,7 @@ Tools: DPNS removed. checks update per keystroke. - Disabled controls always carry a tooltip reason. View-only identity β†’ `Add a key`. Not synced β†’ `Available after sync finishes.` -- Overlay only during registration (UX-001). Request-status refresh shows inline +- 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. diff --git a/docs/ai-design/2026-10-01-usernames-redesign/wireframes.html b/docs/ai-design/2026-10-01-usernames-redesign/wireframes.html index cf464e8a1..f3f6408dc 100644 --- a/docs/ai-design/2026-10-01-usernames-redesign/wireframes.html +++ b/docs/ai-design/2026-10-01-usernames-redesign/wireframes.html @@ -554,7 +554,7 @@

Review and pay

U7

Result: request submitted for a vote

Alex
-
  • After the UX-001 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).
+
  • 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

diff --git a/docs/user-stories.md b/docs/user-stories.md index 263951b25..68d68a227 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -807,7 +807,7 @@ As a user, I want to register a username for one of my identities so that others - 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 Β· 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. -- While registration runs, a full-window blocking overlay (UX-001) prevents a duplicate submission. +- 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. ### DPN-002: View my usernames [Implemented] diff --git a/src/app.rs b/src/app.rs index 7c838a3f5..2cad97273 100644 --- a/src/app.rs +++ b/src/app.rs @@ -20,7 +20,6 @@ use crate::context::connection_status::{ConnectionStatus, OverallConnectionState use crate::context::feature_gate::FeatureGate; use crate::context::migration_status::{MigrationState, MigrationStep}; use crate::database::Database; -use crate::model::dpns_voting::{DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome}; use crate::model::settings::AppSettings; use crate::model::wallet::{TransactionConfirmation, TransactionStatus}; use crate::ui::components::passphrase_modal; @@ -28,6 +27,7 @@ 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::copy::scheduled_vote_clear_feedback; use crate::ui::identity::identity_pill::shorten_id; use crate::ui::network_chooser_screen::{NetworkChooserScreen, chooser_network_label}; use crate::ui::theme::ThemeMode; @@ -328,42 +328,6 @@ fn clear_confirmed_vote_recovery_cutoff( } } -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); - let cleared_message = match cleared { - 0 => "No scheduled votes were removed.".to_owned(), - 1 => "1 scheduled vote was removed.".to_owned(), - count => format!("{count} scheduled votes were removed."), - }; - if in_flight == 0 { - let message_type = if cleared == 0 { - MessageType::Info - } else { - MessageType::Success - }; - return (cleared_message, message_type); - } - let retained_message = match in_flight { - 1 => { - "1 vote already in progress remains listed. Wait for it to finish before trying again." - .to_owned() - } - count => format!( - "{count} votes already in progress remain listed. Wait for them to finish before trying again." - ), - }; - ( - format!("{cleared_message} {retained_message}"), - MessageType::Info, - ) -} - /// Action id for the SPV-sync block's "Cancel" button. /// /// SPV sync is **unbounded** β€” with no peers it stays Connecting/Syncing forever @@ -2698,9 +2662,6 @@ impl AppState { { let votes = masternodes.votes_mut(); votes.display_backend_task_result(context, result.clone()); - if matches!(result, BackendTaskSuccessResult::RefreshedDpnsContests) { - votes.refresh(); - } } } @@ -4796,17 +4757,31 @@ mod dpns_result_routing_tests { assert_eq!( scheduled_vote_clear_feedback(&outcomes), ( - "1 scheduled vote was removed. 2 votes already in progress remain listed. Wait for them to finish before trying again.".to_owned(), + "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]), ( - "1 scheduled vote was removed.".to_owned(), + "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 + ) + ); } } diff --git a/src/backend_task/identity/load_identity.rs b/src/backend_task/identity/load_identity.rs index 2eb5d8511..51d1ceb6b 100644 --- a/src/backend_task/identity/load_identity.rs +++ b/src/backend_task/identity/load_identity.rs @@ -656,8 +656,6 @@ impl AppContext { } } } - // TODO(#889 review): reject resident plaintext left by an incomplete - // legacy migration before sealing around it (as the protect path does). self.seal_merged_plaintext_keys(qi, password)?; } let wallet_info = qi @@ -2674,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/context/contested_names_db.rs b/src/context/contested_names_db.rs index 312cffb61..c6af4dfaf 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -13,8 +13,8 @@ use crate::model::contested_name::{ }; use crate::model::dpns_usernames::{SeenMarkAttempts, UsernameRequest}; use crate::model::dpns_voting::{ - DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, - DpnsVoteTargetStatus, VoteTiming, dpns_vote_authority_rank, + DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, VoteTiming, + dpns_vote_authority_rank, }; use crate::model::qualified_identity::QualifiedIdentity; use crate::utils::time::now_ms; @@ -77,10 +77,8 @@ fn scheduled_vote_journal_summary( .values() .any(|(_, outcome)| outcome.status.holds_lock()); let failed = authoritative_by_target.values().any(|(_, outcome)| { - matches!( - outcome.status, - DpnsVoteTargetStatus::Rejected | DpnsVoteTargetStatus::FailedBeforeSubmission - ) && !dismissed.contains(&(outcome.operation_id, outcome.target.key.clone())) + outcome.status.is_reviewable_failure() + && !dismissed.contains(&(outcome.operation_id, outcome.target.key.clone())) }); (pending, failed) } @@ -878,6 +876,7 @@ mod tests { use super::*; use crate::context::test_support::test_app_context; 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, @@ -1260,12 +1259,32 @@ mod tests { timing: VoteTiming::Scheduled(42), }, ]); - operation.targets[0].status = DpnsVoteTargetStatus::FailedBeforeSubmission; - - assert_eq!( - scheduled_vote_journal_summary(&[operation], voter_id, &BTreeSet::new()), - (false, true) - ); + 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] diff --git a/src/model/dpns_voting/progress.rs b/src/model/dpns_voting/progress.rs index 404a5a440..e955040b6 100644 --- a/src/model/dpns_voting/progress.rs +++ b/src/model/dpns_voting/progress.rs @@ -2,8 +2,8 @@ //! (VOTE-FR-083/084). Pure: callers pass journal operations and the clock. use super::{ - DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTargetKey, - DpnsVoteTargetStatus, VoteTiming, dpns_schedule_is_overdue, + DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTargetStatus, VoteTiming, + dpns_schedule_is_overdue, dpns_vote_authority_rank, }; use std::collections::{BTreeMap, BTreeSet}; @@ -124,16 +124,29 @@ pub fn needs_attention( dismissed: &BTreeSet, now_ms: u64, ) -> NeedsAttention { - let mut latest: BTreeMap<&DpnsVoteTargetKey, u64> = BTreeMap::new(); + let mut latest = BTreeMap::new(); for operation in operations { for outcome in &operation.targets { - let at = latest.entry(&outcome.target.key).or_default(); - *at = (*at).max(operation.created_at); + let rank = dpns_vote_authority_rank( + operation.created_at, + outcome.operation_id, + outcome.status, + ); + let current = latest.entry(&outcome.target.key).or_insert(rank); + *current = (*current).max(rank); } } let mut attention = NeedsAttention::default(); for operation in operations { for outcome in &operation.targets { + let rank = dpns_vote_authority_rank( + operation.created_at, + outcome.operation_id, + outcome.status, + ); + if latest.get(&outcome.target.key) != Some(&rank) { + continue; + } match (outcome.status, outcome.target.timing) { (DpnsVoteTargetStatus::Unconfirmed, _) => attention.checking += 1, (DpnsVoteTargetStatus::Scheduled, VoteTiming::Scheduled(at)) @@ -143,7 +156,6 @@ pub fn needs_attention( } _ if operation.created_at >= since_ms && !dismissed.contains(&operation.id) - && latest.get(&outcome.target.key) == Some(&operation.created_at) && progress_phase(outcome) == Some(ProgressPhase::Failed) => { attention.failed += 1; @@ -294,4 +306,29 @@ mod tests { let dismissed = BTreeSet::from([failed.id]); assert_eq!(needs_attention(&[failed], 0, &dismissed, 300).failed, 0); } + + #[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/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/ui/dpns/contest_card.rs b/src/ui/dpns/contest_card.rs index 072db08c6..3a7a2576d 100644 --- a/src/ui/dpns/contest_card.rs +++ b/src/ui/dpns/contest_card.rs @@ -110,11 +110,17 @@ pub fn changed_vote_count(card: &VoteCard, choice: ResourceVoteChoice) -> usize /// Display label for a node: its alias, else a short identifier. pub fn node_label(node: Identifier, labels: &BTreeMap) -> String { - labels.get(&node).cloned().unwrap_or_else(|| { - let encoded = - node.to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58); - crate::model::identity_name::shorten_id(&encoded) - }) + 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 { diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index 08d3859de..732e24b8e 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -5,10 +5,49 @@ 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::{DpnsVoteFailure, DpnsVoteOperation, DpnsVoteTargetStatus}; +use crate::model::dpns_voting::{ + DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome, DpnsVoteFailure, + DpnsVoteOperation, DpnsVoteTargetStatus, +}; use crate::ui::MessageType; use std::collections::BTreeSet; +/// 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, @@ -298,9 +337,26 @@ pub fn needs_attention_line(attention: NeedsAttention) -> String { failed, missed_schedules, } = attention; - format!( - "Votes still being checked: {checking}. Failed votes: {failed}. Missed scheduled votes: {missed_schedules}." - ) + 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(), + } } /// One part of the History `Your nodes voted` cell, e.g. @@ -470,7 +526,8 @@ 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 node voted outside Dash Evo Tool.".to_owned() + "Changes left unknown. This device has no record of this node's earlier votes." + .to_owned() } } } @@ -775,7 +832,7 @@ mod tests { ); assert_eq!( changes_left_label(ChangesLeft::Unknown), - "Changes left unknown. This node voted outside Dash Evo Tool." + "Changes left unknown. This device has no record of this node's earlier votes." ); } @@ -815,10 +872,31 @@ mod tests { failed: 0, missed_schedules: 2, }), - "Votes still being checked: 1. Failed votes: 0. Missed scheduled votes: 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"); diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 9e534170c..8ac4c539e 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -77,7 +77,7 @@ const NO_OPEN_CONTESTS_MESSAGE: &str = 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 JOURNAL_UNAVAILABLE_MESSAGE: &str = "Saved voting progress could not be read. The displayed history may be incomplete or out of date. Retry loading before managing votes."; +const JOURNAL_UNAVAILABLE_MESSAGE: &str = crate::ui::dpns::copy::JOURNAL_UNAVAILABLE_MESSAGE; 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."; @@ -2658,6 +2658,7 @@ impl ScreenLike for DPNSScreen { self.rebuild_scheduled_vote_rows(); } BackendTaskSuccessResult::RefreshedDpnsContests => { + self.refresh(); self.refresh_banner.take_and_clear(); self.refreshing_status = RefreshingStatus::NotRefreshing; } @@ -2896,6 +2897,30 @@ mod tests { 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(); @@ -3569,7 +3594,7 @@ mod tests { assert!( harness .query_by_label( - "Votes still being checked: 1. Failed votes: 0. Missed scheduled votes: 0." + "Votes still being checked: 1. Do not submit the pending votes again." ) .is_some() ); @@ -3640,7 +3665,7 @@ mod tests { }); }); harness.run(); - let message = "Saved voting progress could not be read. The displayed history may be incomplete or out of date. Retry loading before managing votes."; + 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() @@ -4465,7 +4490,7 @@ mod tests { first.voter_alias = Some("node-one".to_owned()); let mut second = first.clone(); second.key.voter_id = Identifier::from([2; 32]); - second.voter_alias = Some("node-two".to_owned()); + 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()); @@ -4490,7 +4515,7 @@ mod tests { "Casting 3 votes Β· 2 done Β· 0 sending Β· 1 being checked", "node-one Β· alpha.dash Β· Abstain", "Confirmed", - "node-two Β· alpha.dash Β· Abstain", + "02020…202 Β· alpha.dash Β· Abstain", "Rejected", "Review again", "Still being checked. Do not submit it again.", diff --git a/src/ui/dpns/progress_drawer.rs b/src/ui/dpns/progress_drawer.rs index 325f19999..d27ad40f9 100644 --- a/src/ui/dpns/progress_drawer.rs +++ b/src/ui/dpns/progress_drawer.rs @@ -12,7 +12,6 @@ use crate::model::dpns_voting::{DpnsVoteFailure, DpnsVoteOutcome, DpnsVoteTarget use crate::ui::RootScreenType; use crate::ui::dpns::copy::{drawer_header, progress_row_status}; use crate::ui::theme::DashColors; -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, Align2, Id, RichText, Sense, Ui}; @@ -175,12 +174,10 @@ pub fn show(ctx: &egui::Context, app_context: &AppContext, state: &mut DrawerSta .filter(|outcome| progress_phase(outcome).is_some()) { ui.horizontal_wrapped(|ui| { - let node = - outcome.target.voter_alias.clone().unwrap_or_else(|| { - let encoded = - outcome.target.key.voter_id.to_string(Encoding::Base58); - crate::model::identity_name::shorten_id(&encoded) - }); + let node = crate::model::identity_name::masternode_label( + outcome.target.key.voter_id, + outcome.target.voter_alias.as_deref(), + ); ui.label(format!( "{node} Β· {name}.dash Β· {choice}", name = outcome.target.contested_name, diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index a38eb38d7..061969a15 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -213,7 +213,8 @@ 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 identity_id = identity.identity.id(); let recovery = LegacyRecoveryState::new(app_context, identity.identity.id()); diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index 8c517f30b..f6f5990cb 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -33,7 +33,6 @@ use crate::ui::components::styled::island_central_panel; use crate::ui::components::top_panel::add_top_panel_with_global_nav_capturing; use crate::ui::dpns::VotesView; use crate::ui::dpns::dpns_contested_names_screen::DPNSScreen; -use crate::ui::identity::identity_pill::shorten_id; use crate::ui::identity::picker::compute_column_count; use crate::ui::masternodes::card::{MasternodeCard, card_heading}; use crate::ui::masternodes::detail_screen::{DetailOutcome, MasternodeDetailView}; @@ -254,7 +253,7 @@ impl MasternodesScreen { .into_iter() .map(|qi| { let node_id = qi.identity.id(); - let node_id_short = shorten_id(&node_id.to_string(Encoding::Hex)); + 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 @@ -1096,7 +1095,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!( From f9ef2a7fa763a5eec8d6c94a7ede0ae00b70eeaa Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 5 Oct 2026 08:14:07 +0000 Subject: [PATCH 113/194] fix(dpns): refresh saved username outcomes before contest discovery --- docs/user-stories.md | 1 + src/backend_task/identity/dpns_usernames.rs | 212 ++++++++++++++++---- src/context/contested_names_db.rs | 47 ++++- src/model/dpns_usernames.rs | 50 ++++- src/ui/identity/username_copy.rs | 8 + src/ui/identity/username_notices.rs | 21 +- src/ui/identity/username_request_screen.rs | 5 +- src/ui/identity/usernames_card.rs | 2 + tests/kittest/identity_usernames.rs | 40 +++- 9 files changed, 325 insertions(+), 61 deletions(-) diff --git a/docs/user-stories.md b/docs/user-stories.md index 68d68a227..d7635182e 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -816,6 +816,7 @@ As a user, I want to register a username for one of my identities so that others 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. - 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). +- 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. - 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. diff --git a/src/backend_task/identity/dpns_usernames.rs b/src/backend_task/identity/dpns_usernames.rs index e89a098e0..6900b0148 100644 --- a/src/backend_task/identity/dpns_usernames.rs +++ b/src/backend_task/identity/dpns_usernames.rs @@ -176,10 +176,9 @@ impl AppContext { /// Refresh the username requests of every loaded identity. /// - /// One scan of running contests serves all identities. Requests missing - /// from the scan are re-read individually, for their outcome or running - /// tally. Only the network scan fails the task; local storage problems are - /// logged so a background refresh never raises a banner. + /// 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, @@ -197,6 +196,44 @@ impl AppContext { if identities.is_empty() { return Ok(BackendTaskSuccessResult::MyUsernameRequestsRefreshed); } + let durations = self.username_contest_durations(sdk); + let mut checked = BTreeMap::new(); + 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_ms(), + durations, + )); + } + } + self.apply_username_refresh(sdk, identity, &previous, fresh) + .await; + } // 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 = sdk @@ -205,7 +242,6 @@ impl AppContext { .map_err(|source| TaskError::UsernameRequestRefreshFailed { source: Box::new(source), })?; - let durations = self.username_contest_durations(sdk); let now = now_ms(); let snapshots: BTreeMap<&String, (ContestSnapshot, u64)> = running .iter() @@ -220,8 +256,13 @@ impl AppContext { for identity in identities { let identity_id = identity.identity.id(); let previous = self.username_requests_for(&identity_id); - let mut fresh: Vec = snapshots + 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, @@ -233,47 +274,38 @@ impl AppContext { ) }) .collect(); - for old in previous.iter().filter(|old| { - old.phase.is_pending() && !snapshots.contains_key(&old.normalized_label) - }) { - match sdk - .get_contested_dpns_vote_state(&old.normalized_label, None) - .await - { - Ok(contenders) => fresh.extend(username_request_from_contest( - identity_id, - &old.normalized_label, - &self.contest_snapshot(sdk, &contenders), - old.end, - now, - durations, - )), - Err(error) => tracing::debug!( - name = %old.normalized_label, - ?error, - "Username request outcome could not be read; keeping the stored status" - ), - } - } - let newly_won = fresh.iter().any(|request| { - request.phase == RequestPhase::Won - && !previous.iter().any(|old| { - old.normalized_label == request.normalized_label - && old.phase == RequestPhase::Won - }) - }); - if let Err(error) = self.update_username_requests(&identity_id, |current| { - merge_requests(current, fresh, now) - }) { - tracing::warn!(?error, %identity_id, "Username requests could not be stored"); - } - if newly_won { - self.record_won_usernames(sdk, &identity).await; - } + self.apply_username_refresh(sdk, &identity, &previous, fresh) + .await; } Ok(BackendTaskSuccessResult::MyUsernameRequestsRefreshed) } + async fn apply_username_refresh( + &self, + sdk: &Sdk, + identity: &QualifiedIdentity, + previous: &[UsernameRequest], + fresh: Vec, + ) { + let identity_id = identity.identity.id(); + let newly_won = fresh.iter().any(|request| { + request.phase == RequestPhase::Won + && !previous.iter().any(|old| { + old.normalized_label == request.normalized_label + && old.phase == RequestPhase::Won + }) + }); + if let Err(error) = self.update_username_requests(&identity_id, |current| { + merge_requests(current, fresh, now_ms()) + }) { + tracing::warn!(?error, %identity_id, "Username requests could not be stored"); + } + self.egui_ctx().request_repaint(); + if newly_won { + self.record_won_usernames(sdk, identity).await; + } + } + /// Re-read the registered names of an identity that just won a vote, so the /// won name is listed and shown at once. async fn record_won_usernames(&self, sdk: &Sdk, identity: &QualifiedIdentity) { @@ -355,3 +387,97 @@ impl AppContext { Ok(BackendTaskSuccessResult::UsernamePreferencesSaved) } } + +#[cfg(test)] +mod tests { + use super::*; + 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, + }; + + #[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 = QualifiedIdentity { + identity: dash_sdk::dpp::identity::Identity::create_basic_identity( + id, + dash_sdk::dpp::version::PlatformVersion::latest(), + ) + .unwrap(), + associated_voter_identity: None, + associated_operator_identity: None, + associated_owner_key_id: None, + identity_type: crate::model::qualified_identity::IdentityType::User, + alias: None, + private_keys: Default::default(), + dpns_names: vec![], + associated_wallets: Default::default(), + secret_access: None, + wallet_index: None, + top_ups: Default::default(), + status: crate::model::qualified_identity::IdentityStatus::Active, + network: 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/context/contested_names_db.rs b/src/context/contested_names_db.rs index c6af4dfaf..a4be9d12c 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -307,11 +307,18 @@ impl AppContext { /// 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) + .into_iter() + .flatten() .cloned() - .unwrap_or_default() + .map(|mut request| { + request.phase = request.phase_at(now); + request + }) + .collect() } /// Whether any identity has a request still in its community vote. Frame-safe. @@ -368,12 +375,9 @@ impl AppContext { if identity_owns_dpns_name(identity) { return None; } - self.username_cache() - .requests - .get(&identity.identity.id())? - .iter() + self.username_requests_for(&identity.identity.id()) + .into_iter() .find(|request| request.phase.is_pending()) - .cloned() } /// The registered name `identity` shows as its main one. Frame-safe. @@ -945,6 +949,37 @@ mod tests { } } + #[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"); diff --git a/src/model/dpns_usernames.rs b/src/model/dpns_usernames.rs index 84fdcb79b..ff1e6554c 100644 --- a/src/model/dpns_usernames.rs +++ b/src/model/dpns_usernames.rs @@ -315,12 +315,14 @@ pub enum RequestPhase { 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 vote is still running. + /// Whether the request still needs a confirmed network outcome. pub fn is_pending(self) -> bool { - matches!(self, Self::Joinable | Self::Voting) + matches!(self, Self::Joinable | Self::Voting | Self::AwaitingOutcome) } } @@ -394,6 +396,20 @@ pub struct UsernameRequest { } 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 @@ -578,6 +594,36 @@ mod tests { } } + #[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 diff --git a/src/ui/identity/username_copy.rs b/src/ui/identity/username_copy.rs index 2b83dd117..de764e30b 100644 --- a/src/ui/identity/username_copy.rs +++ b/src/ui/identity/username_copy.rs @@ -210,6 +210,7 @@ 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", @@ -246,6 +247,10 @@ pub fn voting_timeline_line(end: TimestampMillis, phase: RequestPhase) -> String "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) + ), _ => format!( "The community vote ended on {date}.", date = format_date(end) @@ -257,6 +262,9 @@ pub fn voting_timeline_line(end: TimestampMillis, phase: RequestPhase) -> String 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.", diff --git a/src/ui/identity/username_notices.rs b/src/ui/identity/username_notices.rs index 8f342c8d8..743308558 100644 --- a/src/ui/identity/username_notices.rs +++ b/src/ui/identity/username_notices.rs @@ -48,7 +48,7 @@ pub fn outcome_banner_text(request: &UsernameRequest) -> Option { RequestPhase::NoWinner => Some(format!( "The vote for @{name} ended without a winner. You can choose a different username." )), - RequestPhase::Joinable | RequestPhase::Voting => None, + RequestPhase::Joinable | RequestPhase::Voting | RequestPhase::AwaitingOutcome => None, } } @@ -128,18 +128,23 @@ pub fn render( notice_frame(ui, dark_mode, |ui| { status_line(ui, Tone::Caution, phase_label(request.phase), dark_mode); let name = &request.label; - let first = match request.end { - Some(end) => format!( + let first = match (request.phase, request.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."), + (_, None) => format!("@{name} is waiting for a community vote."), }; ui.label(RichText::new(first).strong()); - ui.label(standing_line( - request.tally.standing(), - request.tally.others.len(), - )); + 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 { diff --git a/src/ui/identity/username_request_screen.rs b/src/ui/identity/username_request_screen.rs index 1637f8d36..128fd2545 100644 --- a/src/ui/identity/username_request_screen.rs +++ b/src/ui/identity/username_request_screen.rs @@ -87,6 +87,7 @@ impl UsernameRequestScreen { 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 { @@ -118,7 +119,9 @@ impl UsernameRequestScreen { status_line(ui, tone, &text, dark_mode); } let tone = match request.phase { - RequestPhase::Joinable | RequestPhase::Voting => Tone::Neutral, + RequestPhase::Joinable | RequestPhase::Voting | RequestPhase::AwaitingOutcome => { + Tone::Neutral + } RequestPhase::Won => Tone::Positive, RequestPhase::Lost | RequestPhase::Locked | RequestPhase::NoWinner => Tone::Negative, }; diff --git a/src/ui/identity/usernames_card.rs b/src/ui/identity/usernames_card.rs index 6bc8ec0e9..8bdc4b06a 100644 --- a/src/ui/identity/usernames_card.rs +++ b/src/ui/identity/usernames_card.rs @@ -202,6 +202,8 @@ impl UsernamesCard { "Others can ask for this name until {}. Masternodes can already vote.", format_date(join_end) ), + (RequestPhase::AwaitingOutcome, _, _) => + "The estimated voting period has ended. View the status to check the outcome.".to_owned(), (_, _, Some(end)) => { format!("Voting ends around {}.", format_date(end)) } diff --git a/tests/kittest/identity_usernames.rs b/tests/kittest/identity_usernames.rs index aa67411bf..406fc2c06 100644 --- a/tests/kittest/identity_usernames.rs +++ b/tests/kittest/identity_usernames.rs @@ -284,7 +284,11 @@ fn view_only_identity_is_told_to_add_a_key() { fn request(label: &str, phase: RequestPhase) -> UsernameRequest { let mut request = UsernameRequest::submitted( label, - 1_700_000_000_000, + 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), @@ -645,6 +649,40 @@ fn home_shows_pending_request_header_and_card() { }); } +#[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() { From ed897e7341f4d12d79cd66d5c849ca867e328425 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 5 Oct 2026 08:32:21 +0000 Subject: [PATCH 114/194] fix(dpns): replace vote history column with explorer links --- .../02-ux-spec.md | 8 +- .../04-development-plan.md | 2 +- docs/user-stories.md | 2 +- src/ui/dpns/copy.rs | 19 -- src/ui/dpns/dpns_contested_names_screen.rs | 181 +++--------------- src/ui/dpns/mod.rs | 2 +- 6 files changed, 39 insertions(+), 175 deletions(-) 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 index 360012fa0..52fe72176 100644 --- 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 @@ -129,9 +129,11 @@ Columns: Name Β· Nodes (`24 nodes β–Ύ`) Β· Vote Β· When Β· Status Β· actions. ## History (frame V4) -Name Β· Ended Β· Outcome (`Went to {name} ({short_id})` [Copy ID] Β· `Locked for -good, no one can register it`) Β· `Your nodes voted` (`Vote for Zed (24 nodes, -51 votes)` / `Your nodes didn't vote.`). +Name [View in Platform Explorer] Β· Ended Β· Last updated Β· Outcome +(`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) 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 index a46f1d58f..9ac165b1d 100644 --- 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 @@ -194,7 +194,7 @@ details, and the recovery action. Never parse strings. 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: aggregate `Your nodes voted` with weight. +- 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, diff --git a/docs/user-stories.md b/docs/user-stories.md index d7635182e..767112d3b 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -835,7 +835,7 @@ As a masternode operator, I want to see the name contests that need a decision f As a power user, I want to review past contests so that I can see outcomes and how my nodes voted. -- Votes β–Έ History lists finished contests with the outcome in words (went to a named requester with a copyable identifier, or locked for good), and my nodes' votes with their total weight. +- 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 link beside each name that opens its contest in Platform Explorer for the active Mainnet or Testnet network. ### DPN-005: Vote on contested names [Implemented] **Persona:** Priya diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index 732e24b8e..1f290c98f 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -359,16 +359,6 @@ pub fn needs_attention_line(attention: NeedsAttention) -> String { } } -/// One part of the History `Your nodes voted` cell, e.g. -/// `Vote for Zed (24 nodes, 51 votes)`. -pub fn nodes_voted_part(choice: &str, nodes: usize, votes: u32) -> String { - match (nodes, votes) { - (1, 1) => format!("{choice} (1 node, 1 vote)"), - (1, votes) => format!("{choice} (1 node, {votes} votes)"), - (nodes, votes) => format!("{choice} ({nodes} nodes, {votes} votes)"), - } -} - /// A node's voting weight on its detail page (MN-003). pub fn voting_weight_label(weight: u32) -> String { match weight { @@ -388,9 +378,6 @@ pub fn went_to_label(name: Option<&str>, short_id: &str) -> String { /// History outcome of a locked contest. pub const LOCKED_FOR_GOOD: &str = "Locked for good, no one can register it"; -/// History cell when none of your nodes voted on a finished contest. -pub const NODES_DID_NOT_VOTE: &str = "Your nodes didn't vote."; - /// Expander label of a scheduled decision's node list (VOTE-FR-088). pub fn scheduled_nodes_label(nodes: usize) -> String { match nodes { @@ -730,12 +717,6 @@ mod tests { before_end_phrase(std::time::Duration::from_secs(30)), "Less than a minute before the end" ); - assert_eq!( - nodes_voted_part("Vote for Zed", 24, 51), - "Vote for Zed (24 nodes, 51 votes)" - ); - assert_eq!(nodes_voted_part("Lock", 1, 1), "Lock (1 node, 1 vote)"); - assert_eq!(nodes_voted_part("Lock", 1, 4), "Lock (1 node, 4 votes)"); 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." diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 8ac4c539e..5a5083a63 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -7,6 +7,7 @@ use std::sync::{Arc, Mutex}; 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; @@ -29,8 +30,8 @@ use crate::model::dpns_voting::composer::{ }; use crate::model::dpns_voting::operator::NodeExclusion; use crate::model::dpns_voting::operator::{ - ChangesLeft, ChoiceTally, NodeSet, ResolvedNodeSet, VotingNode, VotingNodeKind, - relative_schedule_preset, tally_node_choices, time_left, + ChangesLeft, NodeSet, ResolvedNodeSet, VotingNode, VotingNodeKind, relative_schedule_preset, + time_left, }; use crate::model::dpns_voting::progress::needs_attention; use crate::model::dpns_voting::{ @@ -49,10 +50,10 @@ use crate::ui::dpns::contest_card::{CardEvent, CardView}; use crate::ui::dpns::copy::needs_attention_line; use crate::ui::dpns::copy::tray_label; use crate::ui::dpns::copy::{ - LOCKED_FOR_GOOD, NODES_DID_NOT_VOTE, before_end_phrase, changes_left_label, - confirm_button_label, confirm_change_warning, confirm_title, confirm_transactions_line, - decision_row, ends_in_label, nodes_voted_part, relative_schedule_label, scheduled_nodes_label, - skipped_header, skipped_reason_line, went_to_label, + LOCKED_FOR_GOOD, 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::{ends_soon_now_line, excluded_nodes_line}; use crate::ui::dpns::node_set_picker; @@ -357,6 +358,22 @@ pub enum VoteSubmissionError { TaskFailed, } +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, @@ -482,9 +499,6 @@ pub struct DPNSScreen { /// Cards ticked for a bulk decision, by contest name. selected_cards: BTreeSet, focused_card: Option, - /// History `Your nodes voted` per finished contest; absent when no node's - /// vote is known on this device. - history_votes: BTreeMap>, /// Whether the contest list has keyboard focus for shortcuts. list_focused: bool, } @@ -577,7 +591,6 @@ impl DPNSScreen { relative_schedule_labels: BTreeMap::new(), selected_cards: BTreeSet::new(), focused_card: None, - history_votes: BTreeMap::new(), list_focused: false, }; screen.rebuild_cards(); @@ -638,7 +651,6 @@ impl DPNSScreen { self.selected_cards.clear(); self.focused_card = None; self.list_focused = false; - self.history_votes.clear(); } // --------------------------- @@ -796,87 +808,6 @@ impl DPNSScreen { /// 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. - /// Every loaded node's proved choice on each finished contest, tallied. - /// A contest is listed only when at least one node's vote is known. - fn collect_history_votes(&self) -> BTreeMap> { - let finished: Vec<(String, Identifier)> = self - .contested_names - .lock_recover() - .iter() - .filter(|contest| contest.awarded_to.is_some() || contest.state == ContestState::Locked) - .filter_map(|contest| { - let poll = self - .app_context - .dpns_vote_poll_id(&contest.normalized_contested_name) - .ok()?; - Some((contest.normalized_contested_name.clone(), poll)) - }) - .collect(); - if finished.is_empty() { - return BTreeMap::new(); - } - let states: Vec<(VotingNodeKind, BTreeMap)> = self - .voting_nodes - .iter() - .filter_map(|node| { - let states = self - .app_context - .dpns_current_vote_states(node.id, finished.iter().map(|(_, poll)| *poll)) - .inspect_err(|error| { - tracing::debug!( - ?error, - "Could not read a node's votes on finished contests" - ); - }) - .ok()?; - Some((node.kind, states)) - }) - .collect(); - finished - .into_iter() - .filter_map(|(name, poll)| { - let known: Vec<(VotingNodeKind, Option)> = states - .iter() - .filter_map(|(kind, states)| match states.get(&poll) { - Some(DpnsCurrentVoteState::Available(choice)) => Some((*kind, *choice)), - _ => None, - }) - .collect(); - if known.is_empty() { - return None; - } - let tallies = tally_node_choices( - known - .into_iter() - .filter_map(|(kind, choice)| choice.map(|choice| (kind, choice))), - ); - Some((name, tallies)) - }) - .collect() - } - - /// The History `Your nodes voted` cell; empty when nothing is known. - fn history_votes_cell(&self, contested_name: &str) -> String { - match self.history_votes.get(contested_name) { - None => String::new(), - Some(tallies) if tallies.is_empty() => NODES_DID_NOT_VOTE.to_owned(), - Some(tallies) => tallies - .iter() - .map(|tally| { - nodes_voted_part( - &vote_choice_label( - tally.choice, - self.candidate_name(contested_name, tally.choice), - ), - tally.nodes, - tally.weight, - ) - }) - .collect::>() - .join("; "), - } - } - pub(crate) fn rebuild_cards(&mut self) { let network = self.app_context.network(); if self.node_set_network != Some(network) { @@ -933,7 +864,6 @@ impl DPNSScreen { .collect(); sort_by_time_left(&mut cards); self.cards = cards; - self.history_votes = self.collect_history_votes(); let names: BTreeSet<&str> = self.cards.iter().map(VoteCard::name).collect(); self.selected_cards .retain(|name| names.contains(name.as_str())); @@ -1491,8 +1421,7 @@ 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::remainder()) // Your nodes voted + .column(Column::remainder()) // Outcome .header(30.0, |mut header| { header.col(|ui| { if ui.button("Name").clicked() { @@ -1514,9 +1443,6 @@ impl DPNSScreen { self.toggle_sort(SortColumn::AwardedTo); } }); - header.col(|ui| { - ui.label(RichText::new("Your nodes voted").strong()); - }); }) .body(|mut body| { for contested_name in &contested_names { @@ -1528,6 +1454,13 @@ impl DPNSScreen { RichText::new(&contested_name.normalized_contested_name) .color(DashColors::text_primary(dark_mode)), ); + if let Some(url) = platform_explorer_contest_url( + self.app_context.network(), + &contested_name.normalized_contested_name, + ) { + ui.hyperlink_to("View in Platform Explorer", url) + .on_hover_text("Open this contest in your web browser."); + } }); // Ended Time row.col(|ui| { @@ -1628,13 +1561,6 @@ impl DPNSScreen { } } }); - row.col(|ui| { - ui.label( - self.history_votes_cell( - &contested_name.normalized_contested_name, - ), - ); - }); }); } }); @@ -4095,51 +4021,6 @@ mod tests { ); } - /// VOTE-FR-087 (History): `Your nodes voted` tallies proved choices with - /// weight, says when no node voted, and stays blank when nothing is known. - #[tokio::test] - async fn history_cell_tallies_node_votes() { - let (ctx, _dir) = kv_ctx(); - let mut evonode = masternode_identity(1, "evo", true, ctx.network()); - evonode.identity_type = crate::model::qualified_identity::IdentityType::Evonode; - let masternode = masternode_identity(2, "mn", true, ctx.network()); - let finished = |name: &str| ContestedName { - normalized_contested_name: name.to_owned(), - contestants: None, - locked_votes: None, - abstain_votes: None, - awarded_to: None, - end_time: Some(1), - state: ContestState::Locked, - last_updated: None, - my_votes: BTreeMap::new(), - }; - let voted = ctx.dpns_vote_poll_id("voted").unwrap(); - ctx.seed_proved_dpns_votes_for_test( - evonode.identity.id(), - BTreeMap::from([(voted.to_buffer(), ResourceVoteChoice::Lock)]), - ) - .await - .unwrap(); - ctx.seed_proved_dpns_votes_for_test( - masternode.identity.id(), - BTreeMap::from([(voted.to_buffer(), ResourceVoteChoice::Lock)]), - ) - .await - .unwrap(); - let mut screen = DPNSScreen::new(&ctx, VotesView::History); - *screen.contested_names.lock_recover() = - vec![finished("voted"), finished("skipped"), finished("unknown")]; - screen.voting_identities = vec![evonode, masternode]; - screen.rebuild_cards(); - assert_eq!( - screen.history_votes_cell("voted"), - "Lock name (2 nodes, 5 votes)" - ); - assert_eq!(screen.history_votes_cell("skipped"), NODES_DID_NOT_VOTE); - assert_eq!(screen.history_votes_cell("absent"), ""); - } - /// A request from another screen opens the contest's card, filtered and /// focused, once. #[tokio::test] diff --git a/src/ui/dpns/mod.rs b/src/ui/dpns/mod.rs index d9036cfef..1a9f0f7b5 100644 --- a/src/ui/dpns/mod.rs +++ b/src/ui/dpns/mod.rs @@ -17,7 +17,7 @@ pub enum VotesView { Voted, /// Scheduled and missed automatic votes. Scheduled, - /// Finished contests and how the operator's nodes voted. + /// Finished contests with links to Platform Explorer. History, } From 919dfafddb34bdfd7f2a981c58e9717752f1109d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 5 Oct 2026 08:40:58 +0000 Subject: [PATCH 115/194] fix(dpns): move explorer links to final details column --- .../02-ux-spec.md | 2 +- docs/user-stories.md | 2 +- src/ui/dpns/dpns_contested_names_screen.rs | 22 ++++++++++++------- 3 files changed, 16 insertions(+), 10 deletions(-) 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 index 52fe72176..a60ae4acd 100644 --- 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 @@ -129,7 +129,7 @@ Columns: Name Β· Nodes (`24 nodes β–Ύ`) Β· Vote Β· When Β· Status Β· actions. ## History (frame V4) -Name [View in Platform Explorer] Β· Ended Β· Last updated Β· Outcome +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 diff --git a/docs/user-stories.md b/docs/user-stories.md index 767112d3b..0c1b7de31 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -835,7 +835,7 @@ As a masternode operator, I want to see the name contests that need a decision f As a power user, I want to review past contests so that I can see outcomes and how my nodes voted. -- 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 link beside each name that opens its contest in Platform Explorer for the active Mainnet or Testnet network. +- 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 diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 5a5083a63..719fc2231 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -1421,7 +1421,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::remainder()) // Outcome + .column(Column::auto().resizable(true)) // Outcome + .column(Column::remainder()) // details .header(30.0, |mut header| { header.col(|ui| { if ui.button("Name").clicked() { @@ -1443,6 +1444,9 @@ impl DPNSScreen { self.toggle_sort(SortColumn::AwardedTo); } }); + header.col(|ui| { + ui.label(RichText::new("details").strong()); + }); }) .body(|mut body| { for contested_name in &contested_names { @@ -1454,13 +1458,6 @@ impl DPNSScreen { RichText::new(&contested_name.normalized_contested_name) .color(DashColors::text_primary(dark_mode)), ); - if let Some(url) = platform_explorer_contest_url( - self.app_context.network(), - &contested_name.normalized_contested_name, - ) { - ui.hyperlink_to("View in Platform Explorer", url) - .on_hover_text("Open this contest in your web browser."); - } }); // Ended Time row.col(|ui| { @@ -1561,6 +1558,15 @@ impl DPNSScreen { } } }); + 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."); + } + }); }); } }); From 18cd9c531577bec0eea677c8f2d553e68c0172ce Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 5 Oct 2026 10:20:47 +0000 Subject: [PATCH 116/194] fix(dpns): preserve uncertain votes and concurrent username updates Require authoritative contest closure for reconciliation, keep username reloads atomic and fallible, and preserve decisions staged during vote submission. Co-Authored-By: Codex --- CHANGELOG.md | 4 + docs/user-stories.md | 3 + src/backend_task/contested_names/mod.rs | 73 +++++----- src/context/contested_names_db.rs | 150 +++++++++++++++++++-- src/context/dpns_vote_attention.rs | 4 +- src/model/dpns_voting/mod.rs | 11 +- src/ui/dpns/dpns_contested_names_screen.rs | 148 ++++++++++++++++---- 7 files changed, 310 insertions(+), 83 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index af87d877f..09e0863ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -165,7 +165,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). votes whose results are still uncertain. Cast now, choose a UTC time, or schedule shortly before voting ends. A progress drawer lets you keep working while votes are sent. + Decisions staged or changed during submission remain available afterward. Uncertain results stay visible and blocked from repeat submission. + Passing the estimated deadline alone does not release an uncertain vote. Unresolved operations remain accessible after a contest closes and are not displaced by newer completed votes. Failed scheduled attempts retain an actionable explanation after restarting the app. @@ -181,6 +183,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). community vote show the non-refundable fee before payment; availability is checked again before registration. Request status shows the timeline, tally, and outcome, and suggests alternatives that need no vote. + Request refreshes preserve concurrent edits and retain saved requests when + storage cannot be read. Profile β†’ Usernames lists your names and requests, with a "Show as main" choice for the username displayed when no profile display name is set. The former DPNS tool entry is removed; old voting shortcuts open diff --git a/docs/user-stories.md b/docs/user-stories.md index 0c1b7de31..dac43c02b 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -817,6 +817,7 @@ As a user, I want to see each identity's usernames and their state so that I kno - 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). - 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. - 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. @@ -846,6 +847,7 @@ As a masternode operator, I want to make one decision per contest and have all m - 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. @@ -871,6 +873,7 @@ As a masternode operator, I want to choose which nodes vote and decide many cont - 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. +- 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 diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index b813ae981..b318ec687 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -144,20 +144,17 @@ fn set_relative_schedule_labels( } } -/// The outcome of a target whose contest closed before it was sent -/// (VOTE-FR-087), or `None` while the contest may still accept votes. -/// -/// Terminal for scheduled targets too: a closed poll can never accept the -/// vote, so retrying it would only fail again. +/// 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, now_ms) == DpnsVotePollAvailability::ProvedClosed) - .then_some(( - DpnsVoteTargetStatus::FailedBeforeSubmission, - Some(DpnsVoteFailure::VotingEnded), - )) + (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, @@ -1056,7 +1053,6 @@ impl AppContext { .into_iter() .map(|contest| (contest.normalized_contested_name.clone(), contest)) .collect::>(); - let now_ms = now_ms(); for outcome in operation .targets .iter() @@ -1064,7 +1060,7 @@ impl AppContext { { // Targets may carry the label the operator typed; contests are keyed normalized. let normalized = convert_to_homograph_safe_chars(&outcome.target.contested_name); - let availability = dpns_vote_poll_availability(contests.get(&normalized), now_ms); + let availability = dpns_vote_poll_availability(contests.get(&normalized)); let poll_id = outcome.target.key.vote_poll_id; let query = ContestedResourceVotesGivenByIdentityQuery { identity_id: outcome.target.key.voter_id, @@ -2243,41 +2239,44 @@ mod tests { } #[test] - fn poll_availability_is_proved_only_by_a_cached_decided_or_expired_contest() { + 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(); + for now in [1_000, 2_000, u64::MAX] { + let availability = dpns_vote_poll_availability(contests.first()); + for observed in [None, Some(ResourceVoteChoice::Abstain)] { + let status = + classify_reconciled_vote(observed, ResourceVoteChoice::Lock, availability) + .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); + assert_eq!(status, DpnsVoteTargetStatus::Unconfirmed); + assert!(status.holds_lock()); + } + assert!(voting_ended_outcome(contests.first(), now).is_some()); + } + } + + #[test] + fn poll_availability_requires_a_cached_decided_contest() { let (_temp, context) = vote_context(); assert_eq!( - dpns_vote_poll_availability(None, 1_000), + dpns_vote_poll_availability(None), DpnsVotePollAvailability::MayAccept, "an uncached contest is unknown, not closed" ); - for (end_time, closed, now_ms, expected) in [ - ( - Some(2_000), - false, - 1_000, - DpnsVotePollAvailability::MayAccept, - ), - (None, false, 1_000, DpnsVotePollAvailability::MayAccept), - ( - Some(1_000), - false, - 1_000, - DpnsVotePollAvailability::ProvedClosed, - ), - ( - Some(2_000), - true, - 1_000, - DpnsVotePollAvailability::ProvedClosed, - ), + 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(), now_ms), + dpns_vote_poll_availability(contests.first()), expected, - "end_time {end_time:?}, closed {closed}, now {now_ms}" + "end_time {end_time:?}, closed {closed}" ); } } @@ -2789,7 +2788,7 @@ mod tests { crate::model::contested_name::ContestState::Unknown ); - let availability = dpns_vote_poll_availability(Some(skeleton), 5_000); + let availability = dpns_vote_poll_availability(Some(skeleton)); assert_eq!(availability, DpnsVotePollAvailability::MayAccept); assert_eq!( voting_ended_outcome(Some(skeleton), 5_000), diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index a4be9d12c..8a74e6657 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -247,6 +247,7 @@ impl AppContext { /// main-name choices and seen outcomes without touching storage per frame. pub(crate) fn refresh_pending_dpns_usernames(&self) -> Result<(), TaskError> { 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)) @@ -255,14 +256,11 @@ impl AppContext { let Some(id) = identity_from_key(&key, USERNAME_REQUESTS_KEY_PREFIX) else { continue; }; - match kv.get::>(DetScope::Global, &key) { - Ok(Some(requests)) => { - cache.requests.insert(id, requests); - } - Ok(None) => {} - Err(error) => { - tracing::warn!(key = %key, ?error, "Skipping unreadable username request list") - } + if let Some(requests) = kv + .get::>(DetScope::Global, &key) + .map_err(username_err)? + { + cache.requests.insert(id, requests); } } for key in kv @@ -270,7 +268,9 @@ impl AppContext { .map_err(username_err)? { if let Some(id) = identity_from_key(&key, MAIN_USERNAME_KEY_PREFIX) - && let Ok(Some(name)) = kv.get::(DetScope::Global, &key) + && let Some(name) = kv + .get::(DetScope::Global, &key) + .map_err(username_err)? { cache.main.insert(id, name); } @@ -280,12 +280,13 @@ impl AppContext { .map_err(username_err)? { if let Some(id) = identity_from_key(&key, SEEN_OUTCOMES_KEY_PREFIX) - && let Ok(Some(seen)) = kv.get::>(DetScope::Global, &key) + && let Some(seen) = kv + .get::>(DetScope::Global, &key) + .map_err(username_err)? { cache.seen.insert(id, seen); } } - let mut current = self.username_cache_mut(); cache.seen_marks = std::mem::take(&mut current.seen_marks); *current = cache; Ok(()) @@ -949,6 +950,133 @@ mod tests { } } + #[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 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) + ); + 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)] + ); + } + } + #[test] fn reloaded_expired_request_has_current_phase_without_rewriting_snapshot() { let temp_dir = tempfile::tempdir().unwrap(); diff --git a/src/context/dpns_vote_attention.rs b/src/context/dpns_vote_attention.rs index e6e49ef23..5362fb504 100644 --- a/src/context/dpns_vote_attention.rs +++ b/src/context/dpns_vote_attention.rs @@ -158,14 +158,12 @@ impl AppContext { /// Drop vote counts for polls the contest cache proves closed. pub(crate) fn forget_closed_dpns_vote_counts(&self) { - let now = now_ms(); let closed: BTreeSet = self .all_contested_names() .unwrap_or_default() .iter() .filter(|contest| { - dpns_vote_poll_availability(Some(contest), now) - == DpnsVotePollAvailability::ProvedClosed + dpns_vote_poll_availability(Some(contest)) == DpnsVotePollAvailability::ProvedClosed }) .filter_map(|contest| { self.dpns_vote_poll_id(&contest.normalized_contested_name) diff --git a/src/model/dpns_voting/mod.rs b/src/model/dpns_voting/mod.rs index 0f06fc938..209cbed02 100644 --- a/src/model/dpns_voting/mod.rs +++ b/src/model/dpns_voting/mod.rs @@ -44,25 +44,20 @@ 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 is decided or its deadline has passed. + /// The contest has an authoritative terminal outcome. ProvedClosed, } /// Classify a poll from its cached contest, if DET has one. /// -/// `now_ms` is the current wall clock in Unix milliseconds, matched against the -/// contest deadline. Returns [`DpnsVotePollAvailability::MayAccept`] for a -/// contest DET has never cached or whose state is still unknown. +/// 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>, - now_ms: u64, ) -> DpnsVotePollAvailability { let Some(contest) = contest else { return DpnsVotePollAvailability::MayAccept; }; - let decided = contest.state.is_decided(); - let expired = contest.end_time.is_some_and(|end| end <= now_ms); - if decided || expired { + if contest.state.is_decided() { DpnsVotePollAvailability::ProvedClosed } else { DpnsVotePollAvailability::MayAccept diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 719fc2231..4b55a800f 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -445,6 +445,8 @@ pub struct DPNSScreen { 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. @@ -562,6 +564,8 @@ impl DPNSScreen { 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(), @@ -628,6 +632,8 @@ impl DPNSScreen { 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; @@ -1274,11 +1280,17 @@ impl DPNSScreen { ui.horizontal(|ui| { ui.label(RichText::new(tray_label(decisions, transactions)).strong()); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ComponentStyles::add_primary_button_enabled(ui, transactions > 0, "Cast") - .disabled_tooltip( - "Your nodes already hold these choices. Pick a different decision.", - ) - .clicked() + if ComponentStyles::add_primary_button_enabled( + ui, + transactions > 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(); } @@ -1291,6 +1303,9 @@ impl DPNSScreen { /// 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_voter = None; self.node_overrides.clear(); self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; @@ -2348,6 +2363,9 @@ impl DPNSScreen { } fn bulk_apply_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) => { @@ -2391,6 +2409,13 @@ impl DPNSScreen { }; self.retry_voter = None; self.pending_vote_operation = Some(operation.id); + 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, @@ -2495,6 +2520,8 @@ impl ScreenLike for DPNSScreen { } 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; // The review window disables both Submit and Cancel while a // submission is in flight, so a failed submission must leave that @@ -2550,14 +2577,20 @@ impl ScreenLike for DPNSScreen { let owns_result = self.pending_vote_operation == Some(operation_id); if owns_result { self.pending_vote_operation = None; - if matches!( - self.bulk_vote_handling_status, - VoteHandlingStatus::CastingVotes | VoteHandlingStatus::SchedulingVotes - ) { - self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; - self.selected_votes.clear(); - self.selected_cards.clear(); - } + self.bulk_vote_handling_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!( @@ -2608,7 +2641,9 @@ impl ScreenLike for DPNSScreen { let mut action = AppAction::None; // `Review again` from the progress drawer, which lives outside this panel. - if let Some(outcome) = self.app_context.take_dpns_vote_review_request() { + 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); } @@ -2970,15 +3005,13 @@ mod tests { /// panel's own operation reports, never on another operation's update. #[test] fn own_operation_result_clears_staged_decisions_without_an_overlay() { - let (ctx, _temp_dir) = offline_ctx(); - let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); - screen.selected_votes = vec![SelectedVote { - contested_name: "alpha".to_owned(), - vote_choice: ResourceVoteChoice::Lock, - end_time: None, - }]; - screen.bulk_vote_handling_status = VoteHandlingStatus::CastingVotes; - screen.pending_vote_operation = Some(DpnsVoteOperationId::from_bytes([7; 16])); + let (mut screen, _temp_dir) = voting_ui_review_fixture(); + let ctx = Arc::clone(&screen.app_context); + assert!(matches!( + screen.bulk_apply_votes(), + AppAction::BackendTask(_) + )); + let operation_id = screen.pending_vote_operation.unwrap(); screen.display_task_result(BackendTaskSuccessResult::DpnsVoteOperationUpdated { network: ctx.network(), @@ -2992,7 +3025,7 @@ mod tests { .insert(pending_scheduled_key(&ctx), BackendTaskContext::Unknown); screen.display_task_result(BackendTaskSuccessResult::DpnsVoteOperationUpdated { network: ctx.network(), - operation_id: DpnsVoteOperationId::from_bytes([7; 16]), + operation_id, }); assert!(screen.selected_votes.is_empty()); @@ -3503,6 +3536,73 @@ mod tests { (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.bulk_apply_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.bulk_apply_votes(), + AppAction::BackendTask(_) + )); + let operation_id = screen.pending_vote_operation; + screen.show_bulk_schedule_popup = false; + screen.open_review_for_node_set(); + assert!(!screen.show_bulk_schedule_popup); + assert!(matches!( + screen.bulk_vote_handling_status, + VoteHandlingStatus::CastingVotes + )); + assert!(matches!(screen.bulk_apply_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.bulk_apply_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; From d9c5787cd050535f2e503976e641f00b5d43cd63 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 5 Oct 2026 10:28:41 +0000 Subject: [PATCH 117/194] perf(dpns): count authoritative outcomes in one journal pass Preserve vote authority ordering and consolidate release notes around the final voting and username features. Co-Authored-By: Codex --- CHANGELOG.md | 109 +++++++++++------------------ src/context/dpns_vote_attention.rs | 72 ++++++++++++++++--- 2 files changed, 103 insertions(+), 78 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 09e0863ca..c36390036 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -151,44 +151,45 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). evonode from *Identities β†’ Load Existing Identity β†’ Show Advanced Options*, which no longer offers those identity types. -- **Username voting in Masternodes β†’ Votes**: decide name contests across - your masternodes in one place, with To decide / Voted / Scheduled / History - views, node-set selection, bulk choices, and one confirmation for the batch. - Cards show weighted tallies and your nodes' influence. 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. - Review shows each node's current and requested choice and remaining vote - changes, or Unknown when the local history cannot establish the count. - Refresh updates the visible contests and vote state. Unnamed nodes use the - same shortened ProTxHash throughout voting and progress views. Attention - summaries reflect authoritative vote outcomes and warn against resubmitting - votes whose results are still uncertain. +- **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, node counts and timing. 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. - A progress drawer lets you keep working while votes are sent. - Decisions staged or changed during submission remain available afterward. - Uncertain results stay visible and blocked from repeat submission. - Passing the estimated deadline alone does not release an uncertain vote. - Unresolved operations remain accessible after a contest closes and are - not displaced by newer completed votes. Failed scheduled attempts retain - an actionable explanation after restarting the app. - Scheduled votes retain the selected UTC time and can be edited before - execution starts. New schedules must precede the contest's known deadline; - checking older uncertain votes does not discard schedules already due. - Removing a node cancels its unstarted scheduled votes. - Contests remain readable without a voting key, and a missing voting key - can be added from the node's detail page without replacing its other keys. - -- **Usernames in Identities**: check a name's availability, request it, and - follow its status without opening the voting screen. Names that need a - community vote show the non-refundable fee before payment; availability - is checked again before registration. Request status shows the timeline, - tally, and outcome, and suggests alternatives that need no vote. - Request refreshes preserve concurrent edits and retain saved requests when - storage cannot be read. - Profile β†’ Usernames lists your names and requests, with a "Show as main" - choice for the username displayed when no profile display name is set. - The former DPNS tool entry is removed; old voting shortcuts open - Masternodes β†’ Votes, and old username shortcuts open Identities. + 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 keeps other work + available, and decisions staged or changed during submission survive its + completion. Uncertain votes stay visible and blocked from resubmission; + passing the estimated deadline alone does not release 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. Refresh bursts yield between frames, and unresolved counts + use one pass through the vote journal. 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; + returning from a top-up preserves the chosen name and payment review. + 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. Refresh preserves concurrent identity edits and keeps + the previous request snapshot when storage cannot be read. + 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 @@ -202,36 +203,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed -- Large voting refresh bursts yield between frames so the window remains responsive while queued results are delivered. - -- Votes distinguishes missing nodes from missing voting keys, and node detail refresh reloads cached votes. -- Bulk voting reports confirmed and failed targets together while scheduled preflight failures remain retryable. -- Relative schedule labels follow vote journal retention and clear when the scheduled time changes. -- Exhausted voting limits consistently describe four changes after the initial vote. - -- Refreshing owned usernames preserves concurrent identity alias and key edits. -- Ambiguous vote broadcasts remain locked while their results are checked. Failed recovery - retries only affected targets and cannot release another active voter's claim. -- Holding Enter cannot submit the vote confirmation. Scheduled vote errors release their - own controls during bulk submissions, and card refreshes show the shared progress state. -- Username request badges reflect the joining and voting phases consistently, and voting - choices and feedback use shared labels and complete translation-ready sentences. - -- Returning from a successful identity top-up refreshes the balance on - "Get a username" without clearing the chosen name or payment review. -- Username registration stays blocked while its payment is in progress, - even when an unrelated background task fails. Username updates preserve - concurrent changes to the identity's keys. -- Vote choices show identity handles to distinguish similar names. - "Cast now" leaves other nodes' queued votes untouched, and failed contest - refreshes can be retried. - -- DPNS vote confirmation now highlights the name and chosen vote in separate - blocks, explains Lock and Abstain, and separates the previous vote and timing. - -- DPNS scheduled retries keep the selected choice, and simultaneous scheduled votes share fresh voting information without losing their due status. If a first vote becomes a vote change before submission, DET asks for another review. Unavailable voting information stays visible with a refresh action, successful mixed batches report both cast and scheduled votes, and contest refresh remains available when saved voting progress cannot be recovered. -- DPNS voting now explains missed automatic schedules and unreadable saved progress, with manual recovery actions. Completed scheduled and mixed voting history is bounded without discarding unresolved votes or restoring removed schedules. Adding another node's voting key gives a key-specific error. - - Restoring imported keys remains recoverable after interrupted storage writes and reports unreadable protected keys. Startup migration preserves existing keys, seeds, and their password protection. @@ -919,6 +890,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Removed +- 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). diff --git a/src/context/dpns_vote_attention.rs b/src/context/dpns_vote_attention.rs index 5362fb504..dee0847df 100644 --- a/src/context/dpns_vote_attention.rs +++ b/src/context/dpns_vote_attention.rs @@ -12,8 +12,8 @@ use crate::model::dpns_voting::operator::{ }; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOutcome, DpnsVotePollAvailability, - DpnsVoteTargetKey, DpnsVoteTargetStatus, authoritative_dpns_vote_outcome, - dpns_vote_lock_holders, dpns_vote_poll_availability, + DpnsVoteTargetKey, DpnsVoteTargetStatus, dpns_vote_authority_rank, dpns_vote_lock_holders, + dpns_vote_poll_availability, }; use crate::model::qualified_identity::IdentityType; use crate::utils::time::now_ms; @@ -25,15 +25,25 @@ use std::sync::Arc; /// Distinct targets whose authoritative outcome is still `Unconfirmed`. pub(crate) fn unresolved_target_count(operations: &[DpnsVoteOperation]) -> usize { - let keys: BTreeSet<&DpnsVoteTargetKey> = operations - .iter() - .flat_map(|operation| operation.targets.iter().map(|outcome| &outcome.target.key)) - .collect(); - keys.into_iter() - .filter(|key| { - authoritative_dpns_vote_outcome(operations, key) - .is_some_and(|outcome| outcome.status == DpnsVoteTargetStatus::Unconfirmed) - }) + let mut authoritative = BTreeMap::new(); + for operation in operations { + for outcome in &operation.targets { + let rank = dpns_vote_authority_rank( + operation.created_at, + outcome.operation_id, + outcome.status, + ); + let entry = authoritative + .entry(&outcome.target.key) + .or_insert((rank, outcome.status)); + if rank >= entry.0 { + *entry = (rank, outcome.status); + } + } + } + authoritative + .values() + .filter(|(_, status)| *status == DpnsVoteTargetStatus::Unconfirmed) .count() } @@ -423,6 +433,46 @@ mod tests { 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] From 281bfd97acaf6caaaf44b7b22c40095197b76203 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:24:51 +0000 Subject: [PATCH 118/194] refactor(dpns)!: use only the vote journal for schedules MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove legacy schedule import, mirror writes, fallback rows and cleanup. Detect unexecuted SQLite schedules at startup and ask users to review and cast or schedule them again. Treat the old KV schedule format as unused. Preserve journal locking, restart recovery, retention and identity-removal regressions with storage-independent fault injection. Co-Authored-By: Codex πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 19 +- .../01-requirements.md | 5 +- .../03-test-case-spec.md | 4 +- .../04-development-plan.md | 2 +- docs/user-stories.md | 17 +- src/app.rs | 39 + .../contested_names/edit_scheduled_vote.rs | 5 +- src/backend_task/contested_names/mod.rs | 242 ++--- src/backend_task/error.rs | 20 +- src/backend_task/migration/finish_unwire.rs | 292 +----- src/backend_task/migration/v093_upgrade.rs | 46 +- src/context/contested_names_db.rs | 6 +- src/context/dpns_vote_operations/mod.rs | 724 +++------------ src/context/dpns_vote_operations/retention.rs | 68 +- src/context/identity_db.rs | 859 +----------------- src/context/legacy_scheduled_votes.rs | 131 +++ src/context/mod.rs | 1 + src/model/dpns_voting/mod.rs | 4 +- src/ui/dpns/dpns_contested_names_screen.rs | 67 +- .../scheduled_vote_editor.rs | 6 +- src/ui/state/dpns_vote_operations.rs | 168 +--- src/wallet_backend/kv.rs | 7 + src/wallet_backend/kv_test_support.rs | 21 +- 23 files changed, 526 insertions(+), 2227 deletions(-) create mode 100644 src/context/legacy_scheduled_votes.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index c36390036..6c8ae796b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -890,6 +890,10 @@ 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 users to review and cast or schedule those votes again. + - 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. @@ -988,16 +992,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/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 index 9881d3414..4511b334f 100644 --- 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 @@ -267,8 +267,9 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. with an actionable status. - **VOTE-FR-053** β€” Unconfirmed scheduled targets are not automatically rebroadcast. -- **VOTE-FR-054** β€” Existing scheduled-vote records migrate without losing node, - contest, choice, time, or executed state. +- **VOTE-FR-054** β€” Schedules use only the voting journal. Startup reports + unexecuted schedules in previous SQLite storage and asks the user to cast or + schedule them again; it neither imports nor executes them automatically. - **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 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 index f6ebad9a5..7cbf3092c 100644 --- 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 @@ -65,11 +65,11 @@ K = kittest, B = backend test with fake SDK seam. | 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 migration +## Scheduling and upgrade notices | ID | Description | Preconditions | Steps | Expected outcome | Requirements | |---|---|---|---|---|---| -| VOTE-TC-060 | Legacy schedule migration | Existing scheduled-vote records | Upgrade | Node, contest, choice, time, and executed state are preserved | FR-054 | +| 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 | 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 index 9ac165b1d..63c7d9386 100644 --- 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 @@ -97,7 +97,7 @@ runs on a timer of about 60 s in `AppState::update()`. 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 mirror terminal outcomes to legacy schedules. +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)`. diff --git a/docs/user-stories.md b/docs/user-stories.md index dac43c02b..079781a2f 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -751,7 +751,7 @@ 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. - 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. @@ -884,15 +884,16 @@ As a user, I want my identity's Display name to identify it throughout the app s - 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 review and 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 persistent, dismissible notice directs me to Masternodes β†’ Votes to make a new decision. +- Old schedules are neither imported 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 request [Implemented] **Persona:** Alex @@ -1569,7 +1570,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. --- diff --git a/src/app.rs b/src/app.rs index 2cad97273..5fbe62c5b 100644 --- a/src/app.rs +++ b/src/app.rs @@ -225,6 +225,20 @@ fn show_legacy_settings_import_warning(ctx: &egui::Context, error: &impl std::fm handle.with_details(error); } +fn notify_legacy_scheduled_votes(app_context: &AppContext) { + let ctx = app_context.egui_ctx(); + match app_context.has_legacy_scheduled_votes() { + Ok(true) => { + let network = app_context.network; + MessageBanner::set_global(ctx, format!("Some scheduled votes from an earlier version on {network} will not run automatically. Open Masternodes > Votes to review them and cast or schedule them again."), 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 { @@ -2129,6 +2143,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 @@ -4241,6 +4256,30 @@ mod migration_banner_tests { )); } + #[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()); + } + #[test] fn failed_legacy_settings_import_raises_a_sticky_warning() { use crate::backend_task::migration::legacy_settings::SettingsImportError; diff --git a/src/backend_task/contested_names/edit_scheduled_vote.rs b/src/backend_task/contested_names/edit_scheduled_vote.rs index dddf26c15..6bc782846 100644 --- a/src/backend_task/contested_names/edit_scheduled_vote.rs +++ b/src/backend_task/contested_names/edit_scheduled_vote.rs @@ -58,10 +58,7 @@ impl AppContext { }, }, )?; - let (operation_id, mirror_error) = self.edit_scheduled_dpns_vote_target(&edit)?; - if let Some(error) = mirror_error { - tracing::warn!(?error, %operation_id, "DPNS schedule edit was journaled but its compatibility mirror could not be updated"); - } + 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 b318ec687..54ffc5454 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -66,14 +66,12 @@ pub enum ContestedResourceTask { }, ClearAllScheduledVotes, ClearExecutedScheduledVotes, - DeleteScheduledVote(Identifier, String), CancelScheduledDpnsVote { operation_id: DpnsVoteOperationId, key: DpnsVoteTargetKey, - contested_name: String, }, EditScheduledDpnsVote { - operation_id: Option, + operation_id: DpnsVoteOperationId, key: DpnsVoteTargetKey, expected_choice: ResourceVoteChoice, expected_timestamp: u64, @@ -189,14 +187,6 @@ fn classify_reconciled_vote( } } -fn persist_terminal_then_legacy_mirror( - persist_terminal: impl FnOnce() -> Result<(), TaskError>, - update_legacy_mirror: impl FnOnce() -> Result<(), TaskError>, -) -> Result, TaskError> { - persist_terminal()?; - Ok(update_legacy_mirror().err()) -} - fn wrap_scheduled_vote_sweep_result( network: Network, result: Result, @@ -329,21 +319,8 @@ impl AppContext { self.clear_executed_scheduled_votes()?; Ok(BackendTaskSuccessResult::Refresh) } - ContestedResourceTask::DeleteScheduledVote(voter_id, contested_name) => { - let key = DpnsVoteTargetKey { - network: self.network, - voter_id, - vote_poll_id: self.dpns_vote_poll_id(&contested_name)?, - }; - self.remove_scheduled_dpns_vote(None, &key, &contested_name)?; - Ok(BackendTaskSuccessResult::Refresh) - } - ContestedResourceTask::CancelScheduledDpnsVote { - operation_id, - key, - contested_name, - } => { - self.cancel_scheduled_dpns_vote_target(operation_id, &key, &contested_name)?; + ContestedResourceTask::CancelScheduledDpnsVote { operation_id, key } => { + self.cancel_scheduled_dpns_vote_target(operation_id, &key)?; Ok(BackendTaskSuccessResult::Refresh) } ContestedResourceTask::EditScheduledDpnsVote { @@ -381,7 +358,6 @@ impl AppContext { } return Ok(()); } - self.migrate_dpns_vote_operations()?; self.recover_interrupted_dpns_vote_operations()?; let queued = self .dpns_vote_operations()? @@ -448,35 +424,34 @@ impl AppContext { vote_poll_id: self.dpns_vote_poll_id(&scheduled_vote.contested_name)?, }; let operations = self.dpns_vote_operations()?; - if let Some(outcome) = preferred_outcome_for_scheduled_key(&operations, &key)?.cloned() { - 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 => { + 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); } - 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 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. } } @@ -689,52 +664,7 @@ impl AppContext { .retain(|outcome| requested_keys.contains(&outcome.target.key)); } else { self.validate_new_dpns_schedules(&new_schedules)?; - let scheduled_votes = operation - .targets - .iter() - .filter_map(|outcome| match outcome.target.timing { - VoteTiming::Scheduled(unix_timestamp) => Some(ScheduledDPNSVote { - contested_name: outcome.target.contested_name.clone(), - voter_id: outcome.target.key.voter_id, - choice: outcome.target.requested_choice, - unix_timestamp, - executed_successfully: false, - }), - VoteTiming::Now => None, - }) - .collect::>(); - if let Some(error) = self.insert_dpns_vote_operation_with_scheduled_mirror( - &mut operation, - replacing_scheduled_key.as_ref(), - &scheduled_votes, - )? { - // The journal is authoritative. The legacy table is a - // compatibility mirror, so its failure cannot turn a durable - // schedule into a reported failure that invites a duplicate. - tracing::warn!( - ?error, - operation_id = %operation.id, - "DPNS vote schedule was journaled but its legacy mirror could not be updated" - ); - } - } - - for outcome in operation.targets.iter().filter(|outcome| { - outcome.status == DpnsVoteTargetStatus::Confirmed - && matches!(outcome.target.timing, VoteTiming::Scheduled(_)) - }) { - if let Err(error) = self.mark_vote_executed( - outcome.target.key.voter_id.as_slice(), - outcome.target.contested_name.clone(), - ) { - tracing::warn!( - ?error, - operation_id = %operation.id, - voter_id = %outcome.target.key.voter_id, - contested_name = %outcome.target.contested_name, - "Confirmed DPNS vote was journaled but its legacy mirror could not be updated" - ); - } + self.insert_dpns_vote_operation(&mut operation, replacing_scheduled_key.as_ref())?; } let voters_by_id: BTreeMap = voters @@ -904,37 +834,12 @@ impl AppContext { } } } - let mirror_error = persist_terminal_then_legacy_mirror( - || { - app_context.update_dpns_vote_target( - operation_id, - &target.key, - status, - failure, - ) - }, - || { - if confirmed - && matches!(target.timing, VoteTiming::Scheduled(_)) - { - app_context.mark_vote_executed( - target.key.voter_id.as_slice(), - target.contested_name.clone(), - ) - } else { - Ok(()) - } - }, + app_context.update_dpns_vote_target( + operation_id, + &target.key, + status, + failure, )?; - if let Some(error) = mirror_error { - tracing::warn!( - ?error, - operation_id = %operation_id, - voter_id = %target.key.voter_id, - contested_name = %target.contested_name, - "DPNS vote reached a terminal journal state but its legacy mirror could not be updated" - ); - } if confirmed { app_context.cache_confirmed_dpns_vote( target.key.voter_id, @@ -1093,20 +998,6 @@ impl AppContext { if status != DpnsVoteTargetStatus::Confirmed { continue; } - if matches!(outcome.target.timing, VoteTiming::Scheduled(_)) - && let Err(error) = self.mark_vote_executed( - outcome.target.key.voter_id.as_slice(), - outcome.target.contested_name.clone(), - ) - { - tracing::warn!( - ?error, - operation_id = %operation_id, - voter_id = %outcome.target.key.voter_id, - contested_name = %outcome.target.contested_name, - "Reconciled DPNS vote reached a terminal journal state but its legacy mirror could not be updated" - ); - } self.cache_confirmed_dpns_vote( outcome.target.key.voter_id, poll_id, @@ -1327,7 +1218,6 @@ mod tests { use crate::model::qualified_identity::{IdentityStatus, IdentityType}; use dash_sdk::dpp::identity::Identity; use dash_sdk::dpp::version::PlatformVersion; - use std::cell::RefCell; use std::collections::{BTreeMap, BTreeSet}; fn dapi_connection_refused_error() -> TaskError { @@ -1374,6 +1264,43 @@ mod tests { (temp, context) } + #[test] + 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!( + 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, @@ -1497,8 +1424,7 @@ mod tests { .relative_schedule_preset_ms, Some(600_000) ); - ctx.remove_scheduled_dpns_vote(Some(operation.id), &key, "alice") - .unwrap(); + ctx.remove_scheduled_dpns_vote(operation.id, &key).unwrap(); let prefix = format!("{}:dpns_voting:relative:", ctx.network()); assert!( ctx.app_kv() @@ -1745,7 +1671,7 @@ mod tests { ) .unwrap(); context - .insert_dpns_vote_operation_with_scheduled_mirror(&mut retry, None, &[scheduled]) + .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); @@ -1942,7 +1868,6 @@ mod tests { Err(TaskError::DpnsScheduledVoteInvalidTime) )); assert!(context.dpns_vote_operations().unwrap().is_empty()); - assert!(context.get_scheduled_votes().unwrap().is_empty()); for name in ["missing", "closed"] { if name == "closed" { context.seed_dpns_contest_for_test(name, None, true); @@ -2476,25 +2401,6 @@ mod tests { ); } - #[test] - fn terminal_journal_write_precedes_best_effort_legacy_mirror() { - let events = RefCell::new(Vec::new()); - let mirror_error = persist_terminal_then_legacy_mirror( - || { - events.borrow_mut().push("journal"); - Ok(()) - }, - || { - events.borrow_mut().push("legacy"); - Err(TaskError::DpnsVoteTargetBusy) - }, - ) - .expect("the authoritative journal write succeeded"); - - assert!(mirror_error.is_some()); - assert_eq!(events.into_inner(), vec!["journal", "legacy"]); - } - #[test] fn scheduled_terminal_or_unconfirmed_targets_are_not_due_for_rebroadcast() { for status in [ diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 51a04d4e2..79e6fff49 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1060,14 +1060,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. @@ -1247,15 +1244,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. diff --git a/src/backend_task/migration/finish_unwire.rs b/src/backend_task/migration/finish_unwire.rs index 88fbf1bd5..67ab9833e 100644 --- a/src/backend_task/migration/finish_unwire.rs +++ b/src/backend_task/migration/finish_unwire.rs @@ -214,16 +214,6 @@ 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). /// Wrapped so the combined [`MigrationState::FailedWithUnreadableIdentities`] @@ -1269,11 +1259,7 @@ 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)) } @@ -1511,23 +1497,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; @@ -1566,33 +1536,12 @@ fn migrate_app_data(app_context: &Arc) -> 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, @@ -1608,10 +1557,7 @@ fn migrate_app_data(app_context: &Arc) -> Result( +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, ) -> Result<(), TaskError>, { - 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); - } + let mut outcome = AppDataMigrationOutcome { + votes_unreadable: crate::database::legacy_import::read_scheduled_votes(conn, network) + .map_err(|source| MigrationError::LegacyDbRead { + table: "scheduled_votes", + source, + })? + .unreadable, + ..Default::default() + }; - // 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; @@ -2105,12 +2022,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 } } @@ -3463,15 +3374,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]; @@ -3518,113 +3427,26 @@ 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. - #[test] - fn unreadable_vote_row_is_counted_without_failing_the_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()], - ) - .expect("corrupt vote"); - - 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"); - - 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"); - } - /// 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, @@ -3634,13 +3456,9 @@ mod tests { 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 { .. })), @@ -3658,16 +3476,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); @@ -3689,13 +3501,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!( @@ -3714,21 +3520,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); @@ -6722,11 +6522,9 @@ 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 and are reported without being queued. + assert!(ctx.dpns_vote_operations().unwrap().is_empty()); + assert!(ctx.has_legacy_scheduled_votes().unwrap()); assert_eq!( *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { @@ -6774,20 +6572,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!( @@ -7150,9 +6944,9 @@ mod tests { not swallow a vote with a live deadline", ); - // 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"); + // Old votes require a fresh decision instead of an automatic import. + assert!(ctx.dpns_vote_operations().unwrap().is_empty()); + assert!(ctx.has_legacy_scheduled_votes().unwrap()); // 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 diff --git a/src/backend_task/migration/v093_upgrade.rs b/src/backend_task/migration/v093_upgrade.rs index e984e561c..3425af95f 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; diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 8a74e6657..d2b08f788 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -1378,11 +1378,7 @@ mod tests { .has_failed_scheduled_vote ); context - .remove_scheduled_dpns_vote( - Some(operation.id), - &operation.targets[0].target.key, - "alice", - ) + .remove_scheduled_dpns_vote(operation.id, &operation.targets[0].target.key) .unwrap(); let summary = context.masternode_contest_summary(Some(voter_id)).unwrap(); assert!( diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index e1a479135..8186ced70 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -12,17 +12,12 @@ use retention::*; use transitions::*; use super::AppContext; -use crate::backend_task::contested_names::ScheduledDPNSVote; use crate::backend_task::error::TaskError; -use crate::context::identity_db::{ - delete_scheduled_vote_in, durable_scheduled_vote_keys, insert_scheduled_votes_in, -}; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome, DpnsScheduledVoteEdit, DpnsScheduledVoteKey, DpnsVoteAuthorityRank, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, - DpnsVoteTargetStatus, VoteTiming, authoritative_dpns_vote_outcome, dpns_vote_authority_rank, - unavailable_preflight_outcome, + DpnsVoteTargetStatus, VoteTiming, dpns_vote_authority_rank, unavailable_preflight_outcome, }; use crate::utils::time::now_ms; use crate::wallet_backend::{DetKv, DetScope}; @@ -414,10 +409,7 @@ fn operation_for_schedule_edit( return Err(TaskError::DpnsScheduledVoteNotEditable); } let locks = load_or_rebuild_lock_index(kv, network)?; - let id = edit - .operation_id - .or_else(|| locks.get(&edit.key).copied()) - .ok_or(TaskError::DpnsScheduledVoteNotEditable)?; + let id = edit.operation_id; if locks.get(&edit.key) != Some(&id) { return Err(TaskError::DpnsScheduledVoteNotEditable); } @@ -437,8 +429,8 @@ fn operation_for_schedule_edit( impl AppContext { /// Take the process-wide journal guard, recovering from a poisoned lock. /// - /// Every read and write of the operation journal, its lock index and its - /// compatibility mirror must be serialized behind this one guard; a method + /// 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<'_, ()> { @@ -469,11 +461,11 @@ impl AppContext { .ok_or(TaskError::DpnsScheduledVoteNotEditable) } - /// Apply a validated edit under one journal/mirror guard without releasing its target lock. + /// 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<(DpnsVoteOperationId, Option), TaskError> { + ) -> Result { let (_guard, kv) = self.journal()?; let mut operation = operation_for_schedule_edit(&kv, self.network, edit)?; if edit.unix_timestamp <= now_ms() { @@ -490,18 +482,8 @@ impl AppContext { } outcome.target.timing = VoteTiming::Scheduled(edit.unix_timestamp); outcome.failure = None; - let mirror = ScheduledDPNSVote { - contested_name: outcome.target.contested_name.clone(), - voter_id: edit.key.voter_id, - choice: edit.choice, - unix_timestamp: edit.unix_timestamp, - executed_successfully: false, - }; persist_operation(&kv, self.network, &operation)?; - Ok(( - operation.id, - insert_scheduled_votes_in(&kv, &[mirror]).err(), - )) + Ok(operation.id) } /// Durably claim one due scheduled target before any executor can observe it. @@ -534,35 +516,6 @@ impl AppContext { persist_operation(&kv, self.network, operation) } - /// Persist an operation and its compatibility mirror under one journal guard. - pub(crate) fn insert_dpns_vote_operation_with_scheduled_mirror( - &self, - operation: &mut DpnsVoteOperation, - replacing_scheduled_key: Option<&DpnsVoteTargetKey>, - scheduled_votes: &[ScheduledDPNSVote], - ) -> Result, TaskError> { - if operation - .targets - .iter() - .any(|outcome| outcome.target.key.network != self.network) - { - return Err(TaskError::DpnsVoteTargetBusy); - } - let (_guard, kv) = self.journal()?; - if let Some(key) = replacing_scheduled_key { - replace_scheduled_operation(&kv, self.network, operation, key)?; - } else { - persist_operation(&kv, self.network, operation)?; - } - // A repeated terminal update may have been retired by retention. - match load_operation(&kv, &operation_key(self.network, operation.id)) { - Ok(Some(_)) => {} - Ok(None) => return Ok(None), - Err(error) => return Ok(Some(unreadable_operation_err(error))), - } - Ok(insert_scheduled_votes_in(&kv, scheduled_votes).err()) - } - /// Persist updated target statuses while retaining the original operation ID. pub fn update_dpns_vote_operation( &self, @@ -605,40 +558,6 @@ impl AppContext { Ok(dismissed) } - /// Import stored scheduled votes before backend recovery. - pub(crate) fn migrate_dpns_vote_operations(&self) -> Result<(), TaskError> { - let (_guard, kv) = self.journal()?; - let mut operations = load_operations(&kv, self.network)?; - for legacy in self.get_scheduled_votes()? { - if operations.iter().any(|operation| { - operation.targets.iter().any(|outcome| { - outcome.target.key.voter_id == legacy.voter_id - && outcome.target.contested_name == legacy.contested_name - }) - }) { - continue; - } - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { - key: DpnsVoteTargetKey { - network: self.network, - voter_id: legacy.voter_id, - vote_poll_id: self.dpns_vote_poll_id(&legacy.contested_name)?, - }, - voter_alias: None, - contested_name: legacy.contested_name, - requested_choice: legacy.choice, - current_choice: None, - timing: VoteTiming::Scheduled(legacy.unix_timestamp), - }]); - if legacy.executed_successfully { - operation.targets[0].status = DpnsVoteTargetStatus::Confirmed; - } - persist_operation(&kv, self.network, &operation)?; - operations.push(operation); - } - Ok(()) - } - /// Votes this device saw Platform apply for one node Γ— poll; `None` /// when it holds no record. pub fn dpns_vote_count( @@ -891,32 +810,22 @@ impl AppContext { /// Remove a schedule only after its authoritative journal state permits it. pub(crate) fn remove_scheduled_dpns_vote( &self, - expected_operation_id: Option, + operation_id: DpnsVoteOperationId, key: &DpnsVoteTargetKey, - contested_name: &str, ) -> 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 = match expected_operation_id { - Some(operation_id) => operations - .iter() - .find(|operation| operation.id == operation_id) - .and_then(|operation| { - operation - .outcome(key) - .map(|outcome| (operation.id, outcome.status)) - }), - None => { - if lock_index.contains_key(key) { - return Err(TaskError::DpnsScheduledVoteAlreadyStarted); - } - authoritative_dpns_vote_outcome(&operations, key) - .map(|outcome| (outcome.operation_id, outcome.status)) - } - }; + let selected = operations + .iter() + .find(|operation| operation.id == operation_id) + .and_then(|operation| { + operation + .outcome(key) + .map(|outcome| (operation.id, outcome.status)) + }); - let journal_is_authoritative = match selected { + match selected { Some((operation_id, DpnsVoteTargetStatus::Scheduled)) => { if lock_index .get(key) @@ -927,7 +836,6 @@ impl AppContext { if !cancel_scheduled_target(&kv, self.network, operation_id, key)? { return Err(TaskError::DpnsScheduledVoteAlreadyStarted); } - true } Some(( _, @@ -944,29 +852,14 @@ impl AppContext { return Err(TaskError::DpnsScheduledVoteAlreadyStarted); } dismiss_scheduled_target(&kv, self.network, operation_id, key)?; - true } None => { if lock_index.contains_key(key) { return Err(TaskError::DpnsScheduledVoteAlreadyStarted); } - false } }; - let voter = key.voter_id.to_buffer(); - if let Err(error) = delete_scheduled_vote_in(&kv, &voter, contested_name) { - if !journal_is_authoritative { - return Err(error); - } - tracing::warn!( - ?error, - expected_operation_id = ?expected_operation_id, - voter_id = %key.voter_id, - contested_name, - "Scheduled DPNS vote journal was updated but its compatibility mirror remains" - ); - } Ok(()) } @@ -975,9 +868,16 @@ impl AppContext { &self, operation_id: DpnsVoteOperationId, key: &DpnsVoteTargetKey, - contested_name: &str, ) -> Result<(), TaskError> { - self.remove_scheduled_dpns_vote(Some(operation_id), key, contested_name) + 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. @@ -985,10 +885,9 @@ impl AppContext { &self, ) -> Result, TaskError> { let (_guard, kv) = self.journal()?; - let mut retained = BTreeSet::new(); let mut outcomes = BTreeMap::< DpnsScheduledVoteKey, - (Option, DpnsScheduledVoteClearOutcome), + (DpnsVoteAuthorityRank, DpnsScheduledVoteClearOutcome), >::new(); for mut operation in load_operations(&kv, self.network)? { @@ -1015,7 +914,6 @@ impl AppContext { | DpnsVoteTargetStatus::Submitting | DpnsVoteTargetStatus::Confirming | DpnsVoteTargetStatus::Unconfirmed => { - retained.insert(key.clone()); DpnsScheduledVoteClearDisposition::InFlight(status) } _ => { @@ -1031,12 +929,12 @@ impl AppContext { let rank = dpns_vote_authority_rank(operation.created_at, operation.id, status); let should_replace = outcomes .get(&key) - .is_none_or(|(existing_rank, _)| existing_rank.is_none_or(|old| rank > old)); + .is_none_or(|(existing_rank, _)| rank > *existing_rank); if should_replace { outcomes.insert( key.clone(), ( - Some(rank), + rank, DpnsScheduledVoteClearOutcome { operation_id: Some(operation.id), key, @@ -1051,36 +949,6 @@ impl AppContext { } } - let mirror_keys = durable_scheduled_vote_keys(&kv, self.network)?; - for key in mirror_keys { - let journal_is_authoritative = outcomes.contains_key(&key); - outcomes.entry(key.clone()).or_insert_with(|| { - ( - None, - DpnsScheduledVoteClearOutcome { - operation_id: None, - key: key.clone(), - disposition: DpnsScheduledVoteClearDisposition::Cleared, - }, - ) - }); - if retained.contains(&key) { - continue; - } - let voter = key.voter_id.to_buffer(); - if let Err(error) = delete_scheduled_vote_in(&kv, &voter, &key.contested_name) { - if !journal_is_authoritative { - return Err(error); - } - tracing::warn!( - ?error, - voter_id = %key.voter_id, - contested_name = %key.contested_name, - "Scheduled DPNS vote was cleared in the journal but its compatibility mirror remains" - ); - } - } - prune_terminal_operations(&kv, self.network)?; Ok(outcomes.into_values().map(|(_, outcome)| outcome).collect()) } @@ -1089,7 +957,6 @@ impl AppContext { #[cfg(test)] mod tests { use super::*; - use crate::backend_task::contested_names::ScheduledDPNSVote; use crate::model::dpns_voting::{ DpnsScheduledVoteClearDisposition, DpnsVoteTarget, VoteTiming, }; @@ -1195,17 +1062,6 @@ mod tests { operation } - fn scheduled_vote(operation: &DpnsVoteOperation) -> ScheduledDPNSVote { - let target = &operation.targets[0].target; - ScheduledDPNSVote { - contested_name: target.contested_name.clone(), - voter_id: target.key.voter_id, - choice: target.requested_choice, - unix_timestamp: 42, - executed_successfully: false, - } - } - /// 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. @@ -1255,9 +1111,7 @@ mod tests { ); let (_temp, context) = seed(); - context - .remove_scheduled_dpns_vote(None, &key, "alice") - .unwrap(); + context.remove_scheduled_dpns_vote(newer_id, &key).unwrap(); assert!( context .dismissed_dpns_vote_schedules() @@ -1290,10 +1144,10 @@ mod tests { let (_temp, context) = seed(); let rows = crate::ui::state::dpns_vote_operations::DpnsVoteOperationSnapshot::load(&context) - .scheduled_vote_rows(&[]); + .scheduled_vote_rows(); assert_eq!( rows.iter() - .map(|row| row.journal_target.as_ref().map(|(id, _)| *id)) + .map(|row| Some(row.journal_target.0)) .collect::>(), vec![Some(newer_id)], "Scheduled Votes must show the same operation the other sites prefer" @@ -1454,16 +1308,13 @@ mod tests { context .insert_dpns_vote_operation(&mut scheduled, None) .unwrap(); - context - .insert_scheduled_votes(&[scheduled_vote(&scheduled)]) - .unwrap(); context .queue_scheduled_dpns_vote_target(scheduled.id, &key) .unwrap(); assert!(matches!( context - .remove_scheduled_dpns_vote(Some(scheduled.id), &key, "dominguez") + .remove_scheduled_dpns_vote(scheduled.id, &key) .expect_err("queued targets must not be removed"), TaskError::DpnsScheduledVoteAlreadyStarted )); @@ -1471,7 +1322,6 @@ mod tests { context.dpns_vote_operations().unwrap()[0].targets[0].status, DpnsVoteTargetStatus::Queued ); - assert_eq!(context.get_scheduled_votes().unwrap().len(), 1); } #[test] @@ -1500,9 +1350,6 @@ mod tests { context .insert_dpns_vote_operation(&mut queued, None) .unwrap(); - context - .insert_scheduled_votes(&[scheduled_vote(&queued)]) - .unwrap(); let outcomes = context.clear_all_scheduled_dpns_votes().unwrap(); @@ -1510,7 +1357,6 @@ mod tests { context.dpns_vote_operations().unwrap()[0].targets[0].status, DpnsVoteTargetStatus::Queued ); - assert_eq!(context.get_scheduled_votes().unwrap().len(), 1); assert_eq!(outcomes.len(), 1); assert_eq!( outcomes[0].disposition, @@ -1519,7 +1365,7 @@ mod tests { } #[test] - fn scheduled_removal_persists_cancelled_before_best_effort_mirror_delete() { + 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()); @@ -1533,24 +1379,19 @@ mod tests { context .insert_dpns_vote_operation(&mut scheduled, None) .unwrap(); - context - .insert_scheduled_votes(&[scheduled_vote(&scheduled)]) - .unwrap(); - store.fail_next_deletes_containing("cancel-me", 1); context - .remove_scheduled_dpns_vote(Some(scheduled.id), &key, "cancel-me") + .remove_scheduled_dpns_vote(scheduled.id, &key) .unwrap(); assert_eq!( context.dpns_vote_operations().unwrap()[0].targets[0].status, DpnsVoteTargetStatus::Cancelled ); - assert_eq!(context.get_scheduled_votes().unwrap().len(), 1); } #[test] - fn stale_terminal_operation_cannot_remove_a_newer_locked_mirror() { + 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(); @@ -1564,17 +1405,13 @@ mod tests { context .insert_dpns_vote_operation(&mut current, None) .unwrap(); - context - .insert_scheduled_votes(&[scheduled_vote(¤t)]) - .unwrap(); assert!(matches!( context - .remove_scheduled_dpns_vote(Some(terminal.id), &key, "same-target") + .remove_scheduled_dpns_vote(terminal.id, &key) .expect_err("stale terminal history must not remove the current schedule"), TaskError::DpnsScheduledVoteAlreadyStarted )); - assert_eq!(context.get_scheduled_votes().unwrap().len(), 1); assert!( context .dpns_vote_operations() @@ -1587,60 +1424,6 @@ mod tests { ); } - #[test] - fn legacy_removal_without_expected_operation_deletes_an_unlocked_mirror() { - 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 voter_id = Identifier::from([12; 32]); - let key = DpnsVoteTargetKey { - network: context.network, - voter_id, - vote_poll_id: Identifier::from([13; 32]), - }; - context - .insert_scheduled_votes(&[ScheduledDPNSVote { - contested_name: "legacy-only".to_owned(), - voter_id, - choice: ResourceVoteChoice::Lock, - unix_timestamp: 42, - executed_successfully: false, - }]) - .unwrap(); - - context - .remove_scheduled_dpns_vote(None, &key, "legacy-only") - .unwrap(); - - assert!(context.get_scheduled_votes().unwrap().is_empty()); - } - - #[test] - fn legacy_removal_without_expected_operation_preserves_a_locked_mirror() { - 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, 12, "locked-target"); - let key = scheduled.targets[0].target.key.clone(); - context - .insert_dpns_vote_operation(&mut scheduled, None) - .unwrap(); - context - .insert_scheduled_votes(&[scheduled_vote(&scheduled)]) - .unwrap(); - - assert!(matches!( - context - .remove_scheduled_dpns_vote(None, &key, "locked-target") - .expect_err("a current journal lock must preserve the mirror"), - TaskError::DpnsScheduledVoteAlreadyStarted - )); - assert_eq!(context.get_scheduled_votes().unwrap().len(), 1); - } - #[test] fn clear_all_cancels_pending_and_retains_every_in_flight_target() { let temp_dir = tempfile::tempdir().expect("tempdir"); @@ -1655,41 +1438,14 @@ mod tests { ("unconfirmed", DpnsVoteTargetStatus::Unconfirmed), ("confirmed", DpnsVoteTargetStatus::Confirmed), ]; - let mut votes = Vec::new(); for (index, (name, status)) in cases.into_iter().enumerate() { let mut operation = scheduled_operation(status, index as u8 + 2, name); - votes.push(scheduled_vote(&operation)); context .insert_dpns_vote_operation(&mut operation, None) .unwrap(); } - votes.push(ScheduledDPNSVote { - contested_name: "legacy".to_owned(), - voter_id: Identifier::from([9; 32]), - choice: ResourceVoteChoice::Lock, - unix_timestamp: 42, - executed_successfully: false, - }); - context.insert_scheduled_votes(&votes).unwrap(); - let outcomes = context.clear_all_scheduled_dpns_votes().unwrap(); - - let remaining_names = context - .get_scheduled_votes() - .unwrap() - .into_iter() - .map(|vote| vote.contested_name) - .collect::>(); - assert_eq!( - remaining_names, - BTreeSet::from([ - "confirming".to_owned(), - "queued".to_owned(), - "submitting".to_owned(), - "unconfirmed".to_owned(), - ]) - ); - assert_eq!(outcomes.len(), 7); + assert_eq!(outcomes.len(), 6); for (name, status) in [ ("queued", DpnsVoteTargetStatus::Queued), ("submitting", DpnsVoteTargetStatus::Submitting), @@ -1701,56 +1457,25 @@ mod tests { && outcome.disposition == DpnsScheduledVoteClearDisposition::InFlight(status) })); } - for name in ["scheduled", "confirmed", "legacy"] { + for name in ["scheduled", "confirmed"] { assert!(outcomes.iter().any(|outcome| { outcome.key.contested_name == name && outcome.disposition == DpnsScheduledVoteClearDisposition::Cleared })); } - assert!(outcomes.iter().any(|outcome| { - outcome.key.contested_name == "legacy" && outcome.operation_id.is_none() - })); let remaining_operations = context.dpns_vote_operations().unwrap(); - assert_eq!(remaining_operations.len(), 4); - assert!(remaining_operations.iter().all(|operation| { - matches!( - operation.targets[0].status, - DpnsVoteTargetStatus::Queued - | DpnsVoteTargetStatus::Submitting - | DpnsVoteTargetStatus::Confirming - | DpnsVoteTargetStatus::Unconfirmed - ) - })); - } - - #[test] - fn combined_insert_reports_mirror_error_after_persisting_the_journal() { - 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, "mirror-fails"); - let vote = scheduled_vote(&scheduled); - store.fail_next_puts_containing("det:scheduled_vote:", 1); - - let mirror_error = context - .insert_dpns_vote_operation_with_scheduled_mirror(&mut scheduled, None, &[vote]) - .unwrap() - .expect("mirror failure must be returned separately"); - - assert!(matches!( - mirror_error, - TaskError::ScheduledVoteStorage { .. } - )); assert_eq!( - context.dpns_vote_operations().unwrap(), - vec![scheduled.clone()] + 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) ); - assert!(context.get_scheduled_votes().unwrap().is_empty()); } /// A corrupt indexed row must block lock reconstruction rather than being skipped. @@ -2027,46 +1752,8 @@ mod tests { ); } - #[tokio::test] - async fn operation_getter_does_not_migrate_legacy_scheduled_votes() { - let temp_dir = tempfile::tempdir().expect("tempdir"); - let store = Arc::new(CountingKv::default()); - let context = crate::context::test_support::test_app_context_with_kv( - temp_dir.path(), - Arc::new(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 - .insert_scheduled_votes(&[crate::backend_task::contested_names::ScheduledDPNSVote { - contested_name: "dominguez".to_owned(), - voter_id: Identifier::from([1; 32]), - choice: ResourceVoteChoice::Lock, - unix_timestamp: 42, - executed_successfully: false, - }]) - .unwrap(); - store.reset_counts(); - - assert!(context.dpns_vote_operations().unwrap().is_empty()); - assert_eq!( - store.put_count(), - 0, - "a named getter must not migrate or write legacy rows" - ); - - context.migrate_dpns_vote_operations().unwrap(); - assert_eq!(context.dpns_vote_operations().unwrap().len(), 1); - } - #[test] - fn pruning_removes_terminal_scheduled_and_mixed_but_retains_immediate_history() { + 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); @@ -2088,20 +1775,23 @@ mod tests { persist_operation(&kv, Network::Testnet, &mixed).unwrap(); persist_operation(&kv, Network::Testnet, &live).unwrap(); - assert_eq!(prune_terminal_operations(&kv, Network::Testnet).unwrap(), 2); + 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([immediate.id, live.id])); + 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_none() + .is_some() ); assert!( kv.get::( @@ -2117,42 +1807,12 @@ mod tests { &operation_key(Network::Testnet, mixed.id), ) .unwrap() - .is_none() - ); - } - - #[test] - fn retention_read_failure_keeps_durable_insert_successful() { - 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 mut scheduled = scheduled_operation(DpnsVoteTargetStatus::Scheduled, 2, "read-failure"); - let mirror = scheduled_vote(&scheduled); - store.fail_next_gets_containing(OPERATION_KEY_PREFIX, 1); - let mirror_error = context - .insert_dpns_vote_operation_with_scheduled_mirror(&mut scheduled, None, &[mirror]) - .expect("a post-persistence read failure must not invite another submission"); - assert!(mirror_error.is_some()); - assert_eq!( - context.dpns_vote_operation(scheduled.id).unwrap(), - Some(scheduled.clone()) - ); - assert_eq!( - context - .dpns_vote_target_status(&scheduled.targets[0].target.key) - .unwrap(), - Some(DpnsVoteTargetStatus::Scheduled) + .is_some() ); - assert!(context.get_scheduled_votes().unwrap().is_empty()); } #[test] - fn scheduled_and_mixed_history_is_bounded_with_mirrors() { + 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())); @@ -2172,18 +1832,11 @@ mod tests { .targets .push(operation(DpnsVoteTargetStatus::Confirmed).targets.remove(0)); } - let mirror = ScheduledDPNSVote { - contested_name: format!("history-{index}"), - voter_id: completed.targets[0].target.key.voter_id, - choice: ResourceVoteChoice::Lock, - unix_timestamp: 42, - executed_successfully: true, - }; if index == 0 { oldest = Some(completed.id); } context - .insert_dpns_vote_operation_with_scheduled_mirror(&mut completed, None, &[mirror]) + .insert_dpns_vote_operation(&mut completed, None) .unwrap(); } let mut unresolved = @@ -2201,162 +1854,8 @@ mod tests { .unwrap() .is_none() ); - assert_eq!(context.get_scheduled_votes().unwrap().len(), 256); - context.migrate_dpns_vote_operations().unwrap(); - assert_eq!( - context.dpns_vote_operations().unwrap().len(), - 257, - "pruned mirrors must not migrate back" - ); - assert_eq!( - context - .dpns_vote_target_status(&unresolved.targets[0].target.key) - .unwrap(), - Some(DpnsVoteTargetStatus::Unconfirmed) - ); - } - - #[test] - fn scheduled_retention_cleanup_failures_retry_safely() { - for failing_key in [ - "det:scheduled_vote:", - OPERATION_KEY_PREFIX, - SCHEDULE_DISMISSAL_KEY_PREFIX, - RELATIVE_LABEL_KEY_PREFIX, - ] { - 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.clone()); - let mut oldest = None; - // Fill the history to the prune threshold so the `newest` write below - // is the one that prunes, and meets the injected cleanup failure. - for index in 0..(DPNS_SCHEDULED_HISTORY_LIMIT + DPNS_HISTORY_PRUNE_SLACK) as u64 { - let mut completed = scheduled_operation( - DpnsVoteTargetStatus::Confirmed, - 2, - &format!("cleanup-{index}"), - ); - completed.created_at = index; - completed.targets[0].relative_schedule_preset_ms = Some(600_000); - if index == 0 { - oldest = Some(completed.clone()); - dismiss_scheduled_target( - &kv, - Network::Testnet, - completed.id, - &completed.targets[0].target.key, - ) - .unwrap(); - } - context - .insert_dpns_vote_operation_with_scheduled_mirror( - &mut completed.clone(), - None, - &[scheduled_vote(&completed)], - ) - .unwrap(); - } - let mut unresolved = - scheduled_operation(DpnsVoteTargetStatus::Unconfirmed, 3, "pending"); - context - .insert_dpns_vote_operation(&mut unresolved, None) - .unwrap(); - store.fail_next_deletes_containing(failing_key, 1); - let newest = scheduled_operation(DpnsVoteTargetStatus::Confirmed, 2, "newest"); - context - .insert_dpns_vote_operation_with_scheduled_mirror( - &mut newest.clone(), - None, - &[scheduled_vote(&newest)], - ) - .unwrap(); - assert!( - context.dpns_vote_operation(newest.id).unwrap().is_some(), - "cleanup failure must not undo a confirmed result" - ); - context.recover_interrupted_dpns_vote_operations().unwrap(); - let oldest = oldest.unwrap(); - assert_eq!(context.dpns_vote_operations().unwrap().len(), 257); - assert!(context.dpns_vote_operation(oldest.id).unwrap().is_none()); - assert!( - !context - .get_scheduled_votes() - .unwrap() - .iter() - .any(|vote| vote.contested_name == "cleanup-0") - ); - assert!(context.dismissed_dpns_vote_schedules().unwrap().is_empty()); - assert_eq!( - context - .dpns_vote_target_status(&unresolved.targets[0].target.key) - .unwrap(), - Some(DpnsVoteTargetStatus::Unconfirmed) - ); - context - .mark_vote_executed( - oldest.targets[0].target.key.voter_id.as_slice(), - "cleanup-0".to_owned(), - ) - .unwrap(); - context.migrate_dpns_vote_operations().unwrap(); - assert_eq!( - context.dpns_vote_operations().unwrap().len(), - 257, - "late mirror completion must not revive pruned work" - ); - } - } - - #[test] - fn retention_preserves_a_newer_schedules_mirror() { - let dir = tempfile::tempdir().unwrap(); - let kv = kv(); - 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 mut old = scheduled_operation(DpnsVoteTargetStatus::Confirmed, 2, "shared"); - old.created_at = 0; - context - .insert_dpns_vote_operation_with_scheduled_mirror( - &mut old.clone(), - None, - &[scheduled_vote(&old)], - ) - .unwrap(); - let mut current = scheduled_operation(DpnsVoteTargetStatus::Scheduled, 2, "shared"); - current.targets[0].target.requested_choice = ResourceVoteChoice::Abstain; - let current_mirror = scheduled_vote(¤t); - context - .insert_dpns_vote_operation_with_scheduled_mirror( - &mut current, - None, - std::slice::from_ref(¤t_mirror), - ) - .unwrap(); - for index in 1..=(DPNS_SCHEDULED_HISTORY_LIMIT + DPNS_HISTORY_PRUNE_SLACK) as u64 { - let mut completed = scheduled_operation( - DpnsVoteTargetStatus::Confirmed, - 3, - &format!("other-{index}"), - ); - completed.created_at = index; - persist_operation(&kv, Network::Testnet, &completed).unwrap(); - } - assert!(context.dpns_vote_operation(old.id).unwrap().is_none()); - assert_eq!(context.get_scheduled_votes().unwrap(), vec![current_mirror]); - assert_eq!( - context - .dpns_vote_target_status(¤t.targets[0].target.key) - .unwrap(), - Some(DpnsVoteTargetStatus::Scheduled) - ); + context.prune_terminal_dpns_vote_operations().unwrap(); + assert_eq!(context.dpns_vote_operations().unwrap().len(), 257); } #[test] @@ -2432,7 +1931,7 @@ mod tests { .insert_dpns_vote_operation(&mut scheduled, None) .unwrap(); let edit = DpnsScheduledVoteEdit { - operation_id: Some(scheduled.id), + operation_id: scheduled.id, key: scheduled.targets[0].target.key.clone(), expected_choice: ResourceVoteChoice::Lock, expected_timestamp: u64::MAX - 2, @@ -2459,9 +1958,8 @@ mod tests { expected_choice: choice_only.choice, ..edit }; - let (id, error) = context.edit_scheduled_dpns_vote_target(&edit).unwrap(); + let id = context.edit_scheduled_dpns_vote_target(&edit).unwrap(); assert_eq!(id, scheduled.id); - assert!(error.is_none()); 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); @@ -2493,47 +1991,6 @@ mod tests { context.edit_scheduled_dpns_vote_target(&refreshed), Err(TaskError::DpnsScheduledVoteNotEditable) )); - assert_eq!( - context.get_scheduled_votes().unwrap()[0].choice, - ResourceVoteChoice::Abstain - ); - } - - #[test] - fn schedule_edit_mirror_failure_retains_the_committed_edit_and_lock() { - 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 scheduled = scheduled_operation(DpnsVoteTargetStatus::Scheduled, 2, "edit-me"); - context - .insert_dpns_vote_operation(&mut scheduled, None) - .unwrap(); - store.fail_next_puts_containing("det:scheduled_vote:", 1); - let edit = DpnsScheduledVoteEdit { - operation_id: None, - key: scheduled.targets[0].target.key.clone(), - expected_choice: ResourceVoteChoice::Lock, - expected_timestamp: 42, - choice: ResourceVoteChoice::Abstain, - unix_timestamp: u64::MAX - 1, - }; - let (id, error) = context.edit_scheduled_dpns_vote_target(&edit).unwrap(); - assert_eq!(id, scheduled.id); - assert!(error.is_some()); - assert_eq!( - context.dpns_vote_operation(id).unwrap().unwrap().targets[0] - .target - .requested_choice, - edit.choice - ); - assert_eq!( - context.dpns_vote_target_status(&edit.key).unwrap(), - Some(DpnsVoteTargetStatus::Scheduled) - ); } #[test] @@ -2547,7 +2004,7 @@ mod tests { .insert_dpns_vote_operation(&mut scheduled, None) .unwrap(); let edit = DpnsScheduledVoteEdit { - operation_id: Some(scheduled.id), + operation_id: scheduled.id, key: scheduled.targets[0].target.key.clone(), expected_choice: ResourceVoteChoice::Lock, expected_timestamp: 42, @@ -2558,7 +2015,7 @@ mod tests { 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 = Some(DpnsVoteOperationId::random()); + invalid[3].operation_id = DpnsVoteOperationId::random(); for request in invalid { assert!(matches!( context.edit_scheduled_dpns_vote_target(&request), @@ -2576,7 +2033,6 @@ mod tests { context.dpns_vote_operation(scheduled.id).unwrap(), Some(scheduled) ); - assert!(context.get_scheduled_votes().unwrap().is_empty()); } #[test] @@ -2639,7 +2095,7 @@ mod tests { ) .unwrap(); store.fail_next_deletes_containing(SCHEDULE_DISMISSAL_KEY_PREFIX, 1); - assert!(prune_terminal_operations(&kv, Network::Testnet).is_err()); + assert!(delete_terminal_operations(&kv, Network::Testnet, &[completed.id]).is_err()); assert!( kv.get::( DetScope::Global, @@ -2669,7 +2125,46 @@ mod tests { } #[test] - fn terminal_schedule_dismissal_preserves_outcome_and_survives_mirror_delete_failure() { + 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( @@ -2681,13 +2176,9 @@ mod tests { context .insert_dpns_vote_operation(&mut completed, None) .unwrap(); - context - .insert_scheduled_votes(&[scheduled_vote(&completed)]) - .unwrap(); - store.fail_next_deletes_containing("det:scheduled_vote:", 1); let key = &completed.targets[0].target.key; context - .remove_scheduled_dpns_vote(Some(completed.id), key, "dismiss-me") + .remove_scheduled_dpns_vote(completed.id, key) .unwrap(); assert_eq!( context.dpns_vote_operation(completed.id).unwrap(), @@ -2699,7 +2190,6 @@ mod tests { .unwrap() .contains(&(completed.id, key.clone())) ); - assert_eq!(context.get_scheduled_votes().unwrap().len(), 1); } #[test] diff --git a/src/context/dpns_vote_operations/retention.rs b/src/context/dpns_vote_operations/retention.rs index d67a5ab18..dd19073f4 100644 --- a/src/context/dpns_vote_operations/retention.rs +++ b/src/context/dpns_vote_operations/retention.rs @@ -6,10 +6,8 @@ use super::keys::*; use super::{load_operations, rebuild_lock_index}; use crate::backend_task::error::TaskError; -use crate::context::identity_db::{delete_scheduled_vote_in, durable_scheduled_vote_keys}; use crate::model::dpns_voting::{ - DpnsScheduledVoteKey, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, - DpnsVoteTargetStatus, VoteTiming, + DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, }; use crate::wallet_backend::{DetKv, DetScope, network_prefix}; use dash_sdk::dpp::dashcore::Network; @@ -44,7 +42,7 @@ pub(super) fn dismiss_scheduled_target( Ok(()) } -/// Dismiss confirmed schedule rows before clearing their mirrors, under the journal guard. +/// Dismiss confirmed schedule rows under the journal guard. pub(crate) fn dismiss_confirmed_scheduled_targets( kv: &DetKv, network: Network, @@ -61,9 +59,6 @@ pub(crate) fn dismiss_confirmed_scheduled_targets( } /// Which retention list a completed operation belongs to. -/// -/// Scheduled batches are capped separately because retiring one must also drop -/// the compatibility mirror rows that back it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) enum HistoryKind { Immediate, @@ -93,29 +88,7 @@ impl HistoryKind { } pub(crate) fn prune_terminal_operations(kv: &DetKv, network: Network) -> Result { - let surviving_scheduled_votes = durable_scheduled_vote_keys(kv, network)?; - let operations = load_operations(kv, network)?; - let terminal_ids = operations - .iter() - .filter(|operation| { - operation.is_complete() - && !operation.targets.is_empty() - && operation - .targets - .iter() - .any(|outcome| matches!(outcome.target.timing, VoteTiming::Scheduled(_))) - && operation.targets.iter().all(|outcome| { - !matches!(outcome.target.timing, VoteTiming::Scheduled(_)) - || !surviving_scheduled_votes.contains(&DpnsScheduledVoteKey { - network: outcome.target.key.network, - voter_id: outcome.target.key.voter_id, - contested_name: outcome.target.contested_name.clone(), - }) - }) - }) - .map(|operation| operation.id) - .collect::>(); - let scheduled_count = delete_terminal_operations(kv, network, &terminal_ids)?; + 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) @@ -181,41 +154,6 @@ pub(super) fn prune_completed_history( .map_err(operation_err)?; } let remove_count = ordered.len().saturating_sub(limit); - if kind == HistoryKind::Scheduled && remove_count > 0 { - let removing = ordered[..remove_count] - .iter() - .copied() - .collect::>(); - let surviving_pairs = operations - .iter() - .filter(|operation| !removing.contains(&operation.id)) - .flat_map(|operation| &operation.targets) - .filter(|outcome| matches!(outcome.target.timing, VoteTiming::Scheduled(_))) - .map(|outcome| { - ( - outcome.target.key.voter_id, - outcome.target.contested_name.as_str(), - ) - }) - .collect::>(); - // Remove mirrors before their journals so partial cleanup cannot revive a schedule. - for operation in terminal - .iter() - .filter(|operation| removing.contains(&operation.id)) - { - for outcome in &operation.targets { - let pair = ( - outcome.target.key.voter_id, - outcome.target.contested_name.as_str(), - ); - if matches!(outcome.target.timing, VoteTiming::Scheduled(_)) - && !surviving_pairs.contains(&pair) - { - delete_scheduled_vote_in(kv, &pair.0.to_buffer(), pair.1)?; - } - } - } - } let removed = delete_terminal_operations(kv, network, &ordered[..remove_count])?; if remove_count > 0 { ordered.drain(..remove_count); diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index a97ffa081..960e22d48 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -1,7 +1,5 @@ use super::AppContext; -use crate::backend_task::contested_names::ScheduledDPNSVote; use crate::backend_task::error::TaskError; -use crate::model::dpns_voting::DpnsScheduledVoteKey; use crate::model::identity_discovery::DiscoveryIntent; use crate::model::qualified_identity::{ DPNSNameInfo, IdentityStatus, IdentityType, PrivateKeyTarget, QualifiedIdentity, @@ -14,10 +12,11 @@ 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}; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use std::sync::{Arc, Mutex, MutexGuard, RwLock}; mod import_keys; @@ -44,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"; @@ -194,20 +180,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 } @@ -235,15 +212,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 @@ -322,62 +290,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 @@ -560,130 +472,9 @@ 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) -} - -/// Enumerate scheduled mirror keys without decoding their stored values. -pub(super) fn durable_scheduled_vote_keys( - kv: &DetKv, - network: Network, -) -> std::result::Result, TaskError> { - let mut keys = BTreeSet::new(); - for voter in load_scheduled_vote_voters(kv)? { - for key in scheduled_vote_keys(kv, &voter)? { - if let Some(contested_name) = key.strip_prefix(SCHEDULED_VOTE_KEY_PREFIX) { - keys.insert(DpnsScheduledVoteKey { - network, - voter_id: Identifier::from(voter), - contested_name: contested_name.to_owned(), - }); - } - } - } - Ok(keys) -} - -/// 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) -} - -pub(super) fn insert_scheduled_votes_in( - kv: &DetKv, - scheduled_votes: &[ScheduledDPNSVote], -) -> std::result::Result<(), TaskError> { - 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(()) } -pub(super) fn delete_scheduled_vote_in( - kv: &DetKv, - voter: &[u8; 32], - contested_name: &str, -) -> std::result::Result<(), TaskError> { - kv.delete( - DetScope::Identity(voter), - &scheduled_vote_key(contested_name), - ) - .map_err(scheduled_vote_err)?; - prune_vote_voter_if_empty(kv, voter) -} - impl AppContext { /// Whether the previous version's preserved `data.db` holds any identity of /// this network. @@ -817,7 +608,6 @@ impl AppContext { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); super::dpns_vote_operations::cancel_removed_identity_votes(&kv, self.network, id)?; - delete_scheduled_votes_for_voter(&kv, &id.to_buffer())?; } self.clear_identity_unloaded(&kv, &id.to_buffer())?; self.insert_local_qualified_identity_locked(qualified_identity, wallet_and_identity_id_info) @@ -2276,119 +2066,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> { - insert_scheduled_votes_in(&self.det_kv()?, scheduled_votes) - } - - /// 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 _vote_guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let kv = self.det_kv()?; - super::dpns_vote_operations::dismiss_confirmed_scheduled_targets(&kv, self.network)?; - 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) - .map_err(scheduled_vote_err)? - { - Some(stored) if stored.executed_successfully => { - kv.delete(scope, &key).map_err(scheduled_vote_err)?; - } - Some(_) | None => {} - } - } - prune_vote_voter_if_empty(&kv, voter)?; - } - super::dpns_vote_operations::prune_terminal_operations(&kv, self.network)?; - 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)?; - delete_scheduled_vote_in(&self.det_kv()?, &voter, contested_name) - } - - /// 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 _guard = self - .dpns_vote_operation_guard - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - 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, @@ -2690,21 +2367,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 @@ -2858,20 +2525,6 @@ mod tests { [b; 32] } - fn scheduled_vote( - voter_id: Identifier, - contested_name: &str, - executed_successfully: bool, - ) -> ScheduledDPNSVote { - ScheduledDPNSVote { - contested_name: contested_name.to_owned(), - voter_id, - choice: ResourceVoteChoice::Lock, - unix_timestamp: 42, - executed_successfully, - } - } - fn scheduled_operation( voter_id: Identifier, poll: u8, @@ -3210,436 +2863,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)]), - ) - .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, - }, + &BTreeMap::from([(0u32, 5u64)]), ) .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 clearing_executed_votes_preserves_failed_and_cancelled_journal_records() { - let temp_dir = tempfile::tempdir().expect("tempdir"); - let context = crate::context::test_support::test_app_context(temp_dir.path()); - let kv = empty_kv(); - context.set_det_kv_override_for_test(kv); - let voter = Identifier::from(id(1)); - let cases = [ - ("confirmed", DpnsVoteTargetStatus::Confirmed, true), - ( - "failed", - DpnsVoteTargetStatus::FailedBeforeSubmission, - false, - ), - ("cancelled", DpnsVoteTargetStatus::Cancelled, false), - ]; - let scheduled_votes = cases - .iter() - .enumerate() - .map( - |(index, (name, _, executed_successfully))| ScheduledDPNSVote { - contested_name: (*name).to_owned(), - voter_id: voter, - choice: ResourceVoteChoice::Lock, - unix_timestamp: 42 + index as u64, - executed_successfully: *executed_successfully, - }, - ) - .collect::>(); - context.insert_scheduled_votes(&scheduled_votes).unwrap(); - for (index, (name, status, _)) in cases.iter().enumerate() { - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { - key: DpnsVoteTargetKey { - network: Network::Testnet, - voter_id: voter, - vote_poll_id: Identifier::from([index as u8 + 1; 32]), - }, - voter_alias: None, - contested_name: (*name).to_owned(), - requested_choice: ResourceVoteChoice::Lock, - current_choice: None, - timing: VoteTiming::Scheduled(42 + index as u64), - }]); - operation.targets[0].status = *status; - context - .insert_dpns_vote_operation(&mut operation, None) - .unwrap(); - } - - context.clear_executed_scheduled_votes().unwrap(); - - let mut remaining_legacy_names = context - .get_scheduled_votes() - .unwrap() - .into_iter() - .map(|vote| vote.contested_name) - .collect::>(); - remaining_legacy_names.sort(); - assert_eq!(remaining_legacy_names, vec!["cancelled", "failed"]); - let remaining_operations = context.dpns_vote_operations().unwrap(); - assert_eq!(remaining_operations.len(), 2); - assert!(remaining_operations.iter().any(|operation| { - operation.targets[0].target.contested_name == "failed" - && operation.targets[0].status == DpnsVoteTargetStatus::FailedBeforeSubmission - })); - assert!(remaining_operations.iter().any(|operation| { - operation.targets[0].target.contested_name == "cancelled" - && operation.targets[0].status == DpnsVoteTargetStatus::Cancelled - })); - - context.migrate_dpns_vote_operations().unwrap(); - assert!( - context - .dpns_vote_operations() - .unwrap() - .iter() - .all(|operation| { - operation.targets[0].status != DpnsVoteTargetStatus::Scheduled - }) - ); + assert!(!kv.contains(DetScope::Identity(&a), IDENTITY_KEY).unwrap()); + assert!(!kv.contains(DetScope::Identity(&a), TOP_UPS_KEY).unwrap()); } - #[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]); - } - - #[test] - fn mixed_terminal_operation_is_pruned_only_after_every_scheduled_mirror_is_absent() { - let temp_dir = tempfile::tempdir().expect("tempdir"); - let context = crate::context::test_support::test_app_context(temp_dir.path()); - let kv = empty_kv(); - context.set_det_kv_override_for_test(kv); - let voter = Identifier::from(id(1)); - let first_vote = scheduled_vote(voter, "first", false); - let second_vote = scheduled_vote(voter, "second", false); - context - .insert_scheduled_votes(&[first_vote, second_vote]) - .unwrap(); - let mut operation = scheduled_operation(voter, 1, "first", DpnsVoteTargetStatus::Confirmed); - operation.targets.push( - scheduled_operation(voter, 2, "second", DpnsVoteTargetStatus::Confirmed) - .targets - .remove(0), - ); - let mut immediate = - scheduled_operation(voter, 3, "immediate", DpnsVoteTargetStatus::Confirmed) - .targets - .remove(0); - immediate.target.timing = VoteTiming::Now; - operation.targets.push(immediate); - context - .insert_dpns_vote_operation(&mut operation, None) - .unwrap(); - - assert_eq!(context.prune_terminal_dpns_vote_operations().unwrap(), 0); - context - .delete_scheduled_vote(voter.as_slice(), "first") - .unwrap(); - assert_eq!(context.prune_terminal_dpns_vote_operations().unwrap(), 0); - context - .delete_scheduled_vote(voter.as_slice(), "second") - .unwrap(); - assert_eq!(context.prune_terminal_dpns_vote_operations().unwrap(), 1); - assert!(context.dpns_vote_operations().unwrap().is_empty()); - } - - #[test] - fn journal_only_terminal_scheduled_operation_is_prunable() { - let temp_dir = tempfile::tempdir().expect("tempdir"); - let context = crate::context::test_support::test_app_context(temp_dir.path()); - let kv = empty_kv(); - context.set_det_kv_override_for_test(kv); - let mut operation = scheduled_operation( - Identifier::from(id(1)), - 1, - "journal-only", - DpnsVoteTargetStatus::Confirmed, - ); - context - .insert_dpns_vote_operation(&mut operation, None) - .unwrap(); - - assert_eq!(context.prune_terminal_dpns_vote_operations().unwrap(), 1); - assert!(context.dpns_vote_operations().unwrap().is_empty()); - } - - #[test] - fn clear_executed_cleanup_recovers_after_voter_index_write_failure() { - 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 voter = Identifier::from(id(1)); - context - .insert_scheduled_votes(&[scheduled_vote(voter, "confirmed", true)]) - .unwrap(); - let mut operation = - scheduled_operation(voter, 1, "confirmed", DpnsVoteTargetStatus::Confirmed); - context - .insert_dpns_vote_operation(&mut operation, None) - .unwrap(); - store.fail_next_puts_containing(SCHEDULED_VOTE_VOTERS_KEY, 1); - - assert!(context.clear_executed_scheduled_votes().is_err()); - assert_eq!(context.dpns_vote_operations().unwrap(), vec![operation]); - - context.clear_executed_scheduled_votes().unwrap(); - assert!(context.dpns_vote_operations().unwrap().is_empty()); - assert!( - load_scheduled_vote_voters(&context.det_kv().unwrap()) - .unwrap() - .is_empty() - ); - } - - #[test] - fn clear_executed_cleanup_recovers_after_journal_prune_write_failure() { - 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 voter = Identifier::from(id(1)); - context - .insert_scheduled_votes(&[scheduled_vote(voter, "confirmed", true)]) - .unwrap(); - let mut operation = - scheduled_operation(voter, 1, "confirmed", DpnsVoteTargetStatus::Confirmed); - context - .insert_dpns_vote_operation(&mut operation, None) - .unwrap(); - store.fail_next_puts_containing("dpns_vote_operation_locks_dirty", 1); - - assert!(context.clear_executed_scheduled_votes().is_err()); - assert_eq!(context.dpns_vote_operations().unwrap(), vec![operation]); - - context.clear_executed_scheduled_votes().unwrap(); - assert!(context.dpns_vote_operations().unwrap().is_empty()); - assert!( - load_scheduled_vote_voters(&context.det_kv().unwrap()) - .unwrap() - .is_empty() - ); - } - - #[test] - fn clear_executed_cleanup_fails_closed_on_unreadable_mirror() { - 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 voter = Identifier::from(id(1)); - context - .insert_scheduled_votes(&[scheduled_vote(voter, "unreadable", true)]) - .unwrap(); - let mut operation = - scheduled_operation(voter, 1, "unreadable", DpnsVoteTargetStatus::Confirmed); - context - .insert_dpns_vote_operation(&mut operation, None) - .unwrap(); - store.fail_next_gets_containing(&scheduled_vote_key("unreadable"), 1); - - assert!(matches!( - context - .clear_executed_scheduled_votes() - .expect_err("an unreadable row must stop cleanup"), - TaskError::ScheduledVoteStorage { .. } - )); - assert_eq!(context.dpns_vote_operations().unwrap(), vec![operation]); - assert_eq!(context.get_scheduled_votes().unwrap().len(), 1); - } - - #[test] - fn pruning_treats_an_unreadable_mirror_key_as_surviving() { - 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 voter = Identifier::from(id(1)); - context - .insert_scheduled_votes(&[scheduled_vote(voter, "unreadable", true)]) - .unwrap(); - let mut operation = - scheduled_operation(voter, 1, "unreadable", DpnsVoteTargetStatus::Confirmed); - context - .insert_dpns_vote_operation(&mut operation, None) - .unwrap(); - store.fail_next_gets_containing(&scheduled_vote_key("unreadable"), 1); - - assert_eq!(context.prune_terminal_dpns_vote_operations().unwrap(), 0); - assert_eq!(context.dpns_vote_operations().unwrap(), vec![operation]); - assert!( - context.get_scheduled_votes().unwrap().is_empty(), - "the decode-oriented reader should consume and skip the injected row error" - ); - } - - // --------------------------------------------------------------- - // 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(); @@ -3659,25 +2897,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. @@ -4496,15 +3715,10 @@ mod tests { .unwrap(); operations.push(operation); } - staged - .ctx - .insert_scheduled_votes(&[scheduled_vote(staged.id, "removed", false)]) - .unwrap(); staged .ctx .delete_local_qualified_identity(&staged.id) .unwrap(); - assert!(staged.ctx.get_scheduled_votes().unwrap().is_empty()); for (index, operation) in operations.iter().enumerate() { let saved = staged .ctx @@ -4577,10 +3791,6 @@ mod tests { .ctx .insert_dpns_vote_operation(&mut scheduled, None) .unwrap(); - staged - .ctx - .insert_scheduled_votes(&[scheduled_vote(staged.id, "interrupted", false)]) - .unwrap(); staged.ctx.resume_pending_vault_cleanups(); @@ -4594,7 +3804,6 @@ mod tests { .status, DpnsVoteTargetStatus::Cancelled ); - assert!(staged.ctx.get_scheduled_votes().unwrap().is_empty()); assert!( !staged .ctx @@ -4678,7 +3887,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 @@ -4694,21 +3903,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:?}" @@ -4723,13 +3923,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] { @@ -4790,20 +3987,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); @@ -4830,18 +4013,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, @@ -6074,8 +5245,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(); diff --git a/src/context/legacy_scheduled_votes.rs b/src/context/legacy_scheduled_votes.rs new file mode 100644 index 000000000..96f17bde3 --- /dev/null +++ b/src/context/legacy_scheduled_votes.rs @@ -0,0 +1,131 @@ +//! Read-only detection of schedules that require a new voting decision. + +use super::AppContext; +use crate::backend_task::error::TaskError; +use std::collections::BTreeSet; + +impl AppContext { + /// 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::database::test_helpers::{ + create_legacy_scheduled_votes_table, seed_legacy_scheduled_vote_row, + }; + use crate::model::dpns_voting::{ + DpnsVoteOperation, 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 = DpnsVoteOperation::new(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" + ); + } + + #[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/mod.rs b/src/context/mod.rs index f4fd9fe93..8761dd174 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -5,6 +5,7 @@ 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_state::DpnsVoteRefreshResults; pub mod feature_gate; mod identity_db; diff --git a/src/model/dpns_voting/mod.rs b/src/model/dpns_voting/mod.rs index 209cbed02..53bdfcac8 100644 --- a/src/model/dpns_voting/mod.rs +++ b/src/model/dpns_voting/mod.rs @@ -106,7 +106,7 @@ pub struct DpnsVoteTargetKey { /// Compare-and-set request for one scheduled target; the voter and poll cannot change. #[derive(Debug, Clone, PartialEq)] pub struct DpnsScheduledVoteEdit { - pub operation_id: Option, + pub operation_id: DpnsVoteOperationId, pub key: DpnsVoteTargetKey, pub expected_choice: ResourceVoteChoice, pub expected_timestamp: u64, @@ -164,7 +164,7 @@ pub struct DpnsScheduledVoteKey { pub contested_name: String, } -/// Result of clearing one scheduled target from the compatibility mirror. +/// Result of clearing one scheduled target from the voting journal. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DpnsScheduledVoteClearDisposition { Cleared, diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 4b55a800f..f5760b81c 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -195,16 +195,9 @@ fn scheduled_vote_cast_enabled(status: DpnsVoteTargetStatus, dispatch_pending: b } fn scheduled_vote_removal_task(row: &ScheduledDpnsVoteRow) -> ContestedResourceTask { - match &row.journal_target { - Some((operation_id, key)) => ContestedResourceTask::CancelScheduledDpnsVote { - operation_id: *operation_id, - key: key.clone(), - contested_name: row.vote.contested_name.clone(), - }, - None => ContestedResourceTask::DeleteScheduledVote( - row.vote.voter_id, - row.vote.contested_name.clone(), - ), + ContestedResourceTask::CancelScheduledDpnsVote { + operation_id: row.journal_target.0, + key: row.journal_target.1.clone(), } } @@ -508,10 +501,7 @@ pub struct DPNSScreen { impl DPNSScreen { pub fn new(app_context: &Arc, view: VotesView) -> Self { let vote_operations = DpnsVoteOperationSnapshot::load(app_context); - let legacy_scheduled_votes = app_context.get_scheduled_votes().unwrap_or_default(); - let scheduled_votes = Arc::new(Mutex::new( - vote_operations.scheduled_vote_rows(&legacy_scheduled_votes), - )); + 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( @@ -1608,7 +1598,7 @@ impl DPNSScreen { self.candidate_name(&group.contested_name, group.choice), ); let preset = group.rows.iter().find_map(|row| { - let (_, key) = row.journal_target.as_ref()?; + let (_, key) = &row.journal_target; self.relative_schedule_labels .get(&(key.clone(), group.unix_timestamp)) }); @@ -1684,10 +1674,7 @@ impl DPNSScreen { for scheduled_row in rows { let vote = &scheduled_row.vote; let pending_key = DpnsScheduledVoteKey { - network: scheduled_row - .journal_target - .as_ref() - .map_or(self.app_context.network(), |(_, key)| key.network), + network: scheduled_row.journal_target.1.network, voter_id: vote.voter_id, contested_name: vote.contested_name.clone(), }; @@ -1877,12 +1864,11 @@ impl DPNSScreen { } fn rebuild_scheduled_vote_rows(&mut self) { - let legacy_votes = self.app_context.get_scheduled_votes().unwrap_or_default(); - let rows = self.vote_operations.scheduled_vote_rows(&legacy_votes); + let rows = self.vote_operations.scheduled_vote_rows(); self.relative_schedule_labels = rows .iter() .filter_map(|row| { - let (operation_id, key) = row.journal_target.as_ref()?; + let (operation_id, key) = &row.journal_target; let at = row.vote.unix_timestamp; let preset = self .vote_operations @@ -3283,7 +3269,7 @@ mod tests { } #[test] - fn scheduled_vote_removal_dispatches_the_journal_or_legacy_task() { + fn scheduled_vote_removal_dispatches_the_journal_task() { let operation_id = DpnsVoteOperationId::from_bytes([31; 16]); let key = DpnsVoteTargetKey { network: Network::Testnet, @@ -3299,29 +3285,16 @@ mod tests { }; let journal_row = ScheduledDpnsVoteRow { vote: vote.clone(), - journal_target: Some((operation_id, key.clone())), + journal_target: (operation_id, key.clone()), status: DpnsVoteTargetStatus::Scheduled, failure: None, }; - let legacy_row = ScheduledDpnsVoteRow { - vote, - journal_target: None, - status: DpnsVoteTargetStatus::Scheduled, - failure: None, - }; - assert!(matches!( scheduled_vote_removal_task(&journal_row), ContestedResourceTask::CancelScheduledDpnsVote { operation_id: id, key: task_key, - contested_name, - } if id == operation_id && task_key == key && contested_name == "dispatch" - )); - assert!(matches!( - scheduled_vote_removal_task(&legacy_row), - ContestedResourceTask::DeleteScheduledVote(voter_id, contested_name) - if voter_id == Identifier::from([32; 32]) && contested_name == "dispatch" + } if id == operation_id && task_key == key )); } @@ -4757,18 +4730,10 @@ mod tests { }]); ctx.insert_dpns_vote_operation(&mut operation, None) .expect("insert scheduled operation"); - ctx.insert_scheduled_votes(&[ScheduledDPNSVote { - contested_name: "remove-me".to_owned(), - voter_id, - choice: ResourceVoteChoice::Lock, - unix_timestamp: 42, - executed_successfully: false, - }]) - .expect("insert compatibility mirror"); let mut screen = DPNSScreen::new(&ctx, VotesView::Scheduled); assert_eq!(screen.scheduled_votes.lock_recover().len(), 1); - ctx.cancel_scheduled_dpns_vote_target(operation.id, &key, "remove-me") + ctx.cancel_scheduled_dpns_vote_target(operation.id, &key) .expect("remove the scheduled vote"); screen.display_task_result(BackendTaskSuccessResult::DpnsVoteOperationUpdated { network: ctx.network(), @@ -4838,14 +4803,6 @@ mod tests { }]); ctx.insert_dpns_vote_operation(&mut operation, None) .expect("insert scheduled operation"); - ctx.insert_scheduled_votes(&[ScheduledDPNSVote { - contested_name: "clear-me".to_owned(), - voter_id, - choice: ResourceVoteChoice::Lock, - unix_timestamp: 42, - executed_successfully: false, - }]) - .expect("insert compatibility mirror"); let mut screen = DPNSScreen::new(&ctx, VotesView::Scheduled); assert_eq!(screen.scheduled_votes.lock_recover().len(), 1); 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 index 3ac1fb4d1..d40cf8247 100644 --- a/src/ui/dpns/dpns_contested_names_screen/scheduled_vote_editor.rs +++ b/src/ui/dpns/dpns_contested_names_screen/scheduled_vote_editor.rs @@ -66,7 +66,7 @@ impl ScheduledVoteEditor { return None; } Some(ContestedResourceTask::EditScheduledDpnsVote { - operation_id: self.original.journal_target.as_ref().map(|(id, _)| *id), + operation_id: self.original.journal_target.0, key: self.key.clone(), expected_choice: self.original.vote.choice, expected_timestamp: self.original.vote.unix_timestamp, @@ -159,7 +159,7 @@ mod tests { unix_timestamp: 1_900_000_012_345, executed_successfully: false, }, - journal_target: Some((DpnsVoteOperationId::from_bytes([3; 16]), key.clone())), + journal_target: (DpnsVoteOperationId::from_bytes([3; 16]), key.clone()), status: DpnsVoteTargetStatus::Scheduled, }; let mut editor = ScheduledVoteEditor::new( @@ -185,7 +185,7 @@ mod tests { panic!("expected edit"); }; assert_eq!(edited_key, key); - assert_eq!(operation_id, row.journal_target.map(|(id, _)| id)); + 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); diff --git a/src/ui/state/dpns_vote_operations.rs b/src/ui/state/dpns_vote_operations.rs index 3956acc4e..0695e2cc9 100644 --- a/src/ui/state/dpns_vote_operations.rs +++ b/src/ui/state/dpns_vote_operations.rs @@ -14,7 +14,7 @@ use crate::model::dpns_voting::{ #[derive(Debug, Clone, PartialEq)] pub(crate) struct ScheduledDpnsVoteRow { pub vote: ScheduledDPNSVote, - pub journal_target: Option<(DpnsVoteOperationId, DpnsVoteTargetKey)>, + pub journal_target: (DpnsVoteOperationId, DpnsVoteTargetKey), pub status: DpnsVoteTargetStatus, pub failure: Option, } @@ -109,10 +109,7 @@ impl DpnsVoteOperationSnapshot { self.loaded } - pub(crate) fn scheduled_vote_rows( - &self, - legacy_votes: &[ScheduledDPNSVote], - ) -> Vec { + pub(crate) fn scheduled_vote_rows(&self) -> Vec { let mut journal_rows = BTreeMap::< (dash_sdk::platform::Identifier, String), (DpnsVoteAuthorityRank, ScheduledDpnsVoteRow), @@ -147,7 +144,7 @@ impl DpnsVoteOperationSnapshot { executed_successfully: outcome.status == DpnsVoteTargetStatus::Confirmed, }, - journal_target: Some((operation.id, outcome.target.key.clone())), + journal_target: (operation.id, outcome.target.key.clone()), status: outcome.status, failure: outcome.failure, }, @@ -156,38 +153,12 @@ impl DpnsVoteOperationSnapshot { } } - let journal_pairs = journal_rows.keys().cloned().collect::>(); - // A cancelled target is a dismissed schedule. Its pair stays in - // `journal_pairs` so a mirror row that outlived a best-effort delete - // cannot bring the dismissed schedule back. - let mut rows = journal_rows + journal_rows .into_values() .map(|(_, row)| row) .filter(|row| row.status != DpnsVoteTargetStatus::Cancelled) - .filter(|row| { - !row.journal_target - .as_ref() - .is_some_and(|key| self.dismissed_schedules.contains(key)) - }) - .collect::>(); - rows.extend( - legacy_votes - .iter() - .filter(|vote| { - !journal_pairs.contains(&(vote.voter_id, vote.contested_name.clone())) - }) - .map(|vote| ScheduledDpnsVoteRow { - vote: vote.clone(), - journal_target: None, - failure: None, - status: if vote.executed_successfully { - DpnsVoteTargetStatus::Confirmed - } else { - DpnsVoteTargetStatus::Scheduled - }, - }), - ); - rows + .filter(|row| !self.dismissed_schedules.contains(&row.journal_target)) + .collect() } fn replace(&mut self, operations: Vec) { @@ -212,7 +183,7 @@ mod tests { use dash_sdk::platform::Identifier; #[test] - fn voting_ui_dismissed_terminal_row_suppresses_its_mirror_and_preserves_siblings() { + fn voting_ui_dismissed_terminal_row_preserves_siblings() { let mut operation = scheduled_operation( 10, DpnsVoteTargetStatus::Confirmed, @@ -228,13 +199,7 @@ mod tests { let mut snapshot = DpnsVoteOperationSnapshot::default(); snapshot.replace(vec![operation]); snapshot.dismissed_schedules.insert(dismissed); - let rows = snapshot.scheduled_vote_rows(&[legacy_vote( - original.target.key.voter_id, - "alice", - ResourceVoteChoice::Lock, - 100, - true, - )]); + 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); @@ -282,14 +247,21 @@ mod tests { #[test] fn scheduled_rows_group_by_decision() { let row = |voter: u8, name: &str, choice, timestamp| ScheduledDpnsVoteRow { - vote: legacy_vote( + vote: scheduled_vote( Identifier::from([voter; 32]), name, choice, timestamp, false, ), - journal_target: None, + 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, }; @@ -336,13 +308,10 @@ mod tests { let mut snapshot = DpnsVoteOperationSnapshot::default(); snapshot.replace(vec![pending.clone(), newer_rejected]); - let rows = snapshot.scheduled_vote_rows(&[]); + let rows = snapshot.scheduled_vote_rows(); assert_eq!(rows.len(), 1); - assert_eq!( - rows[0].journal_target.as_ref().map(|(id, _)| *id), - Some(pending.id) - ); + assert_eq!(Some(rows[0].journal_target.0), Some(pending.id)); assert_eq!(rows[0].status, DpnsVoteTargetStatus::Scheduled); } @@ -369,7 +338,7 @@ mod tests { operation } - fn legacy_vote( + fn scheduled_vote( voter_id: Identifier, name: &str, choice: ResourceVoteChoice, @@ -386,7 +355,7 @@ mod tests { } #[test] - fn scheduled_rows_prefer_the_newest_journal_outcome_over_legacy_data() { + fn scheduled_rows_prefer_the_newest_journal_outcome() { let older = scheduled_operation( 10, DpnsVoteTargetStatus::Confirmed, @@ -401,20 +370,13 @@ mod tests { ); let expected_id = newer.id; let expected_key = newer.targets[0].target.key.clone(); - let legacy = legacy_vote( - Identifier::from([7; 32]), - "alice", - ResourceVoteChoice::Lock, - 999, - true, - ); let mut snapshot = DpnsVoteOperationSnapshot::default(); snapshot.replace(vec![older, newer]); - let rows = snapshot.scheduled_vote_rows(&[legacy]); + let rows = snapshot.scheduled_vote_rows(); assert_eq!(rows.len(), 1); - assert_eq!(rows[0].journal_target, Some((expected_id, expected_key))); + 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); @@ -443,13 +405,10 @@ mod tests { let mut snapshot = DpnsVoteOperationSnapshot::default(); snapshot.replace(vec![first, second]); - let rows = snapshot.scheduled_vote_rows(&[]); + let rows = snapshot.scheduled_vote_rows(); assert_eq!(rows.len(), 1); - assert_eq!( - rows[0].journal_target.as_ref().map(|(id, _)| *id), - Some(expected_id) - ); + 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); } @@ -467,37 +426,23 @@ mod tests { let mut snapshot = DpnsVoteOperationSnapshot::default(); snapshot.replace(vec![cancelled]); - assert!(snapshot.scheduled_vote_rows(&[]).is_empty()); + assert!(snapshot.scheduled_vote_rows().is_empty()); } - /// The compatibility-mirror delete is best effort, so a cancelled target - /// must keep suppressing its legacy row even when the mirror survived. #[test] - fn cancelled_targets_still_suppress_their_legacy_mirror_row() { + fn cancelled_targets_are_not_shown() { let cancelled = scheduled_operation( 10, DpnsVoteTargetStatus::Cancelled, ResourceVoteChoice::Lock, 100, ); - let voter_id = cancelled.targets[0].target.key.voter_id; let mut snapshot = DpnsVoteOperationSnapshot::default(); snapshot.replace(vec![cancelled]); - let legacy = [ - legacy_vote(voter_id, "alice", ResourceVoteChoice::Lock, 100, false), - legacy_vote( - Identifier::from([11; 32]), - "unrelated", - ResourceVoteChoice::Abstain, - 300, - false, - ), - ]; - let rows = snapshot.scheduled_vote_rows(&legacy); + let rows = snapshot.scheduled_vote_rows(); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].vote.contested_name, "unrelated"); + assert!(rows.is_empty()); } /// A bulk schedule is one operation with many targets, so cancelling one of @@ -518,7 +463,7 @@ mod tests { let mut snapshot = DpnsVoteOperationSnapshot::default(); snapshot.replace(vec![operation]); - let rows = snapshot.scheduled_vote_rows(&[]); + let rows = snapshot.scheduled_vote_rows(); assert_eq!(rows.len(), 1); assert_eq!(rows[0].vote.contested_name, "bob"); @@ -526,7 +471,7 @@ mod tests { } #[test] - fn scheduled_rows_derive_compatibility_execution_only_from_confirmed_status() { + fn scheduled_rows_mark_only_confirmed_votes_as_executed() { let confirmed = scheduled_operation( 10, DpnsVoteTargetStatus::Confirmed, @@ -536,59 +481,10 @@ mod tests { let mut snapshot = DpnsVoteOperationSnapshot::default(); snapshot.replace(vec![confirmed]); - let rows = snapshot.scheduled_vote_rows(&[]); + let rows = snapshot.scheduled_vote_rows(); assert_eq!(rows.len(), 1); assert_eq!(rows[0].status, DpnsVoteTargetStatus::Confirmed); assert!(rows[0].vote.executed_successfully); } - - #[test] - fn scheduled_rows_append_only_unseen_legacy_pairs() { - let journal = scheduled_operation( - 10, - DpnsVoteTargetStatus::Scheduled, - ResourceVoteChoice::Lock, - 100, - ); - let voter_id = journal.targets[0].target.key.voter_id; - let mut snapshot = DpnsVoteOperationSnapshot::default(); - snapshot.replace(vec![journal]); - let legacy = [ - legacy_vote(voter_id, "alice", ResourceVoteChoice::Abstain, 999, true), - legacy_vote( - Identifier::from([9; 32]), - "confirmed-legacy", - ResourceVoteChoice::Lock, - 300, - true, - ), - legacy_vote( - Identifier::from([10; 32]), - "pending-legacy", - ResourceVoteChoice::Abstain, - 400, - false, - ), - ]; - - let rows = snapshot.scheduled_vote_rows(&legacy); - - assert_eq!(rows.len(), 3); - assert!(rows.iter().any(|row| { - row.vote.contested_name == "alice" - && row.status == DpnsVoteTargetStatus::Scheduled - && row.journal_target.is_some() - })); - assert!(rows.iter().any(|row| { - row.vote.contested_name == "confirmed-legacy" - && row.status == DpnsVoteTargetStatus::Confirmed - && row.journal_target.is_none() - })); - assert!(rows.iter().any(|row| { - row.vote.contested_name == "pending-legacy" - && row.status == DpnsVoteTargetStatus::Scheduled - && row.journal_target.is_none() - })); - } } 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 c0dabcdf1..dbf00cf7f 100644 --- a/src/wallet_backend/kv_test_support.rs +++ b/src/wallet_backend/kv_test_support.rs @@ -118,9 +118,8 @@ impl CountdownFailure { /// 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. -#[derive(Default)] pub(crate) struct FailingKv { - inner: InMemoryKv, + inner: std::sync::Arc, fail_all_reads: AtomicBool, fail_all_deletes: AtomicBool, puts: AtomicUsize, @@ -129,7 +128,25 @@ pub(crate) struct FailingKv { delete_countdown: CountdownFailure, } +impl Default for FailingKv { + fn default() -> Self { + Self::from_store(std::sync::Arc::new(InMemoryKv::default())) + } +} + impl FailingKv { + 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), + 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. From 72b4744e2494dfdb84b74b04fd6906c0bc1e801f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:38:43 +0000 Subject: [PATCH 119/194] fix(dpns): retry won names and bind payment consent to review --- CHANGELOG.md | 5 +- docs/user-stories.md | 2 + src/backend_task/error.rs | 3 + src/backend_task/identity/dpns_usernames.rs | 222 ++++++++++++++---- src/backend_task/identity/mod.rs | 2 + .../identity/register_dpns_name.rs | 38 +++ src/context/contested_names_db.rs | 43 +++- src/model/dpns_usernames.rs | 38 ++- src/ui/identity/hub_screen.rs | 6 +- src/ui/identity/register_dpns_name_screen.rs | 100 ++++++-- tests/backend-e2e/dashpay_tasks.rs | 1 + tests/backend-e2e/framework/fixtures.rs | 1 + tests/backend-e2e/register_dpns.rs | 1 + tests/kittest/identity_usernames.rs | 66 ++++++ 14 files changed, 455 insertions(+), 73 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c8ae796b..32e436fe1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -183,11 +183,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). vote show the non-refundable fee before payment, and availability is checked again before registration. Registration prevents duplicate payment; 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. Refresh preserves concurrent identity edits and keeps - the previous request snapshot when storage cannot be read. + the previous request snapshot when storage cannot be read. 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. diff --git a/docs/user-stories.md b/docs/user-stories.md index 079781a2f..a9b33e282 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -807,6 +807,7 @@ As a user, I want to register a username for one of my identities so that others - 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 Β· 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. @@ -818,6 +819,7 @@ As a user, I want to see each identity's usernames and their state so that I kno - 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). - 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. - 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. diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 79e6fff49..020ac5fd3 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -2105,6 +2105,9 @@ pub enum TaskError { availability: crate::model::dpns_usernames::UsernameAvailability, }, + #[error("The username payment terms changed. Nothing was spent. Review the name and fees again.")] + UsernameRegistrationTermsChanged, + /// 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." diff --git a/src/backend_task/identity/dpns_usernames.rs b/src/backend_task/identity/dpns_usernames.rs index 6900b0148..c499ad452 100644 --- a/src/backend_task/identity/dpns_usernames.rs +++ b/src/backend_task/identity/dpns_usernames.rs @@ -231,8 +231,7 @@ impl AppContext { )); } } - self.apply_username_refresh(sdk, identity, &previous, fresh) - .await; + self.apply_username_refresh(sdk, identity, fresh).await; } // 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. @@ -274,8 +273,7 @@ impl AppContext { ) }) .collect(); - self.apply_username_refresh(sdk, &identity, &previous, fresh) - .await; + self.apply_username_refresh(sdk, &identity, fresh).await; } Ok(BackendTaskSuccessResult::MyUsernameRequestsRefreshed) } @@ -284,50 +282,59 @@ impl AppContext { &self, sdk: &Sdk, identity: &QualifiedIdentity, - previous: &[UsernameRequest], fresh: Vec, ) { let identity_id = identity.identity.id(); - let newly_won = fresh.iter().any(|request| { - request.phase == RequestPhase::Won - && !previous.iter().any(|old| { - old.normalized_label == request.normalized_label - && old.phase == RequestPhase::Won - }) - }); if let Err(error) = self.update_username_requests(&identity_id, |current| { - merge_requests(current, fresh, now_ms()) + merge_requests(current, fresh, now_ms(), Some(&identity.dpns_names)) }) { tracing::warn!(?error, %identity_id, "Username requests could not be stored"); } self.egui_ctx().request_repaint(); - if newly_won { - self.record_won_usernames(sdk, identity).await; - } + self.record_won_usernames(sdk, identity_id).await; } - /// Re-read the registered names of an identity that just won a vote, so the - /// won name is listed and shown at once. - async fn record_won_usernames(&self, sdk: &Sdk, identity: &QualifiedIdentity) { - match self - .fetch_owned_dpns_names(sdk, identity.identity.id()) - .await + /// 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) => { - if let Err(error) = - self.edit_local_qualified_identity(&identity.identity.id(), |fresh| { - fresh.dpns_names = names; - Ok(()) - }) - { - tracing::warn!(?error, "Won username could not be saved on the identity"); + match self.edit_local_qualified_identity(&identity_id, |fresh| { + fresh.dpns_names = names; + Ok(()) + }) { + Ok(saved) => { + 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, - "Registered names could not be re-read after a won vote" - ) + tracing::debug!(?error, %identity_id, "Won username could not be fetched; refresh will retry") } } } @@ -350,7 +357,7 @@ impl AppContext { joined_until, ); self.update_username_requests(identity_id, |current| { - merge_requests(current, vec![submitted], now) + merge_requests(current, vec![submitted], now, None) }) } @@ -397,15 +404,11 @@ mod tests { ContestedDocumentVotePollDriveQuery, ContestedDocumentVotePollDriveQueryResultType, }; - #[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 = QualifiedIdentity { + fn bare_identity( + id: Identifier, + network: dash_sdk::dpp::dashcore::Network, + ) -> QualifiedIdentity { + QualifiedIdentity { identity: dash_sdk::dpp::identity::Identity::create_basic_identity( id, dash_sdk::dpp::version::PlatformVersion::latest(), @@ -423,8 +426,139 @@ mod tests { wallet_index: None, top_ups: Default::default(), status: crate::model::qualified_identity::IdentityStatus::Active, - network: ctx.network, + network, + } + } + + 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 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_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; + 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" + ); + } + + #[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_identity(id, ctx.network); ctx.insert_local_qualified_identity_sidecar_only(&identity) .unwrap(); ctx.store_username_requests( diff --git a/src/backend_task/identity/mod.rs b/src/backend_task/identity/mod.rs index ba0c66df9..9719af650 100644 --- a/src/backend_task/identity/mod.rs +++ b/src/backend_task/identity/mod.rs @@ -448,6 +448,8 @@ 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, } diff --git a/src/backend_task/identity/register_dpns_name.rs b/src/backend_task/identity/register_dpns_name.rs index ebc9396df..1b6385483 100644 --- a/src/backend_task/identity/register_dpns_name.rs +++ b/src/backend_task/identity/register_dpns_name.rs @@ -50,6 +50,15 @@ impl AppContext { return Err(TaskError::InvalidDpnsName { validation }); } + let contest_fee = if crate::model::dpns::is_contested_label(&input.name_input) { + crate::model::fee_estimation::contest_fee_credits(sdk.version()) + } else { + 0 + }; + if input.approved_contest_fee != contest_fee { + 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 @@ -507,6 +516,32 @@ mod tests { )); } + #[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:?}" + ); + } + } + /// 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)] @@ -520,6 +555,9 @@ mod tests { 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, }, ) diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index d2b08f788..11c5b20b4 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -11,7 +11,9 @@ use crate::backend_task::error::TaskError; use crate::model::contested_name::{ ContestState, Contestant, ContestedName, MasternodeVoteStateSummary, }; -use crate::model::dpns_usernames::{SeenMarkAttempts, UsernameRequest}; +use crate::model::dpns_usernames::{ + RequestPhase, SeenMarkAttempts, UsernameRequest, won_username_is_missing, +}; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, VoteTiming, dpns_vote_authority_rank, @@ -260,6 +262,12 @@ impl AppContext { .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); } } @@ -331,6 +339,30 @@ impl AppContext { .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 + } + /// Persist `requests` as the full request list of `identity_id`. pub fn store_username_requests( &self, @@ -360,9 +392,16 @@ impl AppContext { if requests.is_empty() { kv.delete(DetScope::Global, &key).map_err(username_err)?; cache.requests.remove(identity_id); + cache.hydration_pending.remove(identity_id); } else { kv.put(DetScope::Global, &key, &requests) .map_err(username_err)?; + if requests + .iter() + .any(|request| request.phase == RequestPhase::Won) + { + cache.hydration_pending.insert(*identity_id); + } cache.requests.insert(*identity_id, requests); } Ok(()) @@ -525,6 +564,7 @@ impl AppContext { .map_err(username_err)?; } cache.requests.remove(identity_id); + cache.hydration_pending.remove(identity_id); cache.main.remove(identity_id); cache.seen.remove(identity_id); Ok(()) @@ -844,6 +884,7 @@ const SEEN_OUTCOMES_KEY_PREFIX: &str = "det:username_outcomes_seen:"; #[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. diff --git a/src/model/dpns_usernames.rs b/src/model/dpns_usernames.rs index ff1e6554c..6859b6c85 100644 --- a/src/model/dpns_usernames.rs +++ b/src/model/dpns_usernames.rs @@ -196,6 +196,17 @@ impl UsernameAvailability { } } +/// Whether a saved win still needs to be reflected in the identity's owned names. +pub fn won_username_is_missing( + request: &UsernameRequest, + names: &[super::qualified_identity::DPNSNameInfo], +) -> bool { + request.phase == RequestPhase::Won + && !names + .iter() + .any(|name| super::dpns::normalize_dpns_label(&name.name) == request.normalized_label) +} + /// How a finished contest ended. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ContestWinner { @@ -502,11 +513,13 @@ pub fn username_request_from_contest( /// 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. +/// their result can be read. Wins stay until they are reflected in `owned_names`; +/// `None` keeps 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() @@ -544,6 +557,8 @@ pub fn merge_requests( let retention = duration_ms(OUTCOME_RETENTION); merged.retain(|r| { r.phase.is_pending() + || (r.phase == RequestPhase::Won + && owned_names.is_none_or(|names| won_username_is_missing(r, names))) || r.decided_at .is_none_or(|decided| now.saturating_sub(decided) < retention) }); @@ -1078,20 +1093,37 @@ mod tests { stored("recent", RequestPhase::Locked, Some(now - 1)), ]; let fresh = vec![stored("c", RequestPhase::Joinable, None)]; - let labels: Vec<_> = merge_requests(&previous, fresh, now) + 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()); + } + #[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); + 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)); diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index daa72d455..5a378adb3 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -118,9 +118,9 @@ impl IdentityHubScreen { 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 any_pending = self.app_context.any_pending_username_request(); + let needs_refresh = self.app_context.username_requests_need_refresh(); let now = crate::utils::time::now_ms(); - if any_pending { + if needs_refresh { ctx.request_repaint_after(crate::model::dpns_usernames::pending_refresh_interval( network, )); @@ -129,7 +129,7 @@ impl IdentityHubScreen { now, self.usernames_refreshed_at, arriving, - any_pending, + needs_refresh, network, ) { return AppAction::None; diff --git a/src/ui/identity/register_dpns_name_screen.rs b/src/ui/identity/register_dpns_name_screen.rs index 1c0fe1aa2..616fc306e 100644 --- a/src/ui/identity/register_dpns_name_screen.rs +++ b/src/ui/identity/register_dpns_name_screen.rs @@ -77,6 +77,16 @@ enum Availability { 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 app_context: Arc, /// The identity the username is for, taken from the app's selected identity. @@ -85,6 +95,7 @@ pub struct RegisterDpnsNameScreen { 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>>, @@ -111,6 +122,7 @@ impl RegisterDpnsNameScreen { availability: Availability::Idle, step: Step::Choose, consent_dialog: None, + review: None, selected_key: None, selected_wallet: None, wallet_unlock_popup: WalletUnlockPopup::new(), @@ -154,6 +166,7 @@ impl RegisterDpnsNameScreen { .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 = identity.as_ref().and_then(|qi| { get_selected_wallet(qi, Some(&self.app_context), None) @@ -195,12 +208,11 @@ impl RegisterDpnsNameScreen { contest_fee_credits(self.app_context.sdk_platform_version()) } - fn total_fee(&self, needs_vote: bool) -> u64 { - self.registration_fee() + if needs_vote { self.contest_fee() } else { 0 } - } - /// 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 { @@ -244,11 +256,36 @@ impl RegisterDpnsNameScreen { )) } + 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 + }, + }) + } + + fn review_is_current(&self) -> bool { + self.review.is_some() && self.review == self.payment_review() + } + fn continue_clicked(&mut self) { - let Some(availability) = self.current_availability() else { + let Some(review) = self.payment_review() else { return; }; - if !availability.needs_vote() { + let needs_vote = review.needs_vote; + self.review = Some(review); + if !needs_vote { self.step = Step::Confirm; return; } @@ -274,12 +311,23 @@ impl RegisterDpnsNameScreen { /// Dispatch the registration and raise the blocking overlay. fn begin_registration(&mut self, ctx: &Context) -> AppAction { + if self.step != Step::Confirm { + return AppAction::None; + } + 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: self.label().to_owned(), + 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; @@ -329,6 +377,7 @@ impl RegisterDpnsNameScreen { /// 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; } @@ -438,17 +487,22 @@ impl RegisterDpnsNameScreen { } 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 = self.label().to_owned(); - let needs_vote = self - .current_availability() - .is_some_and(UsernameAvailability::needs_vote); - let registration_fee = self.registration_fee(); - let total = self.total_fee(needs_vote); + 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"); @@ -483,7 +537,7 @@ impl RegisterDpnsNameScreen { ui.end_row(); if needs_vote { ui.label("Community vote fee (not returned)"); - ui.label(format_credits_as_dash(self.contest_fee())); + ui.label(format_credits_as_dash(review.contest_fee)); ui.end_row(); } ui.label(RichText::new("Total").strong()); @@ -725,6 +779,8 @@ impl ScreenLike for RegisterDpnsNameScreen { row: AvailabilityRow::Known(*availability), }; self.registration_error_handled = true; + } else if matches!(error, TaskError::UsernameRegistrationTermsChanged) { + self.on_label_changed(); } else { self.step = Step::Confirm; } @@ -864,9 +920,16 @@ impl ScreenLike for RegisterDpnsNameScreen { match dialog.show(ui).inner.dialog_response { Some(ConfirmationStatus::Confirmed) => { self.consent_dialog = None; - self.step = Step::Confirm; + if self.review_is_current() { + self.step = Step::Confirm; + } else { + self.on_label_changed(); + } + } + Some(ConfirmationStatus::Canceled) => { + self.consent_dialog = None; + self.review = None; } - Some(ConfirmationStatus::Canceled) => self.consent_dialog = None, None => {} } } @@ -938,10 +1001,5 @@ mod tests { 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"); - assert_eq!( - screen.total_fee(true), - screen.registration_fee() + 10_000_000_000 - ); - assert_eq!(screen.total_fee(false), screen.registration_fee()); } } diff --git a/tests/backend-e2e/dashpay_tasks.rs b/tests/backend-e2e/dashpay_tasks.rs index c36794652..c1ae089f8 100644 --- a/tests/backend-e2e/dashpay_tasks.rs +++ b/tests/backend-e2e/dashpay_tasks.rs @@ -996,6 +996,7 @@ 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 f0ddfdf15..fdfdeeb4b 100644 --- a/tests/backend-e2e/framework/fixtures.rs +++ b/tests/backend-e2e/framework/fixtures.rs @@ -355,6 +355,7 @@ 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| { diff --git a/tests/backend-e2e/register_dpns.rs b/tests/backend-e2e/register_dpns.rs index f42d32ff6..a0bd02314 100644 --- a/tests/backend-e2e/register_dpns.rs +++ b/tests/backend-e2e/register_dpns.rs @@ -44,6 +44,7 @@ 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) diff --git a/tests/kittest/identity_usernames.rs b/tests/kittest/identity_usernames.rs index 406fc2c06..b8db0e0d1 100644 --- a/tests/kittest/identity_usernames.rs +++ b/tests/kittest/identity_usernames.rs @@ -1054,3 +1054,69 @@ fn loaded_identities_list_the_main_username_first() { 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" + ); + }); +} From b0b7d2e29137a6e3053a811f546fca0f4466986a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:53:53 +0000 Subject: [PATCH 120/194] test(dpns): prepare payment review before overlay error dispatch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Complete availability and payment review in the overlay regression fixture before dispatching, preserving the matching-error and unrelated-error checks. πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- tests/kittest/register_dpns_name_screen.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/kittest/register_dpns_name_screen.rs b/tests/kittest/register_dpns_name_screen.rs index ace3fd03c..d145da7b1 100644 --- a/tests/kittest/register_dpns_name_screen.rs +++ b/tests/kittest/register_dpns_name_screen.rs @@ -17,6 +17,7 @@ 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; @@ -198,6 +199,12 @@ fn dpns_registration_error_clears_overlay() { app_context.set_selected_identity(Some(identity_id)); let mut screen = RegisterDpnsNameScreen::new(&app_context, RegisterDpnsNameSource::Dpns); 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(); let AppAction::BackendTaskWithContext { context, .. } = From 939316ab2f725482652dcd24064620534dfd9e9f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:06:29 +0000 Subject: [PATCH 121/194] fix(dpns): preserve saved requests and address voting review feedback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Read authoritative username requests before incremental writes, expose full contender IDs, and correlate refresh results across stacked screens. Cache scheduled groups and centralize authoritative target selection. Keep voting models pure by supplying operation IDs/time and defining a model schema error. Align node handles, UTC labels, identity entry copy, and the UX specification. Add regressions for initial cache failure, hidden refresh completion, exact target keys, deterministic construction, and full-ID review rendering. Validation: cargo fmt and diff check. Tests and Clippy delegated to CI. πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 6 + .../02-ux-spec.md | 34 ++-- src/app.rs | 81 +++++++- src/backend_task/contested_names/mod.rs | 40 ++-- src/backend_task/error.rs | 7 + src/context/contested_names_db.rs | 123 +++++++++---- src/context/dpns_vote_attention.rs | 26 +-- src/context/dpns_vote_operations/counts.rs | 3 +- src/context/dpns_vote_operations/mod.rs | 67 ++++--- src/context/dpns_vote_state.rs | 8 +- src/context/identity_db.rs | 2 +- src/context/legacy_scheduled_votes.rs | 7 +- src/model/dpns_voting/mod.rs | 173 ++++++++++++------ src/model/dpns_voting/progress.rs | 62 +++---- src/ui/dpns/copy.rs | 5 +- src/ui/dpns/dpns_contested_names_screen.rs | 77 ++++---- src/ui/dpns/progress_drawer.rs | 6 +- .../add_new_identity_screen/success_screen.rs | 2 +- src/ui/identity/username_request_screen.rs | 52 ++++-- src/ui/state/dpns_vote_operations.rs | 121 ++++++------ 20 files changed, 556 insertions(+), 346 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f704ed8e..82e172fb0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -206,6 +206,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- Username request updates preserve saved requests after a failed startup read, and + status refreshes complete when the request page is hidden behind registration. +- Voting confirmation and schedule choices expose full contender identities; + scheduled votes use consistent node handles and explicit UTC timestamps. +- Voting views share outcome selection and reuse scheduled decision groups between refreshes. + - Restoring imported keys remains recoverable after interrupted storage writes and reports unreadable protected keys. Startup migration preserves existing keys, seeds, and their password protection. 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 index a60ae4acd..b0ae8e10b 100644 --- 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 @@ -59,11 +59,11 @@ Card (two columns): - 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}` (1–9) Β· `Lock name` (L) Β· - `Abstain` (A). The node line reads `Your nodes: 19 not voted Β· 4 voted Abstain - Β· mn-07 has no changes left`. When the decision changes earlier votes: +- 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 unavailable for 3 nodes; they're left out.` with + `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. @@ -74,9 +74,8 @@ 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): `Needs attention: 1 vote -from mn-12 on dashfan.dash is still being checked. Don't submit it again. -1 scheduled vote was missed.` [Show]. +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]. ## Node set (frame V1b) @@ -88,6 +87,9 @@ A popover with radios: All my nodes Β· Evonodes only Β· Masternodes only Β· Cust `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 @@ -109,10 +111,11 @@ Rules (unchanged from #901, now in the confirm step): ## Progress drawer (frame V2b) As specified in VOTE-FR-083. -- Row copy by status: `Done` Β· `Sending` Β· `Being checked` + `This vote may - already have been submitted. Don't submit it again.` [Check again] Β· - `Not applied` + `Platform shows a different vote.` [Review again] Β· - `Not cast` + reason. +- Row copy by status: `Confirmed` Β· `Submitting` Β· `Confirming` Β· + `Still being checked. Do not submit it again.` [Check again] Β· + `Not applied` [Review again] Β· `Not submitted` + saved reason. +- A different current vote does not prove that an ambiguous submission failed. + Checking retains the duplicate-prevention lock until a conclusive result. - Collapsed state: a chip `Casting 44 votes Β· 33 done` above the network chip. - The final banner is defined in VOTE-FR-061. @@ -120,9 +123,10 @@ As specified in VOTE-FR-083. 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` + `Dash Evo Tool wasn't - running at that time. Voting is still open for {time}.` [Cast now] [Edit] - [Remove] Β· `Not cast` + saved reason + valid action Β· `Cast with {n} nodes`. +- 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.` @@ -142,7 +146,7 @@ or Testnet network. Devnet and Regtest have no public explorer link. | No nodes loaded | `Load a masternode with its voting key to vote on name contests.` (contests shown read-only; choice tooltip `Load a masternode with a voting key to vote.`) | 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 couldn't be read, so this history may be incomplete. Votes that are still being checked stay protected from resubmission.` | Retry loading | +| 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) diff --git a/src/app.rs b/src/app.rs index 5fbe62c5b..278b7f3ac 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1532,6 +1532,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. /// @@ -3115,6 +3133,11 @@ impl App for AppState { } => { let unboxed_message = *message; 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); match unboxed_message { @@ -3470,6 +3493,11 @@ 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); @@ -3942,7 +3970,7 @@ mod migration_banner_tests { use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; fn feedback_operation(statuses: &[DpnsVoteTargetStatus]) -> DpnsVoteOperation { - let mut operation = DpnsVoteOperation::new( + let mut operation = AppContext::new_dpns_vote_operation( statuses .iter() .enumerate() @@ -4579,6 +4607,57 @@ mod dpns_result_routing_tests { 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" + ); + } + } + #[test] fn voting_ui_results_route_to_the_hidden_voting_panel_only_once() { let result = BackendTaskSuccessResult::ScheduledVoteSweepCompleted { diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 54ffc5454..bacb95d2b 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -464,7 +464,7 @@ impl AppContext { )?; // An explicit retry must reach fresh preflight even if the cached // choice matches. Preflight records an already-satisfied target durably. - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { current_choice: None, ..target }]); @@ -1306,7 +1306,7 @@ mod tests { name: &str, timestamp: u64, ) -> DpnsVoteOperation { - DpnsVoteOperation::new(vec![ + AppContext::new_dpns_vote_operation(vec![ context .dpns_vote_target( &qualified_identity(1), @@ -1328,7 +1328,7 @@ mod tests { first.timing = VoteTiming::Now; let mut second = first.clone(); second.key.voter_id = Identifier::from([2; 32]); - let mut operation = DpnsVoteOperation::new(vec![first, second]); + 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(); @@ -1446,7 +1446,10 @@ mod tests { 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 = DpnsVoteOperation::new(vec![operation.targets[0].target.clone(), sibling]); + 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) @@ -1486,7 +1489,7 @@ mod tests { context .insert_dpns_vote_operation(&mut previous, None) .unwrap(); - let mut newer = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut newer = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { requested_choice: ResourceVoteChoice::Abstain, timing: VoteTiming::Now, ..previous.targets[0].target.clone() @@ -1519,7 +1522,7 @@ mod tests { #[test] fn new_immediate_vote_requires_review_when_it_becomes_a_change() { let (_temp, context) = vote_context(); - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { timing: VoteTiming::Now, ..scheduled_operation_for(&context, "alice", 42).targets[0] .target @@ -1614,7 +1617,7 @@ mod tests { ), (None, None, DpnsVoteTargetStatus::Queued), ] { - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { timing: VoteTiming::Now, current_choice: reviewed, ..scheduled_operation_for(&context, "alice", 42).targets[0] @@ -1859,7 +1862,8 @@ mod tests { 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 = DpnsVoteOperation::new(targets.into_iter().map(|o| o.target).collect()); + 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; @@ -1939,7 +1943,7 @@ mod tests { false, ) .expect("scheduled target"); - let mut operation = DpnsVoteOperation::new(vec![target]); + let mut operation = AppContext::new_dpns_vote_operation(vec![target]); let operation_id = operation.id; context .insert_dpns_vote_operation(&mut operation, None) @@ -1972,13 +1976,13 @@ mod tests { current_choice: None, timing: VoteTiming::Scheduled(42), }; - let mut older = DpnsVoteOperation::new(vec![target.clone()]); + let mut older = AppContext::new_dpns_vote_operation(vec![target.clone()]); older.created_at = 1; older.targets[0].status = DpnsVoteTargetStatus::Confirmed; - let mut newer = DpnsVoteOperation::new(vec![target.clone()]); + 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 = DpnsVoteOperation::new(vec![target]); + 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()]; @@ -2215,7 +2219,7 @@ mod tests { voter_id: Identifier::from([1; 32]), vote_poll_id: Identifier::from([2; 32]), }; - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: key.clone(), voter_alias: None, contested_name: "dominguez".to_owned(), @@ -2300,7 +2304,7 @@ mod tests { "a terminal operation must become prunable instead of growing the journal forever" ); - let mut retry = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut retry = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { current_choice: None, ..persisted.targets[0].target.clone() }]); @@ -2317,7 +2321,7 @@ mod tests { crate::wallet_backend::kv_test_support::InMemoryKv::default(), )); context.set_det_kv_override_for_test(kv); - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: DpnsVoteTargetKey { network: Network::Testnet, voter_id: Identifier::from([1; 32]), @@ -2507,7 +2511,7 @@ mod tests { .expect("wire wallet backend offline"); context .set_det_kv_override_for_test(crate::wallet_backend::DetKv::from_store(store.clone())); - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: DpnsVoteTargetKey { network: Network::Testnet, voter_id: Identifier::from([1; 32]), @@ -2527,7 +2531,7 @@ mod tests { .expect("persist in-flight operation"); context.dpns_vote_recovery.lock().await.initialized = true; let mut live = operation.clone(); - live.id = DpnsVoteOperation::new(Vec::new()).id; + 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(); @@ -2812,7 +2816,7 @@ mod tests { ) .await .unwrap(); - let operation = DpnsVoteOperation::new(vec![ + let operation = AppContext::new_dpns_vote_operation(vec![ context .dpns_vote_target( &voter, diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 020ac5fd3..7ebde227b 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -2034,6 +2034,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 // ────────────────────────────────────────────────────────────────────────── diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 11c5b20b4..02428242b 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -16,7 +16,7 @@ use crate::model::dpns_usernames::{ }; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, VoteTiming, - dpns_vote_authority_rank, + authoritative_dpns_vote_outcomes, }; use crate::model::qualified_identity::QualifiedIdentity; use crate::utils::time::now_ms; @@ -48,32 +48,10 @@ fn scheduled_vote_journal_summary( voter_id: Identifier, dismissed: &BTreeSet<(DpnsVoteOperationId, DpnsVoteTargetKey)>, ) -> (bool, bool) { - let authoritative_by_target = operations - .iter() - .flat_map(|operation| { - operation - .targets - .iter() - .map(move |outcome| (operation.created_at, outcome)) - }) - .filter(|(_, outcome)| { - outcome.target.key.voter_id == voter_id - && matches!(outcome.target.timing, VoteTiming::Scheduled(_)) - }) - .fold( - BTreeMap::new(), - |mut authoritative, (created_at, outcome)| { - let rank = - dpns_vote_authority_rank(created_at, outcome.operation_id, outcome.status); - let entry = authoritative - .entry(&outcome.target.key) - .or_insert((rank, outcome)); - if rank >= entry.0 { - *entry = (rank, outcome); - } - authoritative - }, - ); + 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() @@ -384,18 +362,23 @@ impl AppContext { let kv = self.det_kv()?; let key = identity_key(USERNAME_REQUESTS_KEY_PREFIX, identity_id); let mut cache = self.username_cache_mut(); - let current = cache.requests.get(identity_id).cloned().unwrap_or_default(); + let current = kv + .get::>(DetScope::Global, &key) + .map_err(username_err)? + .unwrap_or_default(); let requests = update(¤t); - if requests == current { - return Ok(()); + 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() { - kv.delete(DetScope::Global, &key).map_err(username_err)?; cache.requests.remove(identity_id); cache.hydration_pending.remove(identity_id); } else { - kv.put(DetScope::Global, &key, &requests) - .map_err(username_err)?; if requests .iter() .any(|request| request.phase == RequestPhase::Won) @@ -1118,6 +1101,68 @@ mod tests { } } + #[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!( + 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!( + 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(); @@ -1406,7 +1451,7 @@ mod tests { current_choice: None, timing: VoteTiming::Scheduled(42), }); - let mut operation = DpnsVoteOperation::new(targets.into()); + let mut operation = AppContext::new_dpns_vote_operation(targets.into()); operation.targets[0].status = DpnsVoteTargetStatus::Rejected; operation.targets[1].status = DpnsVoteTargetStatus::Unconfirmed; context @@ -1445,7 +1490,7 @@ mod tests { #[test] fn terminal_schedule_failure_is_not_reported_as_pending() { let voter_id = Identifier::from([7; 32]); - let mut operation = DpnsVoteOperation::new(vec![ + let mut operation = AppContext::new_dpns_vote_operation(vec![ crate::model::dpns_voting::DpnsVoteTarget { key: crate::model::dpns_voting::DpnsVoteTargetKey { network: Network::Testnet, @@ -1490,7 +1535,7 @@ mod tests { #[test] fn cancelled_schedule_is_not_reported_as_failed() { let voter_id = Identifier::from([7; 32]); - let mut operation = DpnsVoteOperation::new(vec![ + let mut operation = AppContext::new_dpns_vote_operation(vec![ crate::model::dpns_voting::DpnsVoteTarget { key: crate::model::dpns_voting::DpnsVoteTargetKey { network: Network::Testnet, @@ -1528,10 +1573,10 @@ mod tests { current_choice: None, timing: VoteTiming::Scheduled(42), }; - let mut failed = DpnsVoteOperation::new(vec![target.clone()]); + let mut failed = AppContext::new_dpns_vote_operation(vec![target.clone()]); failed.created_at = 1; failed.targets[0].status = DpnsVoteTargetStatus::Rejected; - let mut confirmed = DpnsVoteOperation::new(vec![target]); + let mut confirmed = AppContext::new_dpns_vote_operation(vec![target]); confirmed.created_at = 2; confirmed.targets[0].status = DpnsVoteTargetStatus::Confirmed; @@ -1655,7 +1700,7 @@ mod tests { .unwrap(); } let mut operation = - DpnsVoteOperation::new(vec![crate::model::dpns_voting::DpnsVoteTarget { + AppContext::new_dpns_vote_operation(vec![crate::model::dpns_voting::DpnsVoteTarget { key: DpnsVoteTargetKey { network: Network::Testnet, voter_id: Identifier::from([1; 32]), diff --git a/src/context/dpns_vote_attention.rs b/src/context/dpns_vote_attention.rs index dee0847df..f632c47d3 100644 --- a/src/context/dpns_vote_attention.rs +++ b/src/context/dpns_vote_attention.rs @@ -12,8 +12,8 @@ use crate::model::dpns_voting::operator::{ }; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsVoteOperation, DpnsVoteOutcome, DpnsVotePollAvailability, - DpnsVoteTargetKey, DpnsVoteTargetStatus, dpns_vote_authority_rank, dpns_vote_lock_holders, - dpns_vote_poll_availability, + DpnsVoteTargetKey, DpnsVoteTargetStatus, authoritative_dpns_vote_outcomes, + dpns_vote_lock_holders, dpns_vote_poll_availability, }; use crate::model::qualified_identity::IdentityType; use crate::utils::time::now_ms; @@ -25,25 +25,9 @@ use std::sync::Arc; /// Distinct targets whose authoritative outcome is still `Unconfirmed`. pub(crate) fn unresolved_target_count(operations: &[DpnsVoteOperation]) -> usize { - let mut authoritative = BTreeMap::new(); - for operation in operations { - for outcome in &operation.targets { - let rank = dpns_vote_authority_rank( - operation.created_at, - outcome.operation_id, - outcome.status, - ); - let entry = authoritative - .entry(&outcome.target.key) - .or_insert((rank, outcome.status)); - if rank >= entry.0 { - *entry = (rank, outcome.status); - } - } - } - authoritative + authoritative_dpns_vote_outcomes(operations, |_| true) .values() - .filter(|(_, status)| *status == DpnsVoteTargetStatus::Unconfirmed) + .filter(|(_, outcome)| outcome.status == DpnsVoteTargetStatus::Unconfirmed) .count() } @@ -402,7 +386,7 @@ mod tests { use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; fn operation(poll: u8, status: DpnsVoteTargetStatus, created_at: u64) -> DpnsVoteOperation { - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: DpnsVoteTargetKey { network: Network::Testnet, voter_id: Identifier::from([1; 32]), diff --git a/src/context/dpns_vote_operations/counts.rs b/src/context/dpns_vote_operations/counts.rs index f70e7fd93..8c6bb7c84 100644 --- a/src/context/dpns_vote_operations/counts.rs +++ b/src/context/dpns_vote_operations/counts.rs @@ -104,6 +104,7 @@ pub(super) fn forget_vote_counts( #[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; @@ -119,7 +120,7 @@ mod tests { } fn operation(status: DpnsVoteTargetStatus) -> DpnsVoteOperation { - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: key(2), voter_alias: None, contested_name: "alice".to_owned(), diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index 8186ced70..cf2113881 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -15,9 +15,9 @@ use super::AppContext; use crate::backend_task::error::TaskError; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome, - DpnsScheduledVoteEdit, DpnsScheduledVoteKey, DpnsVoteAuthorityRank, DpnsVoteFailure, - DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, - DpnsVoteTargetStatus, VoteTiming, dpns_vote_authority_rank, unavailable_preflight_outcome, + DpnsScheduledVoteEdit, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, + DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + authoritative_dpns_vote_outcomes, unavailable_preflight_outcome, }; use crate::utils::time::now_ms; use crate::wallet_backend::{DetKv, DetScope}; @@ -427,6 +427,15 @@ fn operation_for_schedule_edit( } 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 @@ -885,12 +894,15 @@ impl AppContext { &self, ) -> Result, TaskError> { let (_guard, kv) = self.journal()?; - let mut outcomes = BTreeMap::< - DpnsScheduledVoteKey, - (DpnsVoteAuthorityRank, DpnsScheduledVoteClearOutcome), - >::new(); - - for mut operation in load_operations(&kv, self.network)? { + 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 @@ -926,22 +938,12 @@ impl AppContext { DpnsScheduledVoteClearDisposition::Cleared } }; - let rank = dpns_vote_authority_rank(operation.created_at, operation.id, status); - let should_replace = outcomes - .get(&key) - .is_none_or(|(existing_rank, _)| rank > *existing_rank); - if should_replace { - outcomes.insert( - key.clone(), - ( - rank, - DpnsScheduledVoteClearOutcome { - operation_id: Some(operation.id), - key, - disposition, - }, - ), - ); + if selected.contains(&(operation.id, outcome.target.key.clone())) { + outcomes.push(DpnsScheduledVoteClearOutcome { + operation_id: Some(operation.id), + key, + disposition, + }); } } if changed { @@ -950,7 +952,7 @@ impl AppContext { } prune_terminal_operations(&kv, self.network)?; - Ok(outcomes.into_values().map(|(_, outcome)| outcome).collect()) + Ok(outcomes) } } @@ -1034,7 +1036,7 @@ mod tests { } fn operation(status: DpnsVoteTargetStatus) -> DpnsVoteOperation { - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: DpnsVoteTargetKey { network: Network::Testnet, voter_id: Identifier::from([1; 32]), @@ -1062,6 +1064,15 @@ mod tests { operation } + #[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. @@ -2015,7 +2026,7 @@ mod tests { 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::random(); + invalid[3].operation_id = DpnsVoteOperationId::from_bytes(rand::random()); for request in invalid { assert!(matches!( context.edit_scheduled_dpns_vote_target(&request), diff --git a/src/context/dpns_vote_state.rs b/src/context/dpns_vote_state.rs index add96c81a..090ab377e 100644 --- a/src/context/dpns_vote_state.rs +++ b/src/context/dpns_vote_state.rs @@ -420,7 +420,7 @@ mod tests { #[tokio::test] async fn review_fixes_overlapping_refreshes_keep_both_due_targets_admitted() { use crate::model::dpns_voting::{ - DpnsVoteOperation, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, }; let temp = tempfile::tempdir().unwrap(); let context = crate::context::test_support::test_app_context(temp.path()); @@ -429,7 +429,7 @@ mod tests { let voter = Identifier::from([1; 32]); let polls = [Identifier::from([2; 32]), Identifier::from([3; 32])]; let mut operations = polls.map(|poll| { - DpnsVoteOperation::new(vec![DpnsVoteTarget { + AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: DpnsVoteTargetKey { network: context.network(), voter_id: voter, @@ -730,14 +730,14 @@ mod tests { assert!(result.state(&context, poll).is_err()); use crate::model::dpns_voting::{ - DpnsVoteOperation, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, }; let key = DpnsVoteTargetKey { network: Network::Testnet, voter_id: voter, vote_poll_id: poll, }; - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: key.clone(), voter_alias: None, contested_name: "example".to_owned(), diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index 960e22d48..fc35391f1 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -2531,7 +2531,7 @@ mod tests { contested_name: &str, status: DpnsVoteTargetStatus, ) -> DpnsVoteOperation { - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: DpnsVoteTargetKey { network: Network::Testnet, voter_id, diff --git a/src/context/legacy_scheduled_votes.rs b/src/context/legacy_scheduled_votes.rs index 96f17bde3..5f986d9ca 100644 --- a/src/context/legacy_scheduled_votes.rs +++ b/src/context/legacy_scheduled_votes.rs @@ -38,12 +38,11 @@ impl AppContext { #[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::{ - DpnsVoteOperation, DpnsVoteTarget, DpnsVoteTargetKey, VoteTiming, - }; + 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, @@ -67,7 +66,7 @@ mod tests { "detection leaves the old record intact" ); - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: DpnsVoteTargetKey { network: Network::Testnet, voter_id: Identifier::from([1; 32]), diff --git a/src/model/dpns_voting/mod.rs b/src/model/dpns_voting/mod.rs index 53bdfcac8..32ff84f81 100644 --- a/src/model/dpns_voting/mod.rs +++ b/src/model/dpns_voting/mod.rs @@ -1,5 +1,3 @@ -use crate::backend_task::error::TaskError; -use crate::utils::time::now_ms; use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::data_contract::DataContract; use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; @@ -69,11 +67,6 @@ pub fn dpns_vote_poll_availability( pub struct DpnsVoteOperationId([u8; 16]); impl DpnsVoteOperationId { - /// Generate a random operation identifier without adding a UUID dependency. - pub fn random() -> Self { - Self(rand::random()) - } - /// Return the stable persisted byte representation. pub fn to_bytes(self) -> [u8; 16] { self.0 @@ -312,9 +305,11 @@ pub struct DpnsVoteOperation { impl DpnsVoteOperation { /// Build an operation while removing targets that match proved current state. - pub fn new(targets: Vec) -> Self { - let id = DpnsVoteOperationId::random(); - let created_at = now_ms(); + pub fn new( + id: DpnsVoteOperationId, + created_at: TimestampMillis, + targets: Vec, + ) -> Self { let original_len = targets.len(); let targets = targets .into_iter() @@ -368,6 +363,15 @@ fn dpns_vote_poll_index_values(normalized_label: &str) -> Vec { ] } +/// 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. @@ -377,20 +381,16 @@ fn dpns_vote_poll_index_values(normalized_label: &str) -> Vec { /// /// # Errors /// -/// [`TaskError::DataContractNotFound`] when the contract carries no `domain` -/// document type, and [`TaskError::ContractSchemaMismatch`] when that document -/// type declares no contested index. +/// 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 { +) -> Result { let document_type = dpns_contract .document_type_for_name("domain") - .map_err(|_| TaskError::DataContractNotFound)?; + .map_err(|_| DpnsVotePollError::MissingDomain)?; let Some(contested_index) = document_type.find_contested_index() else { - return Err(TaskError::ContractSchemaMismatch { - detail: "DPNS domain document type has no contested index", - }); + return Err(DpnsVotePollError::MissingContestedIndex); }; Ok(ContestedDocumentResourceVotePoll { index_name: contested_index.name.clone(), @@ -420,23 +420,35 @@ pub fn dpns_vote_authority_rank( (status.holds_lock(), created_at, operation_id) } -/// The outcome that currently speaks for `key`, by [`dpns_vote_authority_rank`]. -/// -/// Returns `None` when no operation in `operations` targets `key`. +/// 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> { - operations - .iter() - .filter_map(|operation| { - operation - .outcome(key) - .map(|outcome| (operation.created_at, outcome)) - }) - .max_by_key(|(created_at, outcome)| { - dpns_vote_authority_rank(*created_at, outcome.operation_id, outcome.status) - }) + authoritative_dpns_vote_outcomes(operations, |outcome| &outcome.target.key == key) + .into_values() + .next() .map(|(_, outcome)| outcome) } @@ -459,6 +471,55 @@ mod tests { 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)); @@ -468,14 +529,13 @@ mod tests { } #[test] - fn operation_ids_are_random_and_distinct() { - let ids: std::collections::BTreeSet<_> = - (0..64).map(|_| DpnsVoteOperationId::random()).collect(); - assert_eq!(ids.len(), 64, "identifiers must not repeat"); - assert!( - !ids.contains(&DpnsVoteOperationId::from_bytes([0; 16])), - "identifiers must not be all-zero" - ); + 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( @@ -528,15 +588,19 @@ mod tests { /// VOTE-TC-003: choosing the proved current vote cannot create a target. #[test] fn operation_suppresses_exact_no_ops() { - let operation = DpnsVoteOperation::new(vec![ - target( - 1, - 1, - Some(ResourceVoteChoice::Lock), - ResourceVoteChoice::Lock, - ), - target(1, 2, None, ResourceVoteChoice::Abstain), - ]); + 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); @@ -549,8 +613,11 @@ mod tests { /// VOTE-TC-032: outcomes retain the exact voter Γ— contest target. #[test] fn outcomes_retain_target_correlation() { - let operation = - DpnsVoteOperation::new(vec![target(7, 9, None, ResourceVoteChoice::Abstain)]); + 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); @@ -638,7 +705,11 @@ mod tests { } } - let operation = DpnsVoteOperation::new(vec![target(4, 5, None, ResourceVoteChoice::Lock)]); + 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); diff --git a/src/model/dpns_voting/progress.rs b/src/model/dpns_voting/progress.rs index e955040b6..a10d11a56 100644 --- a/src/model/dpns_voting/progress.rs +++ b/src/model/dpns_voting/progress.rs @@ -3,9 +3,9 @@ use super::{ DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTargetStatus, VoteTiming, - dpns_schedule_is_overdue, dpns_vote_authority_rank, + authoritative_dpns_vote_outcomes, dpns_schedule_is_overdue, }; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeSet; /// Where one sent target stands, as the drawer groups it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -124,44 +124,23 @@ pub fn needs_attention( dismissed: &BTreeSet, now_ms: u64, ) -> NeedsAttention { - let mut latest = BTreeMap::new(); - for operation in operations { - for outcome in &operation.targets { - let rank = dpns_vote_authority_rank( - operation.created_at, - outcome.operation_id, - outcome.status, - ); - let current = latest.entry(&outcome.target.key).or_insert(rank); - *current = (*current).max(rank); - } - } let mut attention = NeedsAttention::default(); - for operation in operations { - for outcome in &operation.targets { - let rank = dpns_vote_authority_rank( - operation.created_at, - outcome.operation_id, - outcome.status, - ); - if latest.get(&outcome.target.key) != Some(&rank) { - continue; + 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; } - 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 operation.created_at >= since_ms - && !dismissed.contains(&operation.id) - && progress_phase(outcome) == Some(ProgressPhase::Failed) => - { - attention.failed += 1; - } - _ => {} + _ if operation.created_at >= since_ms + && !dismissed.contains(&operation.id) + && progress_phase(outcome) == Some(ProgressPhase::Failed) => + { + attention.failed += 1; } + _ => {} } } attention @@ -180,6 +159,8 @@ mod tests { statuses: &[(DpnsVoteTargetStatus, VoteTiming)], ) -> DpnsVoteOperation { let mut operation = DpnsVoteOperation::new( + DpnsVoteOperationId::from_bytes((created_at as u128).to_be_bytes()), + created_at, statuses .iter() .enumerate() @@ -197,7 +178,6 @@ mod tests { }) .collect(), ); - operation.created_at = created_at; for (outcome, (status, _)) in operation.targets.iter_mut().zip(statuses) { outcome.status = *status; } @@ -242,10 +222,10 @@ mod tests { #[test] fn drawer_lists_in_flight_and_recent_undismissed_operations() { let old_in_flight = operation(1, &[(S::Unconfirmed, NOW)]); - let old_settled = operation(1, &[(S::Confirmed, NOW)]); + let old_settled = operation(2, &[(S::Confirmed, NOW)]); let recent_settled = operation(100, &[(S::Confirmed, NOW)]); - let dismissed_settled = operation(100, &[(S::Rejected, NOW)]); - let schedule_only = operation(100, &[(S::Scheduled, VoteTiming::Scheduled(500))]); + 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, diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index 1f290c98f..e2dbb073c 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -58,9 +58,8 @@ pub fn vote_choice_label( ResourceVoteChoice::Lock => "Lock name".to_owned(), ResourceVoteChoice::Abstain => "Abstain".to_owned(), ResourceVoteChoice::TowardsIdentity(id) => { - let handle = crate::model::identity_name::shorten_id( - &id.to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58), - ); + 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}"), diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index f5760b81c..0c5a7778b 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -35,9 +35,8 @@ use crate::model::dpns_voting::operator::{ }; use crate::model::dpns_voting::progress::needs_attention; use crate::model::dpns_voting::{ - DpnsCurrentVoteState, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, - DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, - dpns_schedule_is_overdue, + DpnsCurrentVoteState, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperationId, + DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, dpns_schedule_is_overdue, }; use crate::model::qualified_identity::IdentityType; use crate::model::qualified_identity::QualifiedIdentity; @@ -64,7 +63,7 @@ use crate::ui::state::dpns_vote_cards::{ VoteCard, move_focus, shortcut_for, sort_by_time_left, }; use crate::ui::state::dpns_vote_operations::{ - DpnsVoteOperationSnapshot, ScheduledDpnsVoteRow, group_scheduled_rows, + DpnsVoteOperationSnapshot, ScheduledDecisionGroup, ScheduledDpnsVoteRow, group_scheduled_rows, }; use crate::ui::state::dpns_vote_state::DpnsVoteStateSnapshot; use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; @@ -85,7 +84,7 @@ const SCHEDULE_IN_FUTURE_MESSAGE: &str = 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 (in 2 days)`. +/// `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") { @@ -95,7 +94,7 @@ fn timestamp_with_relative(date_time: DateTime) -> String { }; format!( "{absolute} ({relative})", - absolute = date_time.format("%Y-%m-%d %H:%M:%S"), + absolute = date_time.format("%Y-%m-%d %H:%M:%S UTC"), ) } @@ -430,6 +429,7 @@ pub struct DPNSScreen { /// 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, @@ -543,6 +543,7 @@ impl DPNSScreen { active_contests, candidate_names, scheduled_votes, + scheduled_groups: Arc::from([]), selected_votes: Vec::new(), app_context: app_context.clone(), sort_column: SortColumn::ContestedName, @@ -640,6 +641,7 @@ impl DPNSScreen { 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(); @@ -1584,14 +1586,17 @@ impl DPNSScreen { fn render_table_scheduled_votes(&mut self, ui: &mut Ui) -> AppAction { let mut action = AppAction::None; let mut show_cast_progress = false; - let rows = self.scheduled_votes.lock_recover().clone(); - let mut groups = group_scheduled_rows(rows); - if self.sort_order == SortOrder::Descending { - groups.reverse(); - } + let groups = Arc::clone(&self.scheduled_groups); + let descending = self.sort_order == SortOrder::Descending; let now = Utc::now().timestamp_millis().max(0) as u64; egui::ScrollArea::both().show(ui, |ui| { - for (index, group) in groups.iter().enumerate() { + for offset in 0..groups.len() { + let index = if descending { + groups.len() - 1 - offset + } else { + offset + }; + let group = &groups[index]; let dark_mode = ui.visuals().dark_mode; let choice = vote_choice_label( group.choice, @@ -1696,7 +1701,7 @@ impl DPNSScreen { .iter() .find(|identity| identity.identity.id() == vote.voter_id) .and_then(|identity| identity.alias.clone()) - .unwrap_or_else(|| short_identifier(vote.voter_id)); + .unwrap_or_else(|| crate::model::identity_name::masternode_label(vote.voter_id, None)); ui.add(Label::new(voter)); }); row.col(|ui| { @@ -1797,7 +1802,9 @@ impl DPNSScreen { .iter() .find(|identity| identity.identity.id() == row.vote.voter_id) .and_then(|identity| identity.alias.clone()) - .unwrap_or_else(|| short_identifier(row.vote.voter_id)); + .unwrap_or_else(|| { + crate::model::identity_name::masternode_label(row.vote.voter_id, None) + }); let mut choices = vec![ ( ResourceVoteChoice::Lock, @@ -1879,6 +1886,7 @@ impl DPNSScreen { Some(((key.clone(), at), preset)) }) .collect(); + self.scheduled_groups = group_scheduled_rows(rows.clone()).into(); *self.scheduled_votes.lock_recover() = rows; } @@ -2375,7 +2383,7 @@ impl DPNSScreen { return AppAction::None; } let voters = self.casting_voters(&plan); - let operation = DpnsVoteOperation::new(plan.aggregate.targets); + let operation = AppContext::new_dpns_vote_operation(plan.aggregate.targets); let labels = (self.confirm_timing == ConfirmTiming::BeforeEnd).then(|| RelativeScheduleLabels { preset: self.relative_preset, @@ -3074,14 +3082,10 @@ mod tests { Some("alice"), ); assert!(named.starts_with("Vote for alice (")); - assert!(named.contains(&crate::model::identity_name::shorten_id(&encoded))); - assert!(!named.contains(&encoded)); + assert!(named.contains(&encoded)); let unresolved = vote_choice_label(ResourceVoteChoice::TowardsIdentity(candidate_id), None); - assert_eq!( - unresolved, - format!("Vote for {}", short_identifier(candidate_id)) - ); + assert_eq!(unresolved, format!("Vote for {encoded}")); } /// Submission is not blocked when a candidate name cannot be resolved, so @@ -3099,7 +3103,10 @@ mod tests { ); let expected = decision_row( "alpha", - &format!("Vote for {handle}", handle = short_identifier(candidate_id)), + &format!( + "Vote for {handle}", + handle = candidate_id.to_string(Encoding::Base58) + ), 1, ); @@ -3165,7 +3172,13 @@ mod tests { Some("alice") ) ); - assert!(!label.contains(&candidate_id.to_string(Encoding::Base58))); + 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] @@ -3581,7 +3594,7 @@ mod tests { 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 = DpnsVoteOperation::new(vec![target]); + let mut operation = AppContext::new_dpns_vote_operation(vec![target]); operation.targets[0].status = DpnsVoteTargetStatus::Unconfirmed; screen .app_context @@ -3616,7 +3629,7 @@ mod tests { 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 = DpnsVoteOperation::new(vec![target]); + let mut operation = AppContext::new_dpns_vote_operation(vec![target]); operation.targets[0].status = status; screen .app_context @@ -3704,7 +3717,7 @@ mod tests { 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 = DpnsVoteOperation::new(vec![target]); + let mut operation = AppContext::new_dpns_vote_operation(vec![target]); operation.targets[0].failure = Some(failure); screen .app_context @@ -4375,7 +4388,7 @@ mod tests { #[test] fn voting_ui_retry_reviews_only_the_failed_node_and_contest() { let (mut screen, _dir) = voting_ui_review_fixture(); - let operation = DpnsVoteOperation::new(vec![ + let operation = AppContext::new_dpns_vote_operation(vec![ screen .build_review_plan() .unwrap() @@ -4454,7 +4467,7 @@ mod tests { let mut third = first.clone(); third.key.voter_id = Identifier::from([3; 32]); third.voter_alias = Some("node-three".to_owned()); - let mut operation = DpnsVoteOperation::new(vec![first, second, third]); + 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; @@ -4519,7 +4532,7 @@ mod tests { .targets .remove(0); target.timing = VoteTiming::Scheduled(42); - let mut operation = DpnsVoteOperation::new(vec![target]); + let mut operation = AppContext::new_dpns_vote_operation(vec![target]); operation.targets[0].status = DpnsVoteTargetStatus::Queued; screen .app_context @@ -4720,7 +4733,7 @@ mod tests { voter_id, vote_poll_id: Identifier::from([24; 32]), }; - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: key.clone(), voter_alias: None, contested_name: "remove-me".to_owned(), @@ -4759,7 +4772,7 @@ mod tests { vote_poll_id: Identifier::from([26; 32]), }; let at = 1_900_000_000_000; - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: key.clone(), voter_alias: None, contested_name: "later".to_owned(), @@ -4789,7 +4802,7 @@ mod tests { fn clear_all_result_rebuilds_scheduled_rows_immediately() { let (ctx, _temp_dir) = kv_ctx(); let voter_id = Identifier::from([21; 32]); - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: DpnsVoteTargetKey { network: ctx.network(), voter_id, diff --git a/src/ui/dpns/progress_drawer.rs b/src/ui/dpns/progress_drawer.rs index d27ad40f9..d38b9d1ea 100644 --- a/src/ui/dpns/progress_drawer.rs +++ b/src/ui/dpns/progress_drawer.rs @@ -245,14 +245,12 @@ pub fn show(ctx: &egui::Context, app_context: &AppContext, state: &mut DrawerSta #[cfg(test)] mod tests { use super::*; - use crate::model::dpns_voting::{ - DpnsVoteOperation, DpnsVoteTarget, DpnsVoteTargetKey, VoteTiming, - }; + 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 = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: DpnsVoteTargetKey { network: Network::Testnet, voter_id: Identifier::from([1; 32]), 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 395a1dcda..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()), ), ], diff --git a/src/ui/identity/username_request_screen.rs b/src/ui/identity/username_request_screen.rs index 128fd2545..0d7255675 100644 --- a/src/ui/identity/username_request_screen.rs +++ b/src/ui/identity/username_request_screen.rs @@ -8,8 +8,9 @@ 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, BackendTaskSuccessResult}; +use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; use crate::context::AppContext; use crate::model::dpns_usernames::{RequestPhase, TallyStanding, UsernameRequest}; use crate::model::user_role::UserRole; @@ -21,14 +22,14 @@ use crate::ui::identity::register_dpns_name_screen::status_line; use crate::ui::identity::username_copy::{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::{MessageType, RootScreenType, ScreenLike}; +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, - refreshing: bool, + 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. @@ -45,7 +46,7 @@ impl UsernameRequestScreen { app_context: app_context.clone(), identity_id, normalized_label, - refreshing: false, + refresh_context: None, can_vote: false, identity_label: String::new(), }; @@ -63,6 +64,16 @@ impl UsernameRequestScreen { &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) @@ -199,19 +210,16 @@ impl UsernameRequestScreen { ui.add_space(12.0); ui.horizontal(|ui| { ui.label(RichText::new("How the vote is going").strong()); - let label = if self.refreshing { + let label = if self.refresh_context.is_some() { "Refreshing…" } else { "Refresh status" }; if ui - .add_enabled(!self.refreshing, egui::Button::new(label)) + .add_enabled(self.refresh_context.is_none(), egui::Button::new(label)) .clicked() { - self.refreshing = true; - action = AppAction::BackendTask(BackendTask::IdentityTask( - IdentityTask::RefreshMyUsernameRequests, - )); + action = self.begin_refresh(); } }); Self::render_tally(ui, &request); @@ -265,18 +273,24 @@ impl ScreenLike for UsernameRequestScreen { self.refresh(); } - fn display_message(&mut self, _message: &str, message_type: MessageType) { - if matches!(message_type, MessageType::Error | MessageType::Warning) { - self.refreshing = false; + 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_task_result(&mut self, result: BackendTaskSuccessResult) { - if matches!( - result, - BackendTaskSuccessResult::MyUsernameRequestsRefreshed - ) { - self.refreshing = false; + 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; } } diff --git a/src/ui/state/dpns_vote_operations.rs b/src/ui/state/dpns_vote_operations.rs index 0695e2cc9..e845a0b46 100644 --- a/src/ui/state/dpns_vote_operations.rs +++ b/src/ui/state/dpns_vote_operations.rs @@ -7,8 +7,8 @@ use crate::backend_task::contested_names::ScheduledDPNSVote; use crate::backend_task::error::TaskError; use crate::context::AppContext; use crate::model::dpns_voting::{ - DpnsVoteAuthorityRank, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, - DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, dpns_vote_authority_rank, + DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTargetKey, + DpnsVoteTargetStatus, VoteTiming, authoritative_dpns_vote_outcomes, }; #[derive(Debug, Clone, PartialEq)] @@ -32,20 +32,23 @@ pub(crate) struct ScheduledDecisionGroup { /// 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 { - match groups.iter_mut().find(|group| { - group.contested_name == row.vote.contested_name - && group.choice == row.vote.choice - && group.unix_timestamp == row.vote.unix_timestamp - }) { - Some(group) => group.rows.push(row), - None => groups.push(ScheduledDecisionGroup { + 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![row], - }), - } + rows: Vec::new(), + }); + groups.len() - 1 + }); + groups[index].rows.push(row); } groups.sort_by(|a, b| { a.contested_name @@ -110,55 +113,30 @@ impl DpnsVoteOperationSnapshot { } pub(crate) fn scheduled_vote_rows(&self) -> Vec { - let mut journal_rows = BTreeMap::< - (dash_sdk::platform::Identifier, String), - (DpnsVoteAuthorityRank, ScheduledDpnsVoteRow), - >::new(); - for operation in &self.operations { - for outcome in &operation.targets { - let VoteTiming::Scheduled(timestamp) = outcome.target.timing else { - continue; - }; - let pair = ( - outcome.target.key.voter_id, - outcome.target.contested_name.clone(), - ); - let rank = - dpns_vote_authority_rank(operation.created_at, operation.id, outcome.status); - if journal_rows - .get(&pair) - .is_some_and(|(current_rank, _)| *current_rank > rank) - { - continue; - } - journal_rows.insert( - pair, - ( - rank, - 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, - }, - ), - ); - } - } - - journal_rows - .into_values() - .map(|(_, row)| row) - .filter(|row| row.status != DpnsVoteTargetStatus::Cancelled) - .filter(|row| !self.dismissed_schedules.contains(&row.journal_target)) - .collect() + 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) { @@ -206,7 +184,7 @@ mod tests { } fn operation(status: DpnsVoteTargetStatus) -> DpnsVoteOperation { - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: DpnsVoteTargetKey { network: Network::Testnet, voter_id: Identifier::from([1; 32]), @@ -321,7 +299,7 @@ mod tests { choice: ResourceVoteChoice, timestamp: u64, ) -> DpnsVoteOperation { - let mut operation = DpnsVoteOperation::new(vec![DpnsVoteTarget { + let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { key: DpnsVoteTargetKey { network: Network::Testnet, voter_id: Identifier::from([7; 32]), @@ -354,6 +332,23 @@ mod tests { } } + #[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( From 8da0f69950372f6554018369104a778832016926 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:14:00 +0000 Subject: [PATCH 122/194] fix(dpns): publish live vote progress and preserve uncertain outcomes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep cleaned-up contest votes unconfirmed without definitive evidence of their outcome. Reload voting identities when entering Votes, preserving staged node selection. Publish journal changes under the journal guard and update the drawer and cards from memory while a batch runs. Guard awaited username publication against identity removal and propagate local storage failures while retaining successful sibling updates. Add regressions for reconciliation, live progress, roster changes, deletion and storage faults. Validation: cargo fmt --all and git diff --check. Tests and Clippy run in CI. πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 6 + .../04-development-plan.md | 8 +- src/backend_task/contested_names/mod.rs | 234 ++++-------------- src/backend_task/identity/dpns_usernames.rs | 185 ++++++++++++-- src/context/dpns_vote_attention.rs | 7 +- src/context/dpns_vote_operations/mod.rs | 195 ++++++++++----- src/ui/dpns/dpns_contested_names_screen.rs | 142 ++++++++++- src/ui/masternodes/list_screen.rs | 6 +- src/ui/state/dpns_vote_operations.rs | 70 +++++- 9 files changed, 572 insertions(+), 281 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82e172fb0..f5b0fd07b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -206,6 +206,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- Closed contests keep uncertain vote outcomes instead of reporting them as failed + when Platform has removed the voting records. Progress updates during submission, + and entering Votes reloads newly added voting nodes without changing staged choices. +- Username refreshes skip identities removed while a request was in flight and report + local storage errors while retaining successful updates for other identities. + - Username request updates preserve saved requests after a failed startup read, and status refreshes complete when the request page is hidden behind registration. - Voting confirmation and schedule choices expose full contender identities; 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 index 63c7d9386..f16b331ac 100644 --- 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 @@ -106,10 +106,10 @@ If voting has ended, mark it `FailedBeforeSubmission(VotingEnded)`. 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 proved closed contest with no match -marks it NotApplied; while the contest can still accept votes, a missing or -different choice remains Unconfirmed. Transition-based recovery is a future -integration tracked by dashpay/platform#4137. +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) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index bacb95d2b..185762f1a 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -168,23 +168,13 @@ fn missing_voter_outcome( ) } -/// Decide whether one reconciliation observation is terminal. -/// -/// Returns `None` while the outcome stays ambiguous, which keeps the target -/// locked. A current choice that differs from `requested` is not by itself -/// evidence against the submitted transition β€” it may simply predate it β€” so it -/// only becomes terminal once `availability` proves the poll can no longer -/// accept anything. +/// 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, - availability: DpnsVotePollAvailability, ) -> Option { - match (observed, availability) { - (Some(choice), _) if choice == requested => Some(DpnsVoteTargetStatus::Confirmed), - (_, DpnsVotePollAvailability::ProvedClosed) => Some(DpnsVoteTargetStatus::NotApplied), - (_, DpnsVotePollAvailability::MayAccept) => None, - } + (observed == Some(requested)).then_some(DpnsVoteTargetStatus::Confirmed) } fn wrap_scheduled_vote_sweep_result( @@ -950,22 +940,11 @@ impl AppContext { operation_id, }); }; - // TODO: a wedged target is only released once its contest closes. Restore - // the operator-driven "stop waiting and vote again" escape so one can also - // be abandoned mid-contest; that needs a control in the DPNS contests screen. - let contests = self - .all_contested_names()? - .into_iter() - .map(|contest| (contest.normalized_contested_name.clone(), contest)) - .collect::>(); for outcome in operation .targets .iter() .filter(|outcome| outcome.status == DpnsVoteTargetStatus::Unconfirmed) { - // Targets may carry the label the operator typed; contests are keyed normalized. - let normalized = convert_to_homograph_safe_chars(&outcome.target.contested_name); - let availability = dpns_vote_poll_availability(contests.get(&normalized)); let poll_id = outcome.target.key.vote_poll_id; let query = ContestedResourceVotesGivenByIdentityQuery { identity_id: outcome.target.key.voter_id, @@ -980,12 +959,9 @@ impl AppContext { .get(&poll_id) .and_then(Option::as_ref) .map(ResourceVoteGettersV0::resource_vote_choice); - let status = classify_reconciled_vote( - observed, - outcome.target.requested_choice, - availability, - ) - .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); + 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, @@ -2107,77 +2083,30 @@ mod tests { #[test] fn exact_reconciliation_confirms_only_the_requested_choice() { assert_eq!( - classify_reconciled_vote( - Some(ResourceVoteChoice::Lock), - ResourceVoteChoice::Lock, - DpnsVotePollAvailability::MayAccept, - ), + classify_reconciled_vote(Some(ResourceVoteChoice::Lock), ResourceVoteChoice::Lock,), Some(DpnsVoteTargetStatus::Confirmed) ); assert_eq!( - classify_reconciled_vote( - Some(ResourceVoteChoice::Abstain), - ResourceVoteChoice::Lock, - DpnsVotePollAvailability::MayAccept, - ), + 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, - DpnsVotePollAvailability::MayAccept, - ), + classify_reconciled_vote(None, ResourceVoteChoice::Lock,), None, "an absent exact row remains ambiguous and must not release its lock" ); } - /// A closed poll is the terminal evidence that ambiguity alone never supplies. - #[test] - fn a_closed_poll_turns_an_unreconcilable_vote_into_a_terminal_verdict() { - assert_eq!( - classify_reconciled_vote( - Some(ResourceVoteChoice::Abstain), - ResourceVoteChoice::Lock, - DpnsVotePollAvailability::ProvedClosed, - ), - Some(DpnsVoteTargetStatus::NotApplied), - "a decided contest can no longer accept the submitted transition" - ); - assert_eq!( - classify_reconciled_vote( - None, - ResourceVoteChoice::Lock, - DpnsVotePollAvailability::ProvedClosed, - ), - Some(DpnsVoteTargetStatus::NotApplied), - "an absent row on a closed poll proves the vote never applied" - ); - assert_eq!( - classify_reconciled_vote( - Some(ResourceVoteChoice::Lock), - ResourceVoteChoice::Lock, - DpnsVotePollAvailability::ProvedClosed, - ), - Some(DpnsVoteTargetStatus::Confirmed), - "a vote that did apply stays confirmed after the contest closes" - ); - assert!(!DpnsVoteTargetStatus::NotApplied.holds_lock()); - } - #[test] 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(); for now in [1_000, 2_000, u64::MAX] { - let availability = dpns_vote_poll_availability(contests.first()); for observed in [None, Some(ResourceVoteChoice::Abstain)] { - let status = - classify_reconciled_vote(observed, ResourceVoteChoice::Lock, availability) - .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); + let status = classify_reconciled_vote(observed, ResourceVoteChoice::Lock) + .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); assert_eq!(status, DpnsVoteTargetStatus::Unconfirmed); assert!(status.holds_lock()); } @@ -2210,107 +2139,50 @@ mod tests { } } - /// An unreconcilable target must not hold its lock past the contest it belongs to. #[tokio::test] - async fn an_unreconcilable_vote_releases_its_lock_once_the_contest_closes() { + async fn closed_contest_cleanup_does_not_prove_a_vote_failed() { let (_temp, context) = vote_context(); - let key = DpnsVoteTargetKey { - network: Network::Testnet, - voter_id: Identifier::from([1; 32]), - vote_poll_id: Identifier::from([2; 32]), - }; + context.seed_dpns_contest_for_test("dominguez", Some(1), true); let mut operation = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { - key: key.clone(), + 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".to_owned(), - requested_choice: ResourceVoteChoice::Abstain, - current_choice: Some(ResourceVoteChoice::Lock), + contested_name: "dominguez".into(), + requested_choice: ResourceVoteChoice::Lock, + current_choice: None, timing: VoteTiming::Now, }]); - operation.targets[0].status = DpnsVoteTargetStatus::Confirming; - let operation_id = operation.id; + operation.targets[0].status = DpnsVoteTargetStatus::Unconfirmed; context .insert_dpns_vote_operation(&mut operation, None) - .expect("persist confirming operation"); - // The broadcast was lost: the node keeps proving its previous choice. + .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 - .update_dpns_vote_target( - operation_id, - &key, - DpnsVoteTargetStatus::Unconfirmed, - Some(DpnsVoteFailure::ResultUnconfirmed), - ) - .expect("persist unconfirmed operation"); - - let observed = Some(ResourceVoteChoice::Lock); - let mut expected_current = None; - for round in 0..3 { - let status = classify_reconciled_vote( - observed, - ResourceVoteChoice::Abstain, - DpnsVotePollAvailability::MayAccept, - ) - .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); - assert!( - context - .update_dpns_vote_reconciliation( - operation_id, - &key, - expected_current, - observed, - status, - ) - .expect("persist observation") - ); - expected_current = observed; - assert_eq!( - context.dpns_vote_target_status(&key).unwrap(), - Some(DpnsVoteTargetStatus::Unconfirmed), - "round {round}: an open contest keeps the ambiguous target locked" - ); - } - - let terminal = classify_reconciled_vote( - observed, - ResourceVoteChoice::Abstain, - DpnsVotePollAvailability::ProvedClosed, - ) - .expect("a closed poll must reach a terminal verdict"); - assert_eq!(terminal, DpnsVoteTargetStatus::NotApplied); - assert!( - context - .update_dpns_vote_reconciliation( - operation_id, - &key, - expected_current, - observed, - terminal, - ) - .expect("persist terminal verdict") - ); - - assert_eq!( - context.dpns_vote_target_status(&key).unwrap(), - None, - "the exact voter x poll lock must be released" - ); - let persisted = context.dpns_vote_operation(operation_id).unwrap().unwrap(); + .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!( - persisted.targets[0].status, - DpnsVoteTargetStatus::NotApplied - ); - assert!( - persisted.is_complete(), - "a terminal operation must become prunable instead of growing the journal forever" + context + .dpns_vote_count(key.voter_id, key.vote_poll_id) + .unwrap(), + None ); - - let mut retry = AppContext::new_dpns_vote_operation(vec![DpnsVoteTarget { - current_choice: None, - ..persisted.targets[0].target.clone() - }]); - context - .insert_dpns_vote_operation(&mut retry, None) - .expect("a released target must accept a fresh operation"); } #[test] @@ -2360,12 +2232,8 @@ mod tests { ); let observed = Some(ResourceVoteChoice::Abstain); - let first_status = classify_reconciled_vote( - observed, - ResourceVoteChoice::Lock, - DpnsVotePollAvailability::MayAccept, - ) - .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); + 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,) @@ -2374,12 +2242,8 @@ mod tests { 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, - DpnsVotePollAvailability::MayAccept, - ) - .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); + let second_status = classify_reconciled_vote(observed, ResourceVoteChoice::Lock) + .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); assert!( context .update_dpns_vote_reconciliation( @@ -2707,7 +2571,7 @@ mod tests { ); for observed in [None, Some(ResourceVoteChoice::Abstain)] { assert_eq!( - classify_reconciled_vote(observed, ResourceVoteChoice::Lock, availability), + classify_reconciled_vote(observed, ResourceVoteChoice::Lock), None, "observed {observed:?}: the unresolved target stays locked" ); diff --git a/src/backend_task/identity/dpns_usernames.rs b/src/backend_task/identity/dpns_usernames.rs index c499ad452..f9507adb3 100644 --- a/src/backend_task/identity/dpns_usernames.rs +++ b/src/backend_task/identity/dpns_usernames.rs @@ -183,21 +183,13 @@ impl AppContext { &self, sdk: &Sdk, ) -> Result { - let identities = match self.load_local_user_identities() { - Ok(identities) => identities, - Err(error) => { - tracing::debug!( - ?error, - "Username requests not refreshed: identities unavailable" - ); - return Ok(BackendTaskSuccessResult::MyUsernameRequestsRefreshed); - } - }; + 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); @@ -231,16 +223,22 @@ impl AppContext { )); } } - self.apply_username_refresh(sdk, identity, fresh).await; + 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 = sdk - .get_contested_non_resolved_usernames(None) - .await - .map_err(|source| TaskError::UsernameRequestRefreshFailed { - source: Box::new(source), - })?; + 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 now = now_ms(); let snapshots: BTreeMap<&String, (ContestSnapshot, u64)> = running .iter() @@ -273,7 +271,12 @@ impl AppContext { ) }) .collect(); - self.apply_username_refresh(sdk, &identity, fresh).await; + 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) } @@ -283,15 +286,26 @@ impl AppContext { sdk: &Sdk, identity: &QualifiedIdentity, fresh: Vec, - ) { + ) -> Result<(), TaskError> { let identity_id = identity.identity.id(); - if let Err(error) = self.update_username_requests(&identity_id, |current| { - merge_requests(current, fresh, now_ms(), Some(&identity.dpns_names)) - }) { - tracing::warn!(?error, %identity_id, "Username requests could not be stored"); + { + 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. @@ -479,6 +493,128 @@ mod tests { sdk } + #[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_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(); + ctx.delete_local_qualified_identity(&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_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; @@ -516,7 +652,8 @@ mod tests { store.fail_next_puts_containing("det:identity:v1", 1); } ctx.apply_username_refresh(&sdk, &identity, vec![won.clone()]) - .await; + .await + .unwrap(); assert_eq!(ctx.username_requests_for(&id)[0].phase, RequestPhase::Won); assert!( ctx.username_requests_need_refresh(), diff --git a/src/context/dpns_vote_attention.rs b/src/context/dpns_vote_attention.rs index f632c47d3..1a7a296fd 100644 --- a/src/context/dpns_vote_attention.rs +++ b/src/context/dpns_vote_attention.rs @@ -42,8 +42,7 @@ impl AppContext { ) } - /// Journal operations as of the last recompute, for the progress drawer - /// (cheap; safe to call every frame). + /// Live durable journal progress (cheap; safe to call every frame). pub fn dpns_vote_progress(&self) -> Arc<[DpnsVoteOperation]> { Arc::clone( &self @@ -295,10 +294,6 @@ impl AppContext { return self.dpns_vote_attention(); } }; - *self - .dpns_vote_progress - .write() - .unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::from(operations.as_slice()); match self.compute_dpns_vote_attention(&operations) { Ok(summary) => { let summary = Arc::new(summary); diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index cf2113881..a50608128 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -458,6 +458,38 @@ impl AppContext { 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] = operation; + } + } else { + let mut operations = progress.to_vec(); + operations.push(operation); + *progress = operations.into(); + } + 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, @@ -501,8 +533,9 @@ impl AppContext { operation_id: DpnsVoteOperationId, key: &DpnsVoteTargetKey, ) -> Result { - let _guard = self.journal_guard(); - transition_scheduled_target_to_queued(&self.det_kv()?, self.network, operation_id, key) + self.mutate_dpns_vote_operation(operation_id, |kv| { + transition_scheduled_target_to_queued(kv, self.network, operation_id, key) + }) } /// Persist a reviewed operation and atomically acquire all unresolved locks. @@ -511,18 +544,25 @@ impl AppContext { operation: &mut DpnsVoteOperation, replacing_scheduled_key: Option<&DpnsVoteTargetKey>, ) -> Result<(), TaskError> { - if operation - .targets - .iter() - .any(|outcome| outcome.target.key.network != self.network) - { - return Err(TaskError::DpnsVoteTargetBusy); - } - let (_guard, kv) = self.journal()?; - if let Some(key) = replacing_scheduled_key { - return replace_scheduled_operation(&kv, self.network, operation, key); - } - persist_operation(&kv, self.network, operation) + self.mutate_dpns_vote_operation(operation.id, |kv| { + if operation + .targets + .iter() + .any(|outcome| outcome.target.key.network != self.network) + { + return Err(TaskError::DpnsVoteTargetBusy); + } + if let Some(key) = replacing_scheduled_key { + 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(); + return Ok(()); + } + persist_operation(kv, self.network, operation) + }) } /// Persist updated target statuses while retaining the original operation ID. @@ -530,8 +570,9 @@ impl AppContext { &self, operation: &DpnsVoteOperation, ) -> Result<(), TaskError> { - let _guard = self.journal_guard(); - persist_operation(&self.det_kv()?, self.network, operation) + self.mutate_dpns_vote_operation(operation.id, |kv| { + persist_operation(kv, self.network, operation) + }) } /// Load every operation for this network, including completed history. @@ -547,7 +588,12 @@ impl AppContext { { rebuild_lock_index(&kv, self.network)?; } - load_operations_read_only(&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) = Arc::from(operations.as_slice()); + Ok(operations) } /// Read dismissed schedule rows without changing their recorded vote outcomes. @@ -627,19 +673,20 @@ impl AppContext { status: DpnsVoteTargetStatus, failure: Option, ) -> Result<(), TaskError> { - let (_guard, kv) = self.journal()?; - 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(()) + 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. @@ -655,9 +702,8 @@ impl AppContext { observed_choice: Option, status: DpnsVoteTargetStatus, ) -> Result { - let (_guard, kv) = self.journal()?; - Ok( - with_target(&kv, self.network, operation_id, key, |outcome| { + 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 { @@ -672,8 +718,8 @@ impl AppContext { .then_some(DpnsVoteFailure::ResultUnconfirmed); TargetUpdate::Persist(true) })? - .unwrap_or(false), - ) + .unwrap_or(false)) + }) } /// Atomically claim a queued target before any network or nonce work. @@ -682,9 +728,8 @@ impl AppContext { operation_id: DpnsVoteOperationId, key: &DpnsVoteTargetKey, ) -> Result { - let (_guard, kv) = self.journal()?; - Ok( - with_target(&kv, self.network, operation_id, key, |outcome| { + 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); } @@ -692,8 +737,8 @@ impl AppContext { outcome.failure = None; TargetUpdate::Persist(true) })? - .unwrap_or(false), - ) + .unwrap_or(false)) + }) } /// Record that a target is entering the ambiguous broadcast phase. @@ -702,8 +747,9 @@ impl AppContext { operation_id: DpnsVoteOperationId, key: &DpnsVoteTargetKey, ) -> Result { - let _guard = self.journal_guard(); - mark_target_broadcast(&self.det_kv()?, self.network, operation_id, key) + 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. @@ -716,9 +762,8 @@ impl AppContext { key: &DpnsVoteTargetKey, state: DpnsCurrentVoteState, ) -> Result { - let (_guard, kv) = self.journal()?; - Ok( - with_target(&kv, self.network, operation_id, key, |outcome| { + 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); } @@ -737,8 +782,8 @@ impl AppContext { } TargetUpdate::Persist(outcome.status == DpnsVoteTargetStatus::Queued) })? - .unwrap_or(false), - ) + .unwrap_or(false)) + }) } /// Recover interrupted targets according to their durable broadcast phase. @@ -761,17 +806,18 @@ impl AppContext { operation_id: DpnsVoteOperationId, keys: &BTreeSet, ) -> Result<(), TaskError> { - let (_guard, kv) = self.journal()?; - let Some(mut operation): Option = - load_operation(&kv, &operation_key(self.network, operation_id)) - .map_err(unreadable_operation_err)? - else { - return Ok(()); - }; - if recover_interrupted_target_statuses(&mut operation, |key| keys.contains(key)) { - persist_operation(&kv, self.network, &operation)?; - } - Ok(()) + 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(()); + }; + if recover_interrupted_target_statuses(&mut operation, |key| keys.contains(key)) { + persist_operation(kv, self.network, &operation)?; + } + Ok(()) + }) } pub(crate) fn record_dpns_vote_diagnostic( @@ -1064,6 +1110,39 @@ mod tests { 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 + ); + } + #[test] fn new_vote_batches_have_distinct_operation_ids() { let ids: BTreeSet<_> = (0..64) diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 0c5a7778b..29bd8855a 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -60,7 +60,7 @@ 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, shortcut_for, sort_by_time_left, + VoteCard, move_focus, place_card, shortcut_for, sort_by_time_left, }; use crate::ui::state::dpns_vote_operations::{ DpnsVoteOperationSnapshot, ScheduledDecisionGroup, ScheduledDpnsVoteRow, group_scheduled_rows, @@ -1870,6 +1870,45 @@ impl DPNSScreen { candidate_name_index(&self.active_contests, &self.contested_names.lock_recover()); } + 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(|outcome| (outcome.target.key.clone(), 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, + }; + let Some(outcome) = changed.get(&key) else { + continue; + }; + let state = if outcome.status == DpnsVoteTargetStatus::Confirmed { + node.current = Some(outcome.target.requested_choice); + node.changes = ChangesLeft::Unknown; + 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); + } + } + fn rebuild_scheduled_vote_rows(&mut self) { let rows = self.vote_operations.scheduled_vote_rows(); self.relative_schedule_labels = rows @@ -2630,6 +2669,7 @@ impl ScreenLike for DPNSScreen { /// 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; @@ -3420,6 +3460,106 @@ mod tests { 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 + ); + } + + #[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. diff --git a/src/ui/masternodes/list_screen.rs b/src/ui/masternodes/list_screen.rs index f6f5990cb..022114e77 100644 --- a/src/ui/masternodes/list_screen.rs +++ b/src/ui/masternodes/list_screen.rs @@ -178,8 +178,10 @@ impl MasternodesScreen { /// Show `segment` and remember it as the last-used one on this network. pub fn select_segment(&mut self, segment: MasternodesSegment) { - self.votes_arrival_refresh |= - segment == MasternodesSegment::Votes && self.segment != segment; + 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(); } diff --git a/src/ui/state/dpns_vote_operations.rs b/src/ui/state/dpns_vote_operations.rs index e845a0b46..3290e9469 100644 --- a/src/ui/state/dpns_vote_operations.rs +++ b/src/ui/state/dpns_vote_operations.rs @@ -7,7 +7,7 @@ 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, DpnsVoteTargetKey, + DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, authoritative_dpns_vote_outcomes, }; @@ -61,6 +61,7 @@ pub(crate) fn group_scheduled_rows(rows: Vec) -> Vec, + published: Option>, dismissed_schedules: BTreeSet<(DpnsVoteOperationId, DpnsVoteTargetKey)>, target_statuses: BTreeMap, loaded: bool, @@ -92,6 +93,44 @@ impl DpnsVoteOperationSnapshot { Ok(()) } + /// Adopt backend progress without reading storage on a render frame. + pub(crate) fn sync_progress( + &mut self, + app_context: &AppContext, + ) -> Option> { + 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(|outcome| { + previous + .get(&(outcome.operation_id, &outcome.target.key)) + .is_none_or(|old| **old != **outcome) + }) + .cloned() + .collect(); + self.replace(published.to_vec()); + self.published = Some(published); + Some(changed) + } + pub(crate) fn read_error(&self) -> Option<&Arc> { self.read_error.as_ref() } @@ -160,6 +199,35 @@ mod tests { 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()); + } + #[test] fn voting_ui_dismissed_terminal_row_preserves_siblings() { let mut operation = scheduled_operation( From e4aca671c5830531ef07dd8fc76b58d5862e7357 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 07:56:50 +0000 Subject: [PATCH 123/194] fix(dpns): preserve final requests and retry identity cleanup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep older refreshes from replacing completed requests, retain username cleanup manifests after storage errors, and render progress labels from memory. Fix the removal regression fixture and unused import caught by CI. Co-authored-by: OpenAI Codex πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 15 ++-- src/backend_task/contested_names/mod.rs | 1 - src/backend_task/identity/dpns_usernames.rs | 54 ++++++++++++- src/context/contested_names_db.rs | 78 ++++++++++++++++-- src/context/identity_db.rs | 81 ++++++++++++++++--- src/context/mod.rs | 8 +- src/model/dpns_usernames.rs | 30 ++++++- src/ui/dpns/progress_drawer.rs | 89 +++++++++++---------- src/wallet_backend/kv_test_support.rs | 9 +++ 9 files changed, 295 insertions(+), 70 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5b0fd07b..be069fb32 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -165,9 +165,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). 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 keeps other work - available, and decisions staged or changed during submission survive its - completion. Uncertain votes stay visible and blocked from resubmission; + cast and scheduled results together. A progress drawer shows live results + without reading storage during rendering. Decisions staged or changed during + submission survive its completion. Uncertain votes stay visible and blocked from resubmission; passing the estimated deadline alone does not release them. Completed history is bounded without discarding unresolved votes. Removing a node cancels its unstarted scheduled votes. @@ -188,9 +188,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). 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. Refresh preserves concurrent identity edits and keeps - the previous request snapshot when storage cannot be read. Won usernames - retry failed fetches and identity writes, including after restarting the app. + confirms an outcome. Refresh preserves concurrent identity edits and finished + outcomes when an older refresh completes, and keeps the previous request + snapshot when storage cannot be read. 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. diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 185762f1a..9738d4fd4 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -24,7 +24,6 @@ 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::util::strings::convert_to_homograph_safe_chars; 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; diff --git a/src/backend_task/identity/dpns_usernames.rs b/src/backend_task/identity/dpns_usernames.rs index f9507adb3..bba5c9ba9 100644 --- a/src/backend_task/identity/dpns_usernames.rs +++ b/src/backend_task/identity/dpns_usernames.rs @@ -183,6 +183,7 @@ impl AppContext { &self, sdk: &Sdk, ) -> Result { + let now = now_ms(); let identities = self.load_local_user_identities()?; if identities.is_empty() { return Ok(BackendTaskSuccessResult::MyUsernameRequestsRefreshed); @@ -218,7 +219,7 @@ impl AppContext { &old.normalized_label, snapshot, old.end, - now_ms(), + now, durations, )); } @@ -239,7 +240,6 @@ impl AppContext { })); } }; - let now = now_ms(); let snapshots: BTreeMap<&String, (ContestSnapshot, u64)> = running .iter() .map(|(name, info)| { @@ -371,7 +371,12 @@ impl AppContext { joined_until, ); self.update_username_requests(identity_id, |current| { - merge_requests(current, vec![submitted], now, None) + let previous: Vec<_> = current + .iter() + .filter(|request| request.normalized_label != submitted.normalized_label) + .cloned() + .collect(); + merge_requests(&previous, vec![submitted], now, None) }) } @@ -493,6 +498,43 @@ mod tests { 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_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] { @@ -515,7 +557,11 @@ mod tests { request.phase = phase; ctx.store_username_requests(&id, vec![request.clone()]) .unwrap(); - ctx.delete_local_qualified_identity(&id).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(); diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 02428242b..3a5a9bb83 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -174,6 +174,40 @@ impl AppContext { 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()?; @@ -236,6 +270,9 @@ impl AppContext { 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)? @@ -254,6 +291,8 @@ impl AppContext { .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)? @@ -266,6 +305,8 @@ impl AppContext { .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)? @@ -538,19 +579,22 @@ impl AppContext { 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, ] { - kv.delete(DetScope::Global, &identity_key(prefix, identity_id)) - .map_err(username_err)?; + if let Err(error) = kv.delete(DetScope::Global, &identity_key(prefix, identity_id)) { + first_error.get_or_insert(error); + } } - cache.requests.remove(identity_id); - cache.hydration_pending.remove(identity_id); - cache.main.remove(identity_id); - cache.seen.remove(identity_id); - Ok(()) + first_error.map_or(Ok(()), |error| Err(username_err(error))) } /// Seed a current contest through the persisted shape for backend contract tests. @@ -735,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; @@ -764,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(()); } @@ -821,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(()) } diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index fc35391f1..cc5ff9a9b 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -1500,13 +1500,6 @@ impl AppContext { index_remove_identity(&kv, &id)?; self.invalidate_identity_load(*identifier); purge_identity_scope(&kv, &id)?; - if let Err(error) = self.forget_identity_usernames(&kv, identifier) { - tracing::warn!( - identity_id = %identifier, - ?error, - "Removed identity's username records could not be cleared" - ); - } self.save_identity_profile_name(*identifier, None); let sidecar_cleanup = self.finish_identity_removal_cleanup(&kv, &id, vault_keys)?; // Mirror removal into the upstream unowned scope; wallet-owned identities are unaffected. @@ -1529,6 +1522,7 @@ impl AppContext { vault_keys: impl IntoIterator, ) -> 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(); @@ -1542,7 +1536,13 @@ 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 !sidecar_cleanup.is_incomplete() { clear_vault_cleanup_manifest(kv, id); } @@ -1830,7 +1830,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], @@ -5277,6 +5277,69 @@ 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; + } + #[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/mod.rs b/src/context/mod.rs index 8761dd174..01cc99e54 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -213,13 +213,15 @@ pub struct AppContext { cached_settings: 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 as of the last attention recompute (progress drawer). + /// Journal operations published after executor transitions (progress drawer). dpns_vote_progress: RwLock>, /// A `Review again` request from the progress drawer for the voting panel. dpns_vote_review_request: std::sync::Mutex>, @@ -600,6 +602,7 @@ impl AppContext { animations_disabled: AtomicBool::new(false), cached_settings: RwLock::new(None), 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), @@ -1309,6 +1312,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" diff --git a/src/model/dpns_usernames.rs b/src/model/dpns_usernames.rs index 6859b6c85..f88e69ea6 100644 --- a/src/model/dpns_usernames.rs +++ b/src/model/dpns_usernames.rs @@ -508,7 +508,7 @@ pub fn username_request_from_contest( }) } -/// Combine a fresh read with what was stored before. +/// 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 @@ -528,6 +528,11 @@ pub fn merge_requests( .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(); @@ -1117,6 +1122,29 @@ mod tests { assert!(merge_requests(&previous, vec![], now, Some(&names)).is_empty()); } + #[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)]; diff --git a/src/ui/dpns/progress_drawer.rs b/src/ui/dpns/progress_drawer.rs index d38b9d1ea..28438e528 100644 --- a/src/ui/dpns/progress_drawer.rs +++ b/src/ui/dpns/progress_drawer.rs @@ -13,10 +13,7 @@ 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 dash_sdk::platform::Identifier; use eframe::egui::{self, Align2, Id, RichText, Sense, Ui}; -use std::collections::BTreeMap; -use std::sync::Arc; const OPEN_ID: &str = "dpns_vote_progress_drawer_open"; @@ -26,17 +23,11 @@ const OPEN_ID: &str = "dpns_vote_progress_drawer_open"; pub struct DrawerState { /// Settled operations created before this time are not listed. since_ms: u64, - operations: Option>, - candidates: BTreeMap<(String, Identifier), String>, } impl DrawerState { pub fn new(since_ms: u64) -> Self { - Self { - since_ms, - operations: None, - candidates: BTreeMap::new(), - } + Self { since_ms } } /// Settled operations created before this moment are not listed. @@ -113,30 +104,6 @@ pub fn show(ctx: &egui::Context, app_context: &AppContext, state: &mut DrawerSta return AppAction::None; } let counts = progress_counts(shown.iter().copied()); - if !state - .operations - .as_ref() - .is_some_and(|previous| Arc::ptr_eq(previous, &operations)) - { - state.candidates = app_context - .all_contested_names() - .unwrap_or_default() - .into_iter() - .flat_map(|contest| { - contest - .contestants - .unwrap_or_default() - .into_iter() - .map(move |candidate| { - ( - (contest.normalized_contested_name.clone(), candidate.id), - candidate.name, - ) - }) - }) - .collect(); - state.operations = Some(Arc::clone(&operations)); - } let mut open = is_open(ctx); let mut action = AppAction::None; egui::Area::new(Id::new("dpns_vote_progress_drawer")) @@ -178,18 +145,17 @@ pub fn show(ctx: &egui::Context, app_context: &AppContext, state: &mut DrawerSta 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, - match outcome.target.requested_choice { - ResourceVoteChoice::TowardsIdentity(id) => state - .candidates - .get(&(outcome.target.contested_name.clone(), id)) - .map(String::as_str), - _ => None, - }, + candidate.as_deref(), ), )); let color = match progress_phase(outcome) { @@ -268,6 +234,47 @@ mod tests { 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(); + let _ = ctx.run_ui(egui::RawInput::default(), |ui| { + show(ui.ctx(), &app, &mut state); + }); + 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() { diff --git a/src/wallet_backend/kv_test_support.rs b/src/wallet_backend/kv_test_support.rs index dbf00cf7f..efdacf691 100644 --- a/src/wallet_backend/kv_test_support.rs +++ b/src/wallet_backend/kv_test_support.rs @@ -123,6 +123,7 @@ pub(crate) struct FailingKv { fail_all_reads: AtomicBool, fail_all_deletes: AtomicBool, puts: AtomicUsize, + reads: AtomicUsize, get_countdown: CountdownFailure, put_countdown: CountdownFailure, delete_countdown: CountdownFailure, @@ -141,6 +142,7 @@ impl FailingKv { 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(), @@ -166,6 +168,11 @@ impl FailingKv { 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) @@ -184,6 +191,7 @@ impl FailingKv { impl KvStore for FailingKv { fn get(&self, scope: &ObjectId, key: &str) -> Result>, KvError> { + 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) { @@ -213,6 +221,7 @@ impl KvStore for FailingKv { } fn list_keys(&self, scope: &ObjectId, prefix: Option<&str>) -> Result, KvError> { + self.reads.fetch_add(1, Ordering::Relaxed); self.inner.list_keys(scope, prefix) } } From 718d1272eeeda69a9ff48328c4380ef1c0dd08d4 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 08:12:05 +0000 Subject: [PATCH 124/194] test(dpns): discard unused drawer texture deltas MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The headless drawer regression has no renderer; explicitly discard egui's texture deltas so its destructor does not panic before the read-count check. Co-authored-by: OpenAI Codex πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/ui/dpns/progress_drawer.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/ui/dpns/progress_drawer.rs b/src/ui/dpns/progress_drawer.rs index 28438e528..8e8e371c5 100644 --- a/src/ui/dpns/progress_drawer.rs +++ b/src/ui/dpns/progress_drawer.rs @@ -267,9 +267,10 @@ mod tests { for open in [false, true] { ctx.data_mut(|data| data.insert_temp(Id::new(OPEN_ID), open)); let reads = store.read_count(); - let _ = ctx.run_ui(egui::RawInput::default(), |ui| { + 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"); } } From e6c0840c3a1f79a826bb1ac9dfd201d8fd764bbd Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 09:48:49 +0000 Subject: [PATCH 125/194] fix(dpns): keep the voting attention signal alive between refreshes The 120 s proof cap that guards submissions also fed the attention chip, the Masternodes badge and the Votes cards, so every "needs your vote" signal vanished two minutes after each refresh while the background refresh runs every 30 min on mainnet (3 min elsewhere). Split freshness in two: submission preflight keeps the 120 s cap on its own just-fetched proof; display readers accept proof up to two background refresh intervals old. Confirmed-vote overlays are retained for the same window so a vote confirmed minutes ago does not read as "not voted". Addresses review finding RUST-001. Co-Authored-By: Claude Fable 5.1 --- src/context/dpns_vote_attention.rs | 84 ++++++++---- src/context/dpns_vote_state.rs | 207 +++++++++++++++++++++++++++-- src/model/dpns_voting/operator.rs | 17 +++ 3 files changed, 271 insertions(+), 37 deletions(-) diff --git a/src/context/dpns_vote_attention.rs b/src/context/dpns_vote_attention.rs index 1a7a296fd..b72f79282 100644 --- a/src/context/dpns_vote_attention.rs +++ b/src/context/dpns_vote_attention.rs @@ -318,6 +318,19 @@ impl AppContext { .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()? @@ -332,7 +345,7 @@ impl AppContext { .collect(); let polls: Vec = contests.iter().map(|(_, _, poll)| *poll).collect(); let mut states = BTreeMap::new(); - for voter in &resolved.included { + for voter in voters { let voter_states = self .dpns_current_vote_states(*voter, polls.iter().copied()) .unwrap_or_default(); @@ -340,36 +353,30 @@ impl AppContext { } let network = self.network(); - let attention: Vec = contests + Ok(contests .into_iter() .map(|(name, end_time, poll)| { - let needs_decision = - contest_needs_decision(resolved.included.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)) - })); + 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(); - Ok(AttentionSummary::new( - &attention, - unresolved_target_count(operations), - resolved.included.len(), - )) + .collect()) } } @@ -492,6 +499,37 @@ mod tests { ); } + /// 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"); diff --git a/src/context/dpns_vote_state.rs b/src/context/dpns_vote_state.rs index 090ab377e..7d314b0d4 100644 --- a/src/context/dpns_vote_state.rs +++ b/src/context/dpns_vote_state.rs @@ -2,6 +2,7 @@ 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}; @@ -16,6 +17,8 @@ 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 = 120_000; #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -84,6 +87,7 @@ impl RefreshedDpnsVotes { Some(&self.snapshot), poll_id, now_ms(), + CURRENT_VOTE_MAX_AGE_MS, ))) } @@ -131,22 +135,23 @@ fn save_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 { 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) <= CURRENT_VOTE_MAX_AGE_MS + && checked_at_ms.saturating_sub(*updated_at) <= max_age_ms { return DpnsCurrentVoteState::Available(Some(*choice)); } match snapshot { None => DpnsCurrentVoteState::Checking, - Some(snapshot) - if checked_at_ms.saturating_sub(snapshot.updated_at) > CURRENT_VOTE_MAX_AGE_MS => - { + Some(snapshot) if checked_at_ms.saturating_sub(snapshot.updated_at) > max_age_ms => { DpnsCurrentVoteState::Checking } Some(snapshot) if !snapshot.available => DpnsCurrentVoteState::Unavailable, @@ -190,9 +195,14 @@ impl AppContext { 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( @@ -210,6 +220,27 @@ impl AppContext { .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, @@ -293,7 +324,8 @@ impl AppContext { }) } - /// Read the latest proved state without performing network I/O in the frame loop. + /// 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, @@ -304,10 +336,12 @@ impl AppContext { 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. + /// 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, @@ -315,12 +349,13 @@ impl AppContext { ) -> 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, - snapshot_vote_state(snapshot.as_ref(), vote_poll_id, checked_at_ms), + snapshot_vote_state(snapshot.as_ref(), vote_poll_id, checked_at_ms, max_age_ms), ) }) .collect()) @@ -349,9 +384,12 @@ impl AppContext { let kv = self.det_kv()?; let mut snapshot = load_snapshot(&kv, self.network, &voter_id)?.unwrap_or_default(); let confirmed_at = now_ms(); - snapshot.confirmed.retain(|_, (updated_at, _)| { - confirmed_at.saturating_sub(*updated_at) <= CURRENT_VOTE_MAX_AGE_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)); @@ -833,15 +871,20 @@ mod tests { ..Default::default() }; assert_eq!( - snapshot_vote_state(Some(&snapshot), poll, 11), + 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), + 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), + snapshot_vote_state( + Some(&snapshot), + poll, + 11 + CURRENT_VOTE_MAX_AGE_MS, + CURRENT_VOTE_MAX_AGE_MS + ), DpnsCurrentVoteState::Checking ); } @@ -1002,11 +1045,147 @@ mod tests { }; assert_eq!( - snapshot_vote_state(Some(&snapshot), poll, CURRENT_VOTE_MAX_AGE_MS + 2), + 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"); diff --git a/src/model/dpns_voting/operator.rs b/src/model/dpns_voting/operator.rs index a7069a3c9..d597b830e 100644 --- a/src/model/dpns_voting/operator.rs +++ b/src/model/dpns_voting/operator.rs @@ -356,6 +356,13 @@ pub fn background_refresh_interval(network: Network) -> Duration { } } +/// 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 @@ -725,6 +732,16 @@ mod tests { ); } + #[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 time_left_uses_the_largest_whole_unit() { let minute = 60_000; From ab6271f5ac6ad8427a4776711f0ab9c1d6aa3d07 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 09:55:32 +0000 Subject: [PATCH 126/194] fix(dpns): stop re-raising the unconfirmed-vote banner on every sweep The once-a-minute scheduled-vote sweep forwarded every reconciliation result, changed or not, so a dismissed "could not be confirmed yet" banner came back within a minute for as long as any target stayed Unconfirmed, and each such target cost one proved query per minute. Due scheduled votes also waited behind that sequential reconciliation. - The sweep reports a reconciled operation only when a vote was actually confirmed; "Check again" keeps its explicit feedback. - Due schedules are executed first; unconfirmed votes are re-checked afterwards. Schedules that came due meanwhile are still admitted at the end, without re-admitting targets the sweep already tried. - Targets of decided contests are not queried: their vote references are gone, so the query cannot confirm them. Lock and status stay. - The app paces the re-check: three sweeps after startup or vote activity, then every 10 minutes. The conservative lock on ambiguous broadcasts is unchanged. Addresses review findings RUST-003 and SEC-005. Co-Authored-By: Claude Fable 5.1 --- src/app.rs | 101 ++++- src/backend_task/contested_names/mod.rs | 527 +++++++++++++++++++----- 2 files changed, 524 insertions(+), 104 deletions(-) diff --git a/src/app.rs b/src/app.rs index 278b7f3ac..e1a3bcfba 100644 --- a/src/app.rs +++ b/src/app.rs @@ -322,6 +322,54 @@ 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) @@ -1269,6 +1317,8 @@ 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, /// When the voting attention summary was last recomputed per network, so @@ -1854,6 +1904,7 @@ 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_attention_recomputed_at: BTreeMap::new(), dpns_progress_drawer: crate::ui::dpns::progress_drawer::DrawerState::new(unix_time_ms()), @@ -3140,6 +3191,9 @@ impl App for AppState { ); 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( @@ -3589,11 +3643,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()) { @@ -3621,10 +3675,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 }, @@ -4658,6 +4718,39 @@ mod dpns_result_routing_tests { } } + /// 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 { diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 9738d4fd4..c1ebecf9e 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -57,11 +57,13 @@ pub enum ContestedResourceTask { }, 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, @@ -291,11 +293,17 @@ impl AppContext { } 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) - .await + self.cast_due_scheduled_votes( + sdk, + sender, + preserve_eligibility_since_ms, + reconcile_unconfirmed, + ) + .await } .await; wrap_scheduled_vote_sweep_result(self.network, result) @@ -933,17 +941,29 @@ impl AppContext { operation_id: DpnsVoteOperationId, sdk: &Sdk, ) -> Result { - let Some(operation) = self.dpns_vote_operation(operation_id)? else { - return Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated { - network: self.network, - operation_id, - }); - }; - for outcome in operation - .targets - .iter() - .filter(|outcome| outcome.status == DpnsVoteTargetStatus::Unconfirmed) - { + 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, @@ -973,6 +993,7 @@ impl AppContext { if status != DpnsVoteTargetStatus::Confirmed { continue; } + confirmed_any = true; self.cache_confirmed_dpns_vote( outcome.target.key.voter_id, poll_id, @@ -997,50 +1018,138 @@ impl AppContext { } } } - Ok(BackendTaskSuccessResult::DpnsVoteOperationUpdated { - network: self.network, - operation_id, - }) + 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(()) } - /// Preserve durable due targets and catch up after unrelated reconciliation. - async fn prepare_due_scheduled_votes( + /// 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<(Vec, Vec), TaskError> { + ) -> Result<(), TaskError> + where + E: std::future::Future>, + { let started_at = clock(); let eligibility_cutoff = preserve_eligibility_since_ms.unwrap_or(started_at); - // Persist entry admissions before the await so errors or interruption - // cannot turn an eligible target into a stale schedule on the next sweep. - self.queue_due_scheduled_votes_at(started_at, eligibility_cutoff)?; - let reconciliation = reconcile.await; - // Also admit schedules that became due while reconciliation was waiting. - let admitted = self.queue_due_scheduled_votes_at(clock(), eligibility_cutoff)?; - reconciliation?; - Ok(admitted) + // 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 !scheduled_target_should_execute( - outcome.status, - scheduled_at, - now_ms, - Some(eligibility_cutoff), - ) { + 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 @@ -1065,44 +1174,49 @@ impl AppContext { Ok((due_operations, in_progress)) } - /// Reconcile unresolved votes and execute each admitted scheduled operation. - /// Emits progress before execution; terminal results remain in the journal. + /// 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 { - let (due_operations, in_progress) = self - .prepare_due_scheduled_votes(now_ms, preserve_eligibility_since_ms, async { - for operation in self - .dpns_vote_operations()? - .into_iter() - .filter(|operation| { - operation - .targets - .iter() - .any(|outcome| outcome.status == DpnsVoteTargetStatus::Unconfirmed) - }) - { - let result = self - .reconcile_dpns_vote_operation(operation.id, sdk) - .await?; - let _ = sender.send(TaskResult::unattributed_success(result)).await; + 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, + }) + } - Ok(()) - }) - .await?; + 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(BackendTaskSuccessResult::ScheduledVoteSweepCompleted { - network: self.network, - preserve_eligibility_since_ms, - }); + return Ok(()); } - let voters = self.load_local_voting_identities()?; - // Tell the Scheduled Votes screen which votes are now in flight. + // Tell the Scheduled view which votes are now in flight. let _ = sender .send(TaskResult::unattributed_success( BackendTaskSuccessResult::ScheduledVotesInProgress(in_progress), @@ -1137,14 +1251,7 @@ impl AppContext { first_error.get_or_insert(error); } } - if let Some(error) = first_error { - Err(error) - } else { - Ok(BackendTaskSuccessResult::ScheduledVoteSweepCompleted { - network: self.network, - preserve_eligibility_since_ms, - }) - } + first_error.map_or(Ok(()), Err) } } @@ -1666,25 +1773,35 @@ mod tests { } #[tokio::test] - async fn sweep_preserves_due_votes_across_slow_reconciliation() { + async fn sweep_executes_due_votes_before_reconciling_unconfirmed_ones() { let (_temp, context) = vote_context(); let started = 1_000_000; - let clock = std::cell::Cell::new(started); let mut operation = scheduled_operation_for(&context, "alice", started); context .insert_dpns_vote_operation(&mut operation, None) .unwrap(); - let (due, _) = context - .prepare_due_scheduled_votes(|| clock.get(), None, async { - clock.set(started + SCHEDULED_VOTE_MAX_LATENESS_MS + 1); - Ok(()) - }) + 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!( - due.len(), - 1, - "reconciliation must not expire a schedule eligible at sweep entry" + *events.borrow(), + vec![("execute", 1, 1), ("reconcile", 0, 0)], + "a due vote must not wait behind reconciliation of unrelated votes" ); assert_eq!( context @@ -1693,7 +1810,8 @@ mod tests { .unwrap() .targets[0] .status, - DpnsVoteTargetStatus::Queued + DpnsVoteTargetStatus::Queued, + "the admission is durable before execution starts" ); } @@ -1709,10 +1827,15 @@ mod tests { .insert_dpns_vote_operation(&mut newly_due, None) .unwrap(); let result = context - .prepare_due_scheduled_votes(|| clock.get(), None, async { - clock.set(started + SCHEDULED_VOTE_MAX_LATENESS_MS * 2); - Err(TaskError::DpnsVoteTargetBusy) - }) + .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] { @@ -1724,6 +1847,192 @@ mod tests { } } + /// 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 + ); + } + + 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() { @@ -1870,27 +2179,44 @@ mod tests { let started = 1_000_000; let finished = started + SCHEDULED_VOTE_MAX_LATENESS_MS * 2; let clock = std::cell::Cell::new(started); - for (name, timestamp) in [ - ("newlydue", started + 10), - ("stale", started - SCHEDULED_VOTE_MAX_LATENESS_MS - 1), - ("future", finished + 1), + 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 scheduled_operation_for(&context, name, timestamp), - None, - ) + .insert_dpns_vote_operation(&mut operation, None) .unwrap(); + statuses.push((name, operation.id, expected)); } - let (due, _) = context - .prepare_due_scheduled_votes(|| clock.get(), None, async { - clock.set(finished); - Ok(()) - }) + 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(); - assert_eq!(due.len(), 1); - assert_eq!(due[0].targets[0].target.contested_name, "newlydue"); + for (name, id, expected) in statuses { + assert_eq!( + context.dpns_vote_operation(id).unwrap().unwrap().targets[0].status, + expected, + "{name}" + ); + } } #[test] @@ -2315,6 +2641,7 @@ mod tests { .run_contested_resource_task( ContestedResourceTask::CastDueScheduledVotes { preserve_eligibility_since_ms: None, + reconcile_unconfirmed: true, }, &context.sdk(), sender, From aee07f34871f78b1d4f7fac5bed351e5c2e81eae Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 09:57:05 +0000 Subject: [PATCH 127/194] fix(dpns): name the real cause when no vote of a batch was submitted A batch whose targets all failed before submission always said "Check your connection and try again", also when voting had ended or the node's voting key was not loaded, contradicting the per-row drawer status and prescribing a retry that cannot work. The banner now branches on the recorded failure cause and keeps the connection sentence for connection problems only. The mixed-result banner is composed from one complete "Label: n." unit per non-empty outcome plus only the guidance that applies, instead of a comma list that printed every zero bucket. Addresses review findings PROJ-003 and PROJ-007. Co-Authored-By: Claude Fable 5.1 --- src/app.rs | 91 +++++++++++++++++++- src/backend_task/contested_names/mod.rs | 2 +- src/ui/dpns/copy.rs | 107 +++++++++++++++++++----- 3 files changed, 177 insertions(+), 23 deletions(-) diff --git a/src/app.rs b/src/app.rs index e1a3bcfba..a0b61d766 100644 --- a/src/app.rs +++ b/src/app.rs @@ -4232,10 +4232,77 @@ mod migration_banner_tests { assert!(keep_visible); assert_eq!( message, - "Vote results: 1 confirmed, 1 scheduled, 3 needing review, 1 cancelled, 0 in progress, and 1 still being checked. Review failed votes before retrying. Wait for votes in progress or still being checked; do not submit those votes again." + "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 @@ -4270,7 +4337,7 @@ mod migration_banner_tests { assert!(!keep_visible); assert_eq!( message, - "Vote results: 2 confirmed, 0 scheduled, 1 needing review, 0 cancelled, 0 in progress, and 0 still being checked. Review failed votes before retrying. Wait for votes in progress or still being checked; do not submit those votes again." + "Votes confirmed: 2. Votes needing review: 1. Review failed votes before retrying." ); } @@ -4285,8 +4352,26 @@ mod migration_banner_tests { assert_eq!( message, - "Vote results: 0 confirmed, 0 scheduled, 2 needing review, 0 cancelled, 0 in progress, and 0 still being checked. Review failed votes before retrying. Wait for votes in progress or still being checked; do not submit those votes again." + "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. diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index c1ebecf9e..742e38a50 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -1430,7 +1430,7 @@ mod tests { ); let (message, _, _) = crate::ui::dpns::copy::dpns_vote_feedback(&saved); assert!( - message.contains("1 confirmed") && message.contains("1 needing review"), + message.contains("Votes confirmed: 1.") && message.contains("Votes needing review: 1."), "{message}" ); } diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index e2dbb073c..1ae4765a2 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -552,6 +552,87 @@ fn dpns_unconfirmed_guidance(unconfirmed: usize) -> String { } } +/// 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 { @@ -649,12 +730,8 @@ pub(crate) fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, Mess return (message.to_owned(), MessageType::Error, false); } if counts.failed_before_submission == target_count { - let message = 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." - }; - return (message.to_owned(), MessageType::Error, false); + 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 { @@ -680,19 +757,11 @@ pub(crate) fn dpns_vote_feedback(operation: &DpnsVoteOperation) -> (String, Mess ); } - let reviewable = counts.rejected + counts.failed_before_submission + counts.not_applied; - let DpnsVoteFeedbackCounts { - confirmed, - scheduled, - cancelled, - in_progress, - unconfirmed, - .. - } = counts; - let message = format!( - "Vote results: {confirmed} confirmed, {scheduled} scheduled, {reviewable} needing review, {cancelled} cancelled, {in_progress} in progress, and {unconfirmed} still being checked. Review failed votes before retrying. Wait for votes in progress or still being checked; do not submit those votes again." - ); - (message, MessageType::Warning, unconfirmed > 0) + ( + dpns_mixed_vote_feedback(&counts), + MessageType::Warning, + counts.unconfirmed > 0, + ) } #[cfg(test)] From f281b930dd490f7b106aaeeef44e4f8bc9529a10 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:00:46 +0000 Subject: [PATCH 128/194] fix(dpns): make the old-schedule startup notice truthful and self-expiring The notice told users to "review" schedules from an earlier version under Masternodes > Votes, but those schedules are neither imported nor listed, and it returned on every launch with nothing the user could do for a contest that had already ended. - The copy now says the votes were not carried over, are not listed, and have to be scheduled again; the network uses the chooser label. - The notice stops one contest duration after it first appeared (recorded per network): by then every contest an old schedule could refer to has closed. Scheduling the same node and name again still retires it early. Also correct migration copy that predates the journal-only design: the app-data step no longer claims to restore scheduled votes, and the unreadable-vote messages point to Masternodes > Votes instead of the removed Scheduled Votes screen. Addresses review finding RUST-014 and the src/app.rs half of PROJ-002. Co-Authored-By: Claude Fable 5.1 --- src/app.rs | 62 ++++++++++++++--- src/context/legacy_scheduled_votes.rs | 99 +++++++++++++++++++++++++++ 2 files changed, 152 insertions(+), 9 deletions(-) diff --git a/src/app.rs b/src/app.rs index a0b61d766..b6aae28fe 100644 --- a/src/app.rs +++ b/src/app.rs @@ -225,12 +225,25 @@ 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.has_legacy_scheduled_votes() { + match app_context.legacy_scheduled_votes_notice_due() { Ok(true) => { - let network = app_context.network; - MessageBanner::set_global(ctx, format!("Some scheduled votes from an earlier version on {network} will not run automatically. Open Masternodes > Votes to review them and cast or schedule them again."), MessageType::Warning).disable_auto_dismiss(); + MessageBanner::set_global( + ctx, + legacy_scheduled_votes_notice(app_context.network), + MessageType::Warning, + ) + .disable_auto_dismiss(); } Ok(false) => {} Err(error) => { @@ -863,7 +876,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.", @@ -882,7 +895,7 @@ pub fn migration_running_text(step: MigrationStep) -> &'static str { 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." + over ({count} in total). Schedule them again under Masternodes > Votes." ) } @@ -915,7 +928,7 @@ pub fn migration_unreadable_identities_and_votes_text(identities: u32, votes: u3 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." + again under Masternodes > Votes." ) } @@ -959,7 +972,7 @@ pub fn migration_unreadable_data_text(identities: u32, votes: u32, top_ups: u32) (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. \ + and were not carried over. Schedule the votes again under Masternodes > Votes. \ Check each identity's balance history before adding more funds." ), (true, true, true) => format!( @@ -967,8 +980,8 @@ pub fn migration_unreadable_data_text(identities: u32, votes: u32, top_ups: u32) 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 \ + evonode identity, choose + Load on the Masternodes tab. Schedule the votes again \ + under Masternodes > Votes, and check each identity's balance history before adding \ more funds." ), (false, false, false) => { @@ -4453,6 +4466,37 @@ mod migration_banner_tests { 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, and the Scheduled Votes screen is + /// gone: no migration copy may claim otherwise. + #[test] + fn migration_copy_does_not_mention_importing_votes_or_a_removed_screen() { + for step in MigrationStep::ALL { + let text = migration_running_text(step); + assert!(!text.contains("scheduled votes"), "{text}"); + } + for text in [ + migration_unreadable_votes_text(2), + migration_unreadable_identities_and_votes_text(1, 2), + migration_unreadable_data_text(0, 2, 3), + migration_unreadable_data_text(1, 2, 3), + ] { + assert!(!text.contains("Scheduled Votes screen"), "{text}"); + assert!(text.contains("Masternodes > Votes"), "{text}"); + } + } + #[test] fn failed_legacy_settings_import_raises_a_sticky_warning() { use crate::backend_task::migration::legacy_settings::SettingsImportError; diff --git a/src/context/legacy_scheduled_votes.rs b/src/context/legacy_scheduled_votes.rs index 5f986d9ca..bd28fea26 100644 --- a/src/context/legacy_scheduled_votes.rs +++ b/src/context/legacy_scheduled_votes.rs @@ -2,9 +2,58 @@ 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( @@ -87,6 +136,56 @@ mod tests { ); } + /// 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(); From 1bc4dda21fe01957f251a0720ec3d3298c463b49 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:02:33 +0000 Subject: [PATCH 129/194] docs(dpns): align the voting spec with the shipped behaviour The spec is marked "Implemented" but promised a `Not applied` outcome, a transition-hash retry and a reconcile-to-retry path that the code cannot produce: the journal stores no transition hash and a missing or different vote stays Unconfirmed. Mark VOTE-FR-032/042/045, VOTE-TC-054 and the UX drawer row as not implemented, blocked on dashpay/platform#4137, and note on the `NotApplied` status that it is reserved for the journal encoding. Update quoted copy and layout statements to what ships (changes-left wording, voting-ended reason, batch banner, filter field, needs-attention actions, empty state, node detail grid, progress drawer), and document the display freshness of proved vote state, the reconciliation cadence and the self-expiring old-schedule notice. Addresses review findings DOC-003 and DOC-004. Co-Authored-By: Claude Fable 5.1 --- .../01-requirements.md | 55 +++++++++++++------ .../02-ux-spec.md | 29 ++++++---- .../03-test-case-spec.md | 8 +-- src/model/dpns_voting/mod.rs | 4 +- 4 files changed, 64 insertions(+), 32 deletions(-) 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 index 4511b334f..8179e32df 100644 --- 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 @@ -122,7 +122,10 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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. + every 3 min on testnet/devnet, and immediately on Votes arrival. 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. - **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). @@ -157,7 +160,8 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. - **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 node voted outside Dash Evo Tool.` + 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 @@ -210,9 +214,11 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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 `Not applied` after definitive - post-broadcast reconciliation and `Cancelled` when the user cancels a - scheduled target before it is submitted (see VOTE-FR-055). + `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 @@ -232,10 +238,11 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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 or Scheduled. + schedule. It summarizes and links to the drawer (`Show progress`) or Scheduled + (`Open Scheduled`). - **VOTE-FR-087** **[New]** β€” Targets not yet submitted when their contest's - voting ends become `Failed before submission` with the reason `Not cast. Voting - ended.` + voting ends become `Failed before submission` with the reason `Not submitted. + Voting ended.` ### Confirmation and recovery @@ -244,14 +251,23 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. - **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 and, when available, retried by transition hash through the - Platform SDK. + 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** β€” A retry becomes available only after authoritative - reconciliation proves the requested change was not applied. +- **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 @@ -268,8 +284,10 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. - **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 cast or - schedule them again; it neither imports nor executes them automatically. + 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 @@ -291,8 +309,13 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. - **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 `…; {k} are - still being checked.`). + 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 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 index b0ae8e10b..e37f1b1ac 100644 --- 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 @@ -48,8 +48,8 @@ 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 β–Ύ` Β· `Find a name` (homoglyph tooltip: `Search ignores look-alike -characters the way usernames do, so o matches 0 and l matches 1.`). +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: @@ -75,7 +75,9 @@ Tray (outside scroll): `{d} decisions ready Β· {t} transactions, one per node an 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]. +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) @@ -113,10 +115,15 @@ Rules (unchanged from #901, now in the confirm step): As specified in VOTE-FR-083. - Row copy by status: `Confirmed` Β· `Submitting` Β· `Confirming` Β· `Still being checked. Do not submit it again.` [Check again] Β· - `Not applied` [Review again] Β· `Not submitted` + saved reason. + `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. -- Collapsed state: a chip `Casting 44 votes Β· 33 done` above the network chip. +- 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) @@ -143,7 +150,7 @@ or Testnet network. Devnet and Regtest have no public explorer link. | State | Copy | Action | |---|---|---| -| No nodes loaded | `Load a masternode with its voting key to vote on name contests.` (contests shown read-only; choice tooltip `Load a masternode with a voting key to vote.`) | Load a masternode | +| 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 | @@ -151,9 +158,9 @@ or Testnet network. Devnet and Regtest have no public explorer link. ## 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]. The `This node's votes` -table shows Name Β· Vote Β· Changes left Β· Voting ends, with the footer `Changes -left are counted on this device.` +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) @@ -167,5 +174,5 @@ below the Power role or when no node has a voting key. - 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 becomes a bottom sheet; - the tray stays outside the scroll area. +- 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 index 7cbf3092c..80bae38f0 100644 --- 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 @@ -60,7 +60,7 @@ K = kittest, B = backend test with fake SDK seam. | 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 | Unconfirmed target; definitive reconciliation proves absence | Check again | Status allows reviewed resubmission | FR-045 | +| 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 | @@ -99,15 +99,15 @@ K = kittest, B = backend test with fake SDK seam. | 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 node voted outside Dash Evo Tool.` | 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 opens drawer / Scheduled | FR-084 | K | -| VOTE-TC-103 | Contest ends mid-batch | Queued targets past end | Execute | `Failed before submission` + `Not cast. Voting ended.` | FR-087 | B | +| 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 | diff --git a/src/model/dpns_voting/mod.rs b/src/model/dpns_voting/mod.rs index 32ff84f81..7e5efa221 100644 --- a/src/model/dpns_voting/mod.rs +++ b/src/model/dpns_voting/mod.rs @@ -246,7 +246,9 @@ pub enum DpnsVoteTargetStatus { Unconfirmed, Rejected, FailedBeforeSubmission, - /// Reconciliation proved that a submitted vote was not applied. + /// 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, From e9d773152fe4053540edd1b401077da38b710ee4 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:05:52 +0000 Subject: [PATCH 130/194] fix(dpns): keep a card's changes-left known when its vote confirms live Live progress forced "Changes left unknown. This device has no record of this node's earlier votes." onto every target that had just been confirmed, although the journal had counted exactly that vote. The card now derives the new remainder from its cached value and the transition it observed, with the same result a recount gives, and still reads no storage on a render frame. Addresses review finding RUST-004. Co-Authored-By: Claude Fable 5.1 --- src/model/dpns_voting/operator.rs | 32 +++++++ src/ui/dpns/dpns_contested_names_screen.rs | 98 ++++++++++++++++++++-- src/ui/state/dpns_vote_operations.rs | 14 ++-- 3 files changed, 129 insertions(+), 15 deletions(-) diff --git a/src/model/dpns_voting/operator.rs b/src/model/dpns_voting/operator.rs index d597b830e..29c4887bb 100644 --- a/src/model/dpns_voting/operator.rs +++ b/src/model/dpns_voting/operator.rs @@ -210,6 +210,19 @@ impl ChangesLeft { 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. @@ -732,6 +745,25 @@ mod tests { ); } + /// 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 displayed_vote_state_outlives_one_missed_background_refresh() { for network in [Network::Mainnet, Network::Testnet, Network::Devnet] { diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 29bd8855a..010d83e53 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -36,7 +36,8 @@ use crate::model::dpns_voting::operator::{ use crate::model::dpns_voting::progress::needs_attention; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperationId, - DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, dpns_schedule_is_overdue, + DpnsVoteOutcome, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, + dpns_schedule_is_overdue, }; use crate::model::qualified_identity::IdentityType; use crate::model::qualified_identity::QualifiedIdentity; @@ -151,6 +152,20 @@ fn target_outcome_label( } } +/// 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, @@ -1324,7 +1339,7 @@ impl DPNSScreen { } } - fn review_failed_target(&mut self, outcome: &crate::model::dpns_voting::DpnsVoteOutcome) { + fn review_failed_target(&mut self, outcome: &DpnsVoteOutcome) { self.selected_votes.clear(); self.set_selected_vote_from_outcome(outcome); self.retry_voter = Some(outcome.target.key.voter_id); @@ -1369,10 +1384,7 @@ impl DPNSScreen { ui.add_space(6.0); } - fn set_selected_vote_from_outcome( - &mut self, - outcome: &crate::model::dpns_voting::DpnsVoteOutcome, - ) { + fn set_selected_vote_from_outcome(&mut self, outcome: &DpnsVoteOutcome) { let name = outcome.target.contested_name.clone(); if let Some(vote) = self .selected_votes @@ -1877,7 +1889,7 @@ impl DPNSScreen { self.rebuild_scheduled_vote_rows(); let changed: BTreeMap<_, _> = changed .into_iter() - .map(|outcome| (outcome.target.key.clone(), outcome)) + .map(|(previous, outcome)| (outcome.target.key.clone(), (previous, outcome))) .collect(); for card in &mut self.cards { let Some(poll) = card.vote_poll_id else { @@ -1889,12 +1901,14 @@ impl DPNSScreen { voter_id: node.node, vote_poll_id: poll, }; - let Some(outcome) = changed.get(&key) else { + let Some((previous, outcome)) = changed.get(&key) else { continue; }; 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); - node.changes = ChangesLeft::Unknown; DpnsCurrentVoteState::Available(node.current) } else { self.vote_state.state(node.node, poll) @@ -3526,6 +3540,72 @@ mod tests { ); } + /// 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; diff --git a/src/ui/state/dpns_vote_operations.rs b/src/ui/state/dpns_vote_operations.rs index 3290e9469..b61325aa6 100644 --- a/src/ui/state/dpns_vote_operations.rs +++ b/src/ui/state/dpns_vote_operations.rs @@ -94,10 +94,13 @@ impl DpnsVoteOperationSnapshot { } /// 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> { + ) -> Option, DpnsVoteOutcome)>> { let published = app_context.dpns_vote_progress(); if self .published @@ -119,12 +122,11 @@ impl DpnsVoteOperationSnapshot { let changed = published .iter() .flat_map(|operation| operation.targets.iter()) - .filter(|outcome| { - previous - .get(&(outcome.operation_id, &outcome.target.key)) - .is_none_or(|old| **old != **outcome) + .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())) }) - .cloned() .collect(); self.replace(published.to_vec()); self.published = Some(published); From deeb4a788854c61bf99512e96fbe767f7748941d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:06:44 +0000 Subject: [PATCH 131/194] fix(dpns): surface a failed vote that was scheduled in an earlier session "Needs attention" and the progress drawer hid settled failures unless their operation was created in the current session. Scheduled votes are created long before they run, so a rejection or a voting-ended failure of a vote scheduled days ago never reached the operator. Recency now follows when the target was sent: its scheduled time for a scheduled vote, the operation's creation time otherwise. Addresses review finding RUST-005. Co-Authored-By: Claude Fable 5.1 --- src/model/dpns_voting/progress.rs | 76 +++++++++++++++++++++++++++---- 1 file changed, 68 insertions(+), 8 deletions(-) diff --git a/src/model/dpns_voting/progress.rs b/src/model/dpns_voting/progress.rs index a10d11a56..a919fb3e7 100644 --- a/src/model/dpns_voting/progress.rs +++ b/src/model/dpns_voting/progress.rs @@ -78,8 +78,18 @@ pub fn progress_counts<'a>( counts } -/// Operations the drawer lists: anything still in flight, plus settled -/// operations created since `since_ms` that the operator has not dismissed. +/// 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. +fn sent_at(operation: &DpnsVoteOperation, outcome: &DpnsVoteOutcome) -> u64 { + match outcome.target.timing { + VoteTiming::Scheduled(at) => at.max(operation.created_at), + VoteTiming::Now => operation.created_at, + } +} + +/// 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: &'a [DpnsVoteOperation], since_ms: u64, @@ -93,7 +103,10 @@ pub fn drawer_operations<'a>( return false; } counts.in_flight() - || (operation.created_at >= since_ms && !dismissed.contains(&operation.id)) + || (!dismissed.contains(&operation.id) + && operation.targets.iter().any(|outcome| { + progress_phase(outcome).is_some() && sent_at(operation, outcome) >= since_ms + })) }) .collect() } @@ -114,10 +127,10 @@ impl NeedsAttention { /// Targets that need the operator: unconfirmed, failed, or schedules missed. /// -/// A failure counts only while it is the latest outcome for its target, its -/// operation was created 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. +/// 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, @@ -134,7 +147,7 @@ pub fn needs_attention( { attention.missed_schedules += 1; } - _ if operation.created_at >= since_ms + _ if sent_at(operation, outcome) >= since_ms && !dismissed.contains(&operation.id) && progress_phase(outcome) == Some(ProgressPhase::Failed) => { @@ -287,6 +300,53 @@ mod tests { 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()); + } + #[test] fn attention_uses_authority_for_equal_timestamps_and_lock_holders() { let mut failed = operation(100, &[(S::Rejected, NOW)]); From b6c600ac8a366bce1eab245d92c262019ede66b1 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:07:09 +0000 Subject: [PATCH 132/194] test(dpns): make the lock-retention and rebroadcast tests exercise the code Two tests could not fail: one compared hard-coded status constants with `Scheduled` without calling the executor's eligibility rule, the other looped over a clock value the code under test never reads. They now call `scheduled_target_should_execute` for every non-queued status, and drive reconciliation and restart recovery against a contest whose deadline has elapsed, asserting the stored status and lock stay Unconfirmed. Addresses review finding RUST-002. Co-Authored-By: Claude Fable 5.1 --- src/backend_task/contested_names/mod.rs | 75 ++++++++++++++++++++----- 1 file changed, 60 insertions(+), 15 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 742e38a50..ef2b2734b 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -2423,19 +2423,44 @@ mod tests { ); } - #[test] - fn review_safety_elapsed_deadline_keeps_ambiguous_votes_locked() { + /// 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(); - for now in [1_000, 2_000, u64::MAX] { - for observed in [None, Some(ResourceVoteChoice::Abstain)] { - let status = classify_reconciled_vote(observed, ResourceVoteChoice::Lock) - .unwrap_or(DpnsVoteTargetStatus::Unconfirmed); - assert_eq!(status, DpnsVoteTargetStatus::Unconfirmed); - assert!(status.holds_lock()); - } - assert!(voting_ended_outcome(contests.first(), now).is_some()); + 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:?}" + ); } } @@ -2596,13 +2621,33 @@ mod tests { #[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 [ - DpnsVoteTargetStatus::Unconfirmed, - DpnsVoteTargetStatus::Rejected, - DpnsVoteTargetStatus::FailedBeforeSubmission, - DpnsVoteTargetStatus::Confirmed, + S::Submitting, + S::Confirming, + S::Confirmed, + S::Unconfirmed, + S::Rejected, + S::FailedBeforeSubmission, + S::NotApplied, + S::Cancelled, ] { - assert_ne!(status, DpnsVoteTargetStatus::Scheduled); + 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" + ); + } } } From fe4d72e943bd31396428035b3427a8d167f2d0de Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:08:57 +0000 Subject: [PATCH 133/194] fix(dpns): retry an incomplete background refresh soon, not an interval later A background contest refresh that failed was not retried until a full interval had passed since its dispatch (30 min on mainnet), and a pass in which a node's proof query failed was still stamped as a completed refresh, which also suppressed the Votes-arrival refresh. - The refresh is stamped as completed only when every covered node's vote state was proved. - When a background refresh ends without that stamp, the app schedules a retry after a sixth of the interval (5 min mainnet, 30 s elsewhere). Addresses review finding RUST-008. Co-Authored-By: Claude Fable 5.1 --- .../01-requirements.md | 4 +- src/app.rs | 60 +++++++++++++++---- src/backend_task/contested_names/mod.rs | 38 ++++++++++++ .../query_dpns_contested_resources.rs | 16 +++-- .../contested_names/refresh_vote_states.rs | 5 ++ src/model/dpns_voting/operator.rs | 31 ++++++++++ 6 files changed, 139 insertions(+), 15 deletions(-) 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 index 8179e32df..7d64f2e8f 100644 --- 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 @@ -122,7 +122,9 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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. Proved vote + every 3 min on testnet/devnet, and immediately on Votes arrival. A refresh + that fails, or leaves 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. diff --git a/src/app.rs b/src/app.rs index b6aae28fe..d1658c021 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1334,6 +1334,8 @@ pub struct AppState { 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, @@ -1919,6 +1921,7 @@ impl AppState { 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(), @@ -2743,6 +2746,32 @@ impl AppState { } } + /// Called when a background contest refresh ends: if it failed or left 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( @@ -3196,6 +3225,9 @@ 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, @@ -3522,9 +3554,10 @@ impl App for AppState { context: BackendTaskContext::DpnsBackgroundRefresh { network }, error, } => { - // A background refresh retries on its own cadence; the - // voting panel's Refresh is where failures are reported. + // 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, @@ -3729,14 +3762,21 @@ impl App for AppState { && active_context.dpns_vote_attention().voting_nodes > 0 { let now_ms = unix_time_ms(); - if 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), - ) { + 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( diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index ef2b2734b..1a7a5cea1 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -1888,6 +1888,44 @@ mod tests { ); } + /// 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)); + } + fn unconfirmed_operation_for(context: &AppContext, name: &str) -> DpnsVoteOperation { let mut target = scheduled_operation_for(context, name, 42).targets[0] .target 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 a2b26ed29..d6182ef4c 100644 --- a/src/backend_task/contested_names/query_dpns_contested_resources.rs +++ b/src/backend_task/contested_names/query_dpns_contested_resources.rs @@ -237,13 +237,21 @@ impl AppContext { // 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". - if let Err(error) = self.refresh_dpns_vote_states(sdk).await { - tracing::warn!(?error, "Could not refresh DPNS current votes with contests"); - } + 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.mark_dpns_contests_refreshed(); + // A pass that left a node unchecked is not a completed refresh: the + // timer and the Votes-arrival refresh must be free to try again soon. + if vote_states_refreshed { + self.mark_dpns_contests_refreshed(); + } self.refresh_pending_dpns_usernames()?; sender diff --git a/src/backend_task/contested_names/refresh_vote_states.rs b/src/backend_task/contested_names/refresh_vote_states.rs index 954a4177e..7892a0416 100644 --- a/src/backend_task/contested_names/refresh_vote_states.rs +++ b/src/backend_task/contested_names/refresh_vote_states.rs @@ -15,6 +15,11 @@ 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( diff --git a/src/model/dpns_voting/operator.rs b/src/model/dpns_voting/operator.rs index 29c4887bb..21c06d9dd 100644 --- a/src/model/dpns_voting/operator.rs +++ b/src/model/dpns_voting/operator.rs @@ -369,6 +369,18 @@ pub fn background_refresh_interval(network: Network) -> Duration { } } +/// How soon a background refresh that failed, or left 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) +} + /// 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. @@ -774,6 +786,25 @@ mod tests { } } + #[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; From 71fa342f425a26173d6dd7d4fb54513824a2b32f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:10:13 +0000 Subject: [PATCH 134/194] refactor(dpns): drop the confirm step's unreachable in-flight state MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A dispatched submission closes the confirm step in the same frame and every path that reopens it resets the status, so the spinner, the "Submitting votes…" label, both disabled tooltips and the stored `VoteSubmissionError::TaskFailed` text could never be shown. The status now only says whether the last submit click produced nothing to send; being in flight stays `pending_vote_operation`. Addresses review finding RUST-011. Co-Authored-By: Claude Fable 5.1 --- src/ui/dpns/dpns_contested_names_screen.rs | 168 ++++++--------------- 1 file changed, 49 insertions(+), 119 deletions(-) diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 010d83e53..4d9fa9357 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -250,12 +250,6 @@ impl ReviewPlan { self.aggregate.node_count() } - fn has_immediate(&self) -> bool { - self.targets() - .iter() - .any(|target| matches!(target.timing, VoteTiming::Now)) - } - fn has_scheduled(&self) -> bool { self.targets() .iter() @@ -352,17 +346,6 @@ pub enum VoteSubmissionError { NoTargets, #[error("Every selected node already has the requested vote. Nothing will be submitted.")] AllNoOps, - /// A dispatched submission came back as a failure. - /// - /// Fieldless on purpose: `display_task_error` only borrows the `TaskError`, - /// and the alternative β€” stashing its rendered sentence β€” is the very thing - /// a typed error exists to avoid. The specific failure still reaches the - /// user in full, through the global banner AppState raises for every failed - /// task with the technical chain in its details. - #[error( - "The votes could not be submitted. Check your connection and voting key, then review and submit them again." - )] - TaskFailed, } fn platform_explorer_contest_url(network: Network, normalized_label: &str) -> Option { @@ -403,10 +386,13 @@ pub struct SelectedVote { pub end_time: Option, } +/// 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, + /// The click produced nothing to send; the window stays open on the reason. Failed(VoteSubmissionError), } @@ -2087,21 +2073,9 @@ impl DPNSScreen { .default_open(false) .show(ui, |ui| self.render_adjust_nodes(ui, plan.as_ref().ok())); - let operation_in_progress = matches!( - self.bulk_vote_handling_status, - VoteHandlingStatus::CastingVotes | VoteHandlingStatus::SchedulingVotes - ); - if operation_in_progress { - ui.horizontal(|ui| { - ui.spinner(); - ui.label("Submitting votes…"); - }); - } let transactions = plan.as_ref().map_or(0, ReviewPlan::effective_count); let all_now = plan.as_ref().is_ok_and(|plan| !plan.has_scheduled()); - let submit_disabled_reason = if operation_in_progress { - "The selected votes are already being submitted." - } else if plan.is_err() { + 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." @@ -2121,26 +2095,18 @@ impl DPNSScreen { ) }) }); - let can_submit = !operation_in_progress && transactions > 0 && !repeated_enter; + let can_submit = transactions > 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, - if operation_in_progress { - "Submitting votes…".to_owned() - } else { - confirm_button_label(transactions, all_now) - }, + confirm_button_label(transactions, all_now), ) .disabled_tooltip(submit_disabled_reason) .clicked(); let cancel_clicked = ui - .add_enabled( - !operation_in_progress, - ComponentStyles::secondary_button("Cancel", dark_mode), - ) - .disabled_tooltip("Submitted votes cannot be cancelled.") + .add(ComponentStyles::secondary_button("Cancel", dark_mode)) .clicked(); (submit_clicked, cancel_clicked) }) @@ -2151,19 +2117,14 @@ impl DPNSScreen { if can_submit && input.consume_key(egui::Modifiers::NONE, egui::Key::Enter) { submit_clicked = true; } - if !operation_in_progress - && input.consume_key(egui::Modifiers::NONE, egui::Key::Escape) - { + if input.consume_key(egui::Modifiers::NONE, egui::Key::Escape) { cancel_clicked = true; } }); } if submit_clicked { action = self.bulk_apply_votes(); - if matches!( - self.bulk_vote_handling_status, - VoteHandlingStatus::CastingVotes | VoteHandlingStatus::SchedulingVotes - ) { + 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.show_bulk_schedule_popup = false; @@ -2420,7 +2381,6 @@ impl DPNSScreen { return AppAction::None; } }; - let has_immediate = plan.has_immediate(); if plan.aggregate.targets.is_empty() { let all_no_ops = !plan.aggregate.skipped.is_empty() && plan @@ -2449,11 +2409,7 @@ impl DPNSScreen { .collect(), }); self.submission_error_banner.take_and_clear(); - self.bulk_vote_handling_status = if has_immediate { - VoteHandlingStatus::CastingVotes - } else { - VoteHandlingStatus::SchedulingVotes - }; + self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; self.retry_voter = None; self.pending_vote_operation = Some(operation.id); self.submitted_votes = self @@ -2570,23 +2526,14 @@ impl ScreenLike for DPNSScreen { self.submitted_votes.clear(); self.submitted_cards.clear(); self.release_pending_on_error = false; - // The review window disables both Submit and Cancel while a - // submission is in flight, so a failed submission must leave that - // state here. Otherwise the window stays on "Submitting votes…" - // with no way to retry or close it. + // 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.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; self.show_bulk_schedule_popup = !self.selected_votes.is_empty(); - } else if matches!( - self.bulk_vote_handling_status, - VoteHandlingStatus::CastingVotes | VoteHandlingStatus::SchedulingVotes - ) { - // AppState banners the borrowed `TaskError` itself, so the - // window only has to leave its in-flight state. - self.bulk_vote_handling_status = - VoteHandlingStatus::Failed(VoteSubmissionError::TaskFailed); } } if let Err(refresh_error) = self.vote_operations.refresh(&self.app_context) { @@ -3365,54 +3312,51 @@ mod tests { )); } - /// A failed submission must release the review window's in-flight state. - /// While it is held, the window disables Submit *and* Cancel and offers no - /// close control, so a stuck status leaves the user with no way out. + /// 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_releases_the_review_window() { - let (ctx, _temp_dir) = offline_ctx(); - let mut screen = DPNSScreen::new(&ctx, VotesView::ToDecide); - let operation_id = DpnsVoteOperationId::from_bytes([11; 16]); - let context = BackendTaskContext::DpnsVoteOperation { - network: ctx.network(), - operation_id, - }; + 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.bulk_apply_votes(), + AppAction::BackendTask(_) + )); + let operation_id = screen.pending_vote_operation.unwrap(); + screen.show_bulk_schedule_popup = false; let error = TaskError::DpnsCurrentVoteUnavailable; - for in_progress in [ - VoteHandlingStatus::CastingVotes, - VoteHandlingStatus::SchedulingVotes, - ] { - screen.show_bulk_schedule_popup = true; - screen.bulk_vote_handling_status = in_progress; - screen.pending_vote_operation = Some(operation_id); - - screen.display_backend_task_error(&context, &error); - screen.display_task_error(&error); + 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); - let VoteHandlingStatus::Failed(failure) = &screen.bulk_vote_handling_status else { - panic!( - "the review window must leave its in-flight state so Submit and Cancel work again" - ); - }; - assert!(matches!(failure, VoteSubmissionError::TaskFailed)); - assert!( - failure.to_string().contains("review and submit them again"), - "the window must name a recovery step the operator can take" - ); - } + assert_eq!(screen.pending_vote_operation, None); + assert_eq!(screen.selected_votes, staged); + assert!(!staged.is_empty()); + assert!(!screen.show_bulk_schedule_popup); + screen.open_review_for_node_set(); + assert!( + screen.show_bulk_schedule_popup, + "the confirm step must open again once the failed submission is released" + ); + assert!(matches!( + screen.bulk_vote_handling_status, + VoteHandlingStatus::NotStarted + )); } - /// An error belonging to a different operation must not disturb the review - /// window of the submission this screen is still waiting on. + /// 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.show_bulk_schedule_popup = true; - screen.bulk_vote_handling_status = VoteHandlingStatus::CastingVotes; screen.pending_vote_operation = Some(DpnsVoteOperationId::from_bytes([11; 16])); screen.display_backend_task_error( @@ -3428,10 +3372,6 @@ mod tests { screen.pending_vote_operation, Some(DpnsVoteOperationId::from_bytes([11; 16])) ); - assert!(matches!( - screen.bulk_vote_handling_status, - VoteHandlingStatus::CastingVotes - )); } /// VOTE-TC-013: a masternode loaded without its voting key must not reach the @@ -3784,10 +3724,6 @@ mod tests { screen.show_bulk_schedule_popup = false; screen.open_review_for_node_set(); assert!(!screen.show_bulk_schedule_popup); - assert!(matches!( - screen.bulk_vote_handling_status, - VoteHandlingStatus::CastingVotes - )); assert!(matches!(screen.bulk_apply_votes(), AppAction::None)); assert_eq!(screen.pending_vote_operation, operation_id); } @@ -4172,7 +4108,6 @@ mod tests { .insert(key.clone(), dispatch.clone()); let bulk_id = DpnsVoteOperationId::from_bytes([13; 16]); screen.pending_vote_operation = Some(bulk_id); - screen.bulk_vote_handling_status = VoteHandlingStatus::CastingVotes; screen.display_backend_task_error(&dispatch, &error); screen.display_task_error(&error); assert!(screen.pending_scheduled_actions.is_empty()); @@ -4180,10 +4115,6 @@ mod tests { .pending_scheduled_actions .insert(key, dispatch.clone()); assert_eq!(screen.pending_vote_operation, Some(bulk_id)); - assert!(matches!( - screen.bulk_vote_handling_status, - VoteHandlingStatus::CastingVotes - )); screen.reset_for_network_switch(); assert!(screen.pending_scheduled_actions.is_empty()); assert!(!screen.finish_scheduled_dispatch(&dispatch)); @@ -4837,7 +4768,6 @@ mod tests { "two nodes across two contests, two already as requested" ); assert_eq!(plan.node_count(), 2); - assert!(plan.has_immediate()); assert!(plan.has_scheduled()); let retained = plan .targets() From c2000ba8b51097b3e5e30cdb8983051dbbb36dc7 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:11:15 +0000 Subject: [PATCH 135/194] fix(dpns): bound the contest page query retries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The retry counter was declared inside the paging loop, so `continue` reset it and a node that kept answering as stale turned the refresh β€” now also started by the background timer β€” into a request loop that never returned. One page query now gets at most three retries with a growing pause, through a helper that is tested without a network. Addresses review finding RUST-016. Co-Authored-By: Claude Fable 5.1 --- .../query_dpns_contested_resources.rs | 136 ++++++++++++++---- 1 file changed, 108 insertions(+), 28 deletions(-) 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 d6182ef4c..817f91156 100644 --- a/src/backend_task/contested_names/query_dpns_contested_resources.rs +++ b/src/backend_task/contested_names/query_dpns_contested_resources.rs @@ -10,9 +10,55 @@ 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}; +/// 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(error); + } + if retries as usize >= MAX_PAGE_RETRIES { + tracing::error!("Max retries reached for query: {}", error); + return Err(error); + } + retries += 1; + tokio::time::sleep(retry_delay.saturating_mul(retries)).await; + } +} + impl AppContext { /// Refresh the contest cache, contenders, end times and every loaded node's /// proved votes as one snapshot. @@ -37,7 +83,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 { @@ -52,33 +97,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 { @@ -263,3 +285,61 @@ 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(dash_sdk::Error::StaleNode(_)))); + 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); + } + + #[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!(matches!(result, Err(dash_sdk::Error::Generic(_)))); + assert_eq!(attempts.load(Ordering::SeqCst), 1); + } +} From 3515fc0b11a3d477e5bfeb99b60cc96ca50c61f6 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:11:36 +0000 Subject: [PATCH 136/194] fix(dpns): keep the Scheduled view in a fixed order The grouped Scheduled view reversed its groups when the History table's sort had last been set to descending, although Scheduled has no sort control of its own. It now always shows the groups in the order `group_scheduled_rows` yields. Addresses review finding RUST-027. Co-Authored-By: Claude Fable 5.1 --- src/ui/dpns/dpns_contested_names_screen.rs | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 4d9fa9357..177f40d02 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -1580,21 +1580,15 @@ impl DPNSScreen { /// 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. + /// 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 descending = self.sort_order == SortOrder::Descending; let now = Utc::now().timestamp_millis().max(0) as u64; egui::ScrollArea::both().show(ui, |ui| { - for offset in 0..groups.len() { - let index = if descending { - groups.len() - 1 - offset - } else { - offset - }; - let group = &groups[index]; + for (index, group) in groups.iter().enumerate() { let dark_mode = ui.visuals().dark_mode; let choice = vote_choice_label( group.choice, From 02d8a0623c7f6e8dad9954afeb5cafc7f536a4a5 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:15:21 +0000 Subject: [PATCH 137/194] fix(dpns): skip a contest with an unknown deadline instead of failing the batch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "When voting is about to end" on a contest whose deadline had not been read yet failed the whole confirm step with "Choose a future time before the contest ends", although the operator chooses no time in that mode and one such contest blocked every other decision. Those node Γ— name pairs are now skipped with their own reason, and a node told to vote now still votes on the contest. Addresses review finding RUST-019 (model part). Co-Authored-By: Claude Fable 5.1 --- src/model/dpns_voting/composer.rs | 97 ++++++++++++++++++++++++------- src/ui/dpns/copy.rs | 3 + 2 files changed, 78 insertions(+), 22 deletions(-) diff --git a/src/model/dpns_voting/composer.rs b/src/model/dpns_voting/composer.rs index 49ca93a70..c6f77556d 100644 --- a/src/model/dpns_voting/composer.rs +++ b/src/model/dpns_voting/composer.rs @@ -71,6 +71,9 @@ pub enum SkipReason { 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. @@ -136,27 +139,28 @@ impl AggregatePlan { } /// Resolve a timing for one decision. "Before the end" on a contest already -/// inside the lead time votes now; the flag reports that fallback. +/// 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<(VoteTiming, bool), ComposeError> { - let outlasts = || ComposeError::ScheduleOutlastsContest { - contested_name: decision.contested_name.clone(), - }; +) -> Result, ComposeError> { match timing { - BatchTiming::Now => Ok((VoteTiming::Now, false)), + BatchTiming::Now => Ok(Some((VoteTiming::Now, false))), BatchTiming::BeforeEnd(preset) => { - let end = decision.end_time.ok_or_else(outlasts)?; - Ok(match relative_schedule(end, preset, now_ms) { - Ok(at) => (VoteTiming::Scheduled(at), false), - Err(_) => (VoteTiming::Now, true), - }) + 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(|()| (VoteTiming::Scheduled(at), false)) - .map_err(|_| outlasts()), + .map(|()| Some((VoteTiming::Scheduled(at), false))) + .map_err(|_| ComposeError::ScheduleOutlastsContest { + contested_name: decision.contested_name.clone(), + }), } } @@ -185,7 +189,7 @@ pub fn compose( contested_name: decision.contested_name.clone(), }); } - // The batch timing must fit every decision, whichever nodes end up voting. + // 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 { @@ -218,6 +222,15 @@ pub fn compose( plan.skipped.push(skip(SkipReason::NoChangesLeft)); continue; } + 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); plan.targets.push(DpnsVoteTarget { key: DpnsVoteTargetKey { network, @@ -228,14 +241,7 @@ pub fn compose( contested_name: decision.contested_name.clone(), requested_choice: decision.choice, current_choice: current, - timing: { - let (timing, ends_soon) = match timing { - Some(timing) => resolve_timing(timing, decision, now_ms)?, - None => batch_timing, - }; - plan.ends_soon_now += usize::from(ends_soon); - timing - }, + timing, }); } } @@ -416,6 +422,53 @@ mod tests { assert!(!plan.all_now()); } + /// "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() { diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index 1ae4765a2..c885c45de 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -465,6 +465,9 @@ pub fn skipped_reason_line(count: usize, reason: SkipReason) -> String { 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." + ), } } From eab8e62d1bfbecef8c94d16f8c8cdceb44a78b6d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:15:21 +0000 Subject: [PATCH 138/194] fix(dpns): review a failed vote again without dropping staged decisions "Review again" cleared every staged decision and staged the failed target without its deadline, through a third hand-written upsert. With no deadline, "when voting is about to end" could not be used, a fixed time past the contest end was accepted, and the voting-ended check was skipped. - The retried target is reviewed as its own plan (one node, one name); the staged decisions stay in the tray through confirm, cancel and the retry's result, and a retry that needs another review reopens on it. - The confirm step reads each deadline from the contest cards when it is built, so a deadline loaded after staging is used. - The toggle upsert is expressed through `stage_choice`; the outcome upsert is gone. Addresses review findings RUST-013, RUST-015 and RUST-019 (plan-time deadline). Co-Authored-By: Claude Fable 5.1 --- .../01-requirements.md | 14 +- src/ui/dpns/dpns_contested_names_screen.rs | 228 ++++++++++++++---- 2 files changed, 187 insertions(+), 55 deletions(-) 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 index 7d64f2e8f..84ee1f303 100644 --- 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 @@ -235,7 +235,10 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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`). Cards whose targets are in flight show + `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 @@ -301,8 +304,13 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. Β· {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.` Every other contest is - scheduled as above. Absolute times (`At a specific time`) at or after the - deadline are still rejected (existing rule). + 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. diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 177f40d02..79662d9d7 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -386,6 +386,16 @@ pub struct SelectedVote { pub end_time: Option, } +/// 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, +} + /// 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 @@ -464,8 +474,11 @@ pub struct DPNSScreen { show_bulk_schedule_popup: bool, /// Per-node overrides under `Adjust nodes`; absent means "same as above". node_overrides: BTreeMap, - /// Set by `Review again`: the confirm step covers only this node. - retry_voter: Option, + /// 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, bulk_vote_handling_status: VoteHandlingStatus, submission_error_banner: Option, confirm_timing: ConfirmTiming, @@ -571,7 +584,8 @@ impl DPNSScreen { // Vote handling show_bulk_schedule_popup: false, node_overrides: BTreeMap::new(), - retry_voter: None, + retry: None, + submitted_retry: None, bulk_vote_handling_status: VoteHandlingStatus::NotStarted, submission_error_banner: None, confirm_timing: ConfirmTiming::Now, @@ -618,7 +632,8 @@ impl DPNSScreen { self.show_bulk_schedule_popup = false; self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; self.node_overrides.clear(); - self.retry_voter = None; + 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; @@ -1299,36 +1314,54 @@ impl DPNSScreen { if self.pending_vote_operation.is_some() { return; } - self.retry_voter = None; + self.retry = None; self.node_overrides.clear(); self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; self.show_bulk_schedule_popup = true; } + /// Stage `choice` for a contest, or clear it when it is already staged. fn set_selected_vote(&mut self, contest: &ContestedName, choice: ResourceVoteChoice) { - if let Some(index) = self + let name = &contest.normalized_contested_name; + if self .selected_votes .iter() - .position(|vote| vote.contested_name == contest.normalized_contested_name) + .any(|vote| vote.contested_name == *name && vote.vote_choice == choice) { - if self.selected_votes[index].vote_choice == choice { - self.selected_votes.remove(index); - } else { - self.selected_votes[index].vote_choice = choice; - } + self.clear_choice(name); } else { - self.selected_votes.push(SelectedVote { - contested_name: contest.normalized_contested_name.clone(), - vote_choice: choice, - end_time: contest.end_time, - }); + 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.selected_votes.clear(); - self.set_selected_vote_from_outcome(outcome); - self.retry_voter = Some(outcome.target.key.voter_id); + 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.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; @@ -1370,23 +1403,6 @@ impl DPNSScreen { ui.add_space(6.0); } - fn set_selected_vote_from_outcome(&mut self, outcome: &DpnsVoteOutcome) { - let name = outcome.target.contested_name.clone(); - if let Some(vote) = self - .selected_votes - .iter_mut() - .find(|vote| vote.contested_name == name) - { - vote.vote_choice = outcome.target.requested_choice; - } else { - self.selected_votes.push(SelectedVote { - contested_name: name, - vote_choice: outcome.target.requested_choice, - end_time: None, - }); - } - } - /// Progress shows in the non-blocking drawer, never a window overlay /// (VOTE-FR-035/083). fn show_vote_progress(&self, ctx: &egui::Context) { @@ -1961,7 +1977,7 @@ impl DPNSScreen { }); return action; } - if self.selected_votes.is_empty() { + 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.", @@ -2128,7 +2144,7 @@ impl DPNSScreen { if cancel_clicked { // Cancel closes the confirm step; staged decisions stay in the tray. self.show_bulk_schedule_popup = false; - self.retry_voter = None; + self.retry = None; self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; } if let VoteHandlingStatus::Failed(error) = &self.bulk_vote_handling_status { @@ -2258,8 +2274,8 @@ impl DPNSScreen { self.voting_identities .iter() .map(|identity| identity.identity.id()) - .filter(|id| match self.retry_voter { - Some(voter) => *id == voter, + .filter(|id| match &self.retry { + Some(retry) => *id == retry.voter, None => included.contains(id), }) .map(|voter_id| ComposerNode { @@ -2276,7 +2292,7 @@ impl DPNSScreen { fn build_review_plan_at(&self, now: DateTime) -> Result { let now_ms = now.timestamp_millis() as u64; let decisions = self - .selected_votes + .review_votes() .iter() .map(|vote| { let vote_poll_id = self @@ -2296,7 +2312,10 @@ impl DPNSScreen { contested_name: vote.contested_name.clone(), vote_poll_id, choice: vote.vote_choice, - end_time: vote.end_time, + // 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>>()?; @@ -2404,15 +2423,22 @@ impl DPNSScreen { }); self.submission_error_banner.take_and_clear(); self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; - self.retry_voter = None; + self.submitted_retry = self.retry.take(); self.pending_vote_operation = Some(operation.id); - self.submitted_votes = self - .selected_votes - .iter() - .cloned() - .map(|vote| (vote.contested_name.clone(), vote)) - .collect(); - self.submitted_cards = self.selected_cards.clone(); + 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, @@ -2520,6 +2546,7 @@ impl ScreenLike for DPNSScreen { 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. @@ -2527,7 +2554,8 @@ impl ScreenLike for DPNSScreen { // A first vote became a change during preflight: reopen the // confirm on fresh vote state so it shows the change warning. self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; - self.show_bulk_schedule_popup = !self.selected_votes.is_empty(); + self.retry = retried; + self.show_bulk_schedule_popup = !self.review_votes().is_empty(); } } if let Err(refresh_error) = self.vote_operations.refresh(&self.app_context) { @@ -2565,6 +2593,7 @@ impl ScreenLike for DPNSScreen { let owns_result = self.pending_vote_operation == Some(operation_id); if owns_result { self.pending_vote_operation = None; + self.submitted_retry = None; self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; self.selected_votes.retain(|vote| { self.submitted_votes.get(&vote.contested_name) != Some(vote) @@ -4552,6 +4581,7 @@ mod tests { 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); @@ -4559,6 +4589,100 @@ mod tests { 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.bulk_apply_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.bulk_apply_votes(), + AppAction::BackendTask(_) + )); + screen.show_bulk_schedule_popup = 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.show_bulk_schedule_popup); + 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] From 7434f7eb0bdcdc42ca8f1ca1e4733d9c6e95df57 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:16:25 +0000 Subject: [PATCH 139/194] fix(dpns): make a per-node "before the end" timing follow the lead time A node set to "When voting is about to end" under Adjust nodes kept the lead time that was current when it was selected. Editing the lead time afterwards left that node on the old value while the header showed the new one, no option highlighted in its selector, and its scheduled row without the relative label. - Changing the lead time updates the nodes set to it. - Relative labels cover every target placed before the end: nodes following such a batch and nodes set to it individually. Addresses review finding RUST-017. Co-Authored-By: Claude Fable 5.1 --- src/ui/dpns/dpns_contested_names_screen.rs | 104 ++++++++++++++++++--- 1 file changed, 89 insertions(+), 15 deletions(-) diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 79662d9d7..7f97af8f0 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -35,9 +35,9 @@ use crate::model::dpns_voting::operator::{ }; use crate::model::dpns_voting::progress::needs_attention; use crate::model::dpns_voting::{ - DpnsCurrentVoteState, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperationId, - DpnsVoteOutcome, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, - dpns_schedule_is_overdue, + DpnsCurrentVoteState, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, + DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, + VoteTiming, dpns_schedule_is_overdue, }; use crate::model::qualified_identity::IdentityType; use crate::model::qualified_identity::QualifiedIdentity; @@ -2067,7 +2067,7 @@ impl DPNSScreen { .add(egui::DragValue::new(&mut minutes).range(1..=7 * 24 * 60)) .changed() { - self.relative_preset = std::time::Duration::from_secs(minutes * 60); + self.set_relative_preset(std::time::Duration::from_secs(minutes * 60)); } ui.label(before_end_phrase(self.relative_preset)); }); @@ -2153,6 +2153,41 @@ impl DPNSScreen { action } + /// 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; + } + } + } + + /// 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() + .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(|| 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(); @@ -2410,17 +2445,7 @@ impl DPNSScreen { } let voters = self.casting_voters(&plan); let operation = AppContext::new_dpns_vote_operation(plan.aggregate.targets); - let labels = - (self.confirm_timing == ConfirmTiming::BeforeEnd).then(|| RelativeScheduleLabels { - preset: self.relative_preset, - targets: operation - .targets - .iter() - .map(|outcome| &outcome.target.key) - .filter(|key| !self.node_overrides.contains_key(&key.voter_id)) - .cloned() - .collect(), - }); + let labels = self.relative_schedule_labels_for(&operation); self.submission_error_banner.take_and_clear(); self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; self.submitted_retry = self.retry.take(); @@ -4827,6 +4852,55 @@ mod tests { ); } + /// 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)), + ); + + let lead = std::time::Duration::from_secs(90 * 60); + assert_ne!(screen.relative_preset, lead); + screen.set_relative_preset(lead); + + 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()]) + ); + + 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" + ); + } + /// The review sheet must expand every node Γ— contest pair, suppress the /// targets that already hold the requested choice, and count what it dropped. #[tokio::test] From 2c7a316af055dda13df263df9e34bf48fe810c21 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:17:41 +0000 Subject: [PATCH 140/194] fix(dpns): validate schedule times in the UI through the model validator The confirm step and the schedule editor each compared the chosen time with the clock themselves. The editor's copy ignored the contest deadline, so a time at or after it could be saved and was only refused by the backend. Both now call `validate_dpns_schedule_time`; the editor passes the deadline the contest list has read. The editor does not run the full `validate_dpns_schedule_edit`: the backend refreshes the contest's contenders before enforcing it, so checking the choice against the panel's older cache could refuse an edit the backend accepts. Addresses review finding PROJ-004. Co-Authored-By: Claude Fable 5.1 --- src/ui/dpns/dpns_contested_names_screen.rs | 17 ++++-- .../scheduled_vote_editor.rs | 61 +++++++++++++++++-- 2 files changed, 66 insertions(+), 12 deletions(-) diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 7f97af8f0..466564ea0 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -37,7 +37,7 @@ 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, + VoteTiming, dpns_schedule_is_overdue, validate_dpns_schedule_time, }; use crate::model::qualified_identity::IdentityType; use crate::model::qualified_identity::QualifiedIdentity; @@ -1837,8 +1837,13 @@ impl DPNSScreen { 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.scheduled_vote_editor = ScheduledVoteEditor::new( + row.clone(), + key, + node_label, + choices, + self.contest_end_time(&row.vote.contested_name), + ); } /// The batch timing the confirm step resolves targets with. @@ -1851,9 +1856,9 @@ impl DPNSScreen { .simple_schedule .current_value() .ok_or(ReviewPlanError::ScheduleIsNotAValidTime)?; - if at <= now_ms { - return Err(ReviewPlanError::ScheduleIsNotInTheFuture); - } + // 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)) } } 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 index d40cf8247..fac86d115 100644 --- a/src/ui/dpns/dpns_contested_names_screen/scheduled_vote_editor.rs +++ b/src/ui/dpns/dpns_contested_names_screen/scheduled_vote_editor.rs @@ -9,6 +9,8 @@ pub(super) struct ScheduledVoteEditor { 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, } @@ -25,6 +27,7 @@ impl ScheduledVoteEditor { 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)?; @@ -34,6 +37,7 @@ impl ScheduledVoteEditor { key, node_label, choices, + end_time, schedule: UtcScheduleInput::new().with_time(time), time_changed: false, }) @@ -57,11 +61,13 @@ impl ScheduledVoteEditor { } else { self.original.vote.unix_timestamp }; - if timestamp <= now_ms - || !self - .choices - .iter() - .any(|(choice, _)| *choice == self.choice) + // 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; } @@ -112,7 +118,7 @@ impl ScheduledVoteEditor { 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. Only votes that have not started can be edited."); + "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() { @@ -170,6 +176,7 @@ mod tests { (ResourceVoteChoice::Lock, "Lock".into()), (ResourceVoteChoice::Abstain, "Abstain".into()), ], + None, ) .unwrap(); editor.choice = ResourceVoteChoice::Abstain; @@ -211,4 +218,46 @@ mod tests { 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" + ); + } } From 7e459dd423eb87d64797a3fd9363778cc3e6ffdf Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:21:26 +0000 Subject: [PATCH 141/194] fix(dpns): do not send long-queued votes by themselves after a restart Startup recovery re-drove every target still `Queued` from an earlier run, however long the app had been closed, and its preflight skipped the rule that a vote reviewed as a first vote must be reviewed again when it has become a change. - Recovery now stops queued targets older than the two-minute lateness bound (from the review for an immediate vote, from its time for an admitted schedule): the immediate vote becomes a reviewable pre-broadcast failure, the schedule returns to Scheduled as missed. This matches what already happens to an interrupted `Submitting` target. - A recovered immediate vote reviewed as a first vote is failed for review instead of being sent when Platform shows a different current vote. Both transitions run inside the journal guard; nothing was broadcast for a queued target, so no ambiguous outcome is released. Addresses review finding SEC-002. Co-Authored-By: Claude Fable 5.1 --- .../01-requirements.md | 9 +- src/context/dpns_vote_operations/mod.rs | 134 +++++++++++++++++- .../dpns_vote_operations/transitions.rs | 29 +++- 3 files changed, 167 insertions(+), 5 deletions(-) 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 index 84ee1f303..ae28d2d96 100644 --- 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 @@ -230,7 +230,14 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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. + 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. 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 diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index a50608128..842026b8a 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -17,7 +17,8 @@ use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome, DpnsScheduledVoteEdit, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, - authoritative_dpns_vote_outcomes, unavailable_preflight_outcome, + authoritative_dpns_vote_outcomes, failed_before_broadcast_outcome, + unavailable_preflight_outcome, }; use crate::utils::time::now_ms; use crate::wallet_backend::{DetKv, DetScope}; @@ -768,6 +769,16 @@ impl AppContext { 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) { @@ -786,11 +797,18 @@ impl AppContext { }) } - /// Recover interrupted targets according to their durable broadcast phase. + /// 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)? { - if recover_interrupted_target_statuses(&mut operation, |_| true) { + 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)?; } } @@ -2318,6 +2336,116 @@ mod tests { assert!(diagnostics.contains_key(&second_key)); } + /// 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(); + + 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_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(); + 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_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); diff --git a/src/context/dpns_vote_operations/transitions.rs b/src/context/dpns_vote_operations/transitions.rs index a10e89dee..58d42f6b1 100644 --- a/src/context/dpns_vote_operations/transitions.rs +++ b/src/context/dpns_vote_operations/transitions.rs @@ -8,7 +8,7 @@ use super::{load_operation, persist_operation}; use crate::backend_task::error::TaskError; use crate::model::dpns_voting::{ DpnsVoteFailure, DpnsVoteOperation, DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTargetKey, - DpnsVoteTargetStatus, failed_before_broadcast_outcome, + DpnsVoteTargetStatus, VoteTiming, dpns_schedule_is_overdue, failed_before_broadcast_outcome, }; use crate::wallet_backend::DetKv; use dash_sdk::dpp::dashcore::Network; @@ -116,6 +116,33 @@ pub(super) fn recover_interrupted_target_statuses( 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, From e143a3eac0688bfe79a44e1fa1153fff766523dd Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:23:33 +0000 Subject: [PATCH 142/194] fix(dpns): refuse to overwrite a stored vote operation on insert Two latent gaps in the journal insert path, neither reachable from the current UI but both in the enforcement layer: - `insert_dpns_vote_operation` accepted an ID that already had a record and wrote the caller's snapshot over it, which could put targets an executor had claimed or broadcast back in the queue. Insertion now fails inside the journal guard when the ID exists. - After replacing a scheduled target, the executor ran with the whole stored operation, so a queued sibling of another node was claimed without its voter. The insert branch now keeps only the requested targets, like the resume branch. The replace path itself is kept: removing it changes the task's shape and is not needed to close either gap. Addresses review finding SEC-006. Co-Authored-By: Claude Fable 5.1 --- src/backend_task/contested_names/mod.rs | 47 +++++++++++++++++++++++++ src/context/dpns_vote_operations/mod.rs | 44 +++++++++++++++++++++++ 2 files changed, 91 insertions(+) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 1a7a5cea1..41ef02efa 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -662,6 +662,11 @@ impl AppContext { } else { self.validate_new_dpns_schedules(&new_schedules)?; self.insert_dpns_vote_operation(&mut operation, replacing_scheduled_key.as_ref())?; + // 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 @@ -1888,6 +1893,48 @@ mod tests { ); } + /// 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] diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index 842026b8a..782e6e5ad 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -562,6 +562,15 @@ impl AppContext { load_operations_read_only(kv, self.network)?.into(); 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); + } persist_operation(kv, self.network, operation) }) } @@ -2336,6 +2345,41 @@ mod tests { 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] From cf3e9b2cb07865e376f309b21bbed904fb1676ac Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:24:54 +0000 Subject: [PATCH 143/194] fix(dpns): check the proved vote before recording a broadcast rejection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `broadcast` retries internally and returns only its last attempt's error. When an earlier attempt was applied and its response was lost, a retry of the same transition can be refused with a consensus error, which was recorded as `Rejected` β€” a lock-releasing "did not take effect" status β€” for a vote Platform had applied. A rejection reported by the broadcast step is now settled with one proved read of the node's current vote on the contest: the requested choice means `Confirmed`; anything else, or a failed read, keeps `Rejected`. Rejections reported while waiting for the result are bound to the transition and are unchanged. Addresses review finding SEC-007. Co-Authored-By: Claude Fable 5.1 --- .../01-requirements.md | 6 +- .../contested_names/vote_on_dpns_name.rs | 79 ++++++++++++++++++- 2 files changed, 83 insertions(+), 2 deletions(-) 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 index ae28d2d96..c74dfb343 100644 --- 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 @@ -259,7 +259,11 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. ### Confirmation and recovery - **VOTE-FR-040** β€” Structured Platform consensus causes are treated as - confirmed rejection. + 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 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 24a6d055e..8b377e441 100644 --- a/src/backend_task/contested_names/vote_on_dpns_name.rs +++ b/src/backend_task/contested_names/vote_on_dpns_name.rs @@ -18,7 +18,9 @@ use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoic 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::Identifier; @@ -100,6 +102,51 @@ fn classify_broadcast_journal_result( } } +/// Read one node's proved current vote on one contest. +pub(super) async fn proved_dpns_vote_choice( + key: &DpnsVoteTargetKey, + sdk: &Sdk, +) -> Result, dash_sdk::Error> { + 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?; + Ok(votes + .get(&key.vote_poll_id) + .and_then(Option::as_ref) + .map(ResourceVoteGettersV0::resource_vote_choice)) +} + +/// Settle a rejection that `broadcast` reported. +/// +/// `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, dash_sdk::Error>, +) -> 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, @@ -205,7 +252,14 @@ impl AppContext { ) .await { - return Ok(attempt); + return Ok(match attempt { + DpnsVoteAttempt::Rejected(rejection) => settle_broadcast_rejection( + rejection, + vote_choice, + proved_dpns_vote_choice(key, sdk).await, + ), + attempt => attempt, + }); } match Vote::wait_for_response(sdk, state_transition, Some(settings)).await { @@ -268,6 +322,29 @@ mod tests { 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(dash_sdk::Error::Generic("unreachable".to_owned())), + ] { + 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)) From 64d3ae5e96562bdafd032b241c578bf90b0b02b7 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:25:57 +0000 Subject: [PATCH 144/194] refactor(dpns): drop comments and names left over from removed designs - Comments that described the hidden pop-up, the compatibility mirror row, the Active contests screen and the review sheet now describe the confirm step and the journal as they are. - The confirm step's fields and methods use one vocabulary (`confirm_open`, `confirm_status`, `confirm_schedule`, `show_confirm_step`, `submit_confirmed_votes`). - `render_no_voting_nodes` no longer returns an action it never set, and the panel imports `JOURNAL_UNAVAILABLE_MESSAGE` instead of re-declaring it. - Two doc comments cited a requirement about ended voting for History outcomes, and one showed an example its function does not produce. Addresses review finding RUST-024. Co-Authored-By: Claude Fable 5.1 --- src/model/dpns_voting/mod.rs | 3 +- src/model/dpns_voting/operator.rs | 2 +- src/ui/dpns/copy.rs | 4 +- src/ui/dpns/dpns_contested_names_screen.rs | 168 ++++++++++----------- src/ui/state/dpns_contests.rs | 2 +- 5 files changed, 87 insertions(+), 92 deletions(-) diff --git a/src/model/dpns_voting/mod.rs b/src/model/dpns_voting/mod.rs index 7e5efa221..2af369805 100644 --- a/src/model/dpns_voting/mod.rs +++ b/src/model/dpns_voting/mod.rs @@ -149,7 +149,8 @@ pub fn validate_dpns_schedule_edit( Ok(()) } -/// Durable identity of one scheduled-vote compatibility mirror row. +/// 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, diff --git a/src/model/dpns_voting/operator.rs b/src/model/dpns_voting/operator.rs index 21c06d9dd..8f563c4ad 100644 --- a/src/model/dpns_voting/operator.rs +++ b/src/model/dpns_voting/operator.rs @@ -161,7 +161,7 @@ pub struct ChoiceTally { } /// Group nodes' proved choices by choice with summed vote weight; ties break -/// by node count (History, VOTE-FR-087). +/// by node count (History). pub fn tally_node_choices( votes: impl IntoIterator, ) -> Vec { diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index c885c45de..f86a8b49e 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -366,7 +366,7 @@ pub fn voting_weight_label(weight: u32) -> String { } } -/// History outcome of an awarded contest (VOTE-FR-087). +/// 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})"), @@ -449,7 +449,7 @@ pub fn excluded_nodes_line(count: usize, exclusion: NodeExclusion) -> String { } } -/// One skipped-reason line, e.g. `2 votes: no changes left (4 of 4 changes used)`. +/// 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 => { diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 466564ea0..e484ee9f1 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -50,10 +50,10 @@ use crate::ui::dpns::contest_card::{CardEvent, CardView}; use crate::ui::dpns::copy::needs_attention_line; use crate::ui::dpns::copy::tray_label; use crate::ui::dpns::copy::{ - LOCKED_FOR_GOOD, 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, + JOURNAL_UNAVAILABLE_MESSAGE, LOCKED_FOR_GOOD, 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::{ends_soon_now_line, excluded_nodes_line}; use crate::ui::dpns::node_set_picker; @@ -78,7 +78,6 @@ const NO_OPEN_CONTESTS_MESSAGE: &str = 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 JOURNAL_UNAVAILABLE_MESSAGE: &str = crate::ui::dpns::copy::JOURNAL_UNAVAILABLE_MESSAGE; 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."; @@ -470,8 +469,8 @@ pub struct DPNSScreen { refresh_banner: Option, journal_error_banner: Option, - /// Selected vote handling - show_bulk_schedule_popup: bool, + /// Whether the confirm step is open. + confirm_open: bool, /// Per-node overrides under `Adjust nodes`; absent means "same as above". node_overrides: BTreeMap, /// Set by `Review again`: the confirm step covers only this target. @@ -479,14 +478,14 @@ pub struct DPNSScreen { /// The retried target of the pending submission, kept so a submission /// that needs another review reopens on it. submitted_retry: Option, - bulk_vote_handling_status: VoteHandlingStatus, + 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. - simple_schedule: UtcScheduleInput, + 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, @@ -547,7 +546,7 @@ impl DPNSScreen { tracing::warn!(?error, "Could not cache proved DPNS vote state"); } - // Initialize vote handling pop-up state to hidden + // The confirm step's fixed-time input starts one day ahead. let default_schedule_time = Utc::now() + chrono::Duration::days(1); let mut screen = Self { @@ -582,15 +581,15 @@ impl DPNSScreen { journal_error_banner: None, // Vote handling - show_bulk_schedule_popup: false, + confirm_open: false, node_overrides: BTreeMap::new(), retry: None, submitted_retry: None, - bulk_vote_handling_status: VoteHandlingStatus::NotStarted, + confirm_status: VoteHandlingStatus::NotStarted, submission_error_banner: None, confirm_timing: ConfirmTiming::Now, relative_preset: relative_schedule_preset(app_context.network()), - simple_schedule: UtcScheduleInput::new().with_time(default_schedule_time), + confirm_schedule: UtcScheduleInput::new().with_time(default_schedule_time), load_node_requested: false, node_set: NodeSet::All, node_set_network: None, @@ -629,8 +628,8 @@ impl DPNSScreen { pub(crate) fn reset_for_network_switch(&mut self) { self.selected_votes.clear(); - self.show_bulk_schedule_popup = false; - self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; + self.confirm_open = false; + self.confirm_status = VoteHandlingStatus::NotStarted; self.node_overrides.clear(); self.retry = None; self.submitted_retry = None; @@ -719,9 +718,8 @@ impl DPNSScreen { } } - fn render_no_voting_nodes(&mut self, ui: &mut Ui) -> AppAction { + fn render_no_voting_nodes(&mut self, ui: &mut Ui) { let (heading, detail, button) = self.no_voting_nodes_copy(); - let action = AppAction::None; let dark_mode = ui.style().visuals.dark_mode; ui.vertical_centered(|ui| { ui.add_space(24.0); @@ -741,7 +739,6 @@ impl DPNSScreen { }); }); }); - action } fn render_empty_view(&mut self, ui: &mut Ui) -> AppAction { @@ -1159,10 +1156,7 @@ impl DPNSScreen { /// 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.show_bulk_schedule_popup - || ui.ctx().egui_wants_keyboard_input() - { + if !self.list_focused || self.confirm_open || ui.ctx().egui_wants_keyboard_input() { return None; } let shortcuts: Vec = ui.input(|input| { @@ -1316,8 +1310,8 @@ impl DPNSScreen { } self.retry = None; self.node_overrides.clear(); - self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; - self.show_bulk_schedule_popup = true; + self.confirm_status = VoteHandlingStatus::NotStarted; + self.confirm_open = true; } /// Stage `choice` for a contest, or clear it when it is already staged. @@ -1364,8 +1358,8 @@ impl DPNSScreen { }); self.node_overrides.clear(); self.confirm_timing = ConfirmTiming::Now; - self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; - self.show_bulk_schedule_popup = true; + self.confirm_status = VoteHandlingStatus::NotStarted; + self.confirm_open = true; } /// `Needs attention` row (VOTE-FR-084): unconfirmed, failed or missed @@ -1853,7 +1847,7 @@ impl DPNSScreen { ConfirmTiming::BeforeEnd => Ok(BatchTiming::BeforeEnd(self.relative_preset)), ConfirmTiming::At => { let at = self - .simple_schedule + .confirm_schedule .current_value() .ok_or(ReviewPlanError::ScheduleIsNotAValidTime)?; // Each contest's deadline is checked when the plan is composed. @@ -1956,14 +1950,14 @@ impl DPNSScreen { /// The confirm step (VOTE-FR-080): an aggregate of the staged decisions /// across the node set, the batch timing, and `Adjust nodes`. - fn show_review_and_cast_window(&mut self, ui: &mut Ui) -> AppAction { + 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; } @@ -1974,10 +1968,10 @@ impl DPNSScreen { ui.horizontal(|ui| { if ComponentStyles::add_primary_button(ui, button).clicked() { self.load_node_requested = true; - self.show_bulk_schedule_popup = false; + self.confirm_open = false; } if ComponentStyles::add_secondary_button(ui, "Close", dark_mode).clicked() { - self.show_bulk_schedule_popup = false; + self.confirm_open = false; } }); return action; @@ -1988,7 +1982,7 @@ impl DPNSScreen { "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.show_bulk_schedule_popup = false; + self.confirm_open = false; } return action; } @@ -2079,7 +2073,7 @@ impl DPNSScreen { ui.colored_label(DashColors::warning_color(dark_mode), KEEP_RUNNING_MESSAGE); } ConfirmTiming::At => { - self.simple_schedule.show(ui); + self.confirm_schedule.show(ui); ui.colored_label(DashColors::warning_color(dark_mode), KEEP_RUNNING_MESSAGE); } } @@ -2138,21 +2132,21 @@ impl DPNSScreen { }); } if submit_clicked { - action = self.bulk_apply_votes(); + 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.show_bulk_schedule_popup = false; + 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.show_bulk_schedule_popup = false; + self.confirm_open = false; self.retry = None; - self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; + self.confirm_status = VoteHandlingStatus::NotStarted; } - if let VoteHandlingStatus::Failed(error) = &self.bulk_vote_handling_status { + if let VoteHandlingStatus::Failed(error) = &self.confirm_status { ui.colored_label(DashColors::error_color(dark_mode), error.to_string()); } action @@ -2291,12 +2285,12 @@ impl DPNSScreen { if let Some(handle) = &self.submission_error_banner { handle.with_details(&error); } - self.bulk_vote_handling_status = VoteHandlingStatus::Failed(error); + self.confirm_status = VoteHandlingStatus::Failed(error); } /// Resolve every node Γ— contest target the current review would submit. /// - /// The review sheet and the submit click share this so the sheet cannot + /// The confirm step and the submit click share this so the step cannot /// promise something other than what is sent. /// /// # Errors @@ -2408,7 +2402,7 @@ impl DPNSScreen { /// Clone the signing identities of the nodes casting in `plan`. /// - /// Kept out of [`ReviewPlan`], which the review sheet rebuilds every frame: + /// 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 @@ -2423,7 +2417,7 @@ impl DPNSScreen { .collect() } - fn bulk_apply_votes(&mut self) -> AppAction { + fn submit_confirmed_votes(&mut self) -> AppAction { if self.pending_vote_operation.is_some() { return AppAction::None; } @@ -2452,7 +2446,7 @@ impl DPNSScreen { 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.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; + self.confirm_status = VoteHandlingStatus::NotStarted; self.submitted_retry = self.retry.take(); self.pending_vote_operation = Some(operation.id); if self.submitted_retry.is_some() { @@ -2583,9 +2577,9 @@ impl ScreenLike for DPNSScreen { 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.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; + self.confirm_status = VoteHandlingStatus::NotStarted; self.retry = retried; - self.show_bulk_schedule_popup = !self.review_votes().is_empty(); + self.confirm_open = !self.review_votes().is_empty(); } } if let Err(refresh_error) = self.vote_operations.refresh(&self.app_context) { @@ -2624,7 +2618,7 @@ impl ScreenLike for DPNSScreen { if owns_result { self.pending_vote_operation = None; self.submitted_retry = None; - self.bulk_vote_handling_status = VoteHandlingStatus::NotStarted; + self.confirm_status = VoteHandlingStatus::NotStarted; self.selected_votes.retain(|vote| { self.submitted_votes.get(&vote.contested_name) != Some(vote) }); @@ -2820,23 +2814,23 @@ impl ScreenLike for DPNSScreen { } } } - if self.show_bulk_schedule_popup { + if self.confirm_open { egui::Window::new("Confirm votes") .collapsible(false) .resizable(true) .vscroll(true) .show(ui.ctx(), |ui| { - action |= self.show_review_and_cast_window(ui); + action |= self.show_confirm_step(ui); }); } - if self.voting_identity_load_error.is_some() && !self.show_bulk_schedule_popup { + 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() { - action |= self.render_no_voting_nodes(ui); + self.render_no_voting_nodes(ui); } self.render_needs_attention(ui); if self.active_contests.is_empty() { @@ -3056,7 +3050,7 @@ mod tests { let (mut screen, _temp_dir) = voting_ui_review_fixture(); let ctx = Arc::clone(&screen.app_context); assert!(matches!( - screen.bulk_apply_votes(), + screen.submit_confirmed_votes(), AppAction::BackendTask(_) )); let operation_id = screen.pending_vote_operation.unwrap(); @@ -3079,7 +3073,7 @@ mod tests { assert!(screen.selected_votes.is_empty()); assert!(screen.pending_vote_operation.is_none()); assert!(matches!( - screen.bulk_vote_handling_status, + screen.confirm_status, VoteHandlingStatus::NotStarted )); assert!(!screen.pending_scheduled_actions.is_empty()); @@ -3167,7 +3161,7 @@ mod tests { let mut harness = egui_kittest::Harness::builder() .with_size(egui::vec2(1000.0, 800.0)) .build_ui(move |ui| { - screen.show_review_and_cast_window(ui); + screen.show_confirm_step(ui); }); harness.run(); @@ -3372,11 +3366,11 @@ mod tests { let (mut screen, _dir) = voting_ui_review_fixture(); let staged = screen.selected_votes.clone(); assert!(matches!( - screen.bulk_apply_votes(), + screen.submit_confirmed_votes(), AppAction::BackendTask(_) )); let operation_id = screen.pending_vote_operation.unwrap(); - screen.show_bulk_schedule_popup = false; + screen.confirm_open = false; let error = TaskError::DpnsCurrentVoteUnavailable; screen.display_backend_task_error( @@ -3391,14 +3385,14 @@ mod tests { assert_eq!(screen.pending_vote_operation, None); assert_eq!(screen.selected_votes, staged); assert!(!staged.is_empty()); - assert!(!screen.show_bulk_schedule_popup); + assert!(!screen.confirm_open); screen.open_review_for_node_set(); assert!( - screen.show_bulk_schedule_popup, + screen.confirm_open, "the confirm step must open again once the failed submission is released" ); assert!(matches!( - screen.bulk_vote_handling_status, + screen.confirm_status, VoteHandlingStatus::NotStarted )); } @@ -3644,11 +3638,11 @@ mod tests { egui_kittest::Harness::builder() .with_size(egui::vec2(1000.0, 800.0)) .build_ui(move |ui| { - rendering.lock_recover().show_review_and_cast_window(ui); + rendering.lock_recover().show_confirm_step(ui); }) }; let (mut screen, _dir) = voting_ui_review_fixture(); - screen.show_bulk_schedule_popup = true; + screen.confirm_open = true; let screen = Arc::new(Mutex::new(screen)); let mut harness = render(&screen); @@ -3663,10 +3657,10 @@ mod tests { screen.pending_vote_operation.is_none(), "Enter on Cancel must not cast" ); - assert!(!screen.show_bulk_schedule_popup, "Enter on Cancel cancels"); + assert!(!screen.confirm_open, "Enter on Cancel cancels"); } - screen.lock_recover().show_bulk_schedule_popup = true; + screen.lock_recover().confirm_open = true; let mut harness = render(&screen); harness.run(); harness.key_press(egui::Key::Enter); @@ -3701,7 +3695,7 @@ mod tests { }; harness.event(enter(true)); harness.run(); - assert!(screen.lock_recover().show_bulk_schedule_popup); + assert!(screen.lock_recover().confirm_open); assert!(screen.lock_recover().pending_vote_operation.is_none()); harness.event(enter(true)); harness.run_steps(2); @@ -3746,7 +3740,7 @@ mod tests { screen.refresh(); screen.selected_cards.insert("alpha".to_owned()); assert!(matches!( - screen.bulk_apply_votes(), + screen.submit_confirmed_votes(), AppAction::BackendTask(_) )); let operation_id = screen.pending_vote_operation.unwrap(); @@ -3770,14 +3764,14 @@ mod tests { fn review_safety_pending_submission_cannot_be_replaced_by_reopening_review() { let (mut screen, _dir) = voting_ui_review_fixture(); assert!(matches!( - screen.bulk_apply_votes(), + screen.submit_confirmed_votes(), AppAction::BackendTask(_) )); let operation_id = screen.pending_vote_operation; - screen.show_bulk_schedule_popup = false; + screen.confirm_open = false; screen.open_review_for_node_set(); - assert!(!screen.show_bulk_schedule_popup); - assert!(matches!(screen.bulk_apply_votes(), AppAction::None)); + assert!(!screen.confirm_open); + assert!(matches!(screen.submit_confirmed_votes(), AppAction::None)); assert_eq!(screen.pending_vote_operation, operation_id); } @@ -3785,7 +3779,7 @@ mod tests { fn review_safety_submission_result_preserves_changed_staged_choice() { let (mut screen, _dir) = voting_ui_review_fixture(); assert!(matches!( - screen.bulk_apply_votes(), + screen.submit_confirmed_votes(), AppAction::BackendTask(_) )); let operation_id = screen.pending_vote_operation.unwrap(); @@ -4037,9 +4031,9 @@ mod tests { let (mut screen, _dir) = voting_ui_review_fixture(); let now = Utc::now(); screen.confirm_timing = ConfirmTiming::At; - screen.simple_schedule = + screen.confirm_schedule = UtcScheduleInput::new().with_time(now + chrono::Duration::hours(1)); - let scheduled_at = screen.simple_schedule.current_value().unwrap(); + 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!( @@ -4092,7 +4086,7 @@ mod tests { .and_hms_opt(18, 30, 0) .unwrap() .and_utc(); - screen.simple_schedule = UtcScheduleInput::new().with_time(requested); + screen.confirm_schedule = UtcScheduleInput::new().with_time(requested); screen.confirm_timing = ConfirmTiming::At; let plan = screen.build_review_plan().unwrap(); assert_eq!( @@ -4231,7 +4225,7 @@ mod tests { .unwrap(); screen.vote_state.reload(&screen.app_context).unwrap(); assert!(matches!( - screen.bulk_apply_votes(), + screen.submit_confirmed_votes(), AppAction::BackendTask(_) )); let operation_id = screen.pending_vote_operation.unwrap(); @@ -4250,11 +4244,11 @@ mod tests { screen.display_task_error(&error); assert!(screen.pending_vote_operation.is_none()); assert!(matches!( - screen.bulk_vote_handling_status, + screen.confirm_status, VoteHandlingStatus::NotStarted )); assert!( - screen.show_bulk_schedule_popup, + screen.confirm_open, "DPN-005: the confirm reopens with the change warning" ); assert_eq!( @@ -4264,7 +4258,7 @@ mod tests { let mut harness = egui_kittest::Harness::builder() .with_size(egui::vec2(1000.0, 800.0)) .build_ui(move |ui| { - screen.show_review_and_cast_window(ui); + screen.show_confirm_step(ui); }); harness.run(); assert!( @@ -4419,7 +4413,7 @@ mod tests { screen.lock_recover().list_focused = true; harness.key_press(egui::Key::Enter); harness.run(); - assert!(screen.lock_recover().show_bulk_schedule_popup); + assert!(screen.lock_recover().confirm_open); assert!( harness .query_by_label("Cast 2 decisions with 1 node") @@ -4544,7 +4538,7 @@ mod tests { for reviewing in [false, true] { let mut screen = DPNSScreen::new(&context, VotesView::ToDecide); assert!(screen.voting_identity_load_error.is_some()); - screen.show_bulk_schedule_popup = reviewing; + screen.confirm_open = reviewing; let mut harness = egui_kittest::Harness::builder().build_ui(move |ui| { screen.ui(ui); }); @@ -4625,7 +4619,7 @@ mod tests { ); assert!(matches!( - screen.bulk_apply_votes(), + screen.submit_confirmed_votes(), AppAction::BackendTask(_) )); let operation_id = screen.pending_vote_operation.unwrap(); @@ -4663,10 +4657,10 @@ mod tests { let retried = screen.retry.clone(); assert!(retried.is_some()); assert!(matches!( - screen.bulk_apply_votes(), + screen.submit_confirmed_votes(), AppAction::BackendTask(_) )); - screen.show_bulk_schedule_popup = false; + screen.confirm_open = false; let error = TaskError::DpnsVoteReviewRequired; screen.display_backend_task_error( &BackendTaskContext::DpnsVoteOperation { @@ -4677,7 +4671,7 @@ mod tests { ); screen.display_task_error(&error); - assert!(screen.show_bulk_schedule_popup); + 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"); @@ -4720,7 +4714,7 @@ mod tests { 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_review_and_cast_window(ui); + screen.show_confirm_step(ui); }); harness.run(); assert!( @@ -4739,7 +4733,7 @@ mod tests { 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_review_and_cast_window(ui); + screen.show_confirm_step(ui); }); harness.run(); assert!( @@ -4800,7 +4794,7 @@ mod tests { #[test] fn voting_ui_network_switch_discards_staged_choices() { let (mut screen, _temp_dir) = voting_ui_review_fixture(); - screen.show_bulk_schedule_popup = true; + screen.confirm_open = true; screen.pending_scheduled_actions.insert( pending_scheduled_key(&screen.app_context), BackendTaskContext::Unknown, @@ -4816,7 +4810,7 @@ mod tests { screen.reset_for_network_switch(); screen.refresh_on_arrival(); assert!(screen.selected_votes.is_empty()); - assert!(!screen.show_bulk_schedule_popup); + assert!(!screen.confirm_open); assert!(screen.pending_scheduled_actions.is_empty()); } @@ -4906,7 +4900,7 @@ mod tests { ); } - /// The review sheet must expand every node Γ— contest pair, suppress the + /// 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() { diff --git a/src/ui/state/dpns_contests.rs b/src/ui/state/dpns_contests.rs index 60c886133..f1e7f7dc6 100644 --- a/src/ui/state/dpns_contests.rs +++ b/src/ui/state/dpns_contests.rs @@ -12,7 +12,7 @@ pub struct ActiveDpnsContestView { pub vote_poll_id: Option, } -/// Immutable render snapshot for the Active contests screen. +/// Immutable render snapshot of the open contests for the Votes panel. #[derive(Debug, Clone, Default)] pub struct ActiveDpnsContestSnapshot { contests: Arc<[ActiveDpnsContestView]>, From 6cbc38cc8497d45597a482a6661675fad84983da Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:27:37 +0000 Subject: [PATCH 145/194] fix(dpns): return TaskError from the new retry and proved-vote helpers `fetch_page_with_retries` and `proved_dpns_vote_choice` returned the SDK error by value, which clippy rejects as an oversized `Err` variant; both now convert to `TaskError` at the boundary. Also use `then_some` for the relative schedule labels. Follow-up to the fixes for review findings RUST-016, SEC-007 and RUST-017. Co-Authored-By: Claude Fable 5.1 --- .../contested_names/query_dpns_contested_resources.rs | 10 +++++----- src/backend_task/contested_names/vote_on_dpns_name.rs | 10 ++++++---- src/ui/dpns/dpns_contested_names_screen.rs | 2 +- 3 files changed, 12 insertions(+), 10 deletions(-) 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 817f91156..adee5ace3 100644 --- a/src/backend_task/contested_names/query_dpns_contested_resources.rs +++ b/src/backend_task/contested_names/query_dpns_contested_resources.rs @@ -35,7 +35,7 @@ fn page_query_is_retryable(error: &dash_sdk::Error) -> bool { async fn fetch_page_with_retries( retry_delay: Duration, mut fetch: impl FnMut() -> Fut, -) -> Result +) -> Result where Fut: Future>, { @@ -48,11 +48,11 @@ where tracing::error!("Error fetching contested resources: {}", error); super::log_contested_proof_error(&error, RequestType::GetContestedResources); if !page_query_is_retryable(&error) { - return Err(error); + return Err(TaskError::from(error)); } if retries as usize >= MAX_PAGE_RETRIES { tracing::error!("Max retries reached for query: {}", error); - return Err(error); + return Err(TaskError::from(error)); } retries += 1; tokio::time::sleep(retry_delay.saturating_mul(retries)).await; @@ -310,7 +310,7 @@ mod tests { }) .await; - assert!(matches!(result, Err(dash_sdk::Error::StaleNode(_)))); + assert!(matches!(result, Err(TaskError::DapiStaleNode { .. }))); assert_eq!(attempts.load(Ordering::SeqCst), MAX_PAGE_RETRIES + 1); } @@ -339,7 +339,7 @@ mod tests { }) .await; - assert!(matches!(result, Err(dash_sdk::Error::Generic(_)))); + assert!(result.is_err()); assert_eq!(attempts.load(Ordering::SeqCst), 1); } } 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 8b377e441..a0e7e8fb4 100644 --- a/src/backend_task/contested_names/vote_on_dpns_name.rs +++ b/src/backend_task/contested_names/vote_on_dpns_name.rs @@ -106,7 +106,7 @@ fn classify_broadcast_journal_result( pub(super) async fn proved_dpns_vote_choice( key: &DpnsVoteTargetKey, sdk: &Sdk, -) -> Result, dash_sdk::Error> { +) -> Result, TaskError> { let query = ContestedResourceVotesGivenByIdentityQuery { identity_id: key.voter_id, offset: None, @@ -114,7 +114,9 @@ pub(super) async fn proved_dpns_vote_choice( start_at: Some((key.vote_poll_id.to_buffer(), true)), order_ascending: true, }; - let votes = ResourceVote::fetch_many(sdk, query).await?; + let votes = ResourceVote::fetch_many(sdk, query) + .await + .map_err(TaskError::from)?; Ok(votes .get(&key.vote_poll_id) .and_then(Option::as_ref) @@ -132,7 +134,7 @@ pub(super) async fn proved_dpns_vote_choice( fn settle_broadcast_rejection( rejection: TaskError, requested: ResourceVoteChoice, - proved_current: Result, dash_sdk::Error>, + proved_current: Result, TaskError>, ) -> DpnsVoteAttempt { match proved_current { Ok(Some(current)) if current == requested => DpnsVoteAttempt::Confirmed, @@ -336,7 +338,7 @@ mod tests { for proved_current in [ Ok(None), Ok(Some(ResourceVoteChoice::Abstain)), - Err(dash_sdk::Error::Generic("unreachable".to_owned())), + Err(TaskError::DpnsCurrentVoteUnavailable), ] { assert!(matches!( settle_broadcast_rejection(rejection(), lock, proved_current), diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index e484ee9f1..83a75d52f 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -2181,7 +2181,7 @@ impl DPNSScreen { }) .cloned() .collect(); - (!targets.is_empty()).then(|| RelativeScheduleLabels { + (!targets.is_empty()).then_some(RelativeScheduleLabels { preset: self.relative_preset, targets, }) From 115fd2b813f3d50262cf57b1031359a8c41c8a72 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:28:00 +0000 Subject: [PATCH 146/194] docs(dpns): describe failure recency and the Scheduled view order Keeps VOTE-FR-084 and VOTE-FR-088 in step with the fixes for review findings RUST-005 and RUST-027. Co-Authored-By: Claude Fable 5.1 --- .../2026-07-16-dpns-voting-experience/01-requirements.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) 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 index c74dfb343..90ce30e67 100644 --- 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 @@ -251,7 +251,11 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. - **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`). + (`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.` @@ -324,7 +328,8 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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. + 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 From 4820dabd50ec9250aed565a3752a827cf373652d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 09:52:15 +0000 Subject: [PATCH 147/194] fix(migration): stop reading legacy scheduled votes in the app-data pass MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The app-data pass still decoded the legacy scheduled_votes table although its rows are never imported: a structurally damaged table failed the pass before the top-up history import ran, and undecodable rows raised a durable "could not be read" warning that told the user nothing the startup notice for old schedules does not already cover (it reports unreadable rows too). The pass now imports top-up history only. The unreadable-vote warning record, its error variant and the stale existing_votes rustdoc are gone; the durable-warning regressions are kept for the top-up warning. Review findings: PROJ-002 (migration half), DOC-002 (migration rustdoc). Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/backend_task/migration/finish_unwire.rs | 366 ++++++++------------ 1 file changed, 136 insertions(+), 230 deletions(-) diff --git a/src/backend_task/migration/finish_unwire.rs b/src/backend_task/migration/finish_unwire.rs index 527718d5b..4bdee2f90 100644 --- a/src/backend_task/migration/finish_unwire.rs +++ b/src/backend_task/migration/finish_unwire.rs @@ -215,7 +215,7 @@ pub enum MigrationError { }, /// 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")] @@ -245,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 { @@ -579,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 @@ -590,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 @@ -603,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`] @@ -738,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, }); @@ -750,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) => { @@ -773,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, }); @@ -790,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) => { @@ -832,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. @@ -851,37 +841,36 @@ 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, + votes: 0, + top_ups: top_ups_unreadable, }); } Ok(_) => { @@ -905,7 +894,7 @@ 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, @@ -942,22 +931,21 @@ 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, + votes: 0, + top_ups: top_ups_unreadable, }); return Ok(moved_data); } @@ -1268,68 +1256,10 @@ 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)?; @@ -1348,13 +1278,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 { @@ -1396,26 +1322,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 @@ -1528,7 +1441,7 @@ fn migrate_app_data(app_context: &Arc) -> Result) -> Result) -> Result( conn: &Connection, network: dash_sdk::dpp::dashcore::Network, @@ -1606,15 +1516,7 @@ where &std::collections::BTreeMap, ) -> Result<(), TaskError>, { - let mut outcome = AppDataMigrationOutcome { - votes_unreadable: crate::database::legacy_import::read_scheduled_votes(conn, network) - .map_err(|source| MigrationError::LegacyDbRead { - table: "scheduled_votes", - source, - })? - .unreadable, - ..Default::default() - }; + let mut outcome = AppDataMigrationOutcome::default(); let failure = match crate::database::legacy_import::read_top_ups(conn, network) { Ok(top_ups) => { @@ -2026,11 +1928,6 @@ fn table_has_rows(conn: &Connection, table: &'static str) -> Result Date: Tue, 6 Oct 2026 09:52:22 +0000 Subject: [PATCH 148/194] fix(dpns): make the Identities breadcrumb leave the request status page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The request status page is a pushed screen, but its root breadcrumb emitted SetMainScreen, which never clears the screen stack: the click refreshed the hidden hub and left the page on screen. Use OpenIdentityPicker like every sibling identity screen. Review finding: RUST-010. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/ui/identity/username_request_screen.rs | 5 +--- tests/kittest/identity_hub_switcher.rs | 28 ++++++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/ui/identity/username_request_screen.rs b/src/ui/identity/username_request_screen.rs index 0d7255675..a43448e8a 100644 --- a/src/ui/identity/username_request_screen.rs +++ b/src/ui/identity/username_request_screen.rs @@ -301,10 +301,7 @@ impl ScreenLike for UsernameRequestScreen { .map_or_else(|| self.normalized_label.clone(), |r| r.label); let crumb = format!("@{name}"); let breadcrumbs = vec![ - ( - "Identities", - AppAction::SetMainScreen(RootScreenType::RootScreenIdentityHub), - ), + ("Identities", AppAction::OpenIdentityPicker), (identity_label.as_str(), AppAction::PopScreen), (crumb.as_str(), AppAction::None), ]; 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| { From 4ca8bd5f805a90464a833f169daca88555bb3e95 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 09:52:32 +0000 Subject: [PATCH 149/194] fix(dpns): use identity-side tally labels and gate the voter link on vote ability MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The read-only tally on the request status page reused the operator's "Lock name" action label; it now shows the identity-side wording from the spec ("Lock, so no one gets it") from username_copy, dropping the dependency on ui::dpns copy. The "Your nodes can vote on this name" link was shown for any loaded voter identity, including a node without its voting key, and led to a Votes screen with no node able to vote. It now uses can_cast_masternode_vote, the same predicate the Votes screen filters with. Each timeline copy function also gets its own doc line. Review findings: RUST-007, RUST-029, RUST-032 (timeline docs). Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/ui/identity/username_copy.rs | 10 ++- src/ui/identity/username_request_screen.rs | 11 +-- tests/kittest/identity_usernames.rs | 82 +++++++++++++++++----- 3 files changed, 80 insertions(+), 23 deletions(-) diff --git a/src/ui/identity/username_copy.rs b/src/ui/identity/username_copy.rs index de764e30b..9fa44acdf 100644 --- a/src/ui/identity/username_copy.rs +++ b/src/ui/identity/username_copy.rs @@ -218,11 +218,12 @@ pub fn phase_label(phase: RequestPhase) -> &'static str { } } -/// Complete timeline sentences for the request status page. +/// 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!( @@ -237,6 +238,7 @@ pub fn joining_timeline_line(end: TimestampMillis, joining: bool) -> String { } } +/// Timeline sentence for when the community vote ends. pub fn voting_timeline_line(end: TimestampMillis, phase: RequestPhase) -> String { match phase { RequestPhase::Joinable => format!( @@ -272,6 +274,12 @@ pub fn request_result_line(phase: RequestPhase) -> &'static str { } } +/// 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 { diff --git a/src/ui/identity/username_request_screen.rs b/src/ui/identity/username_request_screen.rs index a43448e8a..aa658b09c 100644 --- a/src/ui/identity/username_request_screen.rs +++ b/src/ui/identity/username_request_screen.rs @@ -13,13 +13,16 @@ 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::{Tone, format_date_time, phase_label, what_happens_next}; +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}; @@ -169,11 +172,11 @@ impl UsernameRequestScreen { ui.label(votes.to_string()); ui.end_row(); } - ui.label(crate::ui::dpns::copy::vote_choice_label(dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice::Lock, None)); + ui.label(TALLY_LOCK_LABEL); ui.label(lock_standing); ui.label(tally.lock.to_string()); ui.end_row(); - ui.label(crate::ui::dpns::copy::vote_choice_label(dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice::Abstain, None)); + ui.label(TALLY_ABSTAIN_LABEL); ui.label(""); ui.label(tally.abstain.to_string()); ui.end_row(); @@ -266,7 +269,7 @@ impl ScreenLike for UsernameRequestScreen { .load_local_qualified_identities() .unwrap_or_default() .iter() - .any(|qi| qi.associated_voter_identity.is_some()); + .any(QualifiedIdentity::can_cast_masternode_vote); } fn refresh_on_arrival(&mut self) { diff --git a/tests/kittest/identity_usernames.rs b/tests/kittest/identity_usernames.rs index b8db0e0d1..0a6b14bac 100644 --- a/tests/kittest/identity_usernames.rs +++ b/tests/kittest/identity_usernames.rs @@ -473,7 +473,8 @@ fn request_status_page_explains_the_vote() { "Result: Not decided yet.", "Leading", "Other request (", - "Lock name", + "Lock, so no one gets it", + "Abstain", "Evonodes count as 4 votes.", "becomes yours automatically.", "the most recent request wins.", @@ -493,7 +494,46 @@ fn request_status_page_explains_the_vote() { }); } -/// USR-TC-030: a Power user with a voting node sees the link to vote. +/// 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(|| { @@ -502,22 +542,7 @@ fn request_status_page_links_voters() { app_context .store_username_requests(&id, vec![request("ali", RequestPhase::Voting)]) .expect("store request"); - let mut node = app_context - .load_local_user_identities() - .expect("identities") - .into_iter() - .find(|qi| qi.identity.id() == id) - .expect("seeded"); - let voter = Identity::create_basic_identity( - Identifier::from([0x31; 32]), - PlatformVersion::latest(), - ) - .expect("voter"); - let key = IdentityPublicKey::random_key(9, Some(9), PlatformVersion::latest()); - node.associated_voter_identity = Some((voter, key)); - app_context - .update_local_qualified_identity(&node) - .expect("store node"); + 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!( @@ -528,6 +553,27 @@ fn request_status_page_links_voters() { }); } +/// 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); From 788203ecac024a3fb35fdefcb6dcf0d90a4a6bac Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 09:56:54 +0000 Subject: [PATCH 150/194] fix(dpns): check the approved contest fee against the broadcast document MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The "unapproved contest fee" gate compared the approval with a fee derived from a label predicate over the bundled DPNS contract, while the document that is actually signed is classified separately from the context's contract and the SDK platform version. The two results were never compared, so a divergence could broadcast a contested document under a zero-fee approval. The gate now derives the required fee from the classification of the document being broadcast and still runs before any network call or payment. Review finding: SEC-004. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- .../identity/register_dpns_name.rs | 90 ++++++++++++------- 1 file changed, 58 insertions(+), 32 deletions(-) diff --git a/src/backend_task/identity/register_dpns_name.rs b/src/backend_task/identity/register_dpns_name.rs index 1b6385483..2699574e6 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, + validate_dpns_name, + }, + fee_estimation::contest_fee_credits, qualified_identity::DPNSNameInfo, }, }; @@ -20,6 +24,7 @@ use dash_sdk::{ identity::accessors::{IdentityGettersV0, IdentitySettersV0}, platform_value::Bytes32, util::{hash::hash_double, strings::convert_to_homograph_safe_chars}, + version::PlatformVersion, }, platform::Fetch, platform::{Document, transition::put_document::PutDocument}, @@ -39,6 +44,17 @@ fn rebrand_dpns_domain_conflict(error: TaskError) -> TaskError { } } +/// 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, @@ -50,32 +66,6 @@ impl AppContext { return Err(TaskError::InvalidDpnsName { validation }); } - let contest_fee = if crate::model::dpns::is_contested_label(&input.name_input) { - crate::model::fee_estimation::contest_fee_credits(sdk.version()) - } else { - 0 - }; - if input.approved_contest_fee != contest_fee { - 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, - input.qualified_identity.identity.id(), - &input.name_input, - ) - .await?; - if !availability.allows_registration() { - return Err(TaskError::UsernameNoLongerAvailable { availability }); - } - let joined_until = match availability { - UsernameAvailability::Joinable { join_end, .. } => Some(join_end), - _ => None, - }; - let mut rng = StdRng::from_entropy(); let dpns_contract = self.dpns_contract.clone(); @@ -180,6 +170,25 @@ impl AppContext { ) .map_err(|error| SdkError::Protocol(*error))?; + // 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 = match availability { + UsernameAvailability::Joinable { join_end, .. } => Some(join_end), + _ => None, + }; + let public_key = match input.signing_key_id { Some(key_id) => qualified_identity .identity @@ -250,7 +259,7 @@ impl AppContext { sdk: &Sdk, identity: crate::model::qualified_identity::QualifiedIdentity, name: &str, - outcome: crate::model::dpns::DpnsRegistrationOutcome, + outcome: DpnsRegistrationOutcome, joined_until: Option, balance_before: u64, estimated_fee: u64, @@ -258,7 +267,7 @@ impl AppContext { // 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 == crate::model::dpns::DpnsRegistrationOutcome::PendingCommunityVote + if outcome == DpnsRegistrationOutcome::PendingCommunityVote && let Err(error) = self.record_submitted_username_request(sdk, &identity_id, name, joined_until) { @@ -304,7 +313,7 @@ impl AppContext { if let Err(error) = self.edit_local_qualified_identity(&identity_id, |fresh| { if let Some(names) = refreshed_names { fresh.dpns_names = names; - } else if outcome == crate::model::dpns::DpnsRegistrationOutcome::Registered + } else if outcome == DpnsRegistrationOutcome::Registered && !fresh.dpns_names.iter().any(|known| known.name == name) { fresh.dpns_names.push(DPNSNameInfo { @@ -442,7 +451,7 @@ mod tests { &Sdk::new_mock(), stale, "alice-123", - crate::model::dpns::DpnsRegistrationOutcome::Registered, + DpnsRegistrationOutcome::Registered, None, 1_000, 100, @@ -462,7 +471,6 @@ mod tests { /// 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::DpnsRegistrationOutcome; use crate::model::dpns_usernames::RequestPhase; let dir = tempfile::tempdir().expect("tempdir"); let ctx = crate::context::test_support::test_app_context(dir.path()); @@ -542,6 +550,24 @@ mod tests { } } + /// 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 + ); + } + /// 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)] From 2c818022b87d3bb0cbf41152b79d6b7761772ea6 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 09:58:45 +0000 Subject: [PATCH 151/194] test(dpns): cover the pay-time availability guard before the contest fee MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The only backend test of the pay-time re-check exercised a failing network read, so deleting the allows_registration guard left every test green. Add mock-SDK cases proving a taken, locked, join-closed or already-requested name returns UsernameNoLongerAvailable before any broadcast, and that a request joining a running vote is saved with that vote's deadlines. The registered-name lookup query and the join-deadline accessor are extracted so the tests share them with production code; the test module's imports move above its first test. Review findings: RUST-006, RUST-032 (test-module imports). Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/backend_task/identity/dpns_usernames.rs | 12 +- .../identity/register_dpns_name.rs | 214 +++++++++++++++++- src/model/dpns_usernames.rs | 30 +++ 3 files changed, 243 insertions(+), 13 deletions(-) diff --git a/src/backend_task/identity/dpns_usernames.rs b/src/backend_task/identity/dpns_usernames.rs index bba5c9ba9..ca7971c1c 100644 --- a/src/backend_task/identity/dpns_usernames.rs +++ b/src/backend_task/identity/dpns_usernames.rs @@ -87,8 +87,9 @@ impl AppContext { }) } - async fn dpns_domain_exists(&self, sdk: &Sdk, normalized: &str) -> Result { - let query = DocumentQuery { + /// 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(), @@ -112,8 +113,11 @@ impl AppContext { limit: 1, offset: None, start: None, - }; - let documents = Document::fetch_many(sdk, query) + } + } + + 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)) diff --git a/src/backend_task/identity/register_dpns_name.rs b/src/backend_task/identity/register_dpns_name.rs index 2699574e6..bfb0415a7 100644 --- a/src/backend_task/identity/register_dpns_name.rs +++ b/src/backend_task/identity/register_dpns_name.rs @@ -31,9 +31,7 @@ use dash_sdk::{ }; use super::{BackendTaskSuccessResult, RegisterDpnsNameInput}; -use crate::model::dpns_usernames::{ - UsernameAvailability, dpns_signing_requirement, key_can_sign_documents, -}; +use crate::model::dpns_usernames::{dpns_signing_requirement, key_can_sign_documents}; fn rebrand_dpns_domain_conflict(error: TaskError) -> TaskError { match error { @@ -184,10 +182,7 @@ impl AppContext { if !availability.allows_registration() { return Err(TaskError::UsernameNoLongerAvailable { availability }); } - let joined_until = match availability { - UsernameAvailability::Joinable { join_end, .. } => Some(join_end), - _ => None, - }; + let joined_until = availability.join_deadline(); let public_key = match input.signing_key_id { Some(key_id) => qualified_identity @@ -344,6 +339,21 @@ impl AppContext { #[cfg(test)] mod tests { use super::*; + use crate::model::dpns::normalize_dpns_label; + 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::platform::Identifier; + use dash_sdk::query_types::{Contenders, Documents}; #[test] fn dpns_registration_needs_a_high_or_critical_key() { @@ -357,8 +367,6 @@ mod tests { .expect("DPNS"); assert_eq!(dpns_signing_requirement(&contract), SecurityLevel::HIGH); } - use dash_sdk::dpp::consensus::ConsensusError::StateError as ConsensusStateError; - use dash_sdk::dpp::consensus::state::state_error::StateError; fn duplicate_unique_index_conflict(properties: Vec<&str>) -> TaskError { let source_error = Box::new(crate::test_support::duplicate_unique_index_broadcast_error( @@ -568,6 +576,194 @@ mod tests { ); } + /// 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:?}" + ); + } + } + + /// 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)] diff --git a/src/model/dpns_usernames.rs b/src/model/dpns_usernames.rs index f88e69ea6..96b7c4db3 100644 --- a/src/model/dpns_usernames.rs +++ b/src/model/dpns_usernames.rs @@ -194,6 +194,14 @@ impl UsernameAvailability { 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. @@ -957,6 +965,28 @@ mod tests { ); } + #[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()); From 86a3cf07e399b79ad22cfe5f62da6a774e23c023 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:00:17 +0000 Subject: [PATCH 152/194] fix(dpns): never report a possibly paid username request as a plain failure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The name-request broadcast is broadcast-then-wait, so a timeout, transport or exhausted-address error can follow a transition a node already accepted. That error was propagated as an ordinary failure: the request was not recorded and the screen put the Pay step back with the same review, although the non-refundable community vote fee might already be spent. A failed name-request broadcast is now split by evidence, like the vote path. A refusal by the network (consensus cause) keeps its current error. Any other failure is reconciled first: if the vote state already lists the identity (or the name is already owned, for names without a vote) the registration continues as a success. Otherwise a dedicated UsernameRegistrationUnconfirmed error tells the user the request may have gone through and must not be paid for again yet, and the screen returns to the choose step, where a fresh availability check runs before any payment. A second contest fee for the same name was not reachable before this change either: the pay-time re-check returns AlreadyRequested once the first request is applied, and Platform admits one contender per identity per vote. The loss this closes is a user concluding the request failed and paying a second fee for a different name. Review finding: SEC-001. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/backend_task/error.rs | 10 + .../refresh_loaded_identities_dpns_names.rs | 45 ++-- .../identity/register_dpns_name.rs | 196 +++++++++++++++++- src/ui/identity/register_dpns_name_screen.rs | 8 +- tests/kittest/identity_usernames.rs | 28 +++ 5 files changed, 259 insertions(+), 28 deletions(-) diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 7ebde227b..4fb847ad3 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -2115,6 +2115,16 @@ pub enum TaskError { #[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." 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 e27336395..063f94208 100644 --- a/src/backend_task/identity/refresh_loaded_identities_dpns_names.rs +++ b/src/backend_task/identity/refresh_loaded_identities_dpns_names.rs @@ -53,7 +53,29 @@ impl AppContext { sdk: &dash_sdk::Sdk, identity_id: Identifier, ) -> Result, TaskError> { - let query = DocumentQuery { + 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(), @@ -70,26 +92,7 @@ impl AppContext { limit: 100, offset: None, start: None, - }; - let documents = - Document::fetch_many(sdk, query) - .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()) + } } } diff --git a/src/backend_task/identity/register_dpns_name.rs b/src/backend_task/identity/register_dpns_name.rs index bfb0415a7..3fd0fe094 100644 --- a/src/backend_task/identity/register_dpns_name.rs +++ b/src/backend_task/identity/register_dpns_name.rs @@ -7,7 +7,7 @@ use crate::{ model::{ dpns::{ DpnsNameValidationResult, DpnsRegistrationOutcome, classify_dpns_registration_outcome, - validate_dpns_name, + normalize_dpns_label, validate_dpns_name, }, fee_estimation::contest_fee_credits, qualified_identity::DPNSNameInfo, @@ -27,7 +27,7 @@ use dash_sdk::{ version::PlatformVersion, }, platform::Fetch, - platform::{Document, transition::put_document::PutDocument}, + platform::{Document, Identifier, transition::put_document::PutDocument}, }; use super::{BackendTaskSuccessResult, RegisterDpnsNameInput}; @@ -42,6 +42,18 @@ fn rebrand_dpns_domain_conflict(error: TaskError) -> TaskError { } } +/// Whether the network refused the transition, which proves it was not applied. +/// +/// Any other failure (a timeout, a dropped connection, no reachable node) can +/// follow a broadcast that did arrive, so it 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, @@ -214,7 +226,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(), @@ -225,7 +237,16 @@ impl AppContext { None, ) .await - .map_err(|error| rebrand_dpns_domain_conflict(TaskError::from(error)))?; + { + self.resolve_failed_domain_broadcast( + sdk, + qualified_identity.identity.id(), + &input.name_input, + outcome, + error, + ) + .await?; + } Ok(self .finish_username_registration( @@ -240,6 +261,59 @@ impl AppContext { .await) } + /// 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. A refusal keeps its own error. Anything else 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> { + if broadcast_was_rejected(&error) { + return Err(rebrand_dpns_domain_conflict(TaskError::from(error))); + } + if self + .username_request_reached_network(sdk, identity_id, name, outcome) + .await + { + tracing::warn!( + ?error, + %identity_id, + "Username registration reported an error, but the network shows the request; continuing as submitted" + ); + return Ok(()); + } + Err(TaskError::UsernameRegistrationUnconfirmed { + source_error: Box::new(error), + }) + } + + /// Whether the network shows `identity_id`'s request for `name`. A failed + /// read counts as not shown. + async fn username_request_reached_network( + &self, + sdk: &Sdk, + identity_id: Identifier, + name: &str, + outcome: DpnsRegistrationOutcome, + ) -> bool { + match outcome { + DpnsRegistrationOutcome::PendingCommunityVote => sdk + .get_contested_dpns_vote_state(&normalize_dpns_label(name), None) + .await + .is_ok_and(|vote| vote.contenders.contains_key(&identity_id)), + DpnsRegistrationOutcome::Registered => self + .fetch_owned_dpns_names(sdk, identity_id) + .await + .is_ok_and(|names| names.iter().any(|owned| owned.name == name)), + } + } + /// 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 @@ -339,7 +413,6 @@ impl AppContext { #[cfg(test)] mod tests { use super::*; - use crate::model::dpns::normalize_dpns_label; use crate::model::dpns_usernames::UsernameAvailability; use dash_sdk::dpp::block::block_info::BlockInfo; use dash_sdk::dpp::consensus::ConsensusError::StateError as ConsensusStateError; @@ -352,7 +425,6 @@ mod tests { use dash_sdk::drive::query::vote_poll_vote_state_query::{ ContestedDocumentVotePollDriveQuery, ContestedDocumentVotePollDriveQueryResultType, }; - use dash_sdk::platform::Identifier; use dash_sdk::query_types::{Contenders, Documents}; #[test] @@ -728,6 +800,118 @@ mod tests { } } + fn unproven_broadcast_failure() -> SdkError { + SdkError::TimeoutReached(std::time::Duration::from_secs(1), "no answer".to_owned()) + } + + /// A refusal by the network proves nothing was paid, so it 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 refused = crate::test_support::duplicate_unique_index_broadcast_error(vec![ + "normalizedParentDomainName", + "normalizedLabel", + ]); + + let result = ctx + .resolve_failed_domain_broadcast( + &Sdk::new_mock(), + Identifier::from([8; 32]), + "alice", + DpnsRegistrationOutcome::PendingCommunityVote, + refused, + ) + .await; + + assert!( + matches!(result, Err(TaskError::DpnsUsernameAlreadyTaken { .. })), + "{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 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)] diff --git a/src/ui/identity/register_dpns_name_screen.rs b/src/ui/identity/register_dpns_name_screen.rs index 616fc306e..2149a415d 100644 --- a/src/ui/identity/register_dpns_name_screen.rs +++ b/src/ui/identity/register_dpns_name_screen.rs @@ -779,7 +779,13 @@ impl ScreenLike for RegisterDpnsNameScreen { row: AvailabilityRow::Known(*availability), }; self.registration_error_handled = true; - } else if matches!(error, TaskError::UsernameRegistrationTermsChanged) { + } 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; diff --git a/tests/kittest/identity_usernames.rs b/tests/kittest/identity_usernames.rs index 0a6b14bac..b1a0699a9 100644 --- a/tests/kittest/identity_usernames.rs +++ b/tests/kittest/identity_usernames.rs @@ -211,6 +211,34 @@ fn pay_time_recheck_returns_to_choose_with_locked_row() { }); } +/// 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() { From 000fc0c770a9d34421a285c11b531c29ea8cf393 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:00:19 +0000 Subject: [PATCH 153/194] fix(dpns): keep a just-registered username when the follow-up read lags MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After an immediate registration the owned names were re-read and, when the read succeeded, replaced the identity's list wholesale. A node that had not yet seen the new name returned a list without it, so the paid name vanished from the identity while the result page reported success, and nothing re-added it until an unrelated owned-names refresh. The just-registered name is now added whenever the re-read list lacks it, not only when the re-read failed. Review finding: RUST-020. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- .../identity/register_dpns_name.rs | 43 ++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/src/backend_task/identity/register_dpns_name.rs b/src/backend_task/identity/register_dpns_name.rs index 3fd0fe094..972498c35 100644 --- a/src/backend_task/identity/register_dpns_name.rs +++ b/src/backend_task/identity/register_dpns_name.rs @@ -382,7 +382,10 @@ impl AppContext { if let Err(error) = self.edit_local_qualified_identity(&identity_id, |fresh| { if let Some(names) = refreshed_names { fresh.dpns_names = names; - } else if outcome == DpnsRegistrationOutcome::Registered + } + // 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 { @@ -546,6 +549,44 @@ mod tests { 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. From 61092dfc5c61df787cd239778dbf97f36b451cd9 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:02:37 +0000 Subject: [PATCH 154/194] fix(identity): delete identity keys even when the vote journal is unreadable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Identity removal cancelled the identity's pending DPNS votes with `?` before delisting it. That cancellation loads the whole vote journal, which fails closed when any single record cannot be read, so one damaged record blocked single-identity removal and the full-wipe key deletion for every identity on the network, with no repair path. The cancellation result is now carried into the removal cleanup instead of gating it: the identity is delisted and its vault keys are deleted, the outcome is reported as incomplete, and the retained cleanup manifest makes startup recovery retry the cancellation. The startup sweep follows the same rule, so an interrupted removal cannot be stuck behind the journal either. Deferring is safe: no vote runs from an unreadable journal, and a re-import still cancels before it relists the identity. Re-importing an unloaded identity keeps failing closed on purpose, since relisting it without cancelling would let an old schedule run again. Review finding: SEC-003. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/context/identity_db.rs | 99 +++++++++++++++++++++++++++++++++++--- 1 file changed, 91 insertions(+), 8 deletions(-) diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index cc5ff9a9b..a8984b9ec 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -63,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, @@ -1496,12 +1497,21 @@ impl AppContext { .dpns_vote_operation_guard .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - super::dpns_vote_operations::cancel_removed_identity_votes(&kv, self.network, *identifier)?; + // 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) @@ -1520,6 +1530,7 @@ 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); @@ -1543,6 +1554,11 @@ impl AppContext { "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); } @@ -1694,13 +1710,14 @@ impl AppContext { .dpns_vote_operation_guard .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - if let Err(error) = super::dpns_vote_operations::cancel_removed_identity_votes( + // 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), - ) - .and_then(|()| purge_identity_scope(&kv, &id)) - { + ); + if let Err(error) = purge_identity_scope(&kv, &id) { tracing::warn!( identity = %Identifier::from(id), %error, @@ -1711,7 +1728,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!( @@ -5340,6 +5357,72 @@ mod tests { 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; From 898407d6048815ac1b76a094ed87443f7f77a16b Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:03:39 +0000 Subject: [PATCH 155/194] fix(dpns): keep refreshing owned names past a removed or failing identity MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The owned-names refresh snapshots the loaded identities and then awaits a network read per identity, propagating every error with `?`. Removing one identity while it ran (IdentityNotFoundLocally on the write) or one failed read aborted the refresh for every later identity, skipped the UI refresh signal and raised an error for an identity the user had just removed. An identity removed since the snapshot is now skipped silently. Any other failure is remembered, the remaining identities are still refreshed, the refresh signal is still sent, and the first failure is reported at the end. Review finding: RUST-035. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- .../refresh_loaded_identities_dpns_names.rs | 145 +++++++++++++++++- 1 file changed, 138 insertions(+), 7 deletions(-) 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 063f94208..cd1d98ef8 100644 --- a/src/backend_task/identity/refresh_loaded_identities_dpns_names.rs +++ b/src/backend_task/identity/refresh_loaded_identities_dpns_names.rs @@ -18,19 +18,44 @@ impl AppContext { let sdk = self.sdk.load().as_ref().clone(); - for qualified_identity in qualified_identities { - let names = self - .fetch_owned_dpns_names(&sdk, qualified_identity.identity.id()) - .await?; - self.finish_owned_names_refresh(qualified_identity, names)?; - } + 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( @@ -160,4 +185,110 @@ mod tests { 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"]); + } } From b9a78d31c432774b746de0b66cc346cc7687a123 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:04:16 +0000 Subject: [PATCH 156/194] refactor(dpns): drop the unreachable DPNS source of the registration screen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tools > DPNS is gone, so production only ever opens the registration screen from the Identities hub. The Dpns variant was still the default and kept a "DPNS" breadcrumb and left-panel selection that only tests could reach. Remove the variant and its two match arms and point the kittests at the production path. The enum itself stays as the payload of ScreenType::RegisterDpnsName. Review finding: RUST-036. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/ui/identity/register_dpns_name_screen.rs | 29 ++++++-------------- tests/kittest/register_dpns_name_screen.rs | 7 +++-- 2 files changed, 12 insertions(+), 24 deletions(-) diff --git a/src/ui/identity/register_dpns_name_screen.rs b/src/ui/identity/register_dpns_name_screen.rs index 2149a415d..2c95c2ecf 100644 --- a/src/ui/identity/register_dpns_name_screen.rs +++ b/src/ui/identity/register_dpns_name_screen.rs @@ -49,11 +49,11 @@ use super::get_selected_wallet; /// Wait after the last keystroke before asking the network about a name. const AVAILABILITY_DEBOUNCE: Duration = Duration::from_millis(400); -/// Tracks where the user navigated from to reach this screen +/// 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, } @@ -861,26 +861,13 @@ impl ScreenLike for RegisterDpnsNameScreen { fn ui(&mut self, ui: &mut egui::Ui) -> AppAction { let ctx = ui.ctx().clone(); let identity_label = self.identity_label(); - let breadcrumbs = match self.source { - RegisterDpnsNameSource::Dpns => vec![ - ( - "DPNS", - AppAction::SetMainScreen(RootScreenType::RootScreenDPNSActiveContests), - ), - ("Get a username", AppAction::None), - ], - RegisterDpnsNameSource::Identities => vec![ - ("Identities", AppAction::OpenIdentityPicker), - (identity_label.as_str(), AppAction::PopScreen), - ("Get a username", AppAction::None), - ], - }; + 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![]); - let root_screen = match self.source { - RegisterDpnsNameSource::Dpns => RootScreenType::RootScreenDPNSActiveContests, - RegisterDpnsNameSource::Identities => RootScreenType::RootScreenIdentityHub, - }; - action |= add_left_panel(ui, &self.app_context, root_screen); + action |= add_left_panel(ui, &self.app_context, RootScreenType::RootScreenIdentityHub); action |= island_central_panel(ui, |ui| { let mut inner = AppAction::None; diff --git a/tests/kittest/register_dpns_name_screen.rs b/tests/kittest/register_dpns_name_screen.rs index d145da7b1..817cfa776 100644 --- a/tests/kittest/register_dpns_name_screen.rs +++ b/tests/kittest/register_dpns_name_screen.rs @@ -39,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. @@ -177,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 @@ -197,7 +197,8 @@ fn dpns_registration_error_clears_overlay() { 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::Dpns); + 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 { From 701ee430b1bfc1a07521eb35835b4558ca4c3ada Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:05:21 +0000 Subject: [PATCH 157/194] test(dpns): pin contest durations across the versions the SDK can report MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Contest timing is derived from the compile-time platform pin on the voting side and from the live SDK version on the identity side. The SDK is seeded at the pin and only ratchets upward, and the duration tables are identical for every version this build knows, so both sides describe the same windows today. Assert that equality for every protocol version from the pin to the newest known one, so a platform bump that changes a window fails here and forces the two sides onto one source instead of diverging silently. Review finding: RUST-034 (no divergence is reachable in this build). Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/context/mod.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/context/mod.rs b/src/context/mod.rs index 01cc99e54..721a83271 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -1820,6 +1820,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; From 4df6f205461786c4744ec169c8fae0281a304497 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:05:40 +0000 Subject: [PATCH 158/194] docs(dpns): align username model docs with the code they describe MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit username_request_from_contest documented a `label` parameter that is named normalized_label, and computed the contest start and join deadline twice; the values are now computed once and reused. suggest_uncontested claimed to append "a digit from 2 to 9" while its suffix table also holds hyphenated, two-digit and four-digit suffixes. Review findings: RUST-032, DOC-002 (suggest_uncontested). Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/model/dpns.rs | 5 +++-- src/model/dpns_usernames.rs | 10 +++++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/model/dpns.rs b/src/model/dpns.rs index 6422f51fe..aa238883b 100644 --- a/src/model/dpns.rs +++ b/src/model/dpns.rs @@ -137,8 +137,9 @@ 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 digit from 2 to 9, which takes the name out of the -/// contested rule. Returns an empty list when `label` has no usable base. +/// 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('-'); diff --git a/src/model/dpns_usernames.rs b/src/model/dpns_usernames.rs index 96b7c4db3..b5237226a 100644 --- a/src/model/dpns_usernames.rs +++ b/src/model/dpns_usernames.rs @@ -460,7 +460,8 @@ impl UsernameRequest { /// /// 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. `label` is the fallback when no contender document carries it. +/// 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, @@ -473,6 +474,8 @@ pub fn username_request_from_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, @@ -480,8 +483,6 @@ pub fn username_request_from_contest( Some(ContestWinner::Identity(_)) => RequestPhase::Lost, None => { mine?; - let start = contest.started_at(); - let join_end = start.map(|s| s.saturating_add(duration_ms(durations.join))); if join_end.is_some_and(|end| now < end) { RequestPhase::Joinable } else { @@ -489,7 +490,6 @@ pub fn username_request_from_contest( } } }; - let start = contest.started_at(); let tally = RequestTally { you: mine.map_or(0, |c| c.votes), others: contest @@ -508,7 +508,7 @@ pub fn username_request_from_contest( normalized_label: normalized_label.to_owned(), phase, requested_at: mine.and_then(|c| c.created_at), - join_end: start.map(|s| s.saturating_add(duration_ms(durations.join))), + join_end, end: end_time.or_else(|| start.map(|s| s.saturating_add(duration_ms(durations.total)))), decided_at: contest.decided_at, tally, From 1183e588d485097b0dacce4cd1f9d1a1d7ce2f1f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:07:24 +0000 Subject: [PATCH 159/194] docs(dpns): document the vote journal and username keys, retire scheduled-vote keys MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docs/kv-keys.md still described det:scheduled_vote:* and det:scheduled_vote_voters:v1 as live keys and had no entry for any key this change introduces. Mark the scheduled-vote keys (and the migration's unreadable-vote warning key) as retired and never read, and add the DPNS vote journal and identity-side username key families with scope, store, value type and source file. Also unlink a private constant from the suggest_uncontested rustdoc. Review finding: DOC-001. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- docs/kv-keys.md | 50 ++++++++++++++++++++++++++++++++++++++++------- src/model/dpns.rs | 2 +- 2 files changed, 44 insertions(+), 8 deletions(-) diff --git a/docs/kv-keys.md b/docs/kv-keys.md index 66a63a066..2fca950ff 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,52 @@ 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. + +--- + +## 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_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 | + +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` + +--- + +## 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` | 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` | +| `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/src/model/dpns.rs b/src/model/dpns.rs index aa238883b..8eb55751e 100644 --- a/src/model/dpns.rs +++ b/src/model/dpns.rs @@ -137,7 +137,7 @@ 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 +/// 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 { From 3fd15849de46c8a1a9850373ef9d9373fa449daf Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:07:24 +0000 Subject: [PATCH 160/194] docs(changelog): describe DPNS voting and usernames by what users observe MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Fixed block listed five fixes to behaviour that only existed between review rounds of this change and never shipped; their user-visible facts are folded into the two Added entries and the rest are dropped. Sentences about rendering, frame scheduling and journal passes are removed. State the pre-release cut-off for scheduled votes: schedules saved by an earlier development build used a storage format that is no longer read, so they are neither carried over nor listed by the startup notice. Mention that an unconfirmed username request is reported as such rather than as a failure. Review findings: PROJ-005, RUST-009. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 48 +++++++++++++++++++++--------------------------- 1 file changed, 21 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index be069fb32..e1db6f8fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -155,7 +155,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). 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, node counts and timing. Node details show remaining + 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 @@ -165,33 +166,34 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). 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 - without reading storage during rendering. Decisions staged or changed during - submission survive its completion. Uncertain votes stay visible and blocked from resubmission; - passing the estimated deadline alone does not release them. Completed - history is bounded without discarding unresolved votes. Removing a node - cancels its unstarted scheduled votes. + 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. 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. Refresh bursts yield between frames, and unresolved counts - use one pass through the vote journal. History has a final β€œdetails” column - that opens the contest in Platform Explorer on Mainnet or Testnet. + 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; - returning from a top-up preserves the chosen name and payment review. + 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. Refresh preserves concurrent identity edits and finished - outcomes when an older refresh completes, and keeps the previous request - snapshot when storage cannot be read. Removed identities disappear immediately - from username views; failed record cleanup is retried after restarting. + 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 @@ -209,18 +211,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed -- Closed contests keep uncertain vote outcomes instead of reporting them as failed - when Platform has removed the voting records. Progress updates during submission, - and entering Votes reloads newly added voting nodes without changing staged choices. -- Username refreshes skip identities removed while a request was in flight and report - local storage errors while retaining successful updates for other identities. - -- Username request updates preserve saved requests after a failed startup read, and - status refreshes complete when the request page is hidden behind registration. -- Voting confirmation and schedule choices expose full contender identities; - scheduled votes use consistent node handles and explicit UTC timestamps. -- Voting views share outcome selection and reuse scheduled decision groups between refreshes. - - Restoring imported keys remains recoverable after interrupted storage writes and reports unreadable protected keys. Startup migration preserves existing keys, seeds, and their password protection. @@ -915,6 +905,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - 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 users to review and cast or schedule those votes again. + 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 that notice does not list them, 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; From 9abb1089d46e65bfa2a3c1e85832355d66c007ed Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:08:42 +0000 Subject: [PATCH 161/194] docs(dpns): make platform-facts portable and mark resolved contradictions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every citation was relative to one machine's cargo checkout path; state the paths relative to the dashpay/platform repository at the pinned commit instead. The closing section described, in the present tense, two defects this change removed; retitle it as the pre-redesign state and say which items are resolved. Review finding: PROJ-006. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- .../2026-10-01-usernames-redesign/platform-facts.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) 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 index 46ef0ab38..27c04f6ae 100644 --- a/docs/ai-design/2026-10-01-usernames-redesign/platform-facts.md +++ b/docs/ai-design/2026-10-01-usernames-redesign/platform-facts.md @@ -1,7 +1,7 @@ # DPNS usernames & contested-resource voting β€” platform facts Source: dashpay/platform @ `9f7ed16935bd540e4c2a542688800d2953f9f67a` (DET pin). Paths are relative to -`/home/ubuntu/.cargo/git/checkouts/platform-7a21f318038a582f/9f7ed16/packages/`. +`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. @@ -104,11 +104,13 @@ Abbreviations: PV = protocol version; "testing" = any network != Mainnet (testne - 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 +## Contradictions with DET before the redesign -1. `src/ui/identity/register_dpns_name_screen.rs:539` hard-codes "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`. +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` lives in `ui/` (`register_dpns_name_screen.rs:678`) β€” duplicates the contract regex; placement policy wants `model/`, ideally delegating to the contract's `field_matches`. +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. From fb8f3e331b6abb776e5c6a76dd026a4cc0655da7 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:08:42 +0000 Subject: [PATCH 162/194] docs(dpns): align the usernames spec and user stories with the shipped model MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The requirements, test-case spec and user stories described a smaller state model than the code implements. Document what ships: the header shows the request's actual status rather than always "Waiting for vote"; requests can also be awaiting a result or end without a winner; availability can report that the identity already asked for the name; discovery re-reads saved requests and then scans the running contests; and an unconfirmed name request is reported as such instead of as a failure. The model test for registration-blocking results now includes the already-requested case the spec lists. Review finding: PROJ-001. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- .../01-requirements.md | 50 ++++++++++++++----- .../03-test-case-spec.md | 9 ++-- docs/user-stories.md | 11 ++-- src/model/dpns_usernames.rs | 1 + 4 files changed, 51 insertions(+), 20 deletions(-) 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 index 483257006..a78af1cbb 100644 --- a/docs/ai-design/2026-10-01-usernames-redesign/01-requirements.md +++ b/docs/ai-design/2026-10-01-usernames-redesign/01-requirements.md @@ -31,9 +31,10 @@ Scope: identity-side usernames. Voting is Stream V in this order: - main name, then other active names; - pending requests: `Open for other requests` during the join window, - `Waiting for vote` after it; + `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`. + `Locked for good`, `No one got it`. - **AC:** - Given an identity owning `@a` with a pending request `@b`, both rows render. @@ -57,8 +58,9 @@ Scope: identity-side usernames. Voting is Stream V in 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 `@{name} Β· Waiting for vote` - when the identity has no active name. +- **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.` @@ -70,18 +72,28 @@ Scope: identity-side usernames. Voting is Stream V in 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): - - uses `get_non_resolved_dpns_contests_for_identity` + `get_contested_dpns_vote_state`; - - returns per identity a `Vec`; + - 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. - **AC:** an identity owning a name still reports its pending requests. A - finished contest yields Won/Lost/Locked. + 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 @@ -92,7 +104,8 @@ Scope: identity-side usernames. Voting is Stream V in 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. Last updated {time}.`; + `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; @@ -109,7 +122,9 @@ Scope: identity-side usernames. Voting is Stream V in 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`. It combines the awarded-domain lookup with + 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). @@ -124,6 +139,8 @@ Scope: identity-side usernames. Voting is Stream V in - `@{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. @@ -160,7 +177,8 @@ Scope: identity-side usernames. Voting is Stream V in 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, return to U4 with that row; nothing is spent. + 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}`; @@ -168,7 +186,15 @@ Scope: identity-side usernames. Voting is Stream V in 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`). + `with_details`); + - unconfirmed: when the name request was sent but neither a refusal nor the + request itself can be read back from the network, the fee may already be + spent. The app first re-reads the vote (or the owned names) and continues + as a success if the request is there. 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 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 index 2bb771b90..35734d718 100644 --- 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 @@ -26,8 +26,11 @@ Stream V test cases live in `../2026-07-16-dpns-voting-experience/03-test-case-s | 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 | Phases Won / Lost / Locked with dates | FR-020 | B | -| USR-TC-018 | Re-check on pay | Check said NeedsVote; at pay time Locked | Registration not dispatched; U4 shows locked row | FR-037 | B+K | +| 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 | ## UI (kittest) @@ -38,7 +41,7 @@ Stream V test cases live in `../2026-07-16-dpns-voting-experience/03-test-case-s | 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} Β· Waiting for vote` | FR-010 | +| 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 | diff --git a/docs/user-stories.md b/docs/user-stories.md index 7168287bc..8417f56a9 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -804,19 +804,20 @@ As a user, I want to remove an identity from this device from the identity's own 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. - 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 Β· can't check. Only the first three allow continuing. Contested and locked names are never reported as available. +- 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 my usernames [Implemented] **Persona:** Alex, Priya 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. -- 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). +- 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. @@ -902,7 +903,7 @@ As a masternode operator, I want to be told when an upgrade cannot carry over my 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. -- The header subtitle reads `@name Β· Waiting for vote` when the identity has no active name. The Home card and Profile row show every pending request. +- 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. @@ -924,8 +925,8 @@ As a user waiting for a community vote, I want to see how my request is doing an - 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) are announced once with a banner and stay in Profile for 30 days. -- Power users whose nodes can vote on the contest get a link to Masternodes β–Έ Votes for that name. +- 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 diff --git a/src/model/dpns_usernames.rs b/src/model/dpns_usernames.rs index b5237226a..d38efdfe7 100644 --- a/src/model/dpns_usernames.rs +++ b/src/model/dpns_usernames.rs @@ -1002,6 +1002,7 @@ mod tests { UsernameAvailability::JoinClosed, UsernameAvailability::Taken, UsernameAvailability::Locked, + UsernameAvailability::AlreadyRequested, ] { assert!(!blocked.allows_registration(), "{blocked:?}"); } From 2cd51ffe68fa47cba2d6b855a82c88d431170436 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:09:06 +0000 Subject: [PATCH 163/194] docs(migration): describe the app-data step as top-up history only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The migration step and task docs still said the app-data pass imports scheduled DPNS votes and retires unreadable-vote warnings. Describe what the pass does now and mark the unreadable-vote counter of the terminal state as always zero, with a TODO for removing it together with its banner copy and MCP field. Review finding: PROJ-002 (migration half). Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/backend_task/migration/mod.rs | 4 ++-- src/context/migration_status.rs | 8 ++++++-- 2 files changed, 8 insertions(+), 4 deletions(-) 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/context/migration_status.rs b/src/context/migration_status.rs index 66d3afe5f..1c8c4b8fa 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, @@ -124,6 +124,10 @@ pub enum MigrationState { /// identifies the recovery instructions the banner must show. SucceededWithUnreadableData { identities: u32, + /// Always `0`: the storage update does not read legacy scheduled votes; + /// the startup notice for old schedules reports them instead. + // TODO(dpns): remove this counter together with its banner copy and + // the MCP `votes` field; nothing produces a non-zero value. votes: u32, top_ups: u32, }, From 9a54a4ae8ddb2a999cb1e9497d4464badccd2f6d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:14:04 +0000 Subject: [PATCH 164/194] docs(migration): stop describing unreadable scheduled votes as an upgrade report MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The upgrade no longer reads legacy scheduled votes, so it cannot report them as unreadable. The identity-preservation story now names the report that can still combine with unreadable identities (balance top-up records) and points to the story covering old schedules. A test comment no longer names a screen the vote copy has stopped using. Review finding: PROJ-002 (migration half). Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- docs/user-stories.md | 2 +- tests/kittest/migration_banner.rs | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/user-stories.md b/docs/user-stories.md index 8417f56a9..62db3213c 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -753,7 +753,7 @@ As a user, I want the identities I loaded before an upgrade β€” and the keys the - 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 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] diff --git a/tests/kittest/migration_banner.rs b/tests/kittest/migration_banner.rs index 976d713e6..7d2bed7b6 100644 --- a/tests/kittest/migration_banner.rs +++ b/tests/kittest/migration_banner.rs @@ -213,8 +213,7 @@ 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 [ From 8a9b9d263bd050b97f1c308b5040ad4709a6dc7d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:30:07 +0000 Subject: [PATCH 165/194] docs(dpns): document when the old-schedule startup notice stops MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The startup notice for schedules left in the previous SQLite storage now records when it was first due and stops one contest duration later. Add its key to the k/v reference and the behaviour to the user story. Describes behaviour introduced on the voting fix branch (src/context/legacy_scheduled_votes.rs); apply together with it. Review finding: DOC-001. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- docs/kv-keys.md | 8 +++++++- docs/user-stories.md | 1 + 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/kv-keys.md b/docs/kv-keys.md index 2fca950ff..c9abaa587 100644 --- a/docs/kv-keys.md +++ b/docs/kv-keys.md @@ -117,7 +117,13 @@ These keys are **retired**. No current code reads or writes them; scheduled vote | `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. +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` --- diff --git a/docs/user-stories.md b/docs/user-stories.md index 62db3213c..f53d248eb 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -894,6 +894,7 @@ As a masternode operator, I want to be told when an upgrade cannot carry over my - Startup checks for unexecuted schedules in the previous SQLite storage on the selected network. - A persistent, dismissible notice directs me to Masternodes β†’ Votes to make a new decision. +- The notice stops appearing one full voting period after it was first shown, because every vote an old schedule could refer to has ended by then. - Old schedules are neither imported 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. From a44a15dc10bbe075b0fec7359e8fd5ea58c82389 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:58:24 +0000 Subject: [PATCH 166/194] fix(dpns): show an immediate vote that restart recovery stopped Restart recovery turns an old queued immediate vote, or a recovered first vote that became a change, into "Not submitted". The progress drawer and "Needs attention" date an immediate vote by its operation's creation time, which always precedes the session that runs recovery, so the stopped vote appeared nowhere and its "Review again" action was unreachable. Recovery now records when it stopped each immediate target in a display sidecar next to the operation (same lifecycle as the relative schedule labels; the vote record format is unchanged), and the recency rule uses that time. A later session treats it as old history again. Addresses review finding PROJ-001. Co-Authored-By: Claude Fable 5.1 --- .../01-requirements.md | 4 +- src/context/dpns_vote_operations/keys.rs | 7 + src/context/dpns_vote_operations/mod.rs | 120 +++++++++++++++++- src/context/dpns_vote_operations/retention.rs | 8 +- src/model/dpns_voting/mod.rs | 6 + src/model/dpns_voting/progress.rs | 38 +++++- 6 files changed, 174 insertions(+), 9 deletions(-) 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 index 90ce30e67..c34d2b757 100644 --- 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 @@ -235,7 +235,9 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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. A recovered immediate vote that was reviewed as a first + shown as missed. The stopped immediate vote is dated by when recovery stopped + it, so the progress drawer and `Needs attention` of that session list it 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, diff --git a/src/context/dpns_vote_operations/keys.rs b/src/context/dpns_vote_operations/keys.rs index e12f7de09..f3aa94aba 100644 --- a/src/context/dpns_vote_operations/keys.rs +++ b/src/context/dpns_vote_operations/keys.rs @@ -14,6 +14,7 @@ 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_STOP_KEY_PREFIX: &str = "det:dpns_vote_recovery_stops: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:"; @@ -64,3 +65,9 @@ pub(super) fn unreadable_operation_err(source: KvAdapterError) -> TaskError { pub(super) fn relative_labels_key(operation_key: &str) -> String { operation_key.replacen(OPERATION_KEY_PREFIX, RELATIVE_LABEL_KEY_PREFIX, 1) } + +/// When restart recovery stopped an operation's immediate targets; one +/// display record per operation, owned by the same retention lifecycle. +pub(super) fn recovery_stops_key(operation_key: &str) -> String { + operation_key.replacen(OPERATION_KEY_PREFIX, RECOVERY_STOP_KEY_PREFIX, 1) +} diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index 782e6e5ad..4a2b4056a 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -16,8 +16,8 @@ use crate::backend_task::error::TaskError; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduledVoteClearDisposition, DpnsScheduledVoteClearOutcome, DpnsScheduledVoteEdit, DpnsScheduledVoteKey, DpnsVoteFailure, DpnsVoteOperation, - DpnsVoteOperationId, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, - authoritative_dpns_vote_outcomes, failed_before_broadcast_outcome, + DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, + VoteTiming, authoritative_dpns_vote_outcomes, failed_before_broadcast_outcome, unavailable_preflight_outcome, }; use crate::utils::time::now_ms; @@ -57,9 +57,60 @@ fn load_operation( Ok(None) => {} Err(error) => tracing::debug!(?error, "Relative schedule labels unreadable"), } + if operation.targets.iter().any(stoppable_by_recovery) { + match kv.get::(DetScope::Global, &recovery_stops_key(key)) { + Ok(Some(stops)) => { + for outcome in &mut operation.targets { + if stoppable_by_recovery(outcome) { + outcome.stopped_by_recovery_at_ms = stops.get(&outcome.target.key).copied(); + } + } + } + Ok(None) => {} + Err(error) => tracing::debug!(?error, "Vote recovery stop times unreadable"), + } + } Ok(Some(operation)) } +/// When restart recovery stopped each immediate target of one operation, Unix ms. +type RecoveryStops = BTreeMap; + +/// Whether `outcome` is in the state restart recovery leaves a stopped +/// immediate vote in. +fn stoppable_by_recovery(outcome: &DpnsVoteOutcome) -> bool { + outcome.status == DpnsVoteTargetStatus::FailedBeforeSubmission + && outcome.target.timing == VoteTiming::Now +} + +/// Record that restart recovery stopped `keys` of an operation at `at_ms`. +/// +/// Display metadata, like the relative labels: a failed write is logged and +/// never fails the journal transition it describes. Callers hold the journal +/// guard. +fn save_recovery_stops( + kv: &DetKv, + network: Network, + operation_id: DpnsVoteOperationId, + keys: &[DpnsVoteTargetKey], + at_ms: u64, +) { + if keys.is_empty() { + return; + } + let key = recovery_stops_key(&operation_key(network, operation_id)); + let result = kv + .get::(DetScope::Global, &key) + .and_then(|stops| { + let mut stops = stops.unwrap_or_default(); + stops.extend(keys.iter().cloned().map(|key| (key, at_ms))); + kv.put(DetScope::Global, &key, &stops) + }); + if let Err(error) = result { + tracing::debug!(?error, "Could not save vote recovery stop times"); + } +} + fn save_relative_presets(kv: &DetKv, network: Network, operation: &DpnsVoteOperation) { let labels: RelativeSchedulePresets = operation .targets @@ -773,7 +824,8 @@ impl AppContext { state: DpnsCurrentVoteState, ) -> Result { self.mutate_dpns_vote_operation(operation_id, |kv| { - Ok(with_target(kv, self.network, operation_id, key, |outcome| { + let mut stopped = false; + let still_queued = with_target(kv, self.network, operation_id, key, |outcome| { if outcome.status != DpnsVoteTargetStatus::Queued { return TargetUpdate::Skip(false); } @@ -800,9 +852,22 @@ impl AppContext { unavailable_preflight_outcome(outcome.target.timing); } } + stopped = stoppable_by_recovery(outcome); TargetUpdate::Persist(outcome.status == DpnsVoteTargetStatus::Queued) })? - .unwrap_or(false)) + .unwrap_or(false); + if stopped { + // An immediate target is only ever revalidated here when a + // restart left it queued, so its operation predates the session. + save_recovery_stops( + kv, + self.network, + operation_id, + std::slice::from_ref(key), + now_ms(), + ); + } + Ok(still_queued) }) } @@ -815,10 +880,24 @@ impl AppContext { let (_guard, kv) = self.journal()?; let now_ms = now_ms(); for mut operation in load_operations(&kv, self.network)? { + let already_stopped: BTreeSet = operation + .targets + .iter() + .filter(|outcome| stoppable_by_recovery(outcome)) + .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)?; + let stopped: Vec = operation + .targets + .iter() + .filter(|outcome| stoppable_by_recovery(outcome)) + .map(|outcome| outcome.target.key.clone()) + .filter(|key| !already_stopped.contains(key)) + .collect(); + save_recovery_stops(&kv, self.network, operation.id, &stopped, now_ms); } } prune_completed_history(&kv, self.network, None, HistoryKind::Immediate)?; @@ -2396,6 +2475,7 @@ mod tests { 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(); @@ -2413,6 +2493,34 @@ mod tests { None, "nothing was broadcast, so the target is free to be voted again" ); + assert!( + recovered.targets[0] + .stopped_by_recovery_at_ms + .is_some_and(|stopped| stopped >= 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) @@ -2464,6 +2572,10 @@ mod tests { saved.targets[0].status, DpnsVoteTargetStatus::FailedBeforeSubmission ); + assert!( + saved.targets[0].stopped_by_recovery_at_ms.is_some(), + "the operator must be told the vote was stopped" + ); assert_eq!(ctx.dpns_vote_target_status(&key).unwrap(), None); let mut reviewed_change = operation(DpnsVoteTargetStatus::Queued); diff --git a/src/context/dpns_vote_operations/retention.rs b/src/context/dpns_vote_operations/retention.rs index dd19073f4..cd3d5d4e7 100644 --- a/src/context/dpns_vote_operations/retention.rs +++ b/src/context/dpns_vote_operations/retention.rs @@ -183,7 +183,8 @@ pub(super) fn prune_orphaned_schedule_dismissals( .filter_map(|key| key.strip_prefix(&operation_prefix).map(str::to_owned)) .collect::>(); let relative_prefix = format!("{RELATIVE_LABEL_KEY_PREFIX}{}:", network_prefix(network)); - for prefix in [dismissal_prefix, relative_prefix] { + let recovery_stop_prefix = format!("{RECOVERY_STOP_KEY_PREFIX}{}:", network_prefix(network)); + for prefix in [dismissal_prefix, relative_prefix, recovery_stop_prefix] { for key in kv .list(DetScope::Global, Some(&prefix)) .map_err(unreadable_operation_err)? @@ -220,6 +221,11 @@ pub(super) fn delete_terminal_operations( &relative_labels_key(&operation_key(network, *id)), ) .map_err(operation_err)?; + kv.delete( + DetScope::Global, + &recovery_stops_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)) diff --git a/src/model/dpns_voting/mod.rs b/src/model/dpns_voting/mod.rs index 2af369805..ac25353d8 100644 --- a/src/model/dpns_voting/mod.rs +++ b/src/model/dpns_voting/mod.rs @@ -295,6 +295,11 @@ pub struct DpnsVoteOutcome { /// Excluded from the established binary vote record format. #[serde(skip)] pub relative_schedule_preset_ms: Option, + /// When restart recovery stopped this immediate vote before it was sent, + /// in Unix ms. Display-only and hydrated like the preset: it lets the + /// session that stopped the vote report it, although the vote is older. + #[serde(skip)] + pub stopped_by_recovery_at_ms: Option, } /// Reviewed voting batch stored before its first broadcast. @@ -328,6 +333,7 @@ impl DpnsVoteOperation { status, failure: None, relative_schedule_preset_ms: None, + stopped_by_recovery_at_ms: None, } }) .collect::>(); diff --git a/src/model/dpns_voting/progress.rs b/src/model/dpns_voting/progress.rs index a919fb3e7..5fde2a313 100644 --- a/src/model/dpns_voting/progress.rs +++ b/src/model/dpns_voting/progress.rs @@ -80,12 +80,16 @@ pub fn progress_counts<'a>( /// 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. +/// therefore counts as recent once it runs in this one, and so does a vote +/// from an earlier session that restart recovery stopped in this one. fn sent_at(operation: &DpnsVoteOperation, outcome: &DpnsVoteOutcome) -> u64 { - match outcome.target.timing { + let sent = match outcome.target.timing { VoteTiming::Scheduled(at) => at.max(operation.created_at), VoteTiming::Now => operation.created_at, - } + }; + outcome + .stopped_by_recovery_at_ms + .map_or(sent, |stopped| stopped.max(sent)) } /// Operations the drawer lists: anything still in flight, plus operations @@ -347,6 +351,34 @@ mod tests { assert!(drawer_operations(&operations, session_start, &dismissed).is_empty()); } + /// An immediate vote left over from an earlier session and stopped by + /// restart recovery is this session's news: the operator must see it as + /// not submitted and be able to review it again. + #[test] + fn a_vote_stopped_by_restart_recovery_is_surfaced_in_the_new_session() { + let session_start = 1_000; + let mut stopped = operation(10, &[(S::FailedBeforeSubmission, NOW)]); + stopped.targets[0].stopped_by_recovery_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)]); From ff16151f7b086ae4eeb4f5d9ee0418b4820342be Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:01:17 +0000 Subject: [PATCH 167/194] fix(dpns): do not skip a vote as already cast on proof too old to decide The longer display freshness also fed the confirm step, so proof up to two refresh intervals old could conclude "this node already votes this way" and drop the target. A dropped target never reaches the backend's fresh preflight, so a vote changed elsewhere in that window stayed on the other choice while the plan said nothing was needed. The stored state now carries when it was proved. On proof older than the 120 s submission cap the composer sends the target without a reviewed current choice: preflight confirms a true no-op without broadcasting and asks for another review when the vote has changed. The tray count follows the same rule. Cards and the attention signal keep the long window. The "no changes left" skip is unchanged: it rests on this device's durable count of confirmed votes, which proof age cannot invalidate. Addresses review finding SEC-001. Co-Authored-By: Claude Fable 5.1 --- .../01-requirements.md | 4 ++ src/context/dpns_vote_state.rs | 50 +++++++++++++--- src/model/dpns_voting/composer.rs | 52 +++++++++++++++- src/model/dpns_voting/operator.rs | 32 ++++++++++ src/ui/dpns/dpns_contested_names_screen.rs | 59 ++++++++++++++++++- src/ui/state/dpns_vote_state.rs | 25 +++++--- 6 files changed, 202 insertions(+), 20 deletions(-) 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 index c34d2b757..2f871973b 100644 --- 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 @@ -128,6 +128,10 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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. - **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). diff --git a/src/context/dpns_vote_state.rs b/src/context/dpns_vote_state.rs index 7d314b0d4..5fe5f8dbc 100644 --- a/src/context/dpns_vote_state.rs +++ b/src/context/dpns_vote_state.rs @@ -19,7 +19,8 @@ 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 = 120_000; +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 { @@ -143,21 +144,36 @@ fn snapshot_vote_state( 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)); + return ( + DpnsCurrentVoteState::Available(Some(*choice)), + Some(*updated_at), + ); } match snapshot { - None => DpnsCurrentVoteState::Checking, + None => (DpnsCurrentVoteState::Checking, None), Some(snapshot) if checked_at_ms.saturating_sub(snapshot.updated_at) > max_age_ms => { - DpnsCurrentVoteState::Checking - } - Some(snapshot) if !snapshot.available => DpnsCurrentVoteState::Unavailable, - Some(snapshot) => { - DpnsCurrentVoteState::Available(snapshot.votes.get(&vote_poll_id.to_buffer()).copied()) + (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), + ), } } @@ -347,6 +363,22 @@ impl AppContext { 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(); @@ -355,7 +387,7 @@ impl AppContext { .map(|vote_poll_id| { ( vote_poll_id, - snapshot_vote_state(snapshot.as_ref(), vote_poll_id, checked_at_ms, max_age_ms), + proved_vote_state(snapshot.as_ref(), vote_poll_id, checked_at_ms, max_age_ms), ) }) .collect()) diff --git a/src/model/dpns_voting/composer.rs b/src/model/dpns_voting/composer.rs index c6f77556d..0e6ad9579 100644 --- a/src/model/dpns_voting/composer.rs +++ b/src/model/dpns_voting/composer.rs @@ -32,6 +32,9 @@ pub struct NodeStanding { /// 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. @@ -214,10 +217,16 @@ pub fn compose( plan.skipped.push(skip(SkipReason::VoteStateUnavailable)); continue; }; - if current == Some(decision.choice) { + // 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. + 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; } + let current = if unverified_no_op { None } else { current }; if current.is_some() && standing.changes.is_exhausted() { plan.skipped.push(skip(SkipReason::NoChangesLeft)); continue; @@ -282,6 +291,7 @@ mod tests { state: DpnsCurrentVoteState::Available(current), locked: false, changes: ChangesLeft::Known(4), + proof_can_decide: true, } } @@ -422,6 +432,46 @@ mod tests { 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); + } + /// "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. diff --git a/src/model/dpns_voting/operator.rs b/src/model/dpns_voting/operator.rs index 8f563c4ad..925bca562 100644 --- a/src/model/dpns_voting/operator.rs +++ b/src/model/dpns_voting/operator.rs @@ -381,6 +381,18 @@ pub fn background_refresh_incomplete(last_completed_ms: Option, dispatched_ 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. @@ -776,6 +788,26 @@ mod tests { ); } + #[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] { diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 83a75d52f..a097e3c04 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -31,7 +31,7 @@ use crate::model::dpns_voting::composer::{ use crate::model::dpns_voting::operator::NodeExclusion; use crate::model::dpns_voting::operator::{ ChangesLeft, NodeSet, ResolvedNodeSet, VotingNode, VotingNodeKind, relative_schedule_preset, - time_left, + time_left, vote_proof_can_decide, }; use crate::model::dpns_voting::progress::needs_attention; use crate::model::dpns_voting::{ @@ -880,8 +880,11 @@ impl DPNSScreen { .retain(|name| names.contains(name.as_str())); } - /// Votes a staged decision would send: submittable nodes not already on it. + /// Votes a staged decision would send: submittable nodes not already on + /// it. A node shown on the choice by proof too old to decide still counts; + /// the backend's fresh proof settles whether its vote is really in place. fn transaction_count(&self) -> usize { + let now = now_ms(); self.selected_votes .iter() .filter_map(|vote| { @@ -893,7 +896,15 @@ impl DPNSScreen { card.nodes .iter() .filter(|node| node.status.can_submit()) - .filter(|node| node.current != Some(vote.vote_choice)) + .filter(|node| { + node.current != Some(vote.vote_choice) + || !card.vote_poll_id.is_some_and(|poll| { + vote_proof_can_decide( + self.vote_state.proved_at(node.node, poll), + now, + ) + }) + }) .count(), ) }) @@ -2372,6 +2383,10 @@ impl DPNSScreen { 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( @@ -4851,6 +4866,44 @@ mod tests { ); } + /// 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. + #[test] + fn a_vote_matching_only_stale_proof_is_sent_for_a_fresh_check() { + 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.selected_votes[0].vote_choice = ResourceVoteChoice::Lock; + assert_eq!( + screen.build_review_plan().unwrap().effective_count(), + 0, + "control: fresh proof of the same choice is an exact no-op" + ); + + 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" + ); + + 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); + } + /// 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] diff --git a/src/ui/state/dpns_vote_state.rs b/src/ui/state/dpns_vote_state.rs index e5450b114..8b9ea679c 100644 --- a/src/ui/state/dpns_vote_state.rs +++ b/src/ui/state/dpns_vote_state.rs @@ -11,6 +11,8 @@ 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, } @@ -58,27 +60,30 @@ impl DpnsVoteStateSnapshot { 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(voter_id, vote_poll_ids.iter().copied()) + .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)) + .map(|poll| (poll, (DpnsCurrentVoteState::Unavailable, None))) .collect() } }; - states.extend( - voter_states - .into_iter() - .map(|(poll_id, state)| ((voter_id, poll_id), state)), - ); + 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) } @@ -92,6 +97,12 @@ impl DpnsVoteStateSnapshot { .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)] From 9130b0600a39bcb71c8c94d324232c3c524c550d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:03:34 +0000 Subject: [PATCH 168/194] fix(dpns): release immediate votes left queued by a failed executor After an executor error, the scoped recovery normalised only the targets that executor had claimed. Immediate targets it never reached stayed `Queued`: they hold the target lock, the sweep ignores immediate votes and the drawer offers no action for a queued row, so that node and name refused every new vote until the app was restarted. The scoped recovery now also settles those targets as failed before broadcast, limited to the keys the failed executor ran with and taken under the same per-voter gate and journal guard. A queued schedule is left for the sweep. Nothing was claimed, so no ambiguous outcome is released. Addresses review finding CODE-003. Co-Authored-By: Claude Fable 5.1 --- src/backend_task/contested_names/mod.rs | 68 +++++++++++++++++++ src/context/dpns_vote_operations/mod.rs | 56 ++++++++++----- .../dpns_vote_operations/transitions.rs | 23 +++++++ 3 files changed, 130 insertions(+), 17 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 41ef02efa..28c15a3a1 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -1893,6 +1893,74 @@ mod tests { ); } + /// 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. diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index 4a2b4056a..1220846e7 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -83,6 +83,33 @@ fn stoppable_by_recovery(outcome: &DpnsVoteOutcome) -> bool { && outcome.target.timing == VoteTiming::Now } +/// Keys of the immediate targets recovery has already stopped. +fn stopped_immediate_targets(operation: &DpnsVoteOperation) -> BTreeSet { + operation + .targets + .iter() + .filter(|outcome| stoppable_by_recovery(outcome)) + .map(|outcome| outcome.target.key.clone()) + .collect() +} + +/// Persist an operation recovery has changed, and date the immediate targets +/// it stopped beyond those in `already_stopped`. +fn persist_recovered_operation( + kv: &DetKv, + network: Network, + operation: &DpnsVoteOperation, + already_stopped: &BTreeSet, +) -> Result<(), TaskError> { + persist_operation(kv, network, operation)?; + let stopped: Vec = stopped_immediate_targets(operation) + .into_iter() + .filter(|key| !already_stopped.contains(key)) + .collect(); + save_recovery_stops(kv, network, operation.id, &stopped, now_ms()); + Ok(()) +} + /// Record that restart recovery stopped `keys` of an operation at `at_ms`. /// /// Display metadata, like the relative labels: a failed write is logged and @@ -880,24 +907,11 @@ impl AppContext { let (_guard, kv) = self.journal()?; let now_ms = now_ms(); for mut operation in load_operations(&kv, self.network)? { - let already_stopped: BTreeSet = operation - .targets - .iter() - .filter(|outcome| stoppable_by_recovery(outcome)) - .map(|outcome| outcome.target.key.clone()) - .collect(); + let already_stopped = stopped_immediate_targets(&operation); 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)?; - let stopped: Vec = operation - .targets - .iter() - .filter(|outcome| stoppable_by_recovery(outcome)) - .map(|outcome| outcome.target.key.clone()) - .filter(|key| !already_stopped.contains(key)) - .collect(); - save_recovery_stops(&kv, self.network, operation.id, &stopped, now_ms); + persist_recovered_operation(&kv, self.network, &operation, &already_stopped)?; } } prune_completed_history(&kv, self.network, None, HistoryKind::Immediate)?; @@ -907,6 +921,10 @@ impl AppContext { } /// 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, @@ -919,8 +937,12 @@ impl AppContext { else { return Ok(()); }; - if recover_interrupted_target_statuses(&mut operation, |key| keys.contains(key)) { - persist_operation(kv, self.network, &operation)?; + let already_stopped = stopped_immediate_targets(&operation); + 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_recovered_operation(kv, self.network, &operation, &already_stopped)?; } Ok(()) }) diff --git a/src/context/dpns_vote_operations/transitions.rs b/src/context/dpns_vote_operations/transitions.rs index 58d42f6b1..5e212ee69 100644 --- a/src/context/dpns_vote_operations/transitions.rs +++ b/src/context/dpns_vote_operations/transitions.rs @@ -116,6 +116,29 @@ pub(super) fn recover_interrupted_target_statuses( 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 From 3c2e9243381f1adefcfbdc888e74b2d9558b3960 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:10:32 +0000 Subject: [PATCH 169/194] fix(dpns): date every immediate vote restart recovery picks up Dating only the votes recovery stops left a gap: an immediate vote that recovery queues to be sent again can still fail later in the new session (rejected, voting ended, proof unavailable), and it was then hidden by the same creation-time rule. Restart recovery now records one time for every immediate target it picks up, whether it stops the vote or sends it again, so any outcome of that target is reported in the session that produced it. The stamp is written in one place; the revalidation step and the scoped recovery after an executor error no longer write it. Follow-up to the fix for review finding PROJ-001. Co-Authored-By: Claude Fable 5.1 --- .../01-requirements.md | 6 +- src/context/dpns_vote_operations/keys.rs | 8 +- src/context/dpns_vote_operations/mod.rs | 121 +++++++----------- src/context/dpns_vote_operations/retention.rs | 6 +- src/model/dpns_voting/mod.rs | 11 +- src/model/dpns_voting/progress.rs | 16 +-- 6 files changed, 68 insertions(+), 100 deletions(-) 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 index 2f871973b..9c3b15671 100644 --- 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 @@ -239,9 +239,9 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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. The stopped immediate vote is dated by when recovery stopped - it, so the progress drawer and `Needs attention` of that session list it even - though it was reviewed in an earlier one. A recovered immediate vote that was reviewed as a first + 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, diff --git a/src/context/dpns_vote_operations/keys.rs b/src/context/dpns_vote_operations/keys.rs index f3aa94aba..f3342d24a 100644 --- a/src/context/dpns_vote_operations/keys.rs +++ b/src/context/dpns_vote_operations/keys.rs @@ -14,7 +14,7 @@ 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_STOP_KEY_PREFIX: &str = "det:dpns_vote_recovery_stops: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:"; @@ -66,8 +66,8 @@ pub(super) fn relative_labels_key(operation_key: &str) -> String { operation_key.replacen(OPERATION_KEY_PREFIX, RELATIVE_LABEL_KEY_PREFIX, 1) } -/// When restart recovery stopped an operation's immediate targets; one +/// 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_stops_key(operation_key: &str) -> String { - operation_key.replacen(OPERATION_KEY_PREFIX, RECOVERY_STOP_KEY_PREFIX, 1) +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 index 1220846e7..5fd3fcc80 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -57,65 +57,32 @@ fn load_operation( Ok(None) => {} Err(error) => tracing::debug!(?error, "Relative schedule labels unreadable"), } - if operation.targets.iter().any(stoppable_by_recovery) { - match kv.get::(DetScope::Global, &recovery_stops_key(key)) { - Ok(Some(stops)) => { - for outcome in &mut operation.targets { - if stoppable_by_recovery(outcome) { - outcome.stopped_by_recovery_at_ms = stops.get(&outcome.target.key).copied(); - } + 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 stop times unreadable"), + Err(error) => tracing::debug!(?error, "Vote recovery times unreadable"), } } Ok(Some(operation)) } -/// When restart recovery stopped each immediate target of one operation, Unix ms. -type RecoveryStops = BTreeMap; - -/// Whether `outcome` is in the state restart recovery leaves a stopped -/// immediate vote in. -fn stoppable_by_recovery(outcome: &DpnsVoteOutcome) -> bool { - outcome.status == DpnsVoteTargetStatus::FailedBeforeSubmission - && outcome.target.timing == VoteTiming::Now -} +/// When restart recovery picked up each immediate target of one operation, Unix ms. +type RecoveryTimes = BTreeMap; -/// Keys of the immediate targets recovery has already stopped. -fn stopped_immediate_targets(operation: &DpnsVoteOperation) -> BTreeSet { - operation - .targets - .iter() - .filter(|outcome| stoppable_by_recovery(outcome)) - .map(|outcome| outcome.target.key.clone()) - .collect() +fn is_immediate(outcome: &DpnsVoteOutcome) -> bool { + outcome.target.timing == VoteTiming::Now } -/// Persist an operation recovery has changed, and date the immediate targets -/// it stopped beyond those in `already_stopped`. -fn persist_recovered_operation( - kv: &DetKv, - network: Network, - operation: &DpnsVoteOperation, - already_stopped: &BTreeSet, -) -> Result<(), TaskError> { - persist_operation(kv, network, operation)?; - let stopped: Vec = stopped_immediate_targets(operation) - .into_iter() - .filter(|key| !already_stopped.contains(key)) - .collect(); - save_recovery_stops(kv, network, operation.id, &stopped, now_ms()); - Ok(()) -} - -/// Record that restart recovery stopped `keys` of an operation at `at_ms`. +/// 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 journal transition it describes. Callers hold the journal -/// guard. -fn save_recovery_stops( +/// never fails the recovery it describes. Callers hold the journal guard. +fn save_recovery_times( kv: &DetKv, network: Network, operation_id: DpnsVoteOperationId, @@ -125,16 +92,16 @@ fn save_recovery_stops( if keys.is_empty() { return; } - let key = recovery_stops_key(&operation_key(network, operation_id)); + let key = recovery_times_key(&operation_key(network, operation_id)); let result = kv - .get::(DetScope::Global, &key) - .and_then(|stops| { - let mut stops = stops.unwrap_or_default(); - stops.extend(keys.iter().cloned().map(|key| (key, at_ms))); - kv.put(DetScope::Global, &key, &stops) + .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 stop times"); + tracing::debug!(?error, "Could not save vote recovery times"); } } @@ -851,8 +818,7 @@ impl AppContext { state: DpnsCurrentVoteState, ) -> Result { self.mutate_dpns_vote_operation(operation_id, |kv| { - let mut stopped = false; - let still_queued = with_target(kv, self.network, operation_id, key, |outcome| { + Ok(with_target(kv, self.network, operation_id, key, |outcome| { if outcome.status != DpnsVoteTargetStatus::Queued { return TargetUpdate::Skip(false); } @@ -879,22 +845,9 @@ impl AppContext { unavailable_preflight_outcome(outcome.target.timing); } } - stopped = stoppable_by_recovery(outcome); TargetUpdate::Persist(outcome.status == DpnsVoteTargetStatus::Queued) })? - .unwrap_or(false); - if stopped { - // An immediate target is only ever revalidated here when a - // restart left it queued, so its operation predates the session. - save_recovery_stops( - kv, - self.network, - operation_id, - std::slice::from_ref(key), - now_ms(), - ); - } - Ok(still_queued) + .unwrap_or(false)) }) } @@ -907,12 +860,26 @@ impl AppContext { let (_guard, kv) = self.journal()?; let now_ms = now_ms(); for mut operation in load_operations(&kv, self.network)? { - let already_stopped = stopped_immediate_targets(&operation); + // 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_recovered_operation(&kv, self.network, &operation, &already_stopped)?; + 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)?; @@ -937,12 +904,11 @@ impl AppContext { else { return Ok(()); }; - let already_stopped = stopped_immediate_targets(&operation); 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_recovered_operation(kv, self.network, &operation, &already_stopped)?; + persist_operation(kv, self.network, &operation)?; } Ok(()) }) @@ -2517,8 +2483,8 @@ mod tests { ); assert!( recovered.targets[0] - .stopped_by_recovery_at_ms - .is_some_and(|stopped| stopped >= session_start), + .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(); @@ -2585,6 +2551,7 @@ mod tests { 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() @@ -2595,8 +2562,8 @@ mod tests { DpnsVoteTargetStatus::FailedBeforeSubmission ); assert!( - saved.targets[0].stopped_by_recovery_at_ms.is_some(), - "the operator must be told the vote was stopped" + 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); diff --git a/src/context/dpns_vote_operations/retention.rs b/src/context/dpns_vote_operations/retention.rs index cd3d5d4e7..66932da57 100644 --- a/src/context/dpns_vote_operations/retention.rs +++ b/src/context/dpns_vote_operations/retention.rs @@ -183,8 +183,8 @@ pub(super) fn prune_orphaned_schedule_dismissals( .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_stop_prefix = format!("{RECOVERY_STOP_KEY_PREFIX}{}:", network_prefix(network)); - for prefix in [dismissal_prefix, relative_prefix, recovery_stop_prefix] { + 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)? @@ -223,7 +223,7 @@ pub(super) fn delete_terminal_operations( .map_err(operation_err)?; kv.delete( DetScope::Global, - &recovery_stops_key(&operation_key(network, *id)), + &recovery_times_key(&operation_key(network, *id)), ) .map_err(operation_err)?; kv.delete(DetScope::Global, &operation_key(network, *id)) diff --git a/src/model/dpns_voting/mod.rs b/src/model/dpns_voting/mod.rs index ac25353d8..0f3811c4f 100644 --- a/src/model/dpns_voting/mod.rs +++ b/src/model/dpns_voting/mod.rs @@ -295,11 +295,12 @@ pub struct DpnsVoteOutcome { /// Excluded from the established binary vote record format. #[serde(skip)] pub relative_schedule_preset_ms: Option, - /// When restart recovery stopped this immediate vote before it was sent, - /// in Unix ms. Display-only and hydrated like the preset: it lets the - /// session that stopped the vote report it, although the vote is older. + /// 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 stopped_by_recovery_at_ms: Option, + pub recovered_at_ms: Option, } /// Reviewed voting batch stored before its first broadcast. @@ -333,7 +334,7 @@ impl DpnsVoteOperation { status, failure: None, relative_schedule_preset_ms: None, - stopped_by_recovery_at_ms: None, + recovered_at_ms: None, } }) .collect::>(); diff --git a/src/model/dpns_voting/progress.rs b/src/model/dpns_voting/progress.rs index 5fde2a313..2a5928227 100644 --- a/src/model/dpns_voting/progress.rs +++ b/src/model/dpns_voting/progress.rs @@ -81,15 +81,15 @@ pub fn progress_counts<'a>( /// 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 in this one. +/// 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 - .stopped_by_recovery_at_ms - .map_or(sent, |stopped| stopped.max(sent)) + .recovered_at_ms + .map_or(sent, |recovered| recovered.max(sent)) } /// Operations the drawer lists: anything still in flight, plus operations @@ -351,14 +351,14 @@ mod tests { assert!(drawer_operations(&operations, session_start, &dismissed).is_empty()); } - /// An immediate vote left over from an earlier session and stopped by - /// restart recovery is this session's news: the operator must see it as - /// not submitted and be able to review it again. + /// 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_stopped_by_restart_recovery_is_surfaced_in_the_new_session() { + 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].stopped_by_recovery_at_ms = Some(session_start + 60); + 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]; From 1b20894c08364e1846ef5211639d79bfebf1cbf2 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:11:51 +0000 Subject: [PATCH 170/194] fix(dpns): cancel votes stored after their voter was removed Removing an identity cancels its executable votes under the journal guard, but only those already in the journal. An operation is stored after an asynchronous proof refresh, so a vote reviewed before the removal could be stored after it; loading the identity again then let the sweep send a schedule the removal was meant to drop. Storing an operation now applies the same cancellation, inside the same guard, to targets whose voter was removed from this device and not loaded again. Either order of the race ends with the same record. Not covered: a voter removed and loaded again inside one proof refresh. That needs a per-voter lifecycle counter owned by the identity store. Addresses review finding CODE-004. Co-Authored-By: Claude Fable 5.1 --- src/backend_task/contested_names/mod.rs | 91 +++++++++++++++++++++++++ src/context/dpns_vote_operations/mod.rs | 68 +++++++++++++----- 2 files changed, 143 insertions(+), 16 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 28c15a3a1..b57007131 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -1893,6 +1893,97 @@ mod tests { ); } + /// 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; + } + /// 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. diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index 5fd3fcc80..6a08cc4f9 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -352,28 +352,35 @@ pub(super) fn cancel_removed_identity_votes( voter_id: dash_sdk::platform::Identifier, ) -> Result<(), TaskError> { for mut operation in load_operations(kv, network)? { - let mut changed = false; - for outcome in &mut operation.targets { - if outcome.target.key.voter_id == voter_id - && matches!( - outcome.status, - DpnsVoteTargetStatus::Scheduled - | DpnsVoteTargetStatus::Queued - | DpnsVoteTargetStatus::Submitting - ) - { - outcome.status = DpnsVoteTargetStatus::Cancelled; - outcome.failure = None; - changed = true; - } - } - if changed { + 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), @@ -616,10 +623,39 @@ impl AppContext { { 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)?; + cancel_executable_targets(operation, |voter| removed.contains(&voter)); persist_operation(kv, self.network, operation) }) } + /// Voters of `operation` that were removed from this device and not + /// loaded again. The caller holds the journal guard, which a removal + /// keeps from cancelling the voter's votes until the voter is delisted. + fn removed_dpns_voters( + &self, + kv: &DetKv, + operation: &DpnsVoteOperation, + ) -> Result, TaskError> { + let voters: BTreeSet<_> = operation + .targets + .iter() + .map(|outcome| outcome.target.key.voter_id) + .collect(); + let mut removed = BTreeSet::new(); + for voter in voters { + if 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, From 84c38c5f0541b0577df4a2cd82ae57b221554715 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:14:14 +0000 Subject: [PATCH 171/194] fix(dpns): count a vote once when its confirmation is recorded twice The spent-vote count is bumped before the operation record is written. When that write failed, the stored target stayed unresolved, the error path marked it unconfirmed, and the later reconciliation confirmed it again and bumped the count a second time. The node then showed one change fewer than it had, permanently. Each node x poll count now has a record of the operation last counted, and a confirmation by that same operation is not counted again. An unresolved target holds its lock, so one record per count is enough. The count and the journal keep their stored format; the record is a new key, dropped with the count when the poll closes. Addresses review finding CODE-005. Co-Authored-By: Claude Fable 5.1 --- src/context/dpns_vote_operations/counts.rs | 83 +++++++++++++++++----- src/context/dpns_vote_operations/mod.rs | 33 ++++++++- 2 files changed, 99 insertions(+), 17 deletions(-) diff --git a/src/context/dpns_vote_operations/counts.rs b/src/context/dpns_vote_operations/counts.rs index 8c6bb7c84..02c8b4a06 100644 --- a/src/context/dpns_vote_operations/counts.rs +++ b/src/context/dpns_vote_operations/counts.rs @@ -6,12 +6,16 @@ use super::keys::{operation_err, unreadable_operation_err}; use crate::backend_task::error::TaskError; -use crate::model::dpns_voting::{DpnsVoteOperation, DpnsVoteTargetKey, DpnsVoteTargetStatus}; +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)) @@ -21,6 +25,19 @@ fn count_key(network: Network, voter_id: Identifier, vote_poll_id: Identifier) - 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 @@ -50,16 +67,37 @@ pub(super) fn newly_spent_targets<'a>( .collect() } -/// Add one spent vote for `key`. Callers hold the journal guard and bump -/// before persisting the transition: a crash in between over-counts, which -/// understates changes left instead of overstating them. -pub(super) fn bump_vote_count(kv: &DetKv, key: &DpnsVoteTargetKey) -> Result<(), TaskError> { +/// 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) } @@ -86,16 +124,20 @@ pub(super) fn forget_vote_counts( if closed_polls.is_empty() { return Ok(0); } - let prefix = count_key_prefix(network); let suffixes: Vec = closed_polls.iter().map(|poll| format!(":{poll}")).collect(); let mut removed = 0; - 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 += 1; + 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) @@ -162,10 +204,12 @@ mod tests { vote_count(&kv, network, voter, Identifier::from([2; 32])).unwrap(), None ); - for _ in 0..3 { - bump_vote_count(&kv, &key(2)).unwrap(); + 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)).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) @@ -183,6 +227,13 @@ mod tests { 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), diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index 6a08cc4f9..61635dfd9 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -294,7 +294,7 @@ fn persist_operation( } for key in counts::newly_spent_targets(previous.as_ref(), operation) { - counts::bump_vote_count(kv, key)?; + counts::bump_vote_count(kv, key, operation.id)?; } let mut ids = load_operation_ids(kv, network)?; @@ -1911,6 +1911,37 @@ mod tests { ); } + /// 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()); From 2bda1358dd9975aa9276ed86da1d93e93c8bab07 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:15:32 +0000 Subject: [PATCH 172/194] test(dpns): build the vote-state snapshot fixture with its proof times Co-Authored-By: Claude Fable 5.1 --- src/ui/state/dpns_vote_state.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/ui/state/dpns_vote_state.rs b/src/ui/state/dpns_vote_state.rs index 8b9ea679c..f2e9e0e28 100644 --- a/src/ui/state/dpns_vote_state.rs +++ b/src/ui/state/dpns_vote_state.rs @@ -157,6 +157,7 @@ mod tests { let poll = Identifier::from([2; 32]); let snapshot = DpnsVoteStateSnapshot { states: BTreeMap::from([((voter, poll), DpnsCurrentVoteState::Available(None))]), + proved_at: BTreeMap::new(), loaded: true, }; From f778d9491ca74026204c8e5c49fa3cfb3dde8923 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:58:34 +0000 Subject: [PATCH 173/194] fix(dpns): check the network before believing a refused username request MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The SDK re-sends the same signed name request and reports only its last attempt, so a refusal can follow an attempt that was applied and paid for. The refusal was returned before the reconciling read, which reported a paid request as a plain failure and left the Pay step live. Read the network first on every failed broadcast. A refusal is honoured only when the network does not show this identity's request; a failed read leaves the refusal standing, as on the voting side. Review finding: CODE-001. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- .../01-requirements.md | 10 ++- .../03-test-case-spec.md | 1 + .../identity/register_dpns_name.rs | 76 ++++++++++++++----- 3 files changed, 66 insertions(+), 21 deletions(-) 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 index a78af1cbb..be4fa1fd6 100644 --- a/docs/ai-design/2026-10-01-usernames-redesign/01-requirements.md +++ b/docs/ai-design/2026-10-01-usernames-redesign/01-requirements.md @@ -187,10 +187,12 @@ Scope: identity-side usernames. Voting is Stream V in [Go to my identity]; - failure: errors per AGENTS.md (no jargon, an action, details via `with_details`); - - unconfirmed: when the name request was sent but neither a refusal nor the - request itself can be read back from the network, the fee may already be - spent. The app first re-reads the vote (or the owned names) and continues - as a success if the request is there. Otherwise it reports `The app could + - 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 the network does not contradict + keeps its own error. 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 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 index 35734d718..dd5e674fb 100644 --- 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 @@ -31,6 +31,7 @@ Stream V test cases live in `../2026-07-16-dpns-voting-experience/03-test-case-s | 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 | Registration continues as success / the refusal keeps its own error | FR-038 | B | ## UI (kittest) diff --git a/src/backend_task/identity/register_dpns_name.rs b/src/backend_task/identity/register_dpns_name.rs index 972498c35..779987c5d 100644 --- a/src/backend_task/identity/register_dpns_name.rs +++ b/src/backend_task/identity/register_dpns_name.rs @@ -42,10 +42,12 @@ fn rebrand_dpns_domain_conflict(error: TaskError) -> TaskError { } } -/// Whether the network refused the transition, which proves it was not applied. +/// Whether the network refused the last broadcast attempt. /// -/// Any other failure (a timeout, a dropped connection, no reachable node) can -/// follow a broadcast that did arrive, so it proves nothing either way. +/// `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, @@ -264,8 +266,9 @@ impl AppContext { /// 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. A refusal keeps its own error. Anything else is - /// reported as unconfirmed, never as a plain failure that invites paying again. + /// carries on as a success, even after a refusal. A refusal the network + /// does not contradict keeps its own error. Anything else is reported as + /// unconfirmed, never as a plain failure that invites paying again. async fn resolve_failed_domain_broadcast( &self, sdk: &Sdk, @@ -274,9 +277,6 @@ impl AppContext { outcome: DpnsRegistrationOutcome, error: SdkError, ) -> Result<(), TaskError> { - if broadcast_was_rejected(&error) { - return Err(rebrand_dpns_domain_conflict(TaskError::from(error))); - } if self .username_request_reached_network(sdk, identity_id, name, outcome) .await @@ -288,6 +288,9 @@ impl AppContext { ); return Ok(()); } + if broadcast_was_rejected(&error) { + return Err(rebrand_dpns_domain_conflict(TaskError::from(error))); + } Err(TaskError::UsernameRegistrationUnconfirmed { source_error: Box::new(error), }) @@ -845,24 +848,38 @@ mod tests { SdkError::TimeoutReached(std::time::Duration::from_secs(1), "no answer".to_owned()) } - /// A refusal by the network proves nothing was paid, so it keeps its own - /// error and is not turned into an "unconfirmed" warning. + 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 refused = crate::test_support::duplicate_unique_index_broadcast_error(vec![ - "normalizedParentDomainName", - "normalizedLabel", - ]); + 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::new_mock(), - Identifier::from([8; 32]), + &sdk, + id, "alice", DpnsRegistrationOutcome::PendingCommunityVote, - refused, + refused_broadcast(), ) .await; @@ -872,6 +889,31 @@ mod tests { ); } + /// 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)] From bbdb04c1abb6628633dc0e1e8cd2de2e81e1b495 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:58:53 +0000 Subject: [PATCH 174/194] docs(dpns): describe the old-schedule notice as non-listing and self-expiring MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DPN-009 and the changelog still promised a review of old schedules and a persistent notice. The notice lists nothing, returns on each launch, and stops one contest duration after it first appeared. Review finding: PROJ-002. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- CHANGELOG.md | 7 +++++-- docs/user-stories.md | 8 ++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e1db6f8fb..4a21ca82f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -904,10 +904,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - 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 users to review and cast or schedule those votes again. + 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 that notice does not list them, so schedule them again in + 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 diff --git a/docs/user-stories.md b/docs/user-stories.md index f53d248eb..63322bcbe 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -890,12 +890,12 @@ As a user, I want my identity's Display name to identify it throughout the app s ### DPN-009: Notice schedules that need a fresh decision after an upgrade [Implemented] **Persona:** Priya -As a masternode operator, I want to be told when an upgrade cannot carry over my scheduled votes so that I can review and cast or schedule them again. +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. - Startup checks for unexecuted schedules in the previous SQLite storage on the selected network. -- A persistent, dismissible notice directs me to Masternodes β†’ Votes to make a new decision. -- The notice stops appearing one full voting period after it was first shown, because every vote an old schedule could refer to has ended by then. -- Old schedules are neither imported nor executed automatically; their source records remain untouched. +- 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. From aa468f4fb7855e06b4361f9b4c3dca962bba5d64 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:01:02 +0000 Subject: [PATCH 175/194] refactor(migration): remove the unreadable-votes report the upgrade can no longer raise MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The storage update stopped reading legacy scheduled votes, so the `votes` counter of `MigrationState::SucceededWithUnreadableData` could only be zero. Remove the counter, the banner copy and match arms only it could reach, and the tests that pinned that copy. The acknowledgement id that now retires the top-up warning is renamed to `MIGRATION_APP_DATA_ACK_ACTION_ID`; tests of the vote-only banner become tests of the top-up banner it actually acknowledges. The MCP migration summary keeps its `votes` field, which predates this change, documented as always 0 so existing clients keep parsing it. Review finding: PROJ-003. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/app.rs | 121 ++++++-------------- src/app/reconcilers.rs | 36 +++--- src/backend_task/migration/finish_unwire.rs | 14 --- src/backend_task/migration/v093_upgrade.rs | 1 - src/context/migration_status.rs | 14 +-- src/mcp/tools/meta.rs | 8 +- src/ui/wallets/shielded_tab.rs | 9 +- tests/kittest/migration_banner.rs | 38 +++--- 8 files changed, 75 insertions(+), 166 deletions(-) diff --git a/src/app.rs b/src/app.rs index d1658c021..2fe3ec998 100644 --- a/src/app.rs +++ b/src/app.rs @@ -64,11 +64,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 @@ -78,13 +78,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); @@ -886,26 +887,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 under Masternodes > Votes." - ) -} - /// 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 \ @@ -915,26 +903,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 under Masternodes > Votes." - ) -} - /// 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. @@ -948,44 +919,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 under Masternodes > Votes. \ - 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 \ - under Masternodes > Votes, 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() } } } @@ -4476,7 +4429,6 @@ mod migration_banner_tests { assert!(migration_allows_scheduled_vote_sweep( &MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 1, top_ups: 1, }, )); @@ -4518,22 +4470,15 @@ mod migration_banner_tests { assert!(!notice.contains("review")); } - /// Scheduled votes are never imported, and the Scheduled Votes screen is - /// gone: no migration copy may claim otherwise. + /// Scheduled votes are never imported or inspected by the storage update: + /// no migration copy may claim otherwise. #[test] - fn migration_copy_does_not_mention_importing_votes_or_a_removed_screen() { - for step in MigrationStep::ALL { - let text = migration_running_text(step); - assert!(!text.contains("scheduled votes"), "{text}"); - } - for text in [ - migration_unreadable_votes_text(2), - migration_unreadable_identities_and_votes_text(1, 2), - migration_unreadable_data_text(0, 2, 3), - migration_unreadable_data_text(1, 2, 3), - ] { - assert!(!text.contains("Scheduled Votes screen"), "{text}"); - assert!(text.contains("Masternodes > Votes"), "{text}"); + 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}"); } } @@ -4650,7 +4595,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('.')); @@ -4700,7 +4645,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, ]; 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/migration/finish_unwire.rs b/src/backend_task/migration/finish_unwire.rs index 4bdee2f90..8f48fbc81 100644 --- a/src/backend_task/migration/finish_unwire.rs +++ b/src/backend_task/migration/finish_unwire.rs @@ -869,7 +869,6 @@ where ); status.set_state(MigrationState::SucceededWithUnreadableData { identities: unreadable, - votes: 0, top_ups: top_ups_unreadable, }); } @@ -883,7 +882,6 @@ where ); status.set_state(MigrationState::SucceededWithUnreadableData { identities: unreadable, - votes: 0, top_ups: 0, }); } @@ -898,7 +896,6 @@ where ); status.set_state(MigrationState::SucceededWithUnreadableData { identities: unreadable, - votes: 0, top_ups: 0, }); } @@ -944,7 +941,6 @@ where ); status.set_state(MigrationState::SucceededWithUnreadableData { identities: 0, - votes: 0, top_ups: top_ups_unreadable, }); return Ok(moved_data); @@ -6738,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", @@ -6782,7 +6777,6 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 0, - votes: 0, top_ups: 1, }, "a pending warning is surfaced", @@ -6796,7 +6790,6 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 0, - votes: 0, top_ups: 1, }, "a warning the user may have missed must survive a restart", @@ -6851,7 +6844,6 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 0, top_ups: 1, }, "the run must name BOTH remedies β€” the identity warning may not swallow \ @@ -6886,7 +6878,6 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 0, top_ups: 1, }, "the top-up warning must survive a restart even while identities stay unreadable", @@ -6901,7 +6892,6 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 0, top_ups: 0, }, "an acknowledged top-up warning must not come back, but the identity one must", @@ -6961,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", @@ -6995,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", @@ -7032,7 +7020,6 @@ mod tests { *ctx.migration_status().state(), MigrationState::SucceededWithUnreadableData { identities: 1, - votes: 0, top_ups: 0, }, "the discovery run surfaces the warning", @@ -7055,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/v093_upgrade.rs b/src/backend_task/migration/v093_upgrade.rs index 3425af95f..582fe4d5b 100644 --- a/src/backend_task/migration/v093_upgrade.rs +++ b/src/backend_task/migration/v093_upgrade.rs @@ -1555,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/context/migration_status.rs b/src/context/migration_status.rs index 1c8c4b8fa..4386d5c69 100644 --- a/src/context/migration_status.rs +++ b/src/context/migration_status.rs @@ -122,15 +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, - /// Always `0`: the storage update does not read legacy scheduled votes; - /// the startup notice for old schedules reports them instead. - // TODO(dpns): remove this counter together with its banner copy and - // the MCP `votes` field; nothing produces a non-zero value. - 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 @@ -174,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/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/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/tests/kittest/migration_banner.rs b/tests/kittest/migration_banner.rs index 7d2bed7b6..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), ); } @@ -218,7 +216,7 @@ fn unreadable_votes_banner_acknowledgement_enqueues_action() { 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!( @@ -284,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)) From cb12ded5ba88ef350c95f9aea2add976fb42299d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:05:17 +0000 Subject: [PATCH 176/194] fix(dpns): stop listing a won username after it has left the identity MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A saved win missing from the identity's owned names was always treated as "not read back yet": listed as an owned, shareable name, retained without limit and re-fetched on every refresh. After the name had been read back and then left the identity (a transfer), that state never ended. Record on the request that the owned names reflected the win once, both when a refresh merges against the owned names and at the moment the win is saved to the identity. A reflected win is no longer missing, is not listed as owned unless the identity still lists it, and ages out with the other outcomes. The request store is positional, so the flag is not a new stored field: it is written as an appended phase index. Requests stored before the flag existed load unchanged, as not reflected, and unflagged requests keep their stored bytes. One line of src/context/contested_names_db.rs (a test helper's struct literal) gains the new field so the tree compiles. Review finding: CODE-002. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- .../01-requirements.md | 6 +- .../03-test-case-spec.md | 1 + docs/kv-keys.md | 2 +- docs/user-stories.md | 1 + src/backend_task/identity/dpns_usernames.rs | 59 ++++- src/context/contested_names_db.rs | 1 + src/model/dpns_usernames.rs | 243 +++++++++++++++++- src/ui/identity/usernames_card.rs | 25 +- 8 files changed, 326 insertions(+), 12 deletions(-) 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 index be4fa1fd6..07c802418 100644 --- a/docs/ai-design/2026-10-01-usernames-redesign/01-requirements.md +++ b/docs/ai-design/2026-10-01-usernames-redesign/01-requirements.md @@ -91,7 +91,11 @@ Scope: identity-side usernames. Voting is Stream V in - `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. + - 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 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 index dd5e674fb..933ae2019 100644 --- 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 @@ -32,6 +32,7 @@ Stream V test cases live in `../2026-07-16-dpns-voting-experience/03-test-case-s | 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 | Registration continues as success / the refusal keeps its own error | 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) diff --git a/docs/kv-keys.md b/docs/kv-keys.md index c9abaa587..8e8f7b5dd 100644 --- a/docs/kv-keys.md +++ b/docs/kv-keys.md @@ -154,7 +154,7 @@ Per-identity username state. Global-scoped with the identity id in the key, so i | Key | Scope | Store | Value type | Notes | |-----|-------|-------|------------|-------| -| `det:username_requests:` | `None` | `det-.sqlite` | `Vec` | 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` | +| `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 `:` | diff --git a/docs/user-stories.md b/docs/user-stories.md index 63322bcbe..d9fdf37fc 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -821,6 +821,7 @@ As a user, I want to see each identity's usernames and their state so that I kno - 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. diff --git a/src/backend_task/identity/dpns_usernames.rs b/src/backend_task/identity/dpns_usernames.rs index ca7971c1c..903d87c20 100644 --- a/src/backend_task/identity/dpns_usernames.rs +++ b/src/backend_task/identity/dpns_usernames.rs @@ -21,7 +21,8 @@ use crate::model::dpns::{ }; use crate::model::dpns_usernames::{ ContenderTally, ContestSnapshot, ContestWinner, RequestPhase, UsernameAvailability, - UsernameRequest, classify_availability, merge_requests, username_request_from_contest, + UsernameRequest, classify_availability, mark_wins_reflected, merge_requests, + username_request_from_contest, }; use crate::model::qualified_identity::QualifiedIdentity; use crate::utils::time::now_ms; @@ -344,6 +345,15 @@ impl AppContext { 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) => { @@ -737,6 +747,53 @@ mod tests { ); } + /// 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_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(); diff --git a/src/context/contested_names_db.rs b/src/context/contested_names_db.rs index 3a5a9bb83..4e9ab8f41 100644 --- a/src/context/contested_names_db.rs +++ b/src/context/contested_names_db.rs @@ -1035,6 +1035,7 @@ mod tests { decided_at: None, tally: Default::default(), last_updated: 0, + reflected_in_owned_names: false, } } diff --git a/src/model/dpns_usernames.rs b/src/model/dpns_usernames.rs index d38efdfe7..ddff8fe45 100644 --- a/src/model/dpns_usernames.rs +++ b/src/model/dpns_usernames.rs @@ -205,14 +205,37 @@ impl UsernameAvailability { } /// 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 - && !names - .iter() - .any(|name| super::dpns::normalize_dpns_label(&name.name) == request.normalized_label) + && !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. @@ -393,6 +416,7 @@ impl RequestTally { /// 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, @@ -412,6 +436,99 @@ pub struct UsernameRequest { 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 { @@ -452,6 +569,7 @@ impl UsernameRequest { decided_at: None, tally: RequestTally::default(), last_updated: now, + reflected_in_owned_names: false, } } } @@ -513,6 +631,7 @@ pub fn username_request_from_contest( decided_at: contest.decided_at, tally, last_updated: now, + reflected_in_owned_names: false, }) } @@ -521,8 +640,10 @@ pub fn username_request_from_contest( /// 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`; -/// `None` keeps wins when the caller has no current owned-name snapshot. +/// 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, @@ -549,6 +670,7 @@ pub fn merge_requests( 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(); @@ -567,11 +689,13 @@ pub fn merge_requests( 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 - && owned_names.is_none_or(|names| won_username_is_missing(r, names))) + || (r.phase == RequestPhase::Won && !r.reflected_in_owned_names) || r.decided_at .is_none_or(|decided| now.saturating_sub(decided) < retention) }); @@ -1117,6 +1241,7 @@ mod tests { ..Default::default() }, last_updated: 0, + reflected_in_owned_names: false, } } @@ -1153,6 +1278,110 @@ mod tests { 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] { diff --git a/src/ui/identity/usernames_card.rs b/src/ui/identity/usernames_card.rs index 8bdc4b06a..601361d30 100644 --- a/src/ui/identity/usernames_card.rs +++ b/src/ui/identity/usernames_card.rs @@ -52,14 +52,18 @@ pub fn username_rows( requests: &[UsernameRequest], ) -> Vec { // Registered names, plus names won in a vote that the identity's stored - // names do not list yet (they are re-read in the background). + // 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) { + 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))); } @@ -460,6 +464,23 @@ mod tests { )); } + /// 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 From f908ee346e552a153310a0f4a46ff4b7e7ecf824 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:20:36 +0000 Subject: [PATCH 177/194] docs(dpns): list the vote-count key in the k/v reference MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The per-node, per-contest count of applied votes lives in its own namespace and was missing from the DPNS vote journal table. Review finding: DOC-001 (round 1), completing the key list. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- docs/kv-keys.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/kv-keys.md b/docs/kv-keys.md index 8e8f7b5dd..33b0f944f 100644 --- a/docs/kv-keys.md +++ b/docs/kv-keys.md @@ -141,10 +141,11 @@ The journal is the sole store of immediate and scheduled DPNS votes. Every key i | `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 | 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` +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` --- From 772750dd224cb0c35e3cb6e97d19cc07f8c3b77d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:20:36 +0000 Subject: [PATCH 178/194] docs(dpns): list the recovery-time and counted-operation keys MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two sidecar keys of the DPNS vote journal: when restart recovery picked up an operation's immediate targets, and which operation's vote was last added to a node's per-contest count. Describes keys introduced on the voting fix branch (src/context/dpns_vote_operations/keys.rs and counts.rs); apply together with it. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- docs/kv-keys.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/kv-keys.md b/docs/kv-keys.md index 33b0f944f..9e36e6419 100644 --- a/docs/kv-keys.md +++ b/docs/kv-keys.md @@ -138,10 +138,12 @@ The journal is the sole store of immediate and scheduled DPNS votes. Every key i | `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. From baf173905db7306c5c5d78381e0fcf0fbf8e5a5f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:20:47 +0000 Subject: [PATCH 179/194] test(identity): schedule the vote before the interrupted removal it must survive MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The cleanup test inserted its scheduled vote after the identity had been unloaded and unlisted. Scheduling for an already-removed voter is a path the journal can refuse or cancel by itself, which would leave the cleanup's own cancellation unexercised. Insert the vote while the identity is still loaded, as in a real interrupted removal. Requested by fixer-voting alongside their CODE-004 change. Co-Authored-By: Claude Fable 5.1 πŸ€– Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/context/identity_db.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index a8984b9ec..f724eb965 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -3795,6 +3795,14 @@ mod tests { 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 @@ -3802,12 +3810,6 @@ mod tests { .unwrap(); staged.ctx.mark_identity_unloaded(&kv, &id).unwrap(); index_remove_identity(&kv, &id).unwrap(); - let mut scheduled = - scheduled_operation(staged.id, 9, "interrupted", DpnsVoteTargetStatus::Scheduled); - staged - .ctx - .insert_dpns_vote_operation(&mut scheduled, None) - .unwrap(); staged.ctx.resume_pending_vault_cleanups(); From fba85f90a2103d45adbb661091d041f726604ced Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:49:30 +0000 Subject: [PATCH 180/194] fix(dpns): show a vote that is only checked again as cast, not as a first vote A node shown on the requested choice by proof older than the 120 s decision cap is still submitted so the backend's fresh proof can settle it, and its target carries no reviewed current choice. The confirm step and the tray read that erased value as fact: "Current choice: Not voted yet" for a node the card shows as voted, and one more "transaction" although nothing is broadcast when the fresh proof agrees. On mainnet that is the usual state between the 30-minute background refreshes. The plan now records which targets are only checked again. The routing is unchanged; the wording is not: - Adjust nodes row: "Current choice: , as requested. It will be checked again before a vote is sent." - transaction counts (confirm line, primary button, tray) leave these votes out and state them in their own sentence; - when nothing else is sent the primary button reads "Check N votes" / "Schedule N checks", and the tray keeps Cast available. Co-Authored-By: Claude Fable 5.1 --- .../01-requirements.md | 17 +- src/model/dpns_voting/composer.rs | 75 ++++++- src/ui/dpns/copy.rs | 96 +++++++- src/ui/dpns/dpns_contested_names_screen.rs | 211 +++++++++++++----- 4 files changed, 331 insertions(+), 68 deletions(-) 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 index 9c3b15671..d182f67d9 100644 --- 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 @@ -132,6 +132,8 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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. - **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). @@ -188,6 +190,9 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. - **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 @@ -199,11 +204,16 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. - 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); + - 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`. + - 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): @@ -211,7 +221,10 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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`. + 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. ### Operation lifecycle diff --git a/src/model/dpns_voting/composer.rs b/src/model/dpns_voting/composer.rs index 0e6ad9579..538994b93 100644 --- a/src/model/dpns_voting/composer.rs +++ b/src/model/dpns_voting/composer.rs @@ -96,10 +96,15 @@ pub enum ComposeError { VotingEnded { contested_name: String }, } -/// Exactly what a confirm click sends. +/// 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, /// Targets asked to vote "when voting is about to end" whose contest is /// already inside the lead time, so they are sent now. @@ -115,6 +120,20 @@ impl AggregatePlan { .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 @@ -221,6 +240,8 @@ pub fn compose( // 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)); @@ -240,12 +261,16 @@ pub fn compose( continue; }; plan.ends_soon_now += usize::from(ends_soon); + 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: DpnsVoteTargetKey { - network, - voter_id: node.voter_id, - vote_poll_id: decision.vote_poll_id, - }, + key, voter_alias: node.alias.clone(), contested_name: decision.contested_name.clone(), requested_choice: decision.choice, @@ -313,6 +338,8 @@ mod tests { ) .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()); @@ -470,6 +497,42 @@ mod tests { ); 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 diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index f86a8b49e..352c71b4c 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -269,6 +269,16 @@ pub fn tray_label(decisions: usize, transactions: usize) -> String { } } +/// 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) { @@ -405,6 +415,32 @@ pub fn confirm_transactions_line(transactions: usize) -> String { } } +/// 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 { @@ -471,13 +507,18 @@ pub fn skipped_reason_line(count: usize, reason: SkipReason) -> String { } } -/// Confirm primary button (VOTE-FR-080). -pub fn confirm_button_label(transactions: usize, all_now: bool) -> String { - match (transactions, all_now) { - (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"), +/// 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"), } } @@ -851,6 +892,43 @@ mod tests { ); } + /// 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() { @@ -868,8 +946,8 @@ mod tests { 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, true), "Cast 72 votes"); - assert_eq!(confirm_button_label(1, false), "Schedule 1 vote"); + 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" diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index a097e3c04..878a7d5ca 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -48,13 +48,15 @@ use crate::ui::components::{BannerHandle, MessageBanner, OptionBannerExt}; 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::tray_label; use crate::ui::dpns::copy::{ JOURNAL_UNAVAILABLE_MESSAGE, LOCKED_FOR_GOOD, 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; @@ -227,8 +229,8 @@ fn loaded_voting_identities(app_context: &AppContext) -> Result 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() } @@ -256,6 +270,16 @@ impl ReviewPlan { } } +/// 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 { @@ -880,35 +904,32 @@ impl DPNSScreen { .retain(|name| names.contains(name.as_str())); } - /// Votes a staged decision would send: submittable nodes not already on - /// it. A node shown on the choice by proof too old to decide still counts; - /// the backend's fresh proof settles whether its vote is really in place. - fn transaction_count(&self) -> usize { + /// 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. + fn tray_counts(&self) -> TrayCounts { let now = now_ms(); - self.selected_votes - .iter() - .filter_map(|vote| { - let card = self - .cards - .iter() - .find(|card| card.name() == vote.contested_name)?; - Some( - card.nodes - .iter() - .filter(|node| node.status.can_submit()) - .filter(|node| { - node.current != Some(vote.vote_choice) - || !card.vote_poll_id.is_some_and(|poll| { - vote_proof_can_decide( - self.vote_state.proved_at(node.node, poll), - now, - ) - }) - }) - .count(), - ) - }) - .sum() + 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; + } + } + } + counts } /// Show one contest by normalized label: the view holding its card, the @@ -1288,14 +1309,20 @@ impl DPNSScreen { if decisions == 0 { return; } - let transactions = self.transaction_count(); + 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 > 0 && self.pending_vote_operation.is_none(), + transactions + rechecks > 0 && self.pending_vote_operation.is_none(), "Cast", ) .disabled_tooltip(if self.pending_vote_operation.is_some() { @@ -2017,7 +2044,10 @@ impl DPNSScreen { ui.label(row); } ui.add_space(6.0); - ui.label(confirm_transactions_line(plan.effective_count())); + ui.label(confirm_transactions_line(plan.transaction_count())); + 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( @@ -2093,7 +2123,9 @@ impl DPNSScreen { .default_open(false) .show(ui, |ui| self.render_adjust_nodes(ui, plan.as_ref().ok())); - let transactions = plan.as_ref().map_or(0, ReviewPlan::effective_count); + 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." @@ -2115,13 +2147,13 @@ impl DPNSScreen { ) }) }); - let can_submit = transactions > 0 && !repeated_enter; + 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, all_now), + confirm_button_label(transactions, rechecks, all_now), ) .disabled_tooltip(submit_disabled_reason) .clicked(); @@ -2243,19 +2275,7 @@ impl DPNSScreen { 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)); - let requested = vote_choice_label( - target.requested_choice, - self.candidate_name(&target.contested_name, target.requested_choice), - ); - let current = review_current_choice_label( - target.current_choice, - target - .current_choice - .and_then(|choice| self.candidate_name(&target.contested_name, choice)), - ); - ui.label(format!( - "Current choice: {current}. Requested choice: {requested}." - )); + 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)), @@ -2281,6 +2301,27 @@ impl DPNSScreen { }); } + /// 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) + } + /// 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. /// @@ -4868,18 +4909,41 @@ mod tests { /// 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. + /// 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 = 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(); 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" + ); let four_minutes_ago = now_ms() - 4 * 60_000; screen @@ -4898,10 +4962,55 @@ mod tests { "the proof is still fresh enough to display" ); + screen.rebuild_cards(); + 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 [ + "0 transactions, one per node and name. Voting is free for your nodes.", + "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}" + ); + } + 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}" + ); + } } /// A node set to "when voting is about to end" must use the lead time the From 267c6d9d3f9b7d7418b61e75ba0b6387739f1a28 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:50:42 +0000 Subject: [PATCH 181/194] refactor(dpns): build a voting node and map its kind in one place The votes screen, the node-set resolver and the node detail header each mapped an identity type to a vote weight or node kind, and the first two built `VotingNode` field by field. `VotingNodeKind: From` now holds the mapping, `AppContext::dpns_voting_node` builds the node, and the detail header takes its weight from `node_weight`. The screen keeps composing from its own loaded voting identities plus the key-less nodes read from storage, so node order and the degraded-read fallback are unchanged. Its `has_voting_key` now comes from `can_cast_masternode_vote` instead of a literal `true`: the same predicate `loaded_voting_identities` already filters that list on. Addresses RUST-028. Co-Authored-By: Claude Fable 5.1 --- src/context/dpns_vote_attention.rs | 33 +++++++++++----------- src/model/dpns_voting/operator.rs | 12 ++++++++ src/ui/dpns/dpns_contested_names_screen.rs | 20 ++----------- src/ui/masternodes/detail_screen.rs | 9 ++---- 4 files changed, 33 insertions(+), 41 deletions(-) diff --git a/src/context/dpns_vote_attention.rs b/src/context/dpns_vote_attention.rs index b72f79282..78cc8be3a 100644 --- a/src/context/dpns_vote_attention.rs +++ b/src/context/dpns_vote_attention.rs @@ -8,14 +8,14 @@ use super::AppContext; use crate::backend_task::error::TaskError; use crate::model::dpns_voting::operator::{ AttentionSummary, ChangesLeft, ContestAttention, ListMembership, NodeVoteRow, VotingNode, - VotingNodeKind, changes_left, contest_needs_decision, + 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::IdentityType; +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; @@ -185,25 +185,24 @@ impl AppContext { } } + /// 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()? - .into_iter() - .map(|identity| { - let id = identity.identity.id(); - VotingNode { - id, - kind: if identity.identity_type == IdentityType::Evonode { - VotingNodeKind::Evonode - } else { - VotingNodeKind::Masternode - }, - has_voting_key: identity.can_cast_masternode_vote(), - membership: self.masternode_list_membership(id), - alias: identity.alias.clone(), - } - }) + .iter() + .map(|identity| self.dpns_voting_node(identity)) .collect()) } diff --git a/src/model/dpns_voting/operator.rs b/src/model/dpns_voting/operator.rs index 925bca562..567ef19d3 100644 --- a/src/model/dpns_voting/operator.rs +++ b/src/model/dpns_voting/operator.rs @@ -6,6 +6,7 @@ //! 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; @@ -49,6 +50,17 @@ pub enum VotingNodeKind { 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 { diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 878a7d5ca..e6724d3c2 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -30,8 +30,8 @@ use crate::model::dpns_voting::composer::{ }; use crate::model::dpns_voting::operator::NodeExclusion; use crate::model::dpns_voting::operator::{ - ChangesLeft, NodeSet, ResolvedNodeSet, VotingNode, VotingNodeKind, relative_schedule_preset, - time_left, vote_proof_can_decide, + 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::{ @@ -39,7 +39,6 @@ use crate::model::dpns_voting::{ DpnsVoteOperationId, DpnsVoteOutcome, DpnsVoteTarget, DpnsVoteTargetKey, DpnsVoteTargetStatus, VoteTiming, dpns_schedule_is_overdue, validate_dpns_schedule_time, }; -use crate::model::qualified_identity::IdentityType; use crate::model::qualified_identity::QualifiedIdentity; use crate::ui::components::component_trait::{Component, ComponentResponse}; use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; @@ -813,20 +812,7 @@ impl DPNSScreen { let mut nodes: Vec = self .voting_identities .iter() - .map(|identity| { - let id = identity.identity.id(); - VotingNode { - id, - kind: if identity.identity_type == IdentityType::Evonode { - VotingNodeKind::Evonode - } else { - VotingNodeKind::Masternode - }, - has_voting_key: true, - membership: self.app_context.masternode_list_membership(id), - alias: identity.alias.clone(), - } - }) + .map(|identity| self.app_context.dpns_voting_node(identity)) .collect(); match self.app_context.dpns_voting_nodes() { Ok(all) => { diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index 061969a15..650f85daf 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -22,9 +22,7 @@ use crate::backend_task::identity::{IdentityInputToLoad, IdentityLoadMode, Ident use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; use crate::context::AppContext; use crate::context::identity_load_registry::{IdentityLoadPhase, IdentityLoadToken}; -use crate::model::dpns_voting::operator::{ - EVONODE_VOTE_WEIGHT, ListMembership, MASTERNODE_VOTE_WEIGHT, NodeVoteRow, time_left, -}; +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}; @@ -456,10 +454,7 @@ impl MasternodeDetailView { ui.ctx().copy_text(self.node_id_hex_full.clone()); } draw_type_badge(ui, self.badge_label(), dark_mode); - let weight = match self.identity.identity_type { - IdentityType::Evonode => EVONODE_VOTE_WEIGHT, - _ => MASTERNODE_VOTE_WEIGHT, - }; + let weight = node_weight(self.identity.identity_type.into()); ui.label( RichText::new(voting_weight_label(weight)) .color(DashColors::text_secondary(dark_mode)), From 45cce5cb06d46161b16259078ac1471e4ce8dc29 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:51:16 +0000 Subject: [PATCH 182/194] refactor(dpns): carry the composer's error instead of restating it `ReviewPlanError` redeclared `ScheduleOutlastsContest` and `VotingEnded` with their own sentences and re-mapped `ComposeError` field by field; the two copies of the voting-ended sentence had already drifted apart. `ReviewPlanError::Compose` now wraps the composer's error transparently, so each condition has one sentence. The model takes the wording the operator has been reading ("Clear it from your decisions."); its own variant was never displayed. A test pins both sentences as shown. Addresses RUST-030. Co-Authored-By: Claude Fable 5.1 --- src/model/dpns_voting/composer.rs | 2 +- src/ui/dpns/dpns_contested_names_screen.rs | 41 +++++++++++++--------- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/src/model/dpns_voting/composer.rs b/src/model/dpns_voting/composer.rs index 538994b93..76bb36e96 100644 --- a/src/model/dpns_voting/composer.rs +++ b/src/model/dpns_voting/composer.rs @@ -92,7 +92,7 @@ pub struct SkippedTarget { 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. Remove it from your decisions.")] + #[error("Voting has ended for {contested_name}.dash. Clear it from your decisions.")] VotingEnded { contested_name: String }, } diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index e6724d3c2..90099c2dc 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -337,26 +337,14 @@ pub enum ReviewPlanError { ScheduleIsNotInTheFuture, #[error("Choose a valid UTC date and time.")] ScheduleIsNotAValidTime, - #[error("Choose a future time before the contest ends for {contested_name}.dash.")] - ScheduleOutlastsContest { contested_name: String }, #[error("This vote could not be prepared. Refresh the contests and try again.")] VotePollUnavailable { #[source] source: Arc, }, - #[error("Voting has ended for {contested_name}.dash. Clear it from your decisions.")] - VotingEnded { contested_name: String }, -} - -impl From for ReviewPlanError { - fn from(error: ComposeError) -> Self { - match error { - ComposeError::ScheduleOutlastsContest { contested_name } => { - Self::ScheduleOutlastsContest { contested_name } - } - ComposeError::VotingEnded { contested_name } => Self::VotingEnded { contested_name }, - } - } + /// The composer refused the selection; the sentence is the composer's. + #[error(transparent)] + Compose(#[from] ComposeError), } /// Why a submit click produced nothing to send. @@ -4116,7 +4104,8 @@ mod tests { }; assert!(matches!( error, - ReviewPlanError::ScheduleOutlastsContest { contested_name } if contested_name == "beta" + ReviewPlanError::Compose(ComposeError::ScheduleOutlastsContest { contested_name }) + if contested_name == "beta" )); } @@ -5202,6 +5191,26 @@ mod tests { ); } + /// The composer words its own refusals; the confirm step and the + /// submission banner show them unchanged. + #[test] + 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." + ); + } + #[test] fn review_labels_previous_choices() { assert_eq!( From 92f655b5d3c6a2d4280e796cdf6b659d636d54da Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:52:45 +0000 Subject: [PATCH 183/194] refactor(dpns): let the votes panel say which results it handles `app.rs` kept its own list of the results `DPNSScreen::display_task_result` acts on, and a test embedded the screen's source with `include_str!` and scraped it for `BackendTaskSuccessResult::` tokens to keep the two lists in step. That guard depended on rustfmt indentation, on the method name and on no variant being reached through a helper. The screen now classifies a result once, in `VotesPanelResult::of`. `display_task_result` matches exhaustively on that type and `DPNSScreen::handles_result`, which hidden-panel routing calls, is derived from it, so a result cannot be handled without being routed. The same five results are routed and handled as before, with the same network checks. The source-scraping test is replaced by one that checks routing against `handles_result` for the handled results and for unrelated ones. Addresses RUST-022. Co-Authored-By: Claude Fable 5.1 --- src/app.rs | 114 +++++++-------------- src/ui/dpns/dpns_contested_names_screen.rs | 75 +++++++++++--- 2 files changed, 99 insertions(+), 90 deletions(-) diff --git a/src/app.rs b/src/app.rs index 2fe3ec998..facc473a3 100644 --- a/src/app.rs +++ b/src/app.rs @@ -28,6 +28,7 @@ use crate::ui::components::{BannerHandle, MessageBanner, OptionBannerExt, Progre use crate::ui::contracts_documents::contracts_documents_screen::DocumentQueryScreen; use crate::ui::dashpay::{DashPayScreen, DashPaySubscreen, ProfileSearchScreen}; 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; @@ -449,22 +450,6 @@ fn identity_hub_is_visible(selected: RootScreenType, screen_stack_is_empty: bool /// The root screen hosting the voting workspace (Masternodes β–Έ Votes). const VOTING_ROOT_SCREEN: RootScreenType = RootScreenType::RootScreenMasternodes; -/// Every result `DPNSScreen::display_task_result` acts on, so that the voting -/// panel receives it even while its root screen is hidden. Dropping a variant here without -/// dropping its handler arm strands the screen in the state that result would -/// have cleared. `dpns_result_routing_tests` reads the handler's source and -/// fails if the two sets drift apart. -fn is_dpns_vote_result(result: &BackendTaskSuccessResult) -> bool { - matches!( - result, - BackendTaskSuccessResult::DpnsVoteOperationUpdated { .. } - | BackendTaskSuccessResult::RefreshedDpnsContests - | BackendTaskSuccessResult::ScheduledVoteSweepCompleted { .. } - | BackendTaskSuccessResult::ScheduledVotesCleared(_) - | BackendTaskSuccessResult::ScheduledVotesInProgress(_) - ) -} - /// 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. @@ -482,7 +467,10 @@ fn dpns_result_needs_hidden_route( screen_stack_is_empty: bool, result: &BackendTaskSuccessResult, ) -> bool { - is_dpns_vote_result(result) && dpns_screen_is_hidden(target, selected, screen_stack_is_empty) + // 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: @@ -4963,71 +4951,41 @@ mod dpns_result_routing_tests { )); } - /// The DPNS screen's own source, read at compile time so the guard below - /// tracks the handler instead of a hand-copied list of variant names. - const DPNS_SCREEN_SOURCE: &str = include_str!("ui/dpns/dpns_contested_names_screen.rs"); - - /// Result variant names `DPNSScreen::display_task_result` matches on. - fn variants_the_dpns_screen_handles() -> Vec { - const MARKER: &str = "BackendTaskSuccessResult::"; - let start = DPNS_SCREEN_SOURCE - .find("fn display_task_result(") - .expect("DPNSScreen::display_task_result was renamed; update this guard"); - let handler = &DPNS_SCREEN_SOURCE[start..]; - let end = handler[1..] - .find("\n fn ") - .map_or(handler.len(), |offset| offset + 1); - let handler = &handler[..end]; - - let mut variants: Vec = Vec::new(); - for (index, _) in handler.match_indices(MARKER) { - let name: String = handler[index + MARKER.len()..] - .chars() - .take_while(|character| character.is_alphanumeric() || *character == '_') - .collect(); - if !name.is_empty() && !variants.contains(&name) { - variants.push(name); - } - } - assert!( - !variants.is_empty(), - "no handled variants found; the guard no longer locates DPNSScreen::display_task_result" - ); - variants - } - - fn sample_result(variant: &str) -> BackendTaskSuccessResult { - match variant { - "DpnsVoteOperationUpdated" => BackendTaskSuccessResult::DpnsVoteOperationUpdated { + /// 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]), }, - "ScheduledVoteSweepCompleted" => { - BackendTaskSuccessResult::ScheduledVoteSweepCompleted { - network: Network::Testnet, - preserve_eligibility_since_ms: None, - } - } - "ScheduledVotesInProgress" => { - BackendTaskSuccessResult::ScheduledVotesInProgress(Vec::new()) - } - "ScheduledVotesCleared" => BackendTaskSuccessResult::ScheduledVotesCleared(Vec::new()), - "RefreshedDpnsContests" => BackendTaskSuccessResult::RefreshedDpnsContests, - unknown => panic!( - "DPNSScreen::display_task_result now handles {unknown}; add a sample here and route it in is_dpns_vote_result" - ), + 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)); } - } - - /// A result the DPNS screen acts on but `is_dpns_vote_result` rejects is - /// dropped whenever that screen is hidden, so the two sets must agree. - #[test] - fn every_result_the_dpns_screen_handles_is_routed_to_hidden_screens() { - for variant in variants_the_dpns_screen_handles() { - assert!( - is_dpns_vote_result(&sample_result(&variant)), - "DPNSScreen::display_task_result handles {variant} but is_dpns_vote_result drops it while the screen is hidden" - ); + for unrelated in [ + BackendTaskSuccessResult::None, + BackendTaskSuccessResult::Refresh, + BackendTaskSuccessResult::MyUsernameRequestsRefreshed, + ] { + assert!(!DPNSScreen::handles_result(&unrelated)); + assert!(!hidden(&unrelated)); } } diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 90099c2dc..396993725 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -347,6 +347,48 @@ pub enum ReviewPlanError { 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 { @@ -523,6 +565,13 @@ pub struct DPNSScreen { } impl DPNSScreen { + /// 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())); @@ -2633,11 +2682,16 @@ impl ScreenLike for DPNSScreen { } fn display_task_result(&mut self, backend_task_success_result: BackendTaskSuccessResult) { - match backend_task_success_result { - BackendTaskSuccessResult::DpnsVoteOperationUpdated { - network, - operation_id, - } if network == self.app_context.network() => { + 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, @@ -2673,18 +2727,16 @@ impl ScreenLike for DPNSScreen { self.rebuild_cards(); self.app_context.recompute_dpns_vote_attention(); } - BackendTaskSuccessResult::ScheduledVoteSweepCompleted { network, .. } - if network == self.app_context.network() => - { + VotesPanelResult::ScheduledSweepCompleted { .. } => { self.refresh(); } - BackendTaskSuccessResult::ScheduledVotesInProgress(_) => { + 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(); } - BackendTaskSuccessResult::ScheduledVotesCleared(_) => { + VotesPanelResult::ScheduledVotesCleared => { if let Err(error) = self.vote_operations.refresh(&self.app_context) { tracing::warn!( ?error, @@ -2693,12 +2745,11 @@ impl ScreenLike for DPNSScreen { } self.rebuild_scheduled_vote_rows(); } - BackendTaskSuccessResult::RefreshedDpnsContests => { + VotesPanelResult::ContestsRefreshed => { self.refresh(); self.refresh_banner.take_and_clear(); self.refreshing_status = RefreshingStatus::NotRefreshing; } - _ => {} } } From 0dbacbadd1369255d5811c7af679874e6290b5db Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:53:56 +0000 Subject: [PATCH 184/194] refactor(dpns): remove small restatements in the voting task and copy - `ContestedResourceTask::EditScheduledDpnsVote` carries `DpnsScheduledVoteEdit` instead of restating its six fields for the dispatcher to re-pack. - `unavailable_preflight_outcome` and `failed_before_broadcast_outcome` share one body; they differ only in the failure they report. - The name-filter tooltip, "Not in the masternode list. Its votes don't count." and "Not voted yet" each lived in two places; they are constants in `ui/dpns/copy.rs` now. No sentence, status or stored format changes. Addresses RUST-033. Co-Authored-By: Claude Fable 5.1 --- src/backend_task/contested_names/mod.rs | 44 ++++--------------- src/backend_task/mod.rs | 9 ++-- src/model/dpns_voting/mod.rs | 19 +++++--- src/ui/dpns/copy.rs | 10 +++++ src/ui/dpns/dpns_contested_names_screen.rs | 18 +++----- .../scheduled_vote_editor.rs | 29 +++++++----- src/ui/dpns/node_set_picker.rs | 6 +-- src/ui/masternodes/detail_screen.rs | 8 ++-- 8 files changed, 67 insertions(+), 76 deletions(-) diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index b57007131..f7a5543ac 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -11,12 +11,12 @@ use crate::backend_task::error::{DapiAddressAvailability, TaskError}; use crate::context::{AppContext, MAX_CONCURRENT_DPNS_VOTERS}; use crate::model::contested_name::ContestedName; use crate::model::dpns_voting::{ - DpnsCurrentVoteState, DpnsScheduleEditValidationError, 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, + 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; @@ -71,14 +71,7 @@ pub enum ContestedResourceTask { operation_id: DpnsVoteOperationId, key: DpnsVoteTargetKey, }, - EditScheduledDpnsVote { - operation_id: DpnsVoteOperationId, - key: DpnsVoteTargetKey, - expected_choice: ResourceVoteChoice, - expected_timestamp: u64, - choice: ResourceVoteChoice, - unix_timestamp: u64, - }, + EditScheduledDpnsVote(DpnsScheduledVoteEdit), } #[derive(Debug, Clone, PartialEq)] @@ -320,27 +313,8 @@ impl AppContext { self.cancel_scheduled_dpns_vote_target(operation_id, &key)?; Ok(BackendTaskSuccessResult::Refresh) } - ContestedResourceTask::EditScheduledDpnsVote { - operation_id, - key, - expected_choice, - expected_timestamp, - choice, - unix_timestamp, - } => { - self.edit_scheduled_dpns_vote( - crate::model::dpns_voting::DpnsScheduledVoteEdit { - operation_id, - key, - expected_choice, - expected_timestamp, - choice, - unix_timestamp, - }, - sdk, - sender, - ) - .await + ContestedResourceTask::EditScheduledDpnsVote(edit) => { + self.edit_scheduled_dpns_vote(edit, sdk, sender).await } } } diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 8ac288420..d1a355f0e 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -410,10 +410,11 @@ impl BackendTaskContext { network, operation: Box::new(Self::from(task)), }, - BackendTask::ContestedResourceTask(ContestedResourceTask::EditScheduledDpnsVote { - key, - .. - }) => Self::DpnsScheduledVoteEdit { key: key.clone() }, + BackendTask::ContestedResourceTask(ContestedResourceTask::EditScheduledDpnsVote( + edit, + )) => Self::DpnsScheduledVoteEdit { + key: edit.key.clone(), + }, BackendTask::ContestedResourceTask(ContestedResourceTask::CastScheduledVote( vote, _, diff --git a/src/model/dpns_voting/mod.rs b/src/model/dpns_voting/mod.rs index 0f3811c4f..2c00a3de0 100644 --- a/src/model/dpns_voting/mod.rs +++ b/src/model/dpns_voting/mod.rs @@ -180,24 +180,29 @@ pub enum VoteTiming { Scheduled(TimestampMillis), } -pub(crate) fn unavailable_preflight_outcome( +/// 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(DpnsVoteFailure::CurrentVoteUnavailable)) + (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) { - let status = match timing { - VoteTiming::Scheduled(_) => DpnsVoteTargetStatus::Scheduled, - VoteTiming::Now => DpnsVoteTargetStatus::FailedBeforeSubmission, - }; - (status, Some(DpnsVoteFailure::SubmissionFailed)) + not_broadcast_outcome(timing, DpnsVoteFailure::SubmissionFailed) } /// One reviewed node Γ— contest action. diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index 352c71b4c..fca007c67 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -12,6 +12,16 @@ use crate::model::dpns_voting::{ 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."; diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 396993725..ae2db41b1 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -48,10 +48,10 @@ 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, 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, + 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, @@ -323,7 +323,7 @@ fn review_current_choice_label( ) -> String { match current { Some(choice) => vote_choice_label(choice, candidate_name), - None => "Not voted yet".to_owned(), + None => NOT_VOTED_YET.to_owned(), } } @@ -1036,9 +1036,7 @@ impl DPNSScreen { .hint_text("Filter by name") .desired_width(180.0), ) - .on_hover_text( - "The letters i and l match the digit 1, and the letter o matches 0.", - ); + .on_hover_text(NAME_FILTER_LOOKALIKES_HINT); if filter.has_focus() { self.list_focused = false; } @@ -1468,9 +1466,7 @@ impl DPNSScreen { 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) - .on_hover_text( - "The letters i and l match the digit 1, and the letter o matches 0.", - ); + .on_hover_text(NAME_FILTER_LOOKALIKES_HINT); }); let contested_names = { 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 index fac86d115..ca7ad197c 100644 --- a/src/ui/dpns/dpns_contested_names_screen/scheduled_vote_editor.rs +++ b/src/ui/dpns/dpns_contested_names_screen/scheduled_vote_editor.rs @@ -1,6 +1,7 @@ //! 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 { @@ -71,14 +72,16 @@ impl ScheduledVoteEditor { { return None; } - Some(ContestedResourceTask::EditScheduledDpnsVote { - 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, - }) + 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 { @@ -180,14 +183,14 @@ mod tests { ) .unwrap(); editor.choice = ResourceVoteChoice::Abstain; - let ContestedResourceTask::EditScheduledDpnsVote { + let ContestedResourceTask::EditScheduledDpnsVote(DpnsScheduledVoteEdit { operation_id, key: edited_key, expected_choice, expected_timestamp, choice, unix_timestamp, - } = editor.task(1).unwrap() + }) = editor.task(1).unwrap() else { panic!("expected edit"); }; @@ -208,8 +211,10 @@ mod tests { .expect("valid test instant") .and_utc(), ); - let ContestedResourceTask::EditScheduledDpnsVote { unix_timestamp, .. } = - editor.task(1).unwrap() + let ContestedResourceTask::EditScheduledDpnsVote(DpnsScheduledVoteEdit { + unix_timestamp, + .. + }) = editor.task(1).unwrap() else { panic!("expected edit"); }; diff --git a/src/ui/dpns/node_set_picker.rs b/src/ui/dpns/node_set_picker.rs index 6996ebc27..647916a7c 100644 --- a/src/ui/dpns/node_set_picker.rs +++ b/src/ui/dpns/node_set_picker.rs @@ -5,7 +5,7 @@ use crate::model::dpns_voting::operator::{ node_exclusion, }; use crate::ui::dpns::contest_card::node_label; -use crate::ui::dpns::copy::node_set_chip_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}; @@ -23,9 +23,7 @@ pub fn node_set_name(set: &NodeSet) -> &'static str { 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 the masternode list. Its votes don't count.") - } + Some(NodeExclusion::NotInMasternodeList) => Some(NOT_IN_MASTERNODE_LIST), None if node.membership == ListMembership::Unknown => { Some("Masternode list membership unknown.") } diff --git a/src/ui/masternodes/detail_screen.rs b/src/ui/masternodes/detail_screen.rs index 650f85daf..de89449ec 100644 --- a/src/ui/masternodes/detail_screen.rs +++ b/src/ui/masternodes/detail_screen.rs @@ -32,7 +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::{changes_left_label, ends_in_label, voting_weight_label}; +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; @@ -193,7 +195,7 @@ impl MasternodeDetailView { 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, None) => NOT_VOTED_YET.to_owned(), (true, Some(choice)) => { crate::ui::dpns::copy::vote_choice_label(choice, row.contender_name.as_deref()) } @@ -853,7 +855,7 @@ impl MasternodeDetailView { 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 the masternode list. Its votes don't count.", + ListMembership::NotListed => NOT_IN_MASTERNODE_LIST, ListMembership::Unknown => "Masternode list membership unknown.", }; ui.label(RichText::new(membership).color(DashColors::text_secondary(dark_mode))); From f218785a0695c9bccc40b5c1292238d3b578b239 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:54:49 +0000 Subject: [PATCH 185/194] test(identity): share one bare user identity fixture Five test modules each spelled out the same 15-field `QualifiedIdentity` literal for a user identity with no names, alias, keys or wallet, so every new field cost five more edits. `context::test_support::bare_user_identity(id, network)` builds it once; the five sites call it with the identifier and network they used before. Addresses RUST-025. Co-Authored-By: Claude Fable 5.1 --- src/backend_task/identity/dpns_usernames.rs | 39 ++++--------------- .../refresh_loaded_identities_dpns_names.rs | 26 ++----------- .../identity/register_dpns_name.rs | 26 ++----------- src/context/test_support.rs | 28 +++++++++++++ src/ui/identity/username_notices.rs | 26 ++----------- src/ui/identity/usernames_card.rs | 25 ++---------- 6 files changed, 51 insertions(+), 119 deletions(-) diff --git a/src/backend_task/identity/dpns_usernames.rs b/src/backend_task/identity/dpns_usernames.rs index 903d87c20..3af5c4d0e 100644 --- a/src/backend_task/identity/dpns_usernames.rs +++ b/src/backend_task/identity/dpns_usernames.rs @@ -431,38 +431,13 @@ impl AppContext { #[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, }; - fn bare_identity( - id: Identifier, - network: dash_sdk::dpp::dashcore::Network, - ) -> QualifiedIdentity { - QualifiedIdentity { - identity: dash_sdk::dpp::identity::Identity::create_basic_identity( - id, - dash_sdk::dpp::version::PlatformVersion::latest(), - ) - .unwrap(), - associated_voter_identity: None, - associated_operator_identity: None, - associated_owner_key_id: None, - identity_type: crate::model::qualified_identity::IdentityType::User, - alias: None, - private_keys: Default::default(), - dpns_names: vec![], - associated_wallets: Default::default(), - secret_access: None, - wallet_index: None, - top_ups: Default::default(), - status: crate::model::qualified_identity::IdentityStatus::Active, - network, - } - } - async fn sdk_with_owned_name(ctx: &AppContext, id: Identifier) -> Sdk { let query = DocumentQuery { sub_queries: vec![], @@ -520,7 +495,7 @@ mod tests { std::sync::Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()), )); let id = Identifier::from([42; 32]); - let identity = bare_identity(id, ctx.network); + let identity = bare_user_identity(id, ctx.network); ctx.insert_local_qualified_identity_sidecar_only(&identity) .unwrap(); let sdk = Sdk::new_mock(); @@ -558,7 +533,7 @@ mod tests { std::sync::Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()), )); let id = Identifier::from([42; 32]); - let captured = bare_identity(id, ctx.network); + let captured = bare_user_identity(id, ctx.network); ctx.insert_local_qualified_identity_sidecar_only(&captured) .unwrap(); let sdk = Sdk::new_mock(); @@ -611,7 +586,7 @@ mod tests { 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_identity(id, ctx.network)) + ctx.insert_local_qualified_identity_sidecar_only(&bare_user_identity(id, ctx.network)) .unwrap(); ctx.store_username_requests( &id, @@ -692,7 +667,7 @@ mod tests { 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_identity(id, ctx.network); + let identity = bare_user_identity(id, ctx.network); ctx.insert_local_qualified_identity_sidecar_only(&identity) .unwrap(); let mut won = UsernameRequest::submitted( @@ -758,7 +733,7 @@ mod tests { std::sync::Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()), )); let id = Identifier::from([44; 32]); - let identity = bare_identity(id, ctx.network); + let identity = bare_user_identity(id, ctx.network); ctx.insert_local_qualified_identity_sidecar_only(&identity) .unwrap(); let mut won = UsernameRequest::submitted( @@ -802,7 +777,7 @@ mod tests { std::sync::Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()), )); let id = Identifier::from([42; 32]); - let identity = bare_identity(id, ctx.network); + let identity = bare_user_identity(id, ctx.network); ctx.insert_local_qualified_identity_sidecar_only(&identity) .unwrap(); ctx.store_username_requests( 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 cd1d98ef8..a4e2a926e 100644 --- a/src/backend_task/identity/refresh_loaded_identities_dpns_names.rs +++ b/src/backend_task/identity/refresh_loaded_identities_dpns_names.rs @@ -125,28 +125,10 @@ impl AppContext { mod tests { use super::*; fn bare_identity(byte: u8) -> crate::model::qualified_identity::QualifiedIdentity { - use crate::model::qualified_identity::encrypted_key_storage::KeyStorage; - use crate::model::qualified_identity::{IdentityStatus, IdentityType, QualifiedIdentity}; - QualifiedIdentity { - identity: dash_sdk::platform::Identity::create_basic_identity( - [byte; 32].into(), - 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: dash_sdk::dpp::dashcore::Network::Testnet, - } + crate::context::test_support::bare_user_identity( + [byte; 32].into(), + dash_sdk::dpp::dashcore::Network::Testnet, + ) } #[test] diff --git a/src/backend_task/identity/register_dpns_name.rs b/src/backend_task/identity/register_dpns_name.rs index 779987c5d..6d496ad27 100644 --- a/src/backend_task/identity/register_dpns_name.rs +++ b/src/backend_task/identity/register_dpns_name.rs @@ -489,28 +489,10 @@ mod tests { /// A user identity with no names, alias, or keys. fn bare_identity(byte: u8) -> crate::model::qualified_identity::QualifiedIdentity { - use crate::model::qualified_identity::encrypted_key_storage::KeyStorage; - use crate::model::qualified_identity::{IdentityStatus, IdentityType, QualifiedIdentity}; - QualifiedIdentity { - identity: dash_sdk::platform::Identity::create_basic_identity( - [byte; 32].into(), - 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: dash_sdk::dpp::dashcore::Network::Testnet, - } + crate::context::test_support::bare_user_identity( + [byte; 32].into(), + dash_sdk::dpp::dashcore::Network::Testnet, + ) } #[tokio::test] 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/ui/identity/username_notices.rs b/src/ui/identity/username_notices.rs index 743308558..096b4c8f9 100644 --- a/src/ui/identity/username_notices.rs +++ b/src/ui/identity/username_notices.rs @@ -214,8 +214,6 @@ mod tests { #[test] fn failing_seen_store_is_not_retried_every_frame() { use crate::model::dpns_usernames::{SEEN_MARK_MAX_FAILURES, UsernameRequest}; - use crate::model::qualified_identity::encrypted_key_storage::KeyStorage; - use crate::model::qualified_identity::{IdentityStatus, IdentityType}; use crate::utils::egui_mpsc::SenderAsync; use crate::wallet_backend::DetKv; use crate::wallet_backend::kv_test_support::FailingKv; @@ -224,26 +222,10 @@ mod tests { 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 = QualifiedIdentity { - identity: dash_sdk::dpp::identity::Identity::create_basic_identity( - [0x61; 32].into(), - 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: dash_sdk::dpp::dashcore::Network::Testnet, - }; + 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", diff --git a/src/ui/identity/usernames_card.rs b/src/ui/identity/usernames_card.rs index 601361d30..2ec9e8ba1 100644 --- a/src/ui/identity/usernames_card.rs +++ b/src/ui/identity/usernames_card.rs @@ -385,27 +385,10 @@ mod tests { use std::time::Duration; fn identity(names: &[&str]) -> QualifiedIdentity { - use crate::model::qualified_identity::encrypted_key_storage::KeyStorage; - use crate::model::qualified_identity::{IdentityStatus, IdentityType}; - use dash_sdk::dpp::identity::Identity; - use dash_sdk::dpp::version::PlatformVersion; - let mut identity = QualifiedIdentity { - identity: Identity::create_basic_identity([1; 32].into(), 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: dash_sdk::dpp::dashcore::Network::Testnet, - }; + 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 { From 4bb9406f05016165333e133c58d707af1a50532a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:58:10 +0000 Subject: [PATCH 186/194] refactor(identity): keep the username sentences in the copy module `username_copy.rs` is the home of identity-username copy, yet several sentences lived inline in the screens and some existed twice: - "Add a key to this identity to register usernames." (card and register screen) and "People can now find and pay you by this name." (done page and won banner) are constants used from both places. - "The community vote ended on {date}." is one function shared by the card and the request timeline. - The can't-check availability row and `TaskError::UsernameAvailabilityCheckFailed` share one constant instead of two copies of the sentence. - The card detail lines, the Home card sentence, the outcome banners, the done page and the two per-keystroke check labels move into the module. - `validate_dpns_name` uses `MAX_LABEL_LEN` instead of a second literal 63. Every sentence is moved byte for byte. The length rule ("Between 3 and 63 characters.") and the per-keystroke check label (the same words without the full stop) stay two strings, now side by side, because merging them would change what one of them displays. Addresses RUST-018. Co-Authored-By: Claude Fable 5.1 --- src/backend_task/error.rs | 10 +- src/model/dpns.rs | 2 +- src/ui/identity/register_dpns_name_screen.rs | 28 ++- src/ui/identity/username_copy.rs | 180 +++++++++++++++++-- src/ui/identity/username_notices.rs | 33 +--- src/ui/identity/usernames_card.rs | 40 ++--- 6 files changed, 200 insertions(+), 93 deletions(-) diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 4fb847ad3..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 { @@ -2098,9 +2104,7 @@ pub enum TaskError { InvalidPrivateKey, /// The network could not be asked whether a username is free. - #[error( - "Availability can't be checked right now. Check your internet connection and try again." - )] + #[error("{}", USERNAME_AVAILABILITY_CHECK_FAILED)] UsernameAvailabilityCheckFailed { #[source] source: Box, diff --git a/src/model/dpns.rs b/src/model/dpns.rs index 8eb55751e..6bcb73a60 100644 --- a/src/model/dpns.rs +++ b/src/model/dpns.rs @@ -181,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('-') { diff --git a/src/ui/identity/register_dpns_name_screen.rs b/src/ui/identity/register_dpns_name_screen.rs index 2c95c2ecf..b338395b6 100644 --- a/src/ui/identity/register_dpns_name_screen.rs +++ b/src/ui/identity/register_dpns_name_screen.rs @@ -664,11 +664,11 @@ impl RegisterDpnsNameScreen { ui.add_space(40.0); match outcome { DpnsRegistrationOutcome::Registered => { - ui.heading(format!("You're @{name}")); - ui.label("People can now find and pay you by this name."); + ui.heading(username_copy::registered_heading(&name)); + ui.label(username_copy::NAME_REGISTERED_LINE); } DpnsRegistrationOutcome::PendingCommunityVote => { - ui.heading(format!("Your request for @{name} is in")); + 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()) @@ -678,20 +678,12 @@ impl RegisterDpnsNameScreen { if let Some(request) = request && let (Some(join_end), Some(end)) = (request.join_end, request.end) { - ui.label(format!( - "Others can still ask for this name until {join}. The community vote ends around {end}.", - join = username_copy::format_date_time(join_end), - end = username_copy::format_date(end) - )); + ui.label(username_copy::request_schedule_line(join_end, end)); } - ui.label(format!( - "If no one else asks and no one votes to lock it, @{name} becomes yours then." - )); + ui.label(username_copy::request_uncontested_line(&name)); ui.label( - RichText::new( - "We'll show the result on your identity's page. You don't need to keep this screen open.", - ) - .color(DashColors::text_secondary(dark_mode)), + RichText::new(username_copy::REQUEST_RESULT_NOTE) + .color(DashColors::text_secondary(dark_mode)), ); } } @@ -735,13 +727,13 @@ fn render_format_checks(ui: &mut Ui, label: &str, dark_mode: bool) { status_line( ui, tone(length_ok), - "Between 3 and 63 characters", + username_copy::LENGTH_CHECK_LABEL, dark_mode, ); status_line( ui, tone(chars_ok), - "Only letters, numbers, and hyphens", + username_copy::CHARACTERS_CHECK_LABEL, dark_mode, ); if matches!( @@ -895,7 +887,7 @@ impl ScreenLike for RegisterDpnsNameScreen { status_line( ui, Tone::Negative, - "Add a key to this identity to register usernames.", + username_copy::NEEDS_KEY_TO_REGISTER, dark_mode, ); return; diff --git a/src/ui/identity/username_copy.rs b/src/ui/identity/username_copy.rs index 9fa44acdf..50b74aa5e 100644 --- a/src/ui/identity/username_copy.rs +++ b/src/ui/identity/username_copy.rs @@ -8,6 +8,7 @@ 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; @@ -88,19 +89,13 @@ pub fn format_duration(duration: Duration) -> String { /// 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::Checking => (Tone::Neutral, format!("Checking if @{name} is available…")), AvailabilityRow::CantCheck => ( Tone::Negative, - "Availability can't be checked right now. Check your internet connection and try again." - .to_owned(), + USERNAME_AVAILABILITY_CHECK_FAILED.to_owned(), ), AvailabilityRow::Known(availability) => match availability { - UsernameAvailability::Available => { - (Tone::Positive, format!("@{name} is available.")) - } + UsernameAvailability::Available => (Tone::Positive, format!("@{name} is available.")), UsernameAvailability::NeedsVote => ( Tone::Caution, format!("@{name} is available, but it needs a community vote."), @@ -163,6 +158,134 @@ pub const USERNAME_RULES: [&str; 4] = [ "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") @@ -253,10 +376,7 @@ pub fn voting_timeline_line(end: TimestampMillis, phase: RequestPhase) -> String "The estimated voting period ended around {date}.", date = format_date(end) ), - _ => format!( - "The community vote ended on {date}.", - date = format_date(end) - ), + _ => vote_ended_on_line(end), } } @@ -321,6 +441,40 @@ mod tests { } } + /// 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 diff --git a/src/ui/identity/username_notices.rs b/src/ui/identity/username_notices.rs index 096b4c8f9..3f1127b37 100644 --- a/src/ui/identity/username_notices.rs +++ b/src/ui/identity/username_notices.rs @@ -16,7 +16,9 @@ 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, format_date, phase_label, standing_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}; @@ -34,22 +36,7 @@ struct SessionBanners { /// Text of the one-time banner for a finished request, if it gets one. pub fn outcome_banner_text(request: &UsernameRequest) -> Option { - let name = &request.label; - match request.phase { - RequestPhase::Won => Some(format!( - "You're @{name}. People can now find and pay you by this name." - )), - 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, - } + outcome_banner_line(&request.label, request.phase) } fn banner_key(identity_id: &Identifier, request: &UsernameRequest) -> String { @@ -127,17 +114,7 @@ pub fn render( 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 name = &request.label; - let first = match (request.phase, request.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."), - }; + 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( diff --git a/src/ui/identity/usernames_card.rs b/src/ui/identity/usernames_card.rs index 2ec9e8ba1..aed0a52bf 100644 --- a/src/ui/identity/usernames_card.rs +++ b/src/ui/identity/usernames_card.rs @@ -20,7 +20,10 @@ 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::{Tone, format_date, phase_label}; +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. @@ -187,7 +190,7 @@ impl UsernamesCard { }); if acquired_at > 0 { ui.label( - RichText::new(format!("Registered on {}.", format_date(acquired_at))) + RichText::new(registered_on_line(acquired_at)) .small() .color(DashColors::text_secondary(dark_mode)), ); @@ -201,19 +204,9 @@ impl UsernamesCard { action = request_status_action(app_context, identity, &request); } }); - let detail = match (request.phase, request.join_end, request.end) { - (RequestPhase::Joinable, Some(join_end), _) => format!( - "Others can ask for this name until {}. Masternodes can already vote.", - format_date(join_end) - ), - (RequestPhase::AwaitingOutcome, _, _) => - "The estimated voting period has ended. View the status to check the outcome.".to_owned(), - (_, _, Some(end)) => { - format!("Voting ends around {}.", format_date(end)) - } - _ => String::new(), - }; - if !detail.is_empty() { + if let Some(detail) = + pending_request_detail(request.phase, request.join_end, request.end) + { ui.label( RichText::new(detail) .small() @@ -226,21 +219,8 @@ impl UsernamesCard { ui.label(RichText::new(format!("@{}", request.label)).strong()); status_line(ui, Tone::Negative, phase_label(request.phase), dark_mode); }); - let detail = match request.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() - } - _ => request.decided_at.map_or_else( - || "The community vote ended.".to_owned(), - |at| format!("The community vote ended on {}.", format_date(at)), - ), - }; ui.label( - RichText::new(detail) + RichText::new(finished_request_detail(request.phase, request.decided_at)) .small() .color(DashColors::text_secondary(dark_mode)), ); @@ -357,7 +337,7 @@ fn get_username_button( label: &str, ) -> AppAction { let mut action = AppAction::None; - let reason = "Add a key to this identity to register usernames."; + let reason = NEEDS_KEY_TO_REGISTER; let clicked = ComponentStyles::add_primary_button_enabled(ui, can_register, label) .disabled_tooltip(reason) .clicked(); From 9214ac258aa478f27b2afb9b7b935f43ab131c39 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 12:12:34 +0000 Subject: [PATCH 187/194] fix(dpns): do not announce a vote that is only checked again as sent now With "when voting is about to end" and a contest already inside the lead time, `compose` counted every target in `ends_soon_now`, including nodes that are only checked again. The confirm step then read "N of these votes will be sent now because voting ends soon." beside a sentence saying that nothing is sent for the same votes. The count now covers only targets that send a vote, so the line drops to the real number and disappears when no such vote is left. Addresses PROJ-001. Co-Authored-By: Claude Fable 5.1 --- .../01-requirements.md | 4 +- src/model/dpns_voting/composer.rs | 48 +++++++++++++++++-- 2 files changed, 48 insertions(+), 4 deletions(-) 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 index d182f67d9..de05358af 100644 --- 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 @@ -337,7 +337,9 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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.` Every other contest is + 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 diff --git a/src/model/dpns_voting/composer.rs b/src/model/dpns_voting/composer.rs index 76bb36e96..4f9743dda 100644 --- a/src/model/dpns_voting/composer.rs +++ b/src/model/dpns_voting/composer.rs @@ -106,8 +106,9 @@ pub struct AggregatePlan { /// transactions the operator can count on. pub recheck: BTreeSet, pub skipped: Vec, - /// Targets asked to vote "when voting is about to end" whose contest is - /// already inside the lead time, so they are sent now. + /// 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, } @@ -260,7 +261,7 @@ pub fn compose( plan.skipped.push(skip(SkipReason::DeadlineUnknown)); continue; }; - plan.ends_soon_now += usize::from(ends_soon); + plan.ends_soon_now += usize::from(ends_soon && !unverified_no_op); let key = DpnsVoteTargetKey { network, voter_id: node.voter_id, @@ -652,6 +653,47 @@ mod tests { assert_eq!(plan.ends_soon_now, 2); } + /// 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() { From 0bfcb2ecfd8b193944155dea26c93b91ef95f246 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 12:13:33 +0000 Subject: [PATCH 188/194] fix(dpns): skip a node with no changes left instead of checking it again For a node that used all its votes on a contest and is shown on the staged choice by proof too old to decide, the composer erased the reviewed choice before it looked at the changes left, so the node became a vote to check again. The tray leaves such a node out, so the two disagreed: Cast was disabled while Enter opened a confirm step offering "Check 1 vote". A node with no changes left can send nothing whatever a fresh check finds. The composer now skips it for that reason before the stale-proof routing, which is what the cards and the tray already show. VOTE-FR-074 states the exception. The stale-proof screen test's setup moves into two helpers shared with the new tray test. Addresses CODE-001. Co-Authored-By: Claude Fable 5.1 --- .../01-requirements.md | 4 + src/model/dpns_voting/composer.rs | 33 ++++++- src/ui/dpns/dpns_contested_names_screen.rs | 95 +++++++++++++++---- 3 files changed, 110 insertions(+), 22 deletions(-) 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 index de05358af..b56a77b98 100644 --- 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 @@ -134,6 +134,10 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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). diff --git a/src/model/dpns_voting/composer.rs b/src/model/dpns_voting/composer.rs index 4f9743dda..4fae92600 100644 --- a/src/model/dpns_voting/composer.rs +++ b/src/model/dpns_voting/composer.rs @@ -248,11 +248,13 @@ pub fn compose( plan.skipped.push(skip(SkipReason::AlreadyVoted)); continue; } - let current = if unverified_no_op { None } else { current }; + // 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, @@ -653,6 +655,35 @@ mod tests { 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] diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index ae2db41b1..fdcf7113e 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -930,7 +930,8 @@ impl DPNSScreen { /// 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. + /// 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(); @@ -4929,15 +4930,10 @@ mod tests { ); } - /// 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(); + /// 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; @@ -4956,17 +4952,12 @@ mod tests { }], ); screen.rebuild_cards(); - 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" - ); + (voter, poll) + } + /// 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 @@ -4983,8 +4974,31 @@ mod tests { DpnsCurrentVoteState::Available(Some(ResourceVoteChoice::Lock)), "the proof is still fresh enough to display" ); - screen.rebuild_cards(); + } + + /// 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" + ); + + age_lock_proof(&mut screen, voter, poll); let plan = screen.build_review_plan().unwrap(); assert_eq!(plan.effective_count(), 1); @@ -5035,6 +5049,45 @@ mod tests { } } + /// 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" + ); + + 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) + ); + + 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)]) + ); + } + /// 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] From c35813a66bacabc3130b0f5a238aa0b41f98a576 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 12:14:04 +0000 Subject: [PATCH 189/194] fix(dpns): drop the transaction sentence when nothing is sent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A batch whose every vote is only checked again read "0 transactions, one per node and name. Voting is free for your nodes." in the confirm step and "1 decision ready Β· 0 transactions, one per node and name" in the tray: a sentence worded for one or more transactions, stretched to zero. The confirm step now shows no transaction line when the count is zero, so the "already shown as cast" sentence stands alone, and the tray reads "N decisions ready" without the transaction half. VOTE-FR-080 and -086 say so. Addresses PROJ-003. Co-Authored-By: Claude Fable 5.1 --- .../01-requirements.md | 6 ++-- src/ui/dpns/copy.rs | 29 ++++++++++++++----- src/ui/dpns/dpns_contested_names_screen.rs | 9 ++++-- 3 files changed, 32 insertions(+), 12 deletions(-) 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 index b56a77b98..5204243c3 100644 --- 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 @@ -208,7 +208,8 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. - 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); + `{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.`; @@ -228,7 +229,8 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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. + available for them. When `{t}` is 0 the tray reads `{d} decisions ready` + without the transaction half. ### Operation lifecycle diff --git a/src/ui/dpns/copy.rs b/src/ui/dpns/copy.rs index fca007c67..311da2898 100644 --- a/src/ui/dpns/copy.rs +++ b/src/ui/dpns/copy.rs @@ -263,9 +263,12 @@ pub fn sending_with_label(count: usize) -> String { } } -/// Tray summary (VOTE-FR-086). +/// 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") @@ -415,13 +418,16 @@ pub fn confirm_title(decisions: usize, nodes: usize) -> String { } } -/// Confirm transaction line (VOTE-FR-080). -pub fn confirm_transactions_line(transactions: usize) -> String { +/// Confirm transaction line (VOTE-FR-080); none when nothing is sent. +pub fn confirm_transactions_line(transactions: usize) -> Option { match transactions { - 1 => "1 transaction, one per node and name. Voting is free for your nodes.".to_owned(), - count => { - format!("{count} transactions, one per node and name. Voting is free for your nodes.") + 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." + )), } } @@ -892,6 +898,8 @@ mod tests { 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" @@ -944,8 +952,13 @@ mod tests { fn confirm_copy_follows_the_spec() { assert_eq!(confirm_title(3, 24), "Cast 3 decisions with 24 nodes"); assert_eq!( - confirm_transactions_line(72), - "72 transactions, one per node and name. Voting is free for your nodes." + 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), diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index fdcf7113e..1e379dc99 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -2064,7 +2064,9 @@ impl DPNSScreen { ui.label(row); } ui.add_space(6.0); - ui.label(confirm_transactions_line(plan.transaction_count())); + 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())); } @@ -5032,7 +5034,6 @@ mod tests { }); harness.run(); for label in [ - "0 transactions, one per node and name. Voting is free for your nodes.", "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", ] { @@ -5041,6 +5042,10 @@ mod tests { "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(), From bde6a00025aa9423301f351162a968bd8f7cec5d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 16:17:10 +0000 Subject: [PATCH 190/194] fix(dpns): keep a node loaded after staging out of the confirm step Entering Votes marked a node loaded after decisions were staged as "Don't use this node", but Cast and the Enter shortcut cleared every per-node override when they opened the confirm step, so the new node joined the staged decisions anyway. Such nodes are now remembered apart from the disposable per-confirmation overrides and start on "Don't use this node" every time the confirm step opens for those decisions. Picking any other option for the node under Adjust nodes includes it for good; decisions staged after the earlier ones were cast or cleared use every loaded node again. Nodes read again after a failed read of the node list are not treated as newly loaded: the earlier list is unknown there, and excluding every node would leave nothing to submit. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 3 +- .../01-requirements.md | 6 +- docs/user-stories.md | 1 + src/ui/dpns/dpns_contested_names_screen.rs | 181 ++++++++++++++++-- 4 files changed, 178 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a21ca82f..d874e5355 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -169,7 +169,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). 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. Uncertain votes stay visible and blocked from resubmission; neither + 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. 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 index 5204243c3..35caac9f7 100644 --- 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 @@ -187,7 +187,11 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. 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. + 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`. diff --git a/docs/user-stories.md b/docs/user-stories.md index d9fdf37fc..fe7d29916 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -877,6 +877,7 @@ As a masternode operator, I want to choose which nodes vote and decide many cont - 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] diff --git a/src/ui/dpns/dpns_contested_names_screen.rs b/src/ui/dpns/dpns_contested_names_screen.rs index 1e379dc99..5b9622210 100644 --- a/src/ui/dpns/dpns_contested_names_screen.rs +++ b/src/ui/dpns/dpns_contested_names_screen.rs @@ -526,6 +526,10 @@ pub struct DPNSScreen { 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 @@ -643,6 +647,7 @@ impl DPNSScreen { // Vote handling confirm_open: false, node_overrides: BTreeMap::new(), + late_nodes: BTreeSet::new(), retry: None, submitted_retry: None, confirm_status: VoteHandlingStatus::NotStarted, @@ -691,6 +696,7 @@ impl DPNSScreen { 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; @@ -1193,11 +1199,17 @@ impl DPNSScreen { .find(|vote| vote.contested_name == contest.normalized_contested_name) { Some(vote) => vote.vote_choice = choice, - None => self.selected_votes.push(SelectedVote { - contested_name: contest.normalized_contested_name.clone(), - vote_choice: choice, - end_time: contest.end_time, - }), + 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, + }); + } } } @@ -1370,10 +1382,27 @@ impl DPNSScreen { } 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; @@ -2261,6 +2290,7 @@ impl DPNSScreen { .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)) @@ -2276,15 +2306,14 @@ impl DPNSScreen { .selectable_label(current == option, node_timing_label(option)) .clicked() { - if option == NodeTiming::Batch { - self.node_overrides.remove(&node.voter_id); - } else { - self.node_overrides.insert(node.voter_id, option); - } + picked = Some(option); } } }); }); + if let Some(option) = picked { + self.set_node_timing(node.voter_id, option); + } } let Some(plan) = plan else { return; @@ -2590,6 +2619,8 @@ impl ScreenLike for DPNSScreen { } fn refresh_on_arrival(&mut self) { + // 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() @@ -2607,10 +2638,11 @@ impl ScreenLike for DPNSScreen { } } // A node loaded after decisions were staged never joins them silently. - if !self.selected_votes.is_empty() { + 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); } } @@ -4664,6 +4696,133 @@ mod tests { 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(); From 78581f74958603cf71775ebaedb0122444107cf6 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 16:17:26 +0000 Subject: [PATCH 191/194] fix(identity): report a refused name request as unconfirmed when it cannot be verified The SDK re-sends the same signed name request and returns only the last attempt's error, so a refusal can follow an attempt the network already applied and charged for. The lookup that settles this treated a failed read like a read that does not show the request, so a refusal plus an unreachable network became an ordinary failure: the Pay step came back with the same review and a second non-refundable fee could be spent. The lookup now returns a typed result. A refusal keeps its own error only when the read succeeds and does not show the request. When the read fails, the registration is reported as unconfirmed, which sends the user back to a fresh availability check instead of the Pay step. Co-Authored-By: Claude Fable 5.1 --- .../01-requirements.md | 6 +- .../03-test-case-spec.md | 2 +- .../identity/register_dpns_name.rs | 95 ++++++++++++++----- 3 files changed, 77 insertions(+), 26 deletions(-) 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 index 07c802418..e52963037 100644 --- a/docs/ai-design/2026-10-01-usernames-redesign/01-requirements.md +++ b/docs/ai-design/2026-10-01-usernames-redesign/01-requirements.md @@ -195,8 +195,10 @@ Scope: identity-side usernames. Voting is Stream V in 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 the network does not contradict - keeps its own error. Otherwise it reports `The app could + 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 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 index 933ae2019..f232c2332 100644 --- 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 @@ -31,7 +31,7 @@ Stream V test cases live in `../2026-07-16-dpns-voting-experience/03-test-case-s | 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 | Registration continues as success / the refusal keeps its own error | FR-038 | B | +| 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) diff --git a/src/backend_task/identity/register_dpns_name.rs b/src/backend_task/identity/register_dpns_name.rs index 6d496ad27..75305b329 100644 --- a/src/backend_task/identity/register_dpns_name.rs +++ b/src/backend_task/identity/register_dpns_name.rs @@ -266,9 +266,10 @@ impl AppContext { /// 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 the network - /// does not contradict keeps its own error. Anything else is reported as - /// unconfirmed, never as a plain failure that invites paying again. + /// 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, @@ -277,43 +278,56 @@ impl AppContext { outcome: DpnsRegistrationOutcome, error: SdkError, ) -> Result<(), TaskError> { - if self + match self .username_request_reached_network(sdk, identity_id, name, outcome) .await { - tracing::warn!( - ?error, + 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 registration reported an error, but the network shows the request; continuing as submitted" - ); - return Ok(()); - } - if broadcast_was_rejected(&error) { - return Err(rebrand_dpns_domain_conflict(TaskError::from(error))); + "Username request could not be looked up after its broadcast failed; reporting the registration as unconfirmed" + ), } Err(TaskError::UsernameRegistrationUnconfirmed { source_error: Box::new(error), }) } - /// Whether the network shows `identity_id`'s request for `name`. A failed - /// read counts as not shown. + /// 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, - ) -> bool { + ) -> Result { match outcome { - DpnsRegistrationOutcome::PendingCommunityVote => sdk - .get_contested_dpns_vote_state(&normalize_dpns_label(name), None) - .await - .is_ok_and(|vote| vote.contenders.contains_key(&identity_id)), - DpnsRegistrationOutcome::Registered => self - .fetch_owned_dpns_names(sdk, identity_id) - .await - .is_ok_and(|names| names.iter().any(|owned| owned.name == name)), + 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)) + } } } @@ -977,6 +991,41 @@ mod tests { } } + /// 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)] From 34d5ba38f11df9a34850f02298ae05bab574eb02 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 16:17:34 +0000 Subject: [PATCH 192/194] perf(dpns): share published vote operations instead of copying them all The published vote progress was one shared slice of whole operations. While the Votes screen held it, every target transition copied all retained operations under the journal guard, and the screen copied them all again when it adopted the new publication. Each published operation is now shared on its own, so a transition copies a slice of pointers and replaces one operation. The screen's snapshot keeps its own copy of every operation the publication left unchanged and copies only the changed one. No stored format or visible behaviour changes. Co-Authored-By: Claude Fable 5.1 --- src/context/dpns_vote_attention.rs | 2 +- src/context/dpns_vote_operations/mod.rs | 66 ++++++++++++++++++++++--- src/context/mod.rs | 3 +- src/model/dpns_voting/progress.rs | 4 +- src/ui/dpns/progress_drawer.rs | 6 ++- src/ui/state/dpns_vote_operations.rs | 52 ++++++++++++++++++- 6 files changed, 119 insertions(+), 14 deletions(-) diff --git a/src/context/dpns_vote_attention.rs b/src/context/dpns_vote_attention.rs index 78cc8be3a..5b73f8377 100644 --- a/src/context/dpns_vote_attention.rs +++ b/src/context/dpns_vote_attention.rs @@ -43,7 +43,7 @@ impl AppContext { } /// Live durable journal progress (cheap; safe to call every frame). - pub fn dpns_vote_progress(&self) -> Arc<[DpnsVoteOperation]> { + pub fn dpns_vote_progress(&self) -> Arc<[Arc]> { Arc::clone( &self .dpns_vote_progress diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index 61635dfd9..07a7c2df5 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -527,13 +527,16 @@ impl AppContext { .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] = operation; + if *progress[index] != operation { + Arc::make_mut(&mut progress)[index] = Arc::new(operation); } } else { - let mut operations = progress.to_vec(); - operations.push(operation); - *progress = operations.into(); + let operations = progress + .iter() + .cloned() + .chain([Arc::new(operation)]) + .collect(); + *progress = operations; } self.egui_ctx().request_repaint(); } @@ -611,7 +614,10 @@ impl AppContext { .dpns_vote_progress .write() .unwrap_or_else(std::sync::PoisonError::into_inner) = - load_operations_read_only(kv, self.network)?.into(); + 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 @@ -683,7 +689,8 @@ impl AppContext { *self .dpns_vote_progress .write() - .unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::from(operations.as_slice()); + .unwrap_or_else(std::sync::PoisonError::into_inner) = + operations.iter().cloned().map(Arc::new).collect(); Ok(operations) } @@ -1273,6 +1280,51 @@ mod tests { ); } + /// 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) diff --git a/src/context/mod.rs b/src/context/mod.rs index 721a83271..f45aafd42 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -222,7 +222,8 @@ pub struct AppContext { /// until the SPV masternode list is available. masternode_list_membership: RwLock>>>, /// Journal operations published after executor transitions (progress drawer). - dpns_vote_progress: RwLock>, + /// 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. diff --git a/src/model/dpns_voting/progress.rs b/src/model/dpns_voting/progress.rs index 2a5928227..60c6832de 100644 --- a/src/model/dpns_voting/progress.rs +++ b/src/model/dpns_voting/progress.rs @@ -95,12 +95,12 @@ fn sent_at(operation: &DpnsVoteOperation, outcome: &DpnsVoteOutcome) -> u64 { /// 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: &'a [DpnsVoteOperation], + operations: impl IntoIterator, since_ms: u64, dismissed: &BTreeSet, ) -> Vec<&'a DpnsVoteOperation> { operations - .iter() + .into_iter() .filter(|operation| { let counts = progress_counts([*operation]); if counts.total == 0 { diff --git a/src/ui/dpns/progress_drawer.rs b/src/ui/dpns/progress_drawer.rs index 8e8e371c5..fcee0e114 100644 --- a/src/ui/dpns/progress_drawer.rs +++ b/src/ui/dpns/progress_drawer.rs @@ -99,7 +99,11 @@ fn paint_segments(ui: &mut Ui, counts: ProgressCounts) { 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, state.since_ms, &dismissed); + let shown = drawer_operations( + operations.iter().map(std::sync::Arc::as_ref), + state.since_ms, + &dismissed, + ); if shown.is_empty() { return AppAction::None; } diff --git a/src/ui/state/dpns_vote_operations.rs b/src/ui/state/dpns_vote_operations.rs index b61325aa6..7cc74bfd7 100644 --- a/src/ui/state/dpns_vote_operations.rs +++ b/src/ui/state/dpns_vote_operations.rs @@ -61,7 +61,7 @@ pub(crate) fn group_scheduled_rows(rows: Vec) -> Vec, - published: Option>, + published: Option]>>, dismissed_schedules: BTreeSet<(DpnsVoteOperationId, DpnsVoteTargetKey)>, target_statuses: BTreeMap, loaded: bool, @@ -128,7 +128,20 @@ impl DpnsVoteOperationSnapshot { .then(|| (old.map(|old| old.status), outcome.clone())) }) .collect(); - self.replace(published.to_vec()); + // 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) } @@ -230,6 +243,41 @@ mod tests { 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( From d5f738742513f79c24828933c7d4f98e1480a1da Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 17:40:37 +0000 Subject: [PATCH 193/194] fix(dpns): cancel reviewed votes when their node is removed and loaded again Removing a node cancels its votes under the journal guard, but only the ones the journal already holds. A new operation is stored only after its pre-send proof refresh, so a removal during that wait had nothing to cancel, and loading the node again retired the unload marker that the admission check relies on. The votes reviewed before the removal were then stored and sent, and their schedules stayed armed. Count, per voter and in memory, each load that follows a removal. The count moves under the journal guard, right after the stored votes are cancelled. Vote work reads the counts when its task starts, before any wait, and admission cancels the targets of every voter whose count has moved since. A schedule replacement from before the removal is refused the same way, so it cannot overwrite a schedule reviewed afterwards. Nothing is persisted: work that is not in the journal does not survive a restart, so the count does not need to either. Co-Authored-By: Claude Fable 5.1 --- docs/user-stories.md | 2 +- src/backend_task/contested_names/mod.rs | 228 +++++++++++++++++++++++- src/context/dpns_vote_operations/mod.rs | 65 ++++++- src/context/identity_db.rs | 3 + src/context/mod.rs | 5 + 5 files changed, 287 insertions(+), 16 deletions(-) diff --git a/docs/user-stories.md b/docs/user-stories.md index fe7d29916..0bf8413cd 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -792,7 +792,7 @@ 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. --- diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index f7a5543ac..2d48e7885 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -8,7 +8,7 @@ mod vote_on_dpns_name; use crate::app::TaskResult; use crate::backend_task::BackendTaskSuccessResult; use crate::backend_task::error::{DapiAddressAvailability, TaskError}; -use crate::context::{AppContext, MAX_CONCURRENT_DPNS_VOTERS}; +use crate::context::{AppContext, DpnsVoterLifecycles, MAX_CONCURRENT_DPNS_VOTERS}; use crate::model::contested_name::ContestedName; use crate::model::dpns_voting::{ DpnsCurrentVoteState, DpnsScheduleEditValidationError, DpnsScheduledVoteEdit, DpnsVoteFailure, @@ -225,6 +225,9 @@ impl AppContext { 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 @@ -272,6 +275,7 @@ impl AppContext { operation, voters, replacing_scheduled_key, + &submitted, sdk, ) .await @@ -281,8 +285,14 @@ impl AppContext { } ContestedResourceTask::CastScheduledVote(scheduled_vote, voter) => { let operation = self.operation_for_scheduled_vote(&scheduled_vote, &voter)?; - self.execute_dpns_vote_operation_with_recovery(operation, vec![*voter], None, sdk) - .await + self.execute_dpns_vote_operation_with_recovery( + operation, + vec![*voter], + None, + &submitted, + sdk, + ) + .await } ContestedResourceTask::CastDueScheduledVotes { preserve_eligibility_since_ms, @@ -525,11 +535,33 @@ impl AppContext { 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, ) -> Result { if operation.targets.is_empty() { @@ -635,7 +667,11 @@ impl AppContext { .retain(|outcome| requested_keys.contains(&outcome.target.key)); } else { self.validate_new_dpns_schedules(&new_schedules)?; - self.insert_dpns_vote_operation(&mut operation, replacing_scheduled_key.as_ref())?; + 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 @@ -851,6 +887,7 @@ impl AppContext { operation: DpnsVoteOperation, voters: Vec, replacing_scheduled_key: Option, + submitted: &DpnsVoterLifecycles, sdk: &Sdk, ) -> Result { let operation_id = operation.id; @@ -860,7 +897,13 @@ impl AppContext { .map(|outcome| outcome.target.key.clone()) .collect(); let result = self - .execute_dpns_vote_operation(operation, voters, replacing_scheduled_key, sdk) + .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) @@ -1209,8 +1252,12 @@ impl AppContext { 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, &sdk) + .execute_dpns_vote_operation_with_recovery( + operation, voters, None, &submitted, &sdk, + ) .await .map(|_| ()); (operation_id, result) @@ -1533,6 +1580,7 @@ mod tests { selected, vec![qualified_identity(1)], None, + &context.dpns_voter_lifecycles(), &Sdk::new_mock(), ) .await; @@ -1958,6 +2006,174 @@ mod tests { 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. diff --git a/src/context/dpns_vote_operations/mod.rs b/src/context/dpns_vote_operations/mod.rs index 07a7c2df5..13d5b5c42 100644 --- a/src/context/dpns_vote_operations/mod.rs +++ b/src/context/dpns_vote_operations/mod.rs @@ -35,6 +35,9 @@ type DpnsVoteDiagnosticMap = 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, @@ -594,11 +597,45 @@ impl AppContext { }) } + /// 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 @@ -608,7 +645,16 @@ impl AppContext { { 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 @@ -629,32 +675,33 @@ impl AppContext { { 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)?; cancel_executable_targets(operation, |voter| removed.contains(&voter)); persist_operation(kv, self.network, operation) }) } - /// Voters of `operation` that were removed from this device and not - /// loaded again. The caller holds the journal guard, which a removal - /// keeps from cancelling the voter's votes until the voter is delisted. + /// 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 self.is_identity_unloaded(kv, &voter.to_buffer())? - && !self.is_identity_listed(&voter)? + if submitted.get(&voter) != current.get(&voter) + || (self.is_identity_unloaded(kv, &voter.to_buffer())? + && !self.is_identity_listed(&voter)?) { removed.insert(voter); } diff --git a/src/context/identity_db.rs b/src/context/identity_db.rs index f724eb965..bda4d0fa1 100644 --- a/src/context/identity_db.rs +++ b/src/context/identity_db.rs @@ -609,6 +609,9 @@ impl AppContext { .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) diff --git a/src/context/mod.rs b/src/context/mod.rs index f45aafd42..0a49b9871 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -6,6 +6,7 @@ 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; @@ -273,6 +274,9 @@ pub struct AppContext { 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, @@ -623,6 +627,7 @@ impl AppContext { 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(), From cc0848f6cf55ab51279c7c0659ab83d0b8652f70 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 6 Oct 2026 17:45:39 +0000 Subject: [PATCH 194/194] fix(dpns): retry a contest refresh soon when a contest query failed A refresh pass stamped itself complete whenever every loaded node's vote state was checked. The end-time query and the per-contest contender queries only logged their failures, so a pass with unread deadlines, missing contenders or stale tallies still counted as complete and the early retry was skipped. The data then stayed incomplete for a whole interval, 30 minutes on mainnet. Each contest query now reports whether it succeeded, and a query that did not run to its end counts as failed. The pass is stamped complete only when all of them and every node check succeeded, and only after the username snapshot is reloaded, so a failure there leaves the pass open to the retry too. What the pass did refresh is still stored and published, and a background pass still reports no error to the UI. The retry reuses the existing schedule: one attempt a sixth of the interval later, so a contest that fails every time is retried at that pace and no faster. Co-Authored-By: Claude Fable 5.1 --- .../01-requirements.md | 5 +- src/app.rs | 6 +- src/backend_task/contested_names/mod.rs | 64 +++++++++++++++++++ .../query_dpns_contested_resources.rs | 57 +++++++++++++---- src/model/dpns_voting/operator.rs | 5 +- 5 files changed, 119 insertions(+), 18 deletions(-) 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 index 35caac9f7..1c2fe74a8 100644 --- 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 @@ -123,8 +123,9 @@ Validation floor: 24 nodes on one voting key, 6 open contests, 2 ending today. - **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 node's vote state unchecked, does not count as - completed and is retried after a sixth of the interval. Proved vote + 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. diff --git a/src/app.rs b/src/app.rs index facc473a3..3431577f2 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2687,9 +2687,9 @@ impl AppState { } } - /// Called when a background contest refresh ends: if it failed or left a - /// node's vote state unchecked, try again soon instead of a whole interval - /// later. + /// 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, diff --git a/src/backend_task/contested_names/mod.rs b/src/backend_task/contested_names/mod.rs index 2d48e7885..3a59001e4 100644 --- a/src/backend_task/contested_names/mod.rs +++ b/src/backend_task/contested_names/mod.rs @@ -2322,6 +2322,70 @@ mod tests { 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 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 adee5ace3..6c80394bb 100644 --- a/src/backend_task/contested_names/query_dpns_contested_resources.rs +++ b/src/backend_task/contested_names/query_dpns_contested_resources.rs @@ -14,6 +14,7 @@ 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; @@ -59,6 +60,23 @@ where } } +/// 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. @@ -157,7 +175,7 @@ impl AppContext { Ok(permit) => permit, Err(e) => { tracing::error!("Semaphore closed while querying dpns end times: {}", e); - return; + return false; } }; @@ -172,9 +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); @@ -188,6 +208,7 @@ impl AppContext { send_err ); } + false } } }) @@ -210,7 +231,7 @@ impl AppContext { name, e ); - return; + return false; } }; @@ -226,9 +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); @@ -243,6 +266,7 @@ impl AppContext { send_err ); } + false } } }); @@ -250,11 +274,7 @@ 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 @@ -269,12 +289,13 @@ impl AppContext { self.refresh_masternode_list_membership().await; self.forget_closed_dpns_vote_counts(); self.recompute_dpns_vote_attention(); - // A pass that left a node unchecked is not a completed refresh: the - // timer and the Votes-arrival refresh must be free to try again soon. - if vote_states_refreshed { + 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(); } - self.refresh_pending_dpns_usernames()?; sender .send(TaskResult::unattributed_success( @@ -330,6 +351,20 @@ mod tests { 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); diff --git a/src/model/dpns_voting/operator.rs b/src/model/dpns_voting/operator.rs index 567ef19d3..c8eab6634 100644 --- a/src/model/dpns_voting/operator.rs +++ b/src/model/dpns_voting/operator.rs @@ -381,8 +381,9 @@ pub fn background_refresh_interval(network: Network) -> Duration { } } -/// How soon a background refresh that failed, or left a node's vote state -/// unchecked, is tried again instead of waiting a whole interval. +/// 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 }