pub(crate) struct RotateAffidavitKey<T: Config> {
pub by: T::Public,
pub at: BlockNumberFor<T>,
}Expand description
Operational context for affidavit key rotation.
This type represents the contextual information required to observe and commence rotation of the affidavit key, promoting the previously prepared next key to become the active affidavit key once the declaration effects are finalized.
Rotation is a sequential, retry-driven routine that executes as part of the looped offchain workflow. It is entered only after the declaration phase has submitted the declare-affidavit transaction successfully.
§Notes
- This is not a transaction payload.
- This type is never submitted on-chain.
- It is used internally during:
- observation of finalized declaration effects
- validation of next-key availability
- promotion of the next affidavit key to active
- reset of inconsistent key state when rotation cannot proceed
§Dependency: InitAffidavitKey, TryElection, and DeclareAffidavit
This routine depends on the prior initialization, election, and declaration phases. It assumes that:
- a active-tagged affidavit key-pair exists (guaranteed by
InitAffidavitKey), - election has either completed or been safely skipped (handled by
TryElection), - a declare-affidavit transaction has been submitted (by
DeclareAffidavit). - and a next-tagged affidavit key-pair exists,
Whenever these invariants are violated (e.g. missing affidavit keys,
eligibility failure, or window violations), control is redirected to
InitAffidavitKey to repair and re-validate storage and keystore
consistency before retrying rotation observation.
§Fork Awareness
- The
atfield captures the block number at which rotation observation begins. - When executed via offchain workers, this context must tolerate forks, re-orgs, and speculative execution.
- Implementors must ensure idempotency and re-entrancy safety.
§Rotation Flow
The routine verifies that the next affidavit key is referenced in offchain storage and locally available as pair in keystore, then determines whether rotation is currently eligible. If so, the next key is promoted to active and the previous state is cleaned up. If rotation cannot occur within the allowed session window, both active and next keys are reset to recover from inconsistent or stale state.
Failures or inconsistencies at any stage re-enter the initialization phase to re-validate offchain storage and keystore invariants.
loop {
// --- Initialization Phase ---
if !offchain_storage.has_active_affidavit_key()
|| !keystore.has_active_affidavit_key()
{
keystore.create_or_repair_active_key();
offchain_storage.ensure_active_key_reference();
continue;
}
// --- Election Phase (optimistic) ---
if election_constraints_satisfied() {
if submit_elect_authors_extrinsic().is_err() {
continue; // repair + retry via initialization
}
}
// --- Declaration Phase ---
if !offchain_storage.has_next_affidavit_key()
|| !keystore.has_next_affidavit_key()
{
match keystore.create_or_repair_next_key() {
Ok(_) => {
offchain_storage.ensure_next_key_reference();
continue;
}
Err(_) => continue, // fallback to initialization repair loop
}
}
if !affidavit_constraints_satisfied() {
continue; // retry via initialization phase
}
if submit_declare_affidavit_extrinsic().is_err() {
continue; // declaration failed -> repair + retry
}
// --- Rotation Observation Phase ---
if !offchain_storage.has_next_affidavit_key()
|| !keystore.has_next_affidavit_key()
{
continue;
}
if eligible_to_rotate() {
promote_next_key_to_active();
remove_next_key();
break; // rotation completed
}
if within_current_session_window() {
continue; // wait until rotation becomes eligible
// indicates declaration effects are not finalized
}
// Window expired -> reset inconsistent state
remove_active_and_next_affidavit_keys();
break;
}§Guarantee
The rotation phase has exactly three exit outcomes:
-
Rotation Success:
- if the next affidavit key is finalized and present in the keystore, and
- rotation eligibility constraints are satisfied, then the next key is promoted to become the active affidavit key.
-
Deferred Rotation (Same Session):
- if the next affidavit key is finalized but not yet eligible to rotate, and
- the current session window in which the affidavit was declared is still active, the routine keeps retrying until eligibility is satisfied and rotation succeeds.
-
Reset & Repair (Session Elapsed):
- if rotation is still ineligible and the declaring session window has elapsed, both active and next affidavit keys are removed, signaling that the declaration phase effectively failed to converge. The global loop then re-enters the initialization phase to repair and re-establish a consistent state.
loop {
if eligible_to_rotate() {
promote_next_key_to_active();
remove_next_affidavit_key();
break;
}
if within_declaring_session_window() {
continue;
// keep retrying until eligibility becomes true
} else {
remove_active_and_next_affidavit_keys();
break;
// signal reset; initialization phase will repair state
}
}All behavior is supplied by trait implementations operating on this type.
§Timelines & Window Semantics
The global retry loop operates over session-scoped time windows that determine when election, declaration, and rotation are allowed.
Timeline within a single session:
|--------------------- Session N ---------------------|
|--------- Affidavit Window ---------|
|----- Election Window -----|
Session Start
|- Affidavit window opens
|- Election window opens (nested inside affidavit window)
Election window closes
|- Election no longer allowed
Affidavit window closes
|- Declaration and rotation eligibility must already be satisfied
Session ends -> Session N+1 begins
|- Global loop continues with fresh window constraintsProperties:
- The election window is strictly nested within the affidavit window.
- When the affidavit window ends, the election window has already ended.
- Rotation eligibility is evaluated relative to the session in which the affidavit was declared.
- If rotation has not converged before the session window elapses, the routine resets keys and relies on the next session’s loop iteration to re-initialize and re-attempt the full lifecycle.
§FlowChart
Fields§
§by: T::PublicPublic key that is intended to become the new active affidavit key.
at: BlockNumberFor<T>Block number at which key rotation is initiated.
Trait Implementations§
Source§impl<T: Clone + Config> Clone for RotateAffidavitKey<T>where
T::Public: Clone,
impl<T: Clone + Config> Clone for RotateAffidavitKey<T>where
T::Public: Clone,
Source§fn clone(&self) -> RotateAffidavitKey<T>
fn clone(&self) -> RotateAffidavitKey<T>
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl<T> Debug for RotateAffidavitKey<T>
impl<T> Debug for RotateAffidavitKey<T>
Source§impl<T: Config> Decode for RotateAffidavitKey<T>where
T::Public: Decode,
BlockNumberFor<T>: Decode,
impl<T: Config> Decode for RotateAffidavitKey<T>where
T::Public: Decode,
BlockNumberFor<T>: Decode,
Source§fn decode<__CodecInputEdqy: Input>(
__codec_input_edqy: &mut __CodecInputEdqy,
) -> Result<Self, Error>
fn decode<__CodecInputEdqy: Input>( __codec_input_edqy: &mut __CodecInputEdqy, ) -> Result<Self, Error>
§fn decode_into<I>(
input: &mut I,
dst: &mut MaybeUninit<Self>,
) -> Result<DecodeFinished, Error>where
I: Input,
fn decode_into<I>(
input: &mut I,
dst: &mut MaybeUninit<Self>,
) -> Result<DecodeFinished, Error>where
I: Input,
§fn skip<I>(input: &mut I) -> Result<(), Error>where
I: Input,
fn skip<I>(input: &mut I) -> Result<(), Error>where
I: Input,
§fn encoded_fixed_size() -> Option<usize>
fn encoded_fixed_size() -> Option<usize>
Source§impl<T: Config> Encode for RotateAffidavitKey<T>where
T::Public: Encode,
BlockNumberFor<T>: Encode,
impl<T: Config> Encode for RotateAffidavitKey<T>where
T::Public: Encode,
BlockNumberFor<T>: Encode,
Source§fn size_hint(&self) -> usize
fn size_hint(&self) -> usize
Source§fn encode_to<__CodecOutputEdqy: Output + ?Sized>(
&self,
__codec_dest_edqy: &mut __CodecOutputEdqy,
)
fn encode_to<__CodecOutputEdqy: Output + ?Sized>( &self, __codec_dest_edqy: &mut __CodecOutputEdqy, )
§fn using_encoded<R, F>(&self, f: F) -> R
fn using_encoded<R, F>(&self, f: F) -> R
§fn encoded_size(&self) -> usize
fn encoded_size(&self) -> usize
Source§impl<T: Config> MaxEncodedLen for RotateAffidavitKey<T>where
T::Public: MaxEncodedLen,
BlockNumberFor<T>: MaxEncodedLen,
impl<T: Config> MaxEncodedLen for RotateAffidavitKey<T>where
T::Public: MaxEncodedLen,
BlockNumberFor<T>: MaxEncodedLen,
Source§fn max_encoded_len() -> usize
fn max_encoded_len() -> usize
Source§impl<T: Config> RoutineOf<<T as SigningTypes>::Public, <<<T as Config>::Block as HeaderProvider>::HeaderT as Header>::Number> for RotateAffidavitKey<T>
Authorization layer for affidavit key rotation.
impl<T: Config> RoutineOf<<T as SigningTypes>::Public, <<<T as Config>::Block as HeaderProvider>::HeaderT as Header>::Number> for RotateAffidavitKey<T>
Authorization layer for affidavit key rotation.
Resolves the finalized next affidavit key prepared by
DeclareAffidavit and ensures it is locally usable for signing.
This enforces that rotation is performed only with a key that:
- has reached finality, and
- exists in the node’s keystore.
Source§fn who(at: &BlockNumberFor<T>) -> Result<T::Public, Self::Logger>
fn who(at: &BlockNumberFor<T>) -> Result<T::Public, Self::Logger>
Determines the next affidavit public key authorized to finalize key rotation.
§Semantics
- Resolves the next affidavit key previously prepared and finalized
by the
DeclareAffidavitroutine. - Requires the key to be in a
Confidence::Safestate, ensuring it has survived fork re-orgs and met finality requirements.
§Lifecycle position
Reaching this routine implies:
- The
declareextrinsic has already been submitted, and - The node is now waiting to observe whether that transaction has been accepted and reflected in runtime storage.
This routine therefore does not generate or mutate keys. It only:
- re-reads the finalized next affidavit key, and
- verifies that the corresponding key pair still exists in the local keystore.
§Failure semantics
- Missing or non-finalized next affidavit key is treated as a hard stop.
- Storage inconsistencies indicate OCW coordination failure and halt execution.
- If the key exists in storage but not in the keystore, the node is considered misconfigured.
Source§impl<T: Config> Routines<<<<T as Config>::Block as HeaderProvider>::HeaderT as Header>::Number> for RotateAffidavitKey<T>
Offchain routine responsible for finalizing affidavit key rotation.
impl<T: Config> Routines<<<<T as Config>::Block as HeaderProvider>::HeaderT as Header>::Number> for RotateAffidavitKey<T>
Offchain routine responsible for finalizing affidavit key rotation.
Completes the lifecycle by promoting the finalized next affidavit key to active status once the runtime reflects successful affidavit submission.
This routine:
- waits for on-chain confirmation of the rotated key,
- performs a safe transition from next -> active key,
- resets state on failure to avoid inconsistent lifecycle progression.
Designed to be idempotent and driven by repeated OCW execution.
Source§fn can_run(&self) -> Result<(), Self::Logger>
fn can_run(&self) -> Result<(), Self::Logger>
Determines whether affidavit key rotation may be finalized.
§Semantics
- Checks whether the next affidavit key has been successfully
registered in runtime storage for the session after next
(
current_session + 2) (for which next election will be conducted). - Presence of this key in
AffidavitKeysis treated as confirmation that thedeclareextrinsic was accepted.
§Waiting behavior
- If the key is not yet visible, the routine waits passively.
- While the affidavit window is still open, this is logged as an informational “awaiting status” condition.
§Failure and recovery
If the affidavit window has closed and:
- the next affidavit key is still not registered, then
- the system assumes the affidavit transaction failed or was dropped.
In that case:
- All affidavit-related offchain state is cleared.
- Active validation is considered stopped.
- The node must restart the lifecycle via
validateextrinsic in a later block.
This aggressive reset prevents the OCW from getting stuck in a half-rotated or inconsistent state.
Source§fn run_service(&self) -> Result<(), Self::Logger>
fn run_service(&self) -> Result<(), Self::Logger>
Finalizes affidavit key rotation after successful affidavit acceptance.
§Behavior
Once the runtime reflects the rotated affidavit key:
- The next affidavit key is removed from finalized offchain storage.
- The active affidavit key is updated to the rotated key.
This completes the affidavit lifecycle for the current session and enables subsequent OCW executions to:
- attempt elections via
TryElection, and - later begin a new affidavit cycle.
§Guarantees
- Rotation is performed exactly once per successful affidavit.
- Any storage failure is treated as a coordination halt.
Source§fn on_ran_service(&self)
fn on_ran_service(&self)
Logs a info message on a successful RotateAffidavitKey routine.
Source§impl<T> TypeInfo for RotateAffidavitKey<T>where
T::Public: TypeInfo + 'static,
BlockNumberFor<T>: TypeInfo + 'static,
T: Config + 'static,
impl<T> TypeInfo for RotateAffidavitKey<T>where
T::Public: TypeInfo + 'static,
BlockNumberFor<T>: TypeInfo + 'static,
T: Config + 'static,
impl<T: Config> EncodeLike for RotateAffidavitKey<T>where
T::Public: Encode,
BlockNumberFor<T>: Encode,
impl<T: Eq + Config> Eq for RotateAffidavitKey<T>where
T::Public: Eq,
impl<T: Config> StructuralPartialEq for RotateAffidavitKey<T>
Auto Trait Implementations§
impl<T> Freeze for RotateAffidavitKey<T>
impl<T> RefUnwindSafe for RotateAffidavitKey<T>where
<T as SigningTypes>::Public: RefUnwindSafe,
<<<T as Config>::Block as Block>::Header as Header>::Number: RefUnwindSafe,
impl<T> Send for RotateAffidavitKey<T>where
<T as SigningTypes>::Public: Send,
impl<T> Sync for RotateAffidavitKey<T>where
<T as SigningTypes>::Public: Sync,
impl<T> Unpin for RotateAffidavitKey<T>
impl<T> UnwindSafe for RotateAffidavitKey<T>where
<T as SigningTypes>::Public: UnwindSafe,
<<<T as Config>::Block as Block>::Header as Header>::Number: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
§impl<T> CheckedConversion for T
impl<T> CheckedConversion for T
§fn checked_from<T>(t: T) -> Option<Self>where
Self: TryFrom<T>,
fn checked_from<T>(t: T) -> Option<Self>where
Self: TryFrom<T>,
§fn checked_into<T>(self) -> Option<T>where
Self: TryInto<T>,
fn checked_into<T>(self) -> Option<T>where
Self: TryInto<T>,
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<T> DecodeAll for Twhere
T: Decode,
impl<T> DecodeAll for Twhere
T: Decode,
§fn decode_all(input: &mut &[u8]) -> Result<T, Error>
fn decode_all(input: &mut &[u8]) -> Result<T, Error>
Self and consume all of the given input data. Read more§impl<T> DecodeLimit for Twhere
T: Decode,
impl<T> DecodeLimit for Twhere
T: Decode,
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
§impl<T> Hashable for Twhere
T: Codec,
impl<T> Hashable for Twhere
T: Codec,
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T, U, Tag> IntoTag<U, Tag> for Twhere
U: FromTag<T, Tag>,
Tag: DiscriminantTag,
impl<T, U, Tag> IntoTag<U, Tag> for Twhere
U: FromTag<T, Tag>,
Tag: DiscriminantTag,
§impl<Src, Dest> IntoTuple<Dest> for Srcwhere
Dest: FromTuple<Src>,
impl<Src, Dest> IntoTuple<Dest> for Srcwhere
Dest: FromTuple<Src>,
fn into_tuple(self) -> Dest
§impl<T> IsType<T> for T
impl<T> IsType<T> for T
§impl<T, Outer> IsWrappedBy<Outer> for T
impl<T, Outer> IsWrappedBy<Outer> for T
§impl<T> KeyedVec for Twhere
T: Codec,
impl<T> KeyedVec for Twhere
T: Codec,
Source§impl<T, Time> Logging<Time> for Twhere
Time: Time,
impl<T, Time> Logging<Time> for Twhere
Time: Time,
Source§const FALLBACK_TARGET: &'static str = "routine"
const FALLBACK_TARGET: &'static str = "routine"
Default logging target if none is provided.
Most routines, especially offchain workers or background tasks, use this target for simplicity.
It allows a consistent place to look for routine logs without requiring every call to specify a target.
Note: This target is only a conveninence and may be somewhat vague. To ensure errors can still be traced accurately, the logged messages should include additional metadata (e.g., module name, error index, or contextual info) so that the source of the error can be identified even if the target is generic.
Source§type Logger = DispatchError
type Logger = DispatchError
The type taken and returned for logging.
We simply return the same [DispatchError] that was logged,
so logging does not change control flow or error propagation.
DispatchError is used because in Substrate it encompasses all
runtime errors - including module errors, token errors, arithmetic
issues, and transactional boundaries - making it the universal
substrate-side error representation.
Source§type Level = LogLevel
type Level = LogLevel
The log level type.
We use the LogLevel enum to standardize severity levels
(Info, Warn, Error, Debug) across all routine logs.
Source§fn log(
level: <T as Logging<Time>>::Level,
err: &<T as Logging<Time>>::Logger,
timestamp: Time,
target: Option<&str>,
fmt: Option<fn(Time, &<T as Logging<Time>>::Level, &str, &str) -> String>,
) -> <T as Logging<Time>>::Logger
fn log( level: <T as Logging<Time>>::Level, err: &<T as Logging<Time>>::Logger, timestamp: Time, target: Option<&str>, fmt: Option<fn(Time, &<T as Logging<Time>>::Level, &str, &str) -> String>, ) -> <T as Logging<Time>>::Logger
Source§fn info(
err: &Self::Logger,
timestamp: Timestamp,
target: Option<&str>,
fmt: Option<fn(Timestamp, &Self::Level, &str, &str) -> String>,
) -> Self::Loggerwhere
Self: Sized,
fn info(
err: &Self::Logger,
timestamp: Timestamp,
target: Option<&str>,
fmt: Option<fn(Timestamp, &Self::Level, &str, &str) -> String>,
) -> Self::Loggerwhere
Self: Sized,
Source§fn warn(
err: &Self::Logger,
timestamp: Timestamp,
target: Option<&str>,
fmt: Option<fn(Timestamp, &Self::Level, &str, &str) -> String>,
) -> Self::Loggerwhere
Self: Sized,
fn warn(
err: &Self::Logger,
timestamp: Timestamp,
target: Option<&str>,
fmt: Option<fn(Timestamp, &Self::Level, &str, &str) -> String>,
) -> Self::Loggerwhere
Self: Sized,
§impl<T> SaturatedConversion for T
impl<T> SaturatedConversion for T
§fn saturated_from<T>(t: T) -> Selfwhere
Self: UniqueSaturatedFrom<T>,
fn saturated_from<T>(t: T) -> Selfwhere
Self: UniqueSaturatedFrom<T>,
§fn saturated_into<T>(self) -> Twhere
Self: UniqueSaturatedInto<T>,
fn saturated_into<T>(self) -> Twhere
Self: UniqueSaturatedInto<T>,
T. Read more§impl<T, U> TryIntoKey<U> for Twhere
U: TryFromKey<T>,
impl<T, U> TryIntoKey<U> for Twhere
U: TryFromKey<T>,
type Error = <U as TryFromKey<T>>::Error
fn try_into_key(self) -> Result<U, <U as TryFromKey<T>>::Error>
§impl<S, T> UncheckedInto<T> for Swhere
T: UncheckedFrom<S>,
impl<S, T> UncheckedInto<T> for Swhere
T: UncheckedFrom<S>,
§fn unchecked_into(self) -> T
fn unchecked_into(self) -> T
unchecked_from.§impl<T, S> UniqueSaturatedInto<T> for S
impl<T, S> UniqueSaturatedInto<T> for S
§fn unique_saturated_into(self) -> T
fn unique_saturated_into(self) -> T
T.