flexible_transcript/merlin.rs
1use core::fmt::{Debug, Formatter};
2
3use crate::Transcript;
4
5/// A wrapper around a Merlin transcript which satisfiees the Transcript API.
6///
7/// Challenges are fixed to 64 bytes, despite Merlin supporting variable length challenges.
8///
9/// This implementation is intended to remain in the spirit of Merlin more than it's intended to be
10/// in the spirit of the provided DigestTranscript. While DigestTranscript uses flags for each of
11/// its different field types, the domain_separate function simply appends a message with a label
12/// of "dom-sep", Merlin's preferred domain separation label. Since this could introduce transcript
13/// conflicts between a domain separation and a message with a label of "dom-sep", the
14/// append_message function uses an assertion to prevent such labels.
15#[derive(Clone)]
16pub struct MerlinTranscript(merlin::Transcript);
17// Merlin doesn't implement Debug so provide a stub which won't panic
18impl Debug for MerlinTranscript {
19 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
20 fmt.debug_struct("MerlinTranscript").finish_non_exhaustive()
21 }
22}
23
24impl Transcript for MerlinTranscript {
25 // Uses a challenge length of 64 bytes to support wide reduction on commonly used EC scalars
26 // From a security level standpoint (Merlin targets 128-bits), this should just be 32 bytes
27 // From a Merlin standpoint, this should be variable per call
28 // From a practical standpoint, this should be practical
29 type Challenge = [u8; 64];
30
31 fn new(name: &'static [u8]) -> Self {
32 MerlinTranscript(merlin::Transcript::new(name))
33 }
34
35 fn domain_separate(&mut self, label: &'static [u8]) {
36 self.0.append_message(b"dom-sep", label);
37 }
38
39 fn append_message<M: AsRef<[u8]>>(&mut self, label: &'static [u8], message: M) {
40 assert!(
41 label != "dom-sep".as_bytes(),
42 "\"dom-sep\" is reserved for the domain_separate function",
43 );
44 self.0.append_message(label, message.as_ref());
45 }
46
47 fn challenge(&mut self, label: &'static [u8]) -> Self::Challenge {
48 let mut challenge = [0; 64];
49 self.0.challenge_bytes(label, &mut challenge);
50 challenge
51 }
52
53 fn rng_seed(&mut self, label: &'static [u8]) -> [u8; 32] {
54 let mut seed = [0; 32];
55 seed.copy_from_slice(&self.challenge(label)[.. 32]);
56 seed
57 }
58}