hbkr-rs 0.3.2

Hashblock Key Rotation
Documentation
//! HBKR Key Management

use crate::{
    basic::Basic,
    basicpre::BasicPrefix,
    key_config::{nxt_commitment, KeyConfig},
    said::SelfAddressing,
    threshold::SignatureThreshold,
    HBKResult,
};
use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};
use std::fmt::{self, Debug};

use thiserror::Error;

#[derive(Debug, Error)]
pub enum KsSignerError {
    #[error("keypair-pubkey mismatch")]
    KeypairPubkeyMismatch,
}

pub trait PubKey: Debug {
    fn as_base58_string(&self) -> String;
}
pub trait PrivKey: Debug {
    fn as_base58_string(&self) -> String;
}
pub trait KeySet: std::fmt::Debug {
    fn is_barren(&self) -> bool;
    fn from(&mut self, current_kps: Vec<String>, next_kps: Vec<String>);
    fn key_type(&self) -> Basic;
    fn current_private_keys(&self) -> Vec<Privatekey>;
    fn current_public_keys(&self) -> Vec<Publickey>;
    fn next_private_keys(&self) -> Vec<Privatekey>;
    fn next_public_keys(&self) -> Vec<Publickey>;
    fn rotate(&mut self, new_next: Option<Vec<Privatekey>>) -> (Vec<Privatekey>, Vec<Privatekey>);
}

#[derive(Clone, Default, Deserialize, Serialize, BorshDeserialize, BorshSerialize, PartialEq)]
pub struct Privatekey {
    p_key: Vec<u8>,
}
impl Privatekey {
    // pub fn from_bytes(data: [u8; 32]) -> Result<Self, KrError> {
    //     Ok(Self { p_key: data })
    // }
    pub fn new(data: Vec<u8>) -> Self {
        Self { p_key: data }
    }
    pub fn to_bytes(&self) -> Vec<u8> {
        self.p_key.clone()
    }
    pub fn key(&self) -> Vec<u8> {
        self.to_bytes()
    }
}

impl PrivKey for Privatekey {
    fn as_base58_string(&self) -> String {
        // let mut d = vec![0u8; 32];
        // let mut index = 0;
        // for b in &self.p_key {
        //     d[index] = *b;
        //     index += 1;
        // }
        bs58::encode(&self.p_key).into_string()
    }
}

impl From<String> for Privatekey {
    fn from(data: String) -> Self {
        Self {
            p_key: bs58::decode(data).into_vec().unwrap(),
        }
    }
}

impl From<Vec<u8>> for Privatekey {
    fn from(data: Vec<u8>) -> Self {
        Self { p_key: data }
    }
}

/// For debugging but we need to get to the 64 bytes?
impl fmt::Debug for Privatekey {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", bs58::encode(self.as_base58_string()).into_string())?;
        Ok(())
    }
}

#[derive(Clone, Default, Deserialize, Serialize, BorshDeserialize, BorshSerialize, PartialEq)]
pub struct Publickey {
    p_key: Vec<u8>,
}

impl Publickey {
    // pub fn from_bytes(data: [u8; 32]) -> Result<Self, KrError> {
    //     Ok(Self { p_key: data })
    // }
    pub fn new(data: Vec<u8>) -> Self {
        Self { p_key: data }
    }
    pub fn to_bytes(&self) -> Vec<u8> {
        self.p_key.clone()
    }
    pub fn key(&self) -> Vec<u8> {
        self.to_bytes()
    }
}

impl PubKey for Publickey {
    fn as_base58_string(&self) -> String {
        // let mut d = vec![0u8; 32];
        // let mut index = 0;
        // for b in &self.p_key {
        //     d[index] = *b;
        //     index += 1;
        // }
        bs58::encode(&&self.p_key).into_string()
    }
}

/// For debugging but we need to get to the 64 bytes?
impl fmt::Debug for Publickey {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", bs58::encode(self.as_base58_string()).into_string())?;
        Ok(())
    }
}

impl From<Vec<u8>> for Publickey {
    fn from(data: Vec<u8>) -> Self {
        Self { p_key: data }
    }
}

pub fn key_vec_to_prefix_vec(in_keys: &Vec<Publickey>, keytype: Basic) -> Vec<BasicPrefix> {
    in_keys
        .iter()
        .map(|x| BasicPrefix::new(keytype, x.clone()))
        .collect::<Vec<BasicPrefix>>()
}

pub fn keys_to_config(
    active_keys: &Vec<Publickey>,
    next_keys: &Vec<Publickey>,
    keytype: Basic,
    threshold: u64,
    self_addressing: SelfAddressing,
) -> HBKResult<KeyConfig> {
    // Wrap the array of active_keys to BasicPrefix types
    // Build the first set of BasicPrefixes
    let basic_keys = key_vec_to_prefix_vec(active_keys, keytype);

    // Wrap the array of next_keys to BasicPrefix
    // Build next set of BasicPrefixes
    let next_basic_keys = key_vec_to_prefix_vec(next_keys, keytype);

    // Hash the rotation set
    let next_key_hash = nxt_commitment(
        &SignatureThreshold::Simple(threshold),
        &next_basic_keys,
        &self_addressing,
    );

    // Setup the key config
    Ok(KeyConfig::new(
        basic_keys.to_vec(),
        Some(next_key_hash),
        Some(SignatureThreshold::Simple(threshold)),
    ))
}