hashsigs-rs 0.2.1-rc2

Hash-based signatures core library with WOTS+ and SHRINCS primitives
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
// Copyright (C) 2026 quip.network
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Public hybrid SHRINCS verifier surface.
//!
//! Thin, stateless facade (`ShrincsVerifier`) over `dispatch`: every method
//! forwards directly, giving external callers (`wasm`, the `solana`
//! workspace member) one struct-shaped entry point instead of free
//! functions.

use crate::hash::keccak_packed;
use crate::sphincs_plus_c::verifier::SphincsPlusCVerifier;
use crate::verifier::VerifyOutcome;
// Wire types/constants live in dedicated shrincs submodules after the
// restructure. Re-export them here so `hashsigs_rs::shrincs::verifier::*`
// still glob-imports (main used `pub use self::shrincs_verifier_types::*`).
// Not every symbol keeps its historical name: the public key type was
// renamed from `StatefulPublicKey` to `PublicKey` (disambiguated by the
// `shrincs` module path instead), and there is no `StatefulPublicKey` alias.
pub use super::action_context::ActionContext;
pub use super::key::PublicKey;
pub use super::signature::Signature as StatefulSignature;
pub use super::uxmss::STATEFUL_PUBLIC_KEY_BYTES;
pub use crate::hash::suite::HASH_SUITE_KECCAK_256;
pub use crate::hash::{ADDRESS_TYPE_FORS_TREE, ADDRESS_TYPE_TREE, ADDRESS_TYPE_WOTS_HASH};
pub use crate::HASH_LEN;
// SHRINCS genuinely has a stateless signing path, so this is a legitimate
// semantic re-export (not a component shim) — see `shrincs::mod`'s matching
// re-export for the rationale.
pub use crate::sphincs_plus_c::Signature as StatelessSignature;
// Profile parameter tuple also lived in main's shrincs_verifier_types (via
// `pub use profile::*`); re-export from the current profiles module.
use super::dispatch as core_shrincs;
use super::dispatch::{stateful_action_message_hash, stateless_action_message_hash};
use super::key::Commitment;
use super::signature::{decode_stateful_envelope, decode_stateless_envelope};
#[cfg(test)]
use super::signature::{encode_stateful_envelope, encode_stateless_envelope};
pub use crate::profiles::{
    FORS_TREE_HEIGHT, HASH_TRUNC_LEN, HYPERTREE_HEIGHT, NUM_FORS_TREES, NUM_HYPERTREE_LAYERS,
    NUM_WOTS_CHAINS, PROFILE_NAME, STATELESS_SIGNATURE_LIMIT, WOTS_CHAIN_LEN,
};

/// Stateless hybrid SHRINCS verifier facade.
///
/// # Examples
///
/// ```rust,no_run
/// # fn main() -> Result<(), ()> {
/// use hashsigs_rs::shrincs::{sign, ShrincsSigner, ShrincsVerifier, VerifierInterface};
///
/// let (mut keys, public_key) = ShrincsSigner::keygen(b"verify-seed", 4).ok_or(())?;
/// let hash = [9u8; 32];
/// let envelope = sign(&mut keys, &hash).ok_or(())?;
/// let ok = ShrincsVerifier::new().verify(
///     &public_key.public_key_commitment,
///     &hash,
///     &envelope,
/// );
/// assert_eq!(ok, hashsigs_rs::VerifyOutcome::Valid);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy)]
pub struct ShrincsVerifier;

impl Default for ShrincsVerifier {
    fn default() -> Self {
        Self::new()
    }
}

impl ShrincsVerifier {
    /// Construct a verifier handle. The type carries no state; the handle
    /// exists so both schemes share the `VerifierInterface` shape.
    pub fn new() -> Self {
        Self
    }

    /// Verify a stateful (UXMSS fast-path) SHRINCS signature: recompute the
    /// action message from `expected_public_key_commitment` and `context`,
    /// then check `signature` against it and `public_key`. Returns `true` only
    /// for a valid signature bound to that exact context.
    pub fn verify_stateful(
        &self,
        expected_public_key_commitment: [u8; HASH_LEN],
        public_key: &PublicKey,
        context: &ActionContext,
        signature: &StatefulSignature,
    ) -> bool {
        core_shrincs::verify_stateful(
            expected_public_key_commitment,
            public_key,
            context,
            signature,
        )
    }

