Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions prdoc/pr_11215.prdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
title: try state hook for pallet authorship
doc:
- audience: Runtime Dev
description: |-
This PR introduces the try_state hook to pallet-authorship to verify a key storage invariant.

closes part of https://github.com/paritytech/polkadot-sdk/issues/239
crates:
- name: pallet-authorship
bump: minor
32 changes: 32 additions & 0 deletions substrate/frame/authorship/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ pub mod pallet {
// ensure we never go to trie with these values.
<Author<T>>::kill();
}

#[cfg(feature = "try-runtime")]
fn try_state(_n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
Self::do_try_state()
}
}

#[pallet::storage]
Expand Down Expand Up @@ -91,6 +96,32 @@ impl<T: Config> Pallet<T> {
}
}

#[cfg(any(feature = "try-runtime", test))]
impl<T: Config> Pallet<T> {
/// Ensure the correctness of the state of this pallet.
///
/// # Invariants
///
/// * If `Author` storage contains a value, it must match the author derived from the current
/// block's digest via `FindAuthor`.
pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
use frame_support::ensure;

if let Some(stored_author) = <Author<T>>::get() {
let digest = <frame_system::Pallet<T>>::digest();
let pre_runtime_digests = digest.logs.iter().filter_map(|d| d.as_pre_runtime());
if let Some(expected_author) = T::FindAuthor::find_author(pre_runtime_digests) {
ensure!(
stored_author == expected_author,
"Stored author does not match the author derived from digest"
);
}
}

Ok(())
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -172,6 +203,7 @@ mod tests {
System::initialize(&1, &Default::default(), header.digest());

assert_eq!(Authorship::author(), Some(author));
Authorship::do_try_state().unwrap();
});
}
}
Loading