iota-sdk 2.0.0-beta.1

The IOTA SDK provides developers with a seamless experience to develop on IOTA by providing account abstractions and clients to interact with node APIs.
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
// Copyright 2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

//! Secret manager module enabling address generation and transaction signing.

/// Module for ledger nano based secret management.
#[cfg(feature = "ledger_nano")]
#[cfg_attr(docsrs, doc(cfg(feature = "ledger_nano")))]
pub mod ledger_nano;
/// Module for mnemonic based secret management.
pub mod mnemonic;
/// Module for single private key based secret management.
#[cfg(feature = "private_key_secret_manager")]
#[cfg_attr(docsrs, doc(cfg(feature = "private_key_secret_manager")))]
pub mod private_key;
/// Module for stronghold based secret management.
#[cfg(feature = "stronghold")]
#[cfg_attr(docsrs, doc(cfg(feature = "stronghold")))]
pub mod stronghold;
/// Signing related types
pub mod types;

#[cfg(feature = "stronghold")]
use std::time::Duration;
use std::{collections::HashMap, fmt, ops::Range, str::FromStr};

use async_trait::async_trait;
use crypto::{
    hashes::{blake2b::Blake2b256, Digest},
    keys::{bip39::Mnemonic, bip44::Bip44},
    signatures::{
        ed25519,
        secp256k1_ecdsa::{self, EvmAddress},
    },
};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use zeroize::Zeroizing;

#[cfg(feature = "ledger_nano")]
use self::ledger_nano::LedgerSecretManager;
use self::mnemonic::MnemonicSecretManager;
#[cfg(feature = "private_key_secret_manager")]
use self::private_key::PrivateKeySecretManager;
#[cfg(feature = "stronghold")]
use self::stronghold::StrongholdSecretManager;
pub use self::types::{GenerateAddressOptions, LedgerNanoStatus};
#[cfg(feature = "stronghold")]
use crate::client::secret::types::StrongholdDto;
use crate::{
    client::{
        api::{transaction_builder::TransactionBuilderError, PreparedTransactionData, SignedTransactionData},
        ClientError,
    },
    types::block::{
        address::{Address, Ed25519Address},
        core::UnsignedBlock,
        output::Output,
        payload::SignedTransactionPayload,
        protocol::ProtocolParameters,
        signature::{Ed25519Signature, Signature},
        unlock::{AccountUnlock, NftUnlock, ReferenceUnlock, SignatureUnlock, Unlock, Unlocks},
        Block, BlockError,
    },
};

/// The secret manager interface.
#[async_trait]
pub trait SecretManage: Send + Sync {
    type Error: std::error::Error + Send + Sync;

    /// Generates public keys.
    ///
    /// For `coin_type`, see also <https://github.com/satoshilabs/slips/blob/master/slip-0044.md>.
    async fn generate_ed25519_public_keys(
        &self,
        coin_type: u32,
        account_index: u32,
        address_indexes: Range<u32>,
        options: impl Into<Option<GenerateAddressOptions>> + Send,
    ) -> Result<Vec<ed25519::PublicKey>, Self::Error>;

    /// Generates addresses.
    ///
    /// For `coin_type`, see also <https://github.com/satoshilabs/slips/blob/master/slip-0044.md>.
    async fn generate_ed25519_addresses(
        &self,
        coin_type: u32,
        account_index: u32,
        address_indexes: Range<u32>,
        options: impl Into<Option<GenerateAddressOptions>> + Send,
    ) -> Result<Vec<Ed25519Address>, Self::Error> {
        Ok(self
            .generate_ed25519_public_keys(coin_type, account_index, address_indexes, options)
            .await?
            .iter()
            .map(|public_key| Ed25519Address::new(Blake2b256::digest(public_key.to_bytes()).into()))
            .collect())
    }

    async fn generate_evm_addresses(
        &self,
        coin_type: u32,
        account_index: u32,
        address_indexes: Range<u32>,
        options: impl Into<Option<GenerateAddressOptions>> + Send,
    ) -> Result<Vec<EvmAddress>, Self::Error>;

