Sub3.0模板進化2修改aura為babe--by Skyh

node-template起始共識是Aura,就是Round Robin輪流出塊的簡單機制曹体,現(xiàn)在改成Babe就是基于插槽VRF的共識

1. 依賴修改

runtime的Cargo.toml搜索有兩處aura

pallet-aura = { version = "3.0.0", default-features = false }
sp-consensus-aura = { version = "0.9.0", default-features = false }
修改成:
pallet-babe = { version = "3.0.0", default-features = false }
sp-consensus-babe = { version = "0.9.0", default-features = false }
還有std中的

還有node的Cargo.toml也有兩處

sc-consensus-aura = "0.9.0"
sp-consensus-aura = "0.9.0"

2. 修改runtime的lib.rs板驳, 搜索Aura

把SessionKey修改:

impl_opaque_keys! {
    pub struct SessionKeys {
        pub aura: Aura,
        pub grandpa: Grandpa,
    }
}
改成:
impl_opaque_keys! {
    pub struct SessionKeys {
        pub babe: Babe,
        pub grandpa: Grandpa,
    }
}

把aura的定義改成:

parameter_types! {
    pub const EpochDuration: u64 = EPOCH_DURATION_IN_BLOCKS as u64;
    pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
    pub const ReportLongevity: u64 = 0; // by Skyh
        // BondingDuration::get() as u64 * SessionsPerEra::get() as u64 * EpochDuration::get(); // Kusama
}

impl pallet_babe::Config for Runtime {
    type EpochDuration = EpochDuration;
    type ExpectedBlockTime = ExpectedBlockTime;
    type EpochChangeTrigger = pallet_babe::ExternalTrigger;
    type KeyOwnerProofSystem = (); // Historical;
    type KeyOwnerProof =
    <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, pallet_babe::AuthorityId)>>::Proof;
    type KeyOwnerIdentification =
    <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, pallet_babe::AuthorityId)>>::IdentificationTuple;
    type HandleEquivocation = (); //pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, (), ReportLongevity>; // () Offences
    type WeightInfo = ();
}

修改construct_runtime的Aura:

construct_runtime!(
    pub enum Runtime where
        Block = Block,
        NodeBlock = opaque::Block,
        UncheckedExtrinsic = UncheckedExtrinsic
    {
        Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>},
        System: frame_system::{Module, Call, Config, Storage, Event<T>},
        Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},
        Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},
        TransactionPayment: pallet_transaction_payment::{Module, Storage},
        RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage},

        Babe: pallet_babe::{Module, Call, Storage, Config, Inherent, ValidateUnsigned},
        Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event, ValidateUnsigned},

        // Include the custom logic from the template pallet in the runtime.
        TemplateModule: template::{Module, Call, Storage, Event<T>},
    }
);

修改impl_runtime_apis中的AuraApi

impl sp_consensus_babe::BabeApi<Block> for Runtime {
        fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration {
            sp_consensus_babe::BabeGenesisConfiguration {
                slot_duration: Babe::slot_duration(),
                epoch_length: EpochDuration::get(),
                c: PRIMARY_PROBABILITY,
                genesis_authorities: Babe::authorities(),
                randomness: Babe::randomness(),
                allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryPlainSlots,
            }
        }

        fn current_epoch_start() -> sp_consensus_babe::Slot {
            Babe::current_epoch_start()
        }

        fn current_epoch() -> sp_consensus_babe::Epoch {
            Babe::current_epoch()
        }

        fn next_epoch() -> sp_consensus_babe::Epoch {
            Babe::next_epoch()
        }

        fn generate_key_ownership_proof(
            _slot: sp_consensus_babe::Slot,
            authority_id: sp_consensus_babe::AuthorityId,
        ) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> {
            use codec::Encode;

            Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id))
                .map(|p| p.encode())
                .map(sp_consensus_babe::OpaqueKeyOwnershipProof::new)
        }

        fn submit_report_equivocation_unsigned_extrinsic(
            equivocation_proof: sp_consensus_babe::EquivocationProof<<Block as BlockT>::Header>,
            key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof,
            ) -> Option<()> {
            let key_owner_proof = key_owner_proof.decode()?;

            Babe::submit_unsigned_equivocation_report(
                equivocation_proof,
                key_owner_proof,
                )
        }
    }

