Skip to content

Commit

Permalink
Merge branch 'machine-info'
Browse files Browse the repository at this point in the history
  • Loading branch information
ytbiu committed Jun 27, 2024
2 parents 5203d87 + 670304c commit 1068d73
Show file tree
Hide file tree
Showing 12 changed files with 548 additions and 5 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.

50 changes: 50 additions & 0 deletions docs/dev/errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# pallet errors

## rentMachine:
* AccountAlreadyExist, - account already exist
* MachineNotRentable, - machine not rentable
* Overflow, - overflow
* InsufficientValue, - has insufficient value to pay or reserve
* ExpiredConfirm, - confirm expired
* NoOrderExist, - order not exist
* StatusNotAllowed, - when confirm a rent order, the machine is not online or rented
* UnlockToPayFeeFailed, - pay rent fee failed
* UndefinedRentPot, - the target which rent fee should be paid to is not defined
* PayTxFeeFailed, - pay rent tx fee failed
* GetMachinePriceFailed, - get machine price failed
* OnlyHalfHourAllowed, - rent duration must be an integer multiple of 30 minutes
* GPUNotEnough, - free GPU not enough
* NotMachineRenter, - not machine renter
* Unknown, - machine or rent info not fount
* ReletTooShort, - Renewal duration too short, at least for 10 minutes or more


## onlineProfile:
* BadSignature, - signature verification failed
* MachineIdExist, - machine id already exist
* BalanceNotEnough, - balance not enough
* NotMachineController, - not machine controller
* PayTxFeeFailed, - pay tx fee failed when bond a machine or generate a new seerver room
* ClaimRewardFailed, - claim reward failed
* ConvertMachineIdToWalletFailed, - check bonding singature message failed
* NoStashBond, - stash account not bond
* AlreadyController, - the account is already controller
* NoStashAccount, - stash account not exist
* BadMsgLen, - bad message length when checking bonding singature message
* NotAllowedChangeMachineInfo, - not allowed to change machine info
* MachineStashNotEqualControllerStash, - machine stash not equal controller stash
* CalcStakeAmountFailed, - calculate stake amount failed
* SigMachineIdNotEqualBondedMachineId, - signature machine id not equal bonded machine id when checking bonding singature message
* TelecomIsNull, - telecom is not found
* MachineStatusNotAllowed, - machine status not allowed to change
* ServerRoomNotFound, - server room not found
* NotMachineStash, - not machine stash
* TooFastToReStake, - too fast to re stake, should more than 1 year
* NoStakeToReduce, - no stake to reduce
* ReduceStakeFailed, - reduce stake failed
* GetReonlineStakeFailed, - get re online stake failed
* SlashIdNotExist, - slash id not exist
* TimeNotAllowed, - machine online time less than 1 year can not be exit
* ExpiredSlash, - slash expired
* Unknown, - machine not found / pendding slash not found
* ClaimThenFulfillFailed, - failed to supplement the insufficient reserve amount when claim reward
50 changes: 50 additions & 0 deletions docs/dev/machine_status_changed_events.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# machine status changed events

* MachineExit(MachineId) - triggered when a machine exits the system.
* MachineOfflineToMutHardware(MachineId, BalanceOf<T>, BalanceOf<T>) - triggered when a machine transitions from online to offline to mutual hardware.
* ControllerReportOffline(MachineId), - triggered when a machine is reported to offline by a controller.
* ControllerReportOnline(MachineId), - triggered when a machine is reported to online by a controller.
* BondMachine(T::AccountId, MachineId, BalanceOf<T>), - triggered when a new machine is bonded to an account.
* ConfirmRent(RentOrderId, T::AccountId, MachineId, u32, T::BlockNumber, BalanceOf<T>) - triggered when a rent order is confirmed.


# you can subscribe to these events using the following js code:

```javascript
// Import the API
const { ApiPromise, WsProvider } = require('@polkadot/api');

async function main () {
const wsProvider = new WsProvider('ws://127.0.0.1:8000');

const api = await ApiPromise.create({provider:wsProvider});

// Subscribe to system events via storage
api.query.system.events((events) => {
console.log(`\nReceived ${events.length} events:`);

// Loop through the Vec<EventRecord>
events.forEach((record) => {
console.log(`new event received`);

// Extract the event
const {event} = record;
// Show what we are busy with
console.log(`\t${event.section}:${event.method}`);
if (event.section === 'rentMachine' && event.method === 'ConfirmRent') {
console.log(`\tfind Rent confirmed for machine`);

// Extract the event types
const types = event.typeDef;

// Loop through each of the parameters, displaying the type and data
event.data.forEach((data, index) => {
console.log(` ${types[index].type}: ${data.toString()}`);
});
}
});
});
}

```
useful link: https://polkadot.js.org/docs/api/examples/promise/system-events
1 change: 1 addition & 0 deletions pallets/online-profile/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ sp-core = { workspace = true }

