flmodules 0.10.0

Modules used in fledger
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
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
use std::collections::HashMap;

use flarch::{
    broker::SubsystemHandler,
    data_storage::DataStorage,
    nodeids::{NodeID, U256},
    platform_async_trait,
};
use flcrypto::tofrombytes::ToFromBytes;
use serde::{Deserialize, Serialize};
use tokio::sync::watch;

use crate::{
    dht_router::broker::{DHTRouterIn, DHTRouterOut},
    flo::{
        flo::{Flo, FloID},
        realm::{FloRealm, GlobalID, RealmID},
    },
    router::messages::NetworkWrapper,
};

use super::{
    broker::{DHTStorageIn, DHTStorageOut, MODULE_NAME},
    core::*,
};

/// The messages here represent all possible interactions with this module.
#[derive(Debug, Clone, PartialEq)]
pub(super) enum InternIn {
    Routing(DHTRouterOut),
    Storage(DHTStorageIn),
}

#[derive(Debug, Clone, PartialEq)]
pub(super) enum InternOut {
    Routing(DHTRouterIn),
    Storage(DHTStorageOut),
}

/// These messages are sent to the closest node given in the DHTRouting message.
/// Per default, the 'key' value of the DHTRouting will be filled with the FloID.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum MessageClosest {
    // Stores the given Flo in the closest node, and all nodes on the route
    // which have enough place left.
    StoreFlo(Flo),
    // Request a Flo. The FloID is in the DHTRouting::Request.
    ReadFlo(RealmID),
    // Request Cuckoos for the given ID. The FloID is in the DHTRouting::Request.
    GetCuckooIDs(RealmID),
    // Store the Cuckoo-ID in the relevant Flo. The DHTRouting::Request(key) is the
    // parent Flo, and the given GlobalID is the ID of the Cuckoo and the RealmID of the
    // parent Flo and the Cuckoo.
    StoreCuckooID(GlobalID),
}

/// These messages are sent directly to the requester of the MessageNodeClosest.
/// As in this case there is no 'key', the IDs need to be transmitted completely.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum MessageDest {
    // Returns the result of the requested Flo, including any available Cuckoo-IDs.
    FloValue(FloCuckoo),
    // Indicates this Flo is not in the closest node.
    UnknownFlo(GlobalID),
    // The Cuckoo-IDs stored next to the Flo composed of the GlobalID
    CookooIDs(GlobalID, Vec<FloID>),
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum MessageNeighbour {
    RequestRealmIDs,
    AvailableRealmIDs(Vec<RealmID>),
    RequestFloMetas(RealmID),
    AvailableFlos(RealmID, Vec<FloMeta>),
    RequestFlos(RealmID, Vec<FloID>),
    Flos(Vec<FloCuckoo>),
}

#[derive(Debug, Clone)]
pub struct RealmStats {
    pub real_size: usize,
    pub size: u64,
    pub flos: usize,
    pub distribution: Vec<usize>,
    pub config: RealmConfig,
}

#[derive(Debug, Default, Clone)]
pub struct Stats {
    pub realm_stats: HashMap<RealmID, RealmStats>,
    pub system_realms: Vec<RealmID>,
}

/// The message handling part, but only for DHTStorage messages.
pub struct Messages {
    realms: HashMap<RealmID, RealmStorage>,
    nodes: Vec<NodeID>,
    config: DHTConfig,
    ds: Box<dyn DataStorage + Send>,
    tx: Option<watch::Sender<Stats>>,
}

impl Messages {
    /// Returns a new chat module.
    pub fn new(
        ds: Box<dyn DataStorage + Send>,
        config: DHTConfig,
    ) -> (Self, watch::Receiver<Stats>) {
        let str = ds.get(MODULE_NAME).unwrap_or("".into());
        let realms = serde_yaml::from_str(&str).unwrap_or(HashMap::new());
        let (tx, rx) = watch::channel(Stats::default());
        let mut msgs = Self {
            realms,
            config,
            nodes: vec![],
            ds,
            tx: Some(tx),
        };
        msgs.store();
        (msgs, rx)
    }

