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