From 9e29b1506d1f0326f7f7603da066f2f2916cbe13 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Sat, 26 Sep 2026 09:10:48 +0700 Subject: [PATCH] fix(drive-abci)!: refuse bytes after a state transition (PV14) decode_raw_state_transitions v0 decodes with StateTransition::deserialize_from_bytes_untrusted_in_version, which ignores bytes left over after the value, so a transition with bytes appended executed as the original under another transaction hash. v1 decodes with the new StateTransition::deserialize_from_bytes_untrusted_exact_in_version: left over bytes are an InvalidEncoding (SerializedObjectParsingError), refused unpaid in check_tx and block processing. It also reports a transition whose version is not active as StateTransitionNotActiveError (the arm #4993 adds to v0). Only DRIVE_ABCI_METHOD_VERSIONS_V10 (protocol version 14) selects v1; v0's tests are pinned to 13. Co-Authored-By: Claude Opus 5.5 --- packages/rs-dpp/src/state_transition/mod.rs | 97 +++++- .../src/execution/check_tx/v0/mod.rs | 186 ++++++++++- .../decode_raw_state_transitions/mod.rs | 88 ++++- .../decode_raw_state_transitions/v0/mod.rs | 14 +- .../decode_raw_state_transitions/v1/mod.rs | 309 ++++++++++++++++++ .../drive_abci_method_versions/v10.rs | 3 +- .../rs-platform-version/src/version/v14.rs | 10 + 7 files changed, 692 insertions(+), 15 deletions(-) create mode 100644 packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/decode_raw_state_transitions/v1/mod.rs diff --git a/packages/rs-dpp/src/state_transition/mod.rs b/packages/rs-dpp/src/state_transition/mod.rs index af8612a1f0d..cebaefab47b 100644 --- a/packages/rs-dpp/src/state_transition/mod.rs +++ b/packages/rs-dpp/src/state_transition/mod.rs @@ -1021,19 +1021,46 @@ fn batch_carries_a_version_2_document_base(batch_transition: &BatchTransition) - } impl StateTransition { - #[allow(unused_variables)] + /// Decodes a transition from bytes that arrived from outside this node and refuses one + /// whose version is not active at `platform_version`. Bytes left over after the transition + /// are ignored; [`Self::deserialize_from_bytes_untrusted_exact_in_version`] refuses them. pub fn deserialize_from_bytes_untrusted_in_version( bytes: &[u8], platform_version: &PlatformVersion, + ) -> Result { + Self::decode_untrusted_in_version( + bytes, + StateTransition::deserialize_from_bytes_untrusted, + platform_version, + ) + } + + /// [`Self::deserialize_from_bytes_untrusted_in_version`] that also refuses bytes left over + /// after the transition, as a `PlatformDeserializationError`. Leftover bytes are checked + /// before the transition's active version range. + pub fn deserialize_from_bytes_untrusted_exact_in_version( + bytes: &[u8], + platform_version: &PlatformVersion, + ) -> Result { + Self::decode_untrusted_in_version( + bytes, + StateTransition::deserialize_from_bytes_untrusted_exact, + platform_version, + ) + } + + #[allow(unused_variables)] + fn decode_untrusted_in_version( + bytes: &[u8], + decode: fn(&[u8]) -> Result, + platform_version: &PlatformVersion, ) -> Result { let max_value_depth = platform_version .system_limits .max_document_value_depth .map(usize::from); let state_transition = - platform_value::with_value_decode_depth_limit(max_value_depth, || { - StateTransition::deserialize_from_bytes_untrusted(bytes) - })?; + platform_value::with_value_decode_depth_limit(max_value_depth, || decode(bytes))?; #[cfg(all(feature = "state-transitions", feature = "validation"))] { let active_version_range = state_transition.active_version_range(); @@ -2700,6 +2727,48 @@ mod tests { assert_eq!(original, restored); } + #[test] + fn should_refuse_bytes_after_the_transition_only_in_the_exact_in_version_decoder() { + use crate::serialization::PlatformSerializable; + let original = sample_transfer_st(); + let bytes = + PlatformSerializable::serialize_to_bytes(&original).expect("serialize succeeds"); + let platform_version = PlatformVersion::latest(); + + assert_eq!( + StateTransition::deserialize_from_bytes_untrusted_exact_in_version( + &bytes, + platform_version + ) + .expect("the exact bytes decode"), + original + ); + + for left_over in [1usize, 100] { + let mut padded = bytes.clone(); + padded.extend(std::iter::repeat_n(0xAB, left_over)); + + assert_eq!( + StateTransition::deserialize_from_bytes_untrusted_in_version( + &padded, + platform_version + ) + .expect("the loose decoder ignores the suffix"), + original + ); + match StateTransition::deserialize_from_bytes_untrusted_exact_in_version( + &padded, + platform_version, + ) { + Err(ProtocolError::PlatformDeserializationError(message)) => assert!( + message.contains(&format!("{left_over} bytes left over")), + "unexpected message: {message}" + ), + other => panic!("expected a deserialization error, got {other:?}"), + } + } + } + #[test] fn test_transaction_id_is_deterministic() { let st = sample_transfer_st(); @@ -3792,6 +3861,26 @@ mod tests { } } + /// The exact decoder keeps the active version check: exact bytes of a transition that is + /// not active yet are refused as not active, not as left over bytes. + #[cfg(all(feature = "state-transitions", feature = "validation"))] + #[test] + fn should_refuse_an_inactive_transition_in_the_exact_in_version_decoder() { + use crate::serialization::PlatformSerializable; + + // ShieldedTransfer has active_version_range = 12..=LATEST_VERSION. + let bytes = PlatformSerializable::serialize_to_bytes(&sample_shielded_transfer_st()) + .expect("serialize succeeds"); + let low_version = PlatformVersion::get(1).expect("platform version 1 exists"); + + assert!(matches!( + StateTransition::deserialize_from_bytes_untrusted_exact_in_version(&bytes, low_version), + Err(ProtocolError::StateTransitionError( + crate::state_transition::errors::StateTransitionError::StateTransitionIsNotActiveError { .. } + )) + )); + } + // A version 1 data contract create carries contract groups, which only exist from // protocol version 14. Below that a node must reject it rather than create the // contract and drop the group data. diff --git a/packages/rs-drive-abci/src/execution/check_tx/v0/mod.rs b/packages/rs-drive-abci/src/execution/check_tx/v0/mod.rs index da4dbce479c..d6ea3b552b8 100644 --- a/packages/rs-drive-abci/src/execution/check_tx/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/check_tx/v0/mod.rs @@ -246,14 +246,17 @@ where #[cfg(test)] mod tests { use crate::config::{PlatformConfig, PlatformTestConfig}; + use crate::execution::check_tx::CheckTxResult; use crate::platform_types::event_execution_result::EventExecutionResult::{ SuccessfulPaidExecution, UnpaidConsensusExecutionError, UnsuccessfulPaidExecution, }; use crate::platform_types::platform_state::PlatformStateV0Methods; - use crate::test::helpers::setup::TestPlatformBuilder; + use crate::rpc::core::MockCoreRPCLike; + use crate::test::helpers::setup::{TempPlatform, TestPlatformBuilder}; use dpp::block::block_info::BlockInfo; use dpp::consensus::basic::BasicError; use dpp::consensus::signature::SignatureError; + use dpp::validation::ValidationResult; use simple_signer::signer::SimpleSigner; use dpp::consensus::ConsensusError; @@ -289,7 +292,7 @@ mod tests { get_dashpay_contract_fixture, get_dpns_data_contract_fixture, instant_asset_lock_proof_fixture, }; - use dpp::version::PlatformVersion; + use dpp::version::{PlatformVersion, ProtocolVersion}; use crate::execution::check_tx::CheckTxLevel::{FirstTimeCheck, Recheck}; use crate::execution::validation::state_transition::tests::{ @@ -4543,4 +4546,183 @@ mod tests { .expect("expected to check tx"); assert!(recheck_result.is_valid()); } + + /// A platform at `protocol_version` holding one identity, and that identity's serialized, + /// signed DashPay contract create. + fn platform_with_signed_data_contract_create( + protocol_version: ProtocolVersion, + ) -> (TempPlatform, Vec, Identifier) { + let platform = TestPlatformBuilder::new() + .with_initial_protocol_version(protocol_version) + .build_with_mock_rpc(); + let platform_version = + PlatformVersion::get(protocol_version).expect("expected a platform version"); + + let (key, private_key) = IdentityPublicKey::random_ecdsa_critical_level_authentication_key( + 1, + Some(1), + platform_version, + ) + .expect("expected to get key pair"); + + platform + .drive + .create_initial_state_structure(None, platform_version) + .expect("expected to create state structure"); + let identity: Identity = IdentityV0 { + id: Identifier::new([7; 32]), + public_keys: BTreeMap::from([(1, key.clone())]), + balance: 25_000_000_000, // 0.25 Dash + revision: 0, + } + .into(); + let identity_id = identity.id(); + + let dashpay = get_dashpay_contract_fixture(Some(identity_id), 1, protocol_version); + let mut create_contract_state_transition: StateTransition = dashpay + .try_into_platform_versioned(platform_version) + .expect("expected a state transition"); + create_contract_state_transition + .sign(&key, private_key.as_slice(), &NativeBlsModule) + .expect("expected to sign transition"); + let serialized = create_contract_state_transition + .serialize_to_bytes() + .expect("serialized state transition"); + platform + .drive + .add_new_identity( + identity, + false, + &BlockInfo::default(), + true, + None, + platform_version, + ) + .expect("expected to insert identity"); + + (platform, serialized, identity_id) + } + + /// `raw` followed by `left_over` bytes. + fn with_left_over_bytes(raw: &[u8], left_over: usize) -> Vec { + let mut padded = raw.to_vec(); + padded.extend(std::iter::repeat_n(0u8, left_over)); + padded + } + + /// Runs `raw` through `check_tx` and, in a transaction that is dropped afterwards, through + /// block processing, returning the check result, the execution result and the identity's + /// balance after processing. + fn check_and_process( + platform: &TempPlatform, + raw: &[u8], + identity_id: Identifier, + platform_version: &PlatformVersion, + ) -> ( + ValidationResult, + StateTransitionExecutionResult, + u64, + ) { + let platform_state = platform.state.load(); + let platform_ref = PlatformRef { + drive: &platform.drive, + state: &platform_state, + config: &platform.config, + core_rpc: &platform.core_rpc, + }; + + let check_result = platform + .check_tx(raw, FirstTimeCheck, &platform_ref, platform_version) + .expect("expected to check tx"); + + let transaction = platform.drive.grove.start_transaction(); + let processing_result = platform + .platform + .process_raw_state_transitions( + &[raw.to_vec()], + &platform_state, + &BlockInfo::default(), + &transaction, + platform_version, + false, + None, + ) + .expect("expected to process state transition"); + let balance = platform + .drive + .fetch_identity_balance( + identity_id.to_buffer(), + Some(&transaction), + platform_version, + ) + .expect("expected to fetch the balance") + .expect("expected the identity to exist"); + + let [execution_result] = processing_result.execution_results().as_slice() else { + panic!("expected one execution result"); + }; + (check_result, execution_result.clone(), balance) + } + + // Each variant gets its own platform: processing a create caches the contract in Drive's + // block cache, which outlives the dropped transaction. + #[test] + fn should_refuse_bytes_after_a_state_transition_unpaid_from_protocol_version_14() { + let platform_version = PlatformVersion::latest(); + let (platform, serialized, identity_id) = + platform_with_signed_data_contract_create(platform_version.protocol_version); + + let (check_result, execution_result, _) = + check_and_process(&platform, &serialized, identity_id, platform_version); + assert_eq!(check_result.errors.as_slice(), &[]); + assert_matches!( + execution_result, + StateTransitionExecutionResult::SuccessfulExecution { .. } + ); + + for left_over in [1, 100] { + let (platform, serialized, identity_id) = + platform_with_signed_data_contract_create(platform_version.protocol_version); + let padded = with_left_over_bytes(&serialized, left_over); + let (check_result, execution_result, balance) = + check_and_process(&platform, &padded, identity_id, platform_version); + + assert_matches!( + check_result.errors.as_slice(), + [ConsensusError::BasicError( + BasicError::SerializedObjectParsingError(_) + )] + ); + assert_eq!(check_result.data.expect("check tx data").fee_result, None); + assert_matches!( + execution_result, + StateTransitionExecutionResult::UnpaidConsensusError(ConsensusError::BasicError( + BasicError::SerializedObjectParsingError(_) + )) + ); + assert_eq!(balance, 25_000_000_000, "nothing is charged"); + } + } + + /// Protocol version 13 keeps decoding a transition with bytes after it as the transition + /// alone, and executes it. + #[test] + fn should_accept_bytes_after_a_state_transition_at_protocol_version_13() { + let platform_version = PlatformVersion::get(13).expect("protocol version 13 exists"); + + for left_over in [0, 1, 100] { + let (platform, serialized, identity_id) = + platform_with_signed_data_contract_create(platform_version.protocol_version); + let raw = with_left_over_bytes(&serialized, left_over); + let (check_result, execution_result, balance) = + check_and_process(&platform, &raw, identity_id, platform_version); + + assert_eq!(check_result.errors.as_slice(), &[]); + assert_matches!( + execution_result, + StateTransitionExecutionResult::SuccessfulExecution { .. } + ); + assert!(balance < 25_000_000_000, "the create is paid"); + } + } } diff --git a/packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/decode_raw_state_transitions/mod.rs b/packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/decode_raw_state_transitions/mod.rs index 92bf4fc44f2..c9ed0a622bf 100644 --- a/packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/decode_raw_state_transitions/mod.rs +++ b/packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/decode_raw_state_transitions/mod.rs @@ -1,4 +1,5 @@ mod v0; +mod v1; use crate::error::execution::ExecutionError; use crate::error::Error; @@ -13,6 +14,9 @@ where { /// Processes the given raw state transitions based on the `block_info` and `transaction`. /// + /// Version 0 ignores bytes left over after a transition; version 1 (from protocol version + /// 14) refuses them as an invalid encoding. + /// /// # Arguments /// /// * `raw_state_transitions` - A reference to a vector of raw state transitions. @@ -43,11 +47,93 @@ where 0 => Ok(self .decode_raw_state_transitions_v0(raw_state_transitions, platform_version) .into()), + 1 => Ok(self + .decode_raw_state_transitions_v1(raw_state_transitions, platform_version) + .into()), version => Err(Error::Execution(ExecutionError::UnknownVersionMismatch { method: "decode_raw_state_transitions".to_string(), - known_versions: vec![0], + known_versions: vec![0, 1], received: version, })), } } } + +#[cfg(test)] +mod tests { + use crate::execution::types::state_transition_container::v0::DecodedStateTransition; + use crate::test::helpers::setup::TestPlatformBuilder; + use dpp::consensus::basic::BasicError; + use dpp::consensus::ConsensusError; + use dpp::identifier::Identifier; + use dpp::platform_value::BinaryData; + use dpp::serialization::PlatformSerializable; + use dpp::state_transition::batch_transition::{BatchTransition, BatchTransitionV1}; + use dpp::state_transition::StateTransition; + use dpp::version::PlatformVersion; + + /// Protocol version 13 decodes a transition with bytes after it as the transition alone; + /// protocol version 14 refuses it. The exact bytes decode at both. + #[test] + fn should_refuse_bytes_after_a_transition_from_protocol_version_14_only() { + let platform = TestPlatformBuilder::new() + .build_with_mock_rpc() + .set_initial_state_structure(); + + let transition = StateTransition::Batch(BatchTransition::V1(BatchTransitionV1 { + owner_id: Identifier::from([1u8; 32]), + transitions: vec![], + user_fee_increase: 0, + signature_public_key_id: 0, + signature: BinaryData::new(vec![0u8; 65]), + })); + let exact = transition.serialize_to_bytes().expect("serialize"); + let padded = |left_over: usize| { + let mut padded = exact.clone(); + padded.extend(std::iter::repeat_n(0u8, left_over)); + padded + }; + let raw_state_transitions = vec![exact.clone(), padded(1), padded(100)]; + + let decode = |platform_version: &PlatformVersion| -> Vec { + let decoded: Vec = platform + .decode_raw_state_transitions(&raw_state_transitions, platform_version) + .expect("known decoder version") + .into(); + assert_eq!(decoded.len(), 3); + decoded + }; + + let protocol_version_13 = PlatformVersion::get(13).expect("protocol version 13 exists"); + for decoded in decode(protocol_version_13) { + match decoded { + DecodedStateTransition::SuccessfullyDecoded(success) => { + assert_eq!(success.decoded, transition) + } + other => panic!("protocol version 13 decodes every variant, got {other:?}"), + } + } + + let protocol_version_14 = PlatformVersion::get(14).expect("protocol version 14 exists"); + let mut decoded = decode(protocol_version_14).into_iter(); + match decoded.next() { + Some(DecodedStateTransition::SuccessfullyDecoded(success)) => { + assert_eq!(success.decoded, transition) + } + other => panic!("protocol version 14 decodes the exact bytes, got {other:?}"), + } + for refused in decoded { + match refused { + DecodedStateTransition::InvalidEncoding(invalid) => assert!( + matches!( + invalid.error, + ConsensusError::BasicError(BasicError::SerializedObjectParsingError(_)) + ), + "expected SerializedObjectParsingError, got {:?}", + invalid.error + ), + other => panic!("protocol version 14 refuses left over bytes, got {other:?}"), + } + } + } +} diff --git a/packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/decode_raw_state_transitions/v0/mod.rs b/packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/decode_raw_state_transitions/v0/mod.rs index 59994966c6a..c26309085c1 100644 --- a/packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/decode_raw_state_transitions/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/decode_raw_state_transitions/v0/mod.rs @@ -130,7 +130,7 @@ mod tests { #[test] fn test_decode_empty_state_transitions() { - let platform_version = PlatformVersion::latest(); + let platform_version = PlatformVersion::get(13).expect("protocol version 13 exists"); let platform = TestPlatformBuilder::new() .build_with_mock_rpc() .set_initial_state_structure(); @@ -144,7 +144,7 @@ mod tests { #[test] fn test_decode_oversized_state_transition() { - let platform_version = PlatformVersion::latest(); + let platform_version = PlatformVersion::get(13).expect("protocol version 13 exists"); let platform = TestPlatformBuilder::new() .build_with_mock_rpc() .set_initial_state_structure(); @@ -180,7 +180,7 @@ mod tests { #[test] fn test_decode_invalid_bytes_state_transition() { - let platform_version = PlatformVersion::latest(); + let platform_version = PlatformVersion::get(13).expect("protocol version 13 exists"); let platform = TestPlatformBuilder::new() .build_with_mock_rpc() .set_initial_state_structure(); @@ -207,7 +207,7 @@ mod tests { #[test] fn test_decode_multiple_mixed_state_transitions() { - let platform_version = PlatformVersion::latest(); + let platform_version = PlatformVersion::get(13).expect("protocol version 13 exists"); let platform = TestPlatformBuilder::new() .build_with_mock_rpc() .set_initial_state_structure(); @@ -245,7 +245,7 @@ mod tests { /// `InvalidEncoding` or `FailedToDecode`, never an oversized error. #[test] fn test_decode_empty_bytes_is_not_oversized() { - let platform_version = PlatformVersion::latest(); + let platform_version = PlatformVersion::get(13).expect("protocol version 13 exists"); let platform = TestPlatformBuilder::new() .build_with_mock_rpc() .set_initial_state_structure(); @@ -273,7 +273,7 @@ mod tests { /// fields silently. #[test] fn test_decode_oversized_state_transition_reports_correct_sizes() { - let platform_version = PlatformVersion::latest(); + let platform_version = PlatformVersion::get(13).expect("protocol version 13 exists"); let platform = TestPlatformBuilder::new() .build_with_mock_rpc() .set_initial_state_structure(); @@ -314,7 +314,7 @@ mod tests { #[test] fn test_decode_state_transition_at_exact_max_size_is_not_rejected_as_oversized() { - let platform_version = PlatformVersion::latest(); + let platform_version = PlatformVersion::get(13).expect("protocol version 13 exists"); let platform = TestPlatformBuilder::new() .build_with_mock_rpc() .set_initial_state_structure(); diff --git a/packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/decode_raw_state_transitions/v1/mod.rs b/packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/decode_raw_state_transitions/v1/mod.rs new file mode 100644 index 00000000000..deca72aa685 --- /dev/null +++ b/packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/decode_raw_state_transitions/v1/mod.rs @@ -0,0 +1,309 @@ +use crate::execution::types::state_transition_container::v0::{ + DecodedStateTransition, InvalidStateTransition, InvalidWithProtocolErrorStateTransition, + StateTransitionContainerV0, SuccessfullyDecodedStateTransition, +}; +use crate::platform_types::platform::Platform; +use crate::rpc::core::CoreRPCLike; +use dpp::consensus::basic::decode::SerializedObjectParsingError; +use dpp::consensus::basic::state_transition::{ + StateTransitionMaxSizeExceededError, StateTransitionNotActiveError, +}; +use dpp::consensus::basic::BasicError; +use dpp::consensus::ConsensusError; +use dpp::state_transition::errors::StateTransitionError; +use dpp::state_transition::StateTransition; +use dpp::version::PlatformVersion; +use dpp::ProtocolError; +use std::time::{Duration, Instant}; + +impl Platform +where + C: CoreRPCLike, +{ + /// Decodes raw state transitions like version 0, except that each one must be exactly one + /// encoded transition. + /// + /// Version 0 ignores bytes left over after the transition, so the same transition with + /// anything appended decoded, validated and executed as the original. Here left over bytes + /// are an `InvalidEncoding` carrying a `SerializedObjectParsingError`, which is unpaid. A + /// transition whose version is not active at `platform_version` is an `InvalidEncoding` + /// carrying a `StateTransitionNotActiveError`, not a decode failure. + /// + /// ## Arguments + /// + /// - `raw_state_transitions`: the raw state transitions, each as its bytes. + /// - `platform_version`: the active platform version. + /// + /// ## Returns + /// + /// - `StateTransitionContainerV0`: every transition, decoded or with the reason it could not + /// be, in input order. + pub(super) fn decode_raw_state_transitions_v1<'a>( + &self, + raw_state_transitions: &'a [impl AsRef<[u8]>], + platform_version: &PlatformVersion, + ) -> StateTransitionContainerV0<'a> { + let decoded_state_transitions = raw_state_transitions + .iter() + .map(|raw_state_transition| { + if raw_state_transition.as_ref().len() as u64 + > platform_version.system_limits.max_state_transition_size + { + // The state transition is too big + let consensus_error = ConsensusError::BasicError( + BasicError::StateTransitionMaxSizeExceededError( + StateTransitionMaxSizeExceededError::new( + raw_state_transition.as_ref().len() as u64, + platform_version.system_limits.max_state_transition_size, + ), + ), + ); + + DecodedStateTransition::InvalidEncoding(InvalidStateTransition { + raw: raw_state_transition.as_ref(), + error: consensus_error, + elapsed_time: Duration::default(), + }) + } else { + let start_time = Instant::now(); + + match StateTransition::deserialize_from_bytes_untrusted_exact_in_version( + raw_state_transition.as_ref(), + platform_version, + ) { + Ok(state_transition) => DecodedStateTransition::SuccessfullyDecoded( + SuccessfullyDecodedStateTransition { + decoded: state_transition, + raw: raw_state_transition.as_ref(), + elapsed_time: start_time.elapsed(), + }, + ), + Err(error) => match error { + // Also the error for bytes left over after the transition. + ProtocolError::PlatformDeserializationError(message) => { + let consensus_error = + SerializedObjectParsingError::new(message.clone()).into(); + + DecodedStateTransition::InvalidEncoding(InvalidStateTransition { + raw: raw_state_transition.as_ref(), + error: consensus_error, + elapsed_time: start_time.elapsed(), + }) + } + ProtocolError::MaxEncodedBytesReachedError { .. } => { + let message = error.to_string(); + let consensus_error = + SerializedObjectParsingError::new(message.clone()).into(); + + DecodedStateTransition::InvalidEncoding(InvalidStateTransition { + raw: raw_state_transition.as_ref(), + error: consensus_error, + elapsed_time: start_time.elapsed(), + }) + } + // A transition whose version is not active yet decoded fine; its + // bytes are not at fault, and the submitter is owed a coded answer + // rather than an internal error. Matched by variant: the sibling + // `InvalidStateTransitionError` carries its own consensus errors and + // is a separate question. + ProtocolError::StateTransitionError( + StateTransitionError::StateTransitionIsNotActiveError { + state_transition_type, + active_version_range, + current_protocol_version, + }, + ) => { + let consensus_error = StateTransitionNotActiveError::new( + state_transition_type, + current_protocol_version, + *active_version_range.start(), + ) + .into(); + + DecodedStateTransition::InvalidEncoding(InvalidStateTransition { + raw: raw_state_transition.as_ref(), + error: consensus_error, + elapsed_time: start_time.elapsed(), + }) + } + protocol_error => DecodedStateTransition::FailedToDecode( + InvalidWithProtocolErrorStateTransition { + raw: raw_state_transition.as_ref(), + error: protocol_error, + elapsed_time: start_time.elapsed(), + }, + ), + }, + } + } + }) + .collect(); + + StateTransitionContainerV0::new(decoded_state_transitions) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test::helpers::setup::TestPlatformBuilder; + use dpp::identifier::Identifier; + use dpp::platform_value::BinaryData; + use dpp::serialization::PlatformSerializable; + use dpp::state_transition::batch_transition::{BatchTransition, BatchTransitionV1}; + use dpp::version::PlatformVersion; + + fn batch_transition(owner_byte: u8) -> StateTransition { + StateTransition::Batch(BatchTransition::V1(BatchTransitionV1 { + owner_id: Identifier::from([owner_byte; 32]), + transitions: vec![], + user_fee_increase: 0, + signature_public_key_id: 0, + signature: BinaryData::new(vec![0u8; 65]), + })) + } + + fn assert_serialized_object_parsing_error(decoded: &DecodedStateTransition) { + match decoded { + DecodedStateTransition::InvalidEncoding(invalid) => assert!( + matches!( + &invalid.error, + ConsensusError::BasicError(BasicError::SerializedObjectParsingError(_)) + ), + "expected SerializedObjectParsingError, got {:?}", + invalid.error + ), + other => panic!("expected InvalidEncoding, got {other:?}"), + } + } + + #[test] + fn should_decode_the_exact_bytes_of_a_transition() { + let platform = TestPlatformBuilder::new() + .build_with_mock_rpc() + .set_initial_state_structure(); + + let transition = batch_transition(1); + let raw_state_transitions = vec![transition.serialize_to_bytes().expect("serialize")]; + let decoded: Vec<_> = platform + .decode_raw_state_transitions_v1(&raw_state_transitions, PlatformVersion::latest()) + .into_iter() + .collect(); + + match decoded.as_slice() { + [DecodedStateTransition::SuccessfullyDecoded(success)] => { + assert_eq!(success.decoded, transition); + assert_eq!(success.raw, raw_state_transitions[0].as_slice()); + } + other => panic!("expected one decoded transition, got {other:?}"), + } + } + + #[test] + fn should_refuse_bytes_left_over_after_a_transition() { + let platform = TestPlatformBuilder::new() + .build_with_mock_rpc() + .set_initial_state_structure(); + + let bytes = batch_transition(1).serialize_to_bytes().expect("serialize"); + let raw_state_transitions: Vec> = [1usize, 100] + .into_iter() + .map(|left_over| { + let mut padded = bytes.clone(); + padded.extend(std::iter::repeat_n(0u8, left_over)); + padded + }) + .collect(); + + let decoded: Vec<_> = platform + .decode_raw_state_transitions_v1(&raw_state_transitions, PlatformVersion::latest()) + .into_iter() + .collect(); + + assert_eq!(decoded.len(), 2); + decoded + .iter() + .for_each(assert_serialized_object_parsing_error); + } + + /// Two transitions in one raw transaction are refused as a whole, not decoded as the first. + #[test] + fn should_refuse_a_transition_followed_by_another() { + let platform = TestPlatformBuilder::new() + .build_with_mock_rpc() + .set_initial_state_structure(); + + let mut both = batch_transition(1).serialize_to_bytes().expect("serialize"); + both.extend(batch_transition(2).serialize_to_bytes().expect("serialize")); + + let raw_state_transitions = vec![both]; + let decoded: Vec<_> = platform + .decode_raw_state_transitions_v1(&raw_state_transitions, PlatformVersion::latest()) + .into_iter() + .collect(); + + assert_eq!(decoded.len(), 1); + assert_serialized_object_parsing_error(&decoded[0]); + } + + /// The size limit is still checked first, on the whole raw transaction. + #[test] + fn should_refuse_an_oversized_transaction_before_decoding() { + let platform_version = PlatformVersion::latest(); + let platform = TestPlatformBuilder::new() + .build_with_mock_rpc() + .set_initial_state_structure(); + + let max_size = platform_version.system_limits.max_state_transition_size as usize; + let mut oversized = batch_transition(1).serialize_to_bytes().expect("serialize"); + oversized.resize(max_size + 1, 0); + + let raw_state_transitions = vec![oversized]; + let decoded: Vec<_> = platform + .decode_raw_state_transitions_v1(&raw_state_transitions, platform_version) + .into_iter() + .collect(); + + match decoded.as_slice() { + [DecodedStateTransition::InvalidEncoding(invalid)] => assert!( + matches!( + &invalid.error, + ConsensusError::BasicError(BasicError::StateTransitionMaxSizeExceededError(_)) + ), + "expected StateTransitionMaxSizeExceededError, got {:?}", + invalid.error + ), + other => panic!("expected one InvalidEncoding, got {other:?}"), + } + } + + /// A transition that decodes cleanly but whose version is not active is a coded consensus + /// rejection, not a decode failure (which would reach the internal-error path). + #[test] + fn should_report_an_inactive_transition_as_not_active() { + let platform = TestPlatformBuilder::new() + .build_with_mock_rpc() + .set_initial_state_structure(); + + // A batch transition version 1 is active only from protocol version 9. + let raw_state_transitions = + vec![batch_transition(1).serialize_to_bytes().expect("serialize")]; + let older = PlatformVersion::get(1).expect("protocol version 1 should exist"); + let decoded: Vec<_> = platform + .decode_raw_state_transitions_v1(&raw_state_transitions, older) + .into_iter() + .collect(); + + match decoded.as_slice() { + [DecodedStateTransition::InvalidEncoding(invalid)] => assert!( + matches!( + &invalid.error, + ConsensusError::BasicError(BasicError::StateTransitionNotActiveError(_)) + ), + "expected StateTransitionNotActiveError, got {:?}", + invalid.error + ), + other => panic!("expected one InvalidEncoding, got {other:?}"), + } + } +} diff --git a/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_method_versions/v10.rs b/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_method_versions/v10.rs index 7c06312da0f..ba88d8f6f50 100644 --- a/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_method_versions/v10.rs +++ b/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_method_versions/v10.rs @@ -19,6 +19,7 @@ use crate::version::drive_abci_versions::drive_abci_method_versions::{ /// expired entries of the credit inflows sum tree the net daily withdrawal limit reads, and /// bumps `rebroadcast_expired_withdrawal_documents` to 2 so an expired withdrawal whose /// payout is below Core's dust threshold is marked FAILED instead of re-signed forever. +/// `decode_raw_state_transitions` 1 refuses bytes left over after a raw state transition. /// Everything else matches `DRIVE_ABCI_METHOD_VERSIONS_V9`. pub const DRIVE_ABCI_METHOD_VERSIONS_V10: DriveAbciMethodVersions = DriveAbciMethodVersions { engine: DriveAbciEngineMethodVersions { @@ -117,7 +118,7 @@ pub const DRIVE_ABCI_METHOD_VERSIONS_V10: DriveAbciMethodVersions = DriveAbciMet // unchanged from V9: v1 since v13 (records the balance effects of paid-INVALID / // unsuccessful-paid transitions) process_validation_result: 1, - decode_raw_state_transitions: 0, + decode_raw_state_transitions: 1, // changed: refuses bytes left over after a raw state transition validate_fees_of_event: 1, // changed: refuses an expired signing key and a spend the signing key's remaining budget does not cover, and judges a sponsored document batch's fee against its gas sponsor's balance store_address_balances_to_recent_block_storage: Some(0), cleanup_recent_block_storage_address_balances: Some(0), diff --git a/packages/rs-platform-version/src/version/v14.rs b/packages/rs-platform-version/src/version/v14.rs index 8108d1f3470..fd6b4bd0dc1 100644 --- a/packages/rs-platform-version/src/version/v14.rs +++ b/packages/rs-platform-version/src/version/v14.rs @@ -1182,6 +1182,16 @@ pub const PROTOCOL_VERSION_14: ProtocolVersion = 14; /// 1 also ignores the lock tally of a contest resolved without locking. No /// table moves: both generations are selected by this version alone. /// +/// 46. **A raw state transition is exactly one encoded transition**: +/// `decode_raw_state_transitions` 1 (`DRIVE_ABCI_METHOD_VERSIONS_V10`) +/// decodes with `StateTransition::deserialize_from_bytes_untrusted_exact_in_version`, +/// so bytes left over after the transition are an invalid encoding +/// (`SerializedObjectParsingError`, 10002), refused unpaid in `check_tx` and +/// in block processing. Version 0 ignored them, so the transition with +/// anything appended executed as the original under another transaction +/// hash. Version 1 also reports a transition whose version is not active +/// as `StateTransitionNotActiveError` (10603) instead of a decode failure. +/// /// The app-connect system contract (`SystemDataContract::AppConnect`, schema v1) /// carries only the wallet's `loginKeyResponse`: a flat indexOnly entry keyed by /// the app's ephemeral key hash and the responding identity, with the wallet's