From e8e9c3269df20351f0a16baac1e5dc02ec977413 Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sun, 15 Nov 2026 16:14:41 +0100 Subject: [PATCH 01/16] feat(chainstate): add optional PoS seal activation gate Add a disabled-by-default chainstate config setting that refuses to 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 classification reads the per-seal index maintained by the seal duplication tracking and runs at activation time, so it never stores new state and re-evaluates on every attempt: a refused branch becomes activatable again as soon as its segment contains a block with a fresh proof, which then proceeds under the ordinary trust comparison. The gate never fires on the initial block download or on the reorgs of the user-initiated block invalidation path, and it is fail-open: blocks that do not yield a well-formed seal are never classified as duplicates. Refused branches stay stored, valid and relayable. --- CHANGELOG.md | 9 + blockprod/src/tests/helpers.rs | 1 + chainstate/src/config.rs | 10 ++ .../src/detail/block_invalidation/mod.rs | 11 +- chainstate/src/detail/chainstateref/mod.rs | 111 +++++++++++- .../src/detail/chainstateref/seal_index.rs | 29 ++++ chainstate/src/detail/mod.rs | 14 +- .../chainstate_interface_impl_delegation.rs | 1 + chainstate/test-suite/src/tests/bootstrap.rs | 1 + .../src/tests/seal_duplication_tests.rs | 161 +++++++++++++++++- .../test-suite/src/tests/syncing_tests.rs | 1 + node-lib/src/config_files/chainstate/mod.rs | 7 + node-lib/src/config_files/mod.rs | 3 + 13 files changed, 351 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 85f351bffe..6a158ffa3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,15 @@ 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 + (disabled by default): 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. + ### Changed - Storage: - the internal storage iteration APIs (`prefix_iter`, `greater_equal_iter`) now diff --git a/blockprod/src/tests/helpers.rs b/blockprod/src/tests/helpers.rs index 7dc1a492ac..451131b7cf 100644 --- a/blockprod/src/tests/helpers.rs +++ b/blockprod/src/tests/helpers.rs @@ -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(); diff --git a/chainstate/src/config.rs b/chainstate/src/config.rs index beae6e0c1e..c1e4da2570 100644 --- a/chainstate/src/config.rs +++ b/chainstate/src/config.rs @@ -22,6 +22,7 @@ make_config_setting!(MaxDbCommitAttempts, usize, 10); make_config_setting!(MaxOrphanBlocks, usize, 512); make_config_setting!(MaxTipAge, Duration, Duration::from_secs(60 * 60 * 24)); make_config_setting!(PosSealDuplicationTracking, bool, true); +make_config_setting!(PosSealActivationGate, bool, false); /// The chainstate subsystem configuration. #[derive(Debug, Clone, Default)] @@ -52,6 +53,11 @@ 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. + /// Defaults to false. + pub pos_seal_activation_gate: PosSealActivationGate, } impl ChainstateConfig { @@ -79,6 +85,10 @@ impl ChainstateConfig { *self.pos_seal_duplication_tracking } + pub fn pos_seal_activation_gate_enabled(&self) -> bool { + *self.pos_seal_activation_gate + } + 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), diff --git a/chainstate/src/detail/block_invalidation/mod.rs b/chainstate/src/detail/block_invalidation/mod.rs index f6a78e06bc..bf56e59f96 100644 --- a/chainstate/src/detail/block_invalidation/mod.rs +++ b/chainstate/src/detail/block_invalidation/mod.rs @@ -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, @@ -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(()) diff --git a/chainstate/src/detail/chainstateref/mod.rs b/chainstate/src/detail/chainstateref/mod.rs index 0ab878799b..d5da5de043 100644 --- a/chainstate/src/detail/chainstateref/mod.rs +++ b/chainstate/src/detail/chainstateref/mod.rs @@ -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::{ @@ -1438,11 +1438,19 @@ impl ChainstateRe &mut self, new_block_index: &BlockIndex, in_memory_block: Option<&WithId>, + activation_context: ChainActivationContext, ) -> Result { 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, + ¤t_best_block_index.block_id(), + activation_context, + )? { + return Ok(false); + } // Chain trust is higher than the best block self.reorganize( ¤t_best_block_index.block_id(), @@ -1455,6 +1463,78 @@ impl 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 disabled by default, + /// 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, + activation_context: ChainActivationContext, + ) -> Result { + if !self.chainstate_config.pos_seal_activation_gate_enabled() { + 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()?; + + let mut segment_seals_all_duplicated = true; + for block_index in &new_chain { + let seal = + match BlockSeal::from_consensus_data(block_index.block_header().consensus_data()) { + Some(seal) => seal, + // The block does not yield a well-formed seal, so it cannot be + // classified as a duplicate and the segment is not fully + // duplicated. + None => return Ok(false), + }; + let duplicated = + match self.db_tx.get_seal_index_entry(&seal).map_err(BlockError::from)? { + Some(entry) => entry.blocks().len() > 1, + None => false, + }; + if !duplicated { + segment_seals_all_duplicated = false; + break; + } + } + + if !segment_seals_all_duplicated { + return Ok(false); + } + + log::info!( + "Not activating a chain whose new segment consists only of blocks reusing \ + already-known PoS consensus proofs" + ); + Ok(true) + } + #[log_error] pub fn persist_block(&mut self, block: &WithId) -> Result<(), BlockError> { if self.db_tx.block_exists(&block.get_id()).map_err(BlockError::from)? { @@ -1614,6 +1694,33 @@ 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, + } + } +} + #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct NonZeroPoolBalances { total_balance: Amount, diff --git a/chainstate/src/detail/chainstateref/seal_index.rs b/chainstate/src/detail/chainstateref/seal_index.rs index 81c589604b..b056fa1032 100644 --- a/chainstate/src/detail/chainstateref/seal_index.rs +++ b/chainstate/src/detail/chainstateref/seal_index.rs @@ -663,4 +663,33 @@ mod tests { db.expect_set_duplicate_seal_evidence().times(0); index_block_seal_if_enabled(&chainstate_config, &mut db, &block, TEST_HEIGHT).unwrap(); } + + #[test] + fn seal_activation_gate_is_disabled_by_default() { + assert!(!ChainstateConfig::default().pos_seal_activation_gate_enabled()); + } + + #[test] + fn seal_activation_gate_bypass_matrix() { + use super::ChainActivationContext; + + // Normal block processing: the gate applies unless the node is in the + // initial block download. + assert!( + !ChainActivationContext::BlockProcessing { + in_initial_block_download: false + } + .seal_activation_gate_bypassed() + ); + assert!( + ChainActivationContext::BlockProcessing { + in_initial_block_download: true + } + .seal_activation_gate_bypassed() + ); + + // The reorgs of the user-initiated block invalidation path are never + // gated (ground rule: the gate must never fire there). + assert!(ChainActivationContext::InvalidationRecovery.seal_activation_gate_bypassed()); + } } diff --git a/chainstate/src/detail/mod.rs b/chainstate/src/detail/mod.rs index b9e564cd68..cdb868921d 100644 --- a/chainstate/src/detail/mod.rs +++ b/chainstate/src/detail/mod.rs @@ -46,7 +46,7 @@ use chainstate_types::{ BlockIndex, BlockStatus, BlockValidationStage, EpochData, EpochStorageWrite, GenBlockIndexRef, PropertyQueryError, SealedStorageTag, TipStorageTag, pos_randomness::PoSRandomness, }; -use chainstateref::{ChainstateRef, ReorgError}; +use chainstateref::{ChainActivationContext, ChainstateRef, ReorgError}; use common::{ Uint256, chain::{ @@ -379,6 +379,7 @@ impl Chainstate block: &WithId, block_index: BlockIndex, checked_against_tip: Option>, + in_initial_block_download: bool, ) -> Result { let mut block_status = BlockStatus::new(); @@ -451,7 +452,13 @@ impl Chainstate // due to a bad parent. This will be done by the caller code. let result = { let _t = perf_timing::TimingGuard::stage(perf_timing::Stage::Connect); - chainstate_ref.activate_best_chain(&block_index, Some(block)) + chainstate_ref.activate_best_chain( + &block_index, + Some(block), + ChainActivationContext::BlockProcessing { + in_initial_block_download, + }, + ) }; { @@ -533,6 +540,8 @@ impl Chainstate .unwrap_or_else(|e| e.into_inner()) .remove(&block_id); + let in_initial_block_download = self.is_initial_block_download(); + // Perform block checks; `integrate_block_result` is `Result`, where the bool // indicates whether a reorg has occurred. let integrate_block_result = self.with_rw_tx( @@ -542,6 +551,7 @@ impl Chainstate &block, block_index.clone(), checked_against_tip, + in_initial_block_download, ) }, |attempt_number| { diff --git a/chainstate/src/interface/chainstate_interface_impl_delegation.rs b/chainstate/src/interface/chainstate_interface_impl_delegation.rs index a3e02d2995..cb4fbaabec 100644 --- a/chainstate/src/interface/chainstate_interface_impl_delegation.rs +++ b/chainstate/src/interface/chainstate_interface_impl_delegation.rs @@ -511,6 +511,7 @@ mod tests { enable_heavy_checks: Some(true), allow_checkpoints_mismatch: Default::default(), pos_seal_duplication_tracking: Default::default(), + pos_seal_activation_gate: Default::default(), }; let chainstate_storage = Store::new_empty().unwrap(); diff --git a/chainstate/test-suite/src/tests/bootstrap.rs b/chainstate/test-suite/src/tests/bootstrap.rs index 9d4d23d00e..cd89f63f20 100644 --- a/chainstate/test-suite/src/tests/bootstrap.rs +++ b/chainstate/test-suite/src/tests/bootstrap.rs @@ -747,6 +747,7 @@ fn check_reckless_mode( enable_heavy_checks: Default::default(), allow_checkpoints_mismatch: Default::default(), pos_seal_duplication_tracking: Default::default(), + pos_seal_activation_gate: Default::default(), }) .build(); // library default stays opt-in, matching master. diff --git a/chainstate/test-suite/src/tests/seal_duplication_tests.rs b/chainstate/test-suite/src/tests/seal_duplication_tests.rs index 223fe48941..b2debfcd3a 100644 --- a/chainstate/test-suite/src/tests/seal_duplication_tests.rs +++ b/chainstate/test-suite/src/tests/seal_duplication_tests.rs @@ -19,11 +19,13 @@ use rstest::rstest; use chainstate::{BlockSource, ChainstateConfig}; use chainstate_storage::{BlockchainStorageRead, Transactional as _}; -use chainstate_test_framework::{TestFramework, pos_mine}; +use chainstate_test_framework::{ + TestFramework, pos_mine, produce_kernel_signature as produce_block_reward_kernel_signature, +}; use chainstate_types::{BlockSeal, pos_randomness::PoSRandomness}; use common::{ chain::{ - Destination, PoolId, TxOutput, UtxoOutPoint, + Destination, OutPointSourceId, PoolId, TxOutput, UtxoOutPoint, block::{ConsensusData, timestamp::BlockTimestamp}, signature::inputsig::InputWitness, }, @@ -311,3 +313,158 @@ fn duplicate_seal_records_survive_reorg(#[case] seed: Seed) { vec![block_id_a, block_id_b] ); } + +// --------------------------------------------------------------- +// PoS seal activation gate +// +// The gate (disabled by default in this release) refuses to activate a chain +// whose newly activated segment consists entirely of blocks reusing +// already-known PoS consensus proofs. It never fires on a segment that +// contains at least one block with a fresh proof, and it is bypassed for the +// initial block download and for the reorgs of the user-initiated block +// invalidation path. + +fn gate_enabled_config() -> ChainstateConfig { + ChainstateConfig { + pos_seal_activation_gate: true.into(), + ..Default::default() + } +} + +/// Mine and process a fresh-proof PoS block on top of `parent_id`. The block is +/// mined from a timestamp well after the current framework time, so its seal +/// (which binds the timestamp) differs from the seals of all previously +/// processed blocks. +fn mine_and_process_fresh_proof_block( + rng: &mut impl CryptoRng, + tf: &mut TestFramework, + vrf_sk: &VRFPrivateKey, + stake_pool_outpoint: &UtxoOutPoint, + pool_id: PoolId, + staking_sk: &PrivateKey, + parent_id: Id, +) -> Id { + let staking_destination = Destination::PublicKey(PublicKey::from_private_key(staking_sk)); + let reward_outputs = + vec![TxOutput::ProduceBlockFromStake(staking_destination.clone(), pool_id)]; + + // The kernel of a PoS block that follows another PoS block is the + // `ProduceBlockFromStake` reward output of that previous block, not the + // original pool creation output (which the previous block's kernel + // consumed). + let kernel_outpoint = UtxoOutPoint::new(OutPointSourceId::BlockReward(parent_id.into()), 0); + let kernel_sig = produce_block_reward_kernel_signature( + tf, + rng, + staking_sk, + reward_outputs.as_slice(), + staking_destination, + parent_id.into(), + kernel_outpoint.clone(), + ); + + let chain_config = tf.chainstate.get_chain_config(); + let initial_randomness = chain_config.initial_randomness(); + let new_block_height = tf.best_block_index().block_height().next_height(); + let current_difficulty = calculate_new_target(tf, new_block_height).unwrap(); + let final_supply = chain_config.final_supply().unwrap(); + let pos_config = get_pos_chain_config(chain_config, new_block_height); + let initial_timestamp = + BlockTimestamp::from_time(tf.current_time()).add_int_seconds(120).unwrap(); + + let (pos_data, block_timestamp) = pos_mine( + rng, + &tf.storage.transaction_ro().unwrap(), + &pos_config, + initial_timestamp, + kernel_outpoint, + InputWitness::Standard(kernel_sig), + vrf_sk, + PoSRandomness::new(initial_randomness), + pool_id, + final_supply, + 1, + current_difficulty, + ) + .expect("should be able to mine"); + + let block = tf + .make_block_builder() + .with_parent(parent_id.into()) + .with_consensus_data(ConsensusData::PoS(pos_data.into())) + .with_block_signing_key(staking_sk.clone()) + .with_timestamp(block_timestamp) + .with_reward(reward_outputs) + .build(rng); + let block_id = block.get_id(); + tf.process_block(block, BlockSource::Local).unwrap(); + block_id +} + +/// Gate on: a duplicate-proof side twin extended by a block with a fresh proof +/// reorganizes the chain. The candidate segment contains a fresh proof, so the +/// gate must not fire and the duplicate-proof block is activated together with +/// its fresh child under the ordinary trust comparison. +#[rstest] +#[trace] +#[case(Seed::from_entropy())] +fn activation_gate_does_not_block_segment_with_fresh_proof(#[case] seed: Seed) { + let mut rng = make_seedable_rng(seed); + let (vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng(&mut rng, VRFKeyKind::Schnorrkel); + let (mut tf, stake_pool_outpoint, pool_id, staking_sk) = + setup_chain_with_stake_pool_with_chainstate_config(&mut rng, vrf_pk, gate_enabled_config()); + + let (_, _twin_main_id, twin_side_id) = process_two_blocks_with_same_seal( + &mut rng, + &mut tf, + &vrf_sk, + &stake_pool_outpoint, + pool_id, + &staking_sk, + ); + + let fresh_id = mine_and_process_fresh_proof_block( + &mut rng, + &mut tf, + &vrf_sk, + &stake_pool_outpoint, + pool_id, + &staking_sk, + twin_side_id, + ); + + assert_eq!( + tf.best_block_id(), + Id::::from(fresh_id) + ); +} + +/// Gate on: after the user-initiated invalidation of the mainchain twin, the +/// recovery re-activates the best remaining chain even though its segment is a +/// single duplicate-proof block (the gate is bypassed for the invalidation +/// recovery; without the bypass this activation would be refused). +#[rstest] +#[trace] +#[case(Seed::from_entropy())] +fn activation_gate_bypassed_for_invalidation_recovery(#[case] seed: Seed) { + let mut rng = make_seedable_rng(seed); + let (vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng(&mut rng, VRFKeyKind::Schnorrkel); + let (mut tf, stake_pool_outpoint, pool_id, staking_sk) = + setup_chain_with_stake_pool_with_chainstate_config(&mut rng, vrf_pk, gate_enabled_config()); + + let (_, twin_main_id, twin_side_id) = process_two_blocks_with_same_seal( + &mut rng, + &mut tf, + &vrf_sk, + &stake_pool_outpoint, + pool_id, + &staking_sk, + ); + + tf.chainstate.invalidate_block(&twin_main_id).unwrap(); + + assert_eq!( + tf.best_block_id(), + Id::::from(twin_side_id) + ); +} diff --git a/chainstate/test-suite/src/tests/syncing_tests.rs b/chainstate/test-suite/src/tests/syncing_tests.rs index 72908f28ce..3726c57c86 100644 --- a/chainstate/test-suite/src/tests/syncing_tests.rs +++ b/chainstate/test-suite/src/tests/syncing_tests.rs @@ -746,6 +746,7 @@ fn initial_block_download( enable_heavy_checks: Some(true), allow_checkpoints_mismatch: Default::default(), pos_seal_duplication_tracking: Default::default(), + pos_seal_activation_gate: Default::default(), }) .with_initial_time_since_genesis(2) .build(); diff --git a/node-lib/src/config_files/chainstate/mod.rs b/node-lib/src/config_files/chainstate/mod.rs index 637cc8ddf2..ecdf8b4688 100644 --- a/node-lib/src/config_files/chainstate/mod.rs +++ b/node-lib/src/config_files/chainstate/mod.rs @@ -50,6 +50,11 @@ pub struct ChainstateConfigFile { /// indexed and the evidence of a seal seen on more than one block will be recorded. /// Defaults to true. pub pos_seal_duplication_tracking: Option, + + /// 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. + /// Defaults to false. + pub pos_seal_activation_gate: Option, } impl From for ChainstateConfig { @@ -62,6 +67,7 @@ impl From for ChainstateConfig { enable_heavy_checks, allow_checkpoints_mismatch, pos_seal_duplication_tracking, + pos_seal_activation_gate, } = config_file; ChainstateConfig { @@ -72,6 +78,7 @@ impl From for ChainstateConfig { enable_heavy_checks, allow_checkpoints_mismatch, pos_seal_duplication_tracking: pos_seal_duplication_tracking.into(), + pos_seal_activation_gate: pos_seal_activation_gate.into(), } } } diff --git a/node-lib/src/config_files/mod.rs b/node-lib/src/config_files/mod.rs index 7d5d529906..7b1c2adb27 100644 --- a/node-lib/src/config_files/mod.rs +++ b/node-lib/src/config_files/mod.rs @@ -154,6 +154,7 @@ fn chainstate_config( enable_heavy_checks, allow_checkpoints_mismatch, pos_seal_duplication_tracking, + pos_seal_activation_gate, } = chainstate_config; let storage_backend = options.storage_backend.clone().unwrap_or(storage_backend); @@ -176,6 +177,8 @@ fn chainstate_config( // Intentionally not overridden by a CLI option: the config file is the only // control surface for this setting. pos_seal_duplication_tracking, + // Same as above: the config file is the only control surface for this setting. + pos_seal_activation_gate, }; ChainstateLauncherConfigFile { storage_backend, From b3d0c2fffdf8234a9c24f14c0863d96e2f5b1b1d Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sun, 15 Nov 2026 16:34:34 +0100 Subject: [PATCH 02/16] fix(chainstate): address seal gate review round 1 Extract the duplicate-proof segment classification into a testable function with unit tests pinning the refusal semantics (empty segment, fresh proof, unindexed proof, missing seal, at-cap index entry), refuse only non-empty segments explicitly, document the dependency of the gate on the seal duplication tracking with a startup warning when the gate is enabled without its index, and drop an unused parameter from the test mining helper. --- chainstate/src/config.rs | 3 +- chainstate/src/detail/chainstateref/mod.rs | 70 +++++---- .../src/detail/chainstateref/seal_index.rs | 135 +++++++++++++++++- chainstate/src/detail/mod.rs | 12 ++ .../src/tests/seal_duplication_tests.rs | 2 - node-lib/src/config_files/chainstate/mod.rs | 2 +- 6 files changed, 193 insertions(+), 31 deletions(-) diff --git a/chainstate/src/config.rs b/chainstate/src/config.rs index c1e4da2570..eea18fe45c 100644 --- a/chainstate/src/config.rs +++ b/chainstate/src/config.rs @@ -56,7 +56,8 @@ pub struct ChainstateConfig { /// 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. - /// Defaults to false. + /// Only effective together with `pos_seal_duplication_tracking`, which maintains the + /// index this gate classifies against. Defaults to false. pub pos_seal_activation_gate: PosSealActivationGate, } diff --git a/chainstate/src/detail/chainstateref/mod.rs b/chainstate/src/detail/chainstateref/mod.rs index d5da5de043..82820d5602 100644 --- a/chainstate/src/detail/chainstateref/mod.rs +++ b/chainstate/src/detail/chainstateref/mod.rs @@ -1503,36 +1503,23 @@ impl ChainstateRe }) .log_err()?; - let mut segment_seals_all_duplicated = true; - for block_index in &new_chain { - let seal = - match BlockSeal::from_consensus_data(block_index.block_header().consensus_data()) { - Some(seal) => seal, - // The block does not yield a well-formed seal, so it cannot be - // classified as a duplicate and the segment is not fully - // duplicated. - None => return Ok(false), - }; - let duplicated = - match self.db_tx.get_seal_index_entry(&seal).map_err(BlockError::from)? { - Some(entry) => entry.blocks().len() > 1, - None => false, - }; - if !duplicated { - segment_seals_all_duplicated = false; - break; - } + 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. Kept explicit so a future caller gets a silent no-op + // instead of a refusal. + return Ok(false); } - if !segment_seals_all_duplicated { - 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); } - log::info!( - "Not activating a chain whose new segment consists only of blocks reusing \ - already-known PoS consensus proofs" - ); - Ok(true) + Ok(false) } #[log_error] @@ -1721,6 +1708,37 @@ impl ChainActivationContext { } } +/// 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. +fn segment_seals_all_duplicated( + db_tx: &S, + new_chain: &[BlockIndex], +) -> Result { + 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, + }; + if !duplicated { + return Ok(false); + } + } + Ok(true) +} + #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct NonZeroPoolBalances { total_balance: Amount, diff --git a/chainstate/src/detail/chainstateref/seal_index.rs b/chainstate/src/detail/chainstateref/seal_index.rs index b056fa1032..6173904f1a 100644 --- a/chainstate/src/detail/chainstateref/seal_index.rs +++ b/chainstate/src/detail/chainstateref/seal_index.rs @@ -671,7 +671,7 @@ mod tests { #[test] fn seal_activation_gate_bypass_matrix() { - use super::ChainActivationContext; + use crate::detail::chainstateref::ChainActivationContext; // Normal block processing: the gate applies unless the node is in the // initial block download. @@ -692,4 +692,137 @@ mod tests { // gated (ground rule: the gate must never fire there). assert!(ChainActivationContext::InvalidationRecovery.seal_activation_gate_bypassed()); } + + /// Pin the load-bearing classification semantics of the PoS seal activation + /// gate: empty segments are never refused, any non-duplicate (fresh proof, + /// unindexed proof, or missing seal) breaks the refusal, an index entry at + /// the cap still classifies as duplicated, and a fully duplicated segment is + /// refused. + #[test] + fn segment_seals_all_duplicated_classification() { + use super::super::segment_seals_all_duplicated; + use chainstate_types::BlockStatus; + use common::{Uint256, chain::GenBlock}; + + let mut rng = + test_utils::random::make_seedable_rng(test_utils::random::Seed::from_entropy()); + let (vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng(&mut rng, VRFKeyKind::Schnorrkel); + + let chain_config = + ConfigBuilder::test_chain().epoch_length(NonZeroU64::new(3).unwrap()).build(); + + let block_a = make_pos_block( + H256::from_low_u64_be(1), + &vrf_sk, + &vrf_pk, + H256::from_low_u64_be(42), + ); + let block_a_twin = make_pos_block( + H256::from_low_u64_be(1), + &vrf_sk, + &vrf_pk, + H256::from_low_u64_be(42), + ); + let block_b = make_pos_block( + H256::from_low_u64_be(2), + &vrf_sk, + &vrf_pk, + H256::from_low_u64_be(43), + ); + assert_ne!(block_a.get_id(), block_a_twin.get_id()); + + let seal_a = BlockSeal::from_consensus_data(block_a.header().consensus_data()).unwrap(); + let index_a = block_a.get_id(); + let index_a_twin = block_a_twin.get_id(); + + // A non-PoS (or otherwise seal-less) block. + let plain_block = WithId::new( + common::chain::Block::new( + vec![], + chain_config.genesis_block_id(), + BlockTimestamp::from_int_seconds(1), + ConsensusData::None, + BlockReward::new(vec![]), + ) + .unwrap(), + ); + + let make_index = |block: &WithId| { + chainstate_types::BlockIndex::new( + block, + Uint256::ZERO, + chain_config.genesis_block_id(), + TEST_HEIGHT, + BlockTimestamp::from_int_seconds(1), + 0, + BlockStatus::new(), + ) + }; + + // An index entry at the cap: a seal seen on MAX_BLOCKS_PER_SEAL blocks + // still classifies every one of its blocks as duplicated. + let at_cap_entry = SealIndexEntry::new( + seal_a.clone(), + (0..MAX_BLOCKS_PER_SEAL.get()) + .map(|i| (if i == 0 { index_a } else { index_a_twin }, TEST_HEIGHT)) + .collect(), + ); + + // Case: an empty segment never refuses. + let mut db = MockStoreTxRw::new(); + assert!(!segment_seals_all_duplicated(&db, &[]).unwrap()); + + // Case: a single block with an unindexed (fresh) proof never refuses. + let mut db = MockStoreTxRw::new(); + db.expect_get_seal_index_entry().times(1).return_const(Ok(None)); + let segment = vec![make_index(&block_a)]; + assert!(!segment_seals_all_duplicated(&db, &segment).unwrap()); + + // Case: a single block whose seal has only one known block (its twin is + // unknown) never refuses. + let mut db = MockStoreTxRw::new(); + let expected_seal = seal_a.clone(); + db.expect_get_seal_index_entry() + .times(1) + .withf(move |seal: &BlockSeal| seal == &expected_seal) + .return_const(Ok(Some(SealIndexEntry::new( + seal_a.clone(), + vec![(index_a, TEST_HEIGHT)], + )))); + let segment = vec![make_index(&block_a)]; + assert!(!segment_seals_all_duplicated(&db, &segment).unwrap()); + + // Case: a block without a well-formed seal never refuses (fail-open). + let mut db = MockStoreTxRw::new(); + db.expect_get_seal_index_entry().times(0); + let segment = vec![make_index(&plain_block)]; + assert!(!segment_seals_all_duplicated(&db, &segment).unwrap()); + + // Case: a fully duplicated segment is refused; an index entry at the + // cap still classifies as duplicated. + let mut db = MockStoreTxRw::new(); + let expected_seal = seal_a.clone(); + let entry = at_cap_entry; + db.expect_get_seal_index_entry() + .times(1) + .withf(move |seal: &BlockSeal| seal == &expected_seal) + .return_const(Ok(Some(entry))); + let segment = vec![make_index(&block_a)]; + assert!(segment_seals_all_duplicated(&db, &segment).unwrap()); + + // Case: one duplicate and one fresh block in the same segment never + // refuses (the fresh block carries the ordinary trust comparison). + let mut db = MockStoreTxRw::new(); + let expected_seal = seal_a.clone(); + db.expect_get_seal_index_entry() + .times(1) + .withf(move |seal: &BlockSeal| seal == &expected_seal) + .return_const(Ok(Some(SealIndexEntry::new( + seal_a.clone(), + vec![(index_a, TEST_HEIGHT), (index_a_twin, TEST_HEIGHT)], + )))); + db.expect_get_seal_index_entry().times(1).return_const(Ok(None)); + let segment = vec![make_index(&block_a), make_index(&block_b)]; + assert!(!segment_seals_all_duplicated(&db, &segment).unwrap()); + } } diff --git a/chainstate/src/detail/mod.rs b/chainstate/src/detail/mod.rs index cdb868921d..2c3c3f109c 100644 --- a/chainstate/src/detail/mod.rs +++ b/chainstate/src/detail/mod.rs @@ -244,6 +244,18 @@ impl Chainstate time_getter: TimeGetter, shutdown_initiated_rx: Option>, ) -> Self { + if chainstate_config.pos_seal_activation_gate_enabled() + && !chainstate_config.pos_seal_duplication_tracking_enabled() + { + // The gate classifies activation segments against the index that the + // seal duplication tracking maintains; without the tracking, the gate + // has nothing to look up and would silently never fire. + log::warn!( + "The PoS seal activation gate is enabled while the PoS seal duplication \ + tracking is disabled; the gate has no effect without its index" + ); + } + let orphan_blocks = OrphansProxy::new(*chainstate_config.max_orphan_blocks); let subsystem_events = EventsController::new(); let rpc_events = broadcaster::Broadcaster::new(); diff --git a/chainstate/test-suite/src/tests/seal_duplication_tests.rs b/chainstate/test-suite/src/tests/seal_duplication_tests.rs index b2debfcd3a..b0b003b718 100644 --- a/chainstate/test-suite/src/tests/seal_duplication_tests.rs +++ b/chainstate/test-suite/src/tests/seal_duplication_tests.rs @@ -339,7 +339,6 @@ fn mine_and_process_fresh_proof_block( rng: &mut impl CryptoRng, tf: &mut TestFramework, vrf_sk: &VRFPrivateKey, - stake_pool_outpoint: &UtxoOutPoint, pool_id: PoolId, staking_sk: &PrivateKey, parent_id: Id, @@ -427,7 +426,6 @@ fn activation_gate_does_not_block_segment_with_fresh_proof(#[case] seed: Seed) { &mut rng, &mut tf, &vrf_sk, - &stake_pool_outpoint, pool_id, &staking_sk, twin_side_id, diff --git a/node-lib/src/config_files/chainstate/mod.rs b/node-lib/src/config_files/chainstate/mod.rs index ecdf8b4688..4eb497b3a0 100644 --- a/node-lib/src/config_files/chainstate/mod.rs +++ b/node-lib/src/config_files/chainstate/mod.rs @@ -53,7 +53,7 @@ pub struct ChainstateConfigFile { /// 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. - /// Defaults to false. + /// Only effective together with `pos_seal_duplication_tracking`. Defaults to false. pub pos_seal_activation_gate: Option, } From 8fd16a556759e808c5419002fe68396bca14cf65 Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sun, 15 Nov 2026 16:52:58 +0100 Subject: [PATCH 03/16] test(chainstate): harden seal gate twin and refine comments Differentiate the classification test's twin block by parent instead of relying on the randomization of the VRF proof bytes, drop an unused test import, and refine the empty-segment comment wording. --- chainstate/src/detail/chainstateref/mod.rs | 4 ++-- chainstate/src/detail/chainstateref/seal_index.rs | 7 +++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/chainstate/src/detail/chainstateref/mod.rs b/chainstate/src/detail/chainstateref/mod.rs index 82820d5602..a7def4ebc3 100644 --- a/chainstate/src/detail/chainstateref/mod.rs +++ b/chainstate/src/detail/chainstateref/mod.rs @@ -1506,8 +1506,8 @@ impl ChainstateRe 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. Kept explicit so a future caller gets a silent no-op - // instead of a refusal. + // non-empty. The gate declines to refuse here; the ordinary path + // below then enforces its own empty-chain invariant. return Ok(false); } diff --git a/chainstate/src/detail/chainstateref/seal_index.rs b/chainstate/src/detail/chainstateref/seal_index.rs index 6173904f1a..a9e2e561a0 100644 --- a/chainstate/src/detail/chainstateref/seal_index.rs +++ b/chainstate/src/detail/chainstateref/seal_index.rs @@ -702,7 +702,7 @@ mod tests { fn segment_seals_all_duplicated_classification() { use super::super::segment_seals_all_duplicated; use chainstate_types::BlockStatus; - use common::{Uint256, chain::GenBlock}; + use common::Uint256; let mut rng = test_utils::random::make_seedable_rng(test_utils::random::Seed::from_entropy()); @@ -717,8 +717,11 @@ mod tests { &vrf_pk, H256::from_low_u64_be(42), ); + // The twin differs structurally (different parent) so the different + // block id does not rely on the randomization of the VRF proof bytes; + // the seal (pool id + VRF output) is identical, as required. let block_a_twin = make_pos_block( - H256::from_low_u64_be(1), + H256::from_low_u64_be(2), &vrf_sk, &vrf_pk, H256::from_low_u64_be(42), From 360278212fdc22a26a964f7a864704502ca5a45f Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sun, 15 Nov 2026 16:53:56 +0100 Subject: [PATCH 04/16] test(chainstate): drop an unused mut in the seal gate test --- chainstate/src/detail/chainstateref/seal_index.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chainstate/src/detail/chainstateref/seal_index.rs b/chainstate/src/detail/chainstateref/seal_index.rs index a9e2e561a0..e94fa6f80f 100644 --- a/chainstate/src/detail/chainstateref/seal_index.rs +++ b/chainstate/src/detail/chainstateref/seal_index.rs @@ -771,8 +771,8 @@ mod tests { .collect(), ); - // Case: an empty segment never refuses. - let mut db = MockStoreTxRw::new(); + // Case: an empty segment never refuses (no lookups happen). + let db = MockStoreTxRw::new(); assert!(!segment_seals_all_duplicated(&db, &[]).unwrap()); // Case: a single block with an unindexed (fresh) proof never refuses. From 1739c1c5a123f4fee1810076f05956cee892f24d Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sun, 15 Nov 2026 18:49:08 +0100 Subject: [PATCH 05/16] test(chainstate): add the PoS seal adversarial suite Cover the seal activation gate and the equivocation-containment properties at the chainstate level: tip-equivocation races converge via fresh proofs, a withheld variant released late never displaces the incumbent chain, partition halves keep their own valid chains without content-based canonicalization, honest resealing at the same height with different timestamps is never flagged, variant flooding stops at the index cap while every variant stays stored and fully valid, and same-pool chains keep progressing with decayed trust. --- .../src/tests/seal_duplication_tests.rs | 546 +++++++++++++++++- 1 file changed, 541 insertions(+), 5 deletions(-) diff --git a/chainstate/test-suite/src/tests/seal_duplication_tests.rs b/chainstate/test-suite/src/tests/seal_duplication_tests.rs index b0b003b718..1cce79aaa8 100644 --- a/chainstate/test-suite/src/tests/seal_duplication_tests.rs +++ b/chainstate/test-suite/src/tests/seal_duplication_tests.rs @@ -158,6 +158,158 @@ fn process_two_blocks_with_same_seal( (seal, block_id_1, block_id_2) } +/// Mine and process two same-seal PoS blocks on top of the given parent (both +/// fully valid, the second one a side block of the first one), mirroring +/// `process_two_blocks_with_same_seal` but with an explicit parent, so twins +/// can be released on side branches and below the current tip. +#[allow(clippy::too_many_arguments)] +fn mine_and_process_same_seal_twins_on_parent( + rng: &mut impl CryptoRng, + tf: &mut TestFramework, + vrf_sk: &VRFPrivateKey, + stake_pool_outpoint: &UtxoOutPoint, + pool_id: PoolId, + staking_sk: &PrivateKey, + parent_id: Id, + timestamp_offset_seconds: u64, + process_second: bool, +) -> ( + BlockSeal, + Id, + Id, + Option, +) { + let staking_destination = Destination::PublicKey(PublicKey::from_private_key(staking_sk)); + let reward_outputs = + vec![TxOutput::ProduceBlockFromStake(staking_destination.clone(), pool_id)]; + + // The kernel depends on the parent: a PoS parent's stake lives in its + // `ProduceBlockFromStake` reward output (the pool creation output was + // consumed by the first PoS block of the chain), while a non-PoS parent + // leaves the pool creation output in place. + let parent_reward_outpoint = + UtxoOutPoint::new(OutPointSourceId::BlockReward(parent_id.into()), 0); + let parent_reward_outputs = tf.outputs_from_genblock(parent_id.into()); + let parent_is_pos = parent_reward_outputs + .get(&OutPointSourceId::BlockReward(parent_id.into())) + .map(|outputs| !outputs.is_empty()) + .unwrap_or(false); + + let chain_config = tf.chainstate.get_chain_config(); + let parent_height = tf + .storage + .transaction_ro() + .unwrap() + .get_block_index(&parent_id) + .unwrap() + .expect("parent block index is present") + .block_height(); + let new_block_height = parent_height.next_height(); + let pos_randomness = tf.pos_randomness_for_height(&new_block_height); + let current_difficulty = calculate_new_target(tf, new_block_height).unwrap(); + let final_supply = chain_config.final_supply().unwrap(); + let pos_config = get_pos_chain_config(chain_config, new_block_height); + let initial_timestamp = BlockTimestamp::from_time(tf.current_time()) + .add_int_seconds(timestamp_offset_seconds) + .unwrap(); + let epoch_index = chain_config.epoch_index_from_height(&new_block_height); + + let (kernel_sig, kernel_outpoint) = if parent_is_pos { + let kernel_outpoint = parent_reward_outpoint.clone(); + let kernel_sig = produce_block_reward_kernel_signature( + tf, + rng, + staking_sk, + reward_outputs.as_slice(), + staking_destination.clone(), + parent_id.into(), + kernel_outpoint.clone(), + ); + (kernel_sig, kernel_outpoint) + } else { + let kernel_outpoint = stake_pool_outpoint.clone(); + let kernel_sig = produce_kernel_signature( + rng, + tf, + staking_sk, + reward_outputs.as_slice(), + staking_destination.clone(), + kernel_outpoint.clone(), + ); + (kernel_sig, kernel_outpoint) + }; + + let (pos_data_1, block_timestamp_1) = pos_mine( + rng, + &tf.storage.transaction_ro().unwrap(), + &pos_config, + initial_timestamp, + kernel_outpoint.clone(), + InputWitness::Standard(kernel_sig.clone()), + vrf_sk, + pos_randomness, + pool_id, + final_supply, + epoch_index, + current_difficulty, + ) + .expect("should be able to mine"); + + let (pos_data_2, block_timestamp_2) = pos_mine( + rng, + &tf.storage.transaction_ro().unwrap(), + &pos_config, + initial_timestamp, + kernel_outpoint, + InputWitness::Standard(kernel_sig), + vrf_sk, + pos_randomness, + pool_id, + final_supply, + epoch_index, + current_difficulty, + ) + .expect("should be able to mine"); + + assert_eq!(block_timestamp_1, block_timestamp_2); + + let consensus_data_1 = ConsensusData::PoS(pos_data_1.into()); + let consensus_data_2 = ConsensusData::PoS(pos_data_2.into()); + let seal = BlockSeal::from_consensus_data(&consensus_data_1).unwrap(); + assert_eq!( + BlockSeal::from_consensus_data(&consensus_data_2), + Some(seal.clone()) + ); + + let block_1 = tf + .make_block_builder() + .with_parent(parent_id.into()) + .with_consensus_data(consensus_data_1) + .with_block_signing_key(staking_sk.clone()) + .with_timestamp(block_timestamp_1) + .with_reward(reward_outputs.clone()) + .build(rng); + let block_id_1 = block_1.get_id(); + tf.process_block(block_1, BlockSource::Local).unwrap(); + + let block_2 = tf + .make_block_builder() + .with_parent(parent_id.into()) + .with_consensus_data(consensus_data_2) + .with_block_signing_key(staking_sk.clone()) + .with_timestamp(block_timestamp_2) + .with_reward(reward_outputs) + .build(rng); + let block_id_2 = block_2.get_id(); + assert_ne!(block_id_1, block_id_2); + if process_second { + tf.process_block(block_2.clone(), BlockSource::Local).unwrap(); + (seal, block_id_1, block_id_2, None) + } else { + (seal, block_id_1, block_id_2, Some(block_2)) + } +} + // Create a chain genesis <- block_1(StakePool), then process two blocks (block_2a and // block_2b) that carry the same PoS seal (same pool and same VRF output) on top of // block_1. Both blocks are fully valid; block_2b remains a side block. @@ -342,6 +494,7 @@ fn mine_and_process_fresh_proof_block( pool_id: PoolId, staking_sk: &PrivateKey, parent_id: Id, + timestamp_offset_seconds: u64, ) -> Id { let staking_destination = Destination::PublicKey(PublicKey::from_private_key(staking_sk)); let reward_outputs = @@ -363,13 +516,15 @@ fn mine_and_process_fresh_proof_block( ); let chain_config = tf.chainstate.get_chain_config(); - let initial_randomness = chain_config.initial_randomness(); let new_block_height = tf.best_block_index().block_height().next_height(); + let epoch_index = chain_config.epoch_index_from_height(&new_block_height); + let pos_randomness = tf.pos_randomness_for_height(&new_block_height); let current_difficulty = calculate_new_target(tf, new_block_height).unwrap(); let final_supply = chain_config.final_supply().unwrap(); let pos_config = get_pos_chain_config(chain_config, new_block_height); - let initial_timestamp = - BlockTimestamp::from_time(tf.current_time()).add_int_seconds(120).unwrap(); + let initial_timestamp = BlockTimestamp::from_time(tf.current_time()) + .add_int_seconds(timestamp_offset_seconds) + .unwrap(); let (pos_data, block_timestamp) = pos_mine( rng, @@ -379,10 +534,10 @@ fn mine_and_process_fresh_proof_block( kernel_outpoint, InputWitness::Standard(kernel_sig), vrf_sk, - PoSRandomness::new(initial_randomness), + pos_randomness, pool_id, final_supply, - 1, + epoch_index, current_difficulty, ) .expect("should be able to mine"); @@ -429,6 +584,7 @@ fn activation_gate_does_not_block_segment_with_fresh_proof(#[case] seed: Seed) { pool_id, &staking_sk, twin_side_id, + 120, ); assert_eq!( @@ -466,3 +622,383 @@ fn activation_gate_bypassed_for_invalidation_recovery(#[case] seed: Seed) { Id::::from(twin_side_id) ); } + +// --------------------------------------------------------------- +// S5 — adversarial suite for the PoS seal activation gate +// +// Scenarios derived from the design note's attack narratives: tip +// equivocation races, withheld-variant release, partition halves, honest +// resealing at the same height, and the variant cap. The gate must never +// fire on segments that contain at least one fresh proof, must never +// prevent the storage or retrieval of any variant, and must leave the +// ordinary trust comparison in charge of every race. +// --------------------------------------------------------------- + +/// Tip equivocation race: the pool equivocates at two consecutive heights and +/// both branches grow. The branch that collects a fresh proof first wins, the +/// loser's twin becomes a side block, and the gate never fires (every winning +/// segment contains the fresh proof that decided the race). Evidence is +/// recorded for both equivocated proofs. +#[rstest] +#[trace] +#[case(Seed::from_entropy())] +fn equivocation_race_converges_via_fresh_proofs(#[case] seed: Seed) { + let mut rng = make_seedable_rng(seed); + let (vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng(&mut rng, VRFKeyKind::Schnorrkel); + let (mut tf, stake_pool_outpoint, pool_id, staking_sk) = + setup_chain_with_stake_pool_with_chainstate_config(&mut rng, vrf_pk, gate_enabled_config()); + + let (seal2, twin_main, twin_side) = process_two_blocks_with_same_seal( + &mut rng, + &mut tf, + &vrf_sk, + &stake_pool_outpoint, + pool_id, + &staking_sk, + ); + + // The side branch collects a fresh proof and wins the race. + let fresh_on_side = mine_and_process_fresh_proof_block( + &mut rng, + &mut tf, + &vrf_sk, + pool_id, + &staking_sk, + twin_side, + 60, + ); + assert_eq!( + tf.best_block_id(), + Id::::from(fresh_on_side) + ); + + // The pool equivocates again on the new tip: the first-processed twin wins + // the next round under the ordinary trust comparison. + let (seal3, twin3_main, _twin3_side, _unprocessed3) = + mine_and_process_same_seal_twins_on_parent( + &mut rng, + &mut tf, + &vrf_sk, + &stake_pool_outpoint, + pool_id, + &staking_sk, + fresh_on_side, + 100, + true, + ); + assert_eq!( + tf.best_block_id(), + Id::::from(twin3_main) + ); + + // Both equivocated proofs carry their own evidence record. + let db_tx = tf.storage.transaction_ro().unwrap(); + assert_eq!( + db_tx.get_seal_index_entry(&seal2).unwrap().unwrap().blocks().len(), + 2 + ); + assert_eq!( + db_tx.get_seal_index_entry(&seal3).unwrap().unwrap().blocks().len(), + 2 + ); + assert!(db_tx.get_duplicate_seal_evidence(&seal2).unwrap().is_some()); + assert!(db_tx.get_duplicate_seal_evidence(&seal3).unwrap().is_some()); +} + +/// Withheld-variant release: a duplicate variant released after the incumbent +/// chain has moved on never displaces the incumbent (its segment has lower +/// trust), stays stored, and keeps its evidence record. +#[rstest] +#[trace] +#[case(Seed::from_entropy())] +fn withheld_variant_release_keeps_incumbent_stable(#[case] seed: Seed) { + let mut rng = make_seedable_rng(seed); + let (vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng(&mut rng, VRFKeyKind::Schnorrkel); + let (mut tf, stake_pool_outpoint, pool_id, staking_sk) = + setup_chain_with_stake_pool_with_chainstate_config(&mut rng, vrf_pk, gate_enabled_config()); + + // Mine the twins, but withhold the second one (do not process it yet). + let withheld_parent = tf + .best_block_id() + .classify(tf.chainstate.get_chain_config()) + .chain_block_id() + .unwrap(); + let (seal, twin_main, _twin_side, withheld_block) = mine_and_process_same_seal_twins_on_parent( + &mut rng, + &mut tf, + &vrf_sk, + &stake_pool_outpoint, + pool_id, + &staking_sk, + withheld_parent, + 0, + false, + ); + let withheld_id = withheld_block.as_ref().map(|b| b.get_id()).unwrap(); + + // The incumbent chain extends with a fresh proof. + let fresh_id = mine_and_process_fresh_proof_block( + &mut rng, + &mut tf, + &vrf_sk, + pool_id, + &staking_sk, + twin_main, + 60, + ); + + // The withheld variant is released: it is stored and its evidence exists, + // but it never displaces the incumbent chain. + tf.process_block(withheld_block.unwrap(), BlockSource::Local).unwrap(); + + assert_eq!( + tf.best_block_id(), + Id::::from(fresh_id) + ); + + let db_tx = tf.storage.transaction_ro().unwrap(); + let index_entry = db_tx.get_seal_index_entry(&seal).unwrap().unwrap(); + assert_eq!(index_entry.blocks().len(), 2); + let stored = db_tx.get_block(&withheld_id).unwrap().unwrap(); + assert_eq!(stored.get_id(), withheld_id); + assert!(db_tx.get_duplicate_seal_evidence(&seal).unwrap().is_some()); +} + +/// Partition halves: two identical nodes (same keys, same pool) process the +/// two variants of an equivocation in opposite orders, with each node's +/// variants being distinct blocks. The interim tips differ (there is no +/// content-based canonicalization), every variant stays stored in its half +/// (no first-seen drop), and both halves record the evidence. The halves keep +/// their own valid chains: convergence comes from fresh proofs of other pools +/// (see `equivocation_race_converges_via_fresh_proofs`). +#[rstest] +#[trace] +#[case(Seed::from_entropy())] +fn partition_halves_stay_valid_without_canonicalization(#[case] seed: Seed) { + let (vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng( + &mut test_utils::random::make_seedable_rng(seed), + VRFKeyKind::Schnorrkel, + ); + + // Two identical setups (same seed, same keys, same pool). + let mut rng1 = make_seedable_rng(seed); + let mut rng2 = make_seedable_rng(seed); + let (mut tf1, stake_pool_outpoint1, pool_id1, staking_sk1) = + setup_chain_with_stake_pool_with_chainstate_config( + &mut rng1, + vrf_pk.clone(), + gate_enabled_config(), + ); + let (mut tf2, stake_pool_outpoint2, pool_id2, staking_sk2) = + setup_chain_with_stake_pool_with_chainstate_config( + &mut rng2, + vrf_pk, + gate_enabled_config(), + ); + + // The two equivocations use different randomness streams, so the halves + // hold different blocks (different ids) that share the same proof. + let parent_1 = tf1 + .best_block_id() + .classify(tf1.chainstate.get_chain_config()) + .chain_block_id() + .unwrap(); + let (seal_1, main_1, side_1) = { + let mut rng = make_seedable_rng(seed); + let (seal, main, side) = process_two_blocks_with_same_seal( + &mut rng, + &mut tf1, + &vrf_sk, + &stake_pool_outpoint1, + pool_id1, + &staking_sk1, + ); + (seal, main, side) + }; + let parent_2 = tf2 + .best_block_id() + .classify(tf2.chainstate.get_chain_config()) + .chain_block_id() + .unwrap(); + let (seal_2, main_2, side_2) = { + // A different randomness stream: the proofs differ from half 1's, so + // the variants are different blocks (the seal itself is identical, + // since the transcript does not involve randomness). + let mut rng = make_seedable_rng(Seed::from_u64(seed.0 ^ 0xA5A5_A5A5)); + let (seal, main, side) = process_two_blocks_with_same_seal( + &mut rng, + &mut tf2, + &vrf_sk, + &stake_pool_outpoint2, + pool_id2, + &staking_sk2, + ); + (seal, main, side) + }; + assert_eq!(seal_1, seal_2); + assert_ne!(main_1, main_2); + + // Each half keeps its own first-processed variant as the tip: the choice + // is arrival-order based, never content-based. + assert_eq!( + tf1.best_block_id(), + Id::::from(main_1) + ); + assert_eq!( + tf2.best_block_id(), + Id::::from(main_2) + ); + + // Both halves recorded the evidence and stored every variant. + for (db_tx, main, side) in [ + (tf1.storage.transaction_ro().unwrap(), main_1, side_1), + (tf2.storage.transaction_ro().unwrap(), main_2, side_2), + ] { + let index_entry = db_tx.get_seal_index_entry(&seal_1).unwrap().unwrap(); + assert_eq!(index_entry.blocks().len(), 2); + assert!(db_tx.get_block(&main).unwrap().is_some()); + assert!(db_tx.get_block(&side).unwrap().is_some()); + assert!(db_tx.get_duplicate_seal_evidence(&seal_1).unwrap().is_some()); + } +} + +/// Variant cap: an equivocating pool floods the node with same-proof variants. +/// The index entry stops at the cap, the evidence record stays bounded, every +/// variant stays stored and fully valid, and the first-processed variant is +/// never displaced. +#[rstest] +#[trace] +#[case(Seed::from_entropy())] +fn duplicate_proof_variants_are_capped_but_all_stored(#[case] seed: Seed) { + let mut rng = make_seedable_rng(seed); + let (vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng(&mut rng, VRFKeyKind::Schnorrkel); + let (mut tf, stake_pool_outpoint, pool_id, staking_sk) = + setup_chain_with_stake_pool_with_chainstate_config(&mut rng, vrf_pk, gate_enabled_config()); + + let staking_destination = Destination::PublicKey(PublicKey::from_private_key(&staking_sk)); + let reward_outputs = + vec![TxOutput::ProduceBlockFromStake(staking_destination.clone(), pool_id)]; + + let kernel_sig = produce_kernel_signature( + &mut rng, + &tf, + &staking_sk, + reward_outputs.as_slice(), + staking_destination, + stake_pool_outpoint.clone(), + ); + + let chain_config = tf.chainstate.get_chain_config(); + let initial_randomness = chain_config.initial_randomness(); + let new_block_height = tf.best_block_index().block_height().next_height(); + let current_difficulty = calculate_new_target(&tf, new_block_height).unwrap(); + let final_supply = chain_config.final_supply().unwrap(); + let pos_config = get_pos_chain_config(chain_config, new_block_height); + let initial_timestamp = BlockTimestamp::from_time(tf.current_time()); + let parent_id = tf + .best_block_id() + .classify(tf.chainstate.get_chain_config()) + .chain_block_id() + .unwrap(); + + // Mine and process one more variant than the cap (the seal index cap is 8 + // entries per proof; see `MAX_BLOCKS_PER_SEAL` in the chainstate crate). + let variant_count = 8 + 1; + let mut variant_ids = Vec::new(); + let mut seal = None; + for _ in 0..variant_count { + let (pos_data, block_timestamp) = pos_mine( + &mut rng, + &tf.storage.transaction_ro().unwrap(), + &pos_config, + initial_timestamp, + stake_pool_outpoint.clone(), + InputWitness::Standard(kernel_sig.clone()), + &vrf_sk, + PoSRandomness::new(initial_randomness), + pool_id, + final_supply, + 1, + current_difficulty, + ) + .expect("should be able to mine"); + + let consensus_data = ConsensusData::PoS(pos_data.into()); + let this_seal = BlockSeal::from_consensus_data(&consensus_data).unwrap(); + match &seal { + Some(s) => assert_eq!(s, &this_seal), + None => seal = Some(this_seal), + } + + let block = tf + .make_block_builder() + .with_parent(parent_id.into()) + .with_consensus_data(consensus_data) + .with_block_signing_key(staking_sk.clone()) + .with_timestamp(block_timestamp) + .with_reward(reward_outputs.clone()) + .build(&mut rng); + let block_id = block.get_id(); + tf.process_block(block, BlockSource::Local).unwrap(); + variant_ids.push(block_id); + } + let seal = seal.unwrap(); + + // The first-processed variant remains the best chain. + assert_eq!( + tf.best_block_id(), + Id::::from(variant_ids[0]) + ); + + // The index entry is capped; every variant is stored; the evidence exists. + let db_tx = tf.storage.transaction_ro().unwrap(); + let index_entry = db_tx.get_seal_index_entry(&seal).unwrap().unwrap(); + assert_eq!(index_entry.blocks().len(), 8); + for block_id in &variant_ids { + assert!( + index_entry.blocks().iter().any(|(id, _)| id == block_id) + || db_tx.get_block(block_id).unwrap().is_some(), + "variant {block_id} must be known to the node", + ); + } + assert!(db_tx.get_duplicate_seal_evidence(&seal).unwrap().is_some()); +} + +/// A same-pool chain keeps progressing (with decayed trust): the asymptote +/// penalizes same-pool repeats in the trust comparison but never makes such +/// blocks invalid or their chains stuck. +#[rstest] +#[trace] +#[case(Seed::from_entropy())] +fn same_pool_chain_keeps_progressing(#[case] seed: Seed) { + let mut rng = make_seedable_rng(seed); + let (vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng(&mut rng, VRFKeyKind::Schnorrkel); + let (mut tf, stake_pool_outpoint, pool_id, staking_sk) = + setup_chain_with_stake_pool_with_chainstate_config(&mut rng, vrf_pk, gate_enabled_config()); + + let (_, twin_main, twin_side) = process_two_blocks_with_same_seal( + &mut rng, + &mut tf, + &vrf_sk, + &stake_pool_outpoint, + pool_id, + &staking_sk, + ); + + // Two consecutive same-pool blocks on the winning branch: the tip advances + // with each one. + let h3 = mine_and_process_fresh_proof_block( + &mut rng, + &mut tf, + &vrf_sk, + pool_id, + &staking_sk, + twin_main, + 1, + ); + assert_eq!(tf.best_block_id(), Id::::from(h3)); + + let h4 = + mine_and_process_fresh_proof_block(&mut rng, &mut tf, &vrf_sk, pool_id, &staking_sk, h3, 2); + assert_eq!(tf.best_block_id(), Id::::from(h4)); +} From 0cf3330068283404f28e84c8b119f67483176617 Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sun, 15 Nov 2026 18:50:52 +0100 Subject: [PATCH 06/16] test(chainstate): fix unused variables in the seal tests --- chainstate/test-suite/src/tests/seal_duplication_tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chainstate/test-suite/src/tests/seal_duplication_tests.rs b/chainstate/test-suite/src/tests/seal_duplication_tests.rs index 1cce79aaa8..3eaaa5560a 100644 --- a/chainstate/test-suite/src/tests/seal_duplication_tests.rs +++ b/chainstate/test-suite/src/tests/seal_duplication_tests.rs @@ -648,7 +648,7 @@ fn equivocation_race_converges_via_fresh_proofs(#[case] seed: Seed) { let (mut tf, stake_pool_outpoint, pool_id, staking_sk) = setup_chain_with_stake_pool_with_chainstate_config(&mut rng, vrf_pk, gate_enabled_config()); - let (seal2, twin_main, twin_side) = process_two_blocks_with_same_seal( + let (seal2, _twin_main, twin_side) = process_two_blocks_with_same_seal( &mut rng, &mut tf, &vrf_sk, @@ -798,7 +798,7 @@ fn partition_halves_stay_valid_without_canonicalization(#[case] seed: Seed) { // The two equivocations use different randomness streams, so the halves // hold different blocks (different ids) that share the same proof. - let parent_1 = tf1 + let _parent_1 = tf1 .best_block_id() .classify(tf1.chainstate.get_chain_config()) .chain_block_id() @@ -815,7 +815,7 @@ fn partition_halves_stay_valid_without_canonicalization(#[case] seed: Seed) { ); (seal, main, side) }; - let parent_2 = tf2 + let _parent_2 = tf2 .best_block_id() .classify(tf2.chainstate.get_chain_config()) .chain_block_id() From 5df457a86d3f8586c98541935b867dfd27a3643a Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sun, 15 Nov 2026 18:52:21 +0100 Subject: [PATCH 07/16] test(chainstate): fix clippy lints in the seal tests --- chainstate/test-suite/src/tests/seal_duplication_tests.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/chainstate/test-suite/src/tests/seal_duplication_tests.rs b/chainstate/test-suite/src/tests/seal_duplication_tests.rs index 3eaaa5560a..c51a2125e0 100644 --- a/chainstate/test-suite/src/tests/seal_duplication_tests.rs +++ b/chainstate/test-suite/src/tests/seal_duplication_tests.rs @@ -192,8 +192,7 @@ fn mine_and_process_same_seal_twins_on_parent( let parent_reward_outputs = tf.outputs_from_genblock(parent_id.into()); let parent_is_pos = parent_reward_outputs .get(&OutPointSourceId::BlockReward(parent_id.into())) - .map(|outputs| !outputs.is_empty()) - .unwrap_or(false); + .is_some_and(|outputs| !outputs.is_empty()); let chain_config = tf.chainstate.get_chain_config(); let parent_height = tf @@ -976,7 +975,7 @@ fn same_pool_chain_keeps_progressing(#[case] seed: Seed) { let (mut tf, stake_pool_outpoint, pool_id, staking_sk) = setup_chain_with_stake_pool_with_chainstate_config(&mut rng, vrf_pk, gate_enabled_config()); - let (_, twin_main, twin_side) = process_two_blocks_with_same_seal( + let (_, twin_main, _twin_side) = process_two_blocks_with_same_seal( &mut rng, &mut tf, &vrf_sk, From 39052bd26ae3fa3591fd85228859b271233ae471 Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sun, 15 Nov 2026 19:12:59 +0100 Subject: [PATCH 08/16] test(chainstate): address seal suite review round 1 Re-add the honest-reseal test (silently lost in the partition rewrite) with the negative evidence assertions, pin the variant-cap boundedness (index arrival order, ninth variant stored but unindexed, evidence capped), pin the seal-index arrival order in the partition halves, use a 90-second reseal margin inside the future-timestamp limit, assert the twin VRF-proof inequality, and document the parent PoS-ness heuristic. --- .../src/tests/seal_duplication_tests.rs | 166 +++++++++++++++++- 1 file changed, 159 insertions(+), 7 deletions(-) diff --git a/chainstate/test-suite/src/tests/seal_duplication_tests.rs b/chainstate/test-suite/src/tests/seal_duplication_tests.rs index c51a2125e0..365937048d 100644 --- a/chainstate/test-suite/src/tests/seal_duplication_tests.rs +++ b/chainstate/test-suite/src/tests/seal_duplication_tests.rs @@ -186,7 +186,9 @@ fn mine_and_process_same_seal_twins_on_parent( // The kernel depends on the parent: a PoS parent's stake lives in its // `ProduceBlockFromStake` reward output (the pool creation output was // consumed by the first PoS block of the chain), while a non-PoS parent - // leaves the pool creation output in place. + // leaves the pool creation output in place. The PoS-ness of the parent is + // detected via its block-reward outputs, which is exact for every parent + // shape used in this suite. let parent_reward_outpoint = UtxoOutPoint::new(OutPointSourceId::BlockReward(parent_id.into()), 0); let parent_reward_outputs = tf.outputs_from_genblock(parent_id.into()); @@ -271,6 +273,9 @@ fn mine_and_process_same_seal_twins_on_parent( .expect("should be able to mine"); assert_eq!(block_timestamp_1, block_timestamp_2); + // The VRF proofs differ (they are randomized per signing), so the blocks + // are distinct while sharing the seal. + assert_ne!(pos_data_1.vrf_data(), pos_data_2.vrf_data()); let consensus_data_1 = ConsensusData::PoS(pos_data_1.into()); let consensus_data_2 = ConsensusData::PoS(pos_data_2.into()); @@ -583,7 +588,7 @@ fn activation_gate_does_not_block_segment_with_fresh_proof(#[case] seed: Seed) { pool_id, &staking_sk, twin_side_id, - 120, + 90, ); assert_eq!( @@ -848,19 +853,137 @@ fn partition_halves_stay_valid_without_canonicalization(#[case] seed: Seed) { Id::::from(main_2) ); - // Both halves recorded the evidence and stored every variant. + // Both halves recorded the evidence and stored every variant, with the + // index retaining the arrival order of the sightings. for (db_tx, main, side) in [ (tf1.storage.transaction_ro().unwrap(), main_1, side_1), (tf2.storage.transaction_ro().unwrap(), main_2, side_2), ] { let index_entry = db_tx.get_seal_index_entry(&seal_1).unwrap().unwrap(); assert_eq!(index_entry.blocks().len(), 2); + assert_eq!(index_entry.blocks()[0].0, main); + assert_eq!(index_entry.blocks()[1].0, side); assert!(db_tx.get_block(&main).unwrap().is_some()); assert!(db_tx.get_block(&side).unwrap().is_some()); assert!(db_tx.get_duplicate_seal_evidence(&seal_1).unwrap().is_some()); } } +/// Honest resealing: the same pool produces blocks for consecutive heights with +/// different timestamps (e.g. after one of its blocks was orphaned). The two +/// blocks carry different proofs, are not duplicates of each other, produce no +/// evidence, and are both accepted on the main chain. +#[rstest] +#[trace] +#[case(Seed::from_entropy())] +fn honest_reseal_at_same_height_is_not_flagged(#[case] seed: Seed) { + let mut rng = make_seedable_rng(seed); + let (vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng(&mut rng, VRFKeyKind::Schnorrkel); + let (mut tf, stake_pool_outpoint, pool_id, staking_sk) = + setup_chain_with_stake_pool_with_chainstate_config(&mut rng, vrf_pk, gate_enabled_config()); + + // First reseal: the pool creation output is still unspent (no PoS block + // has been produced yet), so the block is mined with the tx-based kernel. + let parent = tf + .best_block_id() + .classify(tf.chainstate.get_chain_config()) + .chain_block_id() + .unwrap(); + let staking_destination = Destination::PublicKey(PublicKey::from_private_key(&staking_sk)); + let reward_outputs = + vec![TxOutput::ProduceBlockFromStake(staking_destination.clone(), pool_id)]; + let kernel_sig = produce_kernel_signature( + &mut rng, + &tf, + &staking_sk, + reward_outputs.as_slice(), + staking_destination, + stake_pool_outpoint.clone(), + ); + let chain_config = tf.chainstate.get_chain_config(); + let reseal_height = FIRST_POS_BLOCK_HEIGHT; + let current_difficulty = calculate_new_target(&tf, reseal_height).unwrap(); + let final_supply = chain_config.final_supply().unwrap(); + let pos_config = get_pos_chain_config(chain_config, reseal_height); + let pos_randomness = tf.pos_randomness_for_height(&reseal_height); + let (pos_data, block_timestamp) = pos_mine( + &mut rng, + &tf.storage.transaction_ro().unwrap(), + &pos_config, + BlockTimestamp::from_time(tf.current_time()).add_int_seconds(90).unwrap(), + stake_pool_outpoint.clone(), + InputWitness::Standard(kernel_sig), + &vrf_sk, + pos_randomness, + pool_id, + final_supply, + 1, + current_difficulty, + ) + .expect("should be able to mine"); + let first_reseal = tf + .make_block_builder() + .with_parent(parent.into()) + .with_consensus_data(ConsensusData::PoS(pos_data.into())) + .with_block_signing_key(staking_sk.clone()) + .with_timestamp(block_timestamp) + .with_reward(reward_outputs.clone()) + .build(&mut rng); + let first_reseal_id = first_reseal.get_id(); + let first_reseal_seal = + BlockSeal::from_consensus_data(first_reseal.header().consensus_data()).unwrap(); + tf.process_block(first_reseal, BlockSource::Local).unwrap(); + + // Second reseal: two minutes later, on top of the first reseal, with the + // kernel taken from the first reseal's stake reward. A different + // timestamp gives a different proof, so the two blocks are not duplicates. + tf.progress_time_seconds_since_epoch(120); + let second_reseal_id = mine_and_process_fresh_proof_block( + &mut rng, + &mut tf, + &vrf_sk, + pool_id, + &staking_sk, + first_reseal_id, + 90, + ); + let second_reseal = tf + .storage + .transaction_ro() + .unwrap() + .get_block(&second_reseal_id) + .unwrap() + .unwrap(); + let second_reseal_seal = + BlockSeal::from_consensus_data(second_reseal.header().consensus_data()).unwrap(); + + // Both blocks are on the main chain and carry different, unindexed proofs: + // no seal-index entries with multiplicity, and no duplicate evidence. + assert_ne!(first_reseal_seal, second_reseal_seal); + let db_tx = tf.storage.transaction_ro().unwrap(); + for (height, expected_id, expected_seal) in [ + (reseal_height, first_reseal_id, &first_reseal_seal), + ( + reseal_height.next_height(), + second_reseal_id, + &second_reseal_seal, + ), + ] { + let id_at_height = db_tx.get_block_id_by_height(height).unwrap().unwrap(); + assert_eq!( + Id::::from(expected_id), + id_at_height + ); + let entry = db_tx.get_seal_index_entry(expected_seal).unwrap(); + assert!( + entry.is_none() + || entry.as_ref().unwrap().blocks().len() == 1 + && entry.as_ref().unwrap().blocks()[0].0 == expected_id, + ); + assert!(db_tx.get_duplicate_seal_evidence(expected_seal).unwrap().is_none()); + } +} + /// Variant cap: an equivocating pool floods the node with same-proof variants. /// The index entry stops at the cap, the evidence record stays bounded, every /// variant stays stored and fully valid, and the first-processed variant is @@ -953,14 +1076,20 @@ fn duplicate_proof_variants_are_capped_but_all_stored(#[case] seed: Seed) { let db_tx = tf.storage.transaction_ro().unwrap(); let index_entry = db_tx.get_seal_index_entry(&seal).unwrap().unwrap(); assert_eq!(index_entry.blocks().len(), 8); + // The index retains the first 8 variants in arrival order; the ninth stays + // stored but is no longer indexed. + assert_eq!( + index_entry.blocks().iter().map(|(id, _)| *id).collect::>(), + variant_ids[..8].to_vec(), + ); for block_id in &variant_ids { assert!( - index_entry.blocks().iter().any(|(id, _)| id == block_id) - || db_tx.get_block(block_id).unwrap().is_some(), - "variant {block_id} must be known to the node", + db_tx.get_block(block_id).unwrap().is_some(), + "variant {block_id} must be stored", ); } - assert!(db_tx.get_duplicate_seal_evidence(&seal).unwrap().is_some()); + let evidence = db_tx.get_duplicate_seal_evidence(&seal).unwrap().unwrap(); + assert!(evidence.headers().len() <= 8); } /// A same-pool chain keeps progressing (with decayed trust): the asymptote @@ -1000,4 +1129,27 @@ fn same_pool_chain_keeps_progressing(#[case] seed: Seed) { let h4 = mine_and_process_fresh_proof_block(&mut rng, &mut tf, &vrf_sk, pool_id, &staking_sk, h3, 2); assert_eq!(tf.best_block_id(), Id::::from(h4)); + + // The reseals carry distinct, unindexed proofs: no seal-index entries with + // multiplicity and no evidence records (honest same-pool progress is never + // flagged). + let db_tx_seals = tf.storage.transaction_ro().unwrap(); + let seal_h3 = BlockSeal::from_consensus_data( + db_tx_seals.get_block(&h3).unwrap().unwrap().header().consensus_data(), + ) + .unwrap(); + let seal_h4 = BlockSeal::from_consensus_data( + db_tx_seals.get_block(&h4).unwrap().unwrap().header().consensus_data(), + ) + .unwrap(); + assert_ne!(seal_h3, seal_h4); + let db_tx = tf.storage.transaction_ro().unwrap(); + for seal in [&seal_h3, &seal_h4] { + let entry = db_tx.get_seal_index_entry(seal).unwrap(); + assert!( + entry.is_none() || entry.as_ref().unwrap().blocks().len() == 1, + "a single same-pool block must not be a duplicate sighting" + ); + assert!(db_tx.get_duplicate_seal_evidence(seal).unwrap().is_none()); + } } From a2664874784f416bc296917d13ae350ee0acc145 Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sun, 15 Nov 2026 19:58:59 +0100 Subject: [PATCH 09/16] test(chainstate): pin seal suite semantics and refusal reachability Tighten the honest-reseal and variant-cap assertions (exact evidence count, storage of every variant, index arrival order), rename the reseal test to consecutive heights, apply neutral wording, add parent-aware target derivation for side-branch mining, and document why the refusal short-circuit is unreachable through normal block processing (fresh sightings pass the gate, twin chains tie on trust, duplicate rebuilds carry identical trust) with the invalidation-recovery state covered by the bypass test. --- .../test-suite/src/tests/helpers/pos.rs | 11 ++ .../src/tests/seal_duplication_tests.rs | 112 +++++++++++++----- 2 files changed, 96 insertions(+), 27 deletions(-) diff --git a/chainstate/test-suite/src/tests/helpers/pos.rs b/chainstate/test-suite/src/tests/helpers/pos.rs index 82c3b2aac6..a176590097 100644 --- a/chainstate/test-suite/src/tests/helpers/pos.rs +++ b/chainstate/test-suite/src/tests/helpers/pos.rs @@ -58,6 +58,17 @@ pub fn calculate_new_target( calculate_new_pos_compact_target(tf, block_height, &tf.best_block_id()) } +/// Same as `calculate_new_target`, but the recalculation window is the chain +/// ending at `chain_tip_id` instead of the best chain: needed when mining a +/// block whose parent is a side block. +pub fn calculate_new_target_for_chain( + tf: &TestFramework, + chain_tip_id: &common::primitives::Id, + block_height: BlockHeight, +) -> Result { + calculate_new_pos_compact_target(tf, block_height, chain_tip_id) +} + pub fn create_custom_genesis_with_stake_pool( staker_pk: PublicKey, vrf_pk: VRFPublicKey, diff --git a/chainstate/test-suite/src/tests/seal_duplication_tests.rs b/chainstate/test-suite/src/tests/seal_duplication_tests.rs index 365937048d..0614626b30 100644 --- a/chainstate/test-suite/src/tests/seal_duplication_tests.rs +++ b/chainstate/test-suite/src/tests/seal_duplication_tests.rs @@ -17,6 +17,7 @@ use rstest::rstest; +use crate::tests::helpers::pos::calculate_new_target_for_chain; use chainstate::{BlockSource, ChainstateConfig}; use chainstate_storage::{BlockchainStorageRead, Transactional as _}; use chainstate_test_framework::{ @@ -495,6 +496,7 @@ fn mine_and_process_fresh_proof_block( rng: &mut impl CryptoRng, tf: &mut TestFramework, vrf_sk: &VRFPrivateKey, + stake_pool_outpoint: &UtxoOutPoint, pool_id: PoolId, staking_sk: &PrivateKey, parent_id: Id, @@ -504,32 +506,61 @@ fn mine_and_process_fresh_proof_block( let reward_outputs = vec![TxOutput::ProduceBlockFromStake(staking_destination.clone(), pool_id)]; - // The kernel of a PoS block that follows another PoS block is the - // `ProduceBlockFromStake` reward output of that previous block, not the - // original pool creation output (which the previous block's kernel - // consumed). - let kernel_outpoint = UtxoOutPoint::new(OutPointSourceId::BlockReward(parent_id.into()), 0); - let kernel_sig = produce_block_reward_kernel_signature( - tf, - rng, - staking_sk, - reward_outputs.as_slice(), - staking_destination, - parent_id.into(), - kernel_outpoint.clone(), - ); + // The kernel depends on the parent: a PoS parent's stake lives in its + // `ProduceBlockFromStake` reward output (the pool creation output was + // consumed by the first PoS block of the chain), while a non-PoS parent + // leaves the pool creation output in place. + let parent_reward_outpoint = + UtxoOutPoint::new(OutPointSourceId::BlockReward(parent_id.into()), 0); + let parent_reward_outputs = tf.outputs_from_genblock(parent_id.into()); + let parent_is_pos = parent_reward_outputs + .get(&OutPointSourceId::BlockReward(parent_id.into())) + .map(|outputs| !outputs.is_empty()) + .unwrap_or(false); let chain_config = tf.chainstate.get_chain_config(); - let new_block_height = tf.best_block_index().block_height().next_height(); + let parent_height = tf + .storage + .transaction_ro() + .unwrap() + .get_block_index(&parent_id) + .unwrap() + .expect("parent block index is present") + .block_height(); + let new_block_height = parent_height.next_height(); let epoch_index = chain_config.epoch_index_from_height(&new_block_height); let pos_randomness = tf.pos_randomness_for_height(&new_block_height); - let current_difficulty = calculate_new_target(tf, new_block_height).unwrap(); + let current_difficulty = + calculate_new_target_for_chain(tf, &parent_id.into(), new_block_height).unwrap(); let final_supply = chain_config.final_supply().unwrap(); let pos_config = get_pos_chain_config(chain_config, new_block_height); let initial_timestamp = BlockTimestamp::from_time(tf.current_time()) .add_int_seconds(timestamp_offset_seconds) .unwrap(); + let (kernel_sig, kernel_outpoint) = if parent_is_pos { + let kernel_sig = produce_block_reward_kernel_signature( + tf, + rng, + staking_sk, + reward_outputs.as_slice(), + staking_destination.clone(), + parent_id.into(), + parent_reward_outpoint.clone(), + ); + (kernel_sig, parent_reward_outpoint) + } else { + let kernel_sig = produce_kernel_signature( + rng, + tf, + staking_sk, + reward_outputs.as_slice(), + staking_destination.clone(), + stake_pool_outpoint.clone(), + ); + (kernel_sig, stake_pool_outpoint.clone()) + }; + let (pos_data, block_timestamp) = pos_mine( rng, &tf.storage.transaction_ro().unwrap(), @@ -552,7 +583,7 @@ fn mine_and_process_fresh_proof_block( .with_consensus_data(ConsensusData::PoS(pos_data.into())) .with_block_signing_key(staking_sk.clone()) .with_timestamp(block_timestamp) - .with_reward(reward_outputs) + .with_reward(reward_outputs.clone()) .build(rng); let block_id = block.get_id(); tf.process_block(block, BlockSource::Local).unwrap(); @@ -585,6 +616,7 @@ fn activation_gate_does_not_block_segment_with_fresh_proof(#[case] seed: Seed) { &mut rng, &mut tf, &vrf_sk, + &stake_pool_outpoint, pool_id, &staking_sk, twin_side_id, @@ -627,13 +659,13 @@ fn activation_gate_bypassed_for_invalidation_recovery(#[case] seed: Seed) { ); } -// --------------------------------------------------------------- -// S5 — adversarial suite for the PoS seal activation gate +// -+ +// S5 — containment suite for the PoS seal activation gate // -// Scenarios derived from the design note's attack narratives: tip +// Scenarios derived from the design note's reuse narratives: tip // equivocation races, withheld-variant release, partition halves, honest -// resealing at the same height, and the variant cap. The gate must never -// fire on segments that contain at least one fresh proof, must never +// resealing, and the variant cap. The gate must never fire on segments that +// contain at least one fresh proof, must never // prevent the storage or retrieval of any variant, and must leave the // ordinary trust comparison in charge of every race. // --------------------------------------------------------------- @@ -666,6 +698,7 @@ fn equivocation_race_converges_via_fresh_proofs(#[case] seed: Seed) { &mut rng, &mut tf, &vrf_sk, + &stake_pool_outpoint, pool_id, &staking_sk, twin_side, @@ -745,6 +778,7 @@ fn withheld_variant_release_keeps_incumbent_stable(#[case] seed: Seed) { &mut rng, &mut tf, &vrf_sk, + &stake_pool_outpoint, pool_id, &staking_sk, twin_main, @@ -876,7 +910,7 @@ fn partition_halves_stay_valid_without_canonicalization(#[case] seed: Seed) { #[rstest] #[trace] #[case(Seed::from_entropy())] -fn honest_reseal_at_same_height_is_not_flagged(#[case] seed: Seed) { +fn honest_reseal_at_consecutive_heights_is_not_flagged(#[case] seed: Seed) { let mut rng = make_seedable_rng(seed); let (vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng(&mut rng, VRFKeyKind::Schnorrkel); let (mut tf, stake_pool_outpoint, pool_id, staking_sk) = @@ -942,6 +976,7 @@ fn honest_reseal_at_same_height_is_not_flagged(#[case] seed: Seed) { &mut rng, &mut tf, &vrf_sk, + &stake_pool_outpoint, pool_id, &staking_sk, first_reseal_id, @@ -984,7 +1019,7 @@ fn honest_reseal_at_same_height_is_not_flagged(#[case] seed: Seed) { } } -/// Variant cap: an equivocating pool floods the node with same-proof variants. +/// Variant cap: a pool reusing one proof across many variants. /// The index entry stops at the cap, the evidence record stays bounded, every /// variant stays stored and fully valid, and the first-processed variant is /// never displaced. @@ -1089,7 +1124,9 @@ fn duplicate_proof_variants_are_capped_but_all_stored(#[case] seed: Seed) { ); } let evidence = db_tx.get_duplicate_seal_evidence(&seal).unwrap().unwrap(); - assert!(evidence.headers().len() <= 8); + // Sightings 2..=8 extend the evidence to exactly the cap; the ninth + // sighting is log-only. + assert_eq!(evidence.headers().len(), 8); } /// A same-pool chain keeps progressing (with decayed trust): the asymptote @@ -1119,6 +1156,7 @@ fn same_pool_chain_keeps_progressing(#[case] seed: Seed) { &mut rng, &mut tf, &vrf_sk, + &stake_pool_outpoint, pool_id, &staking_sk, twin_main, @@ -1126,8 +1164,16 @@ fn same_pool_chain_keeps_progressing(#[case] seed: Seed) { ); assert_eq!(tf.best_block_id(), Id::::from(h3)); - let h4 = - mine_and_process_fresh_proof_block(&mut rng, &mut tf, &vrf_sk, pool_id, &staking_sk, h3, 2); + let h4 = mine_and_process_fresh_proof_block( + &mut rng, + &mut tf, + &vrf_sk, + &stake_pool_outpoint, + pool_id, + &staking_sk, + h3, + 2, + ); assert_eq!(tf.best_block_id(), Id::::from(h4)); // The reseals carry distinct, unindexed proofs: no seal-index entries with @@ -1153,3 +1199,15 @@ fn same_pool_chain_keeps_progressing(#[case] seed: Seed) { assert!(db_tx.get_duplicate_seal_evidence(seal).unwrap().is_none()); } } + +// The gate's refusal short-circuit itself is not exercised end-to-end, and +// cannot be: through normal block processing, a newly mined block always +// carries a first-sighting proof (the gate passes it), a twin-only chain has +// trust exactly equal to the incumbent (the strict trust comparison never +// attempts it), and a pure-duplicate rebuild of an existing chain carries +// trust identical to that chain by construction (same heights, same pool +// sequence, same timestamps). The one state that reaches the refusal — a +// pure-duplicate segment as the best recovery candidate after user-initiated +// invalidation — is covered by the bypass test above with the gate enabled. +// The refusal semantics are pinned by the predicate unit tests; the wiring is +// the four-line short-circuit reviewed in the S4 rounds. From e4dbb06bab76f150060baa3140615c485da32e70 Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sun, 15 Nov 2026 19:59:37 +0100 Subject: [PATCH 10/16] test(chainstate): fix clippy lints in the seal test helpers --- chainstate/test-suite/src/tests/seal_duplication_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chainstate/test-suite/src/tests/seal_duplication_tests.rs b/chainstate/test-suite/src/tests/seal_duplication_tests.rs index 0614626b30..074daf1769 100644 --- a/chainstate/test-suite/src/tests/seal_duplication_tests.rs +++ b/chainstate/test-suite/src/tests/seal_duplication_tests.rs @@ -492,6 +492,7 @@ fn gate_enabled_config() -> ChainstateConfig { /// mined from a timestamp well after the current framework time, so its seal /// (which binds the timestamp) differs from the seals of all previously /// processed blocks. +#[allow(clippy::too_many_arguments)] fn mine_and_process_fresh_proof_block( rng: &mut impl CryptoRng, tf: &mut TestFramework, @@ -515,8 +516,7 @@ fn mine_and_process_fresh_proof_block( let parent_reward_outputs = tf.outputs_from_genblock(parent_id.into()); let parent_is_pos = parent_reward_outputs .get(&OutPointSourceId::BlockReward(parent_id.into())) - .map(|outputs| !outputs.is_empty()) - .unwrap_or(false); + .is_some_and(|outputs| !outputs.is_empty()); let chain_config = tf.chainstate.get_chain_config(); let parent_height = tf From 9531277b5837048c4d850e275f660e798882b7fe Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sun, 15 Nov 2026 20:23:56 +0100 Subject: [PATCH 11/16] test(chainstate): pin the seal gate refusal end to end A block whose consensus data reuses the VRF data of an already-sighted block (the seal binds the pool, the epoch randomness and the timestamp, not the parent or the block content) extends the incumbent chain with strictly higher trust while carrying a duplicate proof. With the gate enabled, its activation is refused: the tip stays on the incumbent, the block stays stored, and the reused proof carries its evidence record. With the gate disabled, the same block activates and becomes the tip. Also fix the section header divider, reword the same-pool trust comment (the asymptote weights timestamp gaps, not pool identity), and derive the twins-helper target from the parent chain like the fresh helper. --- .../src/tests/seal_duplication_tests.rs | 256 ++++++++++++++++-- 1 file changed, 232 insertions(+), 24 deletions(-) diff --git a/chainstate/test-suite/src/tests/seal_duplication_tests.rs b/chainstate/test-suite/src/tests/seal_duplication_tests.rs index 074daf1769..f102f02aac 100644 --- a/chainstate/test-suite/src/tests/seal_duplication_tests.rs +++ b/chainstate/test-suite/src/tests/seal_duplication_tests.rs @@ -17,7 +17,6 @@ use rstest::rstest; -use crate::tests::helpers::pos::calculate_new_target_for_chain; use chainstate::{BlockSource, ChainstateConfig}; use chainstate_storage::{BlockchainStorageRead, Transactional as _}; use chainstate_test_framework::{ @@ -25,12 +24,14 @@ use chainstate_test_framework::{ }; use chainstate_types::{BlockSeal, pos_randomness::PoSRandomness}; use common::{ + Uint256, chain::{ - Destination, OutPointSourceId, PoolId, TxOutput, UtxoOutPoint, - block::{ConsensusData, timestamp::BlockTimestamp}, + Destination, OutPointSourceId, PoolId, TxInput, TxOutput, UtxoOutPoint, + block::{ConsensusData, consensus_data::PoSData, timestamp::BlockTimestamp}, + config::Builder as ConfigBuilder, signature::inputsig::InputWitness, }, - primitives::{Id, Idable}, + primitives::{Compact, Id, Idable}, }; use crypto::{ key::{PrivateKey, PublicKey}, @@ -40,8 +41,10 @@ use randomness::CryptoRng; use test_utils::random::{Seed, make_seedable_rng}; use super::helpers::pos::{ - FIRST_POS_BLOCK_HEIGHT, calculate_new_target, get_pos_chain_config, produce_kernel_signature, - setup_chain_with_stake_pool, setup_chain_with_stake_pool_with_chainstate_config, + FIRST_POS_BLOCK_HEIGHT, add_block_with_stake_pool, calculate_new_target, + calculate_new_target_for_chain, consensus_upgrades_with_pos_at_height, get_pos_chain_config, + produce_kernel_signature, setup_chain_with_stake_pool, + setup_chain_with_stake_pool_with_chainstate_config, }; /// Mine two PoS consensus datas for the same slot by calling `pos_mine` twice with @@ -208,7 +211,8 @@ fn mine_and_process_same_seal_twins_on_parent( .block_height(); let new_block_height = parent_height.next_height(); let pos_randomness = tf.pos_randomness_for_height(&new_block_height); - let current_difficulty = calculate_new_target(tf, new_block_height).unwrap(); + let current_difficulty = + calculate_new_target_for_chain(tf, &parent_id.into(), new_block_height).unwrap(); let final_supply = chain_config.final_supply().unwrap(); let pos_config = get_pos_chain_config(chain_config, new_block_height); let initial_timestamp = BlockTimestamp::from_time(tf.current_time()) @@ -659,15 +663,15 @@ fn activation_gate_bypassed_for_invalidation_recovery(#[case] seed: Seed) { ); } -// -+ +// --------------------------------------------------------------- // S5 — containment suite for the PoS seal activation gate // // Scenarios derived from the design note's reuse narratives: tip // equivocation races, withheld-variant release, partition halves, honest // resealing, and the variant cap. The gate must never fire on segments that -// contain at least one fresh proof, must never -// prevent the storage or retrieval of any variant, and must leave the -// ordinary trust comparison in charge of every race. +// contain at least one fresh proof, must never prevent the storage or +// retrieval of any variant, and must leave the ordinary trust comparison in +// charge of every race that contains a fresh proof. // --------------------------------------------------------------- /// Tip equivocation race: the pool equivocates at two consecutive heights and @@ -1130,8 +1134,8 @@ fn duplicate_proof_variants_are_capped_but_all_stored(#[case] seed: Seed) { } /// A same-pool chain keeps progressing (with decayed trust): the asymptote -/// penalizes same-pool repeats in the trust comparison but never makes such -/// blocks invalid or their chains stuck. +/// weights each block by its timestamp gap, so sparse same-pool progress adds +/// less trust but never makes such blocks invalid or their chains stuck. #[rstest] #[trace] #[case(Seed::from_entropy())] @@ -1200,14 +1204,218 @@ fn same_pool_chain_keeps_progressing(#[case] seed: Seed) { } } -// The gate's refusal short-circuit itself is not exercised end-to-end, and -// cannot be: through normal block processing, a newly mined block always -// carries a first-sighting proof (the gate passes it), a twin-only chain has -// trust exactly equal to the incumbent (the strict trust comparison never -// attempts it), and a pure-duplicate rebuild of an existing chain carries -// trust identical to that chain by construction (same heights, same pool -// sequence, same timestamps). The one state that reaches the refusal — a -// pure-duplicate segment as the best recovery candidate after user-initiated -// invalidation — is covered by the bypass test above with the gate enabled. -// The refusal semantics are pinned by the predicate unit tests; the wiring is -// the four-line short-circuit reviewed in the S4 rounds. +// Note on mining-based constructions: a newly mined block always carries a +// first-sighting proof (the gate passes it), and a twin-only chain has trust +// exactly equal to the incumbent (the strict trust comparison never attempts +// it), so the refusal cannot be reached by mining twins alone. It IS reached +// by grafting a copied proof: a block whose consensus data re-uses the VRF +// data of an already-sighted block (the seal binds the pool, the epoch +// randomness and the timestamp, not the parent or the block content), built +// as an extension of the incumbent chain — see the test below. + +/// The gate's refusal in normal block processing. The seal binds the pool, +/// the epoch randomness and the block timestamp — not the parent or the block +/// content — so a block whose consensus data re-uses the VRF data of an +/// already-sighted block extends the incumbent chain with a strictly higher +/// trust while carrying a duplicate proof. The epoch length of this chain is +/// large enough that the copied block's transcript (epoch, randomness, +/// timestamp) is also valid at the new height. +/// +/// With the gate enabled, the activation of this chain is refused: the tip +/// stays on the incumbent, the reworked block stays stored, and the reused +/// proof carries its evidence record. With the gate disabled, the same block +/// activates and becomes the new tip. +#[rstest] +#[trace] +#[case(Seed::from_entropy())] +fn activation_gate_refuses_reused_proof_extension(#[case] seed: Seed) { + // Gate on: the extension is refused; the incumbent stays the best chain. + let (best_with_gate, reworked_id, incumbent_id) = + run_reused_proof_extension_scenario(seed, true); + assert_eq!( + best_with_gate, + Id::::from(incumbent_id) + ); + assert_ne!(incumbent_id, reworked_id); + + // Gate off: the same extension activates and becomes the best chain (the + // refusal above is the gate's doing, not a validation failure). + let (best_without_gate, reworked_id_off, incumbent_id_off) = + run_reused_proof_extension_scenario(seed, false); + assert_eq!(reworked_id_off, reworked_id); + assert_eq!(incumbent_id_off, incumbent_id); + assert_eq!( + best_without_gate, + Id::::from(reworked_id) + ); +} + +/// Runs the reused-proof-extension scenario deterministically: mines the +/// incumbent chain (A, then B on A), a losing sibling C of B at a later +/// timestamp, and the reworked block D (B's child carrying C's VRF data). +/// Returns the best block id, the reworked block id and the incumbent tip id. +fn run_reused_proof_extension_scenario( + seed: Seed, + gate_enabled: bool, +) -> ( + Id, + Id, + Id, +) { + let mut rng = make_seedable_rng(seed); + let (vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng(&mut rng, VRFKeyKind::Schnorrkel); + + // A chain with a long epoch, so the VRF transcript of a block stays valid + // at the next height (the transcript binds the epoch index). + let chain_config = ConfigBuilder::test_chain() + .consensus_upgrades(consensus_upgrades_with_pos_at_height( + FIRST_POS_BLOCK_HEIGHT, + )) + .epoch_length(std::num::NonZeroU64::new(100).unwrap()) + .sealed_epoch_distance_from_tip(0) + .build(); + let chainstate_config = if gate_enabled { + gate_enabled_config() + } else { + ChainstateConfig { + pos_seal_duplication_tracking: true.into(), + ..Default::default() + } + }; + let mut tf = TestFramework::builder(&mut rng) + .with_chain_config(chain_config) + .with_chainstate_config(chainstate_config) + .build(); + + let (stake_pool_data, staking_sk) = + chainstate_test_framework::create_stake_pool_data_with_all_reward_to_staker( + &mut rng, + tf.chainstate.get_chain_config().min_stake_pool_pledge(), + vrf_pk, + ); + let (stake_pool_outpoint, pool_id) = + add_block_with_stake_pool(&mut rng, &mut tf, stake_pool_data); + + let staking_destination = Destination::PublicKey(PublicKey::from_private_key(&staking_sk)); + let reward_outputs = + vec![TxOutput::ProduceBlockFromStake(staking_destination.clone(), pool_id)]; + + // The incumbent chain: A at the first PoS height, then B as its child. + let pool_block = tf + .best_block_id() + .classify(tf.chainstate.get_chain_config()) + .chain_block_id() + .unwrap(); + let block_a = mine_and_process_fresh_proof_block( + &mut rng, + &mut tf, + &vrf_sk, + &stake_pool_outpoint, + pool_id, + &staking_sk, + pool_block, + 60, + ); + let block_b = mine_and_process_fresh_proof_block( + &mut rng, + &mut tf, + &vrf_sk, + &stake_pool_outpoint, + pool_id, + &staking_sk, + block_a, + 61, + ); + assert_eq!( + tf.best_block_id(), + Id::::from(block_b) + ); + + // A losing sibling of B at a later timestamp: stored as a side block, and + // its proof is the (so far single) sighting of its seal. + let block_c = mine_and_process_fresh_proof_block( + &mut rng, + &mut tf, + &vrf_sk, + &stake_pool_outpoint, + pool_id, + &staking_sk, + block_a, + 100, + ); + assert_eq!( + tf.best_block_id(), + Id::::from(block_b) + ); + + // The reworked block: B's child whose consensus data re-uses the VRF data + // of the side block (the transcript does not bind the parent, the height + // or the block content), with the target required at the new height. It is + // a fully valid block that carries strictly higher trust than the + // incumbent chain. + let c_block = tf.storage.transaction_ro().unwrap().get_block(&block_c).unwrap().unwrap(); + let c_pos_data = match c_block.header().consensus_data() { + ConsensusData::PoS(data) => data, + _ => panic!("the side block is a PoS block"), + }; + let c_timestamp = c_block.header().timestamp(); + + let kernel_outpoint = UtxoOutPoint::new(OutPointSourceId::BlockReward(block_b.into()), 0); + let kernel_sig = produce_block_reward_kernel_signature( + &tf, + &mut rng, + &staking_sk, + reward_outputs.as_slice(), + staking_destination, + block_b.into(), + kernel_outpoint.clone(), + ); + + let next_height = FIRST_POS_BLOCK_HEIGHT.next_height().next_height(); + let required_target = + calculate_new_target_for_chain(&tf, &block_b.into(), next_height).unwrap(); + + let pos_data = PoSData::new( + vec![TxInput::from_utxo(kernel_outpoint.source_id(), kernel_outpoint.output_index())], + vec![InputWitness::Standard(kernel_sig)], + pool_id, + c_pos_data.vrf_data().clone(), + required_target, + ); + + let reworked_block = tf + .make_block_builder() + .with_parent(block_b.into()) + .with_consensus_data(ConsensusData::PoS(pos_data.into())) + .with_block_signing_key(staking_sk.clone()) + .with_timestamp(c_timestamp) + .with_reward(reward_outputs.clone()) + .build(&mut rng); + let reworked_id = reworked_block.get_id(); + + let reused_seal = + BlockSeal::from_consensus_data(reworked_block.header().consensus_data()).unwrap(); + assert_eq!( + Some(reused_seal.clone()), + BlockSeal::from_consensus_data(c_block.header().consensus_data()) + ); + + // The block is accepted (it is fully valid); whether its chain is + // activated depends on the gate. + tf.process_block(reworked_block, BlockSource::Local).unwrap(); + + // The reworked block stays stored either way, and the reused proof + // carries its evidence record with both signed headers. + let db_tx = tf.storage.transaction_ro().unwrap(); + assert!(db_tx.get_block(&reworked_id).unwrap().is_some()); + let index_entry = db_tx.get_seal_index_entry(&reused_seal).unwrap().unwrap(); + assert_eq!(index_entry.blocks().len(), 2); + let evidence = db_tx.get_duplicate_seal_evidence(&reused_seal).unwrap().unwrap(); + assert_eq!( + evidence.headers().iter().map(|header| header.get_id()).collect::>(), + vec![block_c, reworked_id], + ); + drop(db_tx); + + (tf.best_block_id(), reworked_id, block_b) +} From d484ed5de435ec645496b8972b3a39fdc635788c Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sun, 15 Nov 2026 20:24:41 +0100 Subject: [PATCH 12/16] test(chainstate): drop unused imports in the seal tests --- chainstate/test-suite/src/tests/seal_duplication_tests.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/chainstate/test-suite/src/tests/seal_duplication_tests.rs b/chainstate/test-suite/src/tests/seal_duplication_tests.rs index f102f02aac..baab3ac2de 100644 --- a/chainstate/test-suite/src/tests/seal_duplication_tests.rs +++ b/chainstate/test-suite/src/tests/seal_duplication_tests.rs @@ -24,14 +24,13 @@ use chainstate_test_framework::{ }; use chainstate_types::{BlockSeal, pos_randomness::PoSRandomness}; use common::{ - Uint256, chain::{ Destination, OutPointSourceId, PoolId, TxInput, TxOutput, UtxoOutPoint, block::{ConsensusData, consensus_data::PoSData, timestamp::BlockTimestamp}, config::Builder as ConfigBuilder, signature::inputsig::InputWitness, }, - primitives::{Compact, Id, Idable}, + primitives::{Id, Idable}, }; use crypto::{ key::{PrivateKey, PublicKey}, From 33b90b2aa89de7f57b6d933bdc97addcf25b9f45 Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sat, 21 Nov 2026 10:00:37 +0100 Subject: [PATCH 13/16] feat(chainstate): enable the seal gate by default on testnet chains --- CHANGELOG.md | 13 ++-- chainstate/src/config.rs | 59 +++++++++++++++++-- chainstate/src/detail/chainstateref/mod.rs | 2 +- .../src/detail/chainstateref/seal_index.rs | 12 +++- chainstate/src/detail/mod.rs | 2 +- .../src/tests/seal_duplication_tests.rs | 3 + node-lib/src/config_files/chainstate/mod.rs | 2 +- 7 files changed, 77 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a158ffa3f..bef14a78f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,12 +13,13 @@ The format is loosely based on [Keep a Changelog](https://keepachangelog.com/en/ ### Added - Node: - - chainstate: an optional `pos_seal_activation_gate` chainstate config setting - (disabled by default): 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. + - 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. ### Changed - Storage: diff --git a/chainstate/src/config.rs b/chainstate/src/config.rs index eea18fe45c..d2b88efa3c 100644 --- a/chainstate/src/config.rs +++ b/chainstate/src/config.rs @@ -22,7 +22,6 @@ make_config_setting!(MaxDbCommitAttempts, usize, 10); make_config_setting!(MaxOrphanBlocks, usize, 512); make_config_setting!(MaxTipAge, Duration, Duration::from_secs(60 * 60 * 24)); make_config_setting!(PosSealDuplicationTracking, bool, true); -make_config_setting!(PosSealActivationGate, bool, false); /// The chainstate subsystem configuration. #[derive(Debug, Clone, Default)] @@ -57,8 +56,9 @@ pub struct ChainstateConfig { /// 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. Defaults to false. - pub pos_seal_activation_gate: PosSealActivationGate, + /// 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, } impl ChainstateConfig { @@ -86,8 +86,15 @@ impl ChainstateConfig { *self.pos_seal_duplication_tracking } - pub fn pos_seal_activation_gate_enabled(&self) -> bool { - *self.pos_seal_activation_gate + 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 { @@ -112,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))); + } +} diff --git a/chainstate/src/detail/chainstateref/mod.rs b/chainstate/src/detail/chainstateref/mod.rs index a7def4ebc3..b03b16a6d5 100644 --- a/chainstate/src/detail/chainstateref/mod.rs +++ b/chainstate/src/detail/chainstateref/mod.rs @@ -1485,7 +1485,7 @@ impl ChainstateRe best_block_id: &Id, activation_context: ChainActivationContext, ) -> Result { - if !self.chainstate_config.pos_seal_activation_gate_enabled() { + if !self.chainstate_config.pos_seal_activation_gate_enabled(self.chain_config) { return Ok(false); } if activation_context.seal_activation_gate_bypassed() { diff --git a/chainstate/src/detail/chainstateref/seal_index.rs b/chainstate/src/detail/chainstateref/seal_index.rs index e94fa6f80f..2d9c89ef15 100644 --- a/chainstate/src/detail/chainstateref/seal_index.rs +++ b/chainstate/src/detail/chainstateref/seal_index.rs @@ -665,8 +665,16 @@ mod tests { } #[test] - fn seal_activation_gate_is_disabled_by_default() { - assert!(!ChainstateConfig::default().pos_seal_activation_gate_enabled()); + fn seal_activation_gate_defaults_off_on_non_testnet_chains() { + let chain_config = common::chain::config::Builder::test_chain() + .consensus_upgrades(common::chain::NetUpgrades::unit_tests()) + .genesis_unittest(common::chain::Destination::AnyoneCanSpend) + .checkpoints(std::collections::BTreeMap::new()) + .build(); + // The unit-test builder uses the testnet chain type, where the gate now + // defaults to enabled; the resolver tests in `config.rs` cover all chain + // types. Here the default-on behavior is what the suite relies on. + assert!(ChainstateConfig::default().pos_seal_activation_gate_enabled(&chain_config)); } #[test] diff --git a/chainstate/src/detail/mod.rs b/chainstate/src/detail/mod.rs index 2c3c3f109c..325bd2c892 100644 --- a/chainstate/src/detail/mod.rs +++ b/chainstate/src/detail/mod.rs @@ -244,7 +244,7 @@ impl Chainstate time_getter: TimeGetter, shutdown_initiated_rx: Option>, ) -> Self { - if chainstate_config.pos_seal_activation_gate_enabled() + if chainstate_config.pos_seal_activation_gate_enabled(&chain_config) && !chainstate_config.pos_seal_duplication_tracking_enabled() { // The gate classifies activation segments against the index that the diff --git a/chainstate/test-suite/src/tests/seal_duplication_tests.rs b/chainstate/test-suite/src/tests/seal_duplication_tests.rs index baab3ac2de..8ad67a2ea3 100644 --- a/chainstate/test-suite/src/tests/seal_duplication_tests.rs +++ b/chainstate/test-suite/src/tests/seal_duplication_tests.rs @@ -1278,6 +1278,9 @@ fn run_reused_proof_extension_scenario( } else { ChainstateConfig { pos_seal_duplication_tracking: true.into(), + // Explicitly disabled: the unit-test chain builder uses the testnet + // chain type, where the gate now defaults to enabled. + pos_seal_activation_gate: Some(false), ..Default::default() } }; diff --git a/node-lib/src/config_files/chainstate/mod.rs b/node-lib/src/config_files/chainstate/mod.rs index 4eb497b3a0..db3f91625c 100644 --- a/node-lib/src/config_files/chainstate/mod.rs +++ b/node-lib/src/config_files/chainstate/mod.rs @@ -78,7 +78,7 @@ impl From for ChainstateConfig { enable_heavy_checks, allow_checkpoints_mismatch, pos_seal_duplication_tracking: pos_seal_duplication_tracking.into(), - pos_seal_activation_gate: pos_seal_activation_gate.into(), + pos_seal_activation_gate, } } } From 7f14ed930a424709061cfa3513e00b31a86cbd57 Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sat, 21 Nov 2026 10:17:28 +0100 Subject: [PATCH 14/16] fix: harden the seal gate config validation and update its docs --- CHANGELOG.md | 4 ++- chainstate/src/detail/chainstateref/mod.rs | 3 ++- .../src/detail/chainstateref/seal_index.rs | 8 +++--- chainstate/src/detail/error.rs | 5 ++++ chainstate/src/detail/mod.rs | 23 ++++++++--------- .../src/tests/seal_duplication_tests.rs | 25 ++++++++++++++++++- node-lib/src/config_files/chainstate/mod.rs | 4 ++- 7 files changed, 52 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bef14a78f1..fbe4b508ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,9 @@ The format is loosely based on [Keep a Changelog](https://keepachangelog.com/en/ 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. + 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: diff --git a/chainstate/src/detail/chainstateref/mod.rs b/chainstate/src/detail/chainstateref/mod.rs index b03b16a6d5..f42004f01f 100644 --- a/chainstate/src/detail/chainstateref/mod.rs +++ b/chainstate/src/detail/chainstateref/mod.rs @@ -1468,7 +1468,8 @@ impl ChainstateRe /// consensus proofs that were already seen on other known blocks). /// /// This is the PoS seal activation gate - /// (`ChainstateConfig::pos_seal_activation_gate`): it is disabled by default, + /// (`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 diff --git a/chainstate/src/detail/chainstateref/seal_index.rs b/chainstate/src/detail/chainstateref/seal_index.rs index 2d9c89ef15..cc35d0d70a 100644 --- a/chainstate/src/detail/chainstateref/seal_index.rs +++ b/chainstate/src/detail/chainstateref/seal_index.rs @@ -665,15 +665,15 @@ mod tests { } #[test] - fn seal_activation_gate_defaults_off_on_non_testnet_chains() { + fn seal_activation_gate_defaults_on_for_test_chain() { let chain_config = common::chain::config::Builder::test_chain() .consensus_upgrades(common::chain::NetUpgrades::unit_tests()) .genesis_unittest(common::chain::Destination::AnyoneCanSpend) .checkpoints(std::collections::BTreeMap::new()) .build(); - // The unit-test builder uses the testnet chain type, where the gate now - // defaults to enabled; the resolver tests in `config.rs` cover all chain - // types. Here the default-on behavior is what the suite relies on. + // The unit-test builder uses the testnet chain type, where the gate + // defaults to enabled; the resolver tests in `chainstate/src/config.rs` + // cover all chain types and the explicit-override behavior. assert!(ChainstateConfig::default().pos_seal_activation_gate_enabled(&chain_config)); } diff --git a/chainstate/src/detail/error.rs b/chainstate/src/detail/error.rs index bed24c3b65..7af7f4c68c 100644 --- a/chainstate/src/detail/error.rs +++ b/chainstate/src/detail/error.rs @@ -241,6 +241,11 @@ pub enum InitializationError { StorageCompatibilityCheckError(#[from] StorageCompatibilityCheckError), #[error("Error initializing best chain candidates: {0}")] BestChainCandidatesError(#[from] BestChainCandidatesError), + #[error( + "The PoS seal activation gate is enabled while the PoS seal duplication tracking is \ + disabled; the gate has no effect without its index" + )] + SealActivationGateWithoutTracking, } #[derive(Error, Debug, PartialEq, Eq, Clone)] diff --git a/chainstate/src/detail/mod.rs b/chainstate/src/detail/mod.rs index 325bd2c892..97fceca84f 100644 --- a/chainstate/src/detail/mod.rs +++ b/chainstate/src/detail/mod.rs @@ -209,6 +209,17 @@ impl Chainstate db_tx.get_best_block_id()? }; + if chainstate_config.pos_seal_activation_gate_enabled(&chain_config) + && !chainstate_config.pos_seal_duplication_tracking_enabled() + { + // The gate classifies activation segments against the index that the + // seal duplication tracking maintains; without the tracking, the gate + // has nothing to look up and would silently never fire. Refuse the + // contradictory combination instead of neutralizing the hardening + // default with a single unrelated-looking config line. + return Err(InitializationError::SealActivationGateWithoutTracking.into()); + } + let mut chainstate = Self::new_no_genesis( chain_config, chainstate_config, @@ -244,18 +255,6 @@ impl Chainstate time_getter: TimeGetter, shutdown_initiated_rx: Option>, ) -> Self { - if chainstate_config.pos_seal_activation_gate_enabled(&chain_config) - && !chainstate_config.pos_seal_duplication_tracking_enabled() - { - // The gate classifies activation segments against the index that the - // seal duplication tracking maintains; without the tracking, the gate - // has nothing to look up and would silently never fire. - log::warn!( - "The PoS seal activation gate is enabled while the PoS seal duplication \ - tracking is disabled; the gate has no effect without its index" - ); - } - let orphan_blocks = OrphansProxy::new(*chainstate_config.max_orphan_blocks); let subsystem_events = EventsController::new(); let rpc_events = broadcaster::Broadcaster::new(); diff --git a/chainstate/test-suite/src/tests/seal_duplication_tests.rs b/chainstate/test-suite/src/tests/seal_duplication_tests.rs index 8ad67a2ea3..3f078bf55f 100644 --- a/chainstate/test-suite/src/tests/seal_duplication_tests.rs +++ b/chainstate/test-suite/src/tests/seal_duplication_tests.rs @@ -379,6 +379,9 @@ fn seal_tracking_disabled_records_nothing(#[case] seed: Seed) { let (vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng(&mut rng, VRFKeyKind::Schnorrkel); let chainstate_config = ChainstateConfig { pos_seal_duplication_tracking: false.into(), + // The gate defaults to enabled on this testnet-type chain; disabling the + // tracking with the gate on is now rejected at initialization. + pos_seal_activation_gate: Some(false), ..Default::default() }; let (mut tf, stake_pool_outpoint, pool_id, staking_sk) = @@ -477,13 +480,33 @@ fn duplicate_seal_records_survive_reorg(#[case] seed: Seed) { // --------------------------------------------------------------- // PoS seal activation gate // -// The gate (disabled by default in this release) refuses to activate a chain +// The gate (enabled by default on testnet chains -- which includes the +// testnet-type chains this suite builds -- and disabled by default elsewhere) +// refuses to activate a chain // whose newly activated segment consists entirely of blocks reusing // already-known PoS consensus proofs. It never fires on a segment that // contains at least one block with a fresh proof, and it is bypassed for the // initial block download and for the reorgs of the user-initiated block // invalidation path. +/// The contradictory combination (gate enabled, tracking disabled) is refused +/// at chainstate initialization instead of silently neutralizing the gate. +#[test] +#[should_panic(expected = "SealActivationGateWithoutTracking")] +fn gate_enabled_without_tracking_is_rejected() { + let mut rng = test_utils::random::make_seedable_rng(Seed::from_entropy()); + let (vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng(&mut rng, VRFKeyKind::Schnorrkel); + + let chainstate_config = ChainstateConfig { + pos_seal_duplication_tracking: false.into(), + pos_seal_activation_gate: Some(true), + ..Default::default() + }; + + let _tf = + setup_chain_with_stake_pool_with_chainstate_config(&mut rng, vrf_pk, chainstate_config); +} + fn gate_enabled_config() -> ChainstateConfig { ChainstateConfig { pos_seal_activation_gate: true.into(), diff --git a/node-lib/src/config_files/chainstate/mod.rs b/node-lib/src/config_files/chainstate/mod.rs index db3f91625c..67f7e64521 100644 --- a/node-lib/src/config_files/chainstate/mod.rs +++ b/node-lib/src/config_files/chainstate/mod.rs @@ -53,7 +53,9 @@ pub struct ChainstateConfigFile { /// 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`. Defaults to false. + /// Only effective together with `pos_seal_duplication_tracking`, which must stay + /// enabled. An absent value means the chain-type default applies: enabled on the + /// testnet, disabled elsewhere; an explicit value always overrides the default. pub pos_seal_activation_gate: Option, } From 96fdb6f53bc79e028f61fdf19a8e0d896bdc226e Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sat, 21 Nov 2026 10:18:21 +0100 Subject: [PATCH 15/16] test: silence the unused key warning in the seal tracking test --- chainstate/test-suite/src/tests/seal_duplication_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chainstate/test-suite/src/tests/seal_duplication_tests.rs b/chainstate/test-suite/src/tests/seal_duplication_tests.rs index 3f078bf55f..09fc77e3a3 100644 --- a/chainstate/test-suite/src/tests/seal_duplication_tests.rs +++ b/chainstate/test-suite/src/tests/seal_duplication_tests.rs @@ -495,7 +495,7 @@ fn duplicate_seal_records_survive_reorg(#[case] seed: Seed) { #[should_panic(expected = "SealActivationGateWithoutTracking")] fn gate_enabled_without_tracking_is_rejected() { let mut rng = test_utils::random::make_seedable_rng(Seed::from_entropy()); - let (vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng(&mut rng, VRFKeyKind::Schnorrkel); + let (_vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng(&mut rng, VRFKeyKind::Schnorrkel); let chainstate_config = ChainstateConfig { pos_seal_duplication_tracking: false.into(), From 5ed5ef619df863d688d20e0954f344fe018991d2 Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Sat, 21 Nov 2026 10:42:28 +0100 Subject: [PATCH 16/16] test(chainstate): pin seal gate sighting permanence under invalidation --- chainstate/src/detail/chainstateref/mod.rs | 10 + .../src/tests/seal_duplication_tests.rs | 245 ++++++++++++++++++ 2 files changed, 255 insertions(+) diff --git a/chainstate/src/detail/chainstateref/mod.rs b/chainstate/src/detail/chainstateref/mod.rs index f42004f01f..214bcaac3a 100644 --- a/chainstate/src/detail/chainstateref/mod.rs +++ b/chainstate/src/detail/chainstateref/mod.rs @@ -1714,6 +1714,16 @@ impl ChainActivationContext { /// 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( db_tx: &S, new_chain: &[BlockIndex], diff --git a/chainstate/test-suite/src/tests/seal_duplication_tests.rs b/chainstate/test-suite/src/tests/seal_duplication_tests.rs index 09fc77e3a3..35cd6bf481 100644 --- a/chainstate/test-suite/src/tests/seal_duplication_tests.rs +++ b/chainstate/test-suite/src/tests/seal_duplication_tests.rs @@ -1272,6 +1272,251 @@ fn activation_gate_refuses_reused_proof_extension(#[case] seed: Seed) { ); } +/// Sightings are permanent: invalidating one of the twin blocks does not +/// launder the reused seal. After the operator invalidates the side block +/// whose VRF proof the reworked block re-uses, a further reworked block +/// re-using the same proof still forms an all-duplicate segment, and its +/// chain activation stays refused. +/// +/// This pins the deliberate fail-closed semantics of the gate: the seal +/// index is a historical sighting record, so entries are not pruned (and +/// invalid partners are not skipped in the classification). Counting only +/// valid partners would let an attacker make a reused seal look unique +/// again by having one of its twins invalidated, re-opening the +/// trust-inflation construction the gate exists to refuse. Honest chains +/// are never affected: a segment containing any honestly-mined block always +/// carries a fresh seal and activates as usual. +#[rstest] +#[trace] +#[case(Seed::from_entropy())] +fn invalidated_partner_does_not_launder_a_reused_seal(#[case] seed: Seed) { + let mut rng = make_seedable_rng(seed); + let (vrf_sk, vrf_pk) = VRFPrivateKey::new_from_rng(&mut rng, VRFKeyKind::Schnorrkel); + + // A chain with a long epoch, so the VRF transcript of a block stays valid + // at later heights (the transcript binds the epoch index), exactly like + // the reused-proof-extension scenario. + let chain_config = ConfigBuilder::test_chain() + .consensus_upgrades(consensus_upgrades_with_pos_at_height( + FIRST_POS_BLOCK_HEIGHT, + )) + .epoch_length(std::num::NonZeroU64::new(100).unwrap()) + .sealed_epoch_distance_from_tip(0) + .build(); + let mut tf = TestFramework::builder(&mut rng) + .with_chain_config(chain_config) + .with_chainstate_config(gate_enabled_config()) + .build(); + + let (stake_pool_data, staking_sk) = + chainstate_test_framework::create_stake_pool_data_with_all_reward_to_staker( + &mut rng, + tf.chainstate.get_chain_config().min_stake_pool_pledge(), + vrf_pk, + ); + let (stake_pool_outpoint, pool_id) = + add_block_with_stake_pool(&mut rng, &mut tf, stake_pool_data); + + let staking_destination = Destination::PublicKey(PublicKey::from_private_key(&staking_sk)); + let reward_outputs = + vec![TxOutput::ProduceBlockFromStake(staking_destination.clone(), pool_id)]; + + // The incumbent chain: the pool block, then A, then B on top of it. + let pool_block = tf + .best_block_id() + .classify(tf.chainstate.get_chain_config()) + .chain_block_id() + .unwrap(); + let block_a = mine_and_process_fresh_proof_block( + &mut rng, + &mut tf, + &vrf_sk, + &stake_pool_outpoint, + pool_id, + &staking_sk, + pool_block, + 60, + ); + let block_b = mine_and_process_fresh_proof_block( + &mut rng, + &mut tf, + &vrf_sk, + &stake_pool_outpoint, + pool_id, + &staking_sk, + block_a, + 61, + ); + + // A losing sibling of B: the first sighting of the seal that gets reused. + let block_c = mine_and_process_fresh_proof_block( + &mut rng, + &mut tf, + &vrf_sk, + &stake_pool_outpoint, + pool_id, + &staking_sk, + block_a, + 100, + ); + + // The first reworked block: B's child re-using C's VRF data. It is + // fully valid and has strictly higher trust than the incumbent, but its + // segment is all-duplicate, so the gate refuses the activation. + let reworked_id = graft_reused_proof_block( + &mut rng, + &mut tf, + &vrf_sk, + &staking_sk, + staking_destination.clone(), + reward_outputs.clone(), + block_b, + block_c, + pool_id, + ); + assert_eq!( + tf.best_block_id(), + Id::::from(block_b) + ); + + // The operator invalidates the side block C -- the only other sighting + // of the reworked block's seal apart from the reworked blocks + // themselves. + tf.chainstate.invalidate_block(&block_c).unwrap(); + + // The seal index is not pruned by the invalidation: the sightings are a + // historical record. + let reused_seal = { + let db_tx = tf.storage.transaction_ro().unwrap(); + let c_block = db_tx.get_block(&block_c).unwrap().unwrap(); + BlockSeal::from_consensus_data(c_block.header().consensus_data()).unwrap() + }; + { + let db_tx = tf.storage.transaction_ro().unwrap(); + let entry = db_tx.get_seal_index_entry(&reused_seal).unwrap().unwrap(); + assert!(entry.blocks().iter().any(|(id, _)| id == &block_c)); + } + + // A second reworked block: another child of B, re-using the same VRF + // data again (a distinct block via its reward outputs). Even though the + // invalidated C can no longer be part of any acceptable chain, the new + // segment consists of reused proofs only, and its activation stays + // refused. + let alternate_reward_outputs = + vec![TxOutput::ProduceBlockFromStake(Destination::AnyoneCanSpend, pool_id)]; + let reworked_id_2 = graft_reused_proof_block( + &mut rng, + &mut tf, + &vrf_sk, + &staking_sk, + staking_destination, + alternate_reward_outputs, + block_b, + block_c, + pool_id, + ); + assert_eq!( + tf.best_block_id(), + Id::::from(block_b) + ); + // The second reworked block is fully valid and stays stored; only its + // activation was refused. + assert!( + tf.storage + .transaction_ro() + .unwrap() + .get_block(&reworked_id_2) + .unwrap() + .is_some() + ); + + // The refused chain recovers as usual as soon as it gains a block with a + // fresh seal: the gate never permanently strands a chain. + let fresh_extension = mine_and_process_fresh_proof_block( + &mut rng, + &mut tf, + &vrf_sk, + &stake_pool_outpoint, + pool_id, + &staking_sk, + reworked_id, + 110, + ); + assert_eq!( + tf.best_block_id(), + Id::::from(fresh_extension) + ); +} + +/// Builds and processes a block that is a child of `parent` and whose +/// consensus data re-uses the VRF data of `proof_source` (a stored side +/// block), with the target required at the new height. Returns the new +/// block's id. +#[allow(clippy::too_many_arguments)] +fn graft_reused_proof_block( + rng: &mut impl CryptoRng, + tf: &mut TestFramework, + vrf_sk: &VRFPrivateKey, + staking_sk: &PrivateKey, + staking_destination: Destination, + reward_outputs: Vec, + parent: Id, + proof_source: Id, + pool_id: PoolId, +) -> Id { + let _ = vrf_sk; // the proof comes from the proof source, not from fresh mining + let source_block = + tf.storage.transaction_ro().unwrap().get_block(&proof_source).unwrap().unwrap(); + let source_pos_data = match source_block.header().consensus_data() { + ConsensusData::PoS(data) => data, + _ => panic!("the proof source is a PoS block"), + }; + let source_timestamp = source_block.header().timestamp(); + + let kernel_outpoint = UtxoOutPoint::new(OutPointSourceId::BlockReward(parent.into()), 0); + let kernel_sig = produce_block_reward_kernel_signature( + tf, + rng, + staking_sk, + reward_outputs.as_slice(), + staking_destination, + parent.into(), + kernel_outpoint.clone(), + ); + + let parent_height = tf + .storage + .transaction_ro() + .unwrap() + .get_block_index(&parent) + .unwrap() + .unwrap() + .block_height(); + let next_height = parent_height.next_height(); + let required_target = calculate_new_target_for_chain(tf, &parent.into(), next_height).unwrap(); + + let pos_data = PoSData::new( + vec![TxInput::from_utxo(kernel_outpoint.source_id(), kernel_outpoint.output_index())], + vec![InputWitness::Standard(kernel_sig)], + pool_id, + source_pos_data.vrf_data().clone(), + required_target, + ); + + let block = tf + .make_block_builder() + .with_parent(parent.into()) + .with_consensus_data(ConsensusData::PoS(pos_data.into())) + .with_block_signing_key(staking_sk.clone()) + .with_timestamp(source_timestamp) + .with_reward(reward_outputs) + .build(rng); + let block_id = block.get_id(); + + tf.process_block(block, BlockSource::Local).unwrap(); + block_id +} + /// Runs the reused-proof-extension scenario deterministically: mines the /// incumbent chain (A, then B on A), a losing sibling C of B at a later /// timestamp, and the reworked block D (B's child carrying C's VRF data).