坑:在這里心俗,高度抽象化必須對應(yīng)看人家項目使用Historical流酬,所以必須在runtime中加入:

# historical的特性
pallet-session = { version = "3.0.0", default-features = false, features = ["historical"] }

impl pallet_session::historical::Config for Runtime {
    type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
    type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>;
}

Historical: session_historical::{Module},

坑2:也要加入staking, 這算耦合么嘱函,暫時沒有好的解決方法

pallet-staking = { version = "3.0.0", default-features = false }

也在babe和grandpa加入KeyOwnerProofSystem為Historical
編譯報錯要實現(xiàn)super的session的config


image.png

3. 被逼加入session和staking

具體代碼

parameter_types! {
    pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17);
}

impl pallet_session::Config for Runtime {
    type Event = Event;
    type ValidatorId = <Self as frame_system::Config>::AccountId;
    type ValidatorIdOf = pallet_staking::StashOf<Self>;

    type Keys = SessionKeys;
    type ShouldEndSession = Babe;
    type NextSessionRotation = Babe;
    type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, Staking>;
    type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
    type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
    type WeightInfo = ();
}

impl pallet_session::historical::Config for Runtime {
    type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
    type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>;
}

又必須加入staking

pallet_staking_reward_curve::build! {
    const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
        min_inflation: 0_025_000,
        max_inflation: 0_100_000,
        ideal_stake: 0_500_000,
        falloff: 0_050_000,
        max_piece_count: 40,
        test_precision: 0_005_000,
    );
}

parameter_types! {
    pub const SessionsPerEra: sp_staking::SessionIndex = 3; // 3 hours
    pub const BondingDuration: pallet_staking::EraIndex = 4; // 12 hours
    pub const SlashDeferDuration: pallet_staking::EraIndex = 2; // 6 hours
    pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
    pub const ElectionLookahead: BlockNumber = EPOCH_DURATION_IN_BLOCKS / 4;

    pub const MaxNominatorRewardedPerValidator: u32 = 64;
    pub const MaxIterations: u32 = 5;
    // 0.05%. The higher the value, the more strict solution acceptance becomes.
    pub MinSolutionScoreBump: Perbill = Perbill::from_rational_approximation(5u32, 10_000);
    pub StakingUnsignedPriority: TransactionPriority =
        Perbill::from_percent(90) * TransactionPriority::max_value();
}

parameter_types! {
    pub OffchainSolutionWeightLimit: Weight = BlockWeights::get()
        .get(DispatchClass::Normal)
        .max_extrinsic
        .expect("Normal extrinsics have weight limit configured by default; qed")
        .saturating_sub(BlockExecutionWeight::get());
}

pub type CurrencyToVote = frame_support::traits::U128CurrencyToVote;

// TODO: Kusama
// type SlashCancelOrigin = EnsureOneOf<
//  AccountId,
//  EnsureRoot<AccountId>,
//  pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>
// >;

impl pallet_staking::Config for Runtime {
    type Call = Call;
    type Event = Event;
    type UnixTime = Timestamp;

    type Currency = Balances;
    type CurrencyToVote = CurrencyToVote;
    type RewardRemainder = (); // TODO: Treasury
    type Slash = (); // TODO: Treasury
    type Reward = (); // rewards are minted from the voi

    type SessionInterface = Self;
    type NextNewSession = Session;
    type SessionsPerEra = SessionsPerEra;
    type BondingDuration = BondingDuration;
    type SlashDeferDuration = SlashDeferDuration;
    /// A super-majority of the council can cancel the slash.
    type SlashCancelOrigin = EnsureRoot<Self::AccountId>; // TODO: SlashCancelOrigin
    type RewardCurve = RewardCurve;
    type ElectionLookahead = ElectionLookahead;

