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
use std::{
    collections::{HashMap, VecDeque},
    task::{Context, Poll},
};

use libp2p::{
    identify::{Identify, IdentifyConfig, IdentifyEvent},
    identity::PublicKey,
    kad::{
        record::Key, store::RecordStore, Kademlia, KademliaConfig, KademliaEvent, QueryId,
        QueryStats,
    },
    mdns::{Mdns, MdnsEvent},
    ping::{Ping, PingEvent},
    relay::Relay,
    swarm::{
        NetworkBehaviour, NetworkBehaviourAction, NetworkBehaviourEventProcess, PollParameters,
        Swarm,
    },
    Multiaddr, PeerId,
};

const GLYCOS_PROTOCOL_VERSION: &str = "/glycos/0.1.0";

mod control;
mod run;
mod storage;

use storage::GlycosRecordStore;

pub use run::{new, new_in_ram, new_in_ram_with_port, new_with_port, NodeBuilder, NodeFacade};

use crate::graph::{cryptograph, persist::PersistentGraph};

use self::storage::GlycosRecord;

pub type GlycosSwarm = Swarm<GlycosBehaviour>;

type GlycosNetworkBehaviourAction =
    NetworkBehaviourAction<GlycosEvent, <GlycosBehaviour as NetworkBehaviour>::ProtocolsHandler>;

#[derive(Debug)]
enum RunningQuery {
    PutVertex { id: QueryId },
    GetVertex { id: QueryId },
    PutEdge { id: QueryId },
}

#[derive(libp2p::NetworkBehaviour)]
#[behaviour(
    out_event = "GlycosEvent",
    poll_method = "poll_events",
    event_process = true
)]
pub struct GlycosBehaviour {
    kademlia: Kademlia<GlycosRecordStore>,
    identify: Identify,
    relay: Relay,
    ping: Ping,
    mdns: Mdns,

    #[behaviour(ignore)]
    in_flight: HashMap<QueryId, RunningQuery>,

    #[behaviour(ignore)]
    out_events: VecDeque<GlycosNetworkBehaviourAction>,
}

#[derive(Debug)]
pub struct VertexRetrievalOk {
    pub vertex: cryptograph::Vertex,
    pub edges: Vec<cryptograph::Edge>,
}

#[derive(Debug)]
pub enum GlycosQueryResult {
    VertexStored,
    EdgeStored,
    VertexRetrievalComplete {
        result: anyhow::Result<VertexRetrievalOk>,
    },
}

#[derive(Debug)]
pub enum GlycosEvent {
    OutboundQueryCompleted {
        id: QueryId,
        result: GlycosQueryResult,
        stats: QueryStats,
    },
    BootstrapResult {
        id: QueryId,
        result: Result<libp2p::kad::BootstrapOk, libp2p::kad::BootstrapError>,
        stats: QueryStats,
    },
}

impl GlycosBehaviour {
    fn poll_events(
        &mut self,
        _cx: &mut Context<'_>,
        _params: &mut impl PollParameters,
    ) -> Poll<GlycosNetworkBehaviourAction> {
        match self.out_events.pop_front() {
            Some(x) => Poll::Ready(x),
            None => Poll::Pending,
        }
    }
}

impl NetworkBehaviourEventProcess<PingEvent> for GlycosBehaviour {
    fn inject_event(&mut self, _event: PingEvent) {}
}

impl NetworkBehaviourEventProcess<()> for GlycosBehaviour {
    fn inject_event(&mut self, _event: ()) {}
}

impl NetworkBehaviourEventProcess<MdnsEvent> for GlycosBehaviour {
    fn inject_event(&mut self, event: MdnsEvent) {
        if let MdnsEvent::Discovered(addrs) = event {
            for (peer_id, addr) in addrs {
                self.kademlia.add_address(&peer_id, addr);
            }
        }
    }
}

impl NetworkBehaviourEventProcess<IdentifyEvent> for GlycosBehaviour {
    fn inject_event(&mut self, event: IdentifyEvent) {
        log::trace!("identify: {:?}", event);
        if let IdentifyEvent::Received {
            peer_id,
            info:
                libp2p::identify::IdentifyInfo {
                    listen_addrs,
                    observed_addr,
                    ..
                },
        } = event
        {
            log::debug!(
                "Identified node {} ({:?}) by {} (observed {}).",
                peer_id,
                listen_addrs,
                GLYCOS_PROTOCOL_VERSION,
                observed_addr
            );

            // Received identify
            for addr in listen_addrs {
                self.kademlia.add_address(&peer_id, addr);
            }
        }
    }
}

