Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the development framework of Substrate block chain

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how to understand the Substrate blockchain development framework, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

How to build a Substrate chain that supports your own runtime modules.

1. About Rust

Both Substrate and runtime modules are developed using Rust.

Rust is a low-level statically typed language, which is characterized by speed guarantee and reliability, but it is difficult to learn. A very important but often neglected topic in blockchain development is how to master Rust. We won't analyze Rust code in this tutorial, but mastering Rust is a prerequisite for engineers who want to use Susbtrate for blockchain development.

As a programming language, Rust has a steep learning curve. Part of the reason is that the syntax specification adopted by Rust relies heavily on features such as generics, feature extraction, lifecycle, and macros, as well as other considerations such as action and invariance.

Other Substrate learning resources, such as Substrate Kitties collectibles workshop-generated Rust, are easy to master, but this is not the case unless you have more development experience in the underlying language, such as Cellular languages, and have been exposed to more API involving system-level management.

In fact, if you are new to Rust, it takes a little patience and time to understand the core concepts and features of the development language. After mastering Rust, the development of Substrate will become enjoyable. This Rust is well written, suitable for beginners to learn, and suitable for experienced users to review Rust.

2. Install Susbtrate

To install Substrate, you only need to call a bash script on the Parity website. Substrate provides two ways to install:

If you want to quickly grasp the development of blockchain applications, we recommend Huizhi's series of blockchain application development tutorials, which cover a variety of blockchain development languages such as Bitcoin, Ethernet Square, eos, fabric and tendermint, as well as java, go, nodejs, python, php, dart and other development languages.

2.1 Quick installation

Quick installation installs the prebuilt Substrate development chain, Substrate scripts, Substrate chain command-line configuration tools, and run-time modules.

Running the Substrate installation script with the-- fast flag skips installing tools that are not necessary to run Sbustrate:

~ $curl https://getsubstrate.io-sSf | bash-s-fast

The above command pulls the dependencies of Susbtrate, including Rust, OpenSSL, LLVM, and so on, and then installs.

2.2 full installation

In addition to the above, the full installation will also install the following two tools:

SubKey: a command-line tool for creating or restoring Substrate keys, which is useful when you need to manage your account on the command line

Substrate node: a preconfigured Substrate node that can be directly connected to the Substrate test network

Run the following command for a full installation:

/ / full Substrate installation~$ curl https://getsubstrate.io-sSf | bash

Once the installation script has been executed, update your cargo environment to invoke the newly installed program:

~ $source ~ / .cargo/env

You can now access the precompiled Substrate node using the substrate command. To verify that Substrate node and SubKey are installed correctly, check the versions of the two programs:

~ $substrate-- version~$ subkey-- version

Note: the Polkadot JS app already implements subkey in its account management interface-you can manage accounts in a browser without subkey, which is why subkey is optional.

By default, Substrate and tools are installed in the ~ / .tools / bin directory. You can take a look at the specific installation:

~ $cd ~ / .clients / bin~/.cargo/bin$ ls

You will notice that in addition to substrate and subkey, there are also two programs, substrate-node-new and substrate-module-new, which we will use to create new custom nodes and runtime modules.

3. Update the Substrate script

To update the Substrate script, you need to clone the latest version, and then replace the cargo binary with the following command:

~ $f = `mktemp-d` ~ $git clone https://github.com/paritytech/substrate-up $f ~ $cp-a $f cargo/bin * * / .cargo/bin ~ $cp-a $f cargo/bin * *

Now that we have the Substrate tool installed, we are ready to run the Substrate development node. This node starts to block, but it is of no use to the developer.

In any case, we can start the Substrate development chain with the following command:

~ $substrate-- dev

The node is up now, and you can see that the block starts to come out. To see more information about the blockchain, such as the status of each supporting module, we will use the Polkadot JS application.

To view the command line options for substrate, look at the output of-- help:

~ $substrate-- help

Familiarizing yourself with the output of help commands is a proven way to understand the functionality of command-line programs. The current version contains some flags that are useful for testing, such as preconfigured accounts-- alice,-- bob, and so on. The light flag runs the node in lightweight mode, with support for lightweight clients built into the framework.

