monero_serai/
block.rs

1use std_shims::{
2  vec,
3  vec::Vec,
4  io::{self, Read, Write},
5};
6
7use crate::{
8  io::*,
9  primitives::keccak256,
10  merkle::merkle_root,
11  transaction::{Input, Transaction},
12};
13
14const CORRECT_BLOCK_HASH_202612: [u8; 32] =
15  hex_literal::hex!("426d16cff04c71f8b16340b722dc4010a2dd3831c22041431f772547ba6e331a");
16const EXISTING_BLOCK_HASH_202612: [u8; 32] =
17  hex_literal::hex!("bbd604d2ba11ba27935e006ed39c9bfdd99b76bf4a50654bc1e1e61217962698");
18
19/// A Monero block's header.
20#[derive(Clone, PartialEq, Eq, Debug)]
21pub struct BlockHeader {
22  /// The hard fork of the protocol this block follows.
23  ///
24  /// Per the C++ codebase, this is the `major_version`.
25  pub hardfork_version: u8,
26  /// A signal for a proposed hard fork.
27  ///
28  /// Per the C++ codebase, this is the `minor_version`.
29  pub hardfork_signal: u8,
30  /// Seconds since the epoch.
31  pub timestamp: u64,
32  /// The previous block's hash.
33  pub previous: [u8; 32],
34  /// The nonce used to mine the block.
35  ///
36  /// Miners should increment this while attempting to find a block with a hash satisfying the PoW
37  /// rules.
38  pub nonce: u32,
39}
40
41impl BlockHeader {
42  /// Write the BlockHeader.
43  pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
44    write_varint(&self.hardfork_version, w)?;
45    write_varint(&self.hardfork_signal, w)?;
46    write_varint(&self.timestamp, w)?;
47    w.write_all(&self.previous)?;
48    w.write_all(&self.nonce.to_le_bytes())
49  }
50
51  /// Serialize the BlockHeader to a `Vec<u8>`.
52  pub fn serialize(&self) -> Vec<u8> {
53    let mut serialized = vec![];
54    self.write(&mut serialized).unwrap();
55    serialized
56  }
57
58  /// Read a BlockHeader.
59  pub fn read<R: Read>(r: &mut R) -> io::Result<BlockHeader> {
60    Ok(BlockHeader {
61      hardfork_version: read_varint(r)?,
62      hardfork_signal: read_varint(r)?,
63      timestamp: read_varint(r)?,
64      previous: read_bytes(r)?,
65      nonce: read_bytes(r).map(u32::from_le_bytes)?,
66    })
67  }
68}
69
70/// A Monero block.
71#[derive(Clone, PartialEq, Eq, Debug)]
72pub struct Block {
73  /// The block's header.
74  pub header: BlockHeader,
75  /// The miner's transaction.
76  pub miner_transaction: Transaction,
77  /// The transactions within this block.
78  pub transactions: Vec<[u8; 32]>,
79}
80
81impl Block {
82  /// The zero-indexed position of this block within the blockchain.
83  ///
84  /// This information comes from the Block's miner transaction. If the miner transaction isn't
85  /// structed as expected, this will return None. This will return Some for any Block which would
86  /// pass the consensus rules.
87  // https://github.com/monero-project/monero/blob/a1dc85c5373a30f14aaf7dcfdd95f5a7375d3623
88  //   /src/cryptonote_core/blockchain.cpp#L1365-L1382
89  pub fn number(&self) -> Option<usize> {
90    match &self.miner_transaction {
91      Transaction::V1 { prefix, .. } | Transaction::V2 { prefix, .. } => {
92        match prefix.inputs.first() {
93          Some(Input::Gen(number)) => Some(*number),
94          _ => None,
95        }
96      }
97    }
98  }
99
100  /// Write the Block.
101  pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
102    self.header.write(w)?;
103    self.miner_transaction.write(w)?;
104    write_varint(&self.transactions.len(), w)?;
105    for tx in &self.transactions {
106      w.write_all(tx)?;
107    }
108    Ok(())
109  }
110
111  /// Serialize the Block to a `Vec<u8>`.
112  pub fn serialize(&self) -> Vec<u8> {
113    let mut serialized = vec![];
114    self.write(&mut serialized).unwrap();
115    serialized
116  }
117
118  /// Serialize the block as required for the proof of work hash.
119  ///
120  /// This is distinct from the serialization required for the block hash. To get the block hash,
121  /// use the [`Block::hash`] function.
122  pub fn serialize_pow_hash(&self) -> Vec<u8> {
123    let mut blob = self.header.serialize();
124    blob.extend_from_slice(&merkle_root(self.miner_transaction.hash(), &self.transactions));
125    write_varint(&(1 + u64::try_from(self.transactions.len()).unwrap()), &mut blob).unwrap();
126    blob
127  }
128
129  /// Get the hash of this block.
130  pub fn hash(&self) -> [u8; 32] {
131    let mut hashable = self.serialize_pow_hash();
132    // Monero pre-appends a VarInt of the block-to-hash'ss length before getting the block hash,
133    // but doesn't do this when getting the proof of work hash :)
134    let mut hashing_blob = Vec::with_capacity(9 + hashable.len());
135    write_varint(&u64::try_from(hashable.len()).unwrap(), &mut hashing_blob).unwrap();
136    hashing_blob.append(&mut hashable);
137
138    let hash = keccak256(hashing_blob);
139    if hash == CORRECT_BLOCK_HASH_202612 {
140      return EXISTING_BLOCK_HASH_202612;
141    };
142    hash
143  }
144
145  /// Read a Block.
146  pub fn read<R: Read>(r: &mut R) -> io::Result<Block> {
147    Ok(Block {
148      header: BlockHeader::read(r)?,
149      miner_transaction: Transaction::read(r)?,
150      transactions: (0_usize .. read_varint(r)?)
151        .map(|_| read_bytes(r))
152        .collect::<Result<_, _>>()?,
153    })
154  }
155}