-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathclient.rs
469 lines (399 loc) · 14.2 KB
/
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use std::sync::Arc;
use anyhow::{anyhow, Result};
use crate::consensus::ConsensusLightClient;
use log::{error, info, warn};
use tokio::sync::RwLock;
use crate::{
config::{client_config::Config, CheckpointFallback, Network},
consensus::{errors::ConsensusError, rpc::ConsensusRpc},
};
use ethportal_api::{consensus::header::BeaconBlockHeader, light_client::store::LightClientStore};
use std::path::PathBuf;
use tokio::{spawn, time::sleep};
use crate::{database::Database, errors::NodeError, node::Node};
use crate::rpc::Rpc;
#[derive(Default)]
pub struct ClientBuilder {
network: Option<Network>,
consensus_rpc: Option<String>,
checkpoint: Option<Vec<u8>>,
rpc_port: Option<u16>,
data_dir: Option<PathBuf>,
config: Option<Config>,
fallback: Option<String>,
load_external_fallback: bool,
strict_checkpoint_age: bool,
}
impl ClientBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn network(mut self, network: Network) -> Self {
self.network = Some(network);
self
}
pub fn consensus_rpc(mut self, consensus_rpc: &str) -> Self {
self.consensus_rpc = Some(consensus_rpc.to_string());
self
}
pub fn checkpoint(mut self, checkpoint: &str) -> Self {
let checkpoint = hex::decode(checkpoint.strip_prefix("0x").unwrap_or(checkpoint))
.expect("cannot parse checkpoint");
self.checkpoint = Some(checkpoint);
self
}
pub fn rpc_port(mut self, port: u16) -> Self {
self.rpc_port = Some(port);
self
}
pub fn data_dir(mut self, data_dir: PathBuf) -> Self {
self.data_dir = Some(data_dir);
self
}
pub fn config(mut self, config: Config) -> Self {
self.config = Some(config);
self
}
pub fn fallback(mut self, fallback: &str) -> Self {
self.fallback = Some(fallback.to_string());
self
}
pub fn load_external_fallback(mut self) -> Self {
self.load_external_fallback = true;
self
}
pub fn strict_checkpoint_age(mut self) -> Self {
self.strict_checkpoint_age = true;
self
}
pub fn build<DB: Database, R: ConsensusRpc + 'static>(self) -> Result<Client<DB, R>> {
let base_config = if let Some(network) = self.network {
network.to_base_config()
} else {
let config = self
.config
.as_ref()
.ok_or(anyhow!("missing network config"))?;
config.to_base_config()
};
let consensus_rpc = self.consensus_rpc.unwrap_or_else(|| {
self.config
.as_ref()
.expect("missing consensus rpc")
.consensus_rpc
.clone()
});
let checkpoint = if let Some(checkpoint) = self.checkpoint {
Some(checkpoint)
} else if let Some(config) = &self.config {
config.checkpoint.clone()
} else {
None
};
let default_checkpoint = if let Some(config) = &self.config {
config.default_checkpoint.clone()
} else {
base_config.default_checkpoint.clone()
};
let rpc_port = if self.rpc_port.is_some() {
self.rpc_port
} else if let Some(config) = &self.config {
config.rpc_port
} else {
None
};
let data_dir = if self.data_dir.is_some() {
self.data_dir
} else if let Some(config) = &self.config {
config.data_dir.clone()
} else {
None
};
let fallback = if self.fallback.is_some() {
self.fallback
} else if let Some(config) = &self.config {
config.fallback.clone()
} else {
None
};
let load_external_fallback = if let Some(config) = &self.config {
self.load_external_fallback || config.load_external_fallback
} else {
self.load_external_fallback
};
let strict_checkpoint_age = if let Some(config) = &self.config {
self.strict_checkpoint_age || config.strict_checkpoint_age
} else {
self.strict_checkpoint_age
};
let config = Config {
consensus_rpc,
checkpoint,
default_checkpoint,
rpc_port,
data_dir,
chain: base_config.chain,
forks: base_config.forks,
max_checkpoint_age: base_config.max_checkpoint_age,
fallback,
load_external_fallback,
strict_checkpoint_age,
};
Client::new(config)
}
pub fn build_with_rpc<DB: Database, R: ConsensusRpc + 'static>(
self,
portal_rpc: R,
) -> Result<Client<DB, R>> {
let base_config = if let Some(network) = self.network {
network.to_base_config()
} else {
let config = self
.config
.as_ref()
.ok_or(anyhow!("missing network config"))?;
config.to_base_config()
};
let checkpoint = if let Some(checkpoint) = self.checkpoint {
Some(checkpoint)
} else if let Some(config) = &self.config {
config.checkpoint.clone()
} else {
None
};
let default_checkpoint = if let Some(config) = &self.config {
config.default_checkpoint.clone()
} else {
base_config.default_checkpoint.clone()
};
let rpc_port = if self.rpc_port.is_some() {
self.rpc_port
} else if let Some(config) = &self.config {
config.rpc_port
} else {
None
};
let data_dir = if self.data_dir.is_some() {
self.data_dir
} else if let Some(config) = &self.config {
config.data_dir.clone()
} else {
None
};
let fallback = if self.fallback.is_some() {
self.fallback
} else if let Some(config) = &self.config {
config.fallback.clone()
} else {
None
};
let load_external_fallback = if let Some(config) = &self.config {
self.load_external_fallback || config.load_external_fallback
} else {
self.load_external_fallback
};
let strict_checkpoint_age = if let Some(config) = &self.config {
self.strict_checkpoint_age || config.strict_checkpoint_age
} else {
self.strict_checkpoint_age
};
let config = Config {
checkpoint,
default_checkpoint,
rpc_port,
data_dir,
chain: base_config.chain,
forks: base_config.forks,
max_checkpoint_age: base_config.max_checkpoint_age,
fallback,
load_external_fallback,
strict_checkpoint_age,
..Default::default()
};
Client::with_portal(config, portal_rpc)
}
}
#[derive(Clone)]
pub struct Client<DB: Database, R: ConsensusRpc> {
node: Arc<RwLock<Node<R>>>,
rpc: Option<Rpc<R>>,
db: DB,
fallback: Option<String>,
load_external_fallback: bool,
}
impl<DB: Database, R: ConsensusRpc + 'static> Client<DB, R> {
fn new(mut config: Config) -> Result<Self> {
let db = DB::new(&config)?;
if config.checkpoint.is_none() {
let checkpoint = db.load_checkpoint()?;
config.checkpoint = Some(checkpoint);
}
let config = Arc::new(config);
let node = Node::new(config.clone())?;
let node = Arc::new(RwLock::new(node));
let rpc = config.rpc_port.map(|port| Rpc::new(node.clone(), port));
Ok(Client {
node,
rpc,
db,
fallback: config.fallback.clone(),
load_external_fallback: config.load_external_fallback,
})
}
fn with_portal(mut config: Config, portal_rpc: R) -> Result<Self> {
let db = DB::new(&config)?;
if config.checkpoint.is_none() {
let checkpoint = db.load_checkpoint()?;
config.checkpoint = Some(checkpoint);
}
let config = Arc::new(config);
let node = Node::with_portal(config.clone(), portal_rpc)?;
let node = Arc::new(RwLock::new(node));
let rpc = config.rpc_port.map(|port| Rpc::new(node.clone(), port));
Ok(Client {
node,
rpc,
db,
fallback: config.fallback.clone(),
load_external_fallback: config.load_external_fallback,
})
}
pub async fn start(&mut self) -> Result<()> {
if let Some(rpc) = &mut self.rpc {
rpc.start().await?;
}
let sync_res = self.node.write().await.sync().await;
if let Err(err) = sync_res {
match err {
NodeError::ConsensusSyncError(err) => match err
.downcast_ref()
.ok_or(err.to_string())
.map_err(|err| anyhow!(err))?
{
ConsensusError::CheckpointTooOld => {
warn!(
"failed to sync consensus node with checkpoint: 0x{}",
hex::encode(
self.node
.read()
.await
.config
.checkpoint
.clone()
.unwrap_or_default()
),
);
let fallback = self.boot_from_fallback().await;
if fallback.is_err() && self.load_external_fallback {
self.boot_from_external_fallbacks().await?
} else if fallback.is_err() {
error!("Invalid checkpoint. Please update your checkpoint too a more recent block. Alternatively, set an explicit checkpoint fallback service url with the `-f` flag or use the configured external fallback services with `-l` (NOT RECOMMENDED)");
return Err(err);
}
}
_ => return Err(err),
},
_ => return Err(err.into()),
}
}
self.start_advance_thread();
Ok(())
}
fn start_advance_thread(&self) {
let node = self.node.clone();
spawn(async move {
loop {
let res = node.write().await.advance().await;
if let Err(err) = res {
warn!("consensus error: {}", err);
}
let next_update = node.read().await.duration_until_next_update();
sleep(next_update).await;
}
});
}
async fn boot_from_fallback(&self) -> anyhow::Result<()> {
if let Some(fallback) = &self.fallback {
info!(
"attempting to load checkpoint from fallback \"{}\"",
fallback
);
let checkpoint = CheckpointFallback::fetch_checkpoint_from_api(fallback)
.await
.map_err(|_| {
anyhow!("Failed to fetch checkpoint from fallback \"{}\"", fallback)
})?;
info!(
"external fallbacks responded with checkpoint 0x{:?}",
checkpoint
);
// Try to sync again with the new checkpoint by reconstructing the consensus client
// We fail fast here since the node is unrecoverable at this point
let config = self.node.read().await.config.clone();
let consensus = ConsensusLightClient::new(
&config.consensus_rpc,
checkpoint.as_slice(),
config.clone(),
)?;
self.node.write().await.consensus = consensus;
self.node.write().await.sync().await?;
Ok(())
} else {
Err(anyhow!("no explicit fallback specified"))
}
}
async fn boot_from_external_fallbacks(&self) -> anyhow::Result<()> {
info!("attempting to fetch checkpoint from external fallbacks...");
// Build the list of external checkpoint fallback services
let list = CheckpointFallback::new()
.build()
.await
.map_err(|_| anyhow!("Failed to construct external checkpoint sync fallbacks"))?;
let checkpoint = list
.fetch_latest_checkpoint(&Network::Mainnet)
.await
.map_err(|_| {
anyhow!("Failed to fetch latest mainnet checkpoint from external fallbacks")
})?;
info!(
"external fallbacks responded with checkpoint {:?}",
checkpoint
);
// Try to sync again with the new checkpoint by reconstructing the consensus client
// We fail fast here since the node is unrecoverable at this point
let config = self.node.read().await.config.clone();
let consensus = ConsensusLightClient::new(
&config.consensus_rpc,
checkpoint.as_slice(),
config.clone(),
)?;
self.node.write().await.consensus = consensus;
self.node.write().await.sync().await?;
Ok(())
}
pub async fn shutdown(&self) {
let node = self.node.read().await;
let checkpoint = if let Some(checkpoint) = node.get_last_checkpoint() {
checkpoint
} else {
return;
};
info!("saving last checkpoint hash");
let res = self.db.save_checkpoint(checkpoint);
if res.is_err() {
warn!("checkpoint save failed");
}
}
pub async fn chain_id(&self) -> u64 {
self.node.read().await.chain_id()
}
pub async fn get_header(&self) -> Result<BeaconBlockHeader> {
self.node.read().await.get_header()
}
pub async fn get_finalized_header(&self) -> Result<BeaconBlockHeader> {
self.node.read().await.get_finalized_header()
}
pub async fn get_light_client_store(&self) -> Result<LightClientStore> {
self.node.read().await.get_light_client_store()
}
}