Skip to content

Commit

Permalink
fix: polkadot nonce issue (#4054)
Browse files Browse the repository at this point in the history
  • Loading branch information
ramizhasan111 authored and dandanlen committed Oct 2, 2023
1 parent c89bc98 commit cc21fd5
Show file tree
Hide file tree
Showing 8 changed files with 26 additions and 137 deletions.
4 changes: 3 additions & 1 deletion state-chain/chains/src/dot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,10 +267,12 @@ impl Chain for Polkadot {
type DepositChannelState = PolkadotChannelState;
type DepositDetails = ();
type Transaction = PolkadotTransactionData;
type ReplayProtectionParams = ();
type ReplayProtectionParams = ResetProxyAccountNonce;
type ReplayProtection = PolkadotReplayProtection;
}

pub type ResetProxyAccountNonce = bool;

#[derive(Clone, Encode, Decode, MaxEncodedLen, TypeInfo, Debug, PartialEq, Eq, Default)]
pub struct PolkadotChannelState;

Expand Down
7 changes: 4 additions & 3 deletions state-chain/chains/src/dot/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ where
transfer_params: Vec<TransferAssetParams<Polkadot>>,
) -> Result<Self, AllBatchError> {
Ok(Self::BatchFetchAndTransfer(batch_fetch_and_transfer::extrinsic_builder(
E::replay_protection(()),
E::replay_protection(false),
fetch_params,
transfer_params,
E::try_vault_account().ok_or(AllBatchError::Other)?,
Expand All @@ -85,7 +85,7 @@ where
let vault = E::try_vault_account().ok_or(())?;

Ok(Self::ChangeGovKey(rotate_vault_proxy::extrinsic_builder(
E::replay_protection(()),
E::replay_protection(false),
maybe_old_key,
new_key,
vault,
Expand All @@ -104,7 +104,8 @@ where
let vault = E::try_vault_account().ok_or(SetAggKeyWithAggKeyError::Failed)?;

Ok(Self::RotateVaultProxy(rotate_vault_proxy::extrinsic_builder(
E::replay_protection(()),
// we reset the proxy account nonce on a rotation tx
E::replay_protection(true),
maybe_old_key,
new_key,
vault,
Expand Down
16 changes: 9 additions & 7 deletions state-chain/pallets/cf-environment/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -387,15 +387,17 @@ impl<T: Config> Pallet<T> {
})
}

pub fn next_polkadot_proxy_account_nonce() -> PolkadotIndex {
pub fn next_polkadot_proxy_account_nonce(reset_nonce: bool) -> PolkadotIndex {
PolkadotProxyAccountNonce::<T>::mutate(|nonce| {
*nonce += 1;
*nonce - 1
})
}
let current_nonce = *nonce;

pub fn reset_polkadot_proxy_account_nonce() {
PolkadotProxyAccountNonce::<T>::set(0);
if reset_nonce {
*nonce = 0;
} else {
*nonce += 1;
}
current_nonce
})
}

pub fn add_bitcoin_utxo_to_list(
Expand Down
5 changes: 1 addition & 4 deletions state-chain/pallets/cf-vaults/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use cf_traits::{
impl_pallet_safe_mode, offence_reporting::OffenceReporter, AccountRoleRegistry, AsyncResult,
Broadcaster, Chainflip, CurrentEpochIndex, EpochKey, GetBlockHeight, KeyProvider, KeyState,
SafeMode, SetSafeMode, Slashing, ThresholdSigner, VaultKeyWitnessedHandler, VaultRotator,
VaultStatus, VaultTransitionHandler,
VaultStatus,
};
use frame_support::{
pallet_prelude::*,
Expand Down Expand Up @@ -174,8 +174,6 @@ pub mod pallet {
<<Self as pallet::Config<I>>::Chain as Chain>::ChainCrypto,
>;

type VaultTransitionHandler: VaultTransitionHandler<Self::Chain>;

/// The pallet dispatches calls, so it depends on the runtime's aggregated Call type.
type RuntimeCall: From<Call<Self, I>> + IsType<<Self as frame_system::Config>::RuntimeCall>;

Expand Down Expand Up @@ -961,7 +959,6 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
active_from_block: block_number.saturating_add(One::one()),
},
);
T::VaultTransitionHandler::on_new_vault();
Self::deposit_event(Event::VaultRotationCompleted);
}
}
Expand Down
6 changes: 0 additions & 6 deletions state-chain/pallets/cf-vaults/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,11 +132,6 @@ impl ApiCall<MockEthereumChainCrypto> for MockSetAggKeyWithAggKey {
}
}

pub struct MockVaultTransitionHandler;
impl VaultTransitionHandler<MockEthereum> for MockVaultTransitionHandler {
fn on_new_vault() {}
}

pub struct MockBroadcaster;

impl MockBroadcaster {
Expand Down Expand Up @@ -223,7 +218,6 @@ impl pallet_cf_vaults::Config for Test {
type ThresholdSigner = MockThresholdSigner<MockEthereumChainCrypto, RuntimeCall>;
type OffenceReporter = MockOffenceReporter;
type SetAggKeyWithAggKey = MockSetAggKeyWithAggKey;
type VaultTransitionHandler = MockVaultTransitionHandler;
type WeightInfo = ();
type Broadcaster = MockBroadcaster;
type SafeMode = MockRuntimeSafeMode;
Expand Down
20 changes: 4 additions & 16 deletions state-chain/runtime/src/chainflip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use cf_chains::{
},
dot::{
api::PolkadotApi, Polkadot, PolkadotAccountId, PolkadotCrypto, PolkadotReplayProtection,
PolkadotTransactionData, RuntimeVersion,
PolkadotTransactionData, ResetProxyAccountNonce, RuntimeVersion,
},
eth::{
self,
Expand All @@ -47,7 +47,7 @@ use cf_traits::{
impl_runtime_safe_mode, AccountRoleRegistry, BlockEmissions, BroadcastAnyChainGovKey,
Broadcaster, Chainflip, CommKeyBroadcaster, DepositApi, DepositHandler, EgressApi, EpochInfo,
Heartbeat, Issuance, KeyProvider, OnBroadcastReady, QualifyNode, RewardsDistribution,
RuntimeUpgrade, VaultTransitionHandler,
RuntimeUpgrade,
};
use codec::{Decode, Encode};
use frame_support::{
Expand Down Expand Up @@ -323,10 +323,10 @@ pub struct DotEnvironment;
impl ReplayProtectionProvider<Polkadot> for DotEnvironment {
// Get the Environment values for vault_account, NetworkChoice and the next nonce for the
// proxy_account
fn replay_protection(_params: ()) -> PolkadotReplayProtection {
fn replay_protection(reset_nonce: ResetProxyAccountNonce) -> PolkadotReplayProtection {
PolkadotReplayProtection {
genesis_hash: Environment::polkadot_genesis_hash(),
nonce: Environment::next_polkadot_proxy_account_nonce(),
nonce: Environment::next_polkadot_proxy_account_nonce(reset_nonce),
}
}
}
Expand Down Expand Up @@ -369,18 +369,6 @@ impl ChainEnvironment<(), cf_chains::btc::AggKey> for BtcEnvironment {
}
}

pub struct EthVaultTransitionHandler;
impl VaultTransitionHandler<Ethereum> for EthVaultTransitionHandler {}

pub struct DotVaultTransitionHandler;
impl VaultTransitionHandler<Polkadot> for DotVaultTransitionHandler {
fn on_new_vault() {
Environment::reset_polkadot_proxy_account_nonce();
}
}
pub struct BtcVaultTransitionHandler;
impl VaultTransitionHandler<Bitcoin> for BtcVaultTransitionHandler {}

pub struct TokenholderGovernanceBroadcaster;

impl TokenholderGovernanceBroadcaster {
Expand Down
102 changes: 5 additions & 97 deletions state-chain/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use cf_amm::{
};
use cf_chains::{
btc::{BitcoinCrypto, BitcoinNetwork},
dot::{self, PolkadotCrypto, PolkadotExtrinsicBuilder, PolkadotHash, PolkadotReplayProtection},
dot::{self, PolkadotCrypto, PolkadotHash},
eth::{self, api::EthereumApi, Address as EthereumAddress, Ethereum},
evm::EvmCrypto,
Bitcoin, Polkadot,
Expand Down Expand Up @@ -85,11 +85,10 @@ pub use cf_traits::{EpochInfo, QualifyNode, SessionKeysRegistered, SwappingApi};
pub use chainflip::chain_instances::*;
use chainflip::{
epoch_transition::ChainflipEpochTransitions, BroadcastReadyProvider, BtcEnvironment,
BtcVaultTransitionHandler, ChainAddressConverter, ChainflipHeartbeat, EthEnvironment,
EthVaultTransitionHandler, TokenholderGovernanceBroadcaster,
ChainAddressConverter, ChainflipHeartbeat, EthEnvironment, TokenholderGovernanceBroadcaster,
};

use chainflip::{all_vaults_rotator::AllVaultRotator, DotEnvironment, DotVaultTransitionHandler};
use chainflip::{all_vaults_rotator::AllVaultRotator, DotEnvironment};
use constants::common::*;
use pallet_cf_flip::{Bonder, FlipSlasher};
use pallet_cf_vaults::Vault;
Expand Down Expand Up @@ -145,7 +144,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("chainflip-node"),
impl_name: create_runtime_str!("chainflip-node"),
authoring_version: 1,
spec_version: 19,
spec_version: 20,
impl_version: 1,
apis: RUNTIME_API_VERSIONS,
transaction_version: 4,
Expand Down Expand Up @@ -230,7 +229,6 @@ impl pallet_cf_vaults::Config<EthereumInstance> for Runtime {
type Offence = chainflip::Offence;
type Chain = Ethereum;
type SetAggKeyWithAggKey = eth::api::EthereumApi<EthEnvironment>;
type VaultTransitionHandler = EthVaultTransitionHandler;
type Broadcaster = EthereumBroadcaster;
type OffenceReporter = Reputation;
type WeightInfo = pallet_cf_vaults::weights::PalletWeight<Runtime>;
Expand All @@ -248,7 +246,6 @@ impl pallet_cf_vaults::Config<PolkadotInstance> for Runtime {
type Offence = chainflip::Offence;
type Chain = Polkadot;
type SetAggKeyWithAggKey = dot::api::PolkadotApi<DotEnvironment>;
type VaultTransitionHandler = DotVaultTransitionHandler;
type Broadcaster = PolkadotBroadcaster;
type OffenceReporter = Reputation;
type WeightInfo = pallet_cf_vaults::weights::PalletWeight<Runtime>;
Expand All @@ -266,7 +263,6 @@ impl pallet_cf_vaults::Config<BitcoinInstance> for Runtime {
type Offence = chainflip::Offence;
type Chain = Bitcoin;
type SetAggKeyWithAggKey = cf_chains::btc::api::BitcoinApi<BtcEnvironment>;
type VaultTransitionHandler = BtcVaultTransitionHandler;
type Broadcaster = BitcoinBroadcaster;
type OffenceReporter = Reputation;
type WeightInfo = pallet_cf_vaults::weights::PalletWeight<Runtime>;
Expand Down Expand Up @@ -818,97 +814,9 @@ pub type Executive = frame_executive::Executive<
frame_system::ChainContext<Runtime>,
Runtime,
AllPalletsWithSystem,
CustomUpgrade,
(),
>;

// TODO: remove this after upgrade.
pub struct CustomUpgrade;
impl frame_support::traits::OnRuntimeUpgrade for CustomUpgrade {
fn on_runtime_upgrade() -> Weight {
use cf_chains::dot::*;
for (id, _discarded) in
pallet_cf_broadcast::ThresholdSignatureData::<Runtime, PolkadotInstance>::iter()
.drain() {
PolkadotBroadcaster::clean_up_broadcast_storage(id);
}

let mut nonce = 4;
let old_proxy = PolkadotAccountId::from_aliased(
[66, 52, 239, 247, 15, 170, 140, 224, 126, 117, 24, 124, 3, 146, 26, 109, 38, 38, 112, 182, 226, 95, 180, 180, 237, 187, 31, 44, 217, 190, 218, 88]
);
let new_proxy = PolkadotAccountId::from_aliased(
[30, 47, 51, 174, 46, 192, 211, 61, 122, 34, 244, 228, 86, 218, 109, 52, 72, 249, 1, 216, 73, 155, 4, 184, 121, 135, 150, 53, 16, 118, 159, 2]
);
let cf_whale = PolkadotAccountId::from_aliased(
[10, 215, 155, 16, 79, 18, 35, 75, 72, 76, 65, 42, 30, 61, 78, 212, 107, 37, 17, 249, 111, 178, 121, 26, 25, 102, 84, 15, 243, 53, 22, 101]
);
let vault = PolkadotAccountId::from_aliased(
[234, 136, 35, 1, 2, 28, 52, 107, 226, 223, 220, 129, 145, 37, 71, 75, 184, 47, 189, 128, 184, 178, 77, 120, 126, 1, 11, 94, 107, 172, 104, 138]
);
// transfers first
PolkadotBroadcaster::threshold_sign_and_broadcast(
cf_chains::dot::api::PolkadotApi::BatchFetchAndTransfer(PolkadotExtrinsicBuilder::new(
PolkadotReplayProtection {
nonce: 4,
genesis_hash: pallet_cf_environment::PolkadotGenesisHash::<Runtime>::get(),
},
PolkadotRuntimeCall::Utility(UtilityCall::batch_all {
calls: vec![
PolkadotRuntimeCall::Proxy(ProxyCall::proxy {
real: vault.into(),
force_proxy_type: Some(PolkadotProxyType::Any),
call: Box::new(PolkadotRuntimeCall::Utility(UtilityCall::batch_all {
calls: [
Some(PolkadotRuntimeCall::Proxy(ProxyCall::add_proxy {
delegate: new_proxy.into(),
proxy_type: PolkadotProxyType::Any,
delay: 0,
})),
Some(PolkadotRuntimeCall::Proxy(ProxyCall::add_proxy {
delegate: cf_whale.into(),
proxy_type: PolkadotProxyType::Any,
delay: 0,
})),
Some(PolkadotRuntimeCall::Proxy(ProxyCall::remove_proxy {
delegate: old_proxy.into(),
proxy_type: PolkadotProxyType::Any,
delay: 0,
})),
]
.into_iter()
.flatten()
.collect(),
})),
}),
PolkadotRuntimeCall::Balances(BalancesCall::transfer_all {
dest: new_proxy.into(),
keep_alive: false,
}),
],
}),
)),
None
);

Weight::zero()
}

#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<sp_std::vec::Vec<u8>, DispatchError> {
use codec::Encode;
Ok(pallet_cf_broadcast::BroadcastIdCounter::<Runtime, PolkadotInstance>::get().encode())
}

#[cfg(feature = "try-runtime")]
fn post_upgrade(state: sp_std::vec::Vec<u8>) -> Result<(), DispatchError> {
let pre = <u32 as codec::Decode>::decode(&mut &state[..])
.map_err(|_| DispatchError::Other("Invalid state"))?;
let post = pallet_cf_broadcast::BroadcastIdCounter::<Runtime, PolkadotInstance>::get();
assert_eq!(post, pre + 4);
Ok(())
}
}

#[cfg(feature = "runtime-benchmarks")]
#[macro_use]
extern crate frame_benchmarking;
Expand Down
3 changes: 0 additions & 3 deletions state-chain/traits/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -738,9 +738,6 @@ impl<T: frame_system::Config> EgressApi<Polkadot> for T {
}
}

pub trait VaultTransitionHandler<C: Chain> {
fn on_new_vault() {}
}
pub trait VaultKeyWitnessedHandler<C: Chain> {
fn on_new_key_activated(block_number: C::ChainBlockNumber) -> DispatchResultWithPostInfo;
}
Expand Down

0 comments on commit cc21fd5

Please sign in to comment.