Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
ea869d8
fix(drive): charge fees for unshield and shielded withdrawal
QuantumExplorer Jun 5, 2026
b7ff23c
test(drive): PR4 review cleanups — comment, net-zero skip, withdrawal…
QuantumExplorer Jun 5, 2026
a732b10
fix(drive-abci): enforce withdrawal dust floor on shielded withdrawal…
QuantumExplorer Jun 5, 2026
c05b470
test(drive-abci): give shielded-withdrawal validation fixtures a net …
QuantumExplorer Jun 5, 2026
e7c1eb6
docs(drive-abci): note shielded-withdrawal net is guaranteed >= dust …
QuantumExplorer Jun 5, 2026
7db77b4
docs(dpp): explain the 216-byte shielded encrypted-note layout in SHI…
QuantumExplorer Jun 5, 2026
f8ec408
fix(drive-abci): pin shielded-transfer fee to exactly the minimum (re…
QuantumExplorer Jun 5, 2026
e04dc7d
fix(dpp): pin shielded-transfer builder fee to exactly the minimum (a…
QuantumExplorer Jun 5, 2026
c3519de
test(drive): verify the flat shielded fee covers the actual GroveDB w…
QuantumExplorer Jun 5, 2026
055dd7b
test(drive-abci): add ignored benchmark for shielded proof-verificati…
QuantumExplorer Jun 6, 2026
4652b5b
fix(platform-version): price per-action Halo 2 verification in the sh…
QuantumExplorer Jun 6, 2026
667f4ce
fix(drive-abci): route shielded storage cost to storage_fee so it amo…
QuantumExplorer Jun 6, 2026
b472528
docs(dpp): fix clippy doc_lazy_continuation in SHIELDED_STORAGE_BYTES…
QuantumExplorer Jun 6, 2026
fba59b1
refactor(drive-abci): drop dead per-operation fee from shielded trans…
QuantumExplorer Jun 6, 2026
3695838
fix(dpp): address shielded fee-model review findings on #3800
QuantumExplorer Jun 6, 2026
1d06025
fix(dpp): bind core_fee_per_byte/pooling to withdrawal sighash; fix w…
QuantumExplorer Jun 6, 2026
a6582cc
docs(shielded-fees): correct unshield/withdrawal fee and pool-decreme…
QuantumExplorer Jun 6, 2026
cf926df
fix(dpp): address in-depth review findings (withdrawal cap, fee pin, …
QuantumExplorer Jun 6, 2026
07de324
test(shielded): seed RNG for determinism + cover select_notes_with_fee
QuantumExplorer Jun 6, 2026
b2beded
test(shielded): assert error variants on withdrawal-range tests + cov…
QuantumExplorer Jun 6, 2026
e558bc1
refactor(dpp): drop the fee param from shielded builders; return the …
QuantumExplorer Jun 6, 2026
c11eef5
refactor(dpp): version compute_minimum_shielded_fee with the mod + v0…
QuantumExplorer Jun 6, 2026
cbd0cd4
refactor(drive-abci): drop dead block_info/execution_context from shi…
QuantumExplorer Jun 6, 2026
a909cf1
refactor(drive-abci): rename shielded fee-validation locals for clarity
QuantumExplorer Jun 6, 2026
35d9cce
feat: version min_withdrawal_amount; raise to 1000 duffs in protocol …
QuantumExplorer Jun 6, 2026
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 @@ -3,9 +3,12 @@ use crate::error::Error;
use crate::execution::validation::state_transition::state_transitions::shielded_common::{
reconstruct_and_verify_bundle, FLAGS_OUTPUTS_ONLY, FLAGS_SPENDS_AND_OUTPUTS,
};
use dpp::consensus::basic::state_transition::WithdrawalBelowMinAmountError;
use dpp::consensus::basic::BasicError;
use dpp::consensus::state::shielded::insufficient_shielded_fee_error::InsufficientShieldedFeeError;
use dpp::consensus::state::state_error::StateError;
use dpp::shielded::SHIELDED_STORAGE_BYTES_PER_ACTION;
use dpp::state_transition::state_transitions::address_funds::address_credit_withdrawal_transition::MIN_WITHDRAWAL_AMOUNT;
use dpp::state_transition::StateTransition;
use dpp::validation::SimpleConsensusValidationResult;
use dpp::version::PlatformVersion;
Expand Down Expand Up @@ -68,11 +71,21 @@ impl StateTransitionHasShieldedProofValidationV0 for StateTransition {
/// The minimum fee is computed dynamically based on the number of actions:
/// min_fee = proof_verification_fee + num_actions × (processing_fee + storage_fee)
///
/// The fee is derived from the public `value_balance` field (no ZK proof execution needed):
/// - ShieldedTransfer: fee = value_balance
/// - Unshield: fee = value_balance - amount
/// - ShieldedWithdrawal: fee = value_balance - amount
/// - Shield: fee paid by transparent address inputs (skipped here)
/// The amount checked against `min_fee` is derived from public fields (no ZK proof
/// execution needed):
/// - ShieldedTransfer: the whole `value_balance` is the fee, so we check `value_balance >= min_fee`.
/// - Unshield / ShieldedWithdrawal: `unshielding_amount` is the TOTAL value leaving the
/// shielded pool (recipient/net amount + fee). The fee actually charged at execution time
/// is `compute_minimum_shielded_fee` (carved out of `unshielding_amount`), and the
/// recipient/net receives `unshielding_amount - fee`. Requiring `unshielding_amount >= min_fee`
/// guarantees that net amount is non-negative.
/// - ShieldedWithdrawal additionally requires the net (`unshielding_amount - min_fee`) to
/// meet `MIN_WITHDRAWAL_AMOUNT`, because that net becomes a Core `TxOut` and is subject to
/// the same dust floor as the transparent withdrawal path. Without this, a transition that
/// only just covers the fee would queue a zero/sub-dust withdrawal document (rejected
/// downstream as `CorruptedDriveState`, or a malformed entry in the withdrawal queue).
/// Unshield has no such floor: its net is credited to a platform address, not Core.
/// - Shield: fee paid by transparent address inputs (skipped here).
pub(crate) trait StateTransitionShieldedMinimumFeeValidationV0 {
fn validate_minimum_shielded_fee(
&self,
Expand All @@ -91,30 +104,38 @@ impl StateTransitionShieldedMinimumFeeValidationV0 for StateTransition {
.validate_minimum_shielded_fee
{
0 => {
// Extract the fee and action count from the transition.
let (fee, num_actions): (i64, usize) = match self {
// Extract the checked amount, action count, and the minimum NET amount
// (value left after the fee) the transition must leave behind. The net
// floor is `MIN_WITHDRAWAL_AMOUNT` only for ShieldedWithdrawal (whose net
// becomes a Core `TxOut`); for the others a non-negative net suffices, so
// the floor is 0.
let (fee, num_actions, min_net_amount): (i64, usize, u64) = match self {
// Shield: fee is paid from transparent address inputs, not from value_balance.
StateTransition::Shield(_) => {
return Ok(SimpleConsensusValidationResult::new())
}
// ShieldedTransfer: value_balance (u64) IS the fee.
StateTransition::ShieldedTransfer(st) => match st {
dpp::state_transition::shielded_transfer_transition::ShieldedTransferTransition::V0(v0) => {
(v0.value_balance as i64, v0.actions.len())
(v0.value_balance as i64, v0.actions.len(), 0)
}
},
// Unshield: fee = value_balance - amount.
// Unshield: `unshielding_amount` is the TOTAL leaving the pool
// (recipient/net + fee). We check it against `min_fee` so the net
// (`unshielding_amount - compute_minimum_shielded_fee`) credited to
// the recipient at execution time is non-negative. The net is credited
// to a platform address (not Core), so no dust floor applies.
StateTransition::Unshield(st) => match st {
dpp::state_transition::unshield_transition::UnshieldTransition::V0(
v0,
) => {
// unshielding_amount is the total leaving the pool (fee is validated separately)
(v0.unshielding_amount as i64, v0.actions.len())
}
) => (v0.unshielding_amount as i64, v0.actions.len(), 0),
},
// ShieldedWithdrawal: the net (`unshielding_amount - min_fee`) becomes a
// Core `TxOut`, so it must clear the same `MIN_WITHDRAWAL_AMOUNT` dust
// floor the transparent withdrawal path enforces.
StateTransition::ShieldedWithdrawal(st) => match st {
dpp::state_transition::shielded_withdrawal_transition::ShieldedWithdrawalTransition::V0(v0) => {
(v0.unshielding_amount as i64, v0.actions.len())
(v0.unshielding_amount as i64, v0.actions.len(), MIN_WITHDRAWAL_AMOUNT)
}
},
// Other transitions don't go through shielded fee validation.
Expand Down Expand Up @@ -156,7 +177,7 @@ impl StateTransitionShieldedMinimumFeeValidationV0 for StateTransition {
)))?;

if (fee as u64) < minimum_shielded_fee {
Ok(SimpleConsensusValidationResult::new_with_error(
return Ok(SimpleConsensusValidationResult::new_with_error(
StateError::InsufficientShieldedFeeError(
InsufficientShieldedFeeError::new(format!(
"shielded transition fee {} is below minimum required fee {} \
Expand All @@ -169,10 +190,28 @@ impl StateTransitionShieldedMinimumFeeValidationV0 for StateTransition {
)),
)
.into(),
))
} else {
Ok(SimpleConsensusValidationResult::new())
));
}

// For ShieldedWithdrawal, the net value leaving to Core
// (`unshielding_amount - min_fee`) must also clear the dust floor; for the
// other shielded paths `min_net_amount` is 0 and this check is a no-op.
// Safe: `fee as u64 >= minimum_shielded_fee` was just checked above.
let net_amount = (fee as u64) - minimum_shielded_fee;
if net_amount < min_net_amount {
return Ok(SimpleConsensusValidationResult::new_with_error(
BasicError::WithdrawalBelowMinAmountError(
WithdrawalBelowMinAmountError::new(
net_amount,
min_net_amount,
platform_version.system_limits.max_withdrawal_amount,
),
)
.into(),
));
}

Ok(SimpleConsensusValidationResult::new())
}
version => Err(Error::Execution(ExecutionError::UnknownVersionMismatch {
method: "StateTransition::validate_minimum_shielded_fee".to_string(),
Expand Down Expand Up @@ -452,6 +491,22 @@ mod tests {
mod validate_minimum_shielded_fee {
use super::*;

/// A ShieldedWithdrawal transition (no actions) with the given gross amount.
fn shielded_withdrawal_with_amount(unshielding_amount: u64) -> StateTransition {
StateTransition::ShieldedWithdrawal(ShieldedWithdrawalTransition::V0(
ShieldedWithdrawalTransitionV0 {
actions: vec![],
unshielding_amount,
anchor: [0u8; 32],
proof: vec![],
binding_signature: [0u8; 64],
core_fee_per_byte: 0,
pooling: Default::default(),
output_script: Default::default(),
},
))
}

#[test]
fn should_pass_for_non_shielded_transition() {
let platform_version = &platform_version::version::v9::PLATFORM_V9;
Expand All @@ -461,6 +516,36 @@ mod tests {
.expect("should not error");
assert!(result.is_valid());
}

#[test]
fn should_reject_shielded_withdrawal_with_net_below_min_withdrawal_amount() {
let platform_version = PlatformVersion::latest();
let min_fee = dpp::shielded::compute_minimum_shielded_fee(0, platform_version);
// net = MIN_WITHDRAWAL_AMOUNT - 1 → just below the Core dust floor.
let st = shielded_withdrawal_with_amount(min_fee + MIN_WITHDRAWAL_AMOUNT - 1);
let result = st
.validate_minimum_shielded_fee(platform_version)
.expect("should not error");
assert!(
!result.is_valid(),
"a withdrawal whose net is below MIN_WITHDRAWAL_AMOUNT must be rejected at validation"
);
}

#[test]
fn should_accept_shielded_withdrawal_with_net_at_min_withdrawal_amount() {
let platform_version = PlatformVersion::latest();
let min_fee = dpp::shielded::compute_minimum_shielded_fee(0, platform_version);
// net = MIN_WITHDRAWAL_AMOUNT exactly → at the floor, accepted.
let st = shielded_withdrawal_with_amount(min_fee + MIN_WITHDRAWAL_AMOUNT);
let result = st
.validate_minimum_shielded_fee(platform_version)
.expect("should not error");
assert!(
result.is_valid(),
"a withdrawal whose net equals MIN_WITHDRAWAL_AMOUNT must be accepted"
);
}
}

mod validate_shielded_proof {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ mod tests {
fn create_default_shielded_withdrawal_transition() -> StateTransition {
create_shielded_withdrawal_transition(
vec![create_dummy_serialized_action()],
111_549_800, // unshielding_amount: recipient amount + minimum fee for 1 action
112_548_800, // unshielding_amount: recipient (1_000_000, above MIN_WITHDRAWAL_AMOUNT) + min fee for 1 action
[42u8; 32], // non-zero anchor
vec![0u8; 100], // dummy proof bytes
[0u8; 64], // dummy binding signature
Expand Down Expand Up @@ -796,7 +796,7 @@ mod tests {

let transition = create_shielded_withdrawal_transition(
vec![action1, action2], // Both have nullifier [1u8; 32]
123_098_600, // unshielding_amount: recipient amount + minimum fee for 2 actions
124_097_600, // unshielding_amount: recipient (1_000_000, above MIN_WITHDRAWAL_AMOUNT) + min fee for 2 actions
anchor,
vec![0u8; 100],
[0u8; 64],
Expand Down Expand Up @@ -1056,4 +1056,145 @@ mod tests {
);
}
}

mod credit_conservation {
use super::*;
use crate::execution::validation::state_transition::tests::process_state_transitions;
use dpp::block::block_info::BlockInfo;
use grovedb_commitment_tree::{
Builder, BundleType, ClientMemoryCommitmentTree, DashMemo, ExtractedNoteCommitment,
FullViewingKey, Note, NoteValue, Position, RandomSeed, Retention, Rho, Scope,
SpendAuthorizingKey, SpendingKey,
};
use rand::rngs::StdRng;
use rand::SeedableRng;

/// Block-level conservation test for shielded withdrawal. Spends a 500M note
/// and withdraws `value_balance` worth from the pool. Runs the FULL block
/// pipeline (execute + fee distribution + sum-tree validation) and asserts:
/// - total platform credits stay conserved (the invariant whose failure
/// halts the chain),
/// - the shielded pool drops by exactly `unshielding_amount`, and
/// - the system-credit counter drops by the NET (`unshielding_amount - fee`)
/// — only the net leaves the platform to Core; the fee stays in the fee
/// pools. This exercises the `RemoveFromSystemCredits(net)` accounting the
/// conversion-level tests cannot fully validate end-to-end.
#[test]
fn test_shielded_withdrawal_conserves_credits() {
let platform_version = PlatformVersion::latest();
let platform = setup_platform();
insert_dummy_encrypted_notes(&platform, 250);
// Seeded RNG for deterministic, bisectable test randomness (repo convention).
let mut rng = StdRng::seed_from_u64(0);
let pk = get_proving_key();

let sk = SpendingKey::from_bytes([0u8; 32]).unwrap();
let fvk = FullViewingKey::from(&sk);
let recipient = fvk.address_at(0u32, Scope::External);
let ask = SpendAuthorizingKey::from(&sk);

let rho_bytes: [u8; 32] = {
let mut b = [0u8; 32];
b[0] = 1;
b
};
let rho = Rho::from_bytes(&rho_bytes).unwrap();
let rseed = RandomSeed::from_bytes([42u8; 32], &rho).unwrap();
let note =
Note::from_parts(recipient, NoteValue::from_raw(500_000_000), rho, rseed).unwrap();

let cmx = ExtractedNoteCommitment::from(note.commitment());
let mut tree = ClientMemoryCommitmentTree::new(100);
tree.append(cmx.to_bytes(), Retention::Marked).unwrap();
tree.checkpoint(0u32).unwrap();
let anchor = tree.anchor().unwrap();
let merkle_path = tree.witness(Position::from(0u64), 0).unwrap().unwrap();

let mut builder = Builder::<DashMemo>::new(BundleType::DEFAULT, anchor);
builder.add_spend(fvk.clone(), note, merkle_path).unwrap();
builder
.add_output(None, recipient, NoteValue::from_raw(5_000), [0u8; 36])
.unwrap();
let (unauthorized, _) = builder.build::<i64>(&mut rng).unwrap().unwrap();

let output_script = create_output_script();
let unshielding_amount = 499_995_000u64;
let mut extra_sighash_data = output_script.as_bytes().to_vec();
extra_sighash_data.extend_from_slice(&unshielding_amount.to_le_bytes());
let bundle_commitment: [u8; 32] = unauthorized.commitment().into();
let sighash = compute_platform_sighash(&bundle_commitment, &extra_sighash_data);
let proven = unauthorized.create_proof(pk, &mut rng).unwrap();
let bundle = proven.apply_signatures(rng, sighash, &[ask]).unwrap();

let (actions, value_balance, anchor_bytes, proof_bytes, binding_sig) =
serialize_authorized_bundle_i64(&bundle);
assert_eq!(value_balance, 499_995_000);
let num_actions = actions.len();

insert_anchor_into_state(&platform, &anchor_bytes);
set_pool_total_balance(&platform, 500_000_000);

// Capture a balanced starting state (set_pool_total_balance adds matching
// system credits, so the counter and the sum trees agree).
let credits_before = platform
.drive
.calculate_total_credits_balance(None, &platform_version.drive)
.expect("should calculate total credits before withdrawal");
assert!(
credits_before
.ok()
.expect("credit balance check should not overflow"),
"credits must be balanced before the withdrawal: {}",
credits_before
);

let transition = create_shielded_withdrawal_transition(
actions,
unshielding_amount,
anchor_bytes,
proof_bytes,
binding_sig,
1,
Pooling::Never,
output_script,
);

let platform_state = platform.state.load();
let (_fee_results, _processed_block_fees) = process_state_transitions(
&platform,
&[transition],
BlockInfo::default(),
&platform_state,
);

let credits_after = platform
.drive
.calculate_total_credits_balance(None, &platform_version.drive)
.expect("should calculate total credits after withdrawal");
assert!(
credits_after
.ok()
.expect("credit balance check should not overflow"),
"credits must remain balanced after a shielded withdrawal: {}",
credits_after
);

// The shielded pool dropped by exactly the full unshielding_amount.
assert_eq!(
credits_before.total_in_shielded_balances
- credits_after.total_in_shielded_balances,
unshielding_amount as i64,
"shielded pool must drop by the full unshielding amount"
);

// The system-credit counter dropped by the NET (unshielding_amount - fee):
// only the net leaves the platform to Core; the fee stays in the fee pools.
let fee = dpp::shielded::compute_minimum_shielded_fee(num_actions, platform_version);
assert_eq!(
credits_before.total_credits_in_platform - credits_after.total_credits_in_platform,
unshielding_amount - fee,
"system credits must drop by exactly the net withdrawn to Core (amount - fee)"
);
}
}
}
Loading
Loading