polar-bear-biochip 0.1.1

Bio-chip intelligence framework: multi-sensor EEG+motion fusion + rig-core LLM orchestration + ECDSA-signed data provenance
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
//! # ECDSA secp256k1 Provenance Layer
//!
//! ## Algorithm walkthrough (forward-engineered from FIPS 186-5 / SEC 1 v2.0)
//!
//! ### Domain parameters (secp256k1)
//! - Prime field:  p = 2²⁵⁶ − 2³² − 977
//! - Curve:        y² ≡ x³ + 7  (mod p)   ← Weierstrass form
//! - Base point:   G  (compressed, 33 bytes on-chain)
//! - Order:        n  (256-bit prime - number of points in the group)
//! - Cofactor:     h = 1
//!
//! ### Provenance signing (payload bytes P, private key d)
//! 1. canonical_json = serde_json::to_string(InferenceResult)
//! 2. e = SHA-256(canonical_json)          ← payload hash
//! 3. Ephemeral k sampled from CSPRNG
//! 4. R = k·G;  r = R.x mod n
//! 5. s = k⁻¹ · (e + r·d) mod n
//! 6. Signature = (r, s) - 64 bytes compact r‖s
//!
//! ### Offline verification
//! 1. Recompute e = SHA-256(canonical_json)
//! 2. w = s⁻¹ mod n
//! 3. u₁ = e·w mod n;  u₂ = r·w mod n
//! 4. X = u₁·G + u₂·Q
//! 5. Valid iff X.x mod n == r
//!
//! ### Why secp256k1?
//! - Bitcoin / Ethereum / Solana native curve - same key material, zero extra dependencies
//! - 256-bit security at ~128-bit classical security level
//! - 64-byte compact signatures (low overhead in JSON provenance records)

/// A wrapper around `k256`'s ECDSA signing functionality.
use anyhow::{Result, anyhow};
use chrono::Utc;
use k256::{
    EncodedPoint,
    ecdsa::{
        Signature, SigningKey, VerifyingKey,
        signature::{Signer, Verifier},
    },
};
use rand_core::OsRng;
use sha2::{Digest, Sha256};

use crate::types::{InferenceResult, SignedOutput};

// ── EcdsaSigner ───────────────────────────────────────────────────────────────

/// An ECDSA signer backed by a secp256k1 private key.
///
/// # Security
/// The private key is zeroed on drop via k256's `ZeroizeOnDrop`.
/// Never serialise the private scalar to logs, JSON responses, or env vars.
///
/// This struct provides a convenient interface for signing ECDSA signatures using a secp256k1
/// private key.
pub struct EcdsaSigner {
    signing_key: SigningKey,
}

/// A convenience method for generating a fresh ephemeral keypair using a cryptographically secure
/// RNG.
///
/// This method is intended for use in testing and development only.
/// In production, use [`EcdsaSigner::from_bytes`] with a trusted private key.
///
/// # Returns
/// A new [`EcdsaSigner`] instance with a fresh ephemeral keypair.
impl EcdsaSigner {
    /// Generate a fresh ephemeral keypair using a cryptographically secure RNG.
    ///
    /// # Returns
    /// A new [`EcdsaSigner`] instance with a fresh ephemeral keypair.
    #[must_use]
    pub fn generate() -> Self {
        Self {
            signing_key: SigningKey::random(&mut OsRng),
        }
    }

