aptos-sdk 0.4.1

A user-friendly, idiomatic Rust SDK for the Aptos blockchain
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
//! `MultiKey` account implementation.
//!
//! This module provides the [`MultiKeyAccount`] type for M-of-N
//! threshold signature accounts with mixed key types.

use crate::account::account::{Account, AuthenticationKey};
use crate::crypto::{
    AnyPublicKey, AnyPublicKeyVariant, AnySignature, MULTI_KEY_SCHEME, MultiKeyPublicKey,
    MultiKeySignature,
};
use crate::error::{AptosError, AptosResult};
use crate::types::AccountAddress;
use std::fmt;

/// A private key that can be any supported signature scheme.
pub enum AnyPrivateKey {
    /// Ed25519 private key.
    #[cfg(feature = "ed25519")]
    Ed25519(crate::crypto::Ed25519PrivateKey),
    /// Secp256k1 private key.
    #[cfg(feature = "secp256k1")]
    Secp256k1(crate::crypto::Secp256k1PrivateKey),
    /// Secp256r1 private key.
    #[cfg(feature = "secp256r1")]
    Secp256r1(crate::crypto::Secp256r1PrivateKey),
}

impl AnyPrivateKey {
    /// Gets the signature scheme variant.
    #[allow(unreachable_code)]
    pub fn variant(&self) -> AnyPublicKeyVariant {
        match self {
            #[cfg(feature = "ed25519")]
            Self::Ed25519(_) => AnyPublicKeyVariant::Ed25519,
            #[cfg(feature = "secp256k1")]
            Self::Secp256k1(_) => AnyPublicKeyVariant::Secp256k1,
            #[cfg(feature = "secp256r1")]
            Self::Secp256r1(_) => AnyPublicKeyVariant::Secp256r1,
            #[allow(unreachable_patterns)]
            _ => unreachable!("AnyPrivateKey requires at least one crypto feature to be enabled"),
        }
    }

    /// Gets the public key.
    #[allow(unreachable_code)]
    pub fn public_key(&self) -> AnyPublicKey {
        match self {
            #[cfg(feature = "ed25519")]
            Self::Ed25519(key) => AnyPublicKey::ed25519(&key.public_key()),
            #[cfg(feature = "secp256k1")]
            Self::Secp256k1(key) => AnyPublicKey::secp256k1(&key.public_key()),
            #[cfg(feature = "secp256r1")]
            Self::Secp256r1(key) => AnyPublicKey::secp256r1(&key.public_key()),
            #[allow(unreachable_patterns)]
            _ => unreachable!("AnyPrivateKey requires at least one crypto feature to be enabled"),
        }
    }

    /// Signs a message.
    #[allow(unreachable_code, unused_variables)]
    pub fn sign(&self, message: &[u8]) -> AnySignature {
        match self {
            #[cfg(feature = "ed25519")]
            Self::Ed25519(key) => AnySignature::ed25519(&key.sign(message)),
            #[cfg(feature = "secp256k1")]
            Self::Secp256k1(key) => AnySignature::secp256k1(&key.sign(message)),
            #[cfg(feature = "secp256r1")]
            Self::Secp256r1(key) => AnySignature::secp256r1(&key.sign(message)),
            #[allow(unreachable_patterns)]
            _ => unreachable!("AnyPrivateKey requires at least one crypto feature to be enabled"),
        }
    }

    /// Creates an Ed25519 private key.
    #[cfg(feature = "ed25519")]
    pub fn ed25519(key: crate::crypto::Ed25519PrivateKey) -> Self {
        Self::Ed25519(key)
    }

    /// Creates a Secp256k1 private key.
    #[cfg(feature = "secp256k1")]
    pub fn secp256k1(key: crate::crypto::Secp256k1PrivateKey) -> Self {
        Self::Secp256k1(key)
    }

    /// Creates a Secp256r1 private key.
    #[cfg(feature = "secp256r1")]
    pub fn secp256r1(key: crate::crypto::Secp256r1PrivateKey) -> Self {
        Self::Secp256r1(key)
    }
}