    fn msg_dht_router(&mut self, msg: DHTRouterOut) -> Vec<InternOut> {
        match msg {
            DHTRouterOut::MessageRouting(origin, _last_hop, _next_hop, key, msg) => msg
                .unwrap_yaml(MODULE_NAME)
                .map(|mn| self.msg_routing(false, origin, key, mn)),
            DHTRouterOut::MessageClosest(origin, _last_hop, key, msg) => msg
                .unwrap_yaml(MODULE_NAME)
                .map(|mn| self.msg_routing(true, origin, key, mn)),
            DHTRouterOut::MessageDest(_origin, _last_hop, msg) => {
                msg.unwrap_yaml(MODULE_NAME).map(|mn| self.msg_dest(mn))
            }
            DHTRouterOut::NodeList(nodes) => {
                self.nodes = nodes;
                None
            }
            DHTRouterOut::MessageNeighbour(origin, msg) => msg
                .unwrap_yaml(MODULE_NAME)
                .map(|mn| self.msg_neighbour(origin, mn)),
            DHTRouterOut::SystemRealm(realm_id) => {
                if !self.config.realms.contains(&realm_id) {
                    self.config.realms.push(realm_id);
                }
                None
            }
        }
        .unwrap_or(vec![])
    }

    fn msg_dht_storage(&mut self, msg: DHTStorageIn) -> Vec<InternOut> {
        // log::warn!("Storing {msg:?}");
        match msg {
            DHTStorageIn::StoreFlo(flo) => self.store_flo(flo),
            DHTStorageIn::ReadFlo(id) => vec![match self.read_flo(&id) {
                Some(df) => DHTStorageOut::FloValue(df.clone()).into(),
                None => MessageClosest::ReadFlo(id.realm_id().clone())
                    .to_intern_out(id.flo_id().clone().into())
                    // .inspect(|msg| log::info!("{} sends {msg:?}", self.config.our_id))
                    .expect("Creating ReadFlo message"),
            }],
            DHTStorageIn::ReadCuckooIDs(id) => {
                let mut out: Vec<InternOut> = self
                    .realms
                    .get(id.realm_id())
                    .and_then(|realm| realm.get_cuckoo_ids(id.flo_id()))
                    .map(|cids| vec![DHTStorageOut::CuckooIDs(id.clone(), cids).into()])
                    .unwrap_or_default();
                out.push(
                    MessageClosest::GetCuckooIDs(id.realm_id().clone())
                        .to_intern_out(id.flo_id().clone().into())
                        .expect("Creating GetCuckoos"),
                );
                out
            }
            DHTStorageIn::SyncFromNeighbors => vec![MessageNeighbour::RequestRealmIDs
                .to_broadcast()
                .expect("Creating Request broadcast")],
            DHTStorageIn::GetRealms => {
                vec![DHTStorageOut::RealmIDs(self.realms.keys().cloned().collect()).into()]
            }
            DHTStorageIn::GetFlos => {
                vec![DHTStorageOut::FloValues(
                    self.realms
                        .iter()
                        .flat_map(|realm| realm.1.get_all_flo_cuckoos())
                        .collect::<Vec<_>>(),
                )
                .into()]
            }
            DHTStorageIn::PropagateFlos => {
                MessageNeighbour::AvailableRealmIDs(self.realms.keys().cloned().collect())
                    .to_broadcast()
                    .map_or(vec![], |msg| vec![msg])
            }
        }
    }

