2023-04-14 00:35:55 +00:00
|
|
|
use std::{io, collections::HashMap};
|
2023-04-11 17:42:18 +00:00
|
|
|
|
|
|
|
use thiserror::Error;
|
|
|
|
|
|
|
|
use blake2::{Digest, Blake2s256};
|
|
|
|
|
|
|
|
use ciphersuite::{Ciphersuite, Ristretto};
|
|
|
|
|
|
|
|
#[derive(Clone, PartialEq, Eq, Debug, Error)]
|
|
|
|
pub enum BlockError {
|
2023-04-14 00:35:55 +00:00
|
|
|
/// Block was too large.
|
|
|
|
#[error("block exceeded size limit")]
|
|
|
|
TooLargeBlock,
|
2023-04-11 17:42:18 +00:00
|
|
|
/// Header specified a parent which wasn't the chain tip.
|
|
|
|
#[error("header doesn't build off the chain tip")]
|
|
|
|
InvalidParent,
|
|
|
|
/// Header specified an invalid transactions merkle tree hash.
|
|
|
|
#[error("header transactions hash is incorrect")]
|
|
|
|
InvalidTransactions,
|
2023-04-14 00:35:55 +00:00
|
|
|
/// A provided transaction was placed after a non-provided transaction.
|
|
|
|
#[error("a provided transaction was included after a non-provided transaction")]
|
|
|
|
ProvidedAfterNonProvided,
|
|
|
|
/// The block had a provided transaction this validator has yet to be provided.
|
|
|
|
#[error("block had a provided transaction not yet locally provided: {0:?}")]
|
|
|
|
NonLocalProvided([u8; 32]),
|
|
|
|
/// The provided transaction was distinct from the locally provided transaction.
|
|
|
|
#[error("block had a distinct provided transaction")]
|
|
|
|
DistinctProvided,
|
2023-04-11 17:42:18 +00:00
|
|
|
/// An included transaction was invalid.
|
|
|
|
#[error("included transaction had an error")]
|
|
|
|
TransactionError(TransactionError),
|
|
|
|
}
|
|
|
|
|
2023-04-12 00:24:27 +00:00
|
|
|
use crate::{
|
2023-04-14 00:35:55 +00:00
|
|
|
BLOCK_SIZE_LIMIT, ReadWrite, TransactionError, Signed, TransactionKind, Transaction, merkle,
|
2023-04-12 00:24:27 +00:00
|
|
|
verify_transaction,
|
|
|
|
};
|
2023-04-11 17:42:18 +00:00
|
|
|
|
|
|
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
|
|
|
pub struct BlockHeader {
|
2023-04-12 15:13:48 +00:00
|
|
|
pub parent: [u8; 32],
|
|
|
|
pub transactions: [u8; 32],
|
2023-04-11 17:42:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl ReadWrite for BlockHeader {
|
|
|
|
fn read<R: io::Read>(reader: &mut R) -> io::Result<Self> {
|
|
|
|
let mut header = BlockHeader { parent: [0; 32], transactions: [0; 32] };
|
|
|
|
reader.read_exact(&mut header.parent)?;
|
|
|
|
reader.read_exact(&mut header.transactions)?;
|
|
|
|
Ok(header)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn write<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
|
|
|
|
writer.write_all(&self.parent)?;
|
|
|
|
writer.write_all(&self.transactions)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl BlockHeader {
|
2023-04-12 22:04:28 +00:00
|
|
|
pub fn hash(&self) -> [u8; 32] {
|
2023-04-11 17:42:18 +00:00
|
|
|
Blake2s256::digest([b"tributary_block".as_ref(), &self.serialize()].concat()).into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
|
|
|
pub struct Block<T: Transaction> {
|
2023-04-12 15:13:48 +00:00
|
|
|
pub header: BlockHeader,
|
|
|
|
pub transactions: Vec<T>,
|
2023-04-11 17:42:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: Transaction> ReadWrite for Block<T> {
|
|
|
|
fn read<R: io::Read>(reader: &mut R) -> io::Result<Self> {
|
|
|
|
let header = BlockHeader::read(reader)?;
|
|
|
|
|
|
|
|
let mut txs = [0; 4];
|
|
|
|
reader.read_exact(&mut txs)?;
|
|
|
|
let txs = u32::from_le_bytes(txs);
|
|
|
|
|
|
|
|
let mut transactions = Vec::with_capacity(usize::try_from(txs).unwrap());
|
|
|
|
for _ in 0 .. txs {
|
|
|
|
transactions.push(T::read(reader)?);
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(Block { header, transactions })
|
|
|
|
}
|
|
|
|
|
|
|
|
fn write<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
|
|
|
|
self.header.write(writer)?;
|
|
|
|
writer.write_all(&u32::try_from(self.transactions.len()).unwrap().to_le_bytes())?;
|
|
|
|
for tx in &self.transactions {
|
|
|
|
tx.write(writer)?;
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: Transaction> Block<T> {
|
2023-04-12 00:24:27 +00:00
|
|
|
/// Create a new block.
|
|
|
|
///
|
|
|
|
/// mempool is expected to only have valid, non-conflicting transactions.
|
2023-04-14 00:35:55 +00:00
|
|
|
pub(crate) fn new(parent: [u8; 32], provided: Vec<T>, mempool: Vec<T>) -> Self {
|
|
|
|
let mut txs = provided;
|
|
|
|
for tx in mempool {
|
2023-04-12 00:24:27 +00:00
|
|
|
assert!(tx.kind() != TransactionKind::Provided, "provided transaction entered mempool");
|
|
|
|
txs.push(tx);
|
|
|
|
}
|
|
|
|
|
2023-04-14 00:35:55 +00:00
|
|
|
// Check TXs are sorted by nonce.
|
2023-04-12 00:24:27 +00:00
|
|
|
let nonce = |tx: &T| {
|
|
|
|
if let TransactionKind::Signed(Signed { nonce, .. }) = tx.kind() {
|
2023-04-12 15:13:48 +00:00
|
|
|
*nonce
|
2023-04-12 00:24:27 +00:00
|
|
|
} else {
|
|
|
|
0
|
|
|
|
}
|
|
|
|
};
|
|
|
|
let mut last = 0;
|
|
|
|
for tx in &txs {
|
|
|
|
let nonce = nonce(tx);
|
|
|
|
if nonce < last {
|
|
|
|
panic!("failed to sort txs by nonce");
|
|
|
|
}
|
|
|
|
last = nonce;
|
|
|
|
}
|
|
|
|
|
2023-04-14 00:35:55 +00:00
|
|
|
let mut res =
|
|
|
|
Block { header: BlockHeader { parent, transactions: [0; 32] }, transactions: txs };
|
|
|
|
while res.serialize().len() > BLOCK_SIZE_LIMIT {
|
|
|
|
assert!(res.transactions.pop().is_some());
|
|
|
|
}
|
|
|
|
let hashes = res.transactions.iter().map(Transaction::hash).collect::<Vec<_>>();
|
|
|
|
res.header.transactions = merkle(&hashes);
|
|
|
|
res
|
2023-04-12 00:24:27 +00:00
|
|
|
}
|
|
|
|
|
2023-04-20 09:05:17 +00:00
|
|
|
pub fn parent(&self) -> [u8; 32] {
|
|
|
|
self.header.parent
|
|
|
|
}
|
|
|
|
|
2023-04-11 17:42:18 +00:00
|
|
|
pub fn hash(&self) -> [u8; 32] {
|
|
|
|
self.header.hash()
|
|
|
|
}
|
|
|
|
|
2023-04-14 00:35:55 +00:00
|
|
|
pub(crate) fn verify(
|
2023-04-11 17:42:18 +00:00
|
|
|
&self,
|
2023-04-11 23:03:36 +00:00
|
|
|
genesis: [u8; 32],
|
2023-04-11 17:42:18 +00:00
|
|
|
last_block: [u8; 32],
|
2023-04-14 00:35:55 +00:00
|
|
|
locally_provided: &[[u8; 32]],
|
2023-04-12 15:13:48 +00:00
|
|
|
mut next_nonces: HashMap<<Ristretto as Ciphersuite>::G, u32>,
|
2023-04-11 17:42:18 +00:00
|
|
|
) -> Result<(), BlockError> {
|
2023-04-14 00:35:55 +00:00
|
|
|
if self.serialize().len() > BLOCK_SIZE_LIMIT {
|
|
|
|
Err(BlockError::TooLargeBlock)?;
|
|
|
|
}
|
|
|
|
|
2023-04-11 17:42:18 +00:00
|
|
|
if self.header.parent != last_block {
|
|
|
|
Err(BlockError::InvalidParent)?;
|
|
|
|
}
|
|
|
|
|
2023-04-14 00:35:55 +00:00
|
|
|
let mut found_non_provided = false;
|
2023-04-11 17:42:18 +00:00
|
|
|
let mut txs = Vec::with_capacity(self.transactions.len());
|
2023-04-14 00:35:55 +00:00
|
|
|
for (i, tx) in self.transactions.iter().enumerate() {
|
|
|
|
txs.push(tx.hash());
|
|
|
|
|
|
|
|
if tx.kind() == TransactionKind::Provided {
|
|
|
|
if found_non_provided {
|
|
|
|
Err(BlockError::ProvidedAfterNonProvided)?;
|
|
|
|
}
|
|
|
|
|
|
|
|
let Some(local) = locally_provided.get(i) else {
|
|
|
|
Err(BlockError::NonLocalProvided(txs.pop().unwrap()))?
|
|
|
|
};
|
|
|
|
if txs.last().unwrap() != local {
|
|
|
|
Err(BlockError::DistinctProvided)?;
|
|
|
|
}
|
|
|
|
|
|
|
|
// We don't need to call verify_transaction since we did when we locally provided this
|
|
|
|
// transaction. Since it's identical, it must be valid
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
found_non_provided = true;
|
|
|
|
match verify_transaction(tx, genesis, &mut next_nonces) {
|
2023-04-11 17:42:18 +00:00
|
|
|
Ok(()) => {}
|
|
|
|
Err(e) => Err(BlockError::TransactionError(e))?,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if merkle(&txs) != self.header.transactions {
|
|
|
|
Err(BlockError::InvalidTransactions)?;
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|