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
/*
    Appellation: mainnet
    Context: behaviours::ipfs
    Description:
        Implement the network behaviours that enables apps to connect to the ipfs mainnet

*/
use crate::KademliaMS;
use libp2p::{
    kad::{AddProviderOk, KademliaEvent, PeerRecord, PutRecordOk, QueryResult, Record},
    swarm::NetworkBehaviourEventProcess,
    NetworkBehaviour,
};
use std::str::from_utf8;

pub fn capture_kademlia_event(message: KademliaEvent) {
    match message {
        KademliaEvent::OutboundQueryCompleted { result, .. } => match result {
            QueryResult::GetProviders(Ok(ok)) => {
                for peer in ok.providers {
                    println!(
                        "Peer {:?} provides key {:?}",
                        peer,
                        from_utf8(ok.key.as_ref()).unwrap()
                    );
                }
            }
            QueryResult::GetProviders(Err(err)) => {
                eprintln!("Failed to get providers: {:?}", err);
            }
            QueryResult::GetRecord(Ok(ok)) => {
                for PeerRecord {
                    record: Record { key, value, .. },
                    ..
                } in ok.records
                {
                    println!(
                        "Got record {:?} {:?}",
                        from_utf8(key.as_ref()).unwrap(),
                        from_utf8(&value).unwrap()
                    );
                }
            }
            QueryResult::GetRecord(Err(err)) => {
                eprintln!("Failed to get record: {:?}", err);
            }
            QueryResult::PutRecord(Ok(PutRecordOk { key })) => {
                println!(
                    "Successfully put record {:?}",
                    from_utf8(key.as_ref()).unwrap()
                );
            }
            QueryResult::PutRecord(Err(err)) => {
                eprintln!("Failed to put record: {:?}", err);
            }
            QueryResult::StartProviding(Ok(AddProviderOk { key })) => {
                println!(
                    "Successfully put provider record {:?}",
                    from_utf8(key.as_ref()).unwrap()
                );
            }
            QueryResult::StartProviding(Err(err)) => {
                eprintln!("Failed to put provider record: {:?}", err);
            }
            _ => {}
        },
        _ => {}
    }
}

#[derive(NetworkBehaviour)]
#[behaviour(event_process = true)]
pub struct Mainnet {
    pub kademlia: KademliaMS,
}

impl NetworkBehaviourEventProcess<KademliaEvent> for Mainnet {
    fn inject_event(&mut self, message: KademliaEvent) {
        capture_kademlia_event(message)
    }
}