alloy_eip2124/
head.rs

1use alloy_primitives::{BlockNumber, B256, U256};
2use core::fmt;
3#[cfg(feature = "serde")]
4use serde::{Deserialize, Serialize};
5
6/// Describes the current head block.
7///
8/// The head block is the highest fully synced block.
9///
10/// Note: This is a slimmed down version of Header, primarily for communicating the highest block
11/// with the P2P network and the RPC.
12#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
13#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
14pub struct Head {
15    /// The number of the head block.
16    pub number: BlockNumber,
17    /// The hash of the head block.
18    pub hash: B256,
19    /// The difficulty of the head block.
20    pub difficulty: U256,
21    /// The total difficulty at the head block.
22    pub total_difficulty: U256,
23    /// The timestamp of the head block.
24    pub timestamp: u64,
25}
26
27impl Head {
28    /// Creates a new `Head` instance.
29    pub const fn new(
30        number: BlockNumber,
31        hash: B256,
32        difficulty: U256,
33        total_difficulty: U256,
34        timestamp: u64,
35    ) -> Self {
36        Self { number, hash, difficulty, total_difficulty, timestamp }
37    }
38
39    /// Updates the head block with new information.
40    pub fn update(
41        &mut self,
42        number: BlockNumber,
43        hash: B256,
44        difficulty: U256,
45        total_difficulty: U256,
46        timestamp: u64,
47    ) {
48        *self = Self { number, hash, difficulty, total_difficulty, timestamp };
49    }
50
51    /// Checks if the head block is an empty block (i.e., has default values).
52    pub fn is_empty(&self) -> bool {
53        *self == Self::default()
54    }
55}
56
57impl fmt::Display for Head {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        write!(
60            f,
61            "Head Block:\n Number: {}\n Hash: {}\n Difficulty: {:?}\n Total Difficulty: {:?}\n Timestamp: {}",
62            self.number, self.hash, self.difficulty, self.total_difficulty, self.timestamp
63        )
64    }
65}