hyphae-engine 1.0.1

Embeddable facade for the autonomous, durable, and verifiable Hyphae data engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// SPDX-License-Identifier: Apache-2.0

use std::{
    fs::{File, Metadata, OpenOptions},
    io::{Read, Write},
    path::Path,
    time::Duration,
    time::Instant,
};

use hyphae_query::{BoundedQueryError, Record, execute_with_byte_limit};
use hyphae_storage::{SnapshotError, load_snapshot_with_timeout};

use super::{
    MAX_RESULT_PROOF_BYTES, ProofAnchor, ProofError, ProvenOperation, ProvenResult, ResultProof,
    VerificationLimits, VerificationReport, decode_proof, encode_proof,
};
use crate::decode_document;

const PROOF_READ_BUFFER_BYTES: usize = 64 * 1024;

/// Writes a canonical result proof to a new file and synchronizes it.
///
/// Existing paths are never replaced.
///
/// # Errors
///
/// Returns a proof encoding, path, create, write, or synchronization error.
pub fn write_result_proof(path: impl AsRef<Path>, proof: &ResultProof) -> Result<(), ProofError> {
    let encoded = encode_proof(proof)?;
    let mut file = OpenOptions::new().create_new(true).write(true).open(path)?;
    file.write_all(&encoded)?;
    file.sync_all()?;
    Ok(())
}

/// Reads and verifies one canonical result-proof file under a byte limit.
///
/// # Errors
///
/// Returns an I/O, resource-limit, framing, canonicality, checksum, or digest
/// error.
pub fn read_result_proof(
    path: impl AsRef<Path>,
    maximum_bytes: u64,
) -> Result<ResultProof, ProofError> {
    let mut no_deadline = || Ok(());
    decode_proof(&read_result_proof_bytes(
        path,
        maximum_bytes,
        &mut no_deadline,
    )?)
}

/// Verifies a result proof completely offline against a trusted anchor and
/// canonical snapshot witness.
///
/// # Errors
///
/// Returns an error for any proof or snapshot corruption, wrong anchor,
/// resource exhaustion, document failure, timeout, or replay mismatch. No
/// partial result is accepted.
pub fn verify_result_proof(
    proof_path: impl AsRef<Path>,
    snapshot_path: impl AsRef<Path>,
    expected_anchor_digest: [u8; 32],
    limits: &VerificationLimits,
) -> Result<VerificationReport, ProofError> {
    let started = Instant::now();
    let mut check_read_deadline = || check_timeout(started, limits);
    let proof = decode_proof(&read_result_proof_bytes(
        proof_path,
        limits.proof_bytes,
        &mut check_read_deadline,
    )?)?;
    check_timeout(started, limits)?;

    let anchor_digest = proof.anchor_digest();
    if anchor_digest != expected_anchor_digest {
        return Err(ProofError::AnchorMismatch);
    }

    let snapshot = match load_snapshot_with_timeout(
        snapshot_path,
        &limits.snapshot,
        remaining_timeout(started, limits)?,
    ) {
        Err(error) if error.is_timeout() => return Err(ProofError::TimedOut),
        Err(error) => return Err(error.into()),
        Ok(snapshot) => snapshot,
    };
    check_timeout(started, limits)?;
    if ProofAnchor::from_snapshot(&snapshot.info) != *proof.anchor() {
        return Err(ProofError::SnapshotAnchorMismatch);
    }

    let mut records = Vec::with_capacity(snapshot.entries.len());
    for entry in snapshot.entries {
        check_timeout(started, limits)?;
        records.push(Record {
            key: entry.key,
            value: decode_document(&entry.value)?,
        });
    }

    let verified_result = match (proof.operation(), proof.result()) {
        (ProvenOperation::Get { key }, ProvenResult::Get(expected)) => {
            let actual = records
                .binary_search_by(|record| record.key.as_slice().cmp(key))
                .ok()
                .map(|index| records[index].clone());
            if &actual != expected {
                return Err(ProofError::ReexecutionMismatch);
            }
            ProvenResult::Get(actual)
        }
        (ProvenOperation::Query(query), ProvenResult::Query(expected)) => {
            let query_limits = hyphae_query::ExecutionLimits {
                timeout: remaining_timeout(started, limits)?.min(limits.query.timeout),
                ..limits.query.clone()
            };
            let actual = execute_with_byte_limit(
                &[records.as_slice()],
                query,
                &query_limits,
                limits.snapshot.decoded_bytes,
            )
            .map_err(|source| match source {
                BoundedQueryError::Query(source) => ProofError::from(source),
                BoundedQueryError::RecordDocument(source) => ProofError::from(source),
                BoundedQueryError::ScannedByteBudgetExceeded { maximum } => {
                    ProofError::from(SnapshotError::DecodedBytesLimitExceeded { maximum })
                }
            })?;
            if &actual != expected {
                return Err(ProofError::ReexecutionMismatch);
            }
            ProvenResult::Query(actual)
        }
        _ => return Err(ProofError::OperationResultMismatch),
    };
    check_timeout(started, limits)?;

    Ok(VerificationReport {
        anchor: proof.anchor().clone(),
        anchor_digest,
        proof_digest: proof.proof_digest(),
        result: verified_result,
    })
}

