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
//! [README](https://github.com/ip-v8/rust-ipv8/blob/develop/README.md)
#![deny(clippy::missing_docs_in_private_items)]
#[macro_use]
extern crate log;

pub mod error;
pub mod serialization;
pub mod util;

pub mod community;
pub mod configuration;
pub mod crypto;
pub mod networking;
pub mod payloads;

use configuration::Config;
use crate::networking::{NetworkSender, NetworkReceiver};
use std::error::Error;
use crate::community::CommunityRegistry;
use rayon::{ThreadPoolBuilder};
use std::sync::Once;

/// The IPv8 instance.
/// This struct is how you can interact with the network.
///
/// To create a new IPv8 instance with the default configuration do this:
/// ```
/// use rust_ipv8::IPv8;
/// use rust_ipv8::configuration::Config;
///
/// let ipv8 = IPv8::new(Config::default());
/// ```
pub struct IPv8 {
    /// Defines the config used forIPv8
    pub config: Config,
    /// The network receiver which forwards the packets to the correct communities
    pub network_receiver: NetworkReceiver,
    /// The sender used for sending packets over the network
    pub network_sender: NetworkSender,

    /// The registry containing all the communities
    pub communities: CommunityRegistry,
}

// To keep track if the threadpool is already started
#[doc(hidden)]
static THREADPOOL_START: Once = Once::new();

impl IPv8 {
    /// Creates a new instance of the ipv8 struct
    pub fn new(config: configuration::Config) -> Result<Self, Box<dyn Error>> {
        // Setup the global threadpool
        {
            let mut started = None;

            THREADPOOL_START.call_once(|| {
                started = Some(
                    ThreadPoolBuilder::new()
                        .num_threads(config.threadcount)
                        .build_global(),
                )
            });

            if let Some(s) = started {
                s?
            }
        }

        let network_receiver = NetworkReceiver::new(&config.receiving_address)?;
        let network_sender = NetworkSender::new(&config.sending_address)?;
        Ok(IPv8 {
            config,
            network_receiver,
            network_sender,
            communities: CommunityRegistry::default(),
        })
    }

    /// Starts ipv8 to actually listen for packets
    pub fn start(self) {
        self.network_receiver.start(&self.config);
    }
}