peat-btle 0.3.0

Bluetooth Low Energy mesh transport for Peat Protocol
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
// Copyright (c) 2025-2026 (r)evolve - Revolve Team LLC
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Device identity management using Ed25519 signatures
//!
//! Each device in a Peat mesh has a cryptographic identity consisting of:
//! - An Ed25519 signing keypair (private key stored securely)
//! - A derived NodeId (first 4 bytes of BLAKE3 hash of public key)
//!
//! This enables:
//! - Cryptographic binding between node_id and device
//! - Document signing to prove authorship
//! - Identity attestation to prevent impersonation
//!
//! # Example
//!
//! ```
//! use peat_btle::security::DeviceIdentity;
//!
//! // Generate a new identity
//! let identity = DeviceIdentity::generate();
//!
//! // Get the derived node_id
//! let node_id = identity.node_id();
//!
//! // Sign a message
//! let message = b"Hello, mesh!";
//! let signature = identity.sign(message);
//!
//! // Verify signature with public key
//! assert!(identity.verify(message, &signature));
//! ```

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use rand_core::OsRng;

use crate::NodeId;

/// Errors that can occur during identity operations
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IdentityError {
    /// Invalid signature format or verification failed
    InvalidSignature,
    /// Invalid public key format
    InvalidPublicKey,
    /// Invalid private key format
    InvalidPrivateKey,
    /// Serialization/deserialization error
    SerializationError,
}

impl core::fmt::Display for IdentityError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::InvalidSignature => write!(f, "invalid signature"),
            Self::InvalidPublicKey => write!(f, "invalid public key"),
            Self::InvalidPrivateKey => write!(f, "invalid private key"),
            Self::SerializationError => write!(f, "serialization error"),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for IdentityError {}

/// A device's cryptographic identity
///
/// Contains an Ed25519 signing key and derives a unique NodeId from it.
/// The private key should be stored securely (platform secure enclave if available).
pub struct DeviceIdentity {
    /// Ed25519 signing key (contains both private and public key)
    signing_key: SigningKey,
}

impl DeviceIdentity {
    /// Generate a new random device identity
    ///
    /// Uses the platform's cryptographically secure random number generator.
    pub fn generate() -> Self {
        let signing_key = SigningKey::generate(&mut OsRng);
        Self { signing_key }
    }

    /// Create identity from existing private key bytes
    ///
    /// # Arguments
    /// * `private_key` - 32-byte Ed25519 private key
    ///
    /// # Returns
    /// * `Ok(DeviceIdentity)` - If key is valid
    /// * `Err(IdentityError)` - If key format is invalid
    pub fn from_private_key(private_key: &[u8; 32]) -> Result<Self, IdentityError> {
        let signing_key = SigningKey::from_bytes(private_key);
        Ok(Self { signing_key })
    }

    /// Get the private key bytes for secure storage
    ///
    /// **Security**: This exposes the private key. Only use for persisting
    /// to secure storage (keychain, secure enclave, encrypted NVS).
    pub fn private_key_bytes(&self) -> [u8; 32] {
        self.signing_key.to_bytes()
    }

    /// Get the public key bytes
    ///
    /// This can be shared freely to allow others to verify signatures.
    pub fn public_key(&self) -> [u8; 32] {
        self.signing_key.verifying_key().to_bytes()
    }

    /// Get the verifying key for signature verification
    pub fn verifying_key(&self) -> VerifyingKey {
        self.signing_key.verifying_key()
    }

    /// Derive the NodeId from the public key
    ///
    /// The NodeId is the first 4 bytes of the BLAKE3 hash of the public key,
    /// interpreted as a little-endian u32. This provides:
    /// - Deterministic derivation (same key = same node_id)
    /// - Collision resistance (BLAKE3 is cryptographically secure)
    /// - Compact representation (4 bytes vs 32 bytes)
    pub fn node_id(&self) -> NodeId {
        let public_key = self.public_key();
        let hash = blake3::hash(&public_key);
        let hash_bytes = hash.as_bytes();

        // First 4 bytes as little-endian u32
        let id = u32::from_le_bytes([hash_bytes[0], hash_bytes[1], hash_bytes[2], hash_bytes[3]]);

        NodeId::new(id)
    }

    /// Sign a message
    ///
    /// # Arguments
    /// * `message` - Arbitrary bytes to sign
    ///
    /// # Returns
    /// 64-byte Ed25519 signature
    pub fn sign(&self, message: &[u8]) -> [u8; 64] {
        let signature = self.signing_key.sign(message);
        signature.to_bytes()
    }

    /// Verify a signature made by this identity
    ///
    /// # Arguments
    /// * `message` - Original message that was signed
    /// * `signature` - 64-byte signature to verify
    ///
    /// # Returns
    /// `true` if signature is valid, `false` otherwise
    pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> bool {
        let sig = Signature::from_bytes(signature);
        self.signing_key
            .verifying_key()
            .verify(message, &sig)
            .is_ok()
    }

