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

[AHM] Pallet claims #570

Merged
merged 7 commits into from
Feb 1, 2025
Merged
Show file tree
Hide file tree
Changes from 4 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
81 changes: 81 additions & 0 deletions pallets/ah-migrator/src/claims.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::*;
use pallet_rc_migrator::claims::{alias, RcClaimsMessage, RcClaimsMessageOf};

impl<T: Config> Pallet<T> {
pub fn do_receive_claims(messages: Vec<RcClaimsMessageOf<T>>) -> Result<(), Error<T>> {
log::info!(target: LOG_TARGET, "Integrating {} claims", messages.len());
Self::deposit_event(Event::ClaimsBatchReceived { count: messages.len() as u32 });
let (mut count_good, mut count_bad) = (0, 0);

for message in messages {
match Self::do_process_claims(message) {
Ok(()) => count_good += 1,
Err(e) => {
count_bad += 1;
log::error!(target: LOG_TARGET, "Error while integrating claims: {:?}", e);
},
}
}
Self::deposit_event(Event::ClaimsBatchProcessed { count_good, count_bad });

Ok(())
}

pub fn do_process_claims(message: RcClaimsMessageOf<T>) -> Result<(), Error<T>> {
match message {
RcClaimsMessage::StorageValues { total } => {
if pallet_claims::Total::<T>::exists() {
return Err(Error::<T>::InsertConflict);
}
log::debug!(target: LOG_TARGET, "Processing claims message: total");
ggwpez marked this conversation as resolved.
Show resolved Hide resolved
pallet_claims::Total::<T>::put(total);
},
RcClaimsMessage::Claims((who, amount)) => {
if alias::Claims::<T>::contains_key(&who) {
return Err(Error::<T>::InsertConflict);
}
log::debug!(target: LOG_TARGET, "Processing claims message: claims");
alias::Claims::<T>::insert(who, amount);
},
RcClaimsMessage::Vesting { who, schedule } => {
if alias::Vesting::<T>::contains_key(&who) {
return Err(Error::<T>::InsertConflict);
}
log::debug!(target: LOG_TARGET, "Processing claims message: vesting");
alias::Vesting::<T>::insert(who, schedule);
},
RcClaimsMessage::Signing((who, statement_kind)) => {
if alias::Signing::<T>::contains_key(&who) {
return Err(Error::<T>::InsertConflict);
}
log::debug!(target: LOG_TARGET, "Processing claims message: signing");
alias::Signing::<T>::insert(who, statement_kind);
},
RcClaimsMessage::Preclaims((who, address)) => {
if alias::Preclaims::<T>::contains_key(&who) {
return Err(Error::<T>::InsertConflict);
}
log::debug!(target: LOG_TARGET, "Processing claims message: preclaims");
alias::Preclaims::<T>::insert(who, address);
},
}
Ok(())
}
}
30 changes: 29 additions & 1 deletion pallets/ah-migrator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#![cfg_attr(not(feature = "std"), no_std)]

