Skip to content
lib.rs 45 KiB
Newer Older
		if let InitKind::Full = kind {
			<Events<T>>::kill();
			EventCount::kill();
			<EventTopics<T>>::remove_all();
		}
Gav Wood's avatar
Gav Wood committed
	}

	/// Remove temporary "environment" entries in storage.
	pub fn finalize() -> T::Header {
		ExecutionPhase::kill();
		AllExtrinsicsLen::kill();
Gav Wood's avatar
Gav Wood committed

		let number = <Number<T>>::take();
		let parent_hash = <ParentHash<T>>::take();
Gav Wood's avatar
Gav Wood committed
		let extrinsics_root = <ExtrinsicsRoot<T>>::take();

		// move block hash pruning window by one block
		let block_hash_count = <T::BlockHashCount>::get();
		if number > block_hash_count {
			let to_remove = number - block_hash_count - One::one();

			// keep genesis hash
			if to_remove != Zero::zero() {
				<BlockHash<T>>::remove(to_remove);
			}
		}

		let storage_root = T::Hash::decode(&mut &sp_io::storage::root()[..])
			.expect("Node is configured to use the same hash; qed");
		let storage_changes_root = sp_io::storage::changes_root(&parent_hash.encode());

		// we can't compute changes trie root earlier && put it to the Digest
		// because it will include all currently existing temporaries.
		if let Some(storage_changes_root) = storage_changes_root {
			let item = generic::DigestItem::ChangesTrieRoot(
				T::Hash::decode(&mut &storage_changes_root[..])
					.expect("Node is configured to use the same hash; qed")
			);
		// The following fields
		//
		// - <Events<T>>
		// - <EventCount<T>>
		// - <EventTopics<T>>
		//
		// stay to be inspected by the client and will be cleared by `Self::initialize`.
		<T::Header as traits::Header>::new(number, extrinsics_root, storage_root, parent_hash, digest)
	/// Deposits a log and ensures it matches the block's log data.
	/// - `O(1)`
	/// - 1 storage write (codec `O(1)`)
	pub fn deposit_log(item: DigestItemOf<T>) {
		<Digest<T>>::append(item);
Gav Wood's avatar
Gav Wood committed
	}

	/// Get the basic externalities for this module, useful for tests.
	#[cfg(any(feature = "std", test))]
	pub fn externalities() -> TestExternalities {
		TestExternalities::new(sp_core::storage::Storage {
			top: map![
				<BlockHash<T>>::hashed_key_for(T::BlockNumber::zero()) => [69u8; 32].encode(),
				<Number<T>>::hashed_key().to_vec() => T::BlockNumber::one().encode(),
				<ParentHash<T>>::hashed_key().to_vec() => [69u8; 32].encode()
			],
			children_default: map![],
Gav Wood's avatar
Gav Wood committed
	}

	/// Set the block number to something in particular. Can be used as an alternative to
	/// `initialize` for tests that don't need to bother with the other environment entries.
	#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
Gav Wood's avatar
Gav Wood committed
	pub fn set_block_number(n: T::BlockNumber) {
		<Number<T>>::put(n);
	}

	/// Sets the index of extrinsic that is currently executing.
	#[cfg(any(feature = "std", test))]
	pub fn set_extrinsic_index(extrinsic_index: u32) {
		storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &extrinsic_index)
	/// Set the parent hash number to something in particular. Can be used as an alternative to
	/// `initialize` for tests that don't need to bother with the other environment entries.
	#[cfg(any(feature = "std", test))]
	pub fn set_parent_hash(n: T::Hash) {
		<ParentHash<T>>::put(n);
	}

	/// Set the current block weight. This should only be used in some integration tests.
	#[cfg(any(feature = "std", test))]
	pub fn set_block_limits(weight: Weight, len: usize) {
		BlockWeight::mutate(|current_weight| {
			current_weight.put(weight, DispatchClass::Normal)
		});
		AllExtrinsicsLen::put(len as u32);
	}

	/// Reset events. Can be used as an alternative to
	/// `initialize` for tests that don't need to bother with the other environment entries.
	#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
	pub fn reset_events() {
		<Events<T>>::kill();
		EventCount::kill();
		<EventTopics<T>>::remove_all();
	}

	/// Return the chain's current runtime version.
	pub fn runtime_version() -> RuntimeVersion { T::Version::get() }

Gavin Wood's avatar
Gavin Wood committed
	/// Retrieve the account transaction counter from storage.
	pub fn account_nonce(who: impl EncodeLike<T::AccountId>) -> T::Index {
Gavin Wood's avatar
Gavin Wood committed
		Account::<T>::get(who).nonce
Gav Wood's avatar
Gav Wood committed
	/// Increment a particular account's nonce by 1.
Gavin Wood's avatar
Gavin Wood committed
	pub fn inc_account_nonce(who: impl EncodeLike<T::AccountId>) {
Gavin Wood's avatar
Gavin Wood committed
		Account::<T>::mutate(who, |a| a.nonce += T::Index::one());
Gav Wood's avatar
Gav Wood committed
	}
	/// Note what the extrinsic data of the current extrinsic index is. If this
	/// is called, then ensure `derive_extrinsics` is also called before
	/// block-building is completed.
	/// NOTE: This function is called only when the block is being constructed locally.
	/// `execute_block` doesn't note any extrinsics.
	pub fn note_extrinsic(encoded_xt: Vec<u8>) {
		ExtrinsicData::insert(Self::extrinsic_index().unwrap_or_default(), encoded_xt);
	}

	/// To be called immediately after an extrinsic has been applied.
	pub fn note_applied_extrinsic(r: &DispatchResultWithPostInfo, mut info: DispatchInfo) {
		info.weight = extract_actual_weight(r, &info);
		Self::deposit_event(
			match r {
				Ok(_) => RawEvent::ExtrinsicSuccess(info),
				Err(err) => {
					sp_runtime::print(err);
					RawEvent::ExtrinsicFailed(err.error, info)

		let next_extrinsic_index = Self::extrinsic_index().unwrap_or_default() + 1u32;
		storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &next_extrinsic_index);
		ExecutionPhase::put(Phase::ApplyExtrinsic(next_extrinsic_index));
	}

	/// To be called immediately after `note_applied_extrinsic` of the last extrinsic of the block
	/// has been called.
	pub fn note_finished_extrinsics() {
		let extrinsic_index: u32 = storage::unhashed::take(well_known_keys::EXTRINSIC_INDEX)
			.unwrap_or_default();
		ExtrinsicCount::put(extrinsic_index);
		ExecutionPhase::put(Phase::Finalization);
	}

	/// To be called immediately after finishing the initialization of the block
	/// (e.g., called `on_initialize` for all modules).
	pub fn note_finished_initialize() {
		ExecutionPhase::put(Phase::ApplyExtrinsic(0))
	/// Remove all extrinsic data and save the extrinsics trie root.
	pub fn derive_extrinsics() {
		let extrinsics = (0..ExtrinsicCount::get().unwrap_or_default())
			.map(ExtrinsicData::take).collect();
		let xts_root = extrinsics_data_root::<T::Hashing>(extrinsics);
		<ExtrinsicsRoot<T>>::put(xts_root);
	}
Gavin Wood's avatar
Gavin Wood committed

	/// An account is being created.
	pub fn on_created_account(who: T::AccountId) {
		T::OnNewAccount::on_new_account(&who);
		Self::deposit_event(RawEvent::NewAccount(who));
	}

	/// Do anything that needs to be done after an account has been killed.
	fn on_killed_account(who: T::AccountId) {
Gavin Wood's avatar
Gavin Wood committed
		T::OnKilledAccount::on_killed_account(&who);
		Self::deposit_event(RawEvent::KilledAccount(who));
	}

	/// Remove an account from storage. This should only be done when its refs are zero or you'll
	/// get storage leaks in other modules. Nonetheless we assume that the calling logic knows best.
	///
	/// This is a no-op if the account doesn't already exist. If it does then it will ensure
	/// cleanups (those in `on_killed_account`) take place.
	fn kill_account(who: &T::AccountId) {
		if Account::<T>::contains_key(who) {
			let account = Account::<T>::take(who);
			if account.refcount > 0 {
				debug::debug!(
					target: "system",
					"WARNING: Referenced account deleted. This is probably a bug."
				);
			}
		}
		Module::<T>::on_killed_account(who.clone());

	/// Determine whether or not it is possible to update the code.
	///
	/// This function has no side effects and is idempotent, but is fairly
	/// heavy. It is automatically called by `set_code`; in most cases,
	/// a direct call to `set_code` is preferable. It is useful to call
	/// `can_set_code` when it is desirable to perform the appropriate
	/// runtime checks without actually changing the code yet.
	pub fn can_set_code(origin: T::Origin, code: &[u8]) -> Result<(), sp_runtime::DispatchError> {
		ensure_root(origin)?;

		let current_version = T::Version::get();
		let new_version = sp_io::misc::runtime_version(&code)
			.and_then(|v| RuntimeVersion::decode(&mut &v[..]).ok())
			.ok_or_else(|| Error::<T>::FailedToExtractRuntimeVersion)?;

		if new_version.spec_name != current_version.spec_name {
			Err(Error::<T>::InvalidSpecName)?
		}

		if new_version.spec_version <= current_version.spec_version {
			Err(Error::<T>::SpecVersionNeedsToIncrease)?
		}

		Ok(())
	}
Gavin Wood's avatar
Gavin Wood committed
}

/// Event handler which calls on_created_account when it happens.
pub struct CallOnCreatedAccount<T>(PhantomData<T>);
impl<T: Trait> Happened<T::AccountId> for CallOnCreatedAccount<T> {
	fn happened(who: &T::AccountId) {
		Module::<T>::on_created_account(who.clone());
	}
}

/// Event handler which calls kill_account when it happens.
pub struct CallKillAccount<T>(PhantomData<T>);
impl<T: Trait> Happened<T::AccountId> for CallKillAccount<T> {
	fn happened(who: &T::AccountId) {
Gavin Wood's avatar
Gavin Wood committed
		Module::<T>::kill_account(who)
impl<T: Trait> BlockNumberProvider for Module<T>
{
	type BlockNumber = <T as Trait>::BlockNumber;

	fn current_block_number() -> Self::BlockNumber {
		Module::<T>::block_number()
	}
}

Gavin Wood's avatar
Gavin Wood committed
// Implement StoredMap for a simple single-item, kill-account-on-remove system. This works fine for
// storing a single item which is required to not be empty/default for the account to exist.
// Anything more complex will need more sophisticated logic.
impl<T: Trait> StoredMap<T::AccountId, T::AccountData> for Module<T> {
	fn get(k: &T::AccountId) -> T::AccountData {
Gavin Wood's avatar
Gavin Wood committed
		Account::<T>::get(k).data
Gavin Wood's avatar
Gavin Wood committed
	}
	fn is_explicit(k: &T::AccountId) -> bool {
		Account::<T>::contains_key(k)
	}
Gavin Wood's avatar
Gavin Wood committed
	fn insert(k: &T::AccountId, data: T::AccountData) {
Gavin Wood's avatar
Gavin Wood committed
		let existed = Account::<T>::contains_key(k);
Gavin Wood's avatar
Gavin Wood committed
		Account::<T>::mutate(k, |a| a.data = data);
Gavin Wood's avatar
Gavin Wood committed
		if !existed {
			Self::on_created_account(k.clone());
		}
	}
	fn remove(k: &T::AccountId) {
Gavin Wood's avatar
Gavin Wood committed
		Self::kill_account(k)
Gavin Wood's avatar
Gavin Wood committed
	}
	fn mutate<R>(k: &T::AccountId, f: impl FnOnce(&mut T::AccountData) -> R) -> R {
		let existed = Account::<T>::contains_key(k);
Gavin Wood's avatar
Gavin Wood committed
		let r = Account::<T>::mutate(k, |a| f(&mut a.data));
Gavin Wood's avatar
Gavin Wood committed
		if !existed {
			Self::on_created_account(k.clone());
		}
		r
	}
	fn mutate_exists<R>(k: &T::AccountId, f: impl FnOnce(&mut Option<T::AccountData>) -> R) -> R {
Gavin Wood's avatar
Gavin Wood committed
		Self::try_mutate_exists(k, |x| -> Result<R, Infallible> { Ok(f(x)) }).expect("Infallible; qed")
Gavin Wood's avatar
Gavin Wood committed
	}
	fn try_mutate_exists<R, E>(k: &T::AccountId, f: impl FnOnce(&mut Option<T::AccountData>) -> Result<R, E>) -> Result<R, E> {
		Account::<T>::try_mutate_exists(k, |maybe_value| {
			let existed = maybe_value.is_some();
Gavin Wood's avatar
Gavin Wood committed
			let (maybe_prefix, mut maybe_data) = split_inner(
				maybe_value.take(),
				|account| ((account.nonce, account.refcount), account.data)
			);
			f(&mut maybe_data).map(|result| {
				*maybe_value = maybe_data.map(|data| {
					let (nonce, refcount) = maybe_prefix.unwrap_or_default();
					AccountInfo { nonce, refcount, data }
				});
				(existed, maybe_value.is_some(), result)
Gavin Wood's avatar
Gavin Wood committed
			})
		}).map(|(existed, exists, v)| {
			if !existed && exists {
				Self::on_created_account(k.clone());
			} else if existed && !exists {
				Self::on_killed_account(k.clone());
			}
			v
		})
	}
Gavin Wood's avatar
Gavin Wood committed
/// Split an `option` into two constituent options, as defined by a `splitter` function.
pub fn split_inner<T, R, S>(option: Option<T>, splitter: impl FnOnce(T) -> (R, S))
	-> (Option<R>, Option<S>)
{
	match option {
		Some(inner) => {
			let (r, s) = splitter(inner);
			(Some(r), Some(s))
		}
		None => (None, None),
Gavin Wood's avatar
Gavin Wood committed
impl<T: Trait> IsDeadAccount<T::AccountId> for Module<T> {
	fn is_dead_account(who: &T::AccountId) -> bool {
		!Account::<T>::contains_key(who)
	}
}

pub struct ChainContext<T>(sp_std::marker::PhantomData<T>);
impl<T> Default for ChainContext<T> {
	fn default() -> Self {
		ChainContext(sp_std::marker::PhantomData)
	}
}

impl<T: Trait> Lookup for ChainContext<T> {
	type Source = <T::Lookup as StaticLookup>::Source;
	type Target = <T::Lookup as StaticLookup>::Target;

	fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError> {
		<T::Lookup as StaticLookup>::lookup(s)