fn read_result_proof_bytes(
    path: impl AsRef<Path>,
    maximum_bytes: u64,
    check_deadline: &mut impl FnMut() -> Result<(), ProofError>,
) -> Result<Vec<u8>, ProofError> {
    check_deadline()?;
    let path = path.as_ref();
    let path_metadata = std::fs::metadata(path)?;
    check_deadline()?;
    ensure_regular_proof_file(&path_metadata)?;

    let file = File::open(path)?;
    check_deadline()?;
    let initial_metadata = file.metadata()?;
    check_deadline()?;
    ensure_regular_proof_file(&initial_metadata)?;

    read_open_result_proof(
        file,
        &initial_metadata,
        maximum_bytes.min(MAX_RESULT_PROOF_BYTES),
        check_deadline,
    )
}

fn read_open_result_proof(
    mut file: File,
    initial_metadata: &Metadata,
    maximum_bytes: u64,
    check_deadline: &mut impl FnMut() -> Result<(), ProofError>,
) -> Result<Vec<u8>, ProofError> {
    let initial_length = initial_metadata.len();
    if initial_length > maximum_bytes {
        return Err(ProofError::ProofLimitExceeded {
            actual: initial_length,
            maximum: maximum_bytes,
        });
    }
    let capacity = usize::try_from(initial_length).map_err(|_| ProofError::LengthOverflow)?;
    let mut encoded = Vec::with_capacity(capacity);
    let mut remaining = maximum_bytes
        .checked_add(1)
        .ok_or(ProofError::LengthOverflow)?;
    let mut buffer = vec![0_u8; PROOF_READ_BUFFER_BYTES];
    while remaining > 0 {
        check_deadline()?;
        let read_length = usize::try_from(remaining.min(PROOF_READ_BUFFER_BYTES as u64))
            .map_err(|_| ProofError::LengthOverflow)?;
        let read = file.read(&mut buffer[..read_length])?;
        check_deadline()?;
        if read == 0 {
            break;
        }
        encoded.extend_from_slice(&buffer[..read]);
        remaining = remaining
            .checked_sub(u64::try_from(read).map_err(|_| ProofError::LengthOverflow)?)
            .ok_or(ProofError::LengthOverflow)?;
    }

    let final_metadata = file.metadata()?;
    check_deadline()?;
    ensure_regular_proof_file(&final_metadata)?;
    let actual = u64::try_from(encoded.len()).map_err(|_| ProofError::LengthOverflow)?;
    let observed = actual.max(final_metadata.len());
    if observed > maximum_bytes {
        return Err(ProofError::ProofLimitExceeded {
            actual: observed,
            maximum: maximum_bytes,
        });
    }
    if actual != initial_length || final_metadata.len() != initial_length {
        return Err(ProofError::Invalid {
            reason: "proof changed while being read",
        });
    }
    Ok(encoded)
}

fn ensure_regular_proof_file(metadata: &Metadata) -> Result<(), ProofError> {
    if metadata.is_file() {
        Ok(())
    } else {
        Err(ProofError::Invalid {
            reason: "proof path is not a regular file",
        })
    }
}

fn remaining_timeout(
    started: Instant,
    limits: &VerificationLimits,
) -> Result<Duration, ProofError> {
    let remaining = limits
        .timeout
        .checked_sub(started.elapsed())
        .ok_or(ProofError::TimedOut)?;
    if remaining.is_zero() {
        Err(ProofError::TimedOut)
    } else {
        Ok(remaining)
    }
}

