drandite_tlock/lib.rs
1//! Timelock encryption with unchained drand beacons.
2//!
3//! [`Timelock`] encrypts a fixed-size message for a chain and round. Decryption
4//! requires that round's [`VerifiedBeacon`], checked against the same chain.
5//! Supported schemes are [`PedersenBlsUnchained`], [`BlsUnchainedOnG1`], and
6//! [`BlsUnchainedG1Rfc9380`]. Chained schemes are not supported.
7//!
8//! Messages contain 16 to 32 bytes, inclusive. For larger payloads, encrypt a
9//! randomly generated symmetric key and use an authenticated cipher separately.
10//! The message length is part of the ciphertext's type, not its byte encoding.
11//!
12//! # Security
13//!
14//! Pin the chain hash independently before constructing [`Timelock`]. Anyone
15//! with the target round's signature can decrypt; the crate neither checks the
16//! current time nor fetches beacons. A chain's signing-key holders can release
17//! signatures early. Drand randomness is public and must not be used as an
18//! encryption key or as the seed of the encryption RNG.
19//!
20//! Decryption returns a [`Zeroizing`] buffer, which clears its contents on drop.
21//! Copies made by the caller are not cleared automatically.
22//!
23//! # Examples
24//!
25//! Encrypt a key and decrypt it using Quicknet round 1000. This historical
26//! round's signature is already public, so it provides no time delay. For a
27//! real timelock, choose a future round and obtain its beacon after publication.
28//!
29//! The fixed key and RNG seed below are for reproducibility only. In production,
30//! generate a secret key and seed the RNG from a secure entropy source.
31//!
32//! ```
33//! use drandite_core::scheme::BlsUnchainedG1Rfc9380;
34//! use drandite_core::types::{ChainHash, GenesisSeed, Period, Round, UnixTimestamp};
35//! use drandite_core::{Beacon, ChainInfo, Verifier};
36//! use drandite_tlock::{Ciphertext, Timelock, crypto::{G2Projective, ibe}};
37//! use hex_literal::hex;
38//! use rand_chacha::ChaCha20Rng;
39//! use rand_core::SeedableRng;
40//!
41//! let public_key = hex!(
42//! "83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c\
43//! 8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb\
44//! 5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a"
45//! );
46//! let genesis_seed = GenesisSeed::new(hex!(
47//! "f477d5c89f21a17c863a7f937c6a6d15859414d2be09cd448d4279af331c5d3e"
48//! ));
49//! // Obtain the chain hash independently of the relay supplying chain info.
50//! let pinned = ChainHash::new(hex!(
51//! "52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971"
52//! ));
53//! let info = ChainInfo::<BlsUnchainedG1Rfc9380>::new_pinned(
54//! &public_key,
55//! Period::from_secs(3).unwrap(),
56//! UnixTimestamp::from_secs(1_692_803_367),
57//! Some(genesis_seed),
58//! "quicknet",
59//! pinned,
60//! )?;
61//! let round = Round::new(1000).unwrap();
62//! let timelock = Timelock::new(&info);
63//! let key = [42; 32];
64//! let mut rng = ChaCha20Rng::from_seed([7; 32]);
65//! let ciphertext = timelock.encrypt(&mut rng, round, &key)?;
66//!
67//! // Persist the bytes, round, and chain hash together. The encoding omits metadata.
68//! let mut bytes = [0; ibe::Ciphertext::<G2Projective, 32>::encoded_len()];
69//! ciphertext.inner().write_bytes(&mut bytes)?;
70//! let restored = Ciphertext::new(
71//! ciphertext.round(),
72//! ciphertext.chain_hash(),
73//! ibe::Ciphertext::<G2Projective, 32>::from_bytes(&bytes)?,
74//! );
75//!
76//! // Fetch the target beacon, then verify it against the pinned chain.
77//! let signature = hex!(
78//! "b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125\
79//! e342b73a8dd2bacbe47e4b6b63ed5e39"
80//! );
81//! let beacon = Beacon::from_bytes(round, &signature, None)?;
82//! let verified = Verifier::new(&info).verify(beacon)?;
83//! let plaintext = timelock.decrypt(&restored, &verified)?;
84//! assert_eq!(*plaintext, key);
85//! # Ok::<(), Box<dyn std::error::Error>>(())
86//! ```
87//!
88//! # Features
89//!
90//! `portable-blst` selects the portable BLS backend. No features are enabled by
91//! default.
92//!
93//! # Platform support
94//!
95//! This crate is `no_std`. The BLS backend requires a global allocator.
96//!
97#![no_std]
98#![warn(missing_docs)]
99
100use drandite_core::VerifiedBeacon;
101use drandite_core::scheme::{BlsUnchainedG1Rfc9380, BlsUnchainedOnG1, PedersenBlsUnchained};
102use drandite_core::types::{ChainHash, Round};
103use drandite_core::{ChainInfo, Scheme};
104use rand_core::CryptoRng;
105use zeroize::Zeroizing;
106
107use crate::crypto::ibe::ProjectivePoint;
108use crate::crypto::{G1Projective, G2Projective};
109
110pub mod crypto;
111mod error;
112
113pub use error::Error;
114
115/// A specialized [`Result`](core::result::Result) type for timelock operations.
116pub type Result<T, E = Error> = core::result::Result<T, E>;
117
118/// An encrypted message bound to a drand chain and round.
119///
120/// `U` selects the public key's curve group; `N` is the message length in bytes.
121/// Encryption and decryption require `16 <= N <= 32`.
122///
123/// The metadata is checked during decryption but is not cryptographically
124/// authenticated. It does not replace beacon verification or independent
125/// pinning of the chain hash.
126#[derive(Debug, Clone, Copy)]
127pub struct Ciphertext<U: ProjectivePoint, const N: usize> {
128 round: Round,
129 chain_hash: ChainHash,
130 inner: crypto::ibe::Ciphertext<U, N>,
131}
132
133impl<U: ProjectivePoint, const N: usize> Ciphertext<U, N> {
134 /// Creates a ciphertext from its metadata and identity-based ciphertext.
135 ///
136 /// This does not validate the metadata or ciphertext. The timelock's
137 /// `decrypt` method validates both before returning plaintext.
138 #[must_use]
139 #[inline]
140 pub const fn new(
141 round: Round,
142 chain_hash: ChainHash,
143 inner: crypto::ibe::Ciphertext<U, N>,
144 ) -> Self {
145 Self {
146 round,
147 chain_hash,
148 inner,
149 }
150 }
151
152 /// Returns the round whose signature is needed to decrypt this ciphertext.
153 #[must_use]
154 #[inline]
155 pub const fn round(&self) -> Round {
156 self.round
157 }
158
159 /// Returns the hash of the chain used for encryption.
160 #[must_use]
161 #[inline]
162 pub const fn chain_hash(&self) -> ChainHash {
163 self.chain_hash
164 }
165
166 /// Returns the underlying identity-based ciphertext.
167 ///
168 /// Its byte encoding does not include the round or chain hash. Store those
169 /// separately when persisting the ciphertext.
170 /// See the [crate-level example](crate) for encoding and decoding a
171 /// ciphertext together with its metadata.
172 #[must_use]
173 #[inline]
174 pub const fn inner(&self) -> &crypto::ibe::Ciphertext<U, N> {
175 &self.inner
176 }
177
178 fn check_beacon<S: Scheme>(
179 &self,
180 chain: &ChainInfo<S>,
181 beacon: &VerifiedBeacon<S>,
182 ) -> Result<()> {
183 if self.round != beacon.round() {
184 return Err(Error::CiphertextFromDifferentRound);
185 }
186 let chain_hash = chain.digest();
187 if beacon.chain_hash() != chain_hash {
188 return Err(Error::BeaconFromDifferentChain);
189 }
190 if self.chain_hash != chain_hash {
191 return Err(Error::CiphertextFromDifferentChain);
192 }
193 Ok(())
194 }
195}
196
197/// Encrypts and decrypts messages for one drand chain.
198///
199/// Construct the chain info with an independently pinned chain hash. A verified
200/// beacon from that chain is required for decryption.
201#[derive(Debug, Clone, Copy)]
202pub struct Timelock<'a, S: Scheme> {
203 chain_info: &'a ChainInfo<S>,
204}
205
206impl<'a, S: Scheme> Timelock<'a, S> {
207 /// Creates a timelock using `chain_info`.
208 ///
209 /// This does not check a pinned chain hash. Use
210 /// [`ChainInfo::new_pinned`] when obtaining chain info from a relay.
211 #[must_use]
212 #[inline]
213 pub const fn new(chain_info: &'a ChainInfo<S>) -> Self {
214 Self { chain_info }
215 }
216
217 /// Returns the chain info used by this timelock.
218 #[must_use]
219 #[inline]
220 pub const fn chain_info(&self) -> &ChainInfo<S> {
221 self.chain_info
222 }
223}
224
225impl Timelock<'_, PedersenBlsUnchained> {
226 /// Encrypts `msg` for `round` using fresh randomness from `rng`.
227 ///
228 /// `N` must be between 16 and 32, inclusive; other lengths fail to compile.
229 ///
230 /// # Errors
231 ///
232 /// Returns [`Error::InvalidPublicKey`] if the chain's public key is invalid.
233 ///
234 /// # Panics
235 ///
236 /// Panics if the RNG panics or scalar rejection sampling is exhausted.
237 pub fn encrypt<const N: usize>(
238 &self,
239 rng: &mut impl CryptoRng,
240 round: Round,
241 msg: &[u8; N],
242 ) -> Result<Ciphertext<G1Projective, N>> {
243 let master = *self.chain_info().public_key();
244 let id = round.unchained_digest();
245 let chain_hash = self.chain_info().digest();
246
247 let inner = crypto::ibe::encrypt_on_g1(rng, master, &id, msg, PedersenBlsUnchained::DST)?;
248
249 Ok(Ciphertext {
250 round,
251 chain_hash,
252 inner,
253 })
254 }
255
256 /// Decrypts `ciphertext` using the target round's verified beacon.
257 ///
258 /// `N` must be between 16 and 32, inclusive; other lengths fail to compile.
259 /// The returned plaintext is cleared on drop.
260 ///
261 /// # Errors
262 ///
263 /// Returns an error if the round or chain differs, the beacon signature is
264 /// malformed, or the ciphertext fails its integrity check.
265 ///
266 /// # Panics
267 ///
268 /// Panics if scalar rejection sampling is exhausted.
269 pub fn decrypt<const N: usize>(
270 &self,
271 ciphertext: &Ciphertext<G1Projective, N>,
272 beacon: &VerifiedBeacon<PedersenBlsUnchained>,
273 ) -> Result<Zeroizing<[u8; N]>> {
274 ciphertext.check_beacon(self.chain_info(), beacon)?;
275
276 crypto::ibe::decrypt_on_g1(*beacon.signature(), &ciphertext.inner)
277 }
278}
279
280impl Timelock<'_, BlsUnchainedOnG1> {
281 /// Encrypts `msg` for `round` using fresh randomness from `rng`.
282 ///
283 /// This legacy scheme uses drand's non-RFC-9380 domain separation tag.
284 /// `N` must be between 16 and 32, inclusive; other lengths fail to compile.
285 ///
286 /// # Errors
287 ///
288 /// Returns [`Error::InvalidPublicKey`] if the chain's public key is invalid.
289 ///
290 /// # Panics
291 ///
292 /// Panics if the RNG panics or scalar rejection sampling is exhausted.
293 pub fn encrypt<const N: usize>(
294 &self,
295 rng: &mut impl CryptoRng,
296 round: Round,
297 msg: &[u8; N],
298 ) -> Result<Ciphertext<G2Projective, N>> {
299 let master = *self.chain_info().public_key();
300 let id = round.unchained_digest();
301 let chain_hash = self.chain_info().digest();
302
303 let inner = crypto::ibe::encrypt_on_g2(rng, master, &id, msg, BlsUnchainedOnG1::DST)?;
304
305 Ok(Ciphertext {
306 round,
307 chain_hash,
308 inner,
309 })
310 }
311
312 /// Decrypts `ciphertext` using the target round's verified beacon.
313 ///
314 /// `N` must be between 16 and 32, inclusive; other lengths fail to compile.
315 /// The returned plaintext is cleared on drop.
316 ///
317 /// # Errors
318 ///
319 /// Returns an error if the round or chain differs, the beacon signature is
320 /// malformed, or the ciphertext fails its integrity check.
321 ///
322 /// # Panics
323 ///
324 /// Panics if scalar rejection sampling is exhausted.
325 pub fn decrypt<const N: usize>(
326 &self,
327 ciphertext: &Ciphertext<G2Projective, N>,
328 beacon: &VerifiedBeacon<BlsUnchainedOnG1>,
329 ) -> Result<Zeroizing<[u8; N]>> {
330 ciphertext.check_beacon(self.chain_info(), beacon)?;
331
332 crypto::ibe::decrypt_on_g2(*beacon.signature(), &ciphertext.inner)
333 }
334}
335
336impl Timelock<'_, BlsUnchainedG1Rfc9380> {
337 /// Encrypts `msg` for `round` using fresh randomness from `rng`.
338 ///
339 /// `N` must be between 16 and 32, inclusive; other lengths fail to compile.
340 ///
341 /// # Errors
342 ///
343 /// Returns [`Error::InvalidPublicKey`] if the chain's public key is invalid.
344 ///
345 /// # Panics
346 ///
347 /// Panics if the RNG panics or scalar rejection sampling is exhausted.
348 pub fn encrypt<const N: usize>(
349 &self,
350 rng: &mut impl CryptoRng,
351 round: Round,
352 msg: &[u8; N],
353 ) -> Result<Ciphertext<G2Projective, N>> {
354 let master = *self.chain_info().public_key();
355 let id = round.unchained_digest();
356 let chain_hash = self.chain_info().digest();
357
358 let inner = crypto::ibe::encrypt_on_g2(rng, master, &id, msg, BlsUnchainedG1Rfc9380::DST)?;
359
360 Ok(Ciphertext {
361 round,
362 chain_hash,
363 inner,
364 })
365 }
366
367 /// Decrypts `ciphertext` using the target round's verified beacon.
368 ///
369 /// `N` must be between 16 and 32, inclusive; other lengths fail to compile.
370 /// The returned plaintext is cleared on drop.
371 ///
372 /// # Errors
373 ///
374 /// Returns an error if the round or chain differs, the beacon signature is
375 /// malformed, or the ciphertext fails its integrity check.
376 ///
377 /// # Panics
378 ///
379 /// Panics if scalar rejection sampling is exhausted.
380 pub fn decrypt<const N: usize>(
381 &self,
382 ciphertext: &Ciphertext<G2Projective, N>,
383 beacon: &VerifiedBeacon<BlsUnchainedG1Rfc9380>,
384 ) -> Result<Zeroizing<[u8; N]>> {
385 ciphertext.check_beacon(self.chain_info(), beacon)?;
386
387 crypto::ibe::decrypt_on_g2(*beacon.signature(), &ciphertext.inner)
388 }
389}