monero_oxide/
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    VarInt::write(&self.hardfork_version, w)?;
45    VarInt::write(&self.hardfork_signal, w)?;
46    VarInt::write(&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).expect("write failed but <Vec as io::Write> doesn't fail");
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: VarInt::read(r)?,
62      hardfork_signal: VarInt::read(r)?,
63      timestamp: VarInt::read(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  miner_transaction: Transaction,
77  /// The transactions within this block.
78  pub transactions: Vec<[u8; 32]>,
79}
80
81impl Block {
82  /// The maximum amount of transactions a block may have, including the miner transaction.
83  /*
84    Definition of maximum amount of transaction:
85    https://github.com/monero-project/monero
86      /blob/8d4c625713e3419573dfcc7119c8848f47cabbaa/src/cryptonote_config.h#L42
87
88    Limitation of the amount of transactions within the `transactions` field:
89    https://github.com/monero-project/monero
90      /blob/8d4c625713e3419573dfcc7119c8848f47cabbaa/src/cryptonote_basic/cryptonote_basic.h#L571
91
92    This would mean the actual limit is `0x10000000 + 1`, including the miner transaction, except:
93    https://github.com/monero-project/monero
94      /blob/8d4c625713e3419573dfcc7119c8848f47cabbaa/src/crypto/tree-hash.c#L55
95
96    calculation of the Merkle tree representing all transactions will fail if this many
97    transactions is consumed by the `transactions` field alone.
98  */
99  pub const MAX_TRANSACTIONS: usize = 0x10000000;
100
101  /// Construct a new `Block`.
102  ///
103  /// This MAY apply miscellaneous consensus rules as useful for the sanity of working with this
104  /// type. The result is not guaranteed to follow all Monero consensus rules or any specific set
105  /// of consensus rules.
106  pub fn new(
107    header: BlockHeader,
108    miner_transaction: Transaction,
109    transactions: Vec<[u8; 32]>,
110  ) -> Option<Block> {
111    // Check this correctly defines the block's number
112    // https://github.com/monero-project/monero/blob/a1dc85c5373a30f14aaf7dcfdd95f5a7375d3623
113    //   /src/cryptonote_core/blockchain.cpp#L1365-L1382
114    {
115      let inputs = &miner_transaction.prefix().inputs;
116      if inputs.len() != 1 {
117        None?;
118      }
119      match inputs[0] {
120        Input::Gen(_number) => {}
121        _ => None?,
122      }
123    }
124
125    Some(Block { header, miner_transaction, transactions })
126  }
127
128  /// The zero-indexed position of this block within the blockchain.
129  pub fn number(&self) -> usize {
130    match &self.miner_transaction {
131      Transaction::V1 { prefix, .. } | Transaction::V2 { prefix, .. } => {
132        match prefix.inputs.first() {
133          Some(Input::Gen(number)) => *number,
134          _ => panic!("invalid miner transaction accepted into block"),
135        }
136      }
137    }
138  }
139
140  /// The block's miner's transaction.
141  pub fn miner_transaction(&self) -> &Transaction {
142    &self.miner_transaction
143  }
144
145  /// Write the Block.
146  pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
147    self.header.write(w)?;
148    self.miner_transaction.write(w)?;
149    VarInt::write(&self.transactions.len(), w)?;
150    for tx in &self.transactions {
151      w.write_all(tx)?;
152    }
153    Ok(())
154  }
155
156  /// Serialize the Block to a `Vec<u8>`.
157  pub fn serialize(&self) -> Vec<u8> {
158    let mut serialized = vec![];
159    self.write(&mut serialized).expect("write failed but <Vec as io::Write> doesn't fail");
160    serialized
161  }
162
163  /// Serialize the block as required for the proof of work hash.
164  ///
165  /// This is distinct from the serialization required for the block hash. To get the block hash,
166  /// use the [`Block::hash`] function.
167  pub fn serialize_pow_hash(&self) -> Vec<u8> {
168    let mut blob = self.header.serialize();
169
170    let mut transactions = Vec::with_capacity(self.transactions.len() + 1);
171    transactions.push(self.miner_transaction.hash());
172    transactions.extend_from_slice(&self.transactions);
173
174    blob.extend_from_slice(
175      &merkle_root(transactions)
176        .expect("the tree will not be empty, the miner tx is always present"),
177    );
178    VarInt::write(&(1 + self.transactions.len()), &mut blob)
179      .expect("write failed but <Vec as io::Write> doesn't fail");
180    blob
181  }
182
183  /// Get the hash of this block.
184  pub fn hash(&self) -> [u8; 32] {
185    let mut hashable = self.serialize_pow_hash();
186    // Monero pre-appends a VarInt of the block-to-hash's length before getting the block hash,
187    // but doesn't do this when getting the proof of work hash :)
188    let mut hashing_blob = Vec::with_capacity(<usize as VarInt>::UPPER_BOUND + hashable.len());
189    VarInt::write(
190      &u64::try_from(hashable.len()).expect("length of block hash's preimage exceeded u64::MAX"),
191      &mut hashing_blob,
192    )
193    .expect("write failed but <Vec as io::Write> doesn't fail");
194    hashing_blob.append(&mut hashable);
195
196    let hash = keccak256(hashing_blob);
197    if hash == CORRECT_BLOCK_HASH_202612 {
198      return EXISTING_BLOCK_HASH_202612;
199    };
200    hash
201  }
202
203  /// Read a Block.
204  ///
205  /// This MAY error if miscellaneous Monero conseusus rules are broken, as useful when
206  /// deserializing. The result is not guaranteed to follow all Monero consensus rules or any
207  /// specific set of consensus rules.
208  pub fn read<R: Read>(r: &mut R) -> io::Result<Block> {
209    let header = BlockHeader::read(r)?;
210
211    let miner_transaction = Transaction::read(r)?;
212
213    let transactions: usize = VarInt::read(r)?;
214    if transactions >= Self::MAX_TRANSACTIONS {
215      Err(io::Error::other("amount of transaction exceeds limit"))?;
216    }
217    let transactions = (0 .. transactions).map(|_| read_bytes(r)).collect::<Result<_, _>>()?;
218
219    Block::new(header, miner_transaction, transactions)
220      .ok_or_else(|| io::Error::other("block failed sanity checks"))
221  }
222}