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
//! Account trait and common types.

use crate::error::AptosResult;
use crate::types::AccountAddress;
use serde::{Deserialize, Serialize};
use std::fmt;

/// An authentication key used to verify account ownership.
///
/// The authentication key is derived from the public key and can be
/// rotated to support key rotation.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct AuthenticationKey([u8; 32]);

impl AuthenticationKey {
    /// Creates an authentication key from bytes.
    pub fn new(bytes: [u8; 32]) -> Self {
        Self(bytes)
    }

    /// Creates an authentication key from a byte slice.
    ///
    /// # Errors
    ///
    /// Returns an error if the byte slice length is not exactly 32 bytes.
    pub fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
        if bytes.len() != 32 {
            return Err(crate::error::AptosError::InvalidAddress(format!(
                "authentication key must be 32 bytes, got {}",
                bytes.len()
            )));
        }
        let mut key = [0u8; 32];
        key.copy_from_slice(bytes);
        Ok(Self(key))
    }

    /// Creates an authentication key from a hex string.
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The hex string is invalid or cannot be decoded
    /// - The decoded bytes are not exactly 32 bytes long
    pub fn from_hex(hex_str: &str) -> AptosResult<Self> {
        let bytes = const_hex::decode(hex_str)?;
        Self::from_bytes(&bytes)
    }

    /// Returns the authentication key as bytes.
    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    /// Returns the authentication key as a byte array.
    pub fn to_bytes(&self) -> [u8; 32] {
        self.0
    }

    /// Returns the authentication key as a hex string.
    pub fn to_hex(&self) -> String {
        const_hex::encode_prefixed(self.0)
    }

    /// Derives the account address from this authentication key.
    ///
    /// For most accounts, the address equals the authentication key.
    pub fn to_address(&self) -> AccountAddress {
        AccountAddress::new(self.0)
    }
}

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

impl fmt::Display for AuthenticationKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_hex())
    }
}

impl From<[u8; 32]> for AuthenticationKey {
    fn from(bytes: [u8; 32]) -> Self {
        Self(bytes)
    }
}

impl From<AuthenticationKey> for [u8; 32] {
    fn from(key: AuthenticationKey) -> Self {
        key.0
    }
}

impl From<AuthenticationKey> for AccountAddress {
    fn from(key: AuthenticationKey) -> Self {
        key.to_address()
    }
}

/// Trait for account types that can sign transactions.
///
/// This trait provides a common interface for different account types
/// (Ed25519, Secp256k1, multi-sig, keyless, etc.).
pub trait Account: Send + Sync {
    /// Returns the account address.
    fn address(&self) -> AccountAddress;

    /// Returns the authentication key.
    fn authentication_key(&self) -> AuthenticationKey;

    /// Signs a message and returns the signature bytes.
    ///
    /// # Errors
    ///
    /// May return an error if signing fails (e.g., insufficient signatures
    /// for multi-sig accounts).
    fn sign(&self, message: &[u8]) -> AptosResult<Vec<u8>>;

    /// Returns the public key bytes.
    fn public_key_bytes(&self) -> Vec<u8>;

    /// Returns the scheme identifier for this account type.
    fn signature_scheme(&self) -> u8;
}

/// An enum that can hold any account type.
///
/// This is useful when you need to store different account types
/// in the same collection or pass them around generically.
#[derive(Debug)]
#[allow(clippy::large_enum_variant)] // Keyless account is intentionally large; boxing would complicate API
pub enum AnyAccount {
    /// An Ed25519 account.
    #[cfg(feature = "ed25519")]
    Ed25519(super::Ed25519Account),
    /// A multi-Ed25519 account.
    #[cfg(feature = "ed25519")]
    MultiEd25519(super::MultiEd25519Account),
    /// A multi-key account (mixed signature types).
    MultiKey(super::MultiKeyAccount),
    /// A Keyless account.
    #[cfg(feature = "keyless")]
    Keyless(super::KeylessAccount),
    /// A Secp256k1 account.
    #[cfg(feature = "secp256k1")]
    Secp256k1(super::Secp256k1Account),
}