    /// Signs msg using the given [`Bip44`] using Ed25519.
    async fn sign_ed25519(&self, msg: &[u8], chain: Bip44) -> Result<Ed25519Signature, Self::Error>;

    /// Signs msg using the given [`Bip44`] using Secp256k1.
    async fn sign_secp256k1_ecdsa(
        &self,
        msg: &[u8],
        chain: Bip44,
    ) -> Result<(secp256k1_ecdsa::PublicKey, secp256k1_ecdsa::RecoverableSignature), Self::Error>;

    /// Signs `transaction_signing_hash` using the given `chain`, returning an [`Unlock`].
    async fn signature_unlock(&self, transaction_signing_hash: &[u8; 32], chain: Bip44) -> Result<Unlock, Self::Error> {
        Ok(Unlock::from(SignatureUnlock::new(Signature::from(
            self.sign_ed25519(transaction_signing_hash, chain).await?,
        ))))
    }

    async fn transaction_unlocks(
        &self,
        prepared_transaction_data: &PreparedTransactionData,
        protocol_parameters: &ProtocolParameters,
    ) -> Result<Unlocks, Self::Error>;

    async fn sign_transaction(
        &self,
        prepared_transaction_data: PreparedTransactionData,
        protocol_parameters: &ProtocolParameters,
    ) -> Result<SignedTransactionPayload, Self::Error>;
}

pub trait SecretManagerConfig: SecretManage {
    type Config: Serialize + DeserializeOwned + fmt::Debug + Send + Sync;

    fn to_config(&self) -> Option<Self::Config>;

    fn from_config(config: &Self::Config) -> Result<Self, Self::Error>
    where
        Self: Sized;
}

/// Supported secret managers
#[non_exhaustive]
pub enum SecretManager {
    /// Secret manager that uses [`iota_stronghold`] as the backing storage.
    #[cfg(feature = "stronghold")]
    #[cfg_attr(docsrs, doc(cfg(feature = "stronghold")))]
    Stronghold(StrongholdSecretManager),

    /// Secret manager that uses a Ledger Nano hardware wallet or Speculos simulator.
    #[cfg(feature = "ledger_nano")]
    #[cfg_attr(docsrs, doc(cfg(feature = "ledger_nano")))]
    LedgerNano(LedgerSecretManager),

    /// Secret manager that uses a mnemonic in plain memory. It's not recommended for production use. Use
    /// LedgerNano or Stronghold instead.
    Mnemonic(MnemonicSecretManager),

    /// Secret manager that uses a single private key.
    #[cfg(feature = "private_key_secret_manager")]
    #[cfg_attr(docsrs, doc(cfg(feature = "private_key_secret_manager")))]
    PrivateKey(Box<PrivateKeySecretManager>),

    /// Secret manager that's just a placeholder, so it can be provided to an online wallet, but can't be used for
    /// signing.
    Placeholder,
}

#[cfg(feature = "stronghold")]
impl From<StrongholdSecretManager> for SecretManager {
    fn from(secret_manager: StrongholdSecretManager) -> Self {
        Self::Stronghold(secret_manager)
    }
}

#[cfg(feature = "ledger_nano")]
impl From<LedgerSecretManager> for SecretManager {
    fn from(secret_manager: LedgerSecretManager) -> Self {
        Self::LedgerNano(secret_manager)
    }
}

impl From<MnemonicSecretManager> for SecretManager {
    fn from(secret_manager: MnemonicSecretManager) -> Self {
        Self::Mnemonic(secret_manager)
    }
}

#[cfg(feature = "private_key_secret_manager")]
impl From<PrivateKeySecretManager> for SecretManager {
    fn from(secret_manager: PrivateKeySecretManager) -> Self {
        Self::PrivateKey(Box::new(secret_manager))
    }
}

