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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
//! Ergonomic facade for the full TX3 lifecycle.
//!
//! This module provides a high-level API that covers invocation, resolution,
//! signing, submission, and status polling.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;

use serde_json::Value;
use thiserror::Error;

use crate::core::{ArgMap, BytesEnvelope};
use crate::tii::Protocol;
use crate::trp::{self, SubmitParams, TxStage, TxStatus, TxWitness};

#[derive(Clone)]
struct SignerParty {
    name: String,
    address: String,
    signer: Arc<dyn Signer + Send + Sync>,
}

/// Error type for facade operations.
#[derive(Debug, Error)]
pub enum Error {
    /// Error originating from TII operations.
    #[error(transparent)]
    Tii(#[from] crate::tii::Error),

    /// Error originating from TRP operations.
    #[error(transparent)]
    Trp(#[from] crate::trp::Error),

    /// Required parameters were not provided.
    #[error("missing required params: {0:?}")]
    MissingParams(Vec<String>),

    /// A party was provided but not declared in the protocol.
    #[error("unknown party: {0}")]
    UnknownParty(String),

    /// Signer failed to produce a witness.
    #[error("signer error: {0}")]
    Signer(#[source] Box<dyn std::error::Error + Send + Sync>),

    /// Submitted hash does not match the resolved hash.
    #[error("submit hash mismatch: expected {expected}, got {received}")]
    SubmitHashMismatch { expected: String, received: String },

    /// Transaction failed to reach confirmation.
    #[error("tx {hash} failed with stage {stage:?}")]
    FinalizedFailed { hash: String, stage: TxStage },

    /// Transaction did not reach confirmation within the polling window.
    #[error("tx {hash} not confirmed after {attempts} attempts (delay {delay:?})")]
    FinalizedTimeout {
        hash: String,
        attempts: u32,
        delay: Duration,
    },
}

/// Configuration for check-status polling.
///
/// Used by `wait_for_confirmed` and `wait_for_finalized`.
#[derive(Debug, Clone)]
pub struct PollConfig {
    /// Number of attempts before timing out.
    pub attempts: u32,
    /// Delay between attempts.
    pub delay: Duration,
}

impl Default for PollConfig {
    fn default() -> Self {
        Self {
            attempts: 20,
            delay: Duration::from_secs(5),
        }
    }
}

/// Inputs passed to a [`Signer`] for each sign call.
///
/// Carries both the bound tx hash and the full hex-encoded tx CBOR. Hash-based
/// signers (Cardano, Ed25519) read `tx_hash_hex`; tx-based signers (e.g. wallet
/// adapters that need the full tx body) read `tx_cbor_hex`. The SDK always
/// populates both fields.
#[derive(Debug, Clone)]
pub struct SignRequest {
    /// Hex-encoded tx hash bound to this signing call.
    pub tx_hash_hex: String,
    /// Hex-encoded full tx CBOR.
    pub tx_cbor_hex: String,
}

/// A signer capable of producing TRP witnesses.
///
/// Signers are address-aware and must return the address they correspond to.
pub trait Signer: Send + Sync {
    /// Returns the address associated with this signer.
    fn address(&self) -> &str;

    /// Signs the transaction described by `request`.
    fn sign(
        &self,
        request: &SignRequest,
    ) -> Result<TxWitness, Box<dyn std::error::Error + Send + Sync>>;
}

/// A party referenced by the protocol.
#[derive(Clone)]
pub enum Party {
    /// Read-only party with a known address.
    Address(String),
    /// Party capable of signing transactions.
    Signer {
        /// Party address (used for invocation args).
        address: String,
        /// Signer implementation.
        signer: Arc<dyn Signer + Send + Sync>,
    },
}

impl Party {
    /// Creates a read-only party from an address.
    pub fn address(address: impl Into<String>) -> Self {
        Party::Address(address.into())
    }

    /// Creates a signer party from a signer.
    ///
    /// The party address is taken from the signer itself.
    ///
    /// # Example
    ///
    /// ```rust
    /// use tx3_sdk::{CardanoSigner, Party};
    ///
    /// let signer = CardanoSigner::from_hex("addr_test1...", "deadbeef...")?;
    /// let party = Party::signer(signer);
    /// # Ok::<(), tx3_sdk::Error>(())
    /// ```
    pub fn signer(signer: impl Signer + 'static) -> Self {
        Party::Signer {
            address: signer.address().to_string(),
            signer: Arc::new(signer),
        }
    }

    fn address_value(&self) -> &str {
        match self {
            Party::Address(address) => address,
            Party::Signer { address, .. } => address,
        }
    }

    fn signer_party(&self, name: &str) -> Option<SignerParty> {
        match self {
            Party::Signer { address, signer } => Some(SignerParty {
                name: name.to_string(),
                address: address.clone(),
                signer: Arc::clone(signer),
            }),
            _ => None,
        }
    }
}

/// High-level client that ties a protocol to a TRP client.
#[derive(Clone)]
pub struct Tx3Client {
    protocol: Arc<Protocol>,
    trp: trp::Client,
    parties: HashMap<String, Party>,
    profile: Option<String>,
}

impl Tx3Client {
    /// Creates a new facade client.
    pub fn new(protocol: Protocol, trp: trp::Client) -> Self {
        Self {
            protocol: Arc::new(protocol),
            trp,
            parties: HashMap::new(),
            profile: None,
        }
    }

    /// Sets the profile for all invocations created by this client.
    ///
    /// This profile is applied to every invocation created by the client.
    pub fn with_profile(mut self, profile: impl Into<String>) -> Self {
        self.profile = Some(profile.into());
        self
    }

    /// Attaches a party definition to this client.
    pub fn with_party(mut self, name: impl Into<String>, party: Party) -> Self {
        self.parties.insert(name.into().to_lowercase(), party);
        self
    }

    /// Attaches multiple party definitions to this client.
    pub fn with_parties<I, K>(mut self, parties: I) -> Self
    where
        I: IntoIterator<Item = (K, Party)>,
        K: Into<String>,
    {
        for (name, party) in parties {
            self.parties.insert(name.into().to_lowercase(), party);
        }
        self
    }

    /// Starts building a transaction invocation.
    pub fn tx(&self, name: impl Into<String>) -> TxBuilder {
        TxBuilder {
            protocol: Arc::clone(&self.protocol),
            trp: self.trp.clone(),
            tx_name: name.into(),
            args: ArgMap::new(),
            parties: self.parties.clone(),
            profile: self.profile.clone(),
        }
    }
}

/// Builder for transaction invocation.
pub struct TxBuilder {
    protocol: Arc<Protocol>,
    trp: trp::Client,
    tx_name: String,
    args: ArgMap,
    parties: HashMap<String, Party>,
    profile: Option<String>,
}

impl TxBuilder {
    /// Adds a single argument (case-insensitive name).
    pub fn arg(mut self, name: &str, value: impl Into<Value>) -> Self {
        self.args.insert(name.to_lowercase(), value.into());
        self
    }

    /// Adds multiple arguments (case-insensitive names).
    pub fn args(mut self, args: ArgMap) -> Self {
        for (key, value) in args {
            self.args.insert(key.to_lowercase(), value);
        }
        self
    }

    /// Resolves the transaction using the TRP client.
    pub async fn resolve(self) -> Result<ResolvedTx, Error> {
        let mut invocation = self
            .protocol
            .invoke(&self.tx_name, self.profile.as_deref())?;

        let known_parties: HashSet<String> = self
            .protocol
            .parties()
            .keys()
            .map(|key| key.to_lowercase())
            .collect();

        for (name, party) in &self.parties {
            if !known_parties.contains(name) {
                return Err(Error::UnknownParty(name.clone()));
            }

            invocation.set_arg(
                name,
                serde_json::Value::String(party.address_value().to_string()),
            );
        }

        invocation.set_args(self.args);

        let mut missing: Vec<String> = invocation
            .unspecified_params()
            .map(|(key, _)| key.clone())
            .collect();

        if !missing.is_empty() {
            missing.sort();
            return Err(Error::MissingParams(missing));
        }

        let resolve_params = invocation.into_resolve_request()?;
        let envelope = self.trp.resolve(resolve_params).await?;

        let signers = self
            .parties
            .iter()
            .filter_map(|(name, party)| party.signer_party(name))
            .collect();

        Ok(ResolvedTx {
            trp: self.trp,
            hash: envelope.hash,
            tx_hex: envelope.tx,
            signers,
            manual_witnesses: Vec::new(),
        })
    }
}

/// A resolved transaction ready for signing.
pub struct ResolvedTx {
    trp: trp::Client,
    /// Transaction hash.
    pub hash: String,
    /// Hex-encoded CBOR transaction bytes.
    pub tx_hex: String,
    signers: Vec<SignerParty>,
    manual_witnesses: Vec<TxWitness>,
}

impl ResolvedTx {
    /// Returns the transaction hash that signers will sign.
    pub fn signing_hash(&self) -> &str {
        &self.hash
    }

    /// Attaches a pre-computed witness produced outside any registered `Signer`.
    ///
    /// This is the canonical entry point for wallet-app integrations: the consumer
    /// hands `txHex` (or `hash`) to an external wallet, gets back a witness, and
    /// attaches it before calling `sign()`. The witness is appended to the TRP
    /// `SubmitParams.witnesses` array after any witnesses produced by registered
    /// signer parties, in attach order. May be called any number of times.
    ///
    /// The SDK does not verify the witness against the tx hash; that binding is
    /// enforced by TRP at submit time.
    pub fn add_witness(mut self, witness: TxWitness) -> Self {
        self.manual_witnesses.push(witness);
        self
    }

    /// Signs the transaction with every signer party.
    ///
    /// Manually attached witnesses (via `add_witness`) are appended after
    /// witnesses produced by registered signer parties, in attach order.
    /// Succeeds with zero registered signers when at least one witness has
    /// been manually attached.
    pub fn sign(self) -> Result<SignedTx, Error> {
        let total = self.signers.len() + self.manual_witnesses.len();
        let mut witnesses = Vec::with_capacity(total);
        let mut witnesses_info = Vec::with_capacity(total);

        let request = SignRequest {
            tx_hash_hex: self.hash.clone(),
            tx_cbor_hex: self.tx_hex.clone(),
        };

        for signer_party in &self.signers {
            let witness = signer_party
                .signer
                .sign(&request)
                .map_err(Error::Signer)?;
            witnesses_info.push(WitnessInfo {
                party: signer_party.name.clone(),
                address: signer_party.address.clone(),
                key: witness.key.clone(),
                signature: witness.signature.clone(),
                witness_type: witness.witness_type.clone(),
                signed_hash: self.hash.clone(),
            });
            witnesses.push(witness);
        }

        for witness in self.manual_witnesses {
            witnesses_info.push(WitnessInfo {
                party: "<external>".to_string(),
                address: String::new(),
                key: witness.key.clone(),
                signature: witness.signature.clone(),
                witness_type: witness.witness_type.clone(),
                signed_hash: self.hash.clone(),
            });
            witnesses.push(witness);
        }

        let submit = SubmitParams {
            tx: BytesEnvelope {
                content: self.tx_hex,
                content_type: "hex".to_string(),
            },
            witnesses,
        };

        Ok(SignedTx {
            trp: self.trp,
            hash: self.hash,
            submit,
            witnesses_info,
        })
    }
}

/// Witness payloads for submission.
#[derive(Debug, Clone)]
pub struct WitnessInfo {
    /// Party name from the protocol.
    pub party: String,
    /// Party address used in invocation args.
    pub address: String,
    /// Public key envelope sent to the server.
    pub key: BytesEnvelope,
    /// Signature envelope sent to the server.
    pub signature: BytesEnvelope,
    /// Witness type.
    pub witness_type: trp::WitnessType,
    /// Transaction hash that was signed.
    pub signed_hash: String,
}

/// A signed transaction ready for submission.
pub struct SignedTx {
    trp: trp::Client,
    /// Resolved transaction hash.
    pub hash: String,
    /// Submit parameters including witnesses.
    pub submit: SubmitParams,
    witnesses_info: Vec<WitnessInfo>,
}

impl SignedTx {
    /// Returns witness payloads for submission.
    pub fn witnesses(&self) -> &[WitnessInfo] {
        &self.witnesses_info
    }
    /// Submits the signed transaction.
    pub async fn submit(self) -> Result<SubmittedTx, Error> {
        let response = self.trp.submit(self.submit).await?;

        if response.hash != self.hash {
            return Err(Error::SubmitHashMismatch {
                expected: self.hash,
                received: response.hash,
            });
        }

        Ok(SubmittedTx {
            trp: self.trp,
            hash: response.hash,
        })
    }
}

/// A submitted transaction that can be polled for status.
pub struct SubmittedTx {
    trp: trp::Client,
    /// Submitted transaction hash.
    pub hash: String,
}

impl SubmittedTx {
    /// Polls check-status until the transaction is confirmed or fails.
    pub async fn wait_for_confirmed(&self, config: PollConfig) -> Result<TxStatus, Error> {
        self.wait_for_stage(config, TxStage::Confirmed).await
    }

    /// Polls check-status until the transaction is finalized or fails.
    pub async fn wait_for_finalized(&self, config: PollConfig) -> Result<TxStatus, Error> {
        self.wait_for_stage(config, TxStage::Finalized).await
    }

    async fn wait_for_stage(&self, config: PollConfig, target: TxStage) -> Result<TxStatus, Error> {
        for attempt in 1..=config.attempts {
            let response = self.trp.check_status(vec![self.hash.clone()]).await?;

            if let Some(status) = response.statuses.get(&self.hash) {
                match status.stage {
                    TxStage::Finalized => return Ok(status.clone()),
                    TxStage::Confirmed if matches!(target, TxStage::Confirmed) => {
                        return Ok(status.clone())
                    }
                    TxStage::Dropped | TxStage::RolledBack => {
                        return Err(Error::FinalizedFailed {
                            hash: self.hash.clone(),
                            stage: status.stage.clone(),
                        });
                    }
                    _ => {}
                }
            }

            if attempt < config.attempts {
                tokio::time::sleep(config.delay).await;
            }
        }

        Err(Error::FinalizedTimeout {
            hash: self.hash.clone(),
            attempts: config.attempts,
            delay: config.delay,
        })
    }
}

/// Signer implementations.
pub mod signer {
    use super::{SignRequest, Signer};
    use crate::core::BytesEnvelope;
    use crate::trp::{TxWitness, WitnessType};
    use cryptoxide::hmac::Hmac;
    use cryptoxide::pbkdf2::pbkdf2;
    use cryptoxide::sha2::Sha512;
    use ed25519_bip32::{DerivationScheme, XPrv, XPRV_SIZE};
    use pallas_addresses::{Address, ShelleyPaymentPart};
    use pallas_crypto::hash::Hasher;
    use pallas_crypto::key::ed25519::{SecretKey, SecretKeyExtended, Signature};
    use thiserror::Error;

    /// Errors returned by the built-in ed25519 signer.
    #[derive(Debug, Error)]
    pub enum SignerError {
        /// Mnemonic phrase could not be parsed.
        #[error("invalid mnemonic: {0}")]
        InvalidMnemonic(bip39::Error),

        /// Private key hex could not be decoded.
        #[error("invalid private key hex: {0}")]
        InvalidPrivateKeyHex(hex::FromHexError),

        /// Private key length is not 32 bytes.
        #[error("private key must be 32 bytes, got {0}")]
        InvalidPrivateKeyLength(usize),

        /// Transaction hash hex could not be decoded.
        #[error("invalid tx hash hex: {0}")]
        InvalidHashHex(hex::FromHexError),

        /// Transaction hash length is not 32 bytes.
        #[error("transaction hash must be 32 bytes, got {0}")]
        InvalidHashLength(usize),

        /// Address could not be parsed.
        #[error("invalid address: {0}")]
        InvalidAddress(pallas_addresses::Error),

        /// Address does not contain a payment key hash.
        #[error("address does not contain a payment key hash")]
        UnsupportedPaymentCredential,

        /// Signer key doesn't match address payment key.
        #[error("signer key doesn't match address payment key")]
        AddressMismatch,
    }

    /// Built-in ed25519 signer using a 32-byte private key.
    ///
    /// The address is required at construction and returned via `Signer::address`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use tx3_sdk::Ed25519Signer;
    ///
    /// let signer = Ed25519Signer::from_hex("addr_test1...", "deadbeef...")?;
    /// # Ok::<(), tx3_sdk::Error>(())
    /// ```
    #[derive(Debug, Clone)]
    pub struct Ed25519Signer {
        address: String,
        private_key: [u8; 32],
    }

    impl Ed25519Signer {
        /// Creates a signer from a raw 32-byte private key and address.
        pub fn new(address: impl Into<String>, private_key: [u8; 32]) -> Self {
            Self {
                address: address.into(),
                private_key,
            }
        }

        /// Creates a signer from a BIP39 mnemonic phrase.
        ///
        /// The address is required and stored on the signer.
        pub fn from_mnemonic(
            address: impl Into<String>,
            phrase: &str,
        ) -> Result<Self, SignerError> {
            let mnemonic = bip39::Mnemonic::parse(phrase).map_err(SignerError::InvalidMnemonic)?;
            let seed = mnemonic.to_seed("");

            let mut key_array = [0u8; 32];
            key_array.copy_from_slice(&seed[0..32]);

            Ok(Self::new(address, key_array))
        }

        /// Creates a signer from a hex-encoded 32-byte private key.
        ///
        /// The address is required and stored on the signer.
        pub fn from_hex(
            address: impl Into<String>,
            private_key_hex: &str,
        ) -> Result<Self, SignerError> {
            let key_bytes =
                hex::decode(private_key_hex).map_err(SignerError::InvalidPrivateKeyHex)?;

            if key_bytes.len() != 32 {
                return Err(SignerError::InvalidPrivateKeyLength(key_bytes.len()));
            }

            let mut key_array = [0u8; 32];
            key_array.copy_from_slice(&key_bytes);

            Ok(Self::new(address, key_array))
        }
    }

    /// Cardano signer that derives witness key from address payment part.
    ///
    /// This signer derives keys using the Cardano path `m/1852'/1815'/0'/0/0`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use tx3_sdk::CardanoSigner;
    ///
    /// let signer = CardanoSigner::from_mnemonic(
    ///     "addr_test1...",
    ///     "word1 word2 ... word24",
    /// )?;
    /// # Ok::<(), tx3_sdk::Error>(())
    /// ```
    #[derive(Debug, Clone)]
    pub struct CardanoSigner {
        address: String,
        private_key: CardanoPrivateKey,
        payment_key_hash: Vec<u8>,
    }

    #[derive(Debug, Clone)]
    enum CardanoPrivateKey {
        Normal(SecretKey),
        Extended(SecretKeyExtended),
    }

    impl CardanoPrivateKey {
        fn public_key_bytes(&self) -> Vec<u8> {
            match self {
                CardanoPrivateKey::Normal(key) => key.public_key().as_ref().to_vec(),
                CardanoPrivateKey::Extended(key) => key.public_key().as_ref().to_vec(),
            }
        }

        fn sign(&self, msg: &[u8]) -> Signature {
            match self {
                CardanoPrivateKey::Normal(key) => key.sign(msg),
                CardanoPrivateKey::Extended(key) => key.sign(msg),
            }
        }
    }

    impl CardanoSigner {
        /// Creates a Cardano signer from a raw private key and address.
        fn new(
            private_key: CardanoPrivateKey,
            address: impl Into<String>,
        ) -> Result<Self, SignerError> {
            let address = address.into();
            let payment_key_hash = extract_payment_key_hash(&address)?;
            Ok(Self {
                address,
                private_key,
                payment_key_hash,
            })
        }

        /// Creates a Cardano signer from a hex-encoded private key and address.
        pub fn from_hex(
            address: impl Into<String>,
            private_key_hex: &str,
        ) -> Result<Self, SignerError> {
            let key_bytes =
                hex::decode(private_key_hex).map_err(SignerError::InvalidPrivateKeyHex)?;

            if key_bytes.len() != 32 {
                return Err(SignerError::InvalidPrivateKeyLength(key_bytes.len()));
            }

            let mut key_array = [0u8; 32];
            key_array.copy_from_slice(&key_bytes);

            let key: SecretKey = key_array.into();

            Self::new(CardanoPrivateKey::Normal(key), address)
        }

        /// Creates a Cardano signer from a mnemonic phrase and address.
        pub fn from_mnemonic(
            address: impl Into<String>,
            phrase: &str,
        ) -> Result<Self, SignerError> {
            let root = derive_root_xprv(phrase, "")?;
            let payment = derive_cardano_payment_xprv(&root);
            let key =
                unsafe { SecretKeyExtended::from_bytes_unchecked(payment.extended_secret_key()) };

            Self::new(CardanoPrivateKey::Extended(key), address)
        }

        fn verify_address_binding(&self, public_key_bytes: &[u8]) -> Result<(), SignerError> {
            let mut hasher = Hasher::<224>::new();
            hasher.input(public_key_bytes);
            let digest = hasher.finalize();

            if digest.as_ref() != self.payment_key_hash.as_slice() {
                return Err(SignerError::AddressMismatch);
            }

            Ok(())
        }
    }

    impl Signer for CardanoSigner {
        fn address(&self) -> &str {
            &self.address
        }

        fn sign(
            &self,
            request: &SignRequest,
        ) -> Result<TxWitness, Box<dyn std::error::Error + Send + Sync>> {
            let hash_bytes = hex::decode(&request.tx_hash_hex).map_err(|err| {
                Box::new(SignerError::InvalidHashHex(err))
                    as Box<dyn std::error::Error + Send + Sync>
            })?;

            if hash_bytes.len() != 32 {
                return Err(Box::new(SignerError::InvalidHashLength(hash_bytes.len())));
            }

            let public_key_bytes = self.private_key.public_key_bytes();

            let _ = self.verify_address_binding(&public_key_bytes);

            let signature = self.private_key.sign(&hash_bytes);

            Ok(TxWitness {
                key: BytesEnvelope {
                    content: hex::encode(&public_key_bytes),
                    content_type: "hex".to_string(),
                },
                signature: BytesEnvelope {
                    content: hex::encode(signature.as_ref()),
                    content_type: "hex".to_string(),
                },
                witness_type: WitnessType::VKey,
            })
        }
    }

    fn derive_root_xprv(phrase: &str, password: &str) -> Result<XPrv, SignerError> {
        let mnemonic = bip39::Mnemonic::parse(phrase).map_err(SignerError::InvalidMnemonic)?;
        let entropy = mnemonic.to_entropy();

        let mut pbkdf2_result = [0u8; XPRV_SIZE];

        const ITER: u32 = 4096;

        let mut mac = Hmac::new(Sha512::new(), password.as_bytes());
        pbkdf2(&mut mac, &entropy, ITER, &mut pbkdf2_result);

        Ok(XPrv::normalize_bytes_force3rd(pbkdf2_result))
    }

    fn derive_cardano_payment_xprv(root: &XPrv) -> XPrv {
        const HARDENED: u32 = 0x8000_0000;

        root.derive(DerivationScheme::V2, 1852 | HARDENED)
            .derive(DerivationScheme::V2, 1815 | HARDENED)
            .derive(DerivationScheme::V2, HARDENED)
            .derive(DerivationScheme::V2, 0)
            .derive(DerivationScheme::V2, 0)
    }

    fn extract_payment_key_hash(address: &str) -> Result<Vec<u8>, SignerError> {
        let parsed = Address::from_bech32(address).map_err(SignerError::InvalidAddress)?;

        let payment = match parsed {
            Address::Shelley(addr) => addr.payment().clone(),
            _ => return Err(SignerError::UnsupportedPaymentCredential),
        };

        match payment {
            ShelleyPaymentPart::Key(hash) => Ok(hash.as_ref().to_vec()),
            ShelleyPaymentPart::Script(_) => Err(SignerError::UnsupportedPaymentCredential),
        }
    }

    impl Signer for Ed25519Signer {
        fn address(&self) -> &str {
            &self.address
        }

        fn sign(
            &self,
            request: &SignRequest,
        ) -> Result<TxWitness, Box<dyn std::error::Error + Send + Sync>> {
            let hash_bytes = hex::decode(&request.tx_hash_hex).map_err(|err| {
                Box::new(SignerError::InvalidHashHex(err))
                    as Box<dyn std::error::Error + Send + Sync>
            })?;

            if hash_bytes.len() != 32 {
                return Err(Box::new(SignerError::InvalidHashLength(hash_bytes.len())));
            }

            let signing_key: SecretKey = self.private_key.into();
            let public_key = signing_key.public_key();
            let signature = signing_key.sign(&hash_bytes);

            Ok(TxWitness {
                key: BytesEnvelope {
                    content: hex::encode(public_key.as_ref()),
                    content_type: "hex".to_string(),
                },
                signature: BytesEnvelope {
                    content: hex::encode(signature.as_ref()),
                    content_type: "hex".to_string(),
                },
                witness_type: WitnessType::VKey,
            })
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::trp::{ClientOptions, WitnessType};

    fn stub_trp() -> trp::Client {
        trp::Client::new(ClientOptions {
            endpoint: "http://localhost:0/unused".to_string(),
            headers: None,
        })
    }

    fn fake_witness(key_hex: &str, sig_hex: &str) -> TxWitness {
        TxWitness {
            key: BytesEnvelope {
                content: key_hex.to_string(),
                content_type: "hex".to_string(),
            },
            signature: BytesEnvelope {
                content: sig_hex.to_string(),
                content_type: "hex".to_string(),
            },
            witness_type: WitnessType::VKey,
        }
    }

    fn empty_resolved() -> ResolvedTx {
        ResolvedTx {
            trp: stub_trp(),
            hash: "deadbeef".to_string(),
            tx_hex: "84a40081".to_string(),
            signers: Vec::new(),
            manual_witnesses: Vec::new(),
        }
    }

    struct StubSigner {
        address: String,
        witness: TxWitness,
    }

    impl Signer for StubSigner {
        fn address(&self) -> &str {
            &self.address
        }

        fn sign(
            &self,
            _request: &SignRequest,
        ) -> Result<TxWitness, Box<dyn std::error::Error + Send + Sync>> {
            Ok(self.witness.clone())
        }
    }

    #[test]
    fn add_witness_only_no_signers() {
        let witness = fake_witness("aa", "bb");
        let signed = empty_resolved()
            .add_witness(witness.clone())
            .sign()
            .expect("sign with manual witness only must succeed");

        assert_eq!(signed.submit.witnesses.len(), 1);
        assert_eq!(signed.submit.witnesses[0].key.content, witness.key.content);
        assert_eq!(
            signed.submit.witnesses[0].signature.content,
            witness.signature.content
        );
    }

    #[test]
    fn add_witness_mixed_with_registered_signer() {
        let registered_witness = fake_witness("11", "22");
        let manual_witness = fake_witness("aa", "bb");

        let stub = StubSigner {
            address: "addr_test1...".to_string(),
            witness: registered_witness.clone(),
        };

        let resolved = ResolvedTx {
            trp: stub_trp(),
            hash: "deadbeef".to_string(),
            tx_hex: "84a40081".to_string(),
            signers: vec![SignerParty {
                name: "sender".to_string(),
                address: stub.address.clone(),
                signer: Arc::new(stub),
            }],
            manual_witnesses: Vec::new(),
        };

        let signed = resolved
            .add_witness(manual_witness.clone())
            .sign()
            .expect("sign with mixed witnesses must succeed");

        assert_eq!(signed.submit.witnesses.len(), 2);
        assert_eq!(signed.submit.witnesses[0].key.content, "11");
        assert_eq!(signed.submit.witnesses[1].key.content, "aa");
    }

    #[test]
    fn add_witness_preserves_attach_order() {
        let signed = empty_resolved()
            .add_witness(fake_witness("01", "10"))
            .add_witness(fake_witness("02", "20"))
            .add_witness(fake_witness("03", "30"))
            .sign()
            .expect("sign must succeed");

        let keys: Vec<&str> = signed
            .submit
            .witnesses
            .iter()
            .map(|w| w.key.content.as_str())
            .collect();
        assert_eq!(keys, vec!["01", "02", "03"]);
    }
}