Skip to content

Commit

Permalink
Added Logs and Events for OCW-DAC Validation (#411)
Browse files Browse the repository at this point in the history
## Description
<!-- Describe what change this PR is implementing -->

## Types of Changes
Please select the branch type you are merging and fill in the relevant
template.
<!--- Check the following box with an x if the following applies: -->
- [ ] Hotfix
- [ ] Release
- [ ] Fix or Feature

## Fix or Feature
<!--- Check the following box with an x if the following applies: -->

### Types of Changes
<!--- What types of changes does your code introduce? -->
- [ ] Tech Debt (Code improvements)
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Dependency upgrade (A change in substrate or any 3rd party crate
version)

### Migrations and Hooks
<!--- Check the following box with an x if the following applies: -->
- [ ] This change requires a runtime migration.
- [ ] Modifies `on_initialize`
- [ ] Modifies `on_finalize`

### Checklist for Fix or Feature
<!--- All boxes need to be checked. Follow this checklist before
requiring PR review -->
- [ ] Change has been tested locally.
- [ ] Change adds / updates tests if applicable.
- [ ] Changelog doc updated.
- [ ] `spec_version` has been incremented.
- [ ] `network-relayer`'s
[events](https://github.com/Cerebellum-Network/network-relayer/blob/dev-cere/shared/substrate/events.go)
have been updated according to the blockchain events if applicable.
- [ ] All CI checks have been passed successfully

## Checklist for Hotfix
<!--- All boxes need to be checked. Follow this checklist before
requiring PR review -->
- [ ] Change has been deployed to Testnet.
- [ ] Change has been tested in Testnet.
- [ ] Changelog has been updated.
- [ ] Crate version has been updated.
- [ ] `spec_version` has been incremented.
- [ ] Transaction version has been updated if required.
- [ ] Pull Request to `dev` has been created.
- [ ] Pull Request to `staging` has been created.
- [ ] `network-relayer`'s
[events](https://github.com/Cerebellum-Network/network-relayer/blob/dev-cere/shared/substrate/events.go)
have been updated according to the blockchain events if applicable.
- [ ] All CI checks have been passed successfully

## Checklist for Release
<!--- All boxes need to be checked. Follow this checklist before
requiring PR review -->
- [ ] Change has been deployed to Devnet.
- [ ] Change has been tested in Devnet.
- [ ] Change has been deployed to Qanet.
- [ ] Change has been tested in Qanet.
- [ ] Change has been deployed to Testnet.
- [ ] Change has been tested in Testnet.
- [ ] Changelog has been updated.
- [ ] Crate version has been updated.
- [ ] Spec version has been updated.
- [ ] Transaction version has been updated if required.
- [ ] All CI checks have been passed successfully
  • Loading branch information
ayushmishra2005 authored Aug 7, 2024
1 parent 00eed38 commit 32dbf72
Show file tree
Hide file tree
Showing 10 changed files with 709 additions and 487 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions pallets/ddc-payouts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ frame-benchmarking = { workspace = true, optional = true }
frame-election-provider-support = { workspace = true }
frame-support = { workspace = true }
frame-system = { workspace = true }
hex = { workspace = true }
sp-core = { workspace = true }
sp-io = { workspace = true }
sp-runtime = { workspace = true }
Expand All @@ -39,6 +40,7 @@ substrate-test-utils = { workspace = true, default-features = true }
[features]
default = ["std"]
std = [
"hex/std",
"codec/std",
"ddc-primitives/std",
"frame-support/std",
Expand Down
55 changes: 44 additions & 11 deletions pallets/ddc-payouts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ use frame_support::{
};
use frame_system::pallet_prelude::*;
pub use pallet::*;
use sp_runtime::{traits::Convert, PerThing, Perquintill};
use scale_info::prelude::string::String;
use sp_runtime::{traits::Convert, AccountId32, PerThing, Perquintill};
use sp_std::prelude::*;
/// Stores reward in tokens(units) of node provider as per NodeUsage
#[derive(PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, Default, Clone)]
Expand Down Expand Up @@ -126,6 +127,7 @@ pub mod pallet {
type WeightInfo: WeightInfo;
type VoteScoreToU64: Convert<VoteScoreOf<Self>, u64>;
type ValidatorVisitor: ValidatorVisitor<Self>;
type AccountIdConverter: From<Self::AccountId> + Into<AccountId32>;
}

#[pallet::event]
Expand Down Expand Up @@ -258,6 +260,7 @@ pub mod pallet {
NotBucketOwner,
IncorrectClusterId,
ClusterProtocolParamsNotSet,
TotalStoredBytesLessThanZero,
}

#[pallet::storage]
Expand Down Expand Up @@ -468,7 +471,7 @@ pub mod pallet {

let mut updated_billing_report = billing_report;
for (customer_id, bucket_id, customer_usage) in payers {
log::info!("🏭send_charging_customers_batch get_customer_charge customer_id: {:?} - bucket_id: {:?} - era:{:?} - cluster-id:{:?}", customer_id.encode(), bucket_id, era, cluster_id);
log::info!("🏭send_charging_customers_batch get_customer_charge customer_id: {:?} - bucket_id: {:?} - era:{:?} - cluster-id:{:?}", Self::get_account_id_string(customer_id.clone()), bucket_id, era, cluster_id);
let mut customer_charge = get_customer_charge::<T>(
&cluster_id,
&customer_usage,
Expand Down Expand Up @@ -1084,7 +1087,7 @@ pub mod pallet {
.map_err(Into::<Error<T>>::into)?
.map_or(0, |customer_usage| customer_usage.stored_bytes);

ensure!(total_stored_bytes >= 0, Error::<T>::ArithmeticOverflow);
ensure!(total_stored_bytes >= 0, Error::<T>::TotalStoredBytesLessThanZero);

total_stored_bytes = total_stored_bytes
.checked_add(usage.stored_bytes)
Expand Down Expand Up @@ -1170,7 +1173,10 @@ pub mod pallet {
start_era: i64,
end_era: i64,
) -> DispatchResult {
log::info!("🏭begin_billing_report called by: {:?}", origin.encode());
log::info!(
"🏭begin_billing_report called by: {:?}",
Self::get_account_id_string(origin.clone())
);
let origin = frame_system::RawOrigin::Signed(origin).into();
Self::begin_billing_report(origin, cluster_id, era_id, start_era, end_era)
}
Expand All @@ -1181,7 +1187,10 @@ pub mod pallet {
era_id: DdcEra,
max_batch_index: BatchIndex,
) -> DispatchResult {
log::info!("🏭begin_charging_customers called by: {:?}", origin.encode());
log::info!(
"🏭begin_charging_customers called by: {:?}",
Self::get_account_id_string(origin.clone())
);
let origin = frame_system::RawOrigin::Signed(origin).into();
Self::begin_charging_customers(origin, cluster_id, era_id, max_batch_index)
}
Expand All @@ -1194,7 +1203,10 @@ pub mod pallet {
payers: &[(T::AccountId, BucketId, CustomerUsage)],
batch_proof: MMRProof,
) -> DispatchResult {
log::info!("🏭send_charging_customers_batch called by: {:?}", origin.encode());
log::info!(
"🏭send_charging_customers_batch called by: {:?}",
Self::get_account_id_string(origin.clone())
);
let origin = frame_system::RawOrigin::Signed(origin).into();
Self::send_charging_customers_batch(
origin,
Expand All @@ -1211,7 +1223,10 @@ pub mod pallet {
cluster_id: ClusterId,
era_id: DdcEra,
) -> DispatchResult {
log::info!("🏭end_charging_customers called by: {:?}", origin.encode());
log::info!(
"🏭end_charging_customers called by: {:?}",
Self::get_account_id_string(origin.clone())
);
let origin = frame_system::RawOrigin::Signed(origin).into();
Self::end_charging_customers(origin, cluster_id, era_id)
}
Expand All @@ -1223,7 +1238,10 @@ pub mod pallet {
max_batch_index: BatchIndex,
total_node_usage: NodeUsage,
) -> DispatchResult {
log::info!("🏭begin_rewarding_providers called by: {:?}", origin.encode());
log::info!(
"🏭begin_rewarding_providers called by: {:?}",
Self::get_account_id_string(origin.clone())
);
let origin = frame_system::RawOrigin::Signed(origin).into();
Self::begin_rewarding_providers(
origin,
Expand All @@ -1242,7 +1260,10 @@ pub mod pallet {
payees: &[(T::AccountId, NodeUsage)],
batch_proof: MMRProof,
) -> DispatchResult {
log::info!("🏭send_rewarding_providers_batch called by: {:?}", origin.encode());
log::info!(
"🏭send_rewarding_providers_batch called by: {:?}",
Self::get_account_id_string(origin.clone())
);
let origin = frame_system::RawOrigin::Signed(origin).into();
Self::send_rewarding_providers_batch(
origin,
Expand All @@ -1259,7 +1280,10 @@ pub mod pallet {
cluster_id: ClusterId,
era_id: DdcEra,
) -> DispatchResult {
log::info!("🏭end_rewarding_providers called by: {:?}", origin.encode());
log::info!(
"🏭end_rewarding_providers called by: {:?}",
Self::get_account_id_string(origin.clone())
);
let origin = frame_system::RawOrigin::Signed(origin).into();
Self::end_rewarding_providers(origin, cluster_id, era_id)
}
Expand All @@ -1269,7 +1293,10 @@ pub mod pallet {
cluster_id: ClusterId,
era_id: DdcEra,
) -> DispatchResult {
log::info!("🏭end_billing_report called by: {:?}", origin.encode());
log::info!(
"🏭end_billing_report called by: {:?}",
Self::get_account_id_string(origin.clone())
);
let origin = frame_system::RawOrigin::Signed(origin).into();
Self::end_billing_report(origin, cluster_id, era_id)
}
Expand Down Expand Up @@ -1349,6 +1376,12 @@ pub mod pallet {
T::PalletId::get().into_account_truncating()
}

pub fn get_account_id_string(caller: T::AccountId) -> String {
let account_id: T::AccountIdConverter = caller.into();
let account_id_32: AccountId32 = account_id.into();
let account_ref: &[u8; 32] = account_id_32.as_ref();
hex::encode(account_ref)
}
pub fn sub_account_id(cluster_id: ClusterId, era: DdcEra) -> T::AccountId {
let mut bytes = Vec::new();
bytes.extend_from_slice(&cluster_id[..]);
Expand Down
76 changes: 41 additions & 35 deletions pallets/ddc-payouts/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,16 @@ use sp_io::TestExternalities;
#[cfg(feature = "try-runtime")]
use sp_runtime::TryRuntimeError;
use sp_runtime::{
traits::{BlakeTwo256, Identity, IdentityLookup},
BuildStorage, DispatchError, Perquintill,
traits::{BlakeTwo256, IdentifyAccount, Identity, IdentityLookup, Verify},
BuildStorage, DispatchError, MultiSignature, Perquintill,
};
use sp_std::prelude::*;

use crate::{self as pallet_ddc_payouts, *};

pub type Signature = MultiSignature;
/// The AccountId alias in this test module.
pub type AccountId = u128;
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
pub(crate) type AccountIndex = u64;
pub(crate) type BlockNumber = u64;
pub(crate) type Balance = u128;
Expand Down Expand Up @@ -135,19 +136,25 @@ impl crate::pallet::Config for Test {
type VoteScoreToU64 = Identity;
type WeightInfo = ();
type ValidatorVisitor = MockValidatorVisitor;
type AccountIdConverter = AccountId;
}

pub struct MockValidatorVisitor;

impl<T: Config> ValidatorVisitor<T> for MockValidatorVisitor
where
<T as frame_system::Config>::AccountId: From<u128>,
<T as frame_system::Config>::AccountId: From<AccountId>,
{
fn setup_validators(_validators: Vec<T::AccountId>) {
unimplemented!()
}
fn is_ocw_validator(caller: T::AccountId) -> bool {
let validators = [DAC_ACCOUNT_ID.into(), 123u128.into()];
let account_id: [u8; 32] = [123; 32];
let dac: [u8; 32] = DAC_ACCOUNT_ID;
let validators = [
T::AccountId::decode(&mut &dac[..]).unwrap(),
T::AccountId::decode(&mut &account_id[..]).unwrap(),
];
validators.contains(&caller)
}
fn is_customers_batch_valid(
Expand Down Expand Up @@ -193,15 +200,15 @@ impl<T: Config> CustomerCharger<T> for TestCustomerCharger {
amount: u128,
) -> Result<u128, DispatchError> {
let mut amount_to_charge = amount;
let mut temp = ACCOUNT_ID_1.to_ne_bytes();
let mut temp: [u8; 32] = ACCOUNT_ID_1;
let account_1 = T::AccountId::decode(&mut &temp[..]).unwrap();
temp = ACCOUNT_ID_2.to_ne_bytes();
temp = ACCOUNT_ID_2;
let account_2 = T::AccountId::decode(&mut &temp[..]).unwrap();
temp = ACCOUNT_ID_3.to_ne_bytes();
temp = ACCOUNT_ID_3;
let account_3 = T::AccountId::decode(&mut &temp[..]).unwrap();
temp = ACCOUNT_ID_4.to_ne_bytes();
temp = ACCOUNT_ID_4;
let account_4 = T::AccountId::decode(&mut &temp[..]).unwrap();
temp = ACCOUNT_ID_5.to_ne_bytes();
temp = ACCOUNT_ID_5;
let account_5 = T::AccountId::decode(&mut &temp[..]).unwrap();

if content_owner == account_1 ||
Expand Down Expand Up @@ -233,13 +240,13 @@ impl<T: Config> CustomerCharger<T> for TestCustomerCharger {
}
}

pub const ACCOUNT_ID_1: AccountId = 1;
pub const ACCOUNT_ID_2: AccountId = 2;
pub const ACCOUNT_ID_3: AccountId = 3;
pub const ACCOUNT_ID_4: AccountId = 4;
pub const ACCOUNT_ID_5: AccountId = 5;
pub const ACCOUNT_ID_6: AccountId = 6;
pub const ACCOUNT_ID_7: AccountId = 7;
pub const ACCOUNT_ID_1: [u8; 32] = [1; 32];
pub const ACCOUNT_ID_2: [u8; 32] = [2; 32];
pub const ACCOUNT_ID_3: [u8; 32] = [3; 32];
pub const ACCOUNT_ID_4: [u8; 32] = [4; 32];
pub const ACCOUNT_ID_5: [u8; 32] = [5; 32];
pub const ACCOUNT_ID_6: [u8; 32] = [6; 32];
pub const ACCOUNT_ID_7: [u8; 32] = [7; 32];
pub struct TestClusterCreator;
impl<T: Config> ClusterCreator<T, Balance> for TestClusterCreator {
fn create_cluster(
Expand All @@ -263,12 +270,12 @@ impl<T: Config> CustomerDepositor<T> for TestCustomerDepositor {
}
}

pub const DAC_ACCOUNT_ID: AccountId = 2;
pub const RESERVE_ACCOUNT_ID: AccountId = 999;
pub const TREASURY_ACCOUNT_ID: AccountId = 888;
pub const VALIDATOR1_ACCOUNT_ID: AccountId = 111;
pub const VALIDATOR2_ACCOUNT_ID: AccountId = 222;
pub const VALIDATOR3_ACCOUNT_ID: AccountId = 333;
pub const DAC_ACCOUNT_ID: [u8; 32] = [2; 32];
pub const RESERVE_ACCOUNT_ID: [u8; 32] = [9; 32];
pub const TREASURY_ACCOUNT_ID: [u8; 32] = [8; 32];
pub const VALIDATOR1_ACCOUNT_ID: [u8; 32] = [111; 32];
pub const VALIDATOR2_ACCOUNT_ID: [u8; 32] = [222; 32];
pub const VALIDATOR3_ACCOUNT_ID: [u8; 32] = [250; 32];

pub const VALIDATOR1_SCORE: u64 = 30;
pub const VALIDATOR2_SCORE: u64 = 45;
Expand Down Expand Up @@ -358,14 +365,13 @@ pub const PRICING_FEES_ZERO: ClusterFeesParams = ClusterFeesParams {
pub struct TestTreasuryVisitor;
impl<T: frame_system::Config> PalletVisitor<T> for TestTreasuryVisitor {
fn get_account_id() -> T::AccountId {
let reserve_account = TREASURY_ACCOUNT_ID.to_ne_bytes();
let reserve_account: [u8; 32] = TREASURY_ACCOUNT_ID;
T::AccountId::decode(&mut &reserve_account[..]).unwrap()
}
}

fn create_account_id_from_u128<T: frame_system::Config>(id: u128) -> T::AccountId {
let bytes = id.to_ne_bytes();
T::AccountId::decode(&mut &bytes[..]).unwrap()
fn create_account_id_from_u128<T: frame_system::Config>(id: [u8; 32]) -> T::AccountId {
T::AccountId::decode(&mut &id[..]).unwrap()
}

pub struct TestValidatorVisitor<T>(sp_std::marker::PhantomData<T>);
Expand Down Expand Up @@ -521,7 +527,7 @@ impl<T: Config> ClusterProtocol<T, BalanceOf<T>> for TestClusterProtocol {
}

fn get_reserve_account_id(_cluster_id: &ClusterId) -> Result<T::AccountId, DispatchError> {
let reserve_account = RESERVE_ACCOUNT_ID.to_ne_bytes();
let reserve_account: [u8; 32] = RESERVE_ACCOUNT_ID;
Ok(T::AccountId::decode(&mut &reserve_account[..]).unwrap())
}

Expand Down Expand Up @@ -561,13 +567,13 @@ impl ExtBuilder {

let _balance_genesis = pallet_balances::GenesisConfig::<Test> {
balances: vec![
(1, 10000000000000000000000000000),
(2, USER2_BALANCE), // < PARTIAL_CHARGE
(3, USER3_BALANCE), // > PARTIAL_CHARGE
(4, 1000000000000000000000000),
(5, 1000000000000000000000000),
(6, 1000000000000000000000000),
(7, 1000000000000000000000000),
([1; 32].into(), 10000000000000000000000000000),
([2; 32].into(), USER2_BALANCE), // < PARTIAL_CHARGE
([3; 32].into(), USER3_BALANCE), // > PARTIAL_CHARGE
([4; 32].into(), 1000000000000000000000000),
([5; 32].into(), 1000000000000000000000000),
([6; 32].into(), 1000000000000000000000000),
([7; 32].into(), 1000000000000000000000000),
],
}
.assimilate_storage(&mut storage);
Expand Down
Loading

0 comments on commit 32dbf72

Please sign in to comment.