Skip to main content

vector_core/crypto/
batch_verify.rs

1//! Event signatures checked many at a time.
2//!
3//! One BIP-340 batch equation (nostr-verify) accepts a whole slice of signatures for much
4//! less than one libsecp256k1 verification each: 1.7x at 16 signatures, 2.2x at 64 on an
5//! M4. Parsed keys are cached per thread, so a sender seen before skips its square root.
6//! A slice that fails is narrowed down and its signatures checked one at a time by
7//! libsecp256k1, so every `false` is the individual verifier's verdict.
8//!
9//! Only signatures: callers check the event id first, as `Event::verify` does.
10
11use nostr_sdk::prelude::Event;
12use std::cell::RefCell;
13
14thread_local! {
15    static VERIFIER: RefCell<nostr_verify::Verifier> = RefCell::new(nostr_verify::Verifier::new());
16}
17
18/// Whether each event's signature is valid for its id and author, in order.
19pub fn signatures(events: &[&Event]) -> Vec<bool> {
20    // Too few to batch (a live DM): rust-nostr's own check, exactly as before batching.
21    if events.len() < nostr_verify::MIN_BATCH {
22        return events.iter().map(|e| e.verify_signature()).collect();
23    }
24    let refs: Vec<nostr_verify::SigRef<'_>> = events
25        .iter()
26        .map(|e| nostr_verify::SigRef { pubkey: e.pubkey.as_bytes(), msg: e.id.as_bytes(), sig: e.sig.as_bytes() })
27        .collect();
28    let mut ok = Vec::with_capacity(refs.len());
29    VERIFIER.with_borrow_mut(|v| v.verify_batch(&refs, &mut ok));
30    ok
31}
32
33/// Whether one event's signature is valid for its id and author: `Event::verify_signature`,
34/// with the author's parsed key from this thread's cache.
35pub fn signature(e: &Event) -> bool {
36    let sig = nostr_verify::SigRef { pubkey: e.pubkey.as_bytes(), msg: e.id.as_bytes(), sig: e.sig.as_bytes() };
37    VERIFIER.with_borrow_mut(|v| v.verify_one(&sig))
38}
39
40/// This thread's counters: batches and how many held, key-cache hits and misses.
41pub fn stats() -> nostr_verify::Stats {
42    VERIFIER.with_borrow(|v| v.stats())
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48    use nostr_sdk::prelude::*;
49
50    fn note(keys: &Keys, i: usize) -> Event {
51        EventBuilder::new(Kind::TextNote, format!("note {i}")).finalize(keys).unwrap()
52    }
53
54    #[test]
55    fn verdicts_match_each_event_verified_alone() {
56        let keys: Vec<Keys> = (0..3).map(|_| Keys::generate()).collect();
57        let mut events: Vec<Event> = (0..40).map(|i| note(&keys[i % 3], i)).collect();
58        // Signatures moved onto other events: valid signatures, wrong messages.
59        for i in [5, 17, 33] {
60            events[i].sig = events[i + 1].sig;
61        }
62        let refs: Vec<&Event> = events.iter().collect();
63        let ours = signatures(&refs);
64        let theirs: Vec<bool> = events.iter().map(Event::verify_signature).collect();
65        assert_eq!(ours, theirs);
66        assert_eq!(events.iter().map(signature).collect::<Vec<_>>(), theirs, "one at a time too");
67        assert_eq!(ours.iter().filter(|ok| !**ok).count(), 3);
68        assert!(signatures(&[]).is_empty());
69    }
70}