Skip to content

Commit

Permalink
Use CometBFT-compatible format for priv_validator_key.json file
Browse files Browse the repository at this point in the history
  • Loading branch information
romac committed Jun 4, 2024
1 parent d76bac2 commit 3523f70
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 20 deletions.
4 changes: 3 additions & 1 deletion code/cli/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use malachite_node::config::Config;
use malachite_test::{PrivateKey, ValidatorSet};

use crate::logging::DebugSection;
use crate::priv_key::PrivValidatorKey;

const APP_FOLDER: &str = ".malachite";
const CONFIG_FILE: &str = "config.toml";
Expand Down Expand Up @@ -127,7 +128,8 @@ impl Args {
pub fn load_private_key(&self) -> Result<PrivateKey> {
let priv_key_file = self.get_priv_validator_key_file_path()?;
info!("Loading private key from {:?}", priv_key_file.display());
load_json_file(&priv_key_file)
let priv_validator_key: PrivValidatorKey = load_json_file(&priv_key_file)?;
Ok(priv_validator_key.private_key)
}
}

Expand Down
20 changes: 11 additions & 9 deletions code/cli/src/cmd/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,28 @@ use color_eyre::eyre::{eyre, Context, Result};
use tracing::{info, warn};

use malachite_node::config::Config;
use malachite_test::PrivateKey;
use malachite_test::ValidatorSet as Genesis;

use crate::cmd::testnet::{generate_config, generate_genesis, generate_private_keys};
use crate::priv_key::PrivValidatorKey;

