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
use super::types::{
    BlockMessage, Finality, FinalityUpdate, ForkVersion, GetBlockResponse, GetHeaderResponse,
    Proof, ResponseWrapper, Snapshot, SyncCommitteePeriodUpdate,
};
use support_common::error::BridgerError;

pub struct GoerliClient {
    api_client: reqwest::Client,
    api_base_url: String,
}

impl GoerliClient {
    pub fn new(api_endpoint: &str) -> color_eyre::Result<Self> {
        let api_client = reqwest::Client::new();
        Ok(Self {
            api_client,
            api_base_url: String::from(api_endpoint),
        })
    }

    pub async fn get_header(&self, id: impl ToString) -> color_eyre::Result<GetHeaderResponse> {
        let url = format!(
            "{}/eth/v1/beacon/headers/{}",
            self.api_base_url,
            id.to_string()
        );
        let res: ResponseWrapper<GetHeaderResponse> =
            self.api_client.get(url).send().await?.json().await?;
        Ok(res.data)
    }

    pub async fn find_valid_header_since(
        &self,
        current_slot: u64,
        mut slot: u64,
    ) -> color_eyre::Result<(u64, GetHeaderResponse)> {
        let mut header = self.get_header(slot).await;
        let mut count = 0;
        while let Err(err) = header {
            if slot > current_slot {
                tracing::info!(
                    target: "pangoro-goerli",
                    "[header-goerli-to-pangoro] Wait for attested headers since: {:?}",
                    slot - count
                );
                return Err(err);
            };
            slot += 1;
            header = self.get_header(slot).await;
            count += 1;
        }
        Ok((slot, header.expect("Unreachable")))
    }

    pub async fn find_valid_attested_header(
        &self,
        current_slot: u64,
        mut slot: u64,
    ) -> color_eyre::Result<Option<(u64, u64, GetHeaderResponse, BlockMessage)>> {
        loop {
            if slot > current_slot {
                return Ok(None);
            }
            match self.find_valid_header_since(current_slot, slot).await {
                Ok((attest_slot, header)) => {
                    let (sync_slot, _sync_header) = self
                        .find_valid_header_since(current_slot, attest_slot + 1)
                        .await?;

                    let sync_block = self.get_beacon_block(sync_slot).await?;
                    match Self::is_valid_sync_aggregate_block(&sync_block)? {
                        true => return Ok(Some((attest_slot, sync_slot, header, sync_block))),
                        false => {
                            slot += 1;
                            continue;
                        }
                    }
                }
                Err(_) => {
                    slot += 1;
                    continue;
                }
            }
        }
    }

    fn is_valid_sync_aggregate_block(block: &BlockMessage) -> color_eyre::Result<bool> {
        let bytes = hex::decode(&block.body.sync_aggregate.sync_committee_bits.clone()[2..]);
        if let Ok(bytes) = bytes {
            Ok(hamming::weight(&bytes) * 3 > 512 * 2)
        } else {
            Err(BridgerError::Custom(String::from("Failed to decode sync_committee_bits")).into())
        }
    }

    pub async fn get_beacon_block_root(&self, id: impl ToString) -> color_eyre::Result<String> {
        let url = format!(
            "{}/eth/v1/beacon/blocks/{}/root",
            self.api_base_url,
            id.to_string()
        );
        let res: ResponseWrapper<String> = self.api_client.get(url).send().await?.json().await?;
        Ok(res.data)
    }

    pub async fn get_bootstrap(&self, header_root: &str) -> color_eyre::Result<Snapshot> {
        let url = format!(
            "{}/eth/v1/beacon/light_client/bootstrap/{}",
            self.api_base_url, header_root,
        );
        let res: ResponseWrapper<Snapshot> = self.api_client.get(url).send().await?.json().await?;
        Ok(res.data)
    }

    #[allow(dead_code)]
    pub async fn find_valid_snapshot_in_period(&self, period: u64) -> color_eyre::Result<Snapshot> {
        let begin_slot = period * 32 * 256;
        for slot in begin_slot..((period + 1) * 32 * 256) {
            if let Ok(block_root) = self.get_beacon_block_root(slot).await {
                if let Ok(snapshot) = self.get_bootstrap(&block_root).await {
                    return Ok(snapshot);
                }
            };
        }
        Err(BridgerError::Custom("Not found valid snapshot".into()).into())
    }

    pub async fn get_beacon_block(&self, id: impl ToString) -> color_eyre::Result<BlockMessage> {
        let url = format!(
            "{}/eth/v2/beacon/blocks/{}",
            self.api_base_url,
            id.to_string(),
        );
        let res: ResponseWrapper<GetBlockResponse> =
            self.api_client.get(url).send().await?.json().await?;
        Ok(res.data.message)
    }

    #[allow(dead_code)]
    pub async fn get_checkpoint(&self, id: impl ToString) -> color_eyre::Result<Finality> {
        let url = format!(
            "{}/eth/v1/beacon/states/{}/finality_checkpoints",
            self.api_base_url,
            id.to_string(),
        );
        let res: ResponseWrapper<Finality> = self.api_client.get(url).send().await?.json().await?;
        Ok(res.data)
    }