impl Clone for AnyPrivateKey {
    #[allow(unreachable_code)]
    fn clone(&self) -> Self {
        match self {
            #[cfg(feature = "ed25519")]
            Self::Ed25519(key) => Self::Ed25519(key.clone()),
            #[cfg(feature = "secp256k1")]
            Self::Secp256k1(key) => Self::Secp256k1(key.clone()),
            #[cfg(feature = "secp256r1")]
            Self::Secp256r1(key) => Self::Secp256r1(key.clone()),
            #[allow(unreachable_patterns)]
            _ => unreachable!("AnyPrivateKey requires at least one crypto feature to be enabled"),
        }
    }
}

impl fmt::Debug for AnyPrivateKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "AnyPrivateKey({:?})", self.variant())
    }
}

/// A multi-key account supporting M-of-N threshold signatures with mixed key types.
///
/// Unlike `MultiEd25519Account`, this account type supports mixed signature
/// schemes (e.g., 2-of-3 where one key is Ed25519 and two are Secp256k1).
///
/// # Example
///
/// ```rust,ignore
/// use aptos_sdk::account::{MultiKeyAccount, AnyPrivateKey};
/// use aptos_sdk::crypto::{Ed25519PrivateKey, Secp256k1PrivateKey};
///
/// // Create a 2-of-3 multisig with mixed key types
/// let keys = vec![
///     AnyPrivateKey::ed25519(Ed25519PrivateKey::generate()),
///     AnyPrivateKey::secp256k1(Secp256k1PrivateKey::generate()),
///     AnyPrivateKey::ed25519(Ed25519PrivateKey::generate()),
/// ];
/// let account = MultiKeyAccount::new(keys, 2).unwrap();
///
/// println!("Address: {}", account.address());
/// println!("Threshold: {}/{}", account.threshold(), account.num_keys());
/// ```
pub struct MultiKeyAccount {
    /// The private keys owned by this account (may be a subset).
    private_keys: Vec<(u8, AnyPrivateKey)>,
    /// The multi-key public key (contains all public keys).
    public_key: MultiKeyPublicKey,
    /// The derived account address.
    address: AccountAddress,
}

impl MultiKeyAccount {
    /// Creates a new multi-key account from private keys.
    ///
    /// All provided private keys will be used for signing. The threshold
    /// specifies how many signatures are required.
    ///
    /// # Arguments
    ///
    /// * `private_keys` - The private keys (can be mixed types)
    /// * `threshold` - The required number of signatures (M in M-of-N)
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - No private keys are provided
    /// - The threshold exceeds the number of keys
    /// - The multi-key public key creation fails (e.g., too many keys, invalid threshold)
    pub fn new(private_keys: Vec<AnyPrivateKey>, threshold: u8) -> AptosResult<Self> {
        if private_keys.is_empty() {
            return Err(AptosError::InvalidPrivateKey(
                "at least one private key is required".into(),
            ));
        }
        if (threshold as usize) > private_keys.len() {
            return Err(AptosError::InvalidPrivateKey(format!(
                "threshold {} exceeds number of keys {}",
                threshold,
                private_keys.len()
            )));
        }

        let public_keys: Vec<_> = private_keys.iter().map(AnyPrivateKey::public_key).collect();
        let multi_public_key = MultiKeyPublicKey::new(public_keys, threshold)?;
        let address = multi_public_key.to_address();

        // Index the private keys (safe: validated by MultiKeyPublicKey::new above)
        #[allow(clippy::cast_possible_truncation)]
        let indexed_keys: Vec<_> = private_keys
            .into_iter()
            .enumerate()
            .map(|(i, k)| (i as u8, k))
            .collect();

        Ok(Self {
            private_keys: indexed_keys,
            public_key: multi_public_key,
            address,
        })
    }

