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
// TODO: add to the list maintained by maint/add_warning once it's available on all crates
53
#![warn(unnameable_types)]
54

            
55
mod bucket_array;
56
mod collision;
57
mod err;
58
mod solution;
59
mod solver;
60

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

            
66
use hashx::{HashX, HashXBuilder};
67

            
68
pub use hashx::{Runtime, RuntimeOption};
69

            
70
pub use err::{Error, HashError};
71
pub use solution::{Solution, SolutionArray, SolutionByteArray, SolutionItem, SolutionItemArray};
72
pub use solver::SolverMemory;
73

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
213
impl Default for EquiXBuilder {
214
3640
    fn default() -> Self {
215
3640
        Self::new()
216
3640
    }
217
}
218

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

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

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

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