Before we start customizing the build, let's review how to view the Substrate chain. The basic approach is to use the Polkadot JS application, which is developed using Typescript and react.

4. Use Polkadot JS App

The Polkadot JS application not only provides basic blockchain browser functions, but also provides API and interfaces for managing Substrate modules. As its name suggests, this application also supports Polkadot block chains. There are two ways to use Polkadot JS:

Use a Parity-hosted application to visit https://polkadot.js.org/apps

Clone the project repository and run the application on the local machine

Let's clone the project to run locally, and once the installation is complete, we can point to the node of our Susbtrate chain, another running process on our machine.

First, clone and run the Polkadot JS application:

~ $git clone https://github.com/polkadot-js/apps.git~$ mv apps polkadot.js~$ cd polkadot.js & & yarn start

Then start the substrate development chain on another terminal:

Substrate-dev

Access localhost:3000 in your browser. To connect JS App to our local development chain, select Settings from the sidebar menu, and then switch to Local Node endpoint, similar to the following figure:

Click Save & Reload and you will notice that many of the links in the sidebar menu are active, depending on the support of your chain.

Let's take a look at the feature that almost all chains support-accounts. Go to the Accounts section of the application-on the My Account options page you will see a set of accounts that are preconfigured with balances, and we can also transfer money, delete accounts and back up account keys between these accounts. This indicates the location of the Plokadot JS App-interacting with your Substrate chain at the UI layer.

Before we continue, we would like to mention what Polkadot UI can accomplish:

You can upload wasm-compiled Ink smart contracts

As a POS consensus chain, the Staking region allows you to mortgage funds to become a transaction verifier.

The Democracy area is designed to handle voting and management on the chain

You can test the JSON RPC of Substrate in the Toolbox area

You can be confused about which preconfigured accounts come from. In fact, these accounts, including the compiled code of the runtime logic itself, are saved in a Chain Specification file, also known as chain spec.

Use the Chain Spec JSON file configuration chain

The chain configuration is a large JSON object that is generated using substrate's build-spec command. This command extracts the configuration items of the runtime module introduced by the node, some of which are null and some provide default values.

Basically, the runtime module can rely on the creation configuration, that is, the configuration we provide when the blockchain is initialized. The block chain state is initialized by the creation block, the first block of the chain. The job of the chain specJSON file is to define this initial state.

Once the configuration file is generated, we can open the file and modify it according to our needs.

The node provides the purge-chain command to reset the blockchain, which is usually used in development:

~ $substrate purge-chain-- dev

The framework provides three default chain specifications, namely configuration: dev, local, and staging.

The dev:dev specification is provided primarily for development, and the configuration includes a set of accounts and runtime modules

The local:local specification is similar to dev and is mainly used for private chains.

The staging:staging specification is more conservative, defining a limited number of accounts, and you need to define your own module-related configurations. When building a product chain, you should choose this specification.

What we need to do now is to create a new chainspec using the build-spec command and store the output in a separate file. For example, write the specification to the my-chainspec.json file in the current user's home directory:

~ $substrate build-spec-- chain=dev > ~ / my-chainspec.json

Open the file in the file editor to see the available configuration options.

Id: you can change your own name

Name: a name for people to see

TelemetryEndpoints: the access node that provides Telemetry services

...

Once we have modified the chainspec file, we can convert it to the original encoding state with the-- raw flag:

~ $substrate build-spec-- chain ~ / chainspec.json-- raw > ~ / mychain.json

Finally, we use this chain specification file to start our substrate chain. The following assumes that you are running a custom compiled substrate node, replacing the following with the path to the node:

-chain ~ / mychain.json-validator

Next let's look at how to initialize and compile a custom Substrate node.

Initialize the Substrate node

So far, we have used the precompiled Substrate node. It's good to test the development chain, but this limits our use of our own runtime modules and custom configurations. To solve this problem, we need to download the Substrate source code.

There are two ways to start with our custom Substrate chain:

Download a node template that has been configured, such as the test network node template that is included in the full installation using the download script

Use the Substrate script to download the official node template

Basically all Substrate projects are based on the official node template, except in some special cases.

