alephium-web3 2.0.7

A Rust library to interact with the Alephium platform
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
// Copyright 2018 - 2022 The Alephium Authors
// This file is part of the alephium project.

use crate::address::{hash_public_key, Address};
use crate::error::{Error, Result};
use rand::rngs::OsRng;
use serde::{Deserialize, Serialize};

/// Key type for cryptographic operations
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum KeyType {
    #[serde(rename = "secp256k1")]
    Secp256k1,
    #[serde(rename = "secp256r1")]
    Secp256r1,
    #[serde(rename = "ed25519")]
    Ed25519,
}

impl KeyType {
    /// Get the byte prefix for this key type
    pub fn prefix(&self) -> u8 {
        match self {
            KeyType::Secp256k1 => 0x00,
            KeyType::Secp256r1 => 0x01,
            KeyType::Ed25519 => 0x02,
        }
    }

    /// Parse key type from prefix byte
    pub fn from_prefix(prefix: u8) -> Result<Self> {
        match prefix {
            0x00 => Ok(KeyType::Secp256k1),
            0x01 => Ok(KeyType::Secp256r1),
            0x02 => Ok(KeyType::Ed25519),
            _ => Err(Error::InvalidKey(format!("Invalid key type prefix: {}", prefix))),
        }
    }
}

/// Private key
#[derive(Clone)]
pub struct PrivateKey {
    key_type: KeyType,
    bytes: Vec<u8>,
}

impl PrivateKey {
    /// Create a new private key
    pub fn new(key_type: KeyType, bytes: Vec<u8>) -> Result<Self> {
        let expected_len = match key_type {
            KeyType::Secp256k1 | KeyType::Secp256r1 => 32,
            KeyType::Ed25519 => 32,
        };

        if bytes.len() != expected_len {
            return Err(Error::InvalidKey(format!(
                "Invalid private key length: expected {}, got {}",
                expected_len,
                bytes.len()
            )));
        }

        Ok(Self { key_type, bytes })
    }

    /// Generate a new random private key
    pub fn generate(key_type: KeyType) -> Result<Self> {
        let bytes = match key_type {
            KeyType::Secp256k1 => {
                use secp256k1::{rand, Secp256k1};
                let secp = Secp256k1::new();
                let (secret_key, _) = secp.generate_keypair(&mut rand::thread_rng());
                secret_key.secret_bytes().to_vec()
            }
            KeyType::Secp256r1 => {
                use p256::SecretKey;
                let secret_key = SecretKey::random(&mut OsRng);
                secret_key.to_bytes().to_vec()
            }
            KeyType::Ed25519 => {
                use ed25519_dalek::SigningKey;
                let signing_key = SigningKey::generate(&mut OsRng);
                signing_key.to_bytes().to_vec()
            }
        };

        Self::new(key_type, bytes)
    }

    /// Get the key type
    pub fn key_type(&self) -> KeyType {
        self.key_type
    }

    /// Get the raw bytes
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Derive the public key from this private key
    pub fn public_key(&self) -> Result<PublicKey> {
        let bytes = match self.key_type {
            KeyType::Secp256k1 => {
                use secp256k1::{PublicKey as Secp256k1PublicKey, Secp256k1, SecretKey};
                let secp = Secp256k1::new();
                let secret_key = SecretKey::from_slice(&self.bytes)
                    .map_err(|e| Error::InvalidKey(format!("Invalid secp256k1 key: {}", e)))?;
                let public_key = Secp256k1PublicKey::from_secret_key(&secp, &secret_key);
                public_key.serialize().to_vec()
            }
            KeyType::Secp256r1 => {
                use p256::{SecretKey, ecdsa::SigningKey};
                let secret_key = SecretKey::from_slice(&self.bytes)
                    .map_err(|e| Error::InvalidKey(format!("Invalid secp256r1 key: {}", e)))?;
                let signing_key = SigningKey::from(&secret_key);
                let public_key = signing_key.verifying_key();
                // Get compressed encoding
                let encoded_point = public_key.to_encoded_point(true); // true = compressed
                encoded_point.as_bytes().to_vec()
            }
            KeyType::Ed25519 => {
                use ed25519_dalek::{SigningKey, VerifyingKey};
                let signing_key = SigningKey::from_bytes(&self.bytes.clone().try_into().map_err(
                    |_| Error::InvalidKey("Invalid ed25519 key length".to_string()),
                )?);
                let verifying_key: VerifyingKey = (&signing_key).into();
                verifying_key.to_bytes().to_vec()
            }
        };

        PublicKey::new(self.key_type, bytes)
    }