    /// Create an identity attestation
    ///
    /// An attestation proves that the holder of this identity controls
    /// the claimed node_id at a specific point in time.
    pub fn create_attestation(&self, timestamp_ms: u64) -> IdentityAttestation {
        let node_id = self.node_id();
        let public_key = self.public_key();

        // Sign: node_id || public_key || timestamp
        let mut message = Vec::with_capacity(4 + 32 + 8);
        message.extend_from_slice(&node_id.as_u32().to_le_bytes());
        message.extend_from_slice(&public_key);
        message.extend_from_slice(&timestamp_ms.to_le_bytes());

        let signature = self.sign(&message);

        IdentityAttestation {
            node_id,
            public_key,
            timestamp_ms,
            signature,
        }
    }
}

impl Clone for DeviceIdentity {
    fn clone(&self) -> Self {
        Self {
            signing_key: SigningKey::from_bytes(&self.signing_key.to_bytes()),
        }
    }
}

impl core::fmt::Debug for DeviceIdentity {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("DeviceIdentity")
            .field("node_id", &self.node_id())
            .field("public_key", &hex_short(&self.public_key()))
            .field("private_key", &"[REDACTED]")
            .finish()
    }
}

/// An identity attestation proving ownership of a node_id
///
/// Used during mesh joining and periodic re-attestation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IdentityAttestation {
    /// The claimed node_id
    pub node_id: NodeId,
    /// Public key (node_id is derived from this)
    pub public_key: [u8; 32],
    /// Timestamp when attestation was created (milliseconds since epoch)
    pub timestamp_ms: u64,
    /// Signature over (node_id || public_key || timestamp)
    pub signature: [u8; 64],
}

impl IdentityAttestation {
    /// Verify this attestation is valid
    ///
    /// Checks:
    /// 1. Signature is valid for the public key
    /// 2. node_id correctly derives from public key
    ///
    /// Does NOT check timestamp freshness (caller should do that).
    pub fn verify(&self) -> bool {
        // Verify node_id derives from public_key
        let hash = blake3::hash(&self.public_key);
        let hash_bytes = hash.as_bytes();
        let expected_id =
            u32::from_le_bytes([hash_bytes[0], hash_bytes[1], hash_bytes[2], hash_bytes[3]]);

        if self.node_id.as_u32() != expected_id {
            return false;
        }

        // Verify signature
        let verifying_key = match VerifyingKey::from_bytes(&self.public_key) {
            Ok(k) => k,
            Err(_) => return false,
        };

        let signature = Signature::from_bytes(&self.signature);

        // Reconstruct signed message
        let mut message = Vec::with_capacity(4 + 32 + 8);
        message.extend_from_slice(&self.node_id.as_u32().to_le_bytes());
        message.extend_from_slice(&self.public_key);
        message.extend_from_slice(&self.timestamp_ms.to_le_bytes());

        verifying_key.verify(&message, &signature).is_ok()
    }

    /// Encode attestation to bytes for wire transmission
    ///
    /// Format: node_id (4) || public_key (32) || timestamp (8) || signature (64) = 108 bytes
    pub fn encode(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(108);
        buf.extend_from_slice(&self.node_id.as_u32().to_le_bytes());
        buf.extend_from_slice(&self.public_key);
        buf.extend_from_slice(&self.timestamp_ms.to_le_bytes());
        buf.extend_from_slice(&self.signature);
        buf
    }

    /// Decode attestation from bytes
    ///
    /// Returns None if data is not exactly 108 bytes.
    pub fn decode(data: &[u8]) -> Option<Self> {
        if data.len() != 108 {
            return None;
        }

        let node_id = NodeId::new(u32::from_le_bytes([data[0], data[1], data[2], data[3]]));

        let mut public_key = [0u8; 32];
        public_key.copy_from_slice(&data[4..36]);

        let timestamp_ms = u64::from_le_bytes([
            data[36], data[37], data[38], data[39], data[40], data[41], data[42], data[43],
        ]);

        let mut signature = [0u8; 64];
        signature.copy_from_slice(&data[44..108]);

        Some(Self {
            node_id,
            public_key,
            timestamp_ms,
            signature,
        })
    }
}

