diff --git a/CHANGELOG.md b/CHANGELOG.md index 85f351bffe..fbe4b508ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,18 @@ The format is loosely based on [Keep a Changelog](https://keepachangelog.com/en/ ## [Unreleased] +### Added + - Node: + - chainstate: an optional `pos_seal_activation_gate` chainstate config setting: + when enabled, the node will not activate a chain whose newly activated segment + consists entirely of blocks whose PoS consensus proofs are duplicates of proofs + already seen on other known blocks. The initial block download and the reorgs + of the user-initiated block invalidation path are never affected. The default + depends on the chain type: enabled on the testnet (hardening it from launch), + disabled elsewhere; an explicit setting always overrides the default. Enabling + the gate while the seal duplication tracking is disabled is now rejected at + chainstate initialization instead of being silently ignored. + ### Changed - Storage: - the internal storage iteration APIs (`prefix_iter`, `greater_equal_iter`) now 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..d2b88efa3c 100644 --- a/chainstate/src/config.rs +++ b/chainstate/src/config.rs @@ -52,6 +52,13 @@ pub struct ChainstateConfig { /// If true, the seals (stake pool id + VRF output) of the processed PoS blocks will be /// indexed and the evidence of a seal seen on more than one block will be recorded. pub pos_seal_duplication_tracking: PosSealDuplicationTracking, + + /// If true, a chain whose newly activated segment consists entirely of blocks whose + /// PoS consensus proofs are duplicates of already-known proofs will not be activated. + /// Only effective together with `pos_seal_duplication_tracking`, which maintains the + /// index this gate classifies against. `None` means the default for the chain type + /// applies: enabled on the testnet (hardening it from launch), disabled elsewhere. + pub pos_seal_activation_gate: Option, } impl ChainstateConfig { @@ -79,6 +86,17 @@ impl ChainstateConfig { *self.pos_seal_duplication_tracking } + pub fn pos_seal_activation_gate_enabled(&self, chain_config: &ChainConfig) -> bool { + if let Some(pos_seal_activation_gate) = self.pos_seal_activation_gate { + return pos_seal_activation_gate; + } + + match chain_config.chain_type() { + ChainType::Testnet => true, + ChainType::Mainnet | ChainType::Signet | ChainType::Regtest => false, + } + } + pub fn db_reckless_mode_in_ibd_enabled(&self) -> bool { // The library default stays identical to master (opt-in): the experimental // default-on behavior lives at the node-daemon layer (node-lib/src/runner.rs), @@ -101,3 +119,45 @@ impl ChainstateConfig { self.allow_checkpoints_mismatch.unwrap_or(false) } } + +#[cfg(test)] +mod tests { + use super::*; + use common::chain::Destination; + use common::chain::NetUpgrades; + use common::chain::config::Builder as ConfigBuilder; + use std::collections::BTreeMap; + + fn chain_config_for(chain_type: ChainType) -> common::chain::config::ChainConfig { + ConfigBuilder::new(chain_type) + .consensus_upgrades(NetUpgrades::unit_tests()) + .genesis_unittest(Destination::AnyoneCanSpend) + .checkpoints(BTreeMap::new()) + .build() + } + + #[test] + fn seal_gate_default_depends_on_chain_type() { + let config = ChainstateConfig::default(); + + assert!(config.pos_seal_activation_gate_enabled(&chain_config_for(ChainType::Testnet))); + assert!(!config.pos_seal_activation_gate_enabled(&chain_config_for(ChainType::Mainnet))); + assert!(!config.pos_seal_activation_gate_enabled(&chain_config_for(ChainType::Signet))); + assert!(!config.pos_seal_activation_gate_enabled(&chain_config_for(ChainType::Regtest))); + } + + #[test] + fn seal_gate_explicit_setting_overrides_the_default() { + let enabled = ChainstateConfig { + pos_seal_activation_gate: Some(true), + ..Default::default() + }; + assert!(enabled.pos_seal_activation_gate_enabled(&chain_config_for(ChainType::Mainnet))); + + let disabled = ChainstateConfig { + pos_seal_activation_gate: Some(false), + ..Default::default() + }; + assert!(!disabled.pos_seal_activation_gate_enabled(&chain_config_for(ChainType::Testnet))); + } +} 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..214bcaac3a 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,66 @@ 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 enabled by default only on + /// testnet chains and disabled by default elsewhere, + /// it never fires during the initial block download or on the reorgs of the + /// user-initiated block invalidation path, and it is fail-open: a block that + /// does not yield a well-formed seal (PoW, genesis, malformed PoS data) is + /// never classified as a duplicate, and a segment that contains at least one + /// non-duplicate block proceeds under the ordinary trust comparison. + /// + /// A refusal is a no-op: the candidate chain stays stored, valid and + /// relayable, and every later activation attempt re-runs this classification, + /// so a refused branch that gains a block with a fresh seal becomes + /// activatable. + fn reorg_segment_activation_refused( + &mut self, + new_block_index: &BlockIndex, + best_block_id: &Id, + activation_context: ChainActivationContext, + ) -> Result { + if !self.chainstate_config.pos_seal_activation_gate_enabled(self.chain_config) { + return Ok(false); + } + if activation_context.seal_activation_gate_bypassed() { + return Ok(false); + } + + let new_chain = self + .get_new_chain(new_block_index) + .map_err(|e| { + BlockError::InvariantErrorFailedToFindNewChainPath( + (*new_block_index.block_id()).into(), + *best_block_id, + e, + ) + }) + .log_err()?; + + if new_chain.is_empty() { + // Unreachable through the current callers: a candidate with strictly + // higher trust is never part of the main chain, so the walk to it is + // non-empty. The gate declines to refuse here; the ordinary path + // below then enforces its own empty-chain invariant. + return Ok(false); + } + + if segment_seals_all_duplicated(&self.db_tx, &new_chain)? { + log::info!( + "Not activating a chain whose new segment consists only of blocks reusing \ + already-known PoS consensus proofs" + ); + return Ok(true); + } + + Ok(false) + } + #[log_error] pub fn persist_block(&mut self, block: &WithId) -> Result<(), BlockError> { if self.db_tx.block_exists(&block.get_id()).map_err(BlockError::from)? { @@ -1614,6 +1682,74 @@ pub enum ReorgError { OtherError(#[from] BlockError), } +/// The context of a best-chain activation attempt. +/// +/// The PoS seal activation gate (see +/// `ChainstateConfig::pos_seal_activation_gate`) must never influence chain +/// re-activations driven by the user-initiated block invalidation path, nor the +/// initial block download, where the liveness of the bootstrap outweighs +/// containment. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChainActivationContext { + /// A newly processed block is being connected during normal operation. + BlockProcessing { in_initial_block_download: bool }, + /// The best chain is being re-activated after user-initiated block invalidation. + InvalidationRecovery, +} + +impl ChainActivationContext { + /// Whether the PoS seal activation gate must be bypassed for this activation. + fn seal_activation_gate_bypassed(&self) -> bool { + match self { + ChainActivationContext::BlockProcessing { + in_initial_block_download, + } => *in_initial_block_download, + ChainActivationContext::InvalidationRecovery => true, + } + } +} + +/// Classifies whether every block of the given activation segment carries a +/// duplicate-seal PoS consensus proof (a proof already seen on another known +/// block, per the seal duplication index). A block that does not yield a +/// well-formed seal is never classified as a duplicate, and an empty segment is +/// never refused. +/// +/// Sightings are permanent: the index is a historical record, so entries are +/// not pruned when a block is invalidated, and the classification does not +/// skip invalidated partner blocks. This is deliberate fail-closed behavior. +/// An honest segment always carries at least one fresh seal (honestly-mined +/// VRF proofs are unique), so the gate cannot refuse an honest chain, while +/// counting only valid partners would let an attacker make a reused seal look +/// unique again by having one of its twins invalidated -- re-opening exactly +/// the trust-inflation construction the gate exists to refuse. A refused chain +/// always recovers by extending with a single fresh-seal block. +fn segment_seals_all_duplicated( + 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 81c589604b..cc35d0d70a 100644 --- a/chainstate/src/detail/chainstateref/seal_index.rs +++ b/chainstate/src/detail/chainstateref/seal_index.rs @@ -663,4 +663,177 @@ 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_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 + // 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)); + } + + #[test] + fn seal_activation_gate_bypass_matrix() { + use crate::detail::chainstateref::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()); + } + + /// 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; + + 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), + ); + // 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(2), + &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 (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. + 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/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 b9e564cd68..97fceca84f 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::{ @@ -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, @@ -379,6 +390,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 +463,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 +551,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 +562,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/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 223fe48941..35cd6bf481 100644 --- a/chainstate/test-suite/src/tests/seal_duplication_tests.rs +++ b/chainstate/test-suite/src/tests/seal_duplication_tests.rs @@ -19,12 +19,15 @@ 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, - 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}, @@ -37,8 +40,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 @@ -156,6 +161,163 @@ 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. 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()); + let parent_is_pos = parent_reward_outputs + .get(&OutPointSourceId::BlockReward(parent_id.into())) + .is_some_and(|outputs| !outputs.is_empty()); + + 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_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 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); + // 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()); + 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. @@ -217,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) = @@ -311,3 +476,1216 @@ fn duplicate_seal_records_survive_reorg(#[case] seed: Seed) { vec![block_id_a, block_id_b] ); } + +// --------------------------------------------------------------- +// PoS seal activation gate +// +// 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(), + ..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. +#[allow(clippy::too_many_arguments)] +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, + timestamp_offset_seconds: u64, +) -> 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 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())) + .is_some_and(|outputs| !outputs.is_empty()); + + 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 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_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(), + &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"); + + 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.clone()) + .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, + 90, + ); + + 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) + ); +} + +// --------------------------------------------------------------- +// 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 that contains a fresh proof. +// --------------------------------------------------------------- + +/// 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, + &stake_pool_outpoint, + 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, + &stake_pool_outpoint, + 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, 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_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) = + 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, + &stake_pool_outpoint, + 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: 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. +#[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); + // 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!( + db_tx.get_block(block_id).unwrap().is_some(), + "variant {block_id} must be stored", + ); + } + let evidence = db_tx.get_duplicate_seal_evidence(&seal).unwrap().unwrap(); + // 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 +/// 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())] +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, + &stake_pool_outpoint, + 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, + &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 + // 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()); + } +} + +// 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) + ); +} + +/// 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). +/// 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(), + // 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() + } + }; + 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) +} 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..67f7e64521 100644 --- a/node-lib/src/config_files/chainstate/mod.rs +++ b/node-lib/src/config_files/chainstate/mod.rs @@ -50,6 +50,13 @@ 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. + /// 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, } impl From for ChainstateConfig { @@ -62,6 +69,7 @@ impl From for ChainstateConfig { enable_heavy_checks, allow_checkpoints_mismatch, pos_seal_duplication_tracking, + pos_seal_activation_gate, } = config_file; ChainstateConfig { @@ -72,6 +80,7 @@ impl From for ChainstateConfig { enable_heavy_checks, allow_checkpoints_mismatch, pos_seal_duplication_tracking: pos_seal_duplication_tracking.into(), + pos_seal_activation_gate, } } } 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,