Substrate - Execute Extrinsic

How runtime runs for a block or extrinsic

ImportBlock

Originated from Consensus and invoked by NetworkWorker

Client as BlockImport::ImportBlock -> prepare_block_storage_changes -> runtime_api.execute_block_with_context

--------------- Enter Runtime ----------------

Executive::execute_block_with_context -> execute_extrinsics_with_book_keeping -> apply_extrinsic(each extrinsic) -> CheckedExtrinsic::apply -> dispatch

/// Import a checked and validated block. If a justification is provided in
	/// `BlockImportParams` then `finalized` *must* be true.
	///
	/// NOTE: only use this implementation when there are NO consensus-level BlockImport
	/// objects. Otherwise, importing blocks directly into the client would be bypassing
	/// important verification work.
	///
	/// If you are not sure that there are no BlockImport objects provided by the consensus
	/// algorithm, dont use this function.
	async fn import_block(
		&mut self,
		mut import_block: BlockImportParams<Block, backend::TransactionFor<B, Block>>,
		new_cache: HashMap<CacheKeyId, Vec<u8>>,
	) -> Result<ImportResult, Self::Error> {
		let span = tracing::span!(tracing::Level::DEBUG, "import_block");
		let _enter = span.enter();

		let storage_changes =
			match self.prepare_block_storage_changes(&mut import_block).map_err(|e| {
				warn!("Block prepare storage changes error:
{:?}", e);
				ConsensusError::ClientImport(e.to_string())
			})? {
				PrepareStorageChangesResult::Discard(res) => return Ok(res),
				PrepareStorageChangesResult::Import(storage_changes) => storage_changes,
			};

		self.lock_import_and_run(|operation| {
			self.apply_block(operation, import_block, new_cache, storage_changes)
		})
		.map_err(|e| {
			warn!("Block import error:
{:?}", e);
			ConsensusError::ClientImport(e.to_string()).into()
		})
	}

Execute a single Extrinsic

Invoked by SimpleSlotWorker::on_slot when authoring block

sc-basic-authorship::Proposer::propose_with -> sc_block_builder::BlockBuilder::push(pending_tx_data) -> runtime_api.apply_extrinsic_with_context

--------------- Enter Runtime ----------------

Executive::apply_extrinsic -> CheckedExtrinsic::apply -> dispatch

See sc-basic-authorship::Proposer::propose_with

经验分享 程序员 微信小程序 职场和发展