/// Execute the init command
pub fn run(config_file: &Path, genesis_file: &Path, priv_validator_key_file: &Path) -> Result<()> {
// Save default configuration
if config_file.exists() {
warn!(
"Configuration file already exists at {:?}, skipping.",
"Configuration file already exists at {:?}, skipping",
config_file.display()
)
} else {
info!("Saving configuration to {:?}.", config_file);
info!("Saving configuration to {:?}", config_file);
save_config(config_file, &generate_config(0, 1))?;
}

// Save default genesis
if genesis_file.exists() {
warn!(
"Genesis file already exists at {:?}, skipping.",
"Genesis file already exists at {:?}, skipping",
genesis_file.display()
)
} else {
Expand All @@ -42,12 +42,14 @@ pub fn run(config_file: &Path, genesis_file: &Path, priv_validator_key_file: &Pa
// Save default priv_validator_key
if priv_validator_key_file.exists() {
warn!(
"Private key file already exists at {:?}, skipping.",
"Private key file already exists at {:?}, skipping",
priv_validator_key_file.display()
)
} else {
info!("Saving private key to {:?}.", priv_validator_key_file);
save_priv_validator_key(priv_validator_key_file, &generate_private_keys(1, false)[0])?;
info!("Saving private key to {:?}", priv_validator_key_file);
let private_keys = generate_private_keys(1, false);
let priv_validator_key = PrivValidatorKey::from(private_keys[0].clone());
save_priv_validator_key(priv_validator_key_file, &priv_validator_key)?;
}

Ok(())
Expand All @@ -66,11 +68,11 @@ pub fn save_genesis(genesis_file: &Path, genesis: &Genesis) -> Result<()> {
/// Save private_key validator key to file
pub fn save_priv_validator_key(
priv_validator_key_file: &Path,
private_key: &PrivateKey,
priv_validator_key: &PrivValidatorKey,
) -> Result<()> {
save(
priv_validator_key_file,
&serde_json::to_string(private_key)?,
&serde_json::to_string_pretty(priv_validator_key)?,
)
}

Expand Down
7 changes: 6 additions & 1 deletion code/cli/src/cmd/testnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use malachite_test::{PrivateKey, PublicKey, Validator};

use crate::args::Args;
use crate::cmd::init::{save_config, save_genesis, save_priv_validator_key};
use crate::priv_key::PrivValidatorKey;

const MIN_VOTING_POWER: u64 = 8;
const MAX_VOTING_POWER: u64 = 15;
Expand All @@ -38,7 +39,11 @@ pub fn run(home_dir: &Path, nodes: usize, deterministic: bool) -> Result<()> {
args.home = Some(node_home_dir);

// Save private key
save_priv_validator_key(&args.get_priv_validator_key_file_path()?, private_key)?;
let priv_validator_key = PrivValidatorKey::from(private_key.clone());
save_priv_validator_key(
&args.get_priv_validator_key_file_path()?,
&priv_validator_key,
)?;

// Save genesis
save_genesis(&args.get_genesis_file_path()?, &genesis)?;
Expand Down
8 changes: 2 additions & 6 deletions code/cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use color_eyre::eyre::Result;
use rand::rngs::OsRng;
use tracing::debug;

use malachite_node::config::Config;
Expand All @@ -11,6 +10,7 @@ use crate::logging::LogLevel;
mod args;
mod cmd;
mod logging;
mod priv_key;

#[tokio::main(flavor = "current_thread")]
pub async fn main() -> Result<()> {
Expand All @@ -37,11 +37,7 @@ fn init(args: &Args) -> Result<()> {

async fn start(args: &Args) -> Result<()> {
let cfg: Config = args.load_config()?;

let sk: PrivateKey = args
.load_private_key()
.unwrap_or_else(|_| PrivateKey::generate(OsRng));

let sk: PrivateKey = args.load_private_key()?;
let vs: ValidatorSet = args.load_genesis()?;

cmd::start::run(sk, cfg, vs).await
Expand Down
23 changes: 23 additions & 0 deletions code/cli/src/priv_key.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use serde::{Deserialize, Serialize};

use malachite_test::{Address, PrivateKey, PublicKey};

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PrivValidatorKey {
pub address: Address,
pub public_key: PublicKey,
pub private_key: PrivateKey,
}

impl From<PrivateKey> for PrivValidatorKey {
fn from(private_key: PrivateKey) -> Self {
let public_key = private_key.public_key();
let address = Address::from_public_key(&public_key);

Self {
address,
public_key,
private_key,
}
}
}
35 changes: 34 additions & 1 deletion code/test/src/serialization.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/// Serde Ed25519 VerificationKey CometBFT serializer/deserializer.
pub mod verificationkey {
pub mod verification_key {
use ed25519_consensus::VerificationKey;
use serde::{Deserialize, Serialize, Serializer};

Expand Down Expand Up @@ -31,6 +31,39 @@ pub mod verificationkey {
}
}

/// Serde Ed25519 SigningKey CometBFT serializer/deserializer.
pub mod signing_key {
use ed25519_consensus::SigningKey;
use serde::{Deserialize, Serialize, Serializer};

#[derive(Serialize, Deserialize)]
struct PrivKey {
#[serde(rename = "type")]
key_type: String,
#[serde(with = "crate::serialization::base64string")]
value: Vec<u8>,
}

pub fn serialize<S>(s: &SigningKey, ser: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
PrivKey {
key_type: "tendermint/PrivKeyEd25519".to_string(),
value: s.as_bytes().to_vec(),
}
.serialize(ser)
}

pub fn deserialize<'de, D>(de: D) -> Result<SigningKey, D::Error>
where
D: serde::Deserializer<'de>,
{
let pk = PrivKey::deserialize(de)?;
SigningKey::try_from(pk.value.as_slice()).map_err(serde::de::Error::custom)
}
}

/// Serialize/deserialize between base64-encoded String and Vec<u8>
pub mod base64string {
use base64::prelude::BASE64_STANDARD;
Expand Down
6 changes: 4 additions & 2 deletions code/test/src/signing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ impl SigningScheme for Ed25519 {

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PrivateKey(ed25519_consensus::SigningKey);
pub struct PrivateKey(
#[serde(with = "crate::serialization::signing_key")] ed25519_consensus::SigningKey,
);

impl PrivateKey {
#[cfg_attr(coverage_nightly, coverage(off))]
Expand Down Expand Up @@ -83,7 +85,7 @@ impl Keypair for PrivateKey {
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PublicKey(
#[serde(with = "crate::serialization::verificationkey")] ed25519_consensus::VerificationKey,
#[serde(with = "crate::serialization::verification_key")] ed25519_consensus::VerificationKey,
);

impl PublicKey {
Expand Down

0 comments on commit 3523f70

Please sign in to comment.