fn check_timeout(started: Instant, limits: &VerificationLimits) -> Result<(), ProofError> {
    if started.elapsed() >= limits.timeout {
        Err(ProofError::TimedOut)
    } else {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::{collections::BTreeMap, error::Error, fs, io::Write as _, path::PathBuf};

    use hyphae_query::{ExecutionLimits, Filter, Query, Record, Value};
    use uuid::Uuid;

    use super::{
        PROOF_READ_BUFFER_BYTES, VerificationLimits, read_open_result_proof, read_result_proof,
        verify_result_proof, write_result_proof,
    };
    use crate::{HyphaeEngine, MAX_RESULT_PROOF_BYTES, ProofError, ProvenResult};

    struct TestDirectory {
        path: PathBuf,
    }

    impl TestDirectory {
        fn create() -> Result<Self, Box<dyn Error>> {
            let path = std::env::temp_dir()
                .join(format!("hyphae-proof-rehashed-tamper-{}", Uuid::now_v7()));
            fs::create_dir_all(&path)?;
            Ok(Self { path })
        }
    }

    impl Drop for TestDirectory {
        fn drop(&mut self) {
            let _ignored = fs::remove_dir_all(&self.path);
        }
    }

    #[test]
    fn result_proof_reader_enforces_the_canonical_hard_limit() -> Result<(), Box<dyn Error>> {
        let temporary = TestDirectory::create()?;
        let proof_path = temporary.path.join("oversized.hyproof");
        let file = fs::File::create(&proof_path)?;
        file.set_len(MAX_RESULT_PROOF_BYTES + 1)?;
        drop(file);

        assert!(matches!(
            read_result_proof(&proof_path, u64::MAX),
            Err(ProofError::ProofLimitExceeded {
                actual,
                maximum: MAX_RESULT_PROOF_BYTES,
            }) if actual == MAX_RESULT_PROOF_BYTES + 1
        ));
        Ok(())
    }

    #[test]
    fn result_proof_reader_detects_same_handle_growth() -> Result<(), Box<dyn Error>> {
        let temporary = TestDirectory::create()?;
        let proof_path = temporary.path.join("growing.hyproof");
        fs::write(&proof_path, b"initial")?;
        let file = fs::File::open(&proof_path)?;
        let initial_metadata = file.metadata()?;
        let mut writer = fs::OpenOptions::new().append(true).open(&proof_path)?;
        writer.write_all(b"-growth")?;
        writer.sync_all()?;
        drop(writer);

        let mut no_deadline = || Ok(());
        assert!(matches!(
            read_open_result_proof(file, &initial_metadata, 1024, &mut no_deadline),
            Err(ProofError::Invalid {
                reason: "proof changed while being read",
            })
        ));
        Ok(())
    }

    #[test]
    fn result_proof_reader_checks_deadline_between_chunks() -> Result<(), Box<dyn Error>> {
        let temporary = TestDirectory::create()?;
        let proof_path = temporary.path.join("timed.hyproof");
        fs::write(&proof_path, vec![0_u8; PROOF_READ_BUFFER_BYTES * 2])?;
        let file = fs::File::open(&proof_path)?;
        let initial_metadata = file.metadata()?;
        let mut checks = 0_u8;
        let mut deadline = || {
            checks += 1;
            if checks == 2 {
                Err(ProofError::TimedOut)
            } else {
                Ok(())
            }
        };

        assert!(matches!(
            read_open_result_proof(
                file,
                &initial_metadata,
                MAX_RESULT_PROOF_BYTES,
                &mut deadline,
            ),
            Err(ProofError::TimedOut)
        ));
        assert_eq!(checks, 2);
        Ok(())
    }

    #[test]
    fn self_consistently_rehashed_result_edits_are_rejected() -> Result<(), Box<dyn Error>> {
        let temporary = TestDirectory::create()?;
        let mut opened = HyphaeEngine::open(temporary.path.join("data"))?;
        opened.engine.put_records(
            Uuid::now_v7(),
            &[record(b"a", 1), record(b"b", 2), record(b"c", 3)],
        )?;
        let artifact = opened.engine.query_with_proof(
            &Query {
                filter: Filter::MatchAll,
                sort: Vec::new(),
                cursor: None,
                limit: 3,
                aggregation: None,
            },
            &ExecutionLimits::default(),
        )?;

        for (name, mutation) in [
            ("delete", 1_u8),
            ("insert", 2_u8),
            ("reorder", 3_u8),
            ("edit", 4_u8),
        ] {
            let mut forged = artifact.proof.clone();
            let ProvenResult::Query(result) = &mut forged.result else {
                return Err(ProofError::OperationResultMismatch.into());
            };
            match mutation {
                1 => {
                    result.rows.remove(0);
                }
                2 => result.rows.push(result.rows[0].clone()),
                3 => result.rows.swap(0, 1),
                4 => result.rows[0].value = Value::Integer(999),
                _ => return Err(ProofError::OperationResultMismatch.into()),
            }
            let proof_path = temporary.path.join(format!("{name}.hyproof"));
            write_result_proof(&proof_path, &forged)?;
            assert!(matches!(
                verify_result_proof(
                    &proof_path,
                    &artifact.snapshot.path,
                    artifact.proof.anchor_digest(),
                    &VerificationLimits::default(),
                ),
                Err(ProofError::ReexecutionMismatch)
            ));
        }
        Ok(())
    }

    fn record(key: &[u8], score: i64) -> Record {
        Record::new(
            key,
            Value::Object(BTreeMap::from([(
                "score".to_owned(),
                Value::Integer(score),
            )])),
        )
    }
}