Skip to main content

bench_ecrecover/
lib.rs

1//! secp256k1 ecrecover benchmark — runs a single ECDSA public key recovery.
2
3#![cfg_attr(target_os = "none", no_std)]
4
5use nub_rt as _;
6
7// ---------------------------------------------------------------------------
8// Bump allocator — k256 needs alloc for internal operations.
9// Single ecrecover uses bounded memory; no deallocation needed.
10// ---------------------------------------------------------------------------
11
12#[cfg(target_os = "none")]
13extern crate alloc;
14
15// ---------------------------------------------------------------------------
16// Test vector (generated from a known private key, verified on host)
17// ---------------------------------------------------------------------------
18
19const MSG_HASH: [u8; 32] = [
20    0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
21    0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
22];
23
24const SIGNATURE: [u8; 64] = [
25    0xff, 0x65, 0x1c, 0x65, 0xee, 0xde, 0xd4, 0x63, 0x83, 0xa4, 0xbd, 0xcd, 0x91, 0x70, 0xff, 0x65,
26    0x9a, 0x4f, 0x61, 0x7b, 0xb6, 0x58, 0xa4, 0x6d, 0xd4, 0x56, 0xc5, 0x1e, 0xc8, 0xcc, 0x21, 0x1a,
27    0x7d, 0xc4, 0xde, 0x91, 0xd0, 0xc8, 0x47, 0xbf, 0x5d, 0xef, 0x99, 0x5b, 0xd0, 0x43, 0x65, 0x81,
28    0x36, 0xfe, 0x21, 0x35, 0xaf, 0xe6, 0x92, 0x82, 0xf7, 0xde, 0x87, 0x39, 0x90, 0xda, 0xcb, 0x77,
29];
30
31const RECOVERY_ID: u8 = 1;
32
33const EXPECTED_PUBKEY: [u8; 33] = [
34    0x02, 0x84, 0xbf, 0x75, 0x62, 0x26, 0x2b, 0xbd, 0x69, 0x40, 0x08, 0x57, 0x48, 0xf3, 0xbe, 0x6a,
35    0xfa, 0x52, 0xae, 0x31, 0x71, 0x55, 0x18, 0x1e, 0xce, 0x31, 0xb6, 0x63, 0x51, 0xcc, 0xff, 0xa4,
36    0xb0,
37];
38
39/// Perform ecrecover: recover the public key from a signature + message hash.
40/// Returns 1 if the recovered key matches the expected public key, 0 otherwise.
41pub fn ecrecover_bench() -> u32 {
42    let sig = match k256::ecdsa::Signature::from_slice(&SIGNATURE) {
43        Ok(s) => s,
44        Err(_) => return 0,
45    };
46    let recid = k256::ecdsa::RecoveryId::new(RECOVERY_ID & 1 != 0, RECOVERY_ID & 2 != 0);
47
48    match k256::ecdsa::VerifyingKey::recover_from_prehash(&MSG_HASH, &sig, recid) {
49        Ok(key) => {
50            let pubkey = key.to_encoded_point(true);
51            let pubkey_bytes = pubkey.as_bytes();
52            if pubkey_bytes.len() != EXPECTED_PUBKEY.len() {
53                return 0;
54            }
55            let mut i = 0;
56            while i < EXPECTED_PUBKEY.len() {
57                if pubkey_bytes[i] != EXPECTED_PUBKEY[i] {
58                    return 0;
59                }
60                i += 1;
61            }
62            1
63        }
64        Err(_) => 0,
65    }
66}