Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
e8e9c32
feat(chainstate): add optional PoS seal activation gate
nullPointerEnjoyer Nov 15, 2026
b3d0c2f
fix(chainstate): address seal gate review round 1
nullPointerEnjoyer Nov 15, 2026
8fd16a5
test(chainstate): harden seal gate twin and refine comments
nullPointerEnjoyer Nov 15, 2026
3602782
test(chainstate): drop an unused mut in the seal gate test
nullPointerEnjoyer Nov 15, 2026
1739c1c
test(chainstate): add the PoS seal adversarial suite
nullPointerEnjoyer Nov 15, 2026
0cf3330
test(chainstate): fix unused variables in the seal tests
nullPointerEnjoyer Nov 15, 2026
5df457a
test(chainstate): fix clippy lints in the seal tests
nullPointerEnjoyer Nov 15, 2026
39052bd
test(chainstate): address seal suite review round 1
nullPointerEnjoyer Nov 15, 2026
a266487
test(chainstate): pin seal suite semantics and refusal reachability
nullPointerEnjoyer Nov 15, 2026
e4dbb06
test(chainstate): fix clippy lints in the seal test helpers
nullPointerEnjoyer Nov 15, 2026
9531277
test(chainstate): pin the seal gate refusal end to end
nullPointerEnjoyer Nov 15, 2026
d484ed5
test(chainstate): drop unused imports in the seal tests
nullPointerEnjoyer Nov 15, 2026
33b90b2
feat(chainstate): enable the seal gate by default on testnet chains
nullPointerEnjoyer Nov 21, 2026
7f14ed9
fix: harden the seal gate config validation and update its docs
nullPointerEnjoyer Nov 21, 2026
96fdb6f
test: silence the unused key warning in the seal tracking test
nullPointerEnjoyer Nov 21, 2026
5ed5ef6
test(chainstate): pin seal gate sighting permanence under invalidation
nullPointerEnjoyer Nov 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@ The format is loosely based on [Keep a Changelog](https://keepachangelog.com/en/

## [Unreleased]

### Added
- Node:
- chainstate: an optional `pos_seal_activation_gate` chainstate config setting:
when enabled, the node will not activate a chain whose newly activated segment
consists entirely of blocks whose PoS consensus proofs are duplicates of proofs
already seen on other known blocks. The initial block download and the reorgs
of the user-initiated block invalidation path are never affected. The default
depends on the chain type: enabled on the testnet (hardening it from launch),
disabled elsewhere; an explicit setting always overrides the default. Enabling
the gate while the seal duplication tracking is disabled is now rejected at
chainstate initialization instead of being silently ignored.

### Changed
- Storage:
- the internal storage iteration APIs (`prefix_iter`, `greater_equal_iter`) now
Expand Down
1 change: 1 addition & 0 deletions blockprod/src/tests/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ impl BlockprodTestSetupBuilder {
max_orphan_blocks: Default::default(),
allow_checkpoints_mismatch: Default::default(),
pos_seal_duplication_tracking: Default::default(),
pos_seal_activation_gate: Default::default(),
};

let mempool_config = self.mempool_config.unwrap_or_default();
Expand Down
60 changes: 60 additions & 0 deletions chainstate/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,13 @@ pub struct ChainstateConfig {
/// If true, the seals (stake pool id + VRF output) of the processed PoS blocks will be
/// indexed and the evidence of a seal seen on more than one block will be recorded.
pub pos_seal_duplication_tracking: PosSealDuplicationTracking,

/// If true, a chain whose newly activated segment consists entirely of blocks whose
/// PoS consensus proofs are duplicates of already-known proofs will not be activated.
/// Only effective together with `pos_seal_duplication_tracking`, which maintains the
/// index this gate classifies against. `None` means the default for the chain type
/// applies: enabled on the testnet (hardening it from launch), disabled elsewhere.
pub pos_seal_activation_gate: Option<bool>,
}

impl ChainstateConfig {
Expand Down Expand Up @@ -79,6 +86,17 @@ impl ChainstateConfig {
*self.pos_seal_duplication_tracking
}

pub fn pos_seal_activation_gate_enabled(&self, chain_config: &ChainConfig) -> bool {
if let Some(pos_seal_activation_gate) = self.pos_seal_activation_gate {
return pos_seal_activation_gate;
}

match chain_config.chain_type() {
ChainType::Testnet => true,
ChainType::Mainnet | ChainType::Signet | ChainType::Regtest => false,
}
}

pub fn db_reckless_mode_in_ibd_enabled(&self) -> bool {
// The library default stays identical to master (opt-in): the experimental
// default-on behavior lives at the node-daemon layer (node-lib/src/runner.rs),
Expand All @@ -101,3 +119,45 @@ impl ChainstateConfig {
self.allow_checkpoints_mismatch.unwrap_or(false)
}
}

#[cfg(test)]
mod tests {
use super::*;
use common::chain::Destination;
use common::chain::NetUpgrades;
use common::chain::config::Builder as ConfigBuilder;
use std::collections::BTreeMap;

fn chain_config_for(chain_type: ChainType) -> common::chain::config::ChainConfig {
ConfigBuilder::new(chain_type)
.consensus_upgrades(NetUpgrades::unit_tests())
.genesis_unittest(Destination::AnyoneCanSpend)
.checkpoints(BTreeMap::new())
.build()
}

#[test]
fn seal_gate_default_depends_on_chain_type() {
let config = ChainstateConfig::default();

assert!(config.pos_seal_activation_gate_enabled(&chain_config_for(ChainType::Testnet)));
assert!(!config.pos_seal_activation_gate_enabled(&chain_config_for(ChainType::Mainnet)));
assert!(!config.pos_seal_activation_gate_enabled(&chain_config_for(ChainType::Signet)));
assert!(!config.pos_seal_activation_gate_enabled(&chain_config_for(ChainType::Regtest)));
}

#[test]
fn seal_gate_explicit_setting_overrides_the_default() {
let enabled = ChainstateConfig {
pos_seal_activation_gate: Some(true),
..Default::default()
};
assert!(enabled.pos_seal_activation_gate_enabled(&chain_config_for(ChainType::Mainnet)));

let disabled = ChainstateConfig {
pos_seal_activation_gate: Some(false),
..Default::default()
};
assert!(!disabled.pos_seal_activation_gate_enabled(&chain_config_for(ChainType::Testnet)));
}
}
11 changes: 9 additions & 2 deletions chainstate/src/detail/block_invalidation/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ use derive_more::Display;
use thiserror::Error;

use self::best_chain_candidates::BestChainCandidates;
use super::{Chainstate, chainstateref::ChainstateRef};
use super::{
Chainstate,
chainstateref::{ChainActivationContext, ChainstateRef},
};
use crate::{
BlockError, BlockProcessingErrorClassification, TransactionVerificationStrategy,
detail::chainstateref::ReorgError,
Expand Down Expand Up @@ -208,7 +211,11 @@ impl<'a, S: BlockchainStorage, V: TransactionVerificationStrategy> BlockInvalida
let block_index =
get_existing_block_index(chainstate_ref, candidate.block_id())?;
let reorg_occured = chainstate_ref
.activate_best_chain(&block_index, None)
.activate_best_chain(
&block_index,
None,
ChainActivationContext::InvalidationRecovery,
)
.map_err(ReorgDuringInvalidationError::ReorgError)?;
assert!(reorg_occured);
Ok(())
Expand Down
140 changes: 138 additions & 2 deletions chainstate/src/detail/chainstateref/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ use thiserror::Error;

use chainstate_storage::{BlockchainStorageRead, BlockchainStorageWrite, TransactionRw};
use chainstate_types::{
BlockIndex, BlockIndexHandle, BlockStatus, BlockValidationStage, EpochData, EpochDataCache,
GenBlockIndex, GetAncestorError, PropertyQueryError, TipStorageTag,
BlockIndex, BlockIndexHandle, BlockSeal, BlockStatus, BlockValidationStage, EpochData,
EpochDataCache, GenBlockIndex, GetAncestorError, PropertyQueryError, TipStorageTag,
block_index_ancestor_getter, get_skip_height,
};
use common::{
Expand Down Expand Up @@ -1438,11 +1438,19 @@ impl<S: BlockchainStorageWrite, V: TransactionVerificationStrategy> ChainstateRe
&mut self,
new_block_index: &BlockIndex,
in_memory_block: Option<&WithId<Block>>,
activation_context: ChainActivationContext,
) -> Result<bool, ReorgError> {
let current_best_block_index =
self.get_best_block_index().map_err(BlockError::BestBlockIndexQueryError)?;

if new_block_index.chain_trust() > current_best_block_index.chain_trust() {
if self.reorg_segment_activation_refused(
new_block_index,
&current_best_block_index.block_id(),
activation_context,
)? {
return Ok(false);
}
// Chain trust is higher than the best block
self.reorganize(
&current_best_block_index.block_id(),
Expand All @@ -1455,6 +1463,66 @@ impl<S: BlockchainStorageWrite, V: TransactionVerificationStrategy> ChainstateRe
Ok(false)
}

/// Classifies whether the activation of the candidate chain must be refused
/// because its new segment consists entirely of duplicate-seal blocks (PoS
/// consensus proofs that were already seen on other known blocks).
///
/// This is the PoS seal activation gate
/// (`ChainstateConfig::pos_seal_activation_gate`): it is enabled by default only on
/// testnet chains and disabled by default elsewhere,
/// it never fires during the initial block download or on the reorgs of the
/// user-initiated block invalidation path, and it is fail-open: a block that
/// does not yield a well-formed seal (PoW, genesis, malformed PoS data) is
/// never classified as a duplicate, and a segment that contains at least one
/// non-duplicate block proceeds under the ordinary trust comparison.
///
/// A refusal is a no-op: the candidate chain stays stored, valid and
/// relayable, and every later activation attempt re-runs this classification,
/// so a refused branch that gains a block with a fresh seal becomes
/// activatable.
fn reorg_segment_activation_refused(
&mut self,
new_block_index: &BlockIndex,
best_block_id: &Id<GenBlock>,
activation_context: ChainActivationContext,
) -> Result<bool, ReorgError> {
if !self.chainstate_config.pos_seal_activation_gate_enabled(self.chain_config) {
return Ok(false);
}
if activation_context.seal_activation_gate_bypassed() {
return Ok(false);
}

let new_chain = self
.get_new_chain(new_block_index)
.map_err(|e| {
BlockError::InvariantErrorFailedToFindNewChainPath(
(*new_block_index.block_id()).into(),
*best_block_id,
e,
)
})
.log_err()?;

if new_chain.is_empty() {
// Unreachable through the current callers: a candidate with strictly
// higher trust is never part of the main chain, so the walk to it is
// non-empty. The gate declines to refuse here; the ordinary path
// below then enforces its own empty-chain invariant.
return Ok(false);
}

if segment_seals_all_duplicated(&self.db_tx, &new_chain)? {
log::info!(
"Not activating a chain whose new segment consists only of blocks reusing \
already-known PoS consensus proofs"
);
return Ok(true);
}

Ok(false)
}

#[log_error]
pub fn persist_block(&mut self, block: &WithId<Block>) -> Result<(), BlockError> {
if self.db_tx.block_exists(&block.get_id()).map_err(BlockError::from)? {
Expand Down Expand Up @@ -1614,6 +1682,74 @@ pub enum ReorgError {
OtherError(#[from] BlockError),
}

/// The context of a best-chain activation attempt.
///
/// The PoS seal activation gate (see
/// `ChainstateConfig::pos_seal_activation_gate`) must never influence chain
/// re-activations driven by the user-initiated block invalidation path, nor the
/// initial block download, where the liveness of the bootstrap outweighs
/// containment.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChainActivationContext {
/// A newly processed block is being connected during normal operation.
BlockProcessing { in_initial_block_download: bool },
/// The best chain is being re-activated after user-initiated block invalidation.
InvalidationRecovery,
}

impl ChainActivationContext {
/// Whether the PoS seal activation gate must be bypassed for this activation.
fn seal_activation_gate_bypassed(&self) -> bool {
match self {
ChainActivationContext::BlockProcessing {
in_initial_block_download,
} => *in_initial_block_download,
ChainActivationContext::InvalidationRecovery => true,
}
}
}

/// Classifies whether every block of the given activation segment carries a
/// duplicate-seal PoS consensus proof (a proof already seen on another known
/// block, per the seal duplication index). A block that does not yield a
/// well-formed seal is never classified as a duplicate, and an empty segment is
/// never refused.
///
/// Sightings are permanent: the index is a historical record, so entries are
/// not pruned when a block is invalidated, and the classification does not
/// skip invalidated partner blocks. This is deliberate fail-closed behavior.
/// An honest segment always carries at least one fresh seal (honestly-mined
/// VRF proofs are unique), so the gate cannot refuse an honest chain, while
/// counting only valid partners would let an attacker make a reused seal look
/// unique again by having one of its twins invalidated -- re-opening exactly
/// the trust-inflation construction the gate exists to refuse. A refused chain
/// always recovers by extending with a single fresh-seal block.
fn segment_seals_all_duplicated<S: BlockchainStorageRead>(
db_tx: &S,
new_chain: &[BlockIndex],
) -> Result<bool, BlockError> {
if new_chain.is_empty() {
return Ok(false);
}
for block_index in new_chain {
let Some(seal) =
BlockSeal::from_consensus_data(block_index.block_header().consensus_data())
else {
// The block does not yield a well-formed seal, so it cannot be
// classified as a duplicate and the segment is not fully duplicated.
return Ok(false);
};
let duplicated = match db_tx.get_seal_index_entry(&seal).map_err(BlockError::from)? {
Some(entry) => entry.blocks().len() > 1,
None => false,
};
Comment on lines +1742 to +1745

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
The duplication classification relies solely on the raw size of the seal index entry, but the index is never pruned when a block is invalidated: index_block_seal adds block ids permanently, and the block invalidation path (which bypasses the gate via ChainActivationContext::InvalidationRecovery) does not remove seal index entries. Consequently, after a user invalidates one of the twin blocks carrying a reused seal, a segment block whose only duplicate partner is that invalidated block is still classified as fully duplicated and its chain activation is refused indefinitely (until a fresh-seal extension exists). Since invalidated blocks are by definition not part of any acceptable chain, this makes the gate fire on what is effectively a unique seal. Consider skipping invalid-pruned/invalidated block ids when counting partner blocks (e.g. checking db_tx.get_block_index(id) status), or documenting why a permanently refused activation is acceptable for invalidated twins.

Suggestion:

Suggested change
let duplicated = match db_tx.get_seal_index_entry(&seal).map_err(BlockError::from)? {
Some(entry) => entry.blocks().len() > 1,
None => false,
};
let duplicated = match db_tx.get_seal_index_entry(&seal).map_err(BlockError::from)? {
Some(entry) => {
// Only count partners that are still known-valid; entries are
// not pruned when a block is invalidated, so an invalidated
// twin must not make a seal look reused.
entry.blocks().iter().any(|(partner_id, _)| {
partner_id != &(*block_index.block_id())
&& db_tx
.get_block_index(partner_id)
.map_err(BlockError::from)?
.map(|idx| idx.status().is_ok())
.unwrap_or(false)
})
}
None => false,
};

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Investigated — the facts are correct (the classification uses the raw entry size and invalidation does not prune the seal index), but the suggested fix is rejected as a security regression, and the behavior is intended and now pinned.

Why counting only valid partners is a laundering vector: a reused seal becomes "unique" again as soon as one of its twins is invalidated (operator action, or the implicit stale-block invalidation path). That would re-enable exactly the trust-inflation activation the gate exists to refuse — an attacker profits from having one of its own twins invalidated.

Why no honest chain can be affected: honestly-mined VRF proofs are unique, and the reference miner's timestamp search starts at prev_block_timestamp + 1, so an honest segment always carries at least one fresh seal and activates normally. A segment that is entirely reused-proof blocks is adversarial by construction. Sightings are historical facts; the index is deliberately append-only (fail-closed direction: invalidation can only grow the duplicated set, never shrink it).

Recovery: a refused chain activates as soon as it gains a single fresh-seal block, so nothing is stranded permanently.

Pinned end to end in invalidated_partner_does_not_launder_a_reused_seal (invalidated twin → second reused-proof sibling still refused → fresh-seal child activates), with the rationale documented on segment_seals_all_duplicated.

if !duplicated {
return Ok(false);
}
}
Ok(true)
}

#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
pub struct NonZeroPoolBalances {
total_balance: Amount,
Expand Down
Loading
Loading