Substrate构建联盟链
联盟链指的就是一条链上有可以进行管理的账户/节点,可以进行允许其它账户/节点加入链,移除节点等操作
在模板基础上修改
# 拉取模板代码
$ git clone -b v3.0.0 --depth 1 https://github.com/substrate-developer-hub/substrate-node-template
添加node-authorization
pallet
修改runtime/Cargo.toml
👇
[dependencies]
....
# 添加pallet-node-authorization依赖
pallet-node-authorization = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', tag = 'monthly-2021-05'}
std = [
...
'pallet-node-authorization/std', // 添加std
]
在runtime/src/lib.rs
中为Runtime
实现pallet_node_authorization::Config
👇
use frame_system::EnsureRoot;
parameter_types! {
pub const MaxWellKnownNodes: u32 = 8;
pub const MaxPeerIdLength: u32 = 128;
}
impl pallet_node_authorization::Config for Runtime {
type Event = Event;
type MaxWellKnownNodes = MaxWellKnownNodes;
type MaxPeerIdLength = MaxPeerIdLength;
type AddOrigin = EnsureRoot<AccountId>;
type RemoveOrigin = EnsureRoot<AccountId>;
type SwapOrigin = EnsureRoot<AccountId>;
type ResetOrigin = EnsureRoot<AccountId>;
type WeightInfo = ();
}
在construct_runtime
宏中添加NodeAuthorization
👇
construct_runtime!(
pub enum Runtime where
Block = Block,
NodeBlock = opaque::Block,
UncheckedExtrinsic = UncheckedExtrinsic
{
...
NodeAuthorization: pallet_node_authorization::{Pallet, Call, Storage, Event<T>, Config<T>},
}
);
添加创世配置,即添加管理账户
node/cargo.toml
中添加bs58
依赖,因为AccountId需要使用这种方式编码👇
[dependencies]
...
bs58 = "0.4.0"
创世配置👇
use sp_core::OpaquePeerId;
use node_template_runtime::NodeAuthorizationConfig;
fn testnet_genesis(
wasm_binary: &[u8],
initial_authorities: Vec<(AuraId, GrandpaId)>,
root_key: AccountId,
endowed_accounts: Vec<AccountId>,
_enable_println: bool,
) -> GenesisConfig {
// 添加下面的内容,这里的两个Account是官方教程中用到的,实际使用的时候要自己使用`subkey generate-node-key`命令生成
pallet_node_authorization: NodeAuthorizationConfig {
nodes: vec![
(
OpaquePeerId(bs58::decode("12D3KooWBmAwcd4PJNJvfV89HwE48nwkRmAgo8Vy3uQEyNNHBox2").into_vec().unwrap()),
endowed_accounts[0].clone()
),
(
OpaquePeerId(bs58::decode("12D3KooWQYV9dGMFoRzNStwpXztXaBUjtPqi6aU76ZgUriHhKust").into_vec().unwrap()),
endowed_accounts[1].clone()
),
],
},
}
运行
$ cargo build --release
# 启动第一个验证节点
$ ./target/release/node-template \
--chain=local \
--base-path /tmp/validator1 \
--alice \
--node-key=c12b6d18942f5ee8528c8e2baf4e147b5c5c18710926ea492d09cbd9f6c9f82a \
--port 30333 \
--ws-port 9944
# 启动第二个验证节点
$ ./target/release/node-template \
--chain=local \
--base-path /tmp/validator2 \
--bob \
--node-key=6ce3be907dbcabf20a9a5a60a712b4256a54196000a8ed4050d352bc113f8c58 \
--port 30334 \
--ws-port 9945
# 此时就已经可以出块了
如何管理节点
关于官方文档中有问题的几点
- 引入依赖时没有指定最近的版本
- 添加
Pallet
到construct_runtime
时,不应该引入Module
,而是Pallet
- 创世配置时,不需要使用
Option
类型