Update node to use pallet sessions

This commit is contained in:
Luke Parker
2022-10-27 05:23:53 -04:00
parent 49ab26209d
commit fa7a03bf60
6 changed files with 94 additions and 16 deletions

3
Cargo.lock generated
View File

@@ -7477,6 +7477,7 @@ dependencies = [
"frame-benchmarking-cli", "frame-benchmarking-cli",
"frame-system", "frame-system",
"jsonrpsee", "jsonrpsee",
"pallet-tendermint",
"pallet-transaction-payment", "pallet-transaction-payment",
"pallet-transaction-payment-rpc", "pallet-transaction-payment-rpc",
"sc-cli", "sc-cli",
@@ -7494,6 +7495,7 @@ dependencies = [
"serai-consensus", "serai-consensus",
"serai-runtime", "serai-runtime",
"sp-api", "sp-api",
"sp-application-crypto",
"sp-block-builder", "sp-block-builder",
"sp-blockchain", "sp-blockchain",
"sp-core", "sp-core",
@@ -7553,6 +7555,7 @@ dependencies = [
"sp-inherents", "sp-inherents",
"sp-offchain", "sp-offchain",
"sp-runtime", "sp-runtime",
"sp-session",
"sp-std", "sp-std",
"sp-transaction-pool", "sp-transaction-pool",
"sp-version", "sp-version",

View File

@@ -1,23 +1,72 @@
// TODO: This should be built around pallet_sessions (and pallet_staking?). use core::ops::Deref;
use std::sync::{Arc, RwLock};
use sp_application_crypto::{ use sp_application_crypto::{
RuntimePublic as PublicTrait, Pair as PairTrait, RuntimePublic as PublicTrait, Pair as PairTrait,
sr25519::{Public, Pair, Signature}, sr25519::{Public, Pair, Signature},
}; };
use sp_staking::SessionIndex;
use pallet_session::Pallet as Session;
use tendermint_machine::ext::{BlockNumber, Round, Weights, SignatureScheme}; use tendermint_machine::ext::{BlockNumber, Round, Weights, SignatureScheme};
const VALIDATORS: usize = 1; struct TendermintValidatorsStruct {
session: SessionIndex,
pub(crate) struct TendermintValidators { total_weight: u64,
keys: Pair, // sp_keystore weights: Vec<u64>,
lookup: Vec<Public>, // sessions
keys: Pair, // TODO: sp_keystore
lookup: Vec<Public>, // TODO: sessions
} }
impl TendermintValidatorsStruct {
fn from_module() -> TendermintValidatorsStruct {
let validators = Session::<serai_runtime::Runtime>::validators();
assert_eq!(validators.len(), 1);
let keys = Pair::from_string("//Alice", None).unwrap();
TendermintValidatorsStruct {
session: Session::<serai_runtime::Runtime>::current_index(),
// TODO
total_weight: validators.len().try_into().unwrap(),
weights: vec![1; validators.len()],
lookup: vec![keys.public()],
keys,
}
}
}
// Wrap every access of the validators struct in something which forces calling refresh
struct Refresh {
_refresh: Arc<RwLock<TendermintValidatorsStruct>>,
}
impl Refresh {
// If the session has changed, re-create the struct with the data on it
fn refresh(&self) {
let session = self._refresh.read().unwrap().session;
if session != Session::<serai_runtime::Runtime>::current_index() {
*self._refresh.write().unwrap() = TendermintValidatorsStruct::from_module();
}
}
}
impl Deref for Refresh {
type Target = RwLock<TendermintValidatorsStruct>;
fn deref(&self) -> &RwLock<TendermintValidatorsStruct> {
self.refresh();
&self._refresh
}
}
pub(crate) struct TendermintValidators(Refresh);
impl TendermintValidators { impl TendermintValidators {
pub(crate) fn new() -> TendermintValidators { pub(crate) fn new() -> TendermintValidators {
let keys = Pair::from_string("//Alice", None).unwrap(); TendermintValidators(Refresh {
TendermintValidators { lookup: vec![keys.public()], keys } _refresh: Arc::new(RwLock::new(TendermintValidatorsStruct::from_module())),
})
} }
} }
@@ -27,11 +76,11 @@ impl SignatureScheme for TendermintValidators {
type AggregateSignature = Vec<Signature>; type AggregateSignature = Vec<Signature>;
fn sign(&self, msg: &[u8]) -> Signature { fn sign(&self, msg: &[u8]) -> Signature {
self.keys.sign(msg) self.0.read().unwrap().keys.sign(msg)
} }
fn verify(&self, validator: u16, msg: &[u8], sig: &Signature) -> bool { fn verify(&self, validator: u16, msg: &[u8], sig: &Signature) -> bool {
self.lookup[usize::try_from(validator).unwrap()].verify(&msg, sig) self.0.read().unwrap().lookup[usize::try_from(validator).unwrap()].verify(&msg, sig)
} }
fn aggregate(sigs: &[Signature]) -> Vec<Signature> { fn aggregate(sigs: &[Signature]) -> Vec<Signature> {
@@ -55,13 +104,15 @@ impl Weights for TendermintValidators {
type ValidatorId = u16; type ValidatorId = u16;
fn total_weight(&self) -> u64 { fn total_weight(&self) -> u64 {
VALIDATORS.try_into().unwrap() self.0.read().unwrap().total_weight
}
fn weight(&self, id: u16) -> u64 {
[1; VALIDATORS][usize::try_from(id).unwrap()]
} }
fn weight(&self, id: u16) -> u64 {
self.0.read().unwrap().weights[usize::try_from(id).unwrap()]
}
// TODO
fn proposer(&self, number: BlockNumber, round: Round) -> u16 { fn proposer(&self, number: BlockNumber, round: Round) -> u16 {
u16::try_from((number.0 + u64::from(round.0)) % u64::try_from(VALIDATORS).unwrap()).unwrap() u16::try_from(number.0 + u64::from(round.0)).unwrap()
} }
} }

View File

@@ -16,6 +16,7 @@ clap = { version = "4", features = ["derive"] }
jsonrpsee = { version = "0.15", features = ["server"] } jsonrpsee = { version = "0.15", features = ["server"] }
sp-core = { git = "https://github.com/serai-dex/substrate" } sp-core = { git = "https://github.com/serai-dex/substrate" }
sp-application-crypto = { git = "https://github.com/serai-dex/substrate" }
sp-runtime = { git = "https://github.com/serai-dex/substrate" } sp-runtime = { git = "https://github.com/serai-dex/substrate" }
sp-timestamp = { git = "https://github.com/serai-dex/substrate" } sp-timestamp = { git = "https://github.com/serai-dex/substrate" }
sp-inherents = { git = "https://github.com/serai-dex/substrate" } sp-inherents = { git = "https://github.com/serai-dex/substrate" }
@@ -46,6 +47,7 @@ sc-rpc-api = { git = "https://github.com/serai-dex/substrate" }
substrate-frame-rpc-system = { git = "https://github.com/serai-dex/substrate" } substrate-frame-rpc-system = { git = "https://github.com/serai-dex/substrate" }
pallet-transaction-payment-rpc = { git = "https://github.com/serai-dex/substrate" } pallet-transaction-payment-rpc = { git = "https://github.com/serai-dex/substrate" }
pallet-tendermint = { path = "../pallet-tendermint", default-features = false }
serai-runtime = { path = "../runtime" } serai-runtime = { path = "../runtime" }
serai-consensus = { path = "../consensus" } serai-consensus = { path = "../consensus" }

View File

@@ -1,8 +1,12 @@
use sc_service::ChainType; use sc_service::ChainType;
use sp_core::{Pair as PairTrait, sr25519::Pair}; use sp_core::{Pair as PairTrait, sr25519::Pair};
use pallet_tendermint::crypto::Public;
use serai_runtime::{WASM_BINARY, AccountId, GenesisConfig, SystemConfig, BalancesConfig}; use serai_runtime::{
WASM_BINARY, AccountId, opaque::SessionKeys, GenesisConfig, SystemConfig, BalancesConfig,
SessionConfig,
};
pub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>; pub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>;
@@ -15,12 +19,16 @@ fn account_id_from_name(name: &'static str) -> AccountId {
} }
fn testnet_genesis(wasm_binary: &[u8], endowed_accounts: Vec<AccountId>) -> GenesisConfig { fn testnet_genesis(wasm_binary: &[u8], endowed_accounts: Vec<AccountId>) -> GenesisConfig {
let alice = account_id_from_name("Alice");
GenesisConfig { GenesisConfig {
system: SystemConfig { code: wasm_binary.to_vec() }, system: SystemConfig { code: wasm_binary.to_vec() },
balances: BalancesConfig { balances: BalancesConfig {
balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 60)).collect(), balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 60)).collect(),
}, },
transaction_payment: Default::default(), transaction_payment: Default::default(),
session: SessionConfig {
keys: vec![(alice, alice, SessionKeys { tendermint: Public::from(alice) })],
},
} }
} }

