Skip to content
Merged
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
Binary file not shown.
Binary file modified artifacts/lez/programs/fee.bin
Binary file not shown.
1 change: 1 addition & 0 deletions integration_tests/tests/async_payouts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ fn prove_trade(
recipient: system_accounts::fee_inbox_account_id(),
amount: fee_reserve(),
refund_to: None,
tip: 0,
}),
},
// One public segment each for the deposit and the request; neither sends anything back.
Expand Down
2 changes: 2 additions & 0 deletions lee/privacy_preserving_circuit/src/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ pub fn compute_circuit_output(
.unwrap_or_else(|e| panic!("{e}"));
let fee = fee.map(|fee| ProvenFee {
refund_to: fee.refund_to,
tip: fee.tip,
fallback: fee_fallback(&fee, &boundary, private_witnesses, ciphertext_padding),
});
let mut output = ProvenExecution {
Expand Down Expand Up @@ -465,6 +466,7 @@ mod tests {
recipient: inbox,
amount: 30,
refund_to: None,
tip: 0,
};
let crossing = |amount| {
BoundaryStep::PrivateToPublic(lee_core::execution_state::Delivery {
Expand Down
5 changes: 4 additions & 1 deletion lee/state_machine/core/src/circuit_io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use crate::{
AuthorizationSecretKey, Commitment, CommitmentSetDigest, InvalidMembershipProof,
MembershipProof, Nullifier, NullifierPublicKey, NullifierSecretKey,
account::{Account, AccountId, Actor, Balance, Nonce},
account::{Account, AccountId, Actor, Balance, Fee, Nonce},
compute_digest_for_path,
encryption::{EncryptedNote, ViewingPublicKey},
execution_state::{Boundary, PredictedCrossMessages, PublicExecutionContext, TransactionEntry},
Expand Down Expand Up @@ -151,13 +151,16 @@ pub struct FeeTransfer {
/// A public account the zone returns any unspent part of the transfer to; `None` returns it
/// to `payer` as presented.
pub refund_to: Option<AccountId>,
/// The part of `amount` the zone pays its producer as a tip.
pub tip: Fee,
}

/// What a proof commits about its fee transfer, see [`FeeTransfer`].
#[derive(BorshSerialize, BorshDeserialize)]
#[cfg_attr(any(feature = "host", test), derive(Debug, Clone, PartialEq, Eq))]
pub struct ProvenFee {
pub refund_to: Option<AccountId>,
pub tip: Fee,
/// What settlement applies instead of the private actions when the public part fails, if the
/// payer's pre-state covers the transfer on its own.
pub fallback: Option<FeeFallback>,
Expand Down
1 change: 1 addition & 0 deletions lee/state_machine/core/src/execution_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1123,6 +1123,7 @@ impl<'witnesses, M: Mode> Executor<'witnesses, M> {
recipient,
amount,
refund_to: _,
tip: _,
}) = fee
else {
return;
Expand Down
2 changes: 2 additions & 0 deletions lee/state_machine/core/src/execution_state/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1586,6 +1586,7 @@ fn a_fee_transfer_runs_after_the_root_in_every_mode() {
recipient: inbox.account_id,
amount: 0,
refund_to: None,
tip: 0,
};
let native = |input: &ReceiveInput| {
native_token::handle_message(input).unwrap_or_else(|error| panic!("{error}"))
Expand Down Expand Up @@ -1680,6 +1681,7 @@ fn a_fee_only_payer_authorizes_the_fee_entry_alone() {
recipient: inbox.account_id,
amount: 0,
refund_to: None,
tip: 0,
};
let run = |kind: RegularKey| {
let mut script = Script::default().on(payer, |input| echo(input, Response::keep_state()));
Expand Down
2 changes: 2 additions & 0 deletions lee/state_machine/src/state/tests/publications.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ fn clear_credit(state: &V03State) -> PrivacyPreservingTransaction {
recipient: INBOX,
amount: FEE,
refund_to: None,
tip: 0,
}),
..proving_input(root(
Actor::native_balance(alice()),
Expand Down Expand Up @@ -122,6 +123,7 @@ fn fee_paying_public_root(state: &V03State, script: &Script) -> PrivacyPreservin
recipient: INBOX,
amount: FEE,
refund_to: None,
tip: 0,
}),
..proving_input(root(sender(), script))
},
Expand Down
134 changes: 114 additions & 20 deletions lez/chain_state/src/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,7 @@ fn settle_private_transaction(
payer,
reserve,
data_bytes,
tip: proven_tip,
},
) = (transaction, view)
else {
Expand All @@ -516,13 +517,13 @@ fn settle_private_transaction(
accumulate_exec_gas(summary.gas_used_exec, market::PRIVATE_VERIFY_GAS).map_err(gas_cap)?;
let gas_used_stor = accumulate_stor_gas(summary.gas_used_stor, *data_bytes).map_err(gas_cap)?;
// The effects may use what is left of the block's execution gas, up to what the reserve
// pays for, so a public part running out of it is a charged revert and never costs more
// than was reserved.
// pays for past the tip, so running out of it is a charged revert.
let proven_tip = u128::from(*proven_tip);
let cycle_budget = market::MAX_GAS_EXEC
.checked_sub(gas_used_exec)
.expect("the accumulator is cap-checked")
.min(private_cycles_affordable(
*reserve,
reserve.saturating_sub(proven_tip),
*data_bytes,
opening.base_fee_exec,
opening.base_fee_stor,
Expand All @@ -548,10 +549,13 @@ fn settle_private_transaction(
opening.base_fee_exec,
opening.base_fee_stor,
);
let surplus = reserve.checked_sub(actual).ok_or_else(|| {
let required = actual
.checked_add(proven_tip)
.expect("a fee and a u64 tip fit u128");
let surplus = reserve.checked_sub(required).ok_or_else(|| {
fee_validity(
FeeError::PrivateFeeBelowRequired {
required: actual,
required,
reserve: *reserve,
}
.to_string(),
Expand All @@ -568,9 +572,8 @@ fn settle_private_transaction(
.apply_state_diff(diff)
.map_err(|err| fee_validity(format!("private action failed: {err}")))?;

// A surplus worth a note goes to the public refund target, else back to the payer if a
// recovery binding lets it be published there; dust and an unbound payer's surplus stay
// as tip.
// A surplus worth a note goes to the refund target, else to a bound payer; otherwise it
// adds to the tip.
let refund_to = private_tx
.message()
.execution
Expand All @@ -579,9 +582,14 @@ fn settle_private_transaction(
.and_then(|fee| fee.refund_to);
let refundable = refund_to.is_some() || state.recovery_binding(*payer).is_some();
let (refund, tip) = if surplus > market::MIN_PRIVATE_REFUND && refundable {
(surplus, 0)
(surplus, proven_tip)
} else {
(0, surplus)
(
0,
proven_tip
.checked_add(surplus)
.expect("the tip and surplus fit in the reserve"),
)
};
if refund > 0 {
let refund_msg = refund_to.map_or_else(
Expand Down Expand Up @@ -1870,6 +1878,7 @@ mod tests {
recipient: system_accounts::fee_inbox_account_id(),
amount,
refund_to: None,
tip: 0,
}
}

Expand Down Expand Up @@ -2080,6 +2089,80 @@ mod tests {
assert_eq!(published_credit(&settled, alias), Some(surplus));
}

#[test]
fn a_private_transaction_pays_its_proven_tip_before_the_refund() {
const TIP: u64 = 5;
let (state, senders) = private_sender_state(&[0x58]);
let sender = &senders[0];
let alias = sender.0.account_id().blinded(&ALIAS_OPENING);
let recipient = initial_pub_accounts_private_keys()[0].account_id;
let build = |amount| {
private_tx(
&state,
sender,
recipient,
10,
Some(lee_core::FeeTransfer {
tip: TIP,
..inbox_fee(amount, sender.0.account_id())
}),
)
};
let required = required_for(0, build);
let surplus = fee_core::market::MIN_PRIVATE_REFUND + 1;
let tx = build(required + u128::from(TIP) + surplus);

let mut settled = state.clone();
let mut summary = BlockFeeSummary::default();
let (_, receipt) = settle_transaction(
&tx,
&mut settled,
&FeeState::genesis(),
1,
100,
0,
&mut summary,
)
.expect("a reserve covering the fee and tip settles");
assert_eq!(summary.revenue_base, required);
assert_eq!(summary.revenue_tip, u128::from(TIP));
assert_eq!(receipt.fee.tip, u128::from(TIP));
assert_eq!(receipt.fee.refund, surplus);
assert_eq!(published_credit(&settled, alias), Some(surplus));

// A dust surplus adds to the proven tip.
let dust = fee_core::market::MIN_PRIVATE_REFUND;
let mut dust_summary = BlockFeeSummary::default();
let (_, dust_receipt) = settle_transaction(
&build(required + u128::from(TIP) + dust),
&mut state.clone(),
&FeeState::genesis(),
1,
100,
0,
&mut dust_summary,
)
.expect("settles");
assert_eq!(dust_summary.revenue_tip, u128::from(TIP) + dust);
assert_eq!(dust_receipt.fee.tip, u128::from(TIP) + dust);
assert_eq!(dust_receipt.fee.refund, 0);

// A reserve covering the fee but not the tip is not admissible.
let short = build(required + u128::from(TIP) - 1);
assert!(matches!(
settle_transaction(
&short,
&mut state.clone(),
&FeeState::genesis(),
1,
100,
0,
&mut BlockFeeSummary::default(),
),
Err(BlockIngestError::InvalidFeeClass { .. })
));
}

#[test]
fn an_unbound_payers_surplus_is_kept_as_tip() {
let (state, senders) = private_sender_state(&[0x56]);
Expand Down Expand Up @@ -2244,17 +2327,21 @@ mod tests {
// The block has `budget` execution gas left after the proof's verification: the
// scripted public root runs out of it, which settlement charges in full.
let budget = 5_000;
let tip = 5;
let build = |amount| {
public_root_private_tx(
&state,
sender,
scripted,
inbox_fee(amount, sender.0.account_id()),
lee_core::FeeTransfer {
tip,
..inbox_fee(amount, sender.0.account_id())
},
)
};
let required = required_for(budget, build);
let surplus = fee_core::market::MIN_PRIVATE_REFUND + 1;
let tx = build(required + surplus);
let tx = build(required + u128::from(tip) + surplus);
let LeeTransaction::PrivacyPreserving(private_tx) = &tx else {
unreachable!("a privacy-preserving transaction was built");
};
Expand Down Expand Up @@ -2291,19 +2378,19 @@ mod tests {
gas_exec: fee_core::market::PRIVATE_VERIFY_GAS + budget,
gas_stor: summary.gas_used_stor,
fee_base: required,
tip: 0,
tip: u128::from(tip),
refund: surplus,
},
}
);
assert!(events.is_empty());
assert_eq!(summary.gas_used_exec, fee_core::market::MAX_GAS_EXEC);
assert_eq!(summary.revenue_base, required);
assert_eq!(summary.revenue_tip, 0);
assert_eq!(summary.revenue_tip, u128::from(tip));
// The reserve reached the inbox and the surplus went back to the alias.
assert_eq!(
native_balance(&settled, system_accounts::fee_inbox_account_id()),
required
required + u128::from(tip)
);
assert_eq!(published_credit(&settled, alias), Some(surplus));
// The payer's note is spent for the fallback's state; none of the other proven
Expand All @@ -2330,18 +2417,24 @@ mod tests {
initial_pub_accounts_private_keys()[0].account_id,
AccountId::from_builtin_program(event_emitter().id()),
);
// The block is empty, but the reserve pays for only `budget` cycles, which the scripted
// public root runs out of: a charged revert, not a fee above the reserve.
// The block is empty, but the reserve pays for only `budget` cycles past the tip, which
// the scripted public root runs out of: a charged revert, not a fee above the reserve.
let budget = 5_000;
// Worth 100 cycles at the genesis base fee, so a budget that ignored it would show.
let tip = 800;
let build = |amount| {
public_root_private_tx(
&state,
sender,
scripted,
inbox_fee(amount, sender.0.account_id()),
lee_core::FeeTransfer {
tip,
..inbox_fee(amount, sender.0.account_id())
},
)
};
let reserve = required_for(budget, build);
let required = required_for(budget, build);
let reserve = required + u128::from(tip);
let tx = build(reserve);

let mut settled = state;
Expand All @@ -2361,7 +2454,8 @@ mod tests {
summary.gas_used_exec,
fee_core::market::PRIVATE_VERIFY_GAS + budget
);
assert_eq!(summary.revenue_base, reserve);
assert_eq!(summary.revenue_base, required);
assert_eq!(summary.revenue_tip, u128::from(tip));
assert_eq!(
native_balance(&settled, system_accounts::fee_inbox_account_id()),
reserve
Expand Down
12 changes: 10 additions & 2 deletions lez/chain_state/src/classify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ pub fn classify(tx: &LeeTransaction, is_genesis: bool) -> Result<FeeClass, Class
payer,
reserve,
data_bytes: tx.charged_bytes()?,
tip: execution.proven_fee.as_ref().map_or(0, |fee| fee.tip),
}));
}
LeeTransaction::Public(public_tx) => public_tx,
Expand Down Expand Up @@ -289,7 +290,7 @@ mod tests {
let class = classify(&tx, false).unwrap();
assert!(matches!(
class,
FeeClass::Charged(FeeTxView::Private { payer, reserve: 42, data_bytes })
FeeClass::Charged(FeeTxView::Private { payer, reserve: 42, data_bytes, tip: 0 })
if payer == self::payer().account_id && data_bytes == size
));
}
Expand Down Expand Up @@ -349,6 +350,7 @@ mod tests {
message.execution.boundary = crediting();
message.execution.proven_fee = Some(lee_core::ProvenFee {
refund_to: Some(target),
tip: 7,
fallback: None,
});
tx(message)
Expand All @@ -359,7 +361,11 @@ mod tests {
));
assert!(matches!(
classify(&targeting(AccountId::new([3; 32])), false),
Ok(FeeClass::Charged(FeeTxView::Private { reserve: 42, .. }))
Ok(FeeClass::Charged(FeeTxView::Private {
reserve: 42,
tip: 7,
..
}))
));
}

Expand All @@ -377,6 +383,7 @@ mod tests {
};
message.execution.proven_fee = proven_fee.then_some(lee_core::ProvenFee {
refund_to: None,
tip: 0,
fallback: None,
});
if crossing_inbox {
Expand Down Expand Up @@ -424,6 +431,7 @@ mod tests {
message.execution.boundary = vec![credit.clone(), BoundaryStep::EndPublicSubtree];
message.execution.proven_fee = Some(lee_core::ProvenFee {
refund_to: None,
tip: 0,
fallback: Some(lee_core::FeeFallback {
action: lee_core::PrivateAction::default(),
boundary,
Expand Down
Loading
Loading