Generate a new node template with the following command:

~ $substrate-node-new my-node "Ross Bulat"

The command takes some time to execute-- pull the latest Substrate source code and compile it.

Once you are done, you can modify the lib.rs file in the runtime/src directory. The template template.rs for the runtime module is also included. Next, let's take a look at the runtime module.

Build a custom node

In the node directory, use the build.sh script to compile the node to wasm before compiling the binary program using cargo:

# build wasm./scripts/build.sh# build binarycargo build-release

The node program is now located in the. / target/release/ directory.

We have called some commands using substrate before, and now we can use our newly compiled program. To reset the blockchain and rerun it, execute the following command:

# clear chain state./target/release/ purge-chain-dev# run in dev mode./target/release/-dev

The last part we want to introduce is the runtime module. Let's take a look at what a runtime module is and how to introduce a runtime module into a substrate node.

Substrate Runtime Module: plug-in Mechanism of Block chain

The versatile and modular structure of Substrate makes it much more practical, and developers can load functions into the node runtime in the form of plug-ins, thus easily creating blockchains that meet individual needs.

These plug-in feature packs are called modules, or rather, runtime modules. The collection of runtime modules preset by Substrate is called the Substrate runtime module library-- SRML.

These modules are very useful, they implement many of the functions of other blockchain frameworks, and the code of these modules can be browsed in github. With these modules, developers do not need to reinvent the wheel, which can save a lot of time. When new features are implemented, they are also developed in the form of run-time modules.

The SRML module is maintained uniformly by Substrate, so its reliability is guaranteed. Here are some modules that are now available:

Assets: an asset module that provides similar ERC20 token support

Balances: a module for managing account balances

The module of Staking:: network maintainer managing mortgage funds

You will notice that these modules are in Rust crate format, which is designed for use in the Substrate runtime environment.

Each SRML module is packaged as crates with a srml_ prefix to the module name, which can be found in the left menu of Parity's crate library.

Overview of runtime module structure

Each module is defined in its own src/lib.rs file, following the convention. We can take a look at the top-level features of a substrate module:

A module is usually a crate of its own, but it is not required

A module can be defined as a single file module-name.rs, or, more commonly, lib.rs, if the module is a crate. A module can also have other supporting files

A module must follow a specific structure and depend on a specific Substrate API

What does the last point refer to? A module adds functionality to your blockchain, which can be provided in various forms of components:

Events: a module can declare custom events that are triggered when certain conditions are met, for example, when you cast a non-homogenization certificate, it may be a TokenCreated event. Events are encapsulated in decl_event! Hongli:

Decl_event! (pub enum Event where:: AccountId,: Hash {TokenCreated (AccountId, Hash),})

Storage: a module can define persistent data structures on the chain, such as mapping tables, lists, and so on. The storage entry is defined in decl_storage! Hongli:

Decl_storage! {trait Store for Module as NFTStorage {TokenToOwner get (token): map T::Hash = > Token; TokenIndex get (get_token_by_index): map U64 = > Tlav token Hash; TotalTokens get (total_tokens): U64;...}}

Distributable functions: functions that can be called by JSON RPC.

Public / private functions: modules can provide public functions that can be called in the runtime environment, as well as private functions that can only be called in the module.

Structure: a module can define a structure, for example, in a blockchain implementation that tracks global transportation, a ShipmenItem structure might be defined.

# [derive (Encode, Decode, Default, Clone, PartialEq)] pub struct ShipmentItem {id: Hash, container_id: Hash, price: Balance, weight: U64} initialization module

Similar to the substrate-node-new tool, we also downloaded the substrate-module-new tool. In the node runtime directory, prepare a new module using the following command:

Substrate-module-new

Let's name it my-module:

Cd runtime/srcsubstrate-module-new my-module > SRML module created as. / my-module.rs and added to git. > Ensure that you include in your. / lib.rs the line: > mod my_module

The result file, my-module, will be the same as the template.rs file contained in the original directory. But using substrate-module-new is the official recommended way to initialize a new runtime module.

Now we can develop this module, package it as create, and even distribute it to github so that everyone can maintain it.

The above is how to understand the Substrate blockchain development framework, the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report