Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swarm Bootstrap Nodes #201

Merged
merged 11 commits into from
Aug 15, 2023
1 change: 1 addition & 0 deletions homestar-runtime/fixtures/settings.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ process_collector_interval = 10
[node.network]
events_buffer_len = 1000
websocket_port = 9999
trusted_node_addresses = ["/ip4/127.0.0.1/tcp/9998/ws"]
mriise marked this conversation as resolved.
Show resolved Hide resolved
7 changes: 6 additions & 1 deletion homestar-runtime/src/event_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ use crate::{
use anyhow::Result;
use async_trait::async_trait;
use fnv::FnvHashMap;
use libp2p::{futures::StreamExt, kad::QueryId, request_response::RequestId, swarm::Swarm};
use libp2p::{
core::ConnectedPoint, futures::StreamExt, kad::QueryId, request_response::RequestId,
swarm::Swarm, PeerId,
};
use std::{sync::Arc, time::Duration};
use swarm_event::ResponseEvent;
use tokio::{select, sync::mpsc};
Expand Down Expand Up @@ -47,6 +50,7 @@ pub(crate) struct EventHandler<DB: Database> {
sender: Arc<mpsc::Sender<Event>>,
receiver: mpsc::Receiver<Event>,
query_senders: FnvHashMap<QueryId, (RequestResponseKey, P2PSender)>,
connected_peers: FnvHashMap<PeerId, ConnectedPoint>,
mriise marked this conversation as resolved.
Show resolved Hide resolved
request_response_senders: FnvHashMap<RequestId, (RequestResponseKey, P2PSender)>,
}

Expand All @@ -70,6 +74,7 @@ where
sender: Arc::new(sender),
receiver,
query_senders: FnvHashMap::default(),
connected_peers: FnvHashMap::default(),
request_response_senders: FnvHashMap::default(),
}
}
Expand Down
12 changes: 12 additions & 0 deletions homestar-runtime/src/event_handler/swarm_event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ async fn handle_swarm_event<THandlerErr: fmt::Debug + Send, DB: Database>(
event_handler: &mut EventHandler<DB>,
) {
match event {
// TODO: add identify for adding compatable kademlia nodes.
// TODO: use kademlia to discover new gossip nodes.
zeeshanlakhani marked this conversation as resolved.
Show resolved Hide resolved
SwarmEvent::Behaviour(ComposedEvent::Gossipsub(gossip_event)) => match *gossip_event {
gossipsub::Event::Message {
message,
Expand Down Expand Up @@ -368,6 +370,16 @@ async fn handle_swarm_event<THandlerErr: fmt::Debug + Send, DB: Database>(
);
}
SwarmEvent::IncomingConnection { .. } => {}
SwarmEvent::ConnectionEstablished {
peer_id, endpoint, ..
} => {
// add peer to connected peers list
event_handler.connected_peers.insert(peer_id, endpoint);
mriise marked this conversation as resolved.
Show resolved Hide resolved
}
SwarmEvent::ConnectionClosed { peer_id, cause, .. } => {
info!("peer connection closed {peer_id}, cause: {cause:?}");
event_handler.connected_peers.remove_entry(&peer_id);
zeeshanlakhani marked this conversation as resolved.
Show resolved Hide resolved
}
_ => {}
}
}
Expand Down
44 changes: 40 additions & 4 deletions homestar-runtime/src/network/swarm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@ use libp2p::{
core::upgrade,
gossipsub::{self, MessageId, SubscriptionError, TopicHash},
kad::{record::store::MemoryStore, Kademlia, KademliaEvent},
mdns, noise,
mdns,
multiaddr::Protocol,
noise,
request_response::{self, ProtocolSupport},
swarm::{NetworkBehaviour, Swarm, SwarmBuilder},
tcp, yamux, StreamProtocol, Transport,
};
use serde::{Deserialize, Serialize};
use std::fmt;
use tracing::{info, warn};

/// Build a new [Swarm] with a given transport and a tokio executor.
pub(crate) async fn new(settings: &settings::Node) -> Result<Swarm<ComposedBehaviour>> {
Expand All @@ -27,6 +30,7 @@ pub(crate) async fn new(settings: &settings::Node) -> Result<Swarm<ComposedBehav
.with_context(|| "Failed to generate/import keypair for libp2p".to_string())?;

let peer_id = keypair.public().to_peer_id();
info!(peer_id=?peer_id.to_string(), "local peer ID generated");

let transport = tcp::tokio::Transport::new(tcp::Config::default().nodelay(true))
.upgrade(upgrade::Version::V1Lazy)
Expand All @@ -53,15 +57,47 @@ pub(crate) async fn new(settings: &settings::Node) -> Result<Swarm<ComposedBehav
)
.build();

startup(&mut swarm, &settings.network)?;

Ok(swarm)
}

