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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
use crate::{
    log::format_auth_entry,
    signer::ledger::LedgerEntry,
    utils::fee_bump_transaction_hash,
    xdr::{
        self, AccountId, DecoratedSignature, FeeBumpTransactionEnvelope, Hash, HashIdPreimage,
        HashIdPreimageSorobanAuthorization, Limits, MuxedAccount, Operation, OperationBody,
        PublicKey, ScAddress, ScMap, ScSymbol, ScVal, Signature, SignatureHint,
        SorobanAddressCredentials, SorobanAuthorizationEntry, SorobanCredentials, Transaction,
        TransactionEnvelope, TransactionV1Envelope, Uint256, VecM, WriteXdr,
    },
};
use ed25519_dalek::{ed25519::signature::Signer as _, Signature as Ed25519Signature};
use sha2::{Digest, Sha256};

use crate::{config::network::Network, print::Print, utils::transaction_hash};
use std::io::{self, BufRead, IsTerminal};

pub mod ledger;
pub mod validation;

#[cfg(feature = "additional-libs")]
mod keyring;
pub mod secure_store;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("Contract addresses are not supported to sign auth entries {address}")]
    ContractAddressAreNotSupported { address: String },
    #[error(transparent)]
    Ed25519(#[from] ed25519_dalek::SignatureError),
    #[error("Missing signing key for account {address}")]
    MissingSignerForAddress { address: String },
    #[error(transparent)]
    TryFromSlice(#[from] std::array::TryFromSliceError),
    #[error("Invalid Soroban authorization entry - {reason}:\n{auth_entry_str}")]
    InvalidAuthEntry {
        reason: String,
        auth_entry_str: String,
    },
    #[error("An authorization entry requires confirmation, but stdin is not interactive. Rerun with --auto-sign to sign anyway.")]
    AuthEntryRequiresConfirmation,
    #[error("signing cancelled by user")]
    AuthRejected,
    #[error(transparent)]
    Xdr(#[from] xdr::Error),
    #[error("Transaction envelope type not supported")]
    UnsupportedTransactionEnvelopeType,
    #[error(transparent)]
    Url(#[from] url::ParseError),
    #[error(transparent)]
    Open(#[from] std::io::Error),
    #[error("Returning a signature from Lab is not yet supported; Transaction can be found and submitted in lab")]
    ReturningSignatureFromLab,
    #[error(transparent)]
    SecureStore(#[from] secure_store::Error),
    #[error(transparent)]
    Ledger(#[from] ledger::Error),
    #[error(transparent)]
    Decode(#[from] stellar_strkey::DecodeError),
}

/// Sign all SorobanAuthorizationEntry's in the transaction with the given signers. Returns a new
/// transaction with the signatures added to each SorobanAuthorizationEntry.
///
/// If no SorobanAuthorizationEntry's need signing (including if none exist), return Ok(None).
///
/// If a SorobanAuthorizationEntry needs signing, but a signature cannot be produced for it,
/// return an Error
pub async fn sign_soroban_authorizations(
    raw: &Transaction,
    signers: &[Signer],
    signature_expiration_ledger: u32,
    network_passphrase: &str,
    skip_approval: bool,
    print: &Print,
) -> Result<Option<Transaction>, Error> {
    // Check if we have exactly one operation and it's InvokeHostFunction
    let [op @ Operation {
        body: OperationBody::InvokeHostFunction(body),
        ..
    }] = raw.operations.as_slice()
    else {
        return Ok(None);
    };

    let network_id = Hash(Sha256::digest(network_passphrase.as_bytes()).into());
    let source_bytes = muxed_account_bytes(&raw.source_account);

    let mut auths_modified = false;
    let mut signed_auths = Vec::with_capacity(body.auth.len());
    for raw_auth in body.auth.as_slice() {
        let SorobanAuthorizationEntry {
            credentials: SorobanCredentials::Address(credentials),
            ..
        } = raw_auth
        else {
            // Doesn't need special signing
            signed_auths.push(raw_auth.clone());
            continue;
        };
        let SorobanAddressCredentials { address, .. } = credentials;

        // Before we attempt to sign, validate the auth entry is strict
        match validation::classify_auth_invocation(&body.host_function, &raw_auth.root_invocation) {
            validation::AuthStyle::Strict => {}
            validation::AuthStyle::NonStrict => {
                handle_non_strict_authorization(raw_auth, skip_approval, print)?;
            }
            validation::AuthStyle::Invalid => {
                return Err(Error::InvalidAuthEntry {
                    reason: "authorization entry is not expected for the transaction".to_string(),
                    auth_entry_str: format_auth_entry(raw_auth),
                });
            }
        }

        // See if we have a signer for this authorizationEntry
        // If not, then we Error
        let auth_address_bytes: &[u8; 32] = match address {
            ScAddress::MuxedAccount(_) => todo!("muxed accounts are not supported"),
            ScAddress::ClaimableBalance(_) => todo!("claimable balance not supported"),
            ScAddress::LiquidityPool(_) => todo!("liquidity pool not supported"),
            ScAddress::Account(AccountId(PublicKey::PublicKeyTypeEd25519(Uint256(ref a)))) => a,
            ScAddress::Contract(stellar_xdr::curr::ContractId(Hash(c))) => {
                // This address is for a contract. This means we're using a custom
                // smart-contract account. Currently the CLI doesn't support that yet.
                return Err(Error::MissingSignerForAddress {
                    address: format!(
                        "{}",
                        stellar_strkey::Strkey::Contract(stellar_strkey::Contract(*c))
                    ),
                });
            }
        };

        // Auth entries should not request a signature from the tx source account via the `Address` credential type
        if auth_address_bytes == source_bytes {
            return Err(Error::InvalidAuthEntry {
                reason: "transaction source account is used as credentials".to_string(),
                auth_entry_str: format_auth_entry(raw_auth),
            });
        }

        let mut signer: Option<&Signer> = None;
        for s in signers {
            if auth_address_bytes == &s.get_public_key()?.0 {
                signer = Some(s);
                break;
            }
        }

        match signer {
            Some(signer) => {
                let signed_entry = sign_soroban_authorization_entry(
                    raw_auth,
                    signer,
                    signature_expiration_ledger,
                    &network_id,
                )
                .await?;
                signed_auths.push(signed_entry);
                auths_modified = true;
            }
            None => {
                return Err(Error::MissingSignerForAddress {
                    address: format!(
                        "{}",
                        stellar_strkey::Strkey::PublicKeyEd25519(
                            stellar_strkey::ed25519::PublicKey(*auth_address_bytes),
                        )
                    ),
                });
            }
        }
    }

    // If we didn't modify any entries, return Ok(None) to indicate no changes needed to the transaction
    if !auths_modified {
        return Ok(None);
    }

    // Build updated transaction with signed auth entries
    let mut tx = raw.clone();
    let mut new_body = body.clone();
    new_body.auth = signed_auths.try_into()?;
    tx.operations = vec![Operation {
        source_account: op.source_account.clone(),
        body: OperationBody::InvokeHostFunction(new_body),
    }]
    .try_into()?;
    Ok(Some(tx))
}

/// Handle a non-strict auth entry. Under `--auto-sign` (`skip_approval`), log
/// the entry through `Print` so the relaxed policy leaves an audit trail that
/// the user can silence with `--quiet`. Otherwise, prompt the user
/// interactively for approval.
fn handle_non_strict_authorization(
    auth: &SorobanAuthorizationEntry,
    skip_approval: bool,
    print: &Print,
) -> Result<(), Error> {
    if skip_approval {
        print.warnln("Signing authorization entry without approval (--auto-sign):");
        print.println(format_auth_entry(auth));
        Ok(())
    } else {
        confirm_non_strict_authorization(auth)
    }
}

fn confirm_non_strict_authorization(auth: &SorobanAuthorizationEntry) -> Result<(), Error> {
    // ignore quiet flag here as we are prompting the user
    let print = Print::new(false);
    print.warnln(
        "Authorization entry does not match the current contract call, and needs approval:",
    );
    print.println(format_auth_entry(auth));

    let stdin = io::stdin();
    if !stdin.is_terminal() {
        return Err(Error::AuthEntryRequiresConfirmation);
    }

    print.warnln("Sign this authorization entry? (y/N)");
    let mut response = String::new();
    stdin.lock().read_line(&mut response)?;
    if response.trim().eq_ignore_ascii_case("y") {
        Ok(())
    } else {
        Err(Error::AuthRejected)
    }
}

async fn sign_soroban_authorization_entry(
    raw: &SorobanAuthorizationEntry,
    signer: &Signer,
    signature_expiration_ledger: u32,
    network_id: &Hash,
) -> Result<SorobanAuthorizationEntry, Error> {
    let mut auth = raw.clone();
    let SorobanAuthorizationEntry {
        credentials: SorobanCredentials::Address(ref mut credentials),
        ..
    } = auth
    else {
        // Doesn't need special signing
        return Ok(auth);
    };
    let SorobanAddressCredentials { nonce, .. } = credentials;

    let preimage = HashIdPreimage::SorobanAuthorization(HashIdPreimageSorobanAuthorization {
        network_id: network_id.clone(),
        invocation: auth.root_invocation.clone(),
        nonce: *nonce,
        signature_expiration_ledger,
    })
    .to_xdr(Limits::none())?;

    let payload = Sha256::digest(preimage);
    let p: [u8; 32] = payload.as_slice().try_into()?;
    let signature = signer.sign_payload(p).await?;
    let public_key_vec = signer.get_public_key()?.0.to_vec();

    let map = ScMap::sorted_from(vec![
        (
            ScVal::Symbol(ScSymbol("public_key".try_into()?)),
            ScVal::Bytes(public_key_vec.try_into().map_err(Error::Xdr)?),
        ),
        (
            ScVal::Symbol(ScSymbol("signature".try_into()?)),
            ScVal::Bytes(
                signature
                    .to_bytes()
                    .to_vec()
                    .try_into()
                    .map_err(Error::Xdr)?,
            ),
        ),
    ])
    .map_err(Error::Xdr)?;
    credentials.signature = ScVal::Vec(Some(
        vec![ScVal::Map(Some(map))].try_into().map_err(Error::Xdr)?,
    ));
    credentials.signature_expiration_ledger = signature_expiration_ledger;
    auth.credentials = SorobanCredentials::Address(credentials.clone());
    Ok(auth)
}

pub struct Signer {
    pub kind: SignerKind,
    pub print: Print,
}

#[allow(clippy::module_name_repetitions, clippy::large_enum_variant)]
pub enum SignerKind {
    Local(LocalKey),
    Ledger(LedgerEntry),
    Lab,
    SecureStore(SecureStoreEntry),
}

// It is advised to use the sign_with module, which handles creating a Signer with the appropriate SignerKind
impl Signer {
    pub async fn sign_tx(
        &self,
        tx: Transaction,
        network: &Network,
    ) -> Result<TransactionEnvelope, Error> {
        let tx_env = TransactionEnvelope::Tx(TransactionV1Envelope {
            tx,
            signatures: VecM::default(),
        });
        self.sign_tx_env(&tx_env, network).await
    }

    pub async fn sign_tx_env(
        &self,
        tx_env: &TransactionEnvelope,
        network: &Network,
    ) -> Result<TransactionEnvelope, Error> {
        match &tx_env {
            TransactionEnvelope::Tx(TransactionV1Envelope { tx, signatures }) => {
                let tx_hash = transaction_hash(tx, &network.network_passphrase)?;
                self.print
                    .infoln(format!("Signing transaction: {}", hex::encode(tx_hash)));
                let decorated_signature = self.sign_tx_hash(tx_hash, tx_env, network).await?;
                let mut sigs = signatures.clone().into_vec();
                sigs.push(decorated_signature);
                Ok(TransactionEnvelope::Tx(TransactionV1Envelope {
                    tx: tx.clone(),
                    signatures: sigs.try_into()?,
                }))
            }
            TransactionEnvelope::TxFeeBump(FeeBumpTransactionEnvelope { tx, signatures }) => {
                let tx_hash = fee_bump_transaction_hash(tx, &network.network_passphrase)?;
                self.print.infoln(format!(
                    "Signing fee bump transaction: {}",
                    hex::encode(tx_hash),
                ));
                let decorated_signature = self.sign_tx_hash(tx_hash, tx_env, network).await?;
                let mut sigs = signatures.clone().into_vec();
                sigs.push(decorated_signature);
                Ok(TransactionEnvelope::TxFeeBump(FeeBumpTransactionEnvelope {
                    tx: tx.clone(),
                    signatures: sigs.try_into()?,
                }))
            }
            TransactionEnvelope::TxV0(_) => Err(Error::UnsupportedTransactionEnvelopeType),
        }
    }

    pub fn get_public_key(&self) -> Result<stellar_strkey::ed25519::PublicKey, Error> {
        match &self.kind {
            SignerKind::Local(local_key) => Ok(stellar_strkey::ed25519::PublicKey::from_payload(
                local_key.key.verifying_key().as_bytes(),
            )?),
            SignerKind::Ledger(ledger) => Ok(ledger
                .public_key
                .expect("Ledger signers reachable here are built from Secret::Ledger and always carry a cached public key")),
            SignerKind::Lab => Err(Error::ReturningSignatureFromLab),
            SignerKind::SecureStore(secure_store_entry) => secure_store_entry.get_public_key(),
        }
    }

    pub async fn sign_payload(&self, payload: [u8; 32]) -> Result<Ed25519Signature, Error> {
        match &self.kind {
            SignerKind::Local(local_key) => local_key.sign_payload(payload),
            SignerKind::Ledger(ledger) => Ok(ledger.sign_payload(payload).await?),
            SignerKind::Lab => Err(Error::ReturningSignatureFromLab),
            SignerKind::SecureStore(secure_store_entry) => secure_store_entry.sign_payload(payload),
        }
    }

    async fn sign_tx_hash(
        &self,
        tx_hash: [u8; 32],
        tx_env: &TransactionEnvelope,
        network: &Network,
    ) -> Result<DecoratedSignature, Error> {
        match &self.kind {
            SignerKind::Local(key) => key.sign_tx_hash(tx_hash),
            SignerKind::Lab => Lab::sign_tx_env(tx_env, network, &self.print),
            SignerKind::Ledger(ledger) => ledger.sign_tx_hash(tx_hash).await.map_err(Error::from),
            SignerKind::SecureStore(entry) => entry.sign_tx_hash(tx_hash),
        }
    }
}

pub struct LocalKey {
    pub key: ed25519_dalek::SigningKey,
}

impl LocalKey {
    pub fn sign_tx_hash(&self, tx_hash: [u8; 32]) -> Result<DecoratedSignature, Error> {
        let hint = SignatureHint(self.key.verifying_key().to_bytes()[28..].try_into()?);
        let signature = Signature(self.key.sign(&tx_hash).to_bytes().to_vec().try_into()?);
        Ok(DecoratedSignature { hint, signature })
    }

    pub fn sign_payload(&self, payload: [u8; 32]) -> Result<Ed25519Signature, Error> {
        Ok(self.key.sign(&payload))
    }
}

pub struct Lab;

impl Lab {
    const URL: &str = "https://lab.stellar.org/transaction/cli-sign";

    pub fn sign_tx_env(
        tx_env: &TransactionEnvelope,
        network: &Network,
        printer: &Print,
    ) -> Result<DecoratedSignature, Error> {
        let xdr = tx_env.to_xdr_base64(Limits::none())?;

        let mut url = url::Url::parse(Self::URL)?;
        url.query_pairs_mut()
            .append_pair("networkPassphrase", &network.network_passphrase)
            .append_pair("xdr", &xdr);
        let url = url.to_string();

        printer.globeln(format!("Opening lab to sign transaction: {url}"));
        open::that(url)?;

        Err(Error::ReturningSignatureFromLab)
    }
}

pub struct SecureStoreEntry {
    pub name: String,
    pub hd_path: Option<u32>,
    pub public_key: Option<stellar_strkey::ed25519::PublicKey>,
}

impl SecureStoreEntry {
    pub fn get_public_key(&self) -> Result<stellar_strkey::ed25519::PublicKey, Error> {
        if let Some(pk) = &self.public_key {
            return Ok(*pk);
        }
        Ok(secure_store::get_public_key(&self.name, self.hd_path)?)
    }

    pub fn sign_tx_hash(&self, tx_hash: [u8; 32]) -> Result<DecoratedSignature, Error> {
        let hint = SignatureHint(self.get_public_key()?.0[28..].try_into()?);

        let signed_tx_hash = secure_store::sign_tx_data(&self.name, self.hd_path, &tx_hash)?;

        let signature = Signature(signed_tx_hash.clone().try_into()?);
        Ok(DecoratedSignature { hint, signature })
    }

    pub fn sign_payload(&self, payload: [u8; 32]) -> Result<Ed25519Signature, Error> {
        let signed_bytes = secure_store::sign_tx_data(&self.name, self.hd_path, &payload)?;
        let sig = Ed25519Signature::from_bytes(signed_bytes.as_slice().try_into()?);
        Ok(sig)
    }
}

/// Extract the Ed25519 public key bytes from a MuxedAccount
fn muxed_account_bytes(source: &MuxedAccount) -> &[u8; 32] {
    match source {
        MuxedAccount::Ed25519(Uint256(bytes)) => bytes,
        MuxedAccount::MuxedEd25519(muxed) => &muxed.ed25519.0,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::signer::ledger::LedgerEntry;
    use crate::xdr::{
        BytesM, HostFunction, InvokeContractArgs, InvokeHostFunctionOp, Memo, Preconditions,
        SequenceNumber, SorobanAuthorizedFunction, SorobanAuthorizedInvocation, TransactionExt,
    };

    const NETWORK: &str = "Test SDF Network ; September 2015";
    const EXPIRATION_LEDGER: u32 = 100;

    fn local_signer(seed: [u8; 32]) -> Signer {
        Signer {
            kind: SignerKind::Local(LocalKey {
                key: ed25519_dalek::SigningKey::from_bytes(&seed),
            }),
            print: Print::new(true),
        }
    }

    fn signer_pubkey(signer: &Signer) -> [u8; 32] {
        signer.get_public_key().unwrap().0
    }

    fn ed25519_address(bytes: [u8; 32]) -> ScAddress {
        ScAddress::Account(AccountId(PublicKey::PublicKeyTypeEd25519(Uint256(bytes))))
    }

    fn invoke_args(contract: [u8; 32], fn_name: &str) -> InvokeContractArgs {
        InvokeContractArgs {
            contract_address: ScAddress::Contract(stellar_xdr::curr::ContractId(Hash(contract))),
            function_name: ScSymbol(fn_name.try_into().unwrap()),
            args: VecM::default(),
        }
    }

    fn invocation(contract: [u8; 32], fn_name: &str) -> SorobanAuthorizedInvocation {
        SorobanAuthorizedInvocation {
            function: SorobanAuthorizedFunction::ContractFn(invoke_args(contract, fn_name)),
            sub_invocations: VecM::default(),
        }
    }

    fn address_auth(
        address: ScAddress,
        invocation: SorobanAuthorizedInvocation,
    ) -> SorobanAuthorizationEntry {
        SorobanAuthorizationEntry {
            credentials: SorobanCredentials::Address(SorobanAddressCredentials {
                address,
                nonce: 0,
                signature_expiration_ledger: 0,
                signature: ScVal::Void,
            }),
            root_invocation: invocation,
        }
    }

    fn build_tx(
        source: MuxedAccount,
        host_function: HostFunction,
        auth: Vec<SorobanAuthorizationEntry>,
    ) -> Transaction {
        Transaction {
            source_account: source,
            fee: 100,
            seq_num: SequenceNumber(1),
            cond: Preconditions::None,
            memo: Memo::None,
            operations: vec![Operation {
                source_account: None,
                body: OperationBody::InvokeHostFunction(InvokeHostFunctionOp {
                    host_function,
                    auth: auth.try_into().unwrap(),
                }),
            }]
            .try_into()
            .unwrap(),
            ext: TransactionExt::V0,
        }
    }

    /// Pull the embedded public_key bytes out of a signed Address-cred entry.
    fn extract_signed_pubkey(creds: &SorobanAddressCredentials) -> [u8; 32] {
        let ScVal::Vec(Some(outer)) = &creds.signature else {
            panic!("expected ScVal::Vec signature");
        };
        let Some(ScVal::Map(Some(map))) = outer.first() else {
            panic!("expected ScVal::Map inside signature vec");
        };
        map.iter()
            .find_map(|e| match (&e.key, &e.val) {
                (ScVal::Symbol(s), ScVal::Bytes(b)) if s.0.as_slice() == b"public_key" => {
                    Some(b.as_slice().try_into().unwrap())
                }
                _ => None,
            })
            .expect("public_key entry")
    }

    #[tokio::test]
    async fn test_signs_address_auth_entry_with_matching_signer() {
        let signer = local_signer([1u8; 32]);
        let signer_unused = local_signer([2u8; 32]);
        let signer_pk = signer_pubkey(&signer);
        let source = MuxedAccount::Ed25519(Uint256([9u8; 32]));
        let contract = [42u8; 32];

        let entry = address_auth(ed25519_address(signer_pk), invocation(contract, "hello"));
        let host_fn = HostFunction::InvokeContract(invoke_args(contract, "hello"));
        let tx = build_tx(source, host_fn, vec![entry]);

        let signed_auth_tx = sign_soroban_authorizations(
            &tx,
            &[signer_unused, signer],
            EXPIRATION_LEDGER,
            NETWORK,
            false,
            &Print::new(true),
        )
        .await
        .unwrap()
        .expect("signing modifies the transaction");

        let OperationBody::InvokeHostFunction(body) = &signed_auth_tx.operations[0].body else {
            panic!("expected InvokeHostFunction");
        };
        let SorobanCredentials::Address(creds) = &body.auth[0].credentials else {
            panic!("expected Address credentials");
        };
        assert!(
            !matches!(creds.signature, ScVal::Void),
            "signature should be filled in"
        );
        assert_eq!(creds.signature_expiration_ledger, EXPIRATION_LEDGER);
        assert_eq!(
            extract_signed_pubkey(creds),
            signer_pk,
            "embedded public_key should match the signer"
        );
    }

    #[tokio::test]
    async fn test_non_strict_auth_signs_when_allowed() {
        let signer = local_signer([1u8; 32]);
        let signer_pk = signer_pubkey(&signer);
        let source = MuxedAccount::Ed25519(Uint256([9u8; 32]));
        let contract = [42u8; 32];
        let other_contract = [99u8; 32];

        let entry = address_auth(
            ed25519_address(signer_pk),
            invocation(other_contract, "hello"),
        );
        let host_fn = HostFunction::InvokeContract(invoke_args(contract, "hello"));
        let tx = build_tx(source, host_fn, vec![entry]);

        let signed_auth_tx = sign_soroban_authorizations(
            &tx,
            &[signer],
            EXPIRATION_LEDGER,
            NETWORK,
            true,
            &Print::new(true),
        )
        .await
        .unwrap()
        .expect("signing modifies the transaction");

        let OperationBody::InvokeHostFunction(body) = &signed_auth_tx.operations[0].body else {
            panic!("expected InvokeHostFunction");
        };
        let SorobanCredentials::Address(creds) = &body.auth[0].credentials else {
            panic!("expected Address credentials");
        };
        assert!(!matches!(creds.signature, ScVal::Void));
    }

    #[tokio::test]
    async fn test_upload_wasm_with_auth_returns_invalid() {
        let signer = local_signer([1u8; 32]);
        let signer_pk = signer_pubkey(&signer);
        let source = MuxedAccount::Ed25519(Uint256([9u8; 32]));
        let wasm: BytesM = [0u8; 32].try_into().unwrap();

        let entry = address_auth(ed25519_address(signer_pk), invocation([42u8; 32], "hello"));
        let host_fn = HostFunction::UploadContractWasm(wasm);
        let tx = build_tx(source, host_fn, vec![entry]);

        let result = sign_soroban_authorizations(
            &tx,
            &[signer],
            EXPIRATION_LEDGER,
            NETWORK,
            false,
            &Print::new(true),
        )
        .await;
        assert!(matches!(result, Err(Error::InvalidAuthEntry { .. })));
    }

    #[tokio::test]
    async fn test_source_account_as_address_returns_invalid() {
        let signer = local_signer([1u8; 32]);
        let signer_pk = signer_pubkey(&signer);
        let source = MuxedAccount::Ed25519(Uint256(signer_pk));
        let contract = [42u8; 32];

        let entry = address_auth(ed25519_address(signer_pk), invocation(contract, "hello"));
        let host_fn = HostFunction::InvokeContract(invoke_args(contract, "hello"));
        let tx = build_tx(source, host_fn, vec![entry]);

        let result = sign_soroban_authorizations(
            &tx,
            &[signer],
            EXPIRATION_LEDGER,
            NETWORK,
            false,
            &Print::new(true),
        )
        .await;
        assert!(matches!(result, Err(Error::InvalidAuthEntry { .. })));
    }

    #[tokio::test]
    async fn test_missing_signer_returns_error() {
        let source = MuxedAccount::Ed25519(Uint256([9u8; 32]));
        let contract = [42u8; 32];
        let unknown = [77u8; 32];

        let entry = address_auth(ed25519_address(unknown), invocation(contract, "hello"));
        let host_fn = HostFunction::InvokeContract(invoke_args(contract, "hello"));
        let tx = build_tx(source, host_fn, vec![entry]);

        let result = sign_soroban_authorizations(
            &tx,
            &[],
            EXPIRATION_LEDGER,
            NETWORK,
            false,
            &Print::new(true),
        )
        .await;
        assert!(matches!(result, Err(Error::MissingSignerForAddress { .. })));
    }

    #[test]
    fn ledger_signer_get_public_key_returns_cached_without_device() {
        const TEST_PUBLIC_KEY: &str = "GAREAZZQWHOCBJS236KIE3AWYBVFLSBK7E5UW3ICI3TCRWQKT5LNLCEZ";
        let pk = stellar_strkey::ed25519::PublicKey::from_string(TEST_PUBLIC_KEY).unwrap();
        let signer = Signer {
            kind: SignerKind::Ledger(LedgerEntry {
                hd_path: 0,
                public_key: Some(pk),
            }),
            print: Print::new(true),
        };
        assert_eq!(
            signer.get_public_key().unwrap().to_string(),
            TEST_PUBLIC_KEY
        );
    }
}