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 bucket_array;
53
mod collision;
54
mod err;
55
mod solution;
56
mod solver;
57

            
58
// Export bucket_array::mem API only to the fuzzer.
59
// (This is not stable; you should not use it except for testing.)
60
#[cfg(feature = "bucket-array")]
61
pub use bucket_array::mem::{BucketArray, BucketArrayMemory, BucketArrayPair, Count, Uninit};
62

            
63
use hashx::{HashX, HashXBuilder};
64

            
65
pub use hashx::{Runtime, RuntimeOption};
66

            
67
pub use err::{Error, HashError};
68
pub use solution::{Solution, SolutionArray, SolutionByteArray, SolutionItem, SolutionItemArray};
69
pub use solver::SolverMemory;
70

            
71
/// One Equi-X instance, customized for a challenge string
72
///
73
/// This includes pre-computed state that depends on the
74
/// puzzle's challenge as well as any options set via [`EquiXBuilder`].
75
#[derive(Debug)]
76
pub struct EquiX {
77
    /// HashX instance generated for this puzzle's challenge string
78
    hash: HashX,
79
}
80

            
81
impl EquiX {
82
    /// Make a new [`EquiX`] instance with a challenge string and
83
    /// default options.
84
    ///
85
    /// It's normal for this to fail with a [`HashError::ProgramConstraints`]
86
    /// for a small fraction of challenge values. Those challenges must be
87
    /// skipped by solvers and rejected by verifiers.
88
3150
    pub fn new(challenge: &[u8]) -> Result<Self, Error> {
89
3150
        EquiXBuilder::new().build(challenge)
90
3150
    }
91

            
92
    /// Check which actual program runtime is in effect.
93
    ///
94
    /// By default we try to generate machine code at runtime to accelerate the
95
    /// hash function, but we fall back to an interpreter if this fails. The
96
    /// compiler can be disabled entirely using [`RuntimeOption::InterpretOnly`]
97
    /// and [`EquiXBuilder`].
98
    pub fn runtime(&self) -> Runtime {
99
        self.hash.runtime()
100
    }
101

            
102
    /// Check a [`Solution`] against this particular challenge.
103
    ///
104
    /// Having a [`Solution`] instance guarantees that the order of items
105
    /// has already been checked. This only needs to check hash tree sums.
106
    /// Returns either `Ok` or [`Error::HashSum`].
107
26740
    pub fn verify(&self, solution: &Solution) -> Result<(), Error> {
108
26740
        solution::check_all_tree_sums(&self.hash, solution)
109
26740
    }
110

            
111
    /// Search for solutions using this particular challenge.
112
    ///
113
    /// Returns a buffer with a variable number of solutions.
114
    /// Memory for the solver is allocated dynamically and not reused.
115
2240
    pub fn solve(&self) -> SolutionArray {
116
2240
        let mut mem = SolverMemory::new();
117
2240
        self.solve_with_memory(&mut mem)
118
2240
    }
119

            
120
    /// Search for solutions, using the provided [`SolverMemory`].
121
    ///
122
    /// Returns a buffer with a variable number of solutions.
123
    ///
124
    /// Allows reuse of solver memory. Preferred for callers which may perform
125
    /// several solve operations in rapid succession, such as in the common case
126
    /// of layering an effort adjustment protocol above Equi-X.
127
5250
    pub fn solve_with_memory(&self, mem: &mut SolverMemory) -> SolutionArray {
128
5250
        let mut result = Default::default();
129
5250
        solver::find_solutions(&self.hash, mem, &mut result);
130
5250
        result
131
5250
    }
132
}
133

            
134
/// Builder for creating [`EquiX`] instances with custom settings
135
#[derive(Debug, Clone, Eq, PartialEq)]
136
pub struct EquiXBuilder {
137
    /// Inner [`HashXBuilder`] for options related to our hash function
138
    hash: HashXBuilder,
139
}
140

            
141
impl EquiXBuilder {
142
    /// Create a new [`EquiXBuilder`] with default settings.
143
    ///
144
    /// Immediately calling [`Self::build()`] would be equivalent to using
145
    /// [`EquiX::new()`].
146
6790
    pub fn new() -> Self {
147
6790
        Self {
148
6790
            hash: HashXBuilder::new(),
149
6790
        }
150
6790
    }
151

            
152
    /// Select a new [`RuntimeOption`].
153
    pub fn runtime(&mut self, runtime: RuntimeOption) -> &mut Self {
154
        self.hash.runtime(runtime);
155
        self
156
    }
157

            
158
    /// Build an [`EquiX`] instance with a challenge string and the
159
    /// selected options.
160
    ///
161
    /// It's normal for this to fail with a [`HashError::ProgramConstraints`]
162
    /// for a small fraction of challenge values. Those challenges must be
163
    /// skipped by solvers and rejected by verifiers.
164
7840
    pub fn build(&self, challenge: &[u8]) -> Result<EquiX, Error> {
165
7840
        match self.hash.build(challenge) {
166
420
            Err(e) => Err(Error::Hash(e)),
167
7420
            Ok(hash) => Ok(EquiX { hash }),
168
        }
169
7840
    }
170

            
171
    /// Search for solutions to a particular challenge.
172
    ///
173
    /// Each solve invocation returns zero or more solutions.
174
    /// Memory for the solver is allocated dynamically and not reused.
175
    ///
176
    /// It's normal for this to fail with a [`HashError::ProgramConstraints`]
177
    /// for a small fraction of challenge values. Those challenges must be
178
    /// skipped by solvers and rejected by verifiers.
179
    pub fn solve(&self, challenge: &[u8]) -> Result<SolutionArray, Error> {
180
        Ok(self.build(challenge)?.solve())
181
    }
182

            
183
    /// Check a [`Solution`] against a particular challenge string.
184
    ///
185
    /// Having a [`Solution`] instance guarantees that the order of items
186
    /// has already been checked. This only needs to check hash tree sums.
187
    /// Returns either `Ok` or [`Error::HashSum`].
188
1680
    pub fn verify(&self, challenge: &[u8], solution: &Solution) -> Result<(), Error> {
189
1680
        self.build(challenge)?.verify(solution)
190
1680
    }
191

            
192
    /// Check a [`SolutionItemArray`].
193
    ///
194
    /// Returns an error if the array is not a well formed [`Solution`] or it's
195
    /// not suitable for the given challenge.
196
    pub fn verify_array(&self, challenge: &[u8], array: &SolutionItemArray) -> Result<(), Error> {
197
        // Check Solution validity before we even construct the instance
198
        self.verify(challenge, &Solution::try_from_array(array)?)
199
    }
200

            
201
    /// Check a [`SolutionByteArray`].
202
    ///
203
    /// Returns an error if the array is not a well formed [`Solution`] or it's
204
    /// not suitable for the given challenge.
205
    pub fn verify_bytes(&self, challenge: &[u8], array: &SolutionByteArray) -> Result<(), Error> {
206
        self.verify(challenge, &Solution::try_from_bytes(array)?)
207
    }
208
}
209

            
210
impl Default for EquiXBuilder {
211
3640
    fn default() -> Self {
212
3640
        Self::new()
213
3640
    }
214
}
215

            
216
/// Search for solutions, using default [`EquiXBuilder`] options.
217
///
218
/// Each solve invocation returns zero or more solutions.
219
/// Memory for the solver is allocated dynamically and not reused.
220
///
221
/// It's normal for this to fail with a [`HashError::ProgramConstraints`] for
222
/// a small fraction of challenge values. Those challenges must be skipped
223
/// by solvers and rejected by verifiers.
224
pub fn solve(challenge: &[u8]) -> Result<SolutionArray, Error> {
225
    Ok(EquiX::new(challenge)?.solve())
226
}
227

            
228
/// Check a [`Solution`] against a particular challenge.
229
///
230
/// Having a [`Solution`] instance guarantees that the order of items
231
/// has already been checked. This only needs to check hash tree sums.
232
/// Returns either `Ok` or [`Error::HashSum`].
233
///
234
/// Uses default [`EquiXBuilder`] options.
235
210
pub fn verify(challenge: &[u8], solution: &Solution) -> Result<(), Error> {
236
210
    EquiX::new(challenge)?.verify(solution)
237
210
}
238

            
239
/// Check a [`SolutionItemArray`].
240
///
241
/// Returns an error if the array is not a well formed [`Solution`] or it's
242
/// not suitable for the given challenge.
243
///
244
/// Uses default [`EquiXBuilder`] options.
245
280
pub fn verify_array(challenge: &[u8], array: &SolutionItemArray) -> Result<(), Error> {
246
    // Check Solution validity before we even construct the instance
247
280
    verify(challenge, &Solution::try_from_array(array)?)
248
280
}
249

            
250
/// Check a [`SolutionByteArray`].
251
///
252
/// Returns an error if the array is not a well formed [`Solution`] or it's
253
/// not suitable for the given challenge.
254
///
255
/// Uses default [`EquiXBuilder`] options.
256
pub fn verify_bytes(challenge: &[u8], array: &SolutionByteArray) -> Result<(), Error> {
257
    // Check Solution validity before we even construct the instance
258
    verify(challenge, &Solution::try_from_bytes(array)?)
259
}