loom_node_grpc_exex_proto/
client.rs

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
use alloy_consensus::BlockHeader;
use alloy_primitives::{map::HashMap, Address, U256};
use alloy_rpc_types::{
    Block, {BlockTransactions, BlockTransactionsKind},
};
use alloy_rpc_types_trace::geth::AccountState;
use async_stream::stream;
use eyre::{eyre, Result};
use reth::primitives::{SealedHeader, TransactionSigned};
use reth::revm::db::states::StorageSlot;
use reth::revm::db::{BundleAccount, StorageWithOriginalValues};
use reth::rpc::eth::EthTxBuilder;
use reth_exex::ExExNotification;
use reth_primitives::SealedBlockWithSenders;
use reth_tracing::tracing::error;
use std::collections::BTreeMap;
use tokio_stream::Stream;
use tonic::transport::Channel;

use crate::helpers::append_all_matching_block_logs_sealed;
use crate::proto::remote_ex_ex_client::RemoteExExClient;
use crate::proto::SubscribeRequest;

#[derive(Debug, Clone)]
pub struct ExExClient {
    client: RemoteExExClient<Channel>,
}

impl ExExClient {
    pub async fn connect(url: String) -> eyre::Result<ExExClient> {
        let client = RemoteExExClient::connect(url).await?.max_encoding_message_size(usize::MAX).max_decoding_message_size(usize::MAX);

        Ok(ExExClient { client })
    }

    pub async fn subscribe_mempool_tx(&self) -> Result<impl Stream<Item = alloy_rpc_types::eth::Transaction> + '_> {
        let stream = self.client.clone().subscribe_mempool_tx(SubscribeRequest {}).await;
        let mut stream = match stream {
            Ok(stream) => stream.into_inner(),
            Err(e) => {
                error!(error=?e, "subscribe header");
                return Err(eyre!("ERROR"));
            }
        };

