Skip to main content

hashx/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3// @@ begin lint list maintained by maint/add_warning @@
4#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6#![warn(missing_docs)]
7#![warn(noop_method_call)]
8#![warn(unreachable_pub)]
9#![warn(clippy::all)]
10#![deny(clippy::await_holding_lock)]
11#![deny(clippy::cargo_common_metadata)]
12#![deny(clippy::cast_lossless)]
13#![deny(clippy::checked_conversions)]
14#![allow(clippy::cognitive_complexity)] // See arti#2556
15#![deny(clippy::debug_assert_with_mut_call)]
16#![deny(clippy::exhaustive_enums)]
17#![deny(clippy::exhaustive_structs)]
18#![deny(clippy::expl_impl_clone_on_copy)]
19#![deny(clippy::fallible_impl_from)]
20#![deny(clippy::implicit_clone)]
21#![deny(clippy::large_stack_arrays)]
22#![warn(clippy::manual_ok_or)]
23#![deny(clippy::missing_docs_in_private_items)]
24#![warn(clippy::needless_borrow)]
25#![warn(clippy::needless_pass_by_value)]
26#![warn(clippy::option_option)]
27#![warn(clippy::or_fun_call)]
28#![deny(clippy::print_stderr)]
29#![deny(clippy::print_stdout)]
30#![warn(clippy::rc_buffer)]
31#![deny(clippy::ref_option_ref)]
32#![warn(clippy::semicolon_if_nothing_returned)]
33#![warn(clippy::trait_duplication_in_bounds)]
34#![deny(clippy::unchecked_time_subtraction)]
35#![deny(clippy::unnecessary_wraps)]
36#![warn(clippy::unseparated_literal_suffix)]
37#![deny(clippy::unwrap_used)]
38#![deny(clippy::mod_module_files)]
39#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40#![allow(clippy::uninlined_format_args)]
41#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44#![allow(clippy::needless_lifetimes)] // See arti#1765
45#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46#![allow(clippy::collapsible_if)] // See arti#2342
47#![deny(clippy::unused_async)]
48#![deny(clippy::string_slice)] // See arti#2571
49#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51
52mod compiler;
53mod constraints;
54mod err;
55mod generator;
56mod program;
57mod rand;
58mod register;
59mod scheduler;
60mod siphash;
61
62use crate::compiler::{Architecture, Executable};
63use crate::program::Program;
64use rand_core::Rng;
65
66pub use crate::err::{CompilerError, Error};
67pub use crate::rand::SipRand;
68pub use crate::siphash::SipState;
69
70/// Option for selecting a HashX runtime
71#[derive(Default, Debug, Copy, Clone, Eq, PartialEq)]
72#[non_exhaustive]
73pub enum RuntimeOption {
74    /// Choose the interpreted runtime, without trying the compiler at all.
75    InterpretOnly,
76    /// Choose the compiled runtime only, and fail if it experiences any errors.
77    CompileOnly,
78    /// Always try the compiler first but fall back to the interpreter on error.
79    /// (This is the default)
80    #[default]
81    TryCompile,
82}
83
84/// Effective HashX runtime for a constructed program
85#[derive(Debug, Copy, Clone, Eq, PartialEq)]
86#[non_exhaustive]
87pub enum Runtime {
88    /// The interpreted runtime is active.
89    Interpret,
90    /// The compiled runtime is active.
91    Compiled,
92}
93
94/// Pre-built hash program that can be rapidly computed with different inputs
95///
96/// The program and initial state representation are not specified in this
97/// public interface, but [`std::fmt::Debug`] can describe program internals.
98#[derive(Debug)]
99pub struct HashX {
100    /// Keys used to generate an initial register state from the hash input
101    ///
102    /// Half of the key material generated from seed bytes go into the random
103    /// program generator, and the other half are saved here for use in each
104    /// hash invocation.
105    register_key: SipState,
106
107    /// A prepared randomly generated hash program
108    ///
109    /// In compiled runtimes this will be executable code, and in the
110    /// interpreter it's a list of instructions. There is no stable API for
111    /// program information, but the Debug trait will list programs in either
112    /// format.
113    program: RuntimeProgram,
114}
115
116/// Combination of [`Runtime`] and the actual program info used by that runtime
117///
118/// All variants of [`RuntimeProgram`] use some kind of inner heap allocation
119/// to store the program data.
120#[derive(Debug)]
121enum RuntimeProgram {
122    /// Select the interpreted runtime, and hold a Program for it to run.
123    Interpret(Program),
124    /// Select the compiled runtime, and hold an executable code page.
125    Compiled(Executable),
126}
127
128impl HashX {
129    /// The maximum available output size for [`Self::hash_to_bytes()`]
130    pub const FULL_SIZE: usize = 32;
131
132    /// Generate a new hash function with the supplied seed.
133    pub fn new(seed: &[u8]) -> Result<Self, Error> {
134        HashXBuilder::new().build(seed)
135    }
136
137    /// Check which actual program runtime is in effect.
138    ///
139    /// By default we try to generate code at runtime to accelerate the hash
140    /// function, but we fall back to an interpreter if this fails. The compiler
141    /// can be disabled entirely using [`RuntimeOption::InterpretOnly`] and
142    /// [`HashXBuilder`].
143    pub fn runtime(&self) -> Runtime {
144        match &self.program {
145            RuntimeProgram::Interpret(_) => Runtime::Interpret,
146            RuntimeProgram::Compiled(_) => Runtime::Compiled,
147        }
148    }
149
150    /// Calculate the first 64-bit word of the hash, without converting to bytes.
151    pub fn hash_to_u64(&self, input: u64) -> u64 {
152        self.hash_to_regs(input).digest(self.register_key)[0]
153    }
154
155    /// Calculate the hash function at its full output width, returning a fixed
156    /// size byte array.
157    pub fn hash_to_bytes(&self, input: u64) -> [u8; Self::FULL_SIZE] {
158        let words = self.hash_to_regs(input).digest(self.register_key);
159        let mut bytes = [0_u8; Self::FULL_SIZE];
160        for word in 0..words.len() {
161            bytes[word * 8..(word + 1) * 8].copy_from_slice(&words[word].to_le_bytes());
162        }
163        bytes
164    }
165
166    /// Common setup for hashes with any output format
167    #[inline(always)]
168    fn hash_to_regs(&self, input: u64) -> register::RegisterFile {
169        let mut regs = register::RegisterFile::new(self.register_key, input);
170        match &self.program {
171            RuntimeProgram::Interpret(program) => program.interpret(&mut regs),
172            RuntimeProgram::Compiled(executable) => executable.invoke(&mut regs),
173        }
174        regs
175    }
176}
177
178/// Builder for creating [`HashX`] instances with custom settings
179#[derive(Default, Debug, Clone, Eq, PartialEq)]
180pub struct HashXBuilder {
181    /// Current runtime() setting for this builder
182    runtime: RuntimeOption,
183}
184
185impl HashXBuilder {
186    /// Create a new [`HashXBuilder`] with default settings.
187    ///
188    /// Immediately calling [`Self::build()`] would be equivalent to using
189    /// [`HashX::new()`].
190    pub fn new() -> Self {
191        Default::default()
192    }
193
194    /// Select a new [`RuntimeOption`].
195    pub fn runtime(&mut self, runtime: RuntimeOption) -> &mut Self {
196        self.runtime = runtime;
197        self
198    }
199
200    /// Build a [`HashX`] instance with a seed and the selected options.
201    pub fn build(&self, seed: &[u8]) -> Result<HashX, Error> {
202        let (key0, key1) = SipState::pair_from_seed(seed);
203        let mut rng = SipRand::new(key0);
204        self.build_from_rng(&mut rng, key1)
205    }
206
207    /// Build a [`HashX`] instance from an arbitrary [`Rng`] and
208    /// a [`SipState`] key used for initializing the register file.
209    pub fn build_from_rng<R: Rng>(
210        &self,
211        rng: &mut R,
212        register_key: SipState,
213    ) -> Result<HashX, Error> {
214        let program = Program::generate(rng)?;
215        self.build_from_program(program, register_key)
216    }
217
218    /// Build a [`HashX`] instance from an already-generated [`Program`] and
219    /// [`SipState`] key.
220    ///
221    /// The program is either stored as-is or compiled, depending on the current
222    /// [`RuntimeOption`]. Requires a program as well as a [`SipState`] to be
223    /// used for initializing the register file.
224    fn build_from_program(&self, program: Program, register_key: SipState) -> Result<HashX, Error> {
225        Ok(HashX {
226            register_key,
227            program: match self.runtime {
228                RuntimeOption::InterpretOnly => RuntimeProgram::Interpret(program),
229                RuntimeOption::CompileOnly => {
230                    RuntimeProgram::Compiled(Architecture::compile((&program).into())?)
231                }
232                RuntimeOption::TryCompile => match Architecture::compile((&program).into()) {
233                    Ok(exec) => RuntimeProgram::Compiled(exec),
234                    Err(_) => RuntimeProgram::Interpret(program),
235                },
236            },
237        })
238    }
239}