    /// Sign a message with this private key
    pub fn sign(&self, message: &[u8]) -> Result<Signature> {
        let bytes = match self.key_type {
            KeyType::Secp256k1 => {
                use secp256k1::{Message, Secp256k1, SecretKey};
                use sha2::{Digest, Sha256};

                let secp = Secp256k1::new();
                let secret_key = SecretKey::from_slice(&self.bytes)
                    .map_err(|e| Error::InvalidKey(format!("Invalid secp256k1 key: {}", e)))?;

                // Hash the message
                let mut hasher = Sha256::new();
                hasher.update(message);
                let hash = hasher.finalize();

                let msg = Message::from_digest_slice(&hash)
                    .map_err(|e| Error::CryptoError(format!("Invalid message: {}", e)))?;

                let sig = secp.sign_ecdsa(&msg, &secret_key);
                sig.serialize_compact().to_vec()
            }
            KeyType::Secp256r1 => {
                use p256::ecdsa::{signature::Signer, Signature as P256Signature, SigningKey};

                let signing_key = SigningKey::from_slice(&self.bytes)
                    .map_err(|e| Error::InvalidKey(format!("Invalid secp256r1 key: {}", e)))?;

                let signature: P256Signature = signing_key.sign(message);
                signature.to_bytes().to_vec()
            }
            KeyType::Ed25519 => {
                use ed25519_dalek::{Signer, SigningKey};

                let signing_key = SigningKey::from_bytes(&self.bytes.clone().try_into().map_err(
                    |_| Error::InvalidKey("Invalid ed25519 key length".to_string()),
                )?);

                let signature = signing_key.sign(message);
                signature.to_bytes().to_vec()
            }
        };

        Signature::new(bytes)
    }

    /// Get P2PKH address from this private key
    pub fn to_address(&self) -> Result<Address> {
        let public_key = self.public_key()?;
        let public_key_hash = hash_public_key(public_key.bytes());
        Address::p2pkh(&public_key_hash)
    }
}

impl std::fmt::Debug for PrivateKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PrivateKey")
            .field("key_type", &self.key_type)
            .field("bytes", &"[REDACTED]")
            .finish()
    }
}

/// Public key
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublicKey {
    key_type: KeyType,
    bytes: Vec<u8>,
}

impl PublicKey {
    /// Create a new public key
    pub fn new(key_type: KeyType, bytes: Vec<u8>) -> Result<Self> {
        let expected_len = match key_type {
            KeyType::Secp256k1 | KeyType::Secp256r1 => 33, // compressed
            KeyType::Ed25519 => 32,
        };

        if bytes.len() != expected_len {
            return Err(Error::InvalidKey(format!(
                "Invalid public key length: expected {}, got {}",
                expected_len,
                bytes.len()
            )));
        }

        Ok(Self { key_type, bytes })
    }

    /// Get the key type
    pub fn key_type(&self) -> KeyType {
        self.key_type
    }

    /// Get the raw bytes
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Verify a signature
    pub fn verify(&self, message: &[u8], signature: &Signature) -> Result<bool> {
        match self.key_type {
            KeyType::Secp256k1 => {
                use secp256k1::{ecdsa::Signature as Secp256k1Sig, Message, PublicKey as Secp256k1PublicKey, Secp256k1};
                use sha2::{Digest, Sha256};

                let secp = Secp256k1::new();
                let public_key = Secp256k1PublicKey::from_slice(&self.bytes)
                    .map_err(|e| Error::InvalidKey(format!("Invalid secp256k1 public key: {}", e)))?;

                // Hash the message
                let mut hasher = Sha256::new();
                hasher.update(message);
                let hash = hasher.finalize();

                let msg = Message::from_digest_slice(&hash)
                    .map_err(|e| Error::CryptoError(format!("Invalid message: {}", e)))?;

                let sig = Secp256k1Sig::from_compact(&signature.bytes()[..64])
                    .map_err(|e| Error::InvalidSignature(format!("Invalid signature: {}", e)))?;

                Ok(secp.verify_ecdsa(&msg, &sig, &public_key).is_ok())
            }
            KeyType::Secp256r1 => {
                use p256::ecdsa::{signature::Verifier, Signature as P256Signature, VerifyingKey};

                let verifying_key = VerifyingKey::from_sec1_bytes(&self.bytes)
                    .map_err(|e| Error::InvalidKey(format!("Invalid secp256r1 public key: {}", e)))?;

                let sig = P256Signature::from_slice(signature.bytes())
                    .map_err(|e| Error::InvalidSignature(format!("Invalid signature: {}", e)))?;

                Ok(verifying_key.verify(message, &sig).is_ok())
            }
            KeyType::Ed25519 => {
                use ed25519_dalek::{Signature as Ed25519Signature, Verifier, VerifyingKey};

                let verifying_key = VerifyingKey::from_bytes(&self.bytes.clone().try_into().map_err(
                    |_| Error::InvalidKey("Invalid ed25519 public key length".to_string()),
                )?)
                .map_err(|e| Error::InvalidKey(format!("Invalid ed25519 public key: {}", e)))?;

                let sig = Ed25519Signature::from_slice(signature.bytes())
                    .map_err(|e| Error::InvalidSignature(format!("Invalid signature: {}", e)))?;

                Ok(verifying_key.verify(message, &sig).is_ok())
            }
        }
    }