    /// Verify a stateless (SPHINCS+C) SHRINCS signature over the action
    /// message derived from `expected_public_key_commitment` and `context`.
    /// Returns `true` only for a valid signature bound to that exact context.
    pub fn verify_stateless(
        &self,
        expected_public_key_commitment: [u8; HASH_LEN],
        public_key: &PublicKey,
        context: &ActionContext,
        signature: &StatelessSignature,
    ) -> bool {
        core_shrincs::verify_stateless(
            expected_public_key_commitment,
            public_key,
            context,
            signature,
        )
    }

    #[cfg(test)]
    pub(crate) fn verify_stateful_unsafe_raw(
        &self,
        expected_public_key_commitment: [u8; HASH_LEN],
        public_key: &PublicKey,
        message: &[u8],
        signature: &StatefulSignature,
    ) -> bool {
        core_shrincs::verify_stateful_unsafe_raw(
            expected_public_key_commitment,
            public_key,
            message,
            signature,
        )
    }

    #[cfg(test)]
    pub(crate) fn verify_stateless_unsafe_raw(
        &self,
        expected_public_key_commitment: [u8; HASH_LEN],
        public_key: &PublicKey,
        message: &[u8],
        signature: &StatelessSignature,
    ) -> bool {
        core_shrincs::verify_stateless_unsafe_raw(
            expected_public_key_commitment,
            public_key,
            message,
            signature,
        )
    }

    /// The 32-byte message a stateful signature must sign: binds the public-key
    /// commitment to the action `context` (nonce, key version, domain,
    /// action type, payload hash).
    pub fn stateful_action_message_hash(
        &self,
        expected_public_key_commitment: [u8; HASH_LEN],
        context: &ActionContext,
    ) -> [u8; HASH_LEN] {
        stateful_action_message_hash(expected_public_key_commitment, context)
    }

    /// The 32-byte message a stateless signature must sign: the same
    /// commitment-to-`context` binding under the stateless domain tag.
    pub fn stateless_action_message_hash(
        &self,
        expected_public_key_commitment: [u8; HASH_LEN],
        context: &ActionContext,
    ) -> [u8; HASH_LEN] {
        stateless_action_message_hash(expected_public_key_commitment, context)
    }

    /// Commitment binding an encoded stateful public key with a stateless
    /// `pk_seed`/`hypertree_root` pair, mirroring
    /// `SHRINCS.publicKeyCommitmentFromParts`. Exposed for callers that need
    /// to derive a candidate bundle's commitment before it is installed.
    pub fn public_key_commitment(
        &self,
        stateful_public_key: &[u8],
        pk_seed: [u8; HASH_LEN],
        hypertree_root: [u8; HASH_LEN],
    ) -> [u8; HASH_LEN] {
        *Commitment::of(stateful_public_key, &pk_seed, &hypertree_root).as_bytes()
    }
}

impl ShrincsVerifier {
    /// `keccak256("quip.shrincs-verifier.v1")`. Mirrors
    /// `SHRINCSVerifier.VERSION_TAG`: names this verifier's key/envelope
    /// format family, not the compiled parameter profile.
    pub fn version_tag() -> [u8; HASH_LEN] {
        keccak_packed(&[b"quip.shrincs-verifier.v1"])
    }
}

/// SHRINCS-specific extension of [`crate::verifier::VerifierInterface`]:
/// the stateless recovery path (ERC-7913's SPHINCS+C-delegated verify),
/// which has no equivalent on the generic stateful interface.
pub trait ShrincsVerifierExt {
    /// Stateless verify through the verifier interface shapes, delegated to the pinned SPHINCS+C sibling.
    /// Mirrors `SHRINCSVerifier.verifyStateless`: decode the commitment key,
    /// run `prepare_stateless_delegation` (mirroring
    /// `SHRINCS.prepareStatelessDelegation`) to extract the delegate
    /// `(pkSeed, hypertreeRoot)` key and re-encoded signature envelope, then
    /// hand both to `SphincsPlusCVerifier::verify`, exactly like the
    /// Solidity adapter's external call to its pinned sibling.
    fn verify_stateless_signature(
        &self,
        key: &[u8],
        hash: &[u8; HASH_LEN],
        stateless_envelope: &[u8],
    ) -> VerifyOutcome;
}

