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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,11 @@ use crate::withdrawal::Pooling;
use platform_version::version::PlatformVersion;
use std::collections::HashSet;

impl StateTransitionStructureValidation for AddressCreditWithdrawalTransitionV0 {
fn validate_structure(
impl AddressCreditWithdrawalTransitionV0 {
/// Validates all structural properties of the transition except for the
/// `input_witnesses` count. This is intended for client-side pre-signing
/// validation, where witnesses are not yet present.
pub fn validate_structure_without_input_witnesses(
&self,
platform_version: &PlatformVersion,
) -> SimpleConsensusValidationResult {
Expand All @@ -46,17 +49,6 @@ impl StateTransitionStructureValidation for AddressCreditWithdrawalTransitionV0
);
}

// Validate input witnesses count matches inputs count
if self.inputs.len() != self.input_witnesses.len() {
return SimpleConsensusValidationResult::new_with_error(
BasicError::InputWitnessCountMismatchError(InputWitnessCountMismatchError::new(
self.inputs.len().min(u16::MAX as usize) as u16,
self.input_witnesses.len().min(u16::MAX as usize) as u16,
))
.into(),
);
}

// Validate output address is not also an input address
if let Some((output_address, _)) = &self.output {
if self.inputs.contains_key(output_address) {
Expand Down Expand Up @@ -242,6 +234,35 @@ impl StateTransitionStructureValidation for AddressCreditWithdrawalTransitionV0

SimpleConsensusValidationResult::new()
}

/// Validates that the number of `input_witnesses` matches the number of
/// inputs. Intended to be invoked after signing, once witnesses have been
/// produced by the signer.
pub fn validate_input_witnesses_count(&self) -> SimpleConsensusValidationResult {
if self.inputs.len() != self.input_witnesses.len() {
return SimpleConsensusValidationResult::new_with_error(
BasicError::InputWitnessCountMismatchError(InputWitnessCountMismatchError::new(
self.inputs.len().min(u16::MAX as usize) as u16,
self.input_witnesses.len().min(u16::MAX as usize) as u16,
))
.into(),
);
}
SimpleConsensusValidationResult::new()
}
}

impl StateTransitionStructureValidation for AddressCreditWithdrawalTransitionV0 {
fn validate_structure(
&self,
platform_version: &PlatformVersion,
) -> SimpleConsensusValidationResult {
let result = self.validate_structure_without_input_witnesses(platform_version);
if !result.is_valid() {
return result;
}
self.validate_input_witnesses_count()
}
}

#[cfg(test)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ use crate::serialization::Signable;
use crate::state_transition::address_credit_withdrawal_transition::methods::AddressCreditWithdrawalTransitionMethodsV0;
use crate::state_transition::address_credit_withdrawal_transition::v0::AddressCreditWithdrawalTransitionV0;
#[cfg(feature = "state-transition-signing")]
use crate::state_transition::first_consensus_error_as_protocol_error;
#[cfg(feature = "state-transition-signing")]
use crate::withdrawal::Pooling;
#[cfg(feature = "state-transition-signing")]
use crate::{
Expand All @@ -35,7 +37,7 @@ impl AddressCreditWithdrawalTransitionMethodsV0 for AddressCreditWithdrawalTrans
output_script: CoreScript,
signer: &S,
user_fee_increase: UserFeeIncrease,
_platform_version: &PlatformVersion,
platform_version: &PlatformVersion,
) -> Result<StateTransition, ProtocolError> {
tracing::debug!("try_from_inputs_with_signer: Started");
tracing::debug!(
Expand All @@ -57,6 +59,15 @@ impl AddressCreditWithdrawalTransitionMethodsV0 for AddressCreditWithdrawalTrans
input_witnesses: Vec::new(),
};

// Pre-signing structure check: validate everything except the witness
// count, so structural errors fail fast before performing any async
// signer work.
let pre_validation_result = address_credit_withdrawal_transition
.validate_structure_without_input_witnesses(platform_version);
if let Some(error) = first_consensus_error_as_protocol_error(pre_validation_result) {
return Err(error);
}

let state_transition: StateTransition = address_credit_withdrawal_transition.clone().into();

let signable_bytes = state_transition.signable_bytes()?;
Expand All @@ -67,6 +78,14 @@ impl AddressCreditWithdrawalTransitionMethodsV0 for AddressCreditWithdrawalTrans
}
address_credit_withdrawal_transition.input_witnesses = input_witnesses;

// After signing, only the witness count needs (re-)validation; the rest
// of the structure was already verified above.
let validation_result =
address_credit_withdrawal_transition.validate_input_witnesses_count();
if let Some(error) = first_consensus_error_as_protocol_error(validation_result) {
return Err(error);
}
Comment on lines 78 to +87
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

🟡 Suggestion: Structure validation runs after async signing — invalid transitions still incur N signer round-trips

validate_structure() is called only after the loop that awaits signer.sign_create_witness(...) for every input. None of the structural checks (max inputs, fee strategy, output script, input/output amounts) actually depend on the witnesses; only the witness-count check does, and it is tautologically satisfied here because the loop produces exactly inputs.len() witnesses. The same pattern exists in address_funds_transfer_transition/v0/v0_methods.rs, address_funding_from_asset_lock_transition/v0/v0_methods.rs, identity_create_from_addresses_transition/v0/v0_methods.rs, and identity_topup_from_addresses_transition/v0/v0_methods.rs. When Signer is backed by a hardware wallet, secure enclave, or remote KMS — the SDK's primary use case — every input requires a user prompt or network round-trip. The whole point of this PR is to fail fast client-side before broadcast; failing fast after N HSM confirmations defeats much of the benefit. Add a pre-signing structure check (skipping only the witness-count assertion) in addition to the existing post-signing call.

source: ['claude']

🤖 Fix this with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `packages/rs-dpp/src/state_transition/state_transitions/address_funds/address_credit_withdrawal_transition/v0/v0_methods.rs`:
- [SUGGESTION] lines 66-78: Structure validation runs after async signing — invalid transitions still incur N signer round-trips
  `validate_structure()` is called only after the loop that awaits `signer.sign_create_witness(...)` for every input. None of the structural checks (max inputs, fee strategy, output script, input/output amounts) actually depend on the witnesses; only the witness-count check does, and it is tautologically satisfied here because the loop produces exactly `inputs.len()` witnesses. The same pattern exists in `address_funds_transfer_transition/v0/v0_methods.rs`, `address_funding_from_asset_lock_transition/v0/v0_methods.rs`, `identity_create_from_addresses_transition/v0/v0_methods.rs`, and `identity_topup_from_addresses_transition/v0/v0_methods.rs`. When `Signer` is backed by a hardware wallet, secure enclave, or remote KMS — the SDK's primary use case — every input requires a user prompt or network round-trip. The whole point of this PR is to fail fast client-side before broadcast; failing fast *after* N HSM confirmations defeats much of the benefit. Add a pre-signing structure check (skipping only the witness-count assertion) in addition to the existing post-signing call.

Comment on lines +83 to +87
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

🟡 Suggestion: errors.into_iter().next().unwrap() pattern duplicated across 7+ sites and discards all but the first error

The same six-line block — call validate_structure/validate_identity_public_keys_structure, check is_valid(), then validation_result.errors.into_iter().next().unwrap() and wrap in ProtocolError::ConsensusError(Box::new(...)) — appears in seven places across this PR (address_credit_withdrawal, address_funding_from_asset_lock, address_funds_transfer, identity_create_from_addresses (×2), identity_credit_transfer_to_addresses, identity_topup_from_addresses, identity_update). Two issues: (1) The unwrap() is technically safe today because ValidationResult::is_valid() is defined as errors.is_empty(), but it relies on a non-local invariant; a future refactor that lets a result be "invalid with no errors" would silently introduce a panic. (2) Discarding every error after the first is user-hostile — a transition with two structural problems requires two round-trips to discover both. A small pub(crate) fn first_error_as_protocol_error(result: SimpleConsensusValidationResult) -> Option<ProtocolError> (or a variant returning all errors) in state_transition/mod.rs would deduplicate the boilerplate and remove the unwrap.

source: ['claude']

🤖 Fix this with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `packages/rs-dpp/src/state_transition/state_transitions/address_funds/address_credit_withdrawal_transition/v0/v0_methods.rs`:
- [SUGGESTION] lines 73-78: `errors.into_iter().next().unwrap()` pattern duplicated across 7+ sites and discards all but the first error
  The same six-line block — call `validate_structure`/`validate_identity_public_keys_structure`, check `is_valid()`, then `validation_result.errors.into_iter().next().unwrap()` and wrap in `ProtocolError::ConsensusError(Box::new(...))` — appears in seven places across this PR (`address_credit_withdrawal`, `address_funding_from_asset_lock`, `address_funds_transfer`, `identity_create_from_addresses` (×2), `identity_credit_transfer_to_addresses`, `identity_topup_from_addresses`, `identity_update`). Two issues: (1) The `unwrap()` is technically safe today because `ValidationResult::is_valid()` is defined as `errors.is_empty()`, but it relies on a non-local invariant; a future refactor that lets a result be "invalid with no errors" would silently introduce a panic. (2) Discarding every error after the first is user-hostile — a transition with two structural problems requires two round-trips to discover both. A small `pub(crate) fn first_error_as_protocol_error(result: SimpleConsensusValidationResult) -> Option<ProtocolError>` (or a variant returning all errors) in `state_transition/mod.rs` would deduplicate the boilerplate and remove the unwrap.


tracing::debug!("try_from_inputs_with_signer: Successfully created transition");
Ok(address_credit_withdrawal_transition.into())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@ use crate::validation::SimpleConsensusValidationResult;
use platform_version::version::PlatformVersion;
use std::collections::HashSet;

impl StateTransitionStructureValidation for AddressFundingFromAssetLockTransitionV0 {
fn validate_structure(
impl AddressFundingFromAssetLockTransitionV0 {
/// Validates all structural properties of the transition except for the
/// `input_witnesses` count. This is intended for client-side pre-signing
/// validation, where witnesses are not yet present.
pub fn validate_structure_without_input_witnesses(
&self,
platform_version: &PlatformVersion,
) -> SimpleConsensusValidationResult {
Expand Down Expand Up @@ -62,17 +65,6 @@ impl StateTransitionStructureValidation for AddressFundingFromAssetLockTransitio
);
}

// Validate input witnesses count matches inputs count (if there are inputs)
if self.inputs.len() != self.input_witnesses.len() {
return SimpleConsensusValidationResult::new_with_error(
BasicError::InputWitnessCountMismatchError(InputWitnessCountMismatchError::new(
self.inputs.len().min(u16::MAX as usize) as u16,
self.input_witnesses.len().min(u16::MAX as usize) as u16,
))
.into(),
);
}

// Validate no output address is also an input address
for output_address in self.outputs.keys() {
if self.inputs.contains_key(output_address) {
Expand Down Expand Up @@ -202,6 +194,35 @@ impl StateTransitionStructureValidation for AddressFundingFromAssetLockTransitio

SimpleConsensusValidationResult::new()
}

/// Validates that the number of `input_witnesses` matches the number of
/// inputs. Intended to be invoked after signing, once witnesses have been
/// produced by the signer.
pub fn validate_input_witnesses_count(&self) -> SimpleConsensusValidationResult {
if self.inputs.len() != self.input_witnesses.len() {
return SimpleConsensusValidationResult::new_with_error(
BasicError::InputWitnessCountMismatchError(InputWitnessCountMismatchError::new(
self.inputs.len().min(u16::MAX as usize) as u16,
self.input_witnesses.len().min(u16::MAX as usize) as u16,
))
.into(),
);
}
SimpleConsensusValidationResult::new()
}
}

impl StateTransitionStructureValidation for AddressFundingFromAssetLockTransitionV0 {
fn validate_structure(
&self,
platform_version: &PlatformVersion,
) -> SimpleConsensusValidationResult {
let result = self.validate_structure_without_input_witnesses(platform_version);
if !result.is_valid() {
return result;
}
self.validate_input_witnesses_count()
}
}

#[cfg(test)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ use crate::serialization::Signable;
use crate::state_transition::address_funding_from_asset_lock_transition::methods::AddressFundingFromAssetLockTransitionMethodsV0;
use crate::state_transition::address_funding_from_asset_lock_transition::v0::AddressFundingFromAssetLockTransitionV0;
#[cfg(feature = "state-transition-signing")]
use crate::state_transition::first_consensus_error_as_protocol_error;
#[cfg(feature = "state-transition-signing")]
use crate::{prelude::UserFeeIncrease, state_transition::StateTransition, ProtocolError};
#[cfg(feature = "state-transition-signing")]
use dashcore::signer;
Expand All @@ -30,7 +32,7 @@ impl AddressFundingFromAssetLockTransitionMethodsV0 for AddressFundingFromAssetL
fee_strategy: AddressFundsFeeStrategy,
signer: &S,
user_fee_increase: UserFeeIncrease,
_platform_version: &PlatformVersion,
platform_version: &PlatformVersion,
) -> Result<StateTransition, ProtocolError> {
tracing::debug!("try_from_asset_lock_with_signer: Started");
tracing::debug!(
Expand All @@ -50,6 +52,15 @@ impl AddressFundingFromAssetLockTransitionMethodsV0 for AddressFundingFromAssetL
input_witnesses: Vec::new(),
};

// Pre-signing structure check: validate everything except the witness
// count, so structural errors fail fast before performing any async
// signer work.
let pre_validation_result =
address_funding_transition.validate_structure_without_input_witnesses(platform_version);
if let Some(error) = first_consensus_error_as_protocol_error(pre_validation_result) {
return Err(error);
}

let state_transition: StateTransition = address_funding_transition.clone().into();

let signable_bytes = state_transition.signable_bytes()?;
Expand All @@ -65,6 +76,13 @@ impl AddressFundingFromAssetLockTransitionMethodsV0 for AddressFundingFromAssetL
}
address_funding_transition.input_witnesses = input_witnesses;

// After signing, only the witness count needs (re-)validation; the rest
// of the structure was already verified above.
let validation_result = address_funding_transition.validate_input_witnesses_count();
if let Some(error) = first_consensus_error_as_protocol_error(validation_result) {
return Err(error);
}

tracing::debug!("try_from_asset_lock_with_signer: Successfully created transition");
Ok(address_funding_transition.into())
}
Expand Down
Loading
Loading