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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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