thru-base 0.5.4

Core Rust primitives for the Thru blockchain: key and address types, transaction builders, state proof helpers, and RPC config.
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
use crate::tn_public_address;
use crate::txn_lib::TnPubkey;
use crate::{tn_public_address::tn_pubkey_to_address_string, tn_signature_encoding};
use anyhow::Result;
use ed25519_dalek::SigningKey;
use hex;
use rand::TryRng;
use rand::rngs::SysRng;
use serde::{Deserialize, Serialize};
use std::fmt;

use thiserror::Error;

pub fn gen_key() -> Result<[u8; 32]> {
    let mut private_key = [0u8; 32];
    let mut rng = SysRng;
    rng.try_fill_bytes(&mut private_key).unwrap();
    Ok(private_key)
}

#[derive(Debug, Clone)]
pub struct KeyPair {
    pub name: String,
    pub private_key: [u8; 32],
    pub public_key: TnPubkey,
    pub address_string: Pubkey,
}

impl KeyPair {
    pub fn generate(name: &str) -> Result<Self> {
        // Generate new key
        let mut private_key = [0u8; 32];
        let mut rng = SysRng;
        rng.try_fill_bytes(&mut private_key)?;
        // Derive public key
        let signing_key = SigningKey::from_bytes(&private_key);
        let verifying_key = signing_key.verifying_key();
        let public_key = verifying_key.to_bytes();

        // Generate proper ta... address string using thru-base utilities
        let address_string = Pubkey::from_bytes(&public_key);

        Ok(Self {
            name: name.to_string(),
            private_key,
            public_key,
            address_string,
        })
    }

    pub fn from_hex_private_key<P: AsRef<[u8]>>(name: &str, hex_private_key: P) -> Result<Self> {
        // Convert hex string to 32-byte array
        let private_key_bytes = hex::decode(hex_private_key)
            .map_err(|e| anyhow::anyhow!("Failed to decode hex private key: {}", e))?;

        if private_key_bytes.len() != 32 {
            return Err(anyhow::anyhow!(
                "Private key must be 32 bytes, got {}",
                private_key_bytes.len()
            ));
        }

        let mut private_key = [0u8; 32];
        private_key.copy_from_slice(&private_key_bytes);

        // Derive public key
        let signing_key = SigningKey::from_bytes(&private_key);
        let verifying_key = signing_key.verifying_key();
        let public_key = verifying_key.to_bytes();

        // Generate proper ta... address string using thru-base utilities
        let address_string = Pubkey::from_bytes(&public_key);

        Ok(Self {
            name: name.to_string(),
            private_key,
            public_key,
            address_string,
        })
    }

    pub fn public_key_hex(&self) -> String {
        hex::encode(self.public_key)
    }
    pub fn public_key_str(&self) -> String {
        tn_pubkey_to_address_string(&self.public_key)
    }

    fn local_signer(&self) -> crate::signer::LocalSigner {
        crate::signer::LocalSigner::from_seed(self.private_key)
    }
}

/// A `KeyPair` holds a raw Ed25519 seed, so it is a local [`Signer`]: every
/// operation delegates to [`crate::signer::LocalSigner`] over the same seed.
/// This lets code that already holds a `KeyPair` sign through the `Signer`
/// abstraction (and later swap in a hardware signer) without re-plumbing.
///
/// [`Signer`]: crate::signer::Signer
impl crate::signer::Signer for KeyPair {
    fn public_key(&self) -> [u8; 32] {
        self.local_signer().public_key()
    }
    fn sign(
        &self,
        msg: &crate::signer::SigningMessage,
    ) -> std::result::Result<[u8; 64], crate::signer::SignError> {
        self.local_signer().sign(msg)
    }
    fn sign_message(
        &self,
        message: &[u8],
    ) -> std::result::Result<[u8; 64], crate::signer::SignError> {
        self.local_signer().sign_message(message)
    }
    fn sign_eoa_auth(
        &self,
        kind: crate::signer::EoaAuthKind,
        chain_id: u16,
        fee_payer: &TnPubkey,
        account: &TnPubkey,
    ) -> std::result::Result<[u8; 64], crate::signer::SignError> {
        self.local_signer()
            .sign_eoa_auth(kind, chain_id, fee_payer, account)
    }
    fn supports_legacy_scheme(&self) -> bool {
        true
    }
}

/// A public key on the blockchain
///
/// Public keys in Thru are encoded as 46-character strings starting with "ta"
/// using a custom base64-url encoding with checksum validation.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Pubkey(String);