impl fmt::Debug for SecretManager {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            #[cfg(feature = "stronghold")]
            Self::Stronghold(_) => f.debug_tuple("Stronghold").field(&"...").finish(),
            #[cfg(feature = "ledger_nano")]
            Self::LedgerNano(_) => f.debug_tuple("LedgerNano").field(&"...").finish(),
            Self::Mnemonic(_) => f.debug_tuple("Mnemonic").field(&"...").finish(),
            #[cfg(feature = "private_key_secret_manager")]
            Self::PrivateKey(_) => f.debug_tuple("PrivateKey").field(&"...").finish(),
            Self::Placeholder => f.debug_struct("Placeholder").finish(),
        }
    }
}

impl fmt::Display for SecretManager {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            #[cfg(feature = "stronghold")]
            Self::Stronghold(_) => write!(f, "Stronghold"),
            #[cfg(feature = "ledger_nano")]
            Self::LedgerNano(l) => {
                if l.is_simulator {
                    write!(f, "LedgerNano Simulator")
                } else {
                    write!(f, "LedgerNano")
                }
            }
            Self::Mnemonic(_) => write!(f, "Mnemonic"),
            #[cfg(feature = "private_key_secret_manager")]
            Self::PrivateKey(_) => write!(f, "PrivateKey"),
            Self::Placeholder => write!(f, "Placeholder"),
        }
    }
}

impl FromStr for SecretManager {
    type Err = ClientError;

    fn from_str(s: &str) -> Result<Self, ClientError> {
        Self::try_from(serde_json::from_str::<SecretManagerDto>(s)?)
    }
}

/// DTO for secret manager types with required data.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub enum SecretManagerDto {
    /// Stronghold
    #[cfg(feature = "stronghold")]
    #[cfg_attr(docsrs, doc(cfg(feature = "stronghold")))]
    #[serde(alias = "stronghold")]
    Stronghold(StrongholdDto),
    /// Ledger Device, bool specifies if it's a simulator or not
    #[cfg(feature = "ledger_nano")]
    #[cfg_attr(docsrs, doc(cfg(feature = "ledger_nano")))]
    #[serde(alias = "ledgerNano")]
    LedgerNano(bool),
    /// Mnemonic
    #[serde(alias = "mnemonic")]
    Mnemonic(Zeroizing<String>),
    /// Private Key
    #[cfg(feature = "private_key_secret_manager")]
    #[cfg_attr(docsrs, doc(cfg(feature = "private_key_secret_manager")))]
    #[serde(alias = "privateKey")]
    PrivateKey(Zeroizing<String>),
    /// Hex seed
    #[serde(alias = "hexSeed")]
    HexSeed(Zeroizing<String>),
    /// Placeholder
    #[serde(alias = "placeholder")]
    Placeholder,
}

impl TryFrom<SecretManagerDto> for SecretManager {
    type Error = ClientError;

    fn try_from(value: SecretManagerDto) -> Result<Self, ClientError> {
        Ok(match value {
            #[cfg(feature = "stronghold")]
            SecretManagerDto::Stronghold(stronghold_dto) => {
                let mut builder = StrongholdSecretManager::builder();

                if let Some(password) = stronghold_dto.password {
                    builder = builder.password(password);
                }

                if let Some(timeout) = stronghold_dto.timeout {
                    builder = builder.timeout(Duration::from_secs(timeout));
                }

                Self::Stronghold(builder.build(&stronghold_dto.snapshot_path)?)
            }

            #[cfg(feature = "ledger_nano")]
            SecretManagerDto::LedgerNano(is_simulator) => Self::LedgerNano(LedgerSecretManager::new(is_simulator)),

            SecretManagerDto::Mnemonic(mnemonic) => {
                Self::Mnemonic(MnemonicSecretManager::try_from_mnemonic(mnemonic.as_str().to_owned())?)
            }

            #[cfg(feature = "private_key_secret_manager")]
            SecretManagerDto::PrivateKey(private_key) => {
                Self::PrivateKey(Box::new(PrivateKeySecretManager::try_from_hex(private_key)?))
            }

            SecretManagerDto::HexSeed(hex_seed) => {
                // `SecretManagerDto` is `ZeroizeOnDrop` so it will take care of zeroizing the original.
                Self::Mnemonic(MnemonicSecretManager::try_from_hex_seed(hex_seed)?)
            }

            SecretManagerDto::Placeholder => Self::Placeholder,
        })
    }
}