    type MinSolutionScoreBump = MinSolutionScoreBump;
    type MaxIterations = MaxIterations;
    type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
    type UnsignedPriority = StakingUnsignedPriority; // Kusama
    type OffchainSolutionWeightLimit = OffchainSolutionWeightLimit;
    type WeightInfo = ();
}

坑3:staking需要實現(xiàn)SendTransactionTypes

impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
    where
        Call: From<C>,
{
    type OverarchingCall = Call;
    type Extrinsic = UncheckedExtrinsic;
}

4. 修改chain_spec.rs和service.rs

chain_spec首先先引入 BabeId

use sp_consensus_babe::AuthorityId as BabeId;

// 加session_key
fn session_keys(
    babe: BabeId,
    grandpa: GrandpaId,
) -> SessionKeys {
    SessionKeys { babe, grandpa }
}

修改authority_keys_from_seed的AuraId

pub fn authority_keys_from_seed(seed: &str) -> (AccountId, AccountId, BabeId, GrandpaId) {
    (
        get_account_id_from_seed::<sr25519::Public>(&format!("{}//stash", seed)),
        get_account_id_from_seed::<sr25519::Public>(seed),
        get_from_seed::<BabeId>(seed),
        get_from_seed::<GrandpaId>(seed),
    )
}

再在testnet_genesis中修改aura:

pallet_babe: Some(Default::default()),
pallet_grandpa: Some(Default::default()),
pallet_session: Some(SessionConfig {
            keys: initial_authorities.iter().map(|x| {
                (x.0.clone(),
                 x.0.clone(),
                 session_keys(
                     x.2.clone(), x.3.clone()
                 ))
            }).collect::<Vec<_>>(),
        }),
        pallet_staking: Some(StakingConfig {
            validator_count: initial_authorities.len() as u32 * 2,
            minimum_validator_count: initial_authorities.len() as u32,
            stakers: initial_authorities
                .iter()
                .map(|x| (x.0.clone(), x.1.clone(), INITIAL_STAKING, StakerStatus::Validator))
                .collect(),
            invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(),
            slash_reward_fraction: Perbill::from_percent(10),
            ..Default::default()
        }),

寫在最后甘畅,這次修改在這里:
https://github.com/skyh24/node-template3/commit/513d4bad382baf1f65d90608143d1bc491e9de74

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市往弓,隨后出現(xiàn)的幾起案子疏唾,更是在濱河造成了極大的恐慌,老刑警劉巖函似,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件槐脏,死亡現(xiàn)場離奇詭異,居然都是意外死亡撇寞,警方通過查閱死者的電腦和手機顿天,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進店門堂氯,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人牌废,你說我怎么就攤上這事咽白。” “怎么了畔规?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵局扶,是天一觀的道長。 經(jīng)常有香客問我叁扫,道長三妈,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任莫绣,我火速辦了婚禮畴蒲,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘对室。我一直安慰自己模燥,他們只是感情好,可當我...
    茶點故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布掩宜。 她就那樣靜靜地躺著蔫骂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪牺汤。 梳的紋絲不亂的頭發(fā)上辽旋,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天,我揣著相機與錄音檐迟,去河邊找鬼补胚。 笑死,一個胖子當著我的面吹牛追迟,可吹牛的內(nèi)容都是我干的溶其。 我是一名探鬼主播,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼敦间,長吁一口氣:“原來是場噩夢啊……” “哼瓶逃!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起每瞒,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤金闽,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后剿骨,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡埠褪,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年浓利,在試婚紗的時候發(fā)現(xiàn)自己被綠了挤庇。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡贷掖,死狀恐怖嫡秕,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情苹威,我是刑警寧澤昆咽,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站牙甫,受9級特大地震影響掷酗,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜窟哺,卻給世界環(huán)境...
    茶點故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一泻轰、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧且轨,春花似錦浮声、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至至朗,卻和暖如春屉符,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背爽丹。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工筑煮, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人粤蝎。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓真仲,卻偏偏與公主長得像,于是被迫代替她去往敵國和親初澎。 傳聞我的和親對象是個殘疾皇子秸应,可洞房花燭夜當晚...
    茶點故事閱讀 45,086評論 2 355

推薦閱讀更多精彩內(nèi)容