tendermint_config/
priv_validator_key.rs

1//! Validator private keys
2
3use std::{fs, path::Path};
4
5use serde::{Deserialize, Serialize};
6use tendermint::{
7    account,
8    private_key::PrivateKey,
9    public_key::{PublicKey, TendermintKey},
10};
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        TendermintKey::new_consensus_key(result.priv_key.public_key())
35            .map_err(Error::tendermint)?;
36
37        Ok(result)
38    }
39
40    /// Load `node_key.json` from a file
41    pub fn load_json_file<P>(path: &P) -> Result<Self, Error>
42    where
43        P: AsRef<Path>,
44    {
45        let json_string = fs::read_to_string(path)
46            .map_err(|e| Error::file_io(format!("{}", path.as_ref().display()), e))?;
47
48        Self::parse_json(json_string)
49    }
50
51    /// Get the consensus public key for this validator private key
52    pub fn consensus_pubkey(&self) -> TendermintKey {
53        TendermintKey::new_consensus_key(self.priv_key.public_key()).unwrap()
54    }
55}