impl ShrincsVerifierExt for ShrincsVerifier {
    fn verify_stateless_signature(
        &self,
        key: &[u8],
        hash: &[u8; HASH_LEN],
        stateless_envelope: &[u8],
    ) -> VerifyOutcome {
        let Some(commitment) = Commitment::from_bytes(key).map(|c| *c.as_bytes()) else {
            return VerifyOutcome::Invalid;
        };
        // `prepare_stateless_delegation` (in `super`/`dispatch`) folds
        // envelope-decode failure, commitment mismatch, and public-key shape
        // failure into a single `None`. Decode
        // once more here, purely to split "framing that can't be read at
        // all" (Malformed) from "well-formed but rejected" (Invalid),
        // without duplicating its commitment/shape-check logic.
        if decode_stateless_envelope(stateless_envelope).is_none() {
            return VerifyOutcome::Malformed;
        }
        let Some((delegate_key, delegate_signature_envelope)) =
            super::prepare_stateless_delegation(commitment, stateless_envelope)
        else {
            return VerifyOutcome::Invalid;
        };
        // `prepare_stateless_delegation` hands back a re-encoded signature
        // envelope, not a typed signature — Solidity's zero-copy calldata
        // pointer aliasing has no Rust equivalent here, so this decodes it
        // straight back into the typed form `SphincsPlusCVerifier::verify`
        // expects (an encode-then-decode round trip the Solidity adapter
        // never pays).
        let Some(delegate_signature) =
            crate::sphincs_plus_c::Signature::from_bytes(&delegate_signature_envelope)
        else {
            // `prepare_stateless_delegation` only ever emits a canonically
            // re-encoded envelope for a delegation it accepted, so this
            // should be unreachable; fail closed as Malformed rather than
            // silently treating a codec-internal inconsistency as Invalid.
            return VerifyOutcome::Malformed;
        };
        if SphincsPlusCVerifier::new().verify_signature(&delegate_key, hash, &delegate_signature) {
            VerifyOutcome::Valid
        } else {
            VerifyOutcome::Invalid
        }
    }
}

impl crate::verifier::VerifierInterface for ShrincsVerifier {
    /// Stateful verify: `key` is the 32-byte SHRINCS `publicKeyCommitment`; Mirrors `SHRINCSVerifier.verify` /
    /// `SHRINCS.verify`: `key` must be exactly 32 bytes (the SHRINCS
    /// `publicKeyCommitment`); `signature_envelope` is
    /// `abi.encode(PublicKey, SHRINCS.Signature)`.
    fn verify(
        &self,
        key: &[u8],
        hash: &[u8; HASH_LEN],
        signature_envelope: &[u8],
    ) -> VerifyOutcome {
        let Some(commitment) = Commitment::from_bytes(key).map(|c| *c.as_bytes()) else {
            return VerifyOutcome::Invalid;
        };
        let Some((public_key, signature)) = decode_stateful_envelope(signature_envelope) else {
            return VerifyOutcome::Malformed;
        };
        // `SHRINCS.verify` packs the bytes32 hash into the signed message as
        // its raw 32 bytes (`SPHINCSPlusC.toMessage`); `hash` IS the message.
        if super::verify_stateful_unsafe_raw(commitment, &public_key, hash, &signature) {
            VerifyOutcome::Valid
        } else {
            VerifyOutcome::Invalid
        }
    }
}

#[cfg(test)]
use crate::verifier::VerifierInterface as _;

#[cfg(test)]
mod interface_tests {
    use super::*;
    use crate::shrincs::{PublicKey, ShrincsSigner, StatelessSignature};

    fn keypair(seed: &[u8]) -> (crate::shrincs::Keys, PublicKey) {
        ShrincsSigner::keygen(seed, 4).expect("keygen must succeed for a valid seed/budget")
    }

    fn commitment_of(public_key: &PublicKey) -> Vec<u8> {
        public_key.public_key_commitment.clone()
    }

    // --- version tag -------------------------------------------------------