pub mod account;
pub mod claims;
pub mod multisig;
pub mod preimage;
pub mod proxy;
Expand All @@ -53,9 +54,11 @@ use frame_support::{
use frame_system::pallet_prelude::*;
use pallet_balances::{AccountData, Reasons as LockReasons};
use pallet_rc_migrator::{
accounts::Account as RcAccount, multisig::*, preimage::*, proxy::*, staking::nom_pools::*,
accounts::Account as RcAccount, claims::RcClaimsMessageOf, multisig::*, preimage::*, proxy::*,
staking::nom_pools::*,
};
use pallet_referenda::TrackIdOf;
use polkadot_runtime_common::claims as pallet_claims;
use referenda::RcReferendumInfoOf;
use sp_application_crypto::Ss58Codec;
use sp_core::H256;
Expand Down Expand Up @@ -86,6 +89,7 @@ pub mod pallet {
frame_system::Config<AccountData = AccountData<u128>, AccountId = AccountId32>
+ pallet_balances::Config<Balance = u128>
+ pallet_multisig::Config
+ pallet_claims::Config
+ pallet_proxy::Config
+ pallet_preimage::Config<Hash = H256>
+ pallet_referenda::Config<Votes = u128>
Expand Down Expand Up @@ -152,6 +156,8 @@ pub mod pallet {
FailedToConvertType,
/// Failed to fetch preimage.
PreimageNotFound,
/// Failed to insert into storage because it is already present.
InsertConflict,
}

#[pallet::event]
Expand Down Expand Up @@ -182,6 +188,18 @@ pub mod pallet {
/// How many multisigs failed to integrate.
count_bad: u32,
},
/// We received a batch of claims that we are going to integrate.
ClaimsBatchReceived {
/// How many claims are in the batch.
count: u32,
},
/// We processed a batch of claims that we received.
ClaimsBatchProcessed {
/// How many claims were successfully integrated.
count_good: u32,
/// How many claims failed to integrate.
count_bad: u32,
},
/// We received a batch of proxies that we are going to integrate.
ProxyProxiesBatchReceived {
/// How many proxies are in the batch.
Expand Down Expand Up @@ -395,6 +413,16 @@ pub mod pallet {

Self::do_receive_referendums(referendums).map_err(Into::into)
}

#[pallet::call_index(10)]
pub fn receive_claims(
origin: OriginFor<T>,
messages: Vec<RcClaimsMessageOf<T>>,
) -> DispatchResult {
ensure_root(origin)?;

Self::do_receive_claims(messages).map_err(Into::into)
}
}

#[pallet::hooks]
Expand Down
223 changes: 223 additions & 0 deletions pallets/rc-migrator/src/claims.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// TODO FAIL-CI: Insecure unless your chain includes `PrevalidateAttests` as a
// `TransactionExtension`.

use crate::*;
use alias::{EthereumAddress, StatementKind};
use frame_support::traits::{Currency, VestingSchedule};

#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
pub enum ClaimsStage<AccountId> {
StorageValues,
Claims(Option<EthereumAddress>),
Vesting(Option<EthereumAddress>),
Signing(Option<EthereumAddress>),
Preclaims(Option<AccountId>),
Finished,
}

#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, RuntimeDebug, Clone, PartialEq, Eq)]
pub enum RcClaimsMessage<AccountId, Balance, BlockNumber> {
StorageValues { total: Balance },
Claims((EthereumAddress, Balance)),
Vesting { who: EthereumAddress, schedule: (Balance, Balance, BlockNumber) },
Signing((EthereumAddress, StatementKind)),
Preclaims((AccountId, EthereumAddress)),
}
pub type RcClaimsMessageOf<T> =
RcClaimsMessage<<T as frame_system::Config>::AccountId, BalanceOf<T>, BlockNumberFor<T>>;

pub type BalanceOf<T> =
<CurrencyOf<T> as Currency<<T as frame_system::Config>::AccountId>>::Balance;
type CurrencyOf<T> = <<T as pallet_claims::Config>::VestingSchedule as VestingSchedule<
<T as frame_system::Config>::AccountId,
>>::Currency;

pub struct ClaimsMigrator<T> {
_phantom: PhantomData<T>,
}

impl<T: Config> PalletMigration for ClaimsMigrator<T> {
type Key = ClaimsStage<T::AccountId>;
type Error = Error<T>;

fn migrate_many(
current_key: Option<Self::Key>,
weight_counter: &mut WeightMeter,
) -> Result<Option<Self::Key>, Self::Error> {
let mut inner_key = current_key.unwrap_or(ClaimsStage::StorageValues);
let mut messages = Vec::new();

loop {
if weight_counter
.try_consume(<T as frame_system::Config>::DbWeight::get().reads_writes(1, 1))
.is_err()
{
if messages.is_empty() {
return Err(Error::OutOfWeight);
} else {
break;
}
}
if messages.len() > 10_000 {
log::warn!("Weight allowed very big batch, stopping");
break;
}

inner_key = match inner_key {
ClaimsStage::StorageValues => {
let total = pallet_claims::Total::<T>::take();
messages.push(RcClaimsMessage::StorageValues { total });
ClaimsStage::Claims(None)
},
ClaimsStage::Claims(address) => {
let mut iter = match address.clone() {
Some(address) => alias::Claims::<T>::iter_from(
alias::Claims::<T>::hashed_key_for(address),
),
None => alias::Claims::<T>::iter(),
};

match iter.next() {
Some((address, amount)) => {
alias::Claims::<T>::remove(&address);
messages.push(RcClaimsMessage::Claims((address, amount)));
ClaimsStage::Claims(Some(address))
},
None => ClaimsStage::Vesting(None),
}
},
ClaimsStage::Vesting(address) => {
let mut iter = match address.clone() {
Some(address) => alias::Vesting::<T>::iter_from(
alias::Vesting::<T>::hashed_key_for(address),
),
None => alias::Vesting::<T>::iter(),
};

match iter.next() {
Some((address, schedule)) => {
alias::Vesting::<T>::remove(&address);
messages.push(RcClaimsMessage::Vesting { who: address, schedule });
ClaimsStage::Vesting(Some(address))
},
None => ClaimsStage::Signing(None),
}
},
ClaimsStage::Signing(address) => {
let mut iter = match address.clone() {
Some(address) => alias::Signing::<T>::iter_from(
alias::Signing::<T>::hashed_key_for(address),
),
None => alias::Signing::<T>::iter(),
};

match iter.next() {
Some((address, statement)) => {
alias::Signing::<T>::remove(&address);
messages.push(RcClaimsMessage::Signing((address, statement)));
ClaimsStage::Signing(Some(address))
},
None => ClaimsStage::Preclaims(None),
}
},
ClaimsStage::Preclaims(address) => {
let mut iter = match address.clone() {
Some(address) => alias::Preclaims::<T>::iter_from(
alias::Preclaims::<T>::hashed_key_for(address),
),
None => alias::Preclaims::<T>::iter(),
};

match iter.next() {
Some((address, statement)) => {
alias::Preclaims::<T>::remove(&address);
messages.push(RcClaimsMessage::Preclaims((address.clone(), statement)));
ClaimsStage::Preclaims(Some(address))
},
None => ClaimsStage::Finished,
}
},
ClaimsStage::Finished => {
break;
},
}
}

if !messages.is_empty() {
Pallet::<T>::send_chunked_xcm(messages, |messages| {
types::AhMigratorCall::<T>::ReceiveClaimsMessages { messages }
})?;
}

if inner_key == ClaimsStage::Finished {
Ok(None)
} else {
Ok(Some(inner_key))
}
}
}

pub mod alias {
use super::*;

/// Copy of the EthereumAddress type from the SDK since the version that we pull is is not MEL
/// :(
// From https://github.com/paritytech/polkadot-sdk/blob/d8df46c7a1488f2358e69368813fd772164c4dac/polkadot/runtime/common/src/claims/mod.rs#L130-L133
#[derive(
Clone, Copy, PartialEq, Eq, Encode, Decode, Default, RuntimeDebug, TypeInfo, MaxEncodedLen,
)]
pub struct EthereumAddress(pub [u8; 20]);

// Also not MEL...
// From https://github.com/paritytech/polkadot-sdk/blob/d8df46c7a1488f2358e69368813fd772164c4dac/polkadot/runtime/common/src/claims/mod.rs#L84-L103
#[derive(Encode, Decode, Clone, Copy, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
pub enum StatementKind {
Regular,
Saft,
}

// From https://github.com/paritytech/polkadot-sdk/blob/d8df46c7a1488f2358e69368813fd772164c4dac/polkadot/runtime/common/src/claims/mod.rs#L226-L227
#[frame_support::storage_alias(pallet_name)]
pub type Claims<T: pallet_claims::Config> =
StorageMap<pallet_claims::Pallet<T>, Identity, EthereumAddress, BalanceOf<T>>;

// From https://github.com/paritytech/polkadot-sdk/blob/d8df46c7a1488f2358e69368813fd772164c4dac/polkadot/runtime/common/src/claims/mod.rs#L241-L242
#[frame_support::storage_alias(pallet_name)]
pub type Signing<T: pallet_claims::Config> =
StorageMap<pallet_claims::Pallet<T>, Identity, EthereumAddress, StatementKind>;

// From https://github.com/paritytech/polkadot-sdk/blob/d8df46c7a1488f2358e69368813fd772164c4dac/polkadot/runtime/common/src/claims/mod.rs#L245-L246
#[frame_support::storage_alias(pallet_name)]
pub type Preclaims<T: pallet_claims::Config> = StorageMap<
pallet_claims::Pallet<T>,
Identity,
<T as frame_system::Config>::AccountId,
EthereumAddress,
>;

// From https://github.com/paritytech/polkadot-sdk/blob/d8df46c7a1488f2358e69368813fd772164c4dac/polkadot/runtime/common/src/claims/mod.rs#L236-L238
#[frame_support::storage_alias(pallet_name)]
pub type Vesting<T: pallet_claims::Config> = StorageMap<
pallet_claims::Pallet<T>,
Identity,
EthereumAddress,
(BalanceOf<T>, BalanceOf<T>, BlockNumberFor<T>),
>;
}
Loading
Loading