Compare commits

...

12 Commits

Author SHA1 Message Date
5e4267fdde
extend event during bridging with exodus_session for UI only
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2026-11-19 17:31:59 +03:00
f526774201
bump runtime version for the upgrade
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2026-11-19 17:15:00 +03:00
26372deadb
compute round 6 merkle proof depth from highest authority index and preserve proof on retry
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2026-11-19 16:05:27 +03:00
c0286574ac
bump spec_version to 17 and crate version to 4.0.23
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2026-11-19 14:44:23 +03:00
ad4c712fbf
stagger DKG offchain submissions using adaptive probability
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2026-11-19 14:41:41 +03:00
279b71832b
scope DKG round 5 lookup and storage cleanup to active curve/index
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2026-11-19 13:31:59 +03:00
2a10db05c5
initialize consensus deadline on resize and guard unready attestations in OCW
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2026-11-17 14:47:19 +03:00
9a7deaa39b
bump spec_version to 15 and crate version to 4.0.21
Signed-off-by: Uncle Fatso <uncle.fatso@ghostchain.io>
2026-11-16 20:15:15 +03:00
ca0988e011
fix offchain submission probability window calculation and saturating block math
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2026-11-16 20:10:51 +03:00
0af8a71d6a
clarify get_submission_probability parameters
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2026-11-16 20:09:11 +03:00
2a6e31db57
align with updated probability signature and skip logic
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2026-11-10 14:05:28 +03:00
07b222468f
scale submission probability linearly with elapsed blocks and update skip logic
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2026-11-10 14:03:46 +03:00
16 changed files with 314 additions and 167 deletions

10
Cargo.lock generated
View File

