use std::{
fmt::{Debug, Display, Formatter},
io::Write,
};
use nimiq_block::{
Block, BlockBody, BlockInclusionProof, BlockType, MacroBlock, MacroHeader, MicroBlock,
MicroHeader, MicroJustification, TendermintProof,
};
#[cfg(feature = "full")]
use nimiq_blockchain::HistoryTreeChunk;
use nimiq_blockchain_interface::Direction;
use nimiq_hash::{Blake2bHash, Blake2sHash, Hash, HashOutput, SerializeContent};
use nimiq_keys::Address;
use nimiq_macros::test_max_req_size;
use nimiq_mmr::mmr::proof::SizeProof;
use nimiq_network_interface::{
network::Topic,
request::{RequestCommon, RequestMarker},
};
use nimiq_primitives::{key_nibbles::KeyNibbles, trie::trie_proof::TrieProof};
use nimiq_serde::{Deserialize, Serialize, SerializedMaxSize};
use nimiq_transaction::{
historic_transaction::HistoricTransaction, history_proof::HistoryTreeProof,
};
use thiserror::Error;
use crate::error::SubscribeToAddressesError;
mod handlers;
#[derive(Debug, Serialize, Deserialize)]
pub enum BlockHeaderMessage {
Macro {
header: MacroHeader,
justification: TendermintProof,
},
Micro {
header: MicroHeader,
justification: MicroJustification,
},
}
impl BlockHeaderMessage {
pub fn ty(&self) -> BlockType {
match self {
BlockHeaderMessage::Macro { .. } => BlockType::Macro,
BlockHeaderMessage::Micro { .. } => BlockType::Micro,
}
}
pub fn body_root(&self) -> &Blake2sHash {
match self {
BlockHeaderMessage::Macro { header, .. } => &header.body_root,
BlockHeaderMessage::Micro { header, .. } => &header.body_root,
}
}
pub fn split_block(block: Block) -> (BlockHeaderMessage, BlockBodyMessage) {
match block {
Block::Macro(block) => {
let header_message = BlockHeaderMessage::Macro {
header: block.header,
justification: block.justification.expect("Justification is required"),
};
let body_message = BlockBodyMessage {
header_message_hash: header_message.hash(),
body: BlockBody::Macro(block.body.expect("Body is required")),
};
(header_message, body_message)
}
Block::Micro(block) => {
let header_message = BlockHeaderMessage::Micro {
header: block.header,
justification: block.justification.expect("Justification is required"),
};
let body_message = BlockBodyMessage {
header_message_hash: header_message.hash(),
body: BlockBody::Micro(block.body.expect("Body is required")),
};
(header_message, body_message)
}
}
}
}
impl Display for BlockHeaderMessage {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
BlockHeaderMessage::Macro { header, .. } => Display::fmt(header, f),
BlockHeaderMessage::Micro { header, .. } => Display::fmt(header, f),
}
}
}
impl SerializeContent for BlockHeaderMessage {
fn serialize_content<W: Write, H: HashOutput>(&self, writer: &mut W) -> std::io::Result<()> {
self.serialize(writer).map(|_| ())
}
}
impl From<BlockHeaderMessage> for Block {
fn from(value: BlockHeaderMessage) -> Block {
match value {
BlockHeaderMessage::Macro {
header,
justification,
} => Block::Macro(MacroBlock {
header,
body: None,
justification: Some(justification),
}),
BlockHeaderMessage::Micro {
header,
justification,
} => Block::Micro(MicroBlock {
header,
body: None,
justification: Some(justification),
}),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BlockBodyMessage {
pub header_message_hash: Blake2bHash,
pub body: BlockBody,
}
#[derive(Clone, Debug, Default)]
pub struct BlockHeaderTopic;
impl Topic for BlockHeaderTopic {
type Item = BlockHeaderMessage;
const BUFFER_SIZE: usize = 16;
const NAME: &'static str = "block-header";
const VALIDATE: bool = true;
const MAX_MESSAGES: u32 = 20;
}
#[derive(Clone, Debug, Default)]
pub struct BlockBodyTopic;
impl Topic for BlockBodyTopic {
type Item = BlockBodyMessage;
const BUFFER_SIZE: usize = 16;
const NAME: &'static str = "block-body";
const VALIDATE: bool = true;
const MAX_MESSAGES: u32 = BlockHeaderTopic::MAX_MESSAGES;
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Checkpoint {
pub block_number: u32,
pub hash: Blake2bHash,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct MacroChain {
pub epochs: Vec<Blake2bHash>,
pub checkpoint: Option<Checkpoint>,
}
#[derive(Clone, Debug, Deserialize, Error, Serialize, SerializedMaxSize)]
pub enum MacroChainError {
#[error("unknown locators")]
UnknownLocators,
#[error("too many locators")]
TooManyLocators,
#[error("unknown error")]
#[serde(other)]
Other,
}
impl Debug for MacroChain {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
let mut dbg = f.debug_struct("MacroChain");
dbg.field("num_epochs", &self.epochs.len());
if !self.epochs.is_empty() {
let first = self.epochs.first().unwrap();
let last = self.epochs.last().unwrap();
dbg.field("first_epoch", &first);
dbg.field("last_epoch", &last);
}
dbg.field("checkpoint", &self.checkpoint);
dbg.finish()
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RequestMacroChain {
pub locators: Vec<Blake2bHash>,
pub max_epochs: u16,
}
impl RequestCommon for RequestMacroChain {
type Kind = RequestMarker;
const TYPE_ID: u16 = 200;
type Response = Result<MacroChain, MacroChainError>;
const MAX_REQUESTS: u32 = 20;
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RequestBatchSet {
pub hash: Blake2bHash,
}
impl RequestCommon for RequestBatchSet {
type Kind = RequestMarker;
const TYPE_ID: u16 = 202;
type Response = Result<BatchSetInfo, BatchSetError>;
const MAX_REQUESTS: u32 = 100;
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BatchSet {
pub macro_block: MacroBlock,
pub history_len: SizeProof<Blake2bHash, HistoricTransaction>,
}
#[derive(Clone, Debug, Deserialize, Error, Serialize)]
pub enum BatchSetError {
#[error("target hash not found")]
TargetHashNotFound,
#[error("the hash of a micro block was given")]
MicroBlockGiven,
#[error("couldn't produce history size proof")]
CouldntProduceHistorySizeProof,
#[error("unknown error")]
#[serde(other)]
Other,
}
#[derive(Clone, Default, Serialize, Deserialize)]
pub struct BatchSetInfo {
pub election_macro_block: Option<MacroBlock>,
pub batch_sets: Vec<BatchSet>,
}
impl BatchSetInfo {
pub fn total_history_len(&self) -> u64 {
self.batch_sets
.last()
.map(|batch_set| batch_set.history_len.size())
.unwrap_or(0)
}
pub fn final_macro_block(&self) -> &MacroBlock {
self.election_macro_block.as_ref().unwrap_or_else(|| {
&self
.batch_sets
.last()
.expect("BatchSet must not be empty")
.macro_block
})
}
}
impl Debug for BatchSetInfo {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut debug_struct = f.debug_struct("BatchSetInfo");
if let Some(block) = &self.election_macro_block {
debug_struct
.field("election_epoch_number", &block.epoch_number())
.field("election_block_number", &block.block_number());
}
debug_struct.field("total_history_len", &self.total_history_len());
debug_struct.field("batch_sets_len", &self.batch_sets.len());
debug_struct.finish()
}
}
#[cfg(feature = "full")]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RequestHistoryChunk {
pub epoch_number: u32,
pub block_number: u32,
pub chunk_index: u64,
}
#[cfg(feature = "full")]
impl RequestCommon for RequestHistoryChunk {
type Kind = RequestMarker;
const TYPE_ID: u16 = 204;
type Response = Result<HistoryChunk, HistoryChunkError>;
const MAX_REQUESTS: u32 = 500;
}
#[cfg(feature = "full")]
#[derive(Debug, Serialize, Deserialize)]
pub struct HistoryChunk {
pub chunk: HistoryTreeChunk,
}
#[cfg(feature = "full")]
#[derive(Clone, Debug, Deserialize, Error, Serialize)]
pub enum HistoryChunkError {
#[error("couldn't produce proof")]
CouldntProduceProof,
#[error("unknown error")]
#[serde(other)]
Other,
}
#[derive(Clone, Debug, Deserialize, Serialize, SerializedMaxSize)]
pub struct RequestBlock {
pub hash: Blake2bHash,
pub include_body: bool,
}
#[derive(Clone, Debug, Deserialize, Error, Serialize, SerializedMaxSize)]
pub enum BlockError {
#[error("target hash not found")]
TargetHashNotFound,
#[error("target hash response hash mismatch")]
ResponseHashMismatch,
#[error("unknown error")]
#[serde(other)]
Other,
}
impl RequestCommon for RequestBlock {
type Kind = RequestMarker;
const TYPE_ID: u16 = 207;
type Response = Result<Block, BlockError>;
const MAX_REQUESTS: u32 = 200;
}
test_max_req_size!(
RequestBlock,
request_block_req_size,
request_block_resp_size,
);
#[derive(Clone, Deserialize, Serialize)]
pub struct ResponseBlocks {
pub blocks: Vec<Block>,
}
#[derive(Clone, Debug, Deserialize, Error, Serialize)]
pub enum ResponseBlocksError {
#[error("target block not on main chain")]
TargetBlockNotOnMainChain,
#[error("target hash not found")]
TargetHashNotFound,
#[error("unknown locators")]
UnknownLocators,
#[error("too many locators")]
TooManyLocators,
#[error("failed to get blocks")]
FailedToGetBlocks,
#[error("unknown error")]
#[serde(other)]
Other,
}
impl Debug for ResponseBlocks {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
let mut dbg = f.debug_struct("ResponseBlocks");
dbg.field("length", &self.blocks.len());
if !self.blocks.is_empty() {
let first = self.blocks.first().unwrap();
let last = self.blocks.last().unwrap();
dbg.field("first_block", &first.block_number());
dbg.field("last_block", &last.block_number());
}
dbg.finish()
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RequestMissingBlocks {
pub target_hash: Blake2bHash,
pub include_body: bool,
pub locators: Vec<Blake2bHash>,
pub direction: Direction,
}
impl RequestCommon for RequestMissingBlocks {
type Kind = RequestMarker;
const TYPE_ID: u16 = 209;
type Response = Result<ResponseBlocks, ResponseBlocksError>;
const MAX_REQUESTS: u32 = 200;
}
#[derive(Clone, Debug, Deserialize, Serialize, SerializedMaxSize)]
pub struct RequestHead {}
#[derive(Clone, Debug, Deserialize, Serialize, SerializedMaxSize)]
pub struct ResponseHead {
pub block_number: u32,
pub block_hash: Blake2bHash,
pub macro_hash: Blake2bHash,
pub election_hash: Blake2bHash,
}
impl RequestCommon for RequestHead {
type Kind = RequestMarker;
const TYPE_ID: u16 = 210;
type Response = ResponseHead;
const MAX_REQUESTS: u32 = 50;
}
test_max_req_size!(RequestHead, request_head_req_size, request_head_resp_size);
#[derive(Serialize, Deserialize)]
pub struct ResponseTransactionsProof {
pub proof: HistoryTreeProof,
pub block: Block,
}
#[derive(Clone, Debug, Deserialize, Error, Serialize)]
pub enum ResponseTransactionProofError {
#[error("empty list of transactions given")]
NoTransactionsProvided,
#[error("too many transactions given")]
TooManyTransactionsProvided,
#[error("requested txn proof from future block {0}, current head is {1}")]
RequestedTxnProofFromFuture(u32, u32),
#[error("requested txn proof that corresponds to a finalized epoch (block number {0}), should use the election block instead")]
RequestedTxnProofFromFinalizedEpoch(u32),
#[error("requested txn proof from finalized batch (block number {0}), should use a checkpoint block instead")]
RequestedTxnProofFromFinalizedBatch(u32),
#[error("Block not found: {0}")]
BlockNotFound(u32),
#[error("couldn't prove inclusion")]
CouldntProveInclusion,
#[error("transaction not found")]
TransactionNotFound,
#[error("unknown error")]
#[serde(other)]
Other,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RequestTransactionsProof {
pub hashes: Vec<Blake2bHash>,
pub block_number: Option<u32>,
}
impl RequestCommon for RequestTransactionsProof {
type Kind = RequestMarker;
const TYPE_ID: u16 = 213;
type Response = Result<ResponseTransactionsProof, ResponseTransactionProofError>;
const MAX_REQUESTS: u32 = 1000;
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RequestTransactionReceiptsByAddress {
pub address: Address,
pub max: Option<u16>,
pub start_at: Option<Blake2bHash>,
}
impl RequestCommon for RequestTransactionReceiptsByAddress {
type Kind = RequestMarker;
const TYPE_ID: u16 = 214;
type Response = ResponseTransactionReceiptsByAddress;
const MAX_REQUESTS: u32 = 20;
}
#[derive(Serialize, Deserialize)]
pub struct ResponseTransactionReceiptsByAddress {
pub receipts: Vec<(Blake2bHash, u32)>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RequestTrieProof {
pub keys: Vec<KeyNibbles>, }
impl RequestCommon for RequestTrieProof {
type Kind = RequestMarker;
const TYPE_ID: u16 = 215;
type Response = Result<ResponseTrieProof, ResponseTrieProofError>;
const MAX_REQUESTS: u32 = 50;
}
#[derive(Serialize, Deserialize)]
pub struct ResponseTrieProof {
pub proof: TrieProof,
pub block_hash: Blake2bHash,
}
#[derive(Clone, Debug, Deserialize, Error, Serialize)]
pub enum ResponseTrieProofError {
#[error("incomplete trie")]
IncompleteTrie,
#[error("empty keys")]
EmptyKeys,
#[error("too many keys")]
TooManyKeys,
#[error("duplicate keys")]
DuplicateKeys,
#[error("unknown error")]
#[serde(other)]
Other,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RequestBlocksProof {
pub election_head: u32,
pub blocks: Vec<u32>,
}
#[derive(Serialize, Deserialize)]
pub struct ResponseBlocksProof {
pub proof: BlockInclusionProof,
}
#[derive(Clone, Debug, Deserialize, Error, Serialize)]
pub enum ResponseBlocksProofError {
#[error("bad block number {0}")]
BadBlockNumber(u32),
#[error("too many blocks")]
TooManyBlocks,
#[error("unknown error")]
#[serde(other)]
Other,
}
impl RequestCommon for RequestBlocksProof {
type Kind = RequestMarker;
const TYPE_ID: u16 = 216;
type Response = Result<ResponseBlocksProof, ResponseBlocksProofError>;
const MAX_REQUESTS: u32 = 50;
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[repr(u8)]
pub enum AddressSubscriptionOperation {
Subscribe,
Unsubscribe,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RequestSubscribeToAddress {
pub operation: AddressSubscriptionOperation,
pub addresses: Vec<Address>,
}
impl RequestCommon for RequestSubscribeToAddress {
type Kind = RequestMarker;
const TYPE_ID: u16 = 217;
type Response = Result<(), SubscribeToAddressesError>;
const MAX_REQUESTS: u32 = 10;
}
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
#[repr(u8)]
pub enum NotificationEvent {
BlockchainExtend,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AddressNotification {
pub event: NotificationEvent,
pub receipts: Vec<(Blake2bHash, u32)>,
}
#[derive(Clone, Debug, Default)]
pub struct AddressSubscriptionTopic;
impl Topic for AddressSubscriptionTopic {
type Item = AddressNotification;
const BUFFER_SIZE: usize = 1024;
const NAME: &'static str = "address-subscription";
const VALIDATE: bool = false;
const MAX_MESSAGES: u32 = 10_000;
}