    /// Restore a signer from a 32-byte big-endian private scalar.
    ///
    /// # Errors
    /// Returns an error if `bytes` is not a valid scalar in \[1, n-1\].
    ///
    /// # Returns
    /// A new [`EcdsaSigner`] instance with the restored private key.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        let signing_key = SigningKey::from_slice(bytes)
            .map_err(|e| anyhow!("invalid ECDSA private key bytes: {e}"))?;
        Ok(Self { signing_key })
    }

    /// Restore a signer from a lowercase hex-encoded private scalar (64 chars).
    ///
    /// # Errors
    /// Returns an error if `hex_str` is not a valid hex-encoded scalar in \[1, n-1\].
    ///
    /// # Returns
    /// A new [`EcdsaSigner`] instance with the restored private key.
    pub fn from_hex(hex_str: &str) -> Result<Self> {
        let bytes = hex::decode(hex_str).map_err(|e| anyhow!("hex decode: {e}"))?;
        Self::from_bytes(&bytes)
    }

    /// Export the private key as 32 raw bytes.  **Never** log or transmit this.
    ///
    /// # Returns
    /// The private key as a 32-byte array.
    #[must_use]
    pub fn private_key_bytes(&self) -> [u8; 32] {
        self.signing_key.to_bytes().into()
    }

    /// Export the private key as a lowercase hex string (64 chars).
    #[must_use]
    pub fn private_key_hex(&self) -> String {
        hex::encode(self.private_key_bytes())
    }

    /// Export the **uncompressed** 65-byte SEC 1 public key (04‖x‖y).
    ///
    /// Used as the embedded public key in [`SignedOutput`] for offline verification.
    ///
    /// # Returns
    /// The public key as a lowercase hex string (65 chars).
    #[must_use]
    pub fn public_key_hex(&self) -> String {
        let vk = VerifyingKey::from(&self.signing_key);
        hex::encode(vk.to_encoded_point(false).as_bytes())
    }

    /// Export the **compressed** 33-byte SEC 1 public key.
    ///
    /// # Returns
    /// The public key as a lowercase hex string (33 chars).
    #[must_use]
    pub fn verifying_key_hex(&self) -> String {
        let vk = VerifyingKey::from(&self.signing_key);
        hex::encode(vk.to_encoded_point(true).as_bytes())
    }

    // ── Signing ───────────────────────────────────────────────────────────────

    /// Sign an [`InferenceResult`], returning a tamper-evident [`SignedOutput`].
    ///
    /// ## Steps
    /// 1. Serialise `result` to canonical JSON.
    /// 2. SHA-256 hash the bytes.
    /// 3. ECDSA-sign the hash (secp256k1 / SHA-256).
    /// 4. Embed signature + uncompressed public key in [`SignedOutput`].
    ///
    /// # Errors
    /// Returns an error if JSON serialisation fails.
    ///
    /// # Returns
    /// A new [`SignedOutput`] instance with the signed result and public key.
    pub fn sign_result(&self, result: &InferenceResult) -> Result<SignedOutput> {
        let payload_json =
            serde_json::to_string(result).map_err(|e| anyhow!("JSON serialise: {e}"))?;

        let hash_bytes = Sha256::digest(payload_json.as_bytes());
        let signature: Signature = self.signing_key.sign(&hash_bytes);
        let signature_hex = hex::encode(signature.to_bytes());
        let payload_hash_hex = hex::encode(hash_bytes);


        Ok(SignedOutput {
            inference_result: result.clone(),
            payload_hash_hex,
            signature_hex,
            public_key_hex: self.public_key_hex(),
            signed_at: Utc::now(),
        })
    }

    /// Verify a `(message, signature_hex)` pair against this signer's public key.
    ///
    /// # Errors
    /// Returns an error if the hex is malformed or the signature bytes are invalid.
    ///
    /// # Returns
    /// `true` if the signature is valid, `false` otherwise.
    pub fn verify(&self, message: &[u8], signature_hex: &str) -> Result<bool> {
        EcdsaVerifier::from_hex(&self.public_key_hex())?.verify(message, signature_hex)
    }

    /// Verify a [`SignedOutput`] entirely from its embedded fields.
    ///
    /// Returns `true` iff the ECDSA signature is cryptographically valid for
    /// the canonical JSON of `signed.inference_result`.
    ///
    /// This is a **pure function** - no private key material is required.
    ///
    /// # Errors
    /// Returns an error on hex decode failure, invalid key material, or
    /// JSON re-serialisation failure.
    ///
    /// # Returns
    /// `true` if the signature is valid, `false` otherwise.
    pub fn verify_signed(signed: &SignedOutput) -> Result<bool> {
        let payload_json = serde_json::to_string(&signed.inference_result)
            .map_err(|e| anyhow!("re-serialise: {e}"))?;
        let hash_bytes = Sha256::digest(payload_json.as_bytes());

        EcdsaVerifier::from_hex(&signed.public_key_hex)?.verify(&hash_bytes, &signed.signature_hex)
    }
}

