//! ECDSA P-256 demonstration: key generation, RFC 6979 deterministic
//! signing, and verification.
//!
//! ```sh
//! cargo run -p arcana --release --example ecdsa_demo
//! ```

use arcana::ecc::curves::{CryptoRng, Curve, P256};
use arcana::hash::sha256::Sha256;

struct DemoRng(u64);

impl CryptoRng for DemoRng {
    fn fill_bytes(&mut self, dest: &mut [u8]) {
        for b in dest.iter_mut() {
            self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1);
            *b = (self.0 >> 33) as u8;
        }
    }
}

fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{:02x}", b)).collect()
}

fn main() {
    let mut rng = DemoRng(0xcafebabe);

    // Key generation
    let (pk, sk) = P256::keygen(&mut rng);
    println!("ECDSA P-256 keygen:");
    println!("  pk ({}B): {}...", pk.bytes.len(), hex(&pk.bytes[..8]));
    println!("  sk ({}B): {}...", sk.bytes.len(), hex(&sk.bytes[..8]));

    // Sign a message (hash + deterministic RFC 6979)
    let msg = b"ECDSA P-256 deterministic signature demo";
    let sig = P256::sign_rfc6979_msg::<Sha256>(&sk, msg);
    println!("\nRFC 6979 sign:");
    println!("  r: {}", hex(&sig.r));
    println!("  s: {}", hex(&sig.s));

    // Verify
    let ok = P256::verify_msg::<Sha256>(&pk, msg, &sig);
    assert!(ok, "signature must verify");
    println!("  verify: OK");

    // Tamper test
    let mut sig_bad = sig.clone();
    sig_bad.r[0] ^= 0xFF;
    assert!(!P256::verify_msg::<Sha256>(&pk, msg, &sig_bad));
    println!("  tamper: correctly rejected");

    println!("\nAll ECDSA demos passed.");
}
