use crate::consensus::{
foundation_index, header_version,
};
use crate::core::{HeaderVersion, Output, TxKernel};
use crate::global::get_foundation_path;
use crate::keychain::Identifier;
use crate::serde::{Deserialize, Serialize};
use serde_json;
use std::fs::{create_dir, File};
use std::io::prelude::*;
use std::io::SeekFrom;
use std::path::Path;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CbData {
pub output: Output,
pub kernel: TxKernel,
pub key_id: Option<Identifier>,
}
pub const FOUNDATION_COINBASE_SIZE_1: usize = 1775;
pub fn serialize_foundation(foundation_coinbases: Vec<CbData>) -> String {
let mut result = String::new();
for f_cb in foundation_coinbases {
let serialized = serde_json::to_string(&f_cb).unwrap();
result.push_str(&serialized);
result.push_str("\n"); }
result
}
pub fn save_in_disk(serialization: String, path: &Path) {
let mut path = path.join("foundation");
if path.exists() == false {
create_dir(path.clone())
.expect(format!("Was not possible to create the file {:?}", path).as_str());
};
path = path.join("foundation.json");
println!("Saving the file as: {}", path.display());
let mut file = match File::create(&path) {
Err(why) => panic!("Couldn't create {}: {}", path.display(), why.to_string()),
Ok(file) => file,
};
file.write_all(serialization.as_bytes())
.expect("Couldn't save the serialization in the disk!")
}
fn get_foundation_tx_version_size(version: HeaderVersion) -> usize {
match version {
HeaderVersion(_) => FOUNDATION_COINBASE_SIZE_1,
}
}
fn get_foundation_tx_offset(index: u64, _version: HeaderVersion) -> u64 {
let size = index * (FOUNDATION_COINBASE_SIZE_1 as u64);
if cfg!(windows) {
size + index
} else {
size
}
}
pub fn load_foundation_output(height: u64) -> CbData {
let height_version = header_version(height);
let index_foundation = foundation_index(height);
let path_str = get_foundation_path()
.unwrap_or_else(|| panic!("No path to the foundation.json was provided!"));
let path = Path::new(&path_str);
let mut file = match File::open(&path) {
Err(why) => panic!(
"Error trying to read the foundation coinbase. Couldn't open the file {}: {}",
path.display(),
why.to_string()
),
Ok(file) => file,
};
let file_len = file.metadata().unwrap().len();
let offset = get_foundation_tx_offset(index_foundation, height_version);
if offset >= file_len {
panic!("Not implemented yet!");
};
let mut buffer = vec![0 as u8; get_foundation_tx_version_size(height_version)];
file.seek(SeekFrom::Start(offset)).unwrap();
file.read_exact(&mut buffer).unwrap();
let buffer_str = String::from_utf8(buffer).unwrap();
serde_json::from_str(&buffer_str).unwrap()
}