dbc-support = { path = "../support", default-features = false }
generic-func = { path = "../generic-func", default-features = false }
log = { workspace = true }

[dev-dependencies]

Expand Down
38 changes: 36 additions & 2 deletions pallets/online-profile/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ mod traits;
mod types;
mod utils;

pub mod migration;
use dbc_support::{
live_machine::LiveMachine,
machine_info::MachineInfo,
Expand Down Expand Up @@ -49,6 +50,8 @@ type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<
<T as frame_system::Config>::AccountId,
>>::NegativeImbalance;

use frame_support::traits::StorageVersion;
const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
#[frame_support::pallet]
pub mod pallet {
use super::*;
Expand All @@ -71,6 +74,7 @@ pub mod pallet {
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
#[pallet::without_storage_info]
#[pallet::storage_version(STORAGE_VERSION)]
pub struct Pallet<T>(_);

#[pallet::storage]
Expand Down Expand Up @@ -1119,6 +1123,37 @@ pub mod pallet {
MaxSlashExeced::<T>::insert(machine_id, now);
Ok(().into())
}

#[pallet::call_index(19)]
#[pallet::weight(10000)]
pub fn update_machine_info(
origin: OriginFor<T>,
machine_id: MachineId,
server_room_info: StakerCustomizeInfo,
) -> DispatchResultWithPostInfo {
let controller = ensure_signed(origin)?;
// check if the machine id is under control of the account
let machine_info = Self::machines_info(&machine_id).ok_or(Error::<T>::Unknown)?;
machine_info
.can_update_server_room_info(&controller)
.map_err::<Error<T>, _>(Into::into)?;

let stash_server_rooms = Self::stash_server_rooms(&machine_info.machine_stash);
ensure!(!server_room_info.telecom_operators.is_empty(), Error::<T>::TelecomIsNull);
ensure!(
stash_server_rooms.binary_search(&server_room_info.server_room).is_ok(),
Error::<T>::ServerRoomNotFound
);

MachinesInfo::<T>::try_mutate(&machine_id, |machine_info| {
let machine_info = machine_info.as_mut().ok_or(Error::<T>::Unknown)?;
machine_info.add_server_room_info(server_room_info);
Ok::<(), DispatchError>(())
})?;

Self::deposit_event(Event::MachineInfoUpdated(machine_id));
Ok(().into())
}
}

#[pallet::event]
Expand All @@ -1136,6 +1171,7 @@ pub mod pallet {
StakeReduced(T::AccountId, BalanceOf<T>),
ServerRoomGenerated(T::AccountId, H256),
MachineInfoAdded(MachineId),
MachineInfoUpdated(MachineId),
ClaimReward(T::AccountId, BalanceOf<T>),
ControllerReportOffline(MachineId),
ControllerReportOnline(MachineId),
Expand All @@ -1162,7 +1198,6 @@ pub mod pallet {
BalanceNotEnough,
NotMachineController,
PayTxFeeFailed,
RewardPhaseOutOfRange,
ClaimRewardFailed,
ConvertMachineIdToWalletFailed,
NoStashBond,
Expand All @@ -1172,7 +1207,6 @@ pub mod pallet {
NotAllowedChangeMachineInfo,
MachineStashNotEqualControllerStash,
CalcStakeAmountFailed,
NotRefusedMachine,
SigMachineIdNotEqualBondedMachineId,
TelecomIsNull,
MachineStatusNotAllowed,
Expand Down
192 changes: 192 additions & 0 deletions pallets/online-profile/src/migration.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@

use frame_support::{pallet_prelude::*, storage_alias, traits::{OnRuntimeUpgrade,StorageInstance}};
use Config;

use crate::*;
use sp_std::prelude::*;

const TARGET: &'static str = "online-profile-migration";


type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
type BlockNumberOf<T> = <T as frame_system::Config>::BlockNumber;

mod v0{
use frame_support::dispatch::{Decode, Encode, TypeInfo};
use frame_support::{RuntimeDebug};
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_core::H256;
use dbc_support::EraIndex;
use dbc_support::machine_type::{CommitteeUploadInfo, Latitude, Longitude, MachineStatus};

#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
pub struct MachineInfo<AccountId: Ord, BlockNumber, Balance> {
/// Who can control this machine
pub controller: AccountId,
/// Who own this machine and will get machine's reward
pub machine_stash: AccountId,
/// Last machine renter
pub renters: Vec<AccountId>,
/// Every 365 days machine can restake(For token price maybe changed)
pub last_machine_restake: BlockNumber,
/// When controller bond this machine
pub bonding_height: BlockNumber,
/// When machine is passed verification and is online
pub online_height: BlockNumber,
/// Last time machine is online
/// (When first online; Rented -> Online, Offline -> Online e.t.)
pub last_online_height: BlockNumber,
/// When first bond_machine, record how much should stake per GPU
pub init_stake_per_gpu: Balance,
/// How much machine staked
pub stake_amount: Balance,
/// Status of machine
pub machine_status: MachineStatus<BlockNumber, AccountId>,
/// How long machine has been rented(will be update after one rent is end)
/// NOTE: 单位从天改为BlockNumber
pub total_rented_duration: BlockNumber,
/// How many times machine has been rented
pub total_rented_times: u64,
/// How much rent fee machine has earned for rented(before Galaxy is ON)
pub total_rent_fee: Balance,
/// How much rent fee is burn after Galaxy is ON
pub total_burn_fee: Balance,
/// Machine's hardware info
pub machine_info_detail: MachineInfoDetail,
/// Committees, verified machine and will be rewarded in the following days.
/// (After machine is online, get 1% rent fee)
pub reward_committee: Vec<AccountId>,
/// When reward will be over for committees
pub reward_deadline: EraIndex,
}

#[derive(Debug, PartialEq, Eq, Clone, Encode, Decode, Default, TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct MachineInfoDetail {
pub committee_upload_info: CommitteeUploadInfo,
pub staker_customize_info: StakerCustomizeInfo,
}

#[derive(Debug, PartialEq, Eq, Clone, Encode, Decode, Default, TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct StakerCustomizeInfo {
pub server_room: H256,
/// 上行带宽
pub upload_net: u64,
/// 下行带宽
pub download_net: u64,
/// 经度(+东经; -西经)
pub longitude: Longitude,
/// 纬度(+北纬; -南纬)
pub latitude: Latitude,
/// 网络运营商
pub telecom_operators: Vec<Vec<u8>>,
}


use super::*;
#[storage_alias]
pub type OldMachinesInfo<T: Config> = StorageMap<
Pallet<T>,
Blake2_128Concat,
MachineId,
MachineInfo< AccountIdOf<T>,BlockNumberOf<T>, BalanceOf<T>>,
>;

}
pub mod v1{
use frame_support::migration::{storage_iter, storage_key_iter};
use frame_support::traits::Len;
use dbc_support::machine_type::MachineInfoDetail;
use super::*;

pub struct Migration<T>(PhantomData<T>);
impl <T: Config > OnRuntimeUpgrade for Migration<T> {
fn on_runtime_upgrade() -> Weight {
migrate::<T>()
}

#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, &'static str> {
log::info!("pre_upgrade ok");
let current_version = Pallet::<T>::current_storage_version();
let on_chain_version = Pallet::<T>::on_chain_storage_version();

log::info!("c : {:?} ",current_version);
log::info!("o : {:?}",on_chain_version);

ensure!(on_chain_version == 0, "this migration can be deleted");
Ok(Vec::new())
}

#[cfg(feature = "try-runtime")]
fn post_upgrade(_state: Vec<u8>) -> Result<(), &'static str> {
let on_chain_version = Pallet::<T>::on_chain_storage_version();

ensure!(on_chain_version == 1, "this migration needs to be removed");

log::info!("post_upgrade ok");
Ok(())
}
}


pub fn migrate<T:Config>() -> Weight {
let on_chain_version = Pallet::<T>::on_chain_storage_version();
let current_version = Pallet::<T>::current_storage_version();
let mut weight = T::DbWeight::get().reads(2);

if on_chain_version == 0 && current_version == 1{
log::info!(target: TARGET,"migrate executing");

MachinesInfo::<T>::translate(
|index, old: v0::MachineInfo<AccountIdOf<T>, BlockNumberOf<T>, BalanceOf<T>>| {
weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));

let new_machine_info = MachineInfo{
controller: old.controller,
machine_stash: old.machine_stash,
renters: old.renters,
last_machine_restake: old.last_machine_restake,
bonding_height:old.bonding_height,
online_height: old.online_height,
last_online_height: old.last_online_height,
init_stake_per_gpu: old.init_stake_per_gpu,
stake_amount: old.stake_amount,
machine_status: old.machine_status,
total_rented_duration: old.total_rented_duration,
total_rented_times: old.total_rented_times,
total_rent_fee: old.total_rent_fee,
total_burn_fee: old.total_burn_fee,
machine_info_detail: MachineInfoDetail{
staker_customize_info: StakerCustomizeInfo{
server_room: old.machine_info_detail.staker_customize_info.server_room,
upload_net: old.machine_info_detail.staker_customize_info.upload_net,
download_net: old.machine_info_detail.staker_customize_info.download_net,
longitude: old.machine_info_detail.staker_customize_info.longitude,
latitude: old.machine_info_detail.staker_customize_info.latitude,
telecom_operators: old.machine_info_detail.staker_customize_info.telecom_operators,
is_bare_machine: false,

},
committee_upload_info: old.machine_info_detail.committee_upload_info,


},

reward_committee: old.reward_committee,
reward_deadline: old.reward_deadline,
};
Some(new_machine_info)
},
);
current_version.put::<Pallet<T>>()
}

log::info!("migrate ok");
weight
}
}
Loading

0 comments on commit 1068d73

Please sign in to comment.