impl From<&SecretManager> for SecretManagerDto {
    fn from(value: &SecretManager) -> Self {
        match value {
            #[cfg(feature = "stronghold")]
            SecretManager::Stronghold(stronghold_adapter) => Self::Stronghold(StrongholdDto {
                password: None,
                timeout: stronghold_adapter.get_timeout().map(|duration| duration.as_secs()),
                snapshot_path: stronghold_adapter
                    .snapshot_path
                    .clone()
                    .into_os_string()
                    .to_string_lossy()
                    .into(),
            }),

            #[cfg(feature = "ledger_nano")]
            SecretManager::LedgerNano(ledger_nano) => Self::LedgerNano(ledger_nano.is_simulator),

            // `MnemonicSecretManager(Seed)` doesn't have Debug or Display implemented and in the current use cases of
            // the client/wallet we also don't need to convert it in this direction with the mnemonic/seed, we only need
            // to know the type
            SecretManager::Mnemonic(_mnemonic) => Self::Mnemonic("...".to_string().into()),

            #[cfg(feature = "private_key_secret_manager")]
            SecretManager::PrivateKey(_private_key) => Self::PrivateKey("...".to_string().into()),

            SecretManager::Placeholder => Self::Placeholder,
        }
    }
}

#[async_trait]
impl SecretManage for SecretManager {
    type Error = ClientError;

    async fn generate_ed25519_public_keys(
        &self,
        coin_type: u32,
        account_index: u32,
        address_indexes: Range<u32>,
        options: impl Into<Option<GenerateAddressOptions>> + Send,
    ) -> Result<Vec<ed25519::PublicKey>, Self::Error> {
        match self {
            #[cfg(feature = "stronghold")]
            Self::Stronghold(secret_manager) => Ok(secret_manager
                .generate_ed25519_public_keys(coin_type, account_index, address_indexes, options)
                .await?),
            #[cfg(feature = "ledger_nano")]
            Self::LedgerNano(secret_manager) => Ok(secret_manager
                .generate_ed25519_public_keys(coin_type, account_index, address_indexes, options)
                .await?),
            Self::Mnemonic(secret_manager) => {
                secret_manager
                    .generate_ed25519_public_keys(coin_type, account_index, address_indexes, options)
                    .await
            }
            #[cfg(feature = "private_key_secret_manager")]
            Self::PrivateKey(secret_manager) => {
                secret_manager
                    .generate_ed25519_public_keys(coin_type, account_index, address_indexes, options)
                    .await
            }
            Self::Placeholder => Err(ClientError::PlaceholderSecretManager),
        }
    }

    async fn generate_evm_addresses(
        &self,
        coin_type: u32,
        account_index: u32,
        address_indexes: Range<u32>,
        options: impl Into<Option<GenerateAddressOptions>> + Send,
    ) -> Result<Vec<EvmAddress>, Self::Error> {
        match self {
            #[cfg(feature = "stronghold")]
            Self::Stronghold(secret_manager) => Ok(secret_manager
                .generate_evm_addresses(coin_type, account_index, address_indexes, options)
                .await?),
            #[cfg(feature = "ledger_nano")]
            Self::LedgerNano(secret_manager) => Ok(secret_manager
                .generate_evm_addresses(coin_type, account_index, address_indexes, options)
                .await?),
            Self::Mnemonic(secret_manager) => {
                secret_manager
                    .generate_evm_addresses(coin_type, account_index, address_indexes, options)
                    .await
            }
            #[cfg(feature = "private_key_secret_manager")]
            Self::PrivateKey(secret_manager) => {
                secret_manager
                    .generate_evm_addresses(coin_type, account_index, address_indexes, options)
                    .await
            }
            Self::Placeholder => Err(ClientError::PlaceholderSecretManager),
        }
    }

