Skip to main content

reth_trie_parallel/
state_root_task.rs

1//! State-root task interface types shared between the engine tree and the payload builder.
2//!
3//! The "state-root task" is the background multiproof and sparse-trie pipeline that computes
4//! state roots incrementally while a block executes. This module holds its boundary types:
5//! the input messages and
6//! stream views that feed it, and the handles
7//! that await its result. The per-block strategy abstraction that decides whether and how the
8//! task runs lives in `reth-engine-tree` under `tree::state_root_strategy`.
9
10use 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/// Messages used internally by the multi proof task.
22#[derive(Debug)]
23pub enum StateRootMessage {
24    /// Prefetch proof targets
25    PrefetchProofs(MultiProofTargetsV2),
26    /// New state update from transaction execution.
27    StateUpdate(StateUpdate),
28    /// Pre-hashed state update from BAL conversion that can be applied directly without proofs.
29    HashedStateUpdate(HashedPostState),
30    /// Signals state update stream end.
31    ///
32    /// This is triggered by block execution, indicating that no additional state updates are
33    /// expected.
34    FinishedStateUpdates,
35}
36
37/// Outcome of the state root computation, including the state root itself with
38/// the trie updates.
39#[derive(Debug, Clone)]
40pub struct StateRootComputeOutcome {
41    /// The state root.
42    pub state_root: B256,
43    /// The trie updates.
44    pub trie_updates: Arc<TrieUpdates>,
45    /// Hashed post state produced while computing the state root.
46    pub hashed_state: Arc<HashedPostState>,
47}
48
49/// Handle to a background sparse trie state root computation.
50///
51/// Provides best-effort access hints, one authoritative update stream, and the final computation
52/// result. Dropping the handle cancels the task if it is still running.
53#[derive(Debug)]
54pub struct StateRootHandle {
55    /// The state root that the cached sparse trie is anchored at (parent block's state root).
56    cached_trie_state_root: B256,
57    /// Best-effort hint capability, taken once by prewarm wiring.
58    hint: Option<StateRootHintStream>,
59    /// The single authoritative update capability.
60    ///
61    /// Taken exactly once, either as an execution hook (serial execution) or as a hashed
62    /// update stream (parallel BAL streaming), so per block exactly one producer can finish
63    /// the update stream. Only producers hold update senders: once the taken capabilities are
64    /// dropped or finished, the update channel closes and the task knows producers are done.
65    authoritative: Option<StateRootUpdateStream>,
66    /// Guard whose drop cancels the state-root task if it is still running.
67    cancel_guard: StateRootTaskCancelGuard,
68    /// Receiver for the final state root result.
69    state_root_rx: Option<Receiver<Result<StateRootComputeOutcome, StateRootTaskError>>>,
70    /// Receiver for the hashed post state.
71    hashed_state_rx: Option<Receiver<Arc<HashedPostState>>>,
72}
73
74impl StateRootHandle {
75    /// Creates a new [`StateRootHandle`].
76    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    /// Returns the state root that the cached sparse trie is anchored at.
95    pub const fn cached_trie_state_root(&self) -> B256 {
96        self.cached_trie_state_root
97    }
98
99    /// Takes the best-effort hint capability used by transaction prewarming.
100    ///
101    /// # Panics
102    ///
103    /// If called more than once.
104    pub const fn take_hint_stream(&mut self) -> StateRootHintStream {
105        self.hint.take().expect("hint stream already taken")
106    }
107
108    /// Takes the authoritative update capability as an EVM state hook.
109    ///
110    /// The hook finishes the update stream when dropped. It shares one slot with
111    /// [`Self::take_hashed_update_stream`], so only one of the two can exist per block.
112    ///
113    /// # Panics
114    ///
115    /// If the authoritative capability was already taken in either form.
116    pub fn take_execution_hook(&mut self) -> StateRootUpdateHook {
117        self.take_hashed_update_stream().into_state_hook()
118    }
119
120    /// Takes the authoritative update capability as a pre-hashed update stream.
121    ///
122    /// The stream is finished explicitly with [`StateRootUpdateStream::finish`]. It shares
123    /// one slot with [`Self::take_execution_hook`], so only one of the two can exist per
124    /// block.
125    ///
126    /// # Panics
127    ///
128    /// If the authoritative capability was already taken in either form.
129    pub const fn take_hashed_update_stream(&mut self) -> StateRootUpdateStream {
130        self.authoritative.take().expect("authoritative update capability already taken")
131    }
132
133    /// Awaits the state root computation result.
134    ///
135    /// # Panics
136    ///
137    /// If called more than once.
138    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    /// Takes the state root receiver for use with custom waiting logic (e.g., timeouts).
147    ///
148    /// # Panics
149    ///
150    /// If called more than once.
151    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    /// Takes the hashed state receiver
158    ///
159    /// # Panics
160    ///
161    /// If called more than once.
162    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    /// Converts this sparse-trie handle into the opaque handle passed to payload builders.
167    ///
168    /// The payload builder only executes transactions, so the handle carries the execution
169    /// hook; the hint capability is dropped here.
170    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/// Guard that cancels a state-root task when dropped.
184///
185/// The task watches the paired receiver in its event loop. No message is ever sent: the guard
186/// dropping disconnects the channel, which the task treats as the consumer abandoning the
187/// computation (for example on a timeout fallback or when a payload job is dropped unused).
188#[derive(Debug)]
189pub struct StateRootTaskCancelGuard(#[allow(dead_code)] Sender<()>);
190
191impl StateRootTaskCancelGuard {
192    /// Creates a guard and the receiver a task watches for cancellation.
193    pub fn channel() -> (Self, channel::Receiver<()>) {
194        let (tx, rx) = channel::bounded(0);
195        (Self(tx), rx)
196    }
197}
198
199/// Opaque state-root task handle passed to payload builders.
200pub struct PayloadStateRootHandle {
201    name: &'static str,
202    /// Execution hook that streams per-transaction updates; taken once when building starts.
203    hook: Option<StateRootUpdateHook>,
204    /// Cancels the backing task when the handle is dropped without consuming the result.
205    cancel_guard: Option<StateRootTaskCancelGuard>,
206    state_root_rx: Option<Receiver<Result<StateRootComputeOutcome, StateRootTaskError>>>,
207    hashed_state_rx: Option<Receiver<Arc<HashedPostState>>>,
208    /// Returns retained state to the engine once the completed block's identity is known.
209    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    /// Creates an opaque payload state-root handle.
226    ///
227    /// Tasks with a drop-to-cancel guard should attach it via the `StateRootHandle`
228    /// conversion; handles created here rely on their own task lifecycle.
229    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    /// Attaches a callback receiving the completed payload's block hash and state root.
246    ///
247    /// The callback must verify that any retained state matches the returned payload.
248    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    /// Takes the callback to invoke after a successful build, before returning its payload.
257    /// Aborted, cancelled, or failed builds must drop the callback without invoking it.
258    pub fn take_on_payload_built(&mut self) -> Option<Box<dyn FnOnce(B256, B256) + Send>> {
259        self.on_payload_built.take()
260    }
261
262    /// Returns the task name used in logs.
263    pub const fn name(&self) -> &'static str {
264        self.name
265    }
266
267    /// Takes the state hook that streams execution updates and finishes the stream on drop.
268    ///
269    /// # Panics
270    ///
271    /// If the handle was created without an execution hook, or the hook was already taken.
272    pub const fn take_state_hook(&mut self) -> StateRootUpdateHook {
273        self.hook.take().expect("payload state root task missing execution hook")
274    }
275
276    /// Awaits the state root computation result.
277    ///
278    /// # Panics
279    ///
280    /// If called more than once.
281    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    /// Takes the state root receiver for use with custom waiting logic (e.g., timeouts).
290    ///
291    /// Dropping the handle continues to cancel the backing task if it owns a cancellation guard.
292    ///
293    /// # Panics
294    ///
295    /// If called more than once.
296    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    /// Takes the hashed state receiver, if the handle was built with one and it was not taken
303    /// yet.
304    pub const fn try_take_hashed_state_rx(&mut self) -> Option<Receiver<Arc<HashedPostState>>> {
305        self.hashed_state_rx.take()
306    }
307}
308
309/// Hashed account and storage keys that a state-root task may want to prefetch.
310///
311/// Hints are not authoritative. They may be missing, duplicated, stale, or ignored by a task.
312/// Conversions to and from proof-target types allocate new collections.
313#[derive(Debug, Clone, Default)]
314pub struct StateAccessHint {
315    /// Hashed account keys that may be touched later in the block.
316    pub accounts: Vec<B256>,
317    /// Hashed storage keys keyed by hashed account.
318    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
351/// Semantic update stream consumed by state-root tasks.
352///
353/// These callbacks submit messages without reporting task completion or failure. Consumers must
354/// obtain the computation result separately, for example through [`StateRootHandle::state_root`].
355trait StateRootSink: Send + Sync + 'static {
356    /// Best-effort access hint from transaction prewarming.
357    fn on_access_hint(&self, _hint: StateAccessHint) {}
358
359    /// Authoritative state update from normal block execution.
360    fn on_state_update(&self, state: StateUpdate);
361
362    /// Authoritative pre-hashed state update, currently used by BAL streaming.
363    fn on_hashed_state_update(&self, state: HashedPostState);
364
365    /// Signals that no more authoritative state updates are expected.
366    fn on_updates_finished(&self);
367}
368
369/// Hint-only view of a state-root stream.
370#[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    /// Creates a new hint stream view.
383    fn new(inner: Arc<dyn StateRootSink>) -> Self {
384        Self { inner }
385    }
386
387    /// Emits a best-effort access hint.
388    pub fn on_access_hint(&self, hint: StateAccessHint) {
389        self.inner.on_access_hint(hint);
390    }
391}
392
393/// Authoritative update capability of a state-root stream.
394///
395/// A [`StateRootHandle`] provides this capability exactly once, so its producer can end the
396/// update stream either through the EVM state hook made with [`Self::into_state_hook`] (finishes
397/// on drop) or through a pre-hashed update stream (calls [`Self::finish`]). The
398/// type is deliberately not `Clone` and finishing consumes it, so a second end-of-stream
399/// signal cannot be produced.
400///
401/// Dropping the stream without calling [`Self::finish`] (for example when a producer dies)
402/// deliberately does not finish it: an unfinished stream means the updates are incomplete,
403/// and the task must not compute a root from them.
404pub 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    /// Creates a new authoritative update stream backed by the given sink.
416    fn new(inner: Arc<dyn StateRootSink>) -> Self {
417        Self { inner }
418    }
419
420    /// Emits an authoritative pre-hashed state update.
421    pub fn on_hashed_state_update(&self, state: HashedPostState) {
422        self.inner.on_hashed_state_update(state);
423    }
424
425    /// Finishes the authoritative update stream.
426    pub fn finish(self) {
427        self.inner.on_updates_finished();
428    }
429
430    /// Converts this capability into an EVM state hook that finishes the stream on drop.
431    ///
432    /// See [`StateRootUpdateHook`] for why the hook finishes on drop while the bare stream
433    /// does not, and how a panic during execution is excluded from that.
434    pub fn into_state_hook(self) -> StateRootUpdateHook {
435        StateRootUpdateHook { inner: self.inner }
436    }
437}
438
439/// EVM hook that forwards state updates to the state-root task.
440///
441/// Dropping the hook signals the end of the update stream, so the hook is deliberately not
442/// `Clone`: a second copy would fire a spurious end-of-stream signal.
443///
444/// Unlike [`StateRootUpdateStream::finish`], the end of the stream is signaled by drop and
445/// not by an explicit call, because the EVM owns the hook until it is dropped and gives it no
446/// other end-of-execution signal. A drop during a panic unwind is excluded: execution died
447/// mid-block, so the stream stays unfinished and the task reports an error instead of
448/// computing a root from incomplete updates. Execution that fails by returning an error still
449/// drops the hook normally and finishes the stream; the caller abandons the result in that
450/// case, and the stored trie is rejected by the anchor check on the next block.
451pub 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        // A drop during a panic unwind means execution died mid-block. Leave the stream
470        // unfinished so the task fails instead of computing a root from partial updates.
471        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
489// Send errors mean the receiving pipeline has stopped, so further updates and the finish
490// signal cannot be processed. Task errors are delivered through the separate result channel;
491// if the task drops that channel without a result, StateRootHandle::state_root reports an error.
492// Cancellation abandons the result. Ignoring send errors here does not report a successful root.
493impl 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    /// A hook dropped by a panic unwind must not finish the stream: the updates are
563    /// incomplete, and a finish marker would make the task compute a root from them.
564    #[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    /// The authoritative capability is a single slot: taking it as a hook and then again as
580    /// a hashed update stream (or in any other combination) must panic.
581    #[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    /// Lifecycle of the opaque handle a strategy hands to the payload builder: the execution
601    /// hook streams updates into the sink and signals completion on drop, the hashed-state
602    /// receiver can be taken exactly once, and the outcome arrives through the state-root
603    /// channel.
604    #[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}