Skip to main content

private_state_manager_shared/
lib.rs

1use base64::Engine;
2use miden_protocol::account::Account;
3use miden_protocol::transaction::TransactionSummary;
4use miden_protocol::utils::serde::{Deserializable, Serializable};
5use serde::{Deserialize, Serialize};
6
7pub mod auth;
8pub mod hex;
9
10/// Supported signature schemes
11#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
12#[serde(rename_all = "snake_case")]
13pub enum SignatureScheme {
14    Falcon,
15    Ecdsa,
16}
17
18impl std::fmt::Display for SignatureScheme {
19    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        match self {
21            SignatureScheme::Falcon => write!(f, "falcon"),
22            SignatureScheme::Ecdsa => write!(f, "ecdsa"),
23        }
24    }
25}
26
27/// Signature type for delta proposals
28#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
29#[serde(tag = "scheme", rename_all = "snake_case")]
30pub enum ProposalSignature {
31    Falcon {
32        /// Hex-encoded Falcon signature
33        signature: String,
34    },
35    Ecdsa {
36        /// Hex-encoded ECDSA secp256k1 signature
37        signature: String,
38        /// Hex-encoded ECDSA public key (required for signature preparation)
39        #[serde(default, skip_serializing_if = "Option::is_none")]
40        public_key: Option<String>,
41    },
42}
43
44impl ProposalSignature {
45    /// Creates a ProposalSignature from a scheme, hex-encoded signature, and optional public key.
46    pub fn from_scheme(
47        scheme: SignatureScheme,
48        signature: String,
49        public_key: Option<String>,
50    ) -> Self {
51        match scheme {
52            SignatureScheme::Falcon => ProposalSignature::Falcon { signature },
53            SignatureScheme::Ecdsa => ProposalSignature::Ecdsa {
54                signature,
55                public_key,
56            },
57        }
58    }
59
60    /// Returns the public key hex if this is an ECDSA signature with a public key.
61    pub fn public_key(&self) -> Option<&str> {
62        match self {
63            ProposalSignature::Ecdsa { public_key, .. } => public_key.as_deref(),
64            _ => None,
65        }
66    }
67}
68
69/// Delta payload structure containing transaction summary and signatures
70/// This is the standard format for delta_payload in proposals
71#[derive(Serialize, Deserialize, Clone, Debug)]
72pub struct DeltaPayload {
73    pub tx_summary: serde_json::Value,
74    #[serde(default, skip_serializing_if = "Vec::is_empty")]
75    pub signatures: Vec<DeltaSignature>,
76}
77
78impl DeltaPayload {
79    pub fn new(tx_summary: serde_json::Value) -> Self {
80        Self {
81            tx_summary,
82            signatures: Vec::new(),
83        }
84    }
85
86    pub fn with_signature(mut self, signature: DeltaSignature) -> Self {
87        self.signatures.push(signature);
88        self
89    }
90
91    pub fn to_json(&self) -> serde_json::Value {
92        serde_json::to_value(self).expect("DeltaPayload should always serialize")
93    }
94}
95
96/// Signature entry in delta payload
97#[derive(Serialize, Deserialize, Clone, Debug)]
98pub struct DeltaSignature {
99    pub signer_id: String,
100    pub signature: ProposalSignature,
101}
102
103pub trait ToJson {
104    fn to_json(&self) -> serde_json::Value;
105}
106
107pub trait FromJson: Sized {
108    fn from_json(json: &serde_json::Value) -> Result<Self, String>;
109}
110
111impl ToJson for Account {
112    fn to_json(&self) -> serde_json::Value {
113        let bytes = self.to_bytes();
114        let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
115        serde_json::json!({
116          "data": encoded,
117          "account_id": self.id().to_hex(),
118        })
119    }
120}
121
122impl FromJson for Account {
123    fn from_json(json: &serde_json::Value) -> Result<Self, String> {
124        let encoded = json
125            .get("data")
126            .and_then(|v| v.as_str())
127            .ok_or("Missing or invalid 'data' field")?;
128
129        let bytes = base64::engine::general_purpose::STANDARD
130            .decode(encoded)
131            .map_err(|e| format!("Base64 decode error: {e}"))?;
132
133        Account::read_from_bytes(&bytes).map_err(|e| format!("Deserialization error: {e}"))
134    }
135}
136
137impl ToJson for TransactionSummary {
138    fn to_json(&self) -> serde_json::Value {
139        let bytes = self.to_bytes();
140        let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
141        serde_json::json!({
142          "data": encoded,
143        })
144    }
145}
146
147impl FromJson for TransactionSummary {
148    fn from_json(json: &serde_json::Value) -> Result<Self, String> {
149        let encoded = json
150            .get("data")
151            .and_then(|v| v.as_str())
152            .ok_or("Missing or invalid 'data' field in delta payload")?;
153
154        let bytes = base64::engine::general_purpose::STANDARD
155            .decode(encoded)
156            .map_err(|e| format!("Base64 decode error: {e}"))?;
157
158        TransactionSummary::read_from_bytes(&bytes)
159            .map_err(|e| format!("AccountDelta deserialization error: {e}"))
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166    use miden_protocol::{
167        account::{AccountBuilder, auth::PublicKeyCommitment},
168        crypto::dsa::falcon512_rpo::SecretKey,
169    };
170    use miden_standards::account::{auth::AuthFalcon512Rpo, wallets::BasicWallet};
171
172    #[test]
173    fn test_account_json_round_trip() {
174        // Create a test account
175        let secret_key = SecretKey::new();
176        let public_key_commitment =
177            PublicKeyCommitment::from(secret_key.public_key().to_commitment());
178        let account = AccountBuilder::new([0xff; 32])
179            .with_auth_component(AuthFalcon512Rpo::new(public_key_commitment))
180            .with_component(BasicWallet)
181            .build()
182            .unwrap();
183
184        // Serialize to JSON
185        let json = account.to_json();
186
187        // Deserialize from JSON
188        let deserialized_account =
189            Account::from_json(&json).expect("Failed to deserialize account");
190
191        // Verify round-trip
192        assert_eq!(account.id(), deserialized_account.id());
193        assert_eq!(account.nonce(), deserialized_account.nonce());
194        assert_eq!(account.commitment(), deserialized_account.commitment());
195        assert_eq!(
196            account.storage().to_commitment(),
197            deserialized_account.storage().to_commitment()
198        );
199        assert_eq!(
200            account.code().commitment(),
201            deserialized_account.code().commitment()
202        );
203    }
204}