From d771a4c41e8adf555d5664eede9941233a6550f3 Mon Sep 17 00:00:00 2001 From: QuantumExplorer Date: Mon, 16 Nov 2026 13:48:18 +0700 Subject: [PATCH 1/4] fix(platform)!: a contest ends whatever its contenders hold (PV15) From protocol version 15 the end of a contested resource vote poll no longer depends on every contender's stored data being usable: - check_for_ended_vote_polls 2: a contender whose stored document does not decode with the contest's document type cannot win; the winner is the earliest of the contenders that decode with the highest tally among them, compared with the lock tally as before. With none that decodes the contest has no winner. When the state refuses the winner's document (a unique index entry or the document's id already taken, or a sum it would take past its range), the award is rolled back to a savepoint and the contest has no winner. Any other error is returned as before. - remove_contested_resource_vote_poll_documents_operations 2: the clean-up finds each contender's document by the id its reference names, instead of decoding the document to read its id. A contest with no winner is recorded and cleaned up as before: its contenders' documents are removed and its prefunded balance goes to the epoch's processing fees. Generation 1 of both moves its shared body into helpers unchanged so generation 2 reuses it; protocol version 14 and earlier select what they selected. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + packages/rs-drive-abci/Cargo.toml | 2 + .../voting/check_for_ended_vote_polls/mod.rs | 10 +- .../check_for_ended_vote_polls/v1/mod.rs | 217 +++-- .../check_for_ended_vote_polls/v2/mod.rs | 144 +++ .../contest_resolution_tests.rs | 846 ++++++++++++++++++ .../masternode_vote/end_date_cleanup_tests.rs | 8 +- .../state_transitions/masternode_vote/mod.rs | 3 + .../state_transition/state_transitions/mod.rs | 33 +- ...sted-unique-index-with-summed-integer.json | 179 ++++ .../mod.rs | 10 +- .../v1/mod.rs | 52 +- .../v2/mod.rs | 99 ++ .../drive_abci_method_versions/v11.rs | 8 +- .../drive_vote_method_versions/v4.rs | 4 + .../rs-platform-version/src/version/v15.rs | 23 +- 16 files changed, 1542 insertions(+), 97 deletions(-) create mode 100644 packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v2/mod.rs create mode 100644 packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_resolution_tests.rs create mode 100644 packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-summed-integer.json create mode 100644 packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/v2/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 99233b4a698..c85f6b83ca3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2495,6 +2495,7 @@ dependencies = [ "file-rotate", "grovedb-bincode", "grovedb-commitment-tree", + "grovedb-merk", "grovedb-path", "grovedb-storage", "hex", diff --git a/packages/rs-drive-abci/Cargo.toml b/packages/rs-drive-abci/Cargo.toml index 082df27f017..355048d1be0 100644 --- a/packages/rs-drive-abci/Cargo.toml +++ b/packages/rs-drive-abci/Cargo.toml @@ -83,6 +83,8 @@ async-trait = "0.1.77" console-subscriber = { version = "0.4", optional = true } dashcore-crypto = { workspace = true, features = ["bls"], optional = true } grovedb-commitment-tree = { workspace = true } +# The error a sum taken past its range returns, which ending a contest tells from others. +grovedb-merk = { workspace = true } nonempty = "0.11" # Shielded-pool snapshot needs raw RocksDB SstFileWriter + ingest_external_file_cf # bindings, and blake3 for the snapshot-file checksum. diff --git a/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/mod.rs b/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/mod.rs index 7b69dfc9b2e..071f9d0b690 100644 --- a/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/mod.rs +++ b/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/mod.rs @@ -9,6 +9,7 @@ use drive::grovedb::TransactionArg; mod v0; mod v1; +mod v2; impl Platform where @@ -43,9 +44,16 @@ where transaction, platform_version, ), + 2 => self.check_for_ended_vote_polls_v2( + last_committed_platform_state, + block_platform_state, + block_info, + transaction, + platform_version, + ), version => Err(Error::Execution(ExecutionError::UnknownVersionMismatch { method: "check_for_ended_vote_polls".to_string(), - known_versions: vec![0, 1], + known_versions: vec![0, 1, 2], received: version, })), } diff --git a/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v1/mod.rs b/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v1/mod.rs index 41e77171bc9..43ea3874e9c 100644 --- a/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v1/mod.rs +++ b/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v1/mod.rs @@ -6,12 +6,14 @@ use crate::platform_types::platform::Platform; use crate::platform_types::platform_state::{PlatformState, PlatformStateV0Methods}; use crate::rpc::core::CoreRPCLike; use dpp::block::block_info::BlockInfo; -use dpp::data_contract::document_type::ContestedIndexResolution; +use dpp::data_contract::document_type::{ContestedIndexResolution, DocumentTypeRef}; use dpp::document::DocumentV0Getters; use dpp::identifier::Identifier; use dpp::prelude::TimestampMillis; use dpp::version::PlatformVersion; -use dpp::voting::contender_structs::FinalizedContender; +use dpp::voting::contender_structs::{ + FinalizedContender, FinalizedContenderWithSerializedDocument, +}; use dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice::TowardsIdentity; use dpp::voting::vote_info_storage::contested_document_vote_poll_winner_info::ContestedDocumentVotePollWinnerInfo; use dpp::voting::vote_polls::yes_no_vote_poll::{ @@ -19,6 +21,7 @@ use dpp::voting::vote_polls::yes_no_vote_poll::{ }; use dpp::voting::vote_polls::VotePoll; use drive::drive::votes::paths::vote_end_date_queries_tree_path_vec; +use drive::drive::votes::resolved::vote_polls::contested_document_resource_vote_poll::ContestedDocumentResourceVotePollWithContractInfo; use drive::drive::votes::resolved::vote_polls::resolve::VotePollResolver; use drive::drive::votes::resolved::vote_polls::{ResolvedVotePoll, ResolvedVotePollWithVotes}; use drive::error::drive::DriveError; @@ -39,10 +42,97 @@ where /// them and cleans their votes up. #[inline(always)] pub(super) fn check_for_ended_vote_polls_v1( + &self, + last_committed_platform_state: &PlatformState, + block_platform_state: &PlatformState, + block_info: &BlockInfo, + transaction: TransactionArg, + platform_version: &PlatformVersion, + ) -> Result<(), Error> { + self.end_due_vote_polls_v1( + last_committed_platform_state, + block_platform_state, + block_info, + Self::award_contest_winner_v1, + transaction, + platform_version, + ) + } + + /// Picks the winner of an ended contest and awards it the document: the earliest of the + /// contenders with the highest tally, every one of them decoded first, unless the lock tally + /// is higher. Any error is returned. + /// + /// Moved here unchanged from the body of generation 1, which protocol version 14 selects, + /// so that generation 2 shares the rest of the body: a pure refactor, reading, writing and + /// failing as before, in the same order. + pub(super) fn award_contest_winner_v1( + &self, + block_info: &BlockInfo, + contest: EndedContest, + transaction: TransactionArg, + platform_version: &PlatformVersion, + ) -> Result { + let EndedContest { + sorted_contenders, + locked_vote_tally, + locking_allowed, + document_type, + vote_poll, + } = contest; + let highest_vote_tally = sorted_contenders + .first() + .map(|max_voted_contender| max_voted_contender.final_vote_tally) + .unwrap_or_default(); + // These are all the people who got top votes, every one of them + // considered (up to `maximum_contenders_to_consider`); version 0 + // compared at most 100 + let top_contenders: Vec = sorted_contenders + .into_iter() + .filter(|c| c.final_vote_tally == highest_vote_tally) + .map(|contender| { + FinalizedContender::try_from_contender_with_serialized_document( + contender, + document_type, + platform_version, + ) + .map_err(Error::Protocol) + }) + .collect::, Error>>()?; + let maybe_top_contender = earliest_contender(top_contenders); + // We award the document to the top contender + let winner_info = if let Some(top_contender) = maybe_top_contender { + // let's check to make sure the lock votes didn't win it + // if the lock is tied with the top contender the top contender gets it + if locking_allowed && locked_vote_tally > top_contender.final_vote_tally { + // the record will show it's locked + ContestedDocumentVotePollWinnerInfo::Locked + } else { + let contender_id = top_contender.identity_id; + // We award the document to the winner of the vote poll + self.award_document_to_winner( + block_info, + top_contender, + vote_poll, + transaction, + platform_version, + )?; + ContestedDocumentVotePollWinnerInfo::WonByIdentity(contender_id) + } + } else { + ContestedDocumentVotePollWinnerInfo::NoWinner + }; + Ok(winner_info) + } + + /// The body of generation 1, with the step picking and awarding a contest's winner given: + /// [`Self::award_contest_winner_v1`] in generation 1, and its successor in generation 2. + pub(super) fn end_due_vote_polls_v1( &self, _last_committed_platform_state: &PlatformState, block_platform_state: &PlatformState, block_info: &BlockInfo, + award_contest_winner: AwardContestWinner, transaction: TransactionArg, platform_version: &PlatformVersion, ) -> Result<(), Error> { @@ -184,68 +274,20 @@ where identifiers_voting_for_contenders.append(&mut other_contenders); - let highest_vote_tally = sorted_contenders - .first() - .map(|max_voted_contender| max_voted_contender.final_vote_tally) - .unwrap_or_default(); - // These are all the people who got top votes, every one of them - // considered (up to `maximum_contenders_to_consider`); version 0 - // compared at most 100 - let top_contenders: Vec = sorted_contenders - .into_iter() - .filter(|c| c.final_vote_tally == highest_vote_tally) - .map(|contender| { - FinalizedContender::try_from_contender_with_serialized_document( - contender, - document_type, - platform_version, - ) - .map_err(Error::Protocol) - }) - .collect::, Error>>()?; - // A tie among the top contenders goes to the earliest document: - // creation time, then block height, then core height, then id. - // Version 0 awarded the latest. - let maybe_top_contender = top_contenders.into_iter().min_by(|a, b| { - a.document - .created_at() - .cmp(&b.document.created_at()) - .then_with(|| { - a.document - .created_at_block_height() - .cmp(&b.document.created_at_block_height()) - }) - .then_with(|| { - a.document - .created_at_core_block_height() - .cmp(&b.document.created_at_core_block_height()) - }) - .then_with(|| a.document.id().cmp(&b.document.id())) - }); - // We award the document to the top contender - let winner_info = if let Some(top_contender) = maybe_top_contender { - // let's check to make sure the lock votes didn't win it - // if the lock is tied with the top contender the top contender gets it - if locking_allowed - && result.locked_vote_tally > top_contender.final_vote_tally - { - // the record will show it's locked - ContestedDocumentVotePollWinnerInfo::Locked - } else { - let contender_id = top_contender.identity_id; - // We award the document to the winner of the vote poll - self.award_document_to_winner( - block_info, - top_contender, - &resolved_contested_document_resource_vote_poll, - transaction, - platform_version, - )?; - ContestedDocumentVotePollWinnerInfo::WonByIdentity(contender_id) - } - } else { - ContestedDocumentVotePollWinnerInfo::NoWinner - }; + // We pick the winner and award the document to it + let winner_info = award_contest_winner( + self, + block_info, + EndedContest { + sorted_contenders, + locked_vote_tally: result.locked_vote_tally, + locking_allowed, + document_type, + vote_poll: &resolved_contested_document_resource_vote_poll, + }, + transaction, + platform_version, + )?; // We want to keep a record of how everyone voted self.keep_record_of_finished_contested_resource_vote_poll( block_platform_state, @@ -363,3 +405,50 @@ where Ok(Some(voters)) } } + +/// What the end of a contest's vote poll picks its winner from +pub(super) struct EndedContest<'a> { + /// The contenders, sorted by tally from the highest + pub(super) sorted_contenders: Vec, + /// The lock tally + pub(super) locked_vote_tally: u32, + /// Whether the lock tally can beat the contenders: not on an index resolved without locking + pub(super) locking_allowed: bool, + /// The contested document type, which the contenders' documents decode with + pub(super) document_type: DocumentTypeRef<'a>, + /// The contest's vote poll + pub(super) vote_poll: &'a ContestedDocumentResourceVotePollWithContractInfo, +} + +/// The step of ending a contest that picks its winner, awards it the document and returns the +/// outcome to record +pub(super) type AwardContestWinner = fn( + &Platform, + &BlockInfo, + EndedContest, + TransactionArg, + &PlatformVersion, +) -> Result; + +/// The earliest of tied contenders: by creation time, then block height, then core height, +/// then id. Version 0 awarded the latest. +pub(super) fn earliest_contender( + contenders: Vec, +) -> Option { + contenders.into_iter().min_by(|a, b| { + a.document + .created_at() + .cmp(&b.document.created_at()) + .then_with(|| { + a.document + .created_at_block_height() + .cmp(&b.document.created_at_block_height()) + }) + .then_with(|| { + a.document + .created_at_core_block_height() + .cmp(&b.document.created_at_core_block_height()) + }) + .then_with(|| a.document.id().cmp(&b.document.id())) + }) +} diff --git a/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v2/mod.rs b/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v2/mod.rs new file mode 100644 index 00000000000..7431696f5f7 --- /dev/null +++ b/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v2/mod.rs @@ -0,0 +1,144 @@ +use super::v1::{earliest_contender, EndedContest}; +use crate::error::Error; +use crate::platform_types::platform::Platform; +use crate::platform_types::platform_state::PlatformState; +use crate::rpc::core::CoreRPCLike; +use dpp::block::block_info::BlockInfo; +use dpp::version::PlatformVersion; +use dpp::voting::contender_structs::FinalizedContender; +use dpp::voting::vote_info_storage::contested_document_vote_poll_winner_info::ContestedDocumentVotePollWinnerInfo; +use drive::error::drive::DriveError; +use drive::error::Error as DriveCrateError; +use drive::grovedb::error::Error as GroveError; +use drive::grovedb::TransactionArg; +use grovedb_merk::error::Error as MerkError; + +impl Platform +where + C: CoreRPCLike, +{ + /// Checks for ended vote polls as generation 1 does, except that a contest ends whatever + /// its contenders hold: a contender whose document does not decode cannot win, and a + /// winner whose document the state refuses leaves the contest with no winner (see + /// [`Self::award_contest_winner_v2`]). + #[inline(always)] + pub(super) fn check_for_ended_vote_polls_v2( + &self, + last_committed_platform_state: &PlatformState, + block_platform_state: &PlatformState, + block_info: &BlockInfo, + transaction: TransactionArg, + platform_version: &PlatformVersion, + ) -> Result<(), Error> { + self.end_due_vote_polls_v1( + last_committed_platform_state, + block_platform_state, + block_info, + Self::award_contest_winner_v2, + transaction, + platform_version, + ) + } + + /// Picks the winner of an ended contest and awards it the document, as generation 1 does, + /// with two differences that make the outcome depend on the contest alone: + /// + /// - A contender whose stored document does not decode with the contest's document type + /// cannot win. The winner is picked from the contenders that decode with the highest + /// tally among them, the earliest of them on a tie, and the lock tally is compared with + /// its tally. With none that decodes, the contest has no winner. + /// - When the state refuses the winner's document (see [`award_was_refused`]), what the + /// award wrote is undone and the contest has no winner. + /// + /// A contest with no winner is recorded and cleaned up like one with no contenders: its + /// contenders' documents are removed and its prefunded balance goes to the epoch's + /// processing fees. + pub(super) fn award_contest_winner_v2( + &self, + block_info: &BlockInfo, + contest: EndedContest, + transaction: TransactionArg, + platform_version: &PlatformVersion, + ) -> Result { + let EndedContest { + sorted_contenders, + locked_vote_tally, + locking_allowed, + document_type, + vote_poll, + } = contest; + // The contenders come sorted by tally from the highest: decode them in that order and + // stop at the first tally below that of a contender that decoded. + let mut eligible_contenders: Vec = vec![]; + for contender in sorted_contenders { + if eligible_contenders + .first() + .is_some_and(|eligible| eligible.final_vote_tally > contender.final_vote_tally) + { + break; + } + if let Ok(contender) = FinalizedContender::try_from_contender_with_serialized_document( + contender, + document_type, + platform_version, + ) { + eligible_contenders.push(contender); + } + } + let Some(top_contender) = earliest_contender(eligible_contenders) else { + return Ok(ContestedDocumentVotePollWinnerInfo::NoWinner); + }; + // If the lock is tied with the top contender the top contender gets it + if locking_allowed && locked_vote_tally > top_contender.final_vote_tally { + return Ok(ContestedDocumentVotePollWinnerInfo::Locked); + } + let contender_id = top_contender.identity_id; + // The award writes in one or more batches: a refusal in a later one would keep what + // the earlier ones wrote, so the award is undone to a savepoint. A savepoint left after + // an award that went through is inert: the block's transaction is committed or dropped + // with it. No contest ends in the genesis block, whose rounds rewind to the one + // savepoint `init_chain` sets. + if let Some(transaction) = transaction { + transaction.set_savepoint(); + } + match self.award_document_to_winner( + block_info, + top_contender, + vote_poll, + transaction, + platform_version, + ) { + Ok(()) => Ok(ContestedDocumentVotePollWinnerInfo::WonByIdentity( + contender_id, + )), + Err(error) if award_was_refused(&error) => { + if let Some(transaction) = transaction { + transaction + .rollback_to_savepoint() + .map_err(GroveError::StorageError) + .map_err(|error| Error::Drive(DriveCrateError::GroveDB(Box::new(error))))?; + } + Ok(ContestedDocumentVotePollWinnerInfo::NoWinner) + } + Err(error) => Err(error), + } + } +} + +/// Whether the state refused the document awarded to a contest's winner, for what the state +/// already holds or what the document adds to it: a unique index entry or the document's id +/// already taken, or a sum the document would take past its range. Each follows from the +/// state every node holds, so every node refuses the same award. Any other error, a storage +/// failure among them, is returned as before. +fn award_was_refused(error: &Error) -> bool { + match error { + Error::Drive(DriveCrateError::Drive( + DriveError::CorruptedContractIndexes(_) | DriveError::CorruptedDocumentAlreadyExists(_), + )) => true, + Error::Drive(DriveCrateError::GroveDB(error)) => matches!( + error.as_ref(), + GroveError::Overflow(_) | GroveError::MerkError(MerkError::Overflow(_)) + ), + _ => false, + } +} diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_resolution_tests.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_resolution_tests.rs new file mode 100644 index 00000000000..87ec9bf09a3 --- /dev/null +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_resolution_tests.rs @@ -0,0 +1,846 @@ +//! The end of a contest whose contenders' stored documents do not decode, or whose winner's +//! document the state refuses. From protocol version 15 (`check_for_ended_vote_polls` 2) such a +//! contender cannot win and such a contest ends with no winner; protocol version 14 +//! (`check_for_ended_vote_polls` 1) returns the error. Contract and document checks keep these +//! states from being reached through transitions, so the tests write them to the state directly. + +use crate::error::Error; +use crate::execution::validation::state_transition::state_transitions::tests::{ + create_dpns_identity_name_contest, dpns_name_vote_poll, get_vote_states, perform_votes_multi, + setup_identity, +}; +use crate::platform_types::state_transitions_processing_result::StateTransitionExecutionResult; +use crate::rpc::core::MockCoreRPCLike; +use crate::test::helpers::fast_forward_to_block::fast_forward_to_block; +use crate::test::helpers::setup::{TempPlatform, TestPlatformBuilder}; +use assert_matches::assert_matches; +use dapi_grpc::platform::v0::get_contested_resource_vote_state_request::get_contested_resource_vote_state_request_v0::ResultType; +use dapi_grpc::platform::v0::get_contested_resource_vote_state_response::get_contested_resource_vote_state_response_v0::finished_vote_info::FinishedVoteOutcome; +use dapi_grpc::platform::v0::get_contested_resource_vote_state_response::get_contested_resource_vote_state_response_v0::FinishedVoteInfo; +use dpp::block::block_info::BlockInfo; +use dpp::dash_to_credits; +use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::data_contract::document_type::random_document::{ + CreateRandomDocument, DocumentFieldFillSize, DocumentFieldFillType, +}; +use dpp::data_contract::DataContract; +use dpp::document::{Document, DocumentV0Getters, DocumentV0Setters}; +use dpp::identity::accessors::IdentityGettersV0; +use dpp::identity::SecurityLevel; +use dpp::platform_value::{Bytes32, Identifier, Value}; +use dpp::prelude::TimestampMillis; +use dpp::serialization::PlatformSerializable; +use dpp::state_transition::batch_transition::document_base_transition::DocumentBaseTransition; +use dpp::state_transition::batch_transition::document_create_transition::DocumentCreateTransitionV0; +use dpp::state_transition::batch_transition::{ + BatchTransition, BatchTransitionV0, DocumentCreateTransition, +}; +use dpp::state_transition::StateTransition; +use dpp::version::PlatformVersion; +use dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use dpp::voting::vote_info_storage::contested_document_vote_poll_stored_info::{ + ContestedDocumentVotePollStatus, ContestedDocumentVotePollStoredInfoV0Getters, +}; +use dpp::voting::vote_polls::contested_document_resource_vote_poll::ContestedDocumentResourceVotePoll; +use drive::drive::document::query::QueryDocumentsOutcomeV0Methods; +use drive::drive::votes::paths::vote_contested_resource_contract_documents_storage_path; +use drive::drive::votes::resolved::vote_polls::contested_document_resource_vote_poll::resolve::ContestedDocumentResourceVotePollResolver; +use drive::error::drive::DriveError; +use drive::error::Error as DriveCrateError; +use drive::grovedb::Element; +use drive::query::DriveDocumentQuery; +use drive::util::object_size_info::DocumentInfo::DocumentRefInfo; +use drive::util::object_size_info::{DocumentAndContractInfo, OwnedDocumentInfo}; +use drive::util::test_helpers::{setup_contract, vote_poll_end_dates}; +use rand::prelude::StdRng; +use rand::{Rng, SeedableRng}; + +/// A contest on `normalizedLabel` and `rank`, where `domain` sums `rank` +const SUMMED_RANK_CONTRACT: &str = + "tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-summed-integer.json"; + +fn protocol_version_14() -> &'static PlatformVersion { + PlatformVersion::get(14).expect("expected protocol version 14") +} + +/// Runs the ended vote poll check of a block at the first end date and returns its result, +/// committing the block when it succeeds +fn end_first_due_vote_polls( + platform: &TempPlatform, + platform_version: &PlatformVersion, +) -> Result<(), Error> { + let time_ms: TimestampMillis = *vote_poll_end_dates(&platform.drive, platform_version) + .keys() + .next() + .expect("expected a vote poll end date"); + fast_forward_to_block(platform, time_ms, 900, 42, 0, false); + let platform_state = platform.state.load(); + let transaction = platform.drive.grove.start_transaction(); + platform.check_for_ended_vote_polls( + &platform_state, + &platform_state, + &BlockInfo { + time_ms, + height: 900, + core_height: 42, + epoch: Default::default(), + }, + Some(&transaction), + platform_version, + )?; + platform + .drive + .grove + .commit_transaction(transaction) + .unwrap() + .expect("expected to commit the block"); + Ok(()) +} + +/// The documents of the DPNS name contest on `name`, by contender +fn contender_documents( + platform: &TempPlatform, + dpns_contract: &DataContract, + name: &str, + platform_version: &PlatformVersion, +) -> Vec<(Identifier, Document)> { + let platform_state = platform.state.load(); + let (contenders, ..) = get_vote_states( + platform, + &platform_state, + dpns_contract, + name, + None, + true, + None, + ResultType::DocumentsAndVoteTally, + platform_version, + ); + contenders + .into_iter() + .map(|contender| { + ( + contender.identity_id(), + contender + .document() + .clone() + .expect("expected the contender's document"), + ) + }) + .collect() +} + +fn finished_vote_info( + platform: &TempPlatform, + dpns_contract: &DataContract, + name: &str, + platform_version: &PlatformVersion, +) -> Option { + let platform_state = platform.state.load(); + get_vote_states( + platform, + &platform_state, + dpns_contract, + name, + None, + true, + None, + ResultType::DocumentsAndVoteTally, + platform_version, + ) + .3 +} + +/// The status the stored record of `vote_poll` holds, and the height of its last finalization +fn stored_poll_status( + platform: &TempPlatform, + vote_poll: &ContestedDocumentResourceVotePoll, + platform_version: &PlatformVersion, +) -> (ContestedDocumentVotePollStatus, Option) { + let resolved_vote_poll = vote_poll + .resolve(&platform.drive, None, platform_version) + .expect("expected to resolve the vote poll"); + let (_, stored_info) = platform + .drive + .fetch_contested_document_vote_poll_stored_info( + &resolved_vote_poll, + None, + None, + platform_version, + ) + .expect("expected to read the vote poll's record"); + let stored_info = stored_info.expect("expected the vote poll's record"); + ( + stored_info.vote_poll_status(), + stored_info + .last_finalization_block() + .map(|block_info| block_info.height), + ) +} + +/// The contest ended in the block at height 900 with no winner: its record is back to not +/// started, so a new contest may open on its values +fn assert_ended_with_no_winner( + platform: &TempPlatform, + vote_poll: &ContestedDocumentResourceVotePoll, + platform_version: &PlatformVersion, +) { + assert_eq!( + stored_poll_status(platform, vote_poll, platform_version), + (ContestedDocumentVotePollStatus::NotStarted, Some(900)) + ); +} + +/// Cuts the stored bytes of a contender's document short, keeping its storage flags, so they +/// no longer decode +fn truncate_contender_document( + platform: &TempPlatform, + contract_id: Identifier, + document_id: Identifier, + platform_version: &PlatformVersion, +) { + let grove_version = &platform_version.drive.grove_version; + let path = + vote_contested_resource_contract_documents_storage_path(contract_id.as_slice(), "domain"); + let element = platform + .drive + .grove + .get_raw( + path.as_ref().into(), + document_id.as_slice(), + None, + grove_version, + ) + .unwrap() + .expect("expected the contender's stored document"); + let Element::Item(bytes, flags) = element else { + panic!("expected the contender's document to be stored as an item"); + }; + platform + .drive + .grove + .insert( + path.as_ref(), + document_id.as_slice(), + Element::Item(bytes[..10].to_vec(), flags), + None, + None, + grove_version, + ) + .unwrap() + .expect("expected to overwrite the contender's document"); +} + +/// Writes `document` to the state as a document of `contract`'s `domain` outside any contest, +/// without the checks of a transition +fn insert_domain_directly( + platform: &TempPlatform, + contract: &DataContract, + document: &Document, + platform_version: &PlatformVersion, +) { + platform + .drive + .add_document_for_contract( + DocumentAndContractInfo { + owned_document_info: OwnedDocumentInfo { + document_info: DocumentRefInfo((document, None)), + owner_id: Some(document.owner_id().to_buffer()), + }, + contract, + document_type: contract + .document_type_for_name("domain") + .expect("expected a domain document type"), + }, + false, + BlockInfo::default_with_time(4000), + true, + None, + platform_version, + ) + .expect("expected to write the domain"); +} + +/// `template` with another id and owner +fn other_domain_like(template: &Document, seed: u8) -> Document { + let mut document = template.clone(); + let owner_id = Identifier::new([seed; 32]); + document.set_id(Identifier::new([seed.wrapping_add(1); 32])); + document.set_owner_id(owner_id); + document.set("records.identity", owner_id.into()); + document +} + +/// The DPNS name contest on "quantum", with two contenders and no votes, at `platform_version` +async fn quantum_contest( + platform_version: &PlatformVersion, +) -> ( + TempPlatform, + Identifier, + Identifier, + DataContract, +) { + let mut platform = TestPlatformBuilder::new() + .with_initial_protocol_version(platform_version.protocol_version) + .build_with_mock_rpc() + .set_genesis_state(); + let platform_state = platform.state.load(); + let (contender_1, contender_2, dpns_contract) = create_dpns_identity_name_contest( + &mut platform, + &platform_state, + 7, + "quantum", + platform_version, + ) + .await; + ( + platform, + contender_1.id(), + contender_2.id(), + dpns_contract.as_ref().clone(), + ) +} + +/// The contest is gone: no end date, no prefunded balance, no contender left +fn assert_contest_cleaned_up( + platform: &TempPlatform, + dpns_contract: &DataContract, + name: &str, + platform_version: &PlatformVersion, +) { + assert!( + vote_poll_end_dates(&platform.drive, platform_version).is_empty(), + "the contest's end date must be removed" + ); + let balance_id = dpns_name_vote_poll(dpns_contract, name) + .specialized_balance_id() + .expect("expected the prefunded balance id"); + let balance = platform + .drive + .fetch_prefunded_specialized_balance(balance_id.to_buffer(), None, platform_version) + .expect("expected to read the prefunded balance"); + assert_eq!( + balance.unwrap_or_default(), + 0, + "the contest's prefunded balance must be emptied" + ); + let platform_state = platform.state.load(); + let (contenders, ..) = get_vote_states( + platform, + &platform_state, + dpns_contract, + name, + None, + true, + None, + ResultType::DocumentsAndVoteTally, + platform_version, + ); + assert!( + contenders + .iter() + .all(|contender| contender.document().is_none()), + "the contenders' documents must be removed" + ); +} + +/// The `domain` documents of `owner_id` in the state, outside any contest +fn awarded_domains( + platform: &TempPlatform, + dpns_contract: &DataContract, + owner_id: Identifier, + platform_version: &PlatformVersion, +) -> Vec { + let query = DriveDocumentQuery::all_items_query( + dpns_contract, + dpns_contract + .document_type_for_name("domain") + .expect("expected a domain document type"), + None, + ); + let documents = platform + .drive + .query_documents( + query, + None, + false, + None, + Some(platform_version.protocol_version), + ) + .expect("expected to query the domains"); + documents + .documents() + .iter() + .filter(|document| document.owner_id() == owner_id) + .cloned() + .collect() +} + +#[tokio::test] +async fn should_award_the_next_earliest_contender_when_the_earliest_does_not_decode() { + let platform_version = PlatformVersion::latest(); + let (platform, contender_1, contender_2, dpns_contract) = + quantum_contest(platform_version).await; + let documents = contender_documents(&platform, &dpns_contract, "quantum", platform_version); + // With no votes the earliest contender, contender 2, would win + let (_, earliest_document) = documents + .iter() + .find(|(contender, _)| *contender == contender_2) + .expect("expected contender 2"); + truncate_contender_document( + &platform, + dpns_contract.id(), + earliest_document.id(), + platform_version, + ); + + end_first_due_vote_polls(&platform, platform_version) + .expect("expected the contest to end with the block"); + + let finished = finished_vote_info(&platform, &dpns_contract, "quantum", platform_version) + .expect("expected the contest to be finished"); + assert_eq!( + finished.finished_vote_outcome, + FinishedVoteOutcome::TowardsIdentity as i32 + ); + assert_eq!(finished.won_by_identity_id, Some(contender_1.to_vec())); + assert_eq!( + awarded_domains(&platform, &dpns_contract, contender_1, platform_version).len(), + 1, + "the contender whose document decodes must be awarded it" + ); + assert_contest_cleaned_up(&platform, &dpns_contract, "quantum", platform_version); +} + +#[tokio::test] +async fn should_end_a_contest_with_no_winner_when_no_contender_decodes() { + let platform_version = PlatformVersion::latest(); + let (platform, contender_1, contender_2, dpns_contract) = + quantum_contest(platform_version).await; + for (_, document) in contender_documents(&platform, &dpns_contract, "quantum", platform_version) + { + truncate_contender_document( + &platform, + dpns_contract.id(), + document.id(), + platform_version, + ); + } + + end_first_due_vote_polls(&platform, platform_version) + .expect("expected the contest to end with the block"); + + assert_ended_with_no_winner( + &platform, + &dpns_name_vote_poll(&dpns_contract, "quantum"), + platform_version, + ); + for contender in [contender_1, contender_2] { + assert!(awarded_domains(&platform, &dpns_contract, contender, platform_version).is_empty()); + } + assert_contest_cleaned_up(&platform, &dpns_contract, "quantum", platform_version); +} + +#[tokio::test] +async fn should_award_the_contender_with_the_most_votes_among_those_that_decode() { + let platform_version = PlatformVersion::latest(); + let (mut platform, contender_1, contender_2, dpns_contract) = + quantum_contest(platform_version).await; + perform_votes_multi( + &mut platform, + &dpns_contract, + vec![ + (ResourceVoteChoice::TowardsIdentity(contender_1), 3), + (ResourceVoteChoice::TowardsIdentity(contender_2), 2), + (ResourceVoteChoice::Lock, 1), + ], + "quantum", + 10, + None, + platform_version, + ) + .await; + let documents = contender_documents(&platform, &dpns_contract, "quantum", platform_version); + let (_, leading_document) = documents + .iter() + .find(|(contender, _)| *contender == contender_1) + .expect("expected contender 1"); + truncate_contender_document( + &platform, + dpns_contract.id(), + leading_document.id(), + platform_version, + ); + + end_first_due_vote_polls(&platform, platform_version) + .expect("expected the contest to end with the block"); + + let finished = finished_vote_info(&platform, &dpns_contract, "quantum", platform_version) + .expect("expected the contest to be finished"); + assert_eq!(finished.won_by_identity_id, Some(contender_2.to_vec())); + assert_eq!( + awarded_domains(&platform, &dpns_contract, contender_2, platform_version).len(), + 1 + ); + assert_contest_cleaned_up(&platform, &dpns_contract, "quantum", platform_version); +} + +#[tokio::test] +async fn should_lock_when_the_lock_beats_every_contender_that_decodes() { + let platform_version = PlatformVersion::latest(); + let (mut platform, contender_1, contender_2, dpns_contract) = + quantum_contest(platform_version).await; + perform_votes_multi( + &mut platform, + &dpns_contract, + vec![ + (ResourceVoteChoice::TowardsIdentity(contender_1), 3), + (ResourceVoteChoice::Lock, 2), + (ResourceVoteChoice::TowardsIdentity(contender_2), 1), + ], + "quantum", + 10, + None, + platform_version, + ) + .await; + let documents = contender_documents(&platform, &dpns_contract, "quantum", platform_version); + let (_, leading_document) = documents + .iter() + .find(|(contender, _)| *contender == contender_1) + .expect("expected contender 1"); + truncate_contender_document( + &platform, + dpns_contract.id(), + leading_document.id(), + platform_version, + ); + + end_first_due_vote_polls(&platform, platform_version) + .expect("expected the contest to end with the block"); + + let finished = finished_vote_info(&platform, &dpns_contract, "quantum", platform_version) + .expect("expected the contest to be finished"); + assert_eq!( + finished.finished_vote_outcome, + FinishedVoteOutcome::Locked as i32 + ); + assert_contest_cleaned_up(&platform, &dpns_contract, "quantum", platform_version); +} + +#[tokio::test] +async fn should_fail_on_a_contender_that_does_not_decode_at_protocol_version_14() { + let platform_version = protocol_version_14(); + let (platform, _, _, dpns_contract) = quantum_contest(platform_version).await; + let (_, document) = + contender_documents(&platform, &dpns_contract, "quantum", platform_version).remove(0); + truncate_contender_document( + &platform, + dpns_contract.id(), + document.id(), + platform_version, + ); + + assert_matches!( + end_first_due_vote_polls(&platform, platform_version), + Err(Error::Protocol(_)) + ); +} + +#[tokio::test] +async fn should_end_a_contest_with_no_winner_when_its_unique_index_entry_is_taken() { + let platform_version = PlatformVersion::latest(); + let (platform, contender_1, contender_2, dpns_contract) = + quantum_contest(platform_version).await; + let (_, template) = + contender_documents(&platform, &dpns_contract, "quantum", platform_version).remove(0); + let holder = other_domain_like(&template, 0x51); + insert_domain_directly(&platform, &dpns_contract, &holder, platform_version); + + end_first_due_vote_polls(&platform, platform_version) + .expect("expected the contest to end with the block"); + + assert_ended_with_no_winner( + &platform, + &dpns_name_vote_poll(&dpns_contract, "quantum"), + platform_version, + ); + for contender in [contender_1, contender_2] { + assert!(awarded_domains(&platform, &dpns_contract, contender, platform_version).is_empty()); + } + assert_eq!( + awarded_domains( + &platform, + &dpns_contract, + holder.owner_id(), + platform_version + ), + vec![holder], + "the document holding the entry must stay as it was" + ); + assert_contest_cleaned_up(&platform, &dpns_contract, "quantum", platform_version); +} + +#[tokio::test] +async fn should_fail_on_a_taken_unique_index_entry_at_protocol_version_14() { + let platform_version = protocol_version_14(); + let (platform, _, _, dpns_contract) = quantum_contest(platform_version).await; + let (_, template) = + contender_documents(&platform, &dpns_contract, "quantum", platform_version).remove(0); + insert_domain_directly( + &platform, + &dpns_contract, + &other_domain_like(&template, 0x51), + platform_version, + ); + + assert_matches!( + end_first_due_vote_polls(&platform, platform_version), + Err(Error::Drive(DriveCrateError::Drive( + DriveError::CorruptedContractIndexes(_) + ))) + ); +} + +/// Opens a contest on `quantum` with `rank` 1 in [`SUMMED_RANK_CONTRACT`], after writing a +/// domain `big` whose `rank` is `i64::MAX`, then ends it at `platform_version` +async fn end_contest_over_a_full_sum( + platform_version: &PlatformVersion, +) -> ( + TempPlatform, + DataContract, + Identifier, + Result<(), Error>, +) { + let mut platform = TestPlatformBuilder::new() + .with_initial_protocol_version(platform_version.protocol_version) + .build_with_mock_rpc() + .set_genesis_state(); + let mut rng = StdRng::seed_from_u64(0x5011_0000); + let (identity, signer, key) = setup_identity(&mut platform, rng.gen(), dash_to_credits!(0.5)); + let contract_owner = setup_identity(&mut platform, rng.gen(), dash_to_credits!(0.5)); + let contract = setup_contract( + &platform.drive, + SUMMED_RANK_CONTRACT, + None, + Some(contract_owner.0.id().to_buffer()), + None::, + None, + Some(platform_version), + ); + let domain = contract + .document_type_for_name("domain") + .expect("expected a domain document type"); + + let entropy = Bytes32::random_with_rng(&mut rng); + let mut document = domain + .random_document_with_identifier_and_entropy( + &mut rng, + identity.id(), + entropy, + DocumentFieldFillType::FillIfNotRequired, + DocumentFieldFillSize::AnyDocumentFillSize, + platform_version, + ) + .expect("expected a random domain document"); + document.set("parentDomainName", "dash".into()); + document.set("normalizedParentDomainName", "dash".into()); + document.set("records.identity", document.owner_id().into()); + document.set("subdomainRules.allowSubdomains", false.into()); + document.set("preorderSalt", rng.gen::<[u8; 32]>().into()); + + let mut big = document.clone(); + big.set("label", "big".into()); + big.set("normalizedLabel", "big".into()); + big.set("rank", Value::I64(i64::MAX)); + let big = other_domain_like(&big, 0x61); + insert_domain_directly(&platform, &contract, &big, platform_version); + + document.set("label", "quantum".into()); + document.set("normalizedLabel", "quantum".into()); + document.set("rank", Value::I64(1)); + document + .set_id_for_creation(domain, &entropy.0, 2, platform_version) + .expect("expected to set the document id"); + let create_transition: DocumentCreateTransition = DocumentCreateTransitionV0 { + base: DocumentBaseTransition::from_document( + &document, + domain, + None, + 2, + platform_version, + None, + ) + .expect("expected a base transition"), + entropy: entropy.0, + data: document.clone().properties_consumed(), + prefunded_voting_balance: Some(( + "parentNameAndLabel".to_string(), + platform_version + .fee_version + .vote_resolution_fund_fees + .contested_document_vote_resolution_fund_required_amount, + )), + } + .into(); + let batch: BatchTransition = BatchTransitionV0 { + owner_id: identity.id(), + transitions: vec![create_transition.into()], + user_fee_increase: 0, + signature_public_key_id: 0, + signature: Default::default(), + } + .into(); + let mut transition: StateTransition = batch.into(); + transition + .sign_external(&key, &signer, Some(|_, _| Ok(SecurityLevel::HIGH))) + .await + .expect("expected to sign"); + let serialized_transition = transition + .serialize_to_bytes() + .expect("expected to serialize the transition"); + let platform_state = platform.state.load(); + let transaction = platform.drive.grove.start_transaction(); + let processing_result = platform + .platform + .process_raw_state_transitions( + &[serialized_transition], + &platform_state, + &BlockInfo::default_with_time(5000), + &transaction, + platform_version, + false, + None, + ) + .expect("expected to process the state transition"); + platform + .drive + .grove + .commit_transaction(transaction) + .unwrap() + .expect("expected to commit transaction"); + assert_matches!( + processing_result.into_execution_results().remove(0), + StateTransitionExecutionResult::SuccessfulExecution { .. }, + "the contender must join the contest" + ); + + let result = end_first_due_vote_polls(&platform, platform_version); + (platform, contract, identity.id(), result) +} + +#[tokio::test] +async fn should_end_a_contest_with_no_winner_when_the_award_takes_a_sum_past_its_range() { + let platform_version = PlatformVersion::latest(); + let (platform, contract, contender, result) = + end_contest_over_a_full_sum(platform_version).await; + result.expect("expected the contest to end with the block"); + + assert!( + awarded_domains(&platform, &contract, contender, platform_version).is_empty(), + "nothing of the refused award may stay in the state" + ); + assert!(vote_poll_end_dates(&platform.drive, platform_version).is_empty()); + assert_ended_with_no_winner( + &platform, + &ContestedDocumentResourceVotePoll { + contract_id: contract.id(), + document_type_name: "domain".to_string(), + index_name: "parentNameAndLabel".to_string(), + index_values: vec![ + Value::Text("dash".to_string()), + Value::Text("quantum".to_string()), + Value::I64(1), + ], + }, + platform_version, + ); +} + +#[tokio::test] +async fn should_fail_on_an_award_taking_a_sum_past_its_range_at_protocol_version_14() { + let (_, _, _, result) = end_contest_over_a_full_sum(protocol_version_14()).await; + assert_matches!(result, Err(Error::Drive(DriveCrateError::GroveDB(_)))); +} + +/// Ends the same contest, with votes for both contenders and the lock, at the latest protocol +/// version with `check_for_ended_vote_polls` and +/// `remove_contested_resource_vote_poll_documents_operations` at the given generations, and +/// returns the state's root hash, the outcome and the awarded domains of the winner +async fn end_an_ordinary_contest_with_generations( + (end_generation, clean_up_generation): (u16, u16), +) -> ([u8; 32], Option, Vec) { + let mut platform_version = PlatformVersion::latest().clone(); + platform_version + .drive_abci + .methods + .voting + .check_for_ended_vote_polls = end_generation; + platform_version + .drive + .methods + .vote + .cleanup + .remove_contested_resource_vote_poll_documents_operations = clean_up_generation; + let (mut platform, contender_1, contender_2, dpns_contract) = + quantum_contest(&platform_version).await; + perform_votes_multi( + &mut platform, + &dpns_contract, + vec![ + (ResourceVoteChoice::TowardsIdentity(contender_1), 2), + (ResourceVoteChoice::TowardsIdentity(contender_2), 3), + (ResourceVoteChoice::Lock, 1), + ], + "quantum", + 10, + None, + &platform_version, + ) + .await; + end_first_due_vote_polls(&platform, &platform_version) + .expect("expected the contest to end with the block"); + let root_hash = platform + .drive + .grove + .root_hash(None, &platform_version.drive.grove_version) + .unwrap() + .expect("expected the root hash"); + ( + root_hash, + finished_vote_info(&platform, &dpns_contract, "quantum", &platform_version), + awarded_domains(&platform, &dpns_contract, contender_2, &platform_version), + ) +} + +/// An ordinary contest ends with the same winner, records and state with the latest +/// generations as with the previous ones +#[tokio::test] +async fn should_end_an_ordinary_contest_as_the_previous_generation_does() { + let latest_version = PlatformVersion::latest(); + let latest_generations = ( + latest_version + .drive_abci + .methods + .voting + .check_for_ended_vote_polls, + latest_version + .drive + .methods + .vote + .cleanup + .remove_contested_resource_vote_poll_documents_operations, + ); + assert_eq!(latest_generations, (2, 2)); + let previous = end_an_ordinary_contest_with_generations((1, 1)).await; + let latest = end_an_ordinary_contest_with_generations(latest_generations).await; + assert_eq!( + latest + .1 + .as_ref() + .map(|finished| finished.finished_vote_outcome), + Some(FinishedVoteOutcome::TowardsIdentity as i32) + ); + assert_eq!(latest.2.len(), 1, "the winner must be awarded its domain"); + assert_eq!(latest, previous); +} diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/end_date_cleanup_tests.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/end_date_cleanup_tests.rs index e2ed7bd3a0a..19d34702b41 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/end_date_cleanup_tests.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/end_date_cleanup_tests.rs @@ -77,10 +77,10 @@ fn end_due_vote_polls( .expect("expected to commit the block"); } -/// The protocol versions the end of block tests run at, 14 first. Protocol version 14 runs the -/// same end of block generations on these paths as 15 today (`check_for_ended_vote_polls` v1, -/// `clean_up_after_vote_polls_end` v0); the run at 14 pins them there, so a later change to 15's -/// tables cannot leave 14 untested. +/// The protocol versions the end of block tests run at, 14 first. Protocol version 14 runs +/// `check_for_ended_vote_polls` v1 and 15 runs v2, which ends these contests as v1 does; both +/// run `clean_up_after_vote_polls_end` v0. The run at 14 pins its generations there, so a later +/// change to 15's tables cannot leave 14 untested. pub(super) fn end_of_block_test_versions() -> [&'static PlatformVersion; 2] { [ PlatformVersion::get(14).expect("expected protocol version 14"), diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/mod.rs index be033d87101..98c239b00ed 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/mod.rs @@ -115,6 +115,9 @@ mod multiple_choice_proposal_tests; #[cfg(test)] mod end_date_cleanup_tests; +#[cfg(test)] +mod contest_resolution_tests; + #[cfg(test)] mod tests { use crate::test::helpers::setup::TestPlatformBuilder; diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/mod.rs index dd82049e016..0b7340f7e1d 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/mod.rs @@ -3665,14 +3665,15 @@ pub(in crate::execution) mod tests { /// vote-poll resolver. When `widen` is true the byteArray `maxItems` is /// flipped (the attack); when false the original contract is left in /// place (the control). - async fn run_contest_then_resolve(widen: bool) -> Result<(), crate::error::Error> { + async fn run_contest_then_resolve( + widen: bool, + platform_version: &'static PlatformVersion, + ) -> Result<(), crate::error::Error> { let mut platform = TestPlatformBuilder::new() - .with_latest_protocol_version() + .with_initial_protocol_version(platform_version.protocol_version) .build_with_mock_rpc() .set_initial_state_structure(); - let platform_version = PlatformVersion::latest(); - let mut rng = StdRng::seed_from_u64(0xB17E_A77A); // Two contenders, each prefunded so they can pay the contested-index @@ -3898,10 +3899,15 @@ pub(in crate::execution) mod tests { /// rejects the widening (see the rs-dpp validate_byte_array_encoding /// tests). This test deliberately writes the corrupt state directly to /// grovedb (bypassing validation) to reproduce the consequence the - /// validation fix prevents. + /// validation fix prevents. Protocol version 14 (`check_for_ended_vote_polls` + /// 1); from protocol version 15 the contest ends with no winner instead. #[tokio::test] async fn widening_byte_array_max_items_halts_vote_poll_resolver() { - let result = run_contest_then_resolve(true).await; + let result = run_contest_then_resolve( + true, + PlatformVersion::get(14).expect("expected protocol version 14"), + ) + .await; assert!( result.is_err(), @@ -3929,7 +3935,7 @@ pub(in crate::execution) mod tests { /// only difference between the two runs is the `maxItems` flip. #[tokio::test] async fn contest_without_widening_resolves_successfully() { - let result = run_contest_then_resolve(false).await; + let result = run_contest_then_resolve(false, PlatformVersion::latest()).await; assert!( result.is_ok(), @@ -3938,6 +3944,19 @@ pub(in crate::execution) mod tests { result ); } + + /// From protocol version 15 a contender whose document does not decode cannot + /// win: with no contender left the contest ends with no winner. + #[tokio::test] + async fn should_end_the_contest_when_no_contender_decodes_at_the_latest_protocol_version() { + let result = run_contest_then_resolve(true, PlatformVersion::latest()).await; + + assert!( + result.is_ok(), + "the contest must end with the block; got {:?}", + result + ); + } } /// End-to-end regression test for the contested-index cross-check. diff --git a/packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-summed-integer.json b/packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-summed-integer.json new file mode 100644 index 00000000000..4ffe892383d --- /dev/null +++ b/packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-summed-integer.json @@ -0,0 +1,179 @@ +{ + "$formatVersion": "0", + "id": "DWBXe9EXFPHxvbArQgT45uQR5gMmi8dfMpLhR5KSbwnZ", + "ownerId": "2QjL594djCH2NyDsn45vd6yQjEDHupMKo7CEGVTHtQxU", + "version": 1, + "documentSchemas": { + "domain": { + "documentsSummable": "rank", + "documentsMutable": false, + "canBeDeleted": true, + "transferable": 1, + "tradeMode": 1, + "type": "object", + "indices": [ + { + "name": "parentNameAndLabel", + "properties": [ + { + "normalizedParentDomainName": "asc" + }, + { + "normalizedLabel": "asc" + }, + { + "rank": "asc" + } + ], + "unique": true, + "contested": { + "fieldMatches": [ + { + "field": "normalizedLabel", + "regexPattern": "^[a-zA-Z01]{3,19}$" + } + ], + "resolution": 0, + "description": "If the normalized label part of this index is less than 20 characters (all alphabet a-z and 0 and 1) then this index is non unique while contest resolution takes place." + } + }, + { + "name": "identityId", + "nullSearchable": false, + "properties": [ + { + "records.identity": "asc" + } + ] + } + ], + "properties": { + "label": { + "type": "string", + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]$", + "minLength": 3, + "maxLength": 63, + "position": 0, + "description": "Domain label. e.g. 'Bob'." + }, + "normalizedLabel": { + "type": "string", + "pattern": "^[a-hj-km-np-z0-9][a-hj-km-np-z0-9-]{0,61}[a-hj-km-np-z0-9]$", + "maxLength": 63, + "position": 1, + "description": "Domain label converted to lowercase for case-insensitive uniqueness validation. \"o\", \"i\" and \"l\" replaced with \"0\" and \"1\" to mitigate homograph attack. e.g. 'b0b'", + "$comment": "Must be equal to the label in lowercase. \"o\", \"i\" and \"l\" must be replaced with \"0\" and \"1\"." + }, + "parentDomainName": { + "type": "string", + "pattern": "^$|^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]$", + "minLength": 0, + "maxLength": 63, + "position": 2, + "description": "A full parent domain name. e.g. 'dash'." + }, + "normalizedParentDomainName": { + "type": "string", + "pattern": "^$|^[a-hj-km-np-z0-9][a-hj-km-np-z0-9-\\.]{0,61}[a-hj-km-np-z0-9]$", + "minLength": 0, + "maxLength": 63, + "position": 3, + "description": "A parent domain name in lowercase for case-insensitive uniqueness validation. \"o\", \"i\" and \"l\" replaced with \"0\" and \"1\" to mitigate homograph attack. e.g. 'dash'", + "$comment": "Must either be equal to an existing domain or empty to create a top level domain. \"o\", \"i\" and \"l\" must be replaced with \"0\" and \"1\". Only the data contract owner can create top level domains." + }, + "preorderSalt": { + "type": "array", + "byteArray": true, + "minItems": 32, + "maxItems": 32, + "position": 4, + "description": "Salt used in the preorder document" + }, + "records": { + "type": "object", + "properties": { + "identity": { + "type": "array", + "byteArray": true, + "minItems": 32, + "maxItems": 32, + "position": 1, + "contentMediaType": "application/x.dash.dpp.identifier", + "description": "Identifier name record that refers to an Identity" + } + }, + "minProperties": 1, + "position": 5, + "additionalProperties": false + }, + "subdomainRules": { + "type": "object", + "properties": { + "allowSubdomains": { + "type": "boolean", + "description": "This option defines who can create subdomains: true - anyone; false - only the domain owner", + "$comment": "Only the domain owner is allowed to create subdomains for non top-level domains", + "position": 0 + } + }, + "position": 6, + "description": "Subdomain rules allow domain owners to define rules for subdomains", + "additionalProperties": false, + "required": [ + "allowSubdomains" + ] + }, + "rank": { + "type": "integer", + "position": 7, + "description": "An integer that is part of the contested index, summed over the domains." + } + }, + "required": [ + "$createdAt", + "$updatedAt", + "$transferredAt", + "label", + "normalizedLabel", + "normalizedParentDomainName", + "preorderSalt", + "records", + "subdomainRules", + "rank" + ], + "additionalProperties": false, + "$comment": "In order to register a domain you need to create a preorder. The preorder step is needed to prevent man-in-the-middle attacks. normalizedLabel + '.' + normalizedParentDomain must not be longer than 253 chars length as defined by RFC 1035. Domain documents are immutable: modification and deletion are restricted" + }, + "preorder": { + "documentsMutable": false, + "canBeDeleted": true, + "type": "object", + "indices": [ + { + "name": "saltedHash", + "properties": [ + { + "saltedDomainHash": "asc" + } + ], + "unique": true + } + ], + "properties": { + "saltedDomainHash": { + "type": "array", + "byteArray": true, + "minItems": 32, + "maxItems": 32, + "position": 0, + "description": "Double sha-256 of the concatenation of a 32 byte random salt and a normalized domain name" + } + }, + "required": [ + "saltedDomainHash" + ], + "additionalProperties": false, + "$comment": "Preorder documents are immutable: modification and deletion are restricted" + } + } +} diff --git a/packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/mod.rs b/packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/mod.rs index 989cf7f4a62..9f605ef87ed 100644 --- a/packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/mod.rs +++ b/packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/mod.rs @@ -1,5 +1,6 @@ mod v0; mod v1; +mod v2; use crate::drive::Drive; use std::collections::BTreeMap; @@ -52,9 +53,16 @@ impl Drive { transaction, platform_version, ), + 2 => self.remove_contested_resource_vote_poll_documents_operations_v2( + vote_polls, + clean_up_testnet_corrupted_reference_issue, + batch_operations, + transaction, + platform_version, + ), version => Err(Error::Drive(DriveError::UnknownVersionMismatch { method: "remove_contested_resource_vote_poll_documents_operations".to_string(), - known_versions: vec![0, 1], + known_versions: vec![0, 1, 2], received: version, })), } diff --git a/packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/v1/mod.rs b/packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/v1/mod.rs index f2bb58bf7e5..c5ffbd0acef 100644 --- a/packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/v1/mod.rs +++ b/packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/v1/mod.rs @@ -79,25 +79,45 @@ impl Drive { } // We also need to delete all the references + self.remove_contested_resource_vote_poll_contender_references_operations_v1( + vote_poll, + vote_choices, + batch_operations, + transaction, + platform_version, + )?; + } - for resource_vote_choice in vote_choices.keys() { - if matches!(resource_vote_choice, ResourceVoteChoice::TowardsIdentity(_)) { - let contender_path = - vote_poll.contender_path(resource_vote_choice, platform_version)?; - self.batch_delete( - contender_path.as_slice().into(), - vec![0].as_slice(), - BatchDeleteApplyType::StatefulBatchDelete { - is_known_to_be_subtree_with_sum: Some(MaybeTree::NotTree), - }, - transaction, - batch_operations, - &platform_version.drive, - )?; - } + Ok(()) + } + + /// Deletes the reference each contender of a contest holds to its document. Moved here + /// unchanged from the body above, which protocol versions 2 to 14 select, so that version 2 + /// shares it: the same operations in the same order. + pub(in crate::drive::votes) fn remove_contested_resource_vote_poll_contender_references_operations_v1( + &self, + vote_poll: &ContestedDocumentResourceVotePollWithContractInfo, + vote_choices: &BTreeMap>, + batch_operations: &mut Vec, + transaction: TransactionArg, + platform_version: &PlatformVersion, + ) -> Result<(), Error> { + for resource_vote_choice in vote_choices.keys() { + if matches!(resource_vote_choice, ResourceVoteChoice::TowardsIdentity(_)) { + let contender_path = + vote_poll.contender_path(resource_vote_choice, platform_version)?; + self.batch_delete( + contender_path.as_slice().into(), + vec![0].as_slice(), + BatchDeleteApplyType::StatefulBatchDelete { + is_known_to_be_subtree_with_sum: Some(MaybeTree::NotTree), + }, + transaction, + batch_operations, + &platform_version.drive, + )?; } } - Ok(()) } } diff --git a/packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/v2/mod.rs b/packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/v2/mod.rs new file mode 100644 index 00000000000..4eb75fbbd1c --- /dev/null +++ b/packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/v2/mod.rs @@ -0,0 +1,99 @@ +use crate::drive::votes::paths::VotePollPaths; +use crate::drive::votes::resolved::vote_polls::contested_document_resource_vote_poll::ContestedDocumentResourceVotePollWithContractInfo; +use crate::drive::Drive; +use crate::error::drive::DriveError; +use crate::error::Error; +use crate::fees::op::LowLevelDriveOperation; +use crate::util::grove_operations::{BatchDeleteApplyType, DirectQueryType}; +use dpp::identifier::Identifier; +use dpp::identity::TimestampMillis; +use dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use grovedb::element::reference_path::ReferencePathType::UpstreamRootHeightReference; +use grovedb::{Element, MaybeTree, TransactionArg}; +use platform_version::version::PlatformVersion; +use std::collections::BTreeMap; + +impl Drive { + /// Removes the documents and references of ended contests as version 1 does, except that a + /// contender's document is found by the id its reference names, where version 1 decoded + /// every contender's document to read its id and failed on one that does not decode. + /// It reads the contenders among `vote_choices`, the ones the tally returned, and version 1 + /// queried all of them: the same contenders from protocol version 14 on, where a contest + /// accepts fewer (`max_contenders_per_contest`) than the tally reads + /// (`maximum_contenders_to_consider`). Selected from protocol version 15. + // TODO: Use type of struct + #[allow(clippy::type_complexity)] + pub(in crate::drive::votes) fn remove_contested_resource_vote_poll_documents_operations_v2( + &self, + vote_polls: &[( + &ContestedDocumentResourceVotePollWithContractInfo, + &TimestampMillis, + &BTreeMap>, + )], + clean_up_testnet_corrupted_reference_issue: bool, + batch_operations: &mut Vec, + transaction: TransactionArg, + platform_version: &PlatformVersion, + ) -> Result<(), Error> { + for (vote_poll, _, vote_choices) in vote_polls { + if !clean_up_testnet_corrupted_reference_issue { + // if we are in clean up we keep all documents + let documents_storage_path = vote_poll.documents_storage_path_vec(); + for resource_vote_choice in vote_choices.keys() { + if !matches!(resource_vote_choice, ResourceVoteChoice::TowardsIdentity(_)) { + continue; + } + let contender_path = + vote_poll.contender_path(resource_vote_choice, platform_version)?; + // A contender references its document in the contest's document storage + // (`make_document_contested_reference`): the reference's last segment is + // the document's id + let Some(reference) = self.grove_get_raw_optional( + contender_path.as_slice().into(), + &[0], + DirectQueryType::StatefulDirectQuery, + transaction, + &mut vec![], + &platform_version.drive, + )? + else { + continue; + }; + let Element::Reference(UpstreamRootHeightReference(_, reference_path), ..) = + reference + else { + return Err(Error::Drive(DriveError::CorruptedDriveState( + "a contender must reference its document".to_string(), + ))); + }; + let document_id = reference_path.last().ok_or(Error::Drive( + DriveError::CorruptedDriveState( + "a contender's reference must name its document".to_string(), + ), + ))?; + self.batch_delete( + documents_storage_path.as_slice().into(), + document_id.as_slice(), + BatchDeleteApplyType::StatefulBatchDelete { + is_known_to_be_subtree_with_sum: Some(MaybeTree::NotTree), + }, + transaction, + batch_operations, + &platform_version.drive, + )?; + } + } + + // We also need to delete all the references + self.remove_contested_resource_vote_poll_contender_references_operations_v1( + vote_poll, + vote_choices, + batch_operations, + transaction, + platform_version, + )?; + } + + Ok(()) + } +} diff --git a/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_method_versions/v11.rs b/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_method_versions/v11.rs index 8df09f6713c..ae5ee3ac986 100644 --- a/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_method_versions/v11.rs +++ b/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_method_versions/v11.rs @@ -101,8 +101,11 @@ const DKG_MINING_SCHEDULES_V1: &[DkgMiningSchedule] = &[ /// `update_core_info` does not ask Core again once it is recorded (the masternode list's /// operator key normalization reads the record too, as described below); in the asset unlocks /// it emits for withdrawals, described below; in the voter key of a masternode that returns to a -/// voting address, described below; in the consensus evidence policy; and in the chain lock -/// verification. The chain lock changes only work as a whole: +/// voting address, described below; in the end of a contest, `voting.check_for_ended_vote_polls` +/// being 2 rather than 1 (a contender whose document does not decode cannot win, and a winner +/// whose document the state refuses leaves the contest with no winner); in the consensus +/// evidence policy; and in the chain lock verification. The chain lock changes only work as a +/// whole: /// - `core_chain_lock.verify_chain_lock_locally` is 1 rather than 0: a chain lock is rejected /// locally only when Platform holds exactly the quorums active at its signing height, using /// Dash Core's DKG mining schedule in `core_chain_lock.dkg_mining_schedules`. When a quorum may @@ -164,6 +167,7 @@ pub const DRIVE_ABCI_METHOD_VERSIONS_V11: DriveAbciMethodVersions = DriveAbciMet ..DRIVE_ABCI_METHOD_VERSIONS_V10.core_based_updates }, voting: DriveAbciVotingMethodVersions { + check_for_ended_vote_polls: 2, // changed in v15: a contender whose document does not decode cannot win, and a winner whose document the state refuses leaves the contest with no winner tally_votes_for_yes_no_vote_poll: Some(0), keep_record_of_finished_yes_no_vote_poll: Some(0), clean_up_after_yes_no_vote_polls_end: Some(0), diff --git a/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v4.rs b/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v4.rs index 7675e0a8c6f..1a1a0e2ddc2 100644 --- a/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v4.rs +++ b/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v4.rs @@ -13,6 +13,9 @@ use crate::version::drive_versions::drive_vote_method_versions::{ /// * `remove_all_votes_given_by_identities` 1 also removes the yes/no votes of a masternode /// that left the list, and deletes a contested resource vote a reference points at while /// that vote is stored. +/// * `cleanup.remove_contested_resource_vote_poll_documents_operations` 2 finds each contender's +/// document of an ended contest by the id its reference names, where 1 decoded every +/// contender's document to read its id. /// * `cleanup.remove_vote_poll_end_date_query_operations` is `Some(0)`: the yes/no clean-up /// removes finished polls from the end date index with it (`None`, not active, before). /// * every `yes_no` method is `Some(0)`: yes/no polls can be opened and voted on from this @@ -36,6 +39,7 @@ pub const DRIVE_VOTE_METHOD_VERSIONS_V4: DriveVoteMethodVersions = DriveVoteMeth }, cleanup: DriveVoteCleanupMethodVersions { remove_all_votes_given_by_identities: 1, + remove_contested_resource_vote_poll_documents_operations: 2, remove_vote_poll_end_date_query_operations: Some(0), ..DRIVE_VOTE_METHOD_VERSIONS_V3.cleanup }, diff --git a/packages/rs-platform-version/src/version/v15.rs b/packages/rs-platform-version/src/version/v15.rs index 4407188f234..076e40c1c10 100644 --- a/packages/rs-platform-version/src/version/v15.rs +++ b/packages/rs-platform-version/src/version/v15.rs @@ -925,12 +925,31 @@ pub const PROTOCOL_VERSION_15: ProtocolVersion = 15; /// public key already refuse high-S. Protocol v14 and earlier keep /// `verify_hash_signature` 0, so the blocks committed under them replay with the same /// results. +/// +/// 44. **A contest ends whatever its contenders hold**: `check_for_ended_vote_polls` 2 +/// (`DRIVE_ABCI_METHOD_VERSIONS_V11`) ends a contest as generation 1 does, except that a +/// contender whose stored document does not decode with the contest's document type +/// cannot win: the winner is the earliest of the contenders that decode with the highest +/// tally among them, and the lock tally is compared with its tally. With none that decodes +/// the contest has no winner. When the state refuses the winner's document (a unique index +/// entry or the document's id already taken, or a sum it would take past its range), what +/// the award wrote is undone and the contest has no winner. A contest with no winner is +/// recorded and cleaned up like one with no contenders: its contenders' documents are +/// removed and its prefunded balance goes to the epoch's processing fees. The clean-up +/// finds a contender's document by the id its reference names +/// (`remove_contested_resource_vote_poll_documents_operations` 2, +/// `DRIVE_VOTE_METHOD_VERSIONS_V4`), where 1 decoded every contender's document to read +/// its id; it reads the contenders the tally returned, which from protocol v14 are all of +/// them (`max_contenders_per_contest` is below `maximum_contenders_to_consider`). +/// Generation 1 of `check_for_ended_vote_polls` returns an error for an undecodable +/// contender or a refused award, and clean-up 1 for an undecodable contender. Protocol +/// v14 keeps both generations 1. pub const PLATFORM_V15: PlatformVersion = PlatformVersion { protocol_version: PROTOCOL_VERSION_15, - drive: DRIVE_VERSION_V10, // changed: calculate_fee 1 prices a refund at the storing epoch's rate (note 27); apply_contract_with_serialization 1 writes nothing for a contract whose format version 1 bytes match the stored one's (note 8); vote method versions v4: register_identity_vote 1 registers a yes/no vote, remove_all_votes_given_by_identities 1 also removes the yes/no votes of a masternode that left the list, every yes_no method and remove_vote_poll_end_date_query_operations Some(0) make yes/no polls active, add_vote_poll_end_date_query_operations 1 adds only the entry when the batch already queues the end date's tree with other storage flags, and verify methods v4 make the yes/no proof verifiers active (note 10) and verify_private_document_entries Some(0) a page of a private type's store (note 13); state transition method versions v5: document_create_transition 1 deletes a consumed document from what its lookup read (note 11); document method versions v5: insert_empty_private_document_store_operation Some(0) creates a private document type's store, and fetch_private_document_entries and prove_private_document_entries Some(0) read and prove a page of it (note 13); apply_drive_operations 2 resolves a batch's estimate, remove_reference_for_index_level_for_contract_operations 2, add_reference_for_index_level_for_contract_operations 1, stateless_delete_of_non_tree_for_costs 1 and for_total_system_credits_update 1 describe their layers as they are (note 14); fetch_core_fork_activation_height and store_core_fork_activation_height Some(0) keep the Core fork activations (note 18); document method versions v5: append_private_document_entries_operations Some(0) appends a private document create's entries (note 25); grove_version GROVE_V5 (note 26); verify methods v4: verify_proof_keep_serialized 1 verifies a document that may be contested (note 29); document method versions v5: single_document_path_query 1 selects the latest retained revision at or before a block time, and verify_proof_keep_serialized 1 verifies it (note 31); retained-history writers, readers, estimates and verifiers select the per-type revision layout (note 35); add_new_keys_to_masternode_identity 1 adds a masternode key whose hash the identity already holds a reference for (note 32); document method versions v5: insert.add_document_for_contract_operations 2, delete.delete_document_for_contract_operations 1, delete.remove_document_from_primary_storage 1 and its estimate 1, query.fetch_document_lifecycle Some(0), and the erase/lifecycle estimate and erase_refund_recipient_cost selectors Some(0); batch_operations.convert_drive_operations_to_grove_operations 2; state transition method versions v5: document_delete_transition 1 and document_erase_transition Some(0); verify methods v4: single_document.verify_proof 1 extend retained history (note 41); document method versions v5: add_indices_for_top_index_level_for_contract_operations 3 writes no entry in an expired time range bucket (note 36) + drive: DRIVE_VERSION_V10, // changed: calculate_fee 1 prices a refund at the storing epoch's rate (note 27); apply_contract_with_serialization 1 writes nothing for a contract whose format version 1 bytes match the stored one's (note 8); vote method versions v4: register_identity_vote 1 registers a yes/no vote, remove_all_votes_given_by_identities 1 also removes the yes/no votes of a masternode that left the list, every yes_no method and remove_vote_poll_end_date_query_operations Some(0) make yes/no polls active, add_vote_poll_end_date_query_operations 1 adds only the entry when the batch already queues the end date's tree with other storage flags, and verify methods v4 make the yes/no proof verifiers active (note 10) and verify_private_document_entries Some(0) a page of a private type's store (note 13); state transition method versions v5: document_create_transition 1 deletes a consumed document from what its lookup read (note 11); document method versions v5: insert_empty_private_document_store_operation Some(0) creates a private document type's store, and fetch_private_document_entries and prove_private_document_entries Some(0) read and prove a page of it (note 13); apply_drive_operations 2 resolves a batch's estimate, remove_reference_for_index_level_for_contract_operations 2, add_reference_for_index_level_for_contract_operations 1, stateless_delete_of_non_tree_for_costs 1 and for_total_system_credits_update 1 describe their layers as they are (note 14); fetch_core_fork_activation_height and store_core_fork_activation_height Some(0) keep the Core fork activations (note 18); document method versions v5: append_private_document_entries_operations Some(0) appends a private document create's entries (note 25); grove_version GROVE_V5 (note 26); verify methods v4: verify_proof_keep_serialized 1 verifies a document that may be contested (note 29); document method versions v5: single_document_path_query 1 selects the latest retained revision at or before a block time, and verify_proof_keep_serialized 1 verifies it (note 31); retained-history writers, readers, estimates and verifiers select the per-type revision layout (note 35); add_new_keys_to_masternode_identity 1 adds a masternode key whose hash the identity already holds a reference for (note 32); document method versions v5: insert.add_document_for_contract_operations 2, delete.delete_document_for_contract_operations 1, delete.remove_document_from_primary_storage 1 and its estimate 1, query.fetch_document_lifecycle Some(0), and the erase/lifecycle estimate and erase_refund_recipient_cost selectors Some(0); batch_operations.convert_drive_operations_to_grove_operations 2; state transition method versions v5: document_delete_transition 1 and document_erase_transition Some(0); verify methods v4: single_document.verify_proof 1 extend retained history (note 41); document method versions v5: add_indices_for_top_index_level_for_contract_operations 3 writes no entry in an expired time range bucket (note 36); vote method versions v4: remove_contested_resource_vote_poll_documents_operations 2 finds a contender's document by its reference (note 44) drive_abci: DriveAbciVersion { structs: DRIVE_ABCI_STRUCTURE_VERSIONS_V2, - methods: DRIVE_ABCI_METHOD_VERSIONS_V11, // changed: perform_events_on_first_block_of_protocol_change 3 migrates retained history after operator-payout reconciliation and other activation work (note 35); the yes/no poll's tally, record, clean-up and finish hook are Some(0) (note 10); verify_chain_lock_locally 1 rejects a chain lock locally only when Platform holds the quorums active at its signing height, and verify_chain_lock_through_core 1 has Core's verifychainlock check the others before submitchainlock; consensus_params_update 2 installs the full evidence policy (note 16); update_core_info 1 records the chain locked height at which Core's V24 is first seen active (note 18); build_untied_withdrawal_transactions_from_documents 1 emits asset unlock payload version 2 once V24 is recorded as active (note 20); update_voter_identity 1 re-enables the voter key of the address a masternode returns to (note 22); update_masternode_list 2 and update_operator_identity 1 make operator payouts and the operator identities' TRANSFER keys follow Core's diffs (note 32) + methods: DRIVE_ABCI_METHOD_VERSIONS_V11, // changed: perform_events_on_first_block_of_protocol_change 3 migrates retained history after operator-payout reconciliation and other activation work (note 35); the yes/no poll's tally, record, clean-up and finish hook are Some(0) (note 10); verify_chain_lock_locally 1 rejects a chain lock locally only when Platform holds the quorums active at its signing height, and verify_chain_lock_through_core 1 has Core's verifychainlock check the others before submitchainlock; consensus_params_update 2 installs the full evidence policy (note 16); update_core_info 1 records the chain locked height at which Core's V24 is first seen active (note 18); build_untied_withdrawal_transactions_from_documents 1 emits asset unlock payload version 2 once V24 is recorded as active (note 20); update_voter_identity 1 re-enables the voter key of the address a masternode returns to (note 22); update_masternode_list 2 and update_operator_identity 1 make operator payouts and the operator identities' TRANSFER keys follow Core's diffs (note 32); check_for_ended_vote_polls 2 ends a contest whose contender does not decode or whose award the state refuses (note 44) validation_and_processing: DRIVE_ABCI_VALIDATION_VERSIONS_V11, // changed: identity update advanced_structure 1 refuses unpaid an identity update whose added key's proof of possession does not verify (note 2); create_domain_data_trigger 2 (note 3); contract update transform_into_action 1 holds an update to the compiled size cap in check_tx (note 8); batch advanced_structure 2 refuses a token config update on a read-only contract (note 9); masternode vote transform_into_action 1 looks up a masternode's previous answer on a yes/no poll (note 10); document_reference_validation 1 keeps what a consumed commitment's lookup read (note 11); document create structure_validation 2 holds a decision proposal to its fund, rule and end date (note 12); data trigger bindings 3 drop the DashPay bindings (note 24); document create state_validation 3 keeps a create outside a contest off the values of a live one its index values do not decide (note 19); identity create basic_structure 1 checks the identity id before the asset lock proof and advanced_structure 2 no longer does (note 23); contract user moderation transform_into_action 1 writes a moderator's field change in the name of whoever holds the document's storage (note 28); validate_state_transition_identity_signed 2 refuses a contract create or update signed by a key with a budget or an expiry (note 34); batch_state_transition.document_delete_transition_structure_validation 2 and document_erase_transition_structure_validation/document_erase_transition_state_validation Some(0) admit the lifecycle (note 41) withdrawal_constants: DRIVE_ABCI_WITHDRAWAL_CONSTANTS_V3, query: DRIVE_ABCI_QUERY_VERSIONS_V3, // changed: getDocumentHistory accepts V1 only From e1b161d86f91ff7d2644973508a478a4d93984b5 Mon Sep 17 00:00:00 2001 From: QuantumExplorer Date: Mon, 16 Nov 2026 22:03:11 +0700 Subject: [PATCH 2/4] test(platform): two contests ending in one block, one award refused Adds tests that end two contests in the same block with one award refused, in both orders, and checks the other award is kept and both contests are cleaned up. When undoing a refused award fails, the award's error is logged with the rollback's. Documents why the clean-up skips a contender with no reference. Co-Authored-By: Claude Opus 5.5 --- .../check_for_ended_vote_polls/v2/mod.rs | 15 ++- .../contest_resolution_tests.rs | 123 ++++++++++++++++++ .../v2/mod.rs | 3 + 3 files changed, 137 insertions(+), 4 deletions(-) diff --git a/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v2/mod.rs b/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v2/mod.rs index 7431696f5f7..09c77ec7555 100644 --- a/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v2/mod.rs +++ b/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v2/mod.rs @@ -113,10 +113,17 @@ where )), Err(error) if award_was_refused(&error) => { if let Some(transaction) = transaction { - transaction - .rollback_to_savepoint() - .map_err(GroveError::StorageError) - .map_err(|error| Error::Drive(DriveCrateError::GroveDB(Box::new(error))))?; + if let Err(rollback_error) = transaction.rollback_to_savepoint() { + // Only the rollback's error is returned: log the award's error with it + tracing::error!( + ?error, + ?rollback_error, + "could not undo a contest award the state refused" + ); + return Err(Error::Drive(DriveCrateError::GroveDB(Box::new( + GroveError::StorageError(rollback_error), + )))); + } } Ok(ContestedDocumentVotePollWinnerInfo::NoWinner) } diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_resolution_tests.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_resolution_tests.rs index 87ec9bf09a3..86eff36314f 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_resolution_tests.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_resolution_tests.rs @@ -73,6 +73,16 @@ fn end_first_due_vote_polls( .keys() .next() .expect("expected a vote poll end date"); + end_vote_polls_due_at(platform, time_ms, platform_version) +} + +/// Runs the ended vote poll check of a block at `time_ms`, which ends every vote poll due by +/// then, and returns its result, committing the block when it succeeds +fn end_vote_polls_due_at( + platform: &TempPlatform, + time_ms: TimestampMillis, + platform_version: &PlatformVersion, +) -> Result<(), Error> { fast_forward_to_block(platform, time_ms, 900, 42, 0, false); let platform_state = platform.state.load(); let transaction = platform.drive.grove.start_transaction(); @@ -581,6 +591,119 @@ async fn should_end_a_contest_with_no_winner_when_its_unique_index_entry_is_take assert_contest_cleaned_up(&platform, &dpns_contract, "quantum", platform_version); } +/// Opens a DPNS name contest on "quantum", then one on "coolio" that ends later, takes the +/// unique index entry of the contest at `refused` (0 or 1, in the order they end), and ends +/// both in one block at the latest protocol version. The award of that contest is refused, and +/// the other contest's award must be kept whichever of the two the block ends first. +async fn end_two_contests_in_one_block_with_one_award_refused(refused: usize) { + let platform_version = PlatformVersion::latest(); + let mut platform = TestPlatformBuilder::new() + .with_initial_protocol_version(platform_version.protocol_version) + .build_with_mock_rpc() + .set_genesis_state(); + let platform_state = platform.state.load(); + let (_, _, dpns_contract) = create_dpns_identity_name_contest( + &mut platform, + &platform_state, + 7, + "quantum", + platform_version, + ) + .await; + fast_forward_to_block(&platform, 500_000, 100, 42, 0, false); + let platform_state = platform.state.load(); + create_dpns_identity_name_contest( + &mut platform, + &platform_state, + 8, + "coolio", + platform_version, + ) + .await; + let names = ["quantum", "coolio"]; + let end_dates = vote_poll_end_dates(&platform.drive, platform_version); + assert_eq!( + end_dates.len(), + 2, + "expected the contests to end at two dates" + ); + let last_end_date = *end_dates + .keys() + .next_back() + .expect("expected a vote poll end date"); + + let (_, template) = + contender_documents(&platform, &dpns_contract, names[refused], platform_version).remove(0); + let holder = other_domain_like(&template, 0x51); + insert_domain_directly(&platform, &dpns_contract, &holder, platform_version); + let contenders = names.map(|name| { + contender_documents(&platform, &dpns_contract, name, platform_version) + .into_iter() + .map(|(contender, _)| contender) + .collect::>() + }); + + end_vote_polls_due_at(&platform, last_end_date, platform_version) + .expect("expected both contests to end with the block"); + + for (index, name) in names.into_iter().enumerate() { + if index == refused { + assert_ended_with_no_winner( + &platform, + &dpns_name_vote_poll(&dpns_contract, name), + platform_version, + ); + for contender in &contenders[index] { + assert!( + awarded_domains(&platform, &dpns_contract, *contender, platform_version) + .is_empty(), + "no contender of the refused contest may be awarded" + ); + } + } else { + let finished = finished_vote_info(&platform, &dpns_contract, name, platform_version) + .expect("expected the other contest to be finished"); + assert_eq!( + finished.finished_vote_outcome, + FinishedVoteOutcome::TowardsIdentity as i32 + ); + let winner = Identifier::from_bytes( + &finished + .won_by_identity_id + .expect("expected the other contest to have a winner"), + ) + .expect("expected the winner's id"); + assert!(contenders[index].contains(&winner)); + assert_eq!( + awarded_domains(&platform, &dpns_contract, winner, platform_version).len(), + 1, + "the other contest's winner must keep its award" + ); + } + assert_contest_cleaned_up(&platform, &dpns_contract, name, platform_version); + } + assert_eq!( + awarded_domains( + &platform, + &dpns_contract, + holder.owner_id(), + platform_version + ), + vec![holder], + "the document holding the entry must stay as it was" + ); +} + +#[tokio::test] +async fn should_keep_an_earlier_award_of_the_block_when_a_later_award_is_refused() { + end_two_contests_in_one_block_with_one_award_refused(1).await; +} + +#[tokio::test] +async fn should_keep_a_later_award_of_the_block_when_an_earlier_award_is_refused() { + end_two_contests_in_one_block_with_one_award_refused(0).await; +} + #[tokio::test] async fn should_fail_on_a_taken_unique_index_entry_at_protocol_version_14() { let platform_version = protocol_version_14(); diff --git a/packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/v2/mod.rs b/packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/v2/mod.rs index 4eb75fbbd1c..cda35e7cd41 100644 --- a/packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/v2/mod.rs +++ b/packages/rs-drive/src/drive/votes/cleanup/remove_contested_resource_vote_poll_documents_operations/v2/mod.rs @@ -57,6 +57,9 @@ impl Drive { &platform_version.drive, )? else { + // With no reference there is no document id to delete: the clean-up + // goes on with the other contenders, as version 1 removed only the + // documents its query found continue; }; let Element::Reference(UpstreamRootHeightReference(_, reference_path), ..) = From ff5f620362d117473bee2d2067e3f9e5bb27817d Mon Sep 17 00:00:00 2001 From: QuantumExplorer Date: Tue, 17 Nov 2026 01:13:54 +0700 Subject: [PATCH 3/4] fix(platform): refuse a contest award only on its own conflicts A taken unique index value is now found before the award writes, by the uniqueness check document creation runs, and the contest then ends with no winner. The errors that end a contest with no winner after the award wrote are narrowed to the document's id already taken and merk's sum tree overflow; any other index or overflow error is returned as before. Co-Authored-By: Claude Opus 5.5 --- .../check_for_ended_vote_polls/v2/mod.rs | 47 ++++++++++++++----- .../rs-platform-version/src/version/v15.rs | 7 +-- 2 files changed, 38 insertions(+), 16 deletions(-) diff --git a/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v2/mod.rs b/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v2/mod.rs index 09c77ec7555..659c60bc2a7 100644 --- a/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v2/mod.rs +++ b/packages/rs-drive-abci/src/execution/platform_events/voting/check_for_ended_vote_polls/v2/mod.rs @@ -47,8 +47,10 @@ where /// cannot win. The winner is picked from the contenders that decode with the highest /// tally among them, the earliest of them on a tie, and the lock tally is compared with /// its tally. With none that decodes, the contest has no winner. - /// - When the state refuses the winner's document (see [`award_was_refused`]), what the - /// award wrote is undone and the contest has no winner. + /// - When another document already holds a value of one of the winner's document's unique + /// indexes, the contest has no winner and nothing is written. When the state refuses the + /// winner's document as the award writes it (see [`award_was_refused`]), what the award + /// wrote is undone and the contest has no winner. /// /// A contest with no winner is recorded and cleaned up like one with no contenders: its /// contenders' documents are removed and its prefunded balance goes to the epoch's @@ -93,6 +95,23 @@ where return Ok(ContestedDocumentVotePollWinnerInfo::Locked); } let contender_id = top_contender.identity_id; + // A value of one of the document's unique indexes already held by another document + // refuses the award before it writes, by the check a document creation runs. The + // document is checked as stored: its owner is the identity it is awarded to. + if !self + .drive + .validate_moderated_document_uniqueness( + vote_poll.contract.as_ref(), + document_type, + &top_contender.document, + None, + transaction, + platform_version, + )? + .is_valid() + { + return Ok(ContestedDocumentVotePollWinnerInfo::NoWinner); + } // The award writes in one or more batches: a refusal in a later one would keep what // the earlier ones wrote, so the award is undone to a savepoint. A savepoint left after // an award that went through is inert: the block's transaction is committed or dropped @@ -133,19 +152,21 @@ where } /// Whether the state refused the document awarded to a contest's winner, for what the state -/// already holds or what the document adds to it: a unique index entry or the document's id -/// already taken, or a sum the document would take past its range. Each follows from the -/// state every node holds, so every node refuses the same award. Any other error, a storage -/// failure among them, is returned as before. +/// already holds or what the document adds to it: the document's id already taken, or a sum +/// tree aggregate the document would take past its integer's range. Merk raises the second as +/// its `Overflow` error when it computes the aggregates of the tree it commits; its other +/// `Overflow` errors come from cost estimation, which an applied write does not run. Each +/// follows from the state every node holds, so every node refuses the same award. Any other +/// error, a storage failure among them, is returned as before. fn award_was_refused(error: &Error) -> bool { match error { - Error::Drive(DriveCrateError::Drive( - DriveError::CorruptedContractIndexes(_) | DriveError::CorruptedDocumentAlreadyExists(_), - )) => true, - Error::Drive(DriveCrateError::GroveDB(error)) => matches!( - error.as_ref(), - GroveError::Overflow(_) | GroveError::MerkError(MerkError::Overflow(_)) - ), + Error::Drive(DriveCrateError::Drive(DriveError::CorruptedDocumentAlreadyExists(_))) => true, + Error::Drive(DriveCrateError::GroveDB(error)) => { + matches!( + error.as_ref(), + GroveError::MerkError(MerkError::Overflow(_)) + ) + } _ => false, } } diff --git a/packages/rs-platform-version/src/version/v15.rs b/packages/rs-platform-version/src/version/v15.rs index cf2b0f54064..f7a3593f5e1 100644 --- a/packages/rs-platform-version/src/version/v15.rs +++ b/packages/rs-platform-version/src/version/v15.rs @@ -940,9 +940,10 @@ pub const PROTOCOL_VERSION_15: ProtocolVersion = 15; /// contender whose stored document does not decode with the contest's document type /// cannot win: the winner is the earliest of the contenders that decode with the highest /// tally among them, and the lock tally is compared with its tally. With none that decodes -/// the contest has no winner. When the state refuses the winner's document (a unique index -/// entry or the document's id already taken, or a sum it would take past its range), what -/// the award wrote is undone and the contest has no winner. A contest with no winner is +/// the contest has no winner. When another document holds a value of one of the winner's +/// document's unique indexes, the check document creation runs refuses the award before it +/// writes; when the award finds the document's id taken or would take a sum past its range, +/// what it wrote is undone. Either way the contest has no winner. A contest with no winner is /// recorded and cleaned up like one with no contenders: its contenders' documents are /// removed and its prefunded balance goes to the epoch's processing fees. The clean-up /// finds a contender's document by the id its reference names From 94083229dcce6a670f4c48c4b8d7afe2d5062bc2 Mon Sep 17 00:00:00 2001 From: QuantumExplorer Date: Tue, 17 Nov 2026 01:33:08 +0700 Subject: [PATCH 4/4] test(platform): refuse the award itself in the two-contest tests The two-contest tests refused one award with a taken unique index value, which the uniqueness check now finds before the award writes. They now refuse it with a sum the award would take past its range, next to a contest awarded as usual, so the refusal comes from the award in both orders. The sum test's setup is split into helpers they share. Co-Authored-By: Claude Opus 5.5 --- .../contest_resolution_tests.rs | 322 ++++++++++-------- 1 file changed, 174 insertions(+), 148 deletions(-) diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_resolution_tests.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_resolution_tests.rs index 86eff36314f..bb1db418fa6 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_resolution_tests.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_resolution_tests.rs @@ -591,119 +591,6 @@ async fn should_end_a_contest_with_no_winner_when_its_unique_index_entry_is_take assert_contest_cleaned_up(&platform, &dpns_contract, "quantum", platform_version); } -/// Opens a DPNS name contest on "quantum", then one on "coolio" that ends later, takes the -/// unique index entry of the contest at `refused` (0 or 1, in the order they end), and ends -/// both in one block at the latest protocol version. The award of that contest is refused, and -/// the other contest's award must be kept whichever of the two the block ends first. -async fn end_two_contests_in_one_block_with_one_award_refused(refused: usize) { - let platform_version = PlatformVersion::latest(); - let mut platform = TestPlatformBuilder::new() - .with_initial_protocol_version(platform_version.protocol_version) - .build_with_mock_rpc() - .set_genesis_state(); - let platform_state = platform.state.load(); - let (_, _, dpns_contract) = create_dpns_identity_name_contest( - &mut platform, - &platform_state, - 7, - "quantum", - platform_version, - ) - .await; - fast_forward_to_block(&platform, 500_000, 100, 42, 0, false); - let platform_state = platform.state.load(); - create_dpns_identity_name_contest( - &mut platform, - &platform_state, - 8, - "coolio", - platform_version, - ) - .await; - let names = ["quantum", "coolio"]; - let end_dates = vote_poll_end_dates(&platform.drive, platform_version); - assert_eq!( - end_dates.len(), - 2, - "expected the contests to end at two dates" - ); - let last_end_date = *end_dates - .keys() - .next_back() - .expect("expected a vote poll end date"); - - let (_, template) = - contender_documents(&platform, &dpns_contract, names[refused], platform_version).remove(0); - let holder = other_domain_like(&template, 0x51); - insert_domain_directly(&platform, &dpns_contract, &holder, platform_version); - let contenders = names.map(|name| { - contender_documents(&platform, &dpns_contract, name, platform_version) - .into_iter() - .map(|(contender, _)| contender) - .collect::>() - }); - - end_vote_polls_due_at(&platform, last_end_date, platform_version) - .expect("expected both contests to end with the block"); - - for (index, name) in names.into_iter().enumerate() { - if index == refused { - assert_ended_with_no_winner( - &platform, - &dpns_name_vote_poll(&dpns_contract, name), - platform_version, - ); - for contender in &contenders[index] { - assert!( - awarded_domains(&platform, &dpns_contract, *contender, platform_version) - .is_empty(), - "no contender of the refused contest may be awarded" - ); - } - } else { - let finished = finished_vote_info(&platform, &dpns_contract, name, platform_version) - .expect("expected the other contest to be finished"); - assert_eq!( - finished.finished_vote_outcome, - FinishedVoteOutcome::TowardsIdentity as i32 - ); - let winner = Identifier::from_bytes( - &finished - .won_by_identity_id - .expect("expected the other contest to have a winner"), - ) - .expect("expected the winner's id"); - assert!(contenders[index].contains(&winner)); - assert_eq!( - awarded_domains(&platform, &dpns_contract, winner, platform_version).len(), - 1, - "the other contest's winner must keep its award" - ); - } - assert_contest_cleaned_up(&platform, &dpns_contract, name, platform_version); - } - assert_eq!( - awarded_domains( - &platform, - &dpns_contract, - holder.owner_id(), - platform_version - ), - vec![holder], - "the document holding the entry must stay as it was" - ); -} - -#[tokio::test] -async fn should_keep_an_earlier_award_of_the_block_when_a_later_award_is_refused() { - end_two_contests_in_one_block_with_one_award_refused(1).await; -} - -#[tokio::test] -async fn should_keep_a_later_award_of_the_block_when_an_earlier_award_is_refused() { - end_two_contests_in_one_block_with_one_award_refused(0).await; -} - #[tokio::test] async fn should_fail_on_a_taken_unique_index_entry_at_protocol_version_14() { let platform_version = protocol_version_14(); @@ -725,22 +612,16 @@ async fn should_fail_on_a_taken_unique_index_entry_at_protocol_version_14() { ); } -/// Opens a contest on `quantum` with `rank` 1 in [`SUMMED_RANK_CONTRACT`], after writing a -/// domain `big` whose `rank` is `i64::MAX`, then ends it at `platform_version` -async fn end_contest_over_a_full_sum( +/// A platform at `platform_version` with [`SUMMED_RANK_CONTRACT`] and a domain `big` whose +/// `rank` is `i64::MAX`, so a winner with a `rank` above 0 takes the sum past its range +fn platform_over_a_full_sum( platform_version: &PlatformVersion, -) -> ( - TempPlatform, - DataContract, - Identifier, - Result<(), Error>, -) { +) -> (TempPlatform, DataContract, StdRng) { let mut platform = TestPlatformBuilder::new() .with_initial_protocol_version(platform_version.protocol_version) .build_with_mock_rpc() .set_genesis_state(); let mut rng = StdRng::seed_from_u64(0x5011_0000); - let (identity, signer, key) = setup_identity(&mut platform, rng.gen(), dash_to_credits!(0.5)); let contract_owner = setup_identity(&mut platform, rng.gen(), dash_to_credits!(0.5)); let contract = setup_contract( &platform.drive, @@ -754,11 +635,40 @@ async fn end_contest_over_a_full_sum( let domain = contract .document_type_for_name("domain") .expect("expected a domain document type"); + let mut big = domain + .random_document_with_rng(&mut rng, platform_version) + .expect("expected a random domain document"); + big.set("parentDomainName", "dash".into()); + big.set("normalizedParentDomainName", "dash".into()); + big.set("subdomainRules.allowSubdomains", false.into()); + big.set("preorderSalt", rng.gen::<[u8; 32]>().into()); + big.set("label", "big".into()); + big.set("normalizedLabel", "big".into()); + big.set("rank", Value::I64(i64::MAX)); + let big = other_domain_like(&big, 0x61); + insert_domain_directly(&platform, &contract, &big, platform_version); + (platform, contract, rng) +} - let entropy = Bytes32::random_with_rng(&mut rng); +/// A new identity joins a contest on `label` with `rank` in [`SUMMED_RANK_CONTRACT`] in a block +/// at `time_ms`, opening it; returns the identity's id +async fn join_summed_rank_contest( + platform: &mut TempPlatform, + contract: &DataContract, + rng: &mut StdRng, + label: &str, + rank: i64, + time_ms: TimestampMillis, + platform_version: &PlatformVersion, +) -> Identifier { + let (identity, signer, key) = setup_identity(platform, rng.gen(), dash_to_credits!(0.5)); + let domain = contract + .document_type_for_name("domain") + .expect("expected a domain document type"); + let entropy = Bytes32::random_with_rng(rng); let mut document = domain .random_document_with_identifier_and_entropy( - &mut rng, + rng, identity.id(), entropy, DocumentFieldFillType::FillIfNotRequired, @@ -771,17 +681,9 @@ async fn end_contest_over_a_full_sum( document.set("records.identity", document.owner_id().into()); document.set("subdomainRules.allowSubdomains", false.into()); document.set("preorderSalt", rng.gen::<[u8; 32]>().into()); - - let mut big = document.clone(); - big.set("label", "big".into()); - big.set("normalizedLabel", "big".into()); - big.set("rank", Value::I64(i64::MAX)); - let big = other_domain_like(&big, 0x61); - insert_domain_directly(&platform, &contract, &big, platform_version); - - document.set("label", "quantum".into()); - document.set("normalizedLabel", "quantum".into()); - document.set("rank", Value::I64(1)); + document.set("label", label.into()); + document.set("normalizedLabel", label.into()); + document.set("rank", Value::I64(rank)); document .set_id_for_creation(domain, &entropy.0, 2, platform_version) .expect("expected to set the document id"); @@ -829,7 +731,7 @@ async fn end_contest_over_a_full_sum( .process_raw_state_transitions( &[serialized_transition], &platform_state, - &BlockInfo::default_with_time(5000), + &BlockInfo::default_with_time(time_ms), &transaction, platform_version, false, @@ -847,9 +749,50 @@ async fn end_contest_over_a_full_sum( StateTransitionExecutionResult::SuccessfulExecution { .. }, "the contender must join the contest" ); + identity.id() +} + +/// The contest on `label` with `rank` in [`SUMMED_RANK_CONTRACT`] +fn summed_rank_vote_poll( + contract: &DataContract, + label: &str, + rank: i64, +) -> ContestedDocumentResourceVotePoll { + ContestedDocumentResourceVotePoll { + contract_id: contract.id(), + document_type_name: "domain".to_string(), + index_name: "parentNameAndLabel".to_string(), + index_values: vec![ + Value::Text("dash".to_string()), + Value::Text(label.to_string()), + Value::I64(rank), + ], + } +} +/// Opens a contest on `quantum` with `rank` 1 over a full sum (see +/// [`platform_over_a_full_sum`]), then ends it at `platform_version` +async fn end_contest_over_a_full_sum( + platform_version: &PlatformVersion, +) -> ( + TempPlatform, + DataContract, + Identifier, + Result<(), Error>, +) { + let (mut platform, contract, mut rng) = platform_over_a_full_sum(platform_version); + let contender = join_summed_rank_contest( + &mut platform, + &contract, + &mut rng, + "quantum", + 1, + 5000, + platform_version, + ) + .await; let result = end_first_due_vote_polls(&platform, platform_version); - (platform, contract, identity.id(), result) + (platform, contract, contender, result) } #[tokio::test] @@ -866,16 +809,7 @@ async fn should_end_a_contest_with_no_winner_when_the_award_takes_a_sum_past_its assert!(vote_poll_end_dates(&platform.drive, platform_version).is_empty()); assert_ended_with_no_winner( &platform, - &ContestedDocumentResourceVotePoll { - contract_id: contract.id(), - document_type_name: "domain".to_string(), - index_name: "parentNameAndLabel".to_string(), - index_values: vec![ - Value::Text("dash".to_string()), - Value::Text("quantum".to_string()), - Value::I64(1), - ], - }, + &summed_rank_vote_poll(&contract, "quantum", 1), platform_version, ); } @@ -886,6 +820,98 @@ async fn should_fail_on_an_award_taking_a_sum_past_its_range_at_protocol_version assert_matches!(result, Err(Error::Drive(DriveCrateError::GroveDB(_)))); } +/// Opens a contest whose award takes the sum past its range (`quantum`, `rank` 1) and one +/// awarded as usual (`zebra`, `rank` 0), the one at `refused` (0 or 1) ending first, and ends +/// both in one block at the latest protocol version. The refused award goes through the award +/// itself, not the uniqueness check before it, and the other contest's award must be kept +/// whichever of the two the block ends first. +async fn end_two_contests_in_one_block_with_one_award_refused(refused: usize) { + let platform_version = PlatformVersion::latest(); + let (mut platform, contract, mut rng) = platform_over_a_full_sum(platform_version); + let refused_contest = ("quantum", 1); + let awarded_contest = ("zebra", 0); + let contests = if refused == 0 { + [refused_contest, awarded_contest] + } else { + [awarded_contest, refused_contest] + }; + let mut contenders = vec![]; + for ((label, rank), time_ms) in contests.into_iter().zip([5000, 500_000]) { + contenders.push( + join_summed_rank_contest( + &mut platform, + &contract, + &mut rng, + label, + rank, + time_ms, + platform_version, + ) + .await, + ); + } + let end_dates = vote_poll_end_dates(&platform.drive, platform_version); + assert_eq!( + end_dates.len(), + 2, + "expected the contests to end at two dates" + ); + let last_end_date = *end_dates + .keys() + .next_back() + .expect("expected a vote poll end date"); + + end_vote_polls_due_at(&platform, last_end_date, platform_version) + .expect("expected both contests to end with the block"); + + assert!(vote_poll_end_dates(&platform.drive, platform_version).is_empty()); + for (index, ((label, rank), contender)) in contests.into_iter().zip(contenders).enumerate() { + let vote_poll = summed_rank_vote_poll(&contract, label, rank); + if index == refused { + assert_ended_with_no_winner(&platform, &vote_poll, platform_version); + assert!( + awarded_domains(&platform, &contract, contender, platform_version).is_empty(), + "nothing of the refused award may stay in the state" + ); + } else { + assert_eq!( + stored_poll_status(&platform, &vote_poll, platform_version), + ( + ContestedDocumentVotePollStatus::Awarded(contender), + Some(900) + ) + ); + assert_eq!( + awarded_domains(&platform, &contract, contender, platform_version).len(), + 1, + "the other contest's winner must keep its award" + ); + } + let balance_id = vote_poll + .specialized_balance_id() + .expect("expected the prefunded balance id"); + let balance = platform + .drive + .fetch_prefunded_specialized_balance(balance_id.to_buffer(), None, platform_version) + .expect("expected to read the prefunded balance"); + assert_eq!( + balance.unwrap_or_default(), + 0, + "the contest's prefunded balance must be emptied" + ); + } +} + +#[tokio::test] +async fn should_keep_an_earlier_award_of_the_block_when_a_later_award_is_refused() { + end_two_contests_in_one_block_with_one_award_refused(1).await; +} + +#[tokio::test] +async fn should_keep_a_later_award_of_the_block_when_an_earlier_award_is_refused() { + end_two_contests_in_one_block_with_one_award_refused(0).await; +} + /// Ends the same contest, with votes for both contenders and the lock, at the latest protocol /// version with `check_for_ended_vote_polls` and /// `remove_contested_resource_vote_poll_documents_operations` at the given generations, and