|
| 1 | +//! Helper that delays resolving the payload |
| 2 | +
|
| 3 | +use futures::{Stream, StreamExt}; |
| 4 | +use jsonrpsee::{ |
| 5 | + core::traits::ToRpcParams, |
| 6 | + types::{error::INVALID_PARAMS_CODE, ErrorObject, Params}, |
| 7 | + MethodsError, RpcModule, |
| 8 | +}; |
| 9 | +use parking_lot::Mutex; |
| 10 | +use reth_chain_state::CanonStateNotification; |
| 11 | +use serde::de::Error; |
| 12 | +use serde_json::value::RawValue; |
| 13 | +use std::{ |
| 14 | + sync::Arc, |
| 15 | + time::{Duration, Instant}, |
| 16 | +}; |
| 17 | + |
| 18 | +/// Delay into the slot |
| 19 | +pub const MAX_DELAY_INTO_SLOT: Duration = Duration::from_millis(500); |
| 20 | + |
| 21 | +/// The getpayload fn we want to delay |
| 22 | +pub const GET_PAYLOAD_V3: &str = "engine_getPayloadV3"; |
| 23 | + |
| 24 | +/// A helper that tracks the block clock timestamp and can delay resolving the payload to give the |
| 25 | +/// payload builder more time to build a block. |
| 26 | +#[derive(Debug, Clone)] |
| 27 | +pub struct DelayedResolver { |
| 28 | + inner: Arc<DelayedResolverInner>, |
| 29 | +} |
| 30 | + |
| 31 | +impl DelayedResolver { |
| 32 | + /// Creates a new instance with the engine module and the duration we should target |
| 33 | + pub fn new(engine_module: RpcModule<()>, max_delay_into_slot: Duration) -> Self { |
| 34 | + Self { |
| 35 | + inner: Arc::new(DelayedResolverInner { |
| 36 | + last_block_time: Mutex::new(Instant::now()), |
| 37 | + engine_module, |
| 38 | + max_delay_into_slot, |
| 39 | + }), |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + /// Listen for new blocks and track the local timestamp. |
| 44 | + pub fn spawn<St>(self, mut st: St) |
| 45 | + where |
| 46 | + St: Stream<Item = CanonStateNotification> + Send + Unpin + 'static, |
| 47 | + { |
| 48 | + tokio::task::spawn(async move { |
| 49 | + while st.next().await.is_some() { |
| 50 | + *self.inner.last_block_time.lock() = Instant::now(); |
| 51 | + } |
| 52 | + }); |
| 53 | + } |
| 54 | + |
| 55 | + async fn call(&self, params: Params<'static>) -> Result<String, MethodsError> { |
| 56 | + let last = *self.inner.last_block_time.lock(); |
| 57 | + let now = Instant::now(); |
| 58 | + // how far we're into the slot |
| 59 | + let offset = now.duration_since(last); |
| 60 | + |
| 61 | + if offset < self.inner.max_delay_into_slot { |
| 62 | + // if we received the request before the max delay exceeded we can delay the request to |
| 63 | + // give the payload builder more time to build the payload. |
| 64 | + let delay = self.inner.max_delay_into_slot - offset; |
| 65 | + tokio::time::sleep(delay).await; |
| 66 | + } |
| 67 | + |
| 68 | + let params = params |
| 69 | + .as_str() |
| 70 | + .ok_or_else(|| MethodsError::Parse(serde_json::Error::missing_field("payload id")))?; |
| 71 | + |
| 72 | + self.inner.engine_module.call(GET_PAYLOAD_V3, PayloadParam(params.to_string())).await |
| 73 | + } |
| 74 | + |
| 75 | + /// Converts this type into a new [`RpcModule`] that delegates the get payload call. |
| 76 | + pub fn into_rpc_module(self) -> RpcModule<()> { |
| 77 | + let mut module = RpcModule::new(()); |
| 78 | + module |
| 79 | + .register_async_method(GET_PAYLOAD_V3, move |params, _ctx, _| { |
| 80 | + let value = self.clone(); |
| 81 | + async move { |
| 82 | + value.call(params).await.map_err(|err| match err { |
| 83 | + MethodsError::JsonRpc(err) => err, |
| 84 | + err => ErrorObject::owned( |
| 85 | + INVALID_PARAMS_CODE, |
| 86 | + format!("invalid payload call: {:?}", err), |
| 87 | + None::<()>, |
| 88 | + ), |
| 89 | + }) |
| 90 | + } |
| 91 | + }) |
| 92 | + .unwrap(); |
| 93 | + |
| 94 | + module |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +#[derive(Debug)] |
| 99 | +struct DelayedResolverInner { |
| 100 | + /// Tracks the time when the last block was emitted |
| 101 | + last_block_time: Mutex<Instant>, |
| 102 | + engine_module: RpcModule<()>, |
| 103 | + /// By how much we want to delay getPayload into the slot |
| 104 | + max_delay_into_slot: Duration, |
| 105 | +} |
| 106 | + |
| 107 | +struct PayloadParam(String); |
| 108 | + |
| 109 | +impl ToRpcParams for PayloadParam { |
| 110 | + fn to_rpc_params(self) -> Result<Option<Box<RawValue>>, serde_json::Error> { |
| 111 | + RawValue::from_string(self.0).map(Some) |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +#[cfg(test)] |
| 116 | +mod tests { |
| 117 | + use super::*; |
| 118 | + use alloy_rpc_types::engine::PayloadId; |
| 119 | + |
| 120 | + #[tokio::test] |
| 121 | + async fn test_delayed_forward() { |
| 122 | + use jsonrpsee::{core::RpcResult, RpcModule}; |
| 123 | + |
| 124 | + let mut module = RpcModule::new(()); |
| 125 | + module |
| 126 | + .register_method::<RpcResult<PayloadId>, _>(GET_PAYLOAD_V3, |params, _, _| { |
| 127 | + params.one::<PayloadId>() |
| 128 | + }) |
| 129 | + .unwrap(); |
| 130 | + |
| 131 | + let id = PayloadId::default(); |
| 132 | + |
| 133 | + let echo: PayloadId = module.call(GET_PAYLOAD_V3, [id]).await.unwrap(); |
| 134 | + assert_eq!(echo, id); |
| 135 | + |
| 136 | + let delayer = DelayedResolver::new(module, MAX_DELAY_INTO_SLOT).into_rpc_module(); |
| 137 | + let echo: PayloadId = delayer.call(GET_PAYLOAD_V3, [id]).await.unwrap(); |
| 138 | + assert_eq!(echo, id); |
| 139 | + } |
| 140 | +} |
0 commit comments