lumina-node 1.0.0

Celestia data availability node implementation in Rust
Documentation
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
#![cfg(not(target_arch = "wasm32"))]

use std::collections::HashSet;
use std::time::Duration;

use beetswap::utils::convert_cid;
use blockstore::Blockstore;
use celestia_rpc::{HeaderClient, ShareClient};
use celestia_types::nmt::{Namespace, NamespacedSha2Hasher};
use celestia_types::sample::SampleId;
use celestia_types::{Blob, ExtendedHeader};
use cid::{Cid, CidGeneric};
use lumina_node::NodeError;
use lumina_node::blockstore::InMemoryBlockstore;
use lumina_node::events::NodeEvent;
use lumina_node::node::P2pError;
use lumina_node::test_utils::test_node_builder;
use rand::RngCore;
use tokio::sync::mpsc;
use tokio::time::timeout;
use utils::new_connected_node_with_builder;

use crate::utils::{blob_submit, bridge_client, new_connected_node, wait_for_header};

mod utils;

#[tokio::test]
async fn shwap_sampling_forward() {
    let (node, _) = new_connected_node().await;

    // create new events sub to ignore all previous events
    let mut events = node.event_subscriber();

    for _ in 0..5 {
        // wait for new block
        let get_new_head = async {
            loop {
                let ev = events.recv().await.unwrap();
                let NodeEvent::AddedHeaderFromHeaderSub { height, .. } = ev.event else {
                    continue;
                };
                break height;
            }
        };
        // timeout is double of the block time on CI
        let new_head = timeout(Duration::from_secs(9), get_new_head).await.unwrap();

        // wait for height to be sampled
        let wait_height_sampled = async {
            loop {
                let ev = events.recv().await.unwrap();
                let NodeEvent::SamplingResult {
                    height, timed_out, ..
                } = ev.event
                else {
                    continue;
                };

                if height == new_head {
                    assert!(!timed_out);
                    break;
                }
            }
        };
        timeout(Duration::from_secs(1), wait_height_sampled)
            .await
            .unwrap();
    }
}

#[tokio::test]
async fn shwap_sampling_backward() {
    let (node, mut events) = new_connected_node().await;

    let current_head = node.get_local_head_header().await.unwrap().height();

    // wait for some past headers to be synchronized
    let new_batch_synced = async {
        loop {
            let ev = events.recv().await.unwrap();
            let NodeEvent::FetchingHeadersFinished {
                from_height,
                to_height,
                ..
            } = ev.event
            else {
                continue;
            };
            if to_height < current_head {
                break (from_height, to_height);
            }
        }
    };
    let (from_height, to_height) = timeout(Duration::from_secs(4), new_batch_synced)
        .await
        .unwrap();

    // take just first N headers because batch size can be big
    let mut headers_to_sample: HashSet<_> = (from_height..to_height).rev().take(10).collect();

    // wait for all heights to be sampled
    timeout(Duration::from_secs(10), async {
        loop {
            let ev = events.recv().await.unwrap();
            let NodeEvent::SamplingResult {
                height, timed_out, ..
            } = ev.event
            else {
                continue;
            };

            assert!(!timed_out);
            headers_to_sample.remove(&height);

            if headers_to_sample.is_empty() {
                break;
            }
        }
    })
    .await
    .unwrap();
}

#[tokio::test]
async fn shwap_request_sample() {
    let (node, _) = new_connected_node().await;
    let client = bridge_client().await;

    let ns = Namespace::const_v0(rand::random());
    let blob_len = rand::random::<usize>() % 4096 + 1;
    let blob = Blob::new(ns, random_bytes(blob_len), None).unwrap();

    let height = blob_submit(&client, &[blob]).await;
    let header = wait_for_header(&node, height).await;
    let square_width = header.square_width();

    // check existing sample
    let expected = client
        .share_get_share(header.height(), header.square_width(), 0, 0)
        .await
        .unwrap();
    let sample = node
        .request_sample(0, 0, height, Some(Duration::from_millis(500)))
        .await
        .unwrap();
    assert_eq!(expected, sample.share);

    // check nonexisting sample
    let err = node
        .request_sample(
            square_width + 1,
            square_width + 1,
            height,
            Some(Duration::from_millis(500)),
        )
        .await
        .unwrap_err();
    assert!(matches!(err, NodeError::P2p(P2pError::RequestTimedOut)));
}