    /// Creates a multi-key account from public keys with a subset of private keys.
    ///
    /// Use this when you don't have all the private keys.
    ///
    /// # Arguments
    ///
    /// * `public_keys` - All the public keys in the account
    /// * `private_keys` - The private keys you own, with their indices
    /// * `threshold` - The required number of signatures
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The multi-key public key creation fails
    /// - A private key index is out of bounds
    /// - A private key doesn't match the public key at its index (wrong type or bytes)
    pub fn from_keys(
        public_keys: Vec<AnyPublicKey>,
        private_keys: Vec<(u8, AnyPrivateKey)>,
        threshold: u8,
    ) -> AptosResult<Self> {
        let multi_public_key = MultiKeyPublicKey::new(public_keys, threshold)?;

        // Validate private key indices and types
        for (index, key) in &private_keys {
            if *index as usize >= multi_public_key.num_keys() {
                return Err(AptosError::InvalidPrivateKey(format!(
                    "private key index {index} out of bounds"
                )));
            }

            // Verify the private key matches the public key at that index
            let Some(expected_pk) = multi_public_key.get(*index as usize) else {
                return Err(AptosError::InvalidPrivateKey(format!(
                    "private key index {index} out of bounds"
                )));
            };

            let actual_pk = key.public_key();
            if expected_pk.variant != actual_pk.variant || expected_pk.bytes != actual_pk.bytes {
                return Err(AptosError::InvalidPrivateKey(format!(
                    "private key at index {index} doesn't match public key"
                )));
            }
        }

        let address = multi_public_key.to_address();

        Ok(Self {
            private_keys,
            public_key: multi_public_key,
            address,
        })
    }

    /// Creates a view-only multi-key account (no signing capability).
    ///
    /// # Errors
    ///
    /// Returns an error if the multi-key public key creation fails (e.g., no keys provided, too many keys, invalid threshold).
    pub fn view_only(public_keys: Vec<AnyPublicKey>, threshold: u8) -> AptosResult<Self> {
        let multi_public_key = MultiKeyPublicKey::new(public_keys, threshold)?;
        let address = multi_public_key.to_address();

        Ok(Self {
            private_keys: vec![],
            public_key: multi_public_key,
            address,
        })
    }

    /// Returns the account address.
    pub fn address(&self) -> AccountAddress {
        self.address
    }

    /// Returns the multi-key public key.
    pub fn public_key(&self) -> &MultiKeyPublicKey {
        &self.public_key
    }

    /// Returns the number of keys in the account.
    pub fn num_keys(&self) -> usize {
        self.public_key.num_keys()
    }

    /// Returns the signature threshold.
    pub fn threshold(&self) -> u8 {
        self.public_key.threshold()
    }

    /// Returns the number of private keys we have.
    pub fn num_owned_keys(&self) -> usize {
        self.private_keys.len()
    }

    /// Checks if we can sign (have enough private keys to meet threshold).
    pub fn can_sign(&self) -> bool {
        self.private_keys.len() >= self.threshold() as usize
    }

    /// Returns the indices of the private keys we own.
    pub fn owned_key_indices(&self) -> Vec<u8> {
        self.private_keys.iter().map(|(i, _)| *i).collect()
    }

    /// Returns the key types for each index.
    pub fn key_types(&self) -> Vec<AnyPublicKeyVariant> {
        self.public_key
            .public_keys()
            .iter()
            .map(|pk| pk.variant)
            .collect()
    }

    /// Signs a message using the owned private keys.
    ///
    /// Will use up to `threshold` keys for signing.
    ///
    /// # Errors
    ///
    /// Returns an error if we don't have enough private keys to meet the threshold.
    pub fn sign_message(&self, message: &[u8]) -> AptosResult<MultiKeySignature> {
        let threshold = self.threshold() as usize;
        if self.private_keys.len() < threshold {
            return Err(AptosError::InsufficientSignatures {
                required: threshold,
                provided: self.private_keys.len(),
            });
        }

        // Sign with the first `threshold` keys
        let signatures: Vec<_> = self.private_keys[..threshold]
            .iter()
            .map(|(index, key)| (*index, key.sign(message)))
            .collect();

        MultiKeySignature::new(signatures)
    }

