Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/multi signature supprt #16

Merged
merged 8 commits into from
Jan 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 3 additions & 6 deletions client/basic-authorship-ver/src/basic_authorship.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,12 @@ use sc_block_builder::{validate_transaction, BlockBuilderApi, BlockBuilderProvid
use sc_client_api::backend;
use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_INFO};
use sc_transaction_pool_api::{InPoolTransaction, TransactionPool};
use sp_api::{ApiExt, ProvideRuntimeApi, TransactionOutcome};
use sp_blockchain::{
ApplyExtrinsicFailed as ApplyExtrinsicFailedOther, ApplyExtrinsicFailed::Validity,
Error::ApplyExtrinsicFailed, HeaderBackend,
};
use sp_api::{ApiExt, ProvideRuntimeApi};
use sp_blockchain::{ApplyExtrinsicFailed::Validity, Error::ApplyExtrinsicFailed, HeaderBackend};
use sp_consensus::{
evaluation, DisableProofRecording, EnableProofRecording, ProofRecording, Proposal,
};
use sp_core::{traits::SpawnNamed, ExecutionContext};
use sp_core::traits::SpawnNamed;
use sp_inherents::InherentData;
use sp_runtime::{
generic::BlockId,
Expand Down
10 changes: 5 additions & 5 deletions client/block-builder-ver/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ use sp_core::ExecutionContext;
use sp_runtime::{
generic::BlockId,
traits::{
BlakeTwo256, Block as BlockT, DigestFor, DigestItemFor, Extrinsic, Hash, HashFor,
Header as HeaderT, NumberFor, One,
BlakeTwo256, Block as BlockT, DigestFor, Hash, HashFor, Header as HeaderT, NumberFor, One,
},
SaturatedConversion,
};
Expand All @@ -46,10 +45,9 @@ pub use sp_block_builder::BlockBuilder as BlockBuilderApi;
use sp_blockchain::HeaderBackend;
use ver_api::VerApi;

use log::info;
use sc_client_api::backend;
use sp_core::ShufflingSeed;
use sp_ver::{extract_inherent_data, CompatibleDigestItemVer, PreDigestVer};
use sp_ver::extract_inherent_data;

/// Used as parameter to [`BlockBuilderProvider`] to express if proof recording should be enabled.
///
Expand Down Expand Up @@ -206,6 +204,7 @@ where
})
}

/// temporaily apply extrinsics and record them on the list
pub fn record_valid_extrinsics_and_revert_changes<
F: FnOnce(&'_ A::Api) -> Vec<Block::Extrinsic>,
>(
Expand Down Expand Up @@ -251,7 +250,7 @@ where
pub fn apply_previous_block_extrinsics(&mut self, seed: ShufflingSeed) {
let parent_hash = self.parent_hash;
let block_id = &self.block_id;
self.api.store_seed(&block_id, seed.seed);
self.api.store_seed(&block_id, seed.seed).unwrap();

let previous_block_header =
self.backend.blockchain().header(BlockId::Hash(parent_hash)).unwrap().unwrap();
Expand Down Expand Up @@ -416,6 +415,7 @@ where
}
}

/// Verifies if trasaction can be executed
pub fn validate_transaction<'a, Block, Api>(
at: &BlockId<Block>,
api: &'_ Api::Api,
Expand Down
3 changes: 1 addition & 2 deletions client/consensus/babe/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -897,9 +897,8 @@ where
// self.keystore.clone()
}

fn get_key(&self, claim: &Self::Claim) -> sp_core::sr25519::Public {
fn get_key(&self, _claim: &Self::Claim) -> sp_core::sr25519::Public {
unimplemented!()
// claim.as_slice().try_into().unwrap()
}
}

Expand Down
4 changes: 2 additions & 2 deletions client/consensus/babe/src/verification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ where
);

check_secondary_plain_header::<B>(pre_hash, secondary, sig, &epoch)?;
}
},
PreDigest::SecondaryVRF(secondary)
if epoch.config.allowed_slots.is_secondary_vrf_slots_allowed() =>
{
Expand All @@ -125,7 +125,7 @@ where
);

check_secondary_vrf_header::<B>(pre_hash, secondary, sig, &epoch)?;
}
},
_ => return Err(babe_err(Error::SecondarySlotAssignmentsDisabled)),
}

