miden-multisig-client 0.16.2

High-level SDK for interacting with multisig accounts on Miden via GUARDIAN
Documentation
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//! Builder pattern for constructing MultisigClient instances.

use std::path::PathBuf;
use std::sync::Arc;

use miden_client::DebugMode;
use miden_client::builder::ClientBuilder;
use miden_client::grpc_support::{
    DEFAULT_GRPC_TIMEOUT_MS, DEVNET_PROVER_ENDPOINT, TESTNET_PROVER_ENDPOINT,
};
use miden_client::keystore::FilesystemKeyStore;
use miden_client::note_transport::grpc::GrpcNoteTransportClient;
use miden_client::note_transport::{
    NOTE_TRANSPORT_DEVNET_ENDPOINT, NOTE_TRANSPORT_TESTNET_ENDPOINT, NoteTransportClient,
};
use miden_client::rpc::{Endpoint, GrpcClient, NodeRpcClient};
use miden_client_sqlite_store::SqliteStore;
use miden_protocol::crypto::dsa::ecdsa_k256_keccak::SigningKey as EcdsaSecretKey;
use miden_protocol::crypto::dsa::falcon512_poseidon2::SecretKey;
use miden_protocol::crypto::rand::RandomCoin;

use crate::MidenSdkClient;
use crate::client::MultisigClient;
use crate::error::{MultisigError, Result};
use crate::keystore::{EcdsaGuardianKeyStore, GuardianKeyStore, KeyManager};
use crate::prover::{ProverConfig, ProverSelection, RetryingTransactionProver};
use crate::rpc::{
    RetryingNodeRpcClient, RpcConfig, RpcSelection, configured_note_transport_client,
};

/// Always constructed with the inner miden-client retry loop disabled:
/// that loop retransmits rate-limited submissions (`is_retryable` covers
/// `ResourceExhausted`/`Unavailable`), which violates at-most-once
/// submission. [`RetryingNodeRpcClient`] is the only retry layer, and it
/// never retries submissions.
///
/// The default per-request deadline is the miden-client 10s default on
/// every path — preset, custom endpoint, and direct commitment reads.
pub(crate) fn configured_node_rpc_client(
    endpoint: &Endpoint,
    rpc_config: &RpcConfig,
) -> Arc<dyn NodeRpcClient> {
    let (timeout_ms, retry_policy) = match rpc_config.resolve(DEFAULT_GRPC_TIMEOUT_MS) {
        RpcSelection::Passthrough => (DEFAULT_GRPC_TIMEOUT_MS, None),
        RpcSelection::Configured {
            timeout_ms,
            retry_policy,
        } => (timeout_ms, Some(retry_policy)),
    };
    let grpc: Arc<dyn NodeRpcClient> =
        Arc::new(GrpcClient::new(endpoint, timeout_ms).with_max_retries(0));
    match retry_policy {
        Some(policy) if policy.max_attempts() > 1 => {
            Arc::new(RetryingNodeRpcClient::new(grpc, &policy))
        }
        _ => grpc,
    }
}

fn preset_note_transport_endpoint(endpoint: &Endpoint) -> Option<&'static str> {
    if endpoint == &Endpoint::testnet() {
        Some(NOTE_TRANSPORT_TESTNET_ENDPOINT)
    } else if endpoint == &Endpoint::devnet() {
        Some(NOTE_TRANSPORT_DEVNET_ENDPOINT)
    } else {
        None
    }
}

/// An explicit endpoint always wires the transport; the preset endpoint is
/// wired only when the RPC config is customized, so a passthrough build
/// keeps the upstream miden-client transport defaults.
fn resolved_note_transport_endpoint(
    endpoint: &Endpoint,
    note_transport_endpoint: Option<&str>,
    selection: &RpcSelection,
) -> Option<String> {
    if let Some(url) = note_transport_endpoint {
        return Some(url.to_string());
    }
    match selection {
        RpcSelection::Passthrough => None,
        RpcSelection::Configured { .. } => {
            preset_note_transport_endpoint(endpoint).map(str::to_string)
        }
    }
}

