Rust区块链扩展库cumulus-pallet-aura-ext的使用,Substrate共识机制增强与Aura协议扩展功能

Rust区块链扩展库cumulus-pallet-aura-ext的使用,Substrate共识机制增强与Aura协议扩展功能

安装

在项目目录中运行以下Cargo命令安装库:

cargo add cumulus-pallet-aura-ext

或者在Cargo.toml中添加以下行:

cumulus-pallet-aura-ext = "0.22.0"

基本信息

  • 版本: 0.22.0
  • 许可证: Apache-2.0
  • 发布时间: 1天前
  • 大小: 36.2 KiB

完整示例代码

以下是cumulus-pallet-aura-ext的使用示例,展示了如何在Substrate运行时中集成和配置该库:

//! 示例:在Substrate运行时中使用cumulus-pallet-aura-ext

use frame_support::{
    construct_runtime, parameter_types,
    traits::{ConstU32, Contains},
};
use sp_core::H256;
use sp_runtime::{
    traits::{BlakeTwo256, IdentityLookup},
    BuildStorage,
};
use cumulus_pallet_aura_ext::Pallet as AuraExt;

// 定义运行时配置
pub struct Runtime;

parameter_types! {
    pub const BlockHashCount: u32 = 250;
}

impl frame_system::Config for Runtime {
    type BaseCallFilter = frame_support::traits::Everything;
    type BlockWeights = ();
    type BlockLength = ();
    type DbWeight = ();
    type RuntimeOrigin = ();
    type RuntimeCall = ();
    type Index = u64;
    type BlockNumber = u64;
    type Hash = H256;
    type Hashing = BlakeTwo256;
    type AccountId = u64;
    type Lookup = IdentityLookup<Self::AccountId>;
    type Header = sp_runtime::generic::Header<Self::BlockNumber, Self::Hashing>;
    type RuntimeEvent = ();
    type BlockHashCount = BlockHashCount;
    type Version = ();
    type PalletInfo = PalletInfo;
    type AccountData = ();
    type OnNewAccount = ();
    type OnKilledAccount = ();
    type SystemWeightInfo = ();
    type SS58Prefix = ();
    type OnSetCode = ();
    type MaxConsumers = ConstU32<16>;
}

impl pallet_aura::Config for Runtime {
    type AuthorityId = sp_consensus_aura::sr25519::AuthorityId;
    type DisabledValidators = ();
    type MaxAuthorities = ConstU32<32>;
}

parameter_types! {
    pub const AllowedDomains: Vec<u64> = vec![1, 2, 3];
    pub const AllowedAccounts: Vec<u64> = vec![4, 5, 6];
}

pub struct AllowedDomainsFilter;
impl Contains<u64> for AllowedDomainsFilter {
    fn contains(a: &u64) -> bool {
        AllowedDomains::get().contains(a)
    }
}

impl cumulus_pallet_aura_ext::Config for Runtime {
    type Event = ();
    type DomainFilter = AllowedDomainsFilter;
    type AccountFilter = AllowedAccounts;
    type WeightInfo = ();
}

construct_runtime!(
    pub enum Runtime {
        System: frame_system,
        Aura: pallet_aura,
        AuraExt: cumulus-pallet-aura-ext,
    }
);

// 创建新的测试运行时
pub fn new_test_ext() -> sp_io::TestExternalities {
    let t = frame_system::GenesisConfig::<Runtime>::default()
        .build_storage()
        .unwrap();
    let mut ext = sp_io::TestExternalities::new(t);
    ext.execute_with(|| System::set_block_number(1));
    ext
}

fn main() {
    println!("Aura扩展库示例运行时配置完成");
}

功能说明

该示例展示了如何:

  1. 配置基本运行时框架
  2. 设置Aura共识机制
  3. 集成cumulus-pallet-aura-ext并配置其参数
  4. 定义域过滤器和账户过滤器
  5. 构建完整的运行时结构

cumulus-pallet-aura-ext提供了对标准Aura共识机制的扩展功能,包括:

  • 特定域的验证权限控制
  • 账户级别的验证权限过滤
  • 与Substrate框架的无缝集成