/// Standalone public-key verifier - no private key required.
///
/// Useful for offline audit tools that receive a [`SignedOutput`] JSON and
/// need to validate it without access to the original signing process.
pub struct EcdsaVerifier {
    verifying_key: VerifyingKey,
}

/// Standalone public-key verifier - no private key required.
impl EcdsaVerifier {
    /// Construct from a compressed (33-byte / 66-char hex) or
    /// uncompressed (65-byte / 130-char hex) SEC 1 public key.
    ///
    /// # Errors
    /// Returns an error if the hex is malformed or the point is not on secp256k1.
    ///
    /// # Returns
    /// A new [`EcdsaVerifier`] instance.
    pub fn from_hex(hex_str: &str) -> Result<Self> {
        let bytes = hex::decode(hex_str).map_err(|e| anyhow!("hex decode: {e}"))?;
        let point =
            EncodedPoint::from_bytes(bytes).map_err(|e| anyhow!("invalid SEC 1 point: {e}"))?;
        let verifying_key = VerifyingKey::from_encoded_point(&point)
            .map_err(|e| anyhow!("point not on curve: {e}"))?;
        Ok(Self { verifying_key })
    }

    /// Verify that `signature_hex` is a valid ECDSA signature over `message`.
    ///
    /// # Errors
    /// Returns an error if the hex or signature bytes are malformed.
    ///
    /// # Returns
    /// `true` if the signature is valid, `false` otherwise.
    pub fn verify(&self, message: &[u8], signature_hex: &str) -> Result<bool> {
        let sig_bytes = hex::decode(signature_hex).map_err(|e| anyhow!("sig hex decode: {e}"))?;
        let signature = Signature::from_slice(&sig_bytes)
            .map_err(|e| anyhow!("invalid signature bytes: {e}"))?;
        Ok(self.verifying_key.verify(message, &signature).is_ok())
    }
}

/// Unit tests for [`EcdsaSigner`] and [`EcdsaVerifier`].
#[cfg(test)]
mod tests {
    use chrono::Utc;

    use super::*;
    use crate::{
        sensors::fusion::SensorFusion,
        types::{AlertLevel, InferenceResult},
    };

    /// Creates a dummy [`InferenceResult`] for testing purposes.
    ///
    /// # Returns
    /// A new [`InferenceResult`] instance with a dummy timestamp and sequence ID.
    fn dummy_result(seq: u64) -> InferenceResult {
        let mut fusion = SensorFusion::new();
        InferenceResult {
            timestamp: Utc::now(),
            sequence_id: seq,
            fused_reading: fusion.sample(seq),
            cognitive_state: "test state".to_string(),
            recommendations: vec!["rec a".to_string(), "rec b".to_string()],
            alert_level: AlertLevel::Normal,
            raw_llm_response:
                r#"{"cognitive_state":"test","alert_level":"Normal","recommendations":[]}"#
                    .to_string(),
        }
    }

    /// Verifies that a valid signature can be verified by the signer's public key.
    ///
    /// # Assertions
    /// - The signature should be verified successfully.
    #[test]
    #[allow(clippy::similar_names)] // `signer` / `signed` are the canonical names here
    fn sign_verify_roundtrip() {
        let signer = EcdsaSigner::generate();
        let result = dummy_result(1);
        let signed = signer.sign_result(&result).unwrap();

        assert!(EcdsaSigner::verify_signed(&signed).unwrap());
    }

