Skip to main content

fedimint_ln_common/
preimage_auth.rs

1use bitcoin::hashes::{Hash as _, sha256};
2use subtle::ConstantTimeEq as _;
3
4/// Authorization value a client presents before receiving an LNv1 preimage.
5#[derive(Clone, Copy)]
6pub struct PreimageAuth(sha256::Hash);
7
8impl PreimageAuth {
9    /// Creates an authorization verifier for a stored LNv1 preimage
10    /// authorization value.
11    pub const fn new(expected: sha256::Hash) -> Self {
12        Self(expected)
13    }
14
15    /// Returns whether the supplied value authorizes access to the LNv1
16    /// preimage.
17    pub fn verifies(self, supplied: sha256::Hash) -> bool {
18        bool::from(self.0.as_byte_array().ct_eq(supplied.as_byte_array()))
19    }
20}
21
22#[cfg(test)]
23mod tests {
24    use bitcoin::hashes::Hash as _;
25
26    use super::PreimageAuth;
27
28    #[test]
29    fn accepts_matching_preimage_auth() {
30        let preimage_auth = bitcoin::hashes::sha256::Hash::hash(b"preimage auth");
31
32        assert!(PreimageAuth::new(preimage_auth).verifies(preimage_auth));
33    }
34
35    #[test]
36    fn rejects_non_matching_preimage_auth() {
37        let expected = bitcoin::hashes::sha256::Hash::hash(b"expected preimage auth");
38        let supplied = bitcoin::hashes::sha256::Hash::hash(b"supplied preimage auth");
39
40        assert!(!PreimageAuth::new(expected).verifies(supplied));
41    }
42}