    fn msg_routing(
        &mut self,
        _closest: bool,
        origin: NodeID,
        key: U256,
        msg: MessageClosest,
    ) -> Vec<InternOut> {
        let fid: FloID = key.into();
        match msg {
            MessageClosest::StoreFlo(flo) => {
                return self.store_flo(flo);
            }
            MessageClosest::ReadFlo(rid) => {
                // log::info!(
                //     "{} got request for {}/{} from {}",
                //     self.config.our_id,
                //     key,
                //     rid,
                //     origin
                // );
                // log::info!("{}", self.realms.get(&rid).is_some());
                if let Some(fc) = self
                    .realms
                    .get(&rid)
                    .and_then(|realm| realm.get_flo_cuckoo(&fid))
                {
                    // log::info!("sends flo {:?}", fc.0);
                    return MessageDest::FloValue(fc)
                        .to_intern_out(origin)
                        // .inspect(|msg| log::info!("{} sends {msg:?}", self.config.our_id))
                        .map_or(vec![], |msg| vec![msg]);
                }
            }
            MessageClosest::GetCuckooIDs(rid) => {
                let parent = GlobalID::new(rid.clone(), fid.clone());
                return self
                    .realms
                    .get(&rid)
                    .and_then(|realm| realm.get_cuckoo_ids(&fid))
                    .map_or(vec![], |ids| {
                        MessageDest::CookooIDs(parent, ids)
                            .to_intern_out(origin)
                            .map_or(vec![], |msg| vec![msg])
                    });
            }
            MessageClosest::StoreCuckooID(gid) => {
                self.realms
                    .get_mut(&gid.realm_id())
                    .map(|realm| realm.store_cuckoo_id(&fid, gid.flo_id().clone()));
            }
        }
        vec![]
    }

    fn msg_dest(&mut self, msg: MessageDest) -> Vec<InternOut> {
        match msg {
            MessageDest::FloValue(fc) => {
                // log::info!("{} stores {:?}", self.config.our_id, flo.0);
                self.store_flo(fc.0.clone());
                self.realms
                    .get_mut(&fc.0.realm_id())
                    .map(|realm| realm.store_cuckoo_ids(&fc.0.flo_id(), fc.1.clone()));
                Some(DHTStorageOut::FloValue(fc).into())
            }
            MessageDest::UnknownFlo(key) => Some(DHTStorageOut::ValueMissing(key).into()),
            MessageDest::CookooIDs(gid, cids) => Some(DHTStorageOut::CuckooIDs(gid, cids).into()),
        }
        .map_or(vec![], |msg| vec![msg])
    }

    fn msg_neighbour(&mut self, origin: NodeID, msg: MessageNeighbour) -> Vec<InternOut> {
        // log::trace!("{} syncs {:?}", self.config.our_id, msg);
        // if let Sync::RequestFloMetas(rid) = &msg {
        //     log::trace!(
        //         "{} receives ReqFloMet from {} and will reply: {}",
        //         self.config.our_id,
        //         origin,
        //         self.realms
        //             .get(rid)
        //             .map(|realm| realm
        //                 .get_flo_metas()
        //                 .iter()
        //                 .map(|fm| format!("{}", fm.id))
        //                 .sorted()
        //                 .collect::<Vec<_>>()
        //                 .join(" - "))
        //             .unwrap_or("".to_string())
        //     );
        // }
        match msg {
            MessageNeighbour::RequestRealmIDs => vec![MessageNeighbour::AvailableRealmIDs(
                self.realms.keys().cloned().collect(),
            )],
            MessageNeighbour::AvailableRealmIDs(realm_ids) => {
                let accepted_realms = realm_ids
                    .into_iter()
                    .filter(|rid| self.config.accepts_realm(&rid))
                    .collect::<Vec<_>>();
                accepted_realms
                    .iter()
                    .filter(|id| !self.realms.contains_key(id))
                    .map(|rid| MessageNeighbour::RequestFlos(rid.clone(), vec![(**rid).into()]))
                    .chain(
                        accepted_realms
                            .iter()
                            .map(|rid| MessageNeighbour::RequestFloMetas(rid.clone())),
                    )
                    .collect()
            }
            MessageNeighbour::RequestFloMetas(realm_id) => self
                .realms
                .get(&realm_id)
                .map(|realm| realm.get_flo_metas())
                .map_or(vec![], |fm| {
                    vec![MessageNeighbour::AvailableFlos(realm_id, fm)]
                }),
            MessageNeighbour::AvailableFlos(realm_id, flo_metas) => self
                .realms
                .get(&realm_id)
                .and_then(|realm| realm.sync_available(&flo_metas))
                .map_or(vec![], |needed| {
                    vec![MessageNeighbour::RequestFlos(realm_id, needed)]
                }),
            MessageNeighbour::RequestFlos(realm_id, flo_ids) => self
                .realms
                .get(&realm_id)
                .map(|realm| {
                    flo_ids
                        .iter()
                        .filter_map(|id| realm.get_flo_cuckoo(id))
                        .collect::<Vec<_>>()
                })
                .map_or(vec![], |flos| vec![MessageNeighbour::Flos(flos)]),
            MessageNeighbour::Flos(flo_cuckoos) => {
                for (flo, cuckoos) in flo_cuckoos {
                    self.store_flo(flo.clone());
                    self.realms.get_mut(&flo.realm_id()).map(|realm| {
                        cuckoos
                            .into_iter()
                            .for_each(|cuckoo| realm.store_cuckoo_id(&flo.flo_id(), cuckoo))
                    });
                }
                vec![]
            }
        }
        .into_iter()
        .filter_map(|msg| msg.to_neighbour(origin))
        .collect()
    }