#[tokio::test]
async fn shwap_request_row() {
    let (node, _) = new_connected_node().await;
    let client = bridge_client().await;

    let ns = Namespace::const_v0(rand::random());
    let blob_len = rand::random::<usize>() % 4096 + 1;
    let blob = Blob::new(ns, random_bytes(blob_len), None).unwrap();

    let height = blob_submit(&client, &[blob]).await;
    let header = wait_for_header(&node, height).await;
    let eds = client.share_get_eds(header.height()).await.unwrap();
    let square_width = header.square_width();

    // check existing row
    let row = node
        .request_row(0, height, Some(Duration::from_secs(1)))
        .await
        .unwrap();
    assert_eq!(eds.row(0).unwrap(), row.shares);

    // check nonexisting row
    let err = node
        .request_row(square_width + 1, height, Some(Duration::from_secs(1)))
        .await
        .unwrap_err();
    assert!(matches!(err, NodeError::P2p(P2pError::RequestTimedOut)));
}

#[tokio::test]
async fn shwap_request_row_namespace_data() {
    let (node, _) = new_connected_node().await;
    let client = bridge_client().await;

    let ns = Namespace::const_v0(rand::random());
    let blob_len = rand::random::<usize>() % 4096 + 1;
    let blob = Blob::new(ns, random_bytes(blob_len), None).unwrap();

    let height = blob_submit(&client, &[blob]).await;
    let header = wait_for_header(&node, height).await;
    let eds = client.share_get_eds(header.height()).await.unwrap();
    let square_width = header.square_width();

    // check existing row namespace data
    let rows_with_ns: Vec<_> = header
        .dah
        .row_roots()
        .iter()
        .enumerate()
        .filter_map(|(n, hash)| {
            hash.contains::<NamespacedSha2Hasher>(*ns)
                .then_some(n as u16)
        })
        .collect();
    let eds_ns_data = eds.get_namespace_data(ns, &header.dah, height).unwrap();

    for (n, &row) in rows_with_ns.iter().enumerate() {
        let row_ns_data = node
            .request_row_namespace_data(ns, row, height, Some(Duration::from_secs(1)))
            .await
            .unwrap();
        assert_eq!(eds_ns_data[n].1, row_ns_data);
    }

    // check nonexisting row row namespace data
    let err = node
        .request_row_namespace_data(ns, square_width + 1, height, Some(Duration::from_secs(1)))
        .await
        .unwrap_err();
    assert!(matches!(err, NodeError::P2p(P2pError::RequestTimedOut)));

    // check nonexisting namespace row namespace data
    // for namespace that row actually contains
    // PFB (0x04) < 0x05 < Primary ns padding (0x255)
    let unknown_ns = Namespace::const_v0([0, 0, 0, 0, 0, 0, 0, 0, 0, 5]);
    let row = node
        .request_row_namespace_data(unknown_ns, 0, height, Some(Duration::from_secs(1)))
        .await
        .unwrap();
    assert!(row.shares.is_empty());

    // check nonexisting namespace row namespace data
    // for namespace that row doesn't contain
    let unknown_ns = Namespace::TAIL_PADDING;
    let err = node
        .request_row_namespace_data(unknown_ns, 0, height, Some(Duration::from_secs(1)))
        .await
        .unwrap_err();
    assert!(matches!(err, NodeError::P2p(P2pError::RequestTimedOut)));
}

#[tokio::test]
async fn shwap_request_all_blobs() {
    let (node, _) = new_connected_node().await;
    let client = bridge_client().await;

    let ns = Namespace::const_v0(rand::random());
    let blobs: Vec<_> = (0..5)
        .map(|_| {
            let blob_len = rand::random::<usize>() % 4096 + 1;
            Blob::new(ns, random_bytes(blob_len), None).unwrap()
        })
        .collect();

    let height = blob_submit(&client, &blobs).await;

    // check existing namespace
    let received = node
        .request_all_blobs(ns, height, Some(Duration::from_secs(2)))
        .await
        .unwrap();

    assert_eq!(blobs, received);

    // check nonexisting namespace
    let ns = Namespace::const_v0(rand::random());
    let received = node
        .request_all_blobs(ns, height, Some(Duration::from_secs(2)))
        .await
        .unwrap();

    assert!(received.is_empty());
}

