P2P networking in Rust and Tokio---Part 2

Posted on July 21, 2017

At the end of the first Tokio article I promised to demonstrate a gossiping protocol. This (overdue) post keeps the promise. You can follow along using the code here.

Before going into the actual gossiping protocol. I must explain some architectural changes that are made since last time. Now the main Node struct is as follows.

#[derive(Clone)]
pub struct Node {
    inner: Rc<RefCell<NodeInner>>,
    pub timer: Timer,
}

This I believe is a common pattern in Rust, especially in Tokio, because we need a convenient way to make new references of NodeInner (i.e. inner.clone()) when using it inside closures. NodeInner has some import functionalities like broadcast(&self, m: String) and send_random(&self, m: Msg). But other than that, most of the logic is in Node.

With the new architecture in mind, it becomes quite easy to understand how gossiping works. We basically periodically select a random node and send our peer list to it with message type AddVec. Upon receiving the list, we basically start a new client for any node that we do not already know, and that’s it! The effect of this is that, if nodes are only partially connected initially (but nevertheless reachable), then eventually the nodes become fully connected.