1use crate::error::StateRootTaskError;
11use alloy_primitives::{map::B256Map, B256};
12use reth_concurrency::sync::{
13 channel,
14 channel::{mpsc::Receiver, Sender},
15 thread,
16};
17use reth_execution_types::{OnStateHook, StateUpdate};
18use reth_trie::{updates::TrieUpdates, HashedPostState, MultiProofTargetsV2, ProofV2Target};
19use std::{fmt, sync::Arc};
20
21#[derive(Debug)]
23pub enum StateRootMessage {
24 PrefetchProofs(MultiProofTargetsV2),
26 StateUpdate(StateUpdate),
28 HashedStateUpdate(HashedPostState),
30 FinishedStateUpdates,
35}
36
37#[derive(Debug, Clone)]
40pub struct StateRootComputeOutcome {
41 pub state_root: B256,
43 pub trie_updates: Arc<TrieUpdates>,
45 pub hashed_state: Arc<HashedPostState>,
47}
48
49#[derive(Debug)]
54pub struct StateRootHandle {
55 cached_trie_state_root: B256,
57 hint: Option<StateRootHintStream>,
59 authoritative: Option<StateRootUpdateStream>,
66 cancel_guard: StateRootTaskCancelGuard,
68 state_root_rx: Option<Receiver<Result<StateRootComputeOutcome, StateRootTaskError>>>,
70 hashed_state_rx: Option<Receiver<Arc<HashedPostState>>>,
72}
73
74impl StateRootHandle {
75 pub fn new(
77 cached_trie_state_root: B256,
78 updates_tx: Sender<StateRootMessage>,
79 cancel_guard: StateRootTaskCancelGuard,
80 state_root_rx: Receiver<Result<StateRootComputeOutcome, StateRootTaskError>>,
81 hashed_state_rx: Receiver<Arc<HashedPostState>>,
82 ) -> Self {
83 let sink: Arc<dyn StateRootSink> = Arc::new(SparseTrieStateRootSink::new(updates_tx));
84 Self {
85 cached_trie_state_root,
86 hint: Some(StateRootHintStream::new(Arc::clone(&sink))),
87 authoritative: Some(StateRootUpdateStream::new(sink)),
88 cancel_guard,
89 state_root_rx: Some(state_root_rx),
90 hashed_state_rx: Some(hashed_state_rx),
91 }
92 }
93
94 pub const fn cached_trie_state_root(&self) -> B256 {
96 self.cached_trie_state_root
97 }
98
99 pub const fn take_hint_stream(&mut self) -> StateRootHintStream {
105 self.hint.take().expect("hint stream already taken")
106 }
107
108 pub fn take_execution_hook(&mut self) -> StateRootUpdateHook {
117 self.take_hashed_update_stream().into_state_hook()
118 }
119
120 pub const fn take_hashed_update_stream(&mut self) -> StateRootUpdateStream {
130 self.authoritative.take().expect("authoritative update capability already taken")
131 }
132
133 pub fn state_root(&mut self) -> Result<StateRootComputeOutcome, StateRootTaskError> {
139 self.state_root_rx
140 .take()
141 .expect("state_root already taken")
142 .recv()
143 .map_err(|_| StateRootTaskError::Other("sparse trie task dropped".into()))?
144 }
145
146 pub const fn take_state_root_rx(
152 &mut self,
153 ) -> Receiver<Result<StateRootComputeOutcome, StateRootTaskError>> {
154 self.state_root_rx.take().expect("state_root already taken")
155 }
156
157 pub const fn take_hashed_state_rx(&mut self) -> Receiver<Arc<HashedPostState>> {
163 self.hashed_state_rx.take().expect("hashed_state already taken")
164 }
165
166 pub fn into_payload_state_root_handle(mut self) -> PayloadStateRootHandle {
171 let hook = self.take_execution_hook();
172 PayloadStateRootHandle {
173 name: "sparse-trie",
174 hook: Some(hook),
175 cancel_guard: Some(self.cancel_guard),
176 state_root_rx: self.state_root_rx.take(),
177 hashed_state_rx: self.hashed_state_rx.take(),
178 on_payload_built: None,
179 }
180 }
181}
182
183#[derive(Debug)]
189pub struct StateRootTaskCancelGuard(#[allow(dead_code)] Sender<()>);
190
191impl StateRootTaskCancelGuard {
192 pub fn channel() -> (Self, channel::Receiver<()>) {
194 let (tx, rx) = channel::bounded(0);
195 (Self(tx), rx)
196 }
197}
198
199pub struct PayloadStateRootHandle {
201 name: &'static str,
202 hook: Option<StateRootUpdateHook>,
204 cancel_guard: Option<StateRootTaskCancelGuard>,
206 state_root_rx: Option<Receiver<Result<StateRootComputeOutcome, StateRootTaskError>>>,
207 hashed_state_rx: Option<Receiver<Arc<HashedPostState>>>,
208 on_payload_built: Option<Box<dyn FnOnce(B256, B256) + Send>>,
210}
211
212impl fmt::Debug for PayloadStateRootHandle {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214 f.debug_struct("PayloadStateRootHandle")
215 .field("name", &self.name)
216 .field("has_hook", &self.hook.is_some())
217 .field("has_cancel_guard", &self.cancel_guard.is_some())
218 .field("has_state_root_rx", &self.state_root_rx.is_some())
219 .field("has_hashed_state_rx", &self.hashed_state_rx.is_some())
220 .finish()
221 }
222}
223
224impl PayloadStateRootHandle {
225 pub const fn new(
230 name: &'static str,
231 hook: Option<StateRootUpdateHook>,
232 state_root_rx: Receiver<Result<StateRootComputeOutcome, StateRootTaskError>>,
233 hashed_state_rx: Option<Receiver<Arc<HashedPostState>>>,
234 ) -> Self {
235 Self {
236 name,
237 hook,
238 cancel_guard: None,
239 state_root_rx: Some(state_root_rx),
240 hashed_state_rx,
241 on_payload_built: None,
242 }
243 }
244
245 pub fn with_on_payload_built(
249 mut self,
250 callback: impl FnOnce(B256, B256) + Send + 'static,
251 ) -> Self {
252 self.on_payload_built = Some(Box::new(callback));
253 self
254 }
255
256 pub fn take_on_payload_built(&mut self) -> Option<Box<dyn FnOnce(B256, B256) + Send>> {
259 self.on_payload_built.take()
260 }
261
262 pub const fn name(&self) -> &'static str {
264 self.name
265 }
266
267 pub const fn take_state_hook(&mut self) -> StateRootUpdateHook {
273 self.hook.take().expect("payload state root task missing execution hook")
274 }
275
276 pub fn state_root(&mut self) -> Result<StateRootComputeOutcome, StateRootTaskError> {
282 self.state_root_rx
283 .take()
284 .expect("state_root already taken")
285 .recv()
286 .map_err(|_| StateRootTaskError::Other("state root task dropped".into()))?
287 }
288
289 pub const fn take_state_root_rx(
297 &mut self,
298 ) -> Receiver<Result<StateRootComputeOutcome, StateRootTaskError>> {
299 self.state_root_rx.take().expect("state_root already taken")
300 }
301
302 pub const fn try_take_hashed_state_rx(&mut self) -> Option<Receiver<Arc<HashedPostState>>> {
305 self.hashed_state_rx.take()
306 }
307}
308
309#[derive(Debug, Clone, Default)]
314pub struct StateAccessHint {
315 pub accounts: Vec<B256>,
317 pub storages: B256Map<Vec<B256>>,
319}
320
321impl From<MultiProofTargetsV2> for StateAccessHint {
322 fn from(targets: MultiProofTargetsV2) -> Self {
323 Self {
324 accounts: targets.account_targets.into_iter().map(|target| target.key()).collect(),
325 storages: targets
326 .storage_targets
327 .into_iter()
328 .map(|(account, slots)| {
329 (account, slots.into_iter().map(|target| target.key()).collect())
330 })
331 .collect(),
332 }
333 }
334}
335
336impl From<StateAccessHint> for MultiProofTargetsV2 {
337 fn from(hint: StateAccessHint) -> Self {
338 Self {
339 account_targets: hint.accounts.into_iter().map(ProofV2Target::from).collect(),
340 storage_targets: hint
341 .storages
342 .into_iter()
343 .map(|(account, slots)| {
344 (account, slots.into_iter().map(ProofV2Target::from).collect())
345 })
346 .collect(),
347 }
348 }
349}
350
351trait StateRootSink: Send + Sync + 'static {
356 fn on_access_hint(&self, _hint: StateAccessHint) {}
358
359 fn on_state_update(&self, state: StateUpdate);
361
362 fn on_hashed_state_update(&self, state: HashedPostState);
364
365 fn on_updates_finished(&self);
367}
368
369#[derive(Clone)]
371pub struct StateRootHintStream {
372 inner: Arc<dyn StateRootSink>,
373}
374
375impl fmt::Debug for StateRootHintStream {
376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377 f.debug_struct("StateRootHintStream").finish_non_exhaustive()
378 }
379}
380
381impl StateRootHintStream {
382 fn new(inner: Arc<dyn StateRootSink>) -> Self {
384 Self { inner }
385 }
386
387 pub fn on_access_hint(&self, hint: StateAccessHint) {
389 self.inner.on_access_hint(hint);
390 }
391}
392
393pub struct StateRootUpdateStream {
405 inner: Arc<dyn StateRootSink>,
406}
407
408impl fmt::Debug for StateRootUpdateStream {
409 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
410 f.debug_struct("StateRootUpdateStream").finish_non_exhaustive()
411 }
412}
413
414impl StateRootUpdateStream {
415 fn new(inner: Arc<dyn StateRootSink>) -> Self {
417 Self { inner }
418 }
419
420 pub fn on_hashed_state_update(&self, state: HashedPostState) {
422 self.inner.on_hashed_state_update(state);
423 }
424
425 pub fn finish(self) {
427 self.inner.on_updates_finished();
428 }
429
430 pub fn into_state_hook(self) -> StateRootUpdateHook {
435 StateRootUpdateHook { inner: self.inner }
436 }
437}
438
439pub struct StateRootUpdateHook {
452 inner: Arc<dyn StateRootSink>,
453}
454
455impl fmt::Debug for StateRootUpdateHook {
456 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457 f.debug_struct("StateRootUpdateHook").finish_non_exhaustive()
458 }
459}
460
461impl OnStateHook for StateRootUpdateHook {
462 fn on_state(&mut self, state: StateUpdate) {
463 self.inner.on_state_update(state);
464 }
465}
466
467impl Drop for StateRootUpdateHook {
468 fn drop(&mut self) {
469 if thread::panicking() {
472 return;
473 }
474 self.inner.on_updates_finished();
475 }
476}
477
478#[derive(Debug, Clone)]
479struct SparseTrieStateRootSink {
480 sender: Sender<StateRootMessage>,
481}
482
483impl SparseTrieStateRootSink {
484 const fn new(sender: Sender<StateRootMessage>) -> Self {
485 Self { sender }
486 }
487}
488
489impl StateRootSink for SparseTrieStateRootSink {
494 fn on_access_hint(&self, hint: StateAccessHint) {
495 let _ = self.sender.send(StateRootMessage::PrefetchProofs(hint.into()));
496 }
497
498 fn on_state_update(&self, state: StateUpdate) {
499 let _ = self.sender.send(StateRootMessage::StateUpdate(state));
500 }
501
502 fn on_hashed_state_update(&self, state: HashedPostState) {
503 let _ = self.sender.send(StateRootMessage::HashedStateUpdate(state));
504 }
505
506 fn on_updates_finished(&self) {
507 let _ = self.sender.send(StateRootMessage::FinishedStateUpdates);
508 }
509}
510
511#[cfg(test)]
512mod tests {
513 use super::*;
514 use reth_concurrency::sync::{
515 atomic::{AtomicUsize, Ordering},
516 channel::{mpsc, RecvTimeoutError, TryRecvError},
517 };
518 use std::time::Duration;
519
520 #[derive(Default)]
521 struct CountingSink {
522 state_updates: AtomicUsize,
523 finished_updates: AtomicUsize,
524 }
525
526 impl StateRootSink for CountingSink {
527 fn on_state_update(&self, state: StateUpdate) {
528 assert!(state.is_empty());
529 self.state_updates.fetch_add(1, Ordering::Relaxed);
530 }
531
532 fn on_hashed_state_update(&self, _state: HashedPostState) {}
533
534 fn on_updates_finished(&self) {
535 self.finished_updates.fetch_add(1, Ordering::Relaxed);
536 }
537 }
538
539 #[reth_concurrency::test]
540 fn state_access_hint_converts_to_sparse_targets() {
541 let account = B256::repeat_byte(0x01);
542 let storage_account = B256::repeat_byte(0x02);
543 let storage_slot = B256::repeat_byte(0x03);
544
545 let mut storages = B256Map::default();
546 storages.insert(storage_account, vec![storage_slot]);
547 let hint = StateAccessHint { accounts: vec![account], storages };
548
549 let targets = MultiProofTargetsV2::from(hint);
550 assert_eq!(targets.account_targets.len(), 1);
551 assert_eq!(targets.account_targets[0].key(), account);
552 assert_eq!(targets.storage_targets.len(), 1);
553 assert_eq!(targets.storage_targets[&storage_account].len(), 1);
554 assert_eq!(targets.storage_targets[&storage_account][0].key(), storage_slot);
555
556 let hint = StateAccessHint::from(targets);
557 assert_eq!(hint.accounts, vec![account]);
558 assert_eq!(hint.storages.len(), 1);
559 assert_eq!(hint.storages[&storage_account], vec![storage_slot]);
560 }
561
562 #[reth_concurrency::test]
565 fn hook_dropped_during_panic_does_not_finish_stream() {
566 let sink = Arc::new(CountingSink::default());
567 let hook = StateRootUpdateStream::new(sink.clone()).into_state_hook();
568
569 let result = thread::spawn(move || {
570 let _hook = hook;
571 panic!("execution died mid-block");
572 })
573 .join();
574
575 assert!(result.is_err());
576 assert_eq!(sink.finished_updates.load(Ordering::Relaxed), 0);
577 }
578
579 #[reth_concurrency::test]
582 #[should_panic(expected = "authoritative update capability already taken")]
583 fn authoritative_capability_can_only_be_taken_once() {
584 let (updates_tx, _updates_rx) = channel::unbounded();
585 let (cancel_guard, _cancel_rx) = StateRootTaskCancelGuard::channel();
586 let (_state_root_tx, state_root_rx) = mpsc::channel();
587 let (_hashed_state_tx, hashed_state_rx) = mpsc::channel();
588 let mut handle = StateRootHandle::new(
589 B256::ZERO,
590 updates_tx,
591 cancel_guard,
592 state_root_rx,
593 hashed_state_rx,
594 );
595
596 let _hook = handle.take_execution_hook();
597 let _ = handle.take_hashed_update_stream();
598 }
599
600 #[reth_concurrency::test]
605 fn payload_state_root_handle_lifecycle() {
606 let sink = Arc::new(CountingSink::default());
607 let hook = StateRootUpdateStream::new(sink.clone()).into_state_hook();
608
609 let (state_root_tx, state_root_rx) = mpsc::channel();
610 let (hashed_state_tx, hashed_state_rx) = mpsc::channel();
611 let mut handle =
612 PayloadStateRootHandle::new("test", Some(hook), state_root_rx, Some(hashed_state_rx));
613
614 assert_eq!(handle.name(), "test");
615
616 {
617 let mut hook = handle.take_state_hook();
618 hook.on_state(StateUpdate::default());
619 }
620 assert_eq!(sink.state_updates.load(Ordering::Relaxed), 1);
621 assert_eq!(sink.finished_updates.load(Ordering::Relaxed), 1);
622
623 hashed_state_tx.send(Arc::new(HashedPostState::default())).unwrap();
624 let rx = handle.try_take_hashed_state_rx().expect("first take returns the receiver");
625 assert!(rx.recv().is_ok());
626 assert!(handle.try_take_hashed_state_rx().is_none(), "second take returns None");
627
628 state_root_tx
629 .send(Ok(StateRootComputeOutcome {
630 state_root: B256::repeat_byte(0x42),
631 trie_updates: Arc::new(TrieUpdates::default()),
632 hashed_state: Arc::new(HashedPostState::default()),
633 }))
634 .unwrap();
635 let outcome = handle.state_root().expect("outcome is delivered");
636 assert_eq!(outcome.state_root, B256::repeat_byte(0x42));
637 }
638
639 #[reth_concurrency::test]
640 fn payload_state_root_receiver_retains_cancellation() {
641 let (updates_tx, _updates_rx) = channel::unbounded();
642 let (cancel_guard, cancel_rx) = StateRootTaskCancelGuard::channel();
643 let (_state_root_tx, state_root_rx) = mpsc::channel();
644 let (_hashed_state_tx, hashed_state_rx) = mpsc::channel();
645 let mut handle = StateRootHandle::new(
646 B256::ZERO,
647 updates_tx,
648 cancel_guard,
649 state_root_rx,
650 hashed_state_rx,
651 )
652 .into_payload_state_root_handle();
653
654 let state_root_rx = handle.take_state_root_rx();
655 assert!(matches!(
656 state_root_rx.recv_timeout(Duration::ZERO),
657 Err(mpsc::RecvTimeoutError::Timeout)
658 ));
659 assert!(matches!(cancel_rx.try_recv(), Err(TryRecvError::Empty)));
660
661 drop(handle);
662 assert!(matches!(
663 cancel_rx.recv_timeout(Duration::from_secs(1)),
664 Err(RecvTimeoutError::Disconnected)
665 ));
666 }
667}