fn configured_client_builder(
    endpoint: &Endpoint,
    note_transport_endpoint: Option<&str>,
    prover_config: &ProverConfig,
    rpc_config: &RpcConfig,
) -> ClientBuilder<FilesystemKeyStore> {
    let base = if endpoint == &Endpoint::devnet() {
        ClientBuilder::<FilesystemKeyStore>::for_devnet()
    } else if endpoint == &Endpoint::testnet() {
        ClientBuilder::<FilesystemKeyStore>::for_testnet()
    } else if endpoint == &Endpoint::localhost() {
        ClientBuilder::<FilesystemKeyStore>::for_localhost()
    } else {
        ClientBuilder::<FilesystemKeyStore>::new()
    };

    let builder = base.rpc(configured_node_rpc_client(endpoint, rpc_config));

    let selection = rpc_config.resolve(DEFAULT_GRPC_TIMEOUT_MS);
    let builder =
        match resolved_note_transport_endpoint(endpoint, note_transport_endpoint, &selection) {
            Some(transport_endpoint) => {
                let timeout_ms = match &selection {
                    RpcSelection::Passthrough => DEFAULT_GRPC_TIMEOUT_MS,
                    RpcSelection::Configured { timeout_ms, .. } => *timeout_ms,
                };
                let transport: Arc<dyn NoteTransportClient> =
                    Arc::new(GrpcNoteTransportClient::new(transport_endpoint, timeout_ms));
                builder.note_transport(configured_note_transport_client(transport, rpc_config))
            }
            None => builder,
        };

    let default_remote = if endpoint == &Endpoint::devnet() {
        Some(DEVNET_PROVER_ENDPOINT)
    } else if endpoint == &Endpoint::testnet() {
        Some(TESTNET_PROVER_ENDPOINT)
    } else {
        None
    };

    match prover_config.resolve(default_remote) {
        ProverSelection::Local => builder,
        ProverSelection::Remote {
            endpoint,
            custom: _,
            retry_policy,
        } => builder.prover(Arc::new(RetryingTransactionProver::remote(
            endpoint,
            retry_policy,
        ))),
    }
}

/// Builder for constructing MultisigClient instances.
///
/// # Example
///
/// ```ignore
/// use miden_multisig_client::MultisigClient;
/// use miden_client::rpc::Endpoint;
///
/// let client = MultisigClient::builder()
///     .miden_endpoint(Endpoint::new("http://localhost:57291"))
///     .guardian_endpoint("http://localhost:50051")
///     .account_dir("/tmp/multisig-client")
///     .prover_config(
///         miden_multisig_client::ProverConfig::new()
///             .with_url("https://prover.example")?
///             .with_retry_policy(miden_multisig_client::ProverRetryPolicy::new(4)),
///     )
///     .generate_key()
///     .build()
///     .await?;
/// ```
pub struct MultisigClientBuilder {
    miden_endpoint: Option<Endpoint>,
    note_transport_endpoint: Option<String>,
    guardian_endpoint: Option<String>,
    account_dir: Option<PathBuf>,
    key_manager: Option<Arc<dyn KeyManager>>,
    prover_config: ProverConfig,
    rpc_config: RpcConfig,
}

impl Default for MultisigClientBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl MultisigClientBuilder {
    /// Creates a new builder with default settings.
    pub fn new() -> Self {
        Self {
            miden_endpoint: None,
            note_transport_endpoint: None,
            guardian_endpoint: None,
            account_dir: None,
            key_manager: None,
            prover_config: ProverConfig::new(),
            rpc_config: RpcConfig::new(),
        }
    }

    /// Sets the Miden node RPC endpoint.
    pub fn miden_endpoint(mut self, endpoint: Endpoint) -> Self {
        self.miden_endpoint = Some(endpoint);
        self
    }

