diff --git a/docs/protocol/decision-proposals.md b/docs/protocol/decision-proposals.md index 9cc64feb53a..8266e99737e 100644 --- a/docs/protocol/decision-proposals.md +++ b/docs/protocol/decision-proposals.md @@ -408,10 +408,14 @@ given its contest fund like any contested create), and their contested resource queries and masternode vote read and answer the vote, with a choice's document id wherever they name a contender by an identity id. -The Rust SDK (`dash_sdk::platform::decision_proposals::multiple_choice`) and the +The Rust SDK (`dash_sdk::platform::decision_proposals::multiple_choice`), the JavaScript SDKs (`sdk.decisionProposals.multipleChoice` in `@dashevo/evo-sdk`, -the `*MultipleChoiceProposal*` methods of `@dashevo/wasm-sdk`) have helpers over -those: +the `*MultipleChoiceProposal*` methods of `@dashevo/wasm-sdk`) and the mobile +SDKs (the `dash_sdk_multiple_choice_proposal_*` C functions of `rs-sdk-ffi` and +the `platform_wallet_multiple_choice_proposal_*` ones of +`rs-platform-wallet-ffi`, wrapped by the Swift SDK and by the Kotlin SDK's +`Sdk.multipleChoiceProposals` and `PlatformWalletManager.multipleChoiceProposals`) +have helpers over those: - build a proposal, its edit and a choice as documents to create or replace; - give the proposal's processing fee and the fund a choice entered now pays; @@ -425,5 +429,7 @@ those: The contest a proposal's choices run in is named from the proposal's id alone (`dpp::decision_proposal::multiple_choice::multiple_choice_proposal_vote_poll`). The helpers write what they are given: which descriptions, texts and choices -Platform takes is checked by the contract, on chain. The mobile SDKs have no -multiple choice helpers yet. +Platform takes is checked by the contract, on chain. The mobile SDKs create +and edit a proposal and enter a choice through the platform wallet, which signs +and puts the document, where the Rust and JavaScript helpers return the document +to put. diff --git a/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md b/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md index 0a276aa692c..b43f3dda640 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md +++ b/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md @@ -182,6 +182,13 @@ Most Platform actions have hard preconditions. Establish these fixtures before s | VOTE-11 | Edit a decision proposal's text | Platform | Thorough | ✅ | proposal | Detail → Edit Text (`decisionProposal.edit`, shown only when a local wallet identity filed it) → `editDecisionProposal.*` → `PlatformWalletManager.decisionProposals.edit` (one `platform_wallet_decision_proposal_edit` call; no signing key is chosen in the app). Accepted for a day after creation; an edit that changes nothing is refused before anything is broadcast, and an edit that raced another one is refused by Platform (consensus code 40106) rather than overwriting it. The dialog cannot be dismissed while it broadcasts. | | VOTE-12 | Masternode vote on a decision proposal (yes / no / abstain) | Platform | Thorough | ✅ | proposal, masternode | Detail → Vote (`decisionProposal.vote`) → `decisionProposalVote.choice` / `.proTxHash` / `.votingKey` / `.submit` → `dash_sdk_decision_proposal_cast_vote`. The voting key shows as dots and a screenshot of the open dialog comes out blank (FLAG_SECURE). **Requires masternode voting credentials**; a vote from a regular wallet is refused (no voter identity). | | VOTE-13 | Read a masternode's answer on a decision proposal | Platform | Thorough | ✅ | proposal, masternode, read-only | Vote dialog → Read This Masternode's Answer (`decisionProposalVote.lookUp`) → `dash_sdk_decision_proposal_get_masternode_vote`. No answer once the poll finished. | +| VOTE-14 | List multiple choice proposals (mine / newest, paged) | Platform | Thorough | ✅ | proposal, read-only | `QueriesListScreen` → Multiple Choice Proposals (`votingQueries.multipleChoiceProposalsLink`) → `MultipleChoiceProposalsScreen`: listing picker (`multipleChoiceProposals.listing`), identity picker for Mine (`multipleChoiceProposals.ownerPicker`), Load More (`multipleChoiceProposals.loadMore`). Needs protocol version 15; an earlier network shows a load error. | +| VOTE-15 | Create a multiple choice proposal | Platform | Thorough | ✅ | proposal | `MultipleChoiceProposalsScreen` + (`multipleChoiceProposals.create`) → `CreateMultipleChoiceProposalScreen` (`createMultipleChoiceProposal.*`) → `PlatformWalletManager.multipleChoiceProposals.create` (one `platform_wallet_multiple_choice_proposal_create` call; the success section shows the returned id). The Proposer section shows the processing fee read from `dash_sdk_multiple_choice_proposal_get_processing_fee` (`createMultipleChoiceProposal.processingFee`, 0.2 DASH at protocol version 15), which Platform charges on top of the fees. The description document is three optional fields (`.descriptionDocumentId` / `.descriptionDocumentContractId` / `.descriptionDocumentType`); the switch `.open` says whether anyone may enter choices. While it broadcasts, system Back does nothing, and a rotation or a bottom-tab switch does not cancel it. Platform refuses a proposal with neither a description document nor a url. Protocol version 15. | +| VOTE-16 | View a multiple choice proposal, its choices and its vote | Platform | Thorough | ✅ | proposal, read-only | `MultipleChoiceProposalDetailScreen` (row `multipleChoiceProposals.row.`): the proposal, who enters choices (`multipleChoiceProposal.open`), the vote status (`multipleChoiceProposal.voteStatus`: no choice entered, voting open, or how it ended), every choice with its tally (`multipleChoiceProposal.choice.`), the none-of-the-choices and abstain tallies, and once the vote ended the kept choice (`multipleChoiceProposal.keptChoice`, read with `dash_sdk_multiple_choice_proposal_get_kept_choice`). | +| VOTE-17 | Enter a choice for a multiple choice proposal | Platform | Thorough | ✅ | proposal | Detail → Enter a Choice (`multipleChoiceProposal.enterChoice`, shown when a loaded wallet holds an identity) → `enterProposalChoice.ownerPicker` / `.title` / `.description` / `.submitButton` → `PlatformWalletManager.multipleChoiceProposals.enterChoice` (one `platform_wallet_multiple_choice_proposal_enter_choice` call). The dialog shows the contest fund read from `dash_sdk_multiple_choice_proposal_get_choice_fund_to_join` (`enterProposalChoice.fund`), paid on top of the fees. The first choice opens the vote. Platform refuses a choice from anyone but the owner when the proposal is not open; the app does not pre-check it. The entry survives a rotation (the detail screen then shows its outcome), system Back does nothing while it broadcasts, and the action result names the new choice id. | +| VOTE-18 | Edit a multiple choice proposal | Platform | Thorough | ✅ | proposal | Detail → Edit (`multipleChoiceProposal.edit`, shown only when a local wallet identity filed it) → `editMultipleChoiceProposal.*` → `PlatformWalletManager.multipleChoiceProposals.edit` (one `platform_wallet_multiple_choice_proposal_edit` call). Only the changed fields are sent; an emptied url, or three emptied description document fields, removes it. Accepted for two hours after creation (Platform refuses it afterwards; the app does not hide the button); an edit that changes nothing is refused before anything is broadcast, one that leaves neither a description document nor a url is refused by Platform, and one that raced another edit is refused with consensus code 40106. The dialog cannot be dismissed while it broadcasts. | +| VOTE-19 | Masternode vote among a multiple choice proposal's choices (a choice / none of the choices / abstain) | Platform | Thorough | ✅ | proposal, masternode | Detail → Vote (`multipleChoiceProposal.vote`) → `multipleChoiceProposalVote.choice` (every choice of the running vote by title and id, then None of the choices and Abstain) / `.proTxHash` / `.votingKey` / `.submit` → `dash_sdk_multiple_choice_proposal_cast_vote`. The voting key shows as dots and a screenshot of the open dialog comes out blank (FLAG_SECURE); the dialog cannot be dismissed while it broadcasts. **Requires masternode voting credentials**; a vote from a regular wallet is refused (no voter identity). | +| VOTE-20 | Read a masternode's answer among a multiple choice proposal's choices | Platform | Thorough | ✅ | proposal, masternode, read-only | Vote dialog → Read This Masternode's Answer (`multipleChoiceProposalVote.lookUp`) → `dash_sdk_multiple_choice_proposal_get_masternode_vote`. No answer once the vote ended. | ### 4.6 Data Contracts — `Domain=Contract` @@ -314,7 +321,7 @@ Counts are of rows reachable in the app (Status `✅`/`🧪`/`⚠️`); `🔌`/` |---|---|---| | Essential | 21 | yes | | Common | 29 | yes | -| Thorough | 42 | yes | +| Thorough | 49 | yes | | Uncommon | 25 | yes | | Manual | 1 (`CORE-08`) | no — physical device | @@ -323,7 +330,7 @@ Counts are of rows reachable in the app (Status `✅`/`🧪`/`⚠️`); `🔌`/` | Layer | Count (approx.) | |---|---| | Core | 17 | -| Platform | ~80 | +| Platform | ~87 | | Cross | 7 | | Shielded | 16 | @@ -337,7 +344,7 @@ Membership of each feature category across **all** sections (primary section mem - **Identity** — `ID-01..15`, `SH-11` - **Address** (DIP-17 platform addresses) — `ADDR-01..04`, `ADDR-06..09`, `ID-06`, `ID-08`, `ID-11` - **DPNS** — `DPNS-01..08` -- **Voting** — `VOTE-01..13`, `DPNS-05`, `DPNS-08` +- **Voting** — `VOTE-01..20`, `DPNS-05`, `DPNS-08` - **Contract** — `DC-01..04` - **Document** — `DOC-01..15` - **Token** — `TOK-01..20` @@ -354,6 +361,6 @@ Tags are cross-cutting modalities. A test may appear under multiple tags. - **contested** — `DPNS-05`, `DPNS-08`, `VOTE-01..06` - **withdrawal** — `ID-10`, `ADDR-04`, `SH-08`, `SH-16` - **regression** — `TOK-17`, `DP-10` -- **read-only** — `SH-13`, `SYS-05`, `SYS-06`, `VOTE-02..06`, `VOTE-08`, `VOTE-10`, `VOTE-13`, `TOK-18`, `TOK-19` -- **masternode** — `VOTE-01`, `VOTE-12`, `VOTE-13` -- **proposal** (decision proposals, protocol version 15): `VOTE-08..13` +- **read-only** — `SH-13`, `SYS-05`, `SYS-06`, `VOTE-02..06`, `VOTE-08`, `VOTE-10`, `VOTE-13`, `VOTE-14`, `VOTE-16`, `VOTE-20`, `TOK-18`, `TOK-19` +- **masternode** — `VOTE-01`, `VOTE-12`, `VOTE-13`, `VOTE-19`, `VOTE-20` +- **proposal** (decision proposals, yes/no and multiple choice, protocol version 15): `VOTE-08..20` diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/navigation/AppNavHost.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/navigation/AppNavHost.kt index b55b17e3b2c..f3429a0eed7 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/navigation/AppNavHost.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/navigation/AppNavHost.kt @@ -32,8 +32,11 @@ import org.dashfoundation.example.ui.identity.AddIdentityKeyScreen import org.dashfoundation.example.ui.identity.ContestDetailScreen import org.dashfoundation.example.ui.identity.CreateDecisionProposalScreen import org.dashfoundation.example.ui.identity.CreateIdentityScreen +import org.dashfoundation.example.ui.identity.CreateMultipleChoiceProposalScreen import org.dashfoundation.example.ui.identity.DecisionProposalDetailScreen import org.dashfoundation.example.ui.identity.DecisionProposalsScreen +import org.dashfoundation.example.ui.identity.MultipleChoiceProposalDetailScreen +import org.dashfoundation.example.ui.identity.MultipleChoiceProposalsScreen import org.dashfoundation.example.ui.dashpay.AddContactScreen import org.dashfoundation.example.ui.dashpay.ContactDetailScreen import org.dashfoundation.example.ui.dashpay.ContactRequestsScreen @@ -486,6 +489,19 @@ fun AppNavHost( ) } + composable { MultipleChoiceProposalsScreen(navController) } + + composable { + CreateMultipleChoiceProposalScreen(navController) + } + + composable { entry -> + MultipleChoiceProposalDetailScreen( + entry.toRoute().proposalId, + navController, + ) + } + composable { entry -> val route = entry.toRoute() GroupDetailScreen(route.contractIdHex, route.position, navController) diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/navigation/Routes.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/navigation/Routes.kt index f9f8ede75c4..05023153150 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/navigation/Routes.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/navigation/Routes.kt @@ -430,6 +430,23 @@ import kotlinx.serialization.Serializable */ @Serializable data class DecisionProposalDetail(val proposalId: String) +/** + * Multiple choice proposal listings: a local identity's and the newest + * (← `MultipleChoiceProposalsView.swift`). Reached from the Platform Queries list, beside + * [DecisionProposalsList]. + */ +@Serializable object MultipleChoiceProposalsList + +/** File a new multiple choice proposal (← `CreateMultipleChoiceProposalView`). */ +@Serializable object CreateMultipleChoiceProposal + +/** + * One multiple choice proposal: its choices and their tallies, how the vote ended, entering + * a choice, the edit and the masternode vote (← `MultipleChoiceProposalDetailView.swift`). + * [proposalId] is base58. + */ +@Serializable data class MultipleChoiceProposalDetail(val proposalId: String) + /** * One contract group's members + live proposals (← `GroupDetailView.swift`). * [position] is the group contract position inside the contract's diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/QueryDetailScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/QueryDetailScreen.kt index edb8e45919b..bdd6bbdf67e 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/QueryDetailScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/QueryDetailScreen.kt @@ -40,6 +40,7 @@ import org.dashfoundation.example.navigation.AddressQueries import org.dashfoundation.example.navigation.DecisionProposalsList import org.dashfoundation.example.navigation.Diagnostics import org.dashfoundation.example.navigation.GroveDbPathElements +import org.dashfoundation.example.navigation.MultipleChoiceProposalsList import org.dashfoundation.example.navigation.QueryDetail import org.dashfoundation.example.ui.components.FormSection import org.dashfoundation.example.ui.components.SubmitButton @@ -136,6 +137,20 @@ fun QueriesListScreen(navController: NavHostController) { .clickable { navController.navigate(DecisionProposalsList) } .testTag("votingQueries.decisionProposalsLink"), ) + ListItem( + headlineContent = { Text("Multiple Choice Proposals") }, + supportingContent = { + Text( + "Browse, file and edit questions answered by the choices entered " + + "for them, enter choices and vote among them (protocol " + + "version 15)", + style = MaterialTheme.typography.bodySmall, + ) + }, + modifier = Modifier + .clickable { navController.navigate(MultipleChoiceProposalsList) } + .testTag("votingQueries.multipleChoiceProposalsLink"), + ) ListItem( headlineContent = { Text("Run All Queries") }, supportingContent = { diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/QueryRegistry.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/QueryRegistry.kt index 58260589e73..b0bdc04f2d6 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/QueryRegistry.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/QueryRegistry.kt @@ -1,7 +1,6 @@ package org.dashfoundation.example.ui.contracts import org.dashfoundation.dashsdk.Sdk -import org.dashfoundation.dashsdk.voting.DecisionProposal import org.dashfoundation.example.ui.identity.decode32ByteHex /** @@ -598,6 +597,105 @@ internal val QUERY_REGISTRY: List = listOf( ?.toString() }, + // ── Multiple Choice Proposals (protocol version 15) ─────────────────── + // The typed reads of `Sdk.multipleChoiceProposals`, shown as their + // Kotlin values. `MultipleChoiceProposalsScreen` is the full flow (list, + // file, edit, enter a choice, vote); these rows run each read on its own. + QueryDefinition( + name = "getMultipleChoiceProposal", + label = "Get Multiple Choice Proposal", + description = "Fetch a multiple choice proposal by its base58 id.", + inputs = listOf(QueryInput("proposalId", "Proposal ID", required = true)), + runsInDiagnostics = false, + ) { sdk, inputs -> + sdk.multipleChoiceProposals.fetch(inputs.getValue("proposalId").trim())?.toString() + }, + QueryDefinition( + name = "getMultipleChoiceProposalsByOwner", + label = "Get Multiple Choice Proposals by Owner", + description = "The multiple choice proposals an identity filed, in the order it filed them.", + inputs = listOf( + QueryInput("ownerId", "Owner Identity ID", required = true), + QueryInput("limit", "Limit", required = false, placeholder = "20"), + QueryInput("startAfter", "Start after proposal ID", required = false), + ), + runsInDiagnostics = false, + ) { sdk, inputs -> + sdk.multipleChoiceProposals.listByOwner( + ownerId = inputs.getValue("ownerId").trim(), + limit = inputs["limit"]?.trim()?.toIntOrNull() ?: 0, + startAfter = inputs["startAfter"]?.trim()?.takeIf { it.isNotEmpty() }, + ).describeProposals() + }, + QueryDefinition( + name = "getMultipleChoiceProposalsByCreatedAt", + label = "Get Multiple Choice Proposals by Creation", + description = "Every multiple choice proposal, newest first.", + inputs = listOf( + QueryInput("limit", "Limit", required = false, placeholder = "20"), + QueryInput("startAfter", "Start after proposal ID", required = false), + ), + runsInDiagnostics = false, + ) { sdk, inputs -> + sdk.multipleChoiceProposals.listByCreatedAt( + limit = inputs["limit"]?.trim()?.toIntOrNull() ?: 0, + startAfter = inputs["startAfter"]?.trim()?.takeIf { it.isNotEmpty() }, + ).describeProposals() + }, + QueryDefinition( + name = "getMultipleChoiceProposalVote", + label = "Get Multiple Choice Proposal Vote", + description = "The choices of a proposal with their tallies, and how the vote ended once it did.", + inputs = listOf(QueryInput("proposalId", "Proposal ID", required = true)), + runsInDiagnostics = false, + ) { sdk, inputs -> + sdk.multipleChoiceProposals.vote(inputs.getValue("proposalId").trim()).toString() + }, + QueryDefinition( + name = "getMultipleChoiceProposalKeptChoice", + label = "Get Multiple Choice Proposal Kept Choice", + description = "The choice a proposal's finished vote kept.", + inputs = listOf(QueryInput("proposalId", "Proposal ID", required = true)), + runsInDiagnostics = false, + ) { sdk, inputs -> + sdk.multipleChoiceProposals.keptChoice(inputs.getValue("proposalId").trim())?.toString() + }, + QueryDefinition( + name = "getMasternodeMultipleChoiceVote", + label = "Get Masternode Multiple Choice Vote", + description = "A masternode's answer among a proposal's choices while the vote runs.", + inputs = listOf( + QueryInput("proTxHash", "pro_tx_hash (64 hex chars, wire order)", required = true), + QueryInput("proposalId", "Proposal ID", required = true), + ), + runsInDiagnostics = false, + ) { sdk, inputs -> + val proTxHash = requireNotNull(decode32ByteHex(inputs.getValue("proTxHash"))) { + "pro_tx_hash must be 32 bytes (64 hex characters)" + } + sdk.multipleChoiceProposals + .masternodeVote(proTxHash, inputs.getValue("proposalId").trim()) + ?.toString() + }, + QueryDefinition( + name = "getMultipleChoiceProposalProcessingFee", + label = "Get Multiple Choice Proposal Processing Fee", + description = "What creating a multiple choice proposal adds to the processing fee, in credits.", + inputs = emptyList(), + runsInDiagnostics = false, + ) { sdk, _ -> + "${sdk.multipleChoiceProposals.processingFee()} credits" + }, + QueryDefinition( + name = "getMultipleChoiceProposalChoiceFundToJoin", + label = "Get Choice Fund to Join", + description = "The contest fund a choice entered now for a proposal pays, in credits.", + inputs = listOf(QueryInput("proposalId", "Proposal ID", required = true)), + runsInDiagnostics = false, + ) { sdk, inputs -> + "${sdk.multipleChoiceProposals.choiceFundToJoin(inputs.getValue("proposalId").trim())} credits" + }, + // ── Protocol & Version ──────────────────────────────────────────────── QueryDefinition( name = "getProtocolVersionUpgradeState", @@ -898,7 +996,10 @@ internal val QUERY_REGISTRY: List = listOf( }, ) -/** A decision proposal listing page as text: its size, then one proposal per line. */ -private fun List.describeProposals(): String = +/** + * A decision proposal listing page (yes/no or multiple choice) as text: its size, then one + * proposal per line. + */ +private fun List.describeProposals(): String = "$size proposal" + (if (size == 1) "" else "s") + joinToString(separator = "\n", prefix = if (isEmpty()) "" else "\n") diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/DecisionProposalDetailScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/DecisionProposalDetailScreen.kt index c76d1737cdd..1be5cd5b379 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/DecisionProposalDetailScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/DecisionProposalDetailScreen.kt @@ -255,9 +255,10 @@ fun DecisionProposalDetailScreen( /** * [read]'s value, or null after handing its failure to [onError], so one failed read - * leaves the others shown. Cancellation is rethrown, never reported as a failure. + * leaves the others shown. Cancellation is rethrown, never reported as a failure. Shared + * with the multiple choice proposal detail screen. */ -private suspend fun readOrNull(onError: (Exception) -> Unit, read: suspend () -> T?): T? = +internal suspend fun readOrNull(onError: (Exception) -> Unit, read: suspend () -> T?): T? = try { read() } catch (e: CancellationException) { diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/MultipleChoiceProposalDetailScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/MultipleChoiceProposalDetailScreen.kt new file mode 100644 index 00000000000..5133c414ce4 --- /dev/null +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/MultipleChoiceProposalDetailScreen.kt @@ -0,0 +1,1022 @@ +package org.dashfoundation.example.ui.identity + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.DialogProperties +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import androidx.navigation.NavHostController +import java.util.Date +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.launch +import org.dashfoundation.dashsdk.persistence.entities.IdentityEntity +import org.dashfoundation.dashsdk.voting.DescriptionDocumentParams +import org.dashfoundation.dashsdk.voting.MultipleChoiceProposal +import org.dashfoundation.dashsdk.voting.MultipleChoiceProposalEdit +import org.dashfoundation.dashsdk.voting.MultipleChoiceProposalVote +import org.dashfoundation.dashsdk.voting.MultipleChoiceVoteChoice +import org.dashfoundation.dashsdk.voting.ProposalChoice +import org.dashfoundation.dashsdk.voting.ProposalChoiceParams +import org.dashfoundation.example.di.LocalAppContainer +import org.dashfoundation.example.di.LocalAppState +import org.dashfoundation.example.ui.components.AccessiblePicker +import org.dashfoundation.example.ui.components.FormSection +import org.dashfoundation.example.ui.components.LabeledContent +import org.dashfoundation.example.ui.components.SubmitButton +import org.dashfoundation.example.ui.tokens.displayLabel +import org.dashfoundation.example.util.Base58 +import org.dashfoundation.example.util.formatCredits +import org.dashfoundation.example.util.formatDate +import org.dashfoundation.example.util.toHex +import org.dashfoundation.example.util.truncateMiddle + +/** + * One multiple choice proposal: port of `MultipleChoiceProposalDetailView.swift`, beside + * the yes/no [DecisionProposalDetailScreen]. + * + * Reads the proposal, the vote among its choices and, once the vote ended, the choice it + * kept through `Sdk.multipleChoiceProposals` (each independently, so one failing read + * leaves the others shown). Shows the choices with their tallies while the vote runs and + * how it ended afterwards. Offers the masternode vote ([MultipleChoiceVoteDialog], the same + * credentials [ContestDetailScreen] collects), entering a choice for a local wallet + * identity ([EnterChoiceDialog]) and, when a local wallet identity filed the proposal, the + * edit ([EditMultipleChoiceProposalDialog]). + * + * Entering a choice pays the contest fund, so it runs in [choiceEntry], which the screen's + * back-stack entry holds, and Back is held while it runs. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun MultipleChoiceProposalDetailScreen( + proposalId: String, + navController: NavHostController, + choiceEntry: MultipleChoiceDocumentCreateViewModel = viewModel(), +) { + val appState = LocalAppState.current + val container = LocalAppContainer.current + val sdk by appState.sdk.collectAsStateWithLifecycle() + val network by appState.currentNetwork.collectAsStateWithLifecycle() + val walletIdentities by container.database.identityDao() + .observeWalletOwnedByNetwork(network.ffiValue) + .collectAsStateWithLifecycle(initialValue = emptyList()) + + var proposal by remember { mutableStateOf(null) } + var vote by remember { mutableStateOf(null) } + var keptChoice by remember { mutableStateOf(null) } + var proposalError by remember { mutableStateOf(null) } + var voteError by remember { mutableStateOf(null) } + var isLoading by remember { mutableStateOf(false) } + var refreshTick by remember { mutableStateOf(0) } + + var showVote by remember { mutableStateOf(false) } + var showEnterChoice by remember { mutableStateOf(false) } + var showEdit by remember { mutableStateOf(false) } + var actionMessage by remember { mutableStateOf(null) } + + LaunchedEffect(sdk, proposalId, refreshTick) { + val currentSdk = sdk ?: run { + proposalError = "SDK not initialized" + return@LaunchedEffect + } + isLoading = true + proposalError = null + voteError = null + try { + proposal = readOrNull({ proposalError = "Loading the proposal failed: ${it.message}" }) { + currentSdk.multipleChoiceProposals.fetch(proposalId) + } + if (proposal == null && proposalError == null) { + proposalError = "Platform has no multiple choice proposal $proposalId." + } + val read = readOrNull({ voteError = "Loading the vote failed: ${it.message}" }) { + currentSdk.multipleChoiceProposals.vote(proposalId) + } + vote = read + // The choices not kept are gone once the vote ended; the kept one is a read of + // its own. + keptChoice = if (read?.result != null) { + readOrNull({ voteError = "Loading the kept choice failed: ${it.message}" }) { + currentSdk.multipleChoiceProposals.keptChoice(proposalId) + } + } else { + null + } + } finally { + isLoading = false + } + } + + // A choice Platform confirmed, also when its dialog left composition meanwhile. + val enteredChoiceId = choiceEntry.createdId + LaunchedEffect(enteredChoiceId) { + if (enteredChoiceId != null) { + showEnterChoice = false + actionMessage = "Choice entered: ${truncateMiddle(enteredChoiceId, 12, 8)}" + choiceEntry.acknowledge() + refreshTick++ + } + } + + // The local wallet identity that filed the proposal, which may edit it. + val owner = remember(proposal, walletIdentities) { + proposal?.let { shown -> + walletIdentities.firstOrNull { Base58.encode(it.identityId) == shown.ownerId } + } + } + + val isEnteringChoice = choiceEntry.isSubmitting + // System Back would pop the entry and clear the paid choice entry with it; the toolbar + // Back is disabled for the same reason. + BackHandler(enabled = isEnteringChoice) {} + + Scaffold( + topBar = { + TopAppBar( + title = { Text("Multiple Choice Proposal") }, + navigationIcon = { + IconButton( + onClick = { navController.popBackStack() }, + enabled = !isEnteringChoice, + ) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") + } + }, + actions = { + IconButton( + onClick = { refreshTick++ }, + enabled = !isLoading, + modifier = Modifier.testTag("multipleChoiceProposal.refresh"), + ) { + Icon(Icons.Default.Refresh, contentDescription = "Refresh") + } + }, + ) + }, + ) { padding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(padding) + .verticalScroll(rememberScrollState()) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + proposalError?.let { message -> + Text( + message, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.testTag("multipleChoiceProposal.error"), + ) + } + + val shown = proposal + if (shown != null) { + MultipleChoiceProposalSection(shown, isOwnerLocal = owner != null) + } + + MultipleChoiceVoteSection( + vote = vote, + keptChoice = keptChoice, + isLoading = isLoading, + error = voteError, + ) + + FormSection(title = "Actions") { + actionMessage?.let { message -> + Text( + message, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.testTag("multipleChoiceProposal.actionResult"), + ) + } + SubmitButton( + text = "Vote as a Masternode…", + isLoading = false, + // Platform takes votes only while the vote runs + enabled = sdk != null && shown != null && vote?.result == null, + modifier = Modifier.fillMaxWidth().testTag("multipleChoiceProposal.vote"), + ) { + actionMessage = null + showVote = true + } + Text( + "Only masternodes vote, with the voting key of a pro_tx_hash: for one " + + "choice, for none of the choices, or abstaining. A regular wallet " + + "has no voting key, so Platform refuses its vote.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + if (walletIdentities.isNotEmpty()) { + SubmitButton( + text = if (isEnteringChoice) "Entering a Choice…" else "Enter a Choice…", + isLoading = isEnteringChoice, + enabled = sdk != null && shown != null && vote?.result == null, + modifier = Modifier + .fillMaxWidth() + .testTag("multipleChoiceProposal.enterChoice"), + ) { + actionMessage = null + choiceEntry.error = null + showEnterChoice = true + } + // Shown here when the dialog that started the entry is gone (a rotation). + if (!showEnterChoice) { + choiceEntry.error?.let { message -> + Text( + message, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.testTag("multipleChoiceProposal.enterChoiceError"), + ) + } + } + Text( + "A choice pays the contest fund on top of the fees and is never " + + "edited. For this proposal, " + + (shown?.whoEntersChoices() ?: "Platform says who enters choices") + ".", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (owner != null) { + SubmitButton( + text = "Edit…", + isLoading = false, + enabled = sdk != null && shown != null, + modifier = Modifier.fillMaxWidth().testTag("multipleChoiceProposal.edit"), + ) { + actionMessage = null + showEdit = true + } + Text( + "Platform accepts an edit of the title, description document and " + + "url for a short time after the proposal is created, and " + + "refuses it afterwards. Whether the proposal is open never " + + "changes.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } + + val shown = proposal + if (showVote && shown != null) { + MultipleChoiceVoteDialog( + proposal = shown, + vote = vote, + onDismiss = { showVote = false }, + onVoted = { message -> + showVote = false + actionMessage = message + refreshTick++ // pull fresh tallies after an accepted vote + }, + ) + } + if (showEnterChoice && shown != null && walletIdentities.isNotEmpty()) { + EnterChoiceDialog( + proposal = shown, + identities = walletIdentities, + proposer = owner, + entry = choiceEntry, + onDismiss = { showEnterChoice = false }, + ) + } + val editor = owner + if (showEdit && shown != null && editor != null) { + EditMultipleChoiceProposalDialog( + proposal = shown, + owner = editor, + onDismiss = { showEdit = false }, + onEdited = { message -> + showEdit = false + actionMessage = message + refreshTick++ + }, + ) + } +} + +@Composable +private fun MultipleChoiceProposalSection(proposal: MultipleChoiceProposal, isOwnerLocal: Boolean) { + FormSection(title = "Proposal") { + Text( + proposal.title, + style = MaterialTheme.typography.titleMedium, + modifier = Modifier.testTag("multipleChoiceProposal.title"), + ) + proposal.url?.let { LabeledContent("URL", it) } + proposal.descriptionDocument?.let { described -> + LabeledContent( + "Description document", + truncateMiddle(described.id, 12, 8), + modifier = Modifier.testTag("multipleChoiceProposal.descriptionDocument"), + ) + LabeledContent("In contract", truncateMiddle(described.contractId, 12, 8)) + LabeledContent("Of type", described.documentType) + } + LabeledContent( + "Choices", + proposal.whoEntersChoices(), + modifier = Modifier.testTag("multipleChoiceProposal.open"), + ) + LabeledContent("ID", truncateMiddle(proposal.id, 12, 8)) + LabeledContent( + "Proposer", + truncateMiddle(proposal.ownerId, 10, 6) + if (isOwnerLocal) " (local)" else "", + ) + proposal.revision?.let { LabeledContent("Revision", "$it") } + proposal.createdAtMs?.let { LabeledContent("Created", formatDate(Date(it))) } + proposal.updatedAtMs?.let { LabeledContent("Updated", formatDate(Date(it))) } + } +} + +@Composable +private fun MultipleChoiceVoteSection( + vote: MultipleChoiceProposalVote?, + keptChoice: ProposalChoice?, + isLoading: Boolean, + error: String?, +) { + FormSection(title = "Vote") { + error?.let { message -> + Text( + message, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.testTag("multipleChoiceProposal.voteError"), + ) + } + when { + vote != null -> MultipleChoiceVoteRows(vote, keptChoice) + isLoading -> LabeledContent("Status", "Loading…") + } + Text( + "A vote names a choice by its id. The choice with the most votes is kept as an " + + "ordinary document and the others are gone, unless the votes for none of " + + "the choices outnumber it. Abstaining is recorded but plays no part in " + + "the result.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +@Composable +private fun MultipleChoiceVoteRows(vote: MultipleChoiceProposalVote, keptChoice: ProposalChoice?) { + val result = vote.result + LabeledContent( + "Status", + when { + result != null -> result.outcome.label() + vote.choices.isEmpty() -> "No choice entered" + else -> "Voting open" + }, + modifier = Modifier.testTag("multipleChoiceProposal.voteStatus"), + ) + if (result != null) { + result.keptChoiceId?.let { keptId -> + LabeledContent( + "Kept choice", + keptChoice?.title ?: truncateMiddle(keptId, 12, 8), + modifier = Modifier.testTag("multipleChoiceProposal.keptChoice"), + ) + keptChoice?.description?.let { Text(it, style = MaterialTheme.typography.bodyMedium) } + LabeledContent("Kept choice ID", truncateMiddle(keptId, 12, 8)) + } + LabeledContent("Closed at block", "${result.finalizationBlock.height}") + } + vote.choices.forEach { entry -> + val kept = result?.keptChoiceId == entry.id + // Once the vote ended the choices are gone from the vote; the kept one is known. + val title = entry.choice?.title + ?: keptChoice?.takeIf { kept }?.title + ?: truncateMiddle(entry.id, 12, 8) + LabeledContent( + title + if (kept) " (kept)" else "", + entry.voteTally.tally(), + modifier = Modifier.testTag("multipleChoiceProposal.choice.${entry.id}"), + ) + entry.choice?.description?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + entry.choice?.let { + Text( + "${truncateMiddle(entry.id, 12, 8)} · entered by ${truncateMiddle(it.ownerId, 10, 6)}", + style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + LabeledContent( + "None of the choices", + vote.noneOfTheChoicesVoteTally.tally(), + modifier = Modifier.testTag("multipleChoiceProposal.noneOfTheChoices"), + ) + LabeledContent( + "Abstain", + vote.abstainVoteTally.tally(), + modifier = Modifier.testTag("multipleChoiceProposal.abstain"), + ) +} + +/** A tally as text; Platform does not report every tally. */ +private fun Long?.tally(): String = this?.let { "$it" } ?: "not reported" + +/** How a finished vote ended, as the status row says it. */ +private fun MultipleChoiceProposalVote.Outcome.label(): String = when (this) { + MultipleChoiceProposalVote.Outcome.KEPT_CHOICE -> "Ended: a choice was kept" + MultipleChoiceProposalVote.Outcome.NONE_OF_THE_CHOICES -> "Ended: none of the choices was kept" + MultipleChoiceProposalVote.Outcome.NO_WINNER -> "Ended without a winner" +} + +/** Display name of a vote answer; a choice shows its title when the vote still holds it. */ +private fun MultipleChoiceVoteChoice.label(vote: MultipleChoiceProposalVote?): String = when (this) { + is MultipleChoiceVoteChoice.Choice -> { + val title = vote?.choices?.firstOrNull { it.id == choiceId }?.choice?.title + val id = truncateMiddle(choiceId, 8, 6) + if (title != null) "$title ($id)" else id + } + MultipleChoiceVoteChoice.NoneOfTheChoices -> "None of the choices" + MultipleChoiceVoteChoice.Abstain -> "Abstain" +} + +/** + * Picks an answer and takes masternode credentials: port of + * `MultipleChoiceProposalVoteSheet` in `MultipleChoiceProposalDetailView.swift`. Votes + * through `Sdk.multipleChoiceProposals.castVote`, and reads the masternode's current answer + * through `Sdk.multipleChoiceProposals.masternodeVote`. The answers offered are the choices + * the vote holds, each by its document id, none of the choices, and abstaining. + * + * The voting private key is masked as it is typed, and screen capture is blocked while the + * dialog is open (see [HoldSecureWindow]). The dialog cannot be dismissed, by Back or a tap + * outside, while a call runs. + */ +@Composable +private fun MultipleChoiceVoteDialog( + proposal: MultipleChoiceProposal, + vote: MultipleChoiceProposalVote?, + onDismiss: () -> Unit, + onVoted: (String) -> Unit, +) { + val appState = LocalAppState.current + val scope = rememberCoroutineScope() + val sdk by appState.sdk.collectAsStateWithLifecycle() + HoldSecureWindow() + + val answers: List = remember(vote) { + vote?.choices.orEmpty().map { MultipleChoiceVoteChoice.Choice(it.id) } + + listOf(MultipleChoiceVoteChoice.NoneOfTheChoices, MultipleChoiceVoteChoice.Abstain) + } + var choice by remember { mutableStateOf(answers.first()) } + var proTxHashHex by remember { mutableStateOf("") } + var votingKeyHex by remember { mutableStateOf("") } + var isBusy by remember { mutableStateOf(false) } + var message by remember { mutableStateOf(null) } + var messageIsError by remember { mutableStateOf(false) } + + AlertDialog( + onDismissRequest = { if (!isBusy) onDismiss() }, + properties = secureDialogProperties(dismissible = !isBusy), + title = { Text("Vote · ${truncateMiddle(proposal.title, 20, 8)}") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + AccessiblePicker( + label = "Answer", + options = answers, + selected = choice, + optionLabel = { it.label(vote) }, + testTag = "multipleChoiceProposalVote.choice", + enabled = !isBusy, + onSelected = { choice = it }, + ) + OutlinedTextField( + value = proTxHashHex, + onValueChange = { proTxHashHex = it }, + label = { Text("pro_tx_hash (64 hex chars, wire order)") }, + singleLine = true, + enabled = !isBusy, + textStyle = MaterialTheme.typography.bodySmall + .copy(fontFamily = FontFamily.Monospace), + modifier = Modifier.fillMaxWidth().testTag("multipleChoiceProposalVote.proTxHash"), + ) + OutlinedTextField( + value = votingKeyHex, + onValueChange = { votingKeyHex = it }, + label = { Text("voting private key (64 hex chars)") }, + singleLine = true, + enabled = !isBusy, + textStyle = MaterialTheme.typography.bodySmall + .copy(fontFamily = FontFamily.Monospace), + // KeyboardType.Password only configures the keyboard; the + // transformation masks what the field shows. + visualTransformation = PasswordVisualTransformation(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), + modifier = Modifier.fillMaxWidth().testTag("multipleChoiceProposalVote.votingKey"), + ) + Text( + "The pro_tx_hash goes in wire order, the reverse of the hex Core " + + "displays. The voting public key and signer are derived from the " + + "private key on the Rust side; the key bytes are not stored.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + TextButton( + enabled = !isBusy && proTxHashHex.isNotBlank(), + onClick = { + val currentSdk = sdk ?: return@TextButton + val proTxHash = decode32ByteHex(proTxHashHex) + if (proTxHash == null) { + message = "pro_tx_hash must be 32 bytes (64 hex characters)." + messageIsError = true + return@TextButton + } + isBusy = true + scope.launch { + try { + val answer = currentSdk.multipleChoiceProposals + .masternodeVote(proTxHash, proposal.id) + message = answer?.let { + "This masternode answered ${it.label(vote)}." + } ?: "This masternode has no answer in the running vote." + messageIsError = false + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + message = "Reading the answer failed: ${e.message}" + messageIsError = true + } finally { + isBusy = false + } + } + }, + modifier = Modifier.testTag("multipleChoiceProposalVote.lookUp"), + ) { Text("Read This Masternode's Answer") } + message?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = if (messageIsError) { + MaterialTheme.colorScheme.error + } else { + MaterialTheme.colorScheme.primary + }, + modifier = Modifier.testTag("multipleChoiceProposalVote.result"), + ) + } + } + }, + confirmButton = { + TextButton( + enabled = !isBusy && proTxHashHex.isNotBlank() && votingKeyHex.isNotBlank(), + onClick = { + val currentSdk = sdk ?: return@TextButton + val proTxHash = decode32ByteHex(proTxHashHex) + if (proTxHash == null) { + message = "pro_tx_hash must be 32 bytes (64 hex characters)." + messageIsError = true + return@TextButton + } + val votingKey = decode32ByteHex(votingKeyHex) + if (votingKey == null) { + message = "Voting private key must be 32 bytes (64 hex characters)." + messageIsError = true + return@TextButton + } + isBusy = true + scope.launch { + try { + currentSdk.multipleChoiceProposals.castVote( + proposalId = proposal.id, + choice = choice, + proTxHash = proTxHash, + votingPrivateKey = votingKey, + ) + onVoted("Vote accepted by Platform.") + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + message = "Vote rejected: ${e.message}" + messageIsError = true + } finally { + votingKey.fill(0) + isBusy = false + } + } + }, + modifier = Modifier.testTag("multipleChoiceProposalVote.submit"), + ) { Text(if (isBusy) "Broadcasting…" else "Submit Vote") } + }, + dismissButton = { + TextButton(enabled = !isBusy, onClick = onDismiss) { Text("Cancel") } + }, + ) +} + +/** + * Enters a choice for a proposal as a local wallet identity: port of + * `EnterProposalChoiceView` (`MultipleChoiceProposalFormViews.swift`). Submits through + * `PlatformWalletManager.multipleChoiceProposals.enterChoice`, one platform wallet call that + * builds the choice, states the contest fund, signs with a key it picks and waits for + * Platform to confirm. The fund is read through `Sdk.multipleChoiceProposals.choiceFundToJoin` + * and shown before the submit. + * + * The entry runs in [entry], held by the detail screen's back-stack entry, so a dialog that + * leaves composition (a rotation) does not cancel a paid choice; the detail screen reports + * its outcome. The dialog cannot be dismissed while the entry runs. Who may enter a choice + * is Platform's to say: any local wallet identity can be picked. + */ +@Composable +private fun EnterChoiceDialog( + proposal: MultipleChoiceProposal, + identities: List, + proposer: IdentityEntity?, + entry: MultipleChoiceDocumentCreateViewModel, + onDismiss: () -> Unit, +) { + val appState = LocalAppState.current + val container = LocalAppContainer.current + val sdk by appState.sdk.collectAsStateWithLifecycle() + val manager by container.walletManagerStore.activeManager.collectAsStateWithLifecycle() + + var owner by remember { mutableStateOf(proposer ?: identities.first()) } + var title by remember { mutableStateOf("") } + var description by remember { mutableStateOf("") } + val isSubmitting = entry.isSubmitting + + // The fund a choice entered now pays, read rather than assumed: it rises as the vote + // fills up. + var fund by remember { mutableStateOf(null) } + var fundError by remember { mutableStateOf(null) } + LaunchedEffect(sdk, proposal.id) { + fund = null + fundError = null + val currentSdk = sdk ?: return@LaunchedEffect + try { + fund = currentSdk.multipleChoiceProposals.choiceFundToJoin(proposal.id) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + fundError = "Reading the contest fund failed: ${e.message}" + } + } + + AlertDialog( + onDismissRequest = { if (!isSubmitting) onDismiss() }, + properties = DialogProperties( + dismissOnBackPress = !isSubmitting, + dismissOnClickOutside = !isSubmitting, + ), + title = { Text("Enter a Choice") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + AccessiblePicker( + label = "Entered by", + options = identities, + selected = owner, + optionLabel = { it.displayLabel() }, + testTag = "enterProposalChoice.ownerPicker", + enabled = !isSubmitting, + onSelected = { owner = it }, + ) + OutlinedTextField( + value = title, + onValueChange = { title = it }, + label = { Text("Title: the answer, in one line") }, + singleLine = true, + enabled = !isSubmitting, + modifier = Modifier.fillMaxWidth().testTag("enterProposalChoice.title"), + ) + OutlinedTextField( + value = description, + onValueChange = { description = it }, + label = { Text("Description: what voting for it means (optional)") }, + minLines = 3, + enabled = !isSubmitting, + modifier = Modifier.fillMaxWidth().testTag("enterProposalChoice.description"), + ) + LabeledContent( + "Contest fund", + fund?.let { formatCredits(it) } + ?: if (fundError == null) "Loading…" else "Unavailable", + modifier = Modifier.testTag("enterProposalChoice.fund"), + ) + Text( + "The choice pays the contest fund on top of the fees and is never " + + "edited. For this proposal, ${proposal.whoEntersChoices()}.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + (entry.error ?: fundError)?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.testTag("enterProposalChoice.error"), + ) + } + } + }, + confirmButton = { + TextButton( + enabled = !isSubmitting && manager != null, + onClick = { + val mgr = manager ?: return@TextButton + val wallet = owner.walletId?.toHex()?.let { mgr.wallets.value[it] } + if (wallet == null) { + entry.error = "The identity's wallet is not loaded in the wallet manager." + return@TextButton + } + val proposalIdBytes = Base58.decodeIdentifier(proposal.id) + if (proposalIdBytes == null) { + entry.error = "The proposal id is not a 32-byte base58 identifier." + return@TextButton + } + val enteredBy = owner.identityId + val params = ProposalChoiceParams( + title = title, + description = description.ifBlank { null }, + ) + entry.submit { + mgr.multipleChoiceProposals.enterChoice( + walletHandle = wallet.handle, + ownerId = enteredBy, + proposalId = proposalIdBytes, + params = params, + signerHandle = mgr.signerHandle, + ).id + } + }, + modifier = Modifier.testTag("enterProposalChoice.submitButton"), + ) { Text(if (isSubmitting) "Broadcasting…" else "Enter / Broadcast") } + }, + dismissButton = { + TextButton(enabled = !isSubmitting, onClick = onDismiss) { Text("Cancel") } + }, + ) +} + +/** + * Gives a proposal a local identity filed a new title, url or description document: port + * of `EditMultipleChoiceProposalView` (`MultipleChoiceProposalFormViews.swift`). Submits + * through `PlatformWalletManager.multipleChoiceProposals.edit`, one platform wallet call + * that reads the stored proposal, applies the edit (rs-sdk refuses one that changes + * nothing), signs with a key it picks and waits for Platform to confirm. + * + * The dialog cannot be dismissed (Back or a tap outside) while the edit runs, so the + * replace running in its scope is not cancelled with it. Should the dialog still leave + * composition mid-edit (a rotation), the detail screen reads the proposal again, and an edit + * repeating one that landed changes nothing, which rs-sdk refuses before anything is + * broadcast. + */ +@Composable +private fun EditMultipleChoiceProposalDialog( + proposal: MultipleChoiceProposal, + owner: IdentityEntity, + onDismiss: () -> Unit, + onEdited: (String) -> Unit, +) { + val container = LocalAppContainer.current + val scope = rememberCoroutineScope() + val manager by container.walletManagerStore.activeManager.collectAsStateWithLifecycle() + + val described = proposal.descriptionDocument + var title by remember { mutableStateOf(proposal.title) } + var url by remember { mutableStateOf(proposal.url.orEmpty()) } + var describedId by remember { mutableStateOf(described?.id.orEmpty()) } + var describedContractId by remember { mutableStateOf(described?.contractId.orEmpty()) } + var describedType by remember { mutableStateOf(described?.documentType.orEmpty()) } + var isSubmitting by remember { mutableStateOf(false) } + var error by remember { mutableStateOf(null) } + + AlertDialog( + onDismissRequest = { if (!isSubmitting) onDismiss() }, + properties = DialogProperties( + dismissOnBackPress = !isSubmitting, + dismissOnClickOutside = !isSubmitting, + ), + title = { Text("Edit Proposal") }, + text = { + Column( + verticalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.verticalScroll(rememberScrollState()), + ) { + OutlinedTextField( + value = title, + onValueChange = { title = it }, + label = { Text("Title") }, + singleLine = true, + enabled = !isSubmitting, + modifier = Modifier.fillMaxWidth().testTag("editMultipleChoiceProposal.title"), + ) + OutlinedTextField( + value = url, + onValueChange = { url = it }, + label = { Text("URL (empty for none)") }, + singleLine = true, + enabled = !isSubmitting, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri), + modifier = Modifier.fillMaxWidth().testTag("editMultipleChoiceProposal.url"), + ) + OutlinedTextField( + value = describedId, + onValueChange = { describedId = it }, + label = { Text("Description document ID (empty for none)") }, + singleLine = true, + enabled = !isSubmitting, + modifier = Modifier + .fillMaxWidth() + .testTag("editMultipleChoiceProposal.descriptionDocumentId"), + ) + OutlinedTextField( + value = describedContractId, + onValueChange = { describedContractId = it }, + label = { Text("Its contract ID") }, + singleLine = true, + enabled = !isSubmitting, + modifier = Modifier + .fillMaxWidth() + .testTag("editMultipleChoiceProposal.descriptionDocumentContractId"), + ) + OutlinedTextField( + value = describedType, + onValueChange = { describedType = it }, + label = { Text("Its document type") }, + singleLine = true, + enabled = !isSubmitting, + modifier = Modifier + .fillMaxWidth() + .testTag("editMultipleChoiceProposal.descriptionDocumentType"), + ) + Text( + "Only the title, url and description document can change, and only " + + "for a short time after the proposal was created. Platform " + + "refuses an edit that leaves the proposal with neither a " + + "description document nor a url.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + error?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.testTag("editMultipleChoiceProposal.error"), + ) + } + } + }, + confirmButton = { + TextButton( + enabled = !isSubmitting && manager != null, + onClick = { + val mgr = manager ?: return@TextButton + val wallet = owner.walletId?.toHex()?.let { mgr.wallets.value[it] } + if (wallet == null) { + error = "The proposer's wallet is not loaded in the wallet manager." + return@TextButton + } + val proposalIdBytes = Base58.decodeIdentifier(proposal.id) + if (proposalIdBytes == null) { + error = "The proposal id is not a 32-byte base58 identifier." + return@TextButton + } + val edit = when ( + val built = multipleChoiceProposalEdit( + proposal = proposal, + title = title, + url = url, + describedId = describedId, + describedContractId = describedContractId, + describedType = describedType, + ) + ) { + is BuiltMultipleChoiceEdit.Unreadable -> { + error = built.message + return@TextButton + } + is BuiltMultipleChoiceEdit.Edit -> built.edit + } + isSubmitting = true + error = null + scope.launch { + try { + mgr.multipleChoiceProposals.edit( + walletHandle = wallet.handle, + ownerId = owner.identityId, + proposalId = proposalIdBytes, + edit = edit, + signerHandle = mgr.signerHandle, + ) + onEdited("Edit accepted by Platform.") + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + error = e.message ?: "Edit failed" + } finally { + isSubmitting = false + } + } + }, + modifier = Modifier.testTag("editMultipleChoiceProposal.submitButton"), + ) { Text(if (isSubmitting) "Broadcasting…" else "Replace / Broadcast") } + }, + dismissButton = { + TextButton(enabled = !isSubmitting, onClick = onDismiss) { Text("Cancel") } + }, + ) +} + +/** The edit an edit form's fields make, or why a field could not be read. */ +internal sealed interface BuiltMultipleChoiceEdit { + data class Edit(val edit: MultipleChoiceProposalEdit) : BuiltMultipleChoiceEdit + + /** A description document id field does not hold the 32 bytes the wallet call takes. */ + data class Unreadable(val message: String) : BuiltMultipleChoiceEdit +} + +/** + * The edit that turns [proposal], as the form was opened with it, into what the form's + * fields now hold. Only the fields the user changed are sent: an untouched field must not + * write back the value the form was opened with over a newer edit by another client. An + * emptied url removes the url, and three emptied description document fields remove the + * description document. Whether the result is an acceptable proposal is not looked at here. + */ +internal fun multipleChoiceProposalEdit( + proposal: MultipleChoiceProposal, + title: String, + url: String, + describedId: String, + describedContractId: String, + describedType: String, +): BuiltMultipleChoiceEdit { + val trimmedUrl = url.trim() + val urlChange = when { + trimmedUrl == proposal.url.orEmpty() -> MultipleChoiceProposalEdit.Change.Keep + trimmedUrl.isEmpty() -> MultipleChoiceProposalEdit.Change.Remove + else -> MultipleChoiceProposalEdit.Change.Set(trimmedUrl) + } + val described = proposal.descriptionDocument + val describedUntouched = describedId.trim() == described?.id.orEmpty() && + describedContractId.trim() == described?.contractId.orEmpty() && + describedType.trim() == described?.documentType.orEmpty() + val describedChange: MultipleChoiceProposalEdit.Change = + if (describedUntouched) { + MultipleChoiceProposalEdit.Change.Keep + } else { + when (val parsed = parseDescriptionDocument(describedId, describedContractId, describedType)) { + is ParsedDescriptionDocument.Unreadable -> + return BuiltMultipleChoiceEdit.Unreadable(parsed.message) + ParsedDescriptionDocument.None -> MultipleChoiceProposalEdit.Change.Remove + is ParsedDescriptionDocument.Document -> + MultipleChoiceProposalEdit.Change.Set(parsed.document) + } + } + return BuiltMultipleChoiceEdit.Edit( + MultipleChoiceProposalEdit( + title = title.takeIf { it != proposal.title }, + descriptionDocument = describedChange, + url = urlChange, + ), + ) +} diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/MultipleChoiceProposalsScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/MultipleChoiceProposalsScreen.kt new file mode 100644 index 00000000000..124a857da84 --- /dev/null +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/MultipleChoiceProposalsScreen.kt @@ -0,0 +1,703 @@ +package org.dashfoundation.example.ui.identity + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.compose.viewModel +import androidx.navigation.NavHostController +import java.util.Date +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.launch +import org.dashfoundation.dashsdk.Sdk +import org.dashfoundation.dashsdk.persistence.entities.IdentityEntity +import org.dashfoundation.dashsdk.voting.DescriptionDocumentParams +import org.dashfoundation.dashsdk.voting.MultipleChoiceProposal +import org.dashfoundation.dashsdk.voting.MultipleChoiceProposalParams +import org.dashfoundation.example.di.LocalAppContainer +import org.dashfoundation.example.di.LocalAppState +import org.dashfoundation.example.navigation.CreateMultipleChoiceProposal +import org.dashfoundation.example.navigation.MultipleChoiceProposalDetail +import org.dashfoundation.example.ui.components.AccessiblePicker +import org.dashfoundation.example.ui.components.ErrorAlertDialog +import org.dashfoundation.example.ui.components.FormSection +import org.dashfoundation.example.ui.components.LabeledContent +import org.dashfoundation.example.ui.components.SubmitButton +import org.dashfoundation.example.ui.tokens.displayLabel +import org.dashfoundation.example.util.Base58 +import org.dashfoundation.example.util.formatCredits +import org.dashfoundation.example.util.formatDate +import org.dashfoundation.example.util.toHex +import org.dashfoundation.example.util.truncateMiddle + +/** The two ways the list reads proposals, each one Platform listing (← `Listing`). */ +private enum class MultipleChoiceListing(val label: String, val footer: String) { + MINE("Mine", "Proposals the selected identity filed, in the order it filed them."), + NEWEST("Newest", "Every multiple choice proposal, newest first."), +} + +/** Proposals per page; a page shorter than this is the last. */ +private const val MULTIPLE_CHOICE_PAGE_SIZE = 20 + +/** + * Multiple choice proposals (protocol version 15): port of + * `MultipleChoiceProposalsView.swift`, beside the yes/no [DecisionProposalsScreen]. + * + * Lists proposals two ways, a page at a time, through `Sdk.multipleChoiceProposals`: the + * ones a local identity filed (`listByOwner`) and the newest (`listByCreatedAt`). Rows drill + * into [MultipleChoiceProposalDetailScreen]; the + action opens + * [CreateMultipleChoiceProposalScreen]. Nothing here decides what a proposal is. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun MultipleChoiceProposalsScreen(navController: NavHostController) { + val appState = LocalAppState.current + val container = LocalAppContainer.current + val scope = rememberCoroutineScope() + val sdk by appState.sdk.collectAsStateWithLifecycle() + val network by appState.currentNetwork.collectAsStateWithLifecycle() + val identities by container.database.identityDao() + .observeByNetwork(network.ffiValue) + .collectAsStateWithLifecycle(initialValue = emptyList()) + + var listing by remember { mutableStateOf(MultipleChoiceListing.NEWEST) } + var owner by remember { mutableStateOf(null) } + var proposals by remember { mutableStateOf>(emptyList()) } + var hasMore by remember { mutableStateOf(false) } + var isLoading by remember { mutableStateOf(false) } + var errorMessage by remember { mutableStateOf(null) } + var refreshTick by remember { mutableStateOf(0) } + // Bumped on every fresh load so a late "load more" page of a previous + // listing is dropped instead of mixed in. + var loadGeneration by remember { mutableStateOf(0) } + + // Start "Mine" on the first local identity rather than empty. + LaunchedEffect(listing, identities) { + if (listing == MultipleChoiceListing.MINE && owner == null) owner = identities.firstOrNull() + } + + val ownerBase58 = owner?.let { Base58.encode(it.identityId) } + + LaunchedEffect(sdk, listing, ownerBase58, refreshTick) { + loadGeneration++ + proposals = emptyList() + hasMore = false + errorMessage = null + val currentSdk = sdk ?: run { + errorMessage = "SDK not initialized" + return@LaunchedEffect + } + if (listing == MultipleChoiceListing.MINE && ownerBase58 == null) return@LaunchedEffect + isLoading = true + try { + val page = loadMultipleChoicePage(currentSdk, listing, ownerBase58, startAfter = null) + proposals = page + hasMore = page.size == MULTIPLE_CHOICE_PAGE_SIZE + } catch (e: Exception) { + errorMessage = "Loading failed: ${e.message}" + } finally { + isLoading = false + } + } + + Scaffold( + topBar = { + TopAppBar( + title = { Text("Multiple Choice Proposals") }, + navigationIcon = { + IconButton(onClick = { navController.popBackStack() }) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") + } + }, + actions = { + IconButton( + onClick = { refreshTick++ }, + enabled = !isLoading, + modifier = Modifier.testTag("multipleChoiceProposals.refresh"), + ) { + Icon(Icons.Default.Refresh, contentDescription = "Refresh") + } + IconButton( + onClick = { navController.navigate(CreateMultipleChoiceProposal) }, + enabled = sdk != null, + modifier = Modifier.testTag("multipleChoiceProposals.create"), + ) { + Icon(Icons.Default.Add, contentDescription = "New multiple choice proposal") + } + }, + ) + }, + ) { padding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(padding) + .verticalScroll(rememberScrollState()) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + FormSection(title = "Listing") { + AccessiblePicker( + label = "Listing", + options = MultipleChoiceListing.entries, + selected = listing, + optionLabel = { it.label }, + testTag = "multipleChoiceProposals.listing", + onSelected = { listing = it }, + ) + if (listing == MultipleChoiceListing.MINE) { + if (identities.isEmpty()) { + Text( + "No local identity on this network.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } else { + AccessiblePicker( + label = "Identity", + options = identities, + selected = owner ?: identities.first(), + optionLabel = { it.displayLabel() }, + testTag = "multipleChoiceProposals.ownerPicker", + onSelected = { owner = it }, + ) + } + } + Text( + listing.footer, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + FormSection(title = "Proposals") { + errorMessage?.let { message -> + Text( + message, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.testTag("multipleChoiceProposals.error"), + ) + } + when { + isLoading && proposals.isEmpty() -> CircularProgressIndicator( + modifier = Modifier.padding(8.dp), + ) + listing == MultipleChoiceListing.MINE && ownerBase58 == null -> Text( + "Select an identity to list its proposals.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + proposals.isEmpty() && errorMessage == null -> Text( + "No proposals", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + proposals.forEach { proposal -> + MultipleChoiceProposalRow(proposal) { + navController.navigate(MultipleChoiceProposalDetail(proposal.id)) + } + } + if (hasMore) { + OutlinedButton( + onClick = { + val currentSdk = sdk ?: return@OutlinedButton + val last = proposals.lastOrNull() ?: return@OutlinedButton + val generation = loadGeneration + isLoading = true + scope.launch { + try { + val page = loadMultipleChoicePage( + currentSdk, + listing, + ownerBase58, + startAfter = last.id, + ) + if (generation == loadGeneration) { + proposals = proposals + page + hasMore = page.size == MULTIPLE_CHOICE_PAGE_SIZE + } + } catch (e: Exception) { + if (generation == loadGeneration) { + errorMessage = "Loading failed: ${e.message}" + } + } finally { + isLoading = false + } + } + }, + enabled = !isLoading, + modifier = Modifier + .fillMaxWidth() + .testTag("multipleChoiceProposals.loadMore"), + ) { + Text("Load More") + } + } + } + } + } +} + +/** One page of [listing] after [startAfter] (null for the first page). */ +private suspend fun loadMultipleChoicePage( + sdk: Sdk, + listing: MultipleChoiceListing, + ownerBase58: String?, + startAfter: String?, +): List = when (listing) { + MultipleChoiceListing.MINE -> sdk.multipleChoiceProposals.listByOwner( + ownerId = requireNotNull(ownerBase58) { "no identity selected" }, + limit = MULTIPLE_CHOICE_PAGE_SIZE, + startAfter = startAfter, + ) + MultipleChoiceListing.NEWEST -> sdk.multipleChoiceProposals.listByCreatedAt( + limit = MULTIPLE_CHOICE_PAGE_SIZE, + startAfter = startAfter, + ) +} + +/** One proposal in a listing (← `MultipleChoiceProposalRow`). */ +@Composable +private fun MultipleChoiceProposalRow(proposal: MultipleChoiceProposal, onClick: () -> Unit) { + ListItem( + headlineContent = { Text(proposal.title, maxLines = 2) }, + supportingContent = { + Column { + Text( + listOfNotNull( + proposal.createdAtMs?.let { "Created ${formatDate(Date(it))}" }, + proposal.whoEntersChoices(), + ).joinToString(" · "), + style = MaterialTheme.typography.bodySmall, + ) + Text( + truncateMiddle(proposal.id, 12, 8), + style = MaterialTheme.typography.labelSmall + .copy(fontFamily = FontFamily.Monospace), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + }, + modifier = Modifier + .clickable(onClick = onClick) + .testTag("multipleChoiceProposals.row.${proposal.id}"), + ) +} + +/** Who may enter choices for this proposal, as the screens say it. */ +internal fun MultipleChoiceProposal.whoEntersChoices(): String = + if (open) "anyone enters choices" else "only its owner enters choices" + +/** + * A paid write of the multiple choice proposal screens that creates a document (the + * proposal on [CreateMultipleChoiceProposalScreen], a choice on + * [MultipleChoiceProposalDetailScreen]), held by the screen's back-stack entry rather than + * by its composition, as [CreateDecisionProposalViewModel] holds the yes/no create. + * + * Creating a proposal pays the processing fee and entering a choice pays the contest fund. + * A coroutine of the composition is cancelled whenever the screen leaves composition (a + * rotation, a switch to another bottom tab), which would drop a write Platform already + * accepted and invite a second, paid retry. The back-stack entry outlives all of those, so + * the write runs to its end and the screen shows the outcome when it composes again. Back, + * which would clear the entry, is held by the screens while the write runs. + */ +class MultipleChoiceDocumentCreateViewModel : ViewModel() { + + /** Whether a write is running. */ + var isSubmitting by mutableStateOf(false) + private set + + /** The message of the last failure, form errors included, until it is dismissed. */ + var error by mutableStateOf(null) + + /** The created document's id, base58, once Platform confirmed the write. */ + var createdId by mutableStateOf(null) + private set + + /** + * Run [create], which returns the created document's id, unless a write is running or + * one succeeded and was not [acknowledge]d: the form is never submitted twice. + */ + fun submit(create: suspend () -> String) { + if (isSubmitting || createdId != null) return + isSubmitting = true + error = null + viewModelScope.launch { + try { + createdId = create() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + error = e.message ?: "Broadcast failed" + } finally { + isSubmitting = false + } + } + } + + /** + * Forget a confirmed write once the screen showed it, so that another document (a + * further choice) can be created. Does nothing while a write runs. + */ + fun acknowledge() { + if (!isSubmitting) createdId = null + } +} + +/** + * Files a new multiple choice proposal for an identity held by a loaded wallet: port of + * `CreateMultipleChoiceProposalView` (`MultipleChoiceProposalFormViews.swift`), beside the + * yes/no [CreateDecisionProposalScreen]. + * + * Submits through `PlatformWalletManager.multipleChoiceProposals.create`, one platform + * wallet call that builds the proposal and waits for Platform to confirm; Platform charges + * the proposer the processing fee, which the screen reads through + * `Sdk.multipleChoiceProposals.processingFee` and shows before the submit. The submission + * lives in [MultipleChoiceDocumentCreateViewModel] and Back is held while it runs, so + * leaving the screen never cancels a paid create. Nothing in the form is checked here: + * Platform refuses a proposal outside its limits. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun CreateMultipleChoiceProposalScreen( + navController: NavHostController, + submission: MultipleChoiceDocumentCreateViewModel = viewModel(), +) { + val appState = LocalAppState.current + val container = LocalAppContainer.current + val sdk by appState.sdk.collectAsStateWithLifecycle() + val network by appState.currentNetwork.collectAsStateWithLifecycle() + val manager by container.walletManagerStore.activeManager.collectAsStateWithLifecycle() + // Identities on the active network held by a loaded wallet, so the + // manager's signer can sign for them. + val identities by container.database.identityDao() + .observeWalletOwnedByNetwork(network.ffiValue) + .collectAsStateWithLifecycle(initialValue = emptyList()) + + var owner by remember { mutableStateOf(null) } + LaunchedEffect(identities) { + if (owner == null) owner = identities.firstOrNull() + } + var title by rememberSaveable { mutableStateOf("") } + var url by rememberSaveable { mutableStateOf("") } + var describedId by rememberSaveable { mutableStateOf("") } + var describedContractId by rememberSaveable { mutableStateOf("") } + var describedType by rememberSaveable { mutableStateOf("") } + var open by rememberSaveable { mutableStateOf(true) } + + // The processing fee as Platform charges it on this network, read rather than assumed. + var processingFee by remember { mutableStateOf(null) } + var processingFeeError by remember { mutableStateOf(null) } + LaunchedEffect(sdk) { + processingFee = null + processingFeeError = null + val currentSdk = sdk ?: return@LaunchedEffect + try { + processingFee = currentSdk.multipleChoiceProposals.processingFee() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + processingFeeError = "Reading the processing fee failed: ${e.message}" + } + } + + val isSubmitting = submission.isSubmitting + // System Back would pop the entry and clear the submission with it; the toolbar Back + // is disabled for the same reason. + BackHandler(enabled = isSubmitting) {} + + Scaffold( + topBar = { + TopAppBar( + title = { Text("New Multiple Choice Proposal") }, + navigationIcon = { + IconButton( + onClick = { navController.popBackStack() }, + enabled = !isSubmitting, + ) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") + } + }, + ) + }, + ) { padding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(padding) + .verticalScroll(rememberScrollState()) + .imePadding() + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + val createdId = submission.createdId + if (createdId != null) { + FormSection(title = "Proposal Created") { + Text( + "Broadcast confirmed on-chain.", + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.testTag("createMultipleChoiceProposal.success"), + ) + LabeledContent("ID", truncateMiddle(createdId, 12, 8)) + } + SubmitButton( + text = "Done", + isLoading = false, + modifier = Modifier + .fillMaxWidth() + .testTag("createMultipleChoiceProposal.doneButton"), + ) { navController.popBackStack() } + return@Column + } + + FormSection(title = "Proposer") { + if (identities.isEmpty()) { + Text( + "No identity held by a loaded wallet on this network.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } else { + AccessiblePicker( + label = "Proposer", + options = identities, + selected = owner ?: identities.first(), + optionLabel = { it.displayLabel() }, + testTag = "createMultipleChoiceProposal.ownerPicker", + enabled = !isSubmitting, + onSelected = { owner = it }, + ) + } + LabeledContent( + "Processing fee", + processingFee?.let { formatCredits(it) } + ?: if (processingFeeError == null) "Loading…" else "Unavailable", + modifier = Modifier.testTag("createMultipleChoiceProposal.processingFee"), + ) + processingFeeError?.let { message -> + Text( + message, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.testTag("createMultipleChoiceProposal.processingFeeError"), + ) + } + Text( + "Platform charges this identity the processing fee for the create, on " + + "top of the fees.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + FormSection(title = "Question") { + OutlinedTextField( + value = title, + onValueChange = { title = it }, + label = { Text("Title: the question, in one line") }, + singleLine = true, + enabled = !isSubmitting, + modifier = Modifier + .fillMaxWidth() + .testTag("createMultipleChoiceProposal.title"), + ) + OutlinedTextField( + value = url, + onValueChange = { url = it }, + label = { Text("URL where it is described or discussed") }, + singleLine = true, + enabled = !isSubmitting, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri), + modifier = Modifier + .fillMaxWidth() + .testTag("createMultipleChoiceProposal.url"), + ) + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth(), + ) { + Text("Anyone may enter choices", modifier = Modifier.weight(1f)) + Switch( + checked = open, + onCheckedChange = { open = it }, + enabled = !isSubmitting, + modifier = Modifier.testTag("createMultipleChoiceProposal.open"), + ) + } + Text( + "The answers are the choices entered once the proposal exists: by " + + "anyone when it is open, by the proposer alone when it is not, " + + "which never changes. The title, url and description document can " + + "be edited for a short time after the proposal is created.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + FormSection(title = "Description Document (optional)") { + OutlinedTextField( + value = describedId, + onValueChange = { describedId = it }, + label = { Text("Document ID (base58)") }, + singleLine = true, + enabled = !isSubmitting, + modifier = Modifier + .fillMaxWidth() + .testTag("createMultipleChoiceProposal.descriptionDocumentId"), + ) + OutlinedTextField( + value = describedContractId, + onValueChange = { describedContractId = it }, + label = { Text("Contract ID (base58)") }, + singleLine = true, + enabled = !isSubmitting, + modifier = Modifier + .fillMaxWidth() + .testTag("createMultipleChoiceProposal.descriptionDocumentContractId"), + ) + OutlinedTextField( + value = describedType, + onValueChange = { describedType = it }, + label = { Text("Document type") }, + singleLine = true, + enabled = !isSubmitting, + modifier = Modifier + .fillMaxWidth() + .testTag("createMultipleChoiceProposal.descriptionDocumentType"), + ) + Text( + "The document saying what is being decided. Platform takes a proposal " + + "with a description document, a url or both, and refuses a " + + "document that is not of a moderated type.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + SubmitButton( + text = if (isSubmitting) "Broadcasting…" else "Create / Broadcast", + isLoading = isSubmitting, + enabled = manager != null && owner != null, + modifier = Modifier + .fillMaxWidth() + .testTag("createMultipleChoiceProposal.submitButton"), + ) { + val mgr = manager ?: return@SubmitButton + val proposer = owner ?: return@SubmitButton + val wallet = proposer.walletId?.toHex()?.let { mgr.wallets.value[it] } + if (wallet == null) { + submission.error = "The proposer's wallet is not loaded in the wallet manager." + return@SubmitButton + } + // Form parsing only: what a proposal must hold is Platform's to say. + val described = when ( + val parsed = parseDescriptionDocument(describedId, describedContractId, describedType) + ) { + is ParsedDescriptionDocument.Unreadable -> { + submission.error = parsed.message + return@SubmitButton + } + ParsedDescriptionDocument.None -> null + is ParsedDescriptionDocument.Document -> parsed.document + } + val params = MultipleChoiceProposalParams( + title = title, + descriptionDocument = described, + url = url.trim().ifEmpty { null }, + open = open, + ) + submission.submit { + mgr.multipleChoiceProposals.create( + walletHandle = wallet.handle, + ownerId = proposer.identityId, + params = params, + signerHandle = mgr.signerHandle, + ).id + } + } + } + } + + ErrorAlertDialog(message = submission.error, onDismiss = { submission.error = null }) +} + +/** What the three description document fields of a form hold. */ +internal sealed interface ParsedDescriptionDocument { + /** All three fields are empty: no description document. */ + data object None : ParsedDescriptionDocument + + /** The fields name a document. */ + data class Document(val document: DescriptionDocumentParams) : ParsedDescriptionDocument + + /** An id field does not hold the 32 bytes the wallet call takes. */ + data class Unreadable(val message: String) : ParsedDescriptionDocument +} + +/** + * Read a form's description document fields into the bytes the wallet call takes. Only the + * text-to-bytes step can fail here; whether the document may describe a proposal is + * Platform's to say. + */ +internal fun parseDescriptionDocument( + id: String, + contractId: String, + documentType: String, +): ParsedDescriptionDocument { + if (id.isBlank() && contractId.isBlank() && documentType.isBlank()) { + return ParsedDescriptionDocument.None + } + val idBytes = Base58.decodeIdentifier(id) + ?: return ParsedDescriptionDocument.Unreadable( + "The description document id is not a 32-byte base58 identifier.", + ) + val contractIdBytes = Base58.decodeIdentifier(contractId) + ?: return ParsedDescriptionDocument.Unreadable( + "The description document's contract id is not a 32-byte base58 identifier.", + ) + return ParsedDescriptionDocument.Document( + DescriptionDocumentParams(idBytes, contractIdBytes, documentType.trim()), + ) +} diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/util/Formatters.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/util/Formatters.kt index 81f6aea4798..84dd959d6e9 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/util/Formatters.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/util/Formatters.kt @@ -69,6 +69,13 @@ fun formatDuffs(duffs: Long): String = formatDashAmount(duffs.toDouble() / 100_0 fun formatCredits(credits: Long): String = formatDashAmount(credits.toDouble() / 100_000_000_000.0) +/** + * [formatCredits] for an amount the SDK reads as unsigned (a fee, a contest fund): it is + * never narrowed to [Long], which would show an amount past [Long.MAX_VALUE] as negative. + */ +fun formatCredits(credits: ULong): String = + formatDashAmount(credits.toDouble() / 100_000_000_000.0) + private fun formatDashAmount(dash: Double): String { val formatter = java.text.DecimalFormat("#,##0.########") return "${formatter.format(dash)} DASH" diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/identity/MultipleChoiceDocumentCreateViewModelTest.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/identity/MultipleChoiceDocumentCreateViewModelTest.kt new file mode 100644 index 00000000000..e7602151be0 --- /dev/null +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/identity/MultipleChoiceDocumentCreateViewModelTest.kt @@ -0,0 +1,174 @@ +package org.dashfoundation.example.ui.identity + +import androidx.lifecycle.ViewModelStore +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * [MultipleChoiceDocumentCreateViewModel] holds the two paid writes of the multiple choice + * proposal screens (creating a proposal, entering a choice) as + * [CreateDecisionProposalViewModel] holds the yes/no create: the write runs in the + * ViewModel's own scope, which lives as long as the screen's back-stack entry rather than + * its composition, is submitted at most once until its outcome was shown, and reports a + * failure without a cancellation passing for one. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class MultipleChoiceDocumentCreateViewModelTest { + + private val dispatcher = StandardTestDispatcher() + + private val proposalId = "8vLzWy3oPYAwJ9W8TjWZ3vSJMy7bDqyuvbMvzQMxVjPN" + private val choiceId = "5DbLwAxGBzUzo81VewMUwn4b5P4bpv9FNFybi25XB5Bk" + + @Before + fun setMain() { + Dispatchers.setMain(dispatcher) + } + + @After + fun resetMain() { + Dispatchers.resetMain() + } + + @Test + fun shouldRecordTheCreatedIdAndNeverSubmitTwice() = runTest(dispatcher) { + val submission = MultipleChoiceDocumentCreateViewModel() + val confirmed = CompletableDeferred() + var creates = 0 + + submission.submit { + creates++ + confirmed.await() + } + advanceUntilIdle() + assertTrue(submission.isSubmitting) + + // A second tap while the first create runs is ignored. + submission.submit { + creates++ + "second" + } + advanceUntilIdle() + assertEquals(1, creates) + + confirmed.complete(proposalId) + advanceUntilIdle() + assertFalse(submission.isSubmitting) + assertEquals(proposalId, submission.createdId) + assertNull(submission.error) + + // So is one after the create succeeded. + submission.submit { + creates++ + "third" + } + advanceUntilIdle() + assertEquals(1, creates) + assertEquals(proposalId, submission.createdId) + } + + @Test + fun shouldRecordAFailureAndAllowAnotherSubmit() = runTest(dispatcher) { + val submission = MultipleChoiceDocumentCreateViewModel() + + submission.submit { throw IllegalStateException("Platform refused the proposal") } + advanceUntilIdle() + assertFalse(submission.isSubmitting) + assertEquals("Platform refused the proposal", submission.error) + assertNull(submission.createdId) + + submission.submit { proposalId } + advanceUntilIdle() + assertNull(submission.error) + assertEquals(proposalId, submission.createdId) + } + + /** + * The detail screen enters one choice after another: once it showed a confirmed choice + * it acknowledges it, and only then is another one submitted. + */ + @Test + fun shouldAllowAnotherChoiceOnlyOnceTheConfirmedOneWasAcknowledged() = runTest(dispatcher) { + val entry = MultipleChoiceDocumentCreateViewModel() + var entries = 0 + + entry.submit { + entries++ + choiceId + } + advanceUntilIdle() + assertEquals(choiceId, entry.createdId) + + entry.acknowledge() + assertNull(entry.createdId) + + entry.submit { + entries++ + proposalId + } + advanceUntilIdle() + assertEquals(2, entries) + assertEquals(proposalId, entry.createdId) + } + + /** Acknowledging while a write runs neither drops its outcome nor lets a second one in. */ + @Test + fun shouldNotAcknowledgeWhileAWriteRuns() = runTest(dispatcher) { + val entry = MultipleChoiceDocumentCreateViewModel() + val confirmed = CompletableDeferred() + var entries = 0 + + entry.submit { + entries++ + confirmed.await() + } + advanceUntilIdle() + entry.acknowledge() + entry.submit { + entries++ + "second" + } + advanceUntilIdle() + assertTrue(entry.isSubmitting) + assertEquals(1, entries) + + confirmed.complete(choiceId) + advanceUntilIdle() + assertEquals(choiceId, entry.createdId) + } + + /** + * Only clearing the back-stack entry's store stops a running write, and the + * cancellation is not reported as a failure. + */ + @Test + fun shouldStopOnlyWhenTheEntryIsClearedWithoutReportingAFailure() = runTest(dispatcher) { + val store = ViewModelStore() + val submission = MultipleChoiceDocumentCreateViewModel() + store.put("createMultipleChoiceProposal", submission) + val confirmed = CompletableDeferred() + + submission.submit { confirmed.await() } + advanceUntilIdle() + assertTrue(submission.isSubmitting) + + store.clear() + advanceUntilIdle() + assertFalse(submission.isSubmitting) + assertNull(submission.error) + assertNull(submission.createdId) + } +} diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/identity/MultipleChoiceProposalFormTest.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/identity/MultipleChoiceProposalFormTest.kt new file mode 100644 index 00000000000..2a43fa86edb --- /dev/null +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/identity/MultipleChoiceProposalFormTest.kt @@ -0,0 +1,163 @@ +package org.dashfoundation.example.ui.identity + +import org.dashfoundation.dashsdk.voting.DescriptionDocumentParams +import org.dashfoundation.dashsdk.voting.MultipleChoiceProposal +import org.dashfoundation.dashsdk.voting.MultipleChoiceProposalEdit +import org.dashfoundation.example.util.Base58 +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * How the multiple choice proposal forms turn their text fields into what the wallet calls + * take: the description document's ids as bytes, and an edit that sends only what the user + * changed. The forms judge nothing else; Platform refuses what it does not accept. + */ +class MultipleChoiceProposalFormTest { + + private val describedIdBytes = ByteArray(32) { 5 } + private val describedContractIdBytes = ByteArray(32) { 6 } + private val describedId = Base58.encode(describedIdBytes) + private val describedContractId = Base58.encode(describedContractIdBytes) + + private val proposal = MultipleChoiceProposal( + id = Base58.encode(ByteArray(32) { 1 }), + ownerId = Base58.encode(ByteArray(32) { 2 }), + revision = 1, + createdAtMs = 1_700_000_000_000, + updatedAtMs = 1_700_000_000_000, + title = "Which block size?", + descriptionDocument = MultipleChoiceProposal.DescriptionDocument(describedId, describedContractId, "post"), + url = "https://forum.dash.org/t/block-size", + open = true, + ) + + /** The edit the form makes when its fields hold what is given, the rest untouched. */ + private fun edit( + proposal: MultipleChoiceProposal = this.proposal, + title: String = proposal.title, + url: String = proposal.url.orEmpty(), + describedId: String = proposal.descriptionDocument?.id.orEmpty(), + describedContractId: String = proposal.descriptionDocument?.contractId.orEmpty(), + describedType: String = proposal.descriptionDocument?.documentType.orEmpty(), + ): BuiltMultipleChoiceEdit = + multipleChoiceProposalEdit(proposal, title, url, describedId, describedContractId, describedType) + + private fun changes(edit: MultipleChoiceProposalEdit) = BuiltMultipleChoiceEdit.Edit(edit) + + @Test + fun shouldReadThreeEmptyFieldsAsNoDescriptionDocument() { + assertEquals(ParsedDescriptionDocument.None, parseDescriptionDocument("", " ", "")) + } + + @Test + fun shouldReadTheDescriptionDocumentIdsAsTheirBytes() { + assertEquals( + ParsedDescriptionDocument.Document( + DescriptionDocumentParams(describedIdBytes, describedContractIdBytes, "post"), + ), + parseDescriptionDocument(" $describedId ", describedContractId, " post "), + ) + } + + @Test + fun shouldReportAnIdFieldThatDoesNotHold32Bytes() { + val noId = parseDescriptionDocument("", describedContractId, "post") + assertTrue("$noId", noId is ParsedDescriptionDocument.Unreadable) + val shortContractId = parseDescriptionDocument(describedId, "abc", "post") + assertTrue("$shortContractId", shortContractId is ParsedDescriptionDocument.Unreadable) + } + + /** A document type left empty still crosses: the wallet is the one to refuse it. */ + @Test + fun shouldLeaveAnEmptyDocumentTypeToTheWallet() { + assertEquals( + ParsedDescriptionDocument.Document( + DescriptionDocumentParams(describedIdBytes, describedContractIdBytes, ""), + ), + parseDescriptionDocument(describedId, describedContractId, ""), + ) + } + + @Test + fun shouldSendNothingForAnUntouchedForm() { + assertEquals(changes(MultipleChoiceProposalEdit()), edit()) + } + + @Test + fun shouldSendOnlyTheFieldTheUserChanged() { + assertEquals( + changes(MultipleChoiceProposalEdit(title = "Which block size next year?")), + edit(title = "Which block size next year?"), + ) + assertEquals( + changes( + MultipleChoiceProposalEdit( + url = MultipleChoiceProposalEdit.Change.Set("https://example.org/sizes"), + ), + ), + edit(url = " https://example.org/sizes "), + ) + val otherId = Base58.encode(ByteArray(32) { 7 }) + assertEquals( + changes( + MultipleChoiceProposalEdit( + descriptionDocument = MultipleChoiceProposalEdit.Change.Set( + DescriptionDocumentParams(ByteArray(32) { 7 }, describedContractIdBytes, "post"), + ), + ), + ), + edit(describedId = otherId), + ) + } + + @Test + fun shouldRemoveAnEmptiedUrlOrDescriptionDocument() { + assertEquals( + changes(MultipleChoiceProposalEdit(url = MultipleChoiceProposalEdit.Change.Remove)), + edit(url = ""), + ) + assertEquals( + changes( + MultipleChoiceProposalEdit( + descriptionDocument = MultipleChoiceProposalEdit.Change.Remove, + ), + ), + edit(describedId = "", describedContractId = "", describedType = ""), + ) + } + + /** Fields that were empty and stay empty are untouched, not a removal. */ + @Test + fun shouldKeepWhatAProposalDoesNotHave() { + val bare = proposal.copy(descriptionDocument = null, url = null) + assertEquals(changes(MultipleChoiceProposalEdit()), edit(proposal = bare)) + assertEquals( + changes( + MultipleChoiceProposalEdit( + descriptionDocument = MultipleChoiceProposalEdit.Change.Set( + DescriptionDocumentParams(describedIdBytes, describedContractIdBytes, "post"), + ), + ), + ), + edit( + proposal = bare, + describedId = describedId, + describedContractId = describedContractId, + describedType = "post", + ), + ) + } + + @Test + fun shouldReportAnEditedDescriptionDocumentIdThatDoesNotHold32Bytes() { + val built = edit(describedId = "abc") + assertTrue("$built", built is BuiltMultipleChoiceEdit.Unreadable) + } + + @Test + fun shouldSayWhoEntersChoices() { + assertEquals("anyone enters choices", proposal.whoEntersChoices()) + assertEquals("only its owner enters choices", proposal.copy(open = false).whoEntersChoices()) + } +} diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/util/FormattersTest.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/util/FormattersTest.kt index 54c9289c452..6f1f6f51423 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/util/FormattersTest.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/util/FormattersTest.kt @@ -1,6 +1,7 @@ package org.dashfoundation.example.util import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Test @@ -32,4 +33,14 @@ class FormattersTest { assertEquals(10_000L, parseDashToDuffs("0.0001")) assertNull(parseDashToDuffs("0.000000001")) } + + @Test + fun formatCreditsKeepsAnUnsignedAmountUnsigned() { + // An unsigned amount formats as the same amount read as a Long. + assertEquals(formatCredits(20_000_000_000L), formatCredits(20_000_000_000uL)) + // Past Long.MAX_VALUE it is still a positive amount, where a narrowing to Long + // would have shown a negative one. + assertFalse(formatCredits(ULong.MAX_VALUE).startsWith("-")) + assertFalse(formatCredits(Long.MAX_VALUE.toULong() + 1uL).startsWith("-")) + } } diff --git a/packages/kotlin-sdk/PARITY.md b/packages/kotlin-sdk/PARITY.md index 8c3c53695a3..5e450bf63fa 100644 --- a/packages/kotlin-sdk/PARITY.md +++ b/packages/kotlin-sdk/PARITY.md @@ -56,7 +56,7 @@ Status legend: | OptionsView.swift | ui/settings/SettingsScreen.kt · `SettingsHome` (+ AboutSheet.kt) | ported — Network/SPV/Data/Platform/About sections incl. About bottom sheet | | PendingPlatformFundFromAssetLocksList.swift | ui/funding/AddressFundProgressScreen.kt (`PendingAssetLocksList`) | ported (embedded in IdentitiesHome, matching iOS) | | PendingRegistrationsList.swift | ui/identity/RegistrationProgressScreen.kt (`PendingRegistrationRow`) | ported (embedded in IdentitiesHome) | -| PlatformQueriesView.swift | ui/contracts/QueryDetailScreen.kt (`QueriesListScreen`) · `QueriesList` | ported — the Decision Proposals link (`votingQueries.decisionProposalsLink`) opens `DecisionProposalsList`, and the seven decision proposal reads have registry rows kept out of Run All Queries; the registry now spans the iOS query catalog (adapted: one flat Material list instead of 12 category groups) plus the dedicated GroveDB Path Elements / Address Queries / Run All Queries entries | +| PlatformQueriesView.swift | ui/contracts/QueryDetailScreen.kt (`QueriesListScreen`) · `QueriesList` | ported — the Decision Proposals link (`votingQueries.decisionProposalsLink`) opens `DecisionProposalsList` and the Multiple Choice Proposals link (`votingQueries.multipleChoiceProposalsLink`) opens `MultipleChoiceProposalsList`; the seven decision proposal reads and the eight multiple choice proposal reads have registry rows kept out of Run All Queries; the registry now spans the iOS query catalog (adapted: one flat Material list instead of 12 category groups) plus the dedicated GroveDB Path Elements / Address Queries / Run All Queries entries | | PlatformStateTransitionsView.swift | ui/transitions/StateTransitionsScreen.kt · `StateTransitions` | ported (iOS file is a trivial wrapper around StateTransitionsView) | | QueryDetailView.swift | ui/contracts/QueryDetailScreen.kt · `QueryDetail` | ported for the bridged registry | | QuickBasicTokenView.swift | ui/tokens/QuickBasicTokenScreen.kt · `QuickBasicToken` | ported — contract-registration submit wired via `ManagedPlatformWallet.dataContracts.create` (`platform_wallet_create_data_contract_with_signer`) | @@ -136,6 +136,24 @@ rebuilt `libdash_sdk_jni.so` and a network at protocol version 15. | DecisionProposalDetailView.swift | ui/identity/DecisionProposalDetailScreen.kt · `DecisionProposalDetail` | ported: proposal, rule, poll state (open tallies or finished result) and poll id; masternode vote and answer lookup over `castVote` / `masternodeVote` with the contest screen's credential form (voting key masked, FLAG_SECURE held while the dialog is open) | | DecisionProposalFormViews.swift | ui/identity/DecisionProposalsScreen.kt · `CreateDecisionProposal` (create); ui/identity/DecisionProposalDetailScreen.kt (edit dialog) | ported: create through `PlatformWalletManager.decisionProposals.create` (`platform_wallet_decision_proposal_create`, returning the proposal id and the confirmed document); edit through `.edit` (`platform_wallet_decision_proposal_edit`; the wallet picks the signing key and a concurrent edit is refused with consensus code 40106). The create runs in a back-stack-entry ViewModel with Back held while it runs, and the edit dialog cannot be dismissed while it runs. The end date is entered as days from now rather than with a date picker | +Multiple choice proposals (protocol version 15): questions answered by the +choices entered for them. The Kotlin SDK bridges every +`dash_sdk_multiple_choice_proposal_*` function and the platform wallet's +`platform_wallet_multiple_choice_proposal_create` / `_edit` / `_enter_choice` +one JNI export each (`rs-unified-sdk-jni/src/multiple_choice_proposals.rs`); +`Sdk.multipleChoiceProposals` reads, reads the processing fee and the contest +fund, and votes, and `PlatformWalletManager.multipleChoiceProposals` creates, +edits and enters a choice, one native call each. Compile-verified, with JVM +tests of the JSON decoding and of the app's form and submission logic; the +device run waits on a rebuilt `libdash_sdk_jni.so` and a network at protocol +version 15. + +| Swift file | Android file / route | Status | +| --- | --- | --- | +| MultipleChoiceProposalsView.swift | ui/identity/MultipleChoiceProposalsScreen.kt · `MultipleChoiceProposalsList` | ported: Mine / Newest listings, paged, over `Sdk.multipleChoiceProposals.listByOwner` / `listByCreatedAt`; reached from the Platform Queries list (`votingQueries.multipleChoiceProposalsLink`) as on iOS | +| MultipleChoiceProposalDetailView.swift | ui/identity/MultipleChoiceProposalDetailScreen.kt · `MultipleChoiceProposalDetail` | ported: proposal, its choices with their tallies while the vote runs, the outcome and the kept choice once it ended (`vote` / `keptChoice`); masternode vote and answer lookup over `castVote` / `masternodeVote` with the contest screen's credential form (voting key masked, FLAG_SECURE held while the dialog is open, no dismissal while a call runs), the answers being the vote's choices by document id, none of the choices and abstain | +| MultipleChoiceProposalFormViews.swift | ui/identity/MultipleChoiceProposalsScreen.kt · `CreateMultipleChoiceProposal` (create); ui/identity/MultipleChoiceProposalDetailScreen.kt (enter a choice and edit dialogs) | ported: create through `PlatformWalletManager.multipleChoiceProposals.create` (`platform_wallet_multiple_choice_proposal_create`), showing the processing fee read through `Sdk.multipleChoiceProposals.processingFee`; enter a choice through `.enterChoice` (`platform_wallet_multiple_choice_proposal_enter_choice`), showing the contest fund read through `choiceFundToJoin`; edit through `.edit` (`platform_wallet_multiple_choice_proposal_edit`), sending only the changed fields, with keep / set / remove for the url and the description document. The create and the choice entry each run in a back-stack-entry ViewModel with Back held while they run, and the dialogs cannot be dismissed while they run. Adapted: the choice entry and the edit are dialogs of the detail screen rather than pushed views. Who may enter a choice and how long the edit stays open are left to Platform, which refuses what it does not accept | + ## Views/Components/ | Swift file | Android file | Status | diff --git a/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/MultipleChoiceProposalsFfiTest.kt b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/MultipleChoiceProposalsFfiTest.kt new file mode 100644 index 00000000000..ac118c8bda0 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/MultipleChoiceProposalsFfiTest.kt @@ -0,0 +1,250 @@ +package org.dashfoundation.dashsdk + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.dashfoundation.dashsdk.errors.DashSdkError +import org.dashfoundation.dashsdk.ffi.DashSDKException +import org.dashfoundation.dashsdk.ffi.MultipleChoiceProposalsNative +import org.dashfoundation.dashsdk.ffi.NativeLoader +import org.dashfoundation.dashsdk.ffi.SdkNative +import org.dashfoundation.dashsdk.persistence.toBase58String +import org.dashfoundation.dashsdk.voting.MultipleChoiceVoteChoice +import org.dashfoundation.dashsdk.voting.toNative +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith + +/** + * Round trips of the multiple choice proposal JNI exports through `rs-sdk-ffi` and + * `platform-wallet-ffi` on a device: the symbol names, the argument marshalling and the + * error codes Kotlin maps. Every call here is refused before anything reaches the network + * (the JNI layer and the C functions read every argument first), so no network, wallet or + * protocol version 15 is needed: `createTrusted` only builds the client. The flows that + * reach Platform (create, edit, enter a choice, the reads, the two amounts, vote) need a + * network at protocol version 15 and are exercised through KotlinExampleApp. + */ +@RunWith(AndroidJUnit4::class) +class MultipleChoiceProposalsFfiTest { + + /** A well-formed 32-byte id that names no proposal. */ + private val proposalIdBytes = ByteArray(32) { 0x11 } + private val proposalId = proposalIdBytes.toBase58String() + + /** A well-formed 32-byte identity id. */ + private val ownerId = ByteArray(32) { 0x22 } + + /** A well-formed id that names no choice, base58. */ + private val choiceId = ByteArray(32) { 0x33 }.toBase58String() + + private var handle = 0L + + @Before + fun createSdk() { + NativeLoader.ensureLoaded() + handle = SdkNative.createTrusted( + network = 1, + dapiAddresses = null, + quorumUrl = null, + skipAssetLockProofVerification = false, + requestRetryCount = 3, + requestTimeoutMs = 30_000, + platformVersion = 0, + ) + assertNotEquals("createTrusted must return a live handle", 0L, handle) + } + + @After + fun destroySdk() { + SdkNative.destroy(handle) + } + + /** rs-sdk-ffi refuses ids that are not base58 with InvalidParameter (1). */ + @Test + fun shouldRefuseBadArgumentsBeforeTheNetwork() { + assertCode(1) { MultipleChoiceProposalsNative.fetch(handle, "0OIl") } + assertCode(1) { MultipleChoiceProposalsNative.getVote(handle, "0OIl") } + assertCode(1) { MultipleChoiceProposalsNative.getKeptChoice(handle, "0OIl") } + assertCode(1) { MultipleChoiceProposalsNative.getChoiceFundToJoin(handle, "0OIl") } + assertCode(1) { MultipleChoiceProposalsNative.listByOwner(handle, "0OIl", 0, null) } + assertCode(1) { MultipleChoiceProposalsNative.listByOwner(handle, proposalId, 0, "0OIl") } + assertCode(1) { MultipleChoiceProposalsNative.listByCreatedAt(handle, 0, "0OIl") } + assertCode(1) { + MultipleChoiceProposalsNative.getMasternodeVote(handle, ByteArray(32) { 1 }, "0OIl") + } + } + + /** The JNI layer refuses a value the C type cannot hold instead of wrapping it. */ + @Test + fun shouldRefuseNumbersOutsideTheCTypes() { + assertCode(1) { MultipleChoiceProposalsNative.listByOwner(handle, proposalId, -1, null) } + assertCode(1) { MultipleChoiceProposalsNative.listByCreatedAt(handle, -1, null) } + } + + /** + * The wallet writes read exactly 32 bytes behind each id, and the two that create a + * document check the array its id is written back to before anything is broadcast. + */ + @Test + fun shouldRefuseAWalletWriteIdThatIsNot32Bytes() { + assertCode(1) { create(outProposalId = ByteArray(31)) } + assertCode(1) { create(ownerId = ByteArray(33)) } + assertCode(1) { create(descriptionDocumentId = ByteArray(31)) } + assertCode(1) { create(descriptionDocumentContractId = ByteArray(33)) } + assertCode(1) { edit(ownerId = ByteArray(31)) } + assertCode(1) { edit(proposalId = ByteArray(33)) } + assertCode(1) { edit(descriptionDocumentId = ByteArray(33)) } + assertCode(1) { enterChoice(outChoiceId = ByteArray(31)) } + assertCode(1) { enterChoice(ownerId = ByteArray(33)) } + assertCode(1) { enterChoice(proposalId = ByteArray(31)) } + } + + /** + * The three wallet writes reach `platform-wallet-ffi`, which refuses a null signer + * (`ErrorNullPointer`, 3) before it looks the wallet up; the code arrives shifted by the + * platform wallet offset, and no id is written back. + */ + @Test + fun shouldReachThePlatformWalletForTheWrites() { + val nullPointer = DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 3 + val outProposalId = ByteArray(32) + assertCode(nullPointer) { create(outProposalId = outProposalId) } + assertArrayEquals(ByteArray(32), outProposalId) + // A description document given in part still crosses: the wallet is the one to refuse it. + assertCode(nullPointer) { create(descriptionDocumentId = null, descriptionDocumentType = null) } + assertCode(nullPointer) { edit() } + assertCode(nullPointer) { edit(url = "https://example.com", removeUrl = true) } + assertCode(nullPointer) { edit(removeDescriptionDocument = true) } + val outChoiceId = ByteArray(32) + assertCode(nullPointer) { enterChoice(outChoiceId = outChoiceId) } + assertArrayEquals(ByteArray(32), outChoiceId) + } + + /** The C functions read exactly 32 bytes behind these pointers. */ + @Test + fun shouldRefuseAProTxHashOrVotingKeyThatIsNot32Bytes() { + assertCode(1) { + MultipleChoiceProposalsNative.getMasternodeVote(handle, ByteArray(31), proposalId) + } + assertCode(1) { + MultipleChoiceProposalsNative.castVote( + handle, proposalId, 1, null, ByteArray(31), ByteArray(32), 1, + ) + } + assertCode(1) { + MultipleChoiceProposalsNative.castVote( + handle, proposalId, 1, null, ByteArray(32), ByteArray(33), 1, + ) + } + } + + /** + * rs-sdk-ffi reads the vote choice and the choice id before the voting key, so every + * Kotlin choice gets past them and is refused on the all-zero key instead, while a byte + * outside the three is refused as a choice. Nothing reaches the network either way. + */ + @Test + fun shouldAcceptExactlyTheThreeVoteChoices() { + val choices = listOf( + MultipleChoiceVoteChoice.Choice(choiceId), + MultipleChoiceVoteChoice.NoneOfTheChoices, + MultipleChoiceVoteChoice.Abstain, + ) + for (choice in choices) { + val vote = choice.toNative() + val error = assertCode(1) { castVote(vote.discriminant, vote.choiceId) } + assertFalse(error.message, error.message.orEmpty().contains("vote_choice")) + assertFalse(error.message, error.message.orEmpty().contains("choice_id")) + } + val refused = assertCode(1) { castVote(3, null) } + assertTrue(refused.message, refused.message.orEmpty().contains("vote_choice")) + assertCode(1) { castVote(256, null) } + } + + /** A vote for a choice names it, and the other answers name none. */ + @Test + fun shouldRefuseAChoiceIdThatDoesNotFitTheVoteChoice() { + val missing = assertCode(1) { castVote(0, null) } + assertTrue(missing.message, missing.message.orEmpty().contains("choice_id")) + for (voteChoice in listOf(1, 2)) { + val superfluous = assertCode(1) { castVote(voteChoice, choiceId) } + assertTrue(superfluous.message, superfluous.message.orEmpty().contains("choice_id")) + } + assertCode(1) { castVote(0, "0OIl") } + } + + /** `castVote` for an all-ones pro_tx_hash with an all-zero voting key. */ + private fun castVote(voteChoice: Int, choiceId: String?) { + MultipleChoiceProposalsNative.castVote( + handle, proposalId, voteChoice, choiceId, ByteArray(32) { 1 }, ByteArray(32), 1, + ) + } + + /** `create` on no wallet and no signer, with valid arguments unless overridden. */ + private fun create( + ownerId: ByteArray = this.ownerId, + descriptionDocumentId: ByteArray? = ByteArray(32) { 0x44 }, + descriptionDocumentContractId: ByteArray? = ByteArray(32) { 0x55 }, + descriptionDocumentType: String? = "post", + outProposalId: ByteArray = ByteArray(32), + ) { + MultipleChoiceProposalsNative.create( + 0L, + ownerId, + "title", + descriptionDocumentId, + descriptionDocumentContractId, + descriptionDocumentType, + null, + true, + 0L, + outProposalId, + ) + } + + /** `edit` on no wallet and no signer, with valid arguments unless overridden. */ + private fun edit( + ownerId: ByteArray = this.ownerId, + proposalId: ByteArray = proposalIdBytes, + descriptionDocumentId: ByteArray? = null, + removeDescriptionDocument: Boolean = false, + url: String? = null, + removeUrl: Boolean = false, + ) { + MultipleChoiceProposalsNative.edit( + 0L, + ownerId, + proposalId, + "new title", + descriptionDocumentId, + null, + null, + removeDescriptionDocument, + url, + removeUrl, + 0L, + ) + } + + /** `enterChoice` on no wallet and no signer, with valid arguments unless overridden. */ + private fun enterChoice( + ownerId: ByteArray = this.ownerId, + proposalId: ByteArray = proposalIdBytes, + outChoiceId: ByteArray = ByteArray(32), + ) { + MultipleChoiceProposalsNative.enterChoice( + 0L, ownerId, proposalId, "title", null, 0L, outChoiceId, + ) + } + + private fun assertCode(code: Int, call: () -> Unit): DashSDKException { + val error = assertThrows(DashSDKException::class.java) { call() } + assertEquals(error.message, code, error.code) + return error + } +} diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/Sdk.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/Sdk.kt index 2f7b4c03291..5f2b12bd30c 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/Sdk.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/Sdk.kt @@ -84,6 +84,16 @@ class Sdk private constructor( org.dashfoundation.dashsdk.voting.DecisionProposals(this) } + /** + * Multiple choice proposal reads, the amounts a proposal and a choice cost, and the + * masternode vote among a proposal's choices (protocol version 15); mirrors the Swift + * SDK's `SDK+MultipleChoiceProposals.swift`. Creating and editing a proposal and + * entering a choice go through `PlatformWalletManager.multipleChoiceProposals`. + */ + val multipleChoiceProposals: org.dashfoundation.dashsdk.voting.MultipleChoiceProposals by lazy { + org.dashfoundation.dashsdk.voting.MultipleChoiceProposals(this) + } + /** Evonode proposed-epoch-block queries. */ val evonodes: org.dashfoundation.dashsdk.queries.Evonodes by lazy { org.dashfoundation.dashsdk.queries.Evonodes(this) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/MultipleChoiceProposalsNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/MultipleChoiceProposalsNative.kt new file mode 100644 index 00000000000..86947a1a60e --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/MultipleChoiceProposalsNative.kt @@ -0,0 +1,181 @@ +package org.dashfoundation.dashsdk.ffi + +/** + * Raw JNI surface for multiple choice proposals (protocol version 15): mirrors + * `rs-unified-sdk-jni/src/multiple_choice_proposals.rs`, one export per C function: each + * `dash_sdk_multiple_choice_proposal_*` function of `rs-sdk-ffi` (the reads, the two amounts + * and the masternode vote), and `platform_wallet_multiple_choice_proposal_create` / `_edit` / + * `_enter_choice` of `platform-wallet-ffi` (the writes). + * + * Internal: the public API is [org.dashfoundation.dashsdk.voting.MultipleChoiceProposals] + * (reads and the masternode vote) and + * [org.dashfoundation.dashsdk.voting.MultipleChoiceProposalTransactions] (create, edit and + * enter a choice), one native call each; no export stitches two C calls together. `sdk` is + * `Sdk.handle`, `walletHandle` a `ManagedPlatformWallet` handle and `signerHandle` the + * manager's `PlatformWalletManager.signerHandle`. Ids are base58 strings except where a + * `ByteArray` is named. Errors throw [DashSDKException]. + */ +internal object MultipleChoiceProposalsNative { + + /** + * Create + broadcast a multiple choice proposal of [ownerId] asking [title], signed via + * [signerHandle]. Bridges `platform_wallet_multiple_choice_proposal_create`: the wallet + * builds the proposal, picks the signing key, broadcasts and waits for Platform to + * confirm; Platform charges the owner the processing fee [getProcessingFee] reads on top + * of the fees. + * + * @param ownerId the proposer's 32-byte identity id. + * @param descriptionDocumentId the 32-byte id of the document saying what is being + * decided; null, with the next two, for none. + * @param descriptionDocumentContractId the 32-byte id of the contract that document + * lives in. + * @param descriptionDocumentType that document's type. + * @param url null for none. + * @param open whether anyone may enter choices; only the owner may when it is false. + * @param outProposalId a `ByteArray(32)`, checked before anything is broadcast, that + * receives the proposal's id. + * @return the confirmed document's canonical JSON. + */ + external fun create( + walletHandle: Long, + ownerId: ByteArray, + title: String, + descriptionDocumentId: ByteArray?, + descriptionDocumentContractId: ByteArray?, + descriptionDocumentType: String?, + url: String?, + open: Boolean, + signerHandle: Long, + outProposalId: ByteArray, + ): String + + /** + * Give the proposal [proposalId] of [ownerId] what the arguments change and broadcast + * the replace, signed via [signerHandle]. Bridges + * `platform_wallet_multiple_choice_proposal_edit`: the wallet reads the proposal once, + * edits it at the revision after the one read and picks the signing key as [create] + * does. + * + * @param ownerId the proposer's 32-byte identity id. + * @param proposalId the proposal's 32-byte id. + * @param title null keeps it. + * @param descriptionDocumentId with the next two, the new description document; all + * null keeps it, unless [removeDescriptionDocument]. + * @param removeDescriptionDocument removes the description document; the wallet refuses + * it together with a new one. + * @param url null keeps it, unless [removeUrl]. + * @param removeUrl removes the url; the wallet refuses it together with a non-null [url]. + * @return the confirmed document's canonical JSON, at its new revision. + */ + external fun edit( + walletHandle: Long, + ownerId: ByteArray, + proposalId: ByteArray, + title: String?, + descriptionDocumentId: ByteArray?, + descriptionDocumentContractId: ByteArray?, + descriptionDocumentType: String?, + removeDescriptionDocument: Boolean, + url: String?, + removeUrl: Boolean, + signerHandle: Long, + ): String + + /** + * Enter a choice of [ownerId] for the proposal [proposalId] and broadcast it, signed via + * [signerHandle]. Bridges `platform_wallet_multiple_choice_proposal_enter_choice`: the + * wallet builds the choice, whose put states the contest fund [getChoiceFundToJoin] + * reads (paid by the owner on top of the fees), picks the signing key, broadcasts and + * waits for Platform to confirm. + * + * @param ownerId the 32-byte id of the identity entering the choice. + * @param proposalId the proposal's 32-byte id. + * @param description null for none. + * @param outChoiceId a `ByteArray(32)`, checked before anything is broadcast, that + * receives the choice's id. + * @return the confirmed document's canonical JSON. + */ + external fun enterChoice( + walletHandle: Long, + ownerId: ByteArray, + proposalId: ByteArray, + title: String, + description: String?, + signerHandle: Long, + outChoiceId: ByteArray, + ): String + + /** + * A proposal as JSON, or null when there is none. Bridges + * `dash_sdk_multiple_choice_proposal_fetch`. + */ + external fun fetch(sdk: Long, proposalId: String): String? + + /** + * One page of [ownerId]'s proposals in filing order, as a JSON array. [limit] 0 is 100. + * Bridges `dash_sdk_multiple_choice_proposal_list_by_owner`. + */ + external fun listByOwner(sdk: Long, ownerId: String, limit: Int, startAfter: String?): String? + + /** + * One page of every proposal, newest first, as a JSON array. Bridges + * `dash_sdk_multiple_choice_proposal_list_by_created_at`. + */ + external fun listByCreatedAt(sdk: Long, limit: Int, startAfter: String?): String? + + /** + * The vote among [proposalId]'s choices as JSON: every choice with its tally, the other + * tallies and how the vote ended once it did. Bridges + * `dash_sdk_multiple_choice_proposal_get_vote`. + */ + external fun getVote(sdk: Long, proposalId: String): String? + + /** + * The choice [proposalId]'s finished vote kept as JSON, or null while the vote runs and + * when it kept none. Bridges `dash_sdk_multiple_choice_proposal_get_kept_choice`. + */ + external fun getKeptChoice(sdk: Long, proposalId: String): String? + + /** + * A masternode's answer in [proposalId]'s vote as `{"choice", "choiceId"}`, or null when + * it has not voted or the vote ended. Bridges + * `dash_sdk_multiple_choice_proposal_get_masternode_vote`. + * + * @param voterProTxHash 32 bytes in wire order, as [castVote] takes it. + */ + external fun getMasternodeVote(sdk: Long, voterProTxHash: ByteArray, proposalId: String): String? + + /** + * What creating one proposal adds to the processing fee of its batch, in credits as a + * decimal string. Bridges `dash_sdk_multiple_choice_proposal_get_processing_fee`. + */ + external fun getProcessingFee(sdk: Long): String? + + /** + * The fund a choice entered now for [proposalId] pays, in credits as a decimal string. + * Bridges `dash_sdk_multiple_choice_proposal_get_choice_fund_to_join`. + */ + external fun getChoiceFundToJoin(sdk: Long, proposalId: String): String? + + /** + * Vote among [proposalId]'s choices for a masternode and wait for the response. Bridges + * `dash_sdk_multiple_choice_proposal_cast_vote`. + * + * @param voteChoice `0` for the choice [choiceId] names, `1` none of the choices, `2` + * abstain. + * @param choiceId the document id of the choice voted for; null for the answers that + * name none. + * @param voterProTxHash 32 bytes in wire order (the reverse of the hex Core displays). + * @param votingPrivateKey the 32-byte masternode voting private key; not stored. + * @param networkOrd `Network.ffiValue`. + */ + external fun castVote( + sdk: Long, + proposalId: String, + voteChoice: Int, + choiceId: String?, + voterProTxHash: ByteArray, + votingPrivateKey: ByteArray, + networkOrd: Int, + ) +} diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/voting/DecisionProposalModels.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/voting/DecisionProposalModels.kt index ffd5c2643ae..7ba70888525 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/voting/DecisionProposalModels.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/voting/DecisionProposalModels.kt @@ -363,15 +363,6 @@ data class YesNoVotePollState( finalizationBlock = block(obj.obj("finalizationBlock")), ) } - - private fun block(obj: JsonObject): PlatformBlockInfo = with(DecisionProposalJson) { - PlatformBlockInfo( - height = obj.long("height"), - coreHeight = obj.long("coreHeight"), - timeMs = obj.long("timeMs"), - epoch = obj.int("epoch"), - ) - } } } @@ -394,6 +385,18 @@ internal object DecisionProposalJson { fun JsonObject.obj(name: String): JsonObject = this[name] as? JsonObject ?: throw malformed(name) + fun JsonObject.optionalObj(name: String): JsonObject? = when (val value = this[name]) { + null, JsonNull -> null + is JsonObject -> value + else -> throw malformed(name) + } + + /** The objects of the array [name], in its order. */ + fun JsonObject.objects(name: String): List = + (this[name] as? JsonArray ?: throw malformed(name)).map { entry -> + entry as? JsonObject ?: throw malformed(name) + } + fun JsonObject.string(name: String): String = (this[name] as? JsonPrimitive)?.takeIf { it.isString }?.content ?: throw malformed(name) @@ -420,6 +423,14 @@ internal object DecisionProposalJson { (this[name] as? JsonPrimitive)?.takeUnless { it.isString }?.booleanOrNull ?: throw malformed(name) + /** A block as every decision proposal read writes it. */ + fun block(obj: JsonObject): PlatformBlockInfo = PlatformBlockInfo( + height = obj.long("height"), + coreHeight = obj.long("coreHeight"), + timeMs = obj.long("timeMs"), + epoch = obj.int("epoch"), + ) + private fun number(value: JsonElement?): Long? = (value as? JsonPrimitive)?.takeUnless { it.isString || it is JsonNull }?.longOrNull diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/voting/MultipleChoiceProposalModels.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/voting/MultipleChoiceProposalModels.kt new file mode 100644 index 00000000000..5cac1180cb9 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/voting/MultipleChoiceProposalModels.kt @@ -0,0 +1,431 @@ +package org.dashfoundation.dashsdk.voting + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import org.dashfoundation.dashsdk.errors.DashSdkError + +// The types the multiple choice proposal reads return, decoded from the JSON rs-sdk-ffi +// writes (`packages/rs-sdk-ffi/src/decision_proposal/multiple_choice/json.rs`), and the +// inputs of the writes. Rust decides every value; these types only carry it. Names and +// shapes follow the Swift SDK (`SwiftDashSDK/Voting/MultipleChoiceProposal.swift`) and +// rs-sdk. + +/** + * A multiple choice proposal (protocol version 15): a question an identity put to the + * masternodes whose answers are the choices entered for it, a `multipleChoiceProposal` + * document of the decision proposals system contract. + * + * The choices contend in a masternode vote the first choice opens; the choice with the most + * votes is kept as an ordinary document, unless the votes for none of the choices outnumber + * it. The title, description document and url can be edited for two hours after the + * proposal is created; [open] never changes. A proposal has a description document, a url + * or both. + */ +data class MultipleChoiceProposal( + /** The proposal's id, base58. */ + val id: String, + /** The proposer's identity id, base58. */ + val ownerId: String, + /** The document revision; null when the document does not carry one. */ + val revision: Long?, + /** When the proposal was created, in milliseconds since the Unix epoch; may be null. */ + val createdAtMs: Long?, + /** When the proposal was last changed, in milliseconds since the Unix epoch; may be null. */ + val updatedAtMs: Long?, + /** The question, in one line. */ + val title: String, + /** The document saying what is being decided; null when the proposal points at none. */ + val descriptionDocument: DescriptionDocument?, + /** Where what is being decided is described or discussed; null when it has none. */ + val url: String?, + /** Whether anyone may enter choices; only the proposal's owner may when it is false. */ + val open: Boolean, +) { + /** + * The document a multiple choice proposal points at for what is being decided, as the + * reads return it. Platform refuses one that is not of a moderated type the elected + * team of its contract may delete. + */ + data class DescriptionDocument( + /** The document's id, base58. */ + val id: String, + /** The id of the contract it lives in, base58. */ + val contractId: String, + /** Its document type. */ + val documentType: String, + ) + + internal companion object { + /** Decode the proposal object every multiple choice proposal read returns. */ + fun fromJson(json: String): MultipleChoiceProposal = fromJsonObject( + DecisionProposalJson.parseObject(json, "multiple choice proposal"), + ) + + /** Decode a listing: a JSON array of proposal objects, in the listing's order. */ + fun listFromJson(json: String): List { + val array = DecisionProposalJson.parse(json, "multiple choice proposal listing") + as? JsonArray + ?: throw DashSdkError.SerializationError( + "Malformed multiple choice proposal listing: $json", + ) + return array.map { entry -> + fromJsonObject( + entry as? JsonObject + ?: throw DashSdkError.SerializationError( + "Malformed multiple choice proposal: $entry", + ), + ) + } + } + + private fun fromJsonObject(json: JsonObject): MultipleChoiceProposal = + with(DecisionProposalJson) { + MultipleChoiceProposal( + id = json.string("id"), + ownerId = json.string("ownerId"), + revision = json.optionalLong("revision"), + createdAtMs = json.optionalLong("createdAt"), + updatedAtMs = json.optionalLong("updatedAt"), + title = json.string("title"), + descriptionDocument = json.optionalObj("descriptionDocument")?.let { described -> + DescriptionDocument( + id = described.string("id"), + contractId = described.string("contractId"), + documentType = described.string("documentType"), + ) + }, + url = json.optionalString("url"), + open = json.boolean("open"), + ) + } + } +} + +/** + * An answer entered for a multiple choice proposal, a `choice` document of the decision + * proposals system contract. A choice is never edited. Its [id] is what a masternode vote + * for it names ([MultipleChoiceVoteChoice.Choice]), not the id of the identity that entered + * it. + */ +data class ProposalChoice( + /** The choice's document id, base58. */ + val id: String, + /** The identity that entered it, base58. */ + val ownerId: String, + /** The proposal it answers, base58. */ + val proposalId: String, + /** The document revision; null when the document does not carry one. */ + val revision: Long?, + /** When the choice was entered, in milliseconds since the Unix epoch; may be null. */ + val createdAtMs: Long?, + /** Null when the document does not carry it. */ + val updatedAtMs: Long?, + /** The answer, in one line. */ + val title: String, + /** What voting for the answer means; null when the choice has none. */ + val description: String?, +) { + internal companion object { + /** Decode the choice object every read of a choice returns. */ + fun fromJson(json: String): ProposalChoice = + fromJsonObject(DecisionProposalJson.parseObject(json, "choice")) + + fun fromJsonObject(json: JsonObject): ProposalChoice = with(DecisionProposalJson) { + ProposalChoice( + id = json.string("id"), + ownerId = json.string("ownerId"), + proposalId = json.string("proposalId"), + revision = json.optionalLong("revision"), + createdAtMs = json.optionalLong("createdAt"), + updatedAtMs = json.optionalLong("updatedAt"), + title = json.string("title"), + description = json.optionalString("description"), + ) + } + } +} + +/** + * The vote among a multiple choice proposal's choices + * (`dash_sdk_multiple_choice_proposal_get_vote`): every choice with its tally while the vote + * runs, and how it ended with every choice's final tally once it did. + */ +data class MultipleChoiceProposalVote( + /** The choices, ordered by choice id; empty for a proposal no choice was entered for. */ + val choices: List, + /** The abstaining votes; null when Platform does not report them. */ + val abstainVoteTally: Long?, + /** The votes for none of the choices; null when Platform does not report them. */ + val noneOfTheChoicesVoteTally: Long?, + /** How the vote ended; null while it runs. */ + val result: Result?, +) { + /** One choice in the vote. */ + data class ChoiceInVote( + /** The choice's document id, base58: the id a vote for it names. */ + val id: String, + /** + * The choice, while the vote runs. Null once it ended: the choices not kept are + * gone, and the kept one is read with [MultipleChoiceProposals.keptChoice]. + */ + val choice: ProposalChoice?, + /** + * The votes towards the choice: so far while the vote runs, final once it ended. + * Null when Platform does not report it. + */ + val voteTally: Long?, + ) + + /** How a finished vote ended. [jsonName] is how the vote JSON names it. */ + enum class Outcome(val jsonName: String) { + /** The choice [Result.keptChoiceId] names was kept as an ordinary document. */ + KEPT_CHOICE("keptChoice"), + + /** The votes for none of the choices outnumbered the leading choice; none was kept. */ + NONE_OF_THE_CHOICES("noneOfTheChoices"), + + /** No choice won; none was kept. */ + NO_WINNER("noWinner"), + ; + + internal companion object { + fun fromJsonName(name: String): Outcome = + entries.firstOrNull { it.jsonName == name } + ?: throw DashSdkError.SerializationError( + "Unknown multiple choice vote outcome: $name", + ) + } + } + + /** The record of a finished vote. */ + data class Result( + val outcome: Outcome, + /** The kept choice's document id, base58; null unless [outcome] is [Outcome.KEPT_CHOICE]. */ + val keptChoiceId: String?, + /** The block that ended the vote. */ + val finalizationBlock: PlatformBlockInfo, + ) + + internal companion object { + /** Decode the vote object. */ + fun fromJson(json: String): MultipleChoiceProposalVote = with(DecisionProposalJson) { + val obj = parseObject(json, "multiple choice proposal vote") + MultipleChoiceProposalVote( + choices = obj.objects("choices").map { entry -> + ChoiceInVote( + id = entry.string("id"), + choice = entry.optionalObj("choice")?.let(ProposalChoice::fromJsonObject), + voteTally = entry.optionalLong("voteTally"), + ) + }, + abstainVoteTally = obj.optionalLong("abstainVoteTally"), + noneOfTheChoicesVoteTally = obj.optionalLong("noneOfTheChoicesVoteTally"), + result = obj.optionalObj("result")?.let { result -> + Result( + outcome = Outcome.fromJsonName(result.string("outcome")), + keptChoiceId = result.optionalString("keptChoiceId"), + finalizationBlock = block(result.obj("finalizationBlock")), + ) + }, + ) + } + } +} + +/** + * A masternode's answer in the vote among a multiple choice proposal's choices: what + * [MultipleChoiceProposals.castVote] takes and [MultipleChoiceProposals.masternodeVote] + * returns. Kotlin mirror of Swift's and rs-dpp's `MultipleChoiceVoteChoice`. + */ +sealed class MultipleChoiceVoteChoice { + /** + * A vote for the choice whose document id is [choiceId], base58 (not the id of the + * identity that entered it). + */ + data class Choice(val choiceId: String) : MultipleChoiceVoteChoice() + + /** A vote that no choice be kept: none is when these outnumber the leading choice. */ + data object NoneOfTheChoices : MultipleChoiceVoteChoice() + + /** An abstention, recorded but playing no part in the result. */ + data object Abstain : MultipleChoiceVoteChoice() + + internal companion object { + /** + * Decode `{"choice": "choice", "choiceId": ""}` or + * `{"choice": "noneOfTheChoices" | "abstain", "choiceId": null}`. + */ + fun fromJson(json: String): MultipleChoiceVoteChoice = with(DecisionProposalJson) { + val obj = parseObject(json, "masternode multiple choice vote") + when (val name = obj.string("choice")) { + "choice" -> Choice(obj.string("choiceId")) + "noneOfTheChoices" -> NoneOfTheChoices + "abstain" -> Abstain + else -> throw DashSdkError.SerializationError( + "Unknown multiple choice vote choice: $name", + ) + } + } + } +} + +/** + * How `dash_sdk_multiple_choice_proposal_cast_vote` takes a [MultipleChoiceVoteChoice]: the + * `vote_choice` byte ([discriminant]: `0` a choice, `1` none of the choices, `2` abstain) and + * the `choice_id`, null for the answers that name none. The header declares no enum, so the + * three values are mirrored here. + */ +internal data class NativeMultipleChoiceVote(val discriminant: Int, val choiceId: String?) + +/** This answer as the `vote_choice` and `choice_id` of the cast vote. */ +internal fun MultipleChoiceVoteChoice.toNative(): NativeMultipleChoiceVote = when (this) { + is MultipleChoiceVoteChoice.Choice -> NativeMultipleChoiceVote(discriminant = 0, choiceId = choiceId) + MultipleChoiceVoteChoice.NoneOfTheChoices -> NativeMultipleChoiceVote(discriminant = 1, choiceId = null) + MultipleChoiceVoteChoice.Abstain -> NativeMultipleChoiceVote(discriminant = 2, choiceId = null) +} + +/** + * The document a new or edited multiple choice proposal points at, as the wallet writes take + * it: the ids as their 32 bytes, like the other ids of + * [MultipleChoiceProposalTransactions]. Kotlin mirror of the C `DescriptionDocumentFFI` and + * Swift's `DescriptionDocumentParams`. Nothing is checked here. + */ +class DescriptionDocumentParams( + /** The document's 32-byte id. */ + val id: ByteArray, + /** The 32-byte id of the contract it lives in. */ + val contractId: ByteArray, + /** Its document type. */ + val documentType: String, +) { + override fun equals(other: Any?): Boolean = + this === other || + other is DescriptionDocumentParams && + id.contentEquals(other.id) && + contractId.contentEquals(other.contractId) && + documentType == other.documentType + + override fun hashCode(): Int = + 31 * (31 * id.contentHashCode() + contractId.contentHashCode()) + documentType.hashCode() + + override fun toString(): String = + "DescriptionDocumentParams(id=${id.toHexString()}, " + + "contractId=${contractId.toHexString()}, documentType=$documentType)" + + private fun ByteArray.toHexString(): String = joinToString("") { "%02x".format(it) } +} + +/** + * What a new multiple choice proposal asks, the input of + * [MultipleChoiceProposalTransactions.create]. Kotlin mirror of the C + * `MultipleChoiceProposalParamsFFI` and Swift's `MultipleChoiceProposalParams`. Nothing is + * checked here: Platform refuses a title of + * more than 128 characters, a url of more than 512, and a proposal that gives neither a + * description document nor a url. + */ +data class MultipleChoiceProposalParams( + /** The question, in one line. */ + val title: String, + /** The document saying what is being decided; null for none. */ + val descriptionDocument: DescriptionDocumentParams? = null, + /** + * Where what is being decided is described, for a proposal that points at no description + * document, or where it is discussed, for one that does; null for none. + */ + val url: String? = null, + /** + * Whether anyone may enter choices; only the proposal's owner may when it is false. It + * never changes. + */ + val open: Boolean, +) + +/** + * What a stored multiple choice proposal changes to, the input of + * [MultipleChoiceProposalTransactions.edit]. A field left as it is here keeps its value. + * Kotlin mirror of the C `MultipleChoiceProposalEditFFI` and Swift's + * `MultipleChoiceProposalEdit`; rs-sdk refuses an edit that changes nothing, and Platform + * one more than two hours after the proposal was created and one that leaves it with + * neither a description document nor a url. + */ +data class MultipleChoiceProposalEdit( + /** The new title; null keeps it. */ + val title: String? = null, + /** What happens to the description document. */ + val descriptionDocument: Change = Change.Keep, + /** What happens to the url. */ + val url: Change = Change.Keep, +) { + /** What an edit does to a field a proposal may not have. */ + sealed interface Change { + /** The field stays as it is. */ + data object Keep : Change + + /** The field becomes [value]. */ + data class Set(val value: T) : Change + + /** The proposal no longer has the field. */ + data object Remove : Change + } +} + +/** + * How `MultipleChoiceProposalEditFFI` says a [MultipleChoiceProposalEdit.Change]: the new + * [value], or null with [remove] set to remove the field, or null without it to keep it. + */ +internal data class NativeChange(val value: T?, val remove: Boolean) + +/** This change as a field and its `remove_` flag of `MultipleChoiceProposalEditFFI`. */ +internal fun MultipleChoiceProposalEdit.Change.toNative(): NativeChange = when (this) { + MultipleChoiceProposalEdit.Change.Keep -> NativeChange(value = null, remove = false) + is MultipleChoiceProposalEdit.Change.Set -> NativeChange(value = value, remove = false) + MultipleChoiceProposalEdit.Change.Remove -> NativeChange(value = null, remove = true) +} + +/** + * An answer to enter for a multiple choice proposal, the input of + * [MultipleChoiceProposalTransactions.enterChoice]. Kotlin mirror of the C `ChoiceParamsFFI` + * and Swift's `ProposalChoiceParams`. Nothing is checked here: Platform refuses a title of + * more than 128 characters and a description of more than 4096. + */ +data class ProposalChoiceParams( + /** The answer, in one line. */ + val title: String, + /** What voting for the answer means; null for none. */ + val description: String? = null, +) + +/** + * A multiple choice proposal Platform confirmed creating, as + * [MultipleChoiceProposalTransactions.create] returns it. + */ +data class CreatedMultipleChoiceProposal( + /** The proposal's id, base58: the id the reads of `Sdk.multipleChoiceProposals` take. */ + val id: String, + /** + * The confirmed document's canonical JSON, the shape the platform wallet's document + * create returns. + */ + val documentJson: String, +) + +/** + * A choice Platform confirmed entering, as [MultipleChoiceProposalTransactions.enterChoice] + * returns it. + */ +data class EnteredProposalChoice( + /** The choice's document id, base58: the id a masternode vote for it names. */ + val id: String, + /** + * The confirmed document's canonical JSON, the shape the platform wallet's document + * create returns. + */ + val documentJson: String, +) + +/** + * The credits a multiple choice proposal amount read returns: rs-sdk-ffi writes them as a + * decimal string, not JSON. Anything else is a [DashSdkError.SerializationError]. + */ +internal fun creditsFromDecimal(decimal: String): ULong = decimal.toULongOrNull() + ?: throw DashSdkError.SerializationError("Malformed credit amount: $decimal") diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/voting/MultipleChoiceProposals.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/voting/MultipleChoiceProposals.kt new file mode 100644 index 00000000000..9c80d62c0bc --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/voting/MultipleChoiceProposals.kt @@ -0,0 +1,299 @@ +package org.dashfoundation.dashsdk.voting + +import org.dashfoundation.dashsdk.Sdk +import org.dashfoundation.dashsdk.errors.DashSdkError +import org.dashfoundation.dashsdk.errors.mapNativeErrors +import org.dashfoundation.dashsdk.ffi.MultipleChoiceProposalsNative +import org.dashfoundation.dashsdk.persistence.toBase58String +import org.dashfoundation.dashsdk.wallet.TeardownGate +import org.dashfoundation.dashsdk.wallet.op +import org.dashfoundation.dashsdk.wallet.opReturningCompletedResult + +/** + * Multiple choice proposals (protocol version 15): questions whose answers are the choices + * entered for them, as `multipleChoiceProposal` and `choice` documents of the decision + * proposals system contract. Reads of proposals and of the vote among their choices, the + * two amounts a proposal and a choice cost, and the masternode vote. Kotlin counterpart of + * the Swift SDK's `SDK+MultipleChoiceProposals.swift`; reach it through + * `Sdk.multipleChoiceProposals`. Creating and editing a proposal and entering a choice go + * through the wallet: [MultipleChoiceProposalTransactions]. + * + * Thin wrapper over [MultipleChoiceProposalsNative]: rs-sdk decides everything (which + * documents are proposals and choices, the vote's contest, the funds and fees), every read + * is proved, and nothing is checked here. Every call runs under the SDK's query gate, so + * closing the SDK waits for it. Ids are base58 strings. A network below protocol version 15 + * has no decision proposals contract, which the calls report as an error. + */ +class MultipleChoiceProposals internal constructor(private val sdk: Sdk) { + + /** The proposal [proposalId], or null when there is none. */ + suspend fun fetch(proposalId: String): MultipleChoiceProposal? = sdk.queryGate.op { + mapNativeErrors { MultipleChoiceProposalsNative.fetch(sdk.handle, proposalId) } + ?.let(MultipleChoiceProposal::fromJson) + } + + /** + * One page of [ownerId]'s proposals, in the order it filed them. + * + * @param limit the most proposals to return, at most 100; 0 for 100. A page shorter + * than the limit is the last. + * @param startAfter the id of the last proposal of the previous page; null for the first. + */ + suspend fun listByOwner( + ownerId: String, + limit: Int = 0, + startAfter: String? = null, + ): List = sdk.queryGate.op { + val json = mapNativeErrors { + MultipleChoiceProposalsNative.listByOwner(sdk.handle, ownerId, limit, startAfter) + } + MultipleChoiceProposal.listFromJson(json.returned("listByOwner")) + } + + /** One page of every proposal, newest first; paging as [listByOwner]. */ + suspend fun listByCreatedAt( + limit: Int = 0, + startAfter: String? = null, + ): List = sdk.queryGate.op { + val json = mapNativeErrors { + MultipleChoiceProposalsNative.listByCreatedAt(sdk.handle, limit, startAfter) + } + MultipleChoiceProposal.listFromJson(json.returned("listByCreatedAt")) + } + + /** + * The vote among [proposalId]'s choices: every choice with its tally while the vote + * runs, and how it ended with every choice's final tally once it did. A proposal no + * choice was entered for has no choices and no result. + */ + suspend fun vote(proposalId: String): MultipleChoiceProposalVote = sdk.queryGate.op { + val json = mapNativeErrors { MultipleChoiceProposalsNative.getVote(sdk.handle, proposalId) } + MultipleChoiceProposalVote.fromJson(json.returned("getVote")) + } + + /** + * The choice [proposalId]'s finished vote kept, an ordinary document of the identity + * that entered it; null while the vote runs, when it kept none of the choices, and for + * a proposal no choice was entered for. + */ + suspend fun keptChoice(proposalId: String): ProposalChoice? = sdk.queryGate.op { + mapNativeErrors { MultipleChoiceProposalsNative.getKeptChoice(sdk.handle, proposalId) } + ?.let(ProposalChoice::fromJson) + } + + /** + * The answer a masternode gave in [proposalId]'s vote, or null when it has not voted in + * it, and once the vote ended. + * + * @param proTxHash the masternode's 32-byte pro_tx_hash in wire order, as [castVote] + * takes it. + */ + suspend fun masternodeVote( + proTxHash: ByteArray, + proposalId: String, + ): MultipleChoiceVoteChoice? = sdk.queryGate.op { + mapNativeErrors { + MultipleChoiceProposalsNative.getMasternodeVote(sdk.handle, proTxHash, proposalId) + }?.let(MultipleChoiceVoteChoice::fromJson) + } + + /** + * What creating one multiple choice proposal adds to the processing fee of its batch, + * in credits (0.2 Dash at protocol version 15). Platform charges the owner it on top of + * the fees; the create does not state it. + */ + suspend fun processingFee(): ULong = sdk.queryGate.op { + creditsFromDecimal( + mapNativeErrors { MultipleChoiceProposalsNative.getProcessingFee(sdk.handle) } + .returned("getProcessingFee"), + ) + } + + /** + * The fund a choice entered now for [proposalId] pays, in credits: the contest's fund, + * raised as the vote fills up. Entering a choice reads and states it itself; this is + * for showing it beforehand. + */ + suspend fun choiceFundToJoin(proposalId: String): ULong = sdk.queryGate.op { + creditsFromDecimal( + mapNativeErrors { + MultipleChoiceProposalsNative.getChoiceFundToJoin(sdk.handle, proposalId) + }.returned("getChoiceFundToJoin"), + ) + } + + /** + * Vote among [proposalId]'s choices for a masternode and wait for the response: the + * vote is signed with the masternode voting key derived from [votingPrivateKey] and + * broadcast for [proTxHash]. A vote from a wallet that is not a masternode is refused + * by Platform (no voter identity), the expected outcome. + * + * @param proTxHash 32-byte pro_tx_hash in wire order: the orientation `Txid` stores, + * which a parsed ProRegTx yields. NOT the byte order of the hex Core displays, which + * is its reverse (see [VoteCasting.castVote]). + * @param votingPrivateKey 32-byte masternode voting private key; not stored. + */ + suspend fun castVote( + proposalId: String, + choice: MultipleChoiceVoteChoice, + proTxHash: ByteArray, + votingPrivateKey: ByteArray, + ) = sdk.queryGate.op { + val vote = choice.toNative() + mapNativeErrors { + MultipleChoiceProposalsNative.castVote( + sdk.handle, + proposalId, + vote.discriminant, + vote.choiceId, + proTxHash, + votingPrivateKey, + sdk.network.ffiValue, + ) + } + } +} + +/** + * Creating and editing multiple choice proposals and entering their choices through the + * platform wallet: the Kotlin counterpart of Swift's `ManagedPlatformWallet` multiple choice + * proposal slice (`ManagedPlatformWalletMultipleChoiceProposals.swift`). Reach it through + * `PlatformWalletManager.multipleChoiceProposals`; callers thread the wallet handle and the + * manager's `signerHandle` into each call, as for the wallet's document calls. + * + * Each call is one native call (`platform_wallet_multiple_choice_proposal_create` / `_edit` + * / `_enter_choice`): the wallet builds the document (or reads the stored proposal and edits + * it), picks the signing key, broadcasts and waits for Platform to confirm. Nothing is + * decided or checked here. + * + * Cancellation: native code cannot see a coroutine's cancellation, so a write can complete + * after its caller was cancelled. Each call then still returns what Platform confirmed + * (see [opReturningCompletedResult]) instead of throwing, so a paid create or choice is + * never hidden from a caller that would otherwise pay for it again. The coroutine stays + * cancelled: handle the result before the next suspension point. + */ +class MultipleChoiceProposalTransactions internal constructor(private val gate: TeardownGate?) { + + /** + * Create and broadcast a multiple choice proposal of [ownerId] asking what [params] + * says, signed via [signerHandle] with a key the wallet selects. Platform charges the + * owner the processing fee [MultipleChoiceProposals.processingFee] reads on top of the + * fees. + * + * @param walletHandle the handle of the wallet that holds [ownerId]. + * @param ownerId the proposer's 32-byte identity id. + * @return the proposal Platform confirmed: its id and the document's canonical JSON. + */ + suspend fun create( + walletHandle: Long, + ownerId: ByteArray, + params: MultipleChoiceProposalParams, + signerHandle: Long, + ): CreatedMultipleChoiceProposal = gate.opReturningCompletedResult { + val proposalId = ByteArray(ID_SIZE) + val documentJson = mapNativeErrors { + MultipleChoiceProposalsNative.create( + walletHandle, + ownerId, + params.title, + params.descriptionDocument?.id, + params.descriptionDocument?.contractId, + params.descriptionDocument?.documentType, + params.url, + params.open, + signerHandle, + proposalId, + ) + } + CreatedMultipleChoiceProposal(id = proposalId.toBase58String(), documentJson = documentJson) + } + + /** + * Give the proposal [proposalId] of [ownerId] what [edit] changes and broadcast the + * replace, signed via [signerHandle] with a key the wallet selects as [create] does. + * + * The wallet reads the proposal once and puts the edit at the revision after the one + * read: if another edit lands in between, Platform refuses this one (its + * [DashSdkError.consensusError] code is 40106) rather than overwrite it, and the caller + * reads the proposal again before offering the edit anew. rs-sdk refuses an edit that + * changes nothing, and Platform one more than two hours after the proposal was created + * and one that leaves it with neither a description document nor a url. + * + * @param proposalId the proposal's 32-byte id. + * @return the confirmed document's canonical JSON, at its new revision. + * @throws DashSdkError.PlatformWallet.NotFound when there is no such proposal. + */ + suspend fun edit( + walletHandle: Long, + ownerId: ByteArray, + proposalId: ByteArray, + edit: MultipleChoiceProposalEdit, + signerHandle: Long, + ): String = gate.opReturningCompletedResult { + val descriptionDocument = edit.descriptionDocument.toNative() + val url = edit.url.toNative() + mapNativeErrors { + MultipleChoiceProposalsNative.edit( + walletHandle, + ownerId, + proposalId, + edit.title, + descriptionDocument.value?.id, + descriptionDocument.value?.contractId, + descriptionDocument.value?.documentType, + descriptionDocument.remove, + url.value, + url.remove, + signerHandle, + ) + } + } + + /** + * Enter the choice [params] describes, owned by [ownerId], for the proposal + * [proposalId] and broadcast it, signed via [signerHandle] with a key the wallet + * selects as [create] does. The put states the contest fund + * [MultipleChoiceProposals.choiceFundToJoin] reads, paid by the owner on top of the + * fees; the first choice opens the vote. Platform refuses a choice for a proposal that + * is not open from anyone but its owner, and one entered once the vote's join window + * closed. A choice is never edited. + * + * @param ownerId the 32-byte id of the identity entering the choice. + * @param proposalId the proposal's 32-byte id. + * @return the choice Platform confirmed: its id and the document's canonical JSON. + */ + suspend fun enterChoice( + walletHandle: Long, + ownerId: ByteArray, + proposalId: ByteArray, + params: ProposalChoiceParams, + signerHandle: Long, + ): EnteredProposalChoice = gate.opReturningCompletedResult { + val choiceId = ByteArray(ID_SIZE) + val documentJson = mapNativeErrors { + MultipleChoiceProposalsNative.enterChoice( + walletHandle, + ownerId, + proposalId, + params.title, + params.description, + signerHandle, + choiceId, + ) + } + EnteredProposalChoice(id = choiceId.toBase58String(), documentJson = documentJson) + } + + private companion object { + /** The length of the id a create writes back. */ + const val ID_SIZE = 32 + } +} + +/** + * The value a native call returned. Null is reserved for a thrown error (already raised by + * the JNI layer) or an absence the call can report; for a call that always answers, null is + * a broken native result. + */ +private fun T?.returned(call: String): T = this + ?: throw DashSdkError.InternalError("MultipleChoiceProposalsNative.$call returned nothing") diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt index c1ec7960603..fd1a4d10ea9 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt @@ -868,6 +868,16 @@ class PlatformWalletManager( val decisionProposals: org.dashfoundation.dashsdk.voting.DecisionProposalTransactions = org.dashfoundation.dashsdk.voting.DecisionProposalTransactions(teardownGate) + /** + * Multiple choice proposal create and edit, and entering a choice (protocol version + * 15): the multiple choice proposal slice of `ManagedPlatformWallet` + * (`ManagedPlatformWalletMultipleChoiceProposals.swift`). Stateless; callers thread the + * wallet handle and [signerHandle] into each call. Reads and the masternode vote are on + * `Sdk.multipleChoiceProposals`. + */ + val multipleChoiceProposals: org.dashfoundation.dashsdk.voting.MultipleChoiceProposalTransactions = + org.dashfoundation.dashsdk.voting.MultipleChoiceProposalTransactions(teardownGate) + // ── Native manager bundle ───────────────────────────────────────── private val nativeInitialization = initializePlatformWalletNativeManager( diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/voting/MultipleChoiceProposalModelsTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/voting/MultipleChoiceProposalModelsTest.kt new file mode 100644 index 00000000000..221baf7df48 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/voting/MultipleChoiceProposalModelsTest.kt @@ -0,0 +1,338 @@ +package org.dashfoundation.dashsdk.voting + +import org.dashfoundation.dashsdk.errors.DashSdkError +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Decoding of what the multiple choice proposal natives return, and the encoding of what + * they take (the vote choice, an edit's changes). + * + * Rust writes every value (rs-sdk-ffi's `decision_proposal/multiple_choice/json.rs` tests + * pin the same shapes); Kotlin only decodes, so these tests pin the JSON as rs-sdk-ffi + * writes it, key for key. Pure JVM: no native library is loaded. + */ +class MultipleChoiceProposalModelsTest { + + private val proposalId = "8vLzWy3oPYAwJ9W8TjWZ3vSJMy7bDqyuvbMvzQMxVjPN" + private val ownerId = "CQwyTH5AnQ5YQVGeYhBP8ihLdMKKbS6ydzN2E8wRWMNn" + private val choiceId = "5DbLwAxGBzUzo81VewMUwn4b5P4bpv9FNFybi25XB5Bk" + private val otherChoiceId = "4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF" + private val describedId = "7NYmEKQsYtniQRUmxwdPGeVcirMoPh5ZPyAKz8BWFy3r" + private val describedContractId = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec" + + private val proposalJson = """ + {"id":"$proposalId","ownerId":"$ownerId","revision":1, + "createdAt":1700000000000,"updatedAt":1700000000000, + "title":"Which block size?", + "descriptionDocument":{"id":"$describedId","contractId":"$describedContractId","documentType":"post"}, + "url":"https://forum.dash.org/t/block-size","open":true} + """.trimIndent() + + private val choiceJson = """ + {"id":"$choiceId","ownerId":"$ownerId","proposalId":"$proposalId","revision":null, + "createdAt":1700000000000,"updatedAt":null, + "title":"Double it","description":"Twice the size it is today."} + """.trimIndent() + + private val choice = ProposalChoice( + id = choiceId, + ownerId = ownerId, + proposalId = proposalId, + revision = null, + createdAtMs = 1_700_000_000_000, + updatedAtMs = null, + title = "Double it", + description = "Twice the size it is today.", + ) + + @Test + fun shouldDecodeAProposalWithEveryField() { + assertEquals( + MultipleChoiceProposal( + id = proposalId, + ownerId = ownerId, + revision = 1, + createdAtMs = 1_700_000_000_000, + updatedAtMs = 1_700_000_000_000, + title = "Which block size?", + descriptionDocument = MultipleChoiceProposal.DescriptionDocument( + id = describedId, + contractId = describedContractId, + documentType = "post", + ), + url = "https://forum.dash.org/t/block-size", + open = true, + ), + MultipleChoiceProposal.fromJson(proposalJson), + ) + } + + @Test + fun shouldDecodeAnAbsentDescriptionDocumentUrlAndSystemFieldsAsNull() { + val proposal = MultipleChoiceProposal.fromJson( + """ + {"id":"$proposalId","ownerId":"$ownerId","revision":null,"createdAt":null, + "updatedAt":null,"title":"t","descriptionDocument":null,"url":null,"open":false} + """.trimIndent(), + ) + assertNull(proposal.descriptionDocument) + assertNull(proposal.url) + assertNull(proposal.revision) + assertNull(proposal.createdAtMs) + assertNull(proposal.updatedAtMs) + assertEquals(false, proposal.open) + } + + @Test + fun shouldDecodeAListingInItsOrder() { + val second = proposalJson.replace(proposalId, otherChoiceId) + val listing = MultipleChoiceProposal.listFromJson("[$proposalJson,$second]") + assertEquals(listOf(proposalId, otherChoiceId), listing.map { it.id }) + assertEquals(emptyList(), MultipleChoiceProposal.listFromJson("[]")) + } + + @Test + fun shouldDecodeAChoiceWithEveryFieldAndAnAbsentDescriptionAsNull() { + assertEquals(choice, ProposalChoice.fromJson(choiceJson)) + val bare = ProposalChoice.fromJson( + choiceJson.replace("\"Twice the size it is today.\"", "null"), + ) + assertNull(bare.description) + assertNull(bare.revision) + assertNull(bare.updatedAtMs) + } + + @Test + fun shouldDecodeARunningVoteWithItsChoicesAndTallies() { + val vote = MultipleChoiceProposalVote.fromJson( + """ + {"choices":[{"id":"$choiceId","choice":$choiceJson,"voteTally":12}, + {"id":"$otherChoiceId","choice":null,"voteTally":null}], + "abstainVoteTally":3,"noneOfTheChoicesVoteTally":1,"result":null} + """.trimIndent(), + ) + assertEquals( + MultipleChoiceProposalVote( + choices = listOf( + MultipleChoiceProposalVote.ChoiceInVote(id = choiceId, choice = choice, voteTally = 12), + MultipleChoiceProposalVote.ChoiceInVote(id = otherChoiceId, choice = null, voteTally = null), + ), + abstainVoteTally = 3, + noneOfTheChoicesVoteTally = 1, + result = null, + ), + vote, + ) + } + + @Test + fun shouldDecodeHowAFinishedVoteEndedForEveryOutcome() { + val outcomes = listOf( + Triple("keptChoice", "\"$choiceId\"", MultipleChoiceProposalVote.Outcome.KEPT_CHOICE), + Triple("noneOfTheChoices", "null", MultipleChoiceProposalVote.Outcome.NONE_OF_THE_CHOICES), + Triple("noWinner", "null", MultipleChoiceProposalVote.Outcome.NO_WINNER), + ) + for ((name, keptChoiceId, outcome) in outcomes) { + val vote = MultipleChoiceProposalVote.fromJson( + """ + {"choices":[{"id":"$choiceId","choice":null,"voteTally":9}], + "abstainVoteTally":null,"noneOfTheChoicesVoteTally":4, + "result":{"outcome":"$name","keptChoiceId":$keptChoiceId, + "finalizationBlock":{"height":9,"coreHeight":42,"timeMs":9000,"epoch":3}}} + """.trimIndent(), + ) + assertEquals( + name, + MultipleChoiceProposalVote( + choices = listOf( + MultipleChoiceProposalVote.ChoiceInVote(id = choiceId, choice = null, voteTally = 9), + ), + abstainVoteTally = null, + noneOfTheChoicesVoteTally = 4, + result = MultipleChoiceProposalVote.Result( + outcome = outcome, + keptChoiceId = choiceId.takeIf { outcome == MultipleChoiceProposalVote.Outcome.KEPT_CHOICE }, + finalizationBlock = PlatformBlockInfo( + height = 9, + coreHeight = 42, + timeMs = 9_000, + epoch = 3, + ), + ), + ), + vote, + ) + } + assertEquals(3, MultipleChoiceProposalVote.Outcome.entries.size) + } + + @Test + fun shouldDecodeAVoteWithNoChoiceAsEmpty() { + assertEquals( + MultipleChoiceProposalVote( + choices = emptyList(), + abstainVoteTally = null, + noneOfTheChoicesVoteTally = null, + result = null, + ), + MultipleChoiceProposalVote.fromJson( + """{"choices":[],"abstainVoteTally":null,"noneOfTheChoicesVoteTally":null,"result":null}""", + ), + ) + } + + @Test + fun shouldDecodeAMasternodeAnswerForEveryChoice() { + assertEquals( + MultipleChoiceVoteChoice.Choice(choiceId), + MultipleChoiceVoteChoice.fromJson("""{"choice":"choice","choiceId":"$choiceId"}"""), + ) + assertEquals( + MultipleChoiceVoteChoice.NoneOfTheChoices, + MultipleChoiceVoteChoice.fromJson("""{"choice":"noneOfTheChoices","choiceId":null}"""), + ) + assertEquals( + MultipleChoiceVoteChoice.Abstain, + MultipleChoiceVoteChoice.fromJson("""{"choice":"abstain","choiceId":null}"""), + ) + } + + /** The `vote_choice` byte and `choice_id` of `dash_sdk_multiple_choice_proposal_cast_vote`. */ + @Test + fun shouldEncodeTheVoteChoiceAsTheFfiByteAndChoiceId() { + assertEquals( + NativeMultipleChoiceVote(discriminant = 0, choiceId = choiceId), + MultipleChoiceVoteChoice.Choice(choiceId).toNative(), + ) + assertEquals( + NativeMultipleChoiceVote(discriminant = 1, choiceId = null), + MultipleChoiceVoteChoice.NoneOfTheChoices.toNative(), + ) + assertEquals( + NativeMultipleChoiceVote(discriminant = 2, choiceId = null), + MultipleChoiceVoteChoice.Abstain.toNative(), + ) + } + + /** A field and its `remove_` flag of `MultipleChoiceProposalEditFFI`, one shape per change. */ + @Test + fun shouldEncodeEveryChangeAsTheEditTakesIt() { + assertEquals( + NativeChange(value = null, remove = false), + (MultipleChoiceProposalEdit.Change.Keep as MultipleChoiceProposalEdit.Change).toNative(), + ) + assertEquals( + NativeChange(value = "https://forum.dash.org/t/block-size", remove = false), + MultipleChoiceProposalEdit.Change.Set("https://forum.dash.org/t/block-size").toNative(), + ) + assertEquals( + NativeChange(value = null, remove = true), + (MultipleChoiceProposalEdit.Change.Remove as MultipleChoiceProposalEdit.Change).toNative(), + ) + + val described = DescriptionDocumentParams(ByteArray(32) { 5 }, ByteArray(32) { 6 }, "post") + assertEquals( + NativeChange(value = described, remove = false), + MultipleChoiceProposalEdit.Change.Set(described).toNative(), + ) + + val untouched = MultipleChoiceProposalEdit() + assertNull(untouched.title) + assertEquals(MultipleChoiceProposalEdit.Change.Keep, untouched.descriptionDocument) + assertEquals(MultipleChoiceProposalEdit.Change.Keep, untouched.url) + } + + /** The input holds byte arrays, so it compares them by content. */ + @Test + fun shouldCompareADescriptionDocumentParamsByItsContent() { + val described = DescriptionDocumentParams(ByteArray(32) { 5 }, ByteArray(32) { 6 }, "post") + val same = DescriptionDocumentParams(ByteArray(32) { 5 }, ByteArray(32) { 6 }, "post") + assertEquals(described, same) + assertEquals(described.hashCode(), same.hashCode()) + assertNotEquals(described, DescriptionDocumentParams(ByteArray(32) { 7 }, ByteArray(32) { 6 }, "post")) + assertNotEquals(described, DescriptionDocumentParams(ByteArray(32) { 5 }, ByteArray(32) { 7 }, "post")) + assertNotEquals(described, DescriptionDocumentParams(ByteArray(32) { 5 }, ByteArray(32) { 6 }, "note")) + } + + /** The two amounts cross as decimal strings of credits, up to `u64::MAX`. */ + @Test + fun shouldDecodeACreditAmountFromItsDecimalString() { + assertEquals(20_000_000_000uL, creditsFromDecimal("20000000000")) + assertEquals(ULong.MAX_VALUE, creditsFromDecimal("18446744073709551615")) + for (malformed in listOf("", "-1", "2e10", "18446744073709551616", "\"20000000000\"")) { + assertThrows(malformed, DashSdkError.SerializationError::class.java) { + creditsFromDecimal(malformed) + } + } + } + + @Test + fun shouldRefuseJsonMissingARequiredField() { + val error = assertThrows(DashSdkError.SerializationError::class.java) { + MultipleChoiceProposal.fromJson(proposalJson.replace("\"open\"", "\"isOpen\"")) + } + assertTrue(error.message.orEmpty(), error.message.orEmpty().contains("open")) + assertThrows(DashSdkError.SerializationError::class.java) { + ProposalChoice.fromJson(choiceJson.replace("\"proposalId\"", "\"proposal\"")) + } + assertThrows(DashSdkError.SerializationError::class.java) { + MultipleChoiceProposalVote.fromJson( + """{"abstainVoteTally":null,"noneOfTheChoicesVoteTally":null,"result":null}""", + ) + } + } + + @Test + fun shouldRefuseAFieldOfTheWrongType() { + assertThrows(DashSdkError.SerializationError::class.java) { + MultipleChoiceProposal.fromJson(proposalJson.replace("\"open\":true", "\"open\":\"true\"")) + } + assertThrows(DashSdkError.SerializationError::class.java) { + MultipleChoiceProposal.fromJson( + proposalJson.replace(Regex("\"descriptionDocument\":\\{[^}]*\\}"), "\"descriptionDocument\":\"post\""), + ) + } + assertThrows(DashSdkError.SerializationError::class.java) { + MultipleChoiceProposalVote.fromJson( + """{"choices":["$choiceId"],"abstainVoteTally":null, + "noneOfTheChoicesVoteTally":null,"result":null}""", + ) + } + } + + @Test + fun shouldRefuseAnUnknownOutcomeOrChoice() { + assertThrows(DashSdkError.SerializationError::class.java) { + MultipleChoiceProposalVote.fromJson( + """{"choices":[],"abstainVoteTally":null,"noneOfTheChoicesVoteTally":null, + "result":{"outcome":"tied","keptChoiceId":null, + "finalizationBlock":{"height":9,"coreHeight":42,"timeMs":9000,"epoch":3}}}""", + ) + } + assertThrows(DashSdkError.SerializationError::class.java) { + MultipleChoiceVoteChoice.fromJson("""{"choice":"maybe","choiceId":null}""") + } + // A vote for a choice names it. + assertThrows(DashSdkError.SerializationError::class.java) { + MultipleChoiceVoteChoice.fromJson("""{"choice":"choice","choiceId":null}""") + } + } + + @Test + fun shouldRefuseTextThatIsNotJson() { + assertThrows(DashSdkError.SerializationError::class.java) { + MultipleChoiceProposal.listFromJson("not json") + } + assertThrows(DashSdkError.SerializationError::class.java) { + MultipleChoiceProposal.listFromJson(proposalJson) + } + assertThrows(DashSdkError.SerializationError::class.java) { + ProposalChoice.fromJson("[]") + } + } +} diff --git a/packages/rs-platform-wallet-ffi/src/decision_proposal.rs b/packages/rs-platform-wallet-ffi/src/decision_proposal.rs index 1b6784d9217..465a35a2a1f 100644 --- a/packages/rs-platform-wallet-ffi/src/decision_proposal.rs +++ b/packages/rs-platform-wallet-ffi/src/decision_proposal.rs @@ -81,7 +81,7 @@ pub struct DecisionProposalEditFFI { /// # Safety /// `ptr` must be null or point to a NUL-terminated string that outlives /// the call. -unsafe fn required_string( +pub(crate) unsafe fn required_string( ptr: *const c_char, field: &str, ) -> Result { diff --git a/packages/rs-platform-wallet-ffi/src/lib.rs b/packages/rs-platform-wallet-ffi/src/lib.rs index 7689e70b984..a7eedf9f7cf 100644 --- a/packages/rs-platform-wallet-ffi/src/lib.rs +++ b/packages/rs-platform-wallet-ffi/src/lib.rs @@ -65,6 +65,7 @@ pub mod masternode_update_service; pub mod masternode_withdrawal; pub mod memory_explorer; pub mod mnemonic_words; +pub mod multiple_choice_proposal; pub mod parse_state_transition; pub mod persistence; pub mod platform_address_sync; @@ -153,6 +154,7 @@ pub use manager::*; pub use manager_diagnostics::*; pub use memory_explorer::*; pub use mnemonic_words::*; +pub use multiple_choice_proposal::*; pub use persistence::*; pub use platform_address_sync::*; pub use platform_address_types::*; diff --git a/packages/rs-platform-wallet-ffi/src/multiple_choice_proposal.rs b/packages/rs-platform-wallet-ffi/src/multiple_choice_proposal.rs new file mode 100644 index 00000000000..a19abcf5caa --- /dev/null +++ b/packages/rs-platform-wallet-ffi/src/multiple_choice_proposal.rs @@ -0,0 +1,872 @@ +//! FFI bindings for multiple choice proposal create and edit, and for +//! entering a choice, on `IdentityWallet` (protocol version 15). +//! +//! Thin: each function reads its C arguments, calls +//! `IdentityWallet::create_multiple_choice_proposal_with_signer`, +//! `IdentityWallet::edit_multiple_choice_proposal_with_signer` or +//! `IdentityWallet::enter_choice_with_signer` on the platform-wallet 8 MB +//! worker stack, and writes the confirmed document back. rs-sdk and the +//! wallet decide everything else: the documents' properties, the contest +//! fund a choice states, the signing key, refusing an edit that changes +//! nothing, and the revision an edit is put at. + +use std::ffi::CString; +use std::os::raw::c_char; +use std::ptr; +use std::slice; + +use dash_sdk::platform::decision_proposals::multiple_choice::{ + ChoiceInput, DescriptionDocument, MultipleChoiceProposalEdit, MultipleChoiceProposalInput, +}; +use dpp::document::{Document, DocumentV0Getters}; +use dpp::prelude::Identifier; +use platform_wallet::PlatformWalletError; +use rs_sdk_ffi::{SignerHandle, VTableSigner}; + +use crate::check_ptr; +use crate::dashpay_profile::decode_opt_c_str; +use crate::decision_proposal::required_string; +use crate::document::confirmed_document_to_json; +use crate::error::*; +use crate::handle::*; +use crate::runtime::block_on_worker; +use crate::types::read_identifier; +use crate::{unwrap_option_or_return, unwrap_result_or_return}; + +/// The document a multiple choice proposal points at for what is being +/// decided. Every field is required. Platform refuses a document that is +/// not of a moderated type the elected team of its contract may delete. +#[repr(C)] +pub struct DescriptionDocumentFFI { + /// The document's 32-byte id. + pub id: *const u8, + /// The 32-byte id of the contract it lives in. + pub contract_id: *const u8, + /// Its document type, NUL-terminated UTF-8. + pub document_type: *const c_char, +} + +/// What a new multiple choice proposal asks +/// (`platform_wallet_multiple_choice_proposal_create`). Platform refuses +/// values outside the limits noted here when the proposal is created, and +/// a proposal that gives neither a description document nor a url; +/// nothing is checked before. +#[repr(C)] +pub struct MultipleChoiceProposalParamsFFI { + /// The question, in one line: 1 to 128 characters. NUL-terminated + /// UTF-8, required. + pub title: *const c_char, + /// The document saying what is being decided; null for none. + pub description_document: *const DescriptionDocumentFFI, + /// Where what is being decided is described, for a proposal that + /// points at no description document, or where it is discussed, for + /// one that does: a URI of at most 512 characters. NUL-terminated + /// UTF-8; null for none. + pub url: *const c_char, + /// Whether anyone may enter choices; only the proposal's owner may + /// when it is false. It never changes. + pub open: bool, +} + +/// What a multiple choice proposal changes to +/// (`platform_wallet_multiple_choice_proposal_edit`). A field left null +/// keeps its value. Platform accepts the edit for two hours after the +/// proposal was created, and refuses one that leaves it with neither a +/// description document nor a url; whether it is open never changes. +#[repr(C)] +pub struct MultipleChoiceProposalEditFFI { + /// The new title, NUL-terminated UTF-8; null keeps it. + pub title: *const c_char, + /// The new description document; null keeps it, unless + /// `remove_description_document` is set. + pub description_document: *const DescriptionDocumentFFI, + /// Removes the description document, leaving the proposal described + /// at its url alone. Setting it together with a non-null + /// `description_document` is refused with `ErrorInvalidParameter`. + pub remove_description_document: bool, + /// The new url, NUL-terminated UTF-8; null keeps it, unless + /// `remove_url` is set. + pub url: *const c_char, + /// Removes the url. Setting it together with a non-null `url` is + /// refused with `ErrorInvalidParameter`. + pub remove_url: bool, +} + +/// An answer to enter for a multiple choice proposal +/// (`platform_wallet_multiple_choice_proposal_enter_choice`). Platform +/// refuses values outside the limits noted here; nothing is checked +/// before. +#[repr(C)] +pub struct ChoiceParamsFFI { + /// The answer, in one line: 1 to 128 characters. NUL-terminated + /// UTF-8, required. + pub title: *const c_char, + /// What voting for the answer means: 1 to 4096 characters. + /// NUL-terminated UTF-8; null for none. + pub description: *const c_char, +} + +/// The description document `description_document` names, `None` when it +/// is null. +/// +/// # Safety +/// `description_document` must be null or point to a +/// `DescriptionDocumentFFI` whose `id` and `contract_id` are null or point +/// to 32 readable bytes and whose `document_type` is null or +/// NUL-terminated. +unsafe fn description_document( + description_document: *const DescriptionDocumentFFI, +) -> Result, PlatformWalletFFIResult> { + let Some(description_document) = description_document.as_ref() else { + return Ok(None); + }; + Ok(Some(DescriptionDocument { + id: read_identifier(description_document.id)?, + contract_id: read_identifier(description_document.contract_id)?, + document_type: required_string( + description_document.document_type, + "description_document.document_type", + )?, + })) +} + +/// `value` as an edit of an optional field: `Some(Some(value))` sets it, +/// `Some(None)` removes it and `None` keeps it. Both at once is refused. +fn set_or_remove( + value: Option, + remove: bool, + field: &str, +) -> Result>, PlatformWalletFFIResult> { + match (value, remove) { + (Some(_), true) => Err(PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorInvalidParameter, + format!("{field} and remove_{field} cannot both be set"), + )), + (Some(value), false) => Ok(Some(Some(value))), + (None, true) => Ok(Some(None)), + (None, false) => Ok(None), + } +} + +/// The proposal input `params` holds. +/// +/// # Safety +/// `params` must point to a `MultipleChoiceProposalParamsFFI` whose +/// pointer fields are null or valid as documented on it. +unsafe fn proposal_input( + params: &MultipleChoiceProposalParamsFFI, +) -> Result { + Ok(MultipleChoiceProposalInput { + title: required_string(params.title, "title")?, + description_document: description_document(params.description_document)?, + url: decode_opt_c_str(params.url)?, + open: params.open, + }) +} + +/// The edit `edit` holds. +/// +/// # Safety +/// `edit` must point to a `MultipleChoiceProposalEditFFI` whose pointer +/// fields are null or valid as documented on it. +unsafe fn proposal_edit( + edit: &MultipleChoiceProposalEditFFI, +) -> Result { + Ok(MultipleChoiceProposalEdit { + title: decode_opt_c_str(edit.title)?, + description_document: set_or_remove( + description_document(edit.description_document)?, + edit.remove_description_document, + "description_document", + )?, + url: set_or_remove(decode_opt_c_str(edit.url)?, edit.remove_url, "url")?, + }) +} + +/// The choice input `params` holds for the proposal `proposal_id`. +/// +/// # Safety +/// `params` must point to a `ChoiceParamsFFI` whose string fields are null +/// or NUL-terminated. +unsafe fn choice_input( + proposal_id: Identifier, + params: &ChoiceParamsFFI, +) -> Result { + Ok(ChoiceInput { + proposal_id, + title: required_string(params.title, "title")?, + description: decode_opt_c_str(params.description)?, + }) +} + +/// Write `json` to `*out_document_json`, handing its ownership to the +/// caller. +/// +/// # Safety +/// `out_document_json` must be a valid, writable pointer. +unsafe fn write_document_json( + json: String, + out_document_json: *mut *mut c_char, +) -> Result<(), PlatformWalletFFIResult> { + // A NUL byte inside the JSON would be a serializer bug; refuse it + // rather than panic across the FFI boundary. + *out_document_json = CString::new(json)?.into_raw(); + Ok(()) +} + +/// Create + broadcast a multiple choice proposal of `owner_identity_id` +/// asking what `params` says, signed via the external `signer_handle`. +/// +/// Goes through `IdentityWallet::create_multiple_choice_proposal_with_signer`: +/// rs-sdk builds the proposal; Platform charges the owner the multiple +/// choice proposal processing fee (0.2 Dash, +/// `dash_sdk_multiple_choice_proposal_get_processing_fee`) on top of the +/// fees, which the create does not state. The wallet signs with the +/// owner's first AUTHENTICATION + ECDSA key at a security level the +/// `multipleChoiceProposal` type accepts that the signer holds, broadcasts +/// on the platform-wallet 8 MB worker stack, waits for the confirmed +/// document and keeps the owner's proven balance. A network below protocol +/// version 15 has no decision proposals, which is an error. +/// +/// On success the proposal's 32-byte id is written to `out_proposal_id`, +/// and the confirmed document's canonical JSON (the shape +/// [`platform_wallet_create_document_with_signer`](crate::platform_wallet_create_document_with_signer) +/// returns) to `*out_document_json`; release it with +/// `platform_wallet_string_free`. On any error `*out_document_json` is +/// left null. A refusal by Platform carries its `consensus_code`. +/// +/// # Safety +/// - `owner_identity_id` must point to 32 readable bytes. +/// - `params` must point to a `MultipleChoiceProposalParamsFFI` whose +/// `title` is a NUL-terminated string, whose `url` is null or one, and +/// whose `description_document` is null or points to a +/// `DescriptionDocumentFFI` with 32 readable bytes at `id` and at +/// `contract_id` and a NUL-terminated `document_type`. +/// - `signer_handle` must be a live signer, which the caller keeps owning. +/// - `out_proposal_id` must point to 32 writable bytes and +/// `out_document_json` must be a valid, writable pointer. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_multiple_choice_proposal_create( + wallet_handle: Handle, + owner_identity_id: *const u8, + params: *const MultipleChoiceProposalParamsFFI, + signer_handle: *mut SignerHandle, + out_proposal_id: *mut u8, + out_document_json: *mut *mut c_char, +) -> PlatformWalletFFIResult { + check_ptr!(params); + check_ptr!(signer_handle); + check_ptr!(out_proposal_id); + check_ptr!(out_document_json); + *out_document_json = ptr::null_mut(); + + let owner_id = unwrap_result_or_return!(read_identifier(owner_identity_id)); + let input = unwrap_result_or_return!(proposal_input(&*params)); + let signer_addr = signer_handle as usize; + + let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { + let identity_wallet = wallet.identity().clone(); + block_on_worker(async move { + let signer: &VTableSigner = &*(signer_addr as *const VTableSigner); + let confirmed: Document = identity_wallet + .create_multiple_choice_proposal_with_signer(&owner_id, &input, signer) + .await?; + let json = confirmed_document_to_json(&confirmed)?; + Ok::<_, PlatformWalletError>((confirmed.id(), json)) + }) + }); + let result = unwrap_option_or_return!(option); + let (proposal_id, document_json) = unwrap_result_or_return!(result); + + unwrap_result_or_return!(write_document_json(document_json, out_document_json)); + slice::from_raw_parts_mut(out_proposal_id, 32).copy_from_slice(proposal_id.as_slice()); + PlatformWalletFFIResult::ok() +} + +/// Give the multiple choice proposal `proposal_id` of `owner_identity_id` +/// what `edit` changes, and broadcast the replace, signed via the external +/// `signer_handle`. +/// +/// Goes through `IdentityWallet::edit_multiple_choice_proposal_with_signer`, +/// which reads the proposal once, applies the edit and the revision after +/// the one read (rs-sdk refuses an edit that changes nothing), signs with a +/// key chosen as the create chooses it and puts that document. It never +/// reads the proposal again before the put: if another edit lands in +/// between, Platform refuses this one (`consensus_code` 40106, +/// `InvalidDocumentRevisionError`) rather than overwrite it, and the host +/// reads the proposal again before offering the edit anew. Platform also +/// refuses an edit more than two hours after the proposal was created, and +/// one that leaves it with neither a description document nor a url. +/// +/// On success the confirmed document's canonical JSON, at its new +/// revision, is written to `*out_document_json`; release it with +/// `platform_wallet_string_free`. On any error it is left null. +/// +/// # Errors +/// - `NotFound` when there is no such proposal; +/// - `ErrorInvalidParameter` when the proposal belongs to another +/// identity, the edit changes nothing, `url` and `remove_url` are both +/// set, or `description_document` and `remove_description_document` are +/// both set; +/// - `ErrorInvalidIdentifier` for a `description_document` whose `id` or +/// `contract_id` is null, and `ErrorNullPointer` for one whose +/// `document_type` is; +/// - `ErrorUtf8Conversion` for a string field that is not UTF-8; +/// - a refusal by Platform carries its `consensus_code`. +/// +/// # Safety +/// - `owner_identity_id` and `proposal_id` must each point to 32 readable +/// bytes. +/// - `edit` must point to a `MultipleChoiceProposalEditFFI` whose string +/// fields are null or NUL-terminated and whose `description_document` is +/// null or valid as `platform_wallet_multiple_choice_proposal_create` +/// requires. +/// - `signer_handle` must be a live signer, which the caller keeps owning. +/// - `out_document_json` must be a valid, writable pointer. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_multiple_choice_proposal_edit( + wallet_handle: Handle, + owner_identity_id: *const u8, + proposal_id: *const u8, + edit: *const MultipleChoiceProposalEditFFI, + signer_handle: *mut SignerHandle, + out_document_json: *mut *mut c_char, +) -> PlatformWalletFFIResult { + check_ptr!(edit); + check_ptr!(signer_handle); + check_ptr!(out_document_json); + *out_document_json = ptr::null_mut(); + + let owner_id = unwrap_result_or_return!(read_identifier(owner_identity_id)); + let proposal_id = unwrap_result_or_return!(read_identifier(proposal_id)); + let edit = unwrap_result_or_return!(proposal_edit(&*edit)); + let signer_addr = signer_handle as usize; + + let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { + let identity_wallet = wallet.identity().clone(); + block_on_worker(async move { + let signer: &VTableSigner = &*(signer_addr as *const VTableSigner); + let confirmed: Document = identity_wallet + .edit_multiple_choice_proposal_with_signer(&owner_id, &proposal_id, &edit, signer) + .await?; + confirmed_document_to_json(&confirmed) + }) + }); + let result = unwrap_option_or_return!(option); + let document_json = unwrap_result_or_return!(result); + + unwrap_result_or_return!(write_document_json(document_json, out_document_json)); + PlatformWalletFFIResult::ok() +} + +/// Enter the choice `params` describes, owned by `owner_identity_id`, for +/// the multiple choice proposal `proposal_id`, and broadcast it, signed +/// via the external `signer_handle`. +/// +/// Goes through `IdentityWallet::enter_choice_with_signer`: rs-sdk builds +/// the choice, and its put reads the fund of the contest among the +/// proposal's choices just before it is signed and states it +/// (`dash_sdk_multiple_choice_proposal_get_choice_fund_to_join` reads the +/// same amount), which the owner pays on top of the fees. The first choice +/// opens the vote. Signed, broadcast and kept like +/// `platform_wallet_multiple_choice_proposal_create`. Platform refuses a +/// choice for a proposal that is not open from anyone but its owner, and +/// one entered once the vote's join window closed. A choice is never +/// edited. +/// +/// On success the choice's 32-byte id, the id a masternode vote towards it +/// names, is written to `out_choice_id`, and the confirmed document's +/// canonical JSON to `*out_document_json`; release it with +/// `platform_wallet_string_free`. On any error `*out_document_json` is +/// left null. A refusal by Platform carries its `consensus_code`. +/// +/// # Safety +/// - `owner_identity_id` and `proposal_id` must each point to 32 readable +/// bytes. +/// - `params` must point to a `ChoiceParamsFFI` whose `title` is a +/// NUL-terminated string and whose `description` is null or one. +/// - `signer_handle` must be a live signer, which the caller keeps owning. +/// - `out_choice_id` must point to 32 writable bytes and +/// `out_document_json` must be a valid, writable pointer. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_multiple_choice_proposal_enter_choice( + wallet_handle: Handle, + owner_identity_id: *const u8, + proposal_id: *const u8, + params: *const ChoiceParamsFFI, + signer_handle: *mut SignerHandle, + out_choice_id: *mut u8, + out_document_json: *mut *mut c_char, +) -> PlatformWalletFFIResult { + check_ptr!(params); + check_ptr!(signer_handle); + check_ptr!(out_choice_id); + check_ptr!(out_document_json); + *out_document_json = ptr::null_mut(); + + let owner_id = unwrap_result_or_return!(read_identifier(owner_identity_id)); + let proposal_id = unwrap_result_or_return!(read_identifier(proposal_id)); + let input = unwrap_result_or_return!(choice_input(proposal_id, &*params)); + let signer_addr = signer_handle as usize; + + let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { + let identity_wallet = wallet.identity().clone(); + block_on_worker(async move { + let signer: &VTableSigner = &*(signer_addr as *const VTableSigner); + let confirmed: Document = identity_wallet + .enter_choice_with_signer(&owner_id, &input, signer) + .await?; + let json = confirmed_document_to_json(&confirmed)?; + Ok::<_, PlatformWalletError>((confirmed.id(), json)) + }) + }); + let result = unwrap_option_or_return!(option); + let (choice_id, document_json) = unwrap_result_or_return!(result); + + unwrap_result_or_return!(write_document_json(document_json, out_document_json)); + slice::from_raw_parts_mut(out_choice_id, 32).copy_from_slice(choice_id.as_slice()); + PlatformWalletFFIResult::ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn c_string(value: &str) -> CString { + CString::new(value).expect("no NUL") + } + + fn no_edit() -> MultipleChoiceProposalEditFFI { + MultipleChoiceProposalEditFFI { + title: ptr::null(), + description_document: ptr::null(), + remove_description_document: false, + url: ptr::null(), + remove_url: false, + } + } + + const DOCUMENT_ID: [u8; 32] = [5; 32]; + const CONTRACT_ID: [u8; 32] = [6; 32]; + + fn expected_description_document() -> DescriptionDocument { + DescriptionDocument { + id: Identifier::from(DOCUMENT_ID), + contract_id: Identifier::from(CONTRACT_ID), + document_type: "post".to_string(), + } + } + + #[test] + fn should_read_the_proposal_params() { + let title = c_string("Which block size?"); + let url = c_string("https://forum.dash.org/t/block-size"); + let document_type = c_string("post"); + let described = DescriptionDocumentFFI { + id: DOCUMENT_ID.as_ptr(), + contract_id: CONTRACT_ID.as_ptr(), + document_type: document_type.as_ptr(), + }; + let mut params = MultipleChoiceProposalParamsFFI { + title: title.as_ptr(), + description_document: &described, + url: url.as_ptr(), + open: true, + }; + unsafe { + assert_eq!( + proposal_input(¶ms).expect("reads"), + MultipleChoiceProposalInput { + title: "Which block size?".to_string(), + description_document: Some(expected_description_document()), + url: Some("https://forum.dash.org/t/block-size".to_string()), + open: true, + } + ); + params.url = ptr::null(); + params.description_document = ptr::null(); + params.open = false; + let read = proposal_input(¶ms).expect("reads"); + assert_eq!(read.url, None); + assert_eq!(read.description_document, None); + assert!(!read.open); + params.title = ptr::null(); + let refused = proposal_input(¶ms).expect_err("no title"); + assert_eq!(refused.code, PlatformWalletFFIResultCode::ErrorNullPointer); + } + } + + /// A description document is all three of its fields or nothing: one + /// with a null field cannot be read. + #[test] + fn should_refuse_a_description_document_with_a_null_field() { + let document_type = c_string("post"); + let complete = DescriptionDocumentFFI { + id: DOCUMENT_ID.as_ptr(), + contract_id: CONTRACT_ID.as_ptr(), + document_type: document_type.as_ptr(), + }; + unsafe { + for no_id in [ + DescriptionDocumentFFI { + id: ptr::null(), + ..complete + }, + DescriptionDocumentFFI { + contract_id: ptr::null(), + ..complete + }, + ] { + let refused = description_document(&no_id).expect_err("no id"); + assert_eq!( + refused.code, + PlatformWalletFFIResultCode::ErrorInvalidIdentifier + ); + } + let refused = description_document(&DescriptionDocumentFFI { + document_type: ptr::null(), + ..complete + }) + .expect_err("no document type"); + assert_eq!(refused.code, PlatformWalletFFIResultCode::ErrorNullPointer); + } + } + + #[test] + fn should_read_the_edit_and_refuse_a_field_both_set_and_removed() { + let title = c_string("Which block size, then?"); + let url = c_string("https://example.com"); + let document_type = c_string("post"); + let described = DescriptionDocumentFFI { + id: DOCUMENT_ID.as_ptr(), + contract_id: CONTRACT_ID.as_ptr(), + document_type: document_type.as_ptr(), + }; + unsafe { + assert_eq!( + proposal_edit(&no_edit()).expect("reads"), + MultipleChoiceProposalEdit::default() + ); + assert_eq!( + proposal_edit(&MultipleChoiceProposalEditFFI { + title: title.as_ptr(), + description_document: &described, + url: url.as_ptr(), + ..no_edit() + }) + .expect("reads"), + MultipleChoiceProposalEdit { + title: Some("Which block size, then?".to_string()), + description_document: Some(Some(expected_description_document())), + url: Some(Some("https://example.com".to_string())), + } + ); + assert_eq!( + proposal_edit(&MultipleChoiceProposalEditFFI { + remove_description_document: true, + remove_url: true, + ..no_edit() + }) + .expect("reads"), + MultipleChoiceProposalEdit { + title: None, + description_document: Some(None), + url: Some(None), + } + ); + for contradictory in [ + MultipleChoiceProposalEditFFI { + url: url.as_ptr(), + remove_url: true, + ..no_edit() + }, + MultipleChoiceProposalEditFFI { + description_document: &described, + remove_description_document: true, + ..no_edit() + }, + ] { + let refused = proposal_edit(&contradictory).expect_err("contradictory"); + assert_eq!( + refused.code, + PlatformWalletFFIResultCode::ErrorInvalidParameter + ); + } + } + } + + #[test] + fn should_read_the_choice_params() { + let proposal_id = Identifier::from([7; 32]); + let title = c_string("Double it"); + let description = c_string("Twice the size it is today."); + let mut params = ChoiceParamsFFI { + title: title.as_ptr(), + description: description.as_ptr(), + }; + unsafe { + assert_eq!( + choice_input(proposal_id, ¶ms).expect("reads"), + ChoiceInput { + proposal_id, + title: "Double it".to_string(), + description: Some("Twice the size it is today.".to_string()), + } + ); + params.description = ptr::null(); + assert_eq!( + choice_input(proposal_id, ¶ms) + .expect("reads") + .description, + None + ); + params.title = ptr::null(); + let refused = choice_input(proposal_id, ¶ms).expect_err("no title"); + assert_eq!(refused.code, PlatformWalletFFIResultCode::ErrorNullPointer); + } + } + + #[test] + fn should_refuse_a_string_that_is_not_utf8() { + let not_utf8 = CString::new(vec![0xff, 0xfe]).expect("no NUL"); + let proposal_id = Identifier::from([7; 32]); + unsafe { + let refused = proposal_input(&MultipleChoiceProposalParamsFFI { + title: not_utf8.as_ptr(), + description_document: ptr::null(), + url: ptr::null(), + open: true, + }) + .expect_err("not UTF-8"); + assert_eq!( + refused.code, + PlatformWalletFFIResultCode::ErrorUtf8Conversion + ); + let not_utf8_type = DescriptionDocumentFFI { + id: DOCUMENT_ID.as_ptr(), + contract_id: CONTRACT_ID.as_ptr(), + document_type: not_utf8.as_ptr(), + }; + for edit in [ + MultipleChoiceProposalEditFFI { + title: not_utf8.as_ptr(), + ..no_edit() + }, + MultipleChoiceProposalEditFFI { + url: not_utf8.as_ptr(), + ..no_edit() + }, + MultipleChoiceProposalEditFFI { + description_document: ¬_utf8_type, + ..no_edit() + }, + ] { + let refused = proposal_edit(&edit).expect_err("not UTF-8"); + assert_eq!( + refused.code, + PlatformWalletFFIResultCode::ErrorUtf8Conversion + ); + } + for params in [ + ChoiceParamsFFI { + title: not_utf8.as_ptr(), + description: ptr::null(), + }, + ChoiceParamsFFI { + title: not_utf8.as_ptr(), + description: not_utf8.as_ptr(), + }, + ] { + let refused = choice_input(proposal_id, ¶ms).expect_err("not UTF-8"); + assert_eq!( + refused.code, + PlatformWalletFFIResultCode::ErrorUtf8Conversion + ); + } + } + } + + /// Every pointer is checked before the wallet is looked up, and the + /// JSON out-param is left null on the way out. + #[test] + fn should_refuse_null_pointers() { + let id = [0u8; 32]; + let mut out_id = [0u8; 32]; + let mut out_json: *mut c_char = ptr::null_mut(); + let title = c_string("Which block size?"); + let url = c_string("https://forum.dash.org/t/block-size"); + let params = MultipleChoiceProposalParamsFFI { + title: title.as_ptr(), + description_document: ptr::null(), + url: url.as_ptr(), + open: true, + }; + let edit = no_edit(); + let choice = ChoiceParamsFFI { + title: title.as_ptr(), + description: ptr::null(), + }; + // A dangling but non-null signer: every call below returns at a + // pointer check before the signer is read. + let signer = ptr::NonNull::::dangling().as_ptr(); + unsafe { + for result in [ + platform_wallet_multiple_choice_proposal_create( + 0, + id.as_ptr(), + ptr::null(), + signer, + out_id.as_mut_ptr(), + &mut out_json, + ), + platform_wallet_multiple_choice_proposal_create( + 0, + id.as_ptr(), + ¶ms, + ptr::null_mut(), + out_id.as_mut_ptr(), + &mut out_json, + ), + platform_wallet_multiple_choice_proposal_create( + 0, + id.as_ptr(), + ¶ms, + signer, + ptr::null_mut(), + &mut out_json, + ), + platform_wallet_multiple_choice_proposal_create( + 0, + id.as_ptr(), + ¶ms, + signer, + out_id.as_mut_ptr(), + ptr::null_mut(), + ), + platform_wallet_multiple_choice_proposal_edit( + 0, + id.as_ptr(), + id.as_ptr(), + ptr::null(), + signer, + &mut out_json, + ), + platform_wallet_multiple_choice_proposal_edit( + 0, + id.as_ptr(), + id.as_ptr(), + &edit, + ptr::null_mut(), + &mut out_json, + ), + platform_wallet_multiple_choice_proposal_edit( + 0, + id.as_ptr(), + id.as_ptr(), + &edit, + signer, + ptr::null_mut(), + ), + platform_wallet_multiple_choice_proposal_enter_choice( + 0, + id.as_ptr(), + id.as_ptr(), + ptr::null(), + signer, + out_id.as_mut_ptr(), + &mut out_json, + ), + platform_wallet_multiple_choice_proposal_enter_choice( + 0, + id.as_ptr(), + id.as_ptr(), + &choice, + ptr::null_mut(), + out_id.as_mut_ptr(), + &mut out_json, + ), + platform_wallet_multiple_choice_proposal_enter_choice( + 0, + id.as_ptr(), + id.as_ptr(), + &choice, + signer, + ptr::null_mut(), + &mut out_json, + ), + platform_wallet_multiple_choice_proposal_enter_choice( + 0, + id.as_ptr(), + id.as_ptr(), + &choice, + signer, + out_id.as_mut_ptr(), + ptr::null_mut(), + ), + ] { + assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorNullPointer); + } + assert!(out_json.is_null()); + } + } + + /// An argument the wallet cannot read is refused before the wallet is + /// looked up, and the JSON out-param is left null. + #[test] + fn should_refuse_unreadable_arguments_before_the_wallet_is_looked_up() { + let id = [0u8; 32]; + let mut out_id = [0u8; 32]; + let mut out_json: *mut c_char = ptr::null_mut(); + let no_title = MultipleChoiceProposalParamsFFI { + title: ptr::null(), + description_document: ptr::null(), + url: ptr::null(), + open: true, + }; + let url = c_string("https://example.com"); + let contradictory = MultipleChoiceProposalEditFFI { + url: url.as_ptr(), + remove_url: true, + ..no_edit() + }; + let untitled_choice = ChoiceParamsFFI { + title: ptr::null(), + description: ptr::null(), + }; + let signer = ptr::NonNull::::dangling().as_ptr(); + unsafe { + let created = platform_wallet_multiple_choice_proposal_create( + 0, + id.as_ptr(), + &no_title, + signer, + out_id.as_mut_ptr(), + &mut out_json, + ); + assert_eq!(created.code, PlatformWalletFFIResultCode::ErrorNullPointer); + let edited = platform_wallet_multiple_choice_proposal_edit( + 0, + id.as_ptr(), + id.as_ptr(), + &contradictory, + signer, + &mut out_json, + ); + assert_eq!( + edited.code, + PlatformWalletFFIResultCode::ErrorInvalidParameter + ); + let entered = platform_wallet_multiple_choice_proposal_enter_choice( + 0, + id.as_ptr(), + id.as_ptr(), + &untitled_choice, + signer, + out_id.as_mut_ptr(), + &mut out_json, + ); + assert_eq!(entered.code, PlatformWalletFFIResultCode::ErrorNullPointer); + assert!(out_json.is_null()); + } + } +} diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/decision_proposal.rs b/packages/rs-platform-wallet/src/wallet/identity/network/decision_proposal.rs index cb6b3d61bc4..9308184ba60 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/decision_proposal.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/decision_proposal.rs @@ -59,7 +59,9 @@ impl IdentityWallet { where S: Signer + Send + Sync, { - let document_type = self.decision_proposal_document_type().await?; + let document_type = self + .decision_proposals_document_type(PROPOSAL_DOCUMENT_TYPE_NAME) + .await?; let DecisionProposalDocument { document, entropy } = self .sdk .build_decision_proposal(*owner_identity_id, input) @@ -110,7 +112,9 @@ impl IdentityWallet { where S: Signer + Send + Sync, { - let document_type = self.decision_proposal_document_type().await?; + let document_type = self + .decision_proposals_document_type(PROPOSAL_DOCUMENT_TYPE_NAME) + .await?; let read = self.sdk.fetch_decision_proposal(*proposal_id).await?; let replacement = decision_proposal_replacement(owner_identity_id, proposal_id, read, edit)?; @@ -129,15 +133,18 @@ impl IdentityWallet { .await?) } - /// The `proposal` document type of the decision proposals contract, - /// which rs-sdk resolves (refusing a network below protocol version - /// 15). The contract is registered for the proof check that follows - /// the put. - async fn decision_proposal_document_type(&self) -> Result { + /// The document type `document_type_name` of the decision proposals + /// contract, which rs-sdk resolves (refusing a network below protocol + /// version 15). The contract is registered for the proof check that + /// follows the put. + pub(super) async fn decision_proposals_document_type( + &self, + document_type_name: &str, + ) -> Result { let contract = self.sdk.fetch_decision_proposals_contract().await?; self.register_contract_for_proof_verification(&contract); contract - .document_type_cloned_for_name(PROPOSAL_DOCUMENT_TYPE_NAME) + .document_type_cloned_for_name(document_type_name) .map_err(|e| PlatformWalletError::Sdk(dash_sdk::Error::Protocol(e.into()))) } } @@ -176,7 +183,7 @@ fn decision_proposal_replacement( } #[cfg(test)] -mod tests { +pub(super) mod tests { use super::super::signing_key::tests::{ available, identity, lock_checking_signer, wallet_with_signing_keys_on, }; @@ -209,15 +216,15 @@ mod tests { const CREATED_AT: u64 = 1_700_000_000_000; /// The identity contract nonce Platform reports for the owner. - const STORED_NONCE: u64 = 4; + pub(crate) const STORED_NONCE: u64 = 4; const NEW_TITLE: &str = "Raise the block size to 4 MB?"; /// The owner identity `wallet_with_signing_keys_on` holds. - fn owner() -> Identifier { + pub(crate) fn owner() -> Identifier { Identifier::default() } - fn proposals_contract() -> Arc { + pub(crate) fn proposals_contract() -> Arc { Arc::new( load_system_data_contract( SystemDataContract::DecisionProposals, @@ -264,7 +271,7 @@ mod tests { /// Serves the bundled decision proposals contract (nothing else), the /// way a host's context provider does, so rs-sdk resolves it without a /// network fetch or a dump directory. - struct ProposalsContractProvider(Arc); + pub(crate) struct ProposalsContractProvider(pub(crate) Arc); impl dash_sdk::platform::ContextProvider for ProposalsContractProvider { fn get_data_contract( @@ -313,7 +320,7 @@ mod tests { /// A mock SDK at the latest protocol version that resolves the /// decision proposals contract. A request without an expectation /// fails. - fn proposals_sdk() -> dash_sdk::Sdk { + pub(crate) fn proposals_sdk() -> dash_sdk::Sdk { dash_sdk::SdkBuilder::new_mock() .with_version(PlatformVersion::latest()) .with_context_provider(ProposalsContractProvider(proposals_contract())) @@ -344,7 +351,7 @@ mod tests { /// Signs with a fixed signature, so the transition it signs is known. #[derive(Debug)] - struct FixedSignatureSigner; + pub(crate) struct FixedSignatureSigner; #[async_trait] impl Signer for FixedSignatureSigner { diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs index ac7eba762cd..5544717563a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs @@ -48,6 +48,7 @@ mod identity_handle; mod key_limits; mod key_selection; mod loading; +mod multiple_choice_proposal; mod register_from_addresses; mod registration; mod state_transition_summary; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/multiple_choice_proposal.rs b/packages/rs-platform-wallet/src/wallet/identity/network/multiple_choice_proposal.rs new file mode 100644 index 00000000000..e0099e4ffb7 --- /dev/null +++ b/packages/rs-platform-wallet/src/wallet/identity/network/multiple_choice_proposal.rs @@ -0,0 +1,664 @@ +//! Multiple choice proposal create and edit, and entering a choice, on +//! `IdentityWallet` (protocol version 15). +//! +//! rs-sdk decides what a multiple choice proposal and a choice are +//! (`dash_sdk::platform::decision_proposals::multiple_choice`): the +//! properties they are created with, refusing an edit that changes +//! nothing, and the revision an edit moves to. The put of a choice states +//! the fund of the contest it joins, read just before it is signed. These +//! operations orchestrate: they resolve the contract, read the proposal, +//! select the signing key, put the document and keep the owner's proven +//! balance, through the steps the yes/no proposal create in +//! `decision_proposal.rs` takes. +//! +//! An edit reads the proposal once and puts that document at the revision +//! after the one it read, exactly as a yes/no proposal edit does: when +//! another edit lands in between, Platform refuses this one +//! (`InvalidDocumentRevisionError`, 40106) instead of letting it overwrite +//! what it never saw. A choice is never edited. + +use dash_sdk::platform::decision_proposals::multiple_choice::{ + build_multiple_choice_proposal_edit, ChoiceInput, MultipleChoiceProposalEdit, + MultipleChoiceProposalInput, +}; +use dash_sdk::platform::decision_proposals::DecisionProposalDocument; +use dpp::decision_proposal::multiple_choice::CHOICE_DOCUMENT_TYPE_NAME; +use dpp::decision_proposal::{ + DECISION_PROPOSALS_CONTRACT_ID, MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, +}; +use dpp::document::{Document, DocumentV0Getters}; +use dpp::identity::signer::Signer; +use dpp::identity::IdentityPublicKey; +use dpp::prelude::Identifier; + +use crate::error::PlatformWalletError; + +use super::*; + +impl IdentityWallet { + /// Create a multiple choice proposal of `owner_identity_id` asking + /// what `input` says, and return it as Platform stored it. + /// + /// rs-sdk builds the proposal (`Sdk::build_multiple_choice_proposal`). + /// Platform charges the owner the multiple choice proposal processing + /// fee (0.2 Dash, `Sdk::multiple_choice_proposal_processing_fee`) on + /// top of the fees; the create does not state it. The transition is + /// signed with the owner's first AUTHENTICATION + ECDSA key at a + /// security level the `multipleChoiceProposal` type accepts that + /// `signer` can sign with, and the owner's balance the proof carries + /// is kept. Platform refuses a proposal that gives neither a + /// description document nor a url. The proposal's id is the id of the + /// returned document. + /// + /// A network below protocol version 15 has no decision proposals + /// contract, which is an error. SDK and Platform failures, a refusal + /// included, arrive as [`PlatformWalletError::Sdk`]. + pub async fn create_multiple_choice_proposal_with_signer( + &self, + owner_identity_id: &Identifier, + input: &MultipleChoiceProposalInput, + signer: &S, + ) -> Result + where + S: Signer + Send + Sync, + { + let document_type = self + .decision_proposals_document_type(MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME) + .await?; + let DecisionProposalDocument { document, entropy } = self + .sdk + .build_multiple_choice_proposal(*owner_identity_id, input) + .await?; + let signing_key = self + .select_document_signing_key(owner_identity_id, &document_type, signer) + .await?; + Ok(self + .put_document_keeping_owner_balance( + &document, + document_type, + Some(entropy.to_buffer()), + signing_key, + signer, + None, + ) + .await?) + } + + /// Give the multiple choice proposal `proposal_id` of + /// `owner_identity_id` what `edit` changes, and return it as Platform + /// stored it. + /// + /// Reads the proposal once, applies the edit with rs-sdk's + /// `build_multiple_choice_proposal_edit` (which refuses an edit that + /// changes nothing and moves to the revision after the one read) and + /// puts that document as a replace, signed and kept like + /// [`Self::create_multiple_choice_proposal_with_signer`]. The put + /// carries the revision after the one read: if another edit lands in + /// between, Platform refuses this one (`InvalidDocumentRevisionError`, + /// 40106) rather than overwrite it, and the caller reads the proposal + /// again. Platform also refuses an edit more than two hours after the + /// proposal was created, and one that leaves it with neither a + /// description document nor a url. + /// + /// # Errors + /// * [`PlatformWalletError::DecisionProposalNotFound`] when there is + /// no such proposal; + /// * [`PlatformWalletError::InvalidParameter`] when the proposal + /// belongs to another identity, or the edit changes nothing; + /// * [`PlatformWalletError::Sdk`] for SDK and Platform failures, + /// Platform's refusals included. + pub async fn edit_multiple_choice_proposal_with_signer( + &self, + owner_identity_id: &Identifier, + proposal_id: &Identifier, + edit: &MultipleChoiceProposalEdit, + signer: &S, + ) -> Result + where + S: Signer + Send + Sync, + { + let document_type = self + .decision_proposals_document_type(MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME) + .await?; + let read = self + .sdk + .fetch_multiple_choice_proposal(*proposal_id) + .await?; + let replacement = + multiple_choice_proposal_replacement(owner_identity_id, proposal_id, read, edit)?; + let signing_key = self + .select_document_signing_key(owner_identity_id, &document_type, signer) + .await?; + Ok(self + .put_document_keeping_owner_balance( + &replacement, + document_type, + None, + signing_key, + signer, + None, + ) + .await?) + } + + /// Enter the choice `input` describes, owned by `owner_identity_id`, + /// for the multiple choice proposal it names, and return it as + /// Platform stored it. + /// + /// rs-sdk builds the choice (`Sdk::build_choice`), and its put reads + /// the fund of the contest among the proposal's choices just before + /// it is signed and states it (`Sdk::choice_fund_to_join`, doubled + /// once the vote holds 250 choices and again for every 50 more); the + /// owner pays it on top of the fees. The first choice opens the vote. + /// The transition is signed and the owner's proven balance kept like + /// [`Self::create_multiple_choice_proposal_with_signer`]. Platform + /// refuses a choice for a proposal that is not open from anyone but + /// its owner, and one entered once the vote's join window closed. The + /// choice's id, which a masternode vote towards it names, is the id of + /// the returned document. + /// + /// A network below protocol version 15 has no decision proposals + /// contract, which is an error. SDK and Platform failures, a refusal + /// included, arrive as [`PlatformWalletError::Sdk`]. + pub async fn enter_choice_with_signer( + &self, + owner_identity_id: &Identifier, + input: &ChoiceInput, + signer: &S, + ) -> Result + where + S: Signer + Send + Sync, + { + let document_type = self + .decision_proposals_document_type(CHOICE_DOCUMENT_TYPE_NAME) + .await?; + let DecisionProposalDocument { document, entropy } = + self.sdk.build_choice(*owner_identity_id, input).await?; + let signing_key = self + .select_document_signing_key(owner_identity_id, &document_type, signer) + .await?; + Ok(self + .put_document_keeping_owner_balance( + &document, + document_type, + Some(entropy.to_buffer()), + signing_key, + signer, + None, + ) + .await?) + } +} + +/// The document an edit of the multiple choice proposal `proposal_id` +/// puts: `read`, the proposal as read once for this edit, with what `edit` +/// changes and the revision after the one read. A proposal that is not +/// there, or that belongs to an identity other than `owner_identity_id`, +/// is refused. +fn multiple_choice_proposal_replacement( + owner_identity_id: &Identifier, + proposal_id: &Identifier, + read: Option, + edit: &MultipleChoiceProposalEdit, +) -> Result { + let proposal = read.ok_or(PlatformWalletError::DecisionProposalNotFound { + proposal_id: *proposal_id, + })?; + if proposal.owner_id() != *owner_identity_id { + return Err(PlatformWalletError::InvalidParameter(format!( + "multiple choice proposal {proposal_id} belongs to identity {}, not to \ + {owner_identity_id}", + proposal.owner_id() + ))); + } + build_multiple_choice_proposal_edit( + &DECISION_PROPOSALS_CONTRACT_ID, + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + &proposal, + edit, + ) + .map_err(|error| match error { + // rs-sdk refuses the edit itself (one that changes nothing) with + // its own text; anything else keeps its SDK error. + dash_sdk::Error::Generic(message) => PlatformWalletError::InvalidParameter(message), + other => PlatformWalletError::Sdk(other), + }) +} + +#[cfg(test)] +mod tests { + use super::super::decision_proposal::tests::{ + owner, proposals_contract, proposals_sdk, FixedSignatureSigner, STORED_NONCE, + }; + use super::super::signing_key::tests::{ + available, identity, lock_checking_signer, wallet_with_signing_keys_on, + }; + use super::*; + use crate::error::SIGNER_KEY_UNAVAILABLE_PREFIX; + use crate::wallet::persister::NoPlatformPersistence; + use dash_sdk::dapi_grpc::platform::v0::{ + GetContestedResourceVoteStateRequest, GetDocumentsRequest, + }; + use dash_sdk::drive::config::DEFAULT_QUERY_LIMIT; + use dash_sdk::drive::query::vote_poll_vote_state_query::{ + ContestedDocumentVotePollDriveQuery, ContestedDocumentVotePollDriveQueryResultType, + }; + use dash_sdk::platform::decision_proposals::multiple_choice::{ + build_multiple_choice_proposal_document, multiple_choice_proposal_vote_poll, + DescriptionDocument, + }; + use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; + use dash_sdk::platform::{DocumentQuery, Query}; + use dash_sdk::query_types::{Contenders, IdentityContractNonceFetcher}; + use dpp::data_contract::accessors::v0::DataContractV0Getters; + use dpp::decision_proposal::multiple_choice::proposal_properties; + use dpp::document::{DocumentV0Setters, INITIAL_REVISION}; + use dpp::identity::accessors::IdentityGettersV0; + use dpp::identity::{KeyType, Purpose, SecurityLevel}; + use dpp::platform_value::{Bytes32, Value}; + use dpp::state_transition::batch_transition::methods::v0::DocumentsBatchTransitionMethodsV0; + use dpp::state_transition::batch_transition::BatchTransition; + use dpp::version::PlatformVersion; + use dpp::voting::contender_structs::ContenderWithSerializedDocument; + use dpp::ProtocolError; + use std::sync::Arc; + + const CREATED_AT: u64 = 1_700_000_000_000; + const NEW_URL: &str = "https://forum.dash.org/t/block-size-4mb"; + + fn description_document() -> DescriptionDocument { + DescriptionDocument { + id: Identifier::from([5; 32]), + contract_id: Identifier::from([6; 32]), + document_type: "post".to_string(), + } + } + + fn input() -> MultipleChoiceProposalInput { + MultipleChoiceProposalInput { + title: "Which block size?".to_string(), + description_document: Some(description_document()), + url: Some("https://forum.dash.org/t/block-size".to_string()), + open: true, + } + } + + fn choice_input() -> ChoiceInput { + ChoiceInput { + proposal_id: Identifier::from([7; 32]), + title: "Double it".to_string(), + description: Some("Twice the size it is today.".to_string()), + } + } + + /// A multiple choice proposal of `owner_id` built by rs-sdk, as + /// Platform stores it at its first revision. + fn stored_proposal(owner_id: Identifier) -> Document { + let mut document = build_multiple_choice_proposal_document( + &proposals_contract(), + owner_id, + &input(), + Bytes32::new([9; 32]), + ) + .expect("builds") + .document; + document.set_created_at(Some(CREATED_AT)); + document.set_updated_at(Some(CREATED_AT)); + document + } + + /// Points the proposal at its url alone, with a new url. + fn readdress() -> MultipleChoiceProposalEdit { + MultipleChoiceProposalEdit { + description_document: Some(None), + url: Some(Some(NEW_URL.to_string())), + ..Default::default() + } + } + + /// The query rs-sdk reads the proposal `proposal_id` with. + fn proposal_query(proposal_id: Identifier) -> DocumentQuery { + DocumentQuery::new( + proposals_contract(), + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + ) + .expect("the multiple choice proposal type") + .with_document_id(&proposal_id) + } + + /// [`proposals_sdk`] answering a read of the proposal `proposal_id` + /// with `stored`. + async fn sdk_storing(proposal_id: Identifier, stored: Option) -> dash_sdk::Sdk { + let mut sdk = proposals_sdk(); + sdk.mock() + .expect_fetch(proposal_query(proposal_id), stored) + .await + .expect("expects the proposal read"); + sdk + } + + /// Times the proposal `proposal_id` was read through `sdk`. + async fn times_read(sdk: &mut dash_sdk::Sdk, proposal_id: Identifier) -> usize { + let request: GetDocumentsRequest = Query::::query( + &proposal_query(proposal_id), + &sdk.query_settings(), + ) + .expect("encodes"); + sdk.mock().request_count(&request).await + } + + /// The query the put of a choice for `proposal_id` counts the choices + /// already entered with, to price the fund it states. + fn contest_fund_query(proposal_id: Identifier) -> ContestedDocumentVotePollDriveQuery { + ContestedDocumentVotePollDriveQuery { + vote_poll: multiple_choice_proposal_vote_poll(proposal_id), + result_type: ContestedDocumentVotePollDriveQueryResultType::VoteTally, + offset: None, + limit: Some(DEFAULT_QUERY_LIMIT), + start_at: None, + allow_include_locked_and_abstaining_vote_tally: false, + } + } + + /// The owner's first key, the one the wallet signs with. + fn owners_first_key() -> IdentityPublicKey { + identity( + Purpose::AUTHENTICATION, + SecurityLevel::CRITICAL, + KeyType::ECDSA_SECP256K1, + ) + .public_keys() + .get(&1) + .expect("the owner's first key") + .clone() + } + + #[test] + fn should_move_the_proposal_read_to_its_next_revision_with_only_the_edited_fields() { + let read = stored_proposal(owner()); + let replacement = multiple_choice_proposal_replacement( + &owner(), + &read.id(), + Some(read.clone()), + &readdress(), + ) + .expect("edits"); + + assert_eq!(replacement.id(), read.id()); + assert_eq!(replacement.owner_id(), owner()); + assert_eq!(replacement.revision(), Some(INITIAL_REVISION + 1)); + assert_eq!(replacement.created_at(), Some(CREATED_AT)); + let mut expected = read.properties().clone(); + for property in [ + proposal_properties::DESCRIPTION_ID, + proposal_properties::DESCRIPTION_CONTRACT_ID, + proposal_properties::DESCRIPTION_DOCUMENT_TYPE, + ] { + expected.remove(property); + } + expected.insert( + proposal_properties::URL.to_string(), + Value::Text(NEW_URL.to_string()), + ); + assert_eq!(replacement.properties(), &expected); + } + + #[test] + fn should_refuse_an_edit_that_changes_nothing() { + let read = stored_proposal(owner()); + let error = multiple_choice_proposal_replacement( + &owner(), + &read.id(), + Some(read.clone()), + &MultipleChoiceProposalEdit { + title: Some(input().title), + description_document: Some(Some(description_document())), + url: Some(input().url), + }, + ) + .expect_err("changes nothing"); + assert!( + matches!(error, PlatformWalletError::InvalidParameter(ref message) + if message.contains("changes nothing")), + "{error:?}" + ); + } + + /// The edit reads the proposal once, then puts exactly that document + /// at the revision after the one read: the broadcast the put sends is + /// the replace built from it, signed with the owner's first eligible + /// key at the next identity contract nonce. The mock answers no + /// broadcast, so the put fails after sending it. + #[tokio::test] + async fn should_put_the_proposal_read_once_at_the_revision_after_it() { + let read = stored_proposal(owner()); + let proposal_id = read.id(); + let mut sdk = sdk_storing(proposal_id, Some(read.clone())).await; + sdk.mock() + .expect_fetch( + (owner(), DECISION_PROPOSALS_CONTRACT_ID), + Some(IdentityContractNonceFetcher(STORED_NONCE)), + ) + .await + .expect("expects the nonce read"); + let wallet = + wallet_with_signing_keys_on(sdk.clone(), Arc::new(NoPlatformPersistence)).await; + + let error = wallet + .identity() + .edit_multiple_choice_proposal_with_signer( + &owner(), + &proposal_id, + &readdress(), + &FixedSignatureSigner, + ) + .await + .expect_err("the mock answers no broadcast"); + assert!(matches!(error, PlatformWalletError::Sdk(_)), "{error:?}"); + assert_eq!(times_read(&mut sdk, proposal_id).await, 1); + + // The proposal as the read returned it: the mock answers with the + // document re-encoded, so its values come back as Platform returns + // them rather than as the builder made them. + let returned = sdk + .fetch_multiple_choice_proposal(proposal_id) + .await + .expect("reads") + .expect("the stored proposal"); + let contract = proposals_contract(); + let document_type = contract + .document_type_for_name(MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME) + .expect("the multiple choice proposal type"); + let mut put_document = returned; + for property in [ + proposal_properties::DESCRIPTION_ID, + proposal_properties::DESCRIPTION_CONTRACT_ID, + proposal_properties::DESCRIPTION_DOCUMENT_TYPE, + ] { + put_document.remove(property); + } + put_document.set(proposal_properties::URL, Value::Text(NEW_URL.to_string())); + put_document.set_revision(Some(INITIAL_REVISION + 1)); + let replace = BatchTransition::new_document_replacement_transition_from_document( + put_document, + document_type, + &owners_first_key(), + STORED_NONCE + 1, + 0, + None, + &FixedSignatureSigner, + PlatformVersion::latest(), + None, + ) + .await + .expect("the replace"); + let broadcast = replace + .broadcast_request_for_state_transition() + .expect("serializes"); + assert!( + sdk.mock().request_count(&broadcast).await > 0, + "the put must broadcast the replace of the proposal as read, at revision {}", + INITIAL_REVISION + 1 + ); + } + + #[tokio::test] + async fn should_refuse_to_edit_a_proposal_that_does_not_exist() { + let proposal_id = Identifier::from([4; 32]); + let mut sdk = sdk_storing(proposal_id, None).await; + let wallet = + wallet_with_signing_keys_on(sdk.clone(), Arc::new(NoPlatformPersistence)).await; + + let error = wallet + .identity() + .edit_multiple_choice_proposal_with_signer( + &owner(), + &proposal_id, + &readdress(), + &available(&[]), + ) + .await + .expect_err("no such proposal"); + assert!( + matches!(error, PlatformWalletError::DecisionProposalNotFound { proposal_id: id } + if id == proposal_id), + "{error:?}" + ); + assert_eq!(times_read(&mut sdk, proposal_id).await, 1); + } + + #[tokio::test] + async fn should_refuse_to_edit_a_proposal_of_another_identity() { + let read = stored_proposal(Identifier::from([3; 32])); + let proposal_id = read.id(); + let sdk = sdk_storing(proposal_id, Some(read)).await; + let wallet = wallet_with_signing_keys_on(sdk, Arc::new(NoPlatformPersistence)).await; + + let error = wallet + .identity() + .edit_multiple_choice_proposal_with_signer( + &owner(), + &proposal_id, + &readdress(), + &available(&[]), + ) + .await + .expect_err("another identity's proposal"); + assert!( + matches!(error, PlatformWalletError::InvalidParameter(ref message) + if message.contains("belongs to identity")), + "{error:?}" + ); + } + + /// The create builds the proposal through rs-sdk, then asks the signer + /// for a key with the wallet manager lock released: a signer that holds + /// no key keeps the structured key-unavailable failure, and an owner + /// the wallet does not hold is refused. + #[tokio::test] + async fn should_create_only_for_an_owner_with_a_key_the_signer_holds() { + let wallet = + wallet_with_signing_keys_on(proposals_sdk(), Arc::new(NoPlatformPersistence)).await; + let signer = lock_checking_signer(wallet.identity()); + + let error = wallet + .identity() + .create_multiple_choice_proposal_with_signer(&owner(), &input(), &signer) + .await + .expect_err("no key available"); + assert!( + matches!(error, PlatformWalletError::Sdk(dash_sdk::Error::Protocol(ProtocolError::Generic(ref message))) + if message.starts_with(SIGNER_KEY_UNAVAILABLE_PREFIX)), + "{error:?}" + ); + + let stranger = Identifier::from([5; 32]); + let error = wallet + .identity() + .create_multiple_choice_proposal_with_signer(&stranger, &input(), &available(&[1])) + .await + .expect_err("not an identity of this wallet"); + assert!( + matches!(error, PlatformWalletError::IdentityNotFound(id) if id == stranger), + "{error:?}" + ); + } + + /// Entering a choice selects its key as a proposal create does: a + /// signer that holds no key keeps the structured key-unavailable + /// failure, and an owner the wallet does not hold is refused. + #[tokio::test] + async fn should_enter_a_choice_only_for_an_owner_with_a_key_the_signer_holds() { + let wallet = + wallet_with_signing_keys_on(proposals_sdk(), Arc::new(NoPlatformPersistence)).await; + let signer = lock_checking_signer(wallet.identity()); + + let error = wallet + .identity() + .enter_choice_with_signer(&owner(), &choice_input(), &signer) + .await + .expect_err("no key available"); + assert!( + matches!(error, PlatformWalletError::Sdk(dash_sdk::Error::Protocol(ProtocolError::Generic(ref message))) + if message.starts_with(SIGNER_KEY_UNAVAILABLE_PREFIX)), + "{error:?}" + ); + + let stranger = Identifier::from([5; 32]); + let error = wallet + .identity() + .enter_choice_with_signer(&stranger, &choice_input(), &available(&[1])) + .await + .expect_err("not an identity of this wallet"); + assert!( + matches!(error, PlatformWalletError::IdentityNotFound(id) if id == stranger), + "{error:?}" + ); + } + + /// The put of a choice counts the choices the vote already holds, to + /// state the fund of the contest, before it reserves the identity + /// contract nonce and broadcasts. The mock holds no choice yet and + /// answers no broadcast, so the put fails after sending it. + #[tokio::test] + async fn should_read_the_contest_fund_before_putting_a_choice() { + let proposal_id = choice_input().proposal_id; + let mut sdk = proposals_sdk(); + sdk.mock() + .expect_fetch_many::<_, ContenderWithSerializedDocument, _, Contenders>( + contest_fund_query(proposal_id), + Some(Contenders::default()), + ) + .await + .expect("expects the contest read"); + sdk.mock() + .expect_fetch( + (owner(), DECISION_PROPOSALS_CONTRACT_ID), + Some(IdentityContractNonceFetcher(STORED_NONCE)), + ) + .await + .expect("expects the nonce read"); + let wallet = + wallet_with_signing_keys_on(sdk.clone(), Arc::new(NoPlatformPersistence)).await; + + let error = wallet + .identity() + .enter_choice_with_signer(&owner(), &choice_input(), &FixedSignatureSigner) + .await + .expect_err("the mock answers no broadcast"); + // The put got as far as the broadcast, which the mock does not answer + assert!( + matches!(error, PlatformWalletError::Sdk(_)) + && format!("{error:?}").contains("BroadcastStateTransitionRequest"), + "{error:?}" + ); + + let contest_read: GetContestedResourceVoteStateRequest = + Query::::query( + &contest_fund_query(proposal_id), + &sdk.query_settings(), + ) + .expect("encodes"); + assert_eq!(sdk.mock().request_count(&contest_read).await, 1); + } +} diff --git a/packages/rs-sdk-ffi/src/decision_proposal/json.rs b/packages/rs-sdk-ffi/src/decision_proposal/json.rs index 84c7f10b88e..30fcb853251 100644 --- a/packages/rs-sdk-ffi/src/decision_proposal/json.rs +++ b/packages/rs-sdk-ffi/src/decision_proposal/json.rs @@ -67,7 +67,7 @@ pub(super) fn proposals_json(documents: Documents) -> Result JsonValue { +pub(super) fn block_json(block: &BlockInfo) -> JsonValue { json!({ "height": block.height, "coreHeight": block.core_height, diff --git a/packages/rs-sdk-ffi/src/decision_proposal/mod.rs b/packages/rs-sdk-ffi/src/decision_proposal/mod.rs index 5f7491b5843..877ef814515 100644 --- a/packages/rs-sdk-ffi/src/decision_proposal/mod.rs +++ b/packages/rs-sdk-ffi/src/decision_proposal/mod.rs @@ -27,9 +27,11 @@ //! contest (see `crate::voting::masternode_vote`). mod json; +mod multiple_choice; mod queries; mod transitions; +pub use multiple_choice::*; pub use queries::*; pub use transitions::*; diff --git a/packages/rs-sdk-ffi/src/decision_proposal/multiple_choice/json.rs b/packages/rs-sdk-ffi/src/decision_proposal/multiple_choice/json.rs new file mode 100644 index 00000000000..5a8de4932dc --- /dev/null +++ b/packages/rs-sdk-ffi/src/decision_proposal/multiple_choice/json.rs @@ -0,0 +1,490 @@ +//! The JSON the multiple choice proposal functions return, one shape per kind, written from +//! the rs-sdk types. Field names follow the wasm bindings +//! (`packages/wasm-sdk/src/decision_proposals/multiple_choice.rs`) and the yes/no proposal +//! JSON of `super::super::json`: camelCase, base58 ids, absent values as null. + +use super::super::json::block_json; +use crate::FFIError; +use dash_sdk::dpp::document::{Document, DocumentV0Getters}; +use dash_sdk::dpp::platform_value::string_encoding::Encoding; +use dash_sdk::dpp::voting::vote_info_storage::contested_document_vote_poll_winner_info::ContestedDocumentVotePollWinnerInfo; +use dash_sdk::platform::decision_proposals::multiple_choice::{ + Choice, MultipleChoiceProposal, MultipleChoiceProposalVote, MultipleChoiceVoteChoice, +}; +use drive_proof_verifier::types::Documents; +use serde::Serialize; +use serde_json::{json, Value as JsonValue}; + +/// The document a multiple choice proposal points at. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct DescriptionDocumentJson<'a> { + /// The document, base58. + id: String, + /// The contract it lives in, base58. + contract_id: String, + document_type: &'a str, +} + +/// A multiple choice proposal as every multiple choice proposal read returns it. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct MultipleChoiceProposalJson<'a> { + /// The proposal's id, base58. + id: String, + /// The proposer, base58. + owner_id: String, + revision: Option, + /// Milliseconds since the Unix epoch. + created_at: Option, + /// Milliseconds since the Unix epoch. + updated_at: Option, + title: &'a str, + description_document: Option>, + url: Option<&'a str>, + open: bool, +} + +/// A choice as every read of one returns it. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct ChoiceJson<'a> { + /// The choice's id, base58: the id a masternode vote towards it names. + id: String, + /// The identity that entered it, base58. + owner_id: String, + /// The proposal it answers, base58. + proposal_id: String, + revision: Option, + /// Milliseconds since the Unix epoch. + created_at: Option, + /// Milliseconds since the Unix epoch. + updated_at: Option, + title: &'a str, + description: Option<&'a str>, +} + +/// `document`, a `multipleChoiceProposal` document, as the proposal JSON object. +pub(super) fn multiple_choice_proposal_json(document: Document) -> Result { + let proposal = MultipleChoiceProposal::from_document(document)?; + let document = &proposal.document; + Ok(serde_json::to_value(MultipleChoiceProposalJson { + id: document.id().to_string(Encoding::Base58), + owner_id: document.owner_id().to_string(Encoding::Base58), + revision: document.revision(), + created_at: document.created_at(), + updated_at: document.updated_at(), + title: &proposal.title, + description_document: proposal.description_document.as_ref().map(|described| { + DescriptionDocumentJson { + id: described.id.to_string(Encoding::Base58), + contract_id: described.contract_id.to_string(Encoding::Base58), + document_type: &described.document_type, + } + }), + url: proposal.url.as_deref(), + open: proposal.open, + })?) +} + +/// One page of a listing as a JSON array of proposals, in the listing's order. +pub(super) fn multiple_choice_proposals_json(documents: Documents) -> Result { + documents + .into_values() + .flatten() + .map(multiple_choice_proposal_json) + .collect::, _>>() + .map(JsonValue::Array) +} + +/// `choice` as the choice JSON object. +fn choice_json(choice: &Choice) -> Result { + let document = &choice.document; + Ok(serde_json::to_value(ChoiceJson { + id: document.id().to_string(Encoding::Base58), + owner_id: document.owner_id().to_string(Encoding::Base58), + proposal_id: choice.proposal_id.to_string(Encoding::Base58), + revision: document.revision(), + created_at: document.created_at(), + updated_at: document.updated_at(), + title: &choice.title, + description: choice.description.as_deref(), + })?) +} + +/// `document`, a `choice` document, as the choice JSON object. +pub(super) fn choice_document_json(document: Document) -> Result { + choice_json(&Choice::from_document(document)?) +} + +/// The vote among a proposal's choices: every choice by id with its tally, the other +/// tallies, and how the vote ended once it did. +pub(super) fn multiple_choice_proposal_vote_json( + vote: &MultipleChoiceProposalVote, +) -> Result { + let choices = vote + .choices + .iter() + .map(|(choice_id, choice_in_vote)| { + Ok(json!({ + "id": choice_id.to_string(Encoding::Base58), + "choice": choice_in_vote.choice.as_ref().map(choice_json).transpose()?, + "voteTally": choice_in_vote.vote_tally, + })) + }) + .collect::, FFIError>>()?; + let result = vote.winner.as_ref().map(|(winner, finalization_block)| { + let outcome = match winner { + ContestedDocumentVotePollWinnerInfo::WonByIdentity(_) => "keptChoice", + ContestedDocumentVotePollWinnerInfo::Locked => "noneOfTheChoices", + ContestedDocumentVotePollWinnerInfo::NoWinner => "noWinner", + }; + json!({ + "outcome": outcome, + "keptChoiceId": vote + .kept_choice_id() + .map(|choice_id| choice_id.to_string(Encoding::Base58)), + "finalizationBlock": block_json(finalization_block), + }) + }); + Ok(json!({ + "choices": choices, + "abstainVoteTally": vote.abstain_vote_tally, + "noneOfTheChoicesVoteTally": vote.none_of_the_choices_vote_tally, + "result": result, + })) +} + +/// The name a masternode's answer is written with: `"choice"`, `"noneOfTheChoices"` or +/// `"abstain"`. +pub(super) fn vote_choice_name(vote_choice: &MultipleChoiceVoteChoice) -> &'static str { + match vote_choice { + MultipleChoiceVoteChoice::Choice(_) => "choice", + MultipleChoiceVoteChoice::NoneOfTheChoices => "noneOfTheChoices", + MultipleChoiceVoteChoice::Abstain => "abstain", + } +} + +/// A masternode's answer; `None` when it has not voted in the vote. +pub(super) fn masternode_vote_json( + vote_choice: Option, +) -> Option { + vote_choice.map(|vote_choice| { + let choice_id = match vote_choice { + MultipleChoiceVoteChoice::Choice(choice_id) => { + Some(choice_id.to_string(Encoding::Base58)) + } + MultipleChoiceVoteChoice::NoneOfTheChoices | MultipleChoiceVoteChoice::Abstain => None, + }; + json!({ + "choice": vote_choice_name(&vote_choice), + "choiceId": choice_id, + }) + }) +} + +#[cfg(test)] +mod tests { + use super::super::super::json::tests::{proposals_contract, CREATED_AT}; + use super::*; + use dash_sdk::dpp::block::block_info::BlockInfo; + use dash_sdk::dpp::block::epoch::Epoch; + use dash_sdk::dpp::decision_proposal::multiple_choice::proposal_properties; + use dash_sdk::dpp::document::DocumentV0Setters; + use dash_sdk::dpp::platform_value::{Bytes32, Identifier}; + use dash_sdk::platform::decision_proposals::multiple_choice::{ + build_choice_document, build_multiple_choice_proposal_document, ChoiceInVote, ChoiceInput, + DescriptionDocument, MultipleChoiceProposalInput, + }; + use std::collections::BTreeMap; + + fn base58(id: Identifier) -> String { + id.to_string(Encoding::Base58) + } + + fn input() -> MultipleChoiceProposalInput { + MultipleChoiceProposalInput { + title: "Which block size?".to_string(), + description_document: Some(DescriptionDocument { + id: Identifier::from([5; 32]), + contract_id: Identifier::from([6; 32]), + document_type: "post".to_string(), + }), + url: Some("https://forum.dash.org/t/block-size".to_string()), + open: true, + } + } + + /// A multiple choice proposal of identity `[3; 32]` built by rs-sdk, as Platform stores + /// it. + fn stored_proposal(input: &MultipleChoiceProposalInput) -> Document { + let mut document = build_multiple_choice_proposal_document( + &proposals_contract(), + Identifier::from([3; 32]), + input, + Bytes32::new([9; 32]), + ) + .expect("builds") + .document; + document.set_created_at(Some(CREATED_AT)); + document.set_updated_at(Some(CREATED_AT)); + document + } + + /// A choice of identity `[4; 32]` for the proposal `[7; 32]`, as Platform stores it. + fn stored_choice(description: Option<&str>) -> Document { + let mut document = build_choice_document( + &proposals_contract(), + Identifier::from([4; 32]), + &ChoiceInput { + proposal_id: Identifier::from([7; 32]), + title: "Double it".to_string(), + description: description.map(str::to_string), + }, + Bytes32::new([8; 32]), + ) + .expect("builds") + .document; + document.set_created_at(Some(CREATED_AT)); + document + } + + fn block(height: u64) -> BlockInfo { + BlockInfo { + time_ms: 1_000 * height, + height, + core_height: 42, + epoch: Epoch::new(3).expect("an epoch"), + } + } + + #[test] + fn should_write_a_proposal_with_every_field() { + let document = stored_proposal(&input()); + let id = document.id(); + assert_eq!( + multiple_choice_proposal_json(document).expect("a proposal"), + json!({ + "id": base58(id), + "ownerId": base58(Identifier::from([3; 32])), + "revision": 1, + "createdAt": CREATED_AT, + "updatedAt": CREATED_AT, + "title": "Which block size?", + "descriptionDocument": { + "id": base58(Identifier::from([5; 32])), + "contractId": base58(Identifier::from([6; 32])), + "documentType": "post", + }, + "url": "https://forum.dash.org/t/block-size", + "open": true, + }) + ); + } + + #[test] + fn should_write_an_absent_description_document_and_url_as_null() { + let document = stored_proposal(&MultipleChoiceProposalInput { + description_document: None, + url: None, + open: false, + ..input() + }); + let proposal = multiple_choice_proposal_json(document).expect("a proposal"); + assert_eq!(proposal["descriptionDocument"], JsonValue::Null); + assert_eq!(proposal["url"], JsonValue::Null); + assert_eq!(proposal["open"], json!(false)); + } + + #[test] + fn should_refuse_a_document_that_is_not_a_multiple_choice_proposal() { + let mut document = stored_proposal(&input()); + document.remove(proposal_properties::TITLE); + assert!(multiple_choice_proposal_json(document).is_err()); + assert!(choice_document_json(stored_proposal(&input())).is_err()); + } + + #[test] + fn should_write_a_listing_in_its_order_without_absent_entries() { + let first = stored_proposal(&input()); + let mut second = stored_proposal(&input()); + second.set_id(Identifier::from([1; 32])); + let documents: Documents = [ + (first.id(), Some(first.clone())), + (Identifier::from([2; 32]), None), + (second.id(), Some(second.clone())), + ] + .into_iter() + .collect(); + let listing = multiple_choice_proposals_json(documents).expect("proposals"); + let ids: Vec<&str> = listing + .as_array() + .expect("an array") + .iter() + .map(|proposal| proposal["id"].as_str().expect("an id")) + .collect(); + assert_eq!(ids, [base58(first.id()), base58(second.id())]); + assert_eq!( + multiple_choice_proposals_json(Documents::default()).expect("empty"), + json!([]) + ); + } + + #[test] + fn should_write_a_choice_with_every_field_and_an_absent_description_as_null() { + let document = stored_choice(Some("Twice the size it is today.")); + let id = document.id(); + assert_eq!( + choice_document_json(document).expect("a choice"), + json!({ + "id": base58(id), + "ownerId": base58(Identifier::from([4; 32])), + "proposalId": base58(Identifier::from([7; 32])), + "revision": null, + "createdAt": CREATED_AT, + "updatedAt": null, + "title": "Double it", + "description": "Twice the size it is today.", + }) + ); + assert_eq!( + choice_document_json(stored_choice(None)).expect("a choice")["description"], + JsonValue::Null + ); + } + + #[test] + fn should_write_a_running_vote_with_its_choices_and_tallies() { + let double = stored_choice(Some("Twice the size it is today.")); + let left_id = Identifier::from([2; 32]); + let vote = MultipleChoiceProposalVote { + choices: BTreeMap::from([ + ( + double.id(), + ChoiceInVote { + choice: Some(Choice::from_document(double.clone()).expect("reads")), + vote_tally: Some(12), + }, + ), + ( + left_id, + ChoiceInVote { + choice: None, + vote_tally: None, + }, + ), + ]), + abstain_vote_tally: Some(3), + none_of_the_choices_vote_tally: Some(1), + winner: None, + }; + // The choices are written in the order of their ids + let mut choices = vec![ + ( + double.id(), + json!({ + "id": base58(double.id()), + "choice": choice_document_json(double.clone()).expect("a choice"), + "voteTally": 12, + }), + ), + ( + left_id, + json!({"id": base58(left_id), "choice": null, "voteTally": null}), + ), + ]; + choices.sort_by_key(|(id, _)| *id); + let choices: Vec = choices.into_iter().map(|(_, choice)| choice).collect(); + assert_eq!( + multiple_choice_proposal_vote_json(&vote).expect("writes"), + json!({ + "choices": choices, + "abstainVoteTally": 3, + "noneOfTheChoicesVoteTally": 1, + "result": null, + }) + ); + } + + #[test] + fn should_write_how_a_finished_vote_ended() { + let kept_id = Identifier::from([2; 32]); + let finished = |winner| MultipleChoiceProposalVote { + choices: BTreeMap::from([( + kept_id, + ChoiceInVote { + choice: None, + vote_tally: Some(9), + }, + )]), + abstain_vote_tally: None, + none_of_the_choices_vote_tally: Some(4), + winner: Some((winner, block(9))), + }; + let finalization_block = + json!({"height": 9, "coreHeight": 42, "timeMs": 9_000, "epoch": 3}); + for (winner, outcome, kept_choice_id) in [ + ( + ContestedDocumentVotePollWinnerInfo::WonByIdentity(kept_id), + "keptChoice", + json!(base58(kept_id)), + ), + ( + ContestedDocumentVotePollWinnerInfo::Locked, + "noneOfTheChoices", + JsonValue::Null, + ), + ( + ContestedDocumentVotePollWinnerInfo::NoWinner, + "noWinner", + JsonValue::Null, + ), + ] { + assert_eq!( + multiple_choice_proposal_vote_json(&finished(winner)).expect("writes"), + json!({ + "choices": [{"id": base58(kept_id), "choice": null, "voteTally": 9}], + "abstainVoteTally": null, + "noneOfTheChoicesVoteTally": 4, + "result": { + "outcome": outcome, + "keptChoiceId": kept_choice_id, + "finalizationBlock": finalization_block, + }, + }) + ); + } + } + + #[test] + fn should_write_a_vote_with_no_choice_as_empty() { + assert_eq!( + multiple_choice_proposal_vote_json(&MultipleChoiceProposalVote::default()) + .expect("writes"), + json!({ + "choices": [], + "abstainVoteTally": null, + "noneOfTheChoicesVoteTally": null, + "result": null, + }) + ); + } + + #[test] + fn should_write_a_masternode_answer() { + let choice_id = Identifier::from([9; 32]); + assert_eq!( + masternode_vote_json(Some(MultipleChoiceVoteChoice::Choice(choice_id))), + Some(json!({"choice": "choice", "choiceId": base58(choice_id)})) + ); + assert_eq!( + masternode_vote_json(Some(MultipleChoiceVoteChoice::NoneOfTheChoices)), + Some(json!({"choice": "noneOfTheChoices", "choiceId": null})) + ); + assert_eq!( + masternode_vote_json(Some(MultipleChoiceVoteChoice::Abstain)), + Some(json!({"choice": "abstain", "choiceId": null})) + ); + assert_eq!(masternode_vote_json(None), None); + } +} diff --git a/packages/rs-sdk-ffi/src/decision_proposal/multiple_choice/mod.rs b/packages/rs-sdk-ffi/src/decision_proposal/multiple_choice/mod.rs new file mode 100644 index 00000000000..abf3ab2d65d --- /dev/null +++ b/packages/rs-sdk-ffi/src/decision_proposal/multiple_choice/mod.rs @@ -0,0 +1,795 @@ +//! Multiple choice proposals (protocol version 15): questions whose answers are the choices +//! entered for them, as `multipleChoiceProposal` and `choice` documents of the decision +//! proposals system contract. Thin bindings over +//! `dash_sdk::platform::decision_proposals::multiple_choice`: rs-sdk decides everything +//! (which documents are proposals and choices, the vote's contest, the funds and fees); these +//! functions read C arguments, call it, and write the result. +//! +//! # Creating, editing and entering choices +//! +//! Through the platform wallet, which signs with the owner's identity keys: +//! `platform_wallet_multiple_choice_proposal_create`, `_edit` and `_enter_choice` in +//! `rs-platform-wallet-ffi`. Creating a proposal costs the processing fee +//! [`dash_sdk_multiple_choice_proposal_get_processing_fee`] reads, on top of the fees; a choice +//! states the contest fund [`dash_sdk_multiple_choice_proposal_get_choice_fund_to_join`] reads. +//! +//! # Reading +//! +//! The reads return JSON, null when what they read is absent. A proposal is always the same +//! object (see [`dash_sdk_multiple_choice_proposal_fetch`]), and so is a choice (see +//! [`dash_sdk_multiple_choice_proposal_get_kept_choice`]); the listings return arrays of +//! proposals. +//! +//! # Voting +//! +//! The choices contend in a masternode vote, in which a choice is named by its document id. +//! [`dash_sdk_multiple_choice_proposal_cast_vote`] answers for a masternode from its voting +//! private key and pro_tx_hash, exactly as `dash_sdk_decision_proposal_cast_vote` answers a +//! yes/no proposal (see `crate::voting::masternode_vote`). + +mod json; + +use self::json::{ + choice_document_json, masternode_vote_json, multiple_choice_proposal_json, + multiple_choice_proposal_vote_json, multiple_choice_proposals_json, +}; +use super::queries::page; +use super::{json_result, optional_identifier, required_identifier, sdk_wrapper, string_result}; +use crate::types::{FFINetwork, SDKHandle}; +use crate::voting::masternode_vote::{pro_tx_hash_from_wire_order, MasternodeVoter}; +use crate::{DashSDKResult, FFIError}; +use dash_sdk::platform::decision_proposals::multiple_choice::{ + multiple_choice_proposal_vote, MultipleChoiceVoteChoice, +}; +use serde_json::Value as JsonValue; +use std::ffi::c_char; + +/// The answer of a masternode's vote among a multiple choice proposal's choices, the +/// `vote_choice` byte of `dash_sdk_multiple_choice_proposal_cast_vote`: `0` = for the choice +/// `choice_id` names, `1` = none of the choices, `2` = abstain. +/// +/// The FFI parameter is a plain `u8`, not this enum: a C caller can pass any byte, and an +/// out-of-range value read as a `#[repr(u8)]` enum is undefined behavior. The byte is +/// compared with these discriminants, and any other value is refused with +/// `InvalidParameter`. Not exported to the C header for that reason; Swift and Kotlin mirror +/// the three values. +#[repr(u8)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum MultipleChoiceVoteChoiceFFI { + Choice = 0, + NoneOfTheChoices = 1, + Abstain = 2, +} + +/// The answer the `vote_choice` byte and `choice_id` name. `choice_id` names the choice for +/// `0` and must be null for the other answers. +/// +/// # Safety +/// `choice_id` must be null or point to a NUL-terminated string. +unsafe fn vote_choice_from_ffi( + vote_choice: u8, + choice_id: *const c_char, +) -> Result { + let choice_id = optional_identifier(choice_id, "choice_id")?; + match (vote_choice, choice_id) { + (x, Some(choice_id)) if x == MultipleChoiceVoteChoiceFFI::Choice as u8 => { + Ok(MultipleChoiceVoteChoice::Choice(choice_id)) + } + (x, None) if x == MultipleChoiceVoteChoiceFFI::Choice as u8 => Err( + FFIError::InvalidParameter("choice_id is null for a vote for a choice".to_string()), + ), + (x, None) if x == MultipleChoiceVoteChoiceFFI::NoneOfTheChoices as u8 => { + Ok(MultipleChoiceVoteChoice::NoneOfTheChoices) + } + (x, None) if x == MultipleChoiceVoteChoiceFFI::Abstain as u8 => { + Ok(MultipleChoiceVoteChoice::Abstain) + } + (x, Some(_)) + if x == MultipleChoiceVoteChoiceFFI::NoneOfTheChoices as u8 + || x == MultipleChoiceVoteChoiceFFI::Abstain as u8 => + { + Err(FFIError::InvalidParameter(format!( + "choice_id must be null for vote_choice {x}, which names no choice" + ))) + } + (other, _) => Err(FFIError::InvalidParameter(format!( + "vote_choice must be 0 (a choice), 1 (none of the choices) or 2 (abstain); got \ + {other}" + ))), + } +} + +/// Fetches a multiple choice proposal by id. +/// +/// # Parameters +/// * `sdk_handle` - Handle to the SDK instance. +/// * `proposal_id` - The proposal's id, base58. +/// +/// # Returns +/// The proposal as a JSON object, or no data when there is none: +/// +/// ```json +/// {"id": "", "ownerId": "", "revision": 1, +/// "createdAt": 1700000000000, "updatedAt": 1700000000000, +/// "title": "Which block size?", +/// "descriptionDocument": {"id": "", "contractId": "", "documentType": "post"}, +/// "url": "https://forum.dash.org/t/block-size", "open": true} +/// ``` +/// +/// `descriptionDocument` and `url` are null when the proposal has none (it has at least one); +/// `revision`, `createdAt` and `updatedAt` are null when the document does not carry them. +/// Times are milliseconds since the Unix epoch. `open` says whether anyone may enter choices +/// (only the owner may when it is false). Every listing returns proposals in this shape. +/// Free the string with `dash_sdk_string_free`. +/// +/// # Safety +/// - `sdk_handle` must be a valid pointer to an initialized `SDKHandle`. +/// - `proposal_id` must be a valid pointer to a NUL-terminated string for the duration of the +/// call. +#[no_mangle] +pub unsafe extern "C" fn dash_sdk_multiple_choice_proposal_fetch( + sdk_handle: *const SDKHandle, + proposal_id: *const c_char, +) -> DashSDKResult { + json_result(fetch_inner(sdk_handle, proposal_id)) +} + +unsafe fn fetch_inner( + sdk_handle: *const SDKHandle, + proposal_id: *const c_char, +) -> Result, FFIError> { + let wrapper = sdk_wrapper(sdk_handle)?; + let proposal_id = required_identifier(proposal_id, "proposal_id")?; + wrapper + .runtime + .block_on(wrapper.sdk.fetch_multiple_choice_proposal(proposal_id))? + .map(multiple_choice_proposal_json) + .transpose() +} + +/// Lists one page of an identity's multiple choice proposals, in the order it filed them. +/// +/// # Parameters +/// * `sdk_handle` - Handle to the SDK instance. +/// * `owner_id` - The proposer's identity id, base58. +/// * `limit` - The most proposals to return, at most 100; 0 for 100. +/// * `start_after` - The id (base58) of the last proposal of the previous page; null for the +/// first page. +/// +/// # Returns +/// A JSON array of proposals in the shape `dash_sdk_multiple_choice_proposal_fetch` returns, +/// `[]` when there is none. A page shorter than the limit is the last. Free the string with +/// `dash_sdk_string_free`. +/// +/// # Safety +/// - `sdk_handle` must be a valid pointer to an initialized `SDKHandle`. +/// - `owner_id` must be a valid pointer to a NUL-terminated string, and `start_after` null or +/// one, for the duration of the call. +#[no_mangle] +pub unsafe extern "C" fn dash_sdk_multiple_choice_proposal_list_by_owner( + sdk_handle: *const SDKHandle, + owner_id: *const c_char, + limit: u32, + start_after: *const c_char, +) -> DashSDKResult { + json_result(list_by_owner_inner( + sdk_handle, + owner_id, + limit, + start_after, + )) +} + +unsafe fn list_by_owner_inner( + sdk_handle: *const SDKHandle, + owner_id: *const c_char, + limit: u32, + start_after: *const c_char, +) -> Result, FFIError> { + let wrapper = sdk_wrapper(sdk_handle)?; + let owner_id = required_identifier(owner_id, "owner_id")?; + let page = page(limit, start_after)?; + let documents = wrapper.runtime.block_on( + wrapper + .sdk + .fetch_multiple_choice_proposals_by_owner(owner_id, page), + )?; + multiple_choice_proposals_json(documents).map(Some) +} + +/// Lists one page of every multiple choice proposal, newest first. +/// +/// # Parameters +/// * `sdk_handle` - Handle to the SDK instance. +/// * `limit` - The most proposals to return, at most 100; 0 for 100. +/// * `start_after` - The id (base58) of the last proposal of the previous page; null for the +/// first page. +/// +/// # Returns +/// A JSON array of proposals in the shape `dash_sdk_multiple_choice_proposal_fetch` returns, +/// `[]` when there is none. Free the string with `dash_sdk_string_free`. +/// +/// # Safety +/// - `sdk_handle` must be a valid pointer to an initialized `SDKHandle`. +/// - `start_after` must be null or a valid pointer to a NUL-terminated string for the duration +/// of the call. +#[no_mangle] +pub unsafe extern "C" fn dash_sdk_multiple_choice_proposal_list_by_created_at( + sdk_handle: *const SDKHandle, + limit: u32, + start_after: *const c_char, +) -> DashSDKResult { + json_result(list_by_created_at_inner(sdk_handle, limit, start_after)) +} + +unsafe fn list_by_created_at_inner( + sdk_handle: *const SDKHandle, + limit: u32, + start_after: *const c_char, +) -> Result, FFIError> { + let wrapper = sdk_wrapper(sdk_handle)?; + let page = page(limit, start_after)?; + let documents = wrapper.runtime.block_on( + wrapper + .sdk + .fetch_multiple_choice_proposals_by_created_at(page), + )?; + multiple_choice_proposals_json(documents).map(Some) +} + +/// The vote among a multiple choice proposal's choices: every choice with its tally while the +/// vote runs, and how it ended with every choice's final tally once it did. +/// +/// # Parameters +/// * `sdk_handle` - Handle to the SDK instance. +/// * `proposal_id` - The proposal's id, base58. +/// +/// # Returns +/// A JSON object. While the vote runs: +/// +/// ```json +/// {"choices": [{"id": "", +/// "choice": {"id": "", "ownerId": "", +/// "proposalId": "", "revision": null, +/// "createdAt": 1700000000000, "updatedAt": null, +/// "title": "Double it", +/// "description": "Twice the size it is today."}, +/// "voteTally": 12}], +/// "abstainVoteTally": 3, "noneOfTheChoicesVoteTally": 1, "result": null} +/// ``` +/// +/// `choices` is ordered by choice id, and `[]` for a proposal no choice was entered for. Each +/// `id` is the choice's document id, the one a vote for it names; `choice` is the choice in +/// the shape `dash_sdk_multiple_choice_proposal_get_kept_choice` returns, null once the vote +/// ended (the choices not kept are gone, and the kept one is read with that function). The +/// tallies are null when Platform does not report them. Once the vote ended, `result` is +/// `{"outcome": "keptChoice" | "noneOfTheChoices" | "noWinner", "keptChoiceId": "", +/// "finalizationBlock": {"height": 9, "coreHeight": 42, "timeMs": 9000, "epoch": 3}}`, with +/// `keptChoiceId` null unless `outcome` is `"keptChoice"`. Free the string with +/// `dash_sdk_string_free`. +/// +/// # Safety +/// - `sdk_handle` must be a valid pointer to an initialized `SDKHandle`. +/// - `proposal_id` must be a valid pointer to a NUL-terminated string for the duration of the +/// call. +#[no_mangle] +pub unsafe extern "C" fn dash_sdk_multiple_choice_proposal_get_vote( + sdk_handle: *const SDKHandle, + proposal_id: *const c_char, +) -> DashSDKResult { + json_result(get_vote_inner(sdk_handle, proposal_id)) +} + +unsafe fn get_vote_inner( + sdk_handle: *const SDKHandle, + proposal_id: *const c_char, +) -> Result, FFIError> { + let wrapper = sdk_wrapper(sdk_handle)?; + let proposal_id = required_identifier(proposal_id, "proposal_id")?; + let vote = wrapper + .runtime + .block_on(wrapper.sdk.fetch_multiple_choice_proposal_vote(proposal_id))?; + multiple_choice_proposal_vote_json(&vote).map(Some) +} + +/// The choice the finished vote of a multiple choice proposal kept, an ordinary document of +/// the identity that entered it. +/// +/// # Parameters +/// * `sdk_handle` - Handle to the SDK instance. +/// * `proposal_id` - The proposal's id, base58. +/// +/// # Returns +/// The choice as a JSON object, or no data while the vote runs, when it kept none of the +/// choices, and for a proposal no choice was entered for: +/// +/// ```json +/// {"id": "", "ownerId": "", "proposalId": "", "revision": null, +/// "createdAt": 1700000000000, "updatedAt": null, +/// "title": "Double it", "description": "Twice the size it is today."} +/// ``` +/// +/// `description` is null when the choice has none; `revision`, `createdAt` and `updatedAt` +/// are null when the document does not carry them. Free the string with +/// `dash_sdk_string_free`. +/// +/// # Safety +/// - `sdk_handle` must be a valid pointer to an initialized `SDKHandle`. +/// - `proposal_id` must be a valid pointer to a NUL-terminated string for the duration of the +/// call. +#[no_mangle] +pub unsafe extern "C" fn dash_sdk_multiple_choice_proposal_get_kept_choice( + sdk_handle: *const SDKHandle, + proposal_id: *const c_char, +) -> DashSDKResult { + json_result(get_kept_choice_inner(sdk_handle, proposal_id)) +} + +unsafe fn get_kept_choice_inner( + sdk_handle: *const SDKHandle, + proposal_id: *const c_char, +) -> Result, FFIError> { + let wrapper = sdk_wrapper(sdk_handle)?; + let proposal_id = required_identifier(proposal_id, "proposal_id")?; + wrapper + .runtime + .block_on(wrapper.sdk.fetch_kept_choice(proposal_id))? + .map(choice_document_json) + .transpose() +} + +/// The answer a masternode gave in the vote among a multiple choice proposal's choices. +/// +/// # Parameters +/// * `sdk_handle` - Handle to the SDK instance. +/// * `voter_pro_tx_hash` - Pointer to the masternode's 32-byte pro_tx_hash in wire order, the +/// same bytes `dash_sdk_multiple_choice_proposal_cast_vote` takes (the reverse of the hex +/// Core displays). They are reversed here, as for the vote. +/// * `proposal_id` - The proposal's id, base58. +/// +/// # Returns +/// `{"choice": "choice", "choiceId": ""}` for a vote for a choice, or +/// `{"choice": "noneOfTheChoices" | "abstain", "choiceId": null}`; no data when the +/// masternode has not voted in it, and once the vote ended. Free the string with +/// `dash_sdk_string_free`. +/// +/// # Safety +/// - `sdk_handle` must be a valid pointer to an initialized `SDKHandle`. +/// - `voter_pro_tx_hash` must point to 32 readable bytes and `proposal_id` to a +/// NUL-terminated string for the duration of the call. +#[no_mangle] +pub unsafe extern "C" fn dash_sdk_multiple_choice_proposal_get_masternode_vote( + sdk_handle: *const SDKHandle, + voter_pro_tx_hash: *const u8, + proposal_id: *const c_char, +) -> DashSDKResult { + json_result(get_masternode_vote_inner( + sdk_handle, + voter_pro_tx_hash, + proposal_id, + )) +} + +unsafe fn get_masternode_vote_inner( + sdk_handle: *const SDKHandle, + voter_pro_tx_hash: *const u8, + proposal_id: *const c_char, +) -> Result, FFIError> { + let wrapper = sdk_wrapper(sdk_handle)?; + let pro_tx_hash = pro_tx_hash_from_wire_order(voter_pro_tx_hash)?; + let proposal_id = required_identifier(proposal_id, "proposal_id")?; + let vote_choice = wrapper.runtime.block_on( + wrapper + .sdk + .fetch_masternode_multiple_choice_vote(pro_tx_hash, proposal_id), + )?; + Ok(masternode_vote_json(vote_choice)) +} + +/// What creating one multiple choice proposal adds to the processing fee of its batch, which +/// Platform charges the owner on top of the fees; the create does not state it. A network +/// below protocol version 15 has no multiple choice proposals, which is an error. +/// +/// # Parameters +/// * `sdk_handle` - Handle to the SDK instance. +/// +/// # Returns +/// The fee in credits as a decimal string (not JSON), for example `"20000000000"`. Free it +/// with `dash_sdk_string_free`. +/// +/// # Safety +/// - `sdk_handle` must be a valid pointer to an initialized `SDKHandle`. +#[no_mangle] +pub unsafe extern "C" fn dash_sdk_multiple_choice_proposal_get_processing_fee( + sdk_handle: *const SDKHandle, +) -> DashSDKResult { + string_result(get_processing_fee_inner(sdk_handle)) +} + +unsafe fn get_processing_fee_inner( + sdk_handle: *const SDKHandle, +) -> Result, FFIError> { + let wrapper = sdk_wrapper(sdk_handle)?; + let fee = wrapper + .runtime + .block_on(wrapper.sdk.multiple_choice_proposal_processing_fee())?; + Ok(Some(fee.to_string())) +} + +/// The fund a choice entered now for a multiple choice proposal pays: the contest's fund, +/// doubled once the vote holds 250 choices and again for every 50 more. The put of a choice +/// reads and states it itself; this is for showing it beforehand. +/// +/// # Parameters +/// * `sdk_handle` - Handle to the SDK instance. +/// * `proposal_id` - The proposal's id, base58. +/// +/// # Returns +/// The fund in credits as a decimal string (not JSON), for example `"10000000000"`. Free it +/// with `dash_sdk_string_free`. +/// +/// # Safety +/// - `sdk_handle` must be a valid pointer to an initialized `SDKHandle`. +/// - `proposal_id` must be a valid pointer to a NUL-terminated string for the duration of the +/// call. +#[no_mangle] +pub unsafe extern "C" fn dash_sdk_multiple_choice_proposal_get_choice_fund_to_join( + sdk_handle: *const SDKHandle, + proposal_id: *const c_char, +) -> DashSDKResult { + string_result(get_choice_fund_to_join_inner(sdk_handle, proposal_id)) +} + +unsafe fn get_choice_fund_to_join_inner( + sdk_handle: *const SDKHandle, + proposal_id: *const c_char, +) -> Result, FFIError> { + let wrapper = sdk_wrapper(sdk_handle)?; + let proposal_id = required_identifier(proposal_id, "proposal_id")?; + let fund = wrapper + .runtime + .block_on(wrapper.sdk.choice_fund_to_join(proposal_id))?; + Ok(Some(fund.to_string())) +} + +/// Votes in the vote among a multiple choice proposal's choices for a masternode: builds the +/// vote, signs it with the masternode voting key derived from `voting_private_key`, +/// broadcasts it for `voter_pro_tx_hash` and waits for the response. Every argument is read +/// before anything reaches the network. +/// +/// The signer, the voting key and the voter identity are derived exactly as +/// `dash_sdk_decision_proposal_cast_vote` derives them, and a refused voting key is explained +/// the same way. +/// +/// # Parameters +/// * `sdk_handle` - Handle to the SDK instance. +/// * `proposal_id` - The proposal's id, base58. +/// * `vote_choice` - `0` = for the choice `choice_id` names, `1` = none of the choices (keeps +/// no choice when these votes outnumber the leading choice), `2` = abstain. Any other value +/// is refused with `InvalidParameter`. +/// * `choice_id` - The document id (base58) of the choice voted for, not the id of the +/// identity that entered it. Required for `vote_choice` `0` and null otherwise; anything +/// else is refused with `InvalidParameter`. +/// * `voter_pro_tx_hash` - Pointer to the masternode's 32-byte pro_tx_hash in wire order, as +/// `dash_sdk_decision_proposal_cast_vote` takes it (NOT the byte order of the hex Core +/// displays, which is its reverse). The bytes are reversed here. +/// * `voting_private_key` - Pointer to the 32-byte masternode voting private key. It never +/// leaves this call. +/// * `network` - The network, used for the WIF encoding inside the signer only. +/// +/// # Returns +/// No data on success, or an error. A vote from a wallet that is not a masternode fails with +/// a no-voter-identity error from Platform, the expected outcome. +/// +/// # Safety +/// - `sdk_handle` must be a valid pointer to an initialized `SDKHandle`. +/// - `proposal_id` must be a valid pointer to a NUL-terminated string, and `choice_id` null or +/// one. +/// - `voter_pro_tx_hash` and `voting_private_key` must each point to 32 readable bytes. All +/// must stay valid for the duration of the call. +#[no_mangle] +pub unsafe extern "C" fn dash_sdk_multiple_choice_proposal_cast_vote( + sdk_handle: *const SDKHandle, + proposal_id: *const c_char, + vote_choice: u8, + choice_id: *const c_char, + voter_pro_tx_hash: *const u8, + voting_private_key: *const u8, + network: FFINetwork, +) -> DashSDKResult { + match cast_vote_inner( + sdk_handle, + proposal_id, + vote_choice, + choice_id, + voter_pro_tx_hash, + voting_private_key, + network, + ) { + Ok(()) => DashSDKResult::success(std::ptr::null_mut()), + Err(error) => DashSDKResult::error(error.into()), + } +} + +unsafe fn cast_vote_inner( + sdk_handle: *const SDKHandle, + proposal_id: *const c_char, + vote_choice: u8, + choice_id: *const c_char, + voter_pro_tx_hash: *const u8, + voting_private_key: *const u8, + network: FFINetwork, +) -> Result<(), FFIError> { + let wrapper = sdk_wrapper(sdk_handle)?; + let proposal_id = required_identifier(proposal_id, "proposal_id")?; + let vote_choice = vote_choice_from_ffi(vote_choice, choice_id)?; + let voter = MasternodeVoter::from_raw(voter_pro_tx_hash, voting_private_key, network)?; + let vote = multiple_choice_proposal_vote(proposal_id, vote_choice); + wrapper + .runtime + .block_on(voter.put_vote(&wrapper.sdk, &vote)) +} + +#[cfg(test)] +mod tests { + use super::json::vote_choice_name; + use super::*; + use crate::test_utils::test_utils::{create_mock_sdk_handle, destroy_mock_sdk_handle}; + use crate::{dash_sdk_error_free, DashSDKErrorCode}; + use dash_sdk::dpp::platform_value::string_encoding::Encoding; + use dash_sdk::dpp::platform_value::Identifier; + use std::ffi::CString; + + /// `result` failed with `InvalidParameter`; its error is freed. + unsafe fn assert_invalid_parameter(result: DashSDKResult) { + assert!(result.data.is_null()); + assert!(!result.error.is_null(), "expected an error"); + let code = (*result.error).code; + dash_sdk_error_free(result.error); + assert_eq!(code, DashSDKErrorCode::InvalidParameter); + } + + fn base58(id: Identifier) -> CString { + CString::new(id.to_string(Encoding::Base58)).expect("no NUL") + } + + #[test] + fn should_map_each_vote_choice_byte_and_refuse_the_rest() { + let choice_id = Identifier::new([9; 32]); + let choice = base58(choice_id); + let not_base58 = CString::new("0OIl").expect("no NUL"); + unsafe { + assert_eq!( + vote_choice_from_ffi(0, choice.as_ptr()).ok(), + Some(MultipleChoiceVoteChoice::Choice(choice_id)) + ); + assert_eq!( + vote_choice_from_ffi(1, std::ptr::null()).ok(), + Some(MultipleChoiceVoteChoice::NoneOfTheChoices) + ); + assert_eq!( + vote_choice_from_ffi(2, std::ptr::null()).ok(), + Some(MultipleChoiceVoteChoice::Abstain) + ); + for (byte, choice_id) in [ + // A vote for a choice names it + (0, std::ptr::null()), + (0, not_base58.as_ptr()), + // The other answers name none + (1, choice.as_ptr()), + (2, choice.as_ptr()), + (3, std::ptr::null()), + (3, choice.as_ptr()), + (u8::MAX, std::ptr::null()), + ] { + assert!( + matches!( + vote_choice_from_ffi(byte, choice_id), + Err(FFIError::InvalidParameter(_)) + ), + "vote_choice {byte}" + ); + } + // The byte and the name a masternode's answer is read back with agree + for (byte, choice_id, name) in [ + (0, choice.as_ptr(), "choice"), + (1, std::ptr::null(), "noneOfTheChoices"), + (2, std::ptr::null(), "abstain"), + ] { + assert_eq!( + vote_choice_name(&vote_choice_from_ffi(byte, choice_id).expect("an answer")), + name + ); + } + } + } + + /// Every read refuses a null SDK handle, a null or non-base58 id and a null pro_tx_hash + /// before anything reaches the network. + #[test] + fn should_refuse_missing_or_malformed_arguments_before_any_request() { + let handle = create_mock_sdk_handle(); + let id = base58(Identifier::new([4; 32])); + let not_base58 = CString::new("not base58: 0OIl").expect("no NUL"); + let pro_tx_hash = [1u8; 32]; + unsafe { + for proposal_id in [std::ptr::null(), not_base58.as_ptr()] { + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_fetch( + handle, + proposal_id, + )); + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_list_by_owner( + handle, + proposal_id, + 0, + std::ptr::null(), + )); + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_get_vote( + handle, + proposal_id, + )); + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_get_kept_choice( + handle, + proposal_id, + )); + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_get_masternode_vote( + handle, + pro_tx_hash.as_ptr(), + proposal_id, + )); + assert_invalid_parameter( + dash_sdk_multiple_choice_proposal_get_choice_fund_to_join(handle, proposal_id), + ); + } + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_list_by_owner( + handle, + id.as_ptr(), + 0, + not_base58.as_ptr(), + )); + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_list_by_created_at( + handle, + 0, + not_base58.as_ptr(), + )); + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_get_masternode_vote( + handle, + std::ptr::null(), + id.as_ptr(), + )); + + let no_sdk = std::ptr::null(); + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_fetch(no_sdk, id.as_ptr())); + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_list_by_owner( + no_sdk, + id.as_ptr(), + 0, + std::ptr::null(), + )); + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_list_by_created_at( + no_sdk, + 0, + std::ptr::null(), + )); + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_get_vote( + no_sdk, + id.as_ptr(), + )); + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_get_kept_choice( + no_sdk, + id.as_ptr(), + )); + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_get_masternode_vote( + no_sdk, + pro_tx_hash.as_ptr(), + id.as_ptr(), + )); + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_get_processing_fee(no_sdk)); + assert_invalid_parameter(dash_sdk_multiple_choice_proposal_get_choice_fund_to_join( + no_sdk, + id.as_ptr(), + )); + destroy_mock_sdk_handle(handle); + } + } + + /// The vote reads every argument before it reaches the network. + #[test] + fn should_refuse_a_vote_with_unreadable_arguments() { + let handle = create_mock_sdk_handle(); + let proposal_id = base58(Identifier::new([4; 32])); + let choice_id = base58(Identifier::new([9; 32])); + let not_base58 = CString::new("0OIl").expect("no NUL"); + let pro_tx_hash = [1u8; 32]; + let voting_key = [2u8; 32]; + let zero_key = [0u8; 32]; + unsafe { + for result in [ + dash_sdk_multiple_choice_proposal_cast_vote( + std::ptr::null(), + proposal_id.as_ptr(), + 0, + choice_id.as_ptr(), + pro_tx_hash.as_ptr(), + voting_key.as_ptr(), + FFINetwork::Testnet, + ), + dash_sdk_multiple_choice_proposal_cast_vote( + handle, + std::ptr::null(), + 0, + choice_id.as_ptr(), + pro_tx_hash.as_ptr(), + voting_key.as_ptr(), + FFINetwork::Testnet, + ), + dash_sdk_multiple_choice_proposal_cast_vote( + handle, + not_base58.as_ptr(), + 0, + choice_id.as_ptr(), + pro_tx_hash.as_ptr(), + voting_key.as_ptr(), + FFINetwork::Testnet, + ), + dash_sdk_multiple_choice_proposal_cast_vote( + handle, + proposal_id.as_ptr(), + 0, + std::ptr::null(), + pro_tx_hash.as_ptr(), + voting_key.as_ptr(), + FFINetwork::Testnet, + ), + dash_sdk_multiple_choice_proposal_cast_vote( + handle, + proposal_id.as_ptr(), + 2, + choice_id.as_ptr(), + pro_tx_hash.as_ptr(), + voting_key.as_ptr(), + FFINetwork::Testnet, + ), + dash_sdk_multiple_choice_proposal_cast_vote( + handle, + proposal_id.as_ptr(), + 3, + std::ptr::null(), + pro_tx_hash.as_ptr(), + voting_key.as_ptr(), + FFINetwork::Testnet, + ), + dash_sdk_multiple_choice_proposal_cast_vote( + handle, + proposal_id.as_ptr(), + 1, + std::ptr::null(), + std::ptr::null(), + voting_key.as_ptr(), + FFINetwork::Testnet, + ), + dash_sdk_multiple_choice_proposal_cast_vote( + handle, + proposal_id.as_ptr(), + 1, + std::ptr::null(), + pro_tx_hash.as_ptr(), + std::ptr::null(), + FFINetwork::Testnet, + ), + dash_sdk_multiple_choice_proposal_cast_vote( + handle, + proposal_id.as_ptr(), + 2, + std::ptr::null(), + pro_tx_hash.as_ptr(), + zero_key.as_ptr(), + FFINetwork::Testnet, + ), + ] { + assert_invalid_parameter(result); + } + destroy_mock_sdk_handle(handle); + } + } +} diff --git a/packages/rs-sdk-ffi/src/decision_proposal/queries.rs b/packages/rs-sdk-ffi/src/decision_proposal/queries.rs index d1506c8cbae..cd9b5e4bf43 100644 --- a/packages/rs-sdk-ffi/src/decision_proposal/queries.rs +++ b/packages/rs-sdk-ffi/src/decision_proposal/queries.rs @@ -23,7 +23,10 @@ use std::ffi::c_char; /// /// # Safety /// `start_after` must be null or point to a NUL-terminated string. -unsafe fn page(limit: u32, start_after: *const c_char) -> Result { +pub(super) unsafe fn page( + limit: u32, + start_after: *const c_char, +) -> Result { Ok(DocumentsPage { limit: (limit > 0).then_some(limit), start_after: optional_identifier(start_after, "start_after")?, diff --git a/packages/rs-unified-sdk-jni/src/decision_proposals.rs b/packages/rs-unified-sdk-jni/src/decision_proposals.rs index dcba5e51fa7..c9017c5fb88 100644 --- a/packages/rs-unified-sdk-jni/src/decision_proposals.rs +++ b/packages/rs-unified-sdk-jni/src/decision_proposals.rs @@ -39,14 +39,18 @@ use std::ffi::{CStr, CString}; use std::os::raw::c_char; use std::ptr; -// ── Marshalling helpers ────────────────────────────────────────────────── +// ── Marshalling helpers (shared with `crate::multiple_choice_proposals`) ─ /// Read a nullable JVM string into an owned `CString`. /// /// `Some(None)` for a null string, `Some(Some(_))` for a string, and `None` after throwing /// for a string JNI cannot read or one holding a NUL byte (the caller bails out). An /// unreadable string is never mistaken for an absent one. -fn read_optional_cstring(env: &mut JNIEnv, s: &JString, field: &str) -> Option> { +pub(crate) fn read_optional_cstring( + env: &mut JNIEnv, + s: &JString, + field: &str, +) -> Option> { if s.is_null() { return Some(None); } @@ -69,7 +73,7 @@ fn read_optional_cstring(env: &mut JNIEnv, s: &JString, field: &str) -> Option Option { +pub(crate) fn read_cstring(env: &mut JNIEnv, s: &JString, field: &str) -> Option { match read_optional_cstring(env, s, field)? { Some(c) => Some(c), None => { @@ -80,13 +84,13 @@ fn read_cstring(env: &mut JNIEnv, s: &JString, field: &str) -> Option { } /// The pointer the C functions take for an optional string: null for `None`. -fn c_ptr(value: &Option) -> *const c_char { +pub(crate) fn c_ptr(value: &Option) -> *const c_char { value.as_ref().map_or(ptr::null(), |s| s.as_ptr()) } /// Read a required 32-byte array; throws and returns `None` for a null array or any other /// length (the C functions read exactly 32 bytes through the pointer). -fn read_bytes32(env: &mut JNIEnv, arr: &JByteArray, field: &str) -> Option<[u8; 32]> { +pub(crate) fn read_bytes32(env: &mut JNIEnv, arr: &JByteArray, field: &str) -> Option<[u8; 32]> { let bytes = match env.convert_byte_array(arr) { Ok(b) => b, Err(_) => { @@ -110,7 +114,7 @@ fn read_bytes32(env: &mut JNIEnv, arr: &JByteArray, field: &str) -> Option<[u8; /// Secret-key sibling of [`read_bytes32`]: the returned buffer is scrubbed on drop and the /// intermediate JNI copy is zeroized before it is dropped. For the voting private key only. -fn read_key32_zeroizing( +pub(crate) fn read_key32_zeroizing( env: &mut JNIEnv, arr: &JByteArray, field: &str, @@ -139,7 +143,7 @@ fn read_key32_zeroizing( /// `value` as the unsigned C type `T`; throws and returns `None` for a value `T` cannot /// hold (negative, or too large) instead of wrapping it into a different, valid one. -fn to_unsigned>(env: &mut JNIEnv, value: i64, field: &str) -> Option { +pub(crate) fn to_unsigned>(env: &mut JNIEnv, value: i64, field: &str) -> Option { match T::try_from(value) { Ok(converted) => Some(converted), Err(_) => { @@ -155,7 +159,7 @@ fn to_unsigned>(env: &mut JNIEnv, value: i64, field: &str) -> Op /// # Safety /// `result` must be a `DashSDKResult` freshly returned by an rs-sdk-ffi function whose /// success payload is a `char*` or no data. -unsafe fn string_or_null(env: &mut JNIEnv, result: DashSDKResult) -> jstring { +pub(crate) unsafe fn string_or_null(env: &mut JNIEnv, result: DashSDKResult) -> jstring { unwrap_string(env, result) .map(|s| s.into_raw()) .unwrap_or(ptr::null_mut()) @@ -174,7 +178,7 @@ unsafe fn static_string(env: &mut JNIEnv, value: *const c_char) -> jstring { /// Whether `arr` is a non-null `byte[len]`. Clears the exception a failed length read /// leaves; the caller throws. -fn is_byte_array_of_len(env: &mut JNIEnv, arr: &JByteArray, len: i32) -> bool { +pub(crate) fn is_byte_array_of_len(env: &mut JNIEnv, arr: &JByteArray, len: i32) -> bool { if arr.is_null() { return false; } @@ -194,7 +198,11 @@ fn is_byte_array_of_len(env: &mut JNIEnv, arr: &JByteArray, len: i32) -> bool { /// /// # Safety /// `json` must be null or a string the platform wallet allocated and nothing else frees. -unsafe fn take_wallet_json(env: &mut JNIEnv, json: *mut c_char, call: &str) -> Option { +pub(crate) unsafe fn take_wallet_json( + env: &mut JNIEnv, + json: *mut c_char, + call: &str, +) -> Option { if json.is_null() { throw_sdk_exception( env, @@ -704,7 +712,7 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_DecisionProposalsNati } #[cfg(test)] -mod tests { +pub(crate) mod tests { const DECISION_PROPOSALS_NATIVE_KT: &str = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/../kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/DecisionProposalsNative.kt" @@ -713,10 +721,16 @@ mod tests { /// The parameter types and the return type of `external fun {name}(...)` in /// `DecisionProposalsNative.kt`. fn kotlin_signature(name: &str) -> (Vec, String) { - let declaration = DECISION_PROPOSALS_NATIVE_KT + kotlin_signature_in(DECISION_PROPOSALS_NATIVE_KT, name) + } + + /// The parameter types and the return type of `external fun {name}(...)` in the Kotlin + /// source `kotlin`, the text of a `*Native.kt` file. + pub(crate) fn kotlin_signature_in(kotlin: &str, name: &str) -> (Vec, String) { + let declaration = kotlin .split(&format!("external fun {name}(")) .nth(1) - .unwrap_or_else(|| panic!("DecisionProposalsNative.kt declares {name}")); + .unwrap_or_else(|| panic!("the Kotlin native object declares {name}")); let (parameters, rest) = declaration .split_once(')') .expect("the parameter list closes"); diff --git a/packages/rs-unified-sdk-jni/src/lib.rs b/packages/rs-unified-sdk-jni/src/lib.rs index aaa43632342..b8450bdaa34 100644 --- a/packages/rs-unified-sdk-jni/src/lib.rs +++ b/packages/rs-unified-sdk-jni/src/lib.rs @@ -22,6 +22,7 @@ mod events; mod funding; mod identity; mod mnemonic; +mod multiple_choice_proposals; mod parse_state_transition; mod persistence; mod pubkey_rows; diff --git a/packages/rs-unified-sdk-jni/src/multiple_choice_proposals.rs b/packages/rs-unified-sdk-jni/src/multiple_choice_proposals.rs new file mode 100644 index 00000000000..892a9a78730 --- /dev/null +++ b/packages/rs-unified-sdk-jni/src/multiple_choice_proposals.rs @@ -0,0 +1,812 @@ +//! JNI exports for multiple choice proposals (protocol version 15): questions whose answers +//! are the choices entered for them, as `multipleChoiceProposal` and `choice` documents of +//! the decision proposals system contract. Each export marshals ONE C function: a +//! `dash_sdk_multiple_choice_proposal_*` function of `rs-sdk-ffi` (the reads, the two amounts +//! and the masternode vote), or `platform_wallet_multiple_choice_proposal_create` / `_edit` / +//! `_enter_choice` of `platform-wallet-ffi` (the writes, which the platform wallet builds, +//! signs, broadcasts and confirms itself). It reads the JVM arguments, calls the C function, +//! copies the result into a JVM value and frees every Rust allocation the result carried +//! before returning. +//! +//! Errors and argument checks follow `crate::decision_proposals`, whose marshalling helpers +//! these exports share: a `DashSDKResult` error and a `PlatformWalletFFIResult` error each +//! throw `DashSDKException` by their crate's convention, and only an argument the JVM value +//! cannot carry into the C type (a null required string, a byte array of the wrong length, a +//! number out of the C type's range) is refused here, with code 1 (`InvalidParameter`). +//! +//! Kotlin counterpart: `org.dashfoundation.dashsdk.ffi.MultipleChoiceProposalsNative`. + +use crate::decision_proposals::{ + c_ptr, is_byte_array_of_len, read_bytes32, read_cstring, read_key32_zeroizing, + read_optional_cstring, string_or_null, take_wallet_json, to_unsigned, +}; +use crate::results::take_error; +use crate::support::{guard, net_from_ord, take_pwffi_error, throw_sdk_exception}; +use jni::objects::{JByteArray, JClass, JString}; +use jni::sys::{jboolean, jbyte, jint, jlong, jstring}; +use jni::JNIEnv; +use platform_wallet_ffi::handle::Handle; +use platform_wallet_ffi::{ + platform_wallet_multiple_choice_proposal_create, platform_wallet_multiple_choice_proposal_edit, + platform_wallet_multiple_choice_proposal_enter_choice, ChoiceParamsFFI, DescriptionDocumentFFI, + MultipleChoiceProposalEditFFI, MultipleChoiceProposalParamsFFI, +}; +use rs_sdk_ffi::{ + dash_sdk_multiple_choice_proposal_cast_vote, dash_sdk_multiple_choice_proposal_fetch, + dash_sdk_multiple_choice_proposal_get_choice_fund_to_join, + dash_sdk_multiple_choice_proposal_get_kept_choice, + dash_sdk_multiple_choice_proposal_get_masternode_vote, + dash_sdk_multiple_choice_proposal_get_processing_fee, + dash_sdk_multiple_choice_proposal_get_vote, + dash_sdk_multiple_choice_proposal_list_by_created_at, + dash_sdk_multiple_choice_proposal_list_by_owner, SDKHandle, SignerHandle, +}; +use std::ffi::CString; +use std::os::raw::c_char; +use std::ptr; + +// ── Marshalling helpers ────────────────────────────────────────────────── + +/// Read a nullable 32-byte array. +/// +/// `Some(None)` for a null array, `Some(Some(_))` for one of 32 bytes, and `None` after +/// throwing for any other length (the caller bails out). +fn read_optional_bytes32( + env: &mut JNIEnv, + arr: &JByteArray, + field: &str, +) -> Option> { + if arr.is_null() { + return Some(None); + } + read_bytes32(env, arr, field).map(Some) +} + +/// The three parts of a description document as the JVM handed them over, each absent when +/// its argument was null. They are kept here for as long as the C struct points into them. +struct DescriptionDocumentArgs { + id: Option<[u8; 32]>, + contract_id: Option<[u8; 32]>, + document_type: Option, +} + +impl DescriptionDocumentArgs { + /// Read the three arguments; `None` after throwing for one the C type cannot carry. + fn read( + env: &mut JNIEnv, + id: &JByteArray, + contract_id: &JByteArray, + document_type: &JString, + ) -> Option { + Some(Self { + id: read_optional_bytes32(env, id, "descriptionDocumentId")?, + contract_id: read_optional_bytes32(env, contract_id, "descriptionDocumentContractId")?, + document_type: read_optional_cstring(env, document_type, "descriptionDocumentType")?, + }) + } + + /// The C struct pointing at these parts: `None` (a null `description_document`) when all + /// three are absent, and otherwise a struct whose pointer is null for each absent part, + /// which the platform wallet refuses. + fn as_ffi(&self) -> Option { + if self.id.is_none() && self.contract_id.is_none() && self.document_type.is_none() { + return None; + } + Some(DescriptionDocumentFFI { + id: self.id.as_ref().map_or(ptr::null(), |id| id.as_ptr()), + contract_id: self + .contract_id + .as_ref() + .map_or(ptr::null(), |contract_id| contract_id.as_ptr()), + document_type: c_ptr(&self.document_type), + }) + } +} + +/// The pointer the C structs take for an optional description document: null for `None`. +fn description_document_ptr( + described: &Option, +) -> *const DescriptionDocumentFFI { + described + .as_ref() + .map_or(ptr::null(), |described| described as *const _) +} + +/// Write the id a paid create handed back into `out_id`, a `byte[32]` checked before the +/// create. Throws and returns `false` when the write still fails, with a message that says +/// `what` exists so that a caller does not retry a paid create. +fn write_created_id(env: &mut JNIEnv, out_id: &JByteArray, id: [u8; 32], what: &str) -> bool { + let id = id.map(|b| b as jbyte); + if env.set_byte_array_region(out_id, 0, &id).is_err() { + let _ = env.exception_clear(); + throw_sdk_exception( + env, + 99, + &format!("{what} was created, but its id could not be returned"), + ); + return false; + } + true +} + +// ── Create, edit and enter a choice (platform wallet) ──────────────────── + +/// Create + broadcast a multiple choice proposal of `ownerId`, signed via `signerHandle`: +/// the JNI bridge over `platform_wallet_multiple_choice_proposal_create`. The wallet builds +/// the proposal, picks the signing key itself, broadcasts and waits for Platform to confirm; +/// Platform charges the owner the multiple choice proposal processing fee on top of the fees. +/// +/// The description document is its three arguments together, all null for none; `url` may be +/// null (no url). `outProposalId` must be a non-null `byte[32]`, checked before anything is +/// broadcast so that the id of a paid create can always be written back; it receives the +/// proposal's id. +/// +/// Returns the confirmed document's canonical JSON, its Rust string freed here. Null after +/// throwing; a refusal by Platform carries its consensus code. +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_MultipleChoiceProposalsNative_create( + mut env: JNIEnv, + _class: JClass, + wallet_handle: jlong, + owner_id: JByteArray, + title: JString, + description_document_id: JByteArray, + description_document_contract_id: JByteArray, + description_document_type: JString, + url: JString, + open: jboolean, + signer_handle: jlong, + out_proposal_id: JByteArray, +) -> jstring { + guard(&mut env, ptr::null_mut(), |env| { + // Checked before the paid create: once it succeeded, writing the id back into a + // validated array allocates nothing and cannot go out of bounds. + if !is_byte_array_of_len(env, &out_proposal_id, 32) { + throw_sdk_exception(env, 1, "outProposalId must be a non-null byte[32]"); + return ptr::null_mut(); + } + let Some(owner) = read_bytes32(env, &owner_id, "ownerId") else { + return ptr::null_mut(); + }; + let Some(title) = read_cstring(env, &title, "title") else { + return ptr::null_mut(); + }; + let Some(described) = DescriptionDocumentArgs::read( + env, + &description_document_id, + &description_document_contract_id, + &description_document_type, + ) else { + return ptr::null_mut(); + }; + let Some(url) = read_optional_cstring(env, &url, "url") else { + return ptr::null_mut(); + }; + + let described = described.as_ffi(); + let params = MultipleChoiceProposalParamsFFI { + title: title.as_ptr(), + description_document: description_document_ptr(&described), + url: c_ptr(&url), + open: open != 0, + }; + let mut proposal_id = [0u8; 32]; + let mut out_json: *mut c_char = ptr::null_mut(); + // SAFETY: `owner` and `proposal_id` are 32 bytes, `params` and everything it points + // to outlive the call, and the signer handle is the Kotlin manager's live signer. + let result = unsafe { + platform_wallet_multiple_choice_proposal_create( + wallet_handle as Handle, + owner.as_ptr(), + ¶ms, + signer_handle as *mut SignerHandle, + proposal_id.as_mut_ptr(), + &mut out_json, + ) + }; + if take_pwffi_error(env, result) { + return ptr::null_mut(); + } + // SAFETY: on success `out_json` is the wallet's string, freed by this call only. + let Some(json) = + (unsafe { take_wallet_json(env, out_json, "multiple choice proposal create") }) + else { + return ptr::null_mut(); + }; + if !write_created_id( + env, + &out_proposal_id, + proposal_id, + "the multiple choice proposal", + ) { + return ptr::null_mut(); + } + env.new_string(json) + .map(|s| s.into_raw()) + .unwrap_or(ptr::null_mut()) + }) +} + +/// Give the multiple choice proposal `proposalId` of `ownerId` what the arguments change and +/// broadcast the replace, signed via `signerHandle`: the JNI bridge over +/// `platform_wallet_multiple_choice_proposal_edit`. The wallet reads the proposal once, edits +/// it at the revision after the one read and picks the signing key as the create does; if +/// another edit landed in between, Platform refuses this one (consensus code 40106) rather +/// than overwrite it. +/// +/// `title` and `url` null keep their value, and so do the three description document +/// arguments when all are null; `removeDescriptionDocument` and `removeUrl` remove theirs +/// (the wallet refuses either together with a new value). `ownerId` and `proposalId` are +/// 32-byte ids. +/// +/// Returns the confirmed document's canonical JSON at its new revision, its Rust string +/// freed here. Null after throwing; a proposal that does not exist is the wallet's +/// `NotFound`. +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_MultipleChoiceProposalsNative_edit( + mut env: JNIEnv, + _class: JClass, + wallet_handle: jlong, + owner_id: JByteArray, + proposal_id: JByteArray, + title: JString, + description_document_id: JByteArray, + description_document_contract_id: JByteArray, + description_document_type: JString, + remove_description_document: jboolean, + url: JString, + remove_url: jboolean, + signer_handle: jlong, +) -> jstring { + guard(&mut env, ptr::null_mut(), |env| { + let Some(owner) = read_bytes32(env, &owner_id, "ownerId") else { + return ptr::null_mut(); + }; + let Some(proposal) = read_bytes32(env, &proposal_id, "proposalId") else { + return ptr::null_mut(); + }; + let Some(title) = read_optional_cstring(env, &title, "title") else { + return ptr::null_mut(); + }; + let Some(described) = DescriptionDocumentArgs::read( + env, + &description_document_id, + &description_document_contract_id, + &description_document_type, + ) else { + return ptr::null_mut(); + }; + let Some(url) = read_optional_cstring(env, &url, "url") else { + return ptr::null_mut(); + }; + + let described = described.as_ffi(); + let edit = MultipleChoiceProposalEditFFI { + title: c_ptr(&title), + description_document: description_document_ptr(&described), + remove_description_document: remove_description_document != 0, + url: c_ptr(&url), + remove_url: remove_url != 0, + }; + let mut out_json: *mut c_char = ptr::null_mut(); + // SAFETY: `owner` and `proposal` are 32 bytes, `edit` and everything it points to + // outlive the call, and the signer handle is the Kotlin manager's live signer. + let result = unsafe { + platform_wallet_multiple_choice_proposal_edit( + wallet_handle as Handle, + owner.as_ptr(), + proposal.as_ptr(), + &edit, + signer_handle as *mut SignerHandle, + &mut out_json, + ) + }; + if take_pwffi_error(env, result) { + return ptr::null_mut(); + } + // SAFETY: on success `out_json` is the wallet's string, freed by this call only. + let Some(json) = + (unsafe { take_wallet_json(env, out_json, "multiple choice proposal edit") }) + else { + return ptr::null_mut(); + }; + env.new_string(json) + .map(|s| s.into_raw()) + .unwrap_or(ptr::null_mut()) + }) +} + +/// Enter a choice of `ownerId` for the multiple choice proposal `proposalId` and broadcast +/// it, signed via `signerHandle`: the JNI bridge over +/// `platform_wallet_multiple_choice_proposal_enter_choice`. The wallet builds the choice, +/// whose put states the fund of the contest among the proposal's choices (paid by the owner +/// on top of the fees), picks the signing key, broadcasts and waits for Platform to confirm. +/// +/// `description` may be null (none). `outChoiceId` must be a non-null `byte[32]`, checked +/// before anything is broadcast; it receives the choice's id, the id a masternode vote +/// towards it names. +/// +/// Returns the confirmed document's canonical JSON, its Rust string freed here. Null after +/// throwing; a refusal by Platform carries its consensus code. +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_MultipleChoiceProposalsNative_enterChoice( + mut env: JNIEnv, + _class: JClass, + wallet_handle: jlong, + owner_id: JByteArray, + proposal_id: JByteArray, + title: JString, + description: JString, + signer_handle: jlong, + out_choice_id: JByteArray, +) -> jstring { + guard(&mut env, ptr::null_mut(), |env| { + // Checked before the paid put, as the create checks its out-array. + if !is_byte_array_of_len(env, &out_choice_id, 32) { + throw_sdk_exception(env, 1, "outChoiceId must be a non-null byte[32]"); + return ptr::null_mut(); + } + let Some(owner) = read_bytes32(env, &owner_id, "ownerId") else { + return ptr::null_mut(); + }; + let Some(proposal) = read_bytes32(env, &proposal_id, "proposalId") else { + return ptr::null_mut(); + }; + let Some(title) = read_cstring(env, &title, "title") else { + return ptr::null_mut(); + }; + let Some(description) = read_optional_cstring(env, &description, "description") else { + return ptr::null_mut(); + }; + + let params = ChoiceParamsFFI { + title: title.as_ptr(), + description: c_ptr(&description), + }; + let mut choice_id = [0u8; 32]; + let mut out_json: *mut c_char = ptr::null_mut(); + // SAFETY: `owner`, `proposal` and `choice_id` are 32 bytes, `params` and the strings + // it points to outlive the call, and the signer handle is the Kotlin manager's live + // signer. + let result = unsafe { + platform_wallet_multiple_choice_proposal_enter_choice( + wallet_handle as Handle, + owner.as_ptr(), + proposal.as_ptr(), + ¶ms, + signer_handle as *mut SignerHandle, + choice_id.as_mut_ptr(), + &mut out_json, + ) + }; + if take_pwffi_error(env, result) { + return ptr::null_mut(); + } + // SAFETY: on success `out_json` is the wallet's string, freed by this call only. + let Some(json) = + (unsafe { take_wallet_json(env, out_json, "multiple choice proposal enter choice") }) + else { + return ptr::null_mut(); + }; + if !write_created_id(env, &out_choice_id, choice_id, "the choice") { + return ptr::null_mut(); + } + env.new_string(json) + .map(|s| s.into_raw()) + .unwrap_or(ptr::null_mut()) + }) +} + +// ── Reads ──────────────────────────────────────────────────────────────── + +/// A multiple choice proposal by id as the proposal JSON object +/// (`dash_sdk_multiple_choice_proposal_fetch`); null when there is none, and after throwing. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_MultipleChoiceProposalsNative_fetch( + mut env: JNIEnv, + _class: JClass, + sdk: jlong, + proposal_id: JString, +) -> jstring { + guard(&mut env, ptr::null_mut(), |env| { + let Some(id) = read_cstring(env, &proposal_id, "proposalId") else { + return ptr::null_mut(); + }; + unsafe { + let result = + dash_sdk_multiple_choice_proposal_fetch(sdk as *const SDKHandle, id.as_ptr()); + string_or_null(env, result) + } + }) +} + +/// One page of an identity's multiple choice proposals in filing order +/// (`dash_sdk_multiple_choice_proposal_list_by_owner`), as a JSON array of proposals. `limit` +/// 0 is Platform's cap of 100; `startAfter` (base58) is null for the first page. Null after +/// throwing. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_MultipleChoiceProposalsNative_listByOwner( + mut env: JNIEnv, + _class: JClass, + sdk: jlong, + owner_id: JString, + limit: jint, + start_after: JString, +) -> jstring { + guard(&mut env, ptr::null_mut(), |env| { + let Some(owner) = read_cstring(env, &owner_id, "ownerId") else { + return ptr::null_mut(); + }; + let Some(limit) = to_unsigned(env, limit.into(), "limit") else { + return ptr::null_mut(); + }; + let Some(start_after) = read_optional_cstring(env, &start_after, "startAfter") else { + return ptr::null_mut(); + }; + unsafe { + let result = dash_sdk_multiple_choice_proposal_list_by_owner( + sdk as *const SDKHandle, + owner.as_ptr(), + limit, + c_ptr(&start_after), + ); + string_or_null(env, result) + } + }) +} + +/// One page of every multiple choice proposal, newest first +/// (`dash_sdk_multiple_choice_proposal_list_by_created_at`), as a JSON array of proposals. +/// Paging as for `listByOwner`. Null after throwing. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_MultipleChoiceProposalsNative_listByCreatedAt( + mut env: JNIEnv, + _class: JClass, + sdk: jlong, + limit: jint, + start_after: JString, +) -> jstring { + guard(&mut env, ptr::null_mut(), |env| { + let Some(limit) = to_unsigned(env, limit.into(), "limit") else { + return ptr::null_mut(); + }; + let Some(start_after) = read_optional_cstring(env, &start_after, "startAfter") else { + return ptr::null_mut(); + }; + unsafe { + let result = dash_sdk_multiple_choice_proposal_list_by_created_at( + sdk as *const SDKHandle, + limit, + c_ptr(&start_after), + ); + string_or_null(env, result) + } + }) +} + +/// The vote among a proposal's choices as JSON (`dash_sdk_multiple_choice_proposal_get_vote`): +/// every choice with its tally, the other tallies, and how the vote ended once it did. Null +/// after throwing. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_MultipleChoiceProposalsNative_getVote( + mut env: JNIEnv, + _class: JClass, + sdk: jlong, + proposal_id: JString, +) -> jstring { + guard(&mut env, ptr::null_mut(), |env| { + let Some(id) = read_cstring(env, &proposal_id, "proposalId") else { + return ptr::null_mut(); + }; + unsafe { + let result = + dash_sdk_multiple_choice_proposal_get_vote(sdk as *const SDKHandle, id.as_ptr()); + string_or_null(env, result) + } + }) +} + +/// The choice a proposal's finished vote kept, as the choice JSON object +/// (`dash_sdk_multiple_choice_proposal_get_kept_choice`); null while the vote runs and when +/// it kept none, and after throwing. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_MultipleChoiceProposalsNative_getKeptChoice( + mut env: JNIEnv, + _class: JClass, + sdk: jlong, + proposal_id: JString, +) -> jstring { + guard(&mut env, ptr::null_mut(), |env| { + let Some(id) = read_cstring(env, &proposal_id, "proposalId") else { + return ptr::null_mut(); + }; + unsafe { + let result = dash_sdk_multiple_choice_proposal_get_kept_choice( + sdk as *const SDKHandle, + id.as_ptr(), + ); + string_or_null(env, result) + } + }) +} + +/// A masternode's answer in the vote among a proposal's choices, `{"choice", "choiceId"}` +/// (`dash_sdk_multiple_choice_proposal_get_masternode_vote`); null when it has not voted or +/// the vote ended, and after throwing. `voterProTxHash` is the 32-byte pro_tx_hash in wire +/// order, the same bytes `castVote` takes. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_MultipleChoiceProposalsNative_getMasternodeVote( + mut env: JNIEnv, + _class: JClass, + sdk: jlong, + voter_pro_tx_hash: JByteArray, + proposal_id: JString, +) -> jstring { + guard(&mut env, ptr::null_mut(), |env| { + let Some(pro_tx_hash) = read_bytes32(env, &voter_pro_tx_hash, "voterProTxHash") else { + return ptr::null_mut(); + }; + let Some(id) = read_cstring(env, &proposal_id, "proposalId") else { + return ptr::null_mut(); + }; + unsafe { + let result = dash_sdk_multiple_choice_proposal_get_masternode_vote( + sdk as *const SDKHandle, + pro_tx_hash.as_ptr(), + id.as_ptr(), + ); + string_or_null(env, result) + } + }) +} + +/// What creating one multiple choice proposal adds to the processing fee of its batch, in +/// credits as a decimal string, not JSON +/// (`dash_sdk_multiple_choice_proposal_get_processing_fee`). Null after throwing. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_MultipleChoiceProposalsNative_getProcessingFee( + mut env: JNIEnv, + _class: JClass, + sdk: jlong, +) -> jstring { + guard(&mut env, ptr::null_mut(), |env| unsafe { + let result = dash_sdk_multiple_choice_proposal_get_processing_fee(sdk as *const SDKHandle); + string_or_null(env, result) + }) +} + +/// The fund a choice entered now for a proposal pays, in credits as a decimal string, not +/// JSON (`dash_sdk_multiple_choice_proposal_get_choice_fund_to_join`). Null after throwing. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_MultipleChoiceProposalsNative_getChoiceFundToJoin( + mut env: JNIEnv, + _class: JClass, + sdk: jlong, + proposal_id: JString, +) -> jstring { + guard(&mut env, ptr::null_mut(), |env| { + let Some(id) = read_cstring(env, &proposal_id, "proposalId") else { + return ptr::null_mut(); + }; + unsafe { + let result = dash_sdk_multiple_choice_proposal_get_choice_fund_to_join( + sdk as *const SDKHandle, + id.as_ptr(), + ); + string_or_null(env, result) + } + }) +} + +// ── Vote ───────────────────────────────────────────────────────────────── + +/// Vote among a multiple choice proposal's choices for a masternode and wait for the +/// response (`dash_sdk_multiple_choice_proposal_cast_vote`). +/// +/// * `voteChoice` - `0` for the choice `choiceId` names, `1` none of the choices, `2` +/// abstain; rs-sdk-ffi refuses any other value. A value outside `u8` is refused here +/// rather than wrapped onto a valid answer. +/// * `choiceId` - the document id (base58) of the choice voted for, null for the answers +/// that name none; rs-sdk-ffi refuses a missing or a superfluous one. +/// * `voterProTxHash` / `votingPrivateKey` - each a 32-byte `byte[]`; the pro_tx_hash in wire +/// order, as for `DecisionProposalsNative.castVote`. The key is read through a zeroizing +/// buffer. +/// * `networkOrd` - `Network.ffiValue`, used for the signer's WIF encoding only. +/// +/// Returns nothing on success; throws on error. A vote from a wallet that is not a +/// masternode is refused by Platform (no voter identity), the expected outcome. +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_MultipleChoiceProposalsNative_castVote( + mut env: JNIEnv, + _class: JClass, + sdk: jlong, + proposal_id: JString, + vote_choice: jint, + choice_id: JString, + voter_pro_tx_hash: JByteArray, + voting_private_key: JByteArray, + network_ord: jint, +) { + guard(&mut env, (), |env| { + let Some(id) = read_cstring(env, &proposal_id, "proposalId") else { + return; + }; + let Some(choice) = to_unsigned(env, vote_choice.into(), "voteChoice") else { + return; + }; + let Some(choice_id) = read_optional_cstring(env, &choice_id, "choiceId") else { + return; + }; + let Some(pro_tx_hash) = read_bytes32(env, &voter_pro_tx_hash, "voterProTxHash") else { + return; + }; + let Some(voting_key) = read_key32_zeroizing(env, &voting_private_key, "votingPrivateKey") + else { + return; + }; + let result = unsafe { + dash_sdk_multiple_choice_proposal_cast_vote( + sdk as *const SDKHandle, + id.as_ptr(), + choice, + c_ptr(&choice_id), + pro_tx_hash.as_ptr(), + voting_key.as_ptr(), + net_from_ord(network_ord), + ) + }; + // Success carries no payload; take_error throws and frees on error. + unsafe { take_error(env, &result) }; + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::decision_proposals::tests::kotlin_signature_in; + use std::ffi::CStr; + + const MULTIPLE_CHOICE_PROPOSALS_NATIVE_KT: &str = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/MultipleChoiceProposalsNative.kt" + )); + + /// The parameter types and the return type of `external fun {name}(...)` in + /// `MultipleChoiceProposalsNative.kt`. + fn kotlin_signature(name: &str) -> (Vec, String) { + kotlin_signature_in(MULTIPLE_CHOICE_PROPOSALS_NATIVE_KT, name) + } + + fn types(types: [&str; N]) -> Vec { + types.map(String::from).to_vec() + } + + /// JNI binds an export by its name alone: a Kotlin declaration whose parameters drifted + /// from the export's would hand it the wrong JVM values at run time, which only an + /// instrumented test would otherwise catch. The wallet writes take the most arguments, + /// and the last of the two that create a document is the id out-array. + #[test] + fn should_declare_the_multiple_choice_wallet_writes_as_the_exports_take_them() { + assert_eq!( + kotlin_signature("create"), + ( + types([ + "Long", // wallet_handle + "ByteArray", // owner_id + "String", // title + "ByteArray?", // description_document_id + "ByteArray?", // description_document_contract_id + "String?", // description_document_type + "String?", // url + "Boolean", // open + "Long", // signer_handle + "ByteArray", // out_proposal_id + ]), + "String".to_string() + ) + ); + assert_eq!( + kotlin_signature("edit"), + ( + types([ + "Long", // wallet_handle + "ByteArray", // owner_id + "ByteArray", // proposal_id + "String?", // title + "ByteArray?", // description_document_id + "ByteArray?", // description_document_contract_id + "String?", // description_document_type + "Boolean", // remove_description_document + "String?", // url + "Boolean", // remove_url + "Long", // signer_handle + ]), + "String".to_string() + ) + ); + assert_eq!( + kotlin_signature("enterChoice"), + ( + types([ + "Long", // wallet_handle + "ByteArray", // owner_id + "ByteArray", // proposal_id + "String", // title + "String?", // description + "Long", // signer_handle + "ByteArray", // out_choice_id + ]), + "String".to_string() + ) + ); + } + + /// The vote takes the choice id between the answer and the masternode's credentials. + #[test] + fn should_declare_the_multiple_choice_vote_as_the_export_takes_it() { + assert_eq!( + kotlin_signature("castVote"), + ( + types([ + "Long", // sdk + "String", // proposal_id + "Int", // vote_choice + "String?", // choice_id + "ByteArray", // voter_pro_tx_hash + "ByteArray", // voting_private_key + "Int", // network_ord + ]), + "Unit".to_string() + ) + ); + } + + /// No description document is a null struct pointer, never a struct of null fields: the + /// platform wallet reads the first as "none" and refuses the second. + #[test] + fn should_pass_no_multiple_choice_description_document_as_a_null_pointer() { + let absent = DescriptionDocumentArgs { + id: None, + contract_id: None, + document_type: None, + }; + let described = absent.as_ffi(); + assert!(described.is_none()); + assert!(description_document_ptr(&described).is_null()); + } + + #[test] + fn should_point_the_multiple_choice_description_document_at_each_part_given() { + let complete = DescriptionDocumentArgs { + id: Some([5; 32]), + contract_id: Some([6; 32]), + document_type: Some(CString::new("post").expect("no NUL")), + }; + let described = complete.as_ffi(); + let pointer = description_document_ptr(&described); + assert!(!pointer.is_null()); + // SAFETY: `pointer` points into `described`, whose fields point into `complete`; + // both are alive here. + unsafe { + let read = &*pointer; + assert_eq!(std::slice::from_raw_parts(read.id, 32), [5u8; 32]); + assert_eq!(std::slice::from_raw_parts(read.contract_id, 32), [6u8; 32]); + assert_eq!(CStr::from_ptr(read.document_type).to_bytes(), b"post"); + } + + // A part left out reaches the platform wallet as a null field, which it refuses. + let partial = DescriptionDocumentArgs { + id: Some([5; 32]), + contract_id: None, + document_type: None, + }; + let described = partial.as_ffi().expect("a struct for a partial document"); + assert!(!described.id.is_null()); + assert!(described.contract_id.is_null()); + assert!(described.document_type.is_null()); + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWalletMultipleChoiceProposals.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWalletMultipleChoiceProposals.swift new file mode 100644 index 00000000000..08906713af4 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWalletMultipleChoiceProposals.swift @@ -0,0 +1,261 @@ +import Foundation +import DashSDKFFI + +// MARK: - Multiple choice proposals (protocol version 15) +// +// Creating and editing a multiple choice proposal and entering a choice are +// platform wallet operations (`platform_wallet_multiple_choice_proposal_create`, +// `_edit` and `_enter_choice`, over +// `IdentityWallet::create_multiple_choice_proposal_with_signer`, +// `edit_multiple_choice_proposal_with_signer` and `enter_choice_with_signer`). +// rs-sdk and the wallet decide everything: the documents' properties, the +// contest fund a choice states, the signing key, refusing an edit that +// changes nothing, and the revision an edit is put at. These wrappers marshal +// the arguments in and the confirmed document out; the signing key never +// crosses into Swift logic, the `KeychainSigner` trampoline services the +// signature on demand. + +extension ManagedPlatformWallet { + /// Create + broadcast a multiple choice proposal of `ownerIdentityId` + /// asking what `params` says. Returns the proposal's 32-byte id and the + /// confirmed document's canonical JSON (the shape + /// ``createDocument(ownerIdentityId:contractId:documentType:propertiesJSON:signer:maxContestFund:)`` + /// returns) once Platform confirms the transition. + /// + /// rs-sdk builds the proposal. Platform charges the owner the multiple + /// choice proposal processing fee + /// (``SDK/multipleChoiceProposalProcessingFee()``, 0.2 Dash) on top of + /// the fees; the create does not state it. The wallet signs with the + /// owner's first AUTHENTICATION + ECDSA key at a security level the + /// `multipleChoiceProposal` type accepts that `signer` holds. Platform + /// judges the title, the description document and the url; nothing is + /// checked here. A network below protocol version 15 has no decision + /// proposals, which is an error. + /// + /// Lifetime contract: as `createDocument`, the `signer` is pinned with + /// `withExtendedLifetime` across the synchronous FFI call (Rust holds a + /// `passUnretained` ctx pointer to it), and so is the wallet, whose + /// deinit destroys the handle the call uses. + /// + /// - Parameters: + /// - ownerIdentityId: The proposer's 32-byte identity id. + /// - params: The question. + /// - signer: Signs the create. + /// - Throws: `PlatformWalletError.invalidParameter` for an id that is not + /// 32 bytes or a string holding a NUL character; a refusal by Platform + /// as `PlatformWalletError.consensusRejection`, with its consensus code. + public func createMultipleChoiceProposal( + ownerIdentityId: Identifier, + params: MultipleChoiceProposalParams, + signer: KeychainSigner + ) async throws -> (Identifier, String) { + // The FFI reads exactly 32 bytes of the identifier. + guard ownerIdentityId.count == 32 else { + throw PlatformWalletError.invalidParameter("ownerIdentityId must be exactly 32 bytes") + } + let handle = self.handle + let signerHandle = signer.handle + let ownerBytes = [UInt8](ownerIdentityId) + return try await Task.detached(priority: .userInitiated) { [self] in + var proposalIdBytes = [UInt8](repeating: 0, count: 32) + // Receives an owned canonical-document JSON C string on success; + // freed with `platform_wallet_string_free` below. + var documentJsonPtr: UnsafeMutablePointer? = nil + defer { if let p = documentJsonPtr { platform_wallet_string_free(p) } } + + // Pin the wallet and `signer` for the whole FFI call (see + // `createDocument` for why a bare `_ = signer` is unreliable + // under -O): a wallet deinit mid-call would destroy the handle + // the FFI is still using. Rust reads the params synchronously + // inside the call, so the `withFFI` scope is long enough. + let result = try withExtendedLifetime((self, signer)) { + try ownerBytes.withUnsafeBufferPointer { ownerBp -> PlatformWalletFFIResult in + try params.withFFI { paramsPtr in + proposalIdBytes.withUnsafeMutableBufferPointer { outBp in + platform_wallet_multiple_choice_proposal_create( + handle, + ownerBp.baseAddress!, + paramsPtr, + signerHandle, + outBp.baseAddress!, + &documentJsonPtr + ) + } + } + } + } + + try result.check() + // On success the Rust side always writes the JSON; a null pointer + // is an FFI contract violation, not an empty proposal. + guard let jsonPtr = documentJsonPtr else { + throw PlatformWalletError.walletOperation( + "multiple_choice_proposal_create returned no canonical document JSON" + ) + } + return (Data(proposalIdBytes), String(cString: jsonPtr)) + }.value + } + + /// Give the multiple choice proposal `proposalId` of `ownerIdentityId` + /// what `edit` changes, and broadcast the replace. Returns the confirmed + /// document's canonical JSON, at its new revision, once Platform confirms + /// the transition. + /// + /// The wallet reads the proposal once, applies the edit with rs-sdk + /// (which refuses an edit that changes nothing) and puts it at the + /// revision after the one read, signed with a key chosen as + /// ``createMultipleChoiceProposal(ownerIdentityId:params:signer:)`` + /// chooses it. It never reads the proposal again before the put: if + /// another edit lands in between, Platform refuses this one instead of + /// overwriting it (consensus code 40106, `InvalidDocumentRevisionError`), + /// and the caller reads the proposal again before offering the edit anew. + /// Platform also refuses an edit more than two hours after the proposal + /// was created, and one that leaves it with neither a description + /// document nor a url. + /// + /// Lifetime contract: the wallet and the `signer` are pinned with + /// `withExtendedLifetime` across the synchronous FFI call, as the create + /// pins them. + /// + /// - Parameters: + /// - ownerIdentityId: The proposer's 32-byte identity id. + /// - proposalId: The proposal's 32-byte id. + /// - edit: What changes. + /// - signer: Signs the replace. + /// - Throws: `PlatformWalletError.notFound` when there is no such + /// proposal; `PlatformWalletError.invalidParameter` for an id that is + /// not 32 bytes, a string holding a NUL character, a proposal of another + /// identity or an edit that changes nothing; a refusal by Platform as + /// `PlatformWalletError.consensusRejection`, with its consensus code. + public func editMultipleChoiceProposal( + ownerIdentityId: Identifier, + proposalId: Identifier, + edit: MultipleChoiceProposalEdit, + signer: KeychainSigner + ) async throws -> String { + // The FFI reads exactly 32 bytes of each identifier. + guard ownerIdentityId.count == 32 else { + throw PlatformWalletError.invalidParameter("ownerIdentityId must be exactly 32 bytes") + } + guard proposalId.count == 32 else { + throw PlatformWalletError.invalidParameter("proposalId must be exactly 32 bytes") + } + let handle = self.handle + let signerHandle = signer.handle + let ownerBytes = [UInt8](ownerIdentityId) + let proposalBytes = [UInt8](proposalId) + return try await Task.detached(priority: .userInitiated) { [self] in + var documentJsonPtr: UnsafeMutablePointer? = nil + defer { if let p = documentJsonPtr { platform_wallet_string_free(p) } } + + // Pin the wallet and `signer` for the whole FFI call, as the + // create does. + let result = try withExtendedLifetime((self, signer)) { + try ownerBytes.withUnsafeBufferPointer { ownerBp -> PlatformWalletFFIResult in + try proposalBytes.withUnsafeBufferPointer { proposalBp -> PlatformWalletFFIResult in + try edit.withFFI { editPtr in + platform_wallet_multiple_choice_proposal_edit( + handle, + ownerBp.baseAddress!, + proposalBp.baseAddress!, + editPtr, + signerHandle, + &documentJsonPtr + ) + } + } + } + } + + try result.check() + guard let jsonPtr = documentJsonPtr else { + throw PlatformWalletError.walletOperation( + "multiple_choice_proposal_edit returned no canonical document JSON" + ) + } + return String(cString: jsonPtr) + }.value + } + + /// Enter the choice `params` describes, owned by `ownerIdentityId`, for + /// the multiple choice proposal `proposalId`, and broadcast it. Returns + /// the choice's 32-byte id (the id a masternode vote for it names) and + /// the confirmed document's canonical JSON once Platform confirms the + /// transition. + /// + /// rs-sdk builds the choice; its put reads the fund of the contest among + /// the proposal's choices just before it is signed and states it + /// (``SDK/multipleChoiceProposalChoiceFundToJoin(proposalId:)`` reads the + /// same amount), which the owner pays on top of the fees. The first + /// choice opens the vote. Platform refuses a choice for a proposal that + /// is not open from anyone but its owner, and one entered once the vote's + /// join window closed. A choice is never edited. + /// + /// Lifetime contract: the wallet and the `signer` are pinned with + /// `withExtendedLifetime` across the synchronous FFI call, as the create + /// pins them. + /// + /// - Parameters: + /// - ownerIdentityId: The 32-byte id of the identity entering the + /// choice. + /// - proposalId: The proposal's 32-byte id. + /// - params: The answer. + /// - signer: Signs the create. + /// - Throws: `PlatformWalletError.invalidParameter` for an id that is not + /// 32 bytes or a string holding a NUL character; a refusal by Platform + /// as `PlatformWalletError.consensusRejection`, with its consensus code. + public func enterMultipleChoiceProposalChoice( + ownerIdentityId: Identifier, + proposalId: Identifier, + params: ProposalChoiceParams, + signer: KeychainSigner + ) async throws -> (Identifier, String) { + // The FFI reads exactly 32 bytes of each identifier. + guard ownerIdentityId.count == 32 else { + throw PlatformWalletError.invalidParameter("ownerIdentityId must be exactly 32 bytes") + } + guard proposalId.count == 32 else { + throw PlatformWalletError.invalidParameter("proposalId must be exactly 32 bytes") + } + let handle = self.handle + let signerHandle = signer.handle + let ownerBytes = [UInt8](ownerIdentityId) + let proposalBytes = [UInt8](proposalId) + return try await Task.detached(priority: .userInitiated) { [self] in + var choiceIdBytes = [UInt8](repeating: 0, count: 32) + var documentJsonPtr: UnsafeMutablePointer? = nil + defer { if let p = documentJsonPtr { platform_wallet_string_free(p) } } + + // Pin the wallet and `signer` for the whole FFI call, as the + // create does. + let result = try withExtendedLifetime((self, signer)) { + try ownerBytes.withUnsafeBufferPointer { ownerBp -> PlatformWalletFFIResult in + try proposalBytes.withUnsafeBufferPointer { proposalBp -> PlatformWalletFFIResult in + try params.withFFI { paramsPtr in + choiceIdBytes.withUnsafeMutableBufferPointer { outBp in + platform_wallet_multiple_choice_proposal_enter_choice( + handle, + ownerBp.baseAddress!, + proposalBp.baseAddress!, + paramsPtr, + signerHandle, + outBp.baseAddress!, + &documentJsonPtr + ) + } + } + } + } + } + + try result.check() + guard let jsonPtr = documentJsonPtr else { + throw PlatformWalletError.walletOperation( + "multiple_choice_proposal_enter_choice returned no canonical document JSON" + ) + } + return (Data(choiceIdBytes), String(cString: jsonPtr)) + }.value + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Voting/MultipleChoiceProposal.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Voting/MultipleChoiceProposal.swift new file mode 100644 index 00000000000..10c12acb943 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Voting/MultipleChoiceProposal.swift @@ -0,0 +1,437 @@ +import Foundation +import DashSDKFFI + +// MARK: - Proposal + +/// A multiple choice proposal: a question an identity puts to the +/// masternodes, answered by the choices entered for it. Decoded from the JSON +/// every multiple choice proposal read returns +/// (`dash_sdk_multiple_choice_proposal_fetch` and the two listings). +public struct MultipleChoiceProposal: Decodable, Sendable, Equatable, Hashable, Identifiable { + /// The document a proposal points at for what is being decided. + public struct DescriptionDocument: Decodable, Sendable, Equatable, Hashable { + /// The document's id, base58. + public let id: String + /// The id of the contract it lives in, base58. + public let contractId: String + /// Its document type. + public let documentType: String + } + + /// The proposal's id, base58. + public let id: String + /// The proposer's identity id, base58. + public let ownerId: String + /// `nil` when the document does not carry it. + public let revision: UInt64? + /// Milliseconds since the Unix epoch; `nil` when the document does not + /// carry it. + public let createdAtMs: UInt64? + /// Milliseconds since the Unix epoch; `nil` when the document does not + /// carry it. + public let updatedAtMs: UInt64? + /// The question, in one line. + public let title: String + /// The document saying what is being decided; `nil` when it has none. + public let descriptionDocument: DescriptionDocument? + /// Where what is being decided is described or discussed; `nil` when it + /// has none. + public let url: String? + /// Whether anyone may enter choices; only the proposer may when `false`. + public let open: Bool + + private enum CodingKeys: String, CodingKey { + case id + case ownerId + case revision + case createdAtMs = "createdAt" + case updatedAtMs = "updatedAt" + case title + case descriptionDocument + case url + case open + } + + /// When the proposal was created, if the document carries it. + public var createdAt: Date? { createdAtMs.map(Date.init(millisecondsSince1970:)) } + /// When the proposal was last edited, if the document carries it. + public var updatedAt: Date? { updatedAtMs.map(Date.init(millisecondsSince1970:)) } +} + +// MARK: - Choice + +/// A choice entered for a multiple choice proposal: one answer the +/// masternodes may vote for. Decoded from the choice JSON +/// (`dash_sdk_multiple_choice_proposal_get_kept_choice`, and each running +/// choice of ``MultipleChoiceProposalVote``). +public struct ProposalChoice: Decodable, Sendable, Equatable, Hashable, Identifiable { + /// The choice's document id, base58: the id a vote for it names. + public let id: String + /// The identity that entered it, base58. + public let ownerId: String + /// The proposal it answers, base58. + public let proposalId: String + /// `nil` when the document does not carry it. + public let revision: UInt64? + /// Milliseconds since the Unix epoch; `nil` when the document does not + /// carry it. + public let createdAtMs: UInt64? + /// Milliseconds since the Unix epoch; `nil` when the document does not + /// carry it. + public let updatedAtMs: UInt64? + /// The answer, in one line. + public let title: String + /// What voting for the answer means; `nil` when it has none. + public let description: String? + + private enum CodingKeys: String, CodingKey { + case id + case ownerId + case proposalId + case revision + case createdAtMs = "createdAt" + case updatedAtMs = "updatedAt" + case title + case description + } + + /// When the choice was entered, if the document carries it. + public var createdAt: Date? { createdAtMs.map(Date.init(millisecondsSince1970:)) } +} + +// MARK: - Vote + +/// The vote among a multiple choice proposal's choices +/// (`dash_sdk_multiple_choice_proposal_get_vote`). +public struct MultipleChoiceProposalVote: Decodable, Sendable, Equatable { + /// One choice in the vote. + public struct ChoiceInVote: Decodable, Sendable, Equatable, Identifiable { + /// The choice's document id, base58: the id a vote for it names. + public let id: String + /// The choice while the vote runs; `nil` once it ended (the choices + /// not kept are gone, and the kept one is read with + /// ``SDK/multipleChoiceProposalKeptChoice(proposalId:)``). + public let choice: ProposalChoice? + /// The votes for it; `nil` when Platform does not report it. + public let voteTally: UInt32? + } + + /// How a finished vote ended. + public enum Outcome: String, Decodable, Sendable, Equatable { + /// The choice ``Result/keptChoiceId`` names was kept. + case keptChoice + /// The votes for none of the choices outnumbered the leading choice; + /// no choice was kept. + case noneOfTheChoices + /// No choice won; none was kept. + case noWinner + } + + /// The record of a finished vote. + public struct Result: Decodable, Sendable, Equatable { + public let outcome: Outcome + /// The kept choice's id, base58; `nil` unless ``outcome`` is + /// ``Outcome/keptChoice``. + public let keptChoiceId: String? + /// The block the vote was closed in. + public let finalizationBlock: PlatformBlockInfo + } + + /// Every choice, ordered by choice id; empty for a proposal no choice + /// was entered for. + public let choices: [ChoiceInVote] + /// The abstaining votes; `nil` when Platform does not report them. + public let abstainVoteTally: UInt32? + /// The votes for none of the choices; `nil` when Platform does not + /// report them. + public let noneOfTheChoicesVoteTally: UInt32? + /// How the vote ended; `nil` while it runs. + public let result: Result? +} + +/// A masternode's answer in the vote among a multiple choice proposal's +/// choices, as rs-sdk's `MultipleChoiceVoteChoice`. +/// +/// Decodes the masternode-answer JSON +/// (`dash_sdk_multiple_choice_proposal_get_masternode_vote`): +/// `{"choice": "choice" | "noneOfTheChoices" | "abstain", "choiceId": ...}`. +/// ``ffiTag`` and ``choiceId`` are the `vote_choice` byte and `choice_id` +/// string `dash_sdk_multiple_choice_proposal_cast_vote` takes. +public enum MultipleChoiceVoteChoice: Decodable, Sendable, Equatable, Hashable { + /// For the choice whose document id (base58) is `id`, not the id of the + /// identity that entered it. + case choice(id: String) + /// For none of the choices: keeps no choice when these votes outnumber + /// the leading choice. + case noneOfTheChoices + case abstain + + /// The `vote_choice` byte passed across the FFI. The C parameter is a + /// plain `uint8_t` with no enum in the header, so the three values are + /// mirrored here and must agree with `MultipleChoiceVoteChoiceFFI` in + /// `packages/rs-sdk-ffi/src/decision_proposal/multiple_choice/mod.rs`: + /// `Choice = 0`, `NoneOfTheChoices = 1`, `Abstain = 2`. + var ffiTag: UInt8 { + switch self { + case .choice: return 0 + case .noneOfTheChoices: return 1 + case .abstain: return 2 + } + } + + /// The choice voted for, base58; `nil` for the answers that name none + /// (the FFI requires a null `choice_id` then). + public var choiceId: String? { + guard case .choice(let id) = self else { return nil } + return id + } + + private enum CodingKeys: String, CodingKey { + case choice + case choiceId + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let name = try container.decode(String.self, forKey: .choice) + switch name { + case "choice": + self = .choice(id: try container.decode(String.self, forKey: .choiceId)) + case "noneOfTheChoices": + self = .noneOfTheChoices + case "abstain": + self = .abstain + default: + throw DecodingError.dataCorruptedError( + forKey: .choice, + in: container, + debugDescription: "Unknown multiple choice vote answer \(name)" + ) + } + } +} + +// MARK: - Params + +/// The document a new or edited multiple choice proposal points at +/// (`DescriptionDocumentFFI`). Platform judges whether it may be pointed at; +/// nothing is checked here. +public struct DescriptionDocumentParams: Sendable, Equatable { + /// The document's 32-byte id. + public var id: Identifier + /// The 32-byte id of the contract it lives in. + public var contractId: Identifier + /// Its document type. + public var documentType: String + + public init(id: Identifier, contractId: Identifier, documentType: String) { + self.id = id + self.contractId = contractId + self.documentType = documentType + } +} + +/// The question of a new multiple choice proposal, as +/// `ManagedPlatformWallet.createMultipleChoiceProposal` passes it on +/// (`MultipleChoiceProposalParamsFFI`). Platform judges every value when the +/// proposal is created; nothing is checked here. +public struct MultipleChoiceProposalParams: Sendable, Equatable { + /// The question, in one line. + public var title: String + /// The document saying what is being decided; `nil` for none. + public var descriptionDocument: DescriptionDocumentParams? + /// Where what is being decided is described or discussed; `nil` for + /// none. + public var url: String? + /// Whether anyone may enter choices; only the proposer may when `false`. + /// It never changes. + public var open: Bool + + public init( + title: String, + descriptionDocument: DescriptionDocumentParams? = nil, + url: String? = nil, + open: Bool + ) { + self.title = title + self.descriptionDocument = descriptionDocument + self.url = url + self.open = open + } +} + +/// What a stored multiple choice proposal changes to, as +/// `ManagedPlatformWallet.editMultipleChoiceProposal` passes it on +/// (`MultipleChoiceProposalEditFFI`). A field left `nil` (or `.keep`) keeps +/// its value. rs-sdk refuses an edit that changes nothing; Platform accepts +/// an edit only within its window after the proposal was created, and never +/// a change to whether it is open. +public struct MultipleChoiceProposalEdit: Sendable, Equatable { + /// What happens to an optional field. + public enum Change: Sendable, Equatable { + /// Keep the value as it is (or keep having none). + case keep + /// Set the value. + case set(Value) + /// Remove the value. + case remove + } + + /// The new title; `nil` keeps it. + public var title: String? + /// The description document change. + public var descriptionDocument: Change + /// The url change. + public var url: Change + + public init( + title: String? = nil, + descriptionDocument: Change = .keep, + url: Change = .keep + ) { + self.title = title + self.descriptionDocument = descriptionDocument + self.url = url + } +} + +/// An answer to enter for a multiple choice proposal, as +/// `ManagedPlatformWallet.enterMultipleChoiceProposalChoice` passes it on +/// (`ChoiceParamsFFI`). Platform judges every value; nothing is checked here. +public struct ProposalChoiceParams: Sendable, Equatable { + /// The answer, in one line. + public var title: String + /// What voting for the answer means; `nil` for none. + public var description: String? + + public init(title: String, description: String? = nil) { + self.title = title + self.description = description + } +} + +// MARK: - FFI marshalling + +/// Run `body` with `document` as a `DescriptionDocumentFFI`, or with `nil` +/// when `document` is `nil`. The FFI reads exactly 32 bytes through each id +/// pointer, so an id of another length is refused before any pointer is +/// made; the document type goes through ``withDecisionProposalCString(_:field:invalid:_:)``. +func withDescriptionDocumentFFI( + _ document: DescriptionDocumentParams?, + _ body: (UnsafePointer?) throws -> R +) throws -> R { + guard let document else { return try body(nil) } + guard document.id.count == 32 else { + throw PlatformWalletError.invalidParameter("descriptionDocument.id must be exactly 32 bytes") + } + guard document.contractId.count == 32 else { + throw PlatformWalletError.invalidParameter( + "descriptionDocument.contractId must be exactly 32 bytes" + ) + } + let idBytes = [UInt8](document.id) + let contractIdBytes = [UInt8](document.contractId) + return try idBytes.withUnsafeBufferPointer { idBp in + try contractIdBytes.withUnsafeBufferPointer { contractBp in + try withDecisionProposalCString( + document.documentType, + field: "descriptionDocument.documentType", + invalid: PlatformWalletError.invalidParameter + ) { documentTypePtr in + let ffi = DescriptionDocumentFFI( + id: idBp.baseAddress, + contract_id: contractBp.baseAddress, + document_type: documentTypePtr + ) + return try withUnsafePointer(to: ffi) { try body($0) } + } + } + } +} + +extension MultipleChoiceProposalParams { + /// Run `body` with these params as a `MultipleChoiceProposalParamsFFI` + /// whose pointers stay valid for the call. A string holding a NUL or an + /// id that is not 32 bytes is refused with + /// `PlatformWalletError.invalidParameter` before `body` runs. + func withFFI(_ body: (UnsafePointer) throws -> R) throws -> R { + try withDecisionProposalCString( + title, field: "title", invalid: PlatformWalletError.invalidParameter + ) { titlePtr in + try withDescriptionDocumentFFI(descriptionDocument) { documentPtr in + try withDecisionProposalCString( + url, field: "url", invalid: PlatformWalletError.invalidParameter + ) { urlPtr in + let ffi = MultipleChoiceProposalParamsFFI( + title: titlePtr, + description_document: documentPtr, + url: urlPtr, + open: open + ) + return try withUnsafePointer(to: ffi) { try body($0) } + } + } + } + } +} + +extension MultipleChoiceProposalEdit.Change { + /// The change as the FFI writes it: the value to set (`nil` to keep or + /// remove) beside the remove flag. + var ffiParts: (value: Value?, remove: Bool) { + switch self { + case .keep: return (nil, false) + case .set(let value): return (value, false) + case .remove: return (nil, true) + } + } +} + +extension MultipleChoiceProposalEdit { + /// Run `body` with this edit as a `MultipleChoiceProposalEditFFI` whose + /// pointers stay valid for the call. `MultipleChoiceProposalEditFFI` + /// says "remove" with a flag beside a null value, so a `.set` never + /// raises the flag and a `.remove` never carries a value. A string + /// holding a NUL or an id that is not 32 bytes is refused with + /// `PlatformWalletError.invalidParameter` before `body` runs. + func withFFI(_ body: (UnsafePointer) throws -> R) throws -> R { + let documentChange = self.descriptionDocument.ffiParts + let urlChange = self.url.ffiParts + return try withDecisionProposalCString( + title, field: "title", invalid: PlatformWalletError.invalidParameter + ) { titlePtr in + try withDescriptionDocumentFFI(documentChange.value) { documentPtr in + try withDecisionProposalCString( + urlChange.value, field: "url", invalid: PlatformWalletError.invalidParameter + ) { urlPtr in + let ffi = MultipleChoiceProposalEditFFI( + title: titlePtr, + description_document: documentPtr, + remove_description_document: documentChange.remove, + url: urlPtr, + remove_url: urlChange.remove + ) + return try withUnsafePointer(to: ffi) { try body($0) } + } + } + } + } +} + +extension ProposalChoiceParams { + /// Run `body` with these params as a `ChoiceParamsFFI` whose pointers + /// stay valid for the call. A string holding a NUL is refused with + /// `PlatformWalletError.invalidParameter` before `body` runs. + func withFFI(_ body: (UnsafePointer) throws -> R) throws -> R { + try withDecisionProposalCString( + title, field: "title", invalid: PlatformWalletError.invalidParameter + ) { titlePtr in + try withDecisionProposalCString( + description, field: "description", invalid: PlatformWalletError.invalidParameter + ) { descriptionPtr in + let ffi = ChoiceParamsFFI(title: titlePtr, description: descriptionPtr) + return try withUnsafePointer(to: ffi) { try body($0) } + } + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+DecisionProposals.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+DecisionProposals.swift index 11ae35fc1e7..985007c0a26 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+DecisionProposals.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+DecisionProposals.swift @@ -261,9 +261,9 @@ extension SDK { // MARK: - FFI result handling /// Takes ownership of the `DashSDKResult`s the decision proposal functions -/// return: every owned string and error is freed on every path, so only -/// Swift values leave these functions. -private enum DecisionProposalFFI { +/// (yes/no and multiple choice) return: every owned string and error is +/// freed on every path, so only Swift values leave these functions. +enum DecisionProposalFFI { /// Throw the typed FFI error, freeing it. static func throwIfFailed(_ result: DashSDKResult) throws { guard let error = result.error else { return } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+MultipleChoiceProposals.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+MultipleChoiceProposals.swift new file mode 100644 index 00000000000..7aac79fdf10 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+MultipleChoiceProposals.swift @@ -0,0 +1,312 @@ +import Foundation +import DashSDKFFI + +// MARK: - Multiple choice proposals (protocol version 15) +// +// Thin bridges over the `dash_sdk_multiple_choice_proposal_*` functions of +// `rs-sdk-ffi`, which call +// `dash_sdk::platform::decision_proposals::multiple_choice`. rs-sdk decides +// everything: which documents are proposals and choices, the vote's +// contest, the fee and the fund. These wrappers marshal arguments in and +// decode the JSON out. Every string goes to C through +// ``withDecisionProposalCString(_:field:invalid:_:)``, which refuses one +// with an embedded NUL. +// +// Every read and the vote park their thread inside Rust until DAPI answers, +// so they run on the shared Platform query queue +// (``SDK/performBlockingQuery(_:)``) and the caller only awaits. +// +// Creating and editing a proposal and entering a choice are platform wallet +// operations: `ManagedPlatformWallet.createMultipleChoiceProposal`, +// `editMultipleChoiceProposal` and `enterMultipleChoiceProposalChoice`. + +extension SDK { + + // MARK: - Reads + + /// The multiple choice proposal `id` names, or `nil` when there is none + /// (`dash_sdk_multiple_choice_proposal_fetch`). + /// + /// - Parameter id: The proposal's id, base58. + public nonisolated func multipleChoiceProposal(id: String) async throws -> MultipleChoiceProposal? { + try await performBlockingQuery { handle in + let result = try withDecisionProposalCString( + id, field: "id", invalid: SDKError.invalidParameter + ) { idPtr in + dash_sdk_multiple_choice_proposal_fetch(handle, idPtr) + } + return try DecisionProposalFFI.consumeString(result).map { + try DecisionProposalJSON.decode(MultipleChoiceProposal.self, from: $0) + } + } + } + + /// One page of an identity's multiple choice proposals, in the order it + /// filed them (`dash_sdk_multiple_choice_proposal_list_by_owner`). + /// + /// - Parameters: + /// - ownerId: The proposer's identity id, base58. + /// - limit: The most proposals to return; `nil` for Platform's cap. + /// - startAfter: The id (base58) of the last proposal of the previous + /// page; `nil` for the first page. + /// - Returns: The page; one shorter than `limit` is the last. + public nonisolated func multipleChoiceProposalsByOwner( + ownerId: String, + limit: UInt32? = nil, + startAfter: String? = nil + ) async throws -> [MultipleChoiceProposal] { + try await performBlockingQuery { handle in + let result = try withDecisionProposalCString( + ownerId, field: "ownerId", invalid: SDKError.invalidParameter + ) { ownerPtr in + try withDecisionProposalCString( + startAfter, field: "startAfter", invalid: SDKError.invalidParameter + ) { startAfterPtr in + // 0 is the FFI's "Platform's cap". + dash_sdk_multiple_choice_proposal_list_by_owner( + handle, ownerPtr, limit ?? 0, startAfterPtr) + } + } + return try DecisionProposalFFI.consumeMultipleChoiceListing( + result, function: "dash_sdk_multiple_choice_proposal_list_by_owner") + } + } + + /// One page of every multiple choice proposal, newest first + /// (`dash_sdk_multiple_choice_proposal_list_by_created_at`). + /// + /// - Parameters: + /// - limit: The most proposals to return; `nil` for Platform's cap. + /// - startAfter: The id (base58) of the last proposal of the previous + /// page; `nil` for the first page. + public nonisolated func multipleChoiceProposalsByCreatedAt( + limit: UInt32? = nil, + startAfter: String? = nil + ) async throws -> [MultipleChoiceProposal] { + try await performBlockingQuery { handle in + let result = try withDecisionProposalCString( + startAfter, field: "startAfter", invalid: SDKError.invalidParameter + ) { startAfterPtr in + dash_sdk_multiple_choice_proposal_list_by_created_at(handle, limit ?? 0, startAfterPtr) + } + return try DecisionProposalFFI.consumeMultipleChoiceListing( + result, function: "dash_sdk_multiple_choice_proposal_list_by_created_at") + } + } + + /// The vote among a multiple choice proposal's choices: every choice with + /// its tally while the vote runs, and how it ended once it did + /// (`dash_sdk_multiple_choice_proposal_get_vote`). + /// + /// - Parameter proposalId: The proposal's id, base58. + public nonisolated func multipleChoiceProposalVote( + proposalId: String + ) async throws -> MultipleChoiceProposalVote { + try await performBlockingQuery { handle in + let result = try withDecisionProposalCString( + proposalId, field: "proposalId", invalid: SDKError.invalidParameter + ) { idPtr in + dash_sdk_multiple_choice_proposal_get_vote(handle, idPtr) + } + guard let json = try DecisionProposalFFI.consumeString(result) else { + throw SDKError.internalError("dash_sdk_multiple_choice_proposal_get_vote returned no data") + } + return try DecisionProposalJSON.decode(MultipleChoiceProposalVote.self, from: json) + } + } + + /// The choice the finished vote of a multiple choice proposal kept, or + /// `nil` while the vote runs, when it kept none of the choices, and for a + /// proposal no choice was entered for + /// (`dash_sdk_multiple_choice_proposal_get_kept_choice`). + /// + /// - Parameter proposalId: The proposal's id, base58. + public nonisolated func multipleChoiceProposalKeptChoice( + proposalId: String + ) async throws -> ProposalChoice? { + try await performBlockingQuery { handle in + let result = try withDecisionProposalCString( + proposalId, field: "proposalId", invalid: SDKError.invalidParameter + ) { idPtr in + dash_sdk_multiple_choice_proposal_get_kept_choice(handle, idPtr) + } + return try DecisionProposalFFI.consumeString(result).map { + try DecisionProposalJSON.decode(ProposalChoice.self, from: $0) + } + } + } + + /// A masternode's answer in the vote among a multiple choice proposal's + /// choices, or `nil` when it has not voted in it or the vote has ended + /// (`dash_sdk_multiple_choice_proposal_get_masternode_vote`). + /// + /// - Parameters: + /// - proposalId: The proposal's id, base58. + /// - proTxHash: The masternode's 32-byte pro_tx_hash in **wire order**, + /// the same bytes + /// ``castMultipleChoiceProposalVote(proposalId:choice:proTxHash:votingPrivateKey:)`` + /// takes. + public nonisolated func multipleChoiceProposalMasternodeVote( + proposalId: String, + proTxHash: Data + ) async throws -> MultipleChoiceVoteChoice? { + // The FFI reads exactly 32 bytes through the pointer. + guard proTxHash.count == 32 else { + throw SDKError.invalidParameter("proTxHash must be exactly 32 bytes") + } + return try await performBlockingQuery { handle in + let result = try proTxHash.withUnsafeBytes { proTxPtr in + try withDecisionProposalCString( + proposalId, field: "proposalId", invalid: SDKError.invalidParameter + ) { idPtr in + dash_sdk_multiple_choice_proposal_get_masternode_vote( + handle, + proTxPtr.bindMemory(to: UInt8.self).baseAddress, + idPtr + ) + } + } + return try DecisionProposalFFI.consumeString(result).map { + try DecisionProposalJSON.decode(MultipleChoiceVoteChoice.self, from: $0) + } + } + } + + // MARK: - Fee and fund + + /// What creating one multiple choice proposal adds to the processing fee + /// of its batch, in credits, which Platform charges the proposer on top + /// of the fees (`dash_sdk_multiple_choice_proposal_get_processing_fee`). + /// A network below protocol version 15 has no multiple choice proposals, + /// which is an error. + public nonisolated func multipleChoiceProposalProcessingFee() async throws -> UInt64 { + try await performBlockingQuery { handle in + try DecisionProposalFFI.consumeCredits( + dash_sdk_multiple_choice_proposal_get_processing_fee(handle), + function: "dash_sdk_multiple_choice_proposal_get_processing_fee" + ) + } + } + + /// The fund, in credits, a choice entered now for the multiple choice + /// proposal `proposalId` states + /// (`dash_sdk_multiple_choice_proposal_get_choice_fund_to_join`). The + /// choice's put reads and states it itself; this is for showing it + /// beforehand. + /// + /// - Parameter proposalId: The proposal's id, base58. + public nonisolated func multipleChoiceProposalChoiceFundToJoin( + proposalId: String + ) async throws -> UInt64 { + try await performBlockingQuery { handle in + let result = try withDecisionProposalCString( + proposalId, field: "proposalId", invalid: SDKError.invalidParameter + ) { idPtr in + dash_sdk_multiple_choice_proposal_get_choice_fund_to_join(handle, idPtr) + } + return try DecisionProposalFFI.consumeCredits( + result, function: "dash_sdk_multiple_choice_proposal_get_choice_fund_to_join") + } + } + + // MARK: - Vote + + /// Vote in the vote among a multiple choice proposal's choices for a + /// masternode and wait for Platform's response + /// (`dash_sdk_multiple_choice_proposal_cast_vote`). + /// + /// The vote is built, signed with the masternode voting key derived from + /// `votingPrivateKey` and broadcast on the Rust side, exactly as + /// ``castDecisionProposalVote(proposalId:choice:proTxHash:votingPrivateKey:)`` + /// does for a yes/no proposal. A wallet that is not a masternode has no + /// voter identity, so Platform refuses its vote. + /// + /// - Parameters: + /// - proposalId: The proposal's id, base58. + /// - choice: For a choice (by its document id), for none of the + /// choices, or abstain. + /// - proTxHash: The masternode's 32-byte pro_tx_hash in **wire order**, + /// not the byte order of the hex Core displays (see + /// ``castContestedResourceVote(dataContractId:documentTypeName:indexName:indexValues:choice:proTxHash:votingPrivateKey:)``). + /// - votingPrivateKey: The masternode's 32-byte voting private key. It + /// is not retained. + public nonisolated func castMultipleChoiceProposalVote( + proposalId: String, + choice: MultipleChoiceVoteChoice, + proTxHash: Data, + votingPrivateKey: Data + ) async throws { + // The FFI reads exactly 32 bytes through each pointer. + guard proTxHash.count == 32 else { + throw SDKError.invalidParameter("proTxHash must be exactly 32 bytes") + } + guard votingPrivateKey.count == 32 else { + throw SDKError.invalidParameter("votingPrivateKey must be exactly 32 bytes") + } + let voteChoice = choice.ffiTag + let choiceId = choice.choiceId + let networkValue = network.ffiValue + + try await performBlockingQuery { handle in + let result = try proTxHash.withUnsafeBytes { proTxPtr in + try votingPrivateKey.withUnsafeBytes { keyPtr in + try withDecisionProposalCString( + proposalId, field: "proposalId", invalid: SDKError.invalidParameter + ) { idPtr in + try withDecisionProposalCString( + choiceId, field: "choiceId", invalid: SDKError.invalidParameter + ) { choiceIdPtr in + dash_sdk_multiple_choice_proposal_cast_vote( + handle, + idPtr, + voteChoice, + choiceIdPtr, + proTxPtr.bindMemory(to: UInt8.self).baseAddress, + keyPtr.bindMemory(to: UInt8.self).baseAddress, + networkValue + ) + } + } + } + } + // No data on success. + _ = try DecisionProposalFFI.consumeString(result) + } + } +} + +// MARK: - FFI result handling + +extension DecisionProposalFFI { + /// A multiple choice listing page: a JSON array, `[]` when empty and + /// never no data. + static func consumeMultipleChoiceListing( + _ result: DashSDKResult, + function: String + ) throws -> [MultipleChoiceProposal] { + guard let json = try consumeString(result) else { + throw SDKError.internalError("\(function) returned no data") + } + return try DecisionProposalJSON.decode([MultipleChoiceProposal].self, from: json) + } + + /// An amount of credits, written by the FFI as a decimal string (not + /// JSON). + static func consumeCredits(_ result: DashSDKResult, function: String) throws -> UInt64 { + guard let string = try consumeString(result) else { + throw SDKError.internalError("\(function) returned no data") + } + return try DecisionProposalJSON.credits(from: string) + } +} + +extension DecisionProposalJSON { + /// The credits `string` writes as a decimal number, the form the fee and + /// fund reads return. + static func credits(from string: String) throws -> UInt64 { + guard let credits = UInt64(string) else { + throw SDKError.serializationError("Not an amount of credits: \(string)") + } + return credits + } +} diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DecisionProposals/MultipleChoiceProposalDetailView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DecisionProposals/MultipleChoiceProposalDetailView.swift new file mode 100644 index 00000000000..3a829785c84 --- /dev/null +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DecisionProposals/MultipleChoiceProposalDetailView.swift @@ -0,0 +1,603 @@ +import SwiftUI +import SwiftData +import SwiftDashSDK + +/// One multiple choice proposal: its question, its choices with their +/// tallies while the vote runs, how the vote ended and the kept choice once +/// it did, a masternode vote, entering a choice, and the edit for a proposal +/// a local identity filed. +/// +/// Everything shown is read from Platform through the `SDK` multiple choice +/// proposal wrappers on appear and on pull-to-refresh. Whether a vote, a +/// choice or an edit is accepted is Platform's call; this screen only +/// collects input and shows the outcome. +struct MultipleChoiceProposalDetailView: View { + @EnvironmentObject var appState: AppState + @EnvironmentObject var walletManager: PlatformWalletManager + @Query private var identities: [PersistentIdentity] + + @State private var proposal: MultipleChoiceProposal + @State private var vote: MultipleChoiceProposalVote? + /// `true` once the vote has been read, so "no choices" is not shown while + /// it is still loading. + @State private var voteLoaded = false + /// `true` when the last read of the vote failed. An earlier read stays on + /// screen; without one, the vote shows as unavailable. + @State private var voteLoadFailed = false + @State private var keptChoice: ProposalChoice? + @State private var isRefreshing = false + @State private var errorMessage: String? + + @State private var showVoteSheet = false + @State private var showEnterChoiceSheet = false + @State private var showEditSheet = false + /// Banner after a vote, a choice or an edit. + @State private var actionMessage: String? + + init(proposal: MultipleChoiceProposal) { + _proposal = State(initialValue: proposal) + } + + /// The proposer, when it is an identity on this device held by a loaded + /// wallet, so it can sign an edit. + private var localOwner: PersistentIdentity? { + identities.first { + $0.network == appState.currentNetwork + && $0.wallet != nil + && $0.identityIdBase58 == proposal.ownerId + } + } + + /// Identities on this device held by a loaded wallet, which can sign a + /// choice. + private var localSigners: [PersistentIdentity] { + identities.filter { $0.network == appState.currentNetwork && $0.wallet != nil } + } + + /// The choices a vote can name: the running ones the vote read. + private var votableChoices: [ProposalChoice] { + vote?.choices.compactMap(\.choice) ?? [] + } + + var body: some View { + List { + if let errorMessage { + Section { + Label(errorMessage, systemImage: "exclamationmark.triangle") + .font(.caption) + .foregroundColor(.orange) + } + } + + proposalSection + choicesSection + resultSection + actionsSection + } + .navigationTitle("Proposal") + .navigationBarTitleDisplayMode(.inline) + .refreshable { + await refresh() + } + .task { + await refresh() + } + .sheet(isPresented: $showVoteSheet) { + MultipleChoiceProposalVoteSheet( + proposalId: proposal.id, + proposalTitle: proposal.title, + choices: votableChoices + ) { message in + actionMessage = message + Task { await refresh() } + } + .environmentObject(appState) + } + .sheet(isPresented: $showEnterChoiceSheet, onDismiss: { Task { await refresh() } }) { + EnterProposalChoiceView(proposal: proposal) { message in + actionMessage = message + } + .environmentObject(appState) + .environmentObject(walletManager) + } + // Read the proposal again however the sheet closes: a refused edit + // may have found it changed, and the form then shows the newer text. + .sheet(isPresented: $showEditSheet, onDismiss: { Task { await refresh() } }) { + if let owner = localOwner { + EditMultipleChoiceProposalView(proposal: proposal, owner: owner) { message in + actionMessage = message + } + .environmentObject(appState) + .environmentObject(walletManager) + } + } + } + + // MARK: - Sections + + private var proposalSection: some View { + Section("Proposal") { + Text(proposal.title) + .font(.headline) + .fixedSize(horizontal: false, vertical: true) + if let urlString = proposal.url { + if let url = URL(string: urlString) { + Link(urlString, destination: url) + .font(.caption) + } else { + Text(urlString) + .font(.caption) + } + } + if let document = proposal.descriptionDocument { + DetailRow(label: "Description document", value: document.id) + DetailRow(label: "Its contract", value: document.contractId) + DetailRow(label: "Its document type", value: document.documentType) + } + DetailRow( + label: "Who may enter choices", + value: proposal.open ? "Anyone" : "Only the proposer" + ) + DetailRow(label: "Proposal ID", value: proposal.id) + DetailRow( + label: "Proposer", + value: localOwner.map { "\($0.alias ?? $0.identityIdBase58) (this device)" } + ?? proposal.ownerId + ) + if let revision = proposal.revision { + DetailRow(label: "Revision", value: "\(revision)") + } + if let createdAt = proposal.createdAt { + DetailRow(label: "Created", value: createdAt.formatted(date: .abbreviated, time: .shortened)) + } + if let updatedAt = proposal.updatedAt, updatedAt != proposal.createdAt { + DetailRow(label: "Edited", value: updatedAt.formatted(date: .abbreviated, time: .shortened)) + } + } + } + + @ViewBuilder + private var choicesSection: some View { + Section { + if !voteLoaded && !voteLoadFailed { + HStack { + ProgressView() + Text("Loading choices…") + .font(.caption) + .foregroundColor(.secondary) + } + } else if let vote { + if vote.choices.isEmpty { + Text("No choice has been entered yet. The first choice opens the vote.") + .font(.caption) + .foregroundColor(.secondary) + } + ForEach(vote.choices) { entry in + choiceRow(entry) + } + if let tally = vote.noneOfTheChoicesVoteTally { + tallyRow("None of the choices", systemImage: "nosign", value: tally, color: .red) + } + if let tally = vote.abstainVoteTally { + tallyRow("Abstain", systemImage: "minus.circle", value: tally, color: .gray) + } + } else { + Text("The vote could not be read.") + .font(.caption) + .foregroundColor(.secondary) + } + } header: { + Text("Choices") + } footer: { + Text("Each choice is named by its document id. A vote counts a masternode 1 and an evonode 4.") + } + } + + @ViewBuilder + private var resultSection: some View { + if let result = vote?.result { + Section("Result") { + HStack { + Label("Outcome", systemImage: "flag.fill") + Spacer() + Text(Self.describe(result.outcome)) + .foregroundColor(result.outcome == .keptChoice ? .green : .red) + } + if let keptChoiceId = result.keptChoiceId { + DetailRow(label: "Kept choice ID", value: keptChoiceId) + } + if let keptChoice { + VStack(alignment: .leading, spacing: 4) { + Text(keptChoice.title) + .font(.headline) + if let description = keptChoice.description { + Text(description) + .font(.body) + .fixedSize(horizontal: false, vertical: true) + } + } + DetailRow(label: "Entered by", value: keptChoice.ownerId) + } + DetailRow( + label: "Closed", + value: "Block \(result.finalizationBlock.height), epoch \(result.finalizationBlock.epoch), \(result.finalizationBlock.time.formatted(date: .abbreviated, time: .shortened))" + ) + } + } + } + + private var actionsSection: some View { + Section("Actions") { + if let message = actionMessage { + Label(message, systemImage: "checkmark.circle.fill") + .font(.caption) + .foregroundColor(.green) + } + + Button { + actionMessage = nil + showVoteSheet = true + } label: { + Label("Vote as Masternode…", systemImage: "hand.raised.fill") + } + // An ended vote keeps no votes; Platform refuses one. + .disabled(appState.sdk == nil || vote?.result != nil) + .accessibilityIdentifier("multipleChoiceProposal.vote") + + Button { + actionMessage = nil + showEnterChoiceSheet = true + } label: { + Label("Enter a Choice…", systemImage: "plus.bubble") + } + .disabled(appState.sdk == nil || localSigners.isEmpty || vote?.result != nil) + .accessibilityIdentifier("multipleChoiceProposal.enterChoice") + + if localOwner != nil { + Button { + actionMessage = nil + showEditSheet = true + } label: { + Label("Edit…", systemImage: "pencil") + } + .disabled(appState.sdk == nil) + .accessibilityIdentifier("multipleChoiceProposal.edit") + + Text("Platform accepts an edit of the title, url and description document for two hours after the proposal is created. Whether it is open never changes.") + .font(.caption2) + .foregroundColor(.secondary) + } + + Text("Only masternodes vote, with the voting key of a pro_tx_hash. A choice is never edited; entering one pays the contest fund on top of the fees.") + .font(.caption2) + .foregroundColor(.secondary) + } + } + + // MARK: - Rows + + private func choiceRow(_ entry: MultipleChoiceProposalVote.ChoiceInVote) -> some View { + HStack(alignment: .top) { + VStack(alignment: .leading, spacing: 2) { + Text(entry.choice?.title ?? "Choice no longer stored") + .font(.subheadline) + .foregroundColor(entry.choice == nil ? .secondary : .primary) + if let description = entry.choice?.description { + Text(description) + .font(.caption) + .foregroundColor(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + Text(entry.id) + .font(.system(.caption2, design: .monospaced)) + .foregroundColor(.secondary) + .lineLimit(1) + .truncationMode(.middle) + } + Spacer() + Text(entry.voteTally.map { "\($0)" } ?? "-") + .font(.headline) + } + .accessibilityIdentifier("multipleChoiceProposal.choice.\(entry.id)") + } + + private func tallyRow(_ title: String, systemImage: String, value: UInt32, color: Color) -> some View { + HStack { + Label(title, systemImage: systemImage) + .foregroundColor(color) + Spacer() + Text("\(value)") + .font(.headline) + } + } + + private static func describe(_ outcome: MultipleChoiceProposalVote.Outcome) -> String { + switch outcome { + case .keptChoice: return "A choice was kept" + case .noneOfTheChoices: return "None of the choices" + case .noWinner: return "No winner" + } + } + + // MARK: - Refresh + + /// Read the proposal, its vote and its kept choice. Each read stands on + /// its own, so one failing still shows what the others returned. + private func refresh() async { + guard !isRefreshing else { return } + guard let sdk = appState.sdk else { + errorMessage = "SDK not initialized" + return + } + isRefreshing = true + defer { isRefreshing = false } + + let id = proposal.id + async let fetched = captureResult { try await sdk.multipleChoiceProposal(id: id) } + async let voteValue = captureResult { try await sdk.multipleChoiceProposalVote(proposalId: id) } + async let kept = captureResult { try await sdk.multipleChoiceProposalKeptChoice(proposalId: id) } + + var failures: [String] = [] + switch await fetched { + case .success(let value?): + proposal = value + case .success(nil): + failures.append("Platform no longer has this proposal.") + case .failure(let error): + failures.append("Proposal: \(error.localizedDescription)") + } + switch await voteValue { + case .success(let value): + vote = value + voteLoaded = true + voteLoadFailed = false + case .failure(let error): + voteLoadFailed = true + failures.append("Vote: \(error.localizedDescription)") + } + switch await kept { + case .success(let value): + keptChoice = value + case .failure(let error): + failures.append("Kept choice: \(error.localizedDescription)") + } + errorMessage = failures.isEmpty ? nil : failures.joined(separator: "\n") + } +} + +/// `operation`'s outcome as a `Result`, so reads started together can fail +/// on their own. +private func captureResult( + _ operation: @Sendable () async throws -> T +) async -> Result { + do { + return .success(try await operation()) + } catch { + return .failure(error) + } +} + +// MARK: - Masternode vote + +/// Picks the answer and takes the masternode credentials, the same way the +/// yes/no vote sheet does: the pro_tx_hash and the voting private key as +/// hex, the key in a secure field and never stored. Also reads the +/// masternode's current answer. +private struct MultipleChoiceProposalVoteSheet: View { + let proposalId: String + let proposalTitle: String + /// The running choices, as the vote read them. + let choices: [ProposalChoice] + /// Called with a summary once Platform accepted the vote. + let onVoted: (String) -> Void + + @EnvironmentObject var appState: AppState + @Environment(\.dismiss) private var dismiss + + /// What the picker holds. + private enum Answer: Hashable { + case choice(String) + case noneOfTheChoices + case abstain + } + + @State private var answer: Answer? + @State private var proTxHashHex = "" + @State private var votingKeyHex = "" + @State private var isCasting = false + @State private var isLookingUp = false + @State private var message: String? + @State private var messageIsError = false + + private var voteChoice: MultipleChoiceVoteChoice? { + switch answer { + case .choice(let id): return .choice(id: id) + case .noneOfTheChoices: return .noneOfTheChoices + case .abstain: return .abstain + case nil: return nil + } + } + + var body: some View { + NavigationStack { + Form { + Section("Voting on") { + Text(proposalTitle) + .font(.headline) + } + + Section { + Picker("Answer", selection: $answer) { + Text("Select an answer").tag(Answer?.none) + ForEach(choices) { choice in + Text(choice.title).tag(Answer?.some(.choice(choice.id))) + } + Text("None of the choices").tag(Answer?.some(.noneOfTheChoices)) + Text("Abstain").tag(Answer?.some(.abstain)) + } + .pickerStyle(.inline) + .labelsHidden() + .accessibilityIdentifier("multipleChoiceProposalVote.choice") + } header: { + Text("Your Answer") + } footer: { + Text("When the vote ends the choice with the most votes is kept, unless the votes for none of the choices outnumber it.") + } + + Section { + TextField("pro_tx_hash (64 hex chars)", text: $proTxHashHex) + .font(.system(.caption, design: .monospaced)) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .accessibilityIdentifier("multipleChoiceProposalVote.proTxHash") + SecureField("voting private key (64 hex chars)", text: $votingKeyHex) + .font(.system(.caption, design: .monospaced)) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .accessibilityIdentifier("multipleChoiceProposalVote.votingKey") + } header: { + Text("Masternode Credentials") + } footer: { + Text("The pro_tx_hash goes in wire order, the reverse of the hex Core displays. The voting public key and signer are derived from the private key on the Rust side; the key bytes are not stored.") + } + + Section { + Button { + Task { await castVote() } + } label: { + if isCasting { + HStack { + ProgressView() + Text("Broadcasting…") + } + } else { + Text("Submit Vote") + } + } + .disabled( + isCasting || isLookingUp || voteChoice == nil + || proTxHashHex.isEmpty || votingKeyHex.isEmpty + ) + .accessibilityIdentifier("multipleChoiceProposalVote.submit") + + Button { + Task { await lookUpAnswer() } + } label: { + if isLookingUp { + HStack { + ProgressView() + Text("Reading…") + } + } else { + Text("Read This Masternode's Answer") + } + } + .disabled(isCasting || isLookingUp || proTxHashHex.isEmpty) + .accessibilityIdentifier("multipleChoiceProposalVote.lookUp") + + if let message { + Text(message) + .font(.caption) + .foregroundColor(messageIsError ? .orange : .secondary) + } + } + } + .navigationTitle("Vote") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + .disabled(isCasting) + } + } + .interactiveDismissDisabled(isCasting) + } + } + + /// Decode a 32-byte value typed as 64 hex characters. `Data(hexString:)` + /// drops a trailing odd nibble, so the length is checked first, as on the + /// yes/no vote sheet. + private static func decode32(_ hex: String) -> Data? { + let trimmed = hex.trimmingCharacters(in: .whitespacesAndNewlines) + guard trimmed.count == 64, let data = Data(hexString: trimmed), data.count == 32 else { + return nil + } + return data + } + + private func describe(_ choice: MultipleChoiceVoteChoice) -> String { + switch choice { + case .choice(let id): + return choices.first { $0.id == id }.map { "\"\($0.title)\"" } ?? "the choice \(id)" + case .noneOfTheChoices: + return "none of the choices" + case .abstain: + return "abstain" + } + } + + private func castVote() async { + guard let sdk = appState.sdk else { + show("SDK not initialized", isError: true) + return + } + guard let choice = voteChoice else { + show("Select an answer.", isError: true) + return + } + guard let proTxHash = Self.decode32(proTxHashHex) else { + show("pro_tx_hash must be 32 bytes (64 hex characters).", isError: true) + return + } + guard let votingKey = Self.decode32(votingKeyHex) else { + show("Voting private key must be 32 bytes (64 hex characters).", isError: true) + return + } + + isCasting = true + defer { isCasting = false } + do { + try await sdk.castMultipleChoiceProposalVote( + proposalId: proposalId, + choice: choice, + proTxHash: proTxHash, + votingPrivateKey: votingKey + ) + onVoted("Vote for \(describe(choice)) accepted by Platform.") + dismiss() + } catch { + show("Vote rejected: \(error.localizedDescription)", isError: true) + } + } + + private func lookUpAnswer() async { + guard let sdk = appState.sdk else { + show("SDK not initialized", isError: true) + return + } + guard let proTxHash = Self.decode32(proTxHashHex) else { + show("pro_tx_hash must be 32 bytes (64 hex characters).", isError: true) + return + } + + isLookingUp = true + defer { isLookingUp = false } + do { + if let current = try await sdk.multipleChoiceProposalMasternodeVote( + proposalId: proposalId, + proTxHash: proTxHash + ) { + show("Current answer: \(describe(current)).", isError: false) + } else { + show("This masternode has no answer in the vote (none yet, or the vote has ended).", isError: false) + } + } catch { + show("Reading the answer failed: \(error.localizedDescription)", isError: true) + } + } + + private func show(_ text: String, isError: Bool) { + message = text + messageIsError = isError + } +} diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DecisionProposals/MultipleChoiceProposalFormViews.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DecisionProposals/MultipleChoiceProposalFormViews.swift new file mode 100644 index 00000000000..8ee1615fabf --- /dev/null +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DecisionProposals/MultipleChoiceProposalFormViews.swift @@ -0,0 +1,794 @@ +import SwiftUI +import SwiftData +import SwiftDashSDK + +// MARK: - Shared input + +/// An amount of credits as Dash, for display (1 Dash = 100,000,000,000 +/// credits). +func multipleChoiceProposalDash(_ credits: UInt64) -> String { + let dash = Double(credits) / 100_000_000_000 + return "\(dash.formatted(.number.precision(.fractionLength(0...8)))) Dash" +} + +/// The three text fields naming a description document, as typed. +struct DescriptionDocumentInput: Equatable { + var id = "" + var contractId = "" + var documentType = "" + + init() {} + + init(_ document: MultipleChoiceProposal.DescriptionDocument?) { + id = document?.id ?? "" + contractId = document?.contractId ?? "" + documentType = document?.documentType ?? "" + } + + private var trimmed: (id: String, contractId: String, documentType: String) { + ( + id.trimmingCharacters(in: .whitespacesAndNewlines), + contractId.trimmingCharacters(in: .whitespacesAndNewlines), + documentType.trimmingCharacters(in: .whitespacesAndNewlines) + ) + } + + /// Whether every field is empty: no description document. + var isEmpty: Bool { + let fields = trimmed + return fields.id.isEmpty && fields.contractId.isEmpty && fields.documentType.isEmpty + } + + /// Whether the fields name `document`. + func matches(_ document: MultipleChoiceProposal.DescriptionDocument?) -> Bool { + let fields = trimmed + guard let document else { return isEmpty } + return fields.id == document.id + && fields.contractId == document.contractId + && fields.documentType == document.documentType + } + + /// The fields as the SDK params, `nil` when they are all empty. Throws + /// when an id is not base58; Platform judges the rest. + func params() throws -> DescriptionDocumentParams? { + guard !isEmpty else { return nil } + let fields = trimmed + guard let id = Data.identifier(fromBase58: fields.id) else { + throw DescriptionDocumentInputError.notBase58("document id") + } + guard let contractId = Data.identifier(fromBase58: fields.contractId) else { + throw DescriptionDocumentInputError.notBase58("contract id") + } + return DescriptionDocumentParams(id: id, contractId: contractId, documentType: fields.documentType) + } +} + +enum DescriptionDocumentInputError: LocalizedError { + case notBase58(String) + + var errorDescription: String? { + switch self { + case .notBase58(let field): + return "The description document's \(field) is not a base58 identifier." + } + } +} + +/// The text fields of a ``DescriptionDocumentInput``. +private struct DescriptionDocumentFields: View { + @Binding var input: DescriptionDocumentInput + let identifierPrefix: String + + var body: some View { + TextField("Document ID (base58)", text: $input.id) + .font(.system(.caption, design: .monospaced)) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .accessibilityIdentifier("\(identifierPrefix).descriptionDocumentId") + TextField("Contract ID (base58)", text: $input.contractId) + .font(.system(.caption, design: .monospaced)) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .accessibilityIdentifier("\(identifierPrefix).descriptionDocumentContractId") + TextField("Document type", text: $input.documentType) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .accessibilityIdentifier("\(identifierPrefix).descriptionDocumentType") + } +} + +// MARK: - Create + +/// Files a new multiple choice proposal for an identity held by a loaded +/// wallet. +/// +/// The platform wallet creates it +/// (`ManagedPlatformWallet.createMultipleChoiceProposal`): rs-sdk builds the +/// proposal and the wallet chooses and uses the signing key on the Rust side +/// through the `KeychainSigner`. Platform judges the title, the description +/// document and the url, and charges the processing fee shown here (read +/// from the SDK); this form only collects the input. +struct CreateMultipleChoiceProposalView: View { + /// Called with the new proposal's id (base58) once Platform confirmed it. + let onCreated: (String) -> Void + + @EnvironmentObject var appState: AppState + @EnvironmentObject var walletManager: PlatformWalletManager + @Environment(\.modelContext) private var modelContext + @Environment(\.dismiss) private var dismiss + @Query private var identities: [PersistentIdentity] + + /// Base58 id of the proposer. + @State private var selectedOwnerId = "" + @State private var title = "" + @State private var url = "" + @State private var descriptionDocument = DescriptionDocumentInput() + @State private var open = true + + /// The processing fee in credits, once read. + @State private var processingFee: UInt64? + @State private var processingFeeError: String? + + @State private var isSubmitting = false + @State private var submitError: String? + @State private var createdProposalId: String? + + /// Identities on the active network held by a loaded wallet, so a + /// `KeychainSigner` can sign for them. + private var ownerIdentities: [PersistentIdentity] { + identities.filter { $0.network == appState.currentNetwork && $0.wallet != nil } + } + + private var selectedOwner: PersistentIdentity? { + ownerIdentities.first { $0.identityIdBase58 == selectedOwnerId } + } + + private var managedWallet: ManagedPlatformWallet? { + guard let walletId = selectedOwner?.wallet?.walletId else { return nil } + return walletManager.wallet(for: walletId) + } + + var body: some View { + NavigationStack { + Form { + if let createdProposalId { + successSection(proposalId: createdProposalId) + } else { + ownerSection + questionSection + descriptionDocumentSection + submitSection + } + } + .navigationTitle("New Proposal") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .navigationBarLeading) { + Button(createdProposalId == nil ? "Cancel" : "Done") { dismiss() } + .disabled(isSubmitting) + } + } + // The broadcast is not idempotent; keep the sheet up until it ends. + .interactiveDismissDisabled(isSubmitting) + .alert( + "Create failed", + isPresented: Binding( + get: { submitError != nil }, + set: { if !$0 { submitError = nil } } + ) + ) { + Button("OK", role: .cancel) {} + } message: { + Text(submitError ?? "") + } + .onAppear { + if selectedOwnerId.isEmpty, let first = ownerIdentities.first { + selectedOwnerId = first.identityIdBase58 + } + } + .task { + await loadProcessingFee() + } + } + } + + // MARK: - Sections + + private var ownerSection: some View { + Section { + Picker("Proposer", selection: $selectedOwnerId) { + Text("Select identity").tag("") + ForEach(ownerIdentities) { identity in + Text(identity.alias ?? identity.identityIdBase58) + .tag(identity.identityIdBase58) + } + } + .accessibleFormPicker("createMultipleChoiceProposal.ownerPicker") + .disabled(isSubmitting) + + HStack { + Text("Processing fee") + Spacer() + if let processingFee { + Text(multipleChoiceProposalDash(processingFee)) + .foregroundColor(.secondary) + .accessibilityIdentifier("createMultipleChoiceProposal.processingFee") + } else if processingFeeError != nil { + Text("Unavailable") + .foregroundColor(.orange) + } else { + ProgressView().controlSize(.small) + } + } + } header: { + Text("Proposer") + } footer: { + if let processingFeeError { + Text("The processing fee could not be read: \(processingFeeError)") + } else { + Text("Platform charges this identity the processing fee on top of the fees when the proposal is created.") + } + } + } + + private var questionSection: some View { + Section { + TextField("Title: the question, in one line", text: $title) + .accessibilityIdentifier("createMultipleChoiceProposal.title") + TextField("URL where it is described or discussed", text: $url) + .keyboardType(.URL) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .accessibilityIdentifier("createMultipleChoiceProposal.url") + Toggle("Anyone may enter choices", isOn: $open) + .accessibilityIdentifier("createMultipleChoiceProposal.open") + } header: { + Text("Question") + } footer: { + Text("When it is off, only the proposer may enter choices. This never changes after the proposal is created; the title, url and description document can be edited for two hours.") + } + .disabled(isSubmitting) + } + + private var descriptionDocumentSection: some View { + Section { + DescriptionDocumentFields( + input: $descriptionDocument, + identifierPrefix: "createMultipleChoiceProposal" + ) + } header: { + Text("Description Document (optional)") + } footer: { + Text("A document saying what is being decided. Platform requires a description document, a url, or both, and accepts only a document its contract's elected team may delete.") + } + .disabled(isSubmitting) + } + + private var submitSection: some View { + Section { + Button { + submit() + } label: { + HStack { + if isSubmitting { + ProgressView() + .controlSize(.small) + Text("Broadcasting…") + } else { + Text("Create / Broadcast") + } + } + .frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + .accessibilityIdentifier("createMultipleChoiceProposal.submitButton") + .disabled(isSubmitting || managedWallet == nil) + } + } + + private func successSection(proposalId: String) -> some View { + Section { + VStack(alignment: .leading, spacing: 8) { + Label("Proposal created", systemImage: "checkmark.seal.fill") + .foregroundColor(.green) + .font(.headline) + HStack(alignment: .top) { + Text("ID:") + .foregroundColor(.secondary) + Text(proposalId) + .font(.system(.caption, design: .monospaced)) + .lineLimit(2) + .truncationMode(.middle) + } + Button { + dismiss() + } label: { + Text("Done") + .frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + .accessibilityIdentifier("createMultipleChoiceProposal.doneButton") + .padding(.top, 4) + } + } + } + + // MARK: - Actions + + private func loadProcessingFee() async { + guard let sdk = appState.sdk else { + processingFeeError = "SDK not initialized" + return + } + do { + processingFee = try await sdk.multipleChoiceProposalProcessingFee() + processingFeeError = nil + } catch { + processingFeeError = error.localizedDescription + } + } + + private func submit() { + guard let owner = selectedOwner, let wallet = managedWallet else { + submitError = DocumentActionError.noWallet.localizedDescription + return + } + let document: DescriptionDocumentParams? + do { + document = try descriptionDocument.params() + } catch { + submitError = error.localizedDescription + return + } + + let trimmedURL = url.trimmingCharacters(in: .whitespacesAndNewlines) + let params = MultipleChoiceProposalParams( + title: title, + descriptionDocument: document, + url: trimmedURL.isEmpty ? nil : trimmedURL, + open: open + ) + let ownerId = owner.identityId + // Fresh `KeychainSigner` per submit, as `CreateDocumentView` does. + let signer = KeychainSigner(modelContainer: modelContext.container) + + isSubmitting = true + Task { + do { + let (proposalId, _) = try await wallet.createMultipleChoiceProposal( + ownerIdentityId: ownerId, + params: params, + signer: signer + ) + let proposalIdBase58 = proposalId.toBase58String() + createdProposalId = proposalIdBase58 + onCreated(proposalIdBase58) + } catch { + submitError = error.localizedDescription + } + isSubmitting = false + } + } +} + +// MARK: - Edit + +/// Changes the title, url or description document of a proposal a local +/// identity filed. +/// +/// The platform wallet edits it +/// (`ManagedPlatformWallet.editMultipleChoiceProposal`): it reads the +/// proposal, rs-sdk applies the edit (refusing one that changes nothing) and +/// the wallet chooses the signing key and puts the proposal at the revision +/// after the one it read. Platform refuses the edit outside the edit window, +/// one that leaves the proposal with neither a description document nor a +/// url, and one made after another edit landed after that read. +/// +/// After any failure the form reads the proposal again. When Platform's copy +/// differs from the one the form was opened on, the form shows that copy in +/// place of the fields, so the next try starts from it. +struct EditMultipleChoiceProposalView: View { + let owner: PersistentIdentity + /// Called with a summary once Platform confirmed the edit. + let onEdited: (String) -> Void + + @EnvironmentObject var appState: AppState + @EnvironmentObject var walletManager: PlatformWalletManager + @Environment(\.modelContext) private var modelContext + @Environment(\.dismiss) private var dismiss + + /// The proposal as last read, which the fields were filled from. + @State private var proposal: MultipleChoiceProposal + @State private var title: String + @State private var url: String + @State private var descriptionDocument: DescriptionDocumentInput + @State private var isSubmitting = false + @State private var submitError: String? + + init(proposal: MultipleChoiceProposal, owner: PersistentIdentity, onEdited: @escaping (String) -> Void) { + self.owner = owner + self.onEdited = onEdited + _proposal = State(initialValue: proposal) + _title = State(initialValue: proposal.title) + _url = State(initialValue: proposal.url ?? "") + _descriptionDocument = State(initialValue: DescriptionDocumentInput(proposal.descriptionDocument)) + } + + private var managedWallet: ManagedPlatformWallet? { + guard let walletId = owner.wallet?.walletId else { return nil } + return walletManager.wallet(for: walletId) + } + + var body: some View { + NavigationStack { + Form { + Section { + TextField("Title", text: $title) + .accessibilityIdentifier("editMultipleChoiceProposal.title") + TextField("URL (empty for none)", text: $url) + .keyboardType(.URL) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .accessibilityIdentifier("editMultipleChoiceProposal.url") + } header: { + Text("Question") + } + .disabled(isSubmitting) + + Section { + DescriptionDocumentFields( + input: $descriptionDocument, + identifierPrefix: "editMultipleChoiceProposal" + ) + } header: { + Text("Description Document") + } footer: { + Text("Empty every field to remove it. Only the title, url and description document can change, and only for two hours after the proposal was created.") + } + .disabled(isSubmitting) + + Section { + Button { + submit() + } label: { + HStack { + if isSubmitting { + ProgressView() + .controlSize(.small) + Text("Broadcasting…") + } else { + Text("Replace / Broadcast") + } + } + .frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + .accessibilityIdentifier("editMultipleChoiceProposal.submitButton") + .disabled(isSubmitting || managedWallet == nil) + } + } + .navigationTitle("Edit Proposal") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .navigationBarLeading) { + Button("Cancel") { dismiss() } + .disabled(isSubmitting) + } + } + .interactiveDismissDisabled(isSubmitting) + .alert( + "Edit failed", + isPresented: Binding( + get: { submitError != nil }, + set: { if !$0 { submitError = nil } } + ) + ) { + Button("OK", role: .cancel) {} + } message: { + Text(submitError ?? "") + } + } + } + + private func submit() { + guard let wallet = managedWallet else { + submitError = DocumentActionError.noWallet.localizedDescription + return + } + guard let proposalId = Data.identifier(fromBase58: proposal.id), proposalId.count == 32 else { + submitError = "The proposal id is not a 32-byte base58 identifier." + return + } + + // Only the fields the user changed from the proposal this form shows + // are sent: an untouched field must not write back the value it was + // opened with over a newer edit by another client. An emptied field + // removes the value. + let trimmedURL = url.trimmingCharacters(in: .whitespacesAndNewlines) + let urlChange: MultipleChoiceProposalEdit.Change + if trimmedURL == (proposal.url ?? "") { + urlChange = .keep + } else if trimmedURL.isEmpty { + urlChange = .remove + } else { + urlChange = .set(trimmedURL) + } + let documentChange: MultipleChoiceProposalEdit.Change + if descriptionDocument.matches(proposal.descriptionDocument) { + documentChange = .keep + } else { + do { + if let document = try descriptionDocument.params() { + documentChange = .set(document) + } else { + documentChange = .remove + } + } catch { + submitError = error.localizedDescription + return + } + } + let edit = MultipleChoiceProposalEdit( + title: title == proposal.title ? nil : title, + descriptionDocument: documentChange, + url: urlChange + ) + let ownerId = owner.identityId + let signer = KeychainSigner(modelContainer: modelContext.container) + + isSubmitting = true + Task { + do { + _ = try await wallet.editMultipleChoiceProposal( + ownerIdentityId: ownerId, + proposalId: proposalId, + edit: edit, + signer: signer + ) + onEdited("Edit accepted by Platform.") + isSubmitting = false + dismiss() + } catch { + let reloadNote = await reloadAfterFailure() + submitError = [error.localizedDescription, reloadNote] + .compactMap { $0 } + .joined(separator: "\n\n") + isSubmitting = false + } + } + } + + /// Read the proposal again after a failed edit. When Platform's copy + /// differs from the one the fields were filled from, take it and refill + /// the fields. Returns what the person should know about the reload, or + /// `nil` when there is nothing to add. + private func reloadAfterFailure() async -> String? { + guard let sdk = appState.sdk else { return nil } + do { + guard let current = try await sdk.multipleChoiceProposal(id: proposal.id) else { + return "Platform no longer has this proposal." + } + guard current != proposal else { return nil } + proposal = current + title = current.title + url = current.url ?? "" + descriptionDocument = DescriptionDocumentInput(current.descriptionDocument) + let revision = current.revision.map { " (revision \($0))" } ?? "" + return "Platform's copy of the proposal changed since this form was opened; the form now shows it\(revision)." + } catch { + return "The proposal could not be read again: \(error.localizedDescription)" + } + } +} + +// MARK: - Enter a choice + +/// Enters an answer for a multiple choice proposal, owned by an identity +/// held by a loaded wallet. +/// +/// The platform wallet enters it +/// (`ManagedPlatformWallet.enterMultipleChoiceProposalChoice`): rs-sdk builds +/// the choice and its put states the contest fund shown here (read from the +/// SDK). Platform decides who may enter a choice and until when; this form +/// only collects the answer. +struct EnterProposalChoiceView: View { + let proposal: MultipleChoiceProposal + /// Called with a summary once Platform confirmed the choice. + let onEntered: (String) -> Void + + @EnvironmentObject var appState: AppState + @EnvironmentObject var walletManager: PlatformWalletManager + @Environment(\.modelContext) private var modelContext + @Environment(\.dismiss) private var dismiss + @Query private var identities: [PersistentIdentity] + + /// Base58 id of the identity entering the choice. + @State private var selectedOwnerId = "" + @State private var title = "" + @State private var description = "" + + /// The contest fund in credits, once read. + @State private var fund: UInt64? + @State private var fundError: String? + + @State private var isSubmitting = false + @State private var submitError: String? + + /// Identities on the active network held by a loaded wallet, so a + /// `KeychainSigner` can sign for them. + private var ownerIdentities: [PersistentIdentity] { + identities.filter { $0.network == appState.currentNetwork && $0.wallet != nil } + } + + private var selectedOwner: PersistentIdentity? { + ownerIdentities.first { $0.identityIdBase58 == selectedOwnerId } + } + + private var managedWallet: ManagedPlatformWallet? { + guard let walletId = selectedOwner?.wallet?.walletId else { return nil } + return walletManager.wallet(for: walletId) + } + + var body: some View { + NavigationStack { + Form { + Section("Answering") { + Text(proposal.title) + .font(.headline) + } + + Section { + Picker("Entered by", selection: $selectedOwnerId) { + Text("Select identity").tag("") + ForEach(ownerIdentities) { identity in + Text(identity.alias ?? identity.identityIdBase58) + .tag(identity.identityIdBase58) + } + } + .accessibleFormPicker("enterProposalChoice.ownerPicker") + + HStack { + Text("Contest fund") + Spacer() + if let fund { + Text(multipleChoiceProposalDash(fund)) + .foregroundColor(.secondary) + .accessibilityIdentifier("enterProposalChoice.fund") + } else if fundError != nil { + Text("Unavailable") + .foregroundColor(.orange) + } else { + ProgressView().controlSize(.small) + } + } + } header: { + Text("Identity") + } footer: { + if let fundError { + Text("The contest fund could not be read: \(fundError)") + } else if proposal.open { + Text("Entering a choice pays the contest fund from this identity's credits, on top of the fees. The amount is read again when the choice is signed.") + } else { + Text("Only the proposer may enter choices for this proposal. Entering a choice pays the contest fund on top of the fees.") + } + } + .disabled(isSubmitting) + + Section { + TextField("Title: the answer, in one line", text: $title) + .accessibilityIdentifier("enterProposalChoice.title") + TextField("What voting for it means (optional)", text: $description, axis: .vertical) + .lineLimit(3...10) + .accessibilityIdentifier("enterProposalChoice.description") + } header: { + Text("Choice") + } footer: { + Text("A choice is never edited after it is entered.") + } + .disabled(isSubmitting) + + Section { + Button { + submit() + } label: { + HStack { + if isSubmitting { + ProgressView() + .controlSize(.small) + Text("Broadcasting…") + } else { + Text("Enter / Broadcast") + } + } + .frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + .accessibilityIdentifier("enterProposalChoice.submitButton") + .disabled(isSubmitting || managedWallet == nil) + } + } + .navigationTitle("Enter a Choice") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .navigationBarLeading) { + Button("Cancel") { dismiss() } + .disabled(isSubmitting) + } + } + // The broadcast is not idempotent; keep the sheet up until it ends. + .interactiveDismissDisabled(isSubmitting) + .alert( + "Entering the choice failed", + isPresented: Binding( + get: { submitError != nil }, + set: { if !$0 { submitError = nil } } + ) + ) { + Button("OK", role: .cancel) {} + } message: { + Text(submitError ?? "") + } + .onAppear { + if selectedOwnerId.isEmpty { + // Start on the proposer when it is local, else the first + // local identity. + selectedOwnerId = ownerIdentities.first { $0.identityIdBase58 == proposal.ownerId }? + .identityIdBase58 ?? ownerIdentities.first?.identityIdBase58 ?? "" + } + } + .task { + await loadFund() + } + } + } + + private func loadFund() async { + guard let sdk = appState.sdk else { + fundError = "SDK not initialized" + return + } + do { + fund = try await sdk.multipleChoiceProposalChoiceFundToJoin(proposalId: proposal.id) + fundError = nil + } catch { + fundError = error.localizedDescription + } + } + + private func submit() { + guard let owner = selectedOwner, let wallet = managedWallet else { + submitError = DocumentActionError.noWallet.localizedDescription + return + } + guard let proposalId = Data.identifier(fromBase58: proposal.id), proposalId.count == 32 else { + submitError = "The proposal id is not a 32-byte base58 identifier." + return + } + + let trimmedDescription = description.trimmingCharacters(in: .whitespacesAndNewlines) + let params = ProposalChoiceParams( + title: title, + description: trimmedDescription.isEmpty ? nil : description + ) + let ownerId = owner.identityId + let signer = KeychainSigner(modelContainer: modelContext.container) + + isSubmitting = true + Task { + do { + let (choiceId, _) = try await wallet.enterMultipleChoiceProposalChoice( + ownerIdentityId: ownerId, + proposalId: proposalId, + params: params, + signer: signer + ) + onEntered("Choice \(choiceId.toBase58String()) accepted by Platform.") + isSubmitting = false + dismiss() + } catch { + submitError = error.localizedDescription + isSubmitting = false + } + } + } +} diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DecisionProposals/MultipleChoiceProposalsView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DecisionProposals/MultipleChoiceProposalsView.swift new file mode 100644 index 00000000000..7d029f0fd25 --- /dev/null +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DecisionProposals/MultipleChoiceProposalsView.swift @@ -0,0 +1,259 @@ +import SwiftUI +import SwiftData +import SwiftDashSDK + +/// Multiple choice proposals (protocol version 15): questions any identity +/// puts to the masternodes, answered by the choices entered for them. +/// +/// Lists them two ways, each one Platform listing read a page at a time: the +/// ones a local identity filed, and the newest. Drills into +/// ``MultipleChoiceProposalDetailView`` for the choices, the vote, entering a +/// choice and the edit, and creates new ones with +/// ``CreateMultipleChoiceProposalView``. Every read goes through the `SDK` +/// multiple choice proposal wrappers; nothing here decides what a proposal +/// is. +struct MultipleChoiceProposalsView: View { + @EnvironmentObject var appState: AppState + @EnvironmentObject var walletManager: PlatformWalletManager + @Query private var identities: [PersistentIdentity] + + private enum Listing: String, CaseIterable, Identifiable { + case mine = "Mine" + case newest = "Newest" + + var id: String { rawValue } + + var footer: String { + switch self { + case .mine: + return "Proposals the selected identity filed, in the order it filed them." + case .newest: + return "Every multiple choice proposal, newest first." + } + } + } + + /// Proposals per page. + private static let pageSize: UInt32 = 20 + + @State private var listing: Listing = .newest + /// Base58 id of the identity whose proposals "Mine" lists. + @State private var selectedOwnerId = "" + @State private var proposals: [MultipleChoiceProposal] = [] + /// `false` once a page came back shorter than the page size (the last). + @State private var hasMore = false + @State private var isLoading = false + @State private var errorMessage: String? + /// Bumped on every fresh load so a page that arrives late for a previous + /// listing is dropped instead of mixed in. + @State private var loadGeneration = 0 + @State private var showCreate = false + + /// Identities on the active network, for the "Mine" listing. + private var localIdentities: [PersistentIdentity] { + identities.filter { $0.network == appState.currentNetwork } + } + + var body: some View { + List { + Section { + Picker("Listing", selection: $listing) { + ForEach(Listing.allCases) { value in + Text(value.rawValue).tag(value) + } + } + .pickerStyle(.segmented) + .accessibilityIdentifier("multipleChoiceProposals.listing") + + if listing == .mine { + Picker("Identity", selection: $selectedOwnerId) { + Text("Select identity").tag("") + ForEach(localIdentities) { identity in + Text(identity.alias ?? identity.identityIdBase58) + .tag(identity.identityIdBase58) + } + } + .accessibilityIdentifier("multipleChoiceProposals.ownerPicker") + } + } footer: { + Text(listing.footer) + } + + if let errorMessage { + Section { + Label(errorMessage, systemImage: "exclamationmark.triangle") + .font(.caption) + .foregroundColor(.orange) + } + } + + Section("Proposals") { + if proposals.isEmpty { + if isLoading { + HStack { + ProgressView() + Text("Loading proposals…") + .font(.caption) + .foregroundColor(.secondary) + } + } else if listing == .mine && selectedOwnerId.isEmpty { + Text("Select an identity to list its proposals.") + .font(.caption) + .foregroundColor(.secondary) + } else { + Text("No proposals") + .font(.caption) + .foregroundColor(.secondary) + } + } else { + ForEach(proposals) { proposal in + NavigationLink( + destination: MultipleChoiceProposalDetailView(proposal: proposal) + ) { + MultipleChoiceProposalRow(proposal: proposal) + } + .accessibilityIdentifier("multipleChoiceProposals.row.\(proposal.id)") + } + + if hasMore { + Button { + Task { await loadNextPage() } + } label: { + HStack { + if isLoading { + ProgressView().controlSize(.small) + } + Text("Load More") + } + .frame(maxWidth: .infinity) + } + .disabled(isLoading) + .accessibilityIdentifier("multipleChoiceProposals.loadMore") + } + } + } + } + .navigationTitle("Multiple Choice Proposals") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .navigationBarTrailing) { + Button { + showCreate = true + } label: { + Image(systemName: "plus") + } + .disabled(appState.sdk == nil) + .accessibilityLabel("New multiple choice proposal") + .accessibilityIdentifier("multipleChoiceProposals.create") + } + } + .refreshable { + await reload() + } + .task(id: "\(listing.rawValue)|\(selectedOwnerId)") { + await reload() + } + .onChange(of: listing) { _, newListing in + // Start "Mine" on the first local identity rather than empty. + if newListing == .mine, selectedOwnerId.isEmpty, + let first = localIdentities.first { + selectedOwnerId = first.identityIdBase58 + } + } + .sheet(isPresented: $showCreate) { + CreateMultipleChoiceProposalView { _ in + Task { await reload() } + } + .environmentObject(appState) + .environmentObject(walletManager) + } + } + + // MARK: - Loading + + /// Load the first page of the current listing. + private func reload() async { + loadGeneration += 1 + proposals = [] + hasMore = false + errorMessage = nil + if listing == .mine && selectedOwnerId.isEmpty { return } + await load(startAfter: nil, generation: loadGeneration) + } + + /// Load the page after the last proposal shown. + private func loadNextPage() async { + guard let last = proposals.last else { return } + await load(startAfter: last.id, generation: loadGeneration) + } + + private func load(startAfter: String?, generation: Int) async { + guard let sdk = appState.sdk else { + errorMessage = "SDK not initialized" + return + } + isLoading = true + defer { isLoading = false } + + do { + let page: [MultipleChoiceProposal] + switch listing { + case .mine: + page = try await sdk.multipleChoiceProposalsByOwner( + ownerId: selectedOwnerId, + limit: Self.pageSize, + startAfter: startAfter + ) + case .newest: + page = try await sdk.multipleChoiceProposalsByCreatedAt( + limit: Self.pageSize, + startAfter: startAfter + ) + } + guard generation == loadGeneration else { return } + proposals.append(contentsOf: page) + // A page shorter than the page size is the last one. + hasMore = page.count == Int(Self.pageSize) + } catch { + guard generation == loadGeneration else { return } + errorMessage = "Loading failed: \(error.localizedDescription)" + } + } +} + +/// One proposal in a listing. +private struct MultipleChoiceProposalRow: View { + let proposal: MultipleChoiceProposal + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + Text(proposal.title) + .font(.headline) + .lineLimit(2) + HStack(spacing: 12) { + if let createdAt = proposal.createdAt { + Label { + Text(createdAt, style: .date) + } icon: { + Image(systemName: "calendar") + } + } + Label( + proposal.open ? "Open" : "Owner only", + systemImage: proposal.open ? "person.3" : "person" + ) + if proposal.descriptionDocument != nil { + Label("Document", systemImage: "doc.text") + } + } + .font(.caption) + .foregroundColor(.secondary) + Text(proposal.id) + .font(.system(.caption2, design: .monospaced)) + .foregroundColor(.secondary) + .lineLimit(1) + .truncationMode(.middle) + } + .padding(.vertical, 2) + } +} diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/PlatformQueriesView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/PlatformQueriesView.swift index ff0aa774cd2..fd9acc44786 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/PlatformQueriesView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/PlatformQueriesView.swift @@ -129,6 +129,19 @@ struct QueryCategoryDetailView: View { .padding(.vertical, 4) } .accessibilityIdentifier("votingQueries.decisionProposalsLink") + } else if query.name == "multipleChoiceProposals" { + NavigationLink(destination: MultipleChoiceProposalsView()) { + VStack(alignment: .leading, spacing: 4) { + Text(query.label) + .font(.headline) + Text(query.description) + .font(.caption) + .foregroundColor(.secondary) + .lineLimit(2) + } + .padding(.vertical, 4) + } + .accessibilityIdentifier("votingQueries.multipleChoiceProposalsLink") } else if query.name == "testDPNSQueries" { NavigationLink(destination: DPNSTestView()) { VStack(alignment: .leading, spacing: 4) { @@ -209,6 +222,7 @@ struct QueryCategoryDetailView: View { case .voting: return [ QueryDefinition(name: "decisionProposals", label: "Decision Proposals", description: "Browse, file, edit and vote on yes/no questions put to the masternodes (protocol version 15)"), + QueryDefinition(name: "multipleChoiceProposals", label: "Multiple Choice Proposals", description: "Browse, file, edit, enter choices for and vote on questions with several answers (protocol version 15)"), QueryDefinition(name: "getContestedResources", label: "Get Contested Resources", description: "Get list of contested resources"), QueryDefinition(name: "getContestedResourceVoteState", label: "Get Contested Resource Vote State", description: "Get the current vote state for a contested resource"), QueryDefinition(name: "getContestedResourceVotersForIdentity", label: "Get Contested Resource Voters for Identity", description: "Get voters who voted for a specific identity in a contested resource"), diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/MultipleChoiceProposalDecodingTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/MultipleChoiceProposalDecodingTests.swift new file mode 100644 index 00000000000..03bad85248e --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/MultipleChoiceProposalDecodingTests.swift @@ -0,0 +1,269 @@ +import Foundation +import XCTest +@testable import SwiftDashSDK + +/// Hermetic tests for the multiple choice proposal JSON the `rs-sdk-ffi` +/// `dash_sdk_multiple_choice_proposal_*` reads return, decoded by +/// `DecisionProposalJSON` exactly as the `SDK` wrappers decode it, and for the +/// `vote_choice` byte and `choice_id` `dash_sdk_multiple_choice_proposal_cast_vote` +/// takes. +/// +/// The payloads mirror the shapes the FFI's +/// `packages/rs-sdk-ffi/src/decision_proposal/multiple_choice/json.rs` writes +/// (and its tests pin). No SDK handle, no network. +final class MultipleChoiceProposalDecodingTests: XCTestCase { + private let createdAt: UInt64 = 1_700_000_000_000 + private let proposalId = "4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF" + private let ownerId = "CQgw5i7y2Y4Ns6rTgV6cq7MhQ7b4oJxEf1vsaFgM2KXJ" + private let choiceId = "8wtF3Sji4LR7gRmmSPXuQbqWf9GmgPJyDukTEBpHmh5K" + private let otherChoiceId = "11111111111111111111111111111111" + + private func decode(_ type: T.Type, _ json: String) throws -> T { + try DecisionProposalJSON.decode(type, from: json) + } + + private func proposalJSON(descriptionDocument: String, url: String, open: Bool = true) -> String { + """ + {"id":"\(proposalId)","ownerId":"\(ownerId)",\ + "revision":1,"createdAt":\(createdAt),"updatedAt":\(createdAt),\ + "title":"Which block size?",\ + "descriptionDocument":\(descriptionDocument),"url":\(url),"open":\(open)} + """ + } + + private var descriptionDocumentJSON: String { + #"{"id":"\#(otherChoiceId)","contractId":"\#(ownerId)","documentType":"post"}"# + } + + private func choiceJSON(id: String, description: String) -> String { + """ + {"id":"\(id)","ownerId":"\(ownerId)","proposalId":"\(proposalId)",\ + "revision":null,"createdAt":\(createdAt),"updatedAt":null,\ + "title":"Double it","description":\(description)} + """ + } + + // MARK: - Proposal + + func testShouldDecodeAProposalWithEveryField() throws { + let proposal = try decode( + MultipleChoiceProposal.self, + proposalJSON( + descriptionDocument: descriptionDocumentJSON, + url: #""https://forum.dash.org/t/block-size""# + ) + ) + + XCTAssertEqual(proposal.id, proposalId) + XCTAssertEqual(proposal.ownerId, ownerId) + XCTAssertEqual(proposal.revision, 1) + XCTAssertEqual(proposal.createdAtMs, createdAt) + XCTAssertEqual(proposal.updatedAtMs, createdAt) + XCTAssertEqual(proposal.createdAt, Date(timeIntervalSince1970: 1_700_000_000)) + XCTAssertEqual(proposal.title, "Which block size?") + XCTAssertEqual(proposal.descriptionDocument?.id, otherChoiceId) + XCTAssertEqual(proposal.descriptionDocument?.contractId, ownerId) + XCTAssertEqual(proposal.descriptionDocument?.documentType, "post") + XCTAssertEqual(proposal.url, "https://forum.dash.org/t/block-size") + XCTAssertTrue(proposal.open) + } + + func testShouldDecodeAnAbsentDescriptionDocumentAndUrlAsNil() throws { + let proposal = try decode( + MultipleChoiceProposal.self, + proposalJSON(descriptionDocument: "null", url: "null", open: false) + ) + + XCTAssertNil(proposal.descriptionDocument) + XCTAssertNil(proposal.url) + XCTAssertFalse(proposal.open) + } + + func testShouldDecodeNullSystemFieldsAsAbsent() throws { + let json = """ + {"id":"\(proposalId)","ownerId":"\(ownerId)",\ + "revision":null,"createdAt":null,"updatedAt":null,\ + "title":"t","descriptionDocument":null,"url":"https://dash.org","open":true} + """ + let proposal = try decode(MultipleChoiceProposal.self, json) + + XCTAssertNil(proposal.revision) + XCTAssertNil(proposal.createdAtMs) + XCTAssertNil(proposal.createdAt) + XCTAssertNil(proposal.updatedAtMs) + XCTAssertNil(proposal.updatedAt) + } + + func testShouldDecodeAListingInItsOrder() throws { + let first = proposalJSON(descriptionDocument: "null", url: #""https://dash.org""#) + let second = first.replacingOccurrences(of: proposalId, with: otherChoiceId) + let listing = try decode([MultipleChoiceProposal].self, "[\(first),\(second)]") + + XCTAssertEqual(listing.map(\.id), [proposalId, otherChoiceId]) + XCTAssertEqual(try decode([MultipleChoiceProposal].self, "[]"), []) + } + + func testShouldRefuseAProposalMissingARequiredField() { + let json = proposalJSON(descriptionDocument: "null", url: "null") + .replacingOccurrences(of: #","open":true"#, with: "") + + XCTAssertThrowsError(try decode(MultipleChoiceProposal.self, json)) { error in + guard case SDKError.serializationError = error else { + return XCTFail("expected a serialization error, got \(error)") + } + } + } + + // MARK: - Choice + + func testShouldDecodeAChoiceWithEveryField() throws { + let choice = try decode( + ProposalChoice.self, + choiceJSON(id: choiceId, description: #""Twice the size it is today.""#) + ) + + XCTAssertEqual(choice.id, choiceId) + XCTAssertEqual(choice.ownerId, ownerId) + XCTAssertEqual(choice.proposalId, proposalId) + XCTAssertNil(choice.revision) + XCTAssertEqual(choice.createdAtMs, createdAt) + XCTAssertEqual(choice.createdAt, Date(timeIntervalSince1970: 1_700_000_000)) + XCTAssertNil(choice.updatedAtMs) + XCTAssertEqual(choice.title, "Double it") + XCTAssertEqual(choice.description, "Twice the size it is today.") + } + + func testShouldDecodeAChoiceWithoutADescription() throws { + let choice = try decode(ProposalChoice.self, choiceJSON(id: choiceId, description: "null")) + + XCTAssertNil(choice.description) + XCTAssertEqual(choice.title, "Double it") + } + + // MARK: - Vote + + func testShouldDecodeARunningVoteWithItsChoicesAndTallies() throws { + let json = """ + {"choices":[\ + {"id":"\(otherChoiceId)","choice":null,"voteTally":null},\ + {"id":"\(choiceId)","choice":\(choiceJSON(id: choiceId, description: "null")),"voteTally":12}],\ + "abstainVoteTally":3,"noneOfTheChoicesVoteTally":1,"result":null} + """ + let vote = try decode(MultipleChoiceProposalVote.self, json) + + XCTAssertEqual(vote.choices.map(\.id), [otherChoiceId, choiceId]) + XCTAssertNil(vote.choices[0].choice) + XCTAssertNil(vote.choices[0].voteTally) + XCTAssertEqual(vote.choices[1].choice?.id, choiceId) + XCTAssertEqual(vote.choices[1].choice?.title, "Double it") + XCTAssertEqual(vote.choices[1].voteTally, 12) + XCTAssertEqual(vote.abstainVoteTally, 3) + XCTAssertEqual(vote.noneOfTheChoicesVoteTally, 1) + XCTAssertNil(vote.result) + } + + func testShouldDecodeHowAFinishedVoteEnded() throws { + for (outcomeName, outcome, keptChoiceId) in [ + ("keptChoice", MultipleChoiceProposalVote.Outcome.keptChoice, #""\#(choiceId)""#), + ("noneOfTheChoices", .noneOfTheChoices, "null"), + ("noWinner", .noWinner, "null"), + ] { + let json = """ + {"choices":[{"id":"\(choiceId)","choice":null,"voteTally":9}],\ + "abstainVoteTally":null,"noneOfTheChoicesVoteTally":4,\ + "result":{"outcome":"\(outcomeName)","keptChoiceId":\(keptChoiceId),\ + "finalizationBlock":{"height":9,"coreHeight":42,"timeMs":9000,"epoch":3}}} + """ + let vote = try decode(MultipleChoiceProposalVote.self, json) + let result = try XCTUnwrap(vote.result, outcomeName) + + XCTAssertEqual(result.outcome, outcome) + XCTAssertEqual(result.keptChoiceId, outcome == .keptChoice ? choiceId : nil) + XCTAssertEqual(result.finalizationBlock.height, 9) + XCTAssertEqual(result.finalizationBlock.coreHeight, 42) + XCTAssertEqual(result.finalizationBlock.timeMs, 9000) + XCTAssertEqual(result.finalizationBlock.epoch, 3) + XCTAssertEqual(result.finalizationBlock.time, Date(timeIntervalSince1970: 9)) + XCTAssertEqual(vote.choices.first?.voteTally, 9) + XCTAssertNil(vote.choices.first?.choice) + XCTAssertNil(vote.abstainVoteTally) + XCTAssertEqual(vote.noneOfTheChoicesVoteTally, 4) + } + } + + func testShouldDecodeAVoteWithNoChoiceAsEmpty() throws { + let vote = try decode( + MultipleChoiceProposalVote.self, + #"{"choices":[],"abstainVoteTally":null,"noneOfTheChoicesVoteTally":null,"result":null}"# + ) + + XCTAssertEqual(vote.choices, []) + XCTAssertNil(vote.abstainVoteTally) + XCTAssertNil(vote.noneOfTheChoicesVoteTally) + XCTAssertNil(vote.result) + } + + func testShouldRefuseAnUnknownOutcome() { + let json = """ + {"choices":[],"abstainVoteTally":null,"noneOfTheChoicesVoteTally":null,\ + "result":{"outcome":"locked","keptChoiceId":null,\ + "finalizationBlock":{"height":9,"coreHeight":42,"timeMs":9000,"epoch":3}}} + """ + + XCTAssertThrowsError(try decode(MultipleChoiceProposalVote.self, json)) + } + + // MARK: - Masternode answer and vote choice + + func testShouldDecodeAMasternodeAnswerForEveryChoice() throws { + XCTAssertEqual( + try decode(MultipleChoiceVoteChoice.self, #"{"choice":"choice","choiceId":"\#(choiceId)"}"#), + .choice(id: choiceId) + ) + XCTAssertEqual( + try decode(MultipleChoiceVoteChoice.self, #"{"choice":"noneOfTheChoices","choiceId":null}"#), + .noneOfTheChoices + ) + XCTAssertEqual( + try decode(MultipleChoiceVoteChoice.self, #"{"choice":"abstain","choiceId":null}"#), + .abstain + ) + } + + func testShouldRefuseAMasternodeAnswerThatCannotBeRead() { + // A vote for a choice that names none, and an unknown answer. + XCTAssertThrowsError( + try decode(MultipleChoiceVoteChoice.self, #"{"choice":"choice","choiceId":null}"#) + ) + XCTAssertThrowsError( + try decode(MultipleChoiceVoteChoice.self, #"{"choice":"lock","choiceId":null}"#) + ) + } + + /// The `vote_choice` byte must agree with `MultipleChoiceVoteChoiceFFI` in + /// `rs-sdk-ffi`: a choice 0, none of the choices 1, abstain 2. The FFI + /// requires `choice_id` for 0 and a null one otherwise. + func testShouldEncodeTheVoteChoicesAsTheFFIBytesAndChoiceId() { + XCTAssertEqual(MultipleChoiceVoteChoice.choice(id: choiceId).ffiTag, 0) + XCTAssertEqual(MultipleChoiceVoteChoice.noneOfTheChoices.ffiTag, 1) + XCTAssertEqual(MultipleChoiceVoteChoice.abstain.ffiTag, 2) + + XCTAssertEqual(MultipleChoiceVoteChoice.choice(id: choiceId).choiceId, choiceId) + XCTAssertNil(MultipleChoiceVoteChoice.noneOfTheChoices.choiceId) + XCTAssertNil(MultipleChoiceVoteChoice.abstain.choiceId) + } + + // MARK: - Credits + + func testShouldReadTheFeeAndFundAsDecimalCredits() throws { + XCTAssertEqual(try DecisionProposalJSON.credits(from: "20000000000"), 20_000_000_000) + XCTAssertEqual(try DecisionProposalJSON.credits(from: "18446744073709551615"), UInt64.max) + for notCredits in ["", "-1", "1.5", "\"20000000000\"", "18446744073709551616"] { + XCTAssertThrowsError(try DecisionProposalJSON.credits(from: notCredits), notCredits) { error in + guard case SDKError.serializationError = error else { + return XCTFail("expected a serialization error, got \(error)") + } + } + } + } +} diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/MultipleChoiceProposalMarshallingTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/MultipleChoiceProposalMarshallingTests.swift new file mode 100644 index 00000000000..1ec4928d0d4 --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/MultipleChoiceProposalMarshallingTests.swift @@ -0,0 +1,207 @@ +import Foundation +import XCTest +@testable import SwiftDashSDK + +/// Hermetic tests for the C structs the multiple choice proposal wallet +/// wrappers hand to `platform_wallet_multiple_choice_proposal_*` +/// (`MultipleChoiceProposalParamsFFI`, `MultipleChoiceProposalEditFFI`, +/// `ChoiceParamsFFI`, `DescriptionDocumentFFI`). Each string goes through +/// `withDecisionProposalCString`, so one holding U+0000 is refused rather +/// than handed over cut short; each id must be the 32 bytes the Rust side +/// reads. No FFI call is made. +final class MultipleChoiceProposalMarshallingTests: XCTestCase { + private let documentId = Data(repeating: 5, count: 32) + private let contractId = Data(repeating: 6, count: 32) + + private var descriptionDocument: DescriptionDocumentParams { + DescriptionDocumentParams(id: documentId, contractId: contractId, documentType: "post") + } + + /// The string `pointer` holds up to its NUL terminator; `nil` for null. + private func string(_ pointer: UnsafePointer?) -> String? { + pointer.map { String(cString: $0) } + } + + /// The 32 bytes `pointer` holds; `nil` for null. + private func bytes32(_ pointer: UnsafePointer?) -> Data? { + pointer.map { Data(bytes: $0, count: 32) } + } + + /// The description document `pointer` holds, read as the Rust side reads + /// it; `nil` for null. + private func readDescriptionDocument( + _ pointer: UnsafePointer? + ) -> DescriptionDocumentParams? { + guard let document = pointer?.pointee else { return nil } + return DescriptionDocumentParams( + id: bytes32(document.id) ?? Data(), + contractId: bytes32(document.contract_id) ?? Data(), + documentType: string(document.document_type) ?? "" + ) + } + + /// `body` refuses with `PlatformWalletError.invalidParameter` naming + /// `field`, without running the marshalled body. + private func assertRefused( + field: String, + file: StaticString = #filePath, + line: UInt = #line, + _ body: (_ bodyRan: inout Bool) throws -> Void + ) { + var bodyRan = false + XCTAssertThrowsError(try body(&bodyRan), file: file, line: line) { error in + guard case PlatformWalletError.invalidParameter(let message) = error else { + return XCTFail("expected PlatformWalletError.invalidParameter, got \(error)", file: file, line: line) + } + XCTAssertTrue(message.hasPrefix("\(field) "), message, file: file, line: line) + } + XCTAssertFalse(bodyRan, "a refused value must not reach C", file: file, line: line) + } + + // MARK: - Create params + + func testShouldHandOverEveryCreateParam() throws { + let params = MultipleChoiceProposalParams( + title: "Which block size? 是 ✓", + descriptionDocument: descriptionDocument, + url: "https://forum.dash.org/t/block-size", + open: true + ) + try params.withFFI { ffi in + XCTAssertEqual(string(ffi.pointee.title), "Which block size? 是 ✓") + XCTAssertEqual(readDescriptionDocument(ffi.pointee.description_document), descriptionDocument) + XCTAssertEqual(string(ffi.pointee.url), "https://forum.dash.org/t/block-size") + XCTAssertTrue(ffi.pointee.open) + } + } + + func testShouldHandOverAbsentCreateParamsAsNullPointers() throws { + let params = MultipleChoiceProposalParams(title: "t", open: false) + try params.withFFI { ffi in + XCTAssertEqual(string(ffi.pointee.title), "t") + XCTAssertNil(ffi.pointee.description_document) + XCTAssertNil(ffi.pointee.url) + XCTAssertFalse(ffi.pointee.open) + } + } + + func testShouldRefuseACreateParamHoldingANUL() { + assertRefused(field: "title") { bodyRan in + try MultipleChoiceProposalParams(title: "Which\0", open: true).withFFI { _ in bodyRan = true } + } + assertRefused(field: "url") { bodyRan in + try MultipleChoiceProposalParams(title: "t", url: "https://\0", open: true) + .withFFI { _ in bodyRan = true } + } + var document = descriptionDocument + document.documentType = "po\0st" + assertRefused(field: "descriptionDocument.documentType") { bodyRan in + try MultipleChoiceProposalParams(title: "t", descriptionDocument: document, open: true) + .withFFI { _ in bodyRan = true } + } + } + + func testShouldRefuseADescriptionDocumentIdThatIsNot32Bytes() { + var shortId = descriptionDocument + shortId.id = Data(repeating: 5, count: 31) + assertRefused(field: "descriptionDocument.id") { bodyRan in + try MultipleChoiceProposalParams(title: "t", descriptionDocument: shortId, open: true) + .withFFI { _ in bodyRan = true } + } + var longContractId = descriptionDocument + longContractId.contractId = Data(repeating: 6, count: 33) + assertRefused(field: "descriptionDocument.contractId") { bodyRan in + try MultipleChoiceProposalParams(title: "t", descriptionDocument: longContractId, open: true) + .withFFI { _ in bodyRan = true } + } + } + + // MARK: - Edit + + func testShouldHandOverAnEditThatKeepsEverythingAsNullsWithoutFlags() throws { + try MultipleChoiceProposalEdit().withFFI { ffi in + XCTAssertNil(ffi.pointee.title) + XCTAssertNil(ffi.pointee.description_document) + XCTAssertFalse(ffi.pointee.remove_description_document) + XCTAssertNil(ffi.pointee.url) + XCTAssertFalse(ffi.pointee.remove_url) + } + } + + func testShouldHandOverAnEditThatSetsEveryField() throws { + let edit = MultipleChoiceProposalEdit( + title: "New title", + descriptionDocument: .set(descriptionDocument), + url: .set("https://dash.org") + ) + try edit.withFFI { ffi in + XCTAssertEqual(string(ffi.pointee.title), "New title") + XCTAssertEqual(readDescriptionDocument(ffi.pointee.description_document), descriptionDocument) + XCTAssertFalse(ffi.pointee.remove_description_document) + XCTAssertEqual(string(ffi.pointee.url), "https://dash.org") + XCTAssertFalse(ffi.pointee.remove_url) + } + } + + /// A removal is a null value beside a raised flag; the FFI refuses a + /// value together with its flag. + func testShouldHandOverARemovalAsANullBesideItsFlag() throws { + try MultipleChoiceProposalEdit(descriptionDocument: .remove).withFFI { ffi in + XCTAssertNil(ffi.pointee.description_document) + XCTAssertTrue(ffi.pointee.remove_description_document) + XCTAssertNil(ffi.pointee.url) + XCTAssertFalse(ffi.pointee.remove_url) + } + try MultipleChoiceProposalEdit(url: .remove).withFFI { ffi in + XCTAssertNil(ffi.pointee.description_document) + XCTAssertFalse(ffi.pointee.remove_description_document) + XCTAssertNil(ffi.pointee.url) + XCTAssertTrue(ffi.pointee.remove_url) + } + } + + func testShouldRefuseAnEditHoldingANULOrAShortId() { + assertRefused(field: "title") { bodyRan in + try MultipleChoiceProposalEdit(title: "\0").withFFI { _ in bodyRan = true } + } + assertRefused(field: "url") { bodyRan in + try MultipleChoiceProposalEdit(url: .set("a\0b")).withFFI { _ in bodyRan = true } + } + var shortId = descriptionDocument + shortId.id = Data() + assertRefused(field: "descriptionDocument.id") { bodyRan in + try MultipleChoiceProposalEdit(descriptionDocument: .set(shortId)).withFFI { _ in bodyRan = true } + } + } + + // MARK: - Choice + + func testShouldHandOverAChoice() throws { + try ProposalChoiceParams(title: "Double it", description: "Twice the size.").withFFI { ffi in + XCTAssertEqual(string(ffi.pointee.title), "Double it") + XCTAssertEqual(string(ffi.pointee.description), "Twice the size.") + } + try ProposalChoiceParams(title: "Keep it").withFFI { ffi in + XCTAssertEqual(string(ffi.pointee.title), "Keep it") + XCTAssertNil(ffi.pointee.description) + } + } + + func testShouldRefuseAChoiceHoldingANUL() { + assertRefused(field: "title") { bodyRan in + try ProposalChoiceParams(title: "Double\0it").withFFI { _ in bodyRan = true } + } + assertRefused(field: "description") { bodyRan in + try ProposalChoiceParams(title: "t", description: "\0").withFFI { _ in bodyRan = true } + } + } + + func testShouldPassTheBodysErrorThroughUnchanged() { + struct BodyError: Error, Equatable {} + XCTAssertThrowsError( + try ProposalChoiceParams(title: "t").withFFI { _ in throw BodyError() } + ) { error in + XCTAssertEqual(error as? BodyError, BodyError()) + } + } +}