    #[allow(dead_code)]
    pub async fn get_finality_branch(&self, state_id: impl ToString) -> color_eyre::Result<Proof> {
        self.get_state_proof(state_id, 105).await
    }

    pub async fn get_next_sync_committee_branch(
        &self,
        state_id: impl ToString,
    ) -> color_eyre::Result<Proof> {
        self.get_state_proof(state_id, 55).await
    }

    pub async fn get_latest_execution_payload_state_root_branch(
        &self,
        state_id: impl ToString,
    ) -> color_eyre::Result<Proof> {
        self.get_state_proof(state_id, 898).await
    }

    pub async fn get_state_proof(
        &self,
        state_id: impl ToString,
        gindex: impl ToString,
    ) -> color_eyre::Result<Proof> {
        let url = format!(
            "{}/eth/v1/beacon/light_client/single_proof/{}?gindex={}",
            self.api_base_url,
            state_id.to_string(),
            gindex.to_string(),
        );
        let res = self
            .api_client
            .get(url)
            .header("content-type", "application/octet-stream")
            .send()
            .await?
            .bytes()
            .await?;
        Ok(Proof::from(res))
    }

    pub async fn get_fork_version(&self, id: impl ToString) -> color_eyre::Result<ForkVersion> {
        let url = format!(
            "{}/eth/v1/beacon/states/{}/fork",
            self.api_base_url,
            id.to_string(),
        );
        let res: ResponseWrapper<ForkVersion> =
            self.api_client.get(url).send().await?.json().await?;
        Ok(res.data)
    }

    pub async fn get_finality_update(&self) -> color_eyre::Result<FinalityUpdate> {
        let url = format!(
            "{}/eth/v1/beacon/light_client/finality_update/",
            self.api_base_url,
        );
        let res: ResponseWrapper<FinalityUpdate> =
            self.api_client.get(url).send().await?.json().await?;
        Ok(res.data)
    }

    pub async fn get_sync_committee_period_update(
        &self,
        start_period: impl ToString,
        count: impl ToString,
    ) -> color_eyre::Result<Vec<SyncCommitteePeriodUpdate>> {
        let url = format!(
            "{}/eth/v1/beacon/light_client/updates?start_period={}&count={}",
            self.api_base_url,
            start_period.to_string(),
            count.to_string(),
        );
        let res: ResponseWrapper<Vec<SyncCommitteePeriodUpdate>> =
            self.api_client.get(url).send().await?.json().await?;
        Ok(res.data)
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    fn test_client() -> GoerliClient {
        GoerliClient::new("http://localhost:5052").unwrap()
    }

    #[ignore]
    #[tokio::test]
    async fn test_get_header() {
        let client = test_client();
        let header = client.get_header(1000).await.unwrap();
        println!("Header at slot 651232: {:?}", header);

        let header = client.get_header("finalized").await.unwrap();
        println!("Finalized header: {:?}", header);
    }

    #[ignore]
    #[tokio::test]
    async fn test_get_beacon_block_root() {
        let client = test_client();
        let block_root = client.get_beacon_block_root(120960).await.unwrap();
        println!("Block root at slot 120960: {:?}", block_root);
    }

    #[ignore]
    #[tokio::test]
    async fn test_get_bootstrap() {
        let client = test_client();

        let header_root = client.get_beacon_block_root(120960).await.unwrap();
        println!("Header root: {:?}", header_root);
        let snapshot = client.get_bootstrap(&header_root).await.unwrap();
        println!("Block snapshot: {:?}", snapshot);
    }

    #[ignore]
    #[tokio::test]
    async fn test_get_beacon_block() {
        let client = test_client();
        let block_body = client.get_beacon_block(100).await.unwrap();
        println!(
            "Block body: {:?}",
            block_body.body.execution_payload.block_number
        );
    }

    #[ignore]
    #[tokio::test]
    async fn test_get_checkpoint() {
        let client = test_client();
        let checkpoint = client.get_checkpoint(120960).await.unwrap();
        println!("Checkpoint: {:?}", checkpoint);
    }

    #[ignore]
    #[tokio::test]
    async fn test_get_state_proof() {
        let client = test_client();
        let proof = client.get_state_proof(120960u32, 55u32).await.unwrap();
        println!("Single proof: {:?}", proof);
    }

    #[ignore]
    #[tokio::test]
    async fn test_get_fork_version() {
        let client = test_client();
        let fork_version = client.get_fork_version(120960).await.unwrap();
        println!("Fork version: {:?}", fork_version);
    }

    #[ignore]
    #[tokio::test]
    async fn test_get_sync_committee_period_update() {
        let client = test_client();
        let update = client
            .get_sync_committee_period_update(12, 1)
            .await
            .unwrap();
        println!("Update: {:?}", update);
    }

    #[ignore]
    #[tokio::test]
    async fn test_get_finality_update() {
        let client = test_client();
        let finality_update = client.get_finality_update().await.unwrap();
        println!("Finality update: {:?}", finality_update);
    }
}