Skip to main content

forest/blocks/
header.rs

1// Copyright 2019-2026 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4use std::sync::{
5    OnceLock,
6    atomic::{AtomicBool, Ordering},
7};
8
9use super::{ElectionProof, Error, Ticket, TipsetKey};
10use crate::{
11    beacon::{Beacon as _, BeaconEntry, BeaconSchedule},
12    shim::{
13        address::Address, clock::ChainEpoch, crypto::Signature, econ::TokenAmount,
14        sector::PoStProof, version::NetworkVersion,
15    },
16    utils::{encoding::blake2b_256, get_size::big_int_heap_size_helper, multihash::MultihashCode},
17};
18use cid::Cid;
19use fvm_ipld_blockstore::Blockstore;
20use fvm_ipld_encoding::CborStore as _;
21use fvm_ipld_encoding::tuple::*;
22use get_size2::GetSize;
23use multihash_derive::MultihashDigest as _;
24use num::BigInt;
25use serde::{Deserialize, Serialize};
26
27#[cfg(test)]
28mod test;
29#[cfg(test)]
30pub use test::*;
31
32#[derive(Deserialize_tuple, Serialize_tuple, Clone, Hash, Eq, PartialEq, Debug)]
33pub struct RawBlockHeader {
34    /// The address of the miner actor that mined this block
35    pub miner_address: Address,
36    pub ticket: Option<Ticket>,
37    pub election_proof: Option<ElectionProof>,
38    /// The verifiable oracle randomness used to elect this block's author leader
39    pub beacon_entries: Vec<BeaconEntry>,
40    pub winning_post_proof: Vec<PoStProof>,
41    /// The set of parents this block was based on.
42    /// Typically one, but can be several in the case where there were multiple
43    /// winning ticket-holders for an epoch
44    pub parents: TipsetKey,
45    /// The aggregate chain weight of the parent set
46    #[serde(with = "crate::shim::fvm_shared_latest::bigint::bigint_ser")]
47    pub weight: BigInt,
48    /// The period in which a new block is generated.
49    /// There may be multiple rounds in an epoch.
50    pub epoch: ChainEpoch,
51    /// The CID of the parent state root after calculating parent tipset.
52    pub state_root: Cid,
53    /// The CID of the root of an array of `MessageReceipts`
54    pub message_receipts: Cid,
55    /// The CID of the Merkle links for `bls_messages` and `secp_messages`
56    pub messages: Cid,
57    /// Aggregate signature of miner in block
58    pub bls_aggregate: Option<Signature>,
59    /// Block creation time, in seconds since the Unix epoch
60    pub timestamp: u64,
61    pub signature: Option<Signature>,
62    pub fork_signal: u64,
63    /// The base fee of the parent block
64    pub parent_base_fee: TokenAmount,
65}
66
67impl RawBlockHeader {
68    pub fn cid(&self) -> Cid {
69        self.car_block().expect("CBOR serialization failed").0
70    }
71    pub fn car_block(&self) -> anyhow::Result<(Cid, Vec<u8>)> {
72        let data = fvm_ipld_encoding::to_vec(self)?;
73        let cid = Cid::new_v1(
74            fvm_ipld_encoding::DAG_CBOR,
75            MultihashCode::Blake2b256.digest(&data),
76        );
77        Ok((cid, data))
78    }
79    pub(super) fn tipset_sort_key(&self) -> Option<([u8; 32], Vec<u8>)> {
80        let ticket_hash = blake2b_256(self.ticket.as_ref()?.vrfproof.as_bytes());
81        Some((ticket_hash, self.cid().to_bytes()))
82    }
83    /// Check to ensure block signature is valid
84    pub fn verify_signature_against(&self, addr: &Address) -> Result<(), Error> {
85        let signature = self
86            .signature
87            .as_ref()
88            .ok_or_else(|| Error::InvalidSignature("Signature is nil in header".into()))?;
89
90        signature.verify(&self.signing_bytes(), addr).map_err(|e| {
91            Error::InvalidSignature(format!("Block signature invalid: {e:#}").into())
92        })?;
93
94        Ok(())
95    }
96
97    /// Validates if the current header's Beacon entries are valid to ensure
98    /// randomness was generated correctly
99    pub fn validate_block_drand(
100        &self,
101        network_version: NetworkVersion,
102        b_schedule: &BeaconSchedule,
103        parent_epoch: ChainEpoch,
104        prev_entry: &BeaconEntry,
105    ) -> Result<(), Error> {
106        let (cb_epoch, curr_beacon) = b_schedule
107            .beacon_for_epoch(self.epoch)
108            .map_err(|e| Error::Validation(format!("{e:#}").into()))?;
109        tracing::trace!(
110            "beacon network at {}: {:?}, is_chained: {}",
111            self.epoch,
112            curr_beacon.network(),
113            curr_beacon.network().is_chained()
114        );
115        // Before quicknet upgrade, we had "chained" beacons, and so required two entries at a fork
116        if curr_beacon.network().is_chained() {
117            let (pb_epoch, _) = b_schedule
118                .beacon_for_epoch(parent_epoch)
119                .map_err(|e| Error::Validation(format!("{e:#}").into()))?;
120            if cb_epoch != pb_epoch {
121                // Fork logic
122                if self.beacon_entries.len() != 2 {
123                    return Err(Error::Validation(
124                        format!(
125                            "Expected two beacon entries at beacon fork, got {}",
126                            self.beacon_entries.len()
127                        )
128                        .into(),
129                    ));
130                }
131
132                #[allow(clippy::indexing_slicing)]
133                curr_beacon
134                    .verify_entries(&self.beacon_entries[1..], &self.beacon_entries[0])
135                    .map_err(|e| Error::Validation(format!("{e:#}").into()))?;
136
137                return Ok(());
138            }
139        }
140
141        let max_round = curr_beacon.max_beacon_round_for_epoch(network_version, self.epoch);
142        // We don't expect to ever actually meet this condition
143        if max_round == prev_entry.round() {
144            if !self.beacon_entries.is_empty() {
145                return Err(Error::Validation(
146                    format!(
147                        "expected not to have any beacon entries in this block, got: {}",
148                        self.beacon_entries.len()
149                    )
150                    .into(),
151                ));
152            }
153            return Ok(());
154        }
155
156        // We skip verifying the genesis entry when randomness is "chained".
157        if curr_beacon.network().is_chained() && prev_entry.round() == 0 {
158            // This basically means that the drand entry of the first non-genesis tipset isn't verified IF we are starting on Drand mainnet (the "chained" drand)
159            // Networks that start on drand quicknet, or other unchained randomness sources, will still verify it
160            return Ok(());
161        }
162
163        let last = match self.beacon_entries.last() {
164            Some(last) => last,
165            None => {
166                return Err(Error::Validation(
167                    "Block must include at least 1 beacon entry".into(),
168                ));
169            }
170        };
171
172        if last.round() != max_round {
173            return Err(Error::Validation(
174                format!(
175                    "expected final beacon entry in block to be at round {}, got: {}",
176                    max_round,
177                    last.round()
178                )
179                .into(),
180            ));
181        }
182
183        if !curr_beacon
184            .verify_entries(&self.beacon_entries, prev_entry)
185            .map_err(|e| Error::Validation(format!("{e:#}").into()))?
186        {
187            return Err(Error::Validation("beacon entry was invalid".into()));
188        }
189
190        Ok(())
191    }
192
193    /// Serializes the header to bytes for signing purposes i.e. without the
194    /// signature field
195    pub fn signing_bytes(&self) -> Vec<u8> {
196        let mut blk = self.clone();
197        blk.signature = None;
198        fvm_ipld_encoding::to_vec(&blk).expect("block serialization cannot fail")
199    }
200}
201
202// The derive macro does not compile for some reason
203impl GetSize for RawBlockHeader {
204    fn get_heap_size_with_tracker<T: get_size2::GetSizeTracker>(
205        &self,
206        mut tracker: T,
207    ) -> (usize, T) {
208        let Self {
209            miner_address,
210            ticket,
211            election_proof,
212            beacon_entries,
213            winning_post_proof,
214            parents,
215            weight,
216            epoch: _,
217            state_root: _,
218            message_receipts: _,
219            messages: _,
220            bls_aggregate,
221            timestamp: _,
222            signature,
223            fork_signal: _,
224            parent_base_fee,
225        } = self;
226        (
227            miner_address.get_heap_size_with_tracker(&mut tracker).0
228                + ticket.get_heap_size_with_tracker(&mut tracker).0
229                + election_proof.get_heap_size_with_tracker(&mut tracker).0
230                + beacon_entries.get_heap_size_with_tracker(&mut tracker).0
231                + winning_post_proof
232                    .get_heap_size_with_tracker(&mut tracker)
233                    .0
234                + parents.get_heap_size_with_tracker(&mut tracker).0
235                + big_int_heap_size_helper(weight)
236                + bls_aggregate.get_heap_size_with_tracker(&mut tracker).0
237                + signature.get_heap_size_with_tracker(&mut tracker).0
238                + parent_base_fee.get_heap_size_with_tracker(&mut tracker).0,
239            tracker,
240        )
241    }
242}
243
244/// A [`RawBlockHeader`] which caches calls to [`RawBlockHeader::cid`] and [`RawBlockHeader::verify_signature_against`]
245#[cfg_attr(test, derive(Default))]
246#[derive(Debug, GetSize, derive_more::Deref)]
247pub struct CachingBlockHeader {
248    #[deref]
249    uncached: RawBlockHeader,
250    #[get_size(ignore)]
251    cid: OnceLock<Cid>,
252    has_ever_been_verified_against_any_signature: AtomicBool,
253}
254
255impl PartialEq for CachingBlockHeader {
256    fn eq(&self, other: &Self) -> bool {
257        // Epoch check is redundant but cheap.
258        self.uncached.epoch == other.uncached.epoch && self.cid() == other.cid()
259    }
260}
261
262impl Eq for CachingBlockHeader {}
263
264impl Clone for CachingBlockHeader {
265    fn clone(&self) -> Self {
266        Self {
267            uncached: self.uncached.clone(),
268            cid: self.cid.clone(),
269            has_ever_been_verified_against_any_signature: AtomicBool::new(
270                self.has_ever_been_verified_against_any_signature
271                    .load(Ordering::Acquire),
272            ),
273        }
274    }
275}
276
277impl From<RawBlockHeader> for CachingBlockHeader {
278    fn from(value: RawBlockHeader) -> Self {
279        Self::new(value)
280    }
281}
282
283impl CachingBlockHeader {
284    pub fn new(uncached: RawBlockHeader) -> Self {
285        Self {
286            uncached,
287            cid: OnceLock::new(),
288            has_ever_been_verified_against_any_signature: AtomicBool::new(false),
289        }
290    }
291    pub fn into_raw(self) -> RawBlockHeader {
292        self.uncached
293    }
294    /// Returns [`None`] if the blockstore doesn't contain the CID.
295    pub fn load(store: &impl Blockstore, cid: Cid) -> anyhow::Result<Option<Self>> {
296        if let Some(uncached) = store.get_cbor::<RawBlockHeader>(&cid)? {
297            Ok(Some(Self {
298                uncached,
299                cid: cid.into(),
300                has_ever_been_verified_against_any_signature: AtomicBool::new(false),
301            }))
302        } else {
303            Ok(None)
304        }
305    }
306    pub fn cid(&self) -> &Cid {
307        self.cid.get_or_init(|| self.uncached.cid())
308    }
309
310    pub fn verify_signature_against(&self, addr: &Address) -> Result<(), Error> {
311        match self
312            .has_ever_been_verified_against_any_signature
313            .load(Ordering::Acquire)
314        {
315            true => Ok(()),
316            false => match self.uncached.verify_signature_against(addr) {
317                Ok(()) => {
318                    self.has_ever_been_verified_against_any_signature
319                        .store(true, Ordering::Release);
320                    Ok(())
321                }
322                Err(e) => Err(e),
323            },
324        }
325    }
326}
327
328impl From<CachingBlockHeader> for RawBlockHeader {
329    fn from(value: CachingBlockHeader) -> Self {
330        value.into_raw()
331    }
332}
333
334impl Serialize for CachingBlockHeader {
335    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
336    where
337        S: serde::Serializer,
338    {
339        self.uncached.serialize(serializer)
340    }
341}
342
343impl<'de> Deserialize<'de> for CachingBlockHeader {
344    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
345    where
346        D: serde::Deserializer<'de>,
347    {
348        RawBlockHeader::deserialize(deserializer).map(Self::new)
349    }
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355    use crate::beacon::{BeaconEntry, BeaconPoint, BeaconSchedule, mock_beacon::MockBeacon};
356    use crate::blocks::{CachingBlockHeader, Error};
357    use crate::shim::clock::ChainEpoch;
358    use crate::shim::{address::Address, version::NetworkVersion};
359    use crate::utils::encoding::from_slice_with_fallback;
360    use crate::utils::multihash::MultihashCode;
361    use cid::Cid;
362    use fvm_ipld_encoding::{DAG_CBOR, to_vec};
363
364    impl quickcheck::Arbitrary for CachingBlockHeader {
365        fn arbitrary(g: &mut quickcheck::Gen) -> Self {
366            use crate::blocks::{Ticket, VRFProof};
367            // TODO(forest): https://github.com/ChainSafe/forest/issues/3571
368            CachingBlockHeader::new(RawBlockHeader {
369                miner_address: Address::new_id(0),
370                ticket: Some(Ticket::new(VRFProof::new(Vec::arbitrary(g)))),
371                epoch: ChainEpoch::arbitrary(g),
372                ..Default::default()
373            })
374        }
375    }
376
377    #[test]
378    fn symmetric_header_encoding() {
379        // This test vector is pulled from space race, and contains a valid signature
380        let bz = hex::decode("904300e8078158608798de4e49e02ee129920224ea767650aa6e693857431cc95b5a092a57d80ef4d841ebedbf09f7680a5e286cd297f40100b496648e1fa0fd55f899a45d51404a339564e7d4809741ba41d9fcc8ac0261bf521cd5f718389e81354eff2aa52b338201586084d8929eeedc654d6bec8bb750fcc8a1ebf2775d8167d3418825d9e989905a8b7656d906d23dc83e0dad6e7f7a193df70a82d37da0565ce69b776d995eefd50354c85ec896a2173a5efed53a27275e001ad72a3317b2190b98cceb0f01c46b7b81821a00013cbe5860ae1102b76dea635b2f07b7d06e1671d695c4011a73dc33cace159509eac7edc305fa74495505f0cd0046ee0d3b17fabc0fc0560d44d296c6d91bcc94df76266a8e9d5312c617ca72a2e186cadee560477f6d120f6614e21fb07c2390a166a25981820358c0b965705cec77b46200af8fb2e47c0eca175564075061132949f00473dcbe74529c623eb510081e8b8bd34418d21c646485d893f040dcfb7a7e7af9ae4ed7bd06772c24fb0cc5b8915300ab5904fbd90269d523018fbf074620fd3060d55dd6c6057b4195950ac4155a735e8fec79767f659c30ea6ccf0813a4ab2b4e60f36c04c71fb6c58efc123f60c6ea8797ab3706a80a4ccc1c249989934a391803789ab7d04f514ee0401d0f87a1f5262399c451dcf5f7ec3bb307fc6f1a41f5ff3a5ddb81d82a5827000171a0e402209a0640d0620af5d1c458effce4cbb8969779c9072b164d3fe6f5179d6378d8cd4300310001d82a5827000171a0e402208fbc07f7587e2efebab9ff1ab27c928881abf9d1b7e5ad5206781415615867aed82a5827000171a0e40220e5658b3d18cd06e1db9015b4b0ec55c123a24d5be1ea24d83938c5b8397b4f2fd82a5827000171a0e402209967f10c4c0e336b3517d3a972f701dadea5b41ce33defb126b88e650cf884545861028ec8b64e2d93272f97edcab1f56bcad4a2b145ea88c232bfae228e4adbbd807e6a41740cc8cb569197dae6b2cbf8c1a4035e81fd7805ccbe88a5ec476bcfa438db4bd677de06b45e94310533513e9d17c635940ba8fa2650cdb34d445724c5971a5f44387e5861028a45c70a39fe8e526cbb6ba2a850e9063460873d6329f26cc2fc91972256c40249dba289830cc99619109c18e695d78012f760e7fda1b68bc3f1fe20ff8a017044753da38ca6384de652f3ee13aae5b64e6f88f85fd50d5c862fed3c1f594ace004500053724e0").unwrap();
381        let header = from_slice_with_fallback::<CachingBlockHeader>(&bz).unwrap();
382        assert_eq!(to_vec(&header).unwrap(), bz);
383
384        // Verify the signature of this block header using the resolved address used to
385        // sign. This is a valid signature, but if the block header vector
386        // changes, the address should need to as well.
387        header
388            .verify_signature_against(
389                &"f3vfs6f7tagrcpnwv65wq3leznbajqyg77bmijrpvoyjv3zjyi3urq25vigfbs3ob6ug5xdihajumtgsxnz2pa"
390                .parse()
391                .unwrap())
392            .unwrap();
393    }
394
395    #[test]
396    fn beacon_entry_exists() {
397        // Setup
398        let block_header = CachingBlockHeader::new(RawBlockHeader {
399            miner_address: Address::new_id(0),
400            ..Default::default()
401        });
402        let beacon_schedule = BeaconSchedule(vec![BeaconPoint::new(0, <MockBeacon>::default())]);
403        let chain_epoch = 0;
404        let beacon_entry = BeaconEntry::new(1, vec![]);
405        // Validate_block_drand
406        if let Err(e) = block_header.validate_block_drand(
407            NetworkVersion::V16,
408            &beacon_schedule,
409            chain_epoch,
410            &beacon_entry,
411        ) {
412            // Assert error is for not including a beacon entry in the block
413            match e {
414                Error::Validation(why) => {
415                    assert_eq!(why, "Block must include at least 1 beacon entry");
416                }
417                _ => {
418                    panic!("validate block drand must detect a beacon entry in the block header");
419                }
420            }
421        }
422    }
423
424    #[test]
425    fn test_genesis_parent() {
426        assert_eq!(
427            Cid::new_v1(
428                DAG_CBOR,
429                MultihashCode::Sha2_256.digest(&FILECOIN_GENESIS_BLOCK)
430            ),
431            *FILECOIN_GENESIS_CID
432        );
433    }
434}