1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Offline proposal operations for MultisigClient.
//!
//! This module handles creating, signing, and executing proposals
//! without PSM coordination (offline/side-channel mode).
use std::collections::HashSet;
use miden_objects::asset::FungibleAsset;
use miden_objects::transaction::TransactionSummary;
use private_state_manager_shared::{FromJson, ToJson};
use super::MultisigClient;
use crate::error::{MultisigError, Result};
use crate::execution::{SignatureInput, build_final_transaction_request, collect_signature_advice};
use crate::export::{EXPORT_VERSION, ExportedMetadata, ExportedProposal, ExportedSignature};
use crate::proposal::TransactionType;
impl MultisigClient {
/// Creates a proposal offline without pushing to PSM.
///
/// Use this when PSM is unavailable or you want to share proposals via
/// side channels. The proposal is returned as an `ExportedProposal` that
/// can be serialized to JSON and shared with cosigners.
///
/// The proposer's signature is automatically included in the exported proposal.
///
/// # Example
///
/// ```ignore
/// use miden_multisig_client::TransactionType;
///
/// // Create proposal offline
/// let exported = client.create_proposal_offline(
/// TransactionType::SwitchPsm { new_endpoint, new_commitment }
/// ).await?;
///
/// // Save to file for sharing
/// std::fs::write("proposal.json", exported.to_json()?)?;
/// ```
pub async fn create_proposal_offline(
&mut self,
transaction_type: TransactionType,
) -> Result<ExportedProposal> {
// Sync with the network before executing transaction
self.sync().await?;
let account = self.require_account()?.clone();
let account_id = account.id();
let current_threshold = account.threshold()?;
// Generate salt for replay protection
let salt = crate::transaction::generate_salt();
let salt_hex = crate::transaction::word_to_hex(&salt);
// Build transaction request based on type
let (tx_request, metadata) = match &transaction_type {
TransactionType::SwitchPsm {
new_endpoint,
new_commitment,
} => {
let tx_request = crate::transaction::build_update_psm_transaction_request(
*new_commitment,
salt,
std::iter::empty(),
)?;
let metadata = ExportedMetadata {
salt_hex: Some(salt_hex.clone()),
new_psm_pubkey_hex: Some(crate::transaction::word_to_hex(new_commitment)),
new_psm_endpoint: Some(new_endpoint.clone()),
..Default::default()
};
(tx_request, metadata)
}
TransactionType::P2ID {
recipient,
faucet_id,
amount,
} => {
let asset = FungibleAsset::new(*faucet_id, *amount).map_err(|e| {
MultisigError::InvalidConfig(format!("failed to create asset: {}", e))
})?;
let tx_request = crate::transaction::build_p2id_transaction_request(
account.inner(),
*recipient,
vec![asset.into()],
salt,
std::iter::empty(),
)?;
let metadata = ExportedMetadata {
salt_hex: Some(salt_hex.clone()),
recipient_hex: Some(recipient.to_string()),
faucet_id_hex: Some(faucet_id.to_string()),
amount: Some(*amount),
..Default::default()
};
(tx_request, metadata)
}
TransactionType::ConsumeNotes { note_ids } => {
let tx_request = crate::transaction::build_consume_notes_transaction_request(
note_ids.clone(),
salt,
std::iter::empty(),
)?;
let note_ids_hex: Vec<String> = note_ids.iter().map(|id| id.to_hex()).collect();
let metadata = ExportedMetadata {
salt_hex: Some(salt_hex.clone()),
note_ids_hex,
..Default::default()
};
(tx_request, metadata)
}
TransactionType::AddCosigner { new_commitment } => {
let mut current_signers = account.cosigner_commitments();
current_signers.push(*new_commitment);
let new_threshold = current_threshold as u64;
let (tx_request, _) = crate::transaction::build_update_signers_transaction_request(
new_threshold,
¤t_signers,
salt,
std::iter::empty(),
)?;
let signer_commitments_hex: Vec<String> = current_signers
.iter()
.map(crate::transaction::word_to_hex)
.collect();
let metadata = ExportedMetadata {
salt_hex: Some(salt_hex.clone()),
new_threshold: Some(new_threshold),
signer_commitments_hex,
..Default::default()
};
(tx_request, metadata)
}
TransactionType::RemoveCosigner { commitment } => {
let current_signers = account.cosigner_commitments();
let new_signers: Vec<_> = current_signers
.iter()
.filter(|&c| c != commitment)
.copied()
.collect();
if new_signers.len() == current_signers.len() {
return Err(MultisigError::InvalidConfig(
"commitment to remove not found in signers".to_string(),
));
}
let new_threshold =
std::cmp::min(current_threshold as u64, new_signers.len() as u64);
let (tx_request, _) = crate::transaction::build_update_signers_transaction_request(
new_threshold,
&new_signers,
salt,
std::iter::empty(),
)?;
let signer_commitments_hex: Vec<String> = new_signers
.iter()
.map(crate::transaction::word_to_hex)
.collect();
let metadata = ExportedMetadata {
salt_hex: Some(salt_hex.clone()),
new_threshold: Some(new_threshold),
signer_commitments_hex,
..Default::default()
};
(tx_request, metadata)
}
TransactionType::UpdateSigners {
new_threshold,
signer_commitments,
} => {
let (tx_request, _) = crate::transaction::build_update_signers_transaction_request(
*new_threshold as u64,
signer_commitments,
salt,
std::iter::empty(),
)?;
let signer_commitments_hex: Vec<String> = signer_commitments
.iter()
.map(crate::transaction::word_to_hex)
.collect();
let metadata = ExportedMetadata {
salt_hex: Some(salt_hex.clone()),
new_threshold: Some(*new_threshold as u64),
signer_commitments_hex,
..Default::default()
};
(tx_request, metadata)
}
};
// Execute to get the TransactionSummary
let tx_summary =
crate::transaction::execute_for_summary(&mut self.miden_client, account_id, tx_request)
.await?;
// Sign the transaction summary commitment
let tx_commitment = tx_summary.to_commitment();
let signature_hex = self.key_manager.sign_hex(tx_commitment);
// Build the proposal ID from commitment
let id = format!(
"0x{}",
hex::encode(
tx_commitment
.iter()
.flat_map(|f| f.as_int().to_le_bytes())
.collect::<Vec<_>>()
)
);
// Determine transaction type string
let tx_type_str = match &transaction_type {
TransactionType::P2ID { .. } => "P2ID",
TransactionType::ConsumeNotes { .. } => "ConsumeNotes",
TransactionType::AddCosigner { .. } => "AddCosigner",
TransactionType::RemoveCosigner { .. } => "RemoveCosigner",
TransactionType::SwitchPsm { .. } => "SwitchPsm",
TransactionType::UpdateSigners { .. } => "UpdateSigners",
};
// Create exported proposal with our signature
let exported = ExportedProposal {
version: EXPORT_VERSION,
account_id: account_id.to_string(),
id,
nonce: account.nonce() + 1,
transaction_type: tx_type_str.to_string(),
tx_summary: tx_summary.to_json(),
signatures: vec![ExportedSignature {
signer_commitment: self.key_manager.commitment_hex(),
signature: signature_hex,
}],
signatures_required: current_threshold as usize,
metadata,
};
Ok(exported)
}
/// Signs an imported proposal locally (without PSM).
///
/// The signature is added directly to the proposal. After signing,
/// export the proposal again to share with other cosigners.
///
/// # Example
///
/// ```ignore
/// let mut proposal = client.import_proposal("/tmp/proposal.json")?;
/// client.sign_imported_proposal(&mut proposal)?;
/// let json = proposal.to_json()?;
/// std::fs::write("/tmp/proposal_signed.json", json)?;
/// ```
pub fn sign_imported_proposal(&self, proposal: &mut ExportedProposal) -> Result<()> {
let account = self.require_account()?;
// Check if user is a cosigner
let user_commitment = self.key_manager.commitment();
if !account.is_cosigner(&user_commitment) {
return Err(MultisigError::NotCosigner);
}
// Check if already signed
let user_commitment_hex = self.key_manager.commitment_hex();
if proposal.signatures.iter().any(|s| {
s.signer_commitment
.eq_ignore_ascii_case(&user_commitment_hex)
}) {
return Err(MultisigError::AlreadySigned);
}
// Parse the transaction summary to get the commitment
let tx_summary = TransactionSummary::from_json(&proposal.tx_summary).map_err(|e| {
MultisigError::InvalidConfig(format!("failed to parse tx_summary: {}", e))
})?;
// Sign the transaction summary commitment
let tx_commitment = tx_summary.to_commitment();
let signature_hex = self.key_manager.sign_hex(tx_commitment);
// Add signature to proposal
proposal.add_signature(ExportedSignature {
signer_commitment: user_commitment_hex,
signature: signature_hex,
})?;
Ok(())
}
/// Executes an imported proposal (with all signatures already collected).
///
/// This builds and submits the transaction directly to the Miden network,
/// bypassing PSM entirely. Use this for fully offline workflows.
///
/// **Note:** This does NOT update PSM. The proposal will remain on PSM
/// until it expires or is explicitly deleted.
///
/// # Example
///
/// ```ignore
/// let proposal = client.import_proposal("/tmp/proposal_final.json")?;
/// client.execute_imported_proposal(&proposal).await?;
/// ```
pub async fn execute_imported_proposal(&mut self, exported: &ExportedProposal) -> Result<()> {
// Sync with the network before executing to ensure we have latest state
self.sync().await?;
let account = self.require_account()?.clone();
let account_id = account.id();
// Verify proposal is ready
if !exported.is_ready() {
return Err(MultisigError::ProposalNotReady {
collected: exported.signatures_collected(),
required: exported.signatures_required,
});
}
// Parse the proposal
let proposal = exported.to_proposal()?;
let tx_summary = TransactionSummary::from_json(&exported.tx_summary).map_err(|e| {
MultisigError::InvalidConfig(format!("failed to parse tx_summary: {}", e))
})?;
let tx_summary_commitment = tx_summary.to_commitment();
// Convert exported signatures to SignatureInput format
let signature_inputs: Vec<SignatureInput> = exported
.signatures
.iter()
.map(|sig| SignatureInput {
signer_commitment: sig.signer_commitment.clone(),
signature_hex: sig.signature.clone(),
})
.collect();
// Build signature advice from cosigner signatures
let required_commitments: HashSet<String> =
account.cosigner_commitments_hex().into_iter().collect();
let mut signature_advice = collect_signature_advice(
signature_inputs,
&required_commitments,
tx_summary_commitment,
)?;
// SwitchPsm does NOT require PSM signature
let is_switch_psm = matches!(
&proposal.transaction_type,
TransactionType::SwitchPsm { .. }
);
if !is_switch_psm {
// Get PSM ack signature and add to advice
let psm_advice = self
.get_psm_ack_signature(&account, proposal.nonce, &tx_summary, tx_summary_commitment)
.await?;
signature_advice.push(psm_advice);
}
// Build the final transaction request with all signatures
let salt = proposal.metadata.salt()?;
// For signer-update transactions, we must propagate parse errors for signer commitments
// rather than silently converting to None. This ensures malformed hex is diagnosed properly.
let signer_commitments = if matches!(
&proposal.transaction_type,
TransactionType::AddCosigner { .. }
| TransactionType::RemoveCosigner { .. }
| TransactionType::UpdateSigners { .. }
) {
Some(proposal.metadata.signer_commitments()?)
} else {
proposal.metadata.signer_commitments().ok()
};
let final_tx_request = build_final_transaction_request(
&proposal.transaction_type,
account.inner(),
salt,
signature_advice,
proposal.metadata.new_threshold,
signer_commitments.as_deref(),
)?;
// Execute and finalize
self.finalize_transaction(account_id, final_tx_request, &proposal.transaction_type)
.await
}
}