View File

@@ -23,6 +23,7 @@ sp-std = { git = "https://github.com/serai-dex/substrate", default-features = fa
sp-version = { git = "https://github.com/serai-dex/substrate", default-features = false } sp-version = { git = "https://github.com/serai-dex/substrate", default-features = false }
sp-inherents = { git = "https://github.com/serai-dex/substrate", default-features = false } sp-inherents = { git = "https://github.com/serai-dex/substrate", default-features = false }
sp-offchain = { git = "https://github.com/serai-dex/substrate", default-features = false } sp-offchain = { git = "https://github.com/serai-dex/substrate", default-features = false }
sp-session = { git = "https://github.com/serai-dex/substrate", default-features = false }
sp-transaction-pool = { git = "https://github.com/serai-dex/substrate", default-features = false } sp-transaction-pool = { git = "https://github.com/serai-dex/substrate", default-features = false }
sp-block-builder = { git = "https://github.com/serai-dex/substrate", default-features = false} sp-block-builder = { git = "https://github.com/serai-dex/substrate", default-features = false}
sp-runtime = { git = "https://github.com/serai-dex/substrate", default-features = false } sp-runtime = { git = "https://github.com/serai-dex/substrate", default-features = false }
@@ -61,6 +62,7 @@ std = [
"sp-version/std", "sp-version/std",
"sp-inherents/std", "sp-inherents/std",
"sp-offchain/std", "sp-offchain/std",
"sp-session/std",
"sp-transaction-pool/std", "sp-transaction-pool/std",
"sp-block-builder/std", "sp-block-builder/std",
"sp-runtime/std", "sp-runtime/std",

View File

@@ -7,7 +7,7 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
use sp_core::OpaqueMetadata; use sp_core::OpaqueMetadata;
pub use sp_core::sr25519::{Public, Signature}; pub use sp_core::sr25519::{Public, Signature};
use sp_runtime::{ use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys, create_runtime_str, generic, impl_opaque_keys, KeyTypeId,
traits::{Convert, OpaqueKeys, IdentityLookup, BlakeTwo256, Block as BlockT}, traits::{Convert, OpaqueKeys, IdentityLookup, BlakeTwo256, Block as BlockT},
transaction_validity::{TransactionSource, TransactionValidity}, transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, Perbill, ApplyExtrinsicResult, Perbill,
@@ -349,6 +349,18 @@ sp_api::impl_runtime_apis! {
} }
} }
impl sp_session::SessionKeys<Block> for Runtime {
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
opaque::SessionKeys::generate(seed)
}
fn decode_session_keys(
encoded: Vec<u8>,
) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
opaque::SessionKeys::decode_into_raw_public_keys(&encoded)
}
}
impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime { impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
fn account_nonce(account: AccountId) -> Index { fn account_nonce(account: AccountId) -> Index {
System::account_nonce(account) System::account_nonce(account)