    /// Verifies that a tampered cognitive state fails verification.
    ///
    /// # Assertions
    /// - The signature should not be verified successfully.
    #[test]
    #[allow(clippy::similar_names)]
    fn tampered_cognitive_state_fails_verification() {
        let signer = EcdsaSigner::generate();
        let mut signed = signer.sign_result(&dummy_result(2)).unwrap();

        signed.inference_result.cognitive_state = "tampered!".to_string();
        assert!(!EcdsaSigner::verify_signed(&signed).unwrap());
    }

    /// Verifies that a tampered signature fails verification.
    ///
    /// # Assertions
    /// - The signature should not be verified successfully.
    #[test]
    #[allow(clippy::similar_names)]
    fn tampered_signature_fails_verification() {
        let signer = EcdsaSigner::generate();
        let mut signed = signer.sign_result(&dummy_result(3)).unwrap();

        // Flip the first byte of the signature hex.
        let mut sig = signed.signature_hex.clone();
        let flipped = if sig.starts_with('a') { "b" } else { "a" };
        sig.replace_range(0..1, flipped);
        signed.signature_hex = sig;

        assert!(
            EcdsaSigner::verify_signed(&signed).is_err()
                || !EcdsaSigner::verify_signed(&signed).unwrap()
        );
    }

    /// Verifies that a tampered cognitive state fails verification.
    ///
    /// # Assertions
    /// - The signature should not be verified successfully.
    #[test]
    fn from_hex_roundtrip_preserves_public_key() {
        let original = EcdsaSigner::generate();
        let hex = original.private_key_hex();
        let restored = EcdsaSigner::from_hex(&hex).unwrap();
        assert_eq!(original.public_key_hex(), restored.public_key_hex());
    }

    /// Verifies that a standalone verifier accepts a valid signature.
    ///
    /// # Assertions
    /// - The signature should be verified successfully.
    #[test]
    #[allow(clippy::similar_names)]
    fn standalone_verifier_accepts_valid_signature() {
        let signer = EcdsaSigner::generate();
        let result = dummy_result(4);
        let signed = signer.sign_result(&result).unwrap();

        let verifier = EcdsaVerifier::from_hex(&signed.public_key_hex).unwrap();
        let hash = Sha256::digest(
            serde_json::to_string(&signed.inference_result)
                .unwrap()
                .as_bytes(),
        );
        assert!(verifier.verify(&hash, &signed.signature_hex).unwrap());
    }

    /// Verifies that a standalone verifier rejects an invalid signature.
    ///
    /// # Assertions
    /// - The signature should not be verified successfully.
    #[test]
    fn cross_key_verification_fails() {
        let signer_a = EcdsaSigner::generate();
        let signer_b = EcdsaSigner::generate();
        let signed = signer_a.sign_result(&dummy_result(5)).unwrap();

        let verifier_b = EcdsaVerifier::from_hex(&signer_b.public_key_hex()).unwrap();
        let hash = Sha256::digest(
            serde_json::to_string(&signed.inference_result)
                .unwrap()
                .as_bytes(),
        );
        assert!(!verifier_b.verify(&hash, &signed.signature_hex).unwrap());
    }

    /// Verifies that the public key hex string is 130 characters (uncompressed).
    ///
    /// # Assertions
    /// - The public key hex string should be 130 characters long.
    #[test]
    fn public_key_hex_is_130_chars_uncompressed() {
        let signer = EcdsaSigner::generate();
        // Uncompressed SEC 1: 04 || x (32 B) || y (32 B) = 65 bytes = 130 hex chars.
        assert_eq!(signer.public_key_hex().len(), 130);
    }

    /// Verifies that the signature hex string is 128 characters.
    ///
    /// # Assertions
    /// - The signature hex string should be 128 characters long.
    #[test]
    #[allow(clippy::similar_names)]
    fn signature_hex_is_128_chars() {
        let signer = EcdsaSigner::generate();
        let result = dummy_result(6);
        let signed = signer.sign_result(&result).unwrap();
        // Compact r‖s: 64 bytes = 128 hex chars.
        assert_eq!(signed.signature_hex.len(), 128);
    }
}