Skip to content

Commit

Permalink
to_file for FromShelleyFile types
Browse files Browse the repository at this point in the history
  • Loading branch information
iquerejeta authored and jpraynaud committed Sep 23, 2022
1 parent e54cbf1 commit da70046
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 10 deletions.
29 changes: 27 additions & 2 deletions mithril-common/src/crypto_helper/cardano/codec.rs
Expand Up @@ -3,6 +3,7 @@ use kes_summed_ed25519::kes::Sum6Kes;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::Write;
use std::path::Path;

/// Parse error
Expand All @@ -23,7 +24,11 @@ struct ShelleyFileFormat {
cbor_hex: String,
}

pub(crate) trait FromShelleyFile {
/// Trait that allows any structure that implements serialize to be formatted following
/// the Shelly json format.
pub(crate) trait FromShelleyFile: serde::Serialize {
const TYPE: &'static str;
const DESCRIPTION: &'static str;
fn from_file<R: DeserializeOwned, P: AsRef<Path>>(path: P) -> Result<R, ParseError> {
let data = fs::read_to_string(path).map_err(ParseError::Path)?;

Expand All @@ -35,6 +40,26 @@ pub(crate) trait FromShelleyFile {
let a: R = serde_cbor::from_slice(&hex_vector).map_err(|_| ParseError::CborData)?;
Ok(a)
}

fn to_file<P: AsRef<Path>>(&self, path: P) -> Result<(), ParseError> {
let cbor_string =
hex::encode(&serde_cbor::to_vec(&self).map_err(|_| ParseError::CborData)?);

let file_format = ShelleyFileFormat {
file_type: Self::TYPE.to_string(),
description: Self::DESCRIPTION.to_string(),
cbor_hex: cbor_string,
};

let mut file = fs::File::create(path).map_err(ParseError::Path)?;
let json_str = serde_json::to_string(&file_format).map_err(ParseError::JsonFormat)?;

write!(file, "{}", json_str).expect("Unable to write bytes to file");
Ok(())
}
}

impl FromShelleyFile for Sum6Kes {}
impl FromShelleyFile for Sum6Kes {
const TYPE: &'static str = "VrfSigningKey_PraosVRF";
const DESCRIPTION: &'static str = "VRF Signing Key";
}
Expand Up @@ -17,7 +17,7 @@ use blake2::{
Blake2b, Digest,
};
use kes_summed_ed25519::kes::{Sum6Kes, Sum6KesSig};
use kes_summed_ed25519::traits::{KesSig, KesSk};
use kes_summed_ed25519::traits::KesSk;
use rand_core::{CryptoRng, RngCore};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
Expand Down
29 changes: 25 additions & 4 deletions mithril-common/src/crypto_helper/cardano/opcert.rs
@@ -1,6 +1,6 @@
use super::FromShelleyFile;

use crate::crypto_helper::cardano::ProtocolRegistrationError;
use crate::crypto_helper::cardano::{ParseError, ProtocolRegistrationError};
use ed25519_dalek::{PublicKey as EdPublicKey, Signature as EdSignature, Verifier};
use kes_summed_ed25519::common::PublicKey as KesPublicKey;
use mithril::RegisterError;
Expand All @@ -20,7 +20,10 @@ struct RawFields(
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
struct RawOpCert(RawFields, EdPublicKey);

impl FromShelleyFile for RawOpCert {}
impl FromShelleyFile for RawOpCert {
const TYPE: &'static str = "NodeOperationalCertificate";
const DESCRIPTION: &'static str = "";
}

/// Parsed Operational Certificate
#[derive(Clone, Debug, PartialEq, Eq)]
Expand All @@ -34,7 +37,6 @@ pub struct OpCert {

impl OpCert {
/// Parse raw bytes into an Operational Certificate
/// todo: write also to_file()
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, RegisterError> {
let a: RawOpCert =
RawOpCert::from_file(path).map_err(|_| RegisterError::SerializationError)?;
Expand All @@ -50,6 +52,20 @@ impl OpCert {
})
}

/// Creates a file in the path provided with the OpCert
pub fn to_file<P: AsRef<Path>>(&self, path: P) -> Result<(), ParseError> {
let raw_cert = RawOpCert(
RawFields(
self.kes_vk.as_bytes().to_vec(),
self.issue_number,
self.start_kes_period,
self.cert_sig.to_bytes().to_vec(),
),
self.cold_vk,
);
raw_cert.to_file(path)
}

/// Validate a certificate
pub fn validate(&self) -> Result<(), ProtocolRegistrationError> {
let mut msg = [0u8; 48];
Expand All @@ -73,6 +89,11 @@ mod tests {
fn test_vector_op_cert() {
let cert = OpCert::from_file("./test-data/node1.cert").unwrap();

assert!(cert.validate().is_ok())
assert!(cert.validate().is_ok());

assert!(cert.to_file("./test-data/node_test.cert").is_ok());

let cert_test = OpCert::from_file("./test-data/node_test.cert").unwrap();
assert!(cert_test.validate().is_ok());
}
}
4 changes: 1 addition & 3 deletions mithril-common/src/crypto_helper/types.rs
@@ -1,6 +1,4 @@
use crate::crypto_helper::cardano::{
KeyRegWrapper, StmClerkWrapper, StmInitializerWrapper, StmSignerWrapper,
};
use crate::crypto_helper::cardano::{StmClerkWrapper, StmInitializerWrapper, StmSignerWrapper};

use mithril::key_reg::KeyReg;
use mithril::stm::{
Expand Down
1 change: 1 addition & 0 deletions mithril-common/test-data/node_test.cert
@@ -0,0 +1 @@
{"type":"NodeOperationalCertificate","description":"","cborHex":"82845820f89d3fa14cabafa151638743b297379d3c3767902e36ae53b02b3a64bddda19d00005840e472042f7e78e3cfc4c2ac99a658a626be0e9d69e7072dc300cb28ce8178c329beb1d2cf4c7a7ce30d6c528ffad9e8d685fd9d58379758924a010ef317290b0e58207acec462970b819f5f7951e5c84eb87c8e7c4f1aceac01e1c1d97f2e25eb6005"}

0 comments on commit da70046

Please sign in to comment.