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