    /// Sets the note transport service endpoint used for private note relay.
    ///
    /// Overrides the default derived from the Miden endpoint (the public
    /// transport services for the testnet and devnet presets). A custom
    /// Miden node endpoint has no derivable transport service, so this is
    /// the only way to enable note transport there.
    pub fn note_transport_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.note_transport_endpoint = Some(endpoint.into());
        self
    }

    /// Sets the GUARDIAN server endpoint.
    pub fn guardian_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.guardian_endpoint = Some(endpoint.into());
        self
    }

    /// Configures the remote transaction prover and its retry policy.
    pub fn prover_config(mut self, prover_config: ProverConfig) -> Self {
        self.prover_config = prover_config;
        self
    }

    /// Configures the Miden node RPC timeout and idempotent-read retry policy.
    pub fn rpc_config(mut self, rpc_config: RpcConfig) -> Self {
        self.rpc_config = rpc_config;
        self
    }

    /// Sets the account directory for miden-client storage.
    ///
    /// This directory will contain the SQLite database for account and transaction data.
    pub fn account_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.account_dir = Some(path.into());
        self
    }

    /// Sets a custom key manager for GUARDIAN authentication and proposal signing.
    pub fn key_manager(mut self, key_manager: Box<dyn KeyManager>) -> Self {
        self.key_manager = Some(key_manager.into());
        self
    }

    /// Uses a FalconKeyStore with the given secret key.
    pub fn with_secret_key(mut self, secret_key: SecretKey) -> Self {
        self.key_manager = Some(Arc::new(GuardianKeyStore::new(secret_key)));
        self
    }

    /// Uses an ECDSA key store with the given secret key.
    pub fn with_ecdsa_secret_key(mut self, secret_key: EcdsaSecretKey) -> Self {
        self.key_manager = Some(Arc::new(EcdsaGuardianKeyStore::new(secret_key)));
        self
    }

    /// Generates a new random key for GUARDIAN authentication.
    pub fn generate_key(mut self) -> Self {
        self.key_manager = Some(Arc::new(GuardianKeyStore::generate()));
        self
    }

    /// Generates a new random ECDSA key for GUARDIAN authentication.
    pub fn generate_ecdsa_key(mut self) -> Self {
        self.key_manager = Some(Arc::new(EcdsaGuardianKeyStore::generate()));
        self
    }

    /// Builds the MultisigClient.
    pub async fn build(self) -> Result<MultisigClient> {
        let miden_endpoint = self
            .miden_endpoint
            .ok_or_else(|| MultisigError::MissingConfig("miden_endpoint".to_string()))?;

        let note_transport_endpoint = match self.note_transport_endpoint {
            Some(endpoint) => {
                let trimmed = endpoint.trim();
                if trimmed.is_empty() {
                    return Err(MultisigError::InvalidConfig(
                        "note_transport_endpoint must not be empty".to_string(),
                    ));
                }
                Some(trimmed.to_string())
            }
            None => None,
        };

        let guardian_endpoint = self
            .guardian_endpoint
            .ok_or_else(|| MultisigError::MissingConfig("guardian_endpoint".to_string()))?;

        let account_dir = self
            .account_dir
            .ok_or_else(|| MultisigError::MissingConfig("account_dir".to_string()))?;

        let key_manager = self.key_manager.ok_or(MultisigError::NoSigner)?;

        // Ensure account directory exists
        std::fs::create_dir_all(&account_dir).map_err(|e| {
            MultisigError::MidenClient(format!("failed to create account dir: {}", e))
        })?;

        let miden_client = create_miden_client(
            &account_dir,
            &miden_endpoint,
            note_transport_endpoint.as_deref(),
            &self.prover_config,
            &self.rpc_config,
        )
        .await?;

        Ok(MultisigClient::new(
            miden_client,
            key_manager,
            guardian_endpoint,
            account_dir,
            miden_endpoint,
            note_transport_endpoint,
            self.prover_config,
            self.rpc_config,
        ))
    }
}

