referrerpolicy=no-referrer-when-downgrade

polkadot_sdk_docs/reference_docs/
extrinsic_encoding.rs

1//! # Constructing and Signing Extrinsics
2//!
3//! Extrinsics are payloads that are stored in blocks which are responsible for altering the state
4//! of a blockchain via the [_state transition
5//! function_][crate::reference_docs::blockchain_state_machines].
6//!
7//! Substrate is configurable enough that extrinsics can take any format. In practice, runtimes
8//! tend to use our [`sp_runtime::generic::UncheckedExtrinsic`] type to represent extrinsics,
9//! because it's generic enough to cater for most (if not all) use cases. In Polkadot, this is
10//! configured [here](https://github.com/polkadot-fellows/runtimes/blob/94b2798b69ba6779764e20a50f056e48db78ebef/relay/polkadot/src/lib.rs#L1478)
11//! at the time of writing.
12//!
13//! What follows is a description of how extrinsics based on this
14//! [`sp_runtime::generic::UncheckedExtrinsic`] type are encoded into bytes. Specifically, we are
15//! looking at how extrinsics with a format version of 5 are encoded. This version is itself a part
16//! of the payload, and if it changes, it indicates that something about the encoding may have
17//! changed.
18//!
19//! # Encoding an Extrinsic
20//!
21//! At a high level, all extrinsics compatible with [`sp_runtime::generic::UncheckedExtrinsic`]
22//! are formed from concatenating some details together, as in the following pseudo-code:
23//!
24//! ```text
25//! extrinsic_bytes = concat(
26//!     compact_encoded_length,
27//!     version_and_extrinsic_type,
28//! 	maybe_extension_data,
29//!     call_data
30//! )
31//! ```
32//!
33//! For clarity, the actual implementation in Substrate looks like this:
34#![doc = docify::embed!("../../substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs", unchecked_extrinsic_encode_impl)]
35//! Let's look at how each of these details is constructed:
36//!
37//! ## compact_encoded_length
38//!
39//! This is a [SCALE compact encoded][frame::deps::codec::Compact] integer which is equal to the
40//! length, in bytes, of the rest of the extrinsic details.
41//!
42//! To obtain this value, we must encode and concatenate together the rest of the extrinsic details
43//! first, and then obtain the byte length of these. We can then compact encode that length, and
44//! prepend it to the rest of the details.
45//!
46//! ## version_and_maybe_signature
47//!
48//! If the extrinsic is _unsigned_, then `version_and_maybe_signature` will be just one byte
49//! denoting the _transaction protocol version_, which is 4 (or `0b0000_0100`).
50//!
51//! If the extrinsic is _signed_ (all extrinsics submitted from users must be signed), then
52//! `version_and_maybe_signature` is obtained by concatenating some details together, ie:
53//!
54//! ```text
55//! version_and_maybe_signature = concat(
56//!     version_and_signed,
57//!     from_address,
58//!     signature,
59//!     transaction_extensions_extra,
60//! )
61//! ```
62//!
63//! Each of the details to be concatenated together is explained below:
64//!
65//! ## version_and_extrinsic_type
66//!
67//! This byte has 2 components:
68//! - the 2 most significant bits represent the extrinsic type:
69//!     - bare - `0b00`
70//!     - signed - `0b10`
71//!     - general - `0b01`
72//! - the 6 least significant bits represent the extrinsic format version (currently 5)
73//!
74//! ### Bare extrinsics
75//!
76//! If the extrinsic is _bare_, then `version_and_extrinsic_type` will be just the _transaction
77//! protocol version_, which is 5 (or `0b0000_0101`). Bare extrinsics do not carry any other
78//! extension data, so `maybe_extension_data` would not be included in the payload and the
79//! `version_and_extrinsic_type` would always be followed by the encoded call bytes.
80//!
81//! ### Signed extrinsics
82//!
83//! If the extrinsic is _signed_ (all extrinsics submitted from users used to be signed up until
84//! version 4), then `version_and_extrinsic_type` is obtained by having a MSB of `1` on the
85//! _transaction protocol version_ byte (which translates to `0b1000_0101`).
86//!
87//! Additionally, _signed_ extrinsics also carry with them address and signature information encoded
88//! as follows:
89//!
90//! #### from_address
91//!
92//! This is the [SCALE encoded][frame::deps::codec] address of the sender of the extrinsic. The
93//! address is the first generic parameter of [`sp_runtime::generic::UncheckedExtrinsic`], and so
94//! can vary from chain to chain.
95//!
96//! The address type used on the Polkadot relay chain is [`sp_runtime::MultiAddress<AccountId32>`],
97//! where `AccountId32` is defined [here][`sp_core::crypto::AccountId32`]. When constructing a
98//! signed extrinsic to be submitted to a Polkadot node, you'll always use the
99//! [`sp_runtime::MultiAddress::Id`] variant to wrap your `AccountId32`.
100//!
101//! #### signature
102//!
103//! This is the [SCALE encoded][frame::deps::codec] signature. The signature type is configured via
104//! the third generic parameter of [`sp_runtime::generic::UncheckedExtrinsic`], which determines the
105//! shape of the signature and signing algorithm that should be used.
106//!
107//! The signature is obtained by signing the _signed payload_ bytes (see below on how this is
108//! constructed) using the private key associated with the address and correct algorithm.
109//!
110//! The signature type used on the Polkadot relay chain is [`sp_runtime::MultiSignature`]; the
111//! variants there are the types of signature that can be provided.
112//!
113//! ### General extrinsics
114//!
115//! If the extrinsic is _general_ (it doesn't carry a signature in the payload, only extension
116//! data), then `version_and_extrinsic_type` is obtained by logical OR between the general
117//! transaction type bits and the _transaction protocol version_ byte (which translates to
118//! `0b0100_0101`).
119//!
120//! ### transaction_extensions_extra
121//!
122//! This is the concatenation of the [SCALE encoded][frame::deps::codec] bytes representing first a
123//! single byte describing the extension version (this is bumped whenever a change occurs in the
124//! transaction extension pipeline) followed by the bytes of each of the [_transaction
125//! extensions_][sp_runtime::traits::TransactionExtension], and are configured by the fourth generic
126//! parameter of [`sp_runtime::generic::UncheckedExtrinsic`]. Learn more about transaction
127//! extensions [here][crate::reference_docs::transaction_extensions].
128//!
129//! When it comes to constructing an extrinsic, each transaction extension has two things that we
130//! are interested in here:
131//!
132//! - The actual SCALE encoding of the transaction extension type itself; this is what will form our
133//!   `transaction_extensions_extra` bytes.
134//! - An `Implicit` type. This is SCALE encoded into the `transaction_extensions_implicit` data (see
135//!   below).
136//!
137//! Either (or both) of these can encode to zero bytes.
138//!
139//! Each chain configures the set of transaction extensions that it uses in its runtime
140//! configuration. At the time of writing, Polkadot configures them
141//! [here](https://github.com/polkadot-fellows/runtimes/blob/1dc04eb954eadf8aadb5d83990b89662dbb5a074/relay/polkadot/src/lib.rs#L1432C25-L1432C25).
142//! Some of the common transaction extensions are defined
143//! [here][frame::deps::frame_system#transaction-extensions].
144//!
145//! Information about exactly which transaction extensions are present on a chain and in what order
146//! is also a part of the metadata for the chain. For V15 metadata, it can be [found
147//! here][frame::deps::frame_support::__private::metadata::v15::ExtrinsicMetadata].
148//!
149//! ## call_data
150//!
151//! This is the main payload of the extrinsic, which is used to determine how the chain's state is
152//! altered. This is defined by the second generic parameter of
153//! [`sp_runtime::generic::UncheckedExtrinsic`].
154//!
155//! A call can be anything that implements [`Encode`][frame::deps::codec::Encode]. In FRAME-based
156//! runtimes, a call is represented as an enum of enums, where the outer enum represents the FRAME
157//! pallet being called, and the inner enum represents the call being made within that pallet, and
158//! any arguments to it. Read more about the call enum
159//! [here][crate::reference_docs::frame_runtime_types].
160//!
161//! FRAME `Call` enums are automatically generated, and end up looking something like this:
162#![doc = docify::embed!("./src/reference_docs/extrinsic_encoding.rs", call_data)]
163//! In pseudo-code, this `Call` enum encodes equivalently to:
164//!
165//! ```text
166//! call_data = concat(
167//!     pallet_index,
168//!     call_index,
169//!     call_args
170//! )
171//! ```
172//!
173//! - `pallet_index` is a single byte denoting the index of the pallet that we are calling into, and
174//!   is what the tag of the outermost enum will encode to.
175//! - `call_index` is a single byte denoting the index of the call that we are making the pallet,
176//!   and is what the tag of the inner enum will encode to.
177//! - `call_args` are the SCALE encoded bytes for each of the arguments that the call expects, and
178//!   are typically provided as values to the inner enum.
179//!
180//! Information about the pallets that exist for a chain (including their indexes), the calls
181//! available in each pallet (including their indexes), and the arguments required for each call can
182//! be found in the metadata for the chain. For V15 metadata, this information [is
183//! here][frame::deps::frame_support::__private::metadata::v15::PalletMetadata].
184//!
185//! # The Signed Payload Format
186//!
187//! All _signed_ extrinsics submitted to a node from the outside world (also known as
188//! _transactions_) need to be _signed_. The data that needs to be signed for some extrinsic is
189//! called the _signed payload_, and its shape is described by the following pseudo-code:
190//!
191//! ```text
192//! signed_payload = blake2_256(
193//! 	concat(
194//!     	call_data,
195//!     	transaction_extensions_extra,
196//!     	transaction_extensions_implicit,
197//! 	)
198//! )
199//! ```
200//!
201//! The bytes representing `call_data` and `transaction_extensions_extra` can be obtained as
202//! descibed above. `transaction_extensions_implicit` is constructed by SCALE encoding the
203//! ["implicit" data][sp_runtime::traits::TransactionExtension::Implicit] for each transaction
204//! extension that the chain is using, in order.
205//!
206//! Once we've concatenated those together, we hash the result using a Blake2 256bit hasher.
207//!
208//! The [`sp_runtime::generic::SignedPayload`] type takes care of assembling the correct payload for
209//! us, given `call_data` and a tuple of transaction extensions.
210//!
211//! # The General Transaction Format
212//!
213//! A General transaction does not have a signature method hardcoded in the check logic of the
214//! extrinsic, such as a traditionally signed transaction. Instead, general transactions should have
215//! one or more extensions in the transaction extension pipeline that auhtorize origins in some way,
216//! one of which could be the traditional signature check that happens for all signed transactions
217//! in the [Checkable](sp_runtime::traits::Checkable) implementation of
218//! [UncheckedExtrinsic](sp_runtime::generic::UncheckedExtrinsic). Therefore, it is up to each
219//! extension to define the format of the payload it will try to check and authorize the right
220//! origin type. For an example, look into the [authorization example pallet
221//! extensions](pallet_example_authorization_tx_extension::extensions)
222//!
223//! # Example Encoding
224//!
225//! Using [`sp_runtime::generic::UncheckedExtrinsic`], we can construct and encode an extrinsic as
226//! follows:
227#![doc = docify::embed!("./src/reference_docs/extrinsic_encoding.rs", encoding_example)]
228
229#[docify::export]
230pub mod call_data {
231	use codec::{Decode, Encode};
232	use sp_runtime::{traits::Dispatchable, DispatchResultWithInfo};
233
234	// The outer enum composes calls within
235	// different pallets together. We have two
236	// pallets, "PalletA" and "PalletB".
237	#[derive(Encode, Decode, Clone)]
238	pub enum Call {
239		#[codec(index = 0)]
240		PalletA(PalletACall),
241		#[codec(index = 7)]
242		PalletB(PalletBCall),
243	}
244
245	// An inner enum represents the calls within
246	// a specific pallet. "PalletA" has one call,
247	// "Foo".
248	#[derive(Encode, Decode, Clone)]
249	pub enum PalletACall {
250		#[codec(index = 0)]
251		Foo(String),
252	}
253
254	#[derive(Encode, Decode, Clone)]
255	pub enum PalletBCall {
256		#[codec(index = 0)]
257		Bar(String),
258	}
259
260	impl Dispatchable for Call {
261		type RuntimeOrigin = ();
262		type Config = ();
263		type Info = ();
264		type PostInfo = ();
265		fn dispatch(self, _origin: Self::RuntimeOrigin) -> DispatchResultWithInfo<Self::PostInfo> {
266			Ok(())
267		}
268	}
269}
270
271#[docify::export]
272pub mod encoding_example {
273	use super::call_data::{Call, PalletACall};
274	use crate::reference_docs::transaction_extensions::transaction_extensions_example;
275	use codec::Encode;
276	use sp_core::crypto::AccountId32;
277	use sp_keyring::sr25519::Keyring;
278	use sp_runtime::{
279		generic::{SignedPayload, UncheckedExtrinsic},
280		MultiAddress, MultiSignature,
281	};
282
283	// Define some transaction extensions to use. We'll use a couple of examples
284	// from the transaction extensions reference doc.
285	type TransactionExtensions = (
286		transaction_extensions_example::AddToPayload,
287		transaction_extensions_example::AddToSignaturePayload,
288	);
289
290	// We'll use `UncheckedExtrinsic` to encode our extrinsic for us. We set
291	// the address and signature type to those used on Polkadot, use our custom
292	// `Call` type, and use our custom set of `TransactionExtensions`.
293	type Extrinsic = UncheckedExtrinsic<
294		MultiAddress<AccountId32, ()>,
295		Call,
296		MultiSignature,
297		TransactionExtensions,
298	>;
299
300	pub fn encode_demo_extrinsic() -> Vec<u8> {
301		// The "from" address will be our Alice dev account.
302		let from_address = MultiAddress::<AccountId32, ()>::Id(Keyring::Alice.to_account_id());
303
304		// We provide some values for our expected transaction extensions.
305		let transaction_extensions = (
306			transaction_extensions_example::AddToPayload(1),
307			transaction_extensions_example::AddToSignaturePayload,
308		);
309
310		// Construct our call data:
311		let call_data = Call::PalletA(PalletACall::Foo("Hello".to_string()));
312
313		// The signed payload. This takes care of encoding the call_data,
314		// transaction_extensions_extra and transaction_extensions_implicit, and hashing
315		// the result if it's > 256 bytes:
316		let signed_payload = SignedPayload::new(call_data.clone(), transaction_extensions.clone());
317
318		// Sign the signed payload with our Alice dev account's private key,
319		// and wrap the signature into the expected type:
320		let signature = {
321			let sig = Keyring::Alice.sign(&signed_payload.encode());
322			MultiSignature::Sr25519(sig)
323		};
324
325		// Now, we can build and encode our extrinsic:
326		let ext = Extrinsic::new_signed(call_data, from_address, signature, transaction_extensions);
327
328		let encoded_ext = ext.encode();
329		encoded_ext
330	}
331}