fn startup(swarm: &mut Swarm<ComposedBehaviour>, settings: &settings::Network) -> Result<()> {
mriise marked this conversation as resolved.
Show resolved Hide resolved
// Listen-on given address
swarm.listen_on(settings.network.listen_address.to_string().parse()?)?;
swarm.listen_on(settings.listen_address.to_string().parse()?)?;

// Dial trusted nodes specified in settings. Failure here shouldn't halt node startup.
for trusted_addr in &settings.trusted_node_addresses {
swarm
.dial(trusted_addr.clone())
.map(|_| {
info!(trusted_address=?trusted_addr, "Successfully dialed configured trusted node")
})
// log dial failure and continue
.map_err(|e| warn!(err=?e, "Failed to dial trusted node"))
.ok();

// add node to kademlia routing table
if let Some(peer_id) = trusted_addr.into_iter().find_map(|proto| match proto {
Protocol::P2p(peer_id) => Some(peer_id),
_ => None,
}) {
info!(trusted_address=?trusted_addr, "added configured trusted node to kademlia routing table");
swarm
.behaviour_mut()
.kademlia
.add_address(&peer_id, trusted_addr.clone());
} else {
warn!(trusted_address=?trusted_addr, "trusted node address did not include a peer ID. not added to kademlia routing table")
}
}

// subscribe to `receipts` topic
// join `receipts` topic
swarm
.behaviour_mut()
.gossip_subscribe(pubsub::RECEIPTS_TOPIC)?;

Ok(swarm)
Ok(())
}

/// Key data structure for [request_response::Event] messages.
Expand Down
9 changes: 7 additions & 2 deletions homestar-runtime/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,9 @@ pub struct Network {
pub(crate) workflow_quorum: usize,
/// Pubkey setup configuration
pub(crate) keypair_config: PubkeyConfig,
/// Multiaddrs of the trusted nodes to connect to on startup. These addresses are added as explicit peers for gossipsub.
#[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
pub(crate) trusted_node_addresses: Vec<libp2p::Multiaddr>,
}

/// Database-related settings for a homestar node.
Expand Down Expand Up @@ -161,6 +164,7 @@ impl Default for Network {
websocket_capacity: 100,
workflow_quorum: 3,
keypair_config: PubkeyConfig::Random,
trusted_node_addresses: Vec::new(),
}
}
}
Expand Down Expand Up @@ -254,8 +258,9 @@ mod test {
default_modded_settings.network.websocket_port = 9999;
default_modded_settings.gc_interval = Duration::from_secs(1800);
default_modded_settings.shutdown_timeout = Duration::from_secs(20);

assert_eq!(settings.node, default_modded_settings);
default_modded_settings.network.trusted_node_addresses =
vec!["/ip4/127.0.0.1/tcp/9998/ws".to_string().try_into().unwrap()];
assert_eq!(settings.node(), &default_modded_settings);
}

#[test]
Expand Down
11 changes: 11 additions & 0 deletions homestar-runtime/tests/test_node1/config/settings.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[monitoring]
process_collector_interval = 10

[node]

[node.network]
websocket_port = 9090
trusted_node_addresses = ["/ip4/127.0.0.1/tcp/9091/ws"]

[node.network.keypair_config]
existing = { key_type = "ed25519", path = "../../fixtures/__testkey_ed25519.pem" }
10 changes: 10 additions & 0 deletions homestar-runtime/tests/test_node2/config/settings.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[monitoring]
process_collector_interval = 10

[node]

[node.network]
websocket_port = 9091
trusted_node_addresses = [
"/ip4/127.0.0.1/tcp/9090/ws/p2p/12D3KooWDpJ7As7BWAwRMfu1VU2WCqNjvq387JEYKDBj4kx6nXTN",
]
Loading