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

            
52
mod compiler;
53
mod constraints;
54
mod err;
55
mod generator;
56
mod program;
57
mod rand;
58
mod register;
59
mod scheduler;
60
mod siphash;
61

            
62
use crate::compiler::{Architecture, Executable};
63
use crate::program::Program;
64
use rand_core::Rng;
65

            
66
pub use crate::err::{CompilerError, Error};
67
pub use crate::rand::SipRand;
68
pub use crate::siphash::SipState;
69

            
70
/// Option for selecting a HashX runtime
71
#[derive(Default, Debug, Copy, Clone, Eq, PartialEq)]
72
#[non_exhaustive]
73
pub 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]
87
pub 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)]
99
pub 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)]
121
enum 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

            
128
impl 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
1872
    pub fn new(seed: &[u8]) -> Result<Self, Error> {
134
1872
        HashXBuilder::new().build(seed)
135
1872
    }
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
353977056
    pub fn hash_to_u64(&self, input: u64) -> u64 {
152
353977056
        self.hash_to_regs(input).digest(self.register_key)[0]
153
353977056
    }
154

            
155
    /// Calculate the hash function at its full output width, returning a fixed
156
    /// size byte array.
157
1584
    pub fn hash_to_bytes(&self, input: u64) -> [u8; Self::FULL_SIZE] {
158
1584
        let words = self.hash_to_regs(input).digest(self.register_key);
159
1584
        let mut bytes = [0_u8; Self::FULL_SIZE];
160
6336
        for word in 0..words.len() {
161
6336
            bytes[word * 8..(word + 1) * 8].copy_from_slice(&words[word].to_le_bytes());
162
6336
        }
163
1584
        bytes
164
1584
    }
165

            
166
    /// Common setup for hashes with any output format
167
    #[inline(always)]
168
353978640
    fn hash_to_regs(&self, input: u64) -> register::RegisterFile {
169
353978640
        let mut regs = register::RegisterFile::new(self.register_key, input);
170
353978640
        match &self.program {
171
288
            RuntimeProgram::Interpret(program) => program.interpret(&mut regs),
172
353978352
            RuntimeProgram::Compiled(executable) => executable.invoke(&mut regs),
173
        }
174
353978640
        regs
175
353978640
    }
176
}
177

            
178
/// Builder for creating [`HashX`] instances with custom settings
179
#[derive(Default, Debug, Clone, Eq, PartialEq)]
180
pub struct HashXBuilder {
181
    /// Current runtime() setting for this builder
182
    runtime: RuntimeOption,
183
}
184

            
185
impl HashXBuilder {
186
    /// Create a new [`HashXBuilder`] with default settings.
187
    ///
188
    /// Immediately calling [`Self::build()`] would be equivalent to using
189
    /// [`HashX::new()`].
190
9144
    pub fn new() -> Self {
191
9144
        Default::default()
192
9144
    }
193

            
194
    /// Select a new [`RuntimeOption`].
195
288
    pub fn runtime(&mut self, runtime: RuntimeOption) -> &mut Self {
196
288
        self.runtime = runtime;
197
288
        self
198
288
    }
199

            
200
    /// Build a [`HashX`] instance with a seed and the selected options.
201
10224
    pub fn build(&self, seed: &[u8]) -> Result<HashX, Error> {
202
10224
        let (key0, key1) = SipState::pair_from_seed(seed);
203
10224
        let mut rng = SipRand::new(key0);
204
10224
        self.build_from_rng(&mut rng, key1)
205
10224
    }
206

            
207
    /// Build a [`HashX`] instance from an arbitrary [`Rng`] and
208
    /// a [`SipState`] key used for initializing the register file.
209
10224
    pub fn build_from_rng<R: Rng>(
210
10224
        &self,
211
10224
        rng: &mut R,
212
10224
        register_key: SipState,
213
10224
    ) -> Result<HashX, Error> {
214
10224
        let program = Program::generate(rng)?;
215
8928
        self.build_from_program(program, register_key)
216
10224
    }
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
8928
    fn build_from_program(&self, program: Program, register_key: SipState) -> Result<HashX, Error> {
225
        Ok(HashX {
226
8928
            register_key,
227
8928
            program: match self.runtime {
228
144
                RuntimeOption::InterpretOnly => RuntimeProgram::Interpret(program),
229
                RuntimeOption::CompileOnly => {
230
144
                    RuntimeProgram::Compiled(Architecture::compile((&program).into())?)
231
                }
232
8640
                RuntimeOption::TryCompile => match Architecture::compile((&program).into()) {
233
8640
                    Ok(exec) => RuntimeProgram::Compiled(exec),
234
                    Err(_) => RuntimeProgram::Interpret(program),
235
                },
236
            },
237
        })
238
8928
    }
239
}