Repository navigation
fix(dashpay): make the voting screens escapable and vote one node at a time #934
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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); | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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) | ||
|
Comment on lines
+233
to
+241
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift Expose vote-history database failures to both callers. The DAO swallows SQLite failures, so callers cannot guarantee that accepted votes are persisted or that wallet cleanup removed old history.
📍 Affects 2 files
🤖 Prompt for AI Agents |
||
| Self.logger.info( | ||
| "🗳️ VOTING :: cast \(choice.logDescription, privacy: .public) on \(normalizedLabel, privacy: .public) with \(node.displayName, privacy: .public)") | ||
| } catch { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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)") | ||
| } | ||
|
Comment on lines
+82
to
+86
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift Do not hide vote-history write failures.
Make 🤖 Prompt for AI Agents |
||
| } | ||
|
|
||
| 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") | ||
|
Comment on lines
+139
to
+141
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift 🧩 Analysis chain🏁 Script executed: #!/bin/bash
set -euo pipefail
# Locate wallet-wipe deletion callers and DAO access sites.
ast-grep outline DashWallet/Sources/Models/Voting/VoteHistoryDAO.swift --items all --view expanded
rg -n -C 6 --glob '*.swift' 'VoteHistoryDAOImpl\.shared|VoteHistoryDAO|\.deleteAll\s*\(' DashWallet/SourcesRepository: dashpay/dashwallet-ios Length of output: 12952 🏁 Script executed: #!/bin/bash
set -euo pipefail
printf '%s\n' '--- App.cleanUp context and callers ---'
sed -n '70,130p' DashWallet/Sources/Application/App.swift
rg -n -C 8 --glob '*.swift' 'cleanUp\s*\(|\.cleanUp\s*\(' DashWallet/Sources
printf '%s\n' '--- Vote caster write path ---'
sed -n '100,260p' DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/MasternodeVoteCaster.swift
rg -n -C 8 --glob '*.swift' 'history\.record|record\s*\(.*CastVoteRecord|castVote|cast\(' DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting DashWallet/Sources/UI/DashPay/Voting
printf '%s\n' '--- DAO and database connection definitions ---'
sed -n '1,155p' DashWallet/Sources/Models/Voting/VoteHistoryDAO.swift
rg -n -C 8 --glob '*.swift' 'class DatabaseConnection|struct DatabaseConnection|static let shared.*DatabaseConnection|Connection\(' DashWallet/SourcesRepository: dashpay/dashwallet-ios Length of output: 43142 🏁 Script executed: #!/bin/bash
set -euo pipefail
printf '%s\n' '--- Wallet wiper structure and call sites ---'
ast-grep outline DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift --items all --view expanded
sed -n '1,210p' DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift
rg -n -C 10 --glob '*.swift' 'SwiftDashSDKWalletWiper|wipeWallet|deleteWallet|removeWallet|wallet.*wipe|wipe.*wallet' DashWallet/Sources
printf '%s\n' '--- Vote-cast task and lifecycle coordination ---'
rg -n -C 8 --glob '*.swift' 'MasternodeVoteCaster|VotingViewModel|Task\s*\{|Task\.|cancel\s*\(|isCasting|cleanUp\s*\(' DashWallet/Sources/Infrastructure/SwiftDashSDK DashWallet/Sources/UI/DashPay/Voting DashWallet/Sources/ApplicationRepository: dashpay/dashwallet-ios Length of output: 50379 🏁 Script executed: #!/bin/bash
set -euo pipefail
printf '%s\n' '--- SwiftDashSDKWalletWiper.swift ---'
wc -l DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift
sed -n '1,190p' DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift
printf '%s\n' '--- Exact App.cleanUp callers ---'
rg -n -C 12 --glob '*.swift' 'App(\.shared)?\.cleanUp|waitForPendingWipe|deleteWalletFromSDK' DashWallet/Sources/Infrastructure/SwiftDashSDK DashWallet/Sources/Application DashWallet/Sources/UI/Setup DashWallet/Sources/UI/Menu
printf '%s\n' '--- Vote task ownership ---'
rg -n -C 5 --glob '*.swift' 'Task\s*\{|Task\.|isCasting|MasternodeVoteCaster' DashWallet/Sources/UI/DashPay/Voting DashWallet/Sources/Infrastructure/SwiftDashSDK/VotingRepository: dashpay/dashwallet-ios Length of output: 50378 🏁 Script executed: #!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
dao = Path("DashWallet/Sources/Models/Voting/VoteHistoryDAO.swift").read_text()
caster = Path("DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/MasternodeVoteCaster.swift").read_text()
app = Path("DashWallet/Sources/Application/App.swift").read_text()
wiper = Path("DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift").read_text()
sheet = Path("DashWallet/Sources/UI/DashPay/Voting/CastVoteSheet.swift").read_text()
bulk = Path("DashWallet/Sources/UI/DashPay/Voting/BulkVoteSheet.swift").read_text()
checks = {
"deleteAll is nonisolated and synchronous": "nonisolated func deleteAll()" in dao,
"record is async": "func record(_ record: CastVoteRecord, network: String) async" in dao,
"successful SDK cast precedes record": (
"try await sdk.castContestedResourceVote(" in caster
and "await Self.history.record(" in caster
and caster.index("try await sdk.castContestedResourceVote(")
< caster.index("await Self.history.record(")
),
"cleanup calls synchronous deleteAll": "VoteHistoryDAOImpl.shared.deleteAll()" in app,
"cleanup is inside main sync": (
"DispatchQueue.main.sync {" in wiper
and wiper.index("DispatchQueue.main.sync {")
< wiper.index("App.shared.cleanUp()")
),
"single-vote UI starts unretained Task": "Task {" in sheet and "await viewModel.cast(" in sheet,
"bulk-vote UI starts unretained Task": "Task { await viewModel.castBulk" in bulk,
}
for name, passed in checks.items():
print(f"{'PASS' if passed else 'FAIL'}: {name}")
if not all(checks.values()):
raise SystemExit(1)
PYRepository: dashpay/dashwallet-ios Length of output: 433 Coordinate wallet-wipe cleanup with vote recording. A successful vote records history asynchronously after the SDK call returns. Wallet wipe can delete history before Make 🤖 Prompt for AI Agents |
||
| } 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 | ||
| } | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Use a non-future migration timestamp.
The filename
20260808030000_add_masternode_vote_history.sqlencodes August 8, 2026. The review date is August 7, 2026. A migration created later on August 7 can sort before this migration in a timestamp-ordered runner. Rename this file with its actual creation timestamp before merge.🤖 Prompt for AI Agents
Source: Coding guidelines