    fn read_flo(&self, id: &GlobalID) -> Option<FloCuckoo> {
        self.realms
            .get(id.realm_id())
            .and_then(|realm| realm.get_flo_cuckoo(id.flo_id()))
    }

    fn store_flo(&mut self, flo: Flo) -> Vec<InternOut> {
        let mut res = vec![];
        if self.upsert_flo(flo.clone()) {
            // log::info!("{}: store_flo", self.config.our_id);
            // TODO: this should not be sent in all cases...
            res.extend(vec![MessageClosest::StoreFlo(flo.clone())
                .to_intern_out(flo.flo_id().into())
                .expect("Storing new DHT")]);
        }
        if let Some(parent) = flo.flo_config().cuckoo_parent() {
            res.extend(vec![MessageClosest::StoreCuckooID(flo.global_id())
                .to_intern_out(*parent.clone())
                .expect("Storing new Cuckoo")])
        }
        res
    }

    // Try really hard to store the flo.
    // Either its realm is already known, or it is a new realm.
    // When 'true' is returned, then the flo has been stored.
    fn upsert_flo(&mut self, flo: Flo) -> bool {
        // log::trace!(
        //     "{} store_flo {}({}/{}) {}",
        //     self.config.our_id,
        //     flo.flo_type(),
        //     flo.flo_id(),
        //     flo.realm_id(),
        //     flo.version()
        // );
        // log::info!(
        //     "{} has realm: {}",
        //     self.config.our_id,
        //     self.realms.get(&flo.realm_id()).is_some()
        // );
        // log::info!(
        //     "Can create FloRealm of {}/{:?}: {:?}",
        //     flo.flo_type(),
        //     flo.data(),
        //     TryInto::<FloRealm>::try_into(flo.clone())
        // );
        let modification = self
            .realms
            .get_mut(&flo.realm_id())
            // .inspect(|rs| log::info!("{} has realm", self.config.our_id))
            .map(|dsc| dsc.upsert_flo(flo.clone()))
            .unwrap_or_else(|| {
                TryInto::<FloRealm>::try_into(flo)
                    .ok()
                    .and_then(|realm| self.create_realm(realm).ok())
                    .is_some()
            });

        if modification {
            self.store();
        }
        modification
    }

    fn create_realm(&mut self, realm: FloRealm) -> anyhow::Result<()> {
        if !self.config.accepts_realm(&realm.realm_id()) {
            return Err(CoreError::RealmNotAccepted.into());
        }
        // log::debug!(
        //     "{} creating realm {}/{}",
        //     self.config.our_id,
        //     realm.realm_id(),
        //     realm.version()
        // );
        let id = realm.flo().realm_id();
        let dsc = RealmStorage::new(self.config.clone(), realm)?;
        self.realms.insert(id.clone(), dsc);
        // log::info!("Realm {}: {}", id, self.realms.get(&id).is_some());
        Ok(())
    }