    #[test]
    fn version_tag_matches_pinned_solidity_constant() {
        // keccak256("quip.shrincs-verifier.v1"), computed independently and
        // pinned here so drift in either the literal string or the hash
        // routine fails loud instead of silently matching itself.
        const EXPECTED: [u8; HASH_LEN] = [
            0x06, 0x4b, 0x5b, 0x1b, 0x1f, 0x5d, 0x6d, 0xc3, 0xd3, 0x8c, 0x8e, 0xd9, 0xf3, 0x8f,
            0xd2, 0x4f, 0x68, 0x62, 0x83, 0x29, 0xf9, 0x32, 0x9a, 0x54, 0xb8, 0xe8, 0xc5, 0x3e,
            0x3b, 0x06, 0xda, 0x58,
        ];
        assert_eq!(ShrincsVerifier::version_tag(), EXPECTED);
    }

    // --- stateful verify -----------------------------------------------------

    #[test]
    fn verify_accepts_a_valid_stateful_signature_over_the_raw_hash() {
        let (mut signing_key, public_key) = keypair(b"verifier stateful accept seed");
        let hash = [0x42u8; HASH_LEN];
        let signature = ShrincsSigner::sign_stateful_raw(&mut signing_key, &hash)
            .expect("signing must succeed for a fresh key");
        let envelope = encode_stateful_envelope(&public_key, &signature);

        let outcome = ShrincsVerifier::new().verify(&commitment_of(&public_key), &hash, &envelope);
        assert_eq!(outcome, VerifyOutcome::Valid);
    }

    #[test]
    fn verify_rejects_a_signature_over_a_different_hash() {
        let (mut signing_key, public_key) = keypair(b"verifier stateful reject seed");
        let hash = [0x11u8; HASH_LEN];
        let signature = ShrincsSigner::sign_stateful_raw(&mut signing_key, &hash)
            .expect("signing must succeed for a fresh key");
        let envelope = encode_stateful_envelope(&public_key, &signature);

        let wrong_hash = [0x22u8; HASH_LEN];
        let outcome =
            ShrincsVerifier::new().verify(&commitment_of(&public_key), &wrong_hash, &envelope);
        assert_eq!(outcome, VerifyOutcome::Invalid);
    }

    #[test]
    fn verify_rejects_a_wrong_length_key() {
        let (mut signing_key, public_key) = keypair(b"verifier stateful wrong key seed");
        let hash = [0x33u8; HASH_LEN];
        let signature = ShrincsSigner::sign_stateful_raw(&mut signing_key, &hash)
            .expect("signing must succeed for a fresh key");
        let envelope = encode_stateful_envelope(&public_key, &signature);

        let mut short_key = commitment_of(&public_key);
        short_key.pop();
        let outcome = ShrincsVerifier::new().verify(&short_key, &hash, &envelope);
        assert_eq!(outcome, VerifyOutcome::Invalid);
    }

    #[test]
    fn verify_reports_a_truncated_envelope_as_malformed() {
        let (mut signing_key, public_key) = keypair(b"verifier stateful malformed seed");
        let hash = [0x44u8; HASH_LEN];
        let signature = ShrincsSigner::sign_stateful_raw(&mut signing_key, &hash)
            .expect("signing must succeed for a fresh key");
        let envelope = encode_stateful_envelope(&public_key, &signature);

        let outcome = ShrincsVerifier::new().verify(
            &commitment_of(&public_key),
            &hash,
            &envelope[..envelope.len() - 1],
        );
        assert_eq!(outcome, VerifyOutcome::Malformed);
    }

    #[test]
    fn verify_reports_an_empty_envelope_as_malformed() {
        let (_signing_key, public_key) = keypair(b"verifier stateful empty seed");
        let hash = [0x55u8; HASH_LEN];
        let outcome = ShrincsVerifier::new().verify(&commitment_of(&public_key), &hash, &[]);
        assert_eq!(outcome, VerifyOutcome::Malformed);
    }

    #[test]
    fn verify_reports_a_mismatched_commitment_as_invalid_not_malformed() {
        let (mut signing_key, public_key) = keypair(b"verifier stateful wrong commitment seed");
        let hash = [0x5du8; HASH_LEN];
        let signature = ShrincsSigner::sign_stateful_raw(&mut signing_key, &hash)
            .expect("signing must succeed for a fresh key");
        let envelope = encode_stateful_envelope(&public_key, &signature);

        // Structurally well-formed (correct-length, well-decoded) but wrong
        // commitment: must be Invalid, not Malformed -- the stateless analog
        // is `verify_stateless_reports_a_mismatched_commitment_as_invalid_not_malformed`.
        let mut wrong_commitment = commitment_of(&public_key);
        wrong_commitment[0] ^= 0x01;
        let outcome = ShrincsVerifier::new().verify(&wrong_commitment, &hash, &envelope);
        assert_eq!(outcome, VerifyOutcome::Invalid);
    }

