Substrate framework introduction
Amit Nadiger
Polyglot(Rust??, Move, C++, C, Kotlin, Java) Blockchain, Polkadot, UTXO, Substrate, Sui, Aptos, Wasm, Proxy-wasm,AndroidTV, Dvb, STB, Linux, Cas, Engineering management.
Note: Slides used in this blog are copied from the other tutorials in YouTube etc.
The Substrate framework is an open-source blockchain development framework created by Parity Technologies. It empowers developers to build their own customized and scalable blockchain networks. Substrate provides a set of tools, libraries, and modules that simplify the process of creating and launching blockchains, enabling developers to focus on building unique features and applications.
The Substrate framework empowers developers to build highly customizable and interoperable blockchain networks while abstracting away much of the complexity associated with blockchain development. Its modular design, efficient runtime, and compatibility with Polkadot make it a powerful tool for creating innovative blockchain solutions.
Above digs is copied from Building blockchains the easy way | Substrate Seminar - YouTube
Key Features of the Substrate Framework:
Architecture of Substrate: Architecture and Rust libraries | Substrate_ Docs
BlockDig :
At a high level, a Substrate node consists of two main parts:
Some of the most important activities that are handled by core client services involve the following components:
Runtime
The runtime determines whether transactions are valid or invalid and is responsible for handling changes to the blockchain state. Requests coming from the outside come through the client into the runtime, and the runtime is responsible for the state transition functions and storing the resulting state.
The Substrate runtime is designed to compile to WebAssembly (Wasm) byte code. This design decision enables:
Core libraries
The Substrate libraries are divided into three main areas of responsibility:
Library Responsibility:
Core client libraries
The libraries that enable a Substrate node to handle its network responsibilities, including consensus and block execution are Rust crates that use the sc_ prefix in the crate name. For example, the sc_service library is responsible for building the networking layer for Substrate blockchains, managing the communication between the network participants and the transaction pool.
Primitive libraries
At the lowest level of the Substrate architecture, there are primitive libraries that give you control over underlying operations and enable communication between the core client services and the runtime. The primitive libraries are Rust crates that use the sp_ prefix in the crate name.
The primitive libraries provide the lowest level of abstraction to expose interfaces that the core client or the runtime can use to perform operations or interact with each other.
For example:
FRAME libraries for the runtime
The libraries that enable you to build the runtime logic and to encode and decode the information passed into and out of the runtime are Rust crates that use the frame_ prefix in the crate name.
The frame_* libraries provide the infrastructure for the runtime. For example, the frame_system library provides a basic set of functions for interacting with other Substrate components andframe_support enables you to declare runtime storage items, errors, and events.
In addition to the infrastructure provided by the frame_* libraries, the runtime can include one or more pallet_* libraries. Each Rust crate that uses the pallet_ prefix represents a single FRAME module. In most cases, you use the pallet_* libraries to assemble the functionality you want to incorporate in the blockchain to suit your project.
You can build a Substrate runtime without using the frame_* or pallet_* libraries using the primitives libraries. For Example Tuxedo runtime(UTXO-based Substrate Runtimes) is built without the Frame or pallet :
FYI
Tuxedo is
Unlike account-based systems(Frame runtime ), where each user has a balance that can be updated by transactions, UTXO-based systems treat each transaction output as a separate entity that can be spent or unspent. This has several benefits, such as parallel processing and simpler state transitions. By implementing UTXO as one of the possible paradigms on substrate, the Tuxedo project aims to demonstrate the flexibility and interoperability of Polkadot.
UTXO MODEL(Tuxedo Runtime)
ACCOUNTS MODEL(Frame Runtime)
ACCOUNTS VS UTXOS
CRYPTOCURRENCY EXAMPLE
Accounts:
AddressBalance0xA11ce50 coins0xB0bbb10 coins
UTXOs:
SerialAddressAmount0x11110xA11ce50 coins0x22220xB0bbb2 coins0x33330xB0bbb4 coins0x44440xB0bbb4 coins
TUXEDO
A framework for writing Substrate Runtimes that are based on the UTXO model.
PPT by Tuxedo team :Tuxedo: UTXOs for Substrate (off-narrative-labs.github.io)
Tuxedo Transaction looks like below :
I will not go many details in to UTXO and Tuxedo, since Tuxedo is still under development, let's keep an eye on Tuxedo.
Pallet:
Let's try to study briefly about pallets which are building blocks of substrate based blockchains, without which it can't be possible to achieve the modularity and extensibility, seamless upgradability, reusability, interoperability of blockchain.
"pallet" is a modular component that encapsulates a specific set of functionalities within the blockchain runtime. Pallets are the building blocks of a Substrate-based blockchain and play a central role in achieving the framework's modularity and customization goals. Each pallet focuses on a specific feature or aspect of the blockchain's behavior, and developers can combine multiple pallets to create a blockchain network tailored to their requirements.
In essence, pallets are the core components of a Substrate-based blockchain's runtime. They enable the modular design of the blockchain, making it easier for developers to build, customize, and upgrade blockchain networks by composing and configuring these building blocks according to their specific use cases and requirements.
Here's how pallets contribute to the modularity of a Substrate-based blockchain:
How to build the substrate-FRAME based pallet : Collactable NFT. Setup (sacha-l.github.io)
Typical Pallet implementation using FRAME is like below (Copied from below Link: Runtime development | Substrate_ Docs
// Add required imports and dependencies
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
// Declare the pallet type
// This is a placeholder to implement traits and methods.
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
// Add the runtime configuration trait
// All types and constants go here.
#[pallet::config]
pub trait Config: frame_system::Config { ... }
// Add runtime storage to declare storage items.
#[pallet::storage]
#[pallet::getter(fn something)]
pub type MyStorage<T: Config> = StorageValue<_, u32>;
// Add runtime events
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> { ... }
// Add hooks to define some logic that should be executed
// in a specific context, for example on_initialize.
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> { ... }
// Pallet internal functions
?impl<T: Config> Pallet<T> { ... }
// Add functions that are callable from outside the runtime.
#[pallet::call]
impl<T:Config> Pallet<T> { ... }
}
Pallets are broadly classified as System ,Functional and para chain pallets , please see link: FRAME pallets | Substrate_ Docs
Will try to write a separate article on how to develop the custom pallet, since the objective of this article is just general overview of substrate framework.
Runtime:
Next important topic is Runtime layer of substrate framework-based network:
The runtime layer is the heart of a Substrate-based blockchain, defining how the blockchain functions, processes transactions, maintains state, interacts with consensus mechanisms, and more. It encapsulates the core logic that distinguishes one blockchain network from another and allows developers to customize and create unique blockchain applications.
As described earlier the runtime layer is a crucial component of a Substrate-based blockchain. It defines the behavior and rules of the blockchain network by encapsulating the logic of the blockchain's operations, including transaction validation, consensus mechanisms, storage management, and more. In the context of Substrate, the runtime layer is written in Rust programming language and compiled into WebAssembly (Wasm) code for efficient execution on blockchain nodes.
领英推荐
Here's a more detailed explanation of the runtime layer in a Substrate blockchain:
Consensus layer :
The consensus layer in the Substrate architecture is responsible for ensuring that all nodes in the blockchain network agree on the validity and order of transactions and blocks. It defines the rules by which nodes come to a consensus on the state of the blockchain. Substrate supports various consensus mechanisms, each with its own strengths and characteristics, allowing developers to choose the one that best suits their blockchain's requirements.
Here's a deeper look into the consensus layer in the Substrate architecture:
Consensus Mechanisms: Substrate allows developers to choose from different consensus mechanisms, each tailored for different use cases. Some of the supported consensus mechanisms include:
The Substrate node template uses a proof of authority consensus model also referred to as?authority round?or?Aura?consensus. The Aura consensus protocol limits block production to a rotating list of authorized accounts. The authorized accounts—authorities—create blocks in a round robin fashion and are generally considered to be trusted participants in the network.
AURA: Stands for Authority based round robin scheduling, it provides a slot-based block authoring mechanism. In Aura a known set of authorities take turns producing blocks.
Aura is a simple and deterministic consensus mechanism suitable for small to medium-sized networks. It relies on a predefined list of validators to take turns producing blocks.
"predefined list of validators" refers to a set of validator nodes that have been selected to participate in the consensus process. These validators are responsible for producing and validating blocks in a decentralized blockchain network.
Here's how the process of validator selection and their predefined list works:
BABE(Blind Assignment for Blockchain Extension): is consensus mechanism designed for larger networks. It uses a verifiable random function to select validators for block production in a probabilistic manner. BABE is a consensus mechanism designed for the Polkadot blockchain. It is a block production mechanism that aims to improve the security and scalability of the network. BABE uses a verifiable random function (VRF) to determine which validator will produce the next block. It introduces randomness to the block production process, making it difficult for malicious actors to predict which validator will be chosen to create the next block. While BABE enhances the security of the blockchain, it is not directly related to Byzantine fault tolerance.
Byzantine Fault Tolerance: Byzantine fault tolerance is a concept in distributed computing and consensus algorithms. It refers to the ability of a distributed system to continue functioning correctly even when some of its nodes (participants) are faulty or malicious (Byzantine). Byzantine fault-tolerant consensus mechanisms ensure that the network can reach a consensus on the state of the system despite the presence of potentially malicious nodes.
In the context of blockchain, Byzantine fault tolerance is a critical property of consensus mechanisms to ensure the security and reliability of the network. Some well-known Byzantine fault-tolerant consensus mechanisms include Practical Byzantine Fault Tolerance (PBFT), HoneyBadgerBFT, and Tendermint.
Please note that while both BABE and Byzantine fault tolerance are important concepts in blockchain technology, they are not directly linked . BABE is a specific block production mechanism used in the Polkadot network, while Byzantine fault tolerance refers to a property of consensus mechanisms that ensures the system's resilience to malicious behavior.
GRANDPA: GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is a finality gadget that provides finality guarantees for blocks. It complements the block production mechanism and helps achieve a secure and final consensus. So please remember "GRANDPA" refers to a finality gadget, not a consensus mechanism in the traditional sense. In blockchain terminology, a finality gadget is a component that helps determine when a block is considered irreversible or "finalized" in a blockchain network.
GRANDPA is a finality gadget used in the Polkadot blockchain ecosystem.It just listens to gossip about blocks that have been produced by block authoring nodes. GRANDPA validators vote on chains, not blocks,. GRANDPA validators vote on a block that they consider best and their votes are applied transitively to all previous blocks. After two-thirds of the GRANDPA authorities have voted for a particular block, it is considered final.
GRANDPA works in conjunction with Polkadot's nominated proof-of-stake (NPoS) consensus mechanism. It aims to achieve faster finality and consensus in a heterogeneous multi-chain environment, where different chains can have varying consensus mechanisms and block finalization speeds. GRANDPA helps to determine the canonical chain and ensure that blocks are finalized in a way that maximizes security and efficiency.
Block Production: Consensus mechanisms in Substrate are responsible for determining how blocks are produced and who is responsible for producing them. Different mechanisms use varying methods to select block producers, whether based on predefined schedules (like Aura) or probabilistic algorithms (like Babe).
Below slide syas about block production within the substrate :
Below slide says about block importing from other nodes:
Finality and Block Validation: Achieving consensus doesn't stop at block production. Finality is an essential aspect of ensuring that confirmed transactions cannot be reverted. Substrate's consensus mechanisms work together with finality gadgets like GRANDPA to establish the irreversible state of the blockchain.
Security and Fault Tolerance: Consensus mechanisms are designed to be secure and resilient against various attack vectors. BFT-based mechanisms like Babe and GRANDPA provide strong fault tolerance, ensuring that the network remains operational even in the presence of malicious nodes.
Interoperability with Polkadot: Substrate's consensus mechanisms are designed to interoperate with the Polkadot network. Substrate-based blockchains can connect to the Polkadot Relay Chain using bridges, enabling cross-chain communication and interoperability.
Consensus Upgrades: Substrate's modular design extends to the consensus layer as well. Developers can choose and switch between consensus mechanisms based on their blockchain's requirements. Upgrading the consensus mechanism can be done as part of a runtime upgrade without disrupting the entire network.
Consensus Agnostic Pallets: Pallets developed for Substrate-based blockchains are designed to be consensus-agnostic. This means that the same pallets can work with different consensus mechanisms seamlessly, offering flexibility when designing and deploying blockchain applications.
Cross-Consensus Messaging.
XCM stands for "Cross-Consensus Messaging." It's a protocol that allows communication and interaction between different blockchains or parachains within the Polkadot ecosystem, which is a multi-chain blockchain platform built using the Substrate framework.
XCM enables inter-chain communication by providing a standardized way for messages to be sent from one parachain to another, or even from one blockchain to another connected through Polkadot's relay chain. This communication includes transferring assets, invoking smart contracts, and triggering actions on remote chains. Essentially, XCM enables composability and interoperability between different chains in the Polkadot network.
Here are a few key points about XCM:
Forkless upgrade:
Reference: Upgrade a running network | Substrate_ Docs
The below slide says about the issues faced in bitcoin due to interger overflow bug :
Bitcoin decided to do hardfork and below slide says what problem happened due to hardfork:
Substrate-based blockchains, the runtime logic is indeed implemented as a WebAssembly (Wasm) module. Substrate supports forkless runtime upgrades, which means that the upgrade process does not require a hard fork or disruption to the network. Here's how the runtime upgrade process typically works in Substrate:
Preparing the New Runtime: Developers create an updated version of the runtime Wasm module, which includes the changes and improvements they want to introduce to the blockchain's logic.
Specifying the Runtime Upgrade: A runtime upgrade is coordinated through a governance process. Network participants (validators, stakeholders, or both) submit and discuss proposals for upgrading the runtime. These proposals include the new runtime Wasm code and related metadata.
Referendum and Voting: The network participants use the governance mechanisms of the blockchain to vote on the proposed upgrade. If the proposal receives enough support (as defined by the governance rules), it progresses to the next step.
Activation of the Upgrade:Once the referendum passes and the required threshold is met, the upgrade is scheduled to be activated at a specific block height. This is done in a way that validators and nodes are aware of the upcoming upgrade.
Pre-Upgrade Preparation: Before the upgrade, nodes download and verify the new runtime Wasm module. This can be done ahead of time to ensure a smooth transition.
Runtime Upgrade at Block Height: When the blockchain reaches the specified block height, the upgrade is triggered. The new runtime Wasm module is activated, replacing the old one. This is a seamless process because all nodes have already downloaded and verified the new module.
No Disruption to the Network: Since all nodes have prepared for the upgrade and are using the new runtime logic, there is no need for a hard fork. Transactions and consensus continue without interruption using the new logic.
Post-Upgrade Operations: Validators and nodes continue to validate and produce blocks using the updated runtime logic. Any new features or changes introduced by the upgrade become active.
Substrate's forkless upgrade mechanism is designed to ensure a smooth transition between runtime versions without requiring network-wide coordination for a hard fork. It promotes more frequent and secure upgrades, making it easier for blockchain projects to innovate and improve their systems over time.
Let's keep in mind that the specifics of the upgrade process might vary based on the Substrate version and any customizations made to the blockchain. We should always refer to the official Substrate documentation and resources for the most accurate and up-to-date information on runtime upgrades.
How the runtime WASM module is distributed to each node?
Runtime WebAssembly (Wasm) modules are distributed to each node in the network via the network itself. When a runtime upgrade is planned and approved through the governance process in a Substrate-based blockchain, the new Wasm module needs to be propagated to all the nodes in a secure and efficient manner. Here's how the distribution process generally works:
It's important to note that the specifics of how the runtime module is distributed and the mechanisms used can vary based on the implementation, network setup, and consensus algorithm of the Substrate-based blockchain. In some cases, specialized tools or processes might be employed to ensure efficient and secure distribution.
To ensure the smoothest runtime upgrade process, it's recommended to follow best practices, such as having redundancy and fallback mechanisms in case of unexpected issues during the distribution process. Substrate's governance and upgrade mechanisms are designed to support these upgrade scenarios and make the process as reliable as possible.
Please read the below article for the Inherents,Transactions,extrinsics in below link:
Important APIS or crates:
The Substrate runtime api is the interface between the node and the runtime. There isn’t a fixed set of runtime apis, instead it is up to the user to declare and implement these runtime apis. The declaration of a runtime api is normally done outside of a runtime, while the implementation of it has to be done in the runtime.
sp_core - Rust (docs.rs); Shareable Substrate types.
sp_metadata_ir - Rust (docs.rs): Intermediate representation of the runtime metadata.
Will be studying the node discovery (trusted and untrusted one ) and other advanced topics in later articles.
Info about nodes : Substrate-nodes | LinkedIn
Info about substrate architecture : Architecture and Rust libraries | Substrate_ Docs
Debugging guide : Debug | Substrate_ Docs
RUST_LOG=runtime=debug ./target/release/node-template --dev
Thanks for reading till end, please comment if you have any.
Senior Technologist, Blockchain Accelerator, Digital/Fintech/Banking-as-a-Service Innovation, Strategy & Compliance
6 个月Liked it, puts everything in place, and takes us through the wilderness, thanks
Lead Technical Specialist @ ITS ? Startup Founder @ Async
8 个月That's a great article! Thanks a lot!