    fn store(&mut self) {
        self.tx.clone().map(|tx| {
            tx.send(Stats::from_realms(&self.realms, self.config.realms.clone()))
                .is_err()
                .then(|| self.tx = None)
        });
        serde_yaml::to_string(&self.realms)
            .ok()
            .map(|s| (*self.ds).set(MODULE_NAME, &s));
    }
}

#[platform_async_trait()]
impl SubsystemHandler<InternIn, InternOut> for Messages {
    async fn messages(&mut self, inputs: Vec<InternIn>) -> Vec<InternOut> {
        let _id = self.config.our_id;
        inputs
            .into_iter()
            .inspect(|msg| log::trace!("DHTStorageIn: {msg:?}"))
            .flat_map(|msg| match msg {
                InternIn::Routing(dhtrouting_out) => self.msg_dht_router(dhtrouting_out),
                InternIn::Storage(dhtstorage_in) => self.msg_dht_storage(dhtstorage_in),
            })
            .inspect(|msg| log::trace!("DHTStorageOut: {msg:?}"))
            .collect()
    }
}

impl Stats {
    fn from_realms(realms: &HashMap<RealmID, RealmStorage>, system_realms: Vec<RealmID>) -> Self {
        Self {
            realm_stats: realms
                .iter()
                .map(|(id, realm)| (id.clone(), RealmStats::from_realm(realm)))
                .collect(),
            system_realms,
        }
    }
}

impl RealmStats {
    fn from_realm(realm: &RealmStorage) -> Self {
        Self {
            real_size: realm.size(),
            size: realm.size,
            flos: realm.flo_count(),
            distribution: realm.flo_distribution(),
            config: realm.realm_config().clone(),
        }
    }
}

impl MessageClosest {
    fn to_intern_out(&self, dst: NodeID) -> Option<InternOut> {
        NetworkWrapper::wrap_yaml(MODULE_NAME, self)
            .ok()
            .map(|msg_wrap| InternOut::Routing(DHTRouterIn::MessageClosest(dst, msg_wrap)))
    }
}

impl MessageDest {
    fn to_intern_out(&self, dst: NodeID) -> Option<InternOut> {
        NetworkWrapper::wrap_yaml(MODULE_NAME, self)
            .ok()
            .map(|msg_wrap| InternOut::Routing(DHTRouterIn::MessageDirect(dst, msg_wrap)))
    }
}

impl From<DHTStorageOut> for InternOut {
    fn from(value: DHTStorageOut) -> Self {
        InternOut::Storage(value)
    }
}

impl MessageNeighbour {
    fn to_neighbour(self, dst: NodeID) -> Option<InternOut> {
        (match &self {
            MessageNeighbour::AvailableRealmIDs(realm_ids) => realm_ids.len(),
            MessageNeighbour::AvailableFlos(_, flo_metas) => flo_metas.len(),
            MessageNeighbour::RequestFlos(_, flo_ids) => flo_ids.len(),
            MessageNeighbour::Flos(items) => items.len(),
            _ => 1,
        } > 0)
            .then(|| {
                NetworkWrapper::wrap_yaml(MODULE_NAME, &self)
                    .ok()
                    .map(|msg_wrap| {
                        InternOut::Routing(DHTRouterIn::MessageNeighbour(dst, msg_wrap))
                    })
            })
            .flatten()
    }

    fn to_broadcast(self) -> Option<InternOut> {
        (match &self {
            MessageNeighbour::AvailableRealmIDs(realm_ids) => realm_ids.len(),
            MessageNeighbour::AvailableFlos(_, flo_metas) => flo_metas.len(),
            MessageNeighbour::RequestFlos(_, flo_ids) => flo_ids.len(),
            MessageNeighbour::Flos(items) => items.len(),
            _ => 1,
        } > 0)
            .then(|| {
                NetworkWrapper::wrap_yaml(MODULE_NAME, &self)
                    .ok()
                    .map(|msg_wrap| InternOut::Routing(DHTRouterIn::MessageBroadcast(msg_wrap)))
            })
            .flatten()
    }
}

