Files
Alfis/src/block.rs
T

76 lines
2.2 KiB
Rust
Raw Normal View History

2019-12-01 22:45:25 +01:00
extern crate serde;
extern crate serde_json;
extern crate num_bigint;
extern crate num_traits;
use super::*;
use std::fmt::Debug;
use chrono::Utc;
2019-12-01 22:45:25 +01:00
use serde::{Serialize, Deserialize};
use num_bigint::BigUint;
use num_traits::One;
use crypto::sha2::Sha256;
2019-12-01 22:45:25 +01:00
use crypto::digest::Digest;
use crate::keys::Bytes;
2019-12-01 22:45:25 +01:00
#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct Block {
pub index: u64,
pub timestamp: i64,
pub chain_name: String,
pub version_flags: u32,
2019-12-01 22:45:25 +01:00
pub difficulty: usize,
pub random: u32,
pub nonce: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub transaction: Option<Transaction>,
#[serde(default, skip_serializing_if = "Bytes::is_zero")]
pub prev_block_hash: Bytes,
#[serde(default, skip_serializing_if = "Bytes::is_zero")]
pub hash: Bytes,
2019-12-01 22:45:25 +01:00
}
impl Block {
pub fn new(index: u64, timestamp: i64, chain_name: &str, version_flags: u32, prev_block_hash: Bytes, transaction: Option<Transaction>) -> Self {
2019-12-01 22:45:25 +01:00
Block {
index,
timestamp,
chain_name: chain_name.to_owned(),
version_flags,
2021-01-14 18:34:43 +01:00
// TODO make difficulty parameter
difficulty: 20,
2019-12-01 22:45:25 +01:00
random: 0,
nonce: 0,
transaction,
prev_block_hash,
hash: Bytes::default(),
2019-12-01 22:45:25 +01:00
}
}
pub fn from_all_params(index: u64, timestamp: i64, chain_name: &str, version_flags: u32, difficulty: usize, random: u32, nonce: u64, prev_block_hash: Bytes, hash: Bytes, transaction: Option<Transaction>) -> Self {
Block {
index,
timestamp,
chain_name: chain_name.to_owned(),
version_flags,
difficulty,
random,
nonce,
transaction,
prev_block_hash,
hash,
}
}
pub fn hash(data: &[u8]) -> Bytes {
let mut buf: [u8; 32] = [0; 32];
let mut digest = Sha256::new();
2019-12-01 22:45:25 +01:00
digest.input(data);
digest.result(&mut buf);
Bytes::new(buf.to_vec())
2019-12-01 22:45:25 +01:00
}
pub fn is_genesis(&self) -> bool {
self.index == 0 && self.transaction.is_none() && self.prev_block_hash == Bytes::default()
2019-12-01 22:45:25 +01:00
}
}