    async fn sign_ed25519(&self, msg: &[u8], chain: Bip44) -> Result<Ed25519Signature, ClientError> {
        match self {
            #[cfg(feature = "stronghold")]
            Self::Stronghold(secret_manager) => Ok(secret_manager.sign_ed25519(msg, chain).await?),
            #[cfg(feature = "ledger_nano")]
            Self::LedgerNano(secret_manager) => Ok(secret_manager.sign_ed25519(msg, chain).await?),
            Self::Mnemonic(secret_manager) => secret_manager.sign_ed25519(msg, chain).await,
            #[cfg(feature = "private_key_secret_manager")]
            Self::PrivateKey(secret_manager) => secret_manager.sign_ed25519(msg, chain).await,
            Self::Placeholder => Err(ClientError::PlaceholderSecretManager),
        }
    }

    async fn sign_secp256k1_ecdsa(
        &self,
        msg: &[u8],
        chain: Bip44,
    ) -> Result<(secp256k1_ecdsa::PublicKey, secp256k1_ecdsa::RecoverableSignature), Self::Error> {
        match self {
            #[cfg(feature = "stronghold")]
            Self::Stronghold(secret_manager) => Ok(secret_manager.sign_secp256k1_ecdsa(msg, chain).await?),
            #[cfg(feature = "ledger_nano")]
            Self::LedgerNano(secret_manager) => Ok(secret_manager.sign_secp256k1_ecdsa(msg, chain).await?),
            Self::Mnemonic(secret_manager) => secret_manager.sign_secp256k1_ecdsa(msg, chain).await,
            #[cfg(feature = "private_key_secret_manager")]
            Self::PrivateKey(secret_manager) => secret_manager.sign_secp256k1_ecdsa(msg, chain).await,
            Self::Placeholder => Err(ClientError::PlaceholderSecretManager),
        }
    }

    async fn transaction_unlocks(
        &self,
        prepared_transaction_data: &PreparedTransactionData,
        protocol_parameters: &ProtocolParameters,
    ) -> Result<Unlocks, Self::Error> {
        match self {
            #[cfg(feature = "stronghold")]
            Self::Stronghold(secret_manager) => Ok(secret_manager
                .transaction_unlocks(prepared_transaction_data, protocol_parameters)
                .await?),
            #[cfg(feature = "ledger_nano")]
            Self::LedgerNano(secret_manager) => Ok(secret_manager
                .transaction_unlocks(prepared_transaction_data, protocol_parameters)
                .await?),
            Self::Mnemonic(secret_manager) => {
                secret_manager
                    .transaction_unlocks(prepared_transaction_data, protocol_parameters)
                    .await
            }
            #[cfg(feature = "private_key_secret_manager")]
            Self::PrivateKey(secret_manager) => {
                secret_manager
                    .transaction_unlocks(prepared_transaction_data, protocol_parameters)
                    .await
            }
            Self::Placeholder => Err(ClientError::PlaceholderSecretManager),
        }
    }

    async fn sign_transaction(
        &self,
        prepared_transaction_data: PreparedTransactionData,
        protocol_parameters: &ProtocolParameters,
    ) -> Result<SignedTransactionPayload, Self::Error> {
        match self {
            #[cfg(feature = "stronghold")]
            Self::Stronghold(secret_manager) => Ok(secret_manager
                .sign_transaction(prepared_transaction_data, protocol_parameters)
                .await?),
            #[cfg(feature = "ledger_nano")]
            Self::LedgerNano(secret_manager) => Ok(secret_manager
                .sign_transaction(prepared_transaction_data, protocol_parameters)
                .await?),
            Self::Mnemonic(secret_manager) => {
                secret_manager
                    .sign_transaction(prepared_transaction_data, protocol_parameters)
                    .await
            }
            #[cfg(feature = "private_key_secret_manager")]
            Self::PrivateKey(secret_manager) => {
                secret_manager
                    .sign_transaction(prepared_transaction_data, protocol_parameters)
                    .await
            }
            Self::Placeholder => Err(ClientError::PlaceholderSecretManager),
        }
    }
}