impl Account for AnyAccount {
    fn address(&self) -> AccountAddress {
        match self {
            #[cfg(feature = "ed25519")]
            AnyAccount::Ed25519(account) => account.address(),
            #[cfg(feature = "ed25519")]
            AnyAccount::MultiEd25519(account) => account.address(),
            AnyAccount::MultiKey(account) => account.address(),
            #[cfg(feature = "keyless")]
            AnyAccount::Keyless(account) => account.address(),
            #[cfg(feature = "secp256k1")]
            AnyAccount::Secp256k1(account) => account.address(),
        }
    }

    fn authentication_key(&self) -> AuthenticationKey {
        match self {
            #[cfg(feature = "ed25519")]
            AnyAccount::Ed25519(account) => account.authentication_key(),
            #[cfg(feature = "ed25519")]
            AnyAccount::MultiEd25519(account) => account.authentication_key(),
            AnyAccount::MultiKey(account) => account.authentication_key(),
            #[cfg(feature = "keyless")]
            AnyAccount::Keyless(account) => account.authentication_key(),
            #[cfg(feature = "secp256k1")]
            AnyAccount::Secp256k1(account) => account.authentication_key(),
        }
    }

    fn sign(&self, message: &[u8]) -> AptosResult<Vec<u8>> {
        match self {
            #[cfg(feature = "ed25519")]
            AnyAccount::Ed25519(account) => Account::sign(account, message),
            #[cfg(feature = "ed25519")]
            AnyAccount::MultiEd25519(account) => Account::sign(account, message),
            AnyAccount::MultiKey(account) => Account::sign(account, message),
            #[cfg(feature = "keyless")]
            AnyAccount::Keyless(account) => Account::sign(account, message),
            #[cfg(feature = "secp256k1")]
            AnyAccount::Secp256k1(account) => Account::sign(account, message),
        }
    }

    fn public_key_bytes(&self) -> Vec<u8> {
        match self {
            #[cfg(feature = "ed25519")]
            AnyAccount::Ed25519(account) => account.public_key_bytes(),
            #[cfg(feature = "ed25519")]
            AnyAccount::MultiEd25519(account) => account.public_key_bytes(),
            AnyAccount::MultiKey(account) => account.public_key_bytes(),
            #[cfg(feature = "keyless")]
            AnyAccount::Keyless(account) => account.public_key_bytes(),
            #[cfg(feature = "secp256k1")]
            AnyAccount::Secp256k1(account) => account.public_key_bytes(),
        }
    }

    fn signature_scheme(&self) -> u8 {
        match self {
            #[cfg(feature = "ed25519")]
            AnyAccount::Ed25519(account) => account.signature_scheme(),
            #[cfg(feature = "ed25519")]
            AnyAccount::MultiEd25519(account) => account.signature_scheme(),
            AnyAccount::MultiKey(account) => account.signature_scheme(),
            #[cfg(feature = "keyless")]
            AnyAccount::Keyless(account) => account.signature_scheme(),
            #[cfg(feature = "secp256k1")]
            AnyAccount::Secp256k1(account) => account.signature_scheme(),
        }
    }
}

#[cfg(feature = "ed25519")]
impl From<super::Ed25519Account> for AnyAccount {
    fn from(account: super::Ed25519Account) -> Self {
        AnyAccount::Ed25519(account)
    }
}

#[cfg(feature = "ed25519")]
impl From<super::MultiEd25519Account> for AnyAccount {
    fn from(account: super::MultiEd25519Account) -> Self {
        AnyAccount::MultiEd25519(account)
    }
}

#[cfg(feature = "keyless")]
impl From<super::KeylessAccount> for AnyAccount {
    fn from(account: super::KeylessAccount) -> Self {
        AnyAccount::Keyless(account)
    }
}

