Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Support hex encoded secret key for --node-key #7052

Merged
merged 3 commits into from
Sep 11, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 36 additions & 30 deletions client/cli/src/params/node_key_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use sc_network::config::NodeKeyConfig;
use sc_network::{config::identity::ed25519, config::NodeKeyConfig};
use sp_core::H256;
use std::{path::PathBuf, str::FromStr};
use structopt::StructOpt;
Expand Down Expand Up @@ -83,7 +83,7 @@ pub struct NodeKeyParams {
/// as follows:
///
/// `ed25519`:
/// The file must contain an unencoded 32 byte Ed25519 secret key.
/// The file must contain an unencoded 32 byte or hex encoded Ed25519 secret key.
///
/// If the file does not exist, it is created with a newly generated secret key of
/// the chosen type.
Expand All @@ -100,12 +100,11 @@ impl NodeKeyParams {
let secret = if let Some(node_key) = self.node_key.as_ref() {
parse_ed25519_secret(node_key)?
} else {
let path = self
.node_key_file
.clone()
.unwrap_or_else(|| net_config_dir.join(NODE_KEY_ED25519_FILE));

sc_network::config::Secret::File(path)
sc_network::config::Secret::File(
self.node_key_file
.clone()
.unwrap_or_else(|| net_config_dir.join(NODE_KEY_ED25519_FILE))
)
};

NodeKeyConfig::Ed25519(secret)
Expand All @@ -124,7 +123,7 @@ fn parse_ed25519_secret(hex: &str) -> error::Result<sc_network::config::Ed25519S
H256::from_str(&hex)
.map_err(invalid_node_key)
.and_then(|bytes| {
sc_network::config::identity::ed25519::SecretKey::from_bytes(bytes)
ed25519::SecretKey::from_bytes(bytes)
.map(sc_network::config::Secret::Input)
.map_err(invalid_node_key)
})
Expand All @@ -133,7 +132,8 @@ fn parse_ed25519_secret(hex: &str) -> error::Result<sc_network::config::Ed25519S
#[cfg(test)]
mod tests {
use super::*;
use sc_network::config::identity::ed25519;
use sc_network::config::identity::{ed25519, Keypair};
use std::fs;

#[test]
fn test_node_key_config_input() {
Expand Down Expand Up @@ -164,28 +164,34 @@ mod tests {

#[test]
fn test_node_key_config_file() {
fn secret_file(net_config_dir: &PathBuf) -> error::Result<()> {
NodeKeyType::variants().iter().try_for_each(|t| {
let node_key_type = NodeKeyType::from_str(t).unwrap();
let tmp = tempfile::Builder::new().prefix("alice").tempdir()?;
let file = tmp.path().join(format!("{}_mysecret", t)).to_path_buf();
let params = NodeKeyParams {
node_key_type,
node_key: None,
node_key_file: Some(file.clone()),
};
params.node_key(net_config_dir).and_then(|c| match c {
NodeKeyConfig::Ed25519(sc_network::config::Secret::File(ref f))
if node_key_type == NodeKeyType::Ed25519 && f == &file =>
{
Ok(())
}
_ => Err(error::Error::Input("Unexpected node key config".into())),
})
})
fn check_key(file: PathBuf, key: &ed25519::SecretKey) {
let params = NodeKeyParams {
node_key_type: NodeKeyType::Ed25519,
node_key: None,
node_key_file: Some(file),
};

let node_key = params.node_key(&PathBuf::from("not-used"))
.expect("Creates node key config")
.into_keypair()
.expect("Creates node key pair");

match node_key {
Keypair::Ed25519(ref pair)
if pair.secret().as_ref() == key.as_ref() => {}
_ => panic!("Invalid key"),
}
}

assert!(secret_file(&PathBuf::from_str("x").unwrap()).is_ok());
let tmp = tempfile::Builder::new().prefix("alice").tempdir().expect("Creates tempfile");
let file = tmp.path().join("mysecret").to_path_buf();
let key = ed25519::SecretKey::generate();

fs::write(&file, hex::encode(key.as_ref())).expect("Writes secret key");
check_key(file.clone(), &key);

fs::write(&file, &key).expect("Writes secret key");
check_key(file.clone(), &key);
}

#[test]
Expand Down
22 changes: 19 additions & 3 deletions client/network/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -625,10 +625,26 @@ impl NodeKeyConfig {
Ok(Keypair::Ed25519(k.into())),

Ed25519(Secret::File(f)) =>
get_secret(f,
|mut b| ed25519::SecretKey::from_bytes(&mut b),
get_secret(
f,
|mut b| {
match String::from_utf8(b.to_vec())
.ok()
.and_then(|s|{
if s.len() == 64 {
Copy link
Member Author

Choose a reason for hiding this comment

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

@tomaka Okay?

Copy link
Contributor

Choose a reason for hiding this comment

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

We can even go the extra mile and use hex::decode instead 🚀

sp_core::H256::from_str(&s).ok()
} else {
None
}}
)
{
Some(s) => ed25519::SecretKey::from_bytes(s),
_ => ed25519::SecretKey::from_bytes(&mut b),
}
},
ed25519::SecretKey::generate,
|b| b.as_ref().to_vec())
|b| b.as_ref().to_vec()
)
.map(ed25519::Keypair::from)
.map(Keypair::Ed25519),
}
Expand Down