Expand Down
5 changes: 1 addition & 4 deletions client/consensus/slots/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,7 @@ use sp_api::{ApiRef, ProvideRuntimeApi};
use sp_arithmetic::traits::BaseArithmetic;
use sp_consensus::{CanAuthorWith, Proposer, SelectChain, SlotData, SyncOracle};
use sp_consensus_slots::Slot;
use sp_core::{
crypto::{key_types::AURA, Public},
sr25519, ShufflingSeed,
};
use sp_core::{crypto::key_types::AURA, sr25519, ShufflingSeed};
use sp_inherents::{CreateInherentDataProviders, InherentDataProvider};
use sp_keystore::{vrf, SyncCryptoStore, SyncCryptoStorePtr};
use sp_runtime::{
Expand Down
32 changes: 12 additions & 20 deletions frame/executive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ use schnorrkel::vrf::{VRFOutput, VRFProof};
use sp_runtime::{
generic::Digest,
traits::{
self, Applyable, CheckEqual, Checkable, Dispatchable, Extrinsic, HasAddress, Header,
NumberFor, One, Saturating, ValidateUnsigned, Zero,
self, Applyable, CheckEqual, Checkable, Dispatchable, Extrinsic, Header,
IdentifyAccountWithLookup, NumberFor, One, Saturating, ValidateUnsigned, Zero,
},
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, SaturatedConversion,
Expand Down Expand Up @@ -171,7 +171,9 @@ impl<
> ExecuteBlock<Block>
for Executive<System, Block, Context, UnsignedValidator, AllPallets, COnRuntimeUpgrade>
where
Block::Extrinsic: HasAddress<AccountId = System::AccountId> + Checkable<Context> + Codec,
Block::Extrinsic: IdentifyAccountWithLookup<Context, AccountId = System::AccountId>
+ Checkable<Context>
+ Codec,
CheckedOf<Block::Extrinsic, Context>: Applyable + GetDispatchInfo,
CallOf<Block::Extrinsic, Context>:
Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
Expand All @@ -198,20 +200,10 @@ where
UnsignedValidator,
AllPallets,
COnRuntimeUpgrade,
>::execute_block_ver(block, public);
>::execute_block_ver_impl(block, public);
}
}

// fn create_shuffling_seed_input_data(prev_seed: &ShufflingSeed) -> vrf::VRFTranscriptData {
// vrf::VRFTranscriptData {
// label: b"shuffling_seed",
// items: vec![(
// "prev_seed",
// vrf::VRFTranscriptValue::Bytes(prev_seed.seed.as_bytes().to_vec()),
// )],
// }
// }

impl<
System: frame_system::Config + EnsureInherentsAreFirst<Block>,
Block: traits::Block<Header = System::Header, Hash = System::Hash>,
Expand All @@ -226,7 +218,9 @@ impl<
> Executive<System, Block, Context, UnsignedValidator, AllPallets, COnRuntimeUpgrade>
where
<System as frame_system::Config>::BlockNumber: AtLeast32BitUnsigned,
Block::Extrinsic: HasAddress<AccountId = System::AccountId> + Checkable<Context> + Codec,
Block::Extrinsic: IdentifyAccountWithLookup<Context, AccountId = System::AccountId>
+ Checkable<Context>
+ Codec,
CheckedOf<Block::Extrinsic, Context>: Applyable + GetDispatchInfo,
CallOf<Block::Extrinsic, Context>:
Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
Expand Down Expand Up @@ -331,7 +325,6 @@ where
digest,
frame_system::InitKind::Full,
);

weight = weight.saturating_add(<frame_system::Pallet<System> as OnInitialize<
System::BlockNumber,
>>::on_initialize(*block_number));
Expand Down Expand Up @@ -368,7 +361,6 @@ where
// Check that `parent_hash` is correct.
sp_tracing::enter_span!(sp_tracing::Level::TRACE, "ver checks");
let header = block.header();
let n = header.number().clone();
// Check that shuffling seedght is generated properly
let new_seed = VRFOutput::from_bytes(&header.seed().seed.as_bytes())
.expect("cannot parse shuffling seed");
Expand Down Expand Up @@ -436,7 +428,7 @@ where
}