pub trait DowncastSecretManager: SecretManage {
    fn downcast<T: 'static + SecretManage>(&self) -> Option<&T>;
}

impl<S: 'static + SecretManage + Send + Sync> DowncastSecretManager for S {
    fn downcast<T: 'static + SecretManage>(&self) -> Option<&T> {
        (self as &(dyn std::any::Any + Send + Sync)).downcast_ref::<T>()
    }
}

impl SecretManagerConfig for SecretManager {
    type Config = SecretManagerDto;

    fn to_config(&self) -> Option<Self::Config> {
        match self {
            #[cfg(feature = "stronghold")]
            Self::Stronghold(s) => s.to_config().map(Self::Config::Stronghold),
            #[cfg(feature = "ledger_nano")]
            Self::LedgerNano(s) => s.to_config().map(Self::Config::LedgerNano),
            Self::Mnemonic(_) => None,
            #[cfg(feature = "private_key_secret_manager")]
            Self::PrivateKey(_) => None,
            Self::Placeholder => None,
        }
    }

    fn from_config(config: &Self::Config) -> Result<Self, Self::Error> {
        Ok(match config {
            #[cfg(feature = "stronghold")]
            SecretManagerDto::Stronghold(config) => Self::Stronghold(StrongholdSecretManager::from_config(config)?),
            #[cfg(feature = "ledger_nano")]
            SecretManagerDto::LedgerNano(config) => Self::LedgerNano(LedgerSecretManager::from_config(config)?),
            SecretManagerDto::HexSeed(hex_seed) => {
                Self::Mnemonic(MnemonicSecretManager::try_from_hex_seed(hex_seed.clone())?)
            }
            SecretManagerDto::Mnemonic(mnemonic) => {
                Self::Mnemonic(MnemonicSecretManager::try_from_mnemonic(mnemonic.as_str().to_owned())?)
            }
            #[cfg(feature = "private_key_secret_manager")]
            SecretManagerDto::PrivateKey(private_key) => {
                Self::PrivateKey(Box::new(PrivateKeySecretManager::try_from_hex(private_key.to_owned())?))
            }
            SecretManagerDto::Placeholder => Self::Placeholder,
        })
    }
}

impl SecretManager {
    /// Tries to create a [`SecretManager`] from a mnemonic string.
    pub fn try_from_mnemonic(mnemonic: impl Into<Mnemonic>) -> Result<Self, ClientError> {
        Ok(Self::Mnemonic(MnemonicSecretManager::try_from_mnemonic(mnemonic)?))
    }

    /// Tries to create a [`SecretManager`] from a seed hex string.
    pub fn try_from_hex_seed(seed: impl Into<Zeroizing<String>>) -> Result<Self, ClientError> {
        Ok(Self::Mnemonic(MnemonicSecretManager::try_from_hex_seed(seed)?))
    }
}

