Skip to content

Feature request allow me to initialize the p2p private key file with new flag #7181 #7191

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

Open
wants to merge 12 commits into
base: unstable
Choose a base branch
from
1 change: 1 addition & 0 deletions beacon_node/lighthouse_network/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ tracing-subscriber = { workspace = true }
types = { workspace = true }
unsigned-varint = { version = "0.8", features = ["codec"] }
unused_port = { workspace = true }
clap = { version = "4", features = ["derive"] }
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Un-intended change?


[dependencies.libp2p]
version = "0.55"
Expand Down
8 changes: 6 additions & 2 deletions beacon_node/lighthouse_network/src/service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ use types::{
};
use types::{ChainSpec, ForkName};
use utils::{build_transport, strip_peer_id, Context as ServiceContext};
use clap::ArgMatches;
use super::utils;
use crate::NetworkConfig;

pub mod api_types;
mod gossip_cache;
Expand Down Expand Up @@ -178,8 +181,9 @@ impl<E: EthSpec> Network<E> {
let config = ctx.config.clone();
trace!("Libp2p Service starting");
// initialise the node's ID
let local_keypair = utils::load_private_key(&config);

pub fn initialize_network(config: NetworkConfig, cli_args: &ArgMatches) {
let local_keypair = utils::load_private_key(&config, cli_args);
}
Comment on lines +184 to +186
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems out of place, you don't have access to cli_args here. You should pass CLI data through the network config

// Trusted peers will also be marked as explicit in GossipSub.
// Cfr. https://github.com/libp2p/specs/blob/master/pubsub/gossipsub/gossipsub-v1.1.md#explicit-peering-agreements
let trusted_peers: Vec<PeerId> = config
Expand Down
53 changes: 21 additions & 32 deletions beacon_node/lighthouse_network/src/service/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ use tracing::{debug, warn};
use types::{
ChainSpec, DataColumnSubnetId, EnrForkId, EthSpec, ForkContext, SubnetId, SyncSubnetId,
};
use clap::ArgMatches;
use tracing::{error, debug, info}
use std::path::PathBuf;
use std::fs;

pub const NETWORK_KEY_FILENAME: &str = "key";
/// The filename to store our local metadata.
Expand Down Expand Up @@ -107,43 +111,28 @@ fn keypair_from_bytes(mut bytes: Vec<u8>) -> Result<Keypair, String> {
/// generated and is then saved to disk.
///
/// Currently only secp256k1 keys are allowed, as these are the only keys supported by discv5.
pub fn load_private_key(config: &NetworkConfig) -> Keypair {
// check for key from disk
let network_key_f = config.network_dir.join(NETWORK_KEY_FILENAME);
if let Ok(mut network_key_file) = File::open(network_key_f.clone()) {
let mut key_bytes: Vec<u8> = Vec::with_capacity(36);
match network_key_file.read_to_end(&mut key_bytes) {
Err(_) => debug!("Could not read network key file"),
Ok(_) => {
// only accept secp256k1 keys for now
if let Ok(secret_key) = secp256k1::SecretKey::try_from_bytes(&mut key_bytes) {
let kp: secp256k1::Keypair = secret_key.into();
debug!("Loaded network key from disk.");
return kp.into();
} else {
debug!("Network key file is not a valid secp256k1 key");

pub fn load_private_key(config: &NetworkConfig, cli_args: &ArgMatches) -> Keypair {
if let Some(custom_key_path) = cli_args.get_one::<String>("p2p-priv-key") {
let path = PathBuf::from(custom_key_path);
match fs::read_to_string(&path) {
Ok(key_hex) => match keypair_from_hex(key_hex.trim()) {
Ok(keypair) => {
debug!("Loaded custom p2p key from file: {:?}", path);
return keypair;
}
Err(e) => {
error!("Failed to decode custom p2p key from hex: {}", e);
}
},
Err(e) => {
error!("Failed to read custom p2p key file {:?}: {}", path, e);
}
}
}

// if a key could not be loaded from disk, generate a new one and save it
let local_private_key = secp256k1::Keypair::generate();
let _ = std::fs::create_dir_all(&config.network_dir);
match File::create(network_key_f.clone())
.and_then(|mut f| f.write_all(&local_private_key.secret().to_bytes()))
{
Ok(_) => {
debug!("New network key generated and written to disk");
}
Err(e) => {
warn!(
"Could not write node key to file: {:?}. error: {}",
network_key_f, e
);
}
}
local_private_key.into()
let key_path = config.network_dir.join("key");
load_or_create_keypair(key_path)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like the implementation of load_or_create_keypair might be missing—did you forget to include it?"

}

/// Generate authenticated XX Noise config from identity keys
Expand Down
7 changes: 6 additions & 1 deletion boot_node/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ use std::net::{SocketAddrV4, SocketAddrV6};
use std::time::Duration;
use std::{marker::PhantomData, path::PathBuf};
use types::EthSpec;
use clap::ArgMatches;
use crate::utils;

/// A set of configuration parameters for the bootnode, established from CLI arguments.
pub struct BootNodeConfig<E: EthSpec> {
Expand Down Expand Up @@ -83,7 +85,10 @@ impl<E: EthSpec> BootNodeConfig<E> {
network_config.discv5_config.enr_update = false;
}

let private_key = load_private_key(&network_config);
pub fn initialize_network(config: NetworkConfig, cli_args: &ArgMatches) {
let local_keypair = utils::load_private_key(&config, cli_args);
}

let local_key = CombinedKey::from_libp2p(private_key)?;

let local_enr = if let Some(dir) = matches.get_one::<String>("network-dir") {
Expand Down
6 changes: 6 additions & 0 deletions lighthouse/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,12 @@ fn main() {
exit(1)
}
}

let cli_args = cli::parse_args();
let config = NetworkConfig::default();

// pass `cli_args` explicitly into initialize_network
network::initialize_network(config, &cli_args)
}

fn run<E: EthSpec>(
Expand Down