    /// Signs a message using specific key indices.
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - Not enough indices are provided to meet the threshold
    /// - We don't own a private key at one of the specified indices
    pub fn sign_with_indices(
        &self,
        message: &[u8],
        indices: &[u8],
    ) -> AptosResult<MultiKeySignature> {
        if indices.len() < self.threshold() as usize {
            return Err(AptosError::InsufficientSignatures {
                required: self.threshold() as usize,
                provided: indices.len(),
            });
        }

        let mut signatures = Vec::with_capacity(indices.len());

        for &index in indices {
            let key = self
                .private_keys
                .iter()
                .find(|(i, _)| *i == index)
                .ok_or_else(|| {
                    AptosError::InvalidPrivateKey(format!(
                        "don't have private key at index {index}"
                    ))
                })?;

            signatures.push((index, key.1.sign(message)));
        }

        MultiKeySignature::new(signatures)
    }

    /// Verifies a signature against a message.
    ///
    /// # Errors
    ///
    /// Returns an error if signature verification fails (e.g., invalid signature, insufficient signatures, signature mismatch).
    pub fn verify(&self, message: &[u8], signature: &MultiKeySignature) -> AptosResult<()> {
        self.public_key.verify(message, signature)
    }

    /// Returns the authentication key for this account.
    pub fn auth_key(&self) -> AuthenticationKey {
        AuthenticationKey::new(self.public_key.to_authentication_key())
    }

    /// Collects individual signatures into a multi-key signature.
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - No signatures are provided
    /// - Too many signatures are provided (more than 32)
    /// - Signer indices are out of bounds or duplicated
    pub fn aggregate_signatures(
        signatures: Vec<(u8, AnySignature)>,
    ) -> AptosResult<MultiKeySignature> {
        MultiKeySignature::new(signatures)
    }

    /// Creates an individual signature contribution.
    ///
    /// # Errors
    ///
    /// Returns an error if we don't have a private key at the specified index.
    pub fn create_signature_contribution(
        &self,
        message: &[u8],
        key_index: u8,
    ) -> AptosResult<(u8, AnySignature)> {
        let key = self
            .private_keys
            .iter()
            .find(|(i, _)| *i == key_index)
            .ok_or_else(|| {
                AptosError::InvalidPrivateKey(format!(
                    "don't have private key at index {key_index}"
                ))
            })?;

        Ok((key_index, key.1.sign(message)))
    }
}

impl Account for MultiKeyAccount {
    fn address(&self) -> AccountAddress {
        self.address
    }

    fn public_key_bytes(&self) -> Vec<u8> {
        self.public_key.to_bytes()
    }

    fn sign(&self, message: &[u8]) -> AptosResult<Vec<u8>> {
        let sig = self.sign_message(message)?;
        Ok(sig.to_bytes())
    }

    fn authentication_key(&self) -> AuthenticationKey {
        self.auth_key()
    }

    fn signature_scheme(&self) -> u8 {
        MULTI_KEY_SCHEME
    }
}

impl fmt::Debug for MultiKeyAccount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // SECURITY: Intentionally omit private_keys to prevent secret leakage
        // in logs, panic messages, or debug output
        f.debug_struct("MultiKeyAccount")
            .field("address", &self.address)
            .field(
                "keys",
                &format!(
                    "{}-of-{} (own {})",
                    self.threshold(),
                    self.num_keys(),
                    self.num_owned_keys()
                ),
            )
            .field("types", &self.key_types())
            .field("public_key", &self.public_key)
            .field("private_keys", &"[REDACTED]")
            .finish()
    }
}