/// Verify a signature from a known public key
///
/// Utility function for verifying signatures without a full DeviceIdentity.
pub fn verify_signature(public_key: &[u8; 32], message: &[u8], signature: &[u8; 64]) -> bool {
    let verifying_key = match VerifyingKey::from_bytes(public_key) {
        Ok(k) => k,
        Err(_) => return false,
    };

    let sig = Signature::from_bytes(signature);

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

/// Derive NodeId from a public key
///
/// Utility function for deriving node_id without a full DeviceIdentity.
pub fn node_id_from_public_key(public_key: &[u8; 32]) -> NodeId {
    let hash = blake3::hash(public_key);
    let hash_bytes = hash.as_bytes();

    let id = u32::from_le_bytes([hash_bytes[0], hash_bytes[1], hash_bytes[2], hash_bytes[3]]);

    NodeId::new(id)
}

// Helper for debug output
fn hex_short(bytes: &[u8]) -> String {
    if bytes.len() <= 4 {
        hex::encode(bytes)
    } else {
        format!(
            "{}..{}",
            hex::encode(&bytes[..2]),
            hex::encode(&bytes[bytes.len() - 2..])
        )
    }
}

// Need hex for debug output
mod hex {
    pub fn encode(bytes: &[u8]) -> String {
        bytes.iter().map(|b| format!("{:02x}", b)).collect()
    }
}

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

    #[test]
    fn test_generate_identity() {
        let identity = DeviceIdentity::generate();

        // node_id should be non-zero (extremely unlikely to be zero)
        assert_ne!(identity.node_id().as_u32(), 0);

        // Public key should be 32 bytes
        assert_eq!(identity.public_key().len(), 32);
    }

    #[test]
    fn test_identity_from_private_key() {
        let identity1 = DeviceIdentity::generate();
        let private_key = identity1.private_key_bytes();

        let identity2 = DeviceIdentity::from_private_key(&private_key).unwrap();

        // Same private key = same public key = same node_id
        assert_eq!(identity1.public_key(), identity2.public_key());
        assert_eq!(identity1.node_id(), identity2.node_id());
    }

    #[test]
    fn test_node_id_deterministic() {
        let identity = DeviceIdentity::generate();

        // Multiple calls return same node_id
        let id1 = identity.node_id();
        let id2 = identity.node_id();
        assert_eq!(id1, id2);
    }

    #[test]
    fn test_different_identities_different_node_ids() {
        let identity1 = DeviceIdentity::generate();
        let identity2 = DeviceIdentity::generate();

        // Different identities should have different node_ids
        // (collision probability is ~1 in 4 billion)
        assert_ne!(identity1.node_id(), identity2.node_id());
    }

    #[test]
    fn test_sign_verify() {
        let identity = DeviceIdentity::generate();
        let message = b"Test message for signing";

        let signature = identity.sign(message);
        assert!(identity.verify(message, &signature));
    }

    #[test]
    fn test_verify_wrong_message() {
        let identity = DeviceIdentity::generate();
        let message = b"Original message";
        let wrong_message = b"Wrong message";

        let signature = identity.sign(message);
        assert!(!identity.verify(wrong_message, &signature));
    }

    #[test]
    fn test_verify_wrong_key() {
        let identity1 = DeviceIdentity::generate();
        let identity2 = DeviceIdentity::generate();
        let message = b"Test message";

        let signature = identity1.sign(message);
        assert!(!identity2.verify(message, &signature));
    }

    #[test]
    fn test_attestation_create_verify() {
        let identity = DeviceIdentity::generate();
        let timestamp = 1705680000000u64; // Some timestamp

        let attestation = identity.create_attestation(timestamp);

        assert!(attestation.verify());
        assert_eq!(attestation.node_id, identity.node_id());
        assert_eq!(attestation.public_key, identity.public_key());
        assert_eq!(attestation.timestamp_ms, timestamp);
    }

    #[test]
    fn test_attestation_encode_decode() {
        let identity = DeviceIdentity::generate();
        let attestation = identity.create_attestation(1705680000000);

        let encoded = attestation.encode();
        assert_eq!(encoded.len(), 108);

        let decoded = IdentityAttestation::decode(&encoded).unwrap();
        assert_eq!(decoded, attestation);
        assert!(decoded.verify());
    }

    #[test]
    fn test_attestation_tampered() {
        let identity = DeviceIdentity::generate();
        let mut attestation = identity.create_attestation(1705680000000);

        // Tamper with timestamp
        attestation.timestamp_ms += 1;

        // Verification should fail
        assert!(!attestation.verify());
    }

    #[test]
    fn test_node_id_from_public_key() {
        let identity = DeviceIdentity::generate();
        let public_key = identity.public_key();

        let derived_id = node_id_from_public_key(&public_key);
        assert_eq!(derived_id, identity.node_id());
    }

    #[test]
    fn test_verify_signature_utility() {
        let identity = DeviceIdentity::generate();
        let message = b"Test with utility function";

        let signature = identity.sign(message);
        let public_key = identity.public_key();

        assert!(verify_signature(&public_key, message, &signature));
    }

    #[test]
    fn test_identity_clone() {
        let identity1 = DeviceIdentity::generate();
        let identity2 = identity1.clone();

        assert_eq!(identity1.public_key(), identity2.public_key());
        assert_eq!(identity1.node_id(), identity2.node_id());

        // Both can sign and verify each other
        let message = b"Clone test";
        let sig1 = identity1.sign(message);
        let sig2 = identity2.sign(message);

        assert!(identity1.verify(message, &sig2));
        assert!(identity2.verify(message, &sig1));
    }

    #[test]
    fn test_debug_redacts_private_key() {
        let identity = DeviceIdentity::generate();
        let debug_str = format!("{:?}", identity);

        assert!(debug_str.contains("REDACTED"));
        assert!(debug_str.contains("node_id"));
    }
}