    // --- stateless verify ------------------------------------------------

    #[test]
    fn verify_stateless_accepts_a_valid_stateless_signature_over_the_raw_hash() {
        let (signing_key, public_key) = keypair(b"verifier stateless accept seed");
        let hash = [0x66u8; HASH_LEN];
        let signature: StatelessSignature = ShrincsSigner::sign_stateless_raw(&signing_key, &hash)
            .expect("stateless signing must succeed for a fresh key");
        let envelope = encode_stateless_envelope(&public_key, &signature);

        let outcome = ShrincsVerifier::new().verify_stateless_signature(
            &commitment_of(&public_key),
            &hash,
            &envelope,
        );
        assert_eq!(outcome, VerifyOutcome::Valid);
    }

    #[test]
    fn verify_stateless_rejects_a_signature_over_a_different_hash() {
        let (signing_key, public_key) = keypair(b"verifier stateless reject seed");
        let hash = [0x77u8; HASH_LEN];
        let signature = ShrincsSigner::sign_stateless_raw(&signing_key, &hash)
            .expect("stateless signing must succeed for a fresh key");
        let envelope = encode_stateless_envelope(&public_key, &signature);

        let wrong_hash = [0x88u8; HASH_LEN];
        let outcome = ShrincsVerifier::new().verify_stateless_signature(
            &commitment_of(&public_key),
            &wrong_hash,
            &envelope,
        );
        assert_eq!(outcome, VerifyOutcome::Invalid);
    }

    #[test]
    fn verify_stateless_rejects_a_wrong_length_key() {
        let (signing_key, public_key) = keypair(b"verifier stateless wrong key seed");
        let hash = [0x99u8; HASH_LEN];
        let signature = ShrincsSigner::sign_stateless_raw(&signing_key, &hash)
            .expect("stateless signing must succeed for a fresh key");
        let envelope = encode_stateless_envelope(&public_key, &signature);

        let mut short_key = commitment_of(&public_key);
        short_key.pop();
        let outcome =
            ShrincsVerifier::new().verify_stateless_signature(&short_key, &hash, &envelope);
        assert_eq!(outcome, VerifyOutcome::Invalid);
    }

    #[test]
    fn verify_stateless_reports_a_mismatched_commitment_as_invalid_not_malformed() {
        let (signing_key, public_key) = keypair(b"verifier stateless wrong commitment seed");
        let hash = [0xaau8; HASH_LEN];
        let signature = ShrincsSigner::sign_stateless_raw(&signing_key, &hash)
            .expect("stateless signing must succeed for a fresh key");
        let envelope = encode_stateless_envelope(&public_key, &signature);

        let mut wrong_commitment = commitment_of(&public_key);
        wrong_commitment[0] ^= 0x01;
        let outcome =
            ShrincsVerifier::new().verify_stateless_signature(&wrong_commitment, &hash, &envelope);
        assert_eq!(outcome, VerifyOutcome::Invalid);
    }

    #[test]
    fn verify_stateless_reports_a_truncated_envelope_as_malformed() {
        let (signing_key, public_key) = keypair(b"verifier stateless malformed seed");
        let hash = [0xbbu8; HASH_LEN];
        let signature = ShrincsSigner::sign_stateless_raw(&signing_key, &hash)
            .expect("stateless signing must succeed for a fresh key");
        let envelope = encode_stateless_envelope(&public_key, &signature);

        let outcome = ShrincsVerifier::new().verify_stateless_signature(
            &commitment_of(&public_key),
            &hash,
            &envelope[..envelope.len() - 1],
        );
        assert_eq!(outcome, VerifyOutcome::Malformed);
    }

    #[test]
    fn verify_stateless_reports_an_empty_envelope_as_malformed() {
        let (_signing_key, public_key) = keypair(b"verifier stateless empty seed");
        let hash = [0xccu8; HASH_LEN];
        let outcome = ShrincsVerifier::new().verify_stateless_signature(
            &commitment_of(&public_key),
            &hash,
            &[],
        );
        assert_eq!(outcome, VerifyOutcome::Malformed);
    }
}