/// Actually execute all transitions for `block`.
pub fn execute_block_ver(block: Block, public: Vec<u8>) {
pub fn execute_block_ver_impl(block: Block, public: Vec<u8>) {
sp_io::init_tracing();
sp_tracing::within_span! {
sp_tracing::info_span!("execute_block", ?block);
Expand Down Expand Up @@ -466,11 +458,11 @@ where

let extrinsics_with_author: Vec<(_,_)> = tx_to_be_executed.into_iter().map(|e|
(
(e.get_address(), e)
// its safe to panic here
(e.get_account_id(&Default::default()).unwrap(), e)
iStrike7 marked this conversation as resolved.
Show resolved Hide resolved
)
).collect();
let shuffled_extrinsics = extrinsic_shuffler::shuffle_using_seed(extrinsics_with_author, &header.seed().seed);
// let shuffled_extrinsics = tx_to_be_executed;

Self::execute_extrinsics_with_book_keeping(shuffled_extrinsics, *header.number());

Expand Down
11 changes: 2 additions & 9 deletions frame/system/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,9 @@ use sp_runtime::{
traits::{
self, AtLeast32Bit, AtLeast32BitUnsigned, BadOrigin, BlockNumberProvider, Bounded,
CheckEqual, Dispatchable, Hash, Lookup, LookupError, MaybeDisplay, MaybeMallocSizeOf,
MaybeSerializeDeserialize, Member, One, Saturating, SimpleBitOps, StaticLookup,
UniqueSaturatedInto, Zero,
MaybeSerializeDeserialize, Member, One, Saturating, SimpleBitOps, StaticLookup, Zero,
},
DispatchError, Either, Perbill, RuntimeDebug, SaturatedConversion,
DispatchError, Either, Perbill, RuntimeDebug,
};
#[cfg(any(feature = "std", test))]
use sp_std::map;
Expand Down Expand Up @@ -1371,12 +1370,6 @@ impl<T: Config> Pallet<T> {
}

pub fn set_block_seed(seed: &sp_core::H256) {
let number = <Number<T>>::get();
sp_runtime::print("SET SEED");
let number: u64 = number.unique_saturated_into();
for b in seed.as_bytes() {
sp_runtime::print(b);
}
<BlockSeed<T>>::put(seed);
}

Expand Down
10 changes: 5 additions & 5 deletions frame/timestamp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,8 @@ pub mod pallet {
/// - 1 storage deletion (codec `O(1)`).
/// # </weight>
fn on_finalize(_n: BlockNumberFor<T>) {
if !<frame_system::Module<T>>::block_number().is_zero() &&
!<frame_system::Module<T>>::block_number().is_one()
if !<frame_system::Pallet<T>>::block_number().is_zero() &&
!<frame_system::Pallet<T>>::block_number().is_one()
{
assert!(DidUpdate::<T>::take(), "Timestamp must be updated once in the block");
}
Expand Down Expand Up @@ -200,8 +200,8 @@ pub mod pallet {
assert!(!DidUpdate::<T>::exists(), "Timestamp must be updated only once in the block");
let prev = Self::now();
assert!(
!<frame_system::Module<T>>::block_number().is_zero() ||
!<frame_system::Module<T>>::block_number().is_one() ||
!<frame_system::Pallet<T>>::block_number().is_zero() ||
!<frame_system::Pallet<T>>::block_number().is_one() ||
prev.is_zero() || now >= prev + T::MinimumPeriod::get(),
"Timestamp must increment by at least <MinimumPeriod> between sequential blocks"
);
Expand Down Expand Up @@ -298,7 +298,7 @@ impl<T: Config> UnixTime for Pallet<T> {
// `sp_timestamp::InherentDataProvider`.
let now = Self::now();
sp_std::if_std! {
if now == T::Moment::zero() && !<frame_system::Module<T>>::block_number().is_zero() && !<frame_system::Module<T>>::block_number().is_one(){
if now == T::Moment::zero() && !<frame_system::Pallet<T>>::block_number().is_zero() && !<frame_system::Pallet<T>>::block_number().is_one(){
log::error!(
target: "runtime::timestamp",
"`pallet_timestamp::UnixTime::now` is called at genesis, invalid value returned: 0",
Expand Down
53 changes: 13 additions & 40 deletions primitives/runtime/src/generic/unchecked_extrinsic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@
use crate::{
generic::CheckedExtrinsic,
traits::{
self, Checkable, Extrinsic, ExtrinsicMetadata, HasAddress, IdentifyAccount, MaybeDisplay,
Member, SignedExtension,
self, Checkable, Extrinsic, ExtrinsicMetadata, IdentifyAccount, IdentifyAccountWithLookup,
LookupError, MaybeDisplay, Member, SignedExtension,
},
transaction_validity::{InvalidTransaction, TransactionValidityError},
AccountId32, MultiAddress, OpaqueExtrinsic,
AccountId32, OpaqueExtrinsic,
};
use codec::{Compact, Decode, Encode, EncodeLike, Error, Input};
use scale_info::{build::Fields, meta_type, Path, StaticTypeInfo, Type, TypeInfo, TypeParameter};
Expand Down Expand Up @@ -159,51 +159,24 @@ where
}
}

impl<AccountId, AccountIndex, Call, Signature, Extra> HasAddress
for UncheckedExtrinsic<MultiAddress<AccountId, AccountIndex>, Call, Signature, Extra>
where
AccountId: Clone,
Signature: Member + traits::Verify,
<Signature as traits::Verify>::Signer: IdentifyAccount<AccountId = AccountId>,
Extra: SignedExtension<AccountId = AccountId>,
{
type AccountId = AccountId;

fn get_address(&self) -> Option<Self::AccountId> {
match &self.signature {
Some((MultiAddress::<AccountId, AccountIndex>::Id(addr), _, _)) => Some(addr.clone()),
Some(_) => panic!("unsupported address"),
_ => None,
}
}
}

impl<Call, Signature, Extra> HasAddress for UncheckedExtrinsic<AccountId32, Call, Signature, Extra>
impl<Lookup, Address, Call, Signature, Extra> IdentifyAccountWithLookup<Lookup>
for UncheckedExtrinsic<Address, Call, Signature, Extra>
where
Signature: Member + traits::Verify,
Address: Member + MaybeDisplay + Clone,
Signature: Member + traits::Verify + Clone,
<Signature as traits::Verify>::Signer: IdentifyAccount<AccountId = AccountId32>,
Extra: SignedExtension<AccountId = AccountId32>,
Lookup: traits::Lookup<Source = Address, Target = AccountId32>,
{
type AccountId = AccountId32;

fn get_address(&self) -> Option<Self::AccountId> {
self.signature.as_ref().map(|(sig, _, _)| sig).cloned()
fn get_account_id(&self, lookup: &Lookup) -> Result<Option<AccountId32>, LookupError> {
match self.signature {
Some((ref signed, _, _)) => lookup.lookup(signed.clone()).map(|addr| Some(addr)),
None => Ok(None),
}
}
}

// impl<T, Call, Signature, Extra> HasAddress
// for UncheckedExtrinsic<T, Call, Signature, Extra> where
// Signature: Member + traits::Verify,
// <Signature as traits::Verify>::Signer: IdentifyAccount<AccountId = T>,
// Extra: SignedExtension<AccountId = T>,
// {
// type AccountId = AccountId;
//
// fn get_address(&self) -> Option<Self::AccountId>{
// None
// }
// }
//
impl<Address, Call, Signature, Extra> ExtrinsicMetadata
for UncheckedExtrinsic<Address, Call, Signature, Extra>
where
Expand Down
14 changes: 8 additions & 6 deletions primitives/runtime/src/testing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ use crate::{
generic,
scale_info::TypeInfo,
traits::{
self, Applyable, BlakeTwo256, Checkable, DispatchInfoOf, Dispatchable, HasAddress,
OpaqueKeys, PostDispatchInfoOf, SignedExtension, ValidateUnsigned,
self, Applyable, BlakeTwo256, Checkable, DispatchInfoOf, Dispatchable,
IdentifyAccountWithLookup, OpaqueKeys, PostDispatchInfoOf, SignedExtension,
ValidateUnsigned,
},
transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError},
ApplyExtrinsicResultWithInfo, CryptoTypeId, KeyTypeId,
Expand Down Expand Up @@ -331,11 +332,12 @@ impl<Call, Extra> TestXt<Call, Extra> {
}
}

impl<Call, Extra> HasAddress for TestXt<Call, Extra> {
type AccountId = u64;
use crate::traits::LookupError;

fn get_address(&self) -> Option<Self::AccountId> {
self.signature.as_ref().map(|(id, _)| *id)
impl<T, Call, Extra> IdentifyAccountWithLookup<T> for TestXt<Call, Extra> {
type AccountId = u64;
fn get_account_id(&self, lookup: &T) -> Result<Option<u64>, LookupError> {
Ok(None)
}
}

Expand Down
8 changes: 4 additions & 4 deletions primitives/runtime/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -800,12 +800,12 @@ pub trait Checkable<Context>: Sized {
}

/// Provides information about author
pub trait HasAddress {
/// Returned if `check` succeeds.
pub trait IdentifyAccountWithLookup<Lookup> {
/// type that identifis account
type AccountId;

/// Check self, given an instance of Context.
fn get_address(&self) -> Option<Self::AccountId>;
/// performs lookup and returns AccountId if available
fn get_account_id(&self, lookup: &Lookup) -> Result<Option<Self::AccountId>, LookupError>;
}

/// A "checkable" piece of information, used by the standard Substrate Executive in order to
Expand Down
Loading