From ffff719c95fc15795d0b49044ba903d4542faf0c Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Thu, 12 Nov 2026 14:48:42 +0700 Subject: [PATCH 1/3] fix(platform)!: one vote poll per contest for index values sent in different forms (PV15) A contest is stored at the path of its index keys, and its poll is named by an id hashed from its index values. From protocol version 15 a contested create writes every index value the one way its property's type keys it (`Index::extract_contested_values` 1), so the contenders of one contest name one poll: an integer in any integer form as the type's own integer, a date as a u64, an integer or a float of a float property as a float, bytes in any form as bytes, and "\0" as the empty string. Protocol version 14 keeps writing only identifiers one way. Removing the votes of a masternode that left the list (`remove_all_votes_given_by_identities` 1, protocol version 15) deletes a contested resource vote while it is stored at the path its reference names, once when two references point at it. Co-Authored-By: Claude Fable 5.2 --- book/src/data-model/contested-documents.md | 7 + .../index/extract_contested_values/mod.rs | 198 +++++++- .../index/extract_contested_values/v1/mod.rs | 99 ++++ .../contest_index_value_forms_tests.rs | 421 ++++++++++++++++++ .../state_transitions/masternode_vote/mod.rs | 3 + ...t-contested-unique-index-with-integer.json | 180 ++++++++ .../mod.rs | 3 - .../v1/mod.rs | 329 +++++++++++++- .../dpp_versions/dpp_contract_versions/v7.rs | 15 +- .../drive_vote_method_versions/v4.rs | 3 +- .../src/version/drive_versions/v10.rs | 3 +- .../rs-platform-version/src/version/v15.rs | 22 + 12 files changed, 1250 insertions(+), 33 deletions(-) create mode 100644 packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/v1/mod.rs create mode 100644 packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_index_value_forms_tests.rs create mode 100644 packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-integer.json diff --git a/book/src/data-model/contested-documents.md b/book/src/data-model/contested-documents.md index d9f10347eba..daec1d5210f 100644 --- a/book/src/data-model/contested-documents.md +++ b/book/src/data-model/contested-documents.md @@ -58,6 +58,13 @@ but a poll is hashed from its values, and that hash keys the contest's prefunded date: two contenders writing the same identifier two ways would otherwise split one contest into two polls. Before 14 the values are taken as given. +From protocol version 15 every index value is written one way, the way its property's type keys +it: an integer in any integer form as the type's own integer, a date as a `u64`, an integer or a +float of a float property as a float, bytes in any form as bytes, and `"\0"` as the empty string +it shares a key with. That is the value a query of the contest returns. A masternode vote names +its poll by the values it sends, unchanged, and is refused unless a prefunded balance is held +under that poll, so a voter sends the values as the contest query returns them. + ## Resolution 0: masternode vote The DPNS rule. The choices are a contender, abstain, or **lock**, which gives the value to nobody. diff --git a/packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/mod.rs b/packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/mod.rs index 381dc7e1cc8..bfef7300a5d 100644 --- a/packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/mod.rs @@ -1,4 +1,5 @@ mod v0; +mod v1; use crate::data_contract::document_type::property::DocumentProperty; use crate::data_contract::document_type::Index; @@ -18,6 +19,12 @@ impl Index { /// its own prefunded balance and end date. `document_properties` are the document type's /// flattened properties. Before 14 the values are taken as given. /// + /// From protocol version 15 the value of every property is written one way, the way its + /// type keys it: an integer as its type's own integer, an integer or a float of a float + /// property as a float, bytes in any form as bytes, `"\0"` as the empty string it shares + /// a key with. A contest is stored at the path of its index keys, so values with one key + /// are one contest, and they now name one poll. + /// /// # Parameters /// * `data`: the document's properties. /// * `document_properties`: the document type's flattened properties. @@ -40,9 +47,10 @@ impl Index { { None => Ok(self.extract_values(data)), Some(0) => Ok(self.extract_contested_values_v0(data, document_properties)), + Some(1) => Ok(self.extract_contested_values_v1(data, document_properties)), Some(version) => Err(ProtocolError::UnknownVersionMismatch { method: "Index::extract_contested_values".to_string(), - known_versions: vec![0], + known_versions: vec![0, 1], received: version, }), } @@ -70,9 +78,185 @@ mod tests { use super::*; use crate::data_contract::document_type::index::tests::make_index; use crate::data_contract::document_type::property::{ - ByteArrayPropertySizes, DocumentPropertyType, + ByteArrayPropertySizes, DocumentPropertyType, StringPropertySizes, }; + fn property(property_type: DocumentPropertyType) -> DocumentProperty { + DocumentProperty { + property_type, + required: true, + transient: false, + required_since: None, + distinct_from: None, + encrypted_for: None, + generated_from: None, + revealed_reference: None, + } + } + + /// The values a contest over one property of `property_type` names itself by, for a + /// document holding `value`. + fn contest_values( + property_type: &DocumentPropertyType, + value: &Value, + platform_version: &PlatformVersion, + ) -> Vec { + make_index("contested", vec![("value", true)], true) + .extract_contested_values( + &BTreeMap::from([("value".to_string(), value.clone())]), + &IndexMap::from([("value".to_string(), property(property_type.clone()))]), + platform_version, + ) + .expect("values") + } + + /// From protocol version 15 the forms of a value that share a key in the paths of a vote + /// poll are written one way, so they name one poll: the way a query of the contest decodes + /// that key, so a voter reading the contest names the same poll. Protocol version 14 takes + /// them as given, identifiers apart. + #[test] + fn should_write_contest_values_that_share_a_key_one_way_from_version_15() { + let integer_forms = || vec![Value::U8(5), Value::I16(5), Value::U64(5), Value::I128(5)]; + let bytes = ByteArrayPropertySizes { + min_size: None, + max_size: None, + }; + let string = StringPropertySizes { + min_length: None, + max_length: None, + max_bytes: None, + }; + let float_forms = { + let mut forms = integer_forms(); + forms.push(Value::Float(5.0)); + forms + }; + let cases: Vec<(DocumentPropertyType, Vec, Value)> = vec![ + (DocumentPropertyType::U128, integer_forms(), Value::U128(5)), + (DocumentPropertyType::I128, integer_forms(), Value::I128(5)), + (DocumentPropertyType::U64, integer_forms(), Value::U64(5)), + (DocumentPropertyType::I64, integer_forms(), Value::I64(5)), + (DocumentPropertyType::U32, integer_forms(), Value::U32(5)), + (DocumentPropertyType::I32, integer_forms(), Value::I32(5)), + (DocumentPropertyType::U16, integer_forms(), Value::U16(5)), + (DocumentPropertyType::I16, integer_forms(), Value::I16(5)), + (DocumentPropertyType::U8, integer_forms(), Value::U8(5)), + (DocumentPropertyType::I8, integer_forms(), Value::I8(5)), + (DocumentPropertyType::Date, integer_forms(), Value::U64(5)), + (DocumentPropertyType::F64, float_forms, Value::Float(5.0)), + ( + DocumentPropertyType::String(string.clone()), + vec![Value::Text(String::new()), Value::Text("\0".to_string())], + Value::Text(String::new()), + ), + ( + DocumentPropertyType::String(string), + vec![Value::Text("dash".to_string())], + Value::Text("dash".to_string()), + ), + ( + DocumentPropertyType::ByteArray(bytes.clone()), + vec![ + Value::Bytes(vec![1, 2, 3]), + Value::Array(vec![Value::U8(1), Value::U8(2), Value::U8(3)]), + Value::Text("AQID".to_string()), + ], + Value::Bytes(vec![1, 2, 3]), + ), + ( + DocumentPropertyType::ByteArray(bytes.clone()), + vec![ + Value::Bytes(vec![7; 32]), + Value::Bytes32([7; 32]), + Value::Identifier([7; 32]), + ], + Value::Bytes(vec![7; 32]), + ), + // No bytes have the empty key, as a missing value has + ( + DocumentPropertyType::ByteArray(bytes), + vec![Value::Bytes(vec![]), Value::Array(vec![])], + Value::Null, + ), + ( + DocumentPropertyType::Identifier, + vec![ + Value::Identifier([0x7A; 32]), + Value::Bytes32([0x7A; 32]), + Value::Bytes(vec![0x7A; 32]), + Value::Array(vec![Value::U8(0x7A); 32]), + Value::Text(bs58::encode([0x7A; 32]).into_string()), + ], + Value::Identifier([0x7A; 32]), + ), + ( + DocumentPropertyType::Boolean, + vec![Value::Bool(true)], + Value::Bool(true), + ), + ]; + let latest = PlatformVersion::latest(); + let version_14 = PlatformVersion::get(14).expect("protocol version 14"); + + for (property_type, forms, expected) in cases { + for form in forms { + assert_eq!( + contest_values(&property_type, &form, latest), + vec![expected.clone()], + "{property_type:?} {form:?}" + ); + let key = property_type + .encode_value_for_tree_keys(&form) + .expect("expected the key of the value"); + assert_eq!( + property_type + .decode_value_for_tree_keys(&key) + .expect("expected the value of the key"), + expected, + "{property_type:?} {form:?}" + ); + if !matches!(property_type, DocumentPropertyType::Identifier) { + assert_eq!( + contest_values(&property_type, &form, version_14), + vec![form], + "{property_type:?}" + ); + } + } + } + } + + /// A value its property's type does not key is in no contest, and is left as it is. + #[test] + fn should_leave_a_contest_value_its_type_does_not_key_as_it_is() { + let latest = PlatformVersion::latest(); + for (property_type, value) in [ + (DocumentPropertyType::U8, Value::I64(-1)), + (DocumentPropertyType::U8, Value::U64(256)), + (DocumentPropertyType::I64, Value::Text("5".to_string())), + (DocumentPropertyType::F64, Value::Text("5".to_string())), + (DocumentPropertyType::Boolean, Value::U8(1)), + (DocumentPropertyType::Identifier, Value::Bytes(vec![1; 31])), + (DocumentPropertyType::I64, Value::Null), + ] { + assert_eq!( + contest_values(&property_type, &value, latest), + vec![value.clone()], + "{property_type:?} {value:?}" + ); + } + + // A property path or a system property is no top-level property of the type + let index = make_index("contested", vec![("$ownerId", true)], true); + let data = BTreeMap::from([("$ownerId".to_string(), Value::Bytes(vec![1; 32]))]); + assert_eq!( + index + .extract_contested_values(&data, &IndexMap::new(), latest) + .expect("values"), + vec![Value::Bytes(vec![1; 32])] + ); + } + /// From protocol version 14 an identifier index value in any accepted form is written as /// `Value::Identifier`, so every contender of one contest names it with the same poll; a /// byte array property keeps its bytes. Before 14 the values are taken as given. @@ -83,16 +267,6 @@ mod tests { vec![("targetContractId", true), ("salt", true)], true, ); - let property = |property_type| DocumentProperty { - property_type, - required: true, - transient: false, - required_since: None, - distinct_from: None, - encrypted_for: None, - generated_from: None, - revealed_reference: None, - }; let document_properties = IndexMap::from([ ( "targetContractId".to_string(), diff --git a/packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/v1/mod.rs b/packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/v1/mod.rs new file mode 100644 index 00000000000..7fc966fa42a --- /dev/null +++ b/packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/v1/mod.rs @@ -0,0 +1,99 @@ +use super::contested_index_identifier; +use crate::data_contract::document_type::property::{DocumentProperty, DocumentPropertyType}; +use crate::data_contract::document_type::Index; +use indexmap::IndexMap; +use platform_value::Value; +use std::collections::BTreeMap; + +impl Index { + /// The index values of `data`, each written the one way its property's type writes every + /// value that shares its key in the paths of a vote poll. + #[inline(always)] + pub(super) fn extract_contested_values_v1( + &self, + data: &BTreeMap, + document_properties: &IndexMap, + ) -> Vec { + self.properties + .iter() + .zip(self.extract_values(data)) + .map( + |(index_property, value)| match document_properties.get(&index_property.name) { + Some(property) => { + canonical_contested_index_value(&property.property_type, value) + } + // Not a top-level property of the type: a contested create reads its + // index values from the document's top-level properties, so it finds + // no value here + None => value, + }, + ) + .collect() + } +} + +/// `value` as a property of `property_type` writes every value with the same key in the paths +/// of a vote poll (`DocumentPropertyType::encode_value_for_tree_keys`), which is also the +/// value a query of the contest decodes from that key. A value the type does not key (one of +/// another kind, or an integer out of the type's range) is returned as it is: no contest holds +/// it. +/// +/// Every type is listed, so that a new type states the form it takes. +fn canonical_contested_index_value(property_type: &DocumentPropertyType, value: Value) -> Value { + if value.is_null() { + return value; + } + let canonical = match property_type { + // An integer in any integer form is keyed by its number alone + DocumentPropertyType::U128 => value.to_integer().ok().map(Value::U128), + DocumentPropertyType::I128 => value.to_integer().ok().map(Value::I128), + DocumentPropertyType::U64 => value.to_integer().ok().map(Value::U64), + DocumentPropertyType::I64 => value.to_integer().ok().map(Value::I64), + DocumentPropertyType::U32 | DocumentPropertyType::KeyIdWithReference(_) => { + value.to_integer().ok().map(Value::U32) + } + DocumentPropertyType::I32 => value.to_integer().ok().map(Value::I32), + DocumentPropertyType::U16 => value.to_integer().ok().map(Value::U16), + DocumentPropertyType::I16 => value.to_integer().ok().map(Value::I16), + DocumentPropertyType::U8 => value.to_integer().ok().map(Value::U8), + DocumentPropertyType::I8 => value.to_integer().ok().map(Value::I8), + // A date is keyed as its timestamp + DocumentPropertyType::Date => value.to_integer().ok().map(Value::U64), + // A float is keyed by its bits, and an integer as the float it converts to + DocumentPropertyType::F64 => value.to_float().ok().map(Value::Float), + // Only the empty string and `"\0"` share a key, `[0]` + DocumentPropertyType::String(_) => match &value { + Value::Text(text) if text == "\0" => Some(Value::Text(String::new())), + _ => None, + }, + // Bytes in any form are keyed by the bytes alone, and no bytes by the empty key, as + // a missing value is + DocumentPropertyType::ByteArray(_) => value.to_binary_bytes().ok().map(|bytes| { + if bytes.is_empty() { + Value::Null + } else { + Value::Bytes(bytes) + } + }), + // The forms protocol version 14 already wrote as an identifier, then every other + // form keyed by the same 32 bytes + DocumentPropertyType::Identifier | DocumentPropertyType::IdentifierWithReference(_) => { + contested_index_identifier(&value) + .or_else(|| { + value + .to_identifier_bytes() + .ok() + .and_then(|bytes| <[u8; 32]>::try_from(bytes).ok()) + }) + .map(Value::Identifier) + } + // Keyed only as a boolean + DocumentPropertyType::Boolean => None, + // Never keyed whole: no index holds an object, and a contested index holds no array + DocumentPropertyType::Object(_) + | DocumentPropertyType::Array(_) + | DocumentPropertyType::VariableTypeArray(_) + | DocumentPropertyType::TypedArray(_) => None, + }; + canonical.unwrap_or(value) +} diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_index_value_forms_tests.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_index_value_forms_tests.rs new file mode 100644 index 00000000000..6844cd4fcaf --- /dev/null +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_index_value_forms_tests.rs @@ -0,0 +1,421 @@ +//! A contest is stored at the path of its index keys, and its poll is named by an id hashed from +//! its index values. An integer sent as `U64(5)` and as `U8(5)` has one key. From protocol +//! version 15 a contested create writes every index value the one way its property's type keys +//! it, so the contenders of one contest name one poll. A masternode vote names its poll by the +//! values it sends. + +use crate::execution::validation::state_transition::state_transitions::tests::{ + setup_identity, setup_masternode_voting_identity, +}; +use crate::rpc::core::MockCoreRPCLike; +use crate::test::helpers::setup::{TempPlatform, TestPlatformBuilder}; +use dpp::block::block_info::BlockInfo; +use dpp::dash_to_credits; +use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; +use dpp::data_contract::document_type::random_document::{ + CreateRandomDocument, DocumentFieldFillSize, DocumentFieldFillType, +}; +use dpp::data_contract::DataContract; +use dpp::document::{DocumentV0Getters, DocumentV0Setters}; +use dpp::fee::Credits; +use dpp::identity::accessors::IdentityGettersV0; +use dpp::identity::{Identity, IdentityPublicKey, TimestampMillis}; +use dpp::platform_value::{Bytes32, Value}; +use dpp::prelude::Identifier; +use dpp::serialization::PlatformSerializable; +use dpp::state_transition::batch_transition::methods::v0::DocumentsBatchTransitionMethodsV0; +use dpp::state_transition::batch_transition::BatchTransition; +use dpp::state_transition::masternode_vote_transition::methods::MasternodeVoteTransitionMethodsV0; +use dpp::state_transition::masternode_vote_transition::MasternodeVoteTransition; +use dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use dpp::voting::vote_polls::contested_document_resource_vote_poll::ContestedDocumentResourceVotePoll; +use dpp::voting::vote_polls::VotePoll; +use dpp::voting::votes::resource_vote::v0::ResourceVoteV0; +use dpp::voting::votes::resource_vote::ResourceVote; +use dpp::voting::votes::Vote; +use drive::drive::votes::paths::VotePollPaths; +use drive::drive::votes::resolved::vote_polls::contested_document_resource_vote_poll::resolve::ContestedDocumentResourceVotePollResolver; +use drive::util::test_helpers::setup_contract; +use platform_version::version::PlatformVersion; +use rand::prelude::StdRng; +use rand::{Rng, SeedableRng}; +use simple_signer::signer::SimpleSigner; +use std::collections::BTreeMap; + +/// The DPNS-shaped fixture whose contested index ends in the integer property `rank`. +const INTEGER_CONTRACT: &str = + "tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-integer.json"; +const NAME: &str = "quantum"; + +type IdentityInfo = (Identity, SimpleSigner, IdentityPublicKey); + +fn block(time_ms: TimestampMillis, height: u64) -> BlockInfo { + BlockInfo { + time_ms, + height, + core_height: 42, + epoch: Default::default(), + } +} + +fn poll(contract: &DataContract, rank: Value) -> 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(NAME.to_string()), + rank, + ], + } +} + +/// The serialized domain creation of a contender whose `rank` is sent as `rank`. +async fn contender_transition( + contract: &DataContract, + (identity, signer, key): &IdentityInfo, + rank: Value, + rng: &mut StdRng, + platform_version: &PlatformVersion, +) -> Vec { + let domain = contract + .document_type_for_name("domain") + .expect("expected domain document type"); + let entropy = Bytes32::random_with_rng(rng); + let mut document = domain + .random_document_with_identifier_and_entropy( + rng, + identity.id(), + entropy, + DocumentFieldFillType::FillIfNotRequired, + DocumentFieldFillSize::AnyDocumentFillSize, + platform_version, + ) + .expect("expected a random domain document"); + document + .set_id_for_creation(domain, &entropy.0, 2, platform_version) + .expect("expected to set the document id"); + document.set("parentDomainName", "dash".into()); + document.set("normalizedParentDomainName", "dash".into()); + document.set("label", NAME.into()); + document.set("normalizedLabel", NAME.into()); + document.set("records.identity", document.owner_id().into()); + document.set("subdomainRules.allowSubdomains", false.into()); + document.set("preorderSalt", [7u8; 32].into()); + document.set("rank", rank); + BatchTransition::new_document_creation_transition_from_document( + document, + domain, + entropy.0, + key, + 2, + 0, + None, + signer, + platform_version, + None, + ) + .await + .expect("expect to create domain batch transition") + .serialize_to_bytes() + .expect("serialize domain transition") +} + +async fn vote_transition( + vote_poll: ContestedDocumentResourceVotePoll, + resource_vote_choice: ResourceVoteChoice, + signer: &SimpleSigner, + pro_tx_hash: Identifier, + voting_key: &IdentityPublicKey, + nonce: u64, + platform_version: &PlatformVersion, +) -> Vec { + let vote = Vote::ResourceVote(ResourceVote::V0(ResourceVoteV0 { + vote_poll: VotePoll::ContestedDocumentResourceVotePoll(vote_poll), + resource_vote_choice, + })); + MasternodeVoteTransition::try_from_vote_with_signer( + vote, + signer, + pro_tx_hash, + voting_key, + nonce, + platform_version, + None, + ) + .await + .expect("expected to make transition vote") + .serialize_to_bytes() + .expect("expected to serialize the masternode vote") +} + +/// Processes transitions in a block at `time_ms` and returns how each one ended. +fn process( + platform: &TempPlatform, + transitions: &[Vec], + time_ms: TimestampMillis, + platform_version: &PlatformVersion, +) -> Vec { + let platform_state = platform.state.load(); + let transaction = platform.drive.grove.start_transaction(); + let processing_result = platform + .platform + .process_raw_state_transitions( + transitions, + &platform_state, + &block(time_ms, 1), + &transaction, + platform_version, + false, + None, + ) + .expect("expected to process state transitions"); + platform + .drive + .grove + .commit_transaction(transaction) + .unwrap() + .expect("expected to commit transaction"); + processing_result + .execution_results() + .iter() + .map(|result| format!("{:?}", result)) + .collect() +} + +fn process_valid( + platform: &TempPlatform, + transition: Vec, + time_ms: TimestampMillis, + platform_version: &PlatformVersion, +) { + let results = process(platform, &[transition], time_ms, platform_version); + assert!( + results[0].starts_with("SuccessfulExecution"), + "the transition should pass: {}", + results[0] + ); +} + +fn balance( + platform: &TempPlatform, + vote_poll: &ContestedDocumentResourceVotePoll, + platform_version: &PlatformVersion, +) -> Option { + platform + .drive + .fetch_prefunded_specialized_balance( + vote_poll + .specialized_balance_id() + .expect("expected a balance id") + .to_buffer(), + None, + platform_version, + ) + .expect("expected to fetch the prefunded balance") +} + +/// Whether the vote of `pro_tx_hash` towards `contender` is stored in the contest. +fn vote_is_stored( + contest: &Contest, + contender: Identifier, + pro_tx_hash: Identifier, + platform_version: &PlatformVersion, +) -> bool { + let path = contest + .poll + .resolve_with_provided_borrowed_contract(&contest.contract) + .expect("expected to resolve the poll") + .contender_voting_path( + &ResourceVoteChoice::TowardsIdentity(contender), + platform_version, + ) + .expect("expected the voting path of the contender"); + let path: Vec<&[u8]> = path.iter().map(|part| part.as_slice()).collect(); + contest + .platform + .drive + .grove + .has_raw( + path.as_slice(), + pro_tx_hash.as_slice(), + None, + &platform_version.drive.grove_version, + ) + .unwrap() + .expect("expected to read the vote") +} + +/// A contest two contenders joined, the first with `rank` as `U64(5)`, the second as `U8(5)`. +struct Contest { + platform: TempPlatform, + contract: DataContract, + second_contender: Identifier, + /// The poll the contenders name: `rank` as its property's type keys it + poll: ContestedDocumentResourceVotePoll, + /// The poll of the same contest with `rank` in another integer form + alternate_poll: ContestedDocumentResourceVotePoll, + /// What the poll's prefunded balance held once the first contender had joined + balance_after_first_contender: Option, + /// The time of the block the second contender joined in + time_ms: TimestampMillis, +} + +async fn open_contest(platform_version: &PlatformVersion) -> Contest { + let mut platform = TestPlatformBuilder::new() + .with_latest_protocol_version() + .build_with_mock_rpc() + .set_genesis_state(); + let mut rng = StdRng::seed_from_u64(0x5EED_0F02); + let owner = setup_identity(&mut platform, rng.gen(), dash_to_credits!(0.5)); + let contender_a = setup_identity(&mut platform, rng.gen(), dash_to_credits!(1.0)); + let contender_b = setup_identity(&mut platform, rng.gen(), dash_to_credits!(1.0)); + let contract = setup_contract( + &platform.drive, + INTEGER_CONTRACT, + None, + Some(owner.0.id().to_buffer()), + None::, + None, + Some(platform_version), + ); + + let domain = contract + .document_type_for_name("domain") + .expect("expected domain document type"); + let rank = domain + .indexes() + .get("parentNameAndLabel") + .expect("expected the contested index") + .extract_contested_values( + &BTreeMap::from([("rank".to_string(), Value::U64(5))]), + domain.flattened_properties(), + platform_version, + ) + .expect("expected the values of the contest") + .pop() + .expect("expected the rank"); + let alternate_rank = [Value::U8(5), Value::U64(5)] + .into_iter() + .find(|form| form != &rank) + .expect("expected another form of the rank"); + let alternate_poll = poll(&contract, alternate_rank); + let poll = poll(&contract, rank); + assert_ne!( + poll.unique_id().expect("expected a poll id"), + alternate_poll.unique_id().expect("expected a poll id"), + ); + + let start: TimestampMillis = 1_000_000; + let a = contender_transition( + &contract, + &contender_a, + Value::U64(5), + &mut rng, + platform_version, + ) + .await; + process_valid(&platform, a, start, platform_version); + let balance_after_first_contender = balance(&platform, &poll, platform_version); + let b = contender_transition( + &contract, + &contender_b, + Value::U8(5), + &mut rng, + platform_version, + ) + .await; + process_valid(&platform, b, start + 1000, platform_version); + + Contest { + platform, + contract, + second_contender: contender_b.0.id(), + poll, + alternate_poll, + balance_after_first_contender, + time_ms: start + 1000, + } +} + +#[tokio::test] +async fn should_name_one_poll_when_contenders_write_an_index_value_in_two_forms() { + let platform_version = PlatformVersion::latest(); + let contest = open_contest(platform_version).await; + + let first = contest + .balance_after_first_contender + .expect("expected the first contender to fund the poll"); + let both = balance(&contest.platform, &contest.poll, platform_version) + .expect("expected the poll to keep its balance"); + assert!( + both > first, + "the second contender funds the poll of the first: {first} then {both}" + ); + assert_eq!( + balance(&contest.platform, &contest.alternate_poll, platform_version), + None + ); +} + +#[tokio::test] +async fn should_refuse_a_vote_naming_the_poll_by_another_form_of_its_index_values() { + let platform_version = PlatformVersion::latest(); + let mut contest = open_contest(platform_version).await; + let (pro_tx_hash, _, signer, voting_key) = + setup_masternode_voting_identity(&mut contest.platform, 0xA11CE, platform_version); + + let vote = vote_transition( + contest.alternate_poll.clone(), + ResourceVoteChoice::TowardsIdentity(contest.second_contender), + &signer, + pro_tx_hash, + &voting_key, + 1, + platform_version, + ) + .await; + let result = process( + &contest.platform, + &[vote], + contest.time_ms + 1000, + platform_version, + ) + .remove(0); + assert!( + result.starts_with("UnpaidConsensusError") + && result.contains("PrefundedSpecializedBalanceNotFoundError"), + "no balance is held under another id of the contest: {result}" + ); + assert!(!vote_is_stored( + &contest, + contest.second_contender, + pro_tx_hash, + platform_version + )); + + let vote = vote_transition( + contest.poll.clone(), + ResourceVoteChoice::TowardsIdentity(contest.second_contender), + &signer, + pro_tx_hash, + &voting_key, + 1, + platform_version, + ) + .await; + process_valid( + &contest.platform, + vote, + contest.time_ms + 2000, + platform_version, + ); + assert!(vote_is_stored( + &contest, + contest.second_contender, + pro_tx_hash, + platform_version + )); +} 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 a897304e72d..f09e6578bcc 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 @@ -103,6 +103,9 @@ impl StateTransitionStateValidation for MasternodeVoteTransition { #[cfg(test)] mod no_locking_contest_tests; +#[cfg(test)] +mod contest_index_value_forms_tests; + #[cfg(test)] mod charter_election_tests; diff --git a/packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-integer.json b/packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-integer.json new file mode 100644 index 00000000000..22c2aeb931a --- /dev/null +++ b/packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-integer.json @@ -0,0 +1,180 @@ +{ + "$formatVersion": "0", + "id": "DWBXe9EXFPHxvbArQgT45uQR5gMmi8dfMpLhR5KSbwnZ", + "ownerId": "2QjL594djCH2NyDsn45vd6yQjEDHupMKo7CEGVTHtQxU", + "version": 1, + "documentSchemas": { + "domain": { + "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", + "minimum": 0, + "maximum": 1000, + "position": 7, + "description": "An integer that is part of the contested index." + } + }, + "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_all_votes_given_by_identities/mod.rs b/packages/rs-drive/src/drive/votes/cleanup/remove_all_votes_given_by_identities/mod.rs index f5a2ebe5127..9596342b990 100644 --- a/packages/rs-drive/src/drive/votes/cleanup/remove_all_votes_given_by_identities/mod.rs +++ b/packages/rs-drive/src/drive/votes/cleanup/remove_all_votes_given_by_identities/mod.rs @@ -43,9 +43,6 @@ impl Drive { ), 1 => self.remove_all_votes_given_by_identities_v1( identity_ids_as_byte_arrays, - block_height, - network, - chain_id, transaction, platform_version, ), diff --git a/packages/rs-drive/src/drive/votes/cleanup/remove_all_votes_given_by_identities/v1/mod.rs b/packages/rs-drive/src/drive/votes/cleanup/remove_all_votes_given_by_identities/v1/mod.rs index 831e07d98d7..b271664a849 100644 --- a/packages/rs-drive/src/drive/votes/cleanup/remove_all_votes_given_by_identities/v1/mod.rs +++ b/packages/rs-drive/src/drive/votes/cleanup/remove_all_votes_given_by_identities/v1/mod.rs @@ -1,40 +1,42 @@ use crate::drive::Drive; +use crate::error::drive::DriveError; use crate::error::Error; use crate::drive::votes::paths::{ + vote_contested_resource_identity_votes_tree_path_for_identity, + vote_contested_resource_identity_votes_tree_path_vec, vote_decisions_identity_votes_tree_path_vec, vote_decisions_poll_choice_votes_tree_path_vec, vote_decisions_tree_path, IDENTITY_VOTES_TREE_KEY, }; +use crate::drive::votes::storage_form::contested_document_resource_reference_storage_form::ContestedDocumentResourceVoteReferenceStorageForm; use crate::drive::votes::storage_form::yes_no_vote_reference_storage_form::YesNoVoteReferenceStorageForm; use crate::fees::op::LowLevelDriveOperation; +use crate::query::GroveError; use crate::util::grove_operations::{BatchDeleteApplyType, DirectQueryType}; -use dpp::dashcore::Network; -use dpp::prelude::{BlockHeight, Identifier}; +use dpp::platform_serialization::PLATFORM_BINCODE_CONFIG; +use dpp::prelude::Identifier; use dpp::version::PlatformVersion; use grovedb::{MaybeTree, TransactionArg, TreeType}; use std::collections::BTreeSet; impl Drive { /// Version 1 (protocol version 15) removes the contested resource votes of the removed - /// masternodes through version 0, unchanged, then their yes/no votes in a batch of its own: - /// the vote under the poll's choice sum tree, and each removed masternode's tree in the - /// decisions identity votes index, entries included. The two batches touch different - /// subtrees, so applying them one after the other leaves the same state as one batch would. + /// masternodes, then their yes/no votes in a batch of its own: the vote under the poll's + /// choice sum tree, and each removed masternode's tree in the decisions identity votes + /// index, entries included. The two batches touch different subtrees, so applying them one + /// after the other leaves the same state as one batch would. + /// + /// It only runs from protocol version 15, long after the mainnet heights version 0 treats + /// apart, so it takes neither the height nor the network. pub(super) fn remove_all_votes_given_by_identities_v1( &self, identity_ids_as_byte_arrays: Vec>, - block_height: BlockHeight, - network: Network, - chain_id: &str, transaction: TransactionArg, platform_version: &PlatformVersion, ) -> Result<(), Error> { - self.remove_all_votes_given_by_identities_v0( + self.remove_contested_resource_votes_given_by_identities_v1( identity_ids_as_byte_arrays.clone(), - block_height, - network, - chain_id, transaction, platform_version, )?; @@ -123,4 +125,305 @@ impl Drive { Ok(()) } + + /// Removes every contested resource vote reference of the identities, and the vote each + /// one points at while that vote is stored: the vote is looked up at the path its + /// reference names, and deleted there when it is found. A vote two references point at is + /// deleted once. + fn remove_contested_resource_votes_given_by_identities_v1( + &self, + identity_ids_as_byte_arrays: Vec>, + transaction: TransactionArg, + platform_version: &PlatformVersion, + ) -> Result<(), Error> { + // We first query for all vote references that the identities have + + let votes_to_remove_by_identity_id = self.identity_vote_entries_of_identities_v0( + vote_contested_resource_identity_votes_tree_path_vec(), + identity_ids_as_byte_arrays, + transaction, + platform_version, + )?; + + // Then we take each vote reference and go looking for its vote (to remove it) + + let mut deletion_batch = vec![]; + + for (identifier_bytes, votes_to_remove) in votes_to_remove_by_identity_id { + let identity_id = Identifier::from_vec(identifier_bytes.clone())?; + let vote_path_ref = vote_contested_resource_identity_votes_tree_path_for_identity( + identity_id.as_bytes(), + ); + + // The paths this identity's votes were already deleted at + let mut deleted_vote_paths = BTreeSet::new(); + + for (vote_id, vote_to_remove) in votes_to_remove { + // We delete the vote item as reference + self.batch_delete( + vote_path_ref.as_slice().into(), + vote_id.as_slice(), + BatchDeleteApplyType::StatefulBatchDelete { + is_known_to_be_subtree_with_sum: Some(MaybeTree::NotTree), + }, + transaction, + &mut deletion_batch, + &platform_version.drive, + )?; + + let serialized_reference = vote_to_remove.into_item_bytes()?; + let bincode_config = PLATFORM_BINCODE_CONFIG; + let reference: ContestedDocumentResourceVoteReferenceStorageForm = + bincode::decode_from_slice(&serialized_reference, bincode_config) + .map_err(|e| { + Error::Drive(DriveError::CorruptedSerialization(format!( + "serialization of reference {} is corrupted: {}", + hex::encode(serialized_reference), + e + ))) + })? + .0; + let mut absolute_path = reference + .reference_path_type + .absolute_path(vote_path_ref.as_slice(), Some(vote_id.as_slice()))?; + + absolute_path.pop(); // we need to get rid of the key (which is the identifier bytes) + + let absolute_path_ref: Vec<_> = + absolute_path.iter().map(|a| a.as_slice()).collect(); + + // The vote is deleted only while it is stored at the path its reference names + let vote_is_stored = match self.grove_get_raw_optional( + absolute_path_ref.as_slice().into(), + identifier_bytes.as_slice(), + DirectQueryType::StatefulDirectQuery, + transaction, + &mut vec![], + &platform_version.drive, + ) { + Ok(vote) => vote.is_some(), + Err(Error::GroveDB(error)) + if matches!( + *error, + GroveError::PathNotFound(_) + | GroveError::PathParentLayerNotFound(_) + | GroveError::PathKeyNotFound(_) + ) => + { + false + } + Err(error) => return Err(error), + }; + + if !vote_is_stored || !deleted_vote_paths.insert(absolute_path.clone()) { + continue; + } + + // we then need to add to the batch the deletion + + self.batch_delete( + absolute_path_ref.as_slice().into(), + identifier_bytes.as_slice(), + BatchDeleteApplyType::StatefulBatchDelete { + is_known_to_be_subtree_with_sum: Some(MaybeTree::NotTree), + }, + transaction, + &mut deletion_batch, + &platform_version.drive, + )?; + } + } + + if !deletion_batch.is_empty() { + self.apply_batch_low_level_drive_operations( + None, + transaction, + deletion_batch, + &mut vec![], + &platform_version.drive, + ) + .inspect_err(|err| tracing::error!(?err, "vote deletion batch failed"))?; + } + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use crate::drive::votes::paths::{ + vote_contested_resource_identity_votes_tree_path_for_identity, + vote_contested_resource_identity_votes_tree_path_vec, + vote_contested_resource_tree_path_vec, + }; + use crate::drive::votes::storage_form::contested_document_resource_reference_storage_form::ContestedDocumentResourceVoteReferenceStorageForm; + use crate::drive::Drive; + use crate::util::test_helpers::setup::setup_drive_with_initial_state_structure; + use dpp::dashcore::Network; + use dpp::platform_serialization::PLATFORM_BINCODE_CONFIG; + use dpp::version::PlatformVersion; + use grovedb::element::reference_path::ReferencePathType; + use grovedb::Element; + + const IDENTITY_ID: [u8; 32] = [7u8; 32]; + const VOTE_ID: [u8; 32] = [9u8; 32]; + /// The id a second reference to the same vote is stored under + const OTHER_VOTE_ID: [u8; 32] = [10u8; 32]; + /// Subtree under the contested resource tree that holds the vote. + const VOTE_TREE_KEY: &[u8] = b"t"; + + fn insert(drive: &Drive, path: &[&[u8]], key: &[u8], element: Element) { + drive + .grove + .insert( + path, + key, + element, + None, + None, + &PlatformVersion::latest().drive.grove_version, + ) + .unwrap() + .expect("expected to insert"); + } + + fn exists(drive: &Drive, path: &[&[u8]], key: &[u8]) -> bool { + match drive + .grove + .get_raw( + path.into(), + key, + None, + &PlatformVersion::latest().drive.grove_version, + ) + .unwrap() + { + Ok(_) => true, + Err(grovedb::Error::PathKeyNotFound(_)) => false, + Err(error) => panic!("unexpected error: {error}"), + } + } + + fn vote_tree_path() -> Vec> { + let mut path = vote_contested_resource_tree_path_vec(); + path.push(VOTE_TREE_KEY.to_vec()); + path + } + + /// The tree that holds the vote, where the real paths have the trees of a contender. + fn insert_vote_tree(drive: &Drive) { + let path = vote_contested_resource_tree_path_vec(); + let path: Vec<&[u8]> = path.iter().map(|part| part.as_slice()).collect(); + insert(drive, &path, VOTE_TREE_KEY, Element::empty_tree()); + } + + fn insert_vote(drive: &Drive) { + let path = vote_tree_path(); + let path: Vec<&[u8]> = path.iter().map(|part| part.as_slice()).collect(); + // A sum item in the real paths; a delete only needs it not to be a tree + insert(drive, &path, &IDENTITY_ID, Element::new_item(vec![1])); + } + + fn vote_exists(drive: &Drive) -> bool { + let path = vote_tree_path(); + let path: Vec<&[u8]> = path.iter().map(|part| part.as_slice()).collect(); + exists(drive, &path, &IDENTITY_ID) + } + + /// The references of `IDENTITY_ID` to its vote, one under each of `vote_ids`. + fn insert_vote_references(drive: &Drive, vote_ids: &[[u8; 32]]) { + let path = vote_contested_resource_identity_votes_tree_path_vec(); + let path: Vec<&[u8]> = path.iter().map(|part| part.as_slice()).collect(); + insert(drive, &path, &IDENTITY_ID, Element::empty_tree()); + + let storage_form = ContestedDocumentResourceVoteReferenceStorageForm { + reference_path_type: + ReferencePathType::UpstreamRootHeightWithParentPathAdditionReference( + 2, + vec![VOTE_TREE_KEY.to_vec()], + ), + identity_vote_times: 1, + }; + let encoded_reference = bincode::encode_to_vec(storage_form, PLATFORM_BINCODE_CONFIG) + .expect("expected to encode the reference"); + + for vote_id in vote_ids { + insert( + drive, + vote_contested_resource_identity_votes_tree_path_for_identity(&IDENTITY_ID) + .as_slice(), + vote_id, + Element::new_item(encoded_reference.clone()), + ); + } + } + + fn vote_reference_exists(drive: &Drive, vote_id: &[u8; 32]) -> bool { + exists( + drive, + vote_contested_resource_identity_votes_tree_path_for_identity(&IDENTITY_ID).as_slice(), + vote_id, + ) + } + + fn remove_votes(drive: &Drive) { + drive + .remove_all_votes_given_by_identities( + vec![IDENTITY_ID.to_vec()], + 1, + Network::Testnet, + "test", + None, + PlatformVersion::latest(), + ) + .expect("expected to remove the votes"); + } + + #[test] + fn should_remove_a_vote_and_its_reference() { + let drive = setup_drive_with_initial_state_structure(None); + insert_vote_tree(&drive); + insert_vote(&drive); + insert_vote_references(&drive, &[VOTE_ID]); + + remove_votes(&drive); + + assert!(!vote_reference_exists(&drive, &VOTE_ID)); + assert!(!vote_exists(&drive)); + } + + #[test] + fn should_remove_a_reference_whose_vote_tree_is_gone() { + let drive = setup_drive_with_initial_state_structure(None); + insert_vote_references(&drive, &[VOTE_ID]); + + remove_votes(&drive); + + assert!(!vote_reference_exists(&drive, &VOTE_ID)); + } + + #[test] + fn should_remove_a_reference_whose_vote_is_gone_from_its_tree() { + let drive = setup_drive_with_initial_state_structure(None); + insert_vote_tree(&drive); + insert_vote_references(&drive, &[VOTE_ID]); + + remove_votes(&drive); + + assert!(!vote_reference_exists(&drive, &VOTE_ID)); + } + + #[test] + fn should_remove_a_vote_two_references_point_at() { + let drive = setup_drive_with_initial_state_structure(None); + insert_vote_tree(&drive); + insert_vote(&drive); + insert_vote_references(&drive, &[VOTE_ID, OTHER_VOTE_ID]); + + remove_votes(&drive); + + assert!(!vote_reference_exists(&drive, &VOTE_ID)); + assert!(!vote_reference_exists(&drive, &OTHER_VOTE_ID)); + assert!(!vote_exists(&drive)); + } } diff --git a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v7.rs b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v7.rs index 80833ae517c..23bebf1e58d 100644 --- a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v7.rs +++ b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v7.rs @@ -1,7 +1,7 @@ use crate::version::dpp_versions::dpp_contract_versions::v6::CONTRACT_VERSIONS_V6; use crate::version::dpp_versions::dpp_contract_versions::{ - DPPContractVersions, DataContractMethodVersions, DocumentTypeSchemaVersions, - DocumentTypeVersions, + DPPContractVersions, DataContractMethodVersions, DocumentTypeMethodVersions, + DocumentTypeSchemaVersions, DocumentTypeVersions, }; /// Introduced in protocol version 15. Differs from v6 in: @@ -29,7 +29,10 @@ use crate::version::dpp_versions::dpp_contract_versions::{ /// property names, on an integer property; /// - `contract_storage_serialization_version`, 2 rather than 1: Drive stores a contract in /// format version 2, its document types compiled, while state transitions and clients keep -/// format version 1. +/// format version 1; +/// - `canonical_contested_index_values`, `Some(1)` rather than `Some(0)`: every index value +/// of a contest is written the one way its property's type keys it, so the values of one +/// contest name one poll; 0 wrote only identifiers one way. /// /// v6 remains unchanged for `PROTOCOL_VERSION_14`, whose parse refuses a byte array key and /// whose schemas and documents the `jsonschema` crate checks. @@ -57,6 +60,12 @@ pub const CONTRACT_VERSIONS_V7: DPPContractVersions = DPPContractVersions { validate_max_depth: 2, ..CONTRACT_VERSIONS_V6.document_type_versions.schema }, + methods: DocumentTypeMethodVersions { + // changed: every index value of a contest is written the one way its property's + // type keys it, where 0 wrote only identifiers one way + canonical_contested_index_values: Some(1), + ..CONTRACT_VERSIONS_V6.document_type_versions.methods + }, ..CONTRACT_VERSIONS_V6.document_type_versions }, // changed: contracts are stored with their document types compiled, about 1.8 times the 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 54049951c40..620f642be66 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 @@ -10,7 +10,8 @@ use crate::version::drive_versions::drive_vote_method_versions::{ /// * `insert.register_identity_vote` 1 registers a resolved vote of either kind (v0 knows only /// contested resource votes, which v1 still hands to it). /// * `remove_all_votes_given_by_identities` 1 also removes the yes/no votes of a masternode -/// that left the list. +/// that left the list, and deletes a contested resource vote a reference points at while +/// that vote is stored. /// * `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 diff --git a/packages/rs-platform-version/src/version/drive_versions/v10.rs b/packages/rs-platform-version/src/version/drive_versions/v10.rs index bc2ad2d3e9f..4f45391db5f 100644 --- a/packages/rs-platform-version/src/version/drive_versions/v10.rs +++ b/packages/rs-platform-version/src/version/drive_versions/v10.rs @@ -52,7 +52,8 @@ use grovedb_version::version::v5::GROVE_V5; /// * **Yes/no vote polls**: `DRIVE_VOTE_METHOD_VERSIONS_V4` bumps /// `insert.register_identity_vote` to 1, which registers a vote of either poll kind, and /// `cleanup.remove_all_votes_given_by_identities` to 1, which also removes the yes/no votes of -/// a masternode that left the list. It sets every `yes_no` method to `Some(0)`, so yes/no +/// a masternode that left the list and deletes a contested resource vote a reference +/// points at while that vote is stored. It sets every `yes_no` method to `Some(0)`, so yes/no /// polls can be opened and voted on (`None`, not active, in every earlier table), and bumps /// `contested_resource_insert.add_vote_poll_end_date_query_operations` to 1, which adds only /// the entry when the batch already queues the end date's tree with other storage flags. diff --git a/packages/rs-platform-version/src/version/v15.rs b/packages/rs-platform-version/src/version/v15.rs index 35438acbb30..b8d7ac6cfac 100644 --- a/packages/rs-platform-version/src/version/v15.rs +++ b/packages/rs-platform-version/src/version/v15.rs @@ -764,6 +764,28 @@ pub const PROTOCOL_VERSION_15: ProtocolVersion = 15; /// history after the operator-payout reconciliation (note 32) and all other activation /// events in the same transaction. Keep-history index references shrink from 44 to /// 42 bytes by targeting the primary pointer, lowering their reference-size estimates. +/// +/// 36. **Removing the contested resource votes of a masternode that left the list**: +/// `remove_all_votes_given_by_identities` 1 (`DRIVE_VOTE_METHOD_VERSIONS_V4`, note 10) +/// removes every contested resource vote reference of the masternode, and deletes the +/// vote a reference points at while that vote is stored, once when two references point +/// at it. Generation 0 deletes at the path of every reference. Protocol v14 and earlier +/// keep generation 0. +/// +/// 37. **The contenders of one contest name one poll**: a contest is stored at the path of +/// its index keys, and its poll is named by an id hashed from its index values. +/// `canonical_contested_index_values` 1 (`CONTRACT_VERSIONS_V7`) writes every index +/// value of a contested create the one way its property's type keys it: an integer in +/// any integer form as the type's own integer, a date as a `u64`, an integer or a float +/// of a float property as a float, bytes in any form as bytes (none as a missing +/// value), `"\0"` as the empty string, and an identifier as generation 0 writes it. It +/// is the value a query of the contest decodes from the key. Generation 0 writes only +/// identifiers one way, so two contenders sending an integer as `U64(5)` and `U8(5)` +/// name two polls of one contest. A masternode vote names its poll as sent, at every +/// version, and is refused unless a prefunded balance is held under that poll +/// (`PrefundedSpecializedBalanceNotFoundError`, 40401), so a voter sends the values as +/// the contest query returns them. A contest opened earlier keeps the polls its +/// contenders named. Protocol v14 keeps generation 0. 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); create_initial_state_structure 5 adds the token marketplace escrow trees; calculate_total_tokens_balance 2 counts escrowed tokens; the escrow primitives; the identity balance, token balance, prefunded specialized balance and contract fee pot estimations (for_balances 1, for_token_balances 1, estimated_cost_for_prefunded_specialized_balance_update 2, add_estimation_costs_for_contract_fee_pot_update 1) keep a deeper layer description (note 17); 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) From 62a536f5547bf16f4da9e5005f09dc9039198190 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Thu, 12 Nov 2026 17:11:05 +0700 Subject: [PATCH 2/3] fix(platform): a contest under way keeps the poll it was opened under (PV15) A contest's prefunded balance and end date are kept under the poll it was opened under. From protocol version 15 a contested create joining a contest opened in an earlier epoch reads the protocol version that epoch ran (`Drive::fetch_contest_opening_protocol_version`, `None` before) and writes its index values as that version does, so it names the poll the contest already has. The read is billed and made only for a create whose values this version does not write as they were sent. Document create advanced structure validation 1 compares the poll a create names with the expected one by contract, document type and index name: the index values of both are read from the same document. Review follow-ups: an identifier given as text is read only when it is short enough to be one in base 58; the transition tests assert on typed results and cover a contest opened at protocol version 14 and joined at 15, with and without locking; the removal tests store the vote as a sum item in a sum tree and check its tally. Co-Authored-By: Claude Fable 5.2 --- book/src/data-model/contested-documents.md | 4 + .../index/extract_contested_values/mod.rs | 5 + .../index/extract_contested_values/v1/mod.rs | 8 +- .../methods/versioned_methods.rs | 7 +- .../advanced_structure_v1/mod.rs | 13 +- .../contest_index_value_forms_tests.rs | 311 +++++++++++++++--- ...-unique-index-no-locking-with-integer.json | 180 ++++++++++ .../v1/mod.rs | 40 ++- .../mod.rs | 57 ++++ .../v0/mod.rs | 45 +++ .../rs-drive/src/drive/votes/fetch/mod.rs | 1 + .../v0/transformer.rs | 56 +++- .../dpp_versions/dpp_contract_versions/mod.rs | 9 +- .../drive_vote_method_versions/mod.rs | 3 + .../drive_vote_method_versions/v1.rs | 1 + .../drive_vote_method_versions/v2.rs | 1 + .../drive_vote_method_versions/v3.rs | 1 + .../drive_vote_method_versions/v4.rs | 11 +- .../rs-platform-version/src/version/v15.rs | 13 +- 19 files changed, 693 insertions(+), 73 deletions(-) create mode 100644 packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-no-locking-with-integer.json create mode 100644 packages/rs-drive/src/drive/votes/fetch/fetch_contest_opening_protocol_version/mod.rs create mode 100644 packages/rs-drive/src/drive/votes/fetch/fetch_contest_opening_protocol_version/v0/mod.rs diff --git a/book/src/data-model/contested-documents.md b/book/src/data-model/contested-documents.md index daec1d5210f..a120dd4fc2e 100644 --- a/book/src/data-model/contested-documents.md +++ b/book/src/data-model/contested-documents.md @@ -65,6 +65,10 @@ it shares a key with. That is the value a query of the contest returns. A master its poll by the values it sends, unchanged, and is refused unless a prefunded balance is held under that poll, so a voter sends the values as the contest query returns them. +A contest under way keeps the poll it was opened under. A contender that joins a contest opened +at an earlier protocol version has its index values written as that version wrote them, so it +funds the same prefunded balance and the contest keeps its end date. + ## Resolution 0: masternode vote The DPNS rule. The choices are a contender, abstain, or **lock**, which gives the value to nobody. diff --git a/packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/mod.rs b/packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/mod.rs index bfef7300a5d..4f3767582de 100644 --- a/packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/mod.rs @@ -237,6 +237,11 @@ mod tests { (DocumentPropertyType::F64, Value::Text("5".to_string())), (DocumentPropertyType::Boolean, Value::U8(1)), (DocumentPropertyType::Identifier, Value::Bytes(vec![1; 31])), + // Longer than any identifier in base 58, so it is not decoded + ( + DocumentPropertyType::Identifier, + Value::Text("1".repeat(4096)), + ), (DocumentPropertyType::I64, Value::Null), ] { assert_eq!( diff --git a/packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/v1/mod.rs b/packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/v1/mod.rs index 7fc966fa42a..94d0603d9a1 100644 --- a/packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/v1/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/index/extract_contested_values/v1/mod.rs @@ -76,14 +76,16 @@ fn canonical_contested_index_value(property_type: &DocumentPropertyType, value: } }), // The forms protocol version 14 already wrote as an identifier, then every other - // form keyed by the same 32 bytes + // form keyed by the same 32 bytes. A text is read only when it is short enough to be + // an identifier in base 58: no schema has bounded it yet, and decoding base 58 takes + // time quadratic in its length DocumentPropertyType::Identifier | DocumentPropertyType::IdentifierWithReference(_) => { contested_index_identifier(&value) .or_else(|| { value - .to_identifier_bytes() + .to_bounded_identifier() .ok() - .and_then(|bytes| <[u8; 32]>::try_from(bytes).ok()) + .map(|identifier| identifier.to_buffer()) }) .map(Value::Identifier) } diff --git a/packages/rs-dpp/src/data_contract/document_type/methods/versioned_methods.rs b/packages/rs-dpp/src/data_contract/document_type/methods/versioned_methods.rs index fb0f7f1131f..eba6769dfa4 100644 --- a/packages/rs-dpp/src/data_contract/document_type/methods/versioned_methods.rs +++ b/packages/rs-dpp/src/data_contract/document_type/methods/versioned_methods.rs @@ -418,9 +418,10 @@ pub trait DocumentTypeV0MethodsVersioned: DocumentTypeV0Getters + DocumentTypeBa } }) .map(|index| { - // Identifier values are written one way from protocol version 14, so every - // contender of a contest names it with the same poll; before 14 they are taken - // as given, as they always were + // Every contender of a contest names it with the same poll: from protocol + // version 15 every index value is written the one way its property's type keys + // it, at protocol version 14 identifier values alone are written one way, and + // before 14 the values are taken as given let index_values = index.extract_contested_values( document_properties, self.flattened_properties(), diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v1/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v1/mod.rs index face98f61c6..1b7e6b466d2 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v1/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v1/mod.rs @@ -78,7 +78,18 @@ impl DocumentCreateTransitionActionStructureValidationV1 for DocumentCreateTrans // indexes, so the contest would be funded, resolved and cleaned up under a // vote poll that does not describe the contest that was actually created. let provided: ContestedDocumentResourceVotePoll = provided.into(); - if provided != expected { + // In place: the polls are compared by what names the index, where they were + // compared whole. The index values of both are read from this document's + // data, so wherever both are written by the block's protocol version, as + // they always are before protocol version 15, polls of one index are + // equal. From 15 a contender joining a contest opened at an earlier + // protocol version writes its values as that version did + // (`Drive::fetch_contest_opening_protocol_version`), and the expected poll + // does not. + if provided.contract_id != expected.contract_id + || provided.document_type_name != expected.document_type_name + || provided.index_name != expected.index_name + { return Ok(SimpleConsensusValidationResult::new_with_error( DocumentContestIndexMismatchError::new( self.base().id(), diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_index_value_forms_tests.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_index_value_forms_tests.rs index 6844cd4fcaf..a867068b24c 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_index_value_forms_tests.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_index_value_forms_tests.rs @@ -2,14 +2,22 @@ //! its index values. An integer sent as `U64(5)` and as `U8(5)` has one key. From protocol //! version 15 a contested create writes every index value the one way its property's type keys //! it, so the contenders of one contest name one poll. A masternode vote names its poll by the -//! values it sends. +//! values it sends. A contest opened at an earlier protocol version keeps the poll it was +//! opened under: a contender joining it later writes its values as that version did. use crate::execution::validation::state_transition::state_transitions::tests::{ setup_identity, setup_masternode_voting_identity, }; +use crate::platform_types::platform_state::{PlatformState, PlatformStateV0Methods}; +use crate::platform_types::state_transitions_processing_result::StateTransitionExecutionResult; use crate::rpc::core::MockCoreRPCLike; use crate::test::helpers::setup::{TempPlatform, TestPlatformBuilder}; +use assert_matches::assert_matches; use dpp::block::block_info::BlockInfo; +use dpp::block::epoch::Epoch; +use dpp::block::extended_block_info::v0::ExtendedBlockInfoV0; +use dpp::consensus::state::state_error::StateError; +use dpp::consensus::ConsensusError; use dpp::dash_to_credits; use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; @@ -36,26 +44,29 @@ use dpp::voting::votes::resource_vote::ResourceVote; use dpp::voting::votes::Vote; use drive::drive::votes::paths::VotePollPaths; use drive::drive::votes::resolved::vote_polls::contested_document_resource_vote_poll::resolve::ContestedDocumentResourceVotePollResolver; -use drive::util::test_helpers::setup_contract; +use drive::util::test_helpers::{setup_contract, vote_poll_end_dates}; use platform_version::version::PlatformVersion; use rand::prelude::StdRng; use rand::{Rng, SeedableRng}; use simple_signer::signer::SimpleSigner; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; /// The DPNS-shaped fixture whose contested index ends in the integer property `rank`. const INTEGER_CONTRACT: &str = "tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-integer.json"; +/// The same fixture with the contested index resolved without locking. +const NO_LOCKING_INTEGER_CONTRACT: &str = "tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-no-locking-with-integer.json"; const NAME: &str = "quantum"; type IdentityInfo = (Identity, SimpleSigner, IdentityPublicKey); -fn block(time_ms: TimestampMillis, height: u64) -> BlockInfo { +fn block(time_ms: TimestampMillis, epoch_index: u16) -> BlockInfo { BlockInfo { time_ms, - height, + height: 1, core_height: 42, - epoch: Default::default(), + epoch: Epoch::new(epoch_index).expect("expected an epoch"), } } @@ -151,13 +162,15 @@ async fn vote_transition( .expect("expected to serialize the masternode vote") } -/// Processes transitions in a block at `time_ms` and returns how each one ended. +/// Processes transitions in a block at `time_ms` of epoch `epoch_index` and returns how each +/// one ended. fn process( platform: &TempPlatform, transitions: &[Vec], time_ms: TimestampMillis, + epoch_index: u16, platform_version: &PlatformVersion, -) -> Vec { +) -> Vec { let platform_state = platform.state.load(); let transaction = platform.drive.grove.start_transaction(); let processing_result = platform @@ -165,7 +178,7 @@ fn process( .process_raw_state_transitions( transitions, &platform_state, - &block(time_ms, 1), + &block(time_ms, epoch_index), &transaction, platform_version, false, @@ -178,27 +191,108 @@ fn process( .commit_transaction(transaction) .unwrap() .expect("expected to commit transaction"); - processing_result - .execution_results() - .iter() - .map(|result| format!("{:?}", result)) - .collect() + processing_result.execution_results().to_vec() } -fn process_valid( +fn process_valid_in_epoch( platform: &TempPlatform, transition: Vec, time_ms: TimestampMillis, + epoch_index: u16, platform_version: &PlatformVersion, ) { - let results = process(platform, &[transition], time_ms, platform_version); - assert!( - results[0].starts_with("SuccessfulExecution"), - "the transition should pass: {}", - results[0] + assert_matches!( + process( + platform, + &[transition], + time_ms, + epoch_index, + platform_version + ) + .as_slice(), + [StateTransitionExecutionResult::SuccessfulExecution { .. }] ); } +fn process_valid( + platform: &TempPlatform, + transition: Vec, + time_ms: TimestampMillis, + platform_version: &PlatformVersion, +) { + process_valid_in_epoch(platform, transition, time_ms, 0, platform_version); +} + +/// `rank` 5 as the latest protocol version writes it in a poll, and in another integer form. +fn rank_forms(contract: &DataContract) -> (Value, Value) { + let domain = contract + .document_type_for_name("domain") + .expect("expected domain document type"); + let rank = domain + .indexes() + .get("parentNameAndLabel") + .expect("expected the contested index") + .extract_contested_values( + &BTreeMap::from([("rank".to_string(), Value::U64(5))]), + domain.flattened_properties(), + PlatformVersion::latest(), + ) + .expect("expected the values of the contest") + .pop() + .expect("expected the rank"); + let alternate_rank = [Value::U8(5), Value::U64(5)] + .into_iter() + .find(|form| form != &rank) + .expect("expected another form of the rank"); + (rank, alternate_rank) +} + +/// Ends every poll due at `time_ms`, as the block at that time would. +fn end_polls_at( + platform: &TempPlatform, + time_ms: TimestampMillis, + epoch_index: u16, + platform_version: &PlatformVersion, +) { + let mut platform_state = (**platform.state.load()).clone(); + let block_info = block(time_ms, epoch_index); + platform_state.set_last_committed_block_info(Some( + ExtendedBlockInfoV0 { + basic_info: block_info, + app_hash: platform + .drive + .grove + .root_hash(None, &platform_version.drive.grove_version) + .unwrap() + .unwrap(), + quorum_hash: [0u8; 32], + block_id_hash: [0u8; 32], + proposer_pro_tx_hash: [0u8; 32], + signature: [0u8; 96], + round: 0, + } + .into(), + )); + platform.state.store(Arc::new(platform_state)); + let platform_state = platform.state.load(); + let transaction = platform.drive.grove.start_transaction(); + platform + .check_for_ended_vote_polls( + &platform_state, + &platform_state, + &block_info, + Some(&transaction), + platform_version, + ) + .expect("expected to check for ended vote polls"); + platform + .drive + .grove + .commit_transaction(transaction) + .unwrap() + .expect("expected to commit transaction"); +} + fn balance( platform: &TempPlatform, vote_poll: &ContestedDocumentResourceVotePoll, @@ -282,25 +376,7 @@ async fn open_contest(platform_version: &PlatformVersion) -> Contest { Some(platform_version), ); - let domain = contract - .document_type_for_name("domain") - .expect("expected domain document type"); - let rank = domain - .indexes() - .get("parentNameAndLabel") - .expect("expected the contested index") - .extract_contested_values( - &BTreeMap::from([("rank".to_string(), Value::U64(5))]), - domain.flattened_properties(), - platform_version, - ) - .expect("expected the values of the contest") - .pop() - .expect("expected the rank"); - let alternate_rank = [Value::U8(5), Value::U64(5)] - .into_iter() - .find(|form| form != &rank) - .expect("expected another form of the rank"); + let (rank, alternate_rank) = rank_forms(&contract); let alternate_poll = poll(&contract, alternate_rank); let poll = poll(&contract, rank); assert_ne!( @@ -377,17 +453,19 @@ async fn should_refuse_a_vote_naming_the_poll_by_another_form_of_its_index_value platform_version, ) .await; - let result = process( - &contest.platform, - &[vote], - contest.time_ms + 1000, - platform_version, - ) - .remove(0); - assert!( - result.starts_with("UnpaidConsensusError") - && result.contains("PrefundedSpecializedBalanceNotFoundError"), - "no balance is held under another id of the contest: {result}" + // No balance is held under another poll of the contest + assert_matches!( + process( + &contest.platform, + &[vote], + contest.time_ms + 1000, + 0, + platform_version, + ) + .as_slice(), + [StateTransitionExecutionResult::UnpaidConsensusError( + ConsensusError::StateError(StateError::PrefundedSpecializedBalanceNotFoundError(_)) + )] ); assert!(!vote_is_stored( &contest, @@ -419,3 +497,136 @@ async fn should_refuse_a_vote_naming_the_poll_by_another_form_of_its_index_value platform_version )); } + +/// A contest opened at protocol version 14 with `rank` in a form the latest protocol version +/// writes another way is joined, after the upgrade, by a contender sending `rank` the same way, +/// then ended. The second contender funds the poll the contest was opened under, the contest +/// runs to the end of its poll, and nothing is left under either poll once it ended. A contest +/// resolved without locking runs to the end of its join window until a second contender joins. +async fn join_after_the_upgrade_a_contest_opened_at_protocol_version_14( + contract_path: &str, + no_locking: bool, +) { + let version_14 = PlatformVersion::get(14).expect("expected protocol version 14"); + let latest = PlatformVersion::latest(); + let mut platform = TestPlatformBuilder::new() + .with_initial_protocol_version(14) + .build_with_mock_rpc() + .with_no_core_masternodes() + .set_genesis_state(); + let mut rng = StdRng::seed_from_u64(0x5EED_0F03); + let owner = setup_identity(&mut platform, rng.gen(), dash_to_credits!(0.5)); + let contender_a = setup_identity(&mut platform, rng.gen(), dash_to_credits!(1.0)); + let contender_b = setup_identity(&mut platform, rng.gen(), dash_to_credits!(1.0)); + let contract = setup_contract( + &platform.drive, + contract_path, + None, + Some(owner.0.id().to_buffer()), + None::, + None, + Some(version_14), + ); + + let (rank, alternate_rank) = rank_forms(&contract); + // The poll the contest is opened under at protocol version 14, which takes `rank` as sent + let opening_poll = poll(&contract, alternate_rank.clone()); + // The poll the latest protocol version names for a contest it opens + let latest_poll = poll(&contract, rank); + let opening_poll_id = opening_poll.unique_id().expect("expected a poll id"); + + let join_window = latest + .dpp + .validation + .voting + .allow_other_contenders_time_testing_ms; + let poll_duration = latest + .dpp + .voting_versions + .default_vote_poll_time_duration_test_network_ms; + + let start: TimestampMillis = 1_000_000; + let a = contender_transition( + &contract, + &contender_a, + alternate_rank.clone(), + &mut rng, + version_14, + ) + .await; + process_valid_in_epoch(&platform, a, start, 0, version_14); + let balance_after_first_contender = balance(&platform, &opening_poll, version_14) + .expect("expected the first contender to fund the poll"); + let first_end = if no_locking { + start + join_window + } else { + start + poll_duration + }; + assert_eq!( + vote_poll_end_dates(&platform.drive, version_14), + BTreeMap::from([(first_end, BTreeSet::from([opening_poll_id]))]) + ); + + // The first block of the latest protocol version, in the next epoch + let platform_state = platform.state.load(); + let transaction = platform.drive.grove.start_transaction(); + platform + .perform_events_on_first_block_of_protocol_change( + &platform_state, + &mut PlatformState::clone(&platform_state), + &block(start + 500, 1), + &transaction, + 14, + latest, + ) + .expect("expected the first block of the latest protocol version"); + platform + .drive + .grove + .commit_transaction(transaction) + .unwrap() + .expect("expected to commit the transaction"); + let mut upgraded_state = platform_state.as_ref().clone(); + upgraded_state.set_current_protocol_version_in_consensus(latest.protocol_version); + upgraded_state.set_next_epoch_protocol_version(latest.protocol_version); + platform.state.store(Arc::new(upgraded_state)); + + let b = contender_transition(&contract, &contender_b, alternate_rank, &mut rng, latest).await; + process_valid_in_epoch(&platform, b, start + 1000, 1, latest); + + let balance_after_second_contender = + balance(&platform, &opening_poll, latest).expect("expected the poll to keep its balance"); + assert!( + balance_after_second_contender > balance_after_first_contender, + "the second contender funds the poll the contest was opened under: \ + {balance_after_first_contender} then {balance_after_second_contender}" + ); + assert_eq!(balance(&platform, &latest_poll, latest), None); + assert_eq!( + vote_poll_end_dates(&platform.drive, latest), + BTreeMap::from([(start + poll_duration, BTreeSet::from([opening_poll_id]))]) + ); + + end_polls_at(&platform, start + poll_duration, 1, latest); + + assert_eq!(balance(&platform, &opening_poll, latest), None); + assert_eq!(balance(&platform, &latest_poll, latest), None); + assert_eq!( + vote_poll_end_dates(&platform.drive, latest), + BTreeMap::new() + ); +} + +#[tokio::test] +async fn should_keep_the_poll_of_a_contest_opened_before_the_upgrade() { + join_after_the_upgrade_a_contest_opened_at_protocol_version_14(INTEGER_CONTRACT, false).await; +} + +#[tokio::test] +async fn should_keep_the_poll_of_a_contest_without_locking_opened_before_the_upgrade() { + join_after_the_upgrade_a_contest_opened_at_protocol_version_14( + NO_LOCKING_INTEGER_CONTRACT, + true, + ) + .await; +} diff --git a/packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-no-locking-with-integer.json b/packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-no-locking-with-integer.json new file mode 100644 index 00000000000..8dec458bc9f --- /dev/null +++ b/packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-no-locking-with-integer.json @@ -0,0 +1,180 @@ +{ + "$formatVersion": "0", + "id": "DWBXe9EXFPHxvbArQgT45uQR5gMmi8dfMpLhR5KSbwnZ", + "ownerId": "2QjL594djCH2NyDsn45vd6yQjEDHupMKo7CEGVTHtQxU", + "version": 1, + "documentSchemas": { + "domain": { + "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": 1, + "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", + "minimum": 0, + "maximum": 1000, + "position": 7, + "description": "An integer that is part of the contested index." + } + }, + "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_all_votes_given_by_identities/v1/mod.rs b/packages/rs-drive/src/drive/votes/cleanup/remove_all_votes_given_by_identities/v1/mod.rs index b271664a849..6087b14fa2f 100644 --- a/packages/rs-drive/src/drive/votes/cleanup/remove_all_votes_given_by_identities/v1/mod.rs +++ b/packages/rs-drive/src/drive/votes/cleanup/remove_all_votes_given_by_identities/v1/mod.rs @@ -310,18 +310,46 @@ mod tests { path } - /// The tree that holds the vote, where the real paths have the trees of a contender. + /// The voting power of the vote, as an evonode's + const VOTE_STRENGTH: i64 = 4; + + /// The sum tree that holds the vote and tallies it, where the real paths have the trees + /// of a contender above it. fn insert_vote_tree(drive: &Drive) { let path = vote_contested_resource_tree_path_vec(); let path: Vec<&[u8]> = path.iter().map(|part| part.as_slice()).collect(); - insert(drive, &path, VOTE_TREE_KEY, Element::empty_tree()); + insert(drive, &path, VOTE_TREE_KEY, Element::empty_sum_tree()); } fn insert_vote(drive: &Drive) { let path = vote_tree_path(); let path: Vec<&[u8]> = path.iter().map(|part| part.as_slice()).collect(); - // A sum item in the real paths; a delete only needs it not to be a tree - insert(drive, &path, &IDENTITY_ID, Element::new_item(vec![1])); + insert( + drive, + &path, + &IDENTITY_ID, + Element::new_sum_item(VOTE_STRENGTH), + ); + } + + /// What the vote tree tallies + fn vote_tally(drive: &Drive) -> i64 { + let path = vote_contested_resource_tree_path_vec(); + let path: Vec<&[u8]> = path.iter().map(|part| part.as_slice()).collect(); + match drive + .grove + .get_raw( + path.as_slice().into(), + VOTE_TREE_KEY, + None, + &PlatformVersion::latest().drive.grove_version, + ) + .unwrap() + .expect("expected the vote tree") + { + Element::SumTree(_, tally, _) => tally, + element => panic!("expected a sum tree, found {element:?}"), + } } fn vote_exists(drive: &Drive) -> bool { @@ -385,11 +413,13 @@ mod tests { insert_vote_tree(&drive); insert_vote(&drive); insert_vote_references(&drive, &[VOTE_ID]); + assert_eq!(vote_tally(&drive), VOTE_STRENGTH); remove_votes(&drive); assert!(!vote_reference_exists(&drive, &VOTE_ID)); assert!(!vote_exists(&drive)); + assert_eq!(vote_tally(&drive), 0); } #[test] @@ -419,11 +449,13 @@ mod tests { insert_vote_tree(&drive); insert_vote(&drive); insert_vote_references(&drive, &[VOTE_ID, OTHER_VOTE_ID]); + assert_eq!(vote_tally(&drive), VOTE_STRENGTH); remove_votes(&drive); assert!(!vote_reference_exists(&drive, &VOTE_ID)); assert!(!vote_reference_exists(&drive, &OTHER_VOTE_ID)); assert!(!vote_exists(&drive)); + assert_eq!(vote_tally(&drive), 0); } } diff --git a/packages/rs-drive/src/drive/votes/fetch/fetch_contest_opening_protocol_version/mod.rs b/packages/rs-drive/src/drive/votes/fetch/fetch_contest_opening_protocol_version/mod.rs new file mode 100644 index 00000000000..63abf747518 --- /dev/null +++ b/packages/rs-drive/src/drive/votes/fetch/fetch_contest_opening_protocol_version/mod.rs @@ -0,0 +1,57 @@ +mod v0; + +use crate::drive::Drive; + +use crate::error::drive::DriveError; +use crate::error::Error; + +use dpp::block::epoch::Epoch; +use dpp::fee::fee_result::FeeResult; +use dpp::version::PlatformVersion; +use dpp::voting::vote_info_storage::contested_document_vote_poll_stored_info::ContestedDocumentVotePollStoredInfo; +use platform_version::version::ProtocolVersion; + +impl Drive { + /// The protocol version a contest that is under way was opened at, when it was opened in + /// an earlier epoch than the block's. + /// + /// A contest's poll is named by its index values as the protocol version it was opened at + /// writes them, and its prefunded balance and end date are kept under that poll. A + /// contender joining it under a later protocol version names the same poll by writing its + /// values the same way, so it reads the version here. + /// + /// # Parameters + /// - `stored_info`: The stored info of the contest. + /// - `epoch`: The epoch of the block, which the read is billed in. + /// - `platform_version`: The platform version. + /// + /// # Returns + /// The fee of the read and the protocol version of the epoch the contest started in. + /// `None`, and no fee, for a contest that is not under way, for one that started in the + /// block's own epoch, which ran the block's protocol version, and before protocol version + /// 15, which reads nothing. + pub fn fetch_contest_opening_protocol_version( + &self, + stored_info: &ContestedDocumentVotePollStoredInfo, + epoch: &Epoch, + platform_version: &PlatformVersion, + ) -> Result<(FeeResult, Option), Error> { + match platform_version + .drive + .methods + .vote + .fetch + .fetch_contest_opening_protocol_version + { + None => Ok((FeeResult::default(), None)), + Some(0) => { + self.fetch_contest_opening_protocol_version_v0(stored_info, epoch, platform_version) + } + Some(version) => Err(Error::Drive(DriveError::UnknownVersionMismatch { + method: "fetch_contest_opening_protocol_version".to_string(), + known_versions: vec![0], + received: version, + })), + } + } +} diff --git a/packages/rs-drive/src/drive/votes/fetch/fetch_contest_opening_protocol_version/v0/mod.rs b/packages/rs-drive/src/drive/votes/fetch/fetch_contest_opening_protocol_version/v0/mod.rs new file mode 100644 index 00000000000..5e4c2e48e0e --- /dev/null +++ b/packages/rs-drive/src/drive/votes/fetch/fetch_contest_opening_protocol_version/v0/mod.rs @@ -0,0 +1,45 @@ +use crate::drive::Drive; +use crate::error::Error; +use dpp::block::epoch::Epoch; +use dpp::fee::fee_result::FeeResult; +use dpp::version::PlatformVersion; +use dpp::voting::vote_info_storage::contested_document_vote_poll_stored_info::{ + ContestedDocumentVotePollStatus, ContestedDocumentVotePollStoredInfo, + ContestedDocumentVotePollStoredInfoV0Getters, +}; +use platform_version::version::ProtocolVersion; + +impl Drive { + /// The protocol version of the epoch a contest under way started in, when that epoch is + /// not the block's + #[inline(always)] + pub(super) fn fetch_contest_opening_protocol_version_v0( + &self, + stored_info: &ContestedDocumentVotePollStoredInfo, + epoch: &Epoch, + platform_version: &PlatformVersion, + ) -> Result<(FeeResult, Option), Error> { + let ContestedDocumentVotePollStatus::Started(start_block) = stored_info.vote_poll_status() + else { + return Ok((FeeResult::default(), None)); + }; + // The block's own epoch runs the block's protocol version, and records it only at the + // end of its first block + if start_block.epoch.index == epoch.index { + return Ok((FeeResult::default(), None)); + } + // An earlier epoch that started a contest had a block, so its first block recorded its + // protocol version, nothing removes that record, and it was committed before this + // block started, so it is read without a transaction + let mut cost_operations = vec![]; + let opening_protocol_version = self.get_epoch_protocol_version_operations( + &start_block.epoch, + None, + &mut cost_operations, + platform_version, + )?; + let fee_result = + self.calculate_fee(None, Some(cost_operations), epoch, platform_version)?; + Ok((fee_result, Some(opening_protocol_version))) + } +} diff --git a/packages/rs-drive/src/drive/votes/fetch/mod.rs b/packages/rs-drive/src/drive/votes/fetch/mod.rs index 8288d67c834..57d9a3edb20 100644 --- a/packages/rs-drive/src/drive/votes/fetch/mod.rs +++ b/packages/rs-drive/src/drive/votes/fetch/mod.rs @@ -1,3 +1,4 @@ +mod fetch_contest_opening_protocol_version; mod fetch_contested_document_vote_poll_contender_count; mod fetch_contested_document_vote_poll_stored_info; mod fetch_identities_voting_for_contenders; diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/v0/transformer.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/v0/transformer.rs index f58a681f521..40031ded19a 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/v0/transformer.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/v0/transformer.rs @@ -132,7 +132,7 @@ impl DocumentCreateTransitionActionV0 { }) }); - let prefunded_voting_balances_by_vote_poll = prefunded_voting_balance + let mut prefunded_voting_balances_by_vote_poll = prefunded_voting_balance .as_ref() .filter(|_| decision_proposal.is_none()) .map(|(index_name, credits)| { @@ -143,9 +143,10 @@ impl DocumentCreateTransitionActionV0 { document_type.name() )), )?; - // Identifier values are written one way from protocol version 14, so every - // contender of a contest names it with the same poll and prefunds the same - // balance; before 14 they are taken as given, as they always were + // Every contender of a contest names it with the same poll and prefunds the + // same balance: from protocol version 15 every index value is written the one + // way its property's type keys it, at protocol version 14 identifier values + // alone are written one way, and before 14 the values are taken as given let index_values = index.extract_contested_values( &data, document_type.flattened_properties(), @@ -170,7 +171,7 @@ impl DocumentCreateTransitionActionV0 { let (current_store_contest_info, should_store_contest_info) = if let Some((contested_document_resource_vote_poll, _)) = - &prefunded_voting_balances_by_vote_poll + &mut prefunded_voting_balances_by_vote_poll { let (fetch_fee_result, maybe_current_store_contest_info) = drive .fetch_contested_document_vote_poll_stored_info( @@ -183,6 +184,51 @@ impl DocumentCreateTransitionActionV0 { fee_result.checked_add_assign(fetch_fee_result.ok_or(Error::Drive( DriveError::CorruptedCodeExecution("expected fee result"), ))?)?; + + // A contest under way keeps the poll it was opened under: its prefunded balance + // and its end date are kept under that poll. A contender joining it under a + // later protocol version, which writes index values another way, names that + // poll by writing its values as the version the contest was opened at did. The + // contest is found at the path of its index keys, which every version writes + // alike. Only values this version does not write as they were sent can be + // written another way by an earlier one, so nothing is read for the others. + // In place: inert before protocol version 15, where + // `fetch_contest_opening_protocol_version` is `None` and reads nothing. + if let Some(current_store_contest_info) = &maybe_current_store_contest_info { + let index = document_type_indexes + .get(&contested_document_resource_vote_poll.index_name) + .ok_or_else(|| { + ProtocolError::UnknownContestedIndexResolution(format!( + "index {} not found on document type {}", + contested_document_resource_vote_poll.index_name, + document_type.name() + )) + })?; + if contested_document_resource_vote_poll.index_values + != index.extract_values(&data) + { + let (read_fee_result, opening_protocol_version) = drive + .fetch_contest_opening_protocol_version( + current_store_contest_info, + &block_info.epoch, + platform_version, + )?; + fee_result.checked_add_assign(read_fee_result)?; + if let Some(opening_protocol_version) = opening_protocol_version + .filter(|version| *version != platform_version.protocol_version) + { + let opening_platform_version = + PlatformVersion::get(opening_protocol_version) + .map_err(ProtocolError::from)?; + contested_document_resource_vote_poll.index_values = index + .extract_contested_values( + &data, + document_type.flattened_properties(), + opening_platform_version, + )?; + } + } + } let should_store_contest_info = if maybe_current_store_contest_info.is_none() { // We are starting a new contest Some(ContestedDocumentVotePollStoredInfo::new( diff --git a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/mod.rs b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/mod.rs index f0e8edf2ce7..2c3b236c0eb 100644 --- a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/mod.rs +++ b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/mod.rs @@ -112,10 +112,11 @@ pub struct DocumentTypeMethodVersions { /// keyword: the method returns an empty result there, so the shipped /// `DataContract::validate_document_properties` 0 that calls it is inert. pub validate_property_constraints: OptionalFeatureVersion, - /// `Index::extract_contested_values`: writes an identifier property given as bytes or as - /// an array of byte values as `Value::Identifier` in a contest's index values, so every - /// contender names one contest with one poll. `None` on versions that predate it, where - /// the values are taken as given. + /// `Index::extract_contested_values`: writes a contest's index values one way, so every + /// contender names one contest with one poll. Generation 0 writes an identifier property + /// given as bytes or as an array of byte values as `Value::Identifier`; generation 1 writes + /// the value of every property the one way its type keys it. `None` on versions that + /// predate it, where the values are taken as given. pub canonical_contested_index_values: OptionalFeatureVersion, /// `fill_generated_properties`: writes each `generatedFrom` property a /// created or replaced document leaves out, generated from its params, diff --git a/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/mod.rs b/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/mod.rs index ca2addb4604..7daea78f92f 100644 --- a/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/mod.rs +++ b/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/mod.rs @@ -46,6 +46,9 @@ pub struct DriveVoteFetchMethodVersions { pub fetch_identity_contested_resource_vote: FeatureVersion, /// Read by the contested document create state validation v2 (protocol version 14) only. pub fetch_contested_document_vote_poll_contender_count: FeatureVersion, + /// `None` before protocol version 15, where a contested create names its poll as the + /// block's protocol version writes its index values, whatever version opened the contest. + pub fetch_contest_opening_protocol_version: OptionalFeatureVersion, } #[derive(Clone, Debug, Default)] diff --git a/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v1.rs b/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v1.rs index 374623fd85a..5bc1549b8ab 100644 --- a/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v1.rs +++ b/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v1.rs @@ -36,6 +36,7 @@ pub const DRIVE_VOTE_METHOD_VERSIONS_V1: DriveVoteMethodVersions = DriveVoteMeth fetch_contested_document_vote_poll_stored_info: 0, fetch_identity_contested_resource_vote: 0, fetch_contested_document_vote_poll_contender_count: 0, + fetch_contest_opening_protocol_version: None, }, yes_no: DriveVoteYesNoMethodVersions { open_yes_no_vote_poll: None, diff --git a/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v2.rs b/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v2.rs index ac028959b2f..bd85cc53c38 100644 --- a/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v2.rs +++ b/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v2.rs @@ -36,6 +36,7 @@ pub const DRIVE_VOTE_METHOD_VERSIONS_V2: DriveVoteMethodVersions = DriveVoteMeth fetch_contested_document_vote_poll_stored_info: 0, fetch_identity_contested_resource_vote: 0, fetch_contested_document_vote_poll_contender_count: 0, + fetch_contest_opening_protocol_version: None, }, yes_no: DriveVoteYesNoMethodVersions { open_yes_no_vote_poll: None, diff --git a/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v3.rs b/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v3.rs index 776a16cabcd..9d5fe61f49e 100644 --- a/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v3.rs +++ b/packages/rs-platform-version/src/version/drive_versions/drive_vote_method_versions/v3.rs @@ -44,6 +44,7 @@ pub const DRIVE_VOTE_METHOD_VERSIONS_V3: DriveVoteMethodVersions = DriveVoteMeth fetch_contested_document_vote_poll_stored_info: 0, fetch_identity_contested_resource_vote: 0, fetch_contested_document_vote_poll_contender_count: 0, + fetch_contest_opening_protocol_version: None, }, yes_no: DriveVoteYesNoMethodVersions { open_yes_no_vote_poll: None, 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 620f642be66..7675e0a8c6f 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 @@ -1,7 +1,8 @@ use crate::version::drive_versions::drive_vote_method_versions::v3::DRIVE_VOTE_METHOD_VERSIONS_V3; use crate::version::drive_versions::drive_vote_method_versions::{ DriveVoteCleanupMethodVersions, DriveVoteContestedResourceInsertMethodVersions, - DriveVoteInsertMethodVersions, DriveVoteMethodVersions, DriveVoteYesNoMethodVersions, + DriveVoteFetchMethodVersions, DriveVoteInsertMethodVersions, DriveVoteMethodVersions, + DriveVoteYesNoMethodVersions, }; /// Drive vote method versions 4. Introduced in protocol version 15 with the yes/no poll @@ -20,6 +21,10 @@ use crate::version::drive_versions::drive_vote_method_versions::{ /// when the batch already queues an insert of the end date's tree with other storage flags (a /// contest and a yes/no poll opening sharing an end date), where 0 queued the tree twice. /// +/// * `fetch.fetch_contest_opening_protocol_version` is `Some(0)`: a contested create joining a +/// contest opened in an earlier epoch reads the protocol version that epoch ran, and names +/// its poll as that version writes its index values (`None`, not read, before). +/// /// Everything else matches `DRIVE_VOTE_METHOD_VERSIONS_V3`. pub const DRIVE_VOTE_METHOD_VERSIONS_V4: DriveVoteMethodVersions = DriveVoteMethodVersions { insert: DriveVoteInsertMethodVersions { @@ -46,5 +51,9 @@ pub const DRIVE_VOTE_METHOD_VERSIONS_V4: DriveVoteMethodVersions = DriveVoteMeth remove_yes_no_vote_poll_votes_operations: Some(0), remove_yes_no_vote_references_given_by_identity: Some(0), }, + fetch: DriveVoteFetchMethodVersions { + fetch_contest_opening_protocol_version: Some(0), + ..DRIVE_VOTE_METHOD_VERSIONS_V3.fetch + }, ..DRIVE_VOTE_METHOD_VERSIONS_V3 }; diff --git a/packages/rs-platform-version/src/version/v15.rs b/packages/rs-platform-version/src/version/v15.rs index ecdf5fec4bc..e536725804f 100644 --- a/packages/rs-platform-version/src/version/v15.rs +++ b/packages/rs-platform-version/src/version/v15.rs @@ -801,8 +801,17 @@ pub const PROTOCOL_VERSION_15: ProtocolVersion = 15; /// name two polls of one contest. A masternode vote names its poll as sent, at every /// version, and is refused unless a prefunded balance is held under that poll /// (`PrefundedSpecializedBalanceNotFoundError`, 40401), so a voter sends the values as -/// the contest query returns them. A contest opened earlier keeps the polls its -/// contenders named. Protocol v14 keeps generation 0. +/// the contest query returns them. A contest under way keeps the poll it was opened +/// under, which names its prefunded balance and its end date: a contender joining a +/// contest opened in an earlier epoch reads the protocol version that epoch ran +/// (`fetch_contest_opening_protocol_version` 0, `DRIVE_VOTE_METHOD_VERSIONS_V4`, `None` +/// before) and writes its index values as that version does, so a contest opened at +/// protocol version 14 is named as generation 0 names it until it ends. The read is +/// billed, and made only for a create whose values this version does not write as sent. +/// Document create advanced structure validation 1 compares the poll a create names +/// with the one its document type expects by contract, document type and index name (in +/// place: the index values of both are read from the same document, so before this +/// version polls of one index are equal). Protocol v14 keeps generation 0. 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); create_initial_state_structure 5 adds the token marketplace escrow trees; calculate_total_tokens_balance 2 counts escrowed tokens; the escrow primitives; the identity balance, token balance, prefunded specialized balance and contract fee pot estimations (for_balances 1, for_token_balances 1, estimated_cost_for_prefunded_specialized_balance_update 2, add_estimation_costs_for_contract_fee_pot_update 1) keep a deeper layer description (note 17); 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: add_indices_for_top_index_level_for_contract_operations 3 writes no entry in an expired time range bucket (note 36) From 9a76ce1aa8c10c5815fb5e9db58ed1da2d77b1e9 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Thu, 12 Nov 2026 18:38:56 +0700 Subject: [PATCH 3/3] fix(drive-abci): keep protocol version 14's whole-poll comparison of a contested create Document create advanced structure validation 1 compares the poll a contested create names with the poll its document type expects as whole values again, as it did. Its body moved, unchanged, into a method that takes the comparison, so generation 2 (protocol version 15) compares the polls by contract, document type and index name, which a contender joining a contest opened at an earlier protocol version needs. A poll holding a NaN index value is not equal to itself, so the two comparisons give such a create different errors, and protocol version 14's has to stay. A test pins it. The tests of this module run on mainnet's rules, where the comparison is made. Co-Authored-By: Claude Fable 5.2 --- .../advanced_structure_v1/mod.rs | 67 +++++-- .../advanced_structure_v2/mod.rs | 14 +- .../contest_index_value_forms_tests.rs | 71 +++++-- ...ct-contested-unique-index-with-number.json | 178 ++++++++++++++++++ .../drive_abci_validation_versions/v11.rs | 2 +- .../rs-platform-version/src/version/v15.rs | 9 +- 6 files changed, 311 insertions(+), 30 deletions(-) create mode 100644 packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-number.json diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v1/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v1/mod.rs index 1b7e6b466d2..94a13adabe4 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v1/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v1/mod.rs @@ -21,6 +21,21 @@ use drive::state_transition_action::batch::batched_transition::document_transiti use dpp::version::PlatformVersion; use crate::error::Error; +/// How the poll a contested create names is compared with the poll its document type expects +/// of its data. +#[derive(Clone, Copy)] +pub(in crate::execution::validation::state_transition::state_transitions::batch::action_validation) +enum ContestPollComparison { + /// The whole polls, index values included: version 1. + Whole, + /// What names the index: the contract, the document type and the index name. Version 2, + /// where a contender joining a contest opened at an earlier protocol version has its index + /// values written as that version wrote them + /// (`Drive::fetch_contest_opening_protocol_version`), which the expected poll, written by + /// the block's protocol version, does not. + ByIndex, +} + pub(in crate::execution::validation::state_transition::state_transitions::batch::action_validation) trait DocumentCreateTransitionActionStructureValidationV1 { fn validate_structure_v1( &self, @@ -29,14 +44,45 @@ pub(in crate::execution::validation::state_transition::state_transitions::batch: network: Network, platform_version: &PlatformVersion, ) -> Result; + + /// Version 1's checks, comparing the poll a contested create names with the expected one + /// as `contest_poll_comparison` tells. + fn validate_structure_v1_comparing_contest_polls( + &self, + owner_id: Identifier, + block_info: &BlockInfo, + network: Network, + contest_poll_comparison: ContestPollComparison, + platform_version: &PlatformVersion, + ) -> Result; } impl DocumentCreateTransitionActionStructureValidationV1 for DocumentCreateTransitionAction { + // In place, a refactor with the same output: the body moved, unchanged, to + // `validate_structure_v1_comparing_contest_polls`, which compares the polls whole here as + // this did. fn validate_structure_v1( &self, owner_id: Identifier, block_info: &BlockInfo, network: Network, platform_version: &PlatformVersion, + ) -> Result { + self.validate_structure_v1_comparing_contest_polls( + owner_id, + block_info, + network, + ContestPollComparison::Whole, + platform_version, + ) + } + + fn validate_structure_v1_comparing_contest_polls( + &self, + owner_id: Identifier, + block_info: &BlockInfo, + network: Network, + contest_poll_comparison: ContestPollComparison, + platform_version: &PlatformVersion, ) -> Result { let contract_fetch_info = self.base().data_contract_fetch_info(); let data_contract = &contract_fetch_info.contract; @@ -78,18 +124,15 @@ impl DocumentCreateTransitionActionStructureValidationV1 for DocumentCreateTrans // indexes, so the contest would be funded, resolved and cleaned up under a // vote poll that does not describe the contest that was actually created. let provided: ContestedDocumentResourceVotePoll = provided.into(); - // In place: the polls are compared by what names the index, where they were - // compared whole. The index values of both are read from this document's - // data, so wherever both are written by the block's protocol version, as - // they always are before protocol version 15, polls of one index are - // equal. From 15 a contender joining a contest opened at an earlier - // protocol version writes its values as that version did - // (`Drive::fetch_contest_opening_protocol_version`), and the expected poll - // does not. - if provided.contract_id != expected.contract_id - || provided.document_type_name != expected.document_type_name - || provided.index_name != expected.index_name - { + let names_another_poll = match contest_poll_comparison { + ContestPollComparison::Whole => provided != expected, + ContestPollComparison::ByIndex => { + provided.contract_id != expected.contract_id + || provided.document_type_name != expected.document_type_name + || provided.index_name != expected.index_name + } + }; + if names_another_poll { return Ok(SimpleConsensusValidationResult::new_with_error( DocumentContestIndexMismatchError::new( self.base().id(), diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v2/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v2/mod.rs index e35438a37a2..b115a36928b 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v2/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v2/mod.rs @@ -12,7 +12,7 @@ use dpp::voting::vote_polls::yes_no_vote_poll::YesNoVotePoll; use drive::state_transition_action::batch::batched_transition::document_transition::document_base_transition_action::DocumentBaseTransitionActionAccessorsV0; use drive::state_transition_action::batch::batched_transition::document_transition::document_create_transition_action::{DocumentCreateTransitionAction, DocumentCreateTransitionActionAccessorsV0}; use crate::error::Error; -use crate::execution::validation::state_transition::batch::action_validation::document::document_create_transition_action::advanced_structure_v1::DocumentCreateTransitionActionStructureValidationV1; +use crate::execution::validation::state_transition::batch::action_validation::document::document_create_transition_action::advanced_structure_v1::{ContestPollComparison, DocumentCreateTransitionActionStructureValidationV1}; pub(in crate::execution::validation::state_transition::state_transitions::batch::action_validation) trait DocumentCreateTransitionActionStructureValidationV2 { fn validate_structure_v2( @@ -30,6 +30,10 @@ impl DocumentCreateTransitionActionStructureValidationV2 for DocumentCreateTrans /// the system limits, and it must end one to four weeks after the block. All three are on /// the transition, judged against the block as v1's property rules are, so check_tx refuses /// what a block would. + /// + /// Version 1's checks compare the poll a contested create names with the poll its document + /// type expects by what names the index, where version 1 compares them whole + /// ([`ContestPollComparison::ByIndex`]). fn validate_structure_v2( &self, owner_id: Identifier, @@ -37,7 +41,13 @@ impl DocumentCreateTransitionActionStructureValidationV2 for DocumentCreateTrans network: Network, platform_version: &PlatformVersion, ) -> Result { - let result = self.validate_structure_v1(owner_id, block_info, network, platform_version)?; + let result = self.validate_structure_v1_comparing_contest_polls( + owner_id, + block_info, + network, + ContestPollComparison::ByIndex, + platform_version, + )?; if !result.is_valid() { return Ok(result); } diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_index_value_forms_tests.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_index_value_forms_tests.rs index a867068b24c..5387ccf42fe 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_index_value_forms_tests.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/contest_index_value_forms_tests.rs @@ -5,6 +5,7 @@ //! values it sends. A contest opened at an earlier protocol version keeps the poll it was //! opened under: a contender joining it later writes its values as that version did. +use crate::config::PlatformConfig; use crate::execution::validation::state_transition::state_transitions::tests::{ setup_identity, setup_masternode_voting_identity, }; @@ -19,6 +20,7 @@ use dpp::block::extended_block_info::v0::ExtendedBlockInfoV0; use dpp::consensus::state::state_error::StateError; use dpp::consensus::ConsensusError; use dpp::dash_to_credits; +use dpp::dashcore::Network; use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; use dpp::data_contract::document_type::random_document::{ @@ -57,10 +59,27 @@ const INTEGER_CONTRACT: &str = "tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-integer.json"; /// The same fixture with the contested index resolved without locking. const NO_LOCKING_INTEGER_CONTRACT: &str = "tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-no-locking-with-integer.json"; +/// The same fixture with `rank` a number. +const NUMBER_CONTRACT: &str = + "tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-number.json"; const NAME: &str = "quantum"; type IdentityInfo = (Identity, SimpleSigner, IdentityPublicKey); +/// A platform starting at `protocol_version`, on mainnet: on testnet a contested create's poll +/// is not checked against its document before epoch 2080. +fn platform_at(protocol_version: u32) -> TempPlatform { + TestPlatformBuilder::new() + .with_config(PlatformConfig { + network: Network::Mainnet, + ..Default::default() + }) + .with_initial_protocol_version(protocol_version) + .build_with_mock_rpc() + .with_no_core_masternodes() + .set_genesis_state() +} + fn block(time_ms: TimestampMillis, epoch_index: u16) -> BlockInfo { BlockInfo { time_ms, @@ -358,10 +377,7 @@ struct Contest { } async fn open_contest(platform_version: &PlatformVersion) -> Contest { - let mut platform = TestPlatformBuilder::new() - .with_latest_protocol_version() - .build_with_mock_rpc() - .set_genesis_state(); + let mut platform = platform_at(platform_version.protocol_version); let mut rng = StdRng::seed_from_u64(0x5EED_0F02); let owner = setup_identity(&mut platform, rng.gen(), dash_to_credits!(0.5)); let contender_a = setup_identity(&mut platform, rng.gen(), dash_to_credits!(1.0)); @@ -509,11 +525,7 @@ async fn join_after_the_upgrade_a_contest_opened_at_protocol_version_14( ) { let version_14 = PlatformVersion::get(14).expect("expected protocol version 14"); let latest = PlatformVersion::latest(); - let mut platform = TestPlatformBuilder::new() - .with_initial_protocol_version(14) - .build_with_mock_rpc() - .with_no_core_masternodes() - .set_genesis_state(); + let mut platform = platform_at(14); let mut rng = StdRng::seed_from_u64(0x5EED_0F03); let owner = setup_identity(&mut platform, rng.gen(), dash_to_credits!(0.5)); let contender_a = setup_identity(&mut platform, rng.gen(), dash_to_credits!(1.0)); @@ -539,11 +551,11 @@ async fn join_after_the_upgrade_a_contest_opened_at_protocol_version_14( .dpp .validation .voting - .allow_other_contenders_time_testing_ms; + .allow_other_contenders_time_mainnet_ms; let poll_duration = latest .dpp .voting_versions - .default_vote_poll_time_duration_test_network_ms; + .default_vote_poll_time_duration_mainnet_ms; let start: TimestampMillis = 1_000_000; let a = contender_transition( @@ -630,3 +642,40 @@ async fn should_keep_the_poll_of_a_contest_without_locking_opened_before_the_upg ) .await; } + +/// Protocol version 14 compares the poll a contested create names with the poll its document +/// type expects as whole values, and a poll holding a NaN is not equal to itself: such a create +/// is refused with `DocumentContestIndexMismatchError`, and stays so. +#[tokio::test] +async fn should_refuse_a_contested_create_with_a_nan_index_value_as_protocol_version_14_does() { + let version_14 = PlatformVersion::get(14).expect("expected protocol version 14"); + let mut platform = platform_at(14); + let mut rng = StdRng::seed_from_u64(0x5EED_0F04); + let owner = setup_identity(&mut platform, rng.gen(), dash_to_credits!(0.5)); + let contender = setup_identity(&mut platform, rng.gen(), dash_to_credits!(1.0)); + let contract = setup_contract( + &platform.drive, + NUMBER_CONTRACT, + None, + Some(owner.0.id().to_buffer()), + None::, + None, + Some(version_14), + ); + + let create = contender_transition( + &contract, + &contender, + Value::Float(f64::NAN), + &mut rng, + version_14, + ) + .await; + assert_matches!( + process(&platform, &[create], 1_000_000, 0, version_14).as_slice(), + [StateTransitionExecutionResult::PaidConsensusError { + error: ConsensusError::StateError(StateError::DocumentContestIndexMismatchError(_)), + .. + }] + ); +} diff --git a/packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-number.json b/packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-number.json new file mode 100644 index 00000000000..ec94002cac3 --- /dev/null +++ b/packages/rs-drive-abci/tests/supporting_files/contract/dpns/dpns-contract-contested-unique-index-with-number.json @@ -0,0 +1,178 @@ +{ + "$formatVersion": "0", + "id": "DWBXe9EXFPHxvbArQgT45uQR5gMmi8dfMpLhR5KSbwnZ", + "ownerId": "2QjL594djCH2NyDsn45vd6yQjEDHupMKo7CEGVTHtQxU", + "version": 1, + "documentSchemas": { + "domain": { + "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": "number", + "position": 7, + "description": "A number that is part of the contested index." + } + }, + "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-platform-version/src/version/drive_abci_versions/drive_abci_validation_versions/v11.rs b/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_validation_versions/v11.rs index e679b035be7..597d4537f22 100644 --- a/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_validation_versions/v11.rs +++ b/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_validation_versions/v11.rs @@ -114,7 +114,7 @@ pub const DRIVE_ABCI_VALIDATION_VERSIONS_V11: DriveAbciValidationVersions = batch_state_transition: DriveAbciDocumentsStateTransitionValidationVersions { advanced_structure: 2, // a tradeable token must be transferable, checked in check_tx too document_reference_validation: 1, // a consumed commitment keeps what its lookup read - document_create_transition_structure_validation: 2, // a decision proposal states its fund, a rule within the limits and an end date one to four weeks away + document_create_transition_structure_validation: 2, // a decision proposal states its fund, a rule within the limits and an end date one to four weeks away; the poll a contested create names is compared with the expected one by what names the index document_create_transition_state_validation: 3, // a non-contested create cannot take the values of a live contest its index values do not decide data_triggers: DriveAbciValidationDataTriggerAndBindingVersions { bindings: 3, // no DashPay bindings (DashPay v3 declares their checks); the token market contract's orders are written by the marketplace transitions only diff --git a/packages/rs-platform-version/src/version/v15.rs b/packages/rs-platform-version/src/version/v15.rs index e536725804f..7377e01d7c0 100644 --- a/packages/rs-platform-version/src/version/v15.rs +++ b/packages/rs-platform-version/src/version/v15.rs @@ -808,10 +808,11 @@ pub const PROTOCOL_VERSION_15: ProtocolVersion = 15; /// before) and writes its index values as that version does, so a contest opened at /// protocol version 14 is named as generation 0 names it until it ends. The read is /// billed, and made only for a create whose values this version does not write as sent. -/// Document create advanced structure validation 1 compares the poll a create names -/// with the one its document type expects by contract, document type and index name (in -/// place: the index values of both are read from the same document, so before this -/// version polls of one index are equal). Protocol v14 keeps generation 0. +/// Document create advanced structure validation 2 +/// (`DRIVE_ABCI_VALIDATION_VERSIONS_V11`) compares the poll a create +/// names with the one its document type expects by contract, document type and index +/// name, where generation 1, which protocol v14 keeps, compares them whole. Protocol +/// v14 keeps generation 0 of `canonical_contested_index_values`. 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); create_initial_state_structure 5 adds the token marketplace escrow trees; calculate_total_tokens_balance 2 counts escrowed tokens; the escrow primitives; the identity balance, token balance, prefunded specialized balance and contract fee pot estimations (for_balances 1, for_token_balances 1, estimated_cost_for_prefunded_specialized_balance_update 2, add_estimation_costs_for_contract_fee_pot_update 1) keep a deeper layer description (note 17); 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: add_indices_for_top_index_level_for_contract_operations 3 writes no entry in an expired time range bucket (note 36)