soroban-cli 26.1.0

Soroban CLI
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
use serde::{Deserialize, Serialize};
use std::str::FromStr;

use sep5::SeedPhrase;
use stellar_strkey::ed25519::{PrivateKey, PublicKey};

use crate::{
    print::Print,
    signer::{
        self, ledger::LedgerEntry, secure_store, LocalKey, SecureStoreEntry, Signer, SignerKind,
    },
    utils,
};

use super::key::Key;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error(transparent)]
    Secret(#[from] stellar_strkey::DecodeError),
    #[error(transparent)]
    SeedPhrase(#[from] sep5::error::Error),
    #[error(transparent)]
    Ed25519(#[from] ed25519_dalek::SignatureError),
    #[error("cannot parse secret (S) or seed phrase (12 or 24 word)")]
    InvalidSecretOrSeedPhrase,
    #[error(transparent)]
    Signer(#[from] signer::Error),
    #[error("Ledger does not reveal secret key")]
    LedgerDoesNotRevealSecretKey,
    #[error(transparent)]
    SecureStore(#[from] secure_store::Error),
    #[error("Secure Store does not reveal secret key")]
    SecureStoreDoesNotRevealSecretKey,
    #[error(transparent)]
    Ledger(#[from] signer::ledger::Error),
    #[error("--hd-path is fixed at the time a Ledger identity is added; pass `--ledger --hd-path N` to inspect another path on the device")]
    LedgerHdPathFixed,
}

#[derive(Debug, clap::Args, Clone)]
#[group(skip)]
pub struct Args {
    /// ⚠️ Deprecated, use `--secure-store`. Enter secret (S) key when prompted
    #[arg(long)]
    pub secret_key: bool,

    /// ⚠️ Deprecated, use `--secure-store`. Enter key using 12-24 word seed phrase
    #[arg(long)]
    pub seed_phrase: bool,

    /// Save the new key in your OS's credential secure store.
    ///
    /// On Mac this uses Keychain, on Windows it is Secure Store Service, and on *nix platforms it uses a combination of the kernel keyutils and DBus-based Secret Service.
    ///
    /// This only supports seed phrases for now.
    #[arg(long)]
    pub secure_store: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum Secret {
    SecretKey {
        secret_key: String,
    },
    SeedPhrase {
        seed_phrase: String,
        // Persisted derivation index. Lets `--hd-path` set on `keys generate` /
        // `keys add` travel with the identity, so later commands derive the
        // intended account without re-passing the flag. Optional for backwards
        // compatibility with files written before this field existed.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        hd_path: Option<u32>,
    },
    // Hardware-wallet identity. The required `hardware` field tags the device
    // kind (currently only `ledger`) and disambiguates this variant under
    // `untagged`; future wallets can introduce new `HardwareKind` values
    // without a new Secret variant. The cached `public_key` lets address and
    // hint lookups succeed without the device being connected.
    Ledger {
        hardware: HardwareKind,
        public_key: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        hd_path: Option<u32>,
    },
    SecureStore {
        entry_name: String,
        // Cached public key derived from the secure-store entry. Lets us answer
        // address/hint queries without unlocking the keychain. Optional for
        // backwards compatibility with files written before this field existed.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        public_key: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        hd_path: Option<u32>,
    },
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum HardwareKind {
    Ledger,
}

impl FromStr for Secret {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if PrivateKey::from_string(s).is_ok() {
            Ok(Secret::SecretKey {
                secret_key: s.to_string(),
            })
        } else if sep5::SeedPhrase::from_str(s).is_ok() {
            Ok(Secret::SeedPhrase {
                seed_phrase: s.to_string(),
                hd_path: None,
            })
        } else if s.starts_with(secure_store::ENTRY_PREFIX) {
            Ok(Secret::SecureStore {
                entry_name: s.to_string(),
                public_key: None,
                hd_path: None,
            })
        } else {
            Err(Error::InvalidSecretOrSeedPhrase)
        }
    }
}

impl From<PrivateKey> for Secret {
    fn from(value: PrivateKey) -> Self {
        Secret::SecretKey {
            secret_key: format!("{value}"),
        }
    }
}

impl From<Secret> for Key {
    fn from(value: Secret) -> Self {
        Key::Secret(value)
    }
}

impl From<SeedPhrase> for Secret {
    fn from(value: SeedPhrase) -> Self {
        Secret::SeedPhrase {
            seed_phrase: value.seed_phrase.into_phrase(),
            hd_path: None,
        }
    }
}

impl Secret {
    pub fn private_key(&self, index: Option<u32>) -> Result<PrivateKey, Error> {
        Ok(match self {
            Secret::SecretKey { secret_key } => PrivateKey::from_string(secret_key)?,
            Secret::SeedPhrase {
                seed_phrase,
                hd_path,
            } => PrivateKey::from_payload(
                &sep5::SeedPhrase::from_str(seed_phrase)?
                    .from_path_index(index.or(*hd_path).unwrap_or_default() as usize, None)?
                    .private()
                    .0,
            )?,
            Secret::Ledger { .. } => return Err(Error::LedgerDoesNotRevealSecretKey),
            Secret::SecureStore { .. } => {
                return Err(Error::SecureStoreDoesNotRevealSecretKey);
            }
        })
    }

    pub fn public_key(&self, index: Option<u32>) -> Result<PublicKey, Error> {
        match self {
            Secret::SecureStore {
                entry_name,
                public_key,
                hd_path,
            } => {
                let effective = index.or(*hd_path);
                if let Some(cached) = cached_public_key(public_key.as_deref(), *hd_path, effective)
                {
                    return Ok(cached);
                }
                Ok(secure_store::get_public_key(entry_name, effective)?)
            }
            Secret::Ledger { public_key, .. } => {
                if index.is_some() {
                    return Err(Error::LedgerHdPathFixed);
                }
                Ok(PublicKey::from_string(public_key)?)
            }
            _ => {
                let key = self.key_pair(index)?;
                Ok(stellar_strkey::ed25519::PublicKey::from_payload(
                    key.verifying_key().as_bytes(),
                )?)
            }
        }
    }

    pub fn signer(&self, hd_path: Option<u32>, print: Print) -> Result<Signer, Error> {
        let kind = match self {
            Secret::SecretKey { .. } | Secret::SeedPhrase { .. } => {
                let key = self.key_pair(hd_path)?;
                SignerKind::Local(LocalKey { key })
            }
            Secret::Ledger {
                hardware: HardwareKind::Ledger,
                public_key,
                hd_path: cached_hd_path,
            } => {
                if hd_path.is_some() {
                    return Err(Error::LedgerHdPathFixed);
                }
                SignerKind::Ledger(LedgerEntry {
                    hd_path: cached_hd_path.unwrap_or_default(),
                    public_key: Some(PublicKey::from_string(public_key)?),
                })
            }
            Secret::SecureStore {
                entry_name,
                public_key,
                hd_path: cached_hd_path,
            } => {
                let effective = hd_path.or(*cached_hd_path);
                let cached_public_key =
                    cached_public_key(public_key.as_deref(), *cached_hd_path, effective);
                SignerKind::SecureStore(SecureStoreEntry {
                    name: entry_name.clone(),
                    hd_path: effective,
                    public_key: cached_public_key,
                })
            }
        };
        Ok(Signer { kind, print })
    }

    pub fn key_pair(&self, index: Option<u32>) -> Result<ed25519_dalek::SigningKey, Error> {
        Ok(utils::into_signing_key(&self.private_key(index)?))
    }

    pub fn from_seed(seed: Option<&str>) -> Result<Self, Error> {
        Ok(seed_phrase_from_seed(seed)?.into())
    }
}

// Returns the cached public key when it can be used, or `None` to signal a
// cache miss. The cache is best-effort: a malformed cached value is ignored
// rather than propagated, and `None`/`Some(0)` are treated as the same path
// since the rest of the codebase uses `unwrap_or_default()` for hd_path.
fn cached_public_key(
    cached: Option<&str>,
    cached_hd_path: Option<u32>,
    requested_hd_path: Option<u32>,
) -> Option<PublicKey> {
    if cached_hd_path.unwrap_or_default() != requested_hd_path.unwrap_or_default() {
        return None;
    }
    PublicKey::from_string(cached?).ok()
}

pub fn seed_phrase_from_seed(seed: Option<&str>) -> Result<SeedPhrase, Error> {
    Ok(if let Some(seed) = seed.map(str::as_bytes) {
        sep5::SeedPhrase::from_entropy(seed)?
    } else {
        sep5::SeedPhrase::random(sep5::MnemonicType::Words24)?
    })
}

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

    const TEST_PUBLIC_KEY: &str = "GAREAZZQWHOCBJS236KIE3AWYBVFLSBK7E5UW3ICI3TCRWQKT5LNLCEZ";
    const TEST_SECRET_KEY: &str = "SBF5HLRREHMS36XZNTUSKZ6FTXDZGNXOHF4EXKUL5UCWZLPBX3NGJ4BH";
    const TEST_SEED_PHRASE: &str =
        "depth decade power loud smile spatial sign movie judge february rate broccoli";

    #[test]
    fn test_from_str_for_secret_key() {
        let secret = Secret::from_str(TEST_SECRET_KEY).unwrap();
        let public_key = secret.public_key(None).unwrap();
        let private_key = secret.private_key(None).unwrap();

        assert!(matches!(secret, Secret::SecretKey { .. }));
        assert_eq!(public_key.to_string(), TEST_PUBLIC_KEY);
        assert_eq!(private_key.to_string(), TEST_SECRET_KEY);
    }

    #[test]
    fn test_secret_from_seed_phrase() {
        let secret = Secret::from_str(TEST_SEED_PHRASE).unwrap();
        let public_key = secret.public_key(None).unwrap();
        let private_key = secret.private_key(None).unwrap();

        assert!(matches!(secret, Secret::SeedPhrase { .. }));
        assert_eq!(public_key.to_string(), TEST_PUBLIC_KEY);
        assert_eq!(private_key.to_string(), TEST_SECRET_KEY);
    }

    #[test]
    fn test_secret_from_secure_store() {
        //todo: add assertion for getting public key - will need to mock the keychain and add the keypair to the keychain
        let secret = Secret::from_str("secure_store:org.stellar.cli-alice").unwrap();
        assert!(matches!(secret, Secret::SecureStore { .. }));

        let private_key_result = secret.private_key(None);
        assert!(private_key_result.is_err());
        assert!(matches!(
            private_key_result.unwrap_err(),
            Error::SecureStoreDoesNotRevealSecretKey
        ));
    }

    #[test]
    fn test_secret_from_invalid_string() {
        let secret = Secret::from_str("invalid");
        assert!(secret.is_err());
    }

    #[test]
    fn test_secure_store_toml_round_trip_with_cache() {
        let secret = Secret::SecureStore {
            entry_name: "secure_store:org.stellar.cli-alice".to_string(),
            public_key: Some(TEST_PUBLIC_KEY.to_string()),
            hd_path: None,
        };
        let serialized = toml::to_string(&secret).unwrap();
        assert!(
            serialized.contains("entry_name"),
            "expected entry_name field in TOML, got: {serialized}"
        );
        assert!(
            serialized.contains("public_key"),
            "expected public_key field in TOML, got: {serialized}"
        );
        let parsed: Secret = toml::from_str(&serialized).unwrap();
        assert_eq!(secret, parsed);
    }

    #[test]
    fn test_secure_store_legacy_toml_parses_with_none_cache() {
        // Identity files written before this feature only contain entry_name.
        // They must still parse, with public_key/hd_path defaulting to None.
        let toml_str = "entry_name = \"secure_store:org.stellar.cli-alice\"\n";
        let secret: Secret = toml::from_str(toml_str).unwrap();
        match secret {
            Secret::SecureStore {
                entry_name,
                public_key,
                hd_path,
            } => {
                assert_eq!(entry_name, "secure_store:org.stellar.cli-alice");
                assert_eq!(public_key, None);
                assert_eq!(hd_path, None);
            }
            other => panic!("expected SecureStore variant, got {other:?}"),
        }
    }

    #[test]
    fn test_secure_store_public_key_uses_cache_without_keychain_access() {
        // A non-existent entry_name guarantees a keychain lookup would fail.
        // The cached public_key should be returned without touching the keychain.
        let secret = Secret::SecureStore {
            entry_name: "secure_store:org.stellar.cli-no-such-entry".to_string(),
            public_key: Some(TEST_PUBLIC_KEY.to_string()),
            hd_path: None,
        };
        let pk = secret.public_key(None).unwrap();
        assert_eq!(pk.to_string(), TEST_PUBLIC_KEY);
    }

    #[test]
    fn test_secure_store_public_key_falls_back_to_persisted_hd_path() {
        // Bogus entry_name guarantees a keychain lookup would fail. The cache is
        // populated at the persisted hd_path; calling public_key(None) must fall
        // back to that hd_path and hit the cache rather than re-deriving at index 0.
        let secret = Secret::SecureStore {
            entry_name: "secure_store:org.stellar.cli-no-such-entry".to_string(),
            public_key: Some(TEST_PUBLIC_KEY.to_string()),
            hd_path: Some(5),
        };
        let pk = secret.public_key(None).unwrap();
        assert_eq!(pk.to_string(), TEST_PUBLIC_KEY);
    }

    #[test]
    fn test_cached_public_key_treats_none_and_zero_as_equal() {
        // `unwrap_or_default()` is used everywhere else for hd_path, so the
        // cache must treat None and Some(0) as the same path.
        assert!(cached_public_key(Some(TEST_PUBLIC_KEY), None, Some(0)).is_some());
        assert!(cached_public_key(Some(TEST_PUBLIC_KEY), Some(0), None).is_some());
        assert!(cached_public_key(Some(TEST_PUBLIC_KEY), None, None).is_some());
        assert!(cached_public_key(Some(TEST_PUBLIC_KEY), Some(0), Some(0)).is_some());

        // Different paths must still miss.
        assert!(cached_public_key(Some(TEST_PUBLIC_KEY), None, Some(1)).is_none());
        assert!(cached_public_key(Some(TEST_PUBLIC_KEY), Some(1), None).is_none());
    }

    #[test]
    fn test_cached_public_key_treats_corrupt_value_as_miss() {
        // A malformed cached value must be ignored so callers fall through to
        // the keychain instead of erroring out.
        assert!(cached_public_key(Some("not-a-public-key"), None, None).is_none());
        assert!(cached_public_key(Some(""), None, None).is_none());
    }

    #[test]
    fn test_seed_phrase_toml_round_trip_with_hd_path() {
        let secret = Secret::SeedPhrase {
            seed_phrase: TEST_SEED_PHRASE.to_string(),
            hd_path: Some(5),
        };
        let serialized = toml::to_string(&secret).unwrap();
        assert!(
            serialized.contains("hd_path"),
            "expected hd_path field in TOML, got: {serialized}"
        );
        let parsed: Secret = toml::from_str(&serialized).unwrap();
        assert_eq!(secret, parsed);
    }

    #[test]
    fn test_seed_phrase_legacy_toml_parses_with_none_hd_path() {
        // Identity files written before this feature only contain seed_phrase.
        // They must still parse, with hd_path defaulting to None.
        let toml_str = format!("seed_phrase = \"{TEST_SEED_PHRASE}\"\n");
        let secret: Secret = toml::from_str(&toml_str).unwrap();
        match secret {
            Secret::SeedPhrase {
                seed_phrase,
                hd_path,
            } => {
                assert_eq!(seed_phrase, TEST_SEED_PHRASE);
                assert_eq!(hd_path, None);
            }
            other => panic!("expected SeedPhrase variant, got {other:?}"),
        }
    }

    #[test]
    fn test_seed_phrase_uses_persisted_hd_path_when_caller_passes_none() {
        // When the caller passes None, the persisted hd_path should drive derivation.
        let secret = Secret::SeedPhrase {
            seed_phrase: TEST_SEED_PHRASE.to_string(),
            hd_path: Some(1),
        };
        let pk_at_0 = secret.public_key(Some(0)).unwrap();
        let pk_default = secret.public_key(None).unwrap();
        assert_ne!(pk_at_0.to_string(), pk_default.to_string());
    }

    #[test]
    fn test_seed_phrase_caller_hd_path_overrides_persisted() {
        // Caller's explicit hd_path argument always wins over the persisted value.
        let secret = Secret::SeedPhrase {
            seed_phrase: TEST_SEED_PHRASE.to_string(),
            hd_path: Some(1),
        };
        let pk = secret.public_key(Some(0)).unwrap();
        let sk = secret.private_key(Some(0)).unwrap();
        assert_eq!(pk.to_string(), TEST_PUBLIC_KEY);
        assert_eq!(sk.to_string(), TEST_SECRET_KEY);
    }

    #[test]
    fn test_ledger_toml_round_trip_with_hd_path() {
        let secret = Secret::Ledger {
            hardware: HardwareKind::Ledger,
            public_key: TEST_PUBLIC_KEY.to_string(),
            hd_path: Some(5),
        };
        let serialized = toml::to_string(&secret).unwrap();
        assert!(
            serialized.contains("hardware = \"ledger\""),
            "expected `hardware = \"ledger\"` tag in TOML, got: {serialized}"
        );
        assert!(
            serialized.contains("public_key"),
            "expected public_key field in TOML, got: {serialized}"
        );
        assert!(
            serialized.contains("hd_path"),
            "expected hd_path field in TOML, got: {serialized}"
        );
        let parsed: Secret = toml::from_str(&serialized).unwrap();
        assert_eq!(secret, parsed);
    }

    #[test]
    fn test_ledger_toml_omits_hd_path_when_none() {
        let secret = Secret::Ledger {
            hardware: HardwareKind::Ledger,
            public_key: TEST_PUBLIC_KEY.to_string(),
            hd_path: None,
        };
        let serialized = toml::to_string(&secret).unwrap();
        assert!(
            !serialized.contains("hd_path"),
            "expected no hd_path field in TOML when None, got: {serialized}"
        );
        let parsed: Secret = toml::from_str(&serialized).unwrap();
        assert_eq!(secret, parsed);
    }

    #[test]
    fn test_ledger_public_key_returns_cached_without_device() {
        // No emulator/device available in this test; the cached public_key
        // must be returned directly without attempting to query the device.
        let secret = Secret::Ledger {
            hardware: HardwareKind::Ledger,
            public_key: TEST_PUBLIC_KEY.to_string(),
            hd_path: Some(5),
        };
        let pk = secret.public_key(None).unwrap();
        assert_eq!(pk.to_string(), TEST_PUBLIC_KEY);
    }

    #[test]
    fn test_ledger_public_key_rejects_caller_hd_path() {
        // The hd-path on a Ledger alias is fixed at `keys add` time; any
        // caller-supplied --hd-path should error rather than silently using
        // the cached value or attempting to override it. Discovery on other
        // paths goes through `--ledger --hd-path N` instead.
        let secret = Secret::Ledger {
            hardware: HardwareKind::Ledger,
            public_key: TEST_PUBLIC_KEY.to_string(),
            hd_path: Some(5),
        };
        assert!(matches!(
            secret.public_key(Some(5)).unwrap_err(),
            Error::LedgerHdPathFixed,
        ));
        assert!(matches!(
            secret.public_key(Some(7)).unwrap_err(),
            Error::LedgerHdPathFixed,
        ));
    }

    #[test]
    fn test_ledger_public_key_uses_cached_path_when_caller_passes_none() {
        let secret = Secret::Ledger {
            hardware: HardwareKind::Ledger,
            public_key: TEST_PUBLIC_KEY.to_string(),
            hd_path: Some(5),
        };
        assert_eq!(
            secret.public_key(None).unwrap().to_string(),
            TEST_PUBLIC_KEY
        );
    }

    #[test]
    fn test_ledger_private_key_is_rejected() {
        let secret = Secret::Ledger {
            hardware: HardwareKind::Ledger,
            public_key: TEST_PUBLIC_KEY.to_string(),
            hd_path: None,
        };
        assert!(matches!(
            secret.private_key(None).unwrap_err(),
            Error::LedgerDoesNotRevealSecretKey,
        ));
    }

    #[test]
    fn test_ledger_toml_does_not_collide_with_secure_store() {
        // SecureStore TOMLs (entry_name + optional cached public_key) must not
        // be mis-deserialized as Ledger now that Ledger also carries public_key.
        let toml_str = "entry_name = \"secure_store:org.stellar.cli-alice\"\n\
                        public_key = \"GAREAZZQWHOCBJS236KIE3AWYBVFLSBK7E5UW3ICI3TCRWQKT5LNLCEZ\"\n";
        let secret: Secret = toml::from_str(toml_str).unwrap();
        assert!(matches!(secret, Secret::SecureStore { .. }));
    }
}