#[cfg(feature = "secp256k1")]
impl From<super::Secp256k1Account> for AnyAccount {
    fn from(account: super::Secp256k1Account) -> Self {
        AnyAccount::Secp256k1(account)
    }
}

impl From<super::MultiKeyAccount> for AnyAccount {
    fn from(account: super::MultiKeyAccount) -> Self {
        AnyAccount::MultiKey(account)
    }
}

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

    #[test]
    fn test_authentication_key() {
        let key = AuthenticationKey::new([1u8; 32]);
        assert_eq!(key.as_bytes(), &[1u8; 32]);

        let hex = key.to_hex();
        let restored = AuthenticationKey::from_hex(&hex).unwrap();
        assert_eq!(key, restored);
    }

    #[test]
    fn test_auth_key_to_address() {
        let key = AuthenticationKey::new([42u8; 32]);
        let address = key.to_address();
        assert_eq!(address.as_bytes(), &[42u8; 32]);
    }

    #[test]
    fn test_auth_key_from_bytes() {
        let bytes = [5u8; 32];
        let key = AuthenticationKey::from_bytes(&bytes).unwrap();
        assert_eq!(key.to_bytes(), bytes);
    }

    #[test]
    fn test_auth_key_from_bytes_invalid_length() {
        let bytes = [5u8; 16];
        let result = AuthenticationKey::from_bytes(&bytes);
        assert!(result.is_err());
    }

    #[test]
    fn test_auth_key_from_hex_with_prefix() {
        let key = AuthenticationKey::new([0xab; 32]);
        let hex = key.to_hex();
        assert!(hex.starts_with("0x"));
        let restored = AuthenticationKey::from_hex(&hex).unwrap();
        assert_eq!(key, restored);
    }

    #[test]
    fn test_auth_key_from_hex_without_prefix() {
        let key = AuthenticationKey::new([0xcd; 32]);
        let hex = key.to_hex();
        let hex_without_prefix = hex.trim_start_matches("0x");
        let restored = AuthenticationKey::from_hex(hex_without_prefix).unwrap();
        assert_eq!(key, restored);
    }

    #[test]
    fn test_auth_key_display() {
        let key = AuthenticationKey::new([0xff; 32]);
        let display = format!("{key}");
        assert!(display.starts_with("0x"));
        assert_eq!(display.len(), 66); // 0x + 64 hex chars
    }

    #[test]
    fn test_auth_key_debug() {
        let key = AuthenticationKey::new([0xaa; 32]);
        let debug = format!("{key:?}");
        assert!(debug.contains("AuthenticationKey"));
    }

    #[test]
    fn test_auth_key_from_array() {
        let bytes = [7u8; 32];
        let key: AuthenticationKey = bytes.into();
        assert_eq!(key.to_bytes(), bytes);
    }

    #[test]
    fn test_auth_key_to_array() {
        let key = AuthenticationKey::new([8u8; 32]);
        let bytes: [u8; 32] = key.into();
        assert_eq!(bytes, [8u8; 32]);
    }

    #[test]
    fn test_auth_key_to_account_address() {
        let key = AuthenticationKey::new([9u8; 32]);
        let address: AccountAddress = key.into();
        assert_eq!(address.as_bytes(), &[9u8; 32]);
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_any_account_from_ed25519() {
        let ed25519 = super::super::Ed25519Account::generate();
        let any_account: AnyAccount = ed25519.into();
        if let AnyAccount::Ed25519(account) = any_account {
            assert!(!account.address().is_zero());
        } else {
            panic!("Expected Ed25519 account");
        }
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_any_account_ed25519_trait_methods() {
        let ed25519 = super::super::Ed25519Account::generate();
        let address = ed25519.address();
        let auth_key = ed25519.authentication_key();
        let any_account: AnyAccount = ed25519.into();

        assert_eq!(any_account.address(), address);
        assert_eq!(any_account.authentication_key(), auth_key);
        assert!(!any_account.public_key_bytes().is_empty());

        let sig = any_account.sign(b"test message").unwrap();
        assert!(!sig.is_empty());
    }

    #[cfg(feature = "secp256k1")]
    #[test]
    fn test_any_account_from_secp256k1() {
        let secp = super::super::Secp256k1Account::generate();
        let any_account: AnyAccount = secp.into();
        if let AnyAccount::Secp256k1(account) = any_account {
            assert!(!account.address().is_zero());
        } else {
            panic!("Expected Secp256k1 account");
        }
    }

    #[cfg(feature = "secp256k1")]
    #[test]
    fn test_any_account_secp256k1_trait_methods() {
        let secp = super::super::Secp256k1Account::generate();
        let address = secp.address();
        let auth_key = secp.authentication_key();
        let any_account: AnyAccount = secp.into();

        assert_eq!(any_account.address(), address);
        assert_eq!(any_account.authentication_key(), auth_key);
        assert!(!any_account.public_key_bytes().is_empty());

        let sig = any_account.sign(b"test message").unwrap();
        assert!(!sig.is_empty());
    }

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

        let keys: Vec<_> = (0..2).map(|_| Ed25519PrivateKey::generate()).collect();
        let account = super::super::MultiEd25519Account::new(keys, 2).unwrap();
        let any_account: AnyAccount = account.into();

        if let AnyAccount::MultiEd25519(_) = any_account {
            // Success
        } else {
            panic!("Expected MultiEd25519 account");
        }
    }

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

        let keys: Vec<_> = (0..2).map(|_| Ed25519PrivateKey::generate()).collect();
        let account = super::super::MultiEd25519Account::new(keys, 2).unwrap();
        let address = account.address();
        let auth_key = account.authentication_key();
        let any_account: AnyAccount = account.into();

        assert_eq!(any_account.address(), address);
        assert_eq!(any_account.authentication_key(), auth_key);
        assert!(!any_account.public_key_bytes().is_empty());
        assert!(any_account.signature_scheme() > 0);

        let sig = any_account.sign(b"test").unwrap();
        assert!(!sig.is_empty());
    }

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

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

        if let AnyAccount::MultiKey(_) = any_account {
            // Success
        } else {
            panic!("Expected MultiKey account");
        }
    }

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

        let keys: Vec<_> = (0..2)
            .map(|_| AnyPrivateKey::ed25519(Ed25519PrivateKey::generate()))
            .collect();
        let account = super::super::MultiKeyAccount::new(keys, 2).unwrap();
        let address = account.address();
        let auth_key = account.authentication_key();
        let any_account: AnyAccount = account.into();

        assert_eq!(any_account.address(), address);
        assert_eq!(any_account.authentication_key(), auth_key);
        assert!(!any_account.public_key_bytes().is_empty());

        let sig = any_account.sign(b"test").unwrap();
        assert!(!sig.is_empty());
    }

    #[test]
    fn test_auth_key_json_serialization() {
        let key = AuthenticationKey::new([0xab; 32]);
        let json = serde_json::to_string(&key).unwrap();
        let restored: AuthenticationKey = serde_json::from_str(&json).unwrap();
        assert_eq!(key, restored);
    }

    #[test]
    fn test_auth_key_hash() {
        use std::collections::HashSet;
        let key1 = AuthenticationKey::new([1u8; 32]);
        let key2 = AuthenticationKey::new([2u8; 32]);

        let mut set = HashSet::new();
        set.insert(key1);
        set.insert(key2);
        assert_eq!(set.len(), 2);
        assert!(set.contains(&key1));
    }

    #[test]
    fn test_auth_key_clone() {
        let key = AuthenticationKey::new([42u8; 32]);
        let cloned = key;
        assert_eq!(key, cloned);
    }

    #[test]
    fn test_any_account_debug() {
        #[cfg(feature = "ed25519")]
        {
            let ed25519 = super::super::Ed25519Account::generate();
            let any_account: AnyAccount = ed25519.into();
            let debug = format!("{any_account:?}");
            assert!(debug.contains("Ed25519"));
        }
    }
}