forked from eigerco/lumina
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode.rs
335 lines (295 loc) · 10.7 KB
/
node.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
//! High-level integration of [`P2p`], [`Store`], [`Syncer`].
//!
//! [`P2p`]: crate::p2p::P2p
//! [`Store`]: crate::store::Store
//! [`Syncer`]: crate::syncer::Syncer
use std::ops::RangeBounds;
use std::sync::Arc;
use blockstore::Blockstore;
use celestia_types::hash::Hash;
use celestia_types::namespaced_data::NamespacedData;
use celestia_types::nmt::Namespace;
use celestia_types::row::Row;
use celestia_types::sample::Sample;
use celestia_types::ExtendedHeader;
use libp2p::identity::Keypair;
use libp2p::swarm::NetworkInfo;
use libp2p::{Multiaddr, PeerId};
use tokio::select;
use tokio_util::sync::CancellationToken;
use tracing::warn;
use crate::daser::{Daser, DaserArgs, DaserError};
use crate::events::{EventChannel, EventSubscriber};
use crate::executor::spawn;
use crate::p2p::{P2p, P2pArgs, P2pError};
use crate::peer_tracker::PeerTrackerInfo;
use crate::store::{SamplingMetadata, Store, StoreError};
use crate::syncer::{Syncer, SyncerArgs, SyncerError, SyncingInfo};
type Result<T, E = NodeError> = std::result::Result<T, E>;
/// Representation of all the errors that can occur when interacting with the [`Node`].
#[derive(Debug, thiserror::Error)]
pub enum NodeError {
/// An error propagated from the [`P2p`] module.
#[error(transparent)]
P2p(#[from] P2pError),
/// An error propagated from the [`Syncer`] module.
#[error(transparent)]
Syncer(#[from] SyncerError),
/// An error propagated from the [`Store`] module.
#[error(transparent)]
Store(#[from] StoreError),
/// An error propagated from the [`Daser`] module.
#[error(transparent)]
Daser(#[from] DaserError),
}
/// Node conifguration.
pub struct NodeConfig<B, S>
where
B: Blockstore,
S: Store,
{
/// An id of the network to connect to.
pub network_id: String,
/// The hash of the genesis block in network.
pub genesis_hash: Option<Hash>,
/// The keypair to be used as [`Node`]s identity.
pub p2p_local_keypair: Keypair,
/// List of bootstrap nodes to connect to and trust.
pub p2p_bootnodes: Vec<Multiaddr>,
/// List of the addresses where [`Node`] will listen for incoming connections.
pub p2p_listen_on: Vec<Multiaddr>,
/// The blockstore for bitswap.
pub blockstore: B,
/// The store for headers.
pub store: S,
}
/// Celestia node.
pub struct Node<S>
where
S: Store + 'static,
{
event_channel: EventChannel,
p2p: Arc<P2p>,
store: Arc<S>,
syncer: Arc<Syncer<S>>,
_daser: Arc<Daser>,
tasks_cancellation_token: CancellationToken,
}
impl<S> Node<S>
where
S: Store,
{
/// Creates and starts a new celestia node with a given config.
pub async fn new<B>(config: NodeConfig<B, S>) -> Result<Self>
where
B: Blockstore + 'static,
{
let event_channel = EventChannel::new();
let store = Arc::new(config.store);
let p2p = Arc::new(P2p::start(P2pArgs {
network_id: config.network_id,
local_keypair: config.p2p_local_keypair,
bootnodes: config.p2p_bootnodes,
listen_on: config.p2p_listen_on,
blockstore: config.blockstore,
store: store.clone(),
event_pub: event_channel.publisher(),
})?);
let syncer = Arc::new(Syncer::start(SyncerArgs {
genesis_hash: config.genesis_hash,
store: store.clone(),
p2p: p2p.clone(),
})?);
let daser = Arc::new(Daser::start(DaserArgs {
p2p: p2p.clone(),
store: store.clone(),
event_pub: event_channel.publisher(),
})?);
// spawn the task that will stop the services when the fraud is detected
let network_compromised_token = p2p.get_network_compromised_token().await?;
let tasks_cancellation_token = CancellationToken::new();
spawn({
let syncer = syncer.clone();
let daser = daser.clone();
let tasks_cancellation_token = tasks_cancellation_token.child_token();
async move {
select! {
_ = tasks_cancellation_token.cancelled() => (),
_ = network_compromised_token.cancelled() => {
warn!("The network is compromised and should not be trusted.");
warn!("The node will stop synchronizing and sampling.");
warn!("You can still make some queries to the network.");
syncer.stop();
daser.stop();
}
}
}
});
Ok(Node {
event_channel,
p2p,
store,
syncer,
_daser: daser,
tasks_cancellation_token,
})
}
/// Returns a new `EventSubscriber`.
pub fn event_subscriber(&self) -> EventSubscriber {
self.event_channel.subscribe()
}
/// Get node's local peer ID.
pub fn local_peer_id(&self) -> &PeerId {
self.p2p.local_peer_id()
}
/// Get current [`PeerTracker`] info.
///
/// [`PeerTracker`]: crate::peer_tracker::PeerTracker
pub fn peer_tracker_info(&self) -> PeerTrackerInfo {
self.p2p.peer_tracker_info().clone()
}
/// Wait until the node is connected to at least 1 peer.
pub async fn wait_connected(&self) -> Result<()> {
Ok(self.p2p.wait_connected().await?)
}
/// Wait until the node is connected to at least 1 trusted peer.
pub async fn wait_connected_trusted(&self) -> Result<()> {
Ok(self.p2p.wait_connected_trusted().await?)
}
/// Get current network info.
pub async fn network_info(&self) -> Result<NetworkInfo> {
Ok(self.p2p.network_info().await?)
}
/// Get all the multiaddresses on which the node listens.
pub async fn listeners(&self) -> Result<Vec<Multiaddr>> {
Ok(self.p2p.listeners().await?)
}
/// Get all the peers that node is connected to.
pub async fn connected_peers(&self) -> Result<Vec<PeerId>> {
Ok(self.p2p.connected_peers().await?)
}
/// Trust or untrust the peer with a given ID.
pub async fn set_peer_trust(&self, peer_id: PeerId, is_trusted: bool) -> Result<()> {
Ok(self.p2p.set_peer_trust(peer_id, is_trusted).await?)
}
/// Request the head header from the network.
pub async fn request_head_header(&self) -> Result<ExtendedHeader> {
Ok(self.p2p.get_head_header().await?)
}
/// Request a header for the block with a given hash from the network.
pub async fn request_header_by_hash(&self, hash: &Hash) -> Result<ExtendedHeader> {
Ok(self.p2p.get_header(*hash).await?)
}
/// Request a header for the block with a given height from the network.
pub async fn request_header_by_height(&self, hash: u64) -> Result<ExtendedHeader> {
Ok(self.p2p.get_header_by_height(hash).await?)
}
/// Request headers in range (from, from + amount] from the network.
///
/// The headers will be verified with the `from` header.
pub async fn request_verified_headers(
&self,
from: &ExtendedHeader,
amount: u64,
) -> Result<Vec<ExtendedHeader>> {
Ok(self.p2p.get_verified_headers_range(from, amount).await?)
}
/// Request a verified [`Row`] from the network.
///
/// # Errors
///
/// On failure to receive a verified [`Row`] within a certain time, the
/// `NodeError::P2p(P2pError::BitswapQueryTimeout)` error will be returned.
pub async fn request_row(&self, row_index: u16, block_height: u64) -> Result<Row> {
Ok(self.p2p.get_row(row_index, block_height).await?)
}
/// Request a verified [`Sample`] from the network.
///
/// # Errors
///
/// On failure to receive a verified [`Sample`] within a certain time, the
/// `NodeError::P2p(P2pError::BitswapQueryTimeout)` error will be returned.
pub async fn request_sample(
&self,
row_index: u16,
column_index: u16,
block_height: u64,
) -> Result<Sample> {
Ok(self
.p2p
.get_sample(row_index, column_index, block_height)
.await?)
}
/// Request a verified [`NamespacedData`] from the network.
///
/// # Errors
///
/// On failure to receive a verified [`NamespacedData`] within a certain time, the
/// `NodeError::P2p(P2pError::BitswapQueryTimeout)` error will be returned.
pub async fn request_namespaced_data(
&self,
namespace: Namespace,
row_index: u16,
block_height: u64,
) -> Result<NamespacedData> {
Ok(self
.p2p
.get_namespaced_data(namespace, row_index, block_height)
.await?)
}
/// Get current header syncing info.
pub async fn syncer_info(&self) -> Result<SyncingInfo> {
Ok(self.syncer.info().await?)
}
/// Get the latest header announced in the network.
pub fn get_network_head_header(&self) -> Option<ExtendedHeader> {
self.p2p.header_sub_watcher().borrow().clone()
}
/// Get the latest locally synced header.
pub async fn get_local_head_header(&self) -> Result<ExtendedHeader> {
Ok(self.store.get_head().await?)
}
/// Get a synced header for the block with a given hash.
pub async fn get_header_by_hash(&self, hash: &Hash) -> Result<ExtendedHeader> {
Ok(self.store.get_by_hash(hash).await?)
}
/// Get a synced header for the block with a given height.
pub async fn get_header_by_height(&self, height: u64) -> Result<ExtendedHeader> {
Ok(self.store.get_by_height(height).await?)
}
/// Get synced headers from the given heights range.
///
/// If start of the range is unbounded, the first returned header will be of height 1.
/// If end of the range is unbounded, the last returned header will be the last header in the
/// store.
///
/// # Errors
///
/// If range contains a height of a header that is not found in the store or [`RangeBounds`]
/// cannot be converted to a valid range.
pub async fn get_headers<R>(&self, range: R) -> Result<Vec<ExtendedHeader>>
where
R: RangeBounds<u64> + Send,
{
Ok(self.store.get_range(range).await?)
}
/// Get data sampling metadata of an already sampled height.
///
/// Returns `Ok(None)` if metadata for the given height does not exists.
pub async fn get_sampling_metadata(&self, height: u64) -> Result<Option<SamplingMetadata>> {
match self.store.get_sampling_metadata(height).await {
Ok(val) => Ok(val),
Err(StoreError::NotFound) => Ok(None),
Err(e) => Err(e.into()),
}
}
}
impl<S> Drop for Node<S>
where
S: Store,
{
fn drop(&mut self) {
// we have to cancel the task to drop the Arc's passed to it
self.tasks_cancellation_token.cancel();
}
}