Skip to main content

thru_base/
tn_tools.rs

1use crate::tn_public_address;
2use crate::txn_lib::TnPubkey;
3use crate::{tn_public_address::tn_pubkey_to_address_string, tn_signature_encoding};
4use anyhow::Result;
5use ed25519_dalek::SigningKey;
6use hex;
7use rand::TryRng;
8use rand::rngs::SysRng;
9use serde::{Deserialize, Serialize};
10use std::fmt;
11
12use thiserror::Error;
13
14pub fn gen_key() -> Result<[u8; 32]> {
15    let mut private_key = [0u8; 32];
16    let mut rng = SysRng;
17    rng.try_fill_bytes(&mut private_key).unwrap();
18    Ok(private_key)
19}
20
21#[derive(Debug, Clone)]
22pub struct KeyPair {
23    pub name: String,
24    pub private_key: [u8; 32],
25    pub public_key: TnPubkey,
26    pub address_string: Pubkey,
27}
28
29impl KeyPair {
30    pub fn generate(name: &str) -> Result<Self> {
31        // Generate new key
32        let mut private_key = [0u8; 32];
33        let mut rng = SysRng;
34        rng.try_fill_bytes(&mut private_key)?;
35        // Derive public key
36        let signing_key = SigningKey::from_bytes(&private_key);
37        let verifying_key = signing_key.verifying_key();
38        let public_key = verifying_key.to_bytes();
39
40        // Generate proper ta... address string using thru-base utilities
41        let address_string = Pubkey::from_bytes(&public_key);
42
43        Ok(Self {
44            name: name.to_string(),
45            private_key,
46            public_key,
47            address_string,
48        })
49    }
50
51    pub fn from_hex_private_key<P: AsRef<[u8]>>(name: &str, hex_private_key: P) -> Result<Self> {
52        // Convert hex string to 32-byte array
53        let private_key_bytes = hex::decode(hex_private_key)
54            .map_err(|e| anyhow::anyhow!("Failed to decode hex private key: {}", e))?;
55
56        if private_key_bytes.len() != 32 {
57            return Err(anyhow::anyhow!(
58                "Private key must be 32 bytes, got {}",
59                private_key_bytes.len()
60            ));
61        }
62
63        let mut private_key = [0u8; 32];
64        private_key.copy_from_slice(&private_key_bytes);
65
66        // Derive public key
67        let signing_key = SigningKey::from_bytes(&private_key);
68        let verifying_key = signing_key.verifying_key();
69        let public_key = verifying_key.to_bytes();
70
71        // Generate proper ta... address string using thru-base utilities
72        let address_string = Pubkey::from_bytes(&public_key);
73
74        Ok(Self {
75            name: name.to_string(),
76            private_key,
77            public_key,
78            address_string,
79        })
80    }
81
82    pub fn public_key_hex(&self) -> String {
83        hex::encode(self.public_key)
84    }
85    pub fn public_key_str(&self) -> String {
86        tn_pubkey_to_address_string(&self.public_key)
87    }
88
89    fn local_signer(&self) -> crate::signer::LocalSigner {
90        crate::signer::LocalSigner::from_seed(self.private_key)
91    }
92}
93
94/// A `KeyPair` holds a raw Ed25519 seed, so it is a local [`Signer`]: every
95/// operation delegates to [`crate::signer::LocalSigner`] over the same seed.
96/// This lets code that already holds a `KeyPair` sign through the `Signer`
97/// abstraction (and later swap in a hardware signer) without re-plumbing.
98///
99/// [`Signer`]: crate::signer::Signer
100impl crate::signer::Signer for KeyPair {
101    fn public_key(&self) -> [u8; 32] {
102        self.local_signer().public_key()
103    }
104    fn sign(
105        &self,
106        msg: &crate::signer::SigningMessage,
107    ) -> std::result::Result<[u8; 64], crate::signer::SignError> {
108        self.local_signer().sign(msg)
109    }
110    fn sign_message(
111        &self,
112        message: &[u8],
113    ) -> std::result::Result<[u8; 64], crate::signer::SignError> {
114        self.local_signer().sign_message(message)
115    }
116    fn sign_eoa_auth(
117        &self,
118        kind: crate::signer::EoaAuthKind,
119        chain_id: u16,
120        fee_payer: &TnPubkey,
121        account: &TnPubkey,
122    ) -> std::result::Result<[u8; 64], crate::signer::SignError> {
123        self.local_signer()
124            .sign_eoa_auth(kind, chain_id, fee_payer, account)
125    }
126    fn supports_legacy_scheme(&self) -> bool {
127        true
128    }
129}
130
131/// A public key on the blockchain
132///
133/// Public keys in Thru are encoded as 46-character strings starting with "ta"
134/// using a custom base64-url encoding with checksum validation.
135#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
136pub struct Pubkey(String);
137
138impl Pubkey {
139    /// Create a new public key from a string
140    ///
141    /// The string must be a valid 46-character Thru address starting with "ta"
142    pub fn new(key: String) -> Result<Self> {
143        // Basic validation
144        if key.is_empty() {
145            return Err(ValidationError::InvalidPubkey("empty pubkey".to_string()).into());
146        }
147
148        // Validate format: should be 46 characters starting with "ta"
149        if key.len() != 46 {
150            return Err(ValidationError::InvalidPubkey(format!(
151                "invalid pubkey length: expected 46, got {}",
152                key.len()
153            ))
154            .into());
155        }
156
157        if !key.starts_with("ta") {
158            return Err(
159                ValidationError::InvalidPubkey("pubkey must start with 'ta'".to_string()).into(),
160            );
161        }
162
163        // Validate by attempting to decode
164        let mut decoded = [0u8; 32];
165        match tn_public_address::tn_public_address_decode(&mut decoded, key.as_bytes()) {
166            Ok(()) => Ok(Self(key)),
167            Err(code) => Err(ValidationError::InvalidPubkey(format!(
168                "invalid pubkey format: decode error {}",
169                code
170            ))
171            .into()),
172        }
173    }
174
175    /// Get the public key as a string
176    pub fn as_str(&self) -> &str {
177        &self.0
178    }
179
180    /// Convert to bytes (decode the address)
181    pub fn to_bytes(&self) -> Result<[u8; 32]> {
182        let mut bytes = [0u8; 32];
183        match tn_public_address::tn_public_address_decode(&mut bytes, self.0.as_bytes()) {
184            Ok(()) => Ok(bytes),
185            Err(code) => Err(ValidationError::InvalidPubkey(format!(
186                "failed to decode pubkey: error {}",
187                code
188            ))
189            .into()),
190        }
191    }
192
193    /// Create a Pubkey from raw bytes
194    pub fn from_bytes(bytes: &[u8; 32]) -> Self {
195        let address = tn_public_address::tn_pubkey_to_address_string(bytes);
196        // This should never fail since we're encoding from valid bytes
197        Self(address)
198    }
199
200    /// Create a Pubkey from a hex string
201    ///
202    /// The hex string can be 64 characters (32 bytes) with optional "0x" prefix
203    pub fn from_hex(hex_str: &str) -> Result<Self> {
204        // Remove "0x" prefix if present
205        let hex_str = hex_str.strip_prefix("0x").unwrap_or(hex_str);
206
207        // Validate hex string length (should be 64 characters for 32 bytes)
208        if hex_str.len() != 64 {
209            return Err(ValidationError::InvalidPubkey(format!(
210                "invalid hex pubkey length: expected 64 characters, got {}",
211                hex_str.len()
212            ))
213            .into());
214        }
215
216        // Decode hex to bytes
217        let bytes = hex::decode(hex_str).map_err(|e| {
218            ValidationError::InvalidPubkey(format!("invalid hex pubkey format: {}", e))
219        })?;
220
221        // Ensure we have exactly 32 bytes
222        if bytes.len() != 32 {
223            return Err(ValidationError::InvalidPubkey(format!(
224                "invalid hex pubkey: expected 32 bytes, got {}",
225                bytes.len()
226            ))
227            .into());
228        }
229
230        let mut bytes_array = [0u8; 32];
231        bytes_array.copy_from_slice(&bytes);
232
233        // Convert to Thru address format
234        Ok(Self::from_bytes(&bytes_array))
235    }
236}
237
238impl fmt::Display for Pubkey {
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        write!(f, "{}", self.0)
241    }
242}
243
244/// A transaction signature
245///
246/// Signatures in Thru are encoded as 90-character strings starting with "ts"
247/// using a custom base64-url encoding with checksum validation.
248#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
249pub struct Signature(String);
250
251impl Signature {
252    /// Create a new signature from a string
253    ///
254    /// The string must be a valid 90-character Thru signature starting with "ts"
255    pub fn new(sig: String) -> Result<Self> {
256        // Basic validation
257        if sig.is_empty() {
258            return Err(ValidationError::InvalidSignature("empty signature".to_string()).into());
259        }
260
261        // Validate format: should be 90 characters starting with "ts"
262        if sig.len() != 90 {
263            return Err(ValidationError::InvalidSignature(format!(
264                "invalid signature length: expected 90, got {}",
265                sig.len()
266            ))
267            .into());
268        }
269
270        if !sig.starts_with("ts") {
271            return Err(ValidationError::InvalidSignature(
272                "signature must start with 'ts'".to_string(),
273            )
274            .into());
275        }
276
277        // Validate by attempting to decode
278        let mut decoded = [0u8; 64];
279        match tn_signature_encoding::tn_signature_decode(&mut decoded, sig.as_bytes()) {
280            Ok(()) => Ok(Self(sig)),
281            Err(code) => Err(ValidationError::InvalidSignature(format!(
282                "invalid signature format: decode error {}",
283                code
284            ))
285            .into()),
286        }
287    }
288
289    /// Get the signature as a string
290    pub fn as_str(&self) -> &str {
291        &self.0
292    }
293
294    /// Convert to bytes (decode the signature)
295    pub fn to_bytes(&self) -> Result<[u8; 64]> {
296        let mut bytes = [0u8; 64];
297        match tn_signature_encoding::tn_signature_decode(&mut bytes, self.0.as_bytes()) {
298            Ok(()) => Ok(bytes),
299            Err(code) => Err(ValidationError::InvalidSignature(format!(
300                "failed to decode signature: error {}",
301                code
302            ))
303            .into()),
304        }
305    }
306
307    /// Create a Signature from raw bytes
308    pub fn from_bytes(bytes: &[u8; 64]) -> Self {
309        let signature = tn_signature_encoding::tn_signature_to_string(bytes);
310        // This should never fail since we're encoding from valid bytes
311        Self(signature)
312    }
313}
314
315impl fmt::Display for Signature {
316    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317        write!(f, "{}", self.0)
318    }
319}
320
321/// Validation errors for input data
322#[derive(Error, Debug)]
323pub enum ValidationError {
324    /// Invalid public key format
325    #[error("Invalid public key: {0}")]
326    InvalidPubkey(String),
327
328    /// Invalid signature format
329    #[error("Invalid signature: {0}")]
330    InvalidSignature(String),
331}
332
333#[cfg(test)]
334mod tests {
335
336    use super::*;
337
338    #[test]
339    fn keypair_signer_matches_local_signer() {
340        use crate::signer::{self, EoaAuthKind, LocalSigner, Signer};
341        let seed = [3u8; 32];
342        let kp = KeyPair::from_hex_private_key("k", hex::encode(seed)).unwrap();
343        let local = LocalSigner::from_seed(seed);
344        assert_eq!(Signer::public_key(&kp), kp.public_key);
345        assert_eq!(Signer::public_key(&kp), local.public_key());
346        let mut body = vec![0u8; 120];
347        body[48..80].copy_from_slice(&kp.public_key);
348        assert_eq!(
349            signer::sign_transaction_body_with(&kp, &body).unwrap(),
350            signer::sign_transaction_body_with(&local, &body).unwrap()
351        );
352        assert_eq!(
353            signer::sign_message_with(&kp, b"m").unwrap(),
354            signer::sign_message_with(&local, b"m").unwrap()
355        );
356        let fp = [1u8; 32];
357        assert_eq!(
358            signer::sign_eoa_auth_with(&kp, EoaAuthKind::Create, 1, &fp, &kp.public_key).unwrap(),
359            signer::sign_eoa_auth_with(&local, EoaAuthKind::Create, 1, &fp, &kp.public_key)
360                .unwrap()
361        );
362        assert!(Signer::supports_legacy_scheme(&kp));
363    }
364
365    #[test]
366    fn test_pubkey_validation() {
367        // Create a valid pubkey using the encoding function
368        let bytes = [1u8; 32];
369        let valid_pubkey = tn_public_address::tn_pubkey_to_address_string(&bytes);
370        assert!(Pubkey::new(valid_pubkey.to_string()).is_ok());
371
372        // Empty pubkey
373        assert!(Pubkey::new("".to_string()).is_err());
374
375        // Wrong length
376        assert!(Pubkey::new("ta111".to_string()).is_err());
377
378        // Wrong prefix
379        assert!(Pubkey::new("tb1111111111111111111111111111111111111111111".to_string()).is_err());
380
381        // Invalid characters (not base64-url)
382        assert!(Pubkey::new("ta!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!".to_string()).is_err());
383    }
384
385    #[test]
386    fn test_signature_validation() {
387        // Create a valid signature using the encoding function
388        let bytes = [1u8; 64];
389        let valid_signature = tn_signature_encoding::tn_signature_to_string(&bytes);
390        assert!(Signature::new(valid_signature.to_string()).is_ok());
391
392        // Empty signature
393        assert!(Signature::new("".to_string()).is_err());
394
395        // Wrong length
396        assert!(Signature::new("ts111".to_string()).is_err());
397
398        // Wrong prefix
399        assert!(Signature::new("ta111111111111111111111111111111111111111111111111111111111111111111111111111111111111".to_string()).is_err());
400
401        // Invalid characters (not base64-url)
402        assert!(Signature::new("ts!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!".to_string()).is_err());
403    }
404
405    #[test]
406    fn test_pubkey_roundtrip() {
407        // Test encoding and decoding
408        let bytes = [1u8; 32];
409        let pubkey = Pubkey::from_bytes(&bytes);
410        let decoded_bytes = pubkey.to_bytes().unwrap();
411        assert_eq!(bytes, decoded_bytes);
412    }
413
414    #[test]
415    fn test_signature_roundtrip() {
416        // Test encoding and decoding
417        let bytes = [1u8; 64];
418        let signature = Signature::from_bytes(&bytes);
419        let decoded_bytes = signature.to_bytes().unwrap();
420        assert_eq!(bytes, decoded_bytes);
421    }
422}