pub(crate) async fn default_transaction_unlocks<M: SecretManage>(
    secret_manager: &M,
    prepared_transaction_data: &PreparedTransactionData,
    protocol_parameters: &ProtocolParameters,
) -> Result<Unlocks, ClientError>
where
    ClientError: From<M::Error>,
{
    let transaction_signing_hash = prepared_transaction_data.transaction.signing_hash();
    let mut blocks = Vec::new();
    let mut block_indexes = HashMap::<Address, usize>::new();
    let commitment_slot_index = prepared_transaction_data
        .transaction
        .context_inputs()
        .commitment()
        .map(|c| c.slot_index());

    // Assuming inputs_data is ordered by address type
    for (current_block_index, input) in prepared_transaction_data.inputs_data.iter().enumerate() {
        // Get the address that is required to unlock the input
        let required_address = input
            .output
            .required_address(commitment_slot_index, protocol_parameters.committable_age_range())?
            .ok_or(ClientError::ExpirationDeadzone)?;

        // Convert restricted and implicit addresses to Ed25519 address, so they're the same entry in `block_indexes`.
        let required_address = match required_address {
            Address::ImplicitAccountCreation(implicit) => Address::Ed25519(*implicit.ed25519_address()),
            Address::Restricted(restricted) => restricted.address().clone(),
            _ => required_address,
        };

        // Check if we already added an [Unlock] for this address
        match block_indexes.get(&required_address) {
            // If we already have an [Unlock] for this address, add a [Unlock] based on the address type
            Some(block_index) => match required_address {
                Address::Ed25519(_) | Address::ImplicitAccountCreation(_) => {
                    blocks.push(Unlock::Reference(ReferenceUnlock::new(*block_index as u16)?));
                }
                Address::Account(_) => blocks.push(Unlock::Account(AccountUnlock::new(*block_index as u16)?)),
                Address::Nft(_) => blocks.push(Unlock::Nft(NftUnlock::new(*block_index as u16)?)),
                _ => Err(BlockError::UnsupportedAddressKind(required_address.kind()))?,
            },
            None => {
                // We can only sign ed25519 addresses and block_indexes needs to contain the account or nft
                // address already at this point, because the reference index needs to be lower
                // than the current block index
                match &required_address {
                    Address::Ed25519(_) | Address::ImplicitAccountCreation(_) => {}
                    _ => Err(TransactionBuilderError::MissingInputWithEd25519Address)?,
                }

                let chain = input.chain.ok_or(ClientError::MissingBip32Chain)?;

                let block = secret_manager
                    .signature_unlock(&transaction_signing_hash, chain)
                    .await?;
                blocks.push(block);

                // Add the ed25519 address to the block_indexes, so it gets referenced if further inputs have
                // the same address in their unlock condition
                block_indexes.insert(required_address.clone(), current_block_index);
            }
        }

        // When we have an account or Nft output, we will add their account or nft address to block_indexes,
        // because they can be used to unlock outputs via [Unlock::Account] or [Unlock::Nft],
        // that have the corresponding account or nft address in their unlock condition
        match &input.output {
            Output::Account(account_output) => block_indexes.insert(
                Address::Account(account_output.account_address(input.output_id())),
                current_block_index,
            ),
            Output::Nft(nft_output) => block_indexes.insert(
                Address::Nft(nft_output.nft_address(input.output_id())),
                current_block_index,
            ),
            _ => None,
        };
    }

    Ok(Unlocks::new(blocks)?)
}

pub(crate) async fn default_sign_transaction<M: SecretManage>(
    secret_manager: &M,
    prepared_transaction_data: PreparedTransactionData,
    protocol_parameters: &ProtocolParameters,
) -> Result<SignedTransactionPayload, ClientError>
where
    ClientError: From<M::Error>,
{
    log::debug!("[sign_transaction] {:?}", prepared_transaction_data);

    let unlocks = secret_manager
        .transaction_unlocks(&prepared_transaction_data, protocol_parameters)
        .await?;

    let PreparedTransactionData {
        transaction,
        inputs_data,
        mana_rewards,
        issuer_id,
        ..
    } = prepared_transaction_data;
    let tx_payload = SignedTransactionPayload::new(transaction, unlocks)?;

    let data = SignedTransactionData {
        payload: tx_payload,
        inputs_data,
        mana_rewards,
        issuer_id,
    };

    data.verify_semantic(protocol_parameters).inspect_err(|e| {
        log::debug!("[sign_transaction] conflict: {e:?} for {:#?}", data.payload);
    })?;

    Ok(data.payload)
}

#[async_trait]
pub trait SignBlock {
    async fn sign_ed25519<S: SecretManage>(self, secret_manager: &S, chain: Bip44) -> Result<Block, ClientError>
    where
        ClientError: From<S::Error>;
}

#[async_trait]
impl SignBlock for UnsignedBlock {
    async fn sign_ed25519<S: SecretManage>(self, secret_manager: &S, chain: Bip44) -> Result<Block, ClientError>
    where
        ClientError: From<S::Error>,
    {
        let msg = self.signing_input();
        Ok(self.finish(secret_manager.sign_ed25519(&msg, chain).await?)?)
    }
}