注意事项

  • 需要配合pallet-aura使用
  • 配置时需要明确指定过滤规则
  • 适用于基于Substrate的平行链开发

1 回复

Rust区块链扩展库cumulus-pallet-aura-ext的使用:Substrate共识机制增强与Aura协议扩展功能

概述

cumulus-pallet-aura-ext是一个用于Substrate区块链框架的扩展库,专门用于增强Aura共识机制的功能。Aura (Authority Round)是一种基于已知验证者轮流出块的共识算法,这个扩展库为其添加了额外的功能,使其更适合于平行链(parachain)环境。

主要功能

  1. 提供Aura共识机制的扩展功能
  2. 支持平行链与中继链之间的共识协调
  3. 增强验证者集合管理
  4. 提供额外的区块生产控制功能

使用方法

1. 添加依赖

首先,在项目的Cargo.toml中添加依赖:

[dependencies]
cumulus-pallet-aura-ext = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-vX.Y.Z" }

请将X.Y.Z替换为与你项目兼容的Polkadot版本。

2. 在Runtime中集成

在你的Substrate runtime的lib.rs文件中添加以下代码:

impl pallet_aura_ext::Config for Runtime {
    type AuthorityId = AuraId;
    type DisabledValidators = ();
}

construct_runtime!(
    pub enum Runtime where
        Block = Block,
        NodeBlock = opaque::Block,
        UncheckedExtrinsic = UncheckedExtrinsic
    {
        // ... 其他pallet
        AuraExt: pallet_aura_ext::{Pallet, Storage},
    }
);

3. 配置Genesis

chain_spec.rs中配置初始验证者集合:

use sp_consensus_aura::sr25519::AuthorityId as AuraId;

fn testnet_genesis(
    // ... 其他参数
    initial_authorities: Vec<AuraId>,
    // ... 
) -> GenesisConfig {
    GenesisConfig {
        // ... 其他配置
        aura_ext: Some(AuraExtConfig {
            authorities: initial_authorities.clone(),
        }),
        // ...
    }
}

示例代码

1. 自定义验证者逻辑

use pallet_aura_ext::Config;

impl Config for Runtime {
    type AuthorityId = AuraId;
    type DisabledValidators = Session;
    
    // 自定义验证者禁用逻辑
    fn is_authority_disabled(authority_idx: u32) -> bool {
        // 检查当前会话中该验证者是否被禁用
        Session::is_disabled(authority_idx)
    }
}

2. 获取当前验证者集合

use pallet_aura_ext::Authorities;

fn get_current_authorities() -> Vec<AuraId> {
    Authorities::<Runtime>::get()
}

3. 监听验证者变更事件

use frame_support::traits::OnNewAccount;

impl OnNewAccount<AccountId极 for Runtime {
    fn on_new_account(who: &AccountId) {
        // 当新验证者加入时的处理逻辑
        pallet_aura_ext::Pallet::<Runtime>::note_new_authority(who);
    }
}

高级功能

1. 动态验证者管理

use frame_system::RawOrigin;
use pallet_aura_ext::Call;

// 添加新验证者
pub fn add_authority(origin: OriginFor<T>, authority: AuraId) -> DispatchResult {
    ensure_root(origin)?;
    pallet_aura_ext::Pallet::<T>::add_authority(authority);
    Ok(())
}

// 移除验证者
pub fn remove_authority(origin: OriginFor<T>, authority: AuraId) -> DispatchResult {
    ensure_root(origin)?;
    pallet_aura_ext::Pallet::<T>::remove_authority(authority);
    Ok(())
}

2. 自定义出块逻辑

use sp_consensus_aura::AuraApi;

impl AuraApi<Block, AuraId> for Runtime {
    fn slot_duration() -> sp_consensus_aura::SlotDuration {
        // 自定义slot持续时间
        sp_consensus_aura::SlotDuration::from_millis(2000)
    }

