use borsh::BorshDeserialize;
use pyde_crypto::poseidon2::poseidon2_hash;
use crate::error::SdkError;
use crate::types::{
AccessEntry, Address, CommitPayload, FalconSignature, FeePayer, Gas, RevealPayload, Tx, TxHash,
TxType,
};
pub const COMMITMENT_DOMAIN_TAG: &[u8] = b"pyde-commit-reveal-v1";
pub const COMMIT_REVEAL_WINDOW_WAVES: u64 = 120;
pub const MIN_COMMIT_BOND: u128 = 1_000_000_000;
pub const COMMIT_BOND_BPS: u128 = 100;
#[must_use]
pub fn commitment_hash(inner_tx_bytes: &[u8], nonce: &[u8; 32]) -> [u8; 32] {
let mut hasher = blake3::Hasher::new();
hasher.update(COMMITMENT_DOMAIN_TAG);
hasher.update(inner_tx_bytes);
hasher.update(nonce);
*hasher.finalize().as_bytes()
}
#[must_use]
pub fn required_bond(value_ceiling: u128) -> u128 {
let scaled = value_ceiling
.saturating_mul(COMMIT_BOND_BPS)
.saturating_div(10_000);
scaled.max(MIN_COMMIT_BOND)
}
#[must_use]
pub fn tx_hash(tx: &Tx) -> TxHash {
let data_digest: [u8; 32] = poseidon2_hash(&tx.data).into();
let access_list_digest = hash_access_list(&tx.access_list);
let fee_payer_bytes = encode_fee_payer_tag(&tx.fee_payer);
let deadline_bytes = encode_deadline_tag(tx.deadline);
let mut preimage = Vec::with_capacity(
8 + 32 + 32 + 16 + 32 + 8 + 8 + fee_payer_bytes.len() + 32 + deadline_bytes.len() + 1, );
preimage.extend_from_slice(&tx.chain_id.to_le_bytes());
preimage.extend_from_slice(tx.from.as_bytes());
preimage.extend_from_slice(tx.to.as_bytes());
preimage.extend_from_slice(&tx.value.to_le_bytes());
preimage.extend_from_slice(&data_digest);
preimage.extend_from_slice(&tx.gas_limit.to_le_bytes());
preimage.extend_from_slice(&tx.nonce.to_le_bytes());
preimage.extend_from_slice(&fee_payer_bytes);
preimage.extend_from_slice(&access_list_digest);
preimage.extend_from_slice(&deadline_bytes);
preimage.push(tx_type_tag(&tx.tx_type));
let digest: [u8; 32] = poseidon2_hash(&preimage).into();
TxHash::new(digest)
}
fn hash_access_list(list: &[AccessEntry]) -> [u8; 32] {
let encoded = borsh::to_vec(list).unwrap_or_default();
poseidon2_hash(&encoded).into()
}
fn encode_fee_payer_tag(payer: &FeePayer) -> Vec<u8> {
match payer {
FeePayer::Sender => vec![0x00],
FeePayer::GasTank => vec![0x01],
FeePayer::Paymaster(addr) => {
let mut out = Vec::with_capacity(1 + 32);
out.push(0x02);
out.extend_from_slice(addr.as_bytes());
out
}
}
}
fn encode_deadline_tag(deadline: Option<u64>) -> Vec<u8> {
match deadline {
None => vec![0x00],
Some(d) => {
let mut out = Vec::with_capacity(1 + 8);
out.push(0x01);
out.extend_from_slice(&d.to_le_bytes());
out
}
}
}
fn tx_type_tag(t: &TxType) -> u8 {
match t {
TxType::Standard => 0x00,
TxType::Deploy => 0x01,
TxType::StakeDeposit => 0x03,
TxType::StakeWithdraw => 0x04,
TxType::Slash => 0x05,
TxType::ClaimReward => 0x06,
TxType::ClaimAirdrop => 0x07,
TxType::SweepAirdrop => 0x08,
TxType::MultisigTx => 0x09,
TxType::RotateMultisig => 0x0A,
TxType::EmergencyPause => 0x0B,
TxType::EmergencyResume => 0x0C,
TxType::RegisterPubkey => 0x0D,
TxType::Unjail => 0x0E,
TxType::RotateValidatorKeys => 0x0F,
TxType::DisputeSlash => 0x10,
TxType::Commit => 0x11,
TxType::Reveal => 0x12,
}
}
pub fn encode(tx: &Tx) -> Result<Vec<u8>, SdkError> {
borsh::to_vec(tx).map_err(|e| SdkError::Other(format!("borsh encode: {e}")))
}
pub fn decode(bytes: &[u8]) -> Result<Tx, SdkError> {
Tx::try_from_slice(bytes).map_err(|e| SdkError::InvalidArgument(format!("borsh decode: {e}")))
}
#[derive(Clone, Debug)]
pub struct TxBuilder {
from: Option<Address>,
to: Address,
value: u128,
data: Vec<u8>,
gas_limit: Gas,
nonce: u64,
fee_payer: FeePayer,
access_list: Vec<AccessEntry>,
deadline: Option<u64>,
chain_id: u64,
tx_type: TxType,
}
impl Default for TxBuilder {
fn default() -> Self {
Self::new()
}
}
impl TxBuilder {
#[must_use]
pub fn new() -> Self {
Self {
from: None,
to: Address::ZERO,
value: 0,
data: Vec::new(),
gas_limit: crate::types::MIN_GAS_LIMIT,
nonce: 0,
fee_payer: FeePayer::Sender,
access_list: Vec::new(),
deadline: None,
chain_id: 1,
tx_type: TxType::Standard,
}
}
#[must_use]
pub fn from(mut self, addr: Address) -> Self {
self.from = Some(addr);
self
}
#[must_use]
pub fn to(mut self, addr: Address) -> Self {
self.to = addr;
self
}
#[must_use]
pub fn value(mut self, quanta: u128) -> Self {
self.value = quanta;
self
}
#[must_use]
pub fn data(mut self, bytes: Vec<u8>) -> Self {
self.data = bytes;
self
}
#[must_use]
pub fn gas_limit(mut self, gas: Gas) -> Self {
self.gas_limit = gas;
self
}
#[must_use]
pub fn nonce(mut self, nonce: u64) -> Self {
self.nonce = nonce;
self
}
#[must_use]
pub fn fee_payer(mut self, payer: FeePayer) -> Self {
self.fee_payer = payer;
self
}
#[must_use]
pub fn access_list(mut self, list: Vec<AccessEntry>) -> Self {
self.access_list = list;
self
}
#[must_use]
pub fn deadline(mut self, wave: u64) -> Self {
self.deadline = Some(wave);
self
}
#[must_use]
pub fn clear_deadline(mut self) -> Self {
self.deadline = None;
self
}
#[must_use]
pub fn chain_id(mut self, id: u64) -> Self {
self.chain_id = id;
self
}
#[must_use]
pub fn tx_type(mut self, ty: TxType) -> Self {
self.tx_type = ty;
self
}
#[must_use]
pub fn transfer(self, to: Address, quanta: u128) -> Self {
self.tx_type(TxType::Standard).to(to).value(quanta)
}
pub fn deploy(
self,
name: impl Into<String>,
wasm_bytes: Vec<u8>,
contract_type: crate::types::ContractType,
init_calldata: Vec<u8>,
) -> Result<Self, SdkError> {
let data = borsh::to_vec(&crate::types::DeployData {
name: name.into(),
wasm_bytes,
contract_type,
init_calldata,
})
.map_err(|e| SdkError::Other(format!("borsh encode DeployData: {e}")))?;
Ok(self.tx_type(TxType::Deploy).to(Address::ZERO).data(data))
}
#[must_use]
pub fn call(self, contract: Address, calldata: Vec<u8>) -> Self {
self.tx_type(TxType::Standard).to(contract).data(calldata)
}
pub fn multisig_treasury_spend(
self,
target: Address,
amount: u128,
bundle: crate::multisig::SigBundle,
) -> Result<Self, SdkError> {
let payload = crate::multisig::MultisigTxPayload {
target,
amount,
bundle,
};
let data = borsh::to_vec(&payload)
.map_err(|e| SdkError::Other(format!("borsh encode MultisigTxPayload: {e}")))?;
Ok(self
.tx_type(TxType::MultisigTx)
.to(Address::ZERO)
.data(data))
}
pub fn commit(self, commitment: [u8; 32], value_ceiling: u128) -> Result<Self, SdkError> {
let data = borsh::to_vec(&CommitPayload {
commitment,
value_ceiling,
})
.map_err(|e| SdkError::Other(format!("borsh encode CommitPayload: {e}")))?;
Ok(self
.tx_type(TxType::Commit)
.to(Address::ZERO)
.value(required_bond(value_ceiling))
.data(data))
}
pub fn reveal(
self,
commitment: [u8; 32],
nonce: [u8; 32],
inner_tx_bytes: Vec<u8>,
) -> Result<Self, SdkError> {
let data = borsh::to_vec(&RevealPayload {
commitment,
nonce,
inner_tx: inner_tx_bytes,
})
.map_err(|e| SdkError::Other(format!("borsh encode RevealPayload: {e}")))?;
Ok(self
.tx_type(TxType::Reveal)
.to(Address::ZERO)
.value(0)
.data(data))
}
pub fn build(self) -> Result<Tx, SdkError> {
let from = self.from.ok_or_else(|| {
SdkError::InvalidArgument("from address must be set on TxBuilder".into())
})?;
Ok(Tx {
from,
to: self.to,
value: self.value,
data: self.data,
gas_limit: self.gas_limit,
nonce: self.nonce,
signature: FalconSignature::new(Vec::new()),
fee_payer: self.fee_payer,
access_list: self.access_list,
deadline: self.deadline,
chain_id: self.chain_id,
tx_type: self.tx_type,
})
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use crate::types::{AccessType, FalconPubkey, FALCON_PUBKEY_LEN};
fn minimal_tx() -> Tx {
Tx {
from: Address::ZERO,
to: Address::ZERO,
value: 0,
data: Vec::new(),
gas_limit: 0,
nonce: 0,
signature: FalconSignature::new(vec![0u8; 32]),
fee_payer: FeePayer::Sender,
access_list: Vec::new(),
deadline: None,
chain_id: 0,
tx_type: TxType::Standard,
}
}
#[test]
fn same_input_yields_same_hash() {
let tx = minimal_tx();
assert_eq!(tx_hash(&tx), tx_hash(&tx));
}
#[test]
fn signature_not_included_in_hash() {
let mut a = minimal_tx();
let mut b = minimal_tx();
a.signature = FalconSignature::new(vec![0xAA; 666]);
b.signature = FalconSignature::new(vec![0xBB; 666]);
assert_eq!(tx_hash(&a), tx_hash(&b));
}
macro_rules! sensitivity_test {
($name:ident, $mutator_a:expr, $mutator_b:expr) => {
#[test]
fn $name() {
let mut a = minimal_tx();
let mut b = minimal_tx();
$mutator_a(&mut a);
$mutator_b(&mut b);
assert_ne!(tx_hash(&a), tx_hash(&b), "field must affect hash");
}
};
}
sensitivity_test!(
chain_id_change_changes_hash,
|t: &mut Tx| t.chain_id = 1,
|t: &mut Tx| t.chain_id = 31337
);
sensitivity_test!(
from_change_changes_hash,
|t: &mut Tx| t.from = Address::new([0x01; 32]),
|t: &mut Tx| t.from = Address::new([0x02; 32])
);
sensitivity_test!(
to_change_changes_hash,
|t: &mut Tx| t.to = Address::new([0x01; 32]),
|t: &mut Tx| t.to = Address::new([0x02; 32])
);
sensitivity_test!(
value_change_changes_hash,
|t: &mut Tx| t.value = 1,
|t: &mut Tx| t.value = 2
);
sensitivity_test!(
data_change_changes_hash,
|t: &mut Tx| t.data = vec![0x01],
|t: &mut Tx| t.data = vec![0x02]
);
sensitivity_test!(
gas_limit_change_changes_hash,
|t: &mut Tx| t.gas_limit = 21_000,
|t: &mut Tx| t.gas_limit = 21_001
);
sensitivity_test!(
nonce_change_changes_hash,
|t: &mut Tx| t.nonce = 0,
|t: &mut Tx| t.nonce = 1
);
sensitivity_test!(
deadline_presence_changes_hash,
|t: &mut Tx| t.deadline = None,
|t: &mut Tx| t.deadline = Some(0)
);
sensitivity_test!(
deadline_value_changes_hash,
|t: &mut Tx| t.deadline = Some(100),
|t: &mut Tx| t.deadline = Some(101)
);
sensitivity_test!(
tx_type_change_changes_hash,
|t: &mut Tx| t.tx_type = TxType::Standard,
|t: &mut Tx| t.tx_type = TxType::Deploy
);
#[test]
fn fee_payer_variant_change_changes_hash() {
let mut a = minimal_tx();
let mut b = minimal_tx();
let mut c = minimal_tx();
a.fee_payer = FeePayer::Sender;
b.fee_payer = FeePayer::GasTank;
c.fee_payer = FeePayer::Paymaster(Address::new([0x42; 32]));
let ha = tx_hash(&a);
let hb = tx_hash(&b);
let hc = tx_hash(&c);
assert_ne!(ha, hb);
assert_ne!(hb, hc);
assert_ne!(ha, hc);
}
#[test]
fn paymaster_addr_change_changes_hash() {
let mut a = minimal_tx();
let mut b = minimal_tx();
a.fee_payer = FeePayer::Paymaster(Address::new([0x01; 32]));
b.fee_payer = FeePayer::Paymaster(Address::new([0x02; 32]));
assert_ne!(tx_hash(&a), tx_hash(&b));
}
#[test]
fn access_list_ordering_changes_hash() {
let a_entry = AccessEntry {
address: Address::new([0x01; 32]),
storage_keys: vec![[0u8; 32]],
access_type: AccessType::Read,
};
let b_entry = AccessEntry {
address: Address::new([0x02; 32]),
storage_keys: vec![[0u8; 32]],
access_type: AccessType::Read,
};
let mut a = minimal_tx();
let mut b = minimal_tx();
a.access_list = vec![a_entry.clone(), b_entry.clone()];
b.access_list = vec![b_entry, a_entry];
assert_ne!(tx_hash(&a), tx_hash(&b));
}
#[test]
fn empty_access_list_uses_canonical_borsh_encoding() {
let empty_digest = hash_access_list(&[]);
let raw_empty: [u8; 32] = poseidon2_hash(&[]).into();
assert_ne!(empty_digest, raw_empty);
}
#[test]
fn known_vector_hash_is_stable() {
let tx = minimal_tx();
let h1 = tx_hash(&tx);
let h2 = tx_hash(&tx);
assert_eq!(h1, h2);
assert_ne!(h1, TxHash::zero());
}
#[test]
fn every_tx_type_yields_distinct_hash_when_otherwise_identical() {
use TxType::*;
let variants = [
Standard,
Deploy,
StakeDeposit,
StakeWithdraw,
Slash,
ClaimReward,
ClaimAirdrop,
SweepAirdrop,
MultisigTx,
RotateMultisig,
EmergencyPause,
EmergencyResume,
RegisterPubkey,
Unjail,
RotateValidatorKeys,
DisputeSlash,
Commit,
Reveal,
];
let mut seen = std::collections::HashSet::new();
for ty in variants {
let mut tx = minimal_tx();
tx.tx_type = ty;
let h = tx_hash(&tx);
assert!(seen.insert(h), "collision at TxType::{ty:?}");
}
assert_eq!(seen.len(), 18);
}
#[test]
fn encode_decode_round_trip() {
let tx = minimal_tx();
let bytes = encode(&tx).unwrap();
let decoded = decode(&bytes).unwrap();
assert_eq!(tx, decoded);
}
#[test]
fn builder_defaults() {
let pk = FalconPubkey::new([0xAB; FALCON_PUBKEY_LEN]);
let from = Address::from_pubkey(&pk);
let tx = TxBuilder::new().from(from).build().unwrap();
assert_eq!(tx.from, from);
assert_eq!(tx.to, Address::ZERO);
assert_eq!(tx.value, 0);
assert_eq!(tx.gas_limit, crate::types::MIN_GAS_LIMIT);
assert_eq!(tx.chain_id, 1);
assert_eq!(tx.tx_type, TxType::Standard);
assert!(tx.signature.is_empty());
}
#[test]
fn builder_requires_from() {
assert!(TxBuilder::new().build().is_err());
}
#[test]
fn builder_transfer_helper() {
let pk = FalconPubkey::new([0xAB; FALCON_PUBKEY_LEN]);
let from = Address::from_pubkey(&pk);
let to = Address::new([0x55; 32]);
let tx = TxBuilder::new()
.from(from)
.transfer(to, 1_500_000_000)
.build()
.unwrap();
assert_eq!(tx.tx_type, TxType::Standard);
assert_eq!(tx.to, to);
assert_eq!(tx.value, 1_500_000_000);
}
#[test]
fn builder_deploy_helper() {
let pk = FalconPubkey::new([0xAB; FALCON_PUBKEY_LEN]);
let from = Address::from_pubkey(&pk);
let wasm = b"\0asm\x01\0\0\0".to_vec();
let tx = TxBuilder::new()
.from(from)
.deploy(
"my-contract",
wasm.clone(),
crate::types::ContractType::Contract,
Vec::new(),
)
.unwrap()
.gas_limit(5_000_000)
.build()
.unwrap();
assert_eq!(tx.tx_type, TxType::Deploy);
assert!(tx.to.is_zero());
let decoded: crate::types::DeployData = borsh::from_slice(&tx.data).unwrap();
assert_eq!(decoded.name, "my-contract");
assert_eq!(decoded.wasm_bytes, wasm);
assert_eq!(decoded.contract_type, crate::types::ContractType::Contract);
assert!(decoded.init_calldata.is_empty());
}
#[test]
fn builder_call_helper() {
let pk = FalconPubkey::new([0xAB; FALCON_PUBKEY_LEN]);
let from = Address::from_pubkey(&pk);
let contract = Address::from_contract_name("counter");
let calldata = vec![0xDE, 0xAD, 0xBE, 0xEF];
let tx = TxBuilder::new()
.from(from)
.call(contract, calldata.clone())
.build()
.unwrap();
assert_eq!(tx.tx_type, TxType::Standard);
assert_eq!(tx.to, contract);
assert_eq!(tx.data, calldata);
}
#[test]
fn commitment_hash_is_salted_and_deterministic() {
let inner = b"borsh-inner-tx-bytes";
let nonce_a = [0x11u8; 32];
let nonce_b = [0x22u8; 32];
assert_eq!(
commitment_hash(inner, &nonce_a),
commitment_hash(inner, &nonce_a)
);
assert_ne!(
commitment_hash(inner, &nonce_a),
commitment_hash(inner, &nonce_b)
);
assert_ne!(
commitment_hash(b"other", &nonce_a),
commitment_hash(inner, &nonce_a)
);
}
#[test]
fn required_bond_floors_and_scales() {
assert_eq!(required_bond(0), MIN_COMMIT_BOND);
assert_eq!(required_bond(1_000), MIN_COMMIT_BOND);
let crossover = MIN_COMMIT_BOND * 10_000 / COMMIT_BOND_BPS;
assert_eq!(required_bond(crossover), MIN_COMMIT_BOND);
assert_eq!(required_bond(crossover * 10), MIN_COMMIT_BOND * 10);
let _ = required_bond(u128::MAX);
}
#[test]
fn builder_commit_helper() {
let pk = FalconPubkey::new([0xAB; FALCON_PUBKEY_LEN]);
let from = Address::from_pubkey(&pk);
let commitment = [0xCC; 32];
let ceiling = 5_000_000_000u128;
let tx = TxBuilder::new()
.from(from)
.commit(commitment, ceiling)
.unwrap()
.gas_limit(200_000)
.build()
.unwrap();
assert_eq!(tx.tx_type, TxType::Commit);
assert!(tx.to.is_zero());
assert_eq!(tx.value, required_bond(ceiling));
let decoded: crate::types::CommitPayload = borsh::from_slice(&tx.data).unwrap();
assert_eq!(decoded.commitment, commitment);
assert_eq!(decoded.value_ceiling, ceiling);
}
#[test]
fn builder_reveal_helper() {
let pk = FalconPubkey::new([0xAB; FALCON_PUBKEY_LEN]);
let from = Address::from_pubkey(&pk);
let commitment = [0xCC; 32];
let nonce = [0x5A; 32];
let inner_bytes = vec![1, 2, 3, 4, 5];
let tx = TxBuilder::new()
.from(from)
.reveal(commitment, nonce, inner_bytes.clone())
.unwrap()
.gas_limit(5_000_000)
.build()
.unwrap();
assert_eq!(tx.tx_type, TxType::Reveal);
assert!(tx.to.is_zero());
assert_eq!(tx.value, 0);
let decoded: crate::types::RevealPayload = borsh::from_slice(&tx.data).unwrap();
assert_eq!(decoded.commitment, commitment);
assert_eq!(decoded.nonce, nonce);
assert_eq!(decoded.inner_tx, inner_bytes);
}
}