#[tokio::test]
async fn shwap_request_sample_should_cleanup_unneeded_samples() {
    // submit some blobs to celestia to get bigger square, so that daser
    // doesn't sample whole block
    let ns = Namespace::const_v0(rand::random());
    let blobs: Vec<_> = (0..5)
        .map(|_| {
            let blob_len = rand::random::<usize>() % 4096 + 1;
            Blob::new(ns, random_bytes(blob_len), None).unwrap()
        })
        .collect();

    // we submit before creating a node because it's quite slow and events can lag
    let client = bridge_client().await;
    let submitted_height = blob_submit(&client, &blobs).await;
    let header = client.header_get_by_height(submitted_height).await.unwrap();

    let (removed_sender, mut removed_receiver) = mpsc::unbounded_channel();
    let builder = test_node_builder()
        // explicitely set pruning window to something big so that
        // pruner doesn't kick in
        .pruning_window(Duration::from_secs(60 * 60 * 24))
        .blockstore(TestBlockstore::new(removed_sender));

    let (node, mut events) = new_connected_node_with_builder(builder).await;

    // wait for node to sample the height we just submitted
    timeout(Duration::from_secs(10), async {
        loop {
            let ev = events.recv().await.unwrap();
            let NodeEvent::SamplingResult { height, .. } = ev.event else {
                continue;
            };

            if height == submitted_height {
                break;
            }
        }
    })
    .await
    .unwrap();

    // get the cids selected by daser
    let cids = node
        .get_sampling_metadata(submitted_height)
        .await
        .unwrap()
        .unwrap()
        .cids;

    // try to request a sample that wasn't selected by daser
    let (row, col, cid) = loop {
        let (row, col, cid) = random_sample(&header);
        if !cids.contains(&cid) {
            break (row, col, cid);
        }
    };

    node.request_sample(row, col, submitted_height, None)
        .await
        .unwrap();

    // it should already be removed from the blockstore
    let removed_cid = removed_receiver.try_recv().unwrap();
    assert_eq!(removed_cid, cid);

    // now try to get a cid that was selected by daser
    let id = SampleId::try_from(cids[0]).unwrap();
    assert_eq!(id.block_height(), submitted_height);

    node.request_sample(id.row_index(), id.column_index(), submitted_height, None)
        .await
        .unwrap();

    // it shouldn't be removed from blockstore within pruning window
    removed_receiver.try_recv().unwrap_err();
}

struct TestBlockstore {
    blockstore: InMemoryBlockstore,
    removed_sender: mpsc::UnboundedSender<Cid>,
}

impl TestBlockstore {
    fn new(removed_sender: mpsc::UnboundedSender<Cid>) -> Self {
        Self {
            blockstore: InMemoryBlockstore::new(),
            removed_sender,
        }
    }
}

impl Blockstore for TestBlockstore {
    async fn get<const S: usize>(
        &self,
        cid: &CidGeneric<S>,
    ) -> blockstore::Result<Option<Vec<u8>>> {
        self.blockstore.get(cid).await
    }

    async fn put_keyed<const S: usize>(
        &self,
        cid: &CidGeneric<S>,
        data: &[u8],
    ) -> blockstore::Result<()> {
        self.blockstore.put_keyed(cid, data).await
    }

    async fn remove<const S: usize>(&self, cid: &CidGeneric<S>) -> blockstore::Result<()> {
        self.blockstore.remove(cid).await?;

        let cid = convert_cid(cid).unwrap();
        self.removed_sender.send(cid).unwrap();

        Ok(())
    }

    async fn close(self) -> blockstore::Result<()> {
        self.blockstore.close().await
    }
}

fn random_sample(header: &ExtendedHeader) -> (u16, u16, Cid) {
    let square = header.square_width();
    let id = SampleId::new(
        rand::random::<u16>() % square,
        rand::random::<u16>() % square,
        header.height(),
    )
    .unwrap();

    let cid = convert_cid(&id.into()).unwrap();

    (id.row_index(), id.column_index(), cid)
}

fn random_bytes(len: usize) -> Vec<u8> {
    let mut bytes = vec![0u8; len];
    rand::thread_rng().fill_bytes(&mut bytes);
    bytes
}