impl NetworkBehaviourEventProcess<KademliaEvent> for GlycosBehaviour {
    fn inject_event(&mut self, event: KademliaEvent) {
        use libp2p::kad::QueryResult;

        match event {
            KademliaEvent::OutboundQueryCompleted {
                id,
                result: QueryResult::Bootstrap(result),
                stats,
            } => {
                self.out_events
                    .push_back(NetworkBehaviourAction::GenerateEvent(
                        GlycosEvent::BootstrapResult { id, result, stats },
                    ));
            }
            KademliaEvent::OutboundQueryCompleted {
                id,
                result: result @ QueryResult::PutRecord(_),
                stats,
            } => {
                log::debug!("PutRecord result event {:?}", result);
                let event = match self.in_flight.remove(&id) {
                    Some(RunningQuery::PutEdge { .. }) => GlycosEvent::OutboundQueryCompleted {
                        id,
                        stats,
                        result: GlycosQueryResult::EdgeStored,
                    },
                    Some(RunningQuery::PutVertex { .. }) => GlycosEvent::OutboundQueryCompleted {
                        id,
                        stats,
                        result: GlycosQueryResult::VertexStored,
                    },
                    Some(RunningQuery::GetVertex { .. }) => {
                        log::warn!("PutRecord received for a GET request");
                        return;
                    }
                    None => {
                        log::warn!("PUT request without handler.");
                        return;
                    }
                };
                self.out_events
                    .push_back(GlycosNetworkBehaviourAction::GenerateEvent(event));
            }
            KademliaEvent::OutboundQueryCompleted {
                id,
                result: QueryResult::GetRecord(ref x),
                stats,
            } => {
                match (self.in_flight.remove(&id), x) {
                    (Some(RunningQuery::GetVertex { .. }), Ok(x)) => {
                        let records =
                            x.records
                                .iter()
                                .map(|x| {
                                    bincode::deserialize::<(
                                        cryptograph::Vertex,
                                        Vec<cryptograph::Edge>,
                                    )>(&x.record.value)
                                })
                                .filter_map(Result::ok)
                                .filter(|(vertex, edges)| {
                                    vertex.verify_signature()
                                        && edges.iter().all(|e| {
                                            e.verify_signature() && e.verify_is_subject(vertex)
                                        })
                                });
                        let record = records.max_by_key(|(v, _e)| v.clock);
                        // XXX more sanity checks: id should check out, signatures
                        // should be ok, then order by clock.
                        let result = match record {
                            Some(vertex) => {
                                log::debug!("GET ok: {:?}", vertex);
                                Ok(VertexRetrievalOk {
                                    vertex: vertex.0,
                                    edges: vertex.1,
                                })
                            }
                            None => Err(anyhow::format_err!("GET returned None")),
                        };
                        self.out_events
                            .push_back(GlycosNetworkBehaviourAction::GenerateEvent(
                                GlycosEvent::OutboundQueryCompleted {
                                    id,
                                    result: GlycosQueryResult::VertexRetrievalComplete { result },
                                    stats,
                                },
                            ));
                    }
                    (
                        Some(RunningQuery::PutVertex { .. } | RunningQuery::PutEdge { .. }),
                        Ok(_),
                    ) => {
                        log::warn!("GetRecord for PUT request");
                    }
                    (_, Err(e)) => {
                        log::warn!("GET error {:?}", e);
                    }
                    (None, _) => log::warn!("GET request without handler."),
                }
            }
            _ev => (),
        }
    }
}

impl GlycosBehaviour {
    pub fn new(
        kademlia: KademliaConfig,
        relay: Relay,
        local: PublicKey,
        storage: PersistentGraph,
        mdns: Mdns,
    ) -> Self {
        let local_peer_id = local.to_peer_id();
        let storage = GlycosRecordStore::new(storage, local_peer_id);
        let kademlia = Kademlia::with_config(local_peer_id, storage, kademlia);
        GlycosBehaviour {
            kademlia,
            identify: Identify::new(IdentifyConfig::new(
                GLYCOS_PROTOCOL_VERSION.to_string(),
                local,
            )),
            relay,
            ping: Ping::default(),
            mdns,

            in_flight: HashMap::new(),

            out_events: VecDeque::new(),
        }
    }

    pub fn bootstrap(&mut self) -> anyhow::Result<QueryId> {
        Ok(self.kademlia_mut().bootstrap()?)
    }

    pub fn add_address(&mut self, peer: PeerId, addrs: impl IntoIterator<Item = Multiaddr>) {
        for addr in addrs {
            self.kademlia.add_address(&peer, addr);
        }

        self.identify.push(std::iter::once(peer));
    }

    pub fn kademlia(&self) -> &Kademlia<impl for<'a> RecordStore<'a>> {
        &self.kademlia
    }

    pub fn kademlia_mut(&mut self) -> &mut Kademlia<impl for<'a> RecordStore<'a>> {
        &mut self.kademlia
    }

    pub fn store_vertex(&mut self, v: cryptograph::Vertex) -> anyhow::Result<QueryId> {
        let record = GlycosRecord::PutVertex(v).to_record();
        let id = self
            .kademlia
            .put_record(record, libp2p::kad::Quorum::Majority)
            .unwrap(); // XXX cannot convert to anyhow::Error.
        self.in_flight.insert(id, RunningQuery::PutVertex { id });
        Ok(id)
    }

    pub fn store_edge(&mut self, e: cryptograph::Edge) -> anyhow::Result<QueryId> {
        let record = GlycosRecord::PutEdge(e).to_record();
        let id = self
            .kademlia
            .put_record(record, libp2p::kad::Quorum::Majority)
            .unwrap();
        self.in_flight.insert(id, RunningQuery::PutEdge { id });
        Ok(id)
    }

    pub fn search_vertex(&mut self, key: &Key) -> anyhow::Result<QueryId> {
        let id = self.kademlia.get_record(key, libp2p::kad::Quorum::Majority);
        self.in_flight.insert(id, RunningQuery::GetVertex { id });
        Ok(id)
    }
}