Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 85 additions & 4 deletions DashWallet.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -110,24 +110,17 @@ final class ContestedNamesService {
/// never contested, or the poll has been pruned since it resolved.
func voteState(normalizedLabel: String) async throws -> DPNSContestVoteState? {
let sdk = try requireSDK()
// FIXME(sdk): this blocks the main thread. `SDK.dpnsContestVoteState`
// is a synchronous `@MainActor` method around a blocking FFI call that
// goes to an evonode, so the round-trip runs on the main thread and the
// UI freezes until it answers — opening "Request details" hangs the app
// for seconds. It cannot be fixed here: the method's isolation forbids
// calling it off the main actor. The fix belongs in swift-sdk, where
// `dpnsActiveContests` in the same file already shows the shape
// (continuation + a dedicated GCD queue).
return try sdk.dpnsContestVoteState(normalizedLabel: normalizedLabel)
// The off-main read runs the FFI round trip on the SDK's Platform
// query queue, so the main thread only awaits it.
return try await sdk.dpnsContestVoteStateOffMain(normalizedLabel: normalizedLabel)
}

/// Whether a vote cast right now on `normalizedLabel` can still be
/// accepted. Used as a pre-flight so a closed poll fails immediately
/// instead of after a long broadcast retry.
func contestIsOpen(normalizedLabel: String) async throws -> Bool {
let sdk = try requireSDK()
// Same main-thread problem as `voteState`, same place to fix it.
return try sdk.dpnsContestIsOpen(normalizedLabel: normalizedLabel)
return try await sdk.dpnsContestIsOpenOffMain(normalizedLabel: normalizedLabel)
}

/// Homograph-normalize a user-typed label into the form Platform indexes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,11 @@ enum VoteChoice: Hashable {
/// so a partial run is reported as a partial run rather than as an error.
struct VoteOutcome: Identifiable {
let node: VoterNode
/// `nil` on success; the Platform or local error message otherwise.
/// `nil` on success; the reason in plain words otherwise.
let failure: String?
/// `false` when Platform accepted the vote but the local history write
/// failed, so the stored cast count is one low.
var historyRecorded: Bool = true

var id: Data { node.proTxHash }
var succeeded: Bool { failure == nil }
Expand Down Expand Up @@ -108,8 +111,6 @@ 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 {
Expand All @@ -118,12 +119,40 @@ final class MasternodeVoteCaster {
WalletEnvironment.network?.persistenceScope ?? "mainnet"
}

private let registry: MasternodeVoterRegistry
private let contests: ContestedNamesService
private let history: VoteHistoryDAO
private let votingKey: (VoterNode) -> Data?
private let send: VoteSender

/// Broadcasts one vote for one node. Throws on any failure.
typealias VoteSender = (
_ node: VoterNode, _ votingKey: Data, _ choice: VoteChoice, _ normalizedLabel: String
) async throws -> Void

init(registry: MasternodeVoterRegistry, contests: ContestedNamesService) {
self.registry = registry
/// - Parameters:
/// - votingKey: derives a node's voting key; `nil` uses the registry.
/// - send: broadcasts one vote; `nil` uses the SDK.
init(
registry: MasternodeVoterRegistry,
contests: ContestedNamesService,
history: VoteHistoryDAO,
votingKey: ((VoterNode) -> Data?)? = nil,
send: VoteSender? = nil
) {
self.contests = contests
self.history = history
self.votingKey = votingKey ?? { registry.votingPrivateKey(for: $0) }
self.send = send ?? { node, votingKey, choice, normalizedLabel in
guard let sdk = SwiftDashSDKHost.shared.sdk else { throw CastError.sdkUnavailable }
try await sdk.castContestedResourceVote(
dataContractId: DPNSVotePoll.contractId,
documentTypeName: DPNSVotePoll.documentTypeName,
indexName: DPNSVotePoll.indexName,
indexValues: DPNSVotePoll.indexValues(normalizedLabel: normalizedLabel),
choice: choice.sdkChoice,
proTxHash: node.proTxHash,
votingPrivateKey: votingKey)
}
}

enum CastError: LocalizedError {
Expand Down Expand Up @@ -156,7 +185,7 @@ final class MasternodeVoteCaster {
/// Cast `choice` on `normalizedLabel` with each node in `nodes`.
///
/// Prompts for PIN/biometric once, then hands off to
/// ``castAuthenticated(choice:onNormalizedLabel:with:sdk:)``.
/// ``castAuthenticated(choice:onNormalizedLabel:with:)``.
///
/// - Throws: ``CastError`` when the run cannot start at all (auth refused,
/// poll already closed). Once broadcasting starts, per-node failures are
Expand All @@ -168,7 +197,7 @@ final class MasternodeVoteCaster {
with nodes: [VoterNode]
) async throws -> VoteCastReport {
guard !nodes.isEmpty else { throw CastError.noNodesSelected }
guard let sdk = SwiftDashSDKHost.shared.sdk else { throw CastError.sdkUnavailable }
guard SwiftDashSDKHost.shared.sdk != nil else { throw CastError.sdkUnavailable }

// Pre-flight: a closed poll otherwise fails only after a long
// broadcast retry, with an error that says nothing useful.
Expand All @@ -187,7 +216,7 @@ final class MasternodeVoteCaster {
}

return await castAuthenticated(
choice: choice, onNormalizedLabel: normalizedLabel, with: nodes, sdk: sdk)
choice: choice, onNormalizedLabel: normalizedLabel, with: nodes)
}

/// The per-node broadcast loop, after authentication and pre-flight.
Expand All @@ -197,18 +226,34 @@ final class MasternodeVoteCaster {
/// the same node would race on it. Never throws — a node that fails is
/// recorded and the loop continues, so one failure cannot discard the
/// nodes that already succeeded.
private func castAuthenticated(
func castAuthenticated(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion (non-blocking). This went from private to internal so the tests can reach it. That makes a method that signs and broadcasts with the voting keys, with no PIN or biometric prompt, callable from anywhere in the app. The name can also be read as "cast with authentication".

The caster already takes send and votingKey by injection. The steps before the loop could come in the same way: the SDK check, the open-contest pre-flight and the AuthenticationGate call, each defaulting to what runs today. Then the tests could go through cast(...) and this could be private again. If that's more than this stage needs, a name like castAfterAuthentication would at least make a wrong caller stand out. It is still internal at #1347 and #1366.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed at the stack tip in 59f8743 (#1366): it is now castAfterAuthentication. Its doc says it asks no PIN, that it is internal only for the tests, and that app callers go through cast(choice:onNormalizedLabel:with:). I kept the rename and did not inject the pre-flight steps, to keep the change small in the caster.

choice: VoteChoice,
onNormalizedLabel normalizedLabel: String,
with nodes: [VoterNode],
sdk: SDK
with nodes: [VoterNode]
) async -> VoteCastReport {
let indexValues = DPNSVotePoll.indexValues(normalizedLabel: normalizedLabel)
var outcomes: [VoteOutcome] = []
outcomes.reserveCapacity(nodes.count)

for node in nodes {
guard let votingKey = registry.votingPrivateKey(for: node) else {
// Re-read the count before every cast: Platform refuses the sixth,
// and an unreadable count is unknown, never zero.
guard let votes = await history.votes(forContest: normalizedLabel, network: Self.networkKey) else {
outcomes.append(VoteOutcome(
node: node,
failure: NSLocalizedString(
"Could not check how many votes this node has left.",
comment: "Voting")))
continue
}
let castCount = votes.first { $0.proTxHash == node.proTxHash }?.castCount ?? 0
guard castCount < VoteLimit.maxCastsPerNode else {
Comment thread
romchornyi marked this conversation as resolved.
Resolved
outcomes.append(VoteOutcome(
node: node,
failure: NSLocalizedString("No votes left", comment: "Voting")))
continue
}

guard let votingKey = votingKey(node) else {
outcomes.append(VoteOutcome(
node: node,
failure: NSLocalizedString(
Expand All @@ -218,36 +263,39 @@ final class MasternodeVoteCaster {
}

do {
try await sdk.castContestedResourceVote(
dataContractId: DPNSVotePoll.contractId,
documentTypeName: DPNSVotePoll.documentTypeName,
indexName: DPNSVotePoll.indexName,
indexValues: indexValues,
choice: choice.sdkChoice,
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(
try await send(node, votingKey, choice, normalizedLabel)
} catch {
// Stored in plain words: Platform's own text is never shown,
// and never logged beyond the error's type.
let message = VoteErrorMessage.plain(for: error)
outcomes.append(VoteOutcome(node: node, failure: message))
let errorType = String(describing: type(of: error))
let nodeName = node.displayName
Self.logger.error(
"🗳️ VOTING :: cast failed on \(normalizedLabel, privacy: .public) with \(nodeName, privacy: .public): \(errorType, privacy: .public)")
continue
}

// Recorded only on success, so the count the UI shows is
// votes Platform accepted — not votes attempted.
var historyRecorded = true
do {
try await 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 {
// Platform's message is the useful one here — "already voted",
// "too many vote changes", "masternode not found" each tell
// the user something different. Surface it verbatim.
let message = (error as? LocalizedError)?.errorDescription
?? String(describing: error)
outcomes.append(VoteOutcome(node: node, failure: message))
historyRecorded = false
let errorType = String(describing: type(of: error))
Self.logger.error(
"🗳️ VOTING :: cast failed on \(normalizedLabel, privacy: .public) with \(node.displayName, privacy: .public): \(message, privacy: .public)")
"🗳️ VOTING :: history write failed on \(normalizedLabel, privacy: .public): \(errorType, privacy: .public)")
}
outcomes.append(VoteOutcome(node: node, failure: nil, historyRecorded: historyRecorded))
Self.logger.info(
"🗳️ VOTING :: cast \(choice.logDescription, privacy: .public) on \(normalizedLabel, privacy: .public) with \(node.displayName, privacy: .public)")
}

return VoteCastReport(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,17 @@ final class MasternodeVoterRegistry {
static let empty = Resolution(nodes: [], mayBeIncomplete: false)
}

/// The SDK is running and the wallet's sync is done, so an empty
/// ``votableNodes()`` is this wallet's answer rather than a list that is
/// not there yet. The wallet's own masternodes come from its provider
/// transactions, which the filter scan finds after the masternode list
/// has synced, so the gate is the whole sync (`.syncDone`), not the
/// masternode phase.
var isNodeListSynced: Bool {
SwiftDashSDKHost.shared.manager != nil && SwiftDashSDKHost.shared.wallet != nil
&& SyncingActivityMonitor.shared.state == .syncDone
}

/// The wallet's votable nodes, ordered by registration.
///
/// A masternode is votable when all of the following hold:
Expand Down
12 changes: 5 additions & 7 deletions DashWallet/Sources/Models/Voting/VoteHistoryDAO.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ struct CastVoteRecord: Hashable {
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
/// - Throws: the store's error, so a caller whose vote already landed can
/// still count it as a spent cast.
func record(_ record: CastVoteRecord, network: String) async throws
/// Votes this device cast on one contest, newest first. `nil` when the
/// store could not be read — unknown, not "no votes".
func votes(forContest normalizedLabel: String, network: String) async -> [CastVoteRecord]?
Expand All @@ -71,7 +73,7 @@ actor VoteHistoryDAOImpl: VoteHistoryDAO {
self.connection = connection
}

func record(_ record: CastVoteRecord, network: String) async {
func record(_ record: CastVoteRecord, network: String) async throws {
let query = """
INSERT INTO masternode_vote_history
(proTxHash, normalizedLabel, network, choice, contenderIdentityId, castAt, castCount)
Expand All @@ -94,11 +96,7 @@ actor VoteHistoryDAOImpl: VoteHistoryDAO {
Int64(record.castAt.timeIntervalSince1970 * 1000),
]

do {
try db.run(query, bindings)
} catch {
DWLogger.log("VoteHistoryDAO: record failed: \(error)")
}
try db.run(query, bindings)
}

func votes(forContest normalizedLabel: String, network: String) async -> [CastVoteRecord]? {
Expand Down
Loading
Loading