/// Creates a miden-client instance with SQLite storage.
///
/// Each call creates a fresh database with a unique filename to ensure
/// no accumulated state from previous sessions.
pub(crate) async fn create_miden_client(
    account_dir: &std::path::Path,
    endpoint: &Endpoint,
    note_transport_endpoint: Option<&str>,
    prover_config: &ProverConfig,
    rpc_config: &RpcConfig,
) -> Result<MidenSdkClient> {
    let timestamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis();
    let random_suffix: u32 = rand::random();
    let store_path = account_dir.join(format!(
        "miden-client-{}-{}.sqlite",
        timestamp, random_suffix
    ));
    let store = SqliteStore::new(store_path)
        .await
        .map_err(|e| MultisigError::MidenClient(format!("failed to open SQLite store: {}", e)))?;
    let store = Arc::new(store);

    let rng_seed: [u32; 4] = rand::random();
    let rng = Box::new(RandomCoin::new(rng_seed.into()));

    configured_client_builder(endpoint, note_transport_endpoint, prover_config, rpc_config)
        .store(store)
        .rng(rng)
        .in_debug_mode(DebugMode::Enabled)
        .tx_discard_delta(Some(20))
        .max_block_number_delta(256)
        .build()
        .await
        .map_err(|e| MultisigError::MidenClient(format!("failed to create miden client: {}", e)))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rpc::RpcRetryPolicy;

    fn custom_endpoint() -> Endpoint {
        Endpoint::new("http".to_string(), "node".to_string(), Some(57291))
    }

    fn single_attempt_config() -> RpcConfig {
        RpcConfig::new().with_retry_policy(RpcRetryPolicy::new(1))
    }

    fn selection(rpc_config: &RpcConfig) -> RpcSelection {
        rpc_config.resolve(DEFAULT_GRPC_TIMEOUT_MS)
    }

    #[test]
    fn note_transport_endpoints_exist_only_for_public_presets() {
        assert_eq!(
            preset_note_transport_endpoint(&Endpoint::testnet()),
            Some(NOTE_TRANSPORT_TESTNET_ENDPOINT)
        );
        assert_eq!(
            preset_note_transport_endpoint(&Endpoint::devnet()),
            Some(NOTE_TRANSPORT_DEVNET_ENDPOINT)
        );
        assert_eq!(preset_note_transport_endpoint(&Endpoint::localhost()), None);
        assert_eq!(preset_note_transport_endpoint(&custom_endpoint()), None);
    }

    #[test]
    fn explicit_note_transport_endpoint_wires_regardless_of_rpc_config() {
        assert_eq!(
            resolved_note_transport_endpoint(
                &custom_endpoint(),
                Some("https://transport.internal"),
                &selection(&single_attempt_config()),
            ),
            Some("https://transport.internal".to_string())
        );
        assert_eq!(
            resolved_note_transport_endpoint(
                &Endpoint::testnet(),
                Some("https://transport.internal"),
                &selection(&RpcConfig::new()),
            ),
            Some("https://transport.internal".to_string())
        );
    }

    #[test]
    fn preset_note_transport_wires_unless_rpc_config_is_passthrough() {
        assert_eq!(
            resolved_note_transport_endpoint(
                &Endpoint::testnet(),
                None,
                &selection(&RpcConfig::new())
            ),
            Some(NOTE_TRANSPORT_TESTNET_ENDPOINT.to_string())
        );
        assert_eq!(
            resolved_note_transport_endpoint(
                &Endpoint::testnet(),
                None,
                &selection(&single_attempt_config())
            ),
            None
        );
        let timeout_only = single_attempt_config().with_timeout_ms(5_000).unwrap();
        assert_eq!(
            resolved_note_transport_endpoint(&Endpoint::testnet(), None, &selection(&timeout_only)),
            Some(NOTE_TRANSPORT_TESTNET_ENDPOINT.to_string())
        );
    }

    #[test]
    fn custom_endpoint_without_override_has_no_note_transport() {
        assert_eq!(
            resolved_note_transport_endpoint(
                &custom_endpoint(),
                None,
                &selection(&RpcConfig::new())
            ),
            None
        );
    }

    /// Guards the `with_max_retries(0)` carve-out over a real gRPC wire: the
    /// miden-client internal transport-retry loop retransmits rate-limited
    /// requests — including submissions — up to four extra times per attempt
    /// when enabled, so two wrapper attempts must reach the node as exactly
    /// two requests.
    #[tokio::test]
    async fn the_inner_miden_client_retry_loop_stays_disabled_over_a_real_wire() {
        use std::sync::atomic::{AtomicU32, Ordering};

        let calls = Arc::new(AtomicU32::new(0));
        let node = miden_rpc_client::test_node::ScriptedNode::failing(
            u32::MAX,
            || tonic::Status::resource_exhausted("Too Many Requests!"),
            calls.clone(),
        );
        let url = miden_rpc_client::test_node::serve(node).await;
        let address = url
            .strip_prefix("http://")
            .expect("scripted node is plain http");
        let (host, port) = address.rsplit_once(':').expect("endpoint carries a port");
        let endpoint = Endpoint::new(
            "http".to_string(),
            host.to_string(),
            Some(port.parse().expect("ephemeral port parses")),
        );

        let rpc_config = RpcConfig::new().with_retry_policy(RpcRetryPolicy::new(2));
        let client = configured_node_rpc_client(&endpoint, &rpc_config);

        client
            .get_rpc_limits()
            .await
            .expect_err("the scripted node always rate-limits");

        assert_eq!(calls.load(Ordering::SeqCst), 2);
    }
}