Skip to main content

witness_core/
ledger.rs

1//! The ledger header and its hash.
2//!
3//! The ledger hash, which is what validators sign, is SHA-512Half(`LWR\0`,
4//! header). The header pins the roots of two trees (transactions and
5//! state) and links to the previous ledger through the parent hash. So from
6//! a confirmed ledger hash you can reach both its transactions and earlier
7//! ledgers.
8//!
9//! Header serialization, all numbers big-endian, 118 bytes:
10//! sequence (4), total drops (8), parent hash (32), transaction root (32),
11//! state root (32), parent close time (4), close time (4),
12//! close time resolution (1), close flags (1).
13
14use crate::stobject::Error;
15use crate::{HashPrefix, sha512_half};
16
17pub const HEADER_LEN: usize = 118;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct LedgerHeader {
21    pub sequence: u32,
22    pub total_drops: u64,
23    pub parent_hash: [u8; 32],
24    pub transaction_hash: [u8; 32],
25    pub account_hash: [u8; 32],
26    pub parent_close_time: u32,
27    pub close_time: u32,
28    pub close_time_resolution: u8,
29    pub close_flags: u8,
30    hash: [u8; 32],
31}
32
33fn arr<const N: usize>(b: &[u8], at: usize) -> [u8; N] {
34    let mut out = [0u8; N];
35    out.copy_from_slice(&b[at..at + N]);
36    out
37}
38
39impl LedgerHeader {
40    pub fn parse(raw: &[u8]) -> Result<LedgerHeader, Error> {
41        if raw.len() != HEADER_LEN {
42            return Err(Error::Malformed(format!(
43                "ledger header is {} bytes, expected {HEADER_LEN}",
44                raw.len()
45            )));
46        }
47        let mut data = HashPrefix::LedgerMaster.to_bytes().to_vec();
48        data.extend_from_slice(raw);
49        Ok(LedgerHeader {
50            sequence: u32::from_be_bytes(arr(raw, 0)),
51            total_drops: u64::from_be_bytes(arr(raw, 4)),
52            parent_hash: arr(raw, 12),
53            transaction_hash: arr(raw, 44),
54            account_hash: arr(raw, 76),
55            parent_close_time: u32::from_be_bytes(arr(raw, 108)),
56            close_time: u32::from_be_bytes(arr(raw, 112)),
57            close_time_resolution: raw[116],
58            close_flags: raw[117],
59            hash: sha512_half(&data),
60        })
61    }
62
63    /// The ledger hash, which is what validators sign.
64    pub fn hash(&self) -> [u8; 32] {
65        self.hash
66    }
67}