@ -1195,7 +1195,7 @@ dependencies = [
[[package]]
name = "casper-runtime"
version = "4.0.20"
version = "4.0.25"
dependencies = [
"casper-runtime-constants",
"frame-benchmarking",
@ -3685,7 +3685,7 @@ dependencies = [
[[package]]
name = "ghost-exodus"
version = "0.1.7"
version = "0.1.11"
dependencies = [
"chacha20poly1305",
"frame-benchmarking",
@ -3762,7 +3762,7 @@ dependencies = [
[[package]]
name = "ghost-helpers"
version = "0.0.16"
version = "0.0.18"
dependencies = [
"frame-support",
"ghost-traits",
@ -4090,7 +4090,7 @@ dependencies = [
[[package]]
name = "ghost-traits"
version = "0.4.10"
version = "0.4.11"
dependencies = [
"frame-support",
"frost-core",
@ -4114,7 +4114,7 @@ dependencies = [
[[package]]
name = "ghost-weaver"
version = "0.0.27"
version = "0.0.29"
dependencies = [
"frame-benchmarking",
"frame-support",

View File

@ -1,6 +1,6 @@
[package]
name = "ghost-exodus"
version = "0.1.7"
version = "0.1.11"
description = "Threshold signature generation with DKG included"
license.workspace = true
authors.workspace = true

View File

@ -20,8 +20,8 @@ use sp_runtime::{
storage::StorageValueRef,
storage_lock::{StorageLock, Time},
},
traits::UniqueSaturatedInto,
Saturating, Perbill,
traits::{One, TrailingZeroInput, UniqueSaturatedInto},
Saturating, Perbill, PerThing,
};
use sp_std::{vec, vec::Vec, collections::btree_map::BTreeMap};
@ -30,7 +30,8 @@ use sp_runtime::traits::BlockNumberProvider;
use sp_io::hashing::blake2_256;
use ghost_helpers::{
get_byzantium_quorum_threshold, SubstrateBlake2Hasher,
get_byzantium_quorum_threshold, get_submission_probability,
SubstrateBlake2Hasher,
lcg::PerfectSlotMapperU128,
hash_chain::cumulative_hash,
networks::{NetworkData, NetworkCurve, NetworkType},
@ -454,6 +455,7 @@ pub mod pallet {
amount: BalanceOf<T>,
bounty: Perbill,
receiver: EvmAddress,
exodus_session: ExodusSession,
}
}
@ -1797,7 +1799,7 @@ pub mod pallet {
Fortitude::Polite,
)?;
Self::do_register_evm_bridge_out_exodus(
let exodus_session = Self::do_register_evm_bridge_out_exodus(
network_id,
actual_amount,
bounty,
@ -1810,6 +1812,7 @@ pub mod pallet {
amount: actual_amount,
bounty,
receiver,
exodus_session,
});
Ok(())
@ -2083,7 +2086,7 @@ impl<T: Config> Pallet<T> {
fn do_register_evm_exodus(
network_id: NetworkIdOf<T>,
exodus_request: ExodusRequest<T>,
) -> DispatchResult {
) -> Result<ExodusSession, DispatchError> {
let network = T::NetworkDataHandler::get(&network_id)
.ok_or(Error::<T>::NetworkDoesNotExist)?;
@ -2099,7 +2102,7 @@ impl<T: Config> Pallet<T> {
ExodusRequests::<T>::insert((&network.curve, &exodus_context), exodus_request);
Ok(())
Ok(exodus_session)
}
fn do_register_evm_bridge_out_exodus(
@ -2107,7 +2110,7 @@ impl<T: Config> Pallet<T> {
amount: BalanceOf<T>,
bounty: Perbill,
receiver: EvmAddress,
) -> DispatchResult {
) -> Result<ExodusSession, DispatchError> {
let out_amount =
T::NetworkDataHandler::register_outgoing(&network_id, amount)
.map_err(|_| Error::<T>::BridgeOverflow)?;
@ -2121,7 +2124,7 @@ impl<T: Config> Pallet<T> {
network_id: NetworkIdOf<T>,
target_address: EvmAddress,
governance_action: GovernanceAction,
) -> DispatchResult {
) -> Result<ExodusSession, DispatchError> {
let evm_governance_request =
ExodusRequest::evm_governance(target_address, governance_action);
@ -2189,7 +2192,8 @@ impl<T: Config> Pallet<T> {
network_curve,
maybe_cursor,
|cursor_slice, weight| {
let result = Round0Packages::<T>::clear(
let result = Round0Packages::<T>::clear_prefix(
network_curve,
T::RemovalLimit::get(),
cursor_slice,
);
@ -2279,15 +2283,12 @@ impl<T: Config> Pallet<T> {
dkg_qualification: &mut PendingDkgAuthorities<T>,
maybe_cursor: Option<BoundedVec<u8, T::MaxCursorLen>>,
) -> (Weight, bool) {
let dkg_index = dkg_qualification.get_dkg_index();
Self::prepare_round_storage(
network_curve,
maybe_cursor,
|cursor_slice, weight| {
let prev_dkg_index = dkg_index.saturating_sub(1);
let result = Verifications::<T>::clear_prefix(
(network_curve, prev_dkg_index),
(network_curve,),
T::RemovalLimit::get(),
cursor_slice,
);
@ -2354,17 +2355,24 @@ impl<T: Config> Pallet<T> {
dkg_qualification: &mut PendingDkgAuthorities<T>,
maybe_cursor: Option<BoundedVec<u8, T::MaxCursorLen>>,
) -> (Weight, bool) {
let dkg_index = dkg_qualification.get_dkg_index();
Self::prepare_round_storage(
network_curve,
maybe_cursor,
|_, weight| {
let prev_dkg_index = dkg_index.saturating_sub(1);
|cursor_slice, weight| {
let result = VerifyingKeyConsensus::<T>::clear_prefix(
network_curve,
T::RemovalLimit::get(),
cursor_slice,
);
weight.saturating_accrue(T::DbWeight::get().writes(1));
VerifyingKeyConsensus::<T>::remove(network_curve, &prev_dkg_index);
None
weight.saturating_accrue(
T::DbWeight::get().reads_writes(
(result.backend as u64).saturating_add(1),
result.backend as u64
)
);
result.maybe_cursor
},
|weight| {
weight.saturating_accrue(T::DbWeight::get().reads(2));
@ -2375,7 +2383,7 @@ impl<T: Config> Pallet<T> {
let mut number_of_leaked_keys = 0;
let qualified_indexes = dkg_qualification.get_indexes();
let total_authorities_len = qualified_indexes.count_ones::<usize>();
let total_authorities_len = qualified_indexes.active_bits_count() as usize;
let mut failed_authorities = ParticipantsBitmap::<T>::empty_from(
&qualified_indexes,
@ -2463,7 +2471,6 @@ impl<T: Config> Pallet<T> {
return None;
}
let result = VerifyingShares::<T>::clear_prefix(
(network_curve, previous_dkg_index),
T::RemovalLimit::get(),
@ -3201,8 +3208,12 @@ impl<T: Config> Pallet<T> {
return Err(InvalidTransaction::BadProof);
}
let estimated_proof_count = state
.count_ones::<usize>()
let leaf_capacity = state
.highest_bit::<usize>()
.map(|bit| bit.saturating_add(1))
.unwrap_or(0);
let estimated_proof_count = leaf_capacity
.next_power_of_two()
.trailing_zeros();
@ -3782,6 +3793,65 @@ impl<T: Config> Pallet<T> {
Ok(results)
}
fn should_skip_submission(
network_curve: NetworkCurve,
current_block: BlockNumberFor<T>,
qualification_authorities: &PendingDkgAuthorities<T>,
) -> bool {
let dkg_phase = qualification_authorities.get_phase();
let dkg_index = qualification_authorities.get_dkg_index();
let dkg_round_period: BlockNumberFor<T> = T::DkgRoundPeriod::get()
.unique_saturated_into();
let blocks_remaining = qualification_authorities
.get_release_block()
.saturating_sub(current_block);
if blocks_remaining <= 2u32.into() { return false; }
let elapsed_blocks = dkg_round_period
.saturating_sub(blocks_remaining)
.saturating_add(One::one());
let total_authorities = if dkg_phase == DkgPhase::Round0 {
QualificationAuthorities::<T>::decode_len(&network_curve).unwrap_or_default()
} else {
qualification_authorities.count_ones::<usize>()
};
let values_count = match dkg_phase {
DkgPhase::Round0 => qualification_authorities.count_ones::<usize>(),
DkgPhase::Round1 => Round1Packages::<T>::get(network_curve).count_ones::<usize>(),
DkgPhase::Round2 => Round2Packages::<T>::get(network_curve).count_ones::<usize>(),
DkgPhase::Round3 => Complaints::<T>::get(network_curve).len(),
DkgPhase::Round4 => Justifications::<T>::get(network_curve).len(),
DkgPhase::Round5 => {
let consensus = VerifyingKeyConsensus::<T>::get(network_curve, dkg_index);
consensus.state.participants.count_ones::<usize>()
},
DkgPhase::Round6 => {
let shares = VerifyingSharesParticipants::<T>::get(network_curve, dkg_index);
shares.count_ones::<usize>()
},
_ => return false,
};
let submission_probability = get_submission_probability(
total_authorities,
values_count,
dkg_round_period,
elapsed_blocks
);
let seed = sp_io::offchain::random_seed();
let randomness = <u32>::decode(&mut TrailingZeroInput::new(seed.as_ref()))
.expect("input is padded with zeroes; qed");
let random_roll = Perbill::from_parts(randomness % Perbill::ACCURACY);
random_roll >= submission_probability
}
fn dkg_run_process(
authority_index: AuthIndex,
authority_key: T::AuthorityId,
@ -3792,6 +3862,16 @@ impl<T: Config> Pallet<T> {
let block_longevity: BlockNumberFor<T> =
T::UnsignedLongevity::get().unique_saturated_into();
if Self::should_skip_submission(
network_curve,
current_block,
qualification_authorities,
) {
return Ok(ExodusOk::DkgRoundSubmissionSkipped(
authority_index, network_curve,
));
}
let dkg_storage = DkgStorage::default()
.with_network_curve(network_curve)
.with_current_block(current_block)
@ -4574,6 +4654,7 @@ impl<T: Config> Pallet<T> {
) -> ExodusResult<ExodusOk<NetworkCurve, NetworkIdOf<T>>> {
let network_curve = dkg_storage.network_curve;
let authority_index = dkg_storage.authority_index;
let dkg_index = qualification_state.get_dkg_index();
if !qualification_state.contains_index(authority_index) {
return Ok(ExodusOk::DkgNotPartOfRound(
@ -4584,8 +4665,10 @@ impl<T: Config> Pallet<T> {
}
let verification_found_for_self =
VerifyingKeyConsensus::<T>::iter_values()
.any(|consensus| consensus.state.participants.contains(authority_index));
VerifyingKeyConsensus::<T>::get(&network_curve, &dkg_index)
.state
.participants
.contains(authority_index);
if verification_found_for_self {
return Ok(ExodusOk::DkgRoundAlreadyPassed(
@ -4595,7 +4678,6 @@ impl<T: Config> Pallet<T> {
));
}
let dkg_index = qualification_state.get_dkg_index();
let dkg_based_prefix = Self::create_dkg_based_prefix(dkg_index);
let mut round_metadata = dkg_storage.read_local_storage(
@ -4756,7 +4838,7 @@ impl<T: Config> Pallet<T> {
}
let Some(DkgStorageEnum::Round5 { secret_share, merkle_proof }) =
round_metadata.into_inner_mut() else {
round_metadata.into_inner() else {
return Ok(ExodusOk::DkgRoundNothingStored(
ROUND_NUMBER_6,
authority_index,
@ -4767,7 +4849,7 @@ impl<T: Config> Pallet<T> {
let verifying_share = network_curve
.dkg_derive_verifying_share(secret_share)?;
let owned_merkle_proof = core::mem::take(merkle_proof);
let owned_merkle_proof = merkle_proof.clone();
let current_dkg_index = qualification_state.get_dkg_index();
dkg_storage.prepare_signed_call_with_context(
@ -5120,14 +5202,10 @@ impl<T: Config> Pallet<T> {
.ok()
.filter(|b| b.len() == max_size);
match maybe_encoded_bytes {
Some(encoded) => {
if let Some(_) = bitmask.insert(receiver_index) {
blob.extend_from_slice(&encoded);
}
},
None => {
blob.extend_from_slice(&vec![0u8; max_size]);
if let Some(_) = bitmask.insert(receiver_index) {
match maybe_encoded_bytes {
Some(encoded) => blob.extend_from_slice(&encoded),
None => blob.extend_from_slice(&vec![0u8; max_size]),
}
}
}
@ -5323,12 +5401,17 @@ impl<T: Config> EvmGovernanceRegistrar<NetworkIdOf<T>, EvmAddress, GovernanceAct
network_id: NetworkIdOf<T>,
target_address: EvmAddress,
governance_action: GovernanceAction,
) -> DispatchResult {
Self::do_register_evm_governance(
) -> Result<u128, DispatchError> {
let exodus_session = Self::do_register_evm_governance(
network_id,
target_address,
governance_action,
)
)?;
let exodus_session_u128: u128 = exodus_session
.unique_saturated_into();
Ok(exodus_session_u128)
}
}

View File

@ -1433,6 +1433,7 @@ fn register_evm_bridge_out_dynamic_threshold_works() {
amount: amount_1,
bounty,
receiver,
exodus_session: 0,
}
));

View File

@ -10,6 +10,7 @@ pub enum ExodusOk<NetworkCurve, NetworkId> {
ExodusSignedPartially(ExodusSession, NetworkId, RoastSession, AuthIndex, NetworkCurve),
ExodusVerifyingShareMissed(AuthIndex, DkgIndex, NetworkCurve),
DkgRoundSubmissionSkipped(AuthIndex, NetworkCurve),
DkgNotPartOfRound(u8, AuthIndex, NetworkCurve),
DkgRoundRegistered(u8, AuthIndex, NetworkCurve),
DkgPreviousPurged(AuthIndex, NetworkCurve, u32),
@ -47,6 +48,7 @@ where
},
ExodusOk::ExodusVerifyingShareMissed(auth_index, dkg_index, curve) => write!(fmt, "No verifying share found for authority #{auth_index} in EXODUS round based on DKG session #{dkg_index} for curve {curve}."),
ExodusOk::DkgRoundSubmissionSkipped(auth_index, curve) => write!(fmt, "DKG authority #{auth_index} skipped submission for network curve {curve} temporarily."),
ExodusOk::DkgNotPartOfRound(round, auth_index, curve) => write!(fmt, "DKG authority #{auth_index} is not part of Round {round} for network curve {curve}."),
ExodusOk::DkgRoundRegistered(round, auth_index, curve) => write!(fmt, "DKG Round {round} registered by authority #{auth_index} for network curve {curve}."),
ExodusOk::DkgPreviousPurged(auth_index, curve, removed_count) => write!(fmt, "Storage prepared for a new DKG session by authority #{auth_index} for network curve {curve}. {removed_count} entries removed."),

View File

@ -1,6 +1,6 @@
[package]
name = "ghost-helpers"
version = "0.0.16"
version = "0.0.18"
description = "Cryptographic utility suite for custom runtimes: optimized Bitmaps, UTXO parsing, Merkle Tree proofs, and Hash Chain components."
license.workspace = true
authors.workspace = true

View File

@ -52,30 +52,27 @@ where
pub fn get_submission_probability<B>(
participants_count: usize,
values_count: usize,
blocks_left: B
participated_count: usize,
block_duration: B,
elapsed_blocks: B
) -> Perbill
where
B: UniqueSaturatedInto<u32>,
B: UniqueSaturatedInto<u64>,
{
// y = min(1, (1/6) + (A-C)/2x)
let a: u32 = participants_count.unique_saturated_into();
let c: u32 = values_count.unique_saturated_into();
let x: u32 = blocks_left.unique_saturated_into();
// P = ((participants_count - participated_count) / participants_count)
// * (elapsed_blocks / block_duration)
if a == 0 { return Perbill::zero(); }
let participants_count_u32: u32 = participants_count.unique_saturated_into();
let participated_count_u32: u32 = participated_count.unique_saturated_into();
let part_1 = Perbill::from_percent(6);
let part_2 = if x > 0 {
let numerator = a.saturating_sub(c);
let denominator = x.saturating_mul(2);
Perbill::from_rational(numerator, denominator)
} else {
if c < a { Perbill::one() }
else { Perbill::zero() }
};
let block_duration_u64: u64 = block_duration.unique_saturated_into();
let elapsed_blocks_u64: u64 = elapsed_blocks.unique_saturated_into();
part_1.saturating_add(part_2)
let participants_left = participants_count_u32.saturating_sub(participated_count_u32);
let authorities_ratio = Perbill::from_rational(participants_left, participants_count_u32);
let time_window_ratio = Perbill::from_rational(elapsed_blocks_u64, block_duration_u64);
authorities_ratio.saturating_mul(time_window_ratio)
}
macro_rules! impl_ghost_hasher {
@ -186,36 +183,67 @@ mod tests {
}
#[test]
fn test_base_probability_when_plenty_of_time() {
let prob = get_submission_probability(100, 0, 10000u32);
assert!(prob > Perbill::from_percent(6));
assert!(prob < Perbill::from_percent(7));
fn test_submission_probability_handles_zero_participants() {
assert_eq!(get_submission_probability(0, 0, 100u32, 50u32), Perbill::from_percent(50));
assert_eq!(get_submission_probability(0, 0, 100u32, 150u32), Perbill::one())
}
#[test]
fn test_urgency_increases_as_blocks_shrink() {
let prob_far = get_submission_probability(20, 10, 10u32);
assert_eq!(prob_far, Perbill::from_percent(56));
let prob_close = get_submission_probability(20, 10, 2u32);
assert_eq!(prob_close, Perbill::one());
fn test_submission_probability_handles_deadline_edge_cases() {
assert_eq!(get_submission_probability(10, 0, 0u32, 0u32), Perbill::one());
assert_eq!(get_submission_probability(10, 0, 100u32, 100u32), Perbill::one());
assert_eq!(get_submission_probability(10, 0, 100u32, 0u32), Perbill::zero());
assert_eq!(get_submission_probability(10, 2, 100u32, 101u32), Perbill::from_percent(80));
}
#[test]
fn test_deadline_reached_but_votes_missing() {
let prob = get_submission_probability(10, 5, 0u32);
assert_eq!(prob, Perbill::one());
fn test_submission_probability_handles_probability_stragglers_edge_cases() {
assert_eq!(get_submission_probability(10, 0, 100u32, 0u32), Perbill::zero());
assert_eq!(get_submission_probability(10, 10, 100u32, 0u32), Perbill::zero());
assert_eq!(get_submission_probability(10, 15, 100u32, 0u32), Perbill::zero());
}
#[test]
fn test_all_votes_collected() {
let prob = get_submission_probability(10, 10, 5u32);
assert_eq!(prob, Perbill::from_percent(6));
fn test_submission_probability_calculates_normal_probabilities_accurately() {
assert_eq!(get_submission_probability(10, 0, 100u32, 25u32), Perbill::from_percent(25));
assert_eq!(get_submission_probability(10, 5, 100u32, 50u32), Perbill::from_percent(25));
assert_eq!(get_submission_probability(4, 1, 10u32, 2u32), Perbill::from_percent(15));
}
#[test]
fn test_zero_participants_edge_case() {
let prob = get_submission_probability(0, 0, 5u32);
assert_eq!(prob, Perbill::zero());
fn test_submission_probability_progression_from_start_to_deadline() {
// Tick 0: nobody participated, 0 blocks elapsed -> 0%
assert_eq!(get_submission_probability(10, 0, 100u32, 0u32), Perbill::zero());
// Tick 1: nobody participated, 1 block elapsed -> 1%
assert_eq!(get_submission_probability(10, 0, 100u32, 1u32), Perbill::from_percent(1));
// Deadline reached: nobody participated, 100/100 blocks elapsed -> 100%
assert_eq!(get_submission_probability(10, 0, 100u32, 100u32), Perbill::one());
// Past deadline: clamps safely at 100% (or authorities_ratio if some participated)
assert_eq!(get_submission_probability(10, 0, 100u32, 150u32), Perbill::one());
assert_eq!(get_submission_probability(10, 4, 100u32, 150u32), Perbill::from_percent(60));
}
#[test]
fn test_submission_probability_participation_saturation() {
// Everyone already participated -> 0% regardless of block progress
assert_eq!(get_submission_probability(10, 10, 100u32, 50u32), Perbill::zero());
assert_eq!(get_submission_probability(10, 10, 100u32, 100u32), Perbill::zero());
// More participated than total (defensive saturating_sub check) -> 0%
assert_eq!(get_submission_probability(10, 15, 100u32, 50u32), Perbill::zero());
}
#[test]
fn test_submission_probability_repeating_fractions_and_precision() {
// 3 participants, 1 participated -> 2/3 left
// 1 of 3 blocks elapsed -> 1/3 time
// Expected: (2/3) * (1/3) = 2/9 = 222_222_222 parts per billion
assert_eq!(get_submission_probability(3, 1, 3u32, 1u32), Perbill::from_parts(222_222_221));
// Large block window (e.g., 10,000 blocks) -> 1 block elapsed = 0.01% (100_000 ppb)
assert_eq!(get_submission_probability(10, 0, 10_000u32, 1u32), Perbill::from_parts(100_000));
}
}

View File

@ -1,6 +1,6 @@
[package]
name = "ghost-traits"
version = "0.4.10"
version = "0.4.11"
description = "Shared traits including `GhostHasher`, `NetworkDataBasicHandler`, `BoundedBTreeMap`, `MerkleTree` and more."
license.workspace = true
authors.workspace = true

View File

@ -128,5 +128,5 @@ pub trait EvmGovernanceRegistrar<NetworkId, EvmAddress, GovernanceAction> {
network_id: NetworkId,
target_address: EvmAddress,
governance_action: GovernanceAction
) -> frame_support::dispatch::DispatchResult;
) -> Result<u128, frame_support::pallet_prelude::DispatchError>;
}

View File

@ -1,6 +1,6 @@
[package]
name = "ghost-weaver"
version = "0.0.27"
version = "0.0.29"
description = "Weaving a secure cryptographic tapestry across different external chains."
license.workspace = true
authors.workspace = true

View File

@ -7,7 +7,7 @@ pub enum WeavingError<NetworkId> {
UnknownWeavingPhase(NetworkId),
OffchainLockPeriod(NetworkId),
NoEndpointsAvailable(NetworkId),
ContradictoryHashes(NetworkId),
ContradictoryHashes(NetworkId, u32),
ContradictoryBlocks(u32, ExternalBlockNumber, NetworkId),
}
@ -34,9 +34,9 @@ impl<NetworkId: core::fmt::Debug> core::fmt::Debug for WeavingError<NetworkId> {
"No RPC URLs configured for network #{:?}.",
network_id
),
Self::ContradictoryHashes(network_id) => write!(
Self::ContradictoryHashes(network_id, len) => write!(
fmt,
"Divergence among reported hashes for network #{:?}.",
"Divergence among {len} reported hashes for network #{:?}.",
network_id
),
Self::ContradictoryBlocks(len, deviation, network_id) => {

View File

@ -24,7 +24,7 @@ use sp_runtime::{
},
traits::{
TrailingZeroInput, BlockNumberProvider, Saturating,
UniqueSaturatedInto,
UniqueSaturatedInto, One,
},
RuntimeAppPublic, Perbill, PerThing,
};
@ -531,11 +531,10 @@ pub mod pallet {
let mut weight = T::DbWeight::get().reads(1);
let converted_block: usize = current_block.unique_saturated_into();
let (network_id, data) = match T::NetworkDataHandler::network_for_block(converted_block)
{
Some((network_id, data)) => (network_id, data),
None => return weight,
};
let Some((network_id, data)) =
T::NetworkDataHandler::network_for_block(converted_block) else {
return weight;
};
weight.saturating_accrue(T::DbWeight::get().reads_writes(2, 1));
let len = Authorities::<T>::decode_len().unwrap_or_default();
@ -586,45 +585,44 @@ pub mod pallet {
if current_block < next_attempt_block { return weight; }
weight.saturating_accrue(T::DbWeight::get().reads(1));
let attestation_len = NetworkAttestations::<T>::decode_len(&network_id);
weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
let mut maybe_block_numbers = NetworkAttestations::<T>::mutate(
&network_id,
|attestations| -> Option<Vec<ExternalBlockNumber>> {
if attestations.len() != len {
attestations.bounded_resize(len, None);
return None;
}
if attestation_len.unwrap_or(0) != len {
weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
NetworkAttestations::<T>::mutate(&network_id, |attestations| {
attestations.bounded_resize(len, None);
});
return weight;
Some(attestations.iter().flatten().copied().collect())
}
);
if let Some(mut block_numbers) = maybe_block_numbers.as_mut() {
if let Some(median_block) = Self::validate_block_numbers_consensus(
&mut block_numbers,
data.block_deviation,
weaving_threshold,
) {
let tapestry_draft = TapestryDraftBuilder::default()
.with_block_delay(T::WeavingDelay::get())
.with_current_block(current_block)
.with_median_external(median_block)
.build();
TapestryStrands::<T>::remove(&network_id);
TapestryDrafts::<T>::insert(&network_id, tapestry_draft);
weight.saturating_accrue(T::DbWeight::get().writes(2));
}
}
let attestation_delay_converted: BlockNumberFor<T> =
T::AttestationDelay::get().unique_saturated_into();
weight.saturating_accrue(T::DbWeight::get().writes(1));
let next_release_block = current_block + attestation_delay_converted;
let next_release_block = attestation_delay_converted.saturating_add(current_block);
NextConsensusAttemptBlocks::<T>::insert(network_id, next_release_block);
let mut block_numbers = NetworkAttestations::<T>::get(&network_id)
.iter()
.flatten()
.copied()
.collect();
if let Some(median_block) = Self::validate_block_numbers_consensus(
&mut block_numbers,
data.block_deviation,
weaving_threshold,
) {
let tapestry_draft = TapestryDraftBuilder::default()
.with_block_delay(T::WeavingDelay::get())
.with_current_block(current_block)
.with_median_external(median_block)
.build();
TapestryStrands::<T>::remove(&network_id);
TapestryDrafts::<T>::insert(&network_id, tapestry_draft);
weight.saturating_accrue(T::DbWeight::get().writes(2));
}
weight.saturating_accrue(T::DbWeight::get().writes(1));
}
}
@ -830,12 +828,25 @@ impl<T: Config> Pallet<T> {
return Err(WeavingError::NoEndpointsAvailable(network_id));
}
let check_probability = |values_count: usize, blocks_left: BlockNumberFor<T>| -> bool {
let should_skip_submission = |
values_count: usize,
block_until: BlockNumberFor<T>,
constant_delay: u64,
| -> bool {
let total_authorities = Authorities::<T>::decode_len().unwrap_or(1);
let constant_block_delay: BlockNumberFor<T> = constant_delay
.unique_saturated_into();
let blocks_remaining = block_until.saturating_sub(current_block);
let elapsed_blocks = constant_block_delay
.saturating_sub(blocks_remaining)
.saturating_add(One::one());
let submission_probability = get_submission_probability(
total_authorities,
values_count,
blocks_left,
constant_block_delay,
elapsed_blocks
);
let seed = sp_io::offchain::random_seed();
@ -843,7 +854,7 @@ impl<T: Config> Pallet<T> {
.expect("input is padded with zeroes; qed");
let random_roll = Perbill::from_parts(randomness % Perbill::ACCURACY);
random_roll > submission_probability
random_roll >= submission_probability
};
match TapestryDrafts::<T>::get(&network_id) {
@ -854,7 +865,7 @@ impl<T: Config> Pallet<T> {
deadline,
&network_data,
&rpc_endpoints,
check_probability,
should_skip_submission,
),
None => Self::try_request_and_submit_block(
network_id,
@ -862,7 +873,7 @@ impl<T: Config> Pallet<T> {
deadline,
&network_data,
&rpc_endpoints,
check_probability,
should_skip_submission,
),
}
}
@ -874,17 +885,17 @@ impl<T: Config> Pallet<T> {
deadline: rt_offchain::Timestamp,
network_data: &NetworkData,
rpc_endpoints: &Vec<Vec<u8>>,
check_probability: impl Fn(usize, BlockNumberFor<T>) -> bool,
should_skip_submission: impl Fn(usize, BlockNumberFor<T>, u64) -> bool,
) -> WeavingResult<T, WeavingOk<NetworkIdOf<T>>> {
let weaving_session = CurrentWeavingSession::<T>::get(&network_id);
let block_until = tapestry_draft.until.saturating_sub(current_block);
let weaving_count = WeavingStates::<T>::get(&network_id).count as usize;
if check_probability(weaving_count, block_until) {
if should_skip_submission(
WeavingStates::<T>::get(&network_id).count as usize,
tapestry_draft.until,
T::WeavingDelay::get(),
) {
return Ok(WeavingOk::Skipped(network_id));
}
let weaving_session = CurrentWeavingSession::<T>::get(&network_id);
let target_block = tapestry_draft.median;
let request_id = current_block.unique_saturated_into();
@ -915,9 +926,13 @@ impl<T: Config> Pallet<T> {
.then(|| (*first_hash, *first_next_session))
})
.ok_or(WeavingError::<NetworkIdOf<T>>::ContradictoryHashes(
network_id,
network_id, hashes_and_next_sessions.len() as u32
))?;
if LoomStates::<T>::get(&network_id, &weaving_session).root_hash == first_hash {
return Ok(WeavingOk::HashUnchanged(network_id));
}
let next_session_bytes = first_next_session.to_be_bytes();
let weaving_session_bytes = weaving_session.to_be_bytes();
@ -1012,17 +1027,20 @@ impl<T: Config> Pallet<T> {
deadline: rt_offchain::Timestamp,
network_data: &NetworkData,
rpc_endpoints: &Vec<Vec<u8>>,
check_probability: impl Fn(usize, BlockNumberFor<T>) -> bool,
should_skip_submission: impl Fn(usize, BlockNumberFor<T>, u64) -> bool,
) -> WeavingResult<T, WeavingOk<NetworkIdOf<T>>> {
let next_attempt_block = NextConsensusAttemptBlocks::<T>::get(&network_id);
let block_until = next_attempt_block.saturating_sub(current_block);
let authorities_count = Authorities::<T>::decode_len()
.unwrap_or(0);
let attestations_count = NetworkAttestations::<T>::get(&network_id)
.iter()
.flatten()
.count();
let attestations = NetworkAttestations::<T>::get(&network_id);
let attestations_count = attestations.iter().flatten().count();
let attestations_not_ready = authorities_count != attestations.len();
if check_probability(attestations_count, block_until) {
if attestations_not_ready || should_skip_submission(
attestations_count,
NextConsensusAttemptBlocks::<T>::get(&network_id),
T::AttestationDelay::get(),
) {
return Ok(WeavingOk::Skipped(network_id));
}

View File

@ -97,12 +97,13 @@ fn should_successfully_compute_median_and_start_weaving_round() {
assert!(GhostWeaver::tapestry_drafts(network_id).is_none());
System::set_block_number(LOCK_BLOCK_EXPIRATION + 3);
GhostWeaver::on_initialize(LOCK_BLOCK_EXPIRATION + 3);
let target_block = LOCK_BLOCK_EXPIRATION + 1 + AttestationDelay::get();
System::set_block_number(target_block);
GhostWeaver::on_initialize(target_block);
let round = GhostWeaver::tapestry_drafts(network_id);
assert!(round.is_some());
assert_eq!(round.unwrap().until, LOCK_BLOCK_EXPIRATION + 3 + WeavingDelay::get());
assert_eq!(round.unwrap().until, target_block + WeavingDelay::get());
});
}
@ -140,20 +141,21 @@ fn should_apply_cooldown_delay_on_consensus_failure() {
assert!(GhostWeaver::extend_warp(RuntimeOrigin::none(), att2, sig2).is_ok());
assert!(GhostWeaver::extend_warp(RuntimeOrigin::none(), att3, sig3).is_ok());
System::set_block_number(LOCK_BLOCK_EXPIRATION + 11);
GhostWeaver::on_initialize(LOCK_BLOCK_EXPIRATION + 11);
let first_attempt_block = LOCK_BLOCK_EXPIRATION + 9 + AttestationDelay::get();
System::set_block_number(first_attempt_block);
GhostWeaver::on_initialize(first_attempt_block);
let cooldown_block = GhostWeaver::next_consensus_attempt_blocks(network_id);
assert_eq!(cooldown_block, LOCK_BLOCK_EXPIRATION + 14);
assert_eq!(cooldown_block, first_attempt_block + AttestationDelay::get());
TapestryDrafts::<TestRuntime>::remove(network_id);
System::set_block_number(LOCK_BLOCK_EXPIRATION + 12);
GhostWeaver::on_initialize(LOCK_BLOCK_EXPIRATION+ 12);
System::set_block_number(first_attempt_block + 1);
GhostWeaver::on_initialize(first_attempt_block + 1);
assert!(TapestryDrafts::<TestRuntime>::get(network_id).is_none());
System::set_block_number(LOCK_BLOCK_EXPIRATION + 14);
GhostWeaver::on_initialize(LOCK_BLOCK_EXPIRATION + 14);
System::set_block_number(cooldown_block);
GhostWeaver::on_initialize(cooldown_block);
assert!(TapestryDrafts::<TestRuntime>::get(network_id).is_some());
});
}
@ -340,11 +342,17 @@ fn offchain_worker_should_fetch_block_and_submit_unsigned_tx() {
.and_then(|opt| *opt)
.unwrap_or(0);
let target_utxo_block = if curr_utxo_block % 2 == (LOCK_BLOCK_EXPIRATION + 1) % 2 {
curr_utxo_block
} else {
curr_utxo_block + 1
};
assert_eq!(prev_utxo_block, 0);
assert_eq!(curr_utxo_block, 960127);
assert!(TapestryDrafts::<TestRuntime>::get(&utxo_network_id).is_none());
GhostWeaver::on_initialize(LOCK_BLOCK_EXPIRATION + 3u64);
GhostWeaver::on_initialize(target_utxo_block);
assert!(TapestryDrafts::<TestRuntime>::get(&utxo_network_id).is_some());
});
@ -367,12 +375,17 @@ fn offchain_worker_should_fetch_block_and_submit_unsigned_tx() {
.and_then(|opt| *opt)
.unwrap_or(0);
let target_evm_block = if curr_evm_block % 2 == (LOCK_BLOCK_EXPIRATION + 2) % 2 {
curr_evm_block
} else {
curr_evm_block + 1
};
assert_eq!(prev_evm_block, 0);
assert_eq!(curr_evm_block, 25639556);
assert!(TapestryDrafts::<TestRuntime>::get(&evm_network_id).is_none());
GhostWeaver::on_initialize(LOCK_BLOCK_EXPIRATION + 3u64);
GhostWeaver::on_initialize(LOCK_BLOCK_EXPIRATION + 4u64);
GhostWeaver::on_initialize(target_evm_block);
assert!(TapestryDrafts::<TestRuntime>::get(&evm_network_id).is_some());
});
}

View File

@ -37,6 +37,7 @@ const PROTOCOL_PREFIX: [u8; 7] = [0x47, 0x48, 0x53, 0x54, 0x74, 0x6F, 0x3A];
pub enum WeavingOk<NetworkId> {
Skipped(NetworkId),
HashUnchanged(NetworkId),
Block(ExternalBlockNumber, u32, NetworkId),
Hash(ExternalBlockNumber, H256, WeavingSession, NetworkId),
}
@ -47,9 +48,10 @@ where
{
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
match self {
Self::Skipped(network_id) => write!(fmt, "Submission step skipped for network: {:?} based on probability distribution.", network_id),
Self::Block(block, count, network_id) => write!(fmt, "Verified block height #{:?} for network: {:?} based on {} parsed requests.", block, network_id, count),
Self::Hash(block, hash, next_session, network_id) => write!(fmt, "Extracted Merkle Root {:?} (next session is {:?}) from block #{:?} for network: {:?}.", hash, next_session, block, network_id),
Self::Skipped(network_id) => write!(fmt, "Submission step skipped for network: #{:?} based on probability distribution.", network_id),
Self::HashUnchanged(network_id) => write!(fmt, "Merkle Root unchanged for network: #{:?}, skipping submission.", network_id),
Self::Block(block, count, network_id) => write!(fmt, "Verified block height #{:?} for network: #{:?} based on {} parsed requests.", block, network_id, count),
Self::Hash(block, hash, next_session, network_id) => write!(fmt, "Extracted Merkle Root {:?} (next session is {:?}) from block #{:?} for network: #{:?}.", hash, next_session, block, network_id),
}
}
}

View File

@ -1,6 +1,6 @@
[package]
name = "casper-runtime"
version = "4.0.20"
version = "4.0.25"
build = "build.rs"
description = "Runtime of the Casper Network"
edition.workspace = true

View File

@ -124,7 +124,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("casper"),
impl_name: create_runtime_str!("casper-svengali"),
authoring_version: 0,
spec_version: 14,
spec_version: 19,
impl_version: 0,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,