impl Pubkey {
    /// Create a new public key from a string
    ///
    /// The string must be a valid 46-character Thru address starting with "ta"
    pub fn new(key: String) -> Result<Self> {
        // Basic validation
        if key.is_empty() {
            return Err(ValidationError::InvalidPubkey("empty pubkey".to_string()).into());
        }

        // Validate format: should be 46 characters starting with "ta"
        if key.len() != 46 {
            return Err(ValidationError::InvalidPubkey(format!(
                "invalid pubkey length: expected 46, got {}",
                key.len()
            ))
            .into());
        }

        if !key.starts_with("ta") {
            return Err(
                ValidationError::InvalidPubkey("pubkey must start with 'ta'".to_string()).into(),
            );
        }

        // Validate by attempting to decode
        let mut decoded = [0u8; 32];
        match tn_public_address::tn_public_address_decode(&mut decoded, key.as_bytes()) {
            Ok(()) => Ok(Self(key)),
            Err(code) => Err(ValidationError::InvalidPubkey(format!(
                "invalid pubkey format: decode error {}",
                code
            ))
            .into()),
        }
    }

    /// Get the public key as a string
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Convert to bytes (decode the address)
    pub fn to_bytes(&self) -> Result<[u8; 32]> {
        let mut bytes = [0u8; 32];
        match tn_public_address::tn_public_address_decode(&mut bytes, self.0.as_bytes()) {
            Ok(()) => Ok(bytes),
            Err(code) => Err(ValidationError::InvalidPubkey(format!(
                "failed to decode pubkey: error {}",
                code
            ))
            .into()),
        }
    }

    /// Create a Pubkey from raw bytes
    pub fn from_bytes(bytes: &[u8; 32]) -> Self {
        let address = tn_public_address::tn_pubkey_to_address_string(bytes);
        // This should never fail since we're encoding from valid bytes
        Self(address)
    }

    /// Create a Pubkey from a hex string
    ///
    /// The hex string can be 64 characters (32 bytes) with optional "0x" prefix
    pub fn from_hex(hex_str: &str) -> Result<Self> {
        // Remove "0x" prefix if present
        let hex_str = hex_str.strip_prefix("0x").unwrap_or(hex_str);

        // Validate hex string length (should be 64 characters for 32 bytes)
        if hex_str.len() != 64 {
            return Err(ValidationError::InvalidPubkey(format!(
                "invalid hex pubkey length: expected 64 characters, got {}",
                hex_str.len()
            ))
            .into());
        }

        // Decode hex to bytes
        let bytes = hex::decode(hex_str).map_err(|e| {
            ValidationError::InvalidPubkey(format!("invalid hex pubkey format: {}", e))
        })?;

        // Ensure we have exactly 32 bytes
        if bytes.len() != 32 {
            return Err(ValidationError::InvalidPubkey(format!(
                "invalid hex pubkey: expected 32 bytes, got {}",
                bytes.len()
            ))
            .into());
        }

        let mut bytes_array = [0u8; 32];
        bytes_array.copy_from_slice(&bytes);

        // Convert to Thru address format
        Ok(Self::from_bytes(&bytes_array))
    }
}

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

/// A transaction signature
///
/// Signatures in Thru are encoded as 90-character strings starting with "ts"
/// using a custom base64-url encoding with checksum validation.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Signature(String);

impl Signature {
    /// Create a new signature from a string
    ///
    /// The string must be a valid 90-character Thru signature starting with "ts"
    pub fn new(sig: String) -> Result<Self> {
        // Basic validation
        if sig.is_empty() {
            return Err(ValidationError::InvalidSignature("empty signature".to_string()).into());
        }

        // Validate format: should be 90 characters starting with "ts"
        if sig.len() != 90 {
            return Err(ValidationError::InvalidSignature(format!(
                "invalid signature length: expected 90, got {}",
                sig.len()
            ))
            .into());
        }

        if !sig.starts_with("ts") {
            return Err(ValidationError::InvalidSignature(
                "signature must start with 'ts'".to_string(),
            )
            .into());
        }

        // Validate by attempting to decode
        let mut decoded = [0u8; 64];
        match tn_signature_encoding::tn_signature_decode(&mut decoded, sig.as_bytes()) {
            Ok(()) => Ok(Self(sig)),
            Err(code) => Err(ValidationError::InvalidSignature(format!(
                "invalid signature format: decode error {}",
                code
            ))
            .into()),
        }
    }

