Files
serai/substrate/tendermint/client/src/validators.rs

172 lines
4.4 KiB
Rust
Raw Normal View History

use core::{marker::PhantomData, ops::Deref};
2022-10-27 05:23:53 -04:00
use std::sync::{Arc, RwLock};
2022-11-01 16:28:08 -04:00
use async_trait::async_trait;
2022-11-01 20:06:42 -04:00
use tokio::sync::RwLock as AsyncRwLock;
use sp_core::Decode;
use sp_application_crypto::{
2022-11-01 20:06:42 -04:00
RuntimePublic as PublicTrait,
sr25519::{Public, Signature},
};
2022-11-01 20:06:42 -04:00
use sp_keystore::CryptoStore;
2022-10-27 05:23:53 -04:00
use sp_staking::SessionIndex;
use sp_api::{BlockId, ProvideRuntimeApi};
use sc_client_api::HeaderBackend;
2022-10-27 05:23:53 -04:00
use tendermint_machine::ext::{BlockNumber, Round, Weights, SignatureScheme};
2022-10-27 08:44:53 -04:00
use sp_tendermint::TendermintApi;
2022-11-01 20:06:42 -04:00
use crate::{KEY_TYPE_ID, TendermintClient};
2022-10-27 08:44:53 -04:00
2022-10-27 05:23:53 -04:00
struct TendermintValidatorsStruct {
session: SessionIndex,
total_weight: u64,
weights: Vec<u64>,
lookup: Vec<Public>,
2022-10-27 05:23:53 -04:00
}
impl TendermintValidatorsStruct {
2022-11-01 20:06:42 -04:00
fn from_module<T: TendermintClient>(client: &Arc<T::Client>) -> Self {
let last = client.info().finalized_hash;
2022-10-27 08:44:53 -04:00
let api = client.runtime_api();
let session = api.current_session(&BlockId::Hash(last)).unwrap();
let validators = api.validators(&BlockId::Hash(last)).unwrap();
2022-10-27 05:23:53 -04:00
assert_eq!(validators.len(), 1);
2022-11-01 20:06:42 -04:00
Self {
2022-10-27 08:44:53 -04:00
session,
2022-10-27 05:23:53 -04:00
// TODO
total_weight: validators.len().try_into().unwrap(),
weights: vec![1; validators.len()],
lookup: validators,
2022-10-27 05:23:53 -04:00
}
}
}
2022-10-27 05:23:53 -04:00
// Wrap every access of the validators struct in something which forces calling refresh
struct Refresh<T: TendermintClient> {
_tc: PhantomData<T>,
client: Arc<T::Client>,
2022-10-27 05:23:53 -04:00
_refresh: Arc<RwLock<TendermintValidatorsStruct>>,
}
2022-10-27 08:44:53 -04:00
impl<T: TendermintClient> Refresh<T> {
2022-10-27 05:23:53 -04:00
// If the session has changed, re-create the struct with the data on it
fn refresh(&self) {
let session = self._refresh.read().unwrap().session;
2022-10-27 08:44:53 -04:00
if session !=
self
.client
.runtime_api()
.current_session(&BlockId::Hash(self.client.info().finalized_hash))
2022-10-27 08:44:53 -04:00
.unwrap()
{
*self._refresh.write().unwrap() = TendermintValidatorsStruct::from_module::<T>(&self.client);
2022-10-27 05:23:53 -04:00
}
}
}
impl<T: TendermintClient> Deref for Refresh<T> {
2022-10-27 05:23:53 -04:00
type Target = RwLock<TendermintValidatorsStruct>;
fn deref(&self) -> &RwLock<TendermintValidatorsStruct> {
self.refresh();
&self._refresh
}
}
/// Tendermint validators observer, providing data on the active validators.
2022-11-01 20:06:42 -04:00
pub struct TendermintValidators<T: TendermintClient>(
Refresh<T>,
Arc<AsyncRwLock<Option<T::Keystore>>>,
);
2022-10-27 08:44:53 -04:00
impl<T: TendermintClient> TendermintValidators<T> {
pub(crate) fn new(client: Arc<T::Client>) -> TendermintValidators<T> {
2022-11-01 20:06:42 -04:00
TendermintValidators(
Refresh {
_tc: PhantomData,
_refresh: Arc::new(RwLock::new(TendermintValidatorsStruct::from_module::<T>(&client))),
client,
},
Arc::new(AsyncRwLock::new(None)),
)
}
pub(crate) async fn set_keys(&self, keys: T::Keystore) {
*self.1.write().await = Some(keys);
}
}
2022-11-01 16:28:08 -04:00
#[async_trait]
impl<T: TendermintClient> SignatureScheme for TendermintValidators<T> {
type ValidatorId = u16;
type Signature = Signature;
type AggregateSignature = Vec<Signature>;
2022-11-01 16:28:08 -04:00
async fn sign(&self, msg: &[u8]) -> Signature {
2022-11-01 20:06:42 -04:00
let read = self.1.read().await;
let keys = read.as_ref().unwrap();
let key = {
let pubs = keys.sr25519_public_keys(KEY_TYPE_ID).await;
if pubs.is_empty() {
keys.sr25519_generate_new(KEY_TYPE_ID, None).await.unwrap()
} else {
pubs[0]
}
};
Signature::decode(
&mut keys.sign_with(KEY_TYPE_ID, &key.into(), msg).await.unwrap().unwrap().as_ref(),
)
.unwrap()
}
fn verify(&self, validator: u16, msg: &[u8], sig: &Signature) -> bool {
2022-10-27 05:23:53 -04:00
self.0.read().unwrap().lookup[usize::try_from(validator).unwrap()].verify(&msg, sig)
}
fn aggregate(sigs: &[Signature]) -> Vec<Signature> {
sigs.to_vec()
}
fn verify_aggregate(&self, validators: &[u16], msg: &[u8], sigs: &Vec<Signature>) -> bool {
if validators.len() != sigs.len() {
return false;
}
for (v, sig) in validators.iter().zip(sigs.iter()) {
if !self.verify(*v, msg, sig) {
return false;
}
}
true
}
}
impl<T: TendermintClient> Weights for TendermintValidators<T> {
type ValidatorId = u16;
fn total_weight(&self) -> u64 {
2022-10-27 05:23:53 -04:00
self.0.read().unwrap().total_weight
}
2022-10-27 05:23:53 -04:00
fn weight(&self, id: u16) -> u64 {
2022-10-27 05:23:53 -04:00
self.0.read().unwrap().weights[usize::try_from(id).unwrap()]
}
2022-10-27 05:23:53 -04:00
// TODO
fn proposer(&self, number: BlockNumber, round: Round) -> u16 {
u16::try_from(
(number.0 + u64::from(round.0)) % u64::try_from(self.0.read().unwrap().lookup.len()).unwrap(),
)
.unwrap()
}
}