    fn authorities() -> Vec<AuraId> {
        // 自定义获取验证者集合的逻辑
        pallet_aura_ext::Pallet::<Runtime>::authorities()
    }
}

完整示例Demo

下面是一个完整的runtime集成示例,展示了如何将cumulus-pallet-aura-ext集成到Substrate链中:

// runtime/src/lib.rs

// 1. 引入必要的依赖
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use frame_support::traits::OnNewAccount;

// 2. 配置pallet_aura_ext
impl pallet_aura_ext::Config for Runtime {
    type AuthorityId = AuraId;
    type DisabledValidators = Session; // 使用Session pallet管理禁用的验证者
}

// 3. 实现OnNewAccount回调
impl OnNewAccount<AccountId> for Runtime {
    fn on_new_account(who: &AccountId) {
        // 当新账户创建时通知aura_ext pallet
        pallet_aura_ext::Pallet::<Runtime>::note_new_authority(who);
    }
}

// 4. 在construct_runtime!宏中添加pallet
construct_runtime!(
    pub enum Runtime where
        Block = Block,
        NodeBlock = opaque::Block,
        UncheckedExtrinsic = UncheckedExtrinsic
    {
        System: frame_system,
        // ... 其他pallet
        Aura: pallet_aura,
        AuraExt: pallet_aura_ext::{Pallet, Storage, Config<T>},
        Session: pallet_session,
    }
);

// 5. 实现AuraApi
impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
    fn slot_duration() -> sp_consensus_aura::SlotDuration {
        // 设置slot持续时间为2秒
        sp_consensus_aura::SlotDuration::from_millis(2000)
    }

    fn authorities() -> Vec<AuraId> {
        // 从aura_ext pallet获取当前验证者集合
        pallet_aura_ext::Pallet::<Runtime>::authorities()
    }
}
// chain_spec.rs

use node_template_runtime::AuraExtConfig;
use sp_consensus_aura::sr25519::AuthorityId as AuraId;

/// 测试网Genesis配置
pub fn testnet_config() -> GenesisConfig {
    let initial_authorities: Vec<AuraId> = vec![
        // 这里添加初始验证者的公钥
        get_authority_keys_from_seed("Alice"),
        get_authority_keys_from_seed("Bob"),
    ];

    GenesisConfig {
        system: SystemConfig {
            // system配置...
        },
        aura: AuraConfig {
            authorities: initial_authorities.clone(),
        },
        aura_ext: Some(AuraExtConfig {
            authorities: initial_authorities,
        }),
        // 其他pallet配置...
    }
}
// src/aura_extensions.rs

use frame_support::dispatch::DispatchResult;
use frame_system::RawOrigin;
use pallet_aura_ext::Pallet as AuraExt;

/// 自定义模块用于管理验证者
pub mod aura_extensions {
    use super::*;

    /// 添加新验证者
    pub fn add_authority(authority: AuraId) -> DispatchResult {
        AuraExt::<Runtime>::add_authority(RawOrigin::Root.into(), authority)
    }

    /// 移除验证者
    pub fn remove_authority(authority: AuraId) -> DispatchResult {
        AuraExt::<Runtime>::remove_authority(RawOrigin::Root.into(), authority)
    }

    /// 获取当前验证者集合
    pub fn get_authorities() -> Vec<AuraId> {
        AuraExt::<Runtime>::authorities()
    }

    /// 检查验证者是否被禁用
    pub fn is_authority_disabled(index: u32) -> bool {
        <Runtime as pallet_aura_ext::Config>::DisabledValidators::is_disabled(index)
    }
}

注意事项

  1. 使用cumulus-pallet-aura-ext时,需要确保与Substrate和Cumulus的版本兼容
  2. 在生产环境中使用时,应该仔细考虑验证者集合变更的安全性
  3. 平行链环境下的Aura配置可能与独立链有所不同
  4. 性能关键型应用可能需要调整默认的slot持续时间

这个扩展库特别适合需要自定义Aura共识行为或构建平行链的项目,它提供了比标准Aura实现更多的控制选项和灵活性。

回到顶部