From 30b2f5fef391e5cd93020674180eda3efa324d42 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Sat, 8 Aug 2026 03:54:39 +0700 Subject: [PATCH] fix(dashpay): make the voting screens escapable and vote one node at a time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three problems found on device. **You could not leave the contest screen.** `GovernanceMenuScreen` hides its own navigation bar, and `showVoting()` pushed a bare `UIHostingController`. `BaseNavigationController.willShow` only restores the bar for a `NavigationBarDisplayable`, so a non-conforming controller inherits whatever the previous screen left — hidden. No bar meant no back button and no way out, and it silently dropped `.navigationTitle` and the whole `.toolbar` too (sort and "Vote on several" never rendered), because neither applies outside a navigation container. Fixed the way `showMasternodes` directly above already does it: its own `NavigationStack` plus a back button wired explicitly to pop the UIKit stack. **Voting cast every node's vote at once, which is a privacy loss.** Broadcasting several `MasternodeVote` transitions for one poll in quick succession lets an observer group those masternodes as a single operator — and the user cannot undo that afterwards. Voting is now **one node per tap by default**: each tap casts with the next node that has not voted on this contest, so how many nodes you link together is a choice rather than a side effect. The mode is configurable where the node count is shown, as the user asked — "One node at a time" (default) or "All nodes at once" — with a line explaining the trade-off, persisted in `VotingPrefs` so it survives relaunch. The control only appears with more than one node, where the two modes actually differ. **How many votes you have cast is now visible.** The detail screen shows "2 of 5 nodes voted", the vote button reads "Vote ×3" when a tap will use more than one node, nodes that already voted are dropped from the picker with a note saying so, and once every node has voted the buttons give way to an explanation of how to change a vote instead. That needs to survive a relaunch, so votes are recorded in a new `masternode_vote_history` table (`VoteHistoryDAO`), keyed per network so a testnet and a mainnet contest sharing a label never merge. Only accepted votes are recorded, so the count reflects what Platform took, not what was attempted. Platform cannot answer this cheaply — `getContestedResourceVotersForIdentity` is per contender, keyed by voter identity, and cannot see abstain or lock voters at all. Cleared on wallet wipe. Co-Authored-By: Claude Opus 5 --- DashWallet.xcodeproj/project.pbxproj | 14 ++ DashWallet/Sources/Application/App.swift | 4 + ...0808030000_add_masternode_vote_history.sql | 23 +++ .../Voting/MasternodeVoteCaster.swift | 17 ++ .../Models/Voting/VoteHistoryDAO.swift | 179 ++++++++++++++++++ .../Sources/Models/Voting/VotingPrefs.swift | 21 +- .../UI/DashPay/Voting/CastVoteSheet.swift | 36 +++- .../DashPay/Voting/ContestDetailScreen.swift | 52 ++++- .../DashPay/Voting/UsernameVotingScreen.swift | 41 +++- .../UI/DashPay/Voting/VotingViewModel.swift | 53 ++++++ .../Governance/GovernanceMenuScreen.swift | 23 ++- DashWallet/en.lproj/Localizable.strings | 7 + DashWallet/en.lproj/Localizable.stringsdict | 48 +++++ 13 files changed, 506 insertions(+), 12 deletions(-) create mode 100644 DashWallet/Sources/Infrastructure/Database/Migrations.bundle/20260808030000_add_masternode_vote_history.sql create mode 100644 DashWallet/Sources/Models/Voting/VoteHistoryDAO.swift diff --git a/DashWallet.xcodeproj/project.pbxproj b/DashWallet.xcodeproj/project.pbxproj index e502f6d718..4b999918a9 100644 --- a/DashWallet.xcodeproj/project.pbxproj +++ b/DashWallet.xcodeproj/project.pbxproj @@ -1917,6 +1917,8 @@ D19A81C4F6103AC513D737AA /* UsernameRequestStatusScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED4CB35186918CCBD2FFC49F /* UsernameRequestStatusScreen.swift */; }; 63C3BBEF4EE77A6F02144B2D /* BulkVoteSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3E5E523355F3EEC5CDEB00A /* BulkVoteSheet.swift */; }; 25B84141680B6A9F225C995C /* BulkVoteSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3E5E523355F3EEC5CDEB00A /* BulkVoteSheet.swift */; }; + 7062FCF792F292D84A0B819B /* VoteHistoryDAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AFB72236D79932EAE7A38E2 /* VoteHistoryDAO.swift */; }; + 553696A24F315D361BC86231 /* VoteHistoryDAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AFB72236D79932EAE7A38E2 /* VoteHistoryDAO.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -3640,6 +3642,7 @@ FF2C19E8480582798A0155E4 /* CastVoteSheet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CastVoteSheet.swift; sourceTree = ""; }; ED4CB35186918CCBD2FFC49F /* UsernameRequestStatusScreen.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UsernameRequestStatusScreen.swift; sourceTree = ""; }; C3E5E523355F3EEC5CDEB00A /* BulkVoteSheet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = BulkVoteSheet.swift; sourceTree = ""; }; + 0AFB72236D79932EAE7A38E2 /* VoteHistoryDAO.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = VoteHistoryDAO.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFileSystemSynchronizedRootGroup section */ @@ -4522,6 +4525,7 @@ 2A44313D22CF632F009BAF7F /* Models */ = { isa = PBXGroup; children = ( + 515C73491D3755649EB0709D /* Voting */, AA0002192BA0F58E00A1B309 /* Maya */, AA0010002CA0B10001A0B100 /* SwapKit */, AA0020012FA0000000000001 /* Swap */, @@ -8589,6 +8593,14 @@ path = Voting; sourceTree = ""; }; + 515C73491D3755649EB0709D /* Voting */ = { + isa = PBXGroup; + children = ( + 0AFB72236D79932EAE7A38E2 /* VoteHistoryDAO.swift */, + ); + path = Voting; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -9389,6 +9401,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 553696A24F315D361BC86231 /* VoteHistoryDAO.swift in Sources */, 25B84141680B6A9F225C995C /* BulkVoteSheet.swift in Sources */, D19A81C4F6103AC513D737AA /* UsernameRequestStatusScreen.swift in Sources */, 6181C570B638E07D8B369CDB /* VotingViewModel.swift in Sources */, @@ -10257,6 +10270,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 7062FCF792F292D84A0B819B /* VoteHistoryDAO.swift in Sources */, 63C3BBEF4EE77A6F02144B2D /* BulkVoteSheet.swift in Sources */, E503EDEA94E656CAE70E5A11 /* UsernameRequestStatusScreen.swift in Sources */, 1FED991A9D2D236582CE3C99 /* CastVoteSheet.swift in Sources */, diff --git a/DashWallet/Sources/Application/App.swift b/DashWallet/Sources/Application/App.swift index 8c3a08bde1..3f12ebd988 100644 --- a/DashWallet/Sources/Application/App.swift +++ b/DashWallet/Sources/Application/App.swift @@ -103,6 +103,10 @@ final class App { func cleanUp() { TransactionMetadataDAOImpl.shared.deleteAll() AddressUserInfoDAOImpl.shared.deleteAll() + #if DASHPAY + // Which of your masternodes voted on what is wallet-scoped history. + VoteHistoryDAOImpl.shared.deleteAll() + #endif _fiatCurrency = nil UserDefaults.standard.removeObject(forKey: kFiatCurrencyCodeKey) diff --git a/DashWallet/Sources/Infrastructure/Database/Migrations.bundle/20260808030000_add_masternode_vote_history.sql b/DashWallet/Sources/Infrastructure/Database/Migrations.bundle/20260808030000_add_masternode_vote_history.sql new file mode 100644 index 0000000000..47dfad2d2c --- /dev/null +++ b/DashWallet/Sources/Infrastructure/Database/Migrations.bundle/20260808030000_add_masternode_vote_history.sql @@ -0,0 +1,23 @@ +-- One row per (masternode, contest, network): the vote this device last cast +-- with that node on that contest. +-- +-- Needed so the voting UI can say how many of your nodes have already voted on +-- a contest, and so "vote with one node at a time" knows which node is next. +-- Platform can be asked who voted, but only per contender and only by voter +-- identity, so answering "which of MY nodes voted here" from the network costs +-- a query per contender and still cannot see abstain/lock voters. +-- +-- `proTxHash` is stored in raw wire byte order, matching PlatformMasternode. +-- `castAt` is milliseconds since epoch. +CREATE TABLE masternode_vote_history ( + proTxHash BLOB NOT NULL, + normalizedLabel TEXT NOT NULL, + network TEXT NOT NULL, + choice TEXT NOT NULL, + contenderIdentityId TEXT, + castAt INTEGER NOT NULL, + PRIMARY KEY (proTxHash, normalizedLabel, network) +); + +CREATE INDEX idx_masternode_vote_history_contest + ON masternode_vote_history (normalizedLabel, network); diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/MasternodeVoteCaster.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/MasternodeVoteCaster.swift index 5e6f54c555..568bcc6a4b 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/MasternodeVoteCaster.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/MasternodeVoteCaster.swift @@ -108,6 +108,14 @@ final class MasternodeVoteCaster { subsystem: "org.dashfoundation.dash", category: "swift-sdk-migration.voting") + private static let history: VoteHistoryDAO = VoteHistoryDAOImpl.shared + + /// Vote history is per Platform network — a testnet contest and a mainnet + /// one can share a label, and their counts must never merge. + static var networkKey: String { + WalletEnvironment.network == .mainnet ? "mainnet" : "testnet" + } + private let registry: MasternodeVoterRegistry private let contests: ContestedNamesService @@ -222,6 +230,15 @@ final class MasternodeVoteCaster { proTxHash: node.proTxHash, votingPrivateKey: votingKey) outcomes.append(VoteOutcome(node: node, failure: nil)) + // Recorded only on success, so the count the UI shows is + // votes Platform accepted — not votes attempted. + await Self.history.record( + CastVoteRecord( + proTxHash: node.proTxHash, + normalizedLabel: normalizedLabel, + choice: choice, + castAt: Date()), + network: Self.networkKey) Self.logger.info( "🗳️ VOTING :: cast \(choice.logDescription, privacy: .public) on \(normalizedLabel, privacy: .public) with \(node.displayName, privacy: .public)") } catch { diff --git a/DashWallet/Sources/Models/Voting/VoteHistoryDAO.swift b/DashWallet/Sources/Models/Voting/VoteHistoryDAO.swift new file mode 100644 index 0000000000..76e333763e --- /dev/null +++ b/DashWallet/Sources/Models/Voting/VoteHistoryDAO.swift @@ -0,0 +1,179 @@ +// +// VoteHistoryDAO.swift +// DashWallet +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import Foundation +@preconcurrency import SQLite + +// MARK: - CastVoteRecord + +/// A vote this device cast with one of the wallet's masternodes. +/// +/// Records what *we* did, not what Platform holds. Platform is the authority on +/// tallies, but it cannot cheaply answer "which of my nodes already voted +/// here": `getContestedResourceVotersForIdentity` is per contender, keyed by +/// voter identity, and cannot see abstain or lock voters at all. Voting one +/// node at a time needs that answer on every tap, so it is kept locally. +struct CastVoteRecord: Hashable { + /// Raw wire byte order, matching `PlatformMasternode.proTxHash`. + let proTxHash: Data + let normalizedLabel: String + let choice: VoteChoice + let castAt: Date +} + +// MARK: - VoteHistoryDAO + +protocol VoteHistoryDAO { + /// Upsert — a node re-voting on the same contest replaces its own row, + /// mirroring Platform, where a masternode has one live vote per poll. + func record(_ record: CastVoteRecord, network: String) async + /// Votes this device cast on one contest, newest first. + func votes(forContest normalizedLabel: String, network: String) async -> [CastVoteRecord] + /// Every contest this device has voted on, mapped to its vote count. + /// One query for the whole list screen rather than one per row. + func voteCountsByContest(network: String) async -> [String: Int] + func deleteAll() +} + +// MARK: - VoteHistoryDAOImpl + +actor VoteHistoryDAOImpl: VoteHistoryDAO { + static let shared = VoteHistoryDAOImpl() + + private nonisolated var db: Connection { DatabaseConnection.shared.db } + + private init() {} + + func record(_ record: CastVoteRecord, network: String) async { + let query = """ + INSERT INTO masternode_vote_history + (proTxHash, normalizedLabel, network, choice, contenderIdentityId, castAt) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (proTxHash, normalizedLabel, network) DO UPDATE SET + choice = excluded.choice, + contenderIdentityId = excluded.contenderIdentityId, + castAt = excluded.castAt + """ + let bindings: [Binding?] = [ + Blob(bytes: [UInt8](record.proTxHash)), + record.normalizedLabel, + network, + record.choice.storageKind, + record.choice.storageContenderId, + Int64(record.castAt.timeIntervalSince1970 * 1000), + ] + + do { + try db.run(query, bindings) + } catch { + DWLogger.log("VoteHistoryDAO: record failed: \(error)") + } + } + + func votes(forContest normalizedLabel: String, network: String) async -> [CastVoteRecord] { + let query = """ + SELECT proTxHash, normalizedLabel, choice, contenderIdentityId, castAt + FROM masternode_vote_history + WHERE normalizedLabel = ? AND network = ? + ORDER BY castAt DESC + """ + do { + // `prepare` yields positional `[Binding?]` rows, which is what a + // hand-written SELECT needs; `Row` subscripting is for typed + // `Expression` columns. + return try db.prepare(query, [normalizedLabel, network]).compactMap { row -> CastVoteRecord? in + guard let blob = row[0] as? Blob, + let label = row[1] as? String, + let kind = row[2] as? String, + let castAt = row[4] as? Int64, + let choice = VoteChoice(storageKind: kind, contenderId: row[3] as? String) + else { return nil } + return CastVoteRecord( + proTxHash: Data(blob.bytes), + normalizedLabel: label, + choice: choice, + castAt: Date(timeIntervalSince1970: Double(castAt) / 1000)) + } + } catch { + DWLogger.log("VoteHistoryDAO: votes(forContest:) failed: \(error)") + return [] + } + } + + func voteCountsByContest(network: String) async -> [String: Int] { + let query = """ + SELECT normalizedLabel, COUNT(*) + FROM masternode_vote_history + WHERE network = ? + GROUP BY normalizedLabel + """ + do { + var counts: [String: Int] = [:] + for row in try db.prepare(query, [network]) { + guard let label = row[0] as? String, let count = row[1] as? Int64 else { continue } + counts[label] = Int(count) + } + return counts + } catch { + DWLogger.log("VoteHistoryDAO: voteCountsByContest failed: \(error)") + return [:] + } + } + + nonisolated func deleteAll() { + do { + try db.run("DELETE FROM masternode_vote_history") + } catch { + DWLogger.log("VoteHistoryDAO: deleteAll failed: \(error)") + } + } +} + +// MARK: - VoteChoice storage + +extension VoteChoice { + /// Stored as a discriminator plus an optional id rather than a formatted + /// string, so reading it back is a lookup instead of prefix-parsing. + var storageKind: String { + switch self { + case .towards: return "towards" + case .abstain: return "abstain" + case .lock: return "lock" + } + } + + var storageContenderId: String? { + if case .towards(let identityId) = self { return identityId } + return nil + } + + init?(storageKind: String, contenderId: String?) { + switch storageKind { + case "towards": + guard let contenderId else { return nil } + self = .towards(identityId: contenderId) + case "abstain": + self = .abstain + case "lock": + self = .lock + default: + return nil + } + } +} diff --git a/DashWallet/Sources/Models/Voting/VotingPrefs.swift b/DashWallet/Sources/Models/Voting/VotingPrefs.swift index 4d5de41447..67f64448cc 100644 --- a/DashWallet/Sources/Models/Voting/VotingPrefs.swift +++ b/DashWallet/Sources/Models/Voting/VotingPrefs.swift @@ -18,6 +18,7 @@ import Foundation private let kVotingEnabled = "votingEnabledKey" +private let kVoteWithAllNodes = "voteWithAllNodesKey" // MARK: - VotingPrefs @@ -27,7 +28,13 @@ class VotingPrefs { public static let shared: VotingPrefs = .init() init() { - UserDefaults.standard.register(defaults: [kVotingEnabled : true]) + // Voting one node at a time is the default on purpose: casting every + // node's vote in one action publicly links those masternodes to each + // other, which is a privacy loss the user cannot undo afterwards. + UserDefaults.standard.register(defaults: [ + kVotingEnabled: true, + kVoteWithAllNodes: false, + ]) } private var _votingEnabled: Bool? = nil @@ -41,4 +48,16 @@ class VotingPrefs { UserDefaults.standard.set(value, forKey: kVotingEnabled) } } + + /// `false` (default) casts one masternode's vote per tap; `true` casts + /// with every votable node at once. + /// + /// Voting all at once broadcasts several `MasternodeVote` transitions for + /// the same poll in quick succession, which lets an observer group those + /// nodes as one operator. One at a time keeps that correlation the user's + /// choice rather than a side effect of the default. + var voteWithAllNodes: Bool { + get { UserDefaults.standard.bool(forKey: kVoteWithAllNodes) } + set { UserDefaults.standard.set(newValue, forKey: kVoteWithAllNodes) } + } } diff --git a/DashWallet/Sources/UI/DashPay/Voting/CastVoteSheet.swift b/DashWallet/Sources/UI/DashPay/Voting/CastVoteSheet.swift index dea0afbfcc..f64c0fa694 100644 --- a/DashWallet/Sources/UI/DashPay/Voting/CastVoteSheet.swift +++ b/DashWallet/Sources/UI/DashPay/Voting/CastVoteSheet.swift @@ -34,7 +34,14 @@ struct CastVoteSheet: View { @State private var selectedNodeIDs: Set = [] private var selectedNodes: [VoterNode] { - viewModel.votableNodes.filter { selectedNodeIDs.contains($0.proTxHash) } + candidateNodes.filter { selectedNodeIDs.contains($0.proTxHash) } + } + + /// Only nodes that have not voted on this contest yet. A node with a vote + /// on record is not offered again — Platform rejects a repeat of the same + /// choice, and re-listing it would invite that error. + private var candidateNodes: [VoterNode] { + viewModel.nodesYetToVote(on: contest.normalizedLabel) } var body: some View { @@ -63,7 +70,10 @@ struct CastVoteSheet: View { } .onAppear { if selectedNodeIDs.isEmpty { - selectedNodeIDs = Set(viewModel.votableNodes.map(\.proTxHash)) + // Honour the privacy mode: one node preselected by default, + // all of them only when the user asked for that. + selectedNodeIDs = Set( + viewModel.nodesForNextVote(on: contest.normalizedLabel).map(\.proTxHash)) } } } @@ -85,13 +95,27 @@ struct CastVoteSheet: View { Section { VotingBanner(text: castError, tone: .error).listRowInsets(EdgeInsets()) } } - Section(NSLocalizedString("Vote with", comment: "Voting")) { - ForEach(viewModel.votableNodes) { node in + Section { + ForEach(candidateNodes) { node in NodeSelectionRow( node: node, isSelected: selectedNodeIDs.contains(node.proTxHash), toggle: { toggle(node) }) } + } header: { + Text(NSLocalizedString("Vote with", comment: "Voting")) + } footer: { + if alreadyVoted > 0 { + Text(String( + format: NSLocalizedString( + "%d of your nodes already voted here and are not listed.", + comment: "Voting"), + alreadyVoted)) + } else if !viewModel.voteWithAllNodes && viewModel.votableNodes.count > 1 { + Text(NSLocalizedString( + "Selecting fewer nodes reveals less about which masternodes you run.", + comment: "Voting")) + } } Section { @@ -123,6 +147,10 @@ struct CastVoteSheet: View { } } + private var alreadyVoted: Int { + viewModel.votableNodes.count - candidateNodes.count + } + private func toggle(_ node: VoterNode) { if selectedNodeIDs.contains(node.proTxHash) { selectedNodeIDs.remove(node.proTxHash) diff --git a/DashWallet/Sources/UI/DashPay/Voting/ContestDetailScreen.swift b/DashWallet/Sources/UI/DashPay/Voting/ContestDetailScreen.swift index e2b6b018fc..a69117379c 100644 --- a/DashWallet/Sources/UI/DashPay/Voting/ContestDetailScreen.swift +++ b/DashWallet/Sources/UI/DashPay/Voting/ContestDetailScreen.swift @@ -41,7 +41,22 @@ struct ContestDetailScreen: View { viewModel.isClosed(normalizedLabel: contest.normalizedLabel) } - private var canVote: Bool { viewModel.canVote && !isClosed } + private var canVote: Bool { viewModel.canVote && !isClosed && !allNodesVoted } + + /// How many of this wallet's nodes have voted here. + private var castCount: Int { viewModel.castCount(for: contest.normalizedLabel) } + + private var allNodesVoted: Bool { + viewModel.canVote && viewModel.nodesYetToVote(on: contest.normalizedLabel).isEmpty + } + + /// What one tap will do, so the button can say so rather than making the + /// user infer it from a setting on the previous screen. + private var voteButtonTitle: String { + let pending = viewModel.nodesForNextVote(on: contest.normalizedLabel) + if pending.count <= 1 { return NSLocalizedString("Vote", comment: "Voting") } + return String(format: NSLocalizedString("Vote ×%d", comment: "Voting"), pending.count) + } var body: some View { List { @@ -82,6 +97,21 @@ struct ContestDetailScreen: View { Spacer() ContestDeadlineLabel(endTime: current.endTime) } + + if viewModel.canVote { + HStack { + Text(NSLocalizedString("Your votes", comment: "Voting")) + .font(.caption) + .foregroundColor(Color.dash.secondaryText) + Spacer() + Text(String( + format: NSLocalizedString("%d of %d nodes voted", comment: "Voting"), + castCount, viewModel.votableNodes.count)) + .font(.caption) + .fontWeight(.medium) + .foregroundColor(allNodesVoted ? .green : Color.dash.secondaryText) + } + } } .padding(.vertical, 4) } @@ -93,6 +123,7 @@ struct ContestDetailScreen: View { isLeading: contender.id == current.leadingContender?.id && current.lockVotes <= contender.voteTally, canVote: canVote, + voteTitle: voteButtonTitle, onVote: { pendingChoice = .towards(identityId: contender.identityId) }) } } @@ -104,6 +135,7 @@ struct ContestDetailScreen: View { tally: current.lockVotes, systemImage: "lock", canVote: canVote, + voteTitle: voteButtonTitle, onVote: { pendingChoice = .lock }) VoteTallyRow( title: NSLocalizedString("Abstain", comment: "Voting"), @@ -111,9 +143,20 @@ struct ContestDetailScreen: View { tally: current.abstainVotes, systemImage: "minus.circle", canVote: canVote, + voteTitle: voteButtonTitle, onVote: { pendingChoice = .abstain }) } + if allNodesVoted && !isClosed { + Section { + Text(NSLocalizedString( + "All of your masternodes have voted on this username. To change a vote, vote again from the contender you now prefer.", + comment: "Voting")) + .font(.caption) + .foregroundColor(Color.dash.secondaryText) + } + } + if !viewModel.canVote && !isClosed { Section { Text(NSLocalizedString( @@ -126,6 +169,7 @@ struct ContestDetailScreen: View { } .navigationTitle(current.displayTitle) .navigationBarTitleDisplayMode(.inline) + .task { await viewModel.loadVotedNodes(for: contest.normalizedLabel) } .refreshable { await viewModel.refreshContest(normalizedLabel: contest.normalizedLabel) } .sheet(item: $pendingChoice) { choice in CastVoteSheet( @@ -142,6 +186,7 @@ private struct ContenderRow: View { let contender: DPNSContender let isLeading: Bool let canVote: Bool + let voteTitle: String let onVote: () -> Void var body: some View { @@ -160,7 +205,7 @@ private struct ContenderRow: View { Spacer() if canVote { - Button(NSLocalizedString("Vote", comment: "Voting"), action: onVote) + Button(voteTitle, action: onVote) .buttonStyle(.bordered) .controlSize(.small) } @@ -177,6 +222,7 @@ private struct VoteTallyRow: View { let tally: UInt32 let systemImage: String let canVote: Bool + let voteTitle: String let onVote: () -> Void var body: some View { @@ -200,7 +246,7 @@ private struct VoteTallyRow: View { .foregroundColor(Color.dash.secondaryText) if canVote { - Button(NSLocalizedString("Vote", comment: "Voting"), action: onVote) + Button(voteTitle, action: onVote) .buttonStyle(.bordered) .controlSize(.small) } diff --git a/DashWallet/Sources/UI/DashPay/Voting/UsernameVotingScreen.swift b/DashWallet/Sources/UI/DashPay/Voting/UsernameVotingScreen.swift index 89f0470355..95099e0bea 100644 --- a/DashWallet/Sources/UI/DashPay/Voting/UsernameVotingScreen.swift +++ b/DashWallet/Sources/UI/DashPay/Voting/UsernameVotingScreen.swift @@ -28,13 +28,19 @@ import SwiftUI /// Browsing needs no masternode. The voting controls are enabled only when the /// wallet derives the voting key of at least one active registration. struct UsernameVotingScreen: View { + /// Pops the UIKit stack. The screen lives inside its own `NavigationStack` + /// (see `GovernanceMenuScreen.showVoting`), so the back button has to be + /// wired explicitly — SwiftUI cannot see the UIKit stack underneath it. + let onClose: () -> Void + @StateObject private var viewModel = VotingViewModel() var body: some View { VStack(spacing: 0) { VoterCapacityHeader( nodes: viewModel.votableNodes, - totalWeight: viewModel.totalVoteWeight) + totalWeight: viewModel.totalVoteWeight, + voteWithAllNodes: $viewModel.voteWithAllNodes) if viewModel.nodeListMayBeIncomplete { VotingBanner( @@ -57,6 +63,11 @@ struct UsernameVotingScreen: View { placement: .navigationBarDrawer(displayMode: .always), prompt: NSLocalizedString("Search usernames", comment: "Voting")) .toolbar { + ToolbarItem(placement: .navigationBarLeading) { + Button(action: onClose) { + Image(systemName: "chevron.left") + } + } ToolbarItem(placement: .navigationBarTrailing) { if viewModel.isSelecting { Button(NSLocalizedString("Done", comment: "")) { viewModel.endSelecting() } @@ -151,6 +162,7 @@ struct UsernameVotingScreen: View { private struct VoterCapacityHeader: View { let nodes: [VoterNode] let totalWeight: UInt32 + @Binding var voteWithAllNodes: Bool var body: some View { HStack(spacing: 10) { @@ -183,6 +195,33 @@ private struct VoterCapacityHeader: View { .padding(.vertical, 12) .frame(maxWidth: .infinity, alignment: .leading) .background(Color.dash.secondaryBackground) + + // Only meaningful with more than one node — with one, both modes do + // exactly the same thing. + if nodes.count > 1 { + VStack(alignment: .leading, spacing: 4) { + Picker(NSLocalizedString("Vote with", comment: "Voting"), + selection: $voteWithAllNodes) { + Text(NSLocalizedString("One node at a time", comment: "Voting")).tag(false) + Text(NSLocalizedString("All nodes at once", comment: "Voting")).tag(true) + } + .pickerStyle(.segmented) + + Text(voteWithAllNodes + ? NSLocalizedString( + "Every node votes together. Faster, but it publicly links your masternodes to each other.", + comment: "Voting") + : NSLocalizedString( + "Each tap votes with one more node, so you choose how many to link together.", + comment: "Voting")) + .font(.caption) + .foregroundColor(Color.dash.secondaryText) + } + .padding(.horizontal, 16) + .padding(.bottom, 12) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Color.dash.secondaryBackground) + } } private var nodeSummary: String { diff --git a/DashWallet/Sources/UI/DashPay/Voting/VotingViewModel.swift b/DashWallet/Sources/UI/DashPay/Voting/VotingViewModel.swift index 408e31497b..5a11ed1d22 100644 --- a/DashWallet/Sources/UI/DashPay/Voting/VotingViewModel.swift +++ b/DashWallet/Sources/UI/DashPay/Voting/VotingViewModel.swift @@ -82,6 +82,19 @@ final class VotingViewModel: ObservableObject { /// Per-contest results of the most recent bulk run. @Published var bulkReports: [VoteCastReport]? + /// How many of this wallet's nodes have already voted, per contest, from + /// local history. Drives the "2 of 5 votes cast" line and picks the next + /// node in one-at-a-time mode. + @Published private(set) var castCountsByContest: [String: Int] = [:] + /// Which of our nodes voted on the contest currently being viewed. + @Published private(set) var votedProTxHashesForOpenContest: Set = [] + + /// `false` (default) casts with one node per tap. Persisted, because it is + /// a privacy choice the user should not have to re-make each launch. + @Published var voteWithAllNodes: Bool = VotingPrefs.shared.voteWithAllNodes { + didSet { VotingPrefs.shared.voteWithAllNodes = voteWithAllNodes } + } + /// Result banner for the most recent casting run. @Published var lastCastReport: VoteCastReport? /// Error from a casting run that never got as far as broadcasting. @@ -93,6 +106,7 @@ final class VotingViewModel: ObservableObject { private let contestsService: ContestedNamesService private let registry: MasternodeVoterRegistry private let caster: MasternodeVoteCaster + private let history: VoteHistoryDAO = VoteHistoryDAOImpl.shared /// Default arguments would have to be evaluated in a nonisolated context, /// but both services are `@MainActor`, so the defaults are applied inside @@ -168,6 +182,9 @@ final class VotingViewModel: ObservableObject { votableNodes = resolution.nodes nodeListMayBeIncomplete = resolution.mayBeIncomplete + castCountsByContest = await history.voteCountsByContest( + network: MasternodeVoteCaster.networkKey) + do { contests = try await contestsService.activeContests() loadError = nil @@ -228,6 +245,41 @@ final class VotingViewModel: ObservableObject { closedLabels.contains(normalizedLabel) } + // MARK: Vote history + + /// Votes this wallet has cast on `contest`, and how many it could cast in + /// total — the "2 of 5" the row and detail screen show. + func castCount(for normalizedLabel: String) -> Int { + castCountsByContest[normalizedLabel] ?? 0 + } + + /// Nodes that have not yet voted on this contest, in registration order. + func nodesYetToVote(on normalizedLabel: String) -> [VoterNode] { + votableNodes.filter { !votedProTxHashesForOpenContest.contains($0.proTxHash) } + } + + /// Load which of our nodes already voted on one contest. Called when its + /// detail screen opens, so the vote button knows what is left. + func loadVotedNodes(for normalizedLabel: String) async { + let records = await history.votes( + forContest: normalizedLabel, + network: MasternodeVoteCaster.networkKey) + votedProTxHashesForOpenContest = Set(records.map(\.proTxHash)) + castCountsByContest[normalizedLabel] = records.count + } + + /// The nodes a single tap should vote with, honouring the privacy mode. + /// + /// One-at-a-time takes the first node that has not voted on this contest + /// yet; all-at-once takes every node still outstanding. Returns empty when + /// every node has already voted — the caller disables the control rather + /// than re-broadcasting a vote Platform would reject as a duplicate. + func nodesForNextVote(on normalizedLabel: String) -> [VoterNode] { + let remaining = nodesYetToVote(on: normalizedLabel) + guard !remaining.isEmpty else { return [] } + return voteWithAllNodes ? remaining : [remaining[0]] + } + // MARK: Casting /// Cast `choice` on `contest` with `nodes`, then refresh that contest. @@ -242,6 +294,7 @@ final class VotingViewModel: ObservableObject { onNormalizedLabel: contest.normalizedLabel, with: nodes) lastCastReport = report + await loadVotedNodes(for: contest.normalizedLabel) await refreshContest(normalizedLabel: contest.normalizedLabel) } catch { castError = (error as? LocalizedError)?.errorDescription ?? String(describing: error) diff --git a/DashWallet/Sources/UI/Menu/Governance/GovernanceMenuScreen.swift b/DashWallet/Sources/UI/Menu/Governance/GovernanceMenuScreen.swift index 6b11cc5942..073f7ab08c 100644 --- a/DashWallet/Sources/UI/Menu/Governance/GovernanceMenuScreen.swift +++ b/DashWallet/Sources/UI/Menu/Governance/GovernanceMenuScreen.swift @@ -120,9 +120,26 @@ struct GovernanceMenuScreen: View { #if DASHPAY private func showVoting() { - let controller = UIHostingController(rootView: UsernameVotingScreen()) - controller.hidesBottomBarWhenPushed = true - vc.pushViewController(controller, animated: true) + // Same wrapper as `showMasternodes` above, and for the same reasons. + // A bare hosting controller inherits this screen's hidden navigation + // bar (`BaseNavigationController.willShow` only restores it for a + // `NavigationBarDisplayable`), which left the voting screens with no + // back button and no way out — and silently dropped the `.toolbar` + // and `.navigationTitle` as well, since neither renders outside a + // navigation container. + let navController = vc + let popRoot: () -> Void = { [weak navController] in + _ = navController?.popViewController(animated: true) + } + let hosting = UIHostingController( + rootView: AnyView( + NavigationStack { + UsernameVotingScreen(onClose: popRoot) + } + ) + ) + hosting.hidesBottomBarWhenPushed = true + vc.pushViewController(hosting, animated: true) } #endif } diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index 61be815507..9a05170dc5 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -4800,3 +4800,10 @@ "No open contest matches that search." = "No open contest matches that search."; "“%@” could not be read as a Dash username." = "“%@” could not be read as a Dash username."; " or " = " or "; +"Your votes" = "Your votes"; +"All of your masternodes have voted on this username. To change a vote, vote again from the contender you now prefer." = "All of your masternodes have voted on this username. To change a vote, vote again from the contender you now prefer."; +"One node at a time" = "One node at a time"; +"All nodes at once" = "All nodes at once"; +"Every node votes together. Faster, but it publicly links your masternodes to each other." = "Every node votes together. Faster, but it publicly links your masternodes to each other."; +"Each tap votes with one more node, so you choose how many to link together." = "Each tap votes with one more node, so you choose how many to link together."; +"Selecting fewer nodes reveals less about which masternodes you run." = "Selecting fewer nodes reveals less about which masternodes you run."; diff --git a/DashWallet/en.lproj/Localizable.stringsdict b/DashWallet/en.lproj/Localizable.stringsdict index 2d4ae935f3..88b490822c 100644 --- a/DashWallet/en.lproj/Localizable.stringsdict +++ b/DashWallet/en.lproj/Localizable.stringsdict @@ -98,6 +98,22 @@ %2$d masternodes + %d of %d nodes voted + + NSStringLocalizedFormatKey + %1$d of %#@nodes@ voted + nodes + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + d + one + %2$d node + other + %2$d nodes + + %d of %d usernames voted on NSStringLocalizedFormatKey @@ -114,6 +130,22 @@ %2$d usernames + %d of your nodes already voted here and are not listed. + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + d + one + %d of your nodes already voted here and is not listed. + other + %d of your nodes already voted here and are not listed. + + %d requests NSStringLocalizedFormatKey @@ -274,5 +306,21 @@ Vote on %d usernames + Vote ×%d + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + d + one + Vote ×%d + other + Vote ×%d + +