-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlog_ops.rs
More file actions
2647 lines (2407 loc) · 94.2 KB
/
Copy pathlog_ops.rs
File metadata and controls
2647 lines (2407 loc) · 94.2 KB
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Ported from "sunlight" (https://github.com/FiloSottile/sunlight)
// Copyright 2023 The Sunlight Authors
// Licensed under ISC License found in the LICENSE file or at https://opensource.org/license/isc-license-txt
//
// This ports code from the original Go project "sunlight" and adapts it to Rust idioms.
//
// Modifications and Rust implementation Copyright (c) 2025 Cloudflare, Inc.
// Licensed under the BSD-3-Clause license found in the LICENSE file or at https://opensource.org/licenses/BSD-3-Clause
//! Core functionality for a [Static CT API](https://c2sp.org/static-ct-api) log, including
//! creating and loading logs from persistent storage, adding leaves to logs, and sequencing logs.
//!
//! This file contains code ported from the original project [sunlight](https://github.com/FiloSottile/sunlight).
//!
//! References:
//! - [http.go](https://github.com/FiloSottile/sunlight/blob/36be227ff4599ac11afe3cec37a5febcd61da16a/internal/ctlog/http.go)
//! - [ctlog.go](https://github.com/FiloSottile/sunlight/blob/36be227ff4599ac11afe3cec37a5febcd61da16a/internal/ctlog/ctlog.go)
//! - [ctlog_test.go](https://github.com/FiloSottile/sunlight/blob/36be227ff4599ac11afe3cec37a5febcd61da16a/internal/ctlog/ctlog_test.go)
//! - [testlog_test.go](https://github.com/FiloSottile/sunlight/blob/36be227ff4599ac11afe3cec37a5febcd61da16a/internal/ctlog/testlog_test.go)
use crate::{
metrics::{millis_diff_as_secs, AsF64, SequencerMetrics},
util::now_millis,
CacheRead, CacheWrite, LockBackend, LookupKey, ObjectBackend, SequenceMetadata,
SequencerConfig,
};
use anyhow::{anyhow, bail};
use futures_util::future::try_join_all;
use log::{debug, error, info, trace, warn};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use signed_note::VerifierList;
use std::collections::HashMap;
use std::{
cell::RefCell,
cmp::{Ord, Ordering},
string::String,
sync::LazyLock,
};
use thiserror::Error;
use tlog_tiles::{
Hash, HashReader, LogEntry, PendingLogEntry, PreloadedTlogTileReader, Proof, Subtree,
TileHashReader, TileIterator, TlogError, TlogTile, TlogTileRecorder, TreeWithTimestamp,
UnixTimestamp, HASH_SIZE,
};
use tokio::sync::watch::{channel, Receiver, Sender};
/// The maximum tile level is 63 (<c2sp.org/static-ct-api>), so safe to use [`u8::MAX`] as
/// the special level for data tiles. The Go implementation uses -1.
const DATA_TILE_LEVEL_KEY: u8 = u8::MAX;
/// Same as above, anything above 63 is fine to use as the level key.
const AUX_TILE_LEVEL_KEY: u8 = u8::MAX - 1;
/// Path used to store checkpoints, both in the object storage and lock backends.
pub const CHECKPOINT_KEY: &str = "checkpoint";
/// Path used to store staging bundles in the lock backend.
const STAGING_KEY: &str = "staging";
// Limit on the number of entries per batch. Tune this parameter to avoid
// running into various size limitations. For instance, unexpectedly large
// leaves (e.g., with PQ signatures) could cause us to exceed the 128MB Workers
// memory limit. Storing 4000 10KB certificates is 40MB.
const MAX_POOL_SIZE: usize = 4000;
/// Ephemeral state for pooling entries to the CT log.
///
/// The pool is written to by `add_leaf_to_pool`, and by the sequencer
/// when rotating pending and in-sequencing entries.
///
/// As long as the above-mentioned blocks run synchronously (no 'await's), Durable Objects'
/// single-threaded execution guarantees that `add_leaf_to_pool` will never add to a pool that
/// already started sequencing, and that cache reads will see entries from older pools before
/// they are rotated out of `in_sequencing`.
/// <https://blog.cloudflare.com/durable-objects-easy-fast-correct-choose-three/#background-durable-objects-are-single-threaded>
#[derive(Debug)]
pub(crate) struct PoolState<P: PendingLogEntry> {
// How many times sequencing has been skipped for any entries in the pool.
sequence_skips: usize,
// Entries that are ready to be sequenced, along with the Sender used to
// send metadata to receivers once the corresponding entry is sequenced.
pending_entries: Vec<(P, Sender<SequenceMetadata>)>,
// Deduplication cache for entries currently pending sequencing.
pending_dedup: HashMap<LookupKey, Receiver<SequenceMetadata>>,
// Deduplication cache for entries currently being sequenced.
in_sequencing_dedup: HashMap<LookupKey, Receiver<SequenceMetadata>>,
// Ring buffer tracking insertion timestamps for the most recent entries
// that are potentially skippable.
leftover_timestamps_millis: [UnixTimestamp; TlogTile::FULL_WIDTH as usize],
// The next slot to insert an entry timestamp, when reduced modulo
// `TlogTile::FULL_WIDTH`.
leftover_timestamps_next_slot: usize,
}
impl<P: PendingLogEntry> Default for PoolState<P> {
fn default() -> Self {
PoolState {
sequence_skips: 0,
pending_entries: Vec::default(),
pending_dedup: HashMap::default(),
in_sequencing_dedup: HashMap::default(),
leftover_timestamps_millis: [0; TlogTile::FULL_WIDTH as usize],
leftover_timestamps_next_slot: 0,
}
}
}
impl<E: PendingLogEntry> PoolState<E> {
// Check if the key is already in the pool. If so, return a Receiver from
// which to read the entry metadata when it is sequenced.
fn check(&self, key: &LookupKey) -> Option<AddLeafResult> {
if let Some(rx) = self.in_sequencing_dedup.get(key) {
// Entry is being sequenced.
Some(AddLeafResult::Pending {
rx: rx.clone(),
source: PendingSource::InSequencing,
})
} else {
self.pending_dedup
.get(key)
.map(|rx| AddLeafResult::Pending {
rx: rx.clone(),
source: PendingSource::Pool,
})
}
}
// Add a new entry to the pool.
fn add(&mut self, key: LookupKey, entry: E) -> AddLeafResult {
if self.pending_entries.len() >= MAX_POOL_SIZE {
return AddLeafResult::RateLimited;
}
let (tx, rx) = channel((0, 0));
self.pending_entries.push((entry, tx));
self.pending_dedup.insert(key, rx.clone());
self.leftover_timestamps_millis
[self.leftover_timestamps_next_slot % TlogTile::FULL_WIDTH as usize] = now_millis();
self.leftover_timestamps_next_slot += 1;
AddLeafResult::Pending {
rx,
source: PendingSource::Sequencer,
}
}
// Take the entries from the pool that are ready to be sequenced, along with
// the corresponding Senders to update when the entries have been sequenced.
//
// Skip sequencing leftover entries that would be published as a partial
// tile unless they have already been held back `max_sequence_skips` times
// or have been in the pool longer than `sequence_skip_threshold_millis`.
//
// The return value is an Option that indicates whether or not a new
// checkpoint should be produced (even if there are no new entries).
fn take(
&mut self,
old_size: u64,
max_sequence_skips: usize,
sequence_skip_threshold_millis: Option<u64>,
) -> Option<Vec<(E, Sender<SequenceMetadata>)>> {
let new_size = old_size + self.pending_entries.len() as u64;
let publishing_full_tile =
new_size / u64::from(TlogTile::FULL_WIDTH) > old_size / u64::from(TlogTile::FULL_WIDTH);
let num_leftover_entries =
usize::try_from(new_size % u64::from(TlogTile::FULL_WIDTH)).unwrap();
let oldest_leftover_timestamp_millis: UnixTimestamp = self.leftover_timestamps_millis[(self
.leftover_timestamps_next_slot
- num_leftover_entries)
% TlogTile::FULL_WIDTH as usize];
let oldest_leftover_is_expired = sequence_skip_threshold_millis
.is_some_and(|threshold| now_millis() > oldest_leftover_timestamp_millis + threshold);
if publishing_full_tile && max_sequence_skips > 0 && !oldest_leftover_is_expired {
// Sequence full tiles and skip the rest.
// If there are leftover entries, this is the first time they have
// been skipped. Otherwise, set skip count to zero.
self.sequence_skips = usize::from(num_leftover_entries != 0);
let split_index = self.pending_entries.len() - num_leftover_entries;
let leftover_entries = self.pending_entries.split_off(split_index);
let leftover_dedup = leftover_entries
.iter()
.filter_map(|(entry, _)| {
let lookup_key = entry.lookup_key();
self.pending_dedup
.remove(&lookup_key)
.map(|rx| (lookup_key, rx))
})
.collect::<HashMap<_, _>>();
self.in_sequencing_dedup = std::mem::replace(&mut self.pending_dedup, leftover_dedup);
Some(std::mem::replace(
&mut self.pending_entries,
leftover_entries,
))
} else if self.sequence_skips >= max_sequence_skips || oldest_leftover_is_expired {
// Sequence everything. We have reached the skip threshold, and even
// if there are no entries, we want to create a new checkpoint.
self.sequence_skips = 0;
self.in_sequencing_dedup = std::mem::take(&mut self.pending_dedup);
Some(std::mem::take(&mut self.pending_entries))
} else {
// Skip this checkpoint. There are no full tiles to sequence, and
// we're below the thresholds to skip the leftover entries.
self.sequence_skips += 1;
None
}
}
// Reset the map of in-sequencing entries. This should be called after
// sequencing completes since the entries are either in the deduplication
// cache or finalized with an error. In the latter case, we don't want
// a resubmit to deduplicate against the failed sequencing.
fn reset_in_sequencing_dedup(&mut self) {
self.in_sequencing_dedup.clear();
}
}
// State owned by the sequencing loop.
#[derive(Default, Debug, Clone)]
pub(crate) struct SequenceState {
tree: TreeWithTimestamp,
checkpoint: Vec<u8>,
// edge_tiles is a map from level to the right-most tile of that level.
edge_tiles: HashMap<u8, TileWithBytes>,
}
/// A description of a transparency log tile along with the contained bytes.
#[derive(Clone, Default, Debug)]
struct TileWithBytes {
tile: TlogTile,
b: Vec<u8>,
}
/// An error that can occur when creating a log.
#[derive(Error, Debug)]
pub(crate) enum CreateError {
#[error("log exists")]
LogExists,
#[error("failed to create log: {}", .0)]
Other(#[from] anyhow::Error),
}
/// Create a log, updating the object and lock backends.
/// This should only ever need to be called once but is safe to call multiple times.
///
/// If the log already exists, returns an [`CreateError::LogExists`]
/// to allow the caller to differentiate it from other errors.
pub(crate) async fn create_log(
config: &SequencerConfig,
object: &impl ObjectBackend,
lock: &impl LockBackend,
) -> Result<(), CreateError> {
let name = &config.name;
// To reset a dev log without deleting the existing checkpoints from DO
// storage and R2, you can temporarily disable the below checks for the
// specific targeted log name. Make sure to clean up afterwards or the log
// will keep reseting every time the sequencer DO is re-initialized.
//
// if name != "dev1" {
// <check if log exists>
// }
if lock.get(CHECKPOINT_KEY).await.is_ok() {
return Err(CreateError::LogExists);
}
if object
.fetch(CHECKPOINT_KEY)
.await
.map_err(|e| anyhow!("failed to retrieve checkpoint from object storage: {}", e))?
.is_some()
{
return Err(
anyhow!("checkpoint missing from database but present in object storage").into(),
);
}
let timestamp = now_millis();
let tree = TreeWithTimestamp::new(0, tlog_tiles::EMPTY_HASH, timestamp);
// Construct the checkpoint signers
let dyn_signers = config
.checkpoint_signers
.iter()
.map(AsRef::as_ref)
.collect::<Vec<_>>();
// Construct the checkpoint extension
let extensions = (config.checkpoint_extension)(timestamp);
let sth = tree
.sign(
config.origin.as_str(),
&extensions.iter().map(String::as_str).collect::<Vec<_>>(),
&dyn_signers,
&mut rand::thread_rng(),
)
.map_err(|e| anyhow!("failed to sign checkpoint: {}", e))?;
lock.put(CHECKPOINT_KEY, &sth)
.await
.map_err(|e| anyhow!("failed to upload checkpoint to lock backend: {}", e))?;
object
.upload(CHECKPOINT_KEY, sth, &OPTS_CHECKPOINT)
.await
.map_err(|e| anyhow!("failed to upload checkpoint to object backend: {}", e))?;
info!("{name}: Created log; timestamp={timestamp}");
Ok(())
}
impl SequenceState {
/// Loads the sequencing state for a log from object and lock backends.
/// This is called when initially loading a log (e.g., when it is started on a new machine),
/// and when reloading (e.g., to recover after a fatal sequencing error).
///
/// This will return an error if the log has not been created, or if recovery fails.
#[allow(clippy::too_many_lines)]
pub(crate) async fn load<L: LogEntry>(
config: &SequencerConfig,
object: &impl ObjectBackend,
lock: &impl LockBackend,
) -> Result<Self, anyhow::Error> {
// Load the checkpoint from the DO storage. If we crashed during serialization, the one
// in DO storage is going to be the latest.
let stored_checkpoint = lock.get(CHECKPOINT_KEY).await?;
let name = &config.name;
debug!(
"{name}: Loaded checkpoint; checkpoint={}",
std::str::from_utf8(&stored_checkpoint)?
);
// Construct the VerifierList containing the signing and witness pubkeys
let verifiers = VerifierList::new(
config
.checkpoint_signers
.iter()
.map(|s| s.verifier())
.collect(),
);
let (c, timestamp) = tlog_tiles::open_checkpoint(
config.origin.as_str(),
&verifiers,
now_millis(),
&stored_checkpoint,
)?;
let timestamp = match timestamp {
Some(timestamp) => timestamp,
None if L::REQUIRE_CHECKPOINT_TIMESTAMP => {
bail!("no verifiers with timestamped signatures were used")
}
_ => 0,
};
// Load the checkpoint from the object storage backend, verify it, and compare it to the
// DO storage checkpoint.
let sth = object
.fetch(CHECKPOINT_KEY)
.await?
.ok_or(anyhow!("no checkpoint in object storage"))?;
debug!(
"{name}: Loaded checkpoint from object storage; checkpoint={}",
std::str::from_utf8(&stored_checkpoint)?
);
let (c1, _) =
tlog_tiles::open_checkpoint(config.origin.as_str(), &verifiers, now_millis(), &sth)?;
match (Ord::cmp(&c1.size(), &c.size()), c1.hash() == c.hash()) {
(Ordering::Equal, false) => {
bail!(
"{name}: checkpoint hash mismatch: {} != {}",
c1.hash(),
c.hash()
)
}
(Ordering::Greater, _) => bail!(
"{name}: checkpoint in object storage is newer than DO storage checkpoint: {} > {}",
c1.size(),
c.size()
),
(Ordering::Less, _) => {
// It's possible that we crashed between committing a new checkpoint to DO storage and
// uploading it to the object storage backend. Apply the staged tiles before continuing.
warn!(
"{name}: Checkpoint in object storage is older than DO storage checkpoint; old_size={}, size={}", c1.size(), c.size()
);
let staged_uploads = lock.get_multipart(STAGING_KEY).await?;
apply_staged_uploads(object, &staged_uploads, c.size(), c.hash()).await?;
}
(Ordering::Equal, true) => {} // Normal case: the sizes are the same and the hashes match.
}
// Fetch the tiles on the right edge, and verify them against the checkpoint.
let mut edge_tiles = HashMap::new();
if c.size() > 0 {
// Fetch the right-most tree tiles.
edge_tiles = read_edge_tiles(object, c.size(), c.hash()).await?;
// Fetch the right-most data tile.
let (level0_tile, level0_tile_bytes) = {
let x = edge_tiles.get(&0).ok_or(anyhow!("no level 0 tile found"))?;
(x.tile, &x.b)
};
let data_tile = level0_tile.with_data_path(L::Pending::DATA_TILE_PATH);
let data_tile_bytes = object
.fetch(&data_tile.path())
.await?
.ok_or(anyhow!("no data tile in object storage"))?;
// Verify the data tile against the level 0 tile.
let start = u64::from(TlogTile::FULL_WIDTH) * data_tile.level_index();
for (i, entry) in
TileIterator::<L>::new(&data_tile_bytes, data_tile.width() as usize).enumerate()
{
let got = entry?.merkle_tree_leaf();
let exp = level0_tile.hash_at_index(
level0_tile_bytes,
tlog_tiles::stored_hash_index(0, start + i as u64),
)?;
if got != exp {
bail!(
"tile leaf entry {} hashes to {got}, level 0 hash is {exp}",
start + i as u64,
);
}
}
// Store the data tile.
edge_tiles.insert(
DATA_TILE_LEVEL_KEY,
TileWithBytes {
tile: data_tile,
b: data_tile_bytes,
},
);
// Fetch and store the right-most auxiliary tile, if configured.
if let Some(path_elem) = L::Pending::AUX_TILE_PATH {
let aux_tile = level0_tile.with_data_path(path_elem);
let aux_tile_bytes = object
.fetch(&aux_tile.path())
.await?
.ok_or(anyhow!("no auxiliary tile in object storage"))?;
edge_tiles.insert(
AUX_TILE_LEVEL_KEY,
TileWithBytes {
tile: aux_tile,
b: aux_tile_bytes,
},
);
}
}
for tile in &edge_tiles {
trace!("{name}: Edge tile; tile={tile:?}");
}
info!(
"{name}: Loaded log; size={}, timestamp={timestamp}",
c.size()
);
Ok(Self {
edge_tiles,
tree: TreeWithTimestamp::new(c.size(), *c.hash(), timestamp),
checkpoint: stored_checkpoint,
})
}
/// Returns the current checkpoint
pub(crate) fn checkpoint(&self) -> &[u8] {
&self.checkpoint
}
/// Proves inclusion of the last leaf in the current tree.
#[cfg(test)]
pub(crate) fn prove_inclusion_of_last_elem(&self) -> Proof {
let tree_size = self.tree.size();
let reader = HashReaderWithOverlay {
edge_tiles: &self.edge_tiles,
overlay: &HashMap::default(),
};
// We can unwrap because edge_tiles is guaranteed to contain the tiles
// necessary to prove this.
tlog_tiles::inclusion_proof(tree_size, tree_size - 1, &reader).unwrap()
}
/// Proves that this tree of size n is compatible with the subtree of size
/// n-1. In other words, prove that we appended 1 element to the tree.
///
/// # Errors
/// Errors when the last tree was size 0. We cannot prove consistency with
/// respect to an empty tree
#[cfg(test)]
pub(crate) fn prove_consistency_of_single_append(&self) -> Result<Proof, TlogError> {
let tree_size = self.tree.size();
let reader = HashReaderWithOverlay {
edge_tiles: &self.edge_tiles,
overlay: &HashMap::default(),
};
tlog_tiles::consistency_proof(tree_size, tree_size - 1, &reader)
}
}
#[derive(Error, Debug)]
pub enum ProofError {
#[error(transparent)]
Tlog(#[from] tlog_tiles::TlogError),
#[error(transparent)]
Other(#[from] anyhow::Error),
}
/// Returns an inclusion proof that the leaf at index `leaf_index` is included
/// in the current tree of size `cur_tree_size` with hash `cur_tree_hash`.
///
/// # Errors
///
/// Errors when the leaf index is not within the tree, or the desired tiles do
/// not exist as bucket objects.
pub async fn prove_inclusion(
cur_tree_size: u64,
cur_tree_hash: Hash,
leaf_index: u64,
object: &impl ObjectBackend,
) -> Result<Proof, ProofError> {
prove_subtree_inclusion(
cur_tree_size,
cur_tree_hash,
0,
cur_tree_size,
leaf_index,
object,
)
.await
}
/// Returns an inclusion proof that the leaf at index `leaf_index` is included
/// in the subtree `[start, end)`. `cur_tree_size` and `cur_tree_hash` allow us
/// to select the correct partial tiles.
///
/// # Errors
///
/// Errors when the leaf index is not within the subtree, or the desired tiles
/// do not exist as bucket objects.
pub async fn prove_subtree_inclusion(
cur_tree_size: u64,
cur_tree_hash: Hash,
start: u64,
end: u64,
leaf_index: u64,
object: &impl ObjectBackend,
) -> Result<Proof, ProofError> {
// Fetch the tiles needed for the proof.
let n = &Subtree::new(start, end)?;
let indexes = tlog_tiles::subtree_inclusion_proof_indexes(n, leaf_index)?;
let tile_reader = tile_reader_for_indexes(cur_tree_size, &indexes, object).await?;
let hash_reader = TileHashReader::new(cur_tree_size, cur_tree_hash, &tile_reader);
// Construct the proof.
Ok(tlog_tiles::subtree_inclusion_proof(
n,
leaf_index,
&hash_reader,
)?)
}
/// Returns a consistency proof that the tree with size `cur_tree_size` and hash
/// `cur_tree_hash` is an extension of the tree with `prev_tree_size`.
///
/// # Errors
///
/// Errors when the desired tiles do not exist as bucket objects, or if the
/// proof fails.
pub async fn prove_consistency(
cur_tree_hash: Hash,
cur_tree_size: u64,
prev_tree_size: u64,
object: &impl ObjectBackend,
) -> Result<Proof, ProofError> {
prove_subtree_consistency(cur_tree_hash, cur_tree_size, 0, prev_tree_size, object).await
}
/// Returns a consistency proof that the tree with size `cur_tree_size` and hash
/// `cur_tree_hash` is consistent with the subtree `[start, end)`.
///
/// # Errors
///
/// Errors when the desired tiles do not exist as bucket objects, or if the
/// proof fails.
pub async fn prove_subtree_consistency(
cur_tree_hash: Hash,
cur_tree_size: u64,
start: u64,
end: u64,
object: &impl ObjectBackend,
) -> Result<Proof, ProofError> {
let m = &Subtree::new(start, end)?;
// Fetch the tiles needed for the proof.
let indexes = tlog_tiles::subtree_consistency_proof_indexes(cur_tree_size, m)?;
let tile_reader = tile_reader_for_indexes(cur_tree_size, &indexes, object).await?;
let hash_reader = TileHashReader::new(cur_tree_size, cur_tree_hash, &tile_reader);
// Construct the proof.
Ok(tlog_tiles::subtree_consistency_proof(
cur_tree_size,
m,
&hash_reader,
)?)
}
/// Fetch the tree tiles containing the nodes at the requested indexes, as well
/// as all tiles needed to verify those nodes.
async fn tile_reader_for_indexes(
tree_size: u64,
indexes: &[u64],
object: &impl ObjectBackend,
) -> Result<PreloadedTlogTileReader, anyhow::Error> {
// Record the tiles that we'll need.
let tiles_to_fetch = {
let tile_reader = TlogTileRecorder::default();
// Pass in a dummy tree hash since 'read_hashes' doesn't use it before
// it short-circuits with `TlogError::RecordedTilesOnly`.
let hash_reader = TileHashReader::new(tree_size, Hash::default(), &tile_reader);
// `TileRecorder` is guaranteed to make `read_hashes` return a
// `TlogError::RecordedTilesOnly` error. This is fine, because it
// already collected the data we needed.
match hash_reader.read_hashes(indexes) {
Err(TlogError::RecordedTilesOnly) => {}
_ => bail!("expected to get a RecordedTilesOnly error"),
}
tile_reader.0.into_inner()
};
// Fetch all the tiles needed to fetch and authenticate the nodes at the
// requested indexes.
let mut all_tile_data = HashMap::new();
for tile in tiles_to_fetch {
let Some(tile_data) = object.fetch(&tile.path()).await? else {
bail!("tile not found in object backend: {}", tile.path());
};
all_tile_data.insert(tile, tile_data);
}
// Return a `PreloadedTlogTileReader` wrapping with the fetched tiles.
Ok(PreloadedTlogTileReader(all_tile_data))
}
/// Result of an [`add_leaf_to_pool`] request containing either a cached log
/// entry or a pending entry that must be resolved.
pub(crate) enum AddLeafResult {
Cached(SequenceMetadata),
Pending {
rx: Receiver<SequenceMetadata>,
source: PendingSource,
},
RateLimited,
}
impl AddLeafResult {
/// Resolve an `AddLeafResult` to a leaf entry, or None if the
/// entry was not sequenced.
pub(crate) async fn resolve(self) -> Option<SequenceMetadata> {
match self {
AddLeafResult::Cached(entry) => Some(entry),
AddLeafResult::Pending { mut rx, source: _ } => {
// Wait until sequencing completes for this entry's pool.
if rx.changed().await.is_ok() {
Some(*rx.borrow())
} else {
warn!("sender dropped");
None
}
}
AddLeafResult::RateLimited => None,
}
}
pub(crate) fn source(&self) -> &'static str {
match self {
AddLeafResult::Cached(_) => "cache",
AddLeafResult::RateLimited => "ratelimit",
AddLeafResult::Pending { rx: _, source } => match source {
PendingSource::InSequencing => "sequencing",
PendingSource::Pool => "pool",
PendingSource::Sequencer => "sequencer",
},
}
}
}
pub(crate) enum PendingSource {
InSequencing,
Pool,
Sequencer,
}
/// Add a leaf (a certificate or pre-certificate) to the pool of pending entries.
///
/// If the entry has already been sequenced and is in the cache, return immediately
/// with a [`AddLeafResult::Cached`]. If the pool is full, return
/// [`AddLeafResult::RateLimited`]. Otherwise, return a [`AddLeafResult::Pending`] which
/// can be resolved once the entry has been sequenced.
pub(crate) fn add_leaf_to_pool<E: PendingLogEntry>(
state: &RefCell<PoolState<E>>,
cache: &impl CacheRead,
config: &SequencerConfig,
entry: E,
) -> AddLeafResult {
let hash = entry.lookup_key();
let mut state = state.borrow_mut();
if !config.enable_dedup {
// Bypass deduplication and rate limit checks.
state.add(hash, entry)
} else if let Some(result) = state.check(&hash) {
// Entry is already pending or being sequenced.
result
} else if let Some(v) = cache.get_entry(&hash) {
// Entry is cached.
AddLeafResult::Cached(v)
} else {
// This is a new entry. Add it to the pool.
state.add(hash, entry)
}
}
/// Sequences the current pool of pending entries in the ephemeral state.
///
/// # Errors
///
/// Will return an error if sequencing fails with an error that requires the
/// sequencer to be re-initialized to get into a good state.
pub(crate) async fn sequence<L: LogEntry>(
pool_state: &RefCell<PoolState<L::Pending>>,
sequence_state: &RefCell<SequenceState>,
config: &SequencerConfig,
object: &impl ObjectBackend,
lock: &impl LockBackend,
cache: &impl CacheWrite,
metrics: &SequencerMetrics,
) -> Result<(), anyhow::Error> {
// Add the log's initial entry if needed.
if sequence_state.borrow().tree.size() == 0 {
if let Some(entry) = L::initial_entry() {
pool_state.borrow_mut().add(entry.lookup_key(), entry);
}
}
let Some(entries) = pool_state.borrow_mut().take(
sequence_state.borrow().tree.size(),
config.max_sequence_skips,
config.sequence_skip_threshold_millis,
) else {
// Skip this checkpoint. Nothing to sequence.
metrics.seq_count.with_label_values(&["skip"]).inc();
return Ok(());
};
metrics.seq_pool_size.observe(entries.len().as_f64());
let result = match sequence_entries::<L>(
sequence_state,
config,
object,
lock,
cache,
entries,
metrics,
)
.await
{
Ok(()) => {
metrics.seq_count.with_label_values(&["none"]).inc();
Ok(())
}
Err(SequenceError::Fatal(e)) => {
// The ephemeral sequence state may no longer be valid. Return an
// error so the caller can reload the log into a good state.
metrics.seq_count.with_label_values(&["fatal"]).inc();
error!("{}: Fatal sequencing error {e}", config.name);
Err(anyhow!(e))
}
Err(SequenceError::NonFatal(e)) => {
metrics.seq_count.with_label_values(&["non-fatal"]).inc();
error!("{}: Non-fatal sequencing error {e}", config.name);
Ok(())
}
};
// Once [`sequence_entries`] returns, the entries are either in the deduplication
// cache or finalized with an error. In the latter case, we don't want
// a resubmit to deduplicate against the failed sequencing.
pool_state.borrow_mut().reset_in_sequencing_dedup();
result
}
/// An error that can occur when sequencing a pool.
#[derive(Error, Debug)]
enum SequenceError {
#[error("fatal sequencing error: {}", .0)]
Fatal(String),
#[error("non-fatal sequencing error: {}", .0)]
NonFatal(String),
}
/// Sequences the passed-in pool of entries.
/// If the sequencing completes successfully, pending requests are notified.
/// If a non-fatal sequencing error occurs, pending requests will receive an error but the log will continue as normal.
/// If a fatal sequencing error occurs, the ephemeral log state must be reloaded before the next sequencing.
#[allow(clippy::too_many_lines)]
async fn sequence_entries<L: LogEntry>(
sequence_state: &RefCell<SequenceState>,
config: &SequencerConfig,
object: &impl ObjectBackend,
lock: &impl LockBackend,
cache: &impl CacheWrite,
entries: Vec<(L::Pending, Sender<SequenceMetadata>)>,
metrics: &SequencerMetrics,
) -> Result<(), SequenceError> {
let name = &config.name;
let SequenceState {
tree: old_tree,
checkpoint: old_checkpoint,
mut edge_tiles,
} = (*sequence_state.borrow()).clone();
let old_size = old_tree.size();
let old_time = old_tree.time();
let timestamp = now_millis();
// Load the current partial data tile, if any.
let mut tile_uploads: Vec<UploadAction> = Vec::new();
let mut data_tile = Vec::new();
if let Some(t) = edge_tiles.get(&DATA_TILE_LEVEL_KEY) {
if t.tile.width() < TlogTile::FULL_WIDTH {
data_tile.clone_from(&t.b);
}
}
// Load the current partial auxiliary tile, if configured.
let mut aux_tile = Vec::new();
if L::Pending::AUX_TILE_PATH.is_some() {
if let Some(t) = edge_tiles.get(&AUX_TILE_LEVEL_KEY) {
if t.tile.width() < TlogTile::FULL_WIDTH {
aux_tile.clone_from(&t.b);
}
}
}
let mut overlay = HashMap::new();
let mut n = old_size;
let mut sequenced_metadata = Vec::with_capacity(entries.len());
let mut cache_metadata = Vec::with_capacity(entries.len());
for (entry, sender) in entries {
// Add the entry and metadata to our lists of things sequenced
let metadata = (n, timestamp);
cache_metadata.push((entry.lookup_key(), metadata));
sequenced_metadata.push((sender, metadata));
// Write to the auxiliary tile, if configured.
if L::Pending::AUX_TILE_PATH.is_some() {
aux_tile.extend(entry.aux_entry());
}
let sequenced_entry = L::new(entry, metadata);
let tile_leaf = sequenced_entry.to_data_tile_entry();
let merkle_tree_leaf = sequenced_entry.merkle_tree_leaf();
metrics.seq_leaf_size.observe(tile_leaf.len().as_f64());
data_tile.extend(tile_leaf);
// Compute the new tree hashes and add them to the hashReader overlay
// (we will use them later to insert more leaves and finally to produce
// the new tiles).
let hashes = tlog_tiles::stored_hashes_for_record_hash(
n,
merkle_tree_leaf,
&HashReaderWithOverlay {
edge_tiles: &edge_tiles,
overlay: &overlay,
},
)
.map_err(|e| {
SequenceError::NonFatal(format!(
"couldn't compute new hashes for leaf {sequenced_entry:?}: {e}",
))
})?;
for (i, h) in hashes.iter().enumerate() {
let id = tlog_tiles::stored_hash_index(0, n) + i as u64;
overlay.insert(id, *h);
}
n += 1;
// If the data tile is full, stage it.
if n % u64::from(TlogTile::FULL_WIDTH) == 0 {
metrics
.seq_data_tile_size
.with_label_values(&["full"])
.observe(data_tile.len().as_f64());
stage_data_tile::<L>(
n,
&mut edge_tiles,
&mut tile_uploads,
std::mem::take(&mut data_tile),
std::mem::take(&mut aux_tile),
);
}
}
// Stage leftover partial data tile, if any.
if n != old_size && n % u64::from(TlogTile::FULL_WIDTH) != 0 {
metrics
.seq_data_tile_size
.with_label_values(&["partial"])
.observe(data_tile.len().as_f64());
stage_data_tile::<L>(
n,
&mut edge_tiles,
&mut tile_uploads,
std::mem::take(&mut data_tile),
std::mem::take(&mut aux_tile),
);
}
// Produce and stage new tree tiles.
let tiles = TlogTile::new_tiles(old_size, n);
for tile in tiles {
let data = tile
.read_data(&HashReaderWithOverlay {
edge_tiles: &edge_tiles,
overlay: &overlay,
})
.map_err(|e| {
SequenceError::NonFatal(format!("couldn't generate tile {tile:?}: {e}"))
})?;
// Assuming new_tiles_for_size produces tiles in order, this tile should
// always be further right than the one in edge_tiles, but double check.
if edge_tiles.get(&tile.level()).is_none_or(|t| {
t.tile.level_index() < tile.level_index()
|| (t.tile.level_index() == tile.level_index() && t.tile.width() < tile.width())
}) {
debug!(
"{name}: staging tree tile: old_tree_size={old_size}, tree_size={n}, tile={tile:?}, size={}",
data.len()
);
edge_tiles.insert(
tile.level(),
TileWithBytes {
tile,
b: data.clone(),
},
);
}
let action = UploadAction {
key: tile.path(),
data,
opts: OPTS_HASH_TILE.clone(),
};
tile_uploads.push(action);
}
// Construct the new sequence state.
let new = {
let tree = TreeWithTimestamp::from_hash_reader(
n,
&HashReaderWithOverlay {
edge_tiles: &edge_tiles,
overlay: &overlay,
},
timestamp,
)
.map_err(|e| SequenceError::NonFatal(format!("couldn't compute tree head: {e}")))?;
let dyn_signers = config
.checkpoint_signers
.iter()
.map(AsRef::as_ref)
.collect::<Vec<_>>();
let extensions = (config.checkpoint_extension)(timestamp);
let checkpoint = tree
.sign(
config.origin.as_str(),
&extensions.iter().map(String::as_str).collect::<Vec<_>>(),
&dyn_signers,
&mut rand::thread_rng(),
)
.map_err(|e| SequenceError::NonFatal(format!("couldn't sign checkpoint: {e}")))?;
SequenceState {
tree,
checkpoint,
edge_tiles,
}
};
// Upload tiles to staging, where they can be recovered by [SequenceState::load] if we
// crash right after updating DO storage.
let staged_uploads = marshal_staged_uploads(&tile_uploads, new.tree.size(), new.tree.hash())