        Ok(stream! {
            loop {
                match stream.message().await {
                    Ok(Some(transaction_proto)) => {
                        if let Ok(transaction) = TransactionSigned::try_from(&transaction_proto){
                            if let Some(transaction) = transaction.into_ecrecovered() {
                                let transaction = reth_rpc_types_compat::transaction::from_recovered::<EthTxBuilder>(transaction, &EthTxBuilder);
                                if let Ok(transaction) = transaction {
                                    yield transaction;
                                }
                            }
                        }
                    }
                    Ok(None) => break, // Stream has ended
                    Err(err) => {
                        eprintln!("Error receiving mempooltx.message: {:?}", err);
                        break;
                    }
                }
            }
        })
    }

    pub async fn subscribe_header(&self) -> Result<impl Stream<Item = alloy_rpc_types::Header> + '_> {
        let stream = self.client.clone().subscribe_header(SubscribeRequest {}).await;

        let mut stream = match stream {
            Ok(stream) => stream.into_inner(),
            Err(e) => {
                error!(error=?e, "subscribe header");
                return Err(eyre!("ERROR"));
            }
        };
        Ok(stream! {
            loop {
                match stream.message().await {
                    Ok(Some(sealed_header)) => {
                        let Ok(sealed_header) = TryInto::<SealedHeader>::try_into(sealed_header) else {continue};
                        let header = alloy_rpc_types::Header {
                            hash: sealed_header.hash(),
                            total_difficulty: Some(sealed_header.header().difficulty) ,
                            size: Some(U256::from(sealed_header.header().size())),
                            inner : sealed_header.header().clone()};
                        yield header

                    },
                    Ok(None) => {
                        break;

                    } // Stream has ended
                    Err(err) => {
                        eprintln!("Error receiving header.message: {:?}", err);
                        break;
                    }
                }
            }
        })
    }

    pub async fn subscribe_block(&self) -> Result<impl Stream<Item = alloy_rpc_types::Block>> {
        let stream = self.client.clone().subscribe_block(SubscribeRequest {}).await;

        let mut stream = match stream {
            Ok(stream) => stream.into_inner(),
            Err(e) => {
                error!(error=?e, "subscribe header");
                return Err(eyre!("ERROR"));
            }
        };

        Ok(stream! {
            loop {
                match stream.message().await {
                    Ok(Some(block_msg)) => {
                        if let Ok(sealed_block)  = SealedBlockWithSenders::try_from(&block_msg) {
                            let diff = sealed_block.difficulty;
                            let hash = sealed_block.hash();

                            if let Ok(block) = reth_rpc_types_compat::block::from_block::<EthTxBuilder>(
                                sealed_block.unseal(),
                                diff,
                                BlockTransactionsKind::Full,
                                Some(hash),
                                &EthTxBuilder)
                            {

                                let txes = block.transactions.into_transactions().collect();

                                let block_eth : Block = Block {
                                    header: block.header,
                                    uncles: block.uncles,
                                    transactions: BlockTransactions::Full(txes),
                                    withdrawals: block.withdrawals
                                };


                                yield block_eth
                            }
                        }
                    },
                    Ok(None) => break, // Stream has ended
                    Err(err) => {
                        eprintln!("Error receiving block.message: {:?}", err);
                        break;
                    }
                }
            }
        })
    }
    pub async fn subscribe_logs(&self) -> Result<impl Stream<Item = (alloy_rpc_types::Header, Vec<alloy_rpc_types::Log>)>> {
        let stream = self.client.clone().subscribe_receipts(SubscribeRequest {}).await;

        let mut stream = match stream {
            Ok(stream) => stream.into_inner(),
            Err(e) => {
                error!(error=?e, "subscribe receipts");
                return Err(eyre!("ERROR"));
            }
        };
        Ok(stream! {
            loop {
                match stream.message().await {
                    Ok(Some(notification)) => {
                        if let Some(receipts) = notification.receipts {
                            if let Some(block) = notification.block {
                                let Some(sealed_header) = block.header.clone() else {continue};
                                let Ok(sealed_header) = TryInto::<SealedHeader>::try_into(sealed_header) else {continue};


                                if let Ok( logvec) = append_all_matching_block_logs_sealed(
                                    receipts,
                                    false,
                                    block,
                                ){
                                    let header = alloy_rpc_types::Header {
                                        hash : sealed_header.hash(),
                                        inner: sealed_header.header().clone(),
                                        total_difficulty:Some(sealed_header.difficulty),
                                        size: Some(U256::from(sealed_header.size())),
                                        };
                                    yield (header, logvec);
                                }


                            }
                        }

                    },
                    Ok(None) => break, // Stream has ended
                    Err(err) => {
                        eprintln!("Error receiving logs.message: {:?}", err);
                        break;
                    }
                }
            }
        })
    }

    pub async fn subscribe_stata_update(&self) -> Result<impl Stream<Item = (alloy_rpc_types::Header, BTreeMap<Address, AccountState>)>> {
        let stream = self.client.clone().subscribe_state_update(SubscribeRequest {}).await;

        let mut stream = match stream {
            Ok(stream) => stream.into_inner(),
            Err(e) => {
                error!(error=?e, "subscribe receipts");
                return Err(eyre!("ERROR"));
            }
        };
        Ok(stream! {
            loop {
                match stream.message().await {
                    Ok(Some(state_update)) => {
                        if let Some(sealed_header) = state_update.sealed_header {
                            if let Ok(sealed_header) = TryInto::<SealedHeader>::try_into(sealed_header) {
                                if let Some(bundle_proto) = state_update.bundle {
                                    if let Ok(bundle_state) = reth::revm::db::BundleState::try_from(&bundle_proto){
                                        let mut state_update : BTreeMap<Address, AccountState> = BTreeMap::new();

                                        let state_ref: &HashMap<Address, BundleAccount> = &bundle_state.state;

                                        for (address, accounts) in state_ref.iter() {
                                            let account_state = state_update.entry(*address).or_default();
                                            if let Some(account_info) = accounts.info.clone() {
                                                account_state.code = account_info.code.map(|c| c.bytecode().clone());
                                                account_state.balance = Some(account_info.balance);
                                                account_state.nonce = Some(account_info.nonce);
                                            }

                                            let storage: &StorageWithOriginalValues = &accounts.storage;

                                            for (key, storage_slot) in storage.iter() {
                                                let (key, storage_slot): (&U256, &StorageSlot) = (key, storage_slot);
                                                account_state
                                                    .storage
                                                    .insert((*key).into(), storage_slot.present_value.into());
                                            }
                                        }
                                        let header = alloy_rpc_types::Header {
                                            hash: sealed_header.hash(),
                                            total_difficulty: Some(sealed_header.difficulty()),
                                            size: Some(U256::from(sealed_header.size())),
                                            inner : sealed_header.header().clone()
                                        };

                                        yield (header, state_update);
                                    }
                                }
                            }
                        }
                    },
                    Ok(None) => break, // Stream has ended
                    Err(err) => {
                        eprintln!("Error receiving state_update.message: {:?}", err);
                        break;
                    }
                }
            }
        })
    }

    pub async fn subscribe_exex(&self) -> Result<impl Stream<Item = ExExNotification> + '_> {
        let stream = self.client.clone().subscribe_ex_ex(SubscribeRequest {}).await;

        let mut stream = match stream {
            Ok(stream) => stream.into_inner(),
            Err(e) => {
                error!(error=?e, "subscribe exex");
                return Err(eyre!("ERROR"));
            }
        };

        Ok(stream! {


            loop {
                match stream.message().await {
                    Ok(Some(notification)) => {
                            match ExExNotification::try_from(&notification) {
                                Ok(notification) => yield notification,
                                Err(err) => eprintln!("Error converting notification: {:?}", err),
                            }
                        },
                    Ok(None) => break, // Stream has ended
                    Err(err) => {
                        eprintln!("Error receiving exex.message: {:?}", err);
                        break;
                    }
                }
            }
        })
    }
}