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
#![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
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
49
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
50

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

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

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

            
69
/// Option for selecting a HashX runtime
70
#[derive(Default, Debug, Copy, Clone, Eq, PartialEq)]
71
#[non_exhaustive]
72
pub enum RuntimeOption {
73
    /// Choose the interpreted runtime, without trying the compiler at all.
74
    InterpretOnly,
75
    /// Choose the compiled runtime only, and fail if it experiences any errors.
76
    CompileOnly,
77
    /// Always try the compiler first but fall back to the interpreter on error.
78
    /// (This is the default)
79
    #[default]
80
    TryCompile,
81
}
82

            
83
/// Effective HashX runtime for a constructed program
84
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
85
#[non_exhaustive]
86
pub enum Runtime {
87
    /// The interpreted runtime is active.
88
    Interpret,
89
    /// The compiled runtime is active.
90
    Compiled,
91
}
92

            
93
/// Pre-built hash program that can be rapidly computed with different inputs
94
///
95
/// The program and initial state representation are not specified in this
96
/// public interface, but [`std::fmt::Debug`] can describe program internals.
97
#[derive(Debug)]
98
pub struct HashX {
99
    /// Keys used to generate an initial register state from the hash input
100
    ///
101
    /// Half of the key material generated from seed bytes go into the random
102
    /// program generator, and the other half are saved here for use in each
103
    /// hash invocation.
104
    register_key: SipState,
105

            
106
    /// A prepared randomly generated hash program
107
    ///
108
    /// In compiled runtimes this will be executable code, and in the
109
    /// interpreter it's a list of instructions. There is no stable API for
110
    /// program information, but the Debug trait will list programs in either
111
    /// format.
112
    program: RuntimeProgram,
113
}
114

            
115
/// Combination of [`Runtime`] and the actual program info used by that runtime
116
///
117
/// All variants of [`RuntimeProgram`] use some kind of inner heap allocation
118
/// to store the program data.
119
#[derive(Debug)]
120
enum RuntimeProgram {
121
    /// Select the interpreted runtime, and hold a Program for it to run.
122
    Interpret(Program),
123
    /// Select the compiled runtime, and hold an executable code page.
124
    Compiled(Executable),
125
}
126

            
127
impl HashX {
128
    /// The maximum available output size for [`Self::hash_to_bytes()`]
129
    pub const FULL_SIZE: usize = 32;
130

            
131
    /// Generate a new hash function with the supplied seed.
132
1898
    pub fn new(seed: &[u8]) -> Result<Self, Error> {
133
1898
        HashXBuilder::new().build(seed)
134
1898
    }
135

            
136
    /// Check which actual program runtime is in effect.
137
    ///
138
    /// By default we try to generate code at runtime to accelerate the hash
139
    /// function, but we fall back to an interpreter if this fails. The compiler
140
    /// can be disabled entirely using [`RuntimeOption::InterpretOnly`] and
141
    /// [`HashXBuilder`].
142
    pub fn runtime(&self) -> Runtime {
143
        match &self.program {
144
            RuntimeProgram::Interpret(_) => Runtime::Interpret,
145
            RuntimeProgram::Compiled(_) => Runtime::Compiled,
146
        }
147
    }
148

            
149
    /// Calculate the first 64-bit word of the hash, without converting to bytes.
150
358893404
    pub fn hash_to_u64(&self, input: u64) -> u64 {
151
358893404
        self.hash_to_regs(input).digest(self.register_key)[0]
152
358893404
    }
153

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

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

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

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

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

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

            
206
    /// Build a [`HashX`] instance from an arbitrary [`Rng`] and
207
    /// a [`SipState`] key used for initializing the register file.
208
10366
    pub fn build_from_rng<R: Rng>(
209
10366
        &self,
210
10366
        rng: &mut R,
211
10366
        register_key: SipState,
212
10366
    ) -> Result<HashX, Error> {
213
10366
        let program = Program::generate(rng)?;
214
9052
        self.build_from_program(program, register_key)
215
10366
    }
216

            
217
    /// Build a [`HashX`] instance from an already-generated [`Program`] and
218
    /// [`SipState`] key.
219
    ///
220
    /// The program is either stored as-is or compiled, depending on the current
221
    /// [`RuntimeOption`]. Requires a program as well as a [`SipState`] to be
222
    /// used for initializing the register file.
223
9052
    fn build_from_program(&self, program: Program, register_key: SipState) -> Result<HashX, Error> {
224
        Ok(HashX {
225
9052
            register_key,
226
9052
            program: match self.runtime {
227
146
                RuntimeOption::InterpretOnly => RuntimeProgram::Interpret(program),
228
                RuntimeOption::CompileOnly => {
229
146
                    RuntimeProgram::Compiled(Architecture::compile((&program).into())?)
230
                }
231
8760
                RuntimeOption::TryCompile => match Architecture::compile((&program).into()) {
232
8760
                    Ok(exec) => RuntimeProgram::Compiled(exec),
233
                    Err(_) => RuntimeProgram::Interpret(program),
234
                },
235
            },
236
        })
237
9052
    }
238
}