    /// Get P2PKH address from this public key
    pub fn to_address(&self) -> Result<Address> {
        let public_key_hash = hash_public_key(&self.bytes);
        Address::p2pkh(&public_key_hash)
    }

    /// Encode public key with type prefix
    pub fn encode(&self) -> Vec<u8> {
        let mut encoded = vec![self.key_type.prefix()];
        encoded.extend_from_slice(&self.bytes);
        encoded
    }

    /// Decode public key from bytes with type prefix
    pub fn decode(bytes: &[u8]) -> Result<Self> {
        if bytes.is_empty() {
            return Err(Error::InvalidKey("Empty key data".to_string()));
        }

        let key_type = KeyType::from_prefix(bytes[0])?;
        Self::new(key_type, bytes[1..].to_vec())
    }
}

/// Signature
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signature {
    bytes: Vec<u8>,
}

impl Signature {
    /// Create a new signature
    pub fn new(bytes: Vec<u8>) -> Result<Self> {
        if bytes.is_empty() {
            return Err(Error::InvalidSignature("Empty signature".to_string()));
        }
        Ok(Self { bytes })
    }

    /// Get the raw bytes
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Get the length of the signature
    pub fn len(&self) -> usize {
        self.bytes.len()
    }

    /// Check if signature is empty
    pub fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }
}

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

    #[test]
    fn test_key_type_prefix() {
        assert_eq!(KeyType::Secp256k1.prefix(), 0x00);
        assert_eq!(KeyType::Secp256r1.prefix(), 0x01);
        assert_eq!(KeyType::Ed25519.prefix(), 0x02);

        assert_eq!(KeyType::from_prefix(0x00).unwrap(), KeyType::Secp256k1);
        assert_eq!(KeyType::from_prefix(0x01).unwrap(), KeyType::Secp256r1);
        assert_eq!(KeyType::from_prefix(0x02).unwrap(), KeyType::Ed25519);
    }

    #[test]
    fn test_generate_secp256k1_key() {
        let private_key = PrivateKey::generate(KeyType::Secp256k1).unwrap();
        assert_eq!(private_key.key_type(), KeyType::Secp256k1);
        assert_eq!(private_key.bytes().len(), 32);

        // Derive public key
        let public_key = private_key.public_key().unwrap();
        assert_eq!(public_key.key_type(), KeyType::Secp256k1);
        assert_eq!(public_key.bytes().len(), 33);
    }

    #[test]
    fn test_generate_ed25519_key() {
        let private_key = PrivateKey::generate(KeyType::Ed25519).unwrap();
        assert_eq!(private_key.key_type(), KeyType::Ed25519);
        assert_eq!(private_key.bytes().len(), 32);

        // Derive public key
        let public_key = private_key.public_key().unwrap();
        assert_eq!(public_key.key_type(), KeyType::Ed25519);
        assert_eq!(public_key.bytes().len(), 32);
    }

    #[test]
    fn test_sign_and_verify_secp256k1() {
        let private_key = PrivateKey::generate(KeyType::Secp256k1).unwrap();
        let public_key = private_key.public_key().unwrap();

        let message = b"Hello, Alephium!";
        let signature = private_key.sign(message).unwrap();

        assert!(public_key.verify(message, &signature).unwrap());

        // Wrong message should fail
        let wrong_message = b"Wrong message";
        assert!(!public_key.verify(wrong_message, &signature).unwrap());
    }

    #[test]
    fn test_sign_and_verify_ed25519() {
        let private_key = PrivateKey::generate(KeyType::Ed25519).unwrap();
        let public_key = private_key.public_key().unwrap();

        let message = b"Hello, Alephium!";
        let signature = private_key.sign(message).unwrap();

        assert!(public_key.verify(message, &signature).unwrap());

        // Wrong message should fail
        let wrong_message = b"Wrong message";
        assert!(!public_key.verify(wrong_message, &signature).unwrap());
    }

    #[test]
    fn test_public_key_encode_decode() {
        let private_key = PrivateKey::generate(KeyType::Secp256k1).unwrap();
        let public_key = private_key.public_key().unwrap();

        let encoded = public_key.encode();
        let decoded = PublicKey::decode(&encoded).unwrap();

        assert_eq!(public_key, decoded);
    }

    #[test]
    fn test_address_from_private_key() {
        let private_key = PrivateKey::generate(KeyType::Secp256k1).unwrap();
        let address = private_key.to_address().unwrap();

        assert_eq!(address.address_type(), AddressType::P2PKH);
        assert!(address.to_base58().len() > 0);
    }

    #[test]
    fn test_address_from_public_key() {
        let private_key = PrivateKey::generate(KeyType::Secp256k1).unwrap();
        let public_key = private_key.public_key().unwrap();
        let address = public_key.to_address().unwrap();

        // Should match address from private key
        let address_from_private = private_key.to_address().unwrap();
        assert_eq!(address.to_base58(), address_from_private.to_base58());
    }
}