cometbft_config/
priv_validator_key.rs

1//! Validator private keys
2
3use std::{fs, path::Path};
4
5use cometbft::{
6    account,
7    private_key::PrivateKey,
8    public_key::{CometbftKey, PublicKey},
9};
10use serde::{Deserialize, Serialize};
11
12use crate::{error::Error, prelude::*};
13
14/// Validator private key
15#[derive(Serialize, Deserialize)] // JSON custom serialization for priv_validator_key.json
16pub struct PrivValidatorKey {
17    /// Address
18    pub address: account::Id,
19
20    /// Public key
21    pub pub_key: PublicKey,
22
23    /// Private key
24    pub priv_key: PrivateKey,
25}
26
27impl PrivValidatorKey {
28    /// Parse `priv_validator_key.json`
29    pub fn parse_json<T: AsRef<str>>(json_string: T) -> Result<Self, Error> {
30        let result =
31            serde_json::from_str::<Self>(json_string.as_ref()).map_err(Error::serde_json)?;
32
33        // Validate that the parsed key type is usable as a consensus key
34        CometbftKey::new_consensus_key(result.priv_key.public_key()).map_err(Error::cometbft)?;
35
36        Ok(result)
37    }
38
39    /// Load `node_key.json` from a file
40    pub fn load_json_file<P>(path: &P) -> Result<Self, Error>
41    where
42        P: AsRef<Path>,
43    {
44        let json_string = fs::read_to_string(path)
45            .map_err(|e| Error::file_io(format!("{}", path.as_ref().display()), e))?;
46
47        Self::parse_json(json_string)
48    }
49
50    /// Get the consensus public key for this validator private key
51    pub fn consensus_pubkey(&self) -> CometbftKey {
52        CometbftKey::new_consensus_key(self.priv_key.public_key()).unwrap()
53    }
54}