use borsh::{BorshDeserialize, BorshSerialize};
use pyde_crypto::poseidon2::poseidon2_hash;
use crate::error::SdkError;
use crate::signer::Signer;
use crate::types::{Address, FalconSignature, TxHash, TxType};
pub const DOMAIN_MULTISIG_TX: u8 = 0x09;
pub const DOMAIN_ROTATE_MULTISIG: u8 = 0x0A;
pub const DOMAIN_EMERGENCY_PAUSE: u8 = 0x0B;
pub const DOMAIN_EMERGENCY_RESUME: u8 = 0x0C;
pub const DOMAIN_DISPUTE_SLASH: u8 = 0x10;
#[must_use]
pub fn domain_byte(tx_type: TxType) -> Option<u8> {
match tx_type {
TxType::MultisigTx => Some(DOMAIN_MULTISIG_TX),
TxType::RotateMultisig => Some(DOMAIN_ROTATE_MULTISIG),
TxType::EmergencyPause => Some(DOMAIN_EMERGENCY_PAUSE),
TxType::EmergencyResume => Some(DOMAIN_EMERGENCY_RESUME),
TxType::DisputeSlash => Some(DOMAIN_DISPUTE_SLASH),
_ => None,
}
}
#[must_use]
pub fn canonical_msg(tx_type: TxType, nonce: u64, payload: &[u8]) -> Option<[u8; 32]> {
let domain = domain_byte(tx_type)?;
let payload_digest: [u8; 32] = poseidon2_hash(payload).into();
let mut preimage = Vec::with_capacity(1 + 8 + 32);
preimage.push(domain);
preimage.extend_from_slice(&nonce.to_le_bytes());
preimage.extend_from_slice(&payload_digest);
Some(poseidon2_hash(&preimage).into())
}
#[derive(Debug, Clone, Eq, PartialEq, BorshSerialize, BorshDeserialize)]
pub struct BundleEntry {
pub signer_index: u32,
pub signature: FalconSignature,
}
pub type SigBundle = Vec<BundleEntry>;
#[derive(Debug, Clone, Eq, PartialEq, BorshSerialize, BorshDeserialize)]
pub struct MultisigTxPayload {
pub target: Address,
pub amount: u128,
pub bundle: SigBundle,
}
impl MultisigTxPayload {
pub fn canonical_bytes(target: Address, amount: u128) -> Result<Vec<u8>, SdkError> {
borsh::to_vec(&(target, amount))
.map_err(|e| SdkError::Other(format!("borsh encode (target, amount): {e}")))
}
}
pub async fn sign_action(
signer: &dyn Signer,
signer_index: u32,
tx_type: TxType,
nonce: u64,
payload: &[u8],
) -> Result<BundleEntry, SdkError> {
let msg = canonical_msg(tx_type, nonce, payload).ok_or_else(|| {
SdkError::InvalidArgument(format!(
"tx_type {tx_type:?} is not a multisig-driven action"
))
})?;
let hash = TxHash::new(msg);
let signature = signer.sign_hash(&hash).await?;
Ok(BundleEntry {
signer_index,
signature,
})
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use crate::signer::LocalSigner;
#[test]
fn domain_bytes_match_engine_constants() {
assert_eq!(DOMAIN_MULTISIG_TX, 0x09);
assert_eq!(DOMAIN_ROTATE_MULTISIG, 0x0A);
assert_eq!(DOMAIN_EMERGENCY_PAUSE, 0x0B);
assert_eq!(DOMAIN_EMERGENCY_RESUME, 0x0C);
assert_eq!(DOMAIN_DISPUTE_SLASH, 0x10);
}
#[test]
fn domain_byte_maps_every_multisig_tx_type() {
assert_eq!(domain_byte(TxType::MultisigTx), Some(0x09));
assert_eq!(domain_byte(TxType::RotateMultisig), Some(0x0A));
assert_eq!(domain_byte(TxType::EmergencyPause), Some(0x0B));
assert_eq!(domain_byte(TxType::EmergencyResume), Some(0x0C));
assert_eq!(domain_byte(TxType::DisputeSlash), Some(0x10));
}
#[test]
fn domain_byte_rejects_non_multisig_tx_types() {
assert_eq!(domain_byte(TxType::Standard), None);
assert_eq!(domain_byte(TxType::Deploy), None);
assert_eq!(domain_byte(TxType::RegisterPubkey), None);
}
#[test]
fn canonical_msg_returns_none_for_standard_tx() {
assert!(canonical_msg(TxType::Standard, 0, &[]).is_none());
}
#[test]
fn canonical_msg_is_deterministic() {
let a = canonical_msg(TxType::MultisigTx, 7, b"payload").unwrap();
let b = canonical_msg(TxType::MultisigTx, 7, b"payload").unwrap();
assert_eq!(a, b);
}
#[test]
fn canonical_msg_changes_with_action() {
let spend = canonical_msg(TxType::MultisigTx, 1, b"x").unwrap();
let rotate = canonical_msg(TxType::RotateMultisig, 1, b"x").unwrap();
assert_ne!(
spend, rotate,
"domain separation must produce distinct messages"
);
}
#[test]
fn canonical_msg_changes_with_nonce() {
let a = canonical_msg(TxType::MultisigTx, 1, b"x").unwrap();
let b = canonical_msg(TxType::MultisigTx, 2, b"x").unwrap();
assert_ne!(a, b);
}
#[test]
fn canonical_msg_changes_with_payload() {
let a = canonical_msg(TxType::MultisigTx, 1, b"alpha").unwrap();
let b = canonical_msg(TxType::MultisigTx, 1, b"beta").unwrap();
assert_ne!(a, b);
}
#[test]
fn canonical_msg_matches_engine_construction() {
let payload = b"target||amount";
let nonce: u64 = 0xdead_beef;
let payload_digest: [u8; 32] = poseidon2_hash(payload).into();
let mut preimage = Vec::with_capacity(1 + 8 + 32);
preimage.push(DOMAIN_MULTISIG_TX);
preimage.extend_from_slice(&nonce.to_le_bytes());
preimage.extend_from_slice(&payload_digest);
let expected: [u8; 32] = poseidon2_hash(&preimage).into();
let computed = canonical_msg(TxType::MultisigTx, nonce, payload).unwrap();
assert_eq!(computed, expected);
}
#[test]
fn bundle_entry_round_trip() {
let entry = BundleEntry {
signer_index: 7,
signature: FalconSignature::new(vec![1u8; 666]),
};
let bytes = borsh::to_vec(&entry).unwrap();
let decoded: BundleEntry = borsh::from_slice(&bytes).unwrap();
assert_eq!(decoded, entry);
}
#[test]
fn sig_bundle_round_trip() {
let bundle: SigBundle = (0..3)
.map(|i| BundleEntry {
signer_index: i,
signature: FalconSignature::new(vec![i as u8; 666]),
})
.collect();
let bytes = borsh::to_vec(&bundle).unwrap();
let decoded: SigBundle = borsh::from_slice(&bytes).unwrap();
assert_eq!(decoded, bundle);
}
#[test]
fn multisig_tx_payload_round_trip() {
let payload = MultisigTxPayload {
target: Address::ZERO,
amount: 12345,
bundle: vec![BundleEntry {
signer_index: 0,
signature: FalconSignature::new(vec![9u8; 666]),
}],
};
let bytes = borsh::to_vec(&payload).unwrap();
let decoded: MultisigTxPayload = borsh::from_slice(&bytes).unwrap();
assert_eq!(decoded, payload);
}
#[test]
fn multisig_tx_payload_field_order_pinned() {
let payload = MultisigTxPayload {
target: Address::ZERO,
amount: 1,
bundle: Vec::new(),
};
let bytes = borsh::to_vec(&payload).unwrap();
assert_eq!(bytes.len(), 32 + 16 + 4);
assert!(bytes[0..32].iter().all(|b| *b == 0));
assert_eq!(bytes[32], 1);
assert!(bytes[33..48].iter().all(|b| *b == 0));
assert_eq!(&bytes[48..52], &[0u8; 4]);
}
#[test]
fn canonical_bytes_matches_inline_borsh() {
let target = Address::new([0xAB; 32]);
let amount: u128 = 1_000_000;
let from_helper = MultisigTxPayload::canonical_bytes(target, amount).unwrap();
let inline = borsh::to_vec(&(target, amount)).unwrap();
assert_eq!(from_helper, inline);
assert_eq!(from_helper.len(), 32 + 16);
}
#[tokio::test]
async fn sign_action_rejects_non_multisig_tx_type() {
let signer = LocalSigner::random().unwrap();
let err = sign_action(&signer, 0, TxType::Standard, 0, &[])
.await
.unwrap_err();
match err {
SdkError::InvalidArgument(msg) => {
assert!(msg.contains("multisig-driven"), "wrong message: {msg}");
}
other => panic!("expected InvalidArgument, got {other:?}"),
}
}
#[tokio::test]
async fn sign_action_produces_verifiable_entry() {
use pyde_crypto::falcon::{
falcon_verify, FalconPublicKey as CryptoPk, FalconSignature as CryptoSig,
};
let signer = LocalSigner::random().unwrap();
let payload = MultisigTxPayload::canonical_bytes(Address::ZERO, 7).unwrap();
let entry = sign_action(&signer, 3, TxType::MultisigTx, 42, &payload)
.await
.unwrap();
assert_eq!(entry.signer_index, 3);
let msg = canonical_msg(TxType::MultisigTx, 42, &payload).unwrap();
let pk = CryptoPk::from_bytes(signer.pubkey().as_bytes()).expect("valid pubkey");
let sig = CryptoSig::from_bytes(entry.signature.as_bytes()).expect("valid sig");
assert!(
falcon_verify(&pk, &msg, &sig),
"signature must verify against canonical_msg",
);
}
#[tokio::test]
async fn three_signers_produce_distinct_bundle_entries() {
let signers = (0..3)
.map(|_| LocalSigner::random().unwrap())
.collect::<Vec<_>>();
let payload = MultisigTxPayload::canonical_bytes(Address::ZERO, 99).unwrap();
let mut bundle: SigBundle = Vec::new();
for (idx, signer) in signers.iter().enumerate() {
let entry = sign_action(signer, idx as u32, TxType::MultisigTx, 1, &payload)
.await
.unwrap();
bundle.push(entry);
}
assert_eq!(bundle.len(), 3);
assert_eq!(
bundle.iter().map(|e| e.signer_index).collect::<Vec<_>>(),
vec![0, 1, 2],
);
let sigs: std::collections::HashSet<_> = bundle
.iter()
.map(|e| e.signature.as_bytes().to_vec())
.collect();
assert_eq!(sigs.len(), 3);
}
}