mirror of
https://github.com/serai-dex/serai.git
synced 2025-12-12 14:09:25 +00:00
Merge branch 'develop' into HEAD
This commit is contained in:
@@ -16,28 +16,50 @@ rustdoc-args = ["--cfg", "docsrs"]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
scale = { package = "parity-scale-codec", version = "3", features = ["derive"] }
|
||||
scale-info = { version = "2", features = ["derive"] }
|
||||
scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] }
|
||||
scale-info = { version = "2", default-features = false, features = ["derive"] }
|
||||
|
||||
borsh = { version = "1", features = ["derive", "de_strict_order"], optional = true }
|
||||
serde = { version = "1", features = ["derive", "alloc"], optional = true }
|
||||
borsh = { version = "1", default-features = false, features = ["derive", "de_strict_order"], optional = true }
|
||||
serde = { version = "1", default-features = false, features = ["derive", "alloc"], optional = true }
|
||||
|
||||
sp-core = { git = "https://github.com/serai-dex/substrate" }
|
||||
sp-runtime = { git = "https://github.com/serai-dex/substrate" }
|
||||
sp-core = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
|
||||
sp-consensus-babe = { git = "https://github.com/serai-dex/substrate" }
|
||||
sp-consensus-grandpa = { git = "https://github.com/serai-dex/substrate" }
|
||||
sp-consensus-babe = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
sp-consensus-grandpa = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
|
||||
serai-primitives = { path = "../primitives", version = "0.1" }
|
||||
serai-coins-primitives = { path = "../coins/primitives", version = "0.1" }
|
||||
serai-validator-sets-primitives = { path = "../validator-sets/primitives", version = "0.1" }
|
||||
frame-support = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
|
||||
serai-primitives = { path = "../primitives", version = "0.1", default-features = false }
|
||||
serai-coins-primitives = { path = "../coins/primitives", version = "0.1", default-features = false }
|
||||
serai-validator-sets-primitives = { path = "../validator-sets/primitives", version = "0.1", default-features = false }
|
||||
serai-genesis-liquidity-primitives = { path = "../genesis-liquidity/primitives", version = "0.1" }
|
||||
serai-in-instructions-primitives = { path = "../in-instructions/primitives", version = "0.1" }
|
||||
serai-signals-primitives = { path = "../signals/primitives", version = "0.1" }
|
||||
|
||||
frame-support = { git = "https://github.com/serai-dex/substrate" }
|
||||
serai-in-instructions-primitives = { path = "../in-instructions/primitives", version = "0.1", default-features = false }
|
||||
serai-signals-primitives = { path = "../signals/primitives", version = "0.1", default-features = false }
|
||||
|
||||
[features]
|
||||
std = [
|
||||
"scale/std",
|
||||
"scale-info/std",
|
||||
|
||||
"borsh?/std",
|
||||
"serde?/std",
|
||||
|
||||
"sp-core/std",
|
||||
"sp-runtime/std",
|
||||
|
||||
"sp-consensus-babe/std",
|
||||
"sp-consensus-grandpa/std",
|
||||
|
||||
"frame-support/std",
|
||||
|
||||
"serai-primitives/std",
|
||||
"serai-coins-primitives/std",
|
||||
"serai-validator-sets-primitives/std",
|
||||
"serai-genesis-liquidity-primitives/std",
|
||||
"serai-in-instructions-primitives/std",
|
||||
"serai-signals-primitives/std",
|
||||
]
|
||||
borsh = [
|
||||
"dep:borsh",
|
||||
"serai-primitives/borsh",
|
||||
@@ -56,3 +78,4 @@ serde = [
|
||||
"serai-in-instructions-primitives/serde",
|
||||
"serai-signals-primitives/serde",
|
||||
]
|
||||
default = ["std"]
|
||||
|
||||
@@ -4,7 +4,7 @@ use serai_primitives::{Header, SeraiAddress};
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
pub struct ReportEquivocation {
|
||||
pub equivocation_proof: Box<EquivocationProof<Header>>,
|
||||
pub equivocation_proof: alloc::boxed::Box<EquivocationProof<Header>>,
|
||||
pub key_owner_proof: SeraiAddress,
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,8 @@ use primitives::OutInstructionWithBalance;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
|
||||
pub enum Call {
|
||||
transfer { to: SeraiAddress, balance: Balance },
|
||||
burn { balance: Balance },
|
||||
@@ -14,7 +15,17 @@ pub enum Call {
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
|
||||
pub enum LiquidityTokensCall {
|
||||
transfer { to: SeraiAddress, balance: Balance },
|
||||
burn { balance: Balance },
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
|
||||
pub enum Event {
|
||||
Mint { to: SeraiAddress, balance: Balance },
|
||||
Burn { from: SeraiAddress, balance: Balance },
|
||||
|
||||
@@ -6,7 +6,8 @@ type PoolId = Coin;
|
||||
type MaxSwapPathLength = sp_core::ConstU32<3>;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
|
||||
pub enum Call {
|
||||
add_liquidity {
|
||||
coin: Coin,
|
||||
@@ -38,7 +39,8 @@ pub enum Call {
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
|
||||
pub enum Event {
|
||||
PoolCreated {
|
||||
pool_id: PoolId,
|
||||
|
||||
@@ -4,7 +4,7 @@ use serai_primitives::{BlockNumber, SeraiAddress};
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
pub struct ReportEquivocation {
|
||||
pub equivocation_proof: Box<EquivocationProof<[u8; 32], BlockNumber>>,
|
||||
pub equivocation_proof: alloc::boxed::Box<EquivocationProof<[u8; 32], BlockNumber>>,
|
||||
pub key_owner_proof: SeraiAddress,
|
||||
}
|
||||
|
||||
@@ -15,10 +15,10 @@ pub enum Call {
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
|
||||
pub enum Event {
|
||||
NewAuthorities { authority_set: Vec<(SeraiAddress, u64)> },
|
||||
NewAuthorities { authority_set: alloc::vec::Vec<(SeraiAddress, u64)> },
|
||||
// TODO: Remove these
|
||||
Paused,
|
||||
Resumed,
|
||||
|
||||
@@ -5,14 +5,16 @@ use primitives::SignedBatch;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
|
||||
pub enum Call {
|
||||
execute_batch { batch: SignedBatch },
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
|
||||
pub enum Event {
|
||||
Batch { network: NetworkId, id: u32, block: BlockHash, instructions_hash: [u8; 32] },
|
||||
InstructionFailure { network: NetworkId, id: u32, index: u32 },
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
#![allow(non_camel_case_types)]
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
pub use serai_primitives as primitives;
|
||||
|
||||
pub mod system;
|
||||
|
||||
pub mod timestamp;
|
||||
@@ -16,15 +23,13 @@ pub mod genesis_liquidity;
|
||||
pub mod babe;
|
||||
pub mod grandpa;
|
||||
|
||||
pub use serai_primitives as primitives;
|
||||
pub mod tx;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
pub enum Call {
|
||||
System,
|
||||
Timestamp(timestamp::Call),
|
||||
TransactionPayment,
|
||||
Coins(coins::Call),
|
||||
LiquidityTokens(coins::Call),
|
||||
LiquidityTokens(coins::LiquidityTokensCall),
|
||||
Dex(dex::Call),
|
||||
GenesisLiquidity(genesis_liquidity::Call),
|
||||
ValidatorSets(validator_sets::Call),
|
||||
@@ -57,16 +62,20 @@ pub enum Event {
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
|
||||
pub struct Extra {
|
||||
pub era: sp_runtime::generic::Era,
|
||||
pub nonce: scale::Compact<u32>,
|
||||
pub tip: scale::Compact<u64>,
|
||||
#[codec(compact)]
|
||||
pub nonce: u32,
|
||||
#[codec(compact)]
|
||||
pub tip: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
|
||||
pub struct SignedPayloadExtra {
|
||||
pub spec_version: u32,
|
||||
pub tx_version: u32,
|
||||
@@ -74,4 +83,4 @@ pub struct SignedPayloadExtra {
|
||||
pub mortality_checkpoint: [u8; 32],
|
||||
}
|
||||
|
||||
pub type Transaction = primitives::Transaction<Call, Extra>;
|
||||
pub type Transaction = tx::Transaction<Call, Extra>;
|
||||
|
||||
@@ -7,7 +7,8 @@ use primitives::SignalId;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
|
||||
pub enum Call {
|
||||
register_retirement_signal { in_favor_of: [u8; 32] },
|
||||
revoke_retirement_signal { retirement_signal_id: [u8; 32] },
|
||||
@@ -18,7 +19,8 @@ pub enum Call {
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
|
||||
pub enum Event {
|
||||
RetirementSignalRegistered {
|
||||
signal_id: [u8; 32],
|
||||
|
||||
@@ -3,7 +3,6 @@ use frame_support::dispatch::{DispatchInfo, DispatchError};
|
||||
use serai_primitives::SeraiAddress;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum Event {
|
||||
ExtrinsicSuccess { dispatch_info: DispatchInfo },
|
||||
ExtrinsicFailed { dispatch_error: DispatchError, dispatch_info: DispatchInfo },
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
|
||||
pub enum Call {
|
||||
set { now: scale::Compact<u64> },
|
||||
set {
|
||||
#[codec(compact)]
|
||||
now: u64,
|
||||
},
|
||||
}
|
||||
|
||||
183
substrate/abi/src/tx.rs
Normal file
183
substrate/abi/src/tx.rs
Normal file
@@ -0,0 +1,183 @@
|
||||
use scale::Encode;
|
||||
|
||||
use sp_core::sr25519::{Public, Signature};
|
||||
use sp_runtime::traits::Verify;
|
||||
|
||||
use serai_primitives::SeraiAddress;
|
||||
|
||||
use frame_support::dispatch::GetDispatchInfo;
|
||||
|
||||
pub trait TransactionMember:
|
||||
Clone + PartialEq + Eq + core::fmt::Debug + scale::Encode + scale::Decode + scale_info::TypeInfo
|
||||
{
|
||||
}
|
||||
impl<
|
||||
T: Clone
|
||||
+ PartialEq
|
||||
+ Eq
|
||||
+ core::fmt::Debug
|
||||
+ scale::Encode
|
||||
+ scale::Decode
|
||||
+ scale_info::TypeInfo,
|
||||
> TransactionMember for T
|
||||
{
|
||||
}
|
||||
|
||||
type TransactionEncodeAs<'a, Extra> =
|
||||
(&'a crate::Call, &'a Option<(SeraiAddress, Signature, Extra)>);
|
||||
type TransactionDecodeAs<Extra> = (crate::Call, Option<(SeraiAddress, Signature, Extra)>);
|
||||
|
||||
// We use our own Transaction struct, over UncheckedExtrinsic, for more control, a bit more
|
||||
// simplicity, and in order to be immune to https://github.com/paritytech/polkadot-sdk/issues/2947
|
||||
#[allow(private_bounds)]
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub struct Transaction<
|
||||
Call: 'static + TransactionMember + From<crate::Call>,
|
||||
Extra: 'static + TransactionMember,
|
||||
> {
|
||||
call: crate::Call,
|
||||
mapped_call: Call,
|
||||
signature: Option<(SeraiAddress, Signature, Extra)>,
|
||||
}
|
||||
|
||||
impl<Call: 'static + TransactionMember + From<crate::Call>, Extra: 'static + TransactionMember>
|
||||
Transaction<Call, Extra>
|
||||
{
|
||||
pub fn new(call: crate::Call, signature: Option<(SeraiAddress, Signature, Extra)>) -> Self {
|
||||
Self { call: call.clone(), mapped_call: call.into(), signature }
|
||||
}
|
||||
|
||||
pub fn call(&self) -> &crate::Call {
|
||||
&self.call
|
||||
}
|
||||
}
|
||||
|
||||
impl<Call: 'static + TransactionMember + From<crate::Call>, Extra: 'static + TransactionMember>
|
||||
scale::Encode for Transaction<Call, Extra>
|
||||
{
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
let tx: TransactionEncodeAs<Extra> = (&self.call, &self.signature);
|
||||
tx.using_encoded(f)
|
||||
}
|
||||
}
|
||||
impl<Call: 'static + TransactionMember + From<crate::Call>, Extra: 'static + TransactionMember>
|
||||
scale::Decode for Transaction<Call, Extra>
|
||||
{
|
||||
fn decode<I: scale::Input>(input: &mut I) -> Result<Self, scale::Error> {
|
||||
let (call, signature) = TransactionDecodeAs::decode(input)?;
|
||||
let mapped_call = Call::from(call.clone());
|
||||
Ok(Self { call, mapped_call, signature })
|
||||
}
|
||||
}
|
||||
impl<Call: 'static + TransactionMember + From<crate::Call>, Extra: 'static + TransactionMember>
|
||||
scale_info::TypeInfo for Transaction<Call, Extra>
|
||||
{
|
||||
type Identity = TransactionDecodeAs<Extra>;
|
||||
|
||||
// Define the type info as the info of the type equivalent to what we encode as
|
||||
fn type_info() -> scale_info::Type {
|
||||
TransactionDecodeAs::<Extra>::type_info()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
mod _serde {
|
||||
use scale::Encode;
|
||||
use serde::{ser::*, de::*};
|
||||
use super::*;
|
||||
impl<Call: 'static + TransactionMember + From<crate::Call>, Extra: 'static + TransactionMember>
|
||||
Serialize for Transaction<Call, Extra>
|
||||
{
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let encoded = self.encode();
|
||||
serializer.serialize_bytes(&encoded)
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "std")]
|
||||
impl<
|
||||
'a,
|
||||
Call: 'static + TransactionMember + From<crate::Call>,
|
||||
Extra: 'static + TransactionMember,
|
||||
> Deserialize<'a> for Transaction<Call, Extra>
|
||||
{
|
||||
fn deserialize<D: Deserializer<'a>>(de: D) -> Result<Self, D::Error> {
|
||||
let bytes = sp_core::bytes::deserialize(de)?;
|
||||
<Self as scale::Decode>::decode(&mut &bytes[..])
|
||||
.map_err(|e| serde::de::Error::custom(format!("invalid transaction: {e}")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<
|
||||
Call: 'static + TransactionMember + From<crate::Call> + TryInto<crate::Call>,
|
||||
Extra: 'static + TransactionMember,
|
||||
> sp_runtime::traits::Extrinsic for Transaction<Call, Extra>
|
||||
{
|
||||
type Call = Call;
|
||||
type SignaturePayload = (SeraiAddress, Signature, Extra);
|
||||
fn is_signed(&self) -> Option<bool> {
|
||||
Some(self.signature.is_some())
|
||||
}
|
||||
fn new(call: Call, signature: Option<Self::SignaturePayload>) -> Option<Self> {
|
||||
Some(Self { call: call.clone().try_into().ok()?, mapped_call: call, signature })
|
||||
}
|
||||
}
|
||||
|
||||
impl<
|
||||
Call: 'static + TransactionMember + From<crate::Call> + TryInto<crate::Call>,
|
||||
Extra: 'static + TransactionMember,
|
||||
> frame_support::traits::ExtrinsicCall for Transaction<Call, Extra>
|
||||
{
|
||||
fn call(&self) -> &Call {
|
||||
&self.mapped_call
|
||||
}
|
||||
}
|
||||
|
||||
impl<
|
||||
Call: 'static + TransactionMember + From<crate::Call>,
|
||||
Extra: 'static + TransactionMember + sp_runtime::traits::SignedExtension,
|
||||
> sp_runtime::traits::ExtrinsicMetadata for Transaction<Call, Extra>
|
||||
{
|
||||
type SignedExtensions = Extra;
|
||||
|
||||
const VERSION: u8 = 0;
|
||||
}
|
||||
|
||||
impl<
|
||||
Call: 'static + TransactionMember + From<crate::Call> + GetDispatchInfo,
|
||||
Extra: 'static + TransactionMember,
|
||||
> GetDispatchInfo for Transaction<Call, Extra>
|
||||
{
|
||||
fn get_dispatch_info(&self) -> frame_support::dispatch::DispatchInfo {
|
||||
self.mapped_call.get_dispatch_info()
|
||||
}
|
||||
}
|
||||
|
||||
impl<
|
||||
Call: 'static + TransactionMember + From<crate::Call>,
|
||||
Extra: 'static + TransactionMember + sp_runtime::traits::SignedExtension,
|
||||
> sp_runtime::traits::BlindCheckable for Transaction<Call, Extra>
|
||||
{
|
||||
type Checked = sp_runtime::generic::CheckedExtrinsic<Public, Call, Extra>;
|
||||
|
||||
fn check(
|
||||
self,
|
||||
) -> Result<Self::Checked, sp_runtime::transaction_validity::TransactionValidityError> {
|
||||
Ok(match self.signature {
|
||||
Some((signer, signature, extra)) => {
|
||||
if !signature.verify(
|
||||
(&self.call, &extra, extra.additional_signed()?).encode().as_slice(),
|
||||
&signer.into(),
|
||||
) {
|
||||
Err(sp_runtime::transaction_validity::InvalidTransaction::BadProof)?
|
||||
}
|
||||
|
||||
sp_runtime::generic::CheckedExtrinsic {
|
||||
signed: Some((signer.into(), extra)),
|
||||
function: self.mapped_call,
|
||||
}
|
||||
}
|
||||
None => sp_runtime::generic::CheckedExtrinsic { signed: None, function: self.mapped_call },
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use sp_core::{ConstU32, bounded_vec::BoundedVec};
|
||||
use sp_core::{ConstU32, bounded::BoundedVec};
|
||||
|
||||
pub use serai_validator_sets_primitives as primitives;
|
||||
|
||||
@@ -6,11 +6,12 @@ use serai_primitives::*;
|
||||
use serai_validator_sets_primitives::*;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
|
||||
pub enum Call {
|
||||
set_keys {
|
||||
network: NetworkId,
|
||||
removed_participants: Vec<SeraiAddress>,
|
||||
removed_participants: BoundedVec<SeraiAddress, ConstU32<{ MAX_KEY_SHARES_PER_SET / 3 }>>,
|
||||
key_pair: KeyPair,
|
||||
signature: Signature,
|
||||
},
|
||||
@@ -35,7 +36,8 @@ pub enum Call {
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
|
||||
pub enum Event {
|
||||
NewSet {
|
||||
set: ValidatorSet,
|
||||
|
||||
@@ -36,7 +36,7 @@ async-lock = "3"
|
||||
|
||||
simple-request = { path = "../../common/request", version = "0.1", optional = true }
|
||||
|
||||
bitcoin = { version = "0.31", optional = true }
|
||||
bitcoin = { version = "0.32", optional = true }
|
||||
|
||||
ciphersuite = { path = "../../crypto/ciphersuite", version = "0.4", optional = true }
|
||||
monero-serai = { path = "../../coins/monero", version = "0.1.4-alpha", optional = true }
|
||||
|
||||
@@ -6,38 +6,46 @@ use bitcoin::{
|
||||
hashes::{Hash as HashTrait, hash160::Hash},
|
||||
PubkeyHash, ScriptHash,
|
||||
network::Network,
|
||||
WitnessVersion, WitnessProgram,
|
||||
address::{Error, Payload, NetworkChecked, Address as BAddressGeneric},
|
||||
WitnessVersion, WitnessProgram, ScriptBuf,
|
||||
address::{AddressType, NetworkChecked, Address as BAddress},
|
||||
};
|
||||
|
||||
type BAddress = BAddressGeneric<NetworkChecked>;
|
||||
|
||||
#[derive(Clone, Eq, Debug)]
|
||||
pub struct Address(BAddress);
|
||||
pub struct Address(ScriptBuf);
|
||||
|
||||
impl PartialEq for Address {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
// Since Serai defines the Bitcoin-address specification as a variant of the payload alone,
|
||||
// define equivalency as the payload alone
|
||||
self.0.payload() == other.0.payload()
|
||||
// Since Serai defines the Bitcoin-address specification as a variant of the script alone,
|
||||
// define equivalency as the script alone
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Address> for ScriptBuf {
|
||||
fn from(addr: Address) -> ScriptBuf {
|
||||
addr.0
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for Address {
|
||||
type Err = Error;
|
||||
fn from_str(str: &str) -> Result<Address, Error> {
|
||||
type Err = ();
|
||||
fn from_str(str: &str) -> Result<Address, ()> {
|
||||
Address::new(
|
||||
BAddressGeneric::from_str(str)
|
||||
.map_err(|_| Error::UnrecognizedScript)?
|
||||
.require_network(Network::Bitcoin)?,
|
||||
BAddress::from_str(str)
|
||||
.map_err(|_| ())?
|
||||
.require_network(Network::Bitcoin)
|
||||
.map_err(|_| ())?
|
||||
.script_pubkey(),
|
||||
)
|
||||
.ok_or(Error::UnrecognizedScript)
|
||||
.ok_or(())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Address {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.0.fmt(f)
|
||||
BAddress::<NetworkChecked>::from_script(&self.0, Network::Bitcoin)
|
||||
.map_err(|_| fmt::Error)?
|
||||
.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,55 +62,52 @@ enum EncodedAddress {
|
||||
impl TryFrom<Vec<u8>> for Address {
|
||||
type Error = ();
|
||||
fn try_from(data: Vec<u8>) -> Result<Address, ()> {
|
||||
Ok(Address(BAddress::new(
|
||||
Network::Bitcoin,
|
||||
match EncodedAddress::decode(&mut data.as_ref()).map_err(|_| ())? {
|
||||
EncodedAddress::P2PKH(hash) => {
|
||||
Payload::PubkeyHash(PubkeyHash::from_raw_hash(Hash::from_byte_array(hash)))
|
||||
}
|
||||
EncodedAddress::P2SH(hash) => {
|
||||
Payload::ScriptHash(ScriptHash::from_raw_hash(Hash::from_byte_array(hash)))
|
||||
}
|
||||
EncodedAddress::P2WPKH(hash) => {
|
||||
Payload::WitnessProgram(WitnessProgram::new(WitnessVersion::V0, hash).unwrap())
|
||||
}
|
||||
EncodedAddress::P2WSH(hash) => {
|
||||
Payload::WitnessProgram(WitnessProgram::new(WitnessVersion::V0, hash).unwrap())
|
||||
}
|
||||
EncodedAddress::P2TR(key) => {
|
||||
Payload::WitnessProgram(WitnessProgram::new(WitnessVersion::V1, key).unwrap())
|
||||
}
|
||||
},
|
||||
)))
|
||||
Ok(Address(match EncodedAddress::decode(&mut data.as_ref()).map_err(|_| ())? {
|
||||
EncodedAddress::P2PKH(hash) => {
|
||||
ScriptBuf::new_p2pkh(&PubkeyHash::from_raw_hash(Hash::from_byte_array(hash)))
|
||||
}
|
||||
EncodedAddress::P2SH(hash) => {
|
||||
ScriptBuf::new_p2sh(&ScriptHash::from_raw_hash(Hash::from_byte_array(hash)))
|
||||
}
|
||||
EncodedAddress::P2WPKH(hash) => {
|
||||
ScriptBuf::new_witness_program(&WitnessProgram::new(WitnessVersion::V0, &hash).unwrap())
|
||||
}
|
||||
EncodedAddress::P2WSH(hash) => {
|
||||
ScriptBuf::new_witness_program(&WitnessProgram::new(WitnessVersion::V0, &hash).unwrap())
|
||||
}
|
||||
EncodedAddress::P2TR(key) => {
|
||||
ScriptBuf::new_witness_program(&WitnessProgram::new(WitnessVersion::V1, &key).unwrap())
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fn try_to_vec(addr: &Address) -> Result<Vec<u8>, ()> {
|
||||
let parsed_addr =
|
||||
BAddress::<NetworkChecked>::from_script(&addr.0, Network::Bitcoin).map_err(|_| ())?;
|
||||
Ok(
|
||||
(match addr.0.payload() {
|
||||
Payload::PubkeyHash(hash) => EncodedAddress::P2PKH(*hash.as_raw_hash().as_byte_array()),
|
||||
Payload::ScriptHash(hash) => EncodedAddress::P2SH(*hash.as_raw_hash().as_byte_array()),
|
||||
Payload::WitnessProgram(program) => match program.version() {
|
||||
WitnessVersion::V0 => {
|
||||
let program = program.program();
|
||||
if program.len() == 20 {
|
||||
let mut buf = [0; 20];
|
||||
buf.copy_from_slice(program.as_ref());
|
||||
EncodedAddress::P2WPKH(buf)
|
||||
} else if program.len() == 32 {
|
||||
let mut buf = [0; 32];
|
||||
buf.copy_from_slice(program.as_ref());
|
||||
EncodedAddress::P2WSH(buf)
|
||||
} else {
|
||||
Err(())?
|
||||
}
|
||||
}
|
||||
WitnessVersion::V1 => {
|
||||
let program_ref: &[u8] = program.program().as_ref();
|
||||
EncodedAddress::P2TR(program_ref.try_into().map_err(|_| ())?)
|
||||
}
|
||||
_ => Err(())?,
|
||||
},
|
||||
(match parsed_addr.address_type() {
|
||||
Some(AddressType::P2pkh) => {
|
||||
EncodedAddress::P2PKH(*parsed_addr.pubkey_hash().unwrap().as_raw_hash().as_byte_array())
|
||||
}
|
||||
Some(AddressType::P2sh) => {
|
||||
EncodedAddress::P2SH(*parsed_addr.script_hash().unwrap().as_raw_hash().as_byte_array())
|
||||
}
|
||||
Some(AddressType::P2wpkh) => {
|
||||
let program = parsed_addr.witness_program().ok_or(())?;
|
||||
let program = program.program().as_bytes();
|
||||
EncodedAddress::P2WPKH(program.try_into().map_err(|_| ())?)
|
||||
}
|
||||
Some(AddressType::P2wsh) => {
|
||||
let program = parsed_addr.witness_program().ok_or(())?;
|
||||
let program = program.program().as_bytes();
|
||||
EncodedAddress::P2WSH(program.try_into().map_err(|_| ())?)
|
||||
}
|
||||
Some(AddressType::P2tr) => {
|
||||
let program = parsed_addr.witness_program().ok_or(())?;
|
||||
let program = program.program().as_bytes();
|
||||
EncodedAddress::P2TR(program.try_into().map_err(|_| ())?)
|
||||
}
|
||||
_ => Err(())?,
|
||||
})
|
||||
.encode(),
|
||||
@@ -116,20 +121,8 @@ impl From<Address> for Vec<u8> {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Address> for BAddress {
|
||||
fn from(addr: Address) -> BAddress {
|
||||
addr.0
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<BAddress> for Address {
|
||||
fn as_ref(&self) -> &BAddress {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Address {
|
||||
pub fn new(address: BAddress) -> Option<Self> {
|
||||
pub fn new(address: ScriptBuf) -> Option<Self> {
|
||||
let res = Self(address);
|
||||
if try_to_vec(&res).is_ok() {
|
||||
return Some(res);
|
||||
|
||||
@@ -4,7 +4,7 @@ use thiserror::Error;
|
||||
use async_lock::RwLock;
|
||||
use simple_request::{hyper, Request, Client};
|
||||
|
||||
use scale::{Compact, Decode, Encode};
|
||||
use scale::{Decode, Encode};
|
||||
use serde::{Serialize, Deserialize, de::DeserializeOwned};
|
||||
|
||||
pub use sp_core::{
|
||||
@@ -48,8 +48,8 @@ impl Block {
|
||||
/// Returns the time of this block, set by its producer, in milliseconds since the epoch.
|
||||
pub fn time(&self) -> Result<u64, SeraiError> {
|
||||
for transaction in &self.transactions {
|
||||
if let Call::Timestamp(timestamp::Call::set { now }) = &transaction.call {
|
||||
return Ok(u64::from(*now));
|
||||
if let Call::Timestamp(timestamp::Call::set { now }) = transaction.call() {
|
||||
return Ok(*now);
|
||||
}
|
||||
}
|
||||
Err(SeraiError::InvalidNode("no time was present in block".to_string()))
|
||||
@@ -167,15 +167,14 @@ impl Serai {
|
||||
}
|
||||
|
||||
fn unsigned(call: Call) -> Transaction {
|
||||
Transaction { call, signature: None }
|
||||
Transaction::new(call, None)
|
||||
}
|
||||
|
||||
pub fn sign(&self, signer: &Pair, call: Call, nonce: u32, tip: u64) -> Transaction {
|
||||
const SPEC_VERSION: u32 = 1;
|
||||
const TX_VERSION: u32 = 1;
|
||||
|
||||
let extra =
|
||||
Extra { era: sp_runtime::generic::Era::Immortal, nonce: Compact(nonce), tip: Compact(tip) };
|
||||
let extra = Extra { era: sp_runtime::generic::Era::Immortal, nonce, tip };
|
||||
let signature_payload = (
|
||||
&call,
|
||||
&extra,
|
||||
@@ -189,7 +188,7 @@ impl Serai {
|
||||
.encode();
|
||||
let signature = signer.sign(&signature_payload);
|
||||
|
||||
Transaction { call, signature: Some((signer.public().into(), signature, extra)) }
|
||||
Transaction::new(call, Some((signer.public().into(), signature, extra)))
|
||||
}
|
||||
|
||||
pub async fn publish(&self, tx: &Transaction) -> Result<(), SeraiError> {
|
||||
@@ -202,7 +201,7 @@ impl Serai {
|
||||
|
||||
// TODO: move this into substrate/client/src/validator_sets.rs
|
||||
async fn active_network_validators(&self, network: NetworkId) -> Result<Vec<Public>, SeraiError> {
|
||||
let hash: String = self
|
||||
let validators: String = self
|
||||
.call("state_call", ["SeraiRuntimeApi_validators".to_string(), hex::encode(network.encode())])
|
||||
.await?;
|
||||
let bytes = hex_decode(hash)
|
||||
@@ -378,7 +377,10 @@ impl<'a> TemporalSerai<'a> {
|
||||
let res = hex_decode(res)
|
||||
.map_err(|_| SeraiError::InvalidNode("expected hex from node wasn't hex".to_string()))?;
|
||||
Ok(Some(R::decode(&mut res.as_slice()).map_err(|_| {
|
||||
SeraiError::InvalidRuntime("different type present at storage location".to_string())
|
||||
SeraiError::InvalidRuntime(format!(
|
||||
"different type present at storage location, raw value: {}",
|
||||
hex::encode(res)
|
||||
))
|
||||
})?))
|
||||
}
|
||||
|
||||
|
||||
@@ -180,7 +180,10 @@ impl<'a> SeraiValidatorSets<'a> {
|
||||
|
||||
pub fn set_keys(
|
||||
network: NetworkId,
|
||||
removed_participants: Vec<SeraiAddress>,
|
||||
removed_participants: sp_runtime::BoundedVec<
|
||||
SeraiAddress,
|
||||
sp_core::ConstU32<{ primitives::MAX_KEY_SHARES_PER_SET / 3 }>,
|
||||
>,
|
||||
key_pair: KeyPair,
|
||||
signature: Signature,
|
||||
) -> Transaction {
|
||||
|
||||
@@ -31,7 +31,7 @@ pub async fn provide_batch(serai: &Serai, batch: Batch) -> [u8; 32] {
|
||||
keys
|
||||
} else {
|
||||
let keys = KeyPair(pair.public(), vec![].try_into().unwrap());
|
||||
set_keys(serai, set, keys.clone()).await;
|
||||
set_keys(serai, set, keys.clone(), &[insecure_pair_from_name("Alice")]).await;
|
||||
keys
|
||||
};
|
||||
assert_eq!(keys.0, pair.public());
|
||||
|
||||
@@ -14,7 +14,6 @@ use frost::dkg::musig::musig;
|
||||
use schnorrkel::Schnorrkel;
|
||||
|
||||
use serai_client::{
|
||||
primitives::insecure_pair_from_name,
|
||||
validator_sets::{
|
||||
primitives::{ValidatorSet, KeyPair, musig_context, set_keys_message},
|
||||
ValidatorSetsEvent,
|
||||
@@ -25,33 +24,52 @@ use serai_client::{
|
||||
use crate::common::tx::publish_tx;
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub async fn set_keys(serai: &Serai, set: ValidatorSet, key_pair: KeyPair) -> [u8; 32] {
|
||||
let pair = insecure_pair_from_name("Alice");
|
||||
let public = pair.public();
|
||||
pub async fn set_keys(
|
||||
serai: &Serai,
|
||||
set: ValidatorSet,
|
||||
key_pair: KeyPair,
|
||||
pairs: &[Pair],
|
||||
) -> [u8; 32] {
|
||||
let mut pub_keys = vec![];
|
||||
for pair in pairs {
|
||||
let public_key =
|
||||
<Ristretto as Ciphersuite>::read_G::<&[u8]>(&mut pair.public().0.as_ref()).unwrap();
|
||||
pub_keys.push(public_key);
|
||||
}
|
||||
|
||||
let public_key = <Ristretto as Ciphersuite>::read_G::<&[u8]>(&mut public.0.as_ref()).unwrap();
|
||||
let secret_key = <Ristretto as Ciphersuite>::read_F::<&[u8]>(
|
||||
&mut pair.as_ref().secret.to_bytes()[.. 32].as_ref(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(Ristretto::generator() * secret_key, public_key);
|
||||
let threshold_keys =
|
||||
musig::<Ristretto>(&musig_context(set), &Zeroizing::new(secret_key), &[public_key]).unwrap();
|
||||
let mut threshold_keys = vec![];
|
||||
for i in 0 .. pairs.len() {
|
||||
let secret_key = <Ristretto as Ciphersuite>::read_F::<&[u8]>(
|
||||
&mut pairs[i].as_ref().secret.to_bytes()[.. 32].as_ref(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(Ristretto::generator() * secret_key, pub_keys[i]);
|
||||
|
||||
threshold_keys.push(
|
||||
musig::<Ristretto>(&musig_context(set), &Zeroizing::new(secret_key), &pub_keys).unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
let mut musig_keys = HashMap::new();
|
||||
for tk in threshold_keys {
|
||||
musig_keys.insert(tk.params().i(), tk.into());
|
||||
}
|
||||
|
||||
let sig = frost::tests::sign_without_caching(
|
||||
&mut OsRng,
|
||||
frost::tests::algorithm_machines(
|
||||
&mut OsRng,
|
||||
&Schnorrkel::new(b"substrate"),
|
||||
&HashMap::from([(threshold_keys.params().i(), threshold_keys.into())]),
|
||||
),
|
||||
frost::tests::algorithm_machines(&mut OsRng, &Schnorrkel::new(b"substrate"), &musig_keys),
|
||||
&set_keys_message(&set, &[], &key_pair),
|
||||
);
|
||||
|
||||
// Set the key pair
|
||||
let block = publish_tx(
|
||||
serai,
|
||||
&SeraiValidatorSets::set_keys(set.network, vec![], key_pair.clone(), Signature(sig.to_bytes())),
|
||||
&SeraiValidatorSets::set_keys(
|
||||
set.network,
|
||||
vec![].try_into().unwrap(),
|
||||
key_pair.clone(),
|
||||
Signature(sig.to_bytes()),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
|
||||
@@ -1,36 +1,71 @@
|
||||
use rand_core::{RngCore, OsRng};
|
||||
|
||||
use sp_core::{sr25519::Public, Pair};
|
||||
use sp_core::{
|
||||
sr25519::{Public, Pair},
|
||||
Pair as PairTrait,
|
||||
};
|
||||
|
||||
use serai_client::{
|
||||
primitives::{NETWORKS, NetworkId, insecure_pair_from_name},
|
||||
primitives::{NETWORKS, NetworkId, BlockHash, insecure_pair_from_name},
|
||||
validator_sets::{
|
||||
primitives::{Session, ValidatorSet, KeyPair},
|
||||
ValidatorSetsEvent,
|
||||
},
|
||||
in_instructions::{
|
||||
primitives::{Batch, SignedBatch, batch_message},
|
||||
SeraiInInstructions,
|
||||
},
|
||||
Amount, Serai,
|
||||
};
|
||||
|
||||
mod common;
|
||||
use common::validator_sets::{set_keys, allocate_stake, deallocate_stake};
|
||||
use common::{
|
||||
tx::publish_tx,
|
||||
validator_sets::{allocate_stake, deallocate_stake, set_keys},
|
||||
};
|
||||
|
||||
const EPOCH_INTERVAL: u64 = 300;
|
||||
fn get_random_key_pair() -> KeyPair {
|
||||
let mut ristretto_key = [0; 32];
|
||||
OsRng.fill_bytes(&mut ristretto_key);
|
||||
let mut external_key = vec![0; 33];
|
||||
OsRng.fill_bytes(&mut external_key);
|
||||
KeyPair(Public(ristretto_key), external_key.try_into().unwrap())
|
||||
}
|
||||
|
||||
async fn get_ordered_keys(serai: &Serai, network: NetworkId, accounts: &[Pair]) -> Vec<Pair> {
|
||||
// retrieve the current session validators so that we know the order of the keys
|
||||
// that is necessary for the correct musig signature.
|
||||
let validators = serai
|
||||
.as_of_latest_finalized_block()
|
||||
.await
|
||||
.unwrap()
|
||||
.validator_sets()
|
||||
.active_network_validators(network)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// collect the pairs of the validators
|
||||
let mut pairs = vec![];
|
||||
for v in validators {
|
||||
let p = accounts.iter().find(|pair| pair.public() == v).unwrap().clone();
|
||||
pairs.push(p);
|
||||
}
|
||||
|
||||
pairs
|
||||
}
|
||||
|
||||
serai_test!(
|
||||
set_keys_test: (|serai: Serai| async move {
|
||||
let network = NetworkId::Bitcoin;
|
||||
let set = ValidatorSet { session: Session(0), network };
|
||||
|
||||
let public = insecure_pair_from_name("Alice").public();
|
||||
let pair = insecure_pair_from_name("Alice");
|
||||
let public = pair.public();
|
||||
|
||||
// Neither of these keys are validated
|
||||
// The external key is infeasible to validate on-chain, the Ristretto key is feasible
|
||||
// TODO: Should the Ristretto key be validated?
|
||||
let mut ristretto_key = [0; 32];
|
||||
OsRng.fill_bytes(&mut ristretto_key);
|
||||
let mut external_key = vec![0; 33];
|
||||
OsRng.fill_bytes(&mut external_key);
|
||||
let key_pair = KeyPair(Public(ristretto_key), external_key.try_into().unwrap());
|
||||
let key_pair = get_random_key_pair();
|
||||
|
||||
// Make sure the genesis is as expected
|
||||
assert_eq!(
|
||||
@@ -62,7 +97,7 @@ serai_test!(
|
||||
assert_eq!(participants_ref, [public].as_ref());
|
||||
}
|
||||
|
||||
let block = set_keys(&serai, set, key_pair.clone()).await;
|
||||
let block = set_keys(&serai, set, key_pair.clone(), &[pair]).await;
|
||||
|
||||
// While the set_keys function should handle this, it's beneficial to
|
||||
// independently test it
|
||||
@@ -149,11 +184,13 @@ async fn validator_set_rotation() {
|
||||
);
|
||||
|
||||
// genesis accounts
|
||||
let pair1 = insecure_pair_from_name("Alice");
|
||||
let pair2 = insecure_pair_from_name("Bob");
|
||||
let pair3 = insecure_pair_from_name("Charlie");
|
||||
let pair4 = insecure_pair_from_name("Dave");
|
||||
let pair5 = insecure_pair_from_name("Eve");
|
||||
let accounts = vec![
|
||||
insecure_pair_from_name("Alice"),
|
||||
insecure_pair_from_name("Bob"),
|
||||
insecure_pair_from_name("Charlie"),
|
||||
insecure_pair_from_name("Dave"),
|
||||
insecure_pair_from_name("Eve"),
|
||||
];
|
||||
|
||||
// amounts for single key share per network
|
||||
let key_shares = HashMap::from([
|
||||
@@ -164,8 +201,9 @@ async fn validator_set_rotation() {
|
||||
]);
|
||||
|
||||
// genesis participants per network
|
||||
#[allow(clippy::redundant_closure_for_method_calls)]
|
||||
let default_participants =
|
||||
vec![pair1.public(), pair2.public(), pair3.public(), pair4.public()];
|
||||
accounts[.. 4].to_vec().iter().map(|pair| pair.public()).collect::<Vec<_>>();
|
||||
let mut participants = HashMap::from([
|
||||
(NetworkId::Serai, default_participants.clone()),
|
||||
(NetworkId::Bitcoin, default_participants.clone()),
|
||||
@@ -181,28 +219,83 @@ async fn validator_set_rotation() {
|
||||
participants.sort();
|
||||
verify_session_and_active_validators(&serai, network, 0, participants).await;
|
||||
|
||||
// add 1 participant & verify
|
||||
let hash =
|
||||
allocate_stake(&serai, network, key_shares[&network], &pair5, i.try_into().unwrap())
|
||||
.await;
|
||||
participants.push(pair5.public());
|
||||
participants.sort();
|
||||
verify_session_and_active_validators(
|
||||
// add 1 participant
|
||||
let last_participant = accounts[4].clone();
|
||||
let hash = allocate_stake(
|
||||
&serai,
|
||||
network,
|
||||
get_active_session(&serai, network, hash).await,
|
||||
participants,
|
||||
key_shares[&network],
|
||||
&last_participant,
|
||||
i.try_into().unwrap(),
|
||||
)
|
||||
.await;
|
||||
participants.push(last_participant.public());
|
||||
// the session at which set changes becomes active
|
||||
let activation_session = get_session_at_which_changes_activate(&serai, network, hash).await;
|
||||
|
||||
// remove 1 participant & verify
|
||||
let hash =
|
||||
deallocate_stake(&serai, network, key_shares[&network], &pair2, i.try_into().unwrap())
|
||||
.await;
|
||||
participants.swap_remove(participants.iter().position(|k| *k == pair2.public()).unwrap());
|
||||
let active_session = get_active_session(&serai, network, hash).await;
|
||||
// set the keys if it is an external set
|
||||
if network != NetworkId::Serai {
|
||||
let set = ValidatorSet { session: Session(0), network };
|
||||
let key_pair = get_random_key_pair();
|
||||
let pairs = get_ordered_keys(&serai, network, &accounts).await;
|
||||
set_keys(&serai, set, key_pair, &pairs).await;
|
||||
}
|
||||
|
||||
// verify
|
||||
participants.sort();
|
||||
verify_session_and_active_validators(&serai, network, active_session, participants).await;
|
||||
verify_session_and_active_validators(&serai, network, activation_session, participants)
|
||||
.await;
|
||||
|
||||
// remove 1 participant
|
||||
let participant_to_remove = accounts[1].clone();
|
||||
let hash = deallocate_stake(
|
||||
&serai,
|
||||
network,
|
||||
key_shares[&network],
|
||||
&participant_to_remove,
|
||||
i.try_into().unwrap(),
|
||||
)
|
||||
.await;
|
||||
participants.swap_remove(
|
||||
participants.iter().position(|k| *k == participant_to_remove.public()).unwrap(),
|
||||
);
|
||||
let activation_session = get_session_at_which_changes_activate(&serai, network, hash).await;
|
||||
|
||||
if network != NetworkId::Serai {
|
||||
// set the keys if it is an external set
|
||||
let set = ValidatorSet { session: Session(1), network };
|
||||
|
||||
// we need the whole substrate key pair to sign the batch
|
||||
let (substrate_pair, key_pair) = {
|
||||
let pair = insecure_pair_from_name("session-1-key-pair");
|
||||
let public = pair.public();
|
||||
|
||||
let mut external_key = vec![0; 33];
|
||||
OsRng.fill_bytes(&mut external_key);
|
||||
|
||||
(pair, KeyPair(public, external_key.try_into().unwrap()))
|
||||
};
|
||||
let pairs = get_ordered_keys(&serai, network, &accounts).await;
|
||||
set_keys(&serai, set, key_pair, &pairs).await;
|
||||
|
||||
// provide a batch to complete the handover and retire the previous set
|
||||
let mut block_hash = BlockHash([0; 32]);
|
||||
OsRng.fill_bytes(&mut block_hash.0);
|
||||
let batch = Batch { network, id: 0, block: block_hash, instructions: vec![] };
|
||||
publish_tx(
|
||||
&serai,
|
||||
&SeraiInInstructions::execute_batch(SignedBatch {
|
||||
batch: batch.clone(),
|
||||
signature: substrate_pair.sign(&batch_message(&batch)),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// verify
|
||||
participants.sort();
|
||||
verify_session_and_active_validators(&serai, network, activation_session, participants)
|
||||
.await;
|
||||
|
||||
// check pending deallocations
|
||||
let pending = serai
|
||||
@@ -212,8 +305,8 @@ async fn validator_set_rotation() {
|
||||
.validator_sets()
|
||||
.pending_deallocations(
|
||||
network,
|
||||
pair2.public(),
|
||||
Session(u32::try_from(active_session + 1).unwrap()),
|
||||
participant_to_remove.public(),
|
||||
Session(activation_session + 1),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -223,24 +316,39 @@ async fn validator_set_rotation() {
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn session_for_block(serai: &Serai, block: [u8; 32], network: NetworkId) -> u32 {
|
||||
serai.as_of(block).validator_sets().session(network).await.unwrap().unwrap().0
|
||||
}
|
||||
|
||||
async fn verify_session_and_active_validators(
|
||||
serai: &Serai,
|
||||
network: NetworkId,
|
||||
session: u64,
|
||||
session: u32,
|
||||
participants: &[Public],
|
||||
) {
|
||||
// wait untill the epoch block finalized
|
||||
let epoch_block = (session * EPOCH_INTERVAL) + 1;
|
||||
while serai.finalized_block_by_number(epoch_block).await.unwrap().is_none() {
|
||||
// sleep 1 block
|
||||
tokio::time::sleep(tokio::time::Duration::from_secs(6)).await;
|
||||
}
|
||||
let serai_for_block =
|
||||
serai.as_of(serai.finalized_block_by_number(epoch_block).await.unwrap().unwrap().hash());
|
||||
// wait until the active session. This wait should be max 30 secs since the epoch time.
|
||||
let block = tokio::time::timeout(core::time::Duration::from_secs(2 * 60), async move {
|
||||
loop {
|
||||
let mut block = serai.latest_finalized_block_hash().await.unwrap();
|
||||
if session_for_block(serai, block, network).await < session {
|
||||
// Sleep a block
|
||||
tokio::time::sleep(core::time::Duration::from_secs(6)).await;
|
||||
continue;
|
||||
}
|
||||
while session_for_block(serai, block, network).await > session {
|
||||
block = serai.block(block).await.unwrap().unwrap().header.parent_hash.0;
|
||||
}
|
||||
assert_eq!(session_for_block(serai, block, network).await, session);
|
||||
break block;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let serai_for_block = serai.as_of(block);
|
||||
|
||||
// verify session
|
||||
let s = serai_for_block.validator_sets().session(network).await.unwrap().unwrap();
|
||||
assert_eq!(u64::from(s.0), session);
|
||||
assert_eq!(s.0, session);
|
||||
|
||||
// verify participants
|
||||
let mut validators =
|
||||
@@ -249,10 +357,11 @@ async fn verify_session_and_active_validators(
|
||||
assert_eq!(validators, participants);
|
||||
|
||||
// make sure finalization continues as usual after the changes
|
||||
tokio::time::timeout(tokio::time::Duration::from_secs(60), async move {
|
||||
let current_finalized_block = serai.latest_finalized_block().await.unwrap().header.number;
|
||||
tokio::time::timeout(core::time::Duration::from_secs(60), async move {
|
||||
let mut finalized_block = serai.latest_finalized_block().await.unwrap().header.number;
|
||||
while finalized_block <= epoch_block + 2 {
|
||||
tokio::time::sleep(tokio::time::Duration::from_secs(6)).await;
|
||||
while finalized_block <= current_finalized_block + 2 {
|
||||
tokio::time::sleep(core::time::Duration::from_secs(6)).await;
|
||||
finalized_block = serai.latest_finalized_block().await.unwrap().header.number;
|
||||
}
|
||||
})
|
||||
@@ -262,15 +371,18 @@ async fn verify_session_and_active_validators(
|
||||
// TODO: verify key shares as well?
|
||||
}
|
||||
|
||||
async fn get_active_session(serai: &Serai, network: NetworkId, hash: [u8; 32]) -> u64 {
|
||||
let block_number = serai.block(hash).await.unwrap().unwrap().header.number;
|
||||
let epoch = block_number / EPOCH_INTERVAL;
|
||||
async fn get_session_at_which_changes_activate(
|
||||
serai: &Serai,
|
||||
network: NetworkId,
|
||||
hash: [u8; 32],
|
||||
) -> u32 {
|
||||
let session = session_for_block(serai, hash, network).await;
|
||||
|
||||
// changes should be active in the next session
|
||||
if network == NetworkId::Serai {
|
||||
// it takes 1 extra session for serai net to make the changes active.
|
||||
epoch + 2
|
||||
session + 2
|
||||
} else {
|
||||
epoch + 1
|
||||
session + 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,6 +49,9 @@ std = [
|
||||
"coins-primitives/std",
|
||||
]
|
||||
|
||||
# TODO
|
||||
try-runtime = []
|
||||
|
||||
runtime-benchmarks = [
|
||||
"frame-system/runtime-benchmarks",
|
||||
"frame-support/runtime-benchmarks",
|
||||
|
||||
@@ -62,3 +62,6 @@ std = [
|
||||
"genesis-liquidity-pallet/std",
|
||||
]
|
||||
default = ["std"]
|
||||
|
||||
# TODO
|
||||
try-runtime = []
|
||||
|
||||
@@ -20,10 +20,11 @@ workspace = true
|
||||
name = "serai-node"
|
||||
|
||||
[dependencies]
|
||||
rand_core = "0.6"
|
||||
zeroize = "1"
|
||||
hex = "0.4"
|
||||
log = "0.4"
|
||||
|
||||
rand_core = "0.6"
|
||||
schnorrkel = "0.11"
|
||||
|
||||
libp2p = "0.52"
|
||||
|
||||
@@ -19,9 +19,12 @@ fn account_from_name(name: &'static str) -> PublicKey {
|
||||
|
||||
fn wasm_binary() -> Vec<u8> {
|
||||
// TODO: Accept a config of runtime path
|
||||
if let Ok(binary) = std::fs::read("/runtime/serai.wasm") {
|
||||
const WASM_PATH: &str = "/runtime/serai.wasm";
|
||||
if let Ok(binary) = std::fs::read(WASM_PATH) {
|
||||
log::info!("using {WASM_PATH}");
|
||||
return binary;
|
||||
}
|
||||
log::info!("using built-in wasm");
|
||||
WASM_BINARY.ok_or("compiled in wasm not available").unwrap().to_vec()
|
||||
}
|
||||
|
||||
|
||||
@@ -37,9 +37,6 @@ pub use balance::*;
|
||||
mod account;
|
||||
pub use account::*;
|
||||
|
||||
mod tx;
|
||||
pub use tx::*;
|
||||
|
||||
pub type BlockNumber = u64;
|
||||
pub type Header = sp_runtime::generic::Header<BlockNumber, sp_runtime::traits::BlakeTwo256>;
|
||||
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
use scale::Encode;
|
||||
|
||||
use sp_core::sr25519::{Public, Signature};
|
||||
use sp_runtime::traits::Verify;
|
||||
|
||||
use crate::SeraiAddress;
|
||||
|
||||
trait TransactionMember:
|
||||
Clone + PartialEq + Eq + core::fmt::Debug + scale::Encode + scale::Decode + scale_info::TypeInfo
|
||||
{
|
||||
}
|
||||
impl<
|
||||
T: Clone
|
||||
+ PartialEq
|
||||
+ Eq
|
||||
+ core::fmt::Debug
|
||||
+ scale::Encode
|
||||
+ scale::Decode
|
||||
+ scale_info::TypeInfo,
|
||||
> TransactionMember for T
|
||||
{
|
||||
}
|
||||
|
||||
// We use our own Transaction struct, over UncheckedExtrinsic, for more control, a bit more
|
||||
// simplicity, and in order to be immune to https://github.com/paritytech/polkadot-sdk/issues/2947
|
||||
#[allow(private_bounds)]
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
pub struct Transaction<Call: TransactionMember, Extra: TransactionMember> {
|
||||
pub call: Call,
|
||||
pub signature: Option<(SeraiAddress, Signature, Extra)>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
mod _serde {
|
||||
use scale::Encode;
|
||||
use serde::{ser::*, de::*};
|
||||
use super::*;
|
||||
impl<Call: TransactionMember, Extra: TransactionMember> Serialize for Transaction<Call, Extra> {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let encoded = self.encode();
|
||||
serializer.serialize_bytes(&encoded)
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "std")]
|
||||
impl<'a, Call: TransactionMember, Extra: TransactionMember> Deserialize<'a>
|
||||
for Transaction<Call, Extra>
|
||||
{
|
||||
fn deserialize<D: Deserializer<'a>>(de: D) -> Result<Self, D::Error> {
|
||||
let bytes = sp_core::bytes::deserialize(de)?;
|
||||
scale::Decode::decode(&mut &bytes[..])
|
||||
.map_err(|e| serde::de::Error::custom(format!("invalid transaction: {e}")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Call: TransactionMember, Extra: TransactionMember> sp_runtime::traits::Extrinsic
|
||||
for Transaction<Call, Extra>
|
||||
{
|
||||
type Call = Call;
|
||||
type SignaturePayload = (SeraiAddress, Signature, Extra);
|
||||
fn is_signed(&self) -> Option<bool> {
|
||||
Some(self.signature.is_some())
|
||||
}
|
||||
fn new(call: Call, signature: Option<Self::SignaturePayload>) -> Option<Self> {
|
||||
Some(Self { call, signature })
|
||||
}
|
||||
}
|
||||
|
||||
impl<Call: TransactionMember, Extra: TransactionMember> frame_support::traits::ExtrinsicCall
|
||||
for Transaction<Call, Extra>
|
||||
{
|
||||
fn call(&self) -> &Call {
|
||||
&self.call
|
||||
}
|
||||
}
|
||||
|
||||
impl<Call: TransactionMember, Extra: TransactionMember> sp_runtime::traits::ExtrinsicMetadata
|
||||
for Transaction<Call, Extra>
|
||||
where
|
||||
Extra: sp_runtime::traits::SignedExtension,
|
||||
{
|
||||
type SignedExtensions = Extra;
|
||||
|
||||
const VERSION: u8 = 0;
|
||||
}
|
||||
|
||||
impl<Call: TransactionMember, Extra: TransactionMember> frame_support::dispatch::GetDispatchInfo
|
||||
for Transaction<Call, Extra>
|
||||
where
|
||||
Call: frame_support::dispatch::GetDispatchInfo,
|
||||
{
|
||||
fn get_dispatch_info(&self) -> frame_support::dispatch::DispatchInfo {
|
||||
self.call.get_dispatch_info()
|
||||
}
|
||||
}
|
||||
|
||||
impl<Call: TransactionMember, Extra: TransactionMember> sp_runtime::traits::BlindCheckable
|
||||
for Transaction<Call, Extra>
|
||||
where
|
||||
Extra: sp_runtime::traits::SignedExtension,
|
||||
{
|
||||
type Checked = sp_runtime::generic::CheckedExtrinsic<Public, Call, Extra>;
|
||||
|
||||
fn check(
|
||||
self,
|
||||
) -> Result<Self::Checked, sp_runtime::transaction_validity::TransactionValidityError> {
|
||||
Ok(match self.signature {
|
||||
Some((signer, signature, extra)) => {
|
||||
if !signature.verify(
|
||||
(&self.call, &extra, extra.additional_signed()?).encode().as_slice(),
|
||||
&signer.into(),
|
||||
) {
|
||||
Err(sp_runtime::transaction_validity::InvalidTransaction::BadProof)?
|
||||
}
|
||||
|
||||
sp_runtime::generic::CheckedExtrinsic {
|
||||
signed: Some((signer.into(), extra)),
|
||||
function: self.call,
|
||||
}
|
||||
}
|
||||
None => sp_runtime::generic::CheckedExtrinsic { signed: None, function: self.call },
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,7 @@ frame-executive = { git = "https://github.com/serai-dex/substrate", default-feat
|
||||
frame-benchmarking = { git = "https://github.com/serai-dex/substrate", default-features = false, optional = true }
|
||||
|
||||
serai-primitives = { path = "../primitives", default-features = false }
|
||||
serai-abi = { path = "../abi", default-features = false, features = ["serde"] }
|
||||
|
||||
pallet-timestamp = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
pallet-authorship = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
@@ -103,6 +104,8 @@ std = [
|
||||
"frame-executive/std",
|
||||
|
||||
"serai-primitives/std",
|
||||
"serai-abi/std",
|
||||
"serai-abi/serde",
|
||||
|
||||
"pallet-timestamp/std",
|
||||
"pallet-authorship/std",
|
||||
|
||||
363
substrate/runtime/src/abi.rs
Normal file
363
substrate/runtime/src/abi.rs
Normal file
@@ -0,0 +1,363 @@
|
||||
use core::marker::PhantomData;
|
||||
|
||||
use scale::{Encode, Decode};
|
||||
|
||||
use serai_abi::Call;
|
||||
|
||||
use crate::{
|
||||
Vec,
|
||||
primitives::{PublicKey, SeraiAddress},
|
||||
timestamp, coins, dex,
|
||||
validator_sets::{self, MembershipProof},
|
||||
in_instructions, signals, babe, grandpa, RuntimeCall,
|
||||
};
|
||||
|
||||
impl From<Call> for RuntimeCall {
|
||||
fn from(call: Call) -> RuntimeCall {
|
||||
match call {
|
||||
Call::Timestamp(serai_abi::timestamp::Call::set { now }) => {
|
||||
RuntimeCall::Timestamp(timestamp::Call::set { now })
|
||||
}
|
||||
Call::Coins(coins) => match coins {
|
||||
serai_abi::coins::Call::transfer { to, balance } => {
|
||||
RuntimeCall::Coins(coins::Call::transfer { to: to.into(), balance })
|
||||
}
|
||||
serai_abi::coins::Call::burn { balance } => {
|
||||
RuntimeCall::Coins(coins::Call::burn { balance })
|
||||
}
|
||||
serai_abi::coins::Call::burn_with_instruction { instruction } => {
|
||||
RuntimeCall::Coins(coins::Call::burn_with_instruction { instruction })
|
||||
}
|
||||
},
|
||||
Call::LiquidityTokens(lt) => match lt {
|
||||
serai_abi::coins::LiquidityTokensCall::transfer { to, balance } => {
|
||||
RuntimeCall::LiquidityTokens(coins::Call::transfer { to: to.into(), balance })
|
||||
}
|
||||
serai_abi::coins::LiquidityTokensCall::burn { balance } => {
|
||||
RuntimeCall::LiquidityTokens(coins::Call::burn { balance })
|
||||
}
|
||||
},
|
||||
Call::Dex(dex) => match dex {
|
||||
serai_abi::dex::Call::add_liquidity {
|
||||
coin,
|
||||
coin_desired,
|
||||
sri_desired,
|
||||
coin_min,
|
||||
sri_min,
|
||||
mint_to,
|
||||
} => RuntimeCall::Dex(dex::Call::add_liquidity {
|
||||
coin,
|
||||
coin_desired,
|
||||
sri_desired,
|
||||
coin_min,
|
||||
sri_min,
|
||||
mint_to: mint_to.into(),
|
||||
}),
|
||||
serai_abi::dex::Call::remove_liquidity {
|
||||
coin,
|
||||
lp_token_burn,
|
||||
coin_min_receive,
|
||||
sri_min_receive,
|
||||
withdraw_to,
|
||||
} => RuntimeCall::Dex(dex::Call::remove_liquidity {
|
||||
coin,
|
||||
lp_token_burn,
|
||||
coin_min_receive,
|
||||
sri_min_receive,
|
||||
withdraw_to: withdraw_to.into(),
|
||||
}),
|
||||
serai_abi::dex::Call::swap_exact_tokens_for_tokens {
|
||||
path,
|
||||
amount_in,
|
||||
amount_out_min,
|
||||
send_to,
|
||||
} => RuntimeCall::Dex(dex::Call::swap_exact_tokens_for_tokens {
|
||||
path,
|
||||
amount_in,
|
||||
amount_out_min,
|
||||
send_to: send_to.into(),
|
||||
}),
|
||||
serai_abi::dex::Call::swap_tokens_for_exact_tokens {
|
||||
path,
|
||||
amount_out,
|
||||
amount_in_max,
|
||||
send_to,
|
||||
} => RuntimeCall::Dex(dex::Call::swap_tokens_for_exact_tokens {
|
||||
path,
|
||||
amount_out,
|
||||
amount_in_max,
|
||||
send_to: send_to.into(),
|
||||
}),
|
||||
},
|
||||
Call::ValidatorSets(vs) => match vs {
|
||||
serai_abi::validator_sets::Call::set_keys {
|
||||
network,
|
||||
removed_participants,
|
||||
key_pair,
|
||||
signature,
|
||||
} => RuntimeCall::ValidatorSets(validator_sets::Call::set_keys {
|
||||
network,
|
||||
removed_participants: <_>::try_from(
|
||||
removed_participants.into_iter().map(PublicKey::from).collect::<Vec<_>>(),
|
||||
)
|
||||
.unwrap(),
|
||||
key_pair,
|
||||
signature,
|
||||
}),
|
||||
serai_abi::validator_sets::Call::report_slashes { network, slashes, signature } => {
|
||||
RuntimeCall::ValidatorSets(validator_sets::Call::report_slashes {
|
||||
network,
|
||||
slashes: <_>::try_from(
|
||||
slashes
|
||||
.into_iter()
|
||||
.map(|(addr, slash)| (PublicKey::from(addr), slash))
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.unwrap(),
|
||||
signature,
|
||||
})
|
||||
}
|
||||
serai_abi::validator_sets::Call::allocate { network, amount } => {
|
||||
RuntimeCall::ValidatorSets(validator_sets::Call::allocate { network, amount })
|
||||
}
|
||||
serai_abi::validator_sets::Call::deallocate { network, amount } => {
|
||||
RuntimeCall::ValidatorSets(validator_sets::Call::deallocate { network, amount })
|
||||
}
|
||||
serai_abi::validator_sets::Call::claim_deallocation { network, session } => {
|
||||
RuntimeCall::ValidatorSets(validator_sets::Call::claim_deallocation { network, session })
|
||||
}
|
||||
},
|
||||
Call::InInstructions(ii) => match ii {
|
||||
serai_abi::in_instructions::Call::execute_batch { batch } => {
|
||||
RuntimeCall::InInstructions(in_instructions::Call::execute_batch { batch })
|
||||
}
|
||||
},
|
||||
Call::Signals(signals) => match signals {
|
||||
serai_abi::signals::Call::register_retirement_signal { in_favor_of } => {
|
||||
RuntimeCall::Signals(signals::Call::register_retirement_signal { in_favor_of })
|
||||
}
|
||||
serai_abi::signals::Call::revoke_retirement_signal { retirement_signal_id } => {
|
||||
RuntimeCall::Signals(signals::Call::revoke_retirement_signal { retirement_signal_id })
|
||||
}
|
||||
serai_abi::signals::Call::favor { signal_id, for_network } => {
|
||||
RuntimeCall::Signals(signals::Call::favor { signal_id, for_network })
|
||||
}
|
||||
serai_abi::signals::Call::revoke_favor { signal_id, for_network } => {
|
||||
RuntimeCall::Signals(signals::Call::revoke_favor { signal_id, for_network })
|
||||
}
|
||||
serai_abi::signals::Call::stand_against { signal_id, for_network } => {
|
||||
RuntimeCall::Signals(signals::Call::stand_against { signal_id, for_network })
|
||||
}
|
||||
},
|
||||
Call::Babe(babe) => match babe {
|
||||
serai_abi::babe::Call::report_equivocation(report) => {
|
||||
RuntimeCall::Babe(babe::Call::report_equivocation {
|
||||
// TODO: Find a better way to go from Proof<[u8; 32]> to Proof<H256>
|
||||
equivocation_proof: <_>::decode(&mut report.equivocation_proof.encode().as_slice())
|
||||
.unwrap(),
|
||||
key_owner_proof: MembershipProof(report.key_owner_proof.into(), PhantomData),
|
||||
})
|
||||
}
|
||||
serai_abi::babe::Call::report_equivocation_unsigned(report) => {
|
||||
RuntimeCall::Babe(babe::Call::report_equivocation_unsigned {
|
||||
// TODO: Find a better way to go from Proof<[u8; 32]> to Proof<H256>
|
||||
equivocation_proof: <_>::decode(&mut report.equivocation_proof.encode().as_slice())
|
||||
.unwrap(),
|
||||
key_owner_proof: MembershipProof(report.key_owner_proof.into(), PhantomData),
|
||||
})
|
||||
}
|
||||
},
|
||||
Call::Grandpa(grandpa) => match grandpa {
|
||||
serai_abi::grandpa::Call::report_equivocation(report) => {
|
||||
RuntimeCall::Grandpa(grandpa::Call::report_equivocation {
|
||||
// TODO: Find a better way to go from Proof<[u8; 32]> to Proof<H256>
|
||||
equivocation_proof: <_>::decode(&mut report.equivocation_proof.encode().as_slice())
|
||||
.unwrap(),
|
||||
key_owner_proof: MembershipProof(report.key_owner_proof.into(), PhantomData),
|
||||
})
|
||||
}
|
||||
serai_abi::grandpa::Call::report_equivocation_unsigned(report) => {
|
||||
RuntimeCall::Grandpa(grandpa::Call::report_equivocation_unsigned {
|
||||
// TODO: Find a better way to go from Proof<[u8; 32]> to Proof<H256>
|
||||
equivocation_proof: <_>::decode(&mut report.equivocation_proof.encode().as_slice())
|
||||
.unwrap(),
|
||||
key_owner_proof: MembershipProof(report.key_owner_proof.into(), PhantomData),
|
||||
})
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryInto<Call> for RuntimeCall {
|
||||
type Error = ();
|
||||
|
||||
fn try_into(self) -> Result<Call, ()> {
|
||||
Ok(match self {
|
||||
RuntimeCall::Timestamp(timestamp::Call::set { now }) => {
|
||||
Call::Timestamp(serai_abi::timestamp::Call::set { now })
|
||||
}
|
||||
RuntimeCall::Coins(call) => Call::Coins(match call {
|
||||
coins::Call::transfer { to, balance } => {
|
||||
serai_abi::coins::Call::transfer { to: to.into(), balance }
|
||||
}
|
||||
coins::Call::burn { balance } => serai_abi::coins::Call::burn { balance },
|
||||
coins::Call::burn_with_instruction { instruction } => {
|
||||
serai_abi::coins::Call::burn_with_instruction { instruction }
|
||||
}
|
||||
_ => Err(())?,
|
||||
}),
|
||||
RuntimeCall::LiquidityTokens(call) => Call::LiquidityTokens(match call {
|
||||
coins::Call::transfer { to, balance } => {
|
||||
serai_abi::coins::LiquidityTokensCall::transfer { to: to.into(), balance }
|
||||
}
|
||||
coins::Call::burn { balance } => serai_abi::coins::LiquidityTokensCall::burn { balance },
|
||||
_ => Err(())?,
|
||||
}),
|
||||
RuntimeCall::Dex(call) => Call::Dex(match call {
|
||||
dex::Call::add_liquidity {
|
||||
coin,
|
||||
coin_desired,
|
||||
sri_desired,
|
||||
coin_min,
|
||||
sri_min,
|
||||
mint_to,
|
||||
} => serai_abi::dex::Call::add_liquidity {
|
||||
coin,
|
||||
coin_desired,
|
||||
sri_desired,
|
||||
coin_min,
|
||||
sri_min,
|
||||
mint_to: mint_to.into(),
|
||||
},
|
||||
dex::Call::remove_liquidity {
|
||||
coin,
|
||||
lp_token_burn,
|
||||
coin_min_receive,
|
||||
sri_min_receive,
|
||||
withdraw_to,
|
||||
} => serai_abi::dex::Call::remove_liquidity {
|
||||
coin,
|
||||
lp_token_burn,
|
||||
coin_min_receive,
|
||||
sri_min_receive,
|
||||
withdraw_to: withdraw_to.into(),
|
||||
},
|
||||
dex::Call::swap_exact_tokens_for_tokens { path, amount_in, amount_out_min, send_to } => {
|
||||
serai_abi::dex::Call::swap_exact_tokens_for_tokens {
|
||||
path,
|
||||
amount_in,
|
||||
amount_out_min,
|
||||
send_to: send_to.into(),
|
||||
}
|
||||
}
|
||||
dex::Call::swap_tokens_for_exact_tokens { path, amount_out, amount_in_max, send_to } => {
|
||||
serai_abi::dex::Call::swap_tokens_for_exact_tokens {
|
||||
path,
|
||||
amount_out,
|
||||
amount_in_max,
|
||||
send_to: send_to.into(),
|
||||
}
|
||||
}
|
||||
_ => Err(())?,
|
||||
}),
|
||||
RuntimeCall::ValidatorSets(call) => Call::ValidatorSets(match call {
|
||||
validator_sets::Call::set_keys { network, removed_participants, key_pair, signature } => {
|
||||
serai_abi::validator_sets::Call::set_keys {
|
||||
network,
|
||||
removed_participants: <_>::try_from(
|
||||
removed_participants.into_iter().map(SeraiAddress::from).collect::<Vec<_>>(),
|
||||
)
|
||||
.unwrap(),
|
||||
key_pair,
|
||||
signature,
|
||||
}
|
||||
}
|
||||
validator_sets::Call::report_slashes { network, slashes, signature } => {
|
||||
serai_abi::validator_sets::Call::report_slashes {
|
||||
network,
|
||||
slashes: <_>::try_from(
|
||||
slashes
|
||||
.into_iter()
|
||||
.map(|(addr, slash)| (SeraiAddress::from(addr), slash))
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.unwrap(),
|
||||
signature,
|
||||
}
|
||||
}
|
||||
validator_sets::Call::allocate { network, amount } => {
|
||||
serai_abi::validator_sets::Call::allocate { network, amount }
|
||||
}
|
||||
validator_sets::Call::deallocate { network, amount } => {
|
||||
serai_abi::validator_sets::Call::deallocate { network, amount }
|
||||
}
|
||||
validator_sets::Call::claim_deallocation { network, session } => {
|
||||
serai_abi::validator_sets::Call::claim_deallocation { network, session }
|
||||
}
|
||||
_ => Err(())?,
|
||||
}),
|
||||
RuntimeCall::InInstructions(call) => Call::InInstructions(match call {
|
||||
in_instructions::Call::execute_batch { batch } => {
|
||||
serai_abi::in_instructions::Call::execute_batch { batch }
|
||||
}
|
||||
_ => Err(())?,
|
||||
}),
|
||||
RuntimeCall::Signals(call) => Call::Signals(match call {
|
||||
signals::Call::register_retirement_signal { in_favor_of } => {
|
||||
serai_abi::signals::Call::register_retirement_signal { in_favor_of }
|
||||
}
|
||||
signals::Call::revoke_retirement_signal { retirement_signal_id } => {
|
||||
serai_abi::signals::Call::revoke_retirement_signal { retirement_signal_id }
|
||||
}
|
||||
signals::Call::favor { signal_id, for_network } => {
|
||||
serai_abi::signals::Call::favor { signal_id, for_network }
|
||||
}
|
||||
signals::Call::revoke_favor { signal_id, for_network } => {
|
||||
serai_abi::signals::Call::revoke_favor { signal_id, for_network }
|
||||
}
|
||||
signals::Call::stand_against { signal_id, for_network } => {
|
||||
serai_abi::signals::Call::stand_against { signal_id, for_network }
|
||||
}
|
||||
_ => Err(())?,
|
||||
}),
|
||||
RuntimeCall::Babe(call) => Call::Babe(match call {
|
||||
babe::Call::report_equivocation { equivocation_proof, key_owner_proof } => {
|
||||
serai_abi::babe::Call::report_equivocation(serai_abi::babe::ReportEquivocation {
|
||||
// TODO: Find a better way to go from Proof<H256> to Proof<[u8; 32]>
|
||||
equivocation_proof: <_>::decode(&mut equivocation_proof.encode().as_slice()).unwrap(),
|
||||
key_owner_proof: key_owner_proof.0.into(),
|
||||
})
|
||||
}
|
||||
babe::Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } => {
|
||||
serai_abi::babe::Call::report_equivocation_unsigned(serai_abi::babe::ReportEquivocation {
|
||||
// TODO: Find a better way to go from Proof<H256> to Proof<[u8; 32]>
|
||||
equivocation_proof: <_>::decode(&mut equivocation_proof.encode().as_slice()).unwrap(),
|
||||
key_owner_proof: key_owner_proof.0.into(),
|
||||
})
|
||||
}
|
||||
_ => Err(())?,
|
||||
}),
|
||||
RuntimeCall::Grandpa(call) => Call::Grandpa(match call {
|
||||
grandpa::Call::report_equivocation { equivocation_proof, key_owner_proof } => {
|
||||
serai_abi::grandpa::Call::report_equivocation(serai_abi::grandpa::ReportEquivocation {
|
||||
// TODO: Find a better way to go from Proof<H256> to Proof<[u8; 32]>
|
||||
equivocation_proof: <_>::decode(&mut equivocation_proof.encode().as_slice()).unwrap(),
|
||||
key_owner_proof: key_owner_proof.0.into(),
|
||||
})
|
||||
}
|
||||
grandpa::Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } => {
|
||||
serai_abi::grandpa::Call::report_equivocation_unsigned(
|
||||
serai_abi::grandpa::ReportEquivocation {
|
||||
// TODO: Find a better way to go from Proof<H256> to Proof<[u8; 32]>
|
||||
equivocation_proof: <_>::decode(&mut equivocation_proof.encode().as_slice()).unwrap(),
|
||||
key_owner_proof: key_owner_proof.0.into(),
|
||||
},
|
||||
)
|
||||
}
|
||||
_ => Err(())?,
|
||||
}),
|
||||
_ => Err(())?,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,8 @@ use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId;
|
||||
use babe::AuthorityId as BabeId;
|
||||
use grandpa::AuthorityId as GrandpaId;
|
||||
|
||||
mod abi;
|
||||
|
||||
/// Nonce of a transaction in the chain, for a given account.
|
||||
pub type Nonce = u32;
|
||||
|
||||
@@ -82,7 +84,7 @@ pub type SignedExtra = (
|
||||
transaction_payment::ChargeTransactionPayment<Runtime>,
|
||||
);
|
||||
|
||||
pub type Transaction = serai_primitives::Transaction<RuntimeCall, SignedExtra>;
|
||||
pub type Transaction = serai_abi::tx::Transaction<RuntimeCall, SignedExtra>;
|
||||
pub type Block = generic::Block<Header, Transaction>;
|
||||
pub type BlockId = generic::BlockId<Block>;
|
||||
|
||||
@@ -162,38 +164,9 @@ parameter_types! {
|
||||
pub struct CallFilter;
|
||||
impl Contains<RuntimeCall> for CallFilter {
|
||||
fn contains(call: &RuntimeCall) -> bool {
|
||||
match call {
|
||||
RuntimeCall::Timestamp(call) => match call {
|
||||
timestamp::Call::set { .. } => true,
|
||||
timestamp::Call::__Ignore(_, _) => false,
|
||||
},
|
||||
|
||||
// All of these pallets are our own, and all of their written calls are intended to be called
|
||||
RuntimeCall::Coins(call) => !matches!(call, coins::Call::__Ignore(_, _)),
|
||||
RuntimeCall::LiquidityTokens(call) => match call {
|
||||
coins::Call::transfer { .. } | coins::Call::burn { .. } => true,
|
||||
coins::Call::burn_with_instruction { .. } | coins::Call::__Ignore(_, _) => false,
|
||||
},
|
||||
RuntimeCall::Dex(call) => !matches!(call, dex::Call::__Ignore(_, _)),
|
||||
RuntimeCall::ValidatorSets(call) => !matches!(call, validator_sets::Call::__Ignore(_, _)),
|
||||
RuntimeCall::GenesisLiquidity(call) => {
|
||||
!matches!(call, genesis_liquidity::Call::__Ignore(_, _))
|
||||
}
|
||||
RuntimeCall::InInstructions(call) => !matches!(call, in_instructions::Call::__Ignore(_, _)),
|
||||
RuntimeCall::Signals(call) => !matches!(call, signals::Call::__Ignore(_, _)),
|
||||
|
||||
RuntimeCall::Babe(call) => match call {
|
||||
babe::Call::report_equivocation { .. } |
|
||||
babe::Call::report_equivocation_unsigned { .. } => true,
|
||||
babe::Call::plan_config_change { .. } | babe::Call::__Ignore(_, _) => false,
|
||||
},
|
||||
|
||||
RuntimeCall::Grandpa(call) => match call {
|
||||
grandpa::Call::report_equivocation { .. } |
|
||||
grandpa::Call::report_equivocation_unsigned { .. } => true,
|
||||
grandpa::Call::note_stalled { .. } | grandpa::Call::__Ignore(_, _) => false,
|
||||
},
|
||||
}
|
||||
// If the call is defined in our ABI, it's allowed
|
||||
let call: Result<serai_abi::Call, ()> = call.clone().try_into();
|
||||
call.is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -57,4 +57,7 @@ runtime-benchmarks = [
|
||||
"frame-support/runtime-benchmarks",
|
||||
]
|
||||
|
||||
# TODO
|
||||
try-runtime = []
|
||||
|
||||
default = ["std"]
|
||||
|
||||
@@ -70,6 +70,9 @@ std = [
|
||||
"dex-pallet/std",
|
||||
]
|
||||
|
||||
# TODO
|
||||
try-runtime = []
|
||||
|
||||
runtime-benchmarks = [
|
||||
"frame-system/runtime-benchmarks",
|
||||
"frame-support/runtime-benchmarks",
|
||||
|
||||
@@ -124,7 +124,9 @@ pub mod pallet {
|
||||
#[pallet::getter(fn allocation_per_key_share)]
|
||||
pub type AllocationPerKeyShare<T: Config> =
|
||||
StorageMap<_, Identity, NetworkId, Amount, OptionQuery>;
|
||||
/// The validators selected to be in-set.
|
||||
/// The validators selected to be in-set (and their key shares), regardless of if removed.
|
||||
///
|
||||
/// This method allows iterating over all validators and their stake.
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn participants_for_latest_decided_set)]
|
||||
pub(crate) type Participants<T: Config> = StorageMap<
|
||||
@@ -134,8 +136,10 @@ pub mod pallet {
|
||||
BoundedVec<(Public, u64), ConstU32<{ MAX_KEY_SHARES_PER_SET }>>,
|
||||
OptionQuery,
|
||||
>;
|
||||
/// The validators selected to be in-set, regardless of if removed, with the ability to perform a
|
||||
/// check for presence.
|
||||
/// The validators selected to be in-set, regardless of if removed.
|
||||
///
|
||||
/// This method allows quickly checking for presence in-set and looking up a validator's key
|
||||
/// shares.
|
||||
// Uses Identity for NetworkId to avoid a hash of a severely limited fixed key-space.
|
||||
#[pallet::storage]
|
||||
pub(crate) type InSet<T: Config> =
|
||||
@@ -364,7 +368,6 @@ pub mod pallet {
|
||||
let allocation_per_key_share = Self::allocation_per_key_share(network).unwrap().0;
|
||||
|
||||
let mut participants = vec![];
|
||||
let mut total_stake = 0;
|
||||
{
|
||||
let mut iter = SortedAllocationsIter::<T>::new(network);
|
||||
let mut key_shares = 0;
|
||||
@@ -376,7 +379,6 @@ pub mod pallet {
|
||||
participants.push((key, these_key_shares));
|
||||
|
||||
key_shares += these_key_shares;
|
||||
total_stake += amount.0;
|
||||
}
|
||||
amortize_excess_key_shares(&mut participants);
|
||||
}
|
||||
@@ -384,7 +386,6 @@ pub mod pallet {
|
||||
for (key, shares) in &participants {
|
||||
InSet::<T>::set(network, key, Some(*shares));
|
||||
}
|
||||
TotalAllocatedStake::<T>::set(network, Some(Amount(total_stake)));
|
||||
|
||||
let set = ValidatorSet { network, session };
|
||||
Pallet::<T>::deposit_event(Event::NewSet { set });
|
||||
@@ -523,11 +524,16 @@ pub mod pallet {
|
||||
Err(Error::<T>::AllocationWouldPreventFaultTolerance)?;
|
||||
}
|
||||
|
||||
if InSet::<T>::contains_key(network, account) {
|
||||
TotalAllocatedStake::<T>::set(
|
||||
network,
|
||||
Some(Amount(TotalAllocatedStake::<T>::get(network).unwrap_or(Amount(0)).0 + amount.0)),
|
||||
);
|
||||
// If they're in the current set, and the current set has completed its handover (so its
|
||||
// currently being tracked by TotalAllocatedStake), update the TotalAllocatedStake
|
||||
if let Some(session) = Self::session(network) {
|
||||
if InSet::<T>::contains_key(network, account) && Self::handover_completed(network, session)
|
||||
{
|
||||
TotalAllocatedStake::<T>::set(
|
||||
network,
|
||||
Some(Amount(TotalAllocatedStake::<T>::get(network).unwrap_or(Amount(0)).0 + amount.0)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -643,8 +649,9 @@ pub mod pallet {
|
||||
// Checks if this session has completed the handover from the prior session.
|
||||
fn handover_completed(network: NetworkId, session: Session) -> bool {
|
||||
let Some(current_session) = Self::session(network) else { return false };
|
||||
// No handover occurs on genesis
|
||||
if current_session.0 == 0 {
|
||||
|
||||
// If the session we've been queried about is old, it must have completed its handover
|
||||
if current_session.0 > session.0 {
|
||||
return true;
|
||||
}
|
||||
// If the session we've been queried about has yet to start, it can't have completed its
|
||||
@@ -652,19 +659,21 @@ pub mod pallet {
|
||||
if current_session.0 < session.0 {
|
||||
return false;
|
||||
}
|
||||
if current_session.0 == session.0 {
|
||||
// Handover is automatically complete for Serai as it doesn't have a handover protocol
|
||||
// If not Serai, check the prior session had its keys cleared, which happens once its
|
||||
// retired
|
||||
return (network == NetworkId::Serai) ||
|
||||
(!Keys::<T>::contains_key(ValidatorSet {
|
||||
network,
|
||||
session: Session(current_session.0 - 1),
|
||||
}));
|
||||
|
||||
// Handover is automatically complete for Serai as it doesn't have a handover protocol
|
||||
if network == NetworkId::Serai {
|
||||
return true;
|
||||
}
|
||||
// We're currently in a future session, meaning this session definitely performed itself
|
||||
// handover
|
||||
true
|
||||
|
||||
// The current session must have set keys for its handover to be completed
|
||||
if !Keys::<T>::contains_key(ValidatorSet { network, session }) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// This must be the first session (which has set keys) OR the prior session must have been
|
||||
// retired (signified by its keys no longer being present)
|
||||
(session.0 == 0) ||
|
||||
(!Keys::<T>::contains_key(ValidatorSet { network, session: Session(session.0 - 1) }))
|
||||
}
|
||||
|
||||
fn new_session() {
|
||||
@@ -682,6 +691,8 @@ pub mod pallet {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: This is called retire_set, yet just starts retiring the set
|
||||
// Update the nomenclature within this function
|
||||
pub fn retire_set(set: ValidatorSet) {
|
||||
// If the prior prior set didn't report, emit they're retired now
|
||||
if PendingSlashReport::<T>::get(set.network).is_some() {
|
||||
@@ -690,7 +701,7 @@ pub mod pallet {
|
||||
});
|
||||
}
|
||||
|
||||
// Serai network slashes are handled by BABE/GRANDPA
|
||||
// Serai doesn't set keys and network slashes are handled by BABE/GRANDPA
|
||||
if set.network != NetworkId::Serai {
|
||||
// This overwrites the prior value as the prior to-report set's stake presumably just
|
||||
// unlocked, making their report unenforceable
|
||||
@@ -702,6 +713,14 @@ pub mod pallet {
|
||||
Self::deposit_event(Event::AcceptedHandover {
|
||||
set: ValidatorSet { network: set.network, session: Session(set.session.0 + 1) },
|
||||
});
|
||||
|
||||
// Update the total allocated stake to be for the current set
|
||||
let participants =
|
||||
Participants::<T>::get(set.network).expect("set retired without a new set");
|
||||
let total_stake = participants.iter().fold(0, |acc, (addr, _)| {
|
||||
acc + Allocations::<T>::get((set.network, addr)).unwrap_or(Amount(0)).0
|
||||
});
|
||||
TotalAllocatedStake::<T>::set(set.network, Some(Amount(total_stake)));
|
||||
}
|
||||
|
||||
/// Take the amount deallocatable.
|
||||
@@ -873,7 +892,7 @@ pub mod pallet {
|
||||
pub fn set_keys(
|
||||
origin: OriginFor<T>,
|
||||
network: NetworkId,
|
||||
removed_participants: Vec<Public>,
|
||||
removed_participants: BoundedVec<Public, ConstU32<{ MAX_KEY_SHARES_PER_SET / 3 }>>,
|
||||
key_pair: KeyPair,
|
||||
signature: Signature,
|
||||
) -> DispatchResult {
|
||||
|
||||
Reference in New Issue
Block a user