1
#![cfg_attr(docsrs, feature(doc_auto_cfg, 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_duration_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
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
46

            
47
mod compiler;
48
mod constraints;
49
mod err;
50
mod generator;
51
mod program;
52
mod rand;
53
mod register;
54
mod scheduler;
55
mod siphash;
56

            
57
use crate::compiler::{Architecture, Executable};
58
use crate::program::Program;
59
use rand_core::RngCore;
60

            
61
pub use crate::err::{CompilerError, Error};
62
pub use crate::rand::SipRand;
63
pub use crate::siphash::SipState;
64

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

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

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

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

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

            
123
impl HashX {
124
    /// The maximum available output size for [`Self::hash_to_bytes()`]
125
    pub const FULL_SIZE: usize = 32;
126

            
127
    /// Generate a new hash function with the supplied seed.
128
1690
    pub fn new(seed: &[u8]) -> Result<Self, Error> {
129
1690
        HashXBuilder::new().build(seed)
130
1690
    }
131

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

            
145
    /// Calculate the first 64-bit word of the hash, without converting to bytes.
146
319562620
    pub fn hash_to_u64(&self, input: u64) -> u64 {
147
319562620
        self.hash_to_regs(input).digest(self.register_key)[0]
148
319562620
    }
149

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

            
161
    /// Common setup for hashes with any output format
162
    #[inline(always)]
163
319564050
    fn hash_to_regs(&self, input: u64) -> register::RegisterFile {
164
319564050
        let mut regs = register::RegisterFile::new(self.register_key, input);
165
319564050
        match &self.program {
166
260
            RuntimeProgram::Interpret(program) => program.interpret(&mut regs),
167
319563790
            RuntimeProgram::Compiled(executable) => executable.invoke(&mut regs),
168
        }
169
319564050
        regs
170
319564050
    }
171
}
172

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

            
180
impl HashXBuilder {
181
    /// Create a new [`HashXBuilder`] with default settings.
182
    ///
183
    /// Immediately calling [`Self::build()`] would be equivalent to using
184
    /// [`HashX::new()`].
185
8255
    pub fn new() -> Self {
186
8255
        Default::default()
187
8255
    }
188

            
189
    /// Select a new [`RuntimeOption`].
190
260
    pub fn runtime(&mut self, runtime: RuntimeOption) -> &mut Self {
191
260
        self.runtime = runtime;
192
260
        self
193
260
    }
194

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

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

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