    /// Get the signature as a string
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Convert to bytes (decode the signature)
    pub fn to_bytes(&self) -> Result<[u8; 64]> {
        let mut bytes = [0u8; 64];
        match tn_signature_encoding::tn_signature_decode(&mut bytes, self.0.as_bytes()) {
            Ok(()) => Ok(bytes),
            Err(code) => Err(ValidationError::InvalidSignature(format!(
                "failed to decode signature: error {}",
                code
            ))
            .into()),
        }
    }

    /// Create a Signature from raw bytes
    pub fn from_bytes(bytes: &[u8; 64]) -> Self {
        let signature = tn_signature_encoding::tn_signature_to_string(bytes);
        // This should never fail since we're encoding from valid bytes
        Self(signature)
    }
}

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

/// Validation errors for input data
#[derive(Error, Debug)]
pub enum ValidationError {
    /// Invalid public key format
    #[error("Invalid public key: {0}")]
    InvalidPubkey(String),

    /// Invalid signature format
    #[error("Invalid signature: {0}")]
    InvalidSignature(String),
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn keypair_signer_matches_local_signer() {
        use crate::signer::{self, EoaAuthKind, LocalSigner, Signer};
        let seed = [3u8; 32];
        let kp = KeyPair::from_hex_private_key("k", hex::encode(seed)).unwrap();
        let local = LocalSigner::from_seed(seed);
        assert_eq!(Signer::public_key(&kp), kp.public_key);
        assert_eq!(Signer::public_key(&kp), local.public_key());
        let mut body = vec![0u8; 120];
        body[48..80].copy_from_slice(&kp.public_key);
        assert_eq!(
            signer::sign_transaction_body_with(&kp, &body).unwrap(),
            signer::sign_transaction_body_with(&local, &body).unwrap()
        );
        assert_eq!(
            signer::sign_message_with(&kp, b"m").unwrap(),
            signer::sign_message_with(&local, b"m").unwrap()
        );
        let fp = [1u8; 32];
        assert_eq!(
            signer::sign_eoa_auth_with(&kp, EoaAuthKind::Create, 1, &fp, &kp.public_key).unwrap(),
            signer::sign_eoa_auth_with(&local, EoaAuthKind::Create, 1, &fp, &kp.public_key)
                .unwrap()
        );
        assert!(Signer::supports_legacy_scheme(&kp));
    }

    #[test]
    fn test_pubkey_validation() {
        // Create a valid pubkey using the encoding function
        let bytes = [1u8; 32];
        let valid_pubkey = tn_public_address::tn_pubkey_to_address_string(&bytes);
        assert!(Pubkey::new(valid_pubkey.to_string()).is_ok());

        // Empty pubkey
        assert!(Pubkey::new("".to_string()).is_err());

        // Wrong length
        assert!(Pubkey::new("ta111".to_string()).is_err());

        // Wrong prefix
        assert!(Pubkey::new("tb1111111111111111111111111111111111111111111".to_string()).is_err());

        // Invalid characters (not base64-url)
        assert!(Pubkey::new("ta!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!".to_string()).is_err());
    }

    #[test]
    fn test_signature_validation() {
        // Create a valid signature using the encoding function
        let bytes = [1u8; 64];
        let valid_signature = tn_signature_encoding::tn_signature_to_string(&bytes);
        assert!(Signature::new(valid_signature.to_string()).is_ok());

        // Empty signature
        assert!(Signature::new("".to_string()).is_err());

        // Wrong length
        assert!(Signature::new("ts111".to_string()).is_err());

        // Wrong prefix
        assert!(Signature::new("ta111111111111111111111111111111111111111111111111111111111111111111111111111111111111".to_string()).is_err());

        // Invalid characters (not base64-url)
        assert!(Signature::new("ts!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!".to_string()).is_err());
    }

    #[test]
    fn test_pubkey_roundtrip() {
        // Test encoding and decoding
        let bytes = [1u8; 32];
        let pubkey = Pubkey::from_bytes(&bytes);
        let decoded_bytes = pubkey.to_bytes().unwrap();
        assert_eq!(bytes, decoded_bytes);
    }

    #[test]
    fn test_signature_roundtrip() {
        // Test encoding and decoding
        let bytes = [1u8; 64];
        let signature = Signature::from_bytes(&bytes);
        let decoded_bytes = signature.to_bytes().unwrap();
        assert_eq!(bytes, decoded_bytes);
    }
}