impl fmt::Display for MultiKeyAccount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "MultiKeyAccount({}, {}-of-{})",
            self.address.to_short_string(),
            self.threshold(),
            self.num_keys()
        )
    }
}

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

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_create_ed25519_only() {
        use crate::crypto::Ed25519PrivateKey;

        let keys: Vec<_> = (0..3)
            .map(|_| AnyPrivateKey::ed25519(Ed25519PrivateKey::generate()))
            .collect();
        let account = MultiKeyAccount::new(keys, 2).unwrap();

        assert_eq!(account.num_keys(), 3);
        assert_eq!(account.threshold(), 2);
        assert_eq!(account.num_owned_keys(), 3);
        assert!(account.can_sign());

        // All keys should be Ed25519
        for variant in account.key_types() {
            assert_eq!(variant, AnyPublicKeyVariant::Ed25519);
        }
    }

    #[test]
    #[cfg(all(feature = "ed25519", feature = "secp256k1"))]
    fn test_create_mixed_types() {
        use crate::crypto::{Ed25519PrivateKey, Secp256k1PrivateKey};

        let keys = vec![
            AnyPrivateKey::ed25519(Ed25519PrivateKey::generate()),
            AnyPrivateKey::secp256k1(Secp256k1PrivateKey::generate()),
            AnyPrivateKey::ed25519(Ed25519PrivateKey::generate()),
        ];
        let account = MultiKeyAccount::new(keys, 2).unwrap();

        assert_eq!(account.num_keys(), 3);
        let types = account.key_types();
        assert_eq!(types[0], AnyPublicKeyVariant::Ed25519);
        assert_eq!(types[1], AnyPublicKeyVariant::Secp256k1);
        assert_eq!(types[2], AnyPublicKeyVariant::Ed25519);
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_sign_and_verify() {
        use crate::crypto::Ed25519PrivateKey;

        let keys: Vec<_> = (0..3)
            .map(|_| AnyPrivateKey::ed25519(Ed25519PrivateKey::generate()))
            .collect();
        let account = MultiKeyAccount::new(keys, 2).unwrap();

        let message = b"test message";
        let signature = account.sign_message(message).unwrap();

        assert!(account.verify(message, &signature).is_ok());
        assert!(account.verify(b"wrong message", &signature).is_err());
    }

    #[test]
    #[cfg(all(feature = "ed25519", feature = "secp256k1"))]
    fn test_sign_mixed_types() {
        use crate::crypto::{Ed25519PrivateKey, Secp256k1PrivateKey};

        let keys = vec![
            AnyPrivateKey::ed25519(Ed25519PrivateKey::generate()),
            AnyPrivateKey::secp256k1(Secp256k1PrivateKey::generate()),
            AnyPrivateKey::ed25519(Ed25519PrivateKey::generate()),
        ];
        let account = MultiKeyAccount::new(keys, 2).unwrap();

        let message = b"test message";
        let signature = account.sign_message(message).unwrap();

        assert!(account.verify(message, &signature).is_ok());
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_partial_keys() {
        use crate::crypto::Ed25519PrivateKey;

        let all_keys: Vec<_> = (0..3).map(|_| Ed25519PrivateKey::generate()).collect();
        let public_keys: Vec<_> = all_keys
            .iter()
            .map(|k| AnyPublicKey::ed25519(&k.public_key()))
            .collect();

        // Only own keys 0 and 2
        let my_keys = vec![
            (0u8, AnyPrivateKey::ed25519(all_keys[0].clone())),
            (2u8, AnyPrivateKey::ed25519(all_keys[2].clone())),
        ];

        let account = MultiKeyAccount::from_keys(public_keys, my_keys, 2).unwrap();

        assert_eq!(account.num_keys(), 3);
        assert_eq!(account.num_owned_keys(), 2);
        assert!(account.can_sign());

        // Should be able to sign
        let message = b"test";
        let signature = account.sign_message(message).unwrap();
        assert!(account.verify(message, &signature).is_ok());
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_insufficient_keys() {
        use crate::crypto::Ed25519PrivateKey;

        let all_keys: Vec<_> = (0..3).map(|_| Ed25519PrivateKey::generate()).collect();
        let public_keys: Vec<_> = all_keys
            .iter()
            .map(|k| AnyPublicKey::ed25519(&k.public_key()))
            .collect();

        // Only own 1 key but need 2
        let my_keys = vec![(0u8, AnyPrivateKey::ed25519(all_keys[0].clone()))];

        let account = MultiKeyAccount::from_keys(public_keys, my_keys, 2).unwrap();

        assert!(!account.can_sign());
        assert!(account.sign_message(b"test").is_err());
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_view_only() {
        use crate::crypto::Ed25519PrivateKey;

        let keys: Vec<_> = (0..3).map(|_| Ed25519PrivateKey::generate()).collect();
        let public_keys: Vec<_> = keys
            .iter()
            .map(|k| AnyPublicKey::ed25519(&k.public_key()))
            .collect();

        let view_only = MultiKeyAccount::view_only(public_keys, 2).unwrap();

        assert_eq!(view_only.num_keys(), 3);
        assert_eq!(view_only.num_owned_keys(), 0);
        assert!(!view_only.can_sign());
        assert!(view_only.sign_message(b"test").is_err());
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_deterministic_address() {
        use crate::crypto::Ed25519PrivateKey;

        let keys: Vec<_> = (0..3).map(|_| Ed25519PrivateKey::generate()).collect();
        let public_keys: Vec<_> = keys
            .iter()
            .map(|k| AnyPublicKey::ed25519(&k.public_key()))
            .collect();

        let account1 = MultiKeyAccount::new(
            keys.iter()
                .map(|k| AnyPrivateKey::ed25519(k.clone()))
                .collect(),
            2,
        )
        .unwrap();
        let account2 = MultiKeyAccount::view_only(public_keys, 2).unwrap();

        // Same public keys should produce same address
        assert_eq!(account1.address(), account2.address());
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_any_private_key_variant() {
        use crate::crypto::Ed25519PrivateKey;

        let key = AnyPrivateKey::ed25519(Ed25519PrivateKey::generate());
        assert_eq!(key.variant(), AnyPublicKeyVariant::Ed25519);
    }

    #[test]
    #[cfg(feature = "secp256k1")]
    fn test_any_private_key_secp256k1() {
        use crate::crypto::Secp256k1PrivateKey;

        let key = AnyPrivateKey::secp256k1(Secp256k1PrivateKey::generate());
        assert_eq!(key.variant(), AnyPublicKeyVariant::Secp256k1);

        // Test public key extraction
        let pk = key.public_key();
        assert_eq!(pk.variant, AnyPublicKeyVariant::Secp256k1);

        // Test signing - just verify it doesn't panic
        let _sig = key.sign(b"test message");
    }

    #[test]
    #[cfg(feature = "secp256r1")]
    fn test_any_private_key_secp256r1() {
        use crate::crypto::Secp256r1PrivateKey;

        let key = AnyPrivateKey::secp256r1(Secp256r1PrivateKey::generate());
        assert_eq!(key.variant(), AnyPublicKeyVariant::Secp256r1);

        // Test public key extraction
        let pk = key.public_key();
        assert_eq!(pk.variant, AnyPublicKeyVariant::Secp256r1);

        // Test signing - just verify it doesn't panic
        let _sig = key.sign(b"test message");
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_any_private_key_clone() {
        use crate::crypto::Ed25519PrivateKey;

        let key = AnyPrivateKey::ed25519(Ed25519PrivateKey::generate());
        let cloned = key.clone();
        assert_eq!(key.variant(), cloned.variant());
        // Both should produce same public key
        assert_eq!(
            key.public_key().to_bcs_bytes(),
            cloned.public_key().to_bcs_bytes()
        );
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_any_private_key_debug() {
        use crate::crypto::Ed25519PrivateKey;

        let key = AnyPrivateKey::ed25519(Ed25519PrivateKey::generate());
        let debug = format!("{key:?}");
        assert!(debug.contains("AnyPrivateKey"));
        assert!(debug.contains("Ed25519"));
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_multi_key_account_empty_keys() {
        let result = MultiKeyAccount::new(vec![], 1);
        assert!(result.is_err());
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_multi_key_account_threshold_zero() {
        use crate::crypto::Ed25519PrivateKey;

        let keys: Vec<_> = (0..2)
            .map(|_| AnyPrivateKey::ed25519(Ed25519PrivateKey::generate()))
            .collect();
        let result = MultiKeyAccount::new(keys, 0);
        assert!(result.is_err());
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_multi_key_account_threshold_exceeds_keys() {
        use crate::crypto::Ed25519PrivateKey;

        let keys: Vec<_> = (0..2)
            .map(|_| AnyPrivateKey::ed25519(Ed25519PrivateKey::generate()))
            .collect();
        let result = MultiKeyAccount::new(keys, 5);
        assert!(result.is_err());
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_from_keys_invalid_index() {
        use crate::crypto::Ed25519PrivateKey;

        let keys: Vec<_> = (0..3).map(|_| Ed25519PrivateKey::generate()).collect();
        let public_keys: Vec<_> = keys
            .iter()
            .map(|k| AnyPublicKey::ed25519(&k.public_key()))
            .collect();

        // Index 10 is out of bounds (only 3 keys)
        let my_keys = vec![(10u8, AnyPrivateKey::ed25519(keys[0].clone()))];

        let result = MultiKeyAccount::from_keys(public_keys, my_keys, 1);
        assert!(result.is_err());
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_from_keys_mismatched_public_key() {
        use crate::crypto::Ed25519PrivateKey;

        let keys: Vec<_> = (0..3).map(|_| Ed25519PrivateKey::generate()).collect();
        let public_keys: Vec<_> = keys
            .iter()
            .map(|k| AnyPublicKey::ed25519(&k.public_key()))
            .collect();

        // Provide a different private key at index 0
        let different_key = Ed25519PrivateKey::generate();
        let my_keys = vec![(0u8, AnyPrivateKey::ed25519(different_key))];

        let result = MultiKeyAccount::from_keys(public_keys, my_keys, 1);
        assert!(result.is_err());
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_multi_key_account_public_key() {
        use crate::crypto::Ed25519PrivateKey;

        let keys: Vec<_> = (0..2)
            .map(|_| AnyPrivateKey::ed25519(Ed25519PrivateKey::generate()))
            .collect();
        let account = MultiKeyAccount::new(keys, 2).unwrap();
        let pk = account.public_key();
        assert_eq!(pk.num_keys(), 2);
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_multi_key_account_address_not_zero() {
        use crate::crypto::Ed25519PrivateKey;

        let keys: Vec<_> = (0..2)
            .map(|_| AnyPrivateKey::ed25519(Ed25519PrivateKey::generate()))
            .collect();
        let account = MultiKeyAccount::new(keys, 2).unwrap();
        assert!(!account.address().is_zero());
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_multi_key_account_display() {
        use crate::crypto::Ed25519PrivateKey;

        let keys: Vec<_> = (0..2)
            .map(|_| AnyPrivateKey::ed25519(Ed25519PrivateKey::generate()))
            .collect();
        let account = MultiKeyAccount::new(keys, 2).unwrap();
        let display = format!("{account}");
        // Display contains the address which starts with 0x
        assert!(display.contains("0x") || display.contains("MultiKeyAccount"));
    }

    #[test]
    #[cfg(feature = "ed25519")]
    fn test_multi_key_account_debug() {
        use crate::crypto::Ed25519PrivateKey;

        let keys: Vec<_> = (0..2)
            .map(|_| AnyPrivateKey::ed25519(Ed25519PrivateKey::generate()))
            .collect();
        let account = MultiKeyAccount::new(keys, 2).unwrap();
        let debug = format!("{account:?}");
        assert!(debug.contains("MultiKeyAccount"));
    }
}