#[cfg(test)]
mod tests {
    use flarch::{data_storage::DataStorageTemp, start_logging};
    use flcrypto::{access::Condition, signer_ed25519::SignerEd25519};

    use crate::{
        flo::realm::Realm,
        testing::wallet::{FloTesting, Wallet},
    };

    use super::*;

    #[test]
    fn test_choice() -> anyhow::Result<()> {
        let our_id = NodeID::rnd();
        let mut dht = Messages::new(Box::new(DataStorageTemp::new()), DHTConfig::default(our_id)).0;

        let mut wallet = Wallet::new();
        let realm = wallet.get_realm();
        dht.msg_dht_storage(DHTStorageIn::StoreFlo(realm.flo().clone()));
        let out = dht.msg_dht_storage(DHTStorageIn::ReadFlo(realm.global_id()));
        assert_eq!(1, out.len());
        assert_eq!(
            *out.get(0).unwrap(),
            InternOut::Storage(DHTStorageOut::FloValue((realm.flo().clone(), vec![])))
        );
        Ok(())
    }

    #[test]
    fn serialize() -> anyhow::Result<()> {
        let fr = FloRealm::from_type(
            RealmID::rnd(),
            Condition::Pass,
            Realm::new(
                "root".into(),
                RealmConfig {
                    max_space: 1000,
                    max_flo_size: 1000,
                },
            ),
            &[],
        )?;

        let out = NetworkWrapper::wrap_yaml(
            MODULE_NAME,
            &MessageDest::FloValue((fr.flo().clone(), vec![])),
        )
        .unwrap();

        if let MessageDest::FloValue(flo) = out.unwrap_yaml(MODULE_NAME).unwrap() {
            let fr2 = TryInto::<FloRealm>::try_into(flo.0)?;
            assert_eq!(fr, fr2);
        } else {
            return Err(anyhow::anyhow!("Didn't find message"));
        }
        Ok(())
    }

    // Verify that a cuckoo page is correctly stored and retrievable as a cuckoo page.
    #[test]
    fn store_cuckoos() -> anyhow::Result<()> {
        start_logging();
        let mut msg = Messages::new(
            DataStorageTemp::new_box(),
            DHTConfig::default(NodeID::rnd()),
        )
        .0;
        let fr = FloRealm::from_type(
            RealmID::rnd(),
            Condition::Pass,
            Realm::new(
                "root".into(),
                RealmConfig {
                    max_space: 10000,
                    max_flo_size: 1000,
                },
            ),
            &[],
        )?;
        msg.msg_dht_storage(DHTStorageIn::StoreFlo(fr.clone().into()));

        let signer = SignerEd25519::new();
        let fb_root =
            FloTesting::new_cuckoo(fr.realm_id(), "data", Cuckoo::Duration(100000), &signer);
        msg.msg_dht_storage(DHTStorageIn::StoreFlo(fb_root.clone().into()));
        let fb_cu = FloTesting::new_cuckoo(
            fr.realm_id(),
            "data2",
            Cuckoo::Parent(fb_root.flo_id()),
            &signer,
        );
        let ans = msg.msg_dht_storage(DHTStorageIn::StoreFlo(fb_cu.clone().into()));
        log::info!("{ans:?}");

        let ans = msg.msg_dht_storage(DHTStorageIn::ReadCuckooIDs(fb_root.global_id()));
        if let Some(InternOut::Storage(DHTStorageOut::CuckooIDs(_, cs))) = ans.get(0) {
            assert_eq!(Some(&fb_cu.flo_id()), cs.get(0));
        } else {
            assert!(false, "Answer should be CuckooIDs");
        }

        Ok(())
    }
}