diff --git a/Cargo.lock b/Cargo.lock index e61941ab..ad717c69 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -104,33 +104,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "ai-project-register" -version = "4.0.0-dev" -dependencies = [ - "committee", - "dbc-price-ocw", - "dbc-support", - "env_logger 0.11.5", - "frame-support", - "frame-system", - "generic-func", - "hex", - "online-profile", - "pallet-balances", - "pallet-collective", - "pallet-insecure-randomness-collective-flip", - "pallet-timestamp", - "parity-scale-codec", - "rent-machine", - "scale-info", - "sp-core", - "sp-io", - "sp-keyring", - "sp-runtime", - "sp-std", -] - [[package]] name = "allocator-api2" version = "0.2.18" @@ -1546,7 +1519,6 @@ dependencies = [ "pallet-transaction-payment-rpc", "parity-scale-codec", "rand 0.7.3", - "rent-dlc-machine-rpc", "rent-machine-rpc", "sc-authority-discovery", "sc-basic-authorship", @@ -1891,7 +1863,6 @@ dependencies = [ name = "dbc-runtime" version = "4.0.0-dev" dependencies = [ - "ai-project-register", "array-bytes", "committee", "committee-runtime-api", @@ -1903,7 +1874,6 @@ dependencies = [ "dbc-primitives-rpc-evm-tracing-events", "dbc-primitives-rpc-txpool", "dbc-support", - "dlc-machine", "ethabi", "evm-macro", "fp-evm", @@ -1918,7 +1888,6 @@ dependencies = [ "frame-system-rpc-runtime-api", "frame-try-runtime", "generic-func", - "hex", "log", "maintain-committee", "num_enum 0.5.11", @@ -1979,8 +1948,6 @@ dependencies = [ "pallet-treasury", "pallet-utility", "parity-scale-codec", - "rent-dlc-machine", - "rent-dlc-machine-runtime-api", "rent-machine", "rent-machine-runtime-api", "scale-info", @@ -2177,33 +2144,6 @@ dependencies = [ "syn 2.0.79", ] -[[package]] -name = "dlc-machine" -version = "4.0.0-dev" -dependencies = [ - "committee", - "dbc-price-ocw", - "dbc-support", - "env_logger 0.11.5", - "frame-support", - "frame-system", - "generic-func", - "hex", - "online-profile", - "pallet-balances", - "pallet-collective", - "pallet-insecure-randomness-collective-flip", - "pallet-timestamp", - "parity-scale-codec", - "rent-machine", - "scale-info", - "sp-core", - "sp-io", - "sp-keyring", - "sp-runtime", - "sp-std", -] - [[package]] name = "dotenvy" version = "0.15.7" @@ -2427,15 +2367,6 @@ dependencies = [ "syn 2.0.79", ] -[[package]] -name = "env_filter" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f2c92ceda6ceec50f43169f9ee8424fe2db276791afde7b2cd8bc084cb376ab" -dependencies = [ - "log", -] - [[package]] name = "env_logger" version = "0.10.2" @@ -2449,16 +2380,6 @@ dependencies = [ "termcolor", ] -[[package]] -name = "env_logger" -version = "0.11.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13fa619b91fb2381732789fc5de83b45675e882f66623b7d8cb4f643017018d" -dependencies = [ - "env_filter", - "log", -] - [[package]] name = "environmental" version = "1.1.4" @@ -2866,7 +2787,7 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "84f2e425d9790201ba4af4630191feac6dcc98765b118d4d18e91d23c2353866" dependencies = [ - "env_logger 0.10.2", + "env_logger", "log", ] @@ -5142,7 +5063,6 @@ dependencies = [ "committee", "dbc-price-ocw", "dbc-support", - "dlc-machine", "frame-support", "frame-system", "generic-func", @@ -5150,14 +5070,12 @@ dependencies = [ "once_cell", "online-committee", "online-profile", - "pallet-assets", "pallet-balances", "pallet-collective", "pallet-insecure-randomness-collective-flip", "pallet-timestamp", "pallet-treasury", "parity-scale-codec", - "rent-dlc-machine", "rent-machine", "scale-info", "sp-core", @@ -7731,62 +7649,6 @@ version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" -[[package]] -name = "rent-dlc-machine" -version = "4.0.0-dev" -dependencies = [ - "committee", - "dbc-price-ocw", - "dbc-primitives", - "dbc-support", - "dlc-machine", - "frame-support", - "frame-system", - "generic-func", - "hex", - "once_cell", - "online-committee", - "online-profile", - "pallet-assets", - "pallet-balances", - "pallet-collective", - "pallet-insecure-randomness-collective-flip", - "pallet-timestamp", - "pallet-treasury", - "parity-scale-codec", - "rent-machine", - "scale-info", - "sp-core", - "sp-io", - "sp-keyring", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "rent-dlc-machine-rpc" -version = "4.0.0-dev" -dependencies = [ - "dbc-support", - "jsonrpsee", - "parity-scale-codec", - "rent-dlc-machine-runtime-api", - "sp-api", - "sp-blockchain", - "sp-runtime", -] - -[[package]] -name = "rent-dlc-machine-runtime-api" -version = "4.0.0-dev" -dependencies = [ - "dbc-support", - "parity-scale-codec", - "sp-api", - "sp-runtime", - "sp-std", -] - [[package]] name = "rent-machine" version = "4.0.0-dev" diff --git a/Cargo.toml b/Cargo.toml index 3019d1ab..a516e6fe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,11 +43,6 @@ members = [ "pallets/council-reward", "pallets/nfts", "runtime/src/precompiles/macro", - "pallets/ai-project-register", - "pallets/dlc-machine", - "pallets/rent-dlc-machine", - "pallets/rent-dlc-machine/rpc", - "pallets/rent-dlc-machine/rpc/runtime-api", ] [workspace.dependencies] diff --git a/node/cli/Cargo.toml b/node/cli/Cargo.toml index 52cefb1c..64235c45 100644 --- a/node/cli/Cargo.toml +++ b/node/cli/Cargo.toml @@ -102,7 +102,6 @@ committee-rpc = { path = "../../pallets/committee/rpc" } online-committee-rpc = { path = "../../pallets/online-committee/rpc" } online-profile-rpc = { path = "../../pallets/online-profile/rpc" } rent-machine-rpc = { path = "../../pallets/rent-machine/rpc" } -rent-dlc-machine-rpc = { path = "../../pallets/rent-dlc-machine/rpc" } simple-rpc-rpc = { path = "../../pallets/simple-rpc/rpc" } terminating-rental-rpc = { path = "../../pallets/terminating-rental/rpc" } diff --git a/node/cli/src/rpc.rs b/node/cli/src/rpc.rs index 2ef31949..348da35d 100644 --- a/node/cli/src/rpc.rs +++ b/node/cli/src/rpc.rs @@ -65,7 +65,6 @@ where C::Api: online_committee_rpc::OcStorageRuntimeApi, C::Api: rent_machine_rpc::RmStorageRuntimeApi, C::Api: terminating_rental_rpc::IrStorageRuntimeApi, - C::Api: rent_dlc_machine_rpc::RmDlcStorageRuntimeApi, { use dbc_client_rpc_debug::{Debug, DebugServer}; use dbc_client_rpc_trace::{Trace, TraceServer}; @@ -82,7 +81,6 @@ where use committee_rpc::{CmRpcApiServer, CmStorage}; use online_committee_rpc::{OcRpcApiServer, OcStorage}; use online_profile_rpc::{OpRpcApiServer, OpStorage}; - use rent_dlc_machine_rpc::{DlcRmRpcApiServer, DlcRmStorage}; use rent_machine_rpc::{RmRpcApiServer, RmStorage}; use simple_rpc_rpc::{SimpleRpcApiServer, SrStorage}; use terminating_rental_rpc::{IrRpcApiServer, IrStorage}; @@ -148,8 +146,6 @@ where io.merge(OpStorage::new(client.clone()).into_rpc()).ok(); io.merge(RmStorage::new(client.clone()).into_rpc()).ok(); io.merge(IrStorage::new(client.clone()).into_rpc()).ok(); - io.merge(DlcRmStorage::new(client.clone()).into_rpc()).ok(); - io.merge( EthFilter::new( client.clone(), diff --git a/pallets/ai-project-register/Cargo.toml b/pallets/ai-project-register/Cargo.toml deleted file mode 100644 index 054e8715..00000000 --- a/pallets/ai-project-register/Cargo.toml +++ /dev/null @@ -1,57 +0,0 @@ -[package] -name = "ai-project-register" -version = { workspace = true } -authors = { workspace = true } -edition = "2021" -repository = { workspace = true } - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -parity-scale-codec = { workspace = true } -scale-info = { workspace = true } -sp-std = { workspace = true } -# Needed for various traits. In our case, `OnFinalize`. -# Needed for type-safe access to storage DB. -frame-support = { workspace = true } -sp-core = { workspace = true } - -# `system` module provides us with all sorts of useful stuff and macros depend on it being around. -frame-system = { workspace = true } -dbc-support = { path = "../support", default-features = false } -rent-machine = { path = "../rent-machine", default-features = false } - -[dev-dependencies] -sp-std = { workspace = true, features = ["std"] } -sp-io = { workspace = true, features = ["std"] } -pallet-timestamp = { workspace = true } -pallet-insecure-randomness-collective-flip = { workspace = true, features = ["std"] } -pallet-collective = { workspace = true, features = ["std"] } -pallet-balances = { workspace = true, features = ["std"] } -dbc-price-ocw = { path = "../dbc-price-ocw", default-features = false } -generic-func = { path = "../generic-func", default-features = false } -committee = { path = "../committee" } -online-profile = { path = "../online-profile", default-features = false } - -hex = { workspace = true } -sp-keyring = { workspace = true } -sp-runtime = { workspace = true } -env_logger = { workspace = true } - -[features] -default = ["std"] -std = [ - "sp-io/std", - "parity-scale-codec/std", - "scale-info/std", - "sp-std/std", - "frame-support/std", - "frame-system/std", - "pallet-balances/std", - "pallet-insecure-randomness-collective-flip/std", - "pallet-collective/std", - "sp-runtime/std", - "online-profile/std" -] -try-runtime = ["frame-support/try-runtime"] diff --git a/pallets/ai-project-register/src/lib.rs b/pallets/ai-project-register/src/lib.rs deleted file mode 100644 index 714222a8..00000000 --- a/pallets/ai-project-register/src/lib.rs +++ /dev/null @@ -1,206 +0,0 @@ -#![recursion_limit = "256"] -#![cfg_attr(not(feature = "std"), no_std)] -#![warn(unused_crate_dependencies)] -extern crate core; - -#[cfg(test)] -mod mock; -#[allow(non_upper_case_globals)] -#[cfg(test)] -mod tests; - -use frame_support::pallet_prelude::*; - -use frame_system::pallet_prelude::*; -use sp_std::{prelude::*, vec, vec::Vec}; - -use dbc_support::{ - traits::ProjectRegister, - utils::{account_id, verify_signature}, - MachineId, -}; -pub use pallet::*; -use rent_machine::Error as RentMachineError; - -#[frame_support::pallet] -pub mod pallet { - use super::*; - - #[pallet::config] - pub trait Config: frame_system::Config + rent_machine::Config { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; - } - - #[pallet::type_value] - pub(super) fn MaxLimitPerMachineIdCanRegisterDefault() -> u32 { - 3 - } - #[pallet::storage] - #[pallet::getter(fn max_limit_per_machine_id_can_register)] - pub(super) type MaxLimitPerMachineIdCanRegister = - StorageValue<_, u32, ValueQuery, MaxLimitPerMachineIdCanRegisterDefault>; - - // machine_id=> registered_ai_project_name - #[pallet::storage] - #[pallet::getter(fn machine_id_to_ai_project_name)] - pub(super) type MachineId2AIProjectName = - StorageMap<_, Blake2_128Concat, MachineId, Vec>, ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn projec_machine_to_unregistered_times)] - pub(super) type ProjectMachine2UnregisteredTimes = StorageDoubleMap< - _, - Blake2_128Concat, - Vec, - Blake2_128Concat, - MachineId, - ::BlockNumber, - ValueQuery, - >; - - #[pallet::storage] - #[pallet::getter(fn registered_info_to_owner)] - pub(super) type RegisteredInfo2Owner = - StorageDoubleMap<_, Blake2_128Concat, MachineId, Blake2_128Concat, Vec, T::AccountId>; - - #[pallet::error] - pub enum Error { - OverLimitPerMachineIdCanRegister, - MachineNotRegistered, - NotRegisteredInfoOwner, - ProjectNotRegistered, - } - - #[pallet::pallet] - #[pallet::without_storage_info] - pub struct Pallet(_); - - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { - AddMachineRegisteredProject(MachineId, Vec, T::AccountId), - RemoveMachineRegisteredProject( - MachineId, - Vec, - ::BlockNumber, - ), - SignatureVerifyResult(bool), - } - - #[pallet::call] - impl Pallet { - #[pallet::call_index(0)] - #[pallet::weight(Weight::from_parts(10000, 0))] - pub fn set_max_limit_per_machine_id_can_register( - origin: OriginFor, - value: u32, - ) -> DispatchResultWithPostInfo { - let _who = ensure_root(origin)?; - MaxLimitPerMachineIdCanRegister::::mutate(|v| *v = value); - Ok(().into()) - } - } -} - -impl ProjectRegister for Pallet { - fn is_registered(machine_id: MachineId, project_name: Vec) -> bool { - Self::machine_id_to_ai_project_name(&machine_id).contains(&project_name) - } - - fn add_machine_registered_project( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, - machine_id: MachineId, - project_name: Vec, - ) -> Result<(), &'static str> { - let ok = verify_signature(data, sig, from.clone()); - if !ok { - return Err(RentMachineError::::SignVerifiedFailed.as_str()) - }; - - let who = account_id::(from.clone())?; - - let rent_ids = >::get_rent_ids(machine_id.clone(), &who); - if rent_ids.len() == 0 { - return Err(RentMachineError::::MachineNotRented.as_str()) - } - - if !MachineId2AIProjectName::::contains_key(&machine_id) { - MachineId2AIProjectName::::insert(&machine_id, vec![&project_name]); - } else { - let mut project_names = Self::machine_id_to_ai_project_name(&machine_id); - let projects_num = project_names.len() as u32; - if projects_num >= Self::max_limit_per_machine_id_can_register() { - return Err(Error::::OverLimitPerMachineIdCanRegister.as_str()) - } - - if project_names.contains(&project_name) { - return Ok(().into()) - } - project_names.push(project_name.clone()); - MachineId2AIProjectName::::insert(&machine_id, project_names); - } - RegisteredInfo2Owner::::insert(&machine_id, &project_name, &who); - Self::deposit_event(Event::AddMachineRegisteredProject(machine_id, project_name, who)); - Ok(().into()) - } - - fn remove_machine_registered_project( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, - machine_id: MachineId, - project_name: Vec, - ) -> Result<(), &'static str> { - let ok = verify_signature(data, sig, from.clone()); - if !ok { - return Err(RentMachineError::::SignVerifiedFailed.as_str()) - }; - - let who = account_id::(from.clone())?; - let owner = Self::registered_info_to_owner(&machine_id, &project_name) - .ok_or(Error::::MachineNotRegistered.as_str())?; - if who != owner { - return Err(Error::::MachineNotRegistered.as_str()) - } - - if !MachineId2AIProjectName::::contains_key(&machine_id) { - return Err(Error::::MachineNotRegistered.as_str()) - } - let project_names = Self::machine_id_to_ai_project_name(&machine_id); - if !project_names.contains(&project_name) { - return Err(Error::::ProjectNotRegistered.as_str()) - } - - MachineId2AIProjectName::::mutate(&machine_id, |project_names| { - project_names - .into_iter() - .position(|x| *x == project_name) - .map(|i| project_names.remove(i)); - }); - - let now = >::block_number(); - ProjectMachine2UnregisteredTimes::::insert(&project_name, &machine_id, now); - RegisteredInfo2Owner::::remove(&machine_id, &project_name); - Self::deposit_event(Event::RemoveMachineRegisteredProject(machine_id, project_name, now)); - Ok(().into()) - } - - fn is_registered_machine_owner( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, - machine_id: MachineId, - project_name: Vec, - ) -> Result { - let ok = verify_signature(data, sig, from.clone()); - if !ok { - return Err(RentMachineError::::SignVerifiedFailed.as_str()) - }; - let owner = Self::registered_info_to_owner(machine_id, project_name) - .ok_or(Error::::MachineNotRegistered.as_str())?; - let who = account_id::(from.clone())?; - Ok(owner == who) - } -} diff --git a/pallets/ai-project-register/src/mock.rs b/pallets/ai-project-register/src/mock.rs deleted file mode 100644 index ea9bd2a6..00000000 --- a/pallets/ai-project-register/src/mock.rs +++ /dev/null @@ -1,206 +0,0 @@ -use crate as ai_project_register; - -use frame_support::{pallet_prelude::ConstU32, parameter_types, weights::Weight}; -use frame_system::EnsureRoot; -use sp_core::{sr25519, sr25519::Signature, H256}; -use sp_runtime::{ - testing::{Header, TestXt}, - traits::{BlakeTwo256, IdentityLookup, Verify}, -}; - -type Block = frame_system::mocking::MockBlock; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; - -// Configure a mock runtime to test the pallet. -frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system, - Timestamp: pallet_timestamp, - AiProjectRegister: ai_project_register::{Pallet, Call, Storage, Event}, - Balances: pallet_balances, - OnlineProfile: online_profile, - DBCPriceOCW: dbc_price_ocw, - GenericFunc: generic_func, - RandomnessCollectiveFlip: pallet_insecure_randomness_collective_flip, - Committee: committee, - TechnicalCommittee: pallet_collective::, - RentMachine: rent_machine::{Pallet, Call, Storage, Event}, - - } -); - -impl frame_system::Config for Test { - type BaseCallFilter = (); - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = sr25519::Public; - type Lookup = IdentityLookup; - type Header = Header; - type RuntimeEvent = RuntimeEvent; - type BlockHashCount = (); - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); - type OnSetCode = (); - type MaxConsumers = ConstU32<16>; -} - -parameter_types! { - pub const BlockPerEra: u32 = 3600 * 24 / 30; -} - -impl generic_func::Config for Test { - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - type RandomnessSource = RandomnessCollectiveFlip; - type FixedTxFee = (); - type Slash = (); -} - -impl committee::Config for Test { - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - // type WeightInfo = (); -} - -impl pallet_insecure_randomness_collective_flip::Config for Test {} - -impl dbc_price_ocw::Config for Test { - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - type RandomnessSource = RandomnessCollectiveFlip; -} - -type TechnicalCollective = pallet_collective::Instance2; - -parameter_types! { - pub const CouncilMotionDuration: u32 = 5 * 2880; - pub const CouncilMaxProposals: u32 = 100; - pub const CouncilMaxMembers: u32 = 100; - pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights::simple_max(Weight::MAX); - pub MaxProposalWeight: Weight = sp_runtime::Perbill::from_percent(50) * BlockWeights::get().max_block; -} - -impl pallet_collective::Config for Test { - type RuntimeOrigin = RuntimeOrigin; - type Proposal = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type MotionDuration = CouncilMotionDuration; - type MaxProposals = CouncilMaxProposals; - type MaxMembers = CouncilMaxMembers; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type WeightInfo = pallet_collective::weights::SubstrateWeight; - type SetMembersOrigin = EnsureRoot; - - type MaxProposalWeight = MaxProposalWeight; -} - -impl online_profile::Config for Test { - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - type BondingDuration = (); - type DbcPrice = DBCPriceOCW; - type ManageCommittee = Committee; - type Slash = (); - type CancelSlashOrigin = - pallet_collective::EnsureProportionAtLeast; - type SlashAndReward = GenericFunc; -} - -impl ai_project_register::Config for Test { - type RuntimeEvent = RuntimeEvent; -} - -impl rent_machine::Config for Test { - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - type RTOps = OnlineProfile; - type DbcPrice = DBCPriceOCW; -} - -pub type Moment = u64; - -parameter_types! { - pub const MinimumPeriod: Moment = 6000; -} - -impl pallet_timestamp::Config for Test { - type Moment = Moment; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = pallet_timestamp::weights::SubstrateWeight; -} - -parameter_types! { - pub const ExistentialDeposit: Balance = 1; - // For weight estimation, we assume that the most locks on an individual account will be 50. - // This number may need to be adjusted in the future if this assumption no longer holds true. - pub const MaxLocks: u32 = 50; - pub const MaxReserves: u32 = 50; -} -pub type Balance = u128; - -impl pallet_balances::Config for Test { - type MaxLocks = MaxLocks; - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type Balance = Balance; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type WeightInfo = pallet_balances::weights::SubstrateWeight; - type HoldIdentifier = (); - type FreezeIdentifier = (); - type MaxHolds = (); - type MaxFreezes = (); -} - -type TestExtrinsic = TestXt; -impl frame_system::offchain::CreateSignedTransaction for Test -where - RuntimeCall: From, -{ - fn create_transaction>( - call: RuntimeCall, - _public: ::Signer, - _account: ::AccountId, - index: ::Index, - ) -> Option<(RuntimeCall, ::SignaturePayload)> - { - Some((call, (index, ()))) - } -} - -impl frame_system::offchain::SigningTypes for Test { - type Public = ::Signer; - type Signature = Signature; -} - -impl frame_system::offchain::SendTransactionTypes for Test -where - RuntimeCall: From, -{ - type OverarchingCall = RuntimeCall; - type Extrinsic = TestExtrinsic; -} - -// Build genesis storage according to the mock runtime. -pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() -} diff --git a/pallets/ai-project-register/src/tests/mod.rs b/pallets/ai-project-register/src/tests/mod.rs deleted file mode 100644 index 7b788c20..00000000 --- a/pallets/ai-project-register/src/tests/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod test; diff --git a/pallets/ai-project-register/src/tests/test.rs b/pallets/ai-project-register/src/tests/test.rs deleted file mode 100644 index 19ca1bb2..00000000 --- a/pallets/ai-project-register/src/tests/test.rs +++ /dev/null @@ -1,490 +0,0 @@ -use super::super::{mock::*, *}; -use crate::mock::new_test_ext; -use dbc_support::{ - rental_type::{MachineGPUOrder, MachineRenterRentedOrderDetail, RentOrderDetail, RentStatus}, - traits::MachineInfoTrait, -}; -use frame_support::{assert_err, assert_ok, traits::Currency}; -use rent_machine::{ - Error as RentMachineError, MachineRentOrder, MachineRenterRentedOrders, RentInfo, -}; - -use dbc_support::{machine_info::MachineInfo, machine_type::MachineStatus}; -use online_profile::MachinesInfo; -use sp_core::{sr25519, Pair}; -pub use sp_keyring::sr25519::Keyring as Sr25519Keyring; - -type BalanceOf = <::Currency as Currency< - ::AccountId, ->>::Balance; - -#[test] -fn test_add_machine_registered_project_should_work() { - use sp_core::Pair; - let _ = env_logger::builder().is_test(true).try_init(); - - new_test_ext().execute_with(|| { - let staker = sr25519::Public::from(Sr25519Keyring::Alice); - let machine_id = "8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48" - .as_bytes() - .to_vec(); - let fake_machine_id = "8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26xxx" - .as_bytes() - .to_vec(); - let project_name = "dgc".as_bytes().to_vec(); - let project_name1 = "dgc1".as_bytes().to_vec(); - let project_name2 = "dgc2".as_bytes().to_vec(); - let project_name3 = "dgc3".as_bytes().to_vec(); - - let alice = sp_core::sr25519::Pair::from_string("//Alice", None).unwrap(); - let msg: Vec = b"The actual message".to_vec(); - let sig = alice.sign(&msg[..]); - - assert_err!( - AiProjectRegister::add_machine_registered_project( - msg.clone(), - sig.clone(), - alice.public(), - machine_id.clone(), - project_name.clone().clone() - ), - RentMachineError::::MachineNotRented.as_str() - ); - - let rent_info: RentOrderDetail< - ::AccountId, - ::BlockNumber, - BalanceOf, - > = RentOrderDetail { - machine_id: machine_id.clone(), - renter: sr25519::Public::from(Sr25519Keyring::One), - rent_start: 1, - confirm_rent: 1, - rent_end: 1, - stake_amount: 1, - rent_status: Default::default(), - gpu_num: 1, - gpu_index: vec![], - }; - RentInfo::::insert(1, rent_info); - - let order: MachineGPUOrder = MachineGPUOrder { rent_order: vec![1], used_gpu: vec![0] }; - - MachineRentOrder::::insert(machine_id.clone(), order); - - assert_err!( - AiProjectRegister::add_machine_registered_project( - msg.clone(), - sig.clone(), - alice.public(), - machine_id.clone(), - project_name.clone() - ), - RentMachineError::::MachineNotRented.as_str() - ); - - RentInfo::::remove(1); - MachineRentOrder::::remove(machine_id.clone()); - - let rent_info: RentOrderDetail< - ::AccountId, - ::BlockNumber, - BalanceOf, - > = RentOrderDetail { - machine_id: machine_id.clone(), - renter: sr25519::Public::from(Sr25519Keyring::Alice), - rent_start: 1, - confirm_rent: 1, - rent_end: 1, - stake_amount: 1, - rent_status: Default::default(), - gpu_num: 1, - gpu_index: vec![], - }; - RentInfo::::insert(1, rent_info); - let order: MachineGPUOrder = MachineGPUOrder { rent_order: vec![1], used_gpu: vec![0] }; - - MachineRentOrder::::insert(machine_id.clone(), order); - - assert_err!( - AiProjectRegister::add_machine_registered_project( - msg.clone(), - sig.clone(), - alice.public(), - machine_id.clone(), - project_name.clone() - ), - RentMachineError::::MachineNotRented.as_str() - ); - - let rent_info_renting: RentOrderDetail< - ::AccountId, - ::BlockNumber, - BalanceOf, - > = RentOrderDetail { - machine_id: machine_id.clone(), - renter: sr25519::Public::from(Sr25519Keyring::Alice), - rent_start: 1, - confirm_rent: 1, - rent_end: 1, - stake_amount: 1, - rent_status: RentStatus::Renting, - gpu_num: 1, - gpu_index: vec![], - }; - RentInfo::::insert(2, rent_info_renting); - - let order: MachineGPUOrder = MachineGPUOrder { rent_order: vec![2], used_gpu: vec![0] }; - - MachineRentOrder::::insert(machine_id.clone(), order); - assert_err!( - AiProjectRegister::add_machine_registered_project( - msg.clone(), - sig.clone(), - alice.public(), - fake_machine_id.clone(), - project_name.clone() - ), - RentMachineError::::MachineNotRented.as_str() - ); - assert_ok!(AiProjectRegister::add_machine_registered_project( - msg.clone(), - sig.clone(), - alice.public(), - machine_id.clone(), - project_name.clone() - )); - - assert_eq!( - AiProjectRegister::is_registered(machine_id.clone(), project_name.clone()), - true - ); - assert_ok!(AiProjectRegister::add_machine_registered_project( - msg.clone(), - sig.clone(), - alice.public(), - machine_id.clone(), - project_name.clone() - )); - - assert_ok!(AiProjectRegister::add_machine_registered_project( - msg.clone(), - sig.clone(), - alice.public(), - machine_id.clone(), - project_name1.clone() - )); - assert_eq!( - AiProjectRegister::is_registered(machine_id.clone(), project_name1.clone()), - true - ); - - assert_ok!(AiProjectRegister::add_machine_registered_project( - msg.clone(), - sig.clone(), - alice.public(), - machine_id.clone(), - project_name2.clone() - )); - - assert_eq!( - AiProjectRegister::is_registered(machine_id.clone(), project_name2.clone()), - true - ); - - assert_eq!( - AiProjectRegister::registered_info_to_owner(machine_id.clone(), project_name2.clone()) - .unwrap() - .eq(&staker), - true - ); - - assert_err!( - AiProjectRegister::add_machine_registered_project( - msg.clone(), - sig.clone(), - alice.public(), - machine_id.clone(), - project_name3.clone() - ), - Error::::OverLimitPerMachineIdCanRegister.as_str() - ); - }); -} -#[test] -fn test_remove_machine_registered_project_should_work() { - new_test_ext().execute_with(|| { - System::set_block_number(10); - - let machine_id = "8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48" - .as_bytes() - .to_vec(); - let project_name = "dgc".as_bytes().to_vec(); - let project_name1 = "dgc1".as_bytes().to_vec(); - let project_name2 = "dgc2".as_bytes().to_vec(); - let project_name3 = "dgc3".as_bytes().to_vec(); - - let alice = sp_core::sr25519::Pair::from_string("//Alice", None).unwrap(); - let msg: Vec = b"The actual message".to_vec(); - let sig = alice.sign(&msg[..]); - - let rent_info_renting: RentOrderDetail< - ::AccountId, - ::BlockNumber, - BalanceOf, - > = RentOrderDetail { - machine_id: machine_id.clone(), - renter: sr25519::Public::from(Sr25519Keyring::Alice), - rent_start: 1, - confirm_rent: 1, - rent_end: 1, - stake_amount: 1, - rent_status: RentStatus::Renting, - gpu_num: 1, - gpu_index: vec![], - }; - RentInfo::::insert(2, rent_info_renting); - let order: MachineGPUOrder = MachineGPUOrder { rent_order: vec![2], used_gpu: vec![0] }; - - MachineRentOrder::::insert(machine_id.clone(), order); - - assert_err!( - AiProjectRegister::remove_machine_registered_project( - msg.clone(), - sig.clone(), - alice.public(), - machine_id.clone(), - project_name.clone() - ), - Error::::MachineNotRegistered.as_str() - ); - assert_ok!(AiProjectRegister::add_machine_registered_project( - msg.clone(), - sig.clone(), - alice.public(), - machine_id.clone(), - project_name1.clone() - )); - assert_ok!(AiProjectRegister::add_machine_registered_project( - msg.clone(), - sig.clone(), - alice.public(), - machine_id.clone(), - project_name2.clone() - )); - assert_eq!( - AiProjectRegister::machine_id_to_ai_project_name(machine_id.clone()), - vec![project_name1.clone(), project_name2.clone()] - ); - - assert_ok!(AiProjectRegister::add_machine_registered_project( - msg.clone(), - sig.clone(), - alice.public(), - machine_id.clone(), - project_name3.clone() - )); - - assert_eq!( - AiProjectRegister::machine_id_to_ai_project_name(machine_id.clone()), - vec![project_name1.clone(), project_name2.clone(), project_name3.clone()] - ); - assert_err!( - AiProjectRegister::remove_machine_registered_project( - msg.clone(), - sig.clone(), - alice.public(), - machine_id.clone(), - project_name.clone() - ), - Error::::MachineNotRegistered.as_str() - ); - assert_ok!(AiProjectRegister::remove_machine_registered_project( - msg.clone(), - sig.clone(), - alice.public(), - machine_id.clone(), - project_name1.clone() - )); - assert_eq!( - AiProjectRegister::machine_id_to_ai_project_name(machine_id.clone()), - vec![project_name2.clone(), project_name3.clone()] - ); - assert_eq!( - AiProjectRegister::registered_info_to_owner(machine_id.clone(), project_name1.clone()) - .is_none(), - true - ); - assert_eq!( - AiProjectRegister::projec_machine_to_unregistered_times(project_name1, machine_id), - 10 - ); - }); -} - -#[test] -fn sig_verify_should_works() { - use sp_core::Pair; - let _ = env_logger::builder().is_test(true).try_init(); - - new_test_ext().execute_with(|| { - let alice = sp_core::sr25519::Pair::from_string("//Alice", None).unwrap(); - let msg: Vec = b"The actual message".to_vec(); - let sig = alice.sign(&msg[..]); - - - // Works as expected - no magic involved. - assert_eq!(verify_signature(msg.clone(), sig.clone(), alice.public()),true); - // Signature on "The actual message" by Alice via PolkadotJS. - let alice = sp_core::sr25519::Pair::from_string("//Alice", None).unwrap(); - // Signature on "The actual message" by Alice via PolkadotJS. - let origin_sig = b"860ab35af395c6cc989b0498269d26c13d488431f8ceac89ed82744eb84361162ce7f6c817575e46c07287f000397a0c3d5521577ac63e20ce1d0b3ab158cd88"; - let sig = hex::decode(origin_sig).unwrap(); - println!("sig size: {:?}",sig.len()); - - // let a: = sp_core::H256::from(alice.public().as_bytes()); - let sig2 = sp_core::sr25519::Signature::from_slice(&sig[..]).unwrap(); - // This will not work since it's missing the wrapping: - let msg: Vec = b"The actual message".to_vec(); - assert_eq!(verify_signature(msg,sig2.clone(), alice.public()),false); - - // This will work since it's wrapped: - let msg: Vec = b"The actual message".to_vec(); - - assert_eq!(verify_signature(msg, sig2, alice.public()),true); - - - let msg: Vec = b"123".to_vec(); - let sig_str = "5cae2fcdb2c088cc288dea283a10ad260a5e6df8dc4c07b00ad086967e354850cbbec859aaefa5ddc277d6b1c790c9be43b56160965a7dafdf10abbf7d976189"; - let pub_key_str = "34e9bdb4c0107a249c44515441acbda4b9d0f03db123241a54711d2a8ed6ce51"; - - - let sig = hex::decode(sig_str.as_bytes()).unwrap(); - - let mut b = [0u8; 64]; - b.copy_from_slice(&sig[..]); - let sig = sp_core::sr25519::Signature(b); - - - let pub_key = hex::decode(pub_key_str.as_bytes()).unwrap(); - - let mut b = [0u8; 32]; - b.copy_from_slice(&pub_key[..]); - let pub_key = sp_core::sr25519::Public(b); - - println!("sig: {:?}, pub_key: {:?}", sig, pub_key); - assert_eq!(verify_signature(msg, sig,pub_key),true); - }) -} -#[test] -fn test_account_id_should_works() { - use sp_core::Pair; - let _ = env_logger::builder().is_test(true).try_init(); - - new_test_ext().execute_with(|| { - let alice = sp_core::sr25519::Pair::from_string("//Alice", None).unwrap(); - - let r = account_id::(alice.public()).unwrap(); - assert_eq!(r, alice.public()); - }); -} - -#[test] -fn test_get_machine_valid_stake_duration_should_works() { - use sp_core::Pair; - let _ = env_logger::builder().is_test(true).try_init(); - - new_test_ext().execute_with(|| { - let machine_id = "8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48" - .as_bytes() - .to_vec(); - - let alice = sp_core::sr25519::Pair::from_string("//Alice", None).unwrap(); - let msg: Vec = b"The actual message".to_vec(); - let sig = alice.sign(&msg[..]); - - let rent_info_renting: RentOrderDetail< - ::AccountId, - ::BlockNumber, - BalanceOf, - > = RentOrderDetail { - machine_id: machine_id.clone(), - renter: sr25519::Public::from(Sr25519Keyring::Alice), - rent_start: 1, - confirm_rent: 1, - rent_end: 1, - stake_amount: 1, - rent_status: RentStatus::Renting, - gpu_num: 1, - gpu_index: vec![], - }; - - RentInfo::::insert(1, rent_info_renting.clone()); - - let order: MachineRenterRentedOrderDetail<::BlockNumber> = - MachineRenterRentedOrderDetail { rent_id: 1, rent_start: 1, rent_end: 2 }; - - MachineRenterRentedOrders::::insert( - machine_id.clone(), - rent_info_renting.renter, - vec![order], - ); - - let machine_info: MachineInfo< - ::AccountId, - ::BlockNumber, - BalanceOf, - > = MachineInfo { - controller: sr25519::Public::from(Sr25519Keyring::Alice), - machine_stash: sr25519::Public::from(Sr25519Keyring::Bob), - renters: vec![sr25519::Public::from(Sr25519Keyring::Alice)], - last_machine_restake: 1, - bonding_height: 1, - online_height: 1, - last_online_height: 1, - init_stake_per_gpu: 1, - stake_amount: 1, - machine_status: MachineStatus::Rented, - total_rented_duration: 1, - total_rented_times: 0, - total_rent_fee: 1, - total_burn_fee: 1, - machine_info_detail: Default::default(), - reward_committee: vec![], - reward_deadline: 0, - }; - - MachinesInfo::::insert(machine_id.clone(), machine_info.clone()); - - System::set_block_number(10); - let r = RentMachine::get_machine_valid_stake_duration(0, 0, 0, machine_id.clone()); - assert_eq!(r.unwrap(), 1); - - let rent_info_renting: RentOrderDetail< - ::AccountId, - ::BlockNumber, - BalanceOf, - > = RentOrderDetail { - machine_id: machine_id.clone(), - renter: sr25519::Public::from(Sr25519Keyring::Alice), - rent_start: 1, - confirm_rent: 1, - rent_end: 20, - stake_amount: 1, - rent_status: RentStatus::Renting, - gpu_num: 1, - gpu_index: vec![], - }; - RentInfo::::insert(2, rent_info_renting.clone()); - let order: MachineRenterRentedOrderDetail<::BlockNumber> = - MachineRenterRentedOrderDetail { rent_id: 2, rent_start: 1, rent_end: 20 }; - MachineRenterRentedOrders::::insert( - machine_id.clone(), - rent_info_renting.renter, - vec![order], - ); - - let r = RentMachine::get_machine_valid_stake_duration(0, 0, 0, machine_id); - assert_eq!(r.unwrap(), 9); - }); -} diff --git a/pallets/dbc-price-ocw/src/lib.rs b/pallets/dbc-price-ocw/src/lib.rs index 2ca6ec03..6f39a009 100644 --- a/pallets/dbc-price-ocw/src/lib.rs +++ b/pallets/dbc-price-ocw/src/lib.rs @@ -281,4 +281,13 @@ impl DbcPrice for Pallet { .checked_mul(&one_dbc)? .checked_div(&dbc_price) } + + fn get_dlc_amount_by_value(value: u64) -> Option { + let one_dlc: Self::Balance = 1_000_000_000_000_000_u64.saturated_into(); + let dlc_price = 3000u64.saturated_into(); + value + .saturated_into::() + .checked_mul(&one_dlc)? + .checked_div(&dlc_price) + } } diff --git a/pallets/dlc-machine/Cargo.toml b/pallets/dlc-machine/Cargo.toml deleted file mode 100644 index 13b31cac..00000000 --- a/pallets/dlc-machine/Cargo.toml +++ /dev/null @@ -1,51 +0,0 @@ -[package] -name = "dlc-machine" -version = { workspace = true } -authors = { workspace = true } -edition = "2021" -repository = { workspace = true } - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -parity-scale-codec = { workspace = true } -dbc-support = { path = "../support", default-features = false } -scale-info = { workspace = true } - -frame-support = { workspace = true } -frame-system = { workspace = true } -sp-std = { workspace = true } -sp-core = { workspace = true } - -rent-machine = { path = "../rent-machine", default-features = false } -online-profile = { path = "../online-profile", default-features = false } - -[dev-dependencies] -sp-std = { workspace = true, features = ["std"] } -sp-io = { workspace = true, features = ["std"] } -pallet-timestamp = { workspace = true } -pallet-insecure-randomness-collective-flip = { workspace = true, features = ["std"] } -pallet-collective = { workspace = true, features = ["std"] } -pallet-balances = { workspace = true, features = ["std"] } -dbc-price-ocw = { path = "../dbc-price-ocw", default-features = false } -generic-func = { path = "../generic-func", default-features = false } -committee = { path = "../committee" } -online-profile = { path = "../online-profile", default-features = false } - -hex = { workspace = true } -sp-keyring = { workspace = true } -sp-runtime = { workspace = true } -env_logger = { workspace = true } - -[features] -default = ["std"] -std = [ - "parity-scale-codec/std", - "frame-support/std", - "frame-system/std", - "sp-std/std", - "sp-core/std", - "online-profile/std" -] -try-runtime = ["frame-support/try-runtime"] diff --git a/pallets/dlc-machine/src/lib.rs b/pallets/dlc-machine/src/lib.rs deleted file mode 100644 index f5e4678a..00000000 --- a/pallets/dlc-machine/src/lib.rs +++ /dev/null @@ -1,498 +0,0 @@ -#![recursion_limit = "256"] -#![cfg_attr(not(feature = "std"), no_std)] -#![warn(unused_crate_dependencies)] -extern crate core; - -#[cfg(test)] -mod mock; -#[allow(non_upper_case_globals)] -#[cfg(test)] -mod tests; - -pub use dbc_support::machine_type::MachineStatus; -use dbc_support::{ - traits::{DLCMachineReportStakingTrait, MachineInfoTrait, PhaseLevel}, - utils::account_id, - MachineId, -}; -use frame_support::{ - pallet_prelude::*, - sp_runtime::{SaturatedConversion, Saturating}, -}; -pub use pallet::*; -use sp_std::{prelude::*, str, vec::Vec}; - -type RewardPausedAt = ::BlockNumber; -type RewardRecoveredAt = ::BlockNumber; - -#[frame_support::pallet] -pub mod pallet { - use super::*; - use dbc_support::ONE_HOUR; - use frame_system::{ - ensure_root, - pallet_prelude::{BlockNumberFor, OriginFor}, - }; - - #[pallet::config] - pub trait Config: frame_system::Config + rent_machine::Config + online_profile::Config { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; - } - - #[pallet::storage] - #[pallet::getter(fn dlc_machines_in_staking)] - pub type DLCMachinesInStaking = - StorageMap<_, Twox64Concat, MachineId, (), ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn dlc_machines_in_nft_staking_phase_one)] - pub type DLCMachinesInNftStakingPhaseOne = - StorageMap<_, Twox64Concat, MachineId, (), ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn dlc_machines_in_nft_staking_phase_two)] - pub type DLCMachinesInNftStakingPhaseTwo = - StorageMap<_, Twox64Concat, MachineId, (), ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn dlc_machines_in_nft_staking_phase_three)] - pub type DLCMachinesInNftStakingPhaseThree = - StorageMap<_, Twox64Concat, MachineId, (), ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn dlc_machines_owner_rent_ended)] - pub type DLCMachinesOwnerRentEnded = - StorageMap<_, Twox64Concat, MachineId, (), ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn nft_staking_reward_start_threshold)] - pub type NFTStakingRewardStartThreshold = - StorageMap<_, Blake2_128Concat, PhaseLevel, u64, ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn nft_staking_reward_start_at)] - pub type NFTStakingRewardStartAt = - StorageMap<_, Blake2_128Concat, PhaseLevel, T::BlockNumber, ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn nft_staking_paused_details)] - pub type NFTStakingPausedDetails = StorageMap< - _, - Blake2_128Concat, - PhaseLevel, - Vec<(RewardPausedAt, RewardRecoveredAt)>, - ValueQuery, - >; - - #[pallet::storage] - #[pallet::getter(fn machine_id_2_gpu_count_of_idc_machine_nft_staking)] - pub type MachineId2GPUCountInStakingOfIDCMachineNFTStaking = StorageDoubleMap< - _, - Blake2_128Concat, - PhaseLevel, - Blake2_128Concat, - MachineId, - u32, - ValueQuery, - >; - - #[pallet::pallet] - #[pallet::without_storage_info] - pub struct Pallet(_); - - #[pallet::event] - #[pallet::generate_deposit(pub (super) fn deposit_event)] - pub enum Event { - ReportDLCStaking(T::AccountId, MachineId), - DLCMachinesOwnerRentEnded(MachineId), - } - - #[pallet::error] - pub enum Error { - InvalidValue, - RenterNotOwner, - AlreadyInStaking, - } - - #[pallet::hooks] - impl Hooks> for Pallet { - fn on_initialize(block_number: T::BlockNumber) -> Weight { - if block_number.saturated_into::() % ONE_HOUR as u64 == 0 { - frame_support::log::info!("🔍 start clean up machine_ids_in_staking"); - let machine_id_to_remove: Vec = DLCMachinesInStaking::::iter_keys() - .filter(|machine_id| { - let machine_info_result = - online_profile::Pallet::::machines_info(machine_id); - if let Some(machine_info) = machine_info_result { - // must be rented - if machine_info.machine_status != MachineStatus::Rented { - return true - }; - - // must be rented by owner - if machine_info.renters.len() != 1 { - return true - } - - let renter_result = machine_info.renters.last(); - if renter_result.is_none() { - return true - } - - let renter = renter_result.unwrap().clone(); - if machine_info.controller != renter && - machine_info.machine_stash != renter - { - return true - } - } else { - return true - } - - return false - }) - .collect(); - - for machine_id in machine_id_to_remove { - frame_support::log::info!( - "remove machine_id : {}", - str::from_utf8(&machine_id).unwrap() - ); - DLCMachinesOwnerRentEnded::::insert(&machine_id, ()); - DLCMachinesInStaking::::remove(&machine_id); - MachineId2GPUCountInStakingOfIDCMachineNFTStaking::::remove( - &PhaseLevel::PhaseOne, - &machine_id, - ); - MachineId2GPUCountInStakingOfIDCMachineNFTStaking::::remove( - &PhaseLevel::PhaseTwo, - &machine_id, - ); - MachineId2GPUCountInStakingOfIDCMachineNFTStaking::::remove( - &PhaseLevel::PhaseThree, - &machine_id, - ); - Self::deposit_event(Event::DLCMachinesOwnerRentEnded(machine_id)) - } - } - Weight::zero() - } - - fn on_runtime_upgrade() -> frame_support::weights::Weight { - if NFTStakingRewardStartThreshold::::iter().count() as u32 == 0 { - frame_support::log::info!("🔍 start set NFTStakingRewardStartThreshold"); - - NFTStakingRewardStartThreshold::::insert(PhaseLevel::PhaseOne, 500); - NFTStakingRewardStartThreshold::::insert(PhaseLevel::PhaseTwo, 1000); - NFTStakingRewardStartThreshold::::insert(PhaseLevel::PhaseThree, 2000); - } - - Weight::zero() - } - } - - #[pallet::call] - impl Pallet { - #[pallet::call_index(0)] - #[pallet::weight(Weight::from_parts(10000, 0))] - pub fn set_nft_staking_start_threshold( - origin: OriginFor, - phase_level: PhaseLevel, - value: u64, - ) -> DispatchResultWithPostInfo { - let _who = ensure_root(origin)?; - ensure!(value > 0, Error::::InvalidValue); - NFTStakingRewardStartThreshold::::insert(phase_level, value); - Ok(().into()) - } - - #[pallet::call_index(1)] - #[pallet::weight(Weight::from_parts(10000, 0))] - pub fn reset_nft_staking(origin: OriginFor, limit: u32) -> DispatchResultWithPostInfo { - ensure_root(origin)?; - let _ = NFTStakingRewardStartAt::::clear(limit, None); - let _ = NFTStakingPausedDetails::::clear(limit, None); - let _ = MachineId2GPUCountInStakingOfIDCMachineNFTStaking::::clear(limit, None); - Ok(().into()) - } - } -} - -impl DLCMachineReportStakingTrait for Pallet { - type BlockNumber = T::BlockNumber; - fn report_dlc_staking( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, - machine_id: MachineId, - ) -> Result<(), &'static str> { - let result = - as MachineInfoTrait>::is_both_machine_renter_and_owner( - data, - sig, - from.clone(), - machine_id.clone(), - )?; - - if !result { - return Err(Error::::RenterNotOwner.as_str()) - } - if DLCMachinesInStaking::::contains_key(&machine_id) { - return Err(Error::::AlreadyInStaking.as_str()) - } - - DLCMachinesInStaking::::insert(machine_id.clone(), ()); - - let stakeholder = account_id::(from)?; - Self::deposit_event(Event::ReportDLCStaking(stakeholder, machine_id)); - Ok(()) - } - - fn report_dlc_nft_staking( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, - machine_id: MachineId, - phase_level: PhaseLevel, - ) -> Result<(), &'static str> { - let result = - as MachineInfoTrait>::is_both_machine_renter_and_owner( - data, - sig, - from.clone(), - machine_id.clone(), - )?; - - if !result { - return Err(Error::::RenterNotOwner.as_str()) - } - - if DLCMachinesInStaking::::contains_key(&machine_id) { - return Err(Error::::AlreadyInStaking.as_str()) - } - - DLCMachinesInStaking::::insert(machine_id.clone(), ()); - - let machine_info_result = online_profile::Pallet::::machines_info(machine_id.clone()); - if let Some(machine_info) = machine_info_result { - MachineId2GPUCountInStakingOfIDCMachineNFTStaking::::insert( - phase_level.clone(), - &machine_id, - machine_info.machine_info_detail.committee_upload_info.gpu_num, - ); - if phase_level == PhaseLevel::PhaseOne { - DLCMachinesInNftStakingPhaseOne::::insert(machine_id.clone(), ()); - } - if phase_level == PhaseLevel::PhaseTwo { - DLCMachinesInNftStakingPhaseTwo::::insert(machine_id.clone(), ()); - } - if phase_level == PhaseLevel::PhaseThree { - DLCMachinesInNftStakingPhaseThree::::insert(machine_id.clone(), ()); - } - } - - let mut gpu_count = 0u32; - for (_, gpu_count_of_one_machine) in - MachineId2GPUCountInStakingOfIDCMachineNFTStaking::::iter_prefix(&phase_level) - { - gpu_count = gpu_count.saturating_add(gpu_count_of_one_machine); - } - - if gpu_count as u64 >= Self::nft_staking_reward_start_threshold(&phase_level) && - Self::get_nft_staking_reward_start_at(&phase_level).saturated_into::() == 0 - { - NFTStakingRewardStartAt::::insert( - &phase_level, - >::block_number(), - ); - } - - let details = Self::nft_staking_paused_details(&phase_level); - if details.len() > 0 { - NFTStakingPausedDetails::::mutate( - &phase_level, - |paused_details: &mut Vec<(RewardPausedAt, RewardRecoveredAt)>| { - if let Some((_, recovered_at)) = paused_details.last_mut() { - if (*recovered_at).saturated_into::() == 0 { - *recovered_at = >::block_number(); - } - } - }, - ) - } - - let stakeholder = account_id::(from)?; - Self::deposit_event(Event::ReportDLCStaking(stakeholder, machine_id)); - Ok(()) - } - - fn report_dlc_nft_end_staking( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, - machine_id: MachineId, - phase_level: PhaseLevel, - ) -> Result<(), &'static str> { - let result = as MachineInfoTrait>::is_machine_owner( - data, - sig, - from, - machine_id.clone(), - )?; - if !result { - return Err(Error::::RenterNotOwner.as_str()) - } - - DLCMachinesOwnerRentEnded::::remove(&machine_id); - - if phase_level == PhaseLevel::PhaseOne { - DLCMachinesInNftStakingPhaseOne::::remove(machine_id.clone()); - } - if phase_level == PhaseLevel::PhaseTwo { - DLCMachinesInNftStakingPhaseTwo::::remove(machine_id.clone()); - } - if phase_level == PhaseLevel::PhaseThree { - DLCMachinesInNftStakingPhaseThree::::remove(machine_id.clone()); - } - - if !DLCMachinesInStaking::::contains_key(&machine_id) { - return Ok(()) - } - - let gpu_count_of_the_machine = - Self::machine_id_2_gpu_count_of_idc_machine_nft_staking(&phase_level, &machine_id); - - MachineId2GPUCountInStakingOfIDCMachineNFTStaking::::remove(&phase_level, &machine_id); - - let mut gpu_count = 0u32; - for (_, gpu_count_of_one_machine) in - MachineId2GPUCountInStakingOfIDCMachineNFTStaking::::iter_prefix(&phase_level) - { - gpu_count = gpu_count.saturating_add(gpu_count_of_one_machine); - } - - let gpu_count_before = gpu_count.saturating_add(gpu_count_of_the_machine) as u64; - - if Self::get_nft_staking_reward_start_at(&phase_level).saturated_into::() > 0 { - let start_threshold = Self::nft_staking_reward_start_threshold(&phase_level); - if ((gpu_count as u64) < start_threshold) && (gpu_count_before >= start_threshold) { - NFTStakingPausedDetails::::mutate(&phase_level, |details| { - details.push(( - >::block_number(), - T::BlockNumber::default(), - )); - }) - } - } - - DLCMachinesInStaking::::remove(&machine_id); - Ok(()) - } - - fn report_dlc_end_staking( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, - machine_id: MachineId, - ) -> Result<(), &'static str> { - let result = as MachineInfoTrait>::is_machine_owner( - data, - sig, - from, - machine_id.clone(), - )?; - if !result { - return Err(Error::::RenterNotOwner.as_str()) - } - - if DLCMachinesInStaking::::contains_key(&machine_id) { - return Ok(()) - } - - DLCMachinesInStaking::::remove(&machine_id); - Ok(()) - } - - fn get_nft_staking_valid_reward_duration( - last_claim_at: Self::BlockNumber, - total_stake_duration: Self::BlockNumber, - phase_level: PhaseLevel, - ) -> Self::BlockNumber { - if Self::nft_staking_reward_start_at(&phase_level) == T::BlockNumber::default() { - return T::BlockNumber::default() - } - - let mut reward_paused_duration = T::BlockNumber::default(); - let reward_paused_details = Self::nft_staking_paused_details(&phase_level); - if reward_paused_details.len() > 0 { - reward_paused_details.iter().for_each( - |(paused_at_block_number, recovered_at_block_number)| { - if (*recovered_at_block_number).saturated_into::() > 0 { - if last_claim_at < *recovered_at_block_number && - last_claim_at >= *paused_at_block_number - { - reward_paused_duration += - recovered_at_block_number.saturating_sub(*paused_at_block_number); - } - if last_claim_at < *paused_at_block_number { - reward_paused_duration += - recovered_at_block_number.saturating_sub(*paused_at_block_number); - } - } else { - if last_claim_at < *paused_at_block_number { - reward_paused_duration += >::block_number() - .saturating_sub(*paused_at_block_number); - } else { - reward_paused_duration = total_stake_duration; - } - } - }, - ); - return total_stake_duration - reward_paused_duration - } - total_stake_duration - } - - fn get_nft_staking_reward_start_at(phase_level: &PhaseLevel) -> Self::BlockNumber { - Self::nft_staking_reward_start_at(phase_level) - } - - fn get_nft_staking_gpu_count(phase_level: &PhaseLevel) -> (u64, u64) { - let mut gpu_count = 0u32; - for (_, gpu_count_of_one_machine) in - MachineId2GPUCountInStakingOfIDCMachineNFTStaking::::iter_prefix(&phase_level) - { - gpu_count = gpu_count.saturating_add(gpu_count_of_one_machine); - } - let threshold = Self::nft_staking_reward_start_threshold(phase_level); - let mut gpu_count_before_reward_start = 0u64; - if (gpu_count as u64) < threshold { - gpu_count_before_reward_start = threshold - (gpu_count as u64); - }; - - (gpu_count as u64, gpu_count_before_reward_start) - } -} - -impl Pallet { - pub fn dlc_machine_in_staking(machine_id: MachineId) -> bool { - DLCMachinesInStaking::::contains_key(&machine_id) - } - - pub fn report_dlc_machine_slashed(machine_id: MachineId) { - DLCMachinesInStaking::::remove(&machine_id); - } - - pub fn get_machine_ids_in_dlc_nft_staking(phase_level: PhaseLevel) -> Vec { - if phase_level == PhaseLevel::PhaseOne { - return DLCMachinesInNftStakingPhaseOne::::iter_keys().collect() - } - if phase_level == PhaseLevel::PhaseTwo { - return DLCMachinesInNftStakingPhaseTwo::::iter_keys().collect() - } - if phase_level == PhaseLevel::PhaseThree { - return DLCMachinesInNftStakingPhaseThree::::iter_keys().collect() - } - Vec::new() - } -} diff --git a/pallets/dlc-machine/src/mock.rs b/pallets/dlc-machine/src/mock.rs deleted file mode 100644 index d6fd56f9..00000000 --- a/pallets/dlc-machine/src/mock.rs +++ /dev/null @@ -1,207 +0,0 @@ -use crate as ai_project_register; - -use frame_support::{pallet_prelude::ConstU32, parameter_types, weights::Weight}; -use frame_system::EnsureRoot; -use sp_core::{sr25519, sr25519::Signature, H256}; -use sp_runtime::{ - testing::{Header, TestXt}, - traits::{BlakeTwo256, IdentityLookup, Verify}, -}; - -type Block = frame_system::mocking::MockBlock; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; - -// Configure a mock runtime to test the pallet. -frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system, - Timestamp: pallet_timestamp, - AiProjectRegister: ai_project_register, - Balances: pallet_balances, - OnlineProfile: online_profile, - DBCPriceOCW: dbc_price_ocw, - GenericFunc: generic_func, - RandomnessCollectiveFlip: pallet_insecure_randomness_collective_flip, - Committee: committee, - TechnicalCommittee: pallet_collective::, - RentMachine: rent_machine::{Pallet, Call, Storage, Event}, - - } -); - -impl frame_system::Config for Test { - type BaseCallFilter = (); - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = sr25519::Public; - type Lookup = IdentityLookup; - type Header = Header; - type RuntimeEvent = RuntimeEvent; - type BlockHashCount = (); - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); - type OnSetCode = (); - type MaxConsumers = ConstU32<16>; -} - -parameter_types! { - pub const BlockPerEra: u32 = 3600 * 24 / 30; -} - -impl generic_func::Config for Test { - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - type RandomnessSource = RandomnessCollectiveFlip; - type FixedTxFee = (); - type Slash = (); -} - -impl committee::Config for Test { - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - // type WeightInfo = (); -} - -impl pallet_insecure_randomness_collective_flip::Config for Test {} - -impl dbc_price_ocw::Config for Test { - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - type RandomnessSource = RandomnessCollectiveFlip; -} - -type TechnicalCollective = pallet_collective::Instance2; - -parameter_types! { - pub const CouncilMotionDuration: u32 = 5 * 2880; - pub const CouncilMaxProposals: u32 = 100; - pub const CouncilMaxMembers: u32 = 100; - pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights::simple_max(Weight::MAX); - pub MaxProposalWeight: Weight = sp_runtime::Perbill::from_percent(50) * BlockWeights::get().max_block; -} - -impl pallet_collective::Config for Test { - type RuntimeOrigin = RuntimeOrigin; - type Proposal = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type MotionDuration = CouncilMotionDuration; - type MaxProposals = CouncilMaxProposals; - type MaxMembers = CouncilMaxMembers; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type WeightInfo = pallet_collective::weights::SubstrateWeight; - type SetMembersOrigin = EnsureRoot; - - type MaxProposalWeight = MaxProposalWeight; -} - -impl online_profile::Config for Test { - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - type BondingDuration = (); - type DbcPrice = DBCPriceOCW; - type ManageCommittee = Committee; - type Slash = (); - type CancelSlashOrigin = - pallet_collective::EnsureProportionAtLeast; - type SlashAndReward = GenericFunc; -} - -impl ai_project_register::Config for Test { - type RuntimeEvent = RuntimeEvent; -} - -impl rent_machine::Config for Test { - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - type RTOps = OnlineProfile; - type DbcPrice = DBCPriceOCW; -} - -pub type Moment = u64; - -parameter_types! { - pub const MinimumPeriod: Moment = 6000; -} - -impl pallet_timestamp::Config for Test { - type Moment = Moment; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = pallet_timestamp::weights::SubstrateWeight; -} - -parameter_types! { - pub const ExistentialDeposit: Balance = 1; - // For weight estimation, we assume that the most locks on an individual account will be 50. - // This number may need to be adjusted in the future if this assumption no longer holds true. - pub const MaxLocks: u32 = 50; - pub const MaxReserves: u32 = 50; -} -pub type Balance = u128; - -impl pallet_balances::Config for Test { - type MaxLocks = MaxLocks; - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type Balance = Balance; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type WeightInfo = pallet_balances::weights::SubstrateWeight; - - type HoldIdentifier = (); - type FreezeIdentifier = (); - type MaxHolds = (); - type MaxFreezes = (); -} - -type TestExtrinsic = TestXt; -impl frame_system::offchain::CreateSignedTransaction for Test -where - RuntimeCall: From, -{ - fn create_transaction>( - call: RuntimeCall, - _public: ::Signer, - _account: ::AccountId, - index: ::Index, - ) -> Option<(RuntimeCall, ::SignaturePayload)> - { - Some((call, (index, ()))) - } -} - -impl frame_system::offchain::SigningTypes for Test { - type Public = ::Signer; - type Signature = Signature; -} - -impl frame_system::offchain::SendTransactionTypes for Test -where - RuntimeCall: From, -{ - type OverarchingCall = RuntimeCall; - type Extrinsic = TestExtrinsic; -} - -// Build genesis storage according to the mock runtime. -pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() -} diff --git a/pallets/dlc-machine/src/tests/mod.rs b/pallets/dlc-machine/src/tests/mod.rs deleted file mode 100644 index 7b788c20..00000000 --- a/pallets/dlc-machine/src/tests/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod test; diff --git a/pallets/dlc-machine/src/tests/test.rs b/pallets/dlc-machine/src/tests/test.rs deleted file mode 100644 index 8b137891..00000000 --- a/pallets/dlc-machine/src/tests/test.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/pallets/maintain-committee/Cargo.toml b/pallets/maintain-committee/Cargo.toml index fcefee80..8e4728b3 100644 --- a/pallets/maintain-committee/Cargo.toml +++ b/pallets/maintain-committee/Cargo.toml @@ -12,16 +12,11 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-std = { workspace = true } sp-runtime = { workspace = true } -pallet-treasury = { workspace = true } -sp-core = { workspace = true } dbc-support = { path = "../support", default-features = false } generic-func = { path = "../generic-func", default-features = false } online-profile = { path = "../online-profile", default-features = false } rent-machine = { path = "../rent-machine", default-features = false } -pallet-assets = { path = "../assets", default-features = false } -rent-dlc-machine = { path = "../rent-dlc-machine", default-features = false } -dlc-machine = { path = "../dlc-machine",default-features = false} [dev-dependencies] once_cell = { workspace = true } @@ -40,7 +35,6 @@ online-committee = { path = "../online-committee" } committee = { path = "../committee" } online-profile = { path = "../online-profile" } dbc-price-ocw = { path = "../dbc-price-ocw" } -dlc-machine = { path = "../dlc-machine"} [features] @@ -52,9 +46,7 @@ std = [ "frame-system/std", "sp-runtime/std", "sp-std/std", - "sp-core/std", "dbc-support/std", - "pallet-assets/std", "online-profile/std" ] try-runtime = ["frame-support/try-runtime"] diff --git a/pallets/maintain-committee/src/impl_dlc_slash_info.rs b/pallets/maintain-committee/src/impl_dlc_slash_info.rs deleted file mode 100644 index 664a4618..00000000 --- a/pallets/maintain-committee/src/impl_dlc_slash_info.rs +++ /dev/null @@ -1,48 +0,0 @@ -use crate::*; -use dbc_support::traits::DLCMachineSlashInfoTrait; -use sp_core::H160; -impl DLCMachineSlashInfoTrait for Pallet { - fn get_dlc_machine_slashed_at(machine_id: MachineId) -> u64 { - if let Some((_, _, slash_at)) = Self::dlc_machine_2_report_info(&machine_id) { - return slash_at - }; - 0 - } - fn get_dlc_machine_slashed_report_id(machine_id: MachineId) -> u64 { - if let Some((report_id, _, slash_at)) = Self::dlc_machine_2_report_info(&machine_id) { - if slash_at > 0 { - return report_id - } - } - return 0 - } - - fn is_slashed(machine_id: MachineId) -> bool { - if let Some((_, _, slash_at)) = Self::dlc_machine_2_report_info(&machine_id) { - return slash_at > 0 - } - return false - } - - fn get_dlc_machine_slashed_reporter(machine_id: MachineId) -> H160 { - if let Some((_, reporter_evm_address, slash_at)) = - Self::dlc_machine_2_report_info(&machine_id) - { - if slash_at > 0 { - return reporter_evm_address - } - } - - return H160::default() - } -} - -impl Pallet { - pub fn get_slash_report_result( - machine_id: MachineId, - ) -> Option>> { - let (report_id, _, _) = Self::dlc_machine_2_report_info(&machine_id)?; - let report = Self::report_result(&report_id)?; - Some(report) - } -} diff --git a/pallets/maintain-committee/src/lib.rs b/pallets/maintain-committee/src/lib.rs index d7f4f497..087f7a67 100644 --- a/pallets/maintain-committee/src/lib.rs +++ b/pallets/maintain-committee/src/lib.rs @@ -3,7 +3,6 @@ #![warn(unused_crate_dependencies)] // mod migrations; -mod impl_dlc_slash_info; mod slash; mod types; mod utils; @@ -13,7 +12,6 @@ mod mock; #[cfg(test)] #[allow(non_upper_case_globals)] mod tests; -use sp_runtime::SaturatedConversion; use dbc_support::{ report::{ @@ -30,46 +28,28 @@ use dbc_support::{ }; use frame_support::{ pallet_prelude::*, - traits::{fungibles::Mutate, tokens::Preservation, Currency, OnUnbalanced, ReservableCurrency}, - PalletId, + traits::{Currency, OnUnbalanced, ReservableCurrency}, }; use frame_system::pallet_prelude::*; use parity_scale_codec::alloc::string::ToString; -use sp_runtime::{ - traits::{AccountIdConversion, CheckedSub, Saturating, Zero}, - Perbill, -}; +use sp_runtime::traits::{Saturating, Zero}; use sp_std::{str, vec, vec::Vec}; pub use pallet::*; use types::*; - type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; -type DLCBalanceOf = ::Balance; type NegativeImbalanceOf = <::Currency as Currency< ::AccountId, >>::NegativeImbalance; - -pub const ONE_DLC: u128 = 100_000_000; -const PALLET_ID: PalletId = PalletId(*b"dlc_lock"); - #[frame_support::pallet] pub mod pallet { use super::*; use dbc_support::machine_type::MachineStatus; - use sp_core::H160; #[pallet::config] pub trait Config: - frame_system::Config - + online_profile::Config - + generic_func::Config - + rent_machine::Config - + pallet_assets::Config - + pallet_treasury::Config - + rent_dlc_machine::Config - + dlc_machine::Config + frame_system::Config + online_profile::Config + generic_func::Config + rent_machine::Config { type RuntimeEvent: From> + IsType<::RuntimeEvent>; type Currency: ReservableCurrency; @@ -86,11 +66,6 @@ pub mod pallet { type Slash: OnUnbalanced>; type CancelSlashOrigin: EnsureOrigin; type SlashAndReward: GNOps>; - - type AssetId: IsType<::AssetId> + Parameter + From; - - #[pallet::constant] - type DLCAssetId: Get; } #[pallet::pallet] @@ -116,7 +91,6 @@ pub mod pallet { pub(super) fn CommitteeLimitDefault() -> u32 { 3 } - /// Number of available committees for maintain module #[pallet::storage] #[pallet::getter(fn committee_limit)] @@ -161,7 +135,6 @@ pub mod pallet { MTCommitteeOpsDetail>, ValueQuery, >; - /// 系统中还未完成的订单 #[pallet::storage] #[pallet::getter(fn live_report)] @@ -200,27 +173,6 @@ pub mod pallet { ReportId, MTPendingSlashReviewInfo, T::BlockNumber>, >; - - // reserve dlc from user when user report dlc machine fault - #[pallet::storage] - #[pallet::getter(fn account_id_2_reserve_dlc)] - pub(super) type AccountId2ReserveDLC = - StorageMap<_, Blake2_128Concat, T::AccountId, DLCBalanceOf, ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn dlc_machine_2_report_info)] - pub(super) type DLCMachine2ReportInfo = - StorageMap<_, Blake2_128Concat, MachineId, (ReportId, H160, u64)>; - - #[pallet::type_value] - pub(super) fn PalletAccount() -> T::AccountId { - PALLET_ID.try_into_account().unwrap() - } - #[pallet::storage] - #[pallet::getter(fn account_for_reserve_dlc)] - pub(super) type AccountForReserveDLC = - StorageValue<_, T::AccountId, ValueQuery, PalletAccount>; - #[pallet::call] impl Pallet { #[pallet::call_index(0)] @@ -279,7 +231,6 @@ pub mod pallet { None, &mut live_report, &mut reporter_report, - false, )?; LiveReport::::put(live_report); @@ -723,94 +674,6 @@ pub mod pallet { PendingSlashReview::::remove(slashed_report_id); Ok(().into()) } - - #[pallet::call_index(12)] - #[pallet::weight(Weight::from_parts(10000, 0))] - pub fn report_dlc_machine_fault( - origin: OriginFor, - machine_id: MachineId, - rent_order_id: RentOrderId, - reporter_evm_address: H160, - ) -> DispatchResultWithPostInfo { - let reporter = ensure_signed(origin)?; - let dbc_rent_order_id = - >::get_parent_dbc_rent_order_id(rent_order_id.clone())?; - let dlc_rent_info = >::rent_info(rent_order_id.clone()) - .ok_or(Error::::DlcRentOrderNotExist)?; - ensure!(dlc_rent_info.renter == reporter, Error::::NotDLCMachineRenter); - - let report_reason = - MachineFaultType::RentedInaccessible(machine_id.clone(), dbc_rent_order_id); - let mut live_report = Self::live_report(); - let mut reporter_report = Self::reporter_report(&reporter); - - // 支付 - if let MachineFaultType::RentedInaccessible(_, dbc_rent_order_id) = - report_reason.clone() - { - let rent_info = >::rent_info(&dbc_rent_order_id) - .ok_or(Error::::Unknown)?; - - let result = >::machines_info(&rent_info.machine_id); - match result { - Some(machine_info) => { - if machine_info.machine_status == MachineStatus::Rented { - let renters = - >::get_renters(&rent_info.machine_id); - >::add_offline_machine_to_renters( - rent_info.machine_id, - renters, - ); - } - }, - None => {}, - } - } - - let asset_id = Self::get_dlc_asset_id(); - let account_id_for_reserve_dlc = - Self::pallet_account_id().ok_or(Error::::DlcReserveAccountNotSet)?; - // let account_id_for_reserve_dlc_lookup = ::unlookup(account_id_for_reserve_dlc.clone()); - - let reserve_amount = Self::get_dlc_reserve_amount(); - // >::transfer(origin,asset_id.into(),account_id_for_reserve_dlc_lookup,reserve_amount.into())?; - as Mutate>::transfer( - asset_id, - &reporter, - &account_id_for_reserve_dlc, - reserve_amount, - Preservation::Expendable, - )?; - - AccountId2ReserveDLC::::mutate(&reporter, |reserve_dlc| { - *reserve_dlc = reserve_dlc.saturating_add(reserve_amount) - }); - - // Only be error when params not be set - let report_id = Self::do_report_dlc_machine_fault( - reporter.clone(), - report_reason, - None, - &mut live_report, - &mut reporter_report, - )?; - - DLCMachine2ReportInfo::::insert(machine_id, (report_id, reporter_evm_address, 0)); - LiveReport::::put(live_report); - ReporterReport::::insert(&reporter, reporter_report); - Ok(().into()) - } - - #[pallet::call_index(13)] - #[pallet::weight(Weight::from_parts(10000, 0))] - pub fn exec_slash_at( - origin: OriginFor, - slash_at: T::BlockNumber, - ) -> DispatchResultWithPostInfo { - ensure_root(origin)?; - let _ = Self::exec_slash_now(slash_at); - Ok(().into()) - } } #[pallet::event] @@ -825,7 +688,6 @@ pub mod pallet { ReporterReduceStake(T::AccountId, BalanceOf), ApplySlashReview(ReportId), CommitteeBookReport(T::AccountId, ReportId), - ReportDLCMachineFault(T::AccountId, MachineFaultType), } #[pallet::error] @@ -862,10 +724,6 @@ pub mod pallet { NotMachineRenter, ReduceUsedStakeFailed, Unknown, - DlcReserveAccountNotSet, - DlcReportNotAllowed, - DlcRentOrderNotExist, - NotDLCMachineRenter, } } @@ -921,28 +779,11 @@ impl Pallet { report_time: Option, live_report: &mut MTLiveReportList, reporter_report: &mut ReporterReportList, - is_dlc_machine_report: bool, ) -> DispatchResultWithPostInfo { // 获取处理报告需要的信息 let stake_params = Self::reporter_stake_params().ok_or(Error::::GetStakeAmountFailed)?; let report_id = Self::get_new_report_id(); let report_time = report_time.unwrap_or_else(|| >::block_number()); - - let mut stake_amount = stake_params.stake_per_report; - if is_dlc_machine_report { - stake_amount = BalanceOf::::zero(); - - if let MachineFaultType::RentedInaccessible(machine_id, _) = machine_fault_type.clone() - { - DLCMachine2ReportInfo::::mutate(machine_id, |report_info| { - if let Some((_, reporter_evm_address, exec_time)) = *report_info { - *report_info = Some((report_id.clone(), reporter_evm_address, exec_time)); - return *report_info - }; - *report_info - }); - } - } // 记录到 live_report & reporter_report live_report.new_report(report_id); reporter_report.new_report(report_id); @@ -953,7 +794,7 @@ impl Pallet { reporter.clone(), report_time, machine_fault_type.clone(), - stake_amount, + stake_params.stake_per_report, ), ); @@ -961,35 +802,6 @@ impl Pallet { Ok(().into()) } - fn do_report_dlc_machine_fault( - reporter: T::AccountId, - machine_fault_type: MachineFaultType, - report_time: Option, - live_report: &mut MTLiveReportList, - reporter_report: &mut ReporterReportList, - ) -> Result { - // 获取处理报告需要的信息 - let report_id = Self::get_new_report_id(); - let report_time = report_time.unwrap_or_else(|| >::block_number()); - - // 记录到 live_report & reporter_report - live_report.new_report(report_id); - reporter_report.new_report(report_id); - - ReportInfo::::insert( - &report_id, - MTReportInfoDetail::new( - reporter.clone(), - report_time, - machine_fault_type.clone(), - BalanceOf::::zero(), - ), - ); - - Self::deposit_event(Event::ReportDLCMachineFault(reporter, machine_fault_type)); - Ok(report_id) - } - fn book_report( committee: T::AccountId, report_id: ReportId, @@ -1099,7 +911,6 @@ impl Pallet { Some(report_info.report_time), live_report, &mut reporter_report, - report_info.reporter_stake == BalanceOf::::zero(), ) .map_err(|_| ())?; @@ -1431,7 +1242,6 @@ impl Pallet { Some(report_info.report_time), live_report, &mut reporter_report, - report_info.reporter_stake == BalanceOf::::zero(), ); ReporterReport::::insert(&report_info.reporter, reporter_report); }, @@ -1446,103 +1256,4 @@ impl Pallet { ReportInfo::::insert(report_id, report_info); Ok(()) } - - pub fn get_dlc_asset_id() -> ::AssetId { - let asset_id: ::AssetId = ::DLCAssetId::get().into(); - asset_id.into() - } - - pub fn get_dlc_reserve_amount() -> ::Balance { - let reserve_amount = 10000 * ONE_DLC as u64; - DLCBalanceOf::::saturated_from(reserve_amount) - // reserve_amount.saturated_from - } - - pub fn pallet_account_id() -> Option { - PALLET_ID.try_into_account() - } - pub fn get_treasury_account_id() -> T::AccountId { - >::account_id() - } - - fn slash_reporter_dlc( - reporter: T::AccountId, - reward_who: Vec, - reporter_staked_dlc_amount: DLCBalanceOf, - ) -> Result<(), ()> { - let treasury_account = Self::get_treasury_account_id(); - // 如果reward_to为0,则将币转到国库 - let reward_to_num = reward_who.len() as u32; - - let asset_id = Self::get_dlc_asset_id(); - - let account_id_for_reserve_dlc = Self::pallet_account_id().ok_or(())?; - - if reward_to_num == 0 { - // Slash to Treasury - as Mutate>::transfer( - asset_id, - &account_id_for_reserve_dlc, - &treasury_account, - reporter_staked_dlc_amount, - Preservation::Expendable, - ) - .map_err(|_| ())?; - - AccountId2ReserveDLC::::mutate(&reporter, |reserve_dlc| { - *reserve_dlc = reserve_dlc.saturating_sub(reporter_staked_dlc_amount) - }); - - return Ok(()) - } - - let reward_each_get = - Perbill::from_rational(1u32, reward_to_num) * reporter_staked_dlc_amount; - let mut left_reward = reporter_staked_dlc_amount; - - for a_committee in &reward_who { - if left_reward >= reward_each_get { - as Mutate>::transfer( - asset_id.clone(), - &account_id_for_reserve_dlc, - a_committee, - reward_each_get, - Preservation::Expendable, - ) - .map_err(|_| ())?; - - AccountId2ReserveDLC::::mutate(&reporter, |reserve_dlc| { - *reserve_dlc = reserve_dlc.saturating_sub(reward_each_get) - }); - - left_reward = left_reward.checked_sub(&reward_each_get).ok_or(())?; - } else { - as Mutate>::transfer( - asset_id.clone(), - &account_id_for_reserve_dlc, - a_committee, - left_reward, - Preservation::Expendable, - ) - .map_err(|_| ())?; - - AccountId2ReserveDLC::::mutate(&reporter, |reserve_dlc| { - *reserve_dlc = reserve_dlc.saturating_sub(left_reward) - }); - } - } - - if left_reward > Zero::zero() { - as Mutate>::transfer( - asset_id, - &account_id_for_reserve_dlc, - &treasury_account, - left_reward, - Preservation::Expendable, - ) - .map_err(|_| ())?; - } - - Ok(()) - } } diff --git a/pallets/maintain-committee/src/mock.rs b/pallets/maintain-committee/src/mock.rs index 431f2ba7..81be8558 100644 --- a/pallets/maintain-committee/src/mock.rs +++ b/pallets/maintain-committee/src/mock.rs @@ -1,30 +1,25 @@ use crate as maintain_committee; -use crate::ONE_DLC; use dbc_price_ocw::MAX_LEN; use dbc_support::{ machine_type::{ CommitteeUploadInfo, Latitude, Longitude, StakerCustomizeInfo, StandardGpuPointPrice, }, - traits::DLCMachineReportStakingTrait, ONE_DAY, }; use frame_support::{ assert_ok, pallet_prelude::Weight, parameter_types, - traits::{AsEnsureOriginWithArg, ConstU128, ConstU32, OnFinalize, OnInitialize}, + traits::{ConstU32, OnFinalize, OnInitialize}, PalletId, }; pub use frame_system::RawOrigin; -use frame_system::{EnsureRoot, EnsureSigned, EnsureWithSuccess}; -use parity_scale_codec::Compact; -use sp_core::Pair; +use frame_system::{EnsureRoot, EnsureWithSuccess}; pub use sp_core::{ sr25519::{self, Signature}, H256, }; pub use sp_keyring::sr25519::Keyring as Sr25519Keyring; -use sp_keyring::AccountKeyring::Eve; use sp_runtime::{ generic::Header, testing::TestXt, @@ -182,10 +177,6 @@ parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights::simple_max(Weight::MAX); pub MaxProposalWeight: Weight = sp_runtime::Perbill::from_percent(50) * BlockWeights::get().max_block; } - -impl dlc_machine::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; -} type TechnicalCollective = pallet_collective::Instance2; impl pallet_collective::Config for TestRuntime { type RuntimeOrigin = RuntimeOrigin; @@ -252,8 +243,6 @@ impl maintain_committee::Config for TestRuntime { type CancelSlashOrigin = pallet_collective::EnsureProportionAtLeast; type SlashAndReward = GenericFunc; - type AssetId = u32; - type DLCAssetId = ConstU32<88>; } impl rent_machine::Config for TestRuntime { @@ -262,57 +251,6 @@ impl rent_machine::Config for TestRuntime { type RTOps = OnlineProfile; type DbcPrice = DBCPriceOCW; } - -impl rent_dlc_machine::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; - type RTOps = OnlineProfile; - type DbcPrice = DBCPriceOCW; - type AssetId = u32; - type DLCAssetId = ConstU32<88>; -} - -pub const DBCS: Balance = 1_000_000_000_000_000; -pub const DOLLARS: Balance = DBCS / 100; - -parameter_types! { - pub const AssetDeposit: Balance = 100 * DOLLARS; - pub const ApprovalDeposit: Balance = 1 * DOLLARS; - pub const StringLimit: u32 = 50; - pub const MetadataDepositBase: Balance = 10 * DOLLARS; - pub const MetadataDepositPerByte: Balance = 1 * DOLLARS; - - pub const AssetLockLimit: u32 = 1000; - pub const MinLockAmount: Balance = 1 * ONE_DLC; - pub const MaxLockDuration: BlockNumber = 1800 * ONE_DAY; -} -impl pallet_assets::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; - type Balance = u128; - type AssetId = u32; - type AssetIdParameter = Compact; - type Currency = Balances; - type CreateOrigin = - AsEnsureOriginWithArg::AccountId>>; - type ForceOrigin = EnsureRoot<::AccountId>; - type AssetDeposit = AssetDeposit; - type AssetAccountDeposit = ConstU128; - type MetadataDepositBase = MetadataDepositBase; - type MetadataDepositPerByte = MetadataDepositPerByte; - type ApprovalDeposit = ApprovalDeposit; - type StringLimit = StringLimit; - type Freezer = (); - type Extra = (); - type CallbackHandle = (); - type WeightInfo = pallet_assets::weights::SubstrateWeight; - type RemoveItemsLimit = ConstU32<1000>; - - type MinLockAmount = MinLockAmount; - - type MaxLockDuration = MaxLockDuration; - // #[cfg(feature = "runtime-benchmarks")] - // type BenchmarkHelper = (); -} - // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( pub enum TestRuntime where @@ -333,9 +271,6 @@ frame_support::construct_runtime!( MaintainCommittee: maintain_committee, TechnicalCommittee: pallet_collective::, RentMachine: rent_machine, - RentDlcMachine: rent_dlc_machine, - DlcMachine: dlc_machine, - Assets: pallet_assets, } ); @@ -653,62 +588,3 @@ pub fn new_test_with_init_params_ext_1() -> sp_io::TestExternalities { ext } - -pub fn new_test_with_init_dlc_rent_params_ext() -> sp_io::TestExternalities { - let eve = sp_core::sr25519::Pair::from(Eve); - let msg: Vec = b"abc".to_vec(); - let eve_sig = eve.sign(&msg[..]); - - let mut ext = new_test_with_init_machine_online(); - ext.execute_with(|| { - let machine_id = "8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48" - .as_bytes() - .to_vec(); - - let reporter = sr25519::Public::from(Sr25519Keyring::Eve); - // rent machine for 1 days - assert_ok!(RentMachine::rent_machine( - RuntimeOrigin::signed(reporter), - machine_id.clone(), - 4, - 1 * ONE_DAY - )); - assert_ok!(RentMachine::confirm_rent(RuntimeOrigin::signed(reporter), 0)); - - let dlc_renter = sr25519::Public::from(Sr25519Keyring::Two); - - let asset_id = RentDlcMachine::get_dlc_asset_id_parameter(); - assert_ok!(Assets::create(RuntimeOrigin::signed(dlc_renter), asset_id, dlc_renter, 1)); - assert_ok!(Assets::mint( - RuntimeOrigin::signed(dlc_renter), - asset_id, - dlc_renter, - 10_000_000 * ONE_DLC - )); - - assert_eq!(Assets::balance(asset_id.into(), dlc_renter), 10_000_000 * ONE_DLC); - - assert_ok!( - as DLCMachineReportStakingTrait>::report_dlc_staking( - msg, - eve_sig, - Eve.public(), - machine_id.clone() - ) - ); - - assert_eq!( - dlc_machine::DLCMachinesInStaking::::contains_key(&machine_id), - true - ); - - assert_ok!(RentDlcMachine::rent_dlc_machine( - RuntimeOrigin::signed(dlc_renter), - machine_id.clone(), - 4, - 1 * ONE_DAY * 2 - )); - }); - - ext -} diff --git a/pallets/maintain-committee/src/slash.rs b/pallets/maintain-committee/src/slash.rs index 5e6770ac..274378c1 100644 --- a/pallets/maintain-committee/src/slash.rs +++ b/pallets/maintain-committee/src/slash.rs @@ -1,142 +1,15 @@ use crate::{ - pallet::AccountId2ReserveDLC, Config, DLCBalanceOf, DLCMachine2ReportInfo, Pallet, - PendingSlashReview, ReportResult, ReporterStake, UnhandledReportResult, ONE_DLC, + Config, Pallet, PendingSlashReview, ReportResult, ReporterStake, UnhandledReportResult, }; use dbc_support::{ report::{MCSlashResult, MTReportResultInfo, ReportResultType}, traits::MTOps, ReportId, }; -use frame_support::{ - traits::{fungibles::Mutate, tokens::Preservation}, - IterableStorageMap, -}; -use sp_runtime::{SaturatedConversion, Saturating}; +use frame_support::IterableStorageMap; use sp_std::{vec, vec::Vec}; impl Pallet { - pub fn exec_slash_now(now: ::BlockNumber) -> Result<(), ()> { - for slashed_report_id in Self::unhandled_report_result(now) { - let mut report_result_info = Self::report_result(&slashed_report_id).ok_or(())?; - - let MTReportResultInfo { - reporter, - reporter_stake, - inconsistent_committee, - unruly_committee, - reward_committee, - committee_stake, - report_result, - .. - } = report_result_info.clone(); - - if !Self::is_dlc_machine_fault_report(report_result_info.report_id) { - Self::change_reporter_stake_on_report_close( - &reporter, - reporter_stake, - report_result.clone(), - ); - } - - let mut slashed_committee = unruly_committee; - // 无论哪种情况,被惩罚的委员会都是 未完成工作 + 与多数不一致的委员会 - slashed_committee.extend_from_slice(&inconsistent_committee); - - let mut reward_who = vec![]; - - match report_result { - ReportResultType::ReportSucceed => { - reward_who.extend_from_slice(&reward_committee); - reward_who.push(reporter.clone()); - if Self::is_dlc_machine_fault_report(report_result_info.report_id) { - let account_id_for_reserve_dlc = Self::pallet_account_id().ok_or(())?; - let asset_id = Self::get_dlc_asset_id(); - let reserve_amount = Self::get_dlc_reserve_amount(); - - as Mutate>::transfer( - asset_id, - &account_id_for_reserve_dlc, - &reporter, - reserve_amount, - Preservation::Expendable, - ) - .map_err(|_| ())?; - - AccountId2ReserveDLC::::mutate(&reporter, |reserve_dlc| { - *reserve_dlc = reserve_dlc.saturating_sub(reserve_amount) - }); - - dlc_machine::Pallet::::report_dlc_machine_slashed( - report_result_info.machine_id.clone(), - ); - } - }, - // NoConsensus means no committee confirm confirmation, should be slashed all - ReportResultType::NoConsensus => {}, - ReportResultType::ReportRefused | - ReportResultType::ReporterNotSubmitEncryptedInfo => { - if !Self::is_dlc_machine_fault_report(report_result_info.report_id) { - // 惩罚报告人 - let _ = Self::slash_and_reward( - vec![reporter.clone()], - reporter_stake, - reward_committee.clone(), - ); - } else { - let _ = Self::slash_reporter_dlc( - reporter, - reward_committee.clone(), - DLCBalanceOf::::saturated_from(10000 * ONE_DLC as u64), - ); - } - }, - } - - let _ = Self::change_committee_stake_on_report_close( - reward_committee.clone(), - committee_stake, - false, - ); - let _ = Self::change_committee_stake_on_report_close( - slashed_committee.clone(), - committee_stake, - true, - ); - let _ = Self::slash_and_reward(slashed_committee, committee_stake, reward_who); - - report_result_info.slash_result = MCSlashResult::Executed; - ReportResult::::insert(slashed_report_id, report_result_info.clone()); - - if Self::is_dlc_machine_fault_report(report_result_info.report_id) { - if report_result == ReportResultType::ReportSucceed { - DLCMachine2ReportInfo::::mutate( - report_result_info.machine_id, - |report_info| { - if let Some((report_id, reporter_evm_address, _)) = *report_info { - *report_info = Some(( - report_id.clone(), - reporter_evm_address.clone(), - report_result_info.slash_exec_time.saturated_into::(), - )); - return *report_info - }; - *report_info - }, - ); - } else { - DLCMachine2ReportInfo::::remove(report_result_info.machine_id); - } - } - } - - // NOTE: 检查之后再删除,速度上要快非常多 - if UnhandledReportResult::::contains_key(now) { - UnhandledReportResult::::remove(now); - } - - Ok(()) - } - pub fn exec_slash() -> Result<(), ()> { let now = >::block_number(); for slashed_report_id in Self::unhandled_report_result(now) { @@ -153,14 +26,11 @@ impl Pallet { .. } = report_result_info.clone(); - if !Self::is_dlc_machine_fault_report(report_result_info.report_id) { - Self::change_reporter_stake_on_report_close( - &reporter, - reporter_stake, - report_result.clone(), - ); - } - + Self::change_reporter_stake_on_report_close( + &reporter, + reporter_stake, + report_result.clone(), + ); let mut slashed_committee = unruly_committee; // 无论哪种情况,被惩罚的委员会都是 未完成工作 + 与多数不一致的委员会 slashed_committee.extend_from_slice(&inconsistent_committee); @@ -170,48 +40,18 @@ impl Pallet { match report_result { ReportResultType::ReportSucceed => { reward_who.extend_from_slice(&reward_committee); - reward_who.push(reporter.clone()); - if Self::is_dlc_machine_fault_report(report_result_info.report_id) { - let account_id_for_reserve_dlc = Self::pallet_account_id().ok_or(())?; - let asset_id = Self::get_dlc_asset_id(); - let reserve_amount = Self::get_dlc_reserve_amount(); - - as Mutate>::transfer( - asset_id, - &account_id_for_reserve_dlc, - &reporter, - reserve_amount, - Preservation::Expendable, - ) - .map_err(|_| ())?; - - AccountId2ReserveDLC::::mutate(&reporter, |reserve_dlc| { - *reserve_dlc = reserve_dlc.saturating_sub(reserve_amount) - }); - - dlc_machine::Pallet::::report_dlc_machine_slashed( - report_result_info.machine_id.clone(), - ); - } + reward_who.push(reporter); }, // NoConsensus means no committee confirm confirmation, should be slashed all ReportResultType::NoConsensus => {}, ReportResultType::ReportRefused | ReportResultType::ReporterNotSubmitEncryptedInfo => { - if !Self::is_dlc_machine_fault_report(report_result_info.report_id) { - // 惩罚报告人 - let _ = Self::slash_and_reward( - vec![reporter.clone()], - reporter_stake, - reward_committee.clone(), - ); - } else { - let _ = Self::slash_reporter_dlc( - reporter, - reward_committee.clone(), - DLCBalanceOf::::saturated_from(10000 * ONE_DLC as u64), - ); - } + // 惩罚报告人 + let _ = Self::slash_and_reward( + vec![reporter.clone()], + reporter_stake, + reward_committee.clone(), + ); }, } @@ -228,28 +68,7 @@ impl Pallet { let _ = Self::slash_and_reward(slashed_committee, committee_stake, reward_who); report_result_info.slash_result = MCSlashResult::Executed; - ReportResult::::insert(slashed_report_id, report_result_info.clone()); - - if Self::is_dlc_machine_fault_report(report_result_info.report_id) { - if report_result == ReportResultType::ReportSucceed { - DLCMachine2ReportInfo::::mutate( - report_result_info.machine_id, - |report_info| { - if let Some((report_id, reporter_evm_address, _)) = *report_info { - *report_info = Some(( - report_id.clone(), - reporter_evm_address.clone(), - report_result_info.slash_exec_time.saturated_into::(), - )); - return *report_info - }; - *report_info - }, - ); - } else { - DLCMachine2ReportInfo::::remove(report_result_info.machine_id); - } - } + ReportResult::::insert(slashed_report_id, report_result_info); } // NOTE: 检查之后再删除,速度上要快非常多 @@ -308,11 +127,4 @@ impl Pallet { } Ok(()) } - - pub fn is_dlc_machine_fault_report(report_id: ReportId) -> bool { - if let Some(report_info) = Self::report_info(report_id) { - return report_info.reporter_stake == 0u32.into() - } - return false - } } diff --git a/pallets/maintain-committee/src/tests/mod.rs b/pallets/maintain-committee/src/tests/mod.rs index 371c315e..b431e52d 100644 --- a/pallets/maintain-committee/src/tests/mod.rs +++ b/pallets/maintain-committee/src/tests/mod.rs @@ -4,6 +4,4 @@ pub mod test_report_individual_gpu; pub mod test_reporter_apply_review; pub mod test_reporter_cancel_report_works; pub mod test_reporter_change_stake; - -pub mod test_report_dlc_machine_fault; pub mod tests; diff --git a/pallets/maintain-committee/src/tests/test_report_dlc_machine_fault.rs b/pallets/maintain-committee/src/tests/test_report_dlc_machine_fault.rs deleted file mode 100644 index 6aa509ec..00000000 --- a/pallets/maintain-committee/src/tests/test_report_dlc_machine_fault.rs +++ /dev/null @@ -1,800 +0,0 @@ -use super::super::mock::*; -use crate::{Error, MTOrderStatus, ReportStatus, ONE_DLC}; -use dbc_support::{ - live_machine::LiveMachine, machine_type::MachineStatus, verify_slash::OPSlashReason, ONE_DAY, - ONE_MINUTE, -}; -use frame_support::{assert_err, assert_ok}; -use once_cell::sync::Lazy; -use sp_core::H160; -use std::convert::TryInto; -// 报告机器被租用,但是无法访问 -// case1: 只有1委员会预订,同意报告 -// case2: 只有1委员会预订,拒绝报告 -// case3: 只有1人预订,提交了Hash, 未提交最终结果 -// case4: 只有1人预订,未提交Hash, 未提交最终结果 - -// case5: 有3人预订,都同意报告(最普通的情况) -// case6: 有3人预订,2同意1反对 -// case7: 有3人预订,1同意2反对 - -// case8: 有3人预订,0同意3反对 - -// case9: 2人预订,都同意 -// case10: 2人预订,都反对 -// case11: 2人预订,一同意,一反对 - -const committee: Lazy = - Lazy::new(|| sr25519::Public::from(Sr25519Keyring::One)); -const reporter: Lazy = - Lazy::new(|| sr25519::Public::from(Sr25519Keyring::Two)); -const machine_stash: Lazy = - Lazy::new(|| sr25519::Public::from(Sr25519Keyring::Ferdie)); - -const machine_id: Lazy> = Lazy::new(|| { - "8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48" - .as_bytes() - .to_vec() -}); - -#[test] -fn report_dlc_machine_agreed_by_committees_should_works() { - new_test_with_init_dlc_rent_params_ext().execute_with(|| { - let asset_id = MaintainCommittee::get_dlc_asset_id(); - - let owner = sr25519::Public::from(Sr25519Keyring::Eve); - let dlc_renter = sr25519::Public::from(Sr25519Keyring::Two); - let dlc_balance_before_report = Assets::balance(asset_id.into(), dlc_renter); - let dbc_balance_before_report = Balances::free_balance(dlc_renter); - - let rent_order_infos = RentDlcMachine::machine_rent_order(machine_id.clone()); - - let rent_dlc_machine_id = rent_order_infos.rent_order[0]; - assert_eq!(RentDlcMachine::rent_info(rent_dlc_machine_id).is_some(), true); - - let evm_address = H160::default(); - - assert_err!( - MaintainCommittee::report_dlc_machine_fault( - RuntimeOrigin::signed(owner), - machine_id.clone(), - rent_dlc_machine_id, - evm_address, - ), - Error::::NotDLCMachineRenter - ); - - // *** pallet_account_id must have some native token to keep alive - let pallet_account_id = MaintainCommittee::pallet_account_id().unwrap(); - assert_ok!(Balances::transfer( - RuntimeOrigin::signed(owner), - pallet_account_id, - 1 * ONE_DBC - )); - - assert_eq!(Assets::balance(asset_id.into(), dlc_renter), dlc_balance_before_report); - - assert_ok!(MaintainCommittee::report_dlc_machine_fault( - RuntimeOrigin::signed(dlc_renter.clone()), - machine_id.clone(), - rent_dlc_machine_id, - evm_address, - )); - - assert_eq!( - OnlineProfile::offline_machine_to_renters(machine_id.clone()).contains(&dlc_renter), - true - ); - - assert_eq!(Balances::free_balance(&pallet_account_id), 1 * ONE_DBC); - assert_eq!( - Assets::balance(asset_id.into(), dlc_renter), - dlc_balance_before_report - 10000 * ONE_DLC - ); - - assert_eq!(MaintainCommittee::account_id_2_reserve_dlc(dlc_renter), 10000 * ONE_DLC); - - // 判断调用举报之后的状态 - { - assert_eq!( - &MaintainCommittee::live_report(), - &crate::MTLiveReportList { bookable_report: vec![0], ..Default::default() } - ); - assert_eq!( - MaintainCommittee::report_info(0), - Some(crate::MTReportInfoDetail { - reporter: *reporter, - report_time: 11, - reporter_stake: 0, - machine_id: machine_id.clone(), - machine_fault_type: crate::MachineFaultType::RentedInaccessible( - machine_id.clone(), - 0 - ), - report_status: crate::ReportStatus::Reported, - first_book_time: 0, - rent_order_id: 0, - err_info: vec![], - verifying_committee: None, - booked_committee: vec![], - get_encrypted_info_committee: vec![], - hashed_committee: vec![], - confirm_start: BlockNumber::default(), - confirmed_committee: vec![], - support_committee: vec![], - against_committee: vec![] - }) - ); - assert_eq!( - &MaintainCommittee::reporter_report(&*reporter), - &crate::ReporterReportList { processing_report: vec![0], ..Default::default() } - ); - - // TODO: 检查free_balance - // reporter=committee,因此需要质押40000,减去租用机器的租金 - // assert_eq!(Balances::free_balance(&reporter), INIT_BALANCE - 40000 * ONE_DBC - 10 * - // ONE_DBC); - } - - // 委员会订阅机器故障报告 - assert_ok!(MaintainCommittee::committee_book_report(RuntimeOrigin::signed(*committee), 0)); - - // 检查订阅之后的状态 - // do_report_machine_fault: - // - Writes: - // LiveReport, ReportInfo, CommitteeOps, CommitteeOrder, committee pay txFee - { - assert_eq!( - &MaintainCommittee::live_report(), - &crate::MTLiveReportList { bookable_report: vec![0], ..Default::default() } - ); - assert_eq!( - MaintainCommittee::report_info(0), - Some(crate::MTReportInfoDetail { - reporter: *reporter, - report_time: 11, - reporter_stake: 0, - first_book_time: 11, - machine_id: machine_id.clone(), - verifying_committee: None, - booked_committee: vec![*committee], - confirm_start: 11 + 5 * ONE_MINUTE, - machine_fault_type: crate::MachineFaultType::RentedInaccessible( - machine_id.clone(), - 0 - ), - report_status: ReportStatus::WaitingBook, - rent_order_id: 0, - err_info: vec![], - get_encrypted_info_committee: vec![], - hashed_committee: vec![], - confirmed_committee: vec![], - support_committee: vec![], - against_committee: vec![] - }) - ); - assert_eq!( - &MaintainCommittee::committee_ops(&*committee, 0), - &crate::MTCommitteeOpsDetail { - booked_time: 11, - order_status: MTOrderStatus::Verifying, - ..Default::default() - } - ); - assert_eq!( - &MaintainCommittee::committee_order(&*committee), - &crate::MTCommitteeOrderList { booked_report: vec![0], ..Default::default() } - ); - - assert_eq!( - Balances::free_balance(&*committee), - INIT_BALANCE - 20000 * ONE_DBC - 10 * ONE_DBC - ); - } - - // 委员会首先提交Hash: 内容为 订单ID + 验证人自己的随机数 + 机器是否有问题 - // hash(0abcd1) => 0x73124a023f585b4018b9ed3593c7470a - let offline_committee_hash: [u8; 16] = - hex::decode("73124a023f585b4018b9ed3593c7470a").unwrap().try_into().unwrap(); - // - Writes: - // LiveReport, CommitteeOps, CommitteeOrder, ReportInfo - assert_ok!(MaintainCommittee::committee_submit_verify_hash( - RuntimeOrigin::signed(*committee), - 0, - offline_committee_hash.clone() - )); - - // 检查状态 - { - assert_eq!( - &MaintainCommittee::live_report(), - &crate::MTLiveReportList { bookable_report: vec![0], ..Default::default() } - ); - assert_eq!( - MaintainCommittee::report_info(0), - Some(crate::MTReportInfoDetail { - reporter: *reporter, - report_time: 11, - reporter_stake: 0, - first_book_time: 11, - machine_id: machine_id.clone(), - verifying_committee: None, - booked_committee: vec![*committee], - hashed_committee: vec![*committee], - confirm_start: 11 + 5 * ONE_MINUTE, - machine_fault_type: crate::MachineFaultType::RentedInaccessible( - machine_id.clone(), - 0 - ), - report_status: ReportStatus::WaitingBook, - rent_order_id: 0, - err_info: vec![], - get_encrypted_info_committee: vec![], - confirmed_committee: vec![], - support_committee: vec![], - against_committee: vec![] - }) - ); - assert_eq!( - &MaintainCommittee::committee_ops(&*committee, 0), - &crate::MTCommitteeOpsDetail { - booked_time: 11, - confirm_hash: offline_committee_hash, - hash_time: 11, - order_status: MTOrderStatus::WaitingRaw, - ..Default::default() - } - ); - assert_eq!( - &MaintainCommittee::committee_order(&*committee), - &crate::MTCommitteeOrderList { - booked_report: vec![], - hashed_report: vec![0], - ..Default::default() - } - ); - } - - run_to_block(11 + 5 * ONE_MINUTE); - // - Writes: - // ReportInfo, committee_ops, - assert_ok!(MaintainCommittee::committee_submit_inaccessible_raw( - RuntimeOrigin::signed(*committee), - 0, - "abcd".as_bytes().to_vec(), - true - )); - - // 检查提交了确认信息后的状态 - { - assert_eq!( - MaintainCommittee::report_info(0), - Some(crate::MTReportInfoDetail { - reporter: *reporter, - report_time: 11, - reporter_stake: 0, - first_book_time: 11, - machine_id: machine_id.clone(), - verifying_committee: None, - booked_committee: vec![*committee], - hashed_committee: vec![*committee], - confirmed_committee: vec![*committee], - support_committee: vec![*committee], - confirm_start: 11 + 5 * ONE_MINUTE, - machine_fault_type: crate::MachineFaultType::RentedInaccessible( - machine_id.clone(), - 0 - ), - report_status: ReportStatus::SubmittingRaw, - rent_order_id: 0, - err_info: vec![], - get_encrypted_info_committee: vec![], - against_committee: vec![] - }) - ); - assert_eq!( - &MaintainCommittee::committee_ops(&*committee, 0), - &crate::MTCommitteeOpsDetail { - booked_time: 11, - confirm_hash: offline_committee_hash, - hash_time: 11, - confirm_time: 12 + 5 * ONE_MINUTE, - confirm_result: true, - order_status: MTOrderStatus::Finished, - ..Default::default() - } - ); - } - - run_to_block(12 + 5 * ONE_MINUTE); - - // 检查summary的结果 - // summary_a_inaccessible - // - Writes: - // ReportInfo, ReportResult, CommitteeOrder, CommitteeOps - // LiveReport, UnhandledReportResult, ReporterReport, - { - assert_eq!( - MaintainCommittee::report_info(0), - Some(crate::MTReportInfoDetail { - reporter: *reporter, - report_time: 11, - reporter_stake: 0, - first_book_time: 11, - machine_id: machine_id.clone(), - verifying_committee: None, - booked_committee: vec![*committee], - hashed_committee: vec![*committee], - confirmed_committee: vec![*committee], - support_committee: vec![*committee], - confirm_start: 11 + 5 * ONE_MINUTE, - machine_fault_type: crate::MachineFaultType::RentedInaccessible( - machine_id.clone(), - 0 - ), - report_status: ReportStatus::CommitteeConfirmed, - rent_order_id: 0, - err_info: vec![], - get_encrypted_info_committee: vec![], - against_committee: vec![] - }) - ); - assert_eq!( - MaintainCommittee::report_result(0), - Some(crate::MTReportResultInfo { - report_id: 0, - reporter: *reporter, - reporter_stake: 0, - reward_committee: vec![*committee], - machine_id: machine_id.clone(), - machine_stash: Some(*machine_stash), - slash_time: 12 + 5 * ONE_MINUTE, - slash_exec_time: 12 + 5 * ONE_MINUTE + ONE_DAY * 2, - report_result: crate::ReportResultType::ReportSucceed, - slash_result: crate::MCSlashResult::Pending, - inconsistent_committee: vec![], - unruly_committee: vec![], - committee_stake: 0 - }) - ); - assert_eq!( - &MaintainCommittee::committee_order(&*committee), - &crate::MTCommitteeOrderList { finished_report: vec![0], ..Default::default() } - ); - assert_eq!( - &MaintainCommittee::committee_ops(&*committee, 0), - &crate::MTCommitteeOpsDetail { - booked_time: 11, - confirm_hash: offline_committee_hash, - hash_time: 11, - confirm_time: 12 + 5 * ONE_MINUTE, - confirm_result: true, - order_status: crate::MTOrderStatus::Finished, - - ..Default::default() - } - ); - assert_eq!( - &MaintainCommittee::live_report(), - &crate::MTLiveReportList { finished_report: vec![0], ..Default::default() } - ); - let unhandled_report_result: Vec = vec![0]; - - assert_eq!( - &MaintainCommittee::unhandled_report_result(12 + 5 * ONE_MINUTE + ONE_DAY * 2), - &unhandled_report_result - ); - assert_eq!( - &MaintainCommittee::reporter_report(&*reporter), - &crate::ReporterReportList { succeed_report: vec![0], ..Default::default() } - ); - } - - { - assert_eq!( - OnlineProfile::live_machines(), - LiveMachine { offline_machine: vec![machine_id.clone()], ..Default::default() } - ); - let machine_info = OnlineProfile::machines_info(machine_id.clone()).unwrap(); - assert_eq!( - machine_info.machine_status, - MachineStatus::ReporterReportOffline( - OPSlashReason::RentedInaccessible(11), - Box::new(MachineStatus::Rented), - *reporter, - vec![*committee], - ) - ); - } - - // run_to_block(1200+(12 + 5 * ONE_MINUTE) + ONE_DAY * 2); - run_to_block(10 + 12 + 5 * ONE_MINUTE + ONE_DAY * 2); - - let (report_id, evm_address, slash_at) = - MaintainCommittee::dlc_machine_2_report_info(machine_id.clone()).unwrap(); - - assert_eq!(report_id, 0); - assert_eq!(evm_address, H160::default()); - assert_eq!(slash_at, (12 + 5 * ONE_MINUTE + ONE_DAY * 2) as u64); - assert_eq!(MaintainCommittee::account_id_2_reserve_dlc(dlc_renter), 0); - - assert_eq!(Assets::balance(asset_id.into(), dlc_renter), dlc_balance_before_report); - - assert_eq!(Balances::free_balance(dlc_renter), dbc_balance_before_report); - assert_eq!(DlcMachine::dlc_machine_in_staking(machine_id.clone()), false); - }) -} - -#[test] -fn report_dlc_machine_refused_by_committees_should_works() { - new_test_with_init_dlc_rent_params_ext().execute_with(|| { - let asset_id = MaintainCommittee::get_dlc_asset_id(); - - let owner = sr25519::Public::from(Sr25519Keyring::Eve); - let dlc_renter = sr25519::Public::from(Sr25519Keyring::Two); - let dlc_balance_before_report = Assets::balance(asset_id.into(), dlc_renter); - - let rent_order_infos = RentDlcMachine::machine_rent_order(machine_id.clone()); - - let rent_dlc_machine_id = rent_order_infos.rent_order[0]; - assert_eq!(RentDlcMachine::rent_info(rent_dlc_machine_id).is_some(), true); - let evm_address = H160::default(); - - assert_err!( - MaintainCommittee::report_dlc_machine_fault( - RuntimeOrigin::signed(owner), - machine_id.clone(), - rent_dlc_machine_id, - evm_address, - ), - Error::::NotDLCMachineRenter - ); - - // *** pallet_account_id must have some native token to keep alive - let pallet_account_id = MaintainCommittee::pallet_account_id().unwrap(); - assert_ok!(Balances::transfer( - RuntimeOrigin::signed(owner), - pallet_account_id, - 1 * ONE_DBC - )); - - assert_eq!(Assets::balance(asset_id.into(), dlc_renter), dlc_balance_before_report); - - assert_ok!(MaintainCommittee::report_dlc_machine_fault( - RuntimeOrigin::signed(dlc_renter.clone()), - machine_id.clone(), - rent_dlc_machine_id, - evm_address, - )); - - assert_eq!( - OnlineProfile::offline_machine_to_renters(machine_id.clone()).contains(&dlc_renter), - true - ); - - assert_eq!(Balances::free_balance(&pallet_account_id), 1 * ONE_DBC); - assert_eq!( - Assets::balance(asset_id.into(), dlc_renter), - dlc_balance_before_report - 10000 * ONE_DLC - ); - - assert_eq!(MaintainCommittee::account_id_2_reserve_dlc(dlc_renter), 10000 * ONE_DLC); - - // 判断调用举报之后的状态 - { - assert_eq!( - &MaintainCommittee::live_report(), - &crate::MTLiveReportList { bookable_report: vec![0], ..Default::default() } - ); - assert_eq!( - MaintainCommittee::report_info(0), - Some(crate::MTReportInfoDetail { - reporter: *reporter, - report_time: 11, - reporter_stake: 0, - machine_id: machine_id.clone(), - machine_fault_type: crate::MachineFaultType::RentedInaccessible( - machine_id.clone(), - 0 - ), - report_status: crate::ReportStatus::Reported, - first_book_time: 0, - rent_order_id: 0, - err_info: vec![], - verifying_committee: None, - booked_committee: vec![], - get_encrypted_info_committee: vec![], - hashed_committee: vec![], - confirm_start: 0, - confirmed_committee: vec![], - support_committee: vec![], - against_committee: vec![] - }) - ); - assert_eq!( - &MaintainCommittee::reporter_report(&*reporter), - &crate::ReporterReportList { processing_report: vec![0], ..Default::default() } - ); - } - - // 委员会订阅机器故障报告 - assert_ok!(MaintainCommittee::committee_book_report(RuntimeOrigin::signed(*committee), 0)); - - // 检查订阅之后的状态 - // do_report_machine_fault: - // - Writes: - // LiveReport, ReportInfo, CommitteeOps, CommitteeOrder, committee pay txFee - { - assert_eq!( - &MaintainCommittee::live_report(), - &crate::MTLiveReportList { bookable_report: vec![0], ..Default::default() } - ); - assert_eq!( - MaintainCommittee::report_info(0), - Some(crate::MTReportInfoDetail { - reporter: *reporter, - report_time: 11, - reporter_stake: 0, - first_book_time: 11, - machine_id: machine_id.clone(), - verifying_committee: None, - booked_committee: vec![*committee], - confirm_start: 11 + 5 * ONE_MINUTE, - machine_fault_type: crate::MachineFaultType::RentedInaccessible( - machine_id.clone(), - 0 - ), - report_status: ReportStatus::WaitingBook, - rent_order_id: 0, - err_info: vec![], - get_encrypted_info_committee: vec![], - hashed_committee: vec![], - confirmed_committee: vec![], - support_committee: vec![], - against_committee: vec![] - }) - ); - assert_eq!( - &MaintainCommittee::committee_ops(&*committee, 0), - &crate::MTCommitteeOpsDetail { - booked_time: 11, - order_status: MTOrderStatus::Verifying, - ..Default::default() - } - ); - assert_eq!( - &MaintainCommittee::committee_order(&*committee), - &crate::MTCommitteeOrderList { booked_report: vec![0], ..Default::default() } - ); - - assert_eq!( - Balances::free_balance(&*committee), - INIT_BALANCE - 20000 * ONE_DBC - 10 * ONE_DBC - ); - } - - // 委员会首先提交Hash: 内容为 订单ID + 验证人自己的随机数 + 机器是否有问题 - // hash(0abcd1) => 0x73124a023f585b4018b9ed3593c7470a - let offline_committee_hash: [u8; 16] = - hex::decode("98b18d58d8d3bc2f2037cb8310dd6f0e").unwrap().try_into().unwrap(); - // - Writes: - // LiveReport, CommitteeOps, CommitteeOrder, ReportInfo - assert_ok!(MaintainCommittee::committee_submit_verify_hash( - RuntimeOrigin::signed(*committee), - 0, - offline_committee_hash.clone() - )); - - let committee_dlc_balance_before_refuse_report = - Assets::balance(asset_id.into(), *committee); - assert_eq!(committee_dlc_balance_before_refuse_report, 0); - // 检查状态 - { - assert_eq!( - &MaintainCommittee::live_report(), - &crate::MTLiveReportList { bookable_report: vec![0], ..Default::default() } - ); - assert_eq!( - MaintainCommittee::report_info(0), - Some(crate::MTReportInfoDetail { - reporter: *reporter, - report_time: 11, - reporter_stake: 0, - first_book_time: 11, - machine_id: machine_id.clone(), - verifying_committee: None, - booked_committee: vec![*committee], - hashed_committee: vec![*committee], - confirm_start: 11 + 5 * ONE_MINUTE, - machine_fault_type: crate::MachineFaultType::RentedInaccessible( - machine_id.clone(), - 0 - ), - report_status: ReportStatus::WaitingBook, - rent_order_id: 0, - err_info: vec![], - get_encrypted_info_committee: vec![], - confirmed_committee: vec![], - support_committee: vec![], - against_committee: vec![] - }) - ); - assert_eq!( - &MaintainCommittee::committee_ops(&*committee, 0), - &crate::MTCommitteeOpsDetail { - booked_time: 11, - confirm_hash: offline_committee_hash, - hash_time: 11, - order_status: MTOrderStatus::WaitingRaw, - ..Default::default() - } - ); - - assert_eq!( - &MaintainCommittee::committee_order(&*committee), - &crate::MTCommitteeOrderList { - booked_report: vec![], - hashed_report: vec![0], - ..Default::default() - } - ); - } - - run_to_block(11 + 5 * ONE_MINUTE); - // - Writes: - // ReportInfo, committee_ops, - assert_ok!(MaintainCommittee::committee_submit_inaccessible_raw( - RuntimeOrigin::signed(*committee), - 0, - "fedcba111".as_bytes().to_vec(), - false - )); - - // 检查提交了确认信息后的状态 - { - assert_eq!( - MaintainCommittee::report_info(0), - Some(crate::MTReportInfoDetail { - reporter: *reporter, - report_time: 11, - reporter_stake: 0, - first_book_time: 11, - machine_id: machine_id.clone(), - verifying_committee: None, - booked_committee: vec![*committee], - hashed_committee: vec![*committee], - confirmed_committee: vec![*committee], - support_committee: vec![], - confirm_start: 11 + 5 * ONE_MINUTE, - machine_fault_type: crate::MachineFaultType::RentedInaccessible( - machine_id.clone(), - 0 - ), - report_status: ReportStatus::SubmittingRaw, - rent_order_id: 0, - err_info: vec![], - get_encrypted_info_committee: vec![], - against_committee: vec![*committee] - }) - ); - assert_eq!( - &MaintainCommittee::committee_ops(&*committee, 0), - &crate::MTCommitteeOpsDetail { - booked_time: 11, - confirm_hash: offline_committee_hash, - hash_time: 11, - confirm_time: 12 + 5 * ONE_MINUTE, - confirm_result: false, - order_status: MTOrderStatus::Finished, - ..Default::default() - } - ); - } - - run_to_block(12 + 5 * ONE_MINUTE); - - // 检查summary的结果 - // summary_a_inaccessible - // - Writes: - // ReportInfo, ReportResult, CommitteeOrder, CommitteeOps - // LiveReport, UnhandledReportResult, ReporterReport, - { - assert_eq!( - MaintainCommittee::report_info(0), - Some(crate::MTReportInfoDetail { - reporter: *reporter, - report_time: 11, - reporter_stake: 0, - first_book_time: 11, - machine_id: machine_id.clone(), - verifying_committee: None, - booked_committee: vec![*committee], - hashed_committee: vec![*committee], - confirmed_committee: vec![*committee], - support_committee: vec![], - confirm_start: 11 + 5 * ONE_MINUTE, - machine_fault_type: crate::MachineFaultType::RentedInaccessible( - machine_id.clone(), - 0 - ), - report_status: ReportStatus::CommitteeConfirmed, - rent_order_id: 0, - err_info: vec![], - get_encrypted_info_committee: vec![], - against_committee: vec![*committee] - }) - ); - assert_eq!( - MaintainCommittee::report_result(0), - Some(crate::MTReportResultInfo { - report_id: 0, - reporter: *reporter, - reporter_stake: 0, - reward_committee: vec![*committee], - machine_id: machine_id.clone(), - machine_stash: Some(*machine_stash), - slash_time: 12 + 5 * ONE_MINUTE, - slash_exec_time: 12 + 5 * ONE_MINUTE + ONE_DAY * 2, - report_result: crate::ReportResultType::ReportRefused, - slash_result: crate::MCSlashResult::Pending, - inconsistent_committee: vec![], - unruly_committee: vec![], - committee_stake: 0 - }) - ); - assert_eq!( - &MaintainCommittee::committee_order(&*committee), - &crate::MTCommitteeOrderList { finished_report: vec![0], ..Default::default() } - ); - assert_eq!( - &MaintainCommittee::committee_ops(&*committee, 0), - &crate::MTCommitteeOpsDetail { - booked_time: 11, - confirm_hash: offline_committee_hash, - hash_time: 11, - confirm_time: 12 + 5 * ONE_MINUTE, - confirm_result: false, - order_status: crate::MTOrderStatus::Finished, - - ..Default::default() - } - ); - assert_eq!( - &MaintainCommittee::live_report(), - &crate::MTLiveReportList { finished_report: vec![0], ..Default::default() } - ); - let unhandled_report_result: Vec = vec![0]; - assert_eq!( - &MaintainCommittee::unhandled_report_result(12 + 5 * ONE_MINUTE + ONE_DAY * 2), - &unhandled_report_result - ); - assert_eq!( - &MaintainCommittee::reporter_report(&*reporter), - &crate::ReporterReportList { failed_report: vec![0], ..Default::default() } - ); - } - - { - assert_eq!( - OnlineProfile::live_machines(), - LiveMachine { rented_machine: vec![machine_id.clone()], ..Default::default() } - ); - let machine_info = OnlineProfile::machines_info(machine_id.clone()).unwrap(); - assert_eq!(machine_info.machine_status, MachineStatus::Rented); - } - - run_to_block(10 + 12 + 5 * ONE_MINUTE + ONE_DAY * 2); - - assert_eq!(MaintainCommittee::account_id_2_reserve_dlc(dlc_renter), 0); - - assert_eq!( - Assets::balance(asset_id.into(), dlc_renter), - dlc_balance_before_report - 10000 * ONE_DLC - ); - assert_eq!( - Assets::balance(asset_id.into(), *committee), - committee_dlc_balance_before_refuse_report + 10000 * ONE_DLC - ); - assert_eq!(DlcMachine::dlc_machine_in_staking(machine_id.clone()), true); - }) -} diff --git a/pallets/online-profile/src/lib.rs b/pallets/online-profile/src/lib.rs index 4b849150..47077a89 100644 --- a/pallets/online-profile/src/lib.rs +++ b/pallets/online-profile/src/lib.rs @@ -356,6 +356,44 @@ pub mod pallet { Weight::zero() } + fn on_runtime_upgrade() -> Weight { + let now = >::block_number(); + + let machine_id = "f2ed83f9fe6d26ae802fd26e021588ed3f33cd953dc5b208e627d69387336151" + .as_bytes() + .to_vec(); + + let machine_info_result = Self::machines_info(&machine_id); + match machine_info_result { + Some(mut machine_info) => { + if machine_info.reward_deadline > 0 { + return Weight::zero() + } + + machine_info.online_height = now; + let current_era = Self::current_era(); + machine_info.reward_deadline = current_era + REWARD_DURATION; + + MachineRecentReward::::insert( + &machine_id, + MachineRecentRewardInfo { + machine_stash: machine_info.machine_stash.clone(), + reward_committee_deadline: machine_info.reward_deadline, + reward_committee: machine_info.reward_committee.clone(), + recent_machine_reward: VecDeque::new(), + recent_reward_sum: 0u32.into(), + }, + ); + + machine_info.last_online_height = now; + machine_info.last_machine_restake = now; + }, + None => {}, + } + + Weight::zero() + } + // fn on_runtime_upgrade() -> frame_support::weights::Weight { // frame_support::log::info!("🔍 OnlineProfile storage upgrade start"); // if let Some(mut stake_params) = Self::online_stake_params() { @@ -706,22 +744,21 @@ pub mod pallet { UserMutHardwareStake::::contains_key(&machine_info.machine_stash, &machine_id); if is_reonline { UserMutHardwareStake::::remove(&machine_info.machine_stash, &machine_id); - } else { - // 当机器因为补交质押而上线时,不应该记录上线时间为Now - machine_info.online_height = now; - machine_info.reward_deadline = current_era + REWARD_DURATION; - - MachineRecentReward::::insert( - &machine_id, - MachineRecentRewardInfo { - machine_stash: machine_info.machine_stash.clone(), - reward_committee_deadline: machine_info.reward_deadline, - reward_committee: machine_info.reward_committee.clone(), - recent_machine_reward: VecDeque::new(), - recent_reward_sum: 0u32.into(), - }, - ); } + // 当机器因为补交质押而上线时,不应该记录上线时间为Now + machine_info.online_height = now; + machine_info.reward_deadline = current_era + REWARD_DURATION; + + MachineRecentReward::::insert( + &machine_id, + MachineRecentRewardInfo { + machine_stash: machine_info.machine_stash.clone(), + reward_committee_deadline: machine_info.reward_deadline, + reward_committee: machine_info.reward_committee.clone(), + recent_machine_reward: VecDeque::new(), + recent_reward_sum: 0u32.into(), + }, + ); machine_info.last_online_height = now; machine_info.last_machine_restake = now; diff --git a/pallets/rent-dlc-machine/Cargo.toml b/pallets/rent-dlc-machine/Cargo.toml deleted file mode 100644 index deb0509d..00000000 --- a/pallets/rent-dlc-machine/Cargo.toml +++ /dev/null @@ -1,59 +0,0 @@ -[package] -name = "rent-dlc-machine" -version = { workspace = true } -authors = { workspace = true } -edition = "2021" - -[dependencies] -parity-scale-codec = { workspace = true } -dbc-support = { path = "../support", default-features = false } -scale-info = { workspace = true } - -frame-support = { workspace = true } -frame-system = { workspace = true } -sp-std = { workspace = true } -sp-runtime = { workspace = true } - -online-profile = { path = "../online-profile", default-features = false } -rent-machine = { path = "../rent-machine", default-features = false } -pallet-assets = { path = "../assets", default-features = false } -dlc-machine = { path = "../dlc-machine", default-features = false } - -[dev-dependencies] -once_cell = { workspace = true, features = ["std"] } -hex = { workspace = true, features = ["std"] } - -pallet-balances = { workspace = true, features = ["std"] } -pallet-treasury = { workspace = true, features = ["std"] } -sp-core = { workspace = true, features = ["std"] } -pallet-insecure-randomness-collective-flip = { workspace = true, features = ["std"] } -sp-io = { workspace = true, features = ["std"] } -sp-keyring = { workspace = true } -pallet-collective = { workspace = true, features = ["std"] } -pallet-timestamp = { workspace = true, features = ["std"] } - -pallet-assets = { path = "../assets" } -committee = { path = "../committee" } -online-committee = { path = "../online-committee" } -dbc-price-ocw = { path = "../dbc-price-ocw" } -generic-func = { path = "../generic-func"} -dbc-primitives = { path = "../../primitives", default-features = false } - - - - -[features] -default = ["std"] -std = [ - "parity-scale-codec/std", - "frame-support/std", - "frame-system/std", - "online-profile/std", - "rent-machine/std", - "online-profile/std", - "pallet-assets/std", - "sp-runtime/std", - "sp-std/std", - "rent-machine/std", -] -try-runtime = ["frame-support/try-runtime"] diff --git a/pallets/rent-dlc-machine/rpc/Cargo.toml b/pallets/rent-dlc-machine/rpc/Cargo.toml deleted file mode 100644 index 59ae3b48..00000000 --- a/pallets/rent-dlc-machine/rpc/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "rent-dlc-machine-rpc" -version = { workspace = true } -authors = { workspace = true } -edition = "2021" - -[dependencies] -parity-scale-codec = { workspace = true } -jsonrpsee = { workspace = true, features = ["client-core", "server", "macros"] } - -dbc-support = { path = "../../support" } -rent-dlc-machine-runtime-api = { path = "./runtime-api" } - -sp-api = { workspace = true, features = ["std"] } -sp-runtime = { workspace = true, features = ["std"] } -sp-blockchain = { workspace = true } diff --git a/pallets/rent-dlc-machine/rpc/runtime-api/Cargo.toml b/pallets/rent-dlc-machine/rpc/runtime-api/Cargo.toml deleted file mode 100644 index 717a8d98..00000000 --- a/pallets/rent-dlc-machine/rpc/runtime-api/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "rent-dlc-machine-runtime-api" -version = { workspace = true } -authors = { workspace = true } -edition = "2021" - -[dependencies] -parity-scale-codec = { workspace = true } -sp-api = { workspace = true } -sp-runtime = { workspace = true } -sp-std = { workspace = true } - -dbc-support = { path = "../../../support", default-features = false } - -[features] -default = ["std"] -std = [ - "parity-scale-codec/std", - "sp-api/std", - "sp-runtime/std", - "sp-std/std", - "dbc-support/std", -] diff --git a/pallets/rent-dlc-machine/rpc/runtime-api/src/lib.rs b/pallets/rent-dlc-machine/rpc/runtime-api/src/lib.rs deleted file mode 100644 index 7564b959..00000000 --- a/pallets/rent-dlc-machine/rpc/runtime-api/src/lib.rs +++ /dev/null @@ -1,29 +0,0 @@ -#![cfg_attr(not(feature = "std"), no_std)] -#![allow(clippy::too_many_arguments)] -#![allow(clippy::unnecessary_mut_passed)] -#![warn(unused_crate_dependencies)] - -use parity_scale_codec::Codec; -use sp_runtime::traits::MaybeDisplay; -use sp_std::prelude::Vec; - -use dbc_support::{ - rental_type::{MachineGPUOrder, RentOrderDetail}, - MachineId, RentOrderId, -}; - -// Here we declare the runtime API. It is implemented it the `impl` block in -// runtime amalgamator file (the `runtime/src/lib.rs`) -sp_api::decl_runtime_apis! { - pub trait DlcRmRpcApi where - AccountId: Codec + Ord, - BlockNumber: Codec + MaybeDisplay, - Balance: Codec + MaybeDisplay, - { - fn get_dlc_rent_order(rent_id: RentOrderId) -> Option>; - fn get_dlc_rent_list(renter: AccountId) -> Vec; - - fn is_dlc_machine_renter(machine_id: MachineId, renter: AccountId) -> bool; - fn get_dlc_machine_rent_id(machine_id: MachineId) -> MachineGPUOrder; - } -} diff --git a/pallets/rent-dlc-machine/rpc/src/lib.rs b/pallets/rent-dlc-machine/rpc/src/lib.rs deleted file mode 100644 index 772af34e..00000000 --- a/pallets/rent-dlc-machine/rpc/src/lib.rs +++ /dev/null @@ -1,168 +0,0 @@ -#![warn(unused_crate_dependencies)] - -use jsonrpsee::{ - core::{Error as JsonRpseeError, RpcResult}, - proc_macros::rpc, - types::error::{CallError, ErrorCode, ErrorObject}, -}; -use parity_scale_codec::Codec; -use sp_api::ProvideRuntimeApi; -use sp_blockchain::HeaderBackend; -use sp_runtime::traits::{Block as BlockT, MaybeDisplay}; -use std::{fmt::Display, str::FromStr, sync::Arc}; - -use dbc_support::{ - rental_type::{MachineGPUOrder, RentOrderDetail}, - rpc_types::RpcBalance, - RentOrderId, -}; -pub use rent_dlc_machine_runtime_api::DlcRmRpcApi as RmDlcStorageRuntimeApi; - -#[rpc(client, server)] -pub trait DlcRmRpcApi -where - Balance: Display + FromStr, -{ - #[method(name = "rentDlcMachine_getDlcRentOrder")] - fn get_dlc_rent_order( - &self, - rent_id: RentOrderId, - at: Option, - ) -> RpcResult>>; - - #[method(name = "rentDlcMachine_getDlcRentList")] - fn get_dlc_rent_list( - &self, - renter: AccountId, - at: Option, - ) -> RpcResult>; - - #[method(name = "rentDlcMachine_isDlcMachineRenter")] - fn is_dlc_machine_renter( - &self, - machine_id: String, - renter: AccountId, - at: Option, - ) -> RpcResult; - - #[method(name = "rentDlcMachine_getDlcMachineRentId")] - fn get_dlc_machine_rent_id( - &self, - machine_id: String, - at: Option, - ) -> RpcResult; -} - -pub struct DlcRmStorage { - client: Arc, - _marker: std::marker::PhantomData, -} - -impl DlcRmStorage { - pub fn new(client: Arc) -> Self { - Self { client, _marker: Default::default() } - } -} - -impl - DlcRmRpcApiServer<::Hash, AccountId, BlockNumber, Balance> - for DlcRmStorage -where - Block: BlockT, - AccountId: Clone + std::fmt::Display + Codec + Ord, - Balance: Codec + MaybeDisplay + Copy + FromStr, - BlockNumber: Clone + std::fmt::Display + Codec, - C: Send + Sync + 'static, - C: ProvideRuntimeApi, - C: HeaderBackend, - C::Api: RmDlcStorageRuntimeApi, -{ - fn get_dlc_rent_order( - &self, - rent_id: RentOrderId, - at: Option, - ) -> RpcResult>> { - let api = self.client.runtime_api(); - let at_hash = at.unwrap_or_else(|| self.client.info().best_hash); - - let runtime_api_result = api.get_dlc_rent_order(at_hash, rent_id); - if let Ok(Some(order_detail)) = runtime_api_result { - return Ok(RentOrderDetail { - machine_id: order_detail.machine_id, - renter: order_detail.renter, - rent_start: order_detail.rent_start, - confirm_rent: order_detail.confirm_rent, - rent_end: order_detail.rent_end, - stake_amount: order_detail.stake_amount.into(), - rent_status: order_detail.rent_status, - gpu_num: order_detail.gpu_num, - gpu_index: order_detail.gpu_index, - }) - } - return Err(JsonRpseeError::Call(CallError::Custom(ErrorObject::owned( - ErrorCode::InternalError.code(), - "Something wrong", - Some("NotFound"), - )))) - } - - fn get_dlc_rent_list( - &self, - renter: AccountId, - at: Option, - ) -> RpcResult> { - let api = self.client.runtime_api(); - let at_hash = at.unwrap_or_else(|| self.client.info().best_hash); - - let runtime_api_result = api.get_dlc_rent_list(at_hash, renter).map_err(|e| { - JsonRpseeError::Call(CallError::Custom(ErrorObject::owned( - ErrorCode::InternalError.code(), - "Something wrong", - Some(e.to_string()), - ))) - })?; - - Ok(runtime_api_result) - } - - fn is_dlc_machine_renter( - &self, - machine_id: String, - renter: AccountId, - at: Option, - ) -> RpcResult { - let api = self.client.runtime_api(); - let at_hash = at.unwrap_or_else(|| self.client.info().best_hash); - - let machine_id = machine_id.as_bytes().to_vec(); - let runtime_api_result = - api.is_dlc_machine_renter(at_hash, machine_id, renter).map_err(|e| { - JsonRpseeError::Call(CallError::Custom(ErrorObject::owned( - ErrorCode::InternalError.code(), - "Something wrong", - Some(e.to_string()), - ))) - })?; - Ok(runtime_api_result) - } - - fn get_dlc_machine_rent_id( - &self, - machine_id: String, - at: Option, - ) -> RpcResult { - let api = self.client.runtime_api(); - let at_hash = at.unwrap_or_else(|| self.client.info().best_hash); - - let machine_id = machine_id.as_bytes().to_vec(); - let runtime_api_result = api.get_dlc_machine_rent_id(at_hash, machine_id).map_err(|e| { - JsonRpseeError::Call(CallError::Custom(ErrorObject::owned( - ErrorCode::InternalError.code(), - "Something wrong", - Some(e.to_string()), - ))) - })?; - - Ok(runtime_api_result) - } -} diff --git a/pallets/rent-dlc-machine/src/lib.rs b/pallets/rent-dlc-machine/src/lib.rs deleted file mode 100644 index 7468dbb1..00000000 --- a/pallets/rent-dlc-machine/src/lib.rs +++ /dev/null @@ -1,596 +0,0 @@ -#![recursion_limit = "256"] -#![cfg_attr(not(feature = "std"), no_std)] -#![warn(unused_crate_dependencies)] - -// pub mod migrations; -mod rpc; - -#[cfg(test)] -mod mock; -#[allow(non_upper_case_globals)] -#[cfg(test)] -mod tests; - -pub use dbc_support::machine_type::MachineStatus; -use dbc_support::{ - rental_type::{ - DlcBurnDetail, MachineGPUOrder, MachineRenterRentedOrderDetail, RentOrderDetail, RentStatus, - }, - traits::{DLCMachineInfoTrait, DbcPrice, PhaseLevel, RTOps}, - EraIndex, ItemList, MachineId, RentOrderId, HALF_HOUR, ONE_DAY, -}; -use frame_support::{ - ensure, - pallet_prelude::*, - traits::tokens::{ - fungibles::{Inspect, Mutate}, - Fortitude, Precision, - }, -}; -use frame_system::{ensure_signed, pallet_prelude::*}; -use sp_runtime::{ - traits::{CheckedAdd, CheckedDiv, CheckedMul, SaturatedConversion, Saturating, Zero}, - Perbill, -}; -use sp_std::{prelude::*, vec, vec::Vec}; - -type BalanceOf = ::Balance; -pub use pallet::*; - -#[frame_support::pallet] -pub mod pallet { - use super::*; - - #[pallet::config] - pub trait Config: - frame_system::Config - + online_profile::Config - + rent_machine::Config - + pallet_assets::Config - + dlc_machine::Config - { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; - type RTOps: RTOps< - MachineId = MachineId, - MachineStatus = MachineStatus, - AccountId = Self::AccountId, - Balance = BalanceOf, - BlockNumber = Self::BlockNumber, - >; - type DbcPrice: DbcPrice>; - type AssetId: IsType<::AssetId> + Parameter + From; - - #[pallet::constant] - type DLCAssetId: Get; - } - - #[pallet::pallet] - #[pallet::without_storage_info] - pub struct Pallet(_); - - #[pallet::hooks] - impl Hooks> for Pallet { - fn on_finalize(_block_number: T::BlockNumber) { - let _ = Self::check_if_rent_finished(); - } - } - - #[pallet::storage] - #[pallet::getter(fn user_order)] - pub(super) type UserOrder = - StorageMap<_, Blake2_128Concat, T::AccountId, Vec, ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn machine_rent_order)] - pub type MachineRentOrder = - StorageMap<_, Blake2_128Concat, MachineId, MachineGPUOrder, ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn next_rent_id)] - pub(super) type NextRentId = StorageValue<_, RentOrderId, ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn rent_info)] - pub type RentInfo = StorageMap< - _, - Blake2_128Concat, - RentOrderId, - RentOrderDetail>, - >; - - #[pallet::storage] - #[pallet::getter(fn dlc_machine_rented_gpu)] - pub type DLCMachineRentedGPU = - StorageMap<_, Blake2_128Concat, MachineId, u32, ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn rent_ending)] - pub(super) type RentEnding = - StorageMap<_, Blake2_128Concat, T::BlockNumber, Vec, ValueQuery>; - - #[pallet::type_value] - pub(super) fn MaximumRentalDurationDefault() -> EraIndex { - 60 - } - - #[pallet::storage] - #[pallet::getter(fn maximum_rental_duration)] - pub(super) type MaximumRentalDuration = - StorageValue<_, EraIndex, ValueQuery, MaximumRentalDurationDefault>; - - #[pallet::storage] - #[pallet::getter(fn burn_total_amount)] - pub(super) type BurnTotalAmount = StorageValue<_, BalanceOf, ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn burn_details)] - pub(super) type BurnDetails = - StorageValue<_, Vec, T::BlockNumber>>, ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn machine_id_2_burn_record)] - pub(super) type MachineId2BurnRecord = StorageDoubleMap< - _, - Blake2_128Concat, - PhaseLevel, - Blake2_128Concat, - MachineId, - Vec, T::BlockNumber>>, - ValueQuery, - >; - - #[pallet::storage] - #[pallet::getter(fn dlc_rent_id_2_parent_dbc_rent_id)] - pub type DlcRentId2ParentDbcRentId = - StorageMap<_, Blake2_128Concat, RentOrderId, RentOrderId>; - - #[pallet::storage] - #[pallet::getter(fn dlc_machine_rented_orders)] - pub type DlcMachineRentedOrders = StorageMap< - _, - Blake2_128Concat, - MachineId, - Vec>, - ValueQuery, - >; - - #[pallet::call] - impl Pallet { - #[pallet::call_index(0)] - #[pallet::weight(Weight::from_parts(10000, 0))] - pub fn rent_dlc_machine( - origin: OriginFor, - machine_id: MachineId, - rent_gpu_num: u32, - duration: T::BlockNumber, - ) -> DispatchResultWithPostInfo { - let renter = ensure_signed(origin.clone())?; - Self::rent_machine_by_block(renter, machine_id, rent_gpu_num, duration) - } - } - - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { - PayTxFeeAndBurn(RentOrderId, T::AccountId, BalanceOf), - DLCRent(RentOrderId, T::AccountId, MachineId, u32, T::BlockNumber, BalanceOf), - RentFeeValue(u64), - } - - #[pallet::error] - pub enum Error { - MachineNotRentable, - Overflow, - GetMachinePriceFailed, - OnlyHalfHourAllowed, - GPUNotEnough, - MachineNotFound, - - DBCMachineRenterNotOwner, - MachineOwnerNotRentAllGPU, - DBCMachineNotRentedByOwner, - MachineNotDLCStaking, - MappingDlcRentId2ParentDbcRentIdFailed, - DLCRentIdNotFound, - DBCRentIdNotFound, - } - - use dbc_support::rental_type::{DlcBurnDetail, MachineRenterRentedOrderDetail}; -} - -impl Pallet { - fn rent_machine_by_block( - renter: T::AccountId, - machine_id: MachineId, - rent_gpu_num: u32, - duration: T::BlockNumber, - ) -> DispatchResultWithPostInfo { - let found = dlc_machine::Pallet::::dlc_machine_in_staking(machine_id.clone()); - ensure!(found, Error::::MachineNotDLCStaking); - - let now = >::block_number(); - let machine_info = >::machines_info(&machine_id) - .ok_or(Error::::MachineNotFound)?; - let machine_rented_gpu = Self::dlc_machine_rented_gpu(&machine_id); - let gpu_num = machine_info.gpu_num(); - - if gpu_num == 0 || duration == Zero::zero() { - return Ok(().into()) - } - - let dbc_machine_rent_order_info = - >::machine_rent_order(&machine_id); - ensure!( - dbc_machine_rent_order_info.rent_order.len() == 1, - Error::::DBCMachineNotRentedByOwner - ); - - let dbc_rent_order_id = dbc_machine_rent_order_info.rent_order[0]; - let dbc_machine_rent_info = >::rent_info(&dbc_rent_order_id) - .ok_or(Error::::DBCMachineNotRentedByOwner)?; - - ensure!( - dbc_machine_rent_info.renter == machine_info.controller, - Error::::DBCMachineRenterNotOwner - ); - ensure!( - dbc_machine_rent_info.gpu_num == machine_info.gpu_num(), - Error::::MachineOwnerNotRentAllGPU - ); - - // check free GPU number - ensure!(rent_gpu_num + machine_rented_gpu <= gpu_num, Error::::GPUNotEnough); - - // rent duration must be 30min * n - ensure!(duration % HALF_HOUR.into() == Zero::zero(), Error::::OnlyHalfHourAllowed); - - // 检查machine_id状态是否可以租用 - ensure!( - machine_info.machine_status == MachineStatus::Rented, - Error::::MachineNotRentable - ); - - let max_duration = Self::get_dbc_rent_machine_duration(&machine_id)?; - - // rent duration must be less than the rent duration of owner(dbc machine) - let duration = duration.min(max_duration); - - // get machine price - let machine_price = ::RTOps::get_machine_price( - machine_info.calc_point(), - rent_gpu_num, - gpu_num, - ) - .ok_or(Error::::GetMachinePriceFailed)?; - - // calculate rent_fee - let rent_fee_value = machine_price - .checked_mul(duration.saturated_into::()) - .ok_or(Error::::Overflow)? - .checked_div(ONE_DAY as u64) - .ok_or(Error::::Overflow)?; - - Self::deposit_event(Event::RentFeeValue(rent_fee_value.clone())); - - // let dbc_rent_fee = ::DbcPrice::get_dbc_amount_by_value(rent_fee_value) - // .ok_or(Error::::Overflow)?; - let dlc_price: u64 = 3000; - let one_dlc: u64 = 10_000_000; - let dbc_rent_fee: BalanceOf = rent_fee_value - .saturated_into::>() - .checked_mul(&one_dlc.saturated_into()) - .ok_or(Error::::Overflow)? - .checked_div(&dlc_price.saturated_into::>()) - .ok_or(Error::::Overflow)?; - - // dlc rent machine fee should be 125% of dbc rent fee - let rent_fee = Perbill::from_rational(25u32, 100u32) * dbc_rent_fee + dbc_rent_fee; - - // get rent end block number - let rent_end = duration.checked_add(&now).ok_or(Error::::Overflow)?; - - let rent_id = Self::get_new_rent_id(); - ensure!( - Self::mapping_dlc_rent_id_2_parent_dbc_rent_id(&rent_id, &machine_id) == Ok(()), - Error::::MappingDlcRentId2ParentDbcRentIdFailed - ); - - let mut machine_rent_order = Self::machine_rent_order(&machine_id); - let rentable_gpu_index = machine_rent_order.gen_rentable_gpu(rent_gpu_num, gpu_num); - ItemList::add_item(&mut machine_rent_order.rent_order, rent_id); - - let asset_id = Self::get_dlc_asset_id(); - as Inspect>::can_withdraw( - asset_id.clone(), - &renter, - rent_fee.clone(), - ) - .into_result(false)?; - - as Mutate>::burn_from( - asset_id, - &renter, - rent_fee.clone(), - Precision::Exact, - Fortitude::Polite, - )?; - - let now = >::block_number(); - - BurnDetails::::mutate(|details| { - details.push(DlcBurnDetail { - rent_id, - renter: renter.clone(), - burned_amount: rent_fee.clone(), - at: now, - }) - }); - - BurnTotalAmount::::mutate(|total_amount| { - *total_amount = total_amount.saturating_add(rent_fee.clone()) - }); - - let phase_all = vec![PhaseLevel::PhaseOne, PhaseLevel::PhaseTwo, PhaseLevel::PhaseThree]; - - phase_all.iter().for_each(|phase_level| { - if dlc_machine::Pallet::::get_machine_ids_in_dlc_nft_staking(phase_level.clone()) - .contains(&machine_id) - { - MachineId2BurnRecord::::mutate( - phase_level, - machine_id.clone(), - |burn_records| { - burn_records.push(DlcBurnDetail { - rent_id, - renter: renter.clone(), - burned_amount: rent_fee.clone(), - at: now, - }); - }, - ); - } - }); - - Self::deposit_event(Event::PayTxFeeAndBurn(rent_id, renter.clone(), rent_fee.clone())); - - DLCMachineRentedGPU::::mutate(&machine_id, |rented_gpu| { - *rented_gpu = rented_gpu.saturating_add(rent_gpu_num) - }); - - let mut rent_info = RentOrderDetail::new( - machine_id.clone(), - renter.clone(), - now, - rent_end, - rent_fee.clone(), - rent_gpu_num, - rentable_gpu_index, - ); - rent_info.rent_status = RentStatus::Renting; - rent_info.confirm_rent = rent_info.rent_start; - - RentInfo::::insert(&rent_id, rent_info); - - UserOrder::::mutate(&renter, |user_order| { - ItemList::add_item(user_order, rent_id); - }); - - RentEnding::::mutate(rent_end, |rent_ending| { - ItemList::add_item(rent_ending, rent_id); - }); - - MachineRentOrder::::insert(&machine_id, machine_rent_order); - - DlcMachineRentedOrders::::mutate(&machine_id, |dlc_machine_rented_orders| { - dlc_machine_rented_orders.push(MachineRenterRentedOrderDetail { - rent_start: now, - rent_end, - rent_id: rent_id.clone(), - }); - }); - - Self::deposit_event(Event::DLCRent( - rent_id, - renter, - machine_id, - rent_gpu_num, - duration.into(), - rent_fee, - )); - Ok(().into()) - } - - pub fn get_new_rent_id() -> RentOrderId { - let rent_id = Self::next_rent_id(); - - let new_rent_id = loop { - let new_rent_id = if rent_id == u64::MAX { 0 } else { rent_id + 1 }; - if !RentInfo::::contains_key(new_rent_id) { - break new_rent_id - } - }; - - NextRentId::::put(new_rent_id); - - rent_id - } - - // -Write: MachineRentOrder, RentEnding, RentOrder, - // UserOrder, ConfirmingOrder - fn clean_order(who: &T::AccountId, rent_order_id: RentOrderId) -> Result<(), ()> { - let mut user_order = Self::user_order(who); - ItemList::rm_item(&mut user_order, &rent_order_id); - - let rent_info = Self::rent_info(rent_order_id).ok_or(())?; - - let mut rent_ending = Self::rent_ending(rent_info.rent_end); - ItemList::rm_item(&mut rent_ending, &rent_order_id); - - let mut machine_rent_order = Self::machine_rent_order(&rent_info.machine_id); - machine_rent_order.clean_expired_order(rent_order_id, rent_info.gpu_index); - - DLCMachineRentedGPU::::mutate(&rent_info.machine_id, |rented_gpu| { - *rented_gpu = rented_gpu.saturating_sub(rent_info.gpu_num) - }); - - MachineRentOrder::::insert(&rent_info.machine_id, machine_rent_order); - if rent_ending.is_empty() { - RentEnding::::remove(rent_info.rent_end); - } else { - RentEnding::::insert(rent_info.rent_end, rent_ending); - } - RentInfo::::remove(rent_order_id); - if user_order.is_empty() { - UserOrder::::remove(who); - } else { - UserOrder::::insert(who, user_order); - } - Ok(()) - } - - // 这里修rentMachine模块通知onlineProfile机器已经租用完成, - // onlineProfile判断机器是否需要变成online状态,或者记录下之前是租用状态, - // 以便机器再次上线时进行正确的惩罚 - fn check_if_rent_finished() -> Result<(), ()> { - let now = >::block_number(); - if !>::contains_key(now) { - return Ok(()) - } - let pending_ending = Self::rent_ending(now); - - for rent_id in pending_ending { - let rent_info = Self::rent_info(&rent_id).ok_or(())?; - - let _ = Self::clean_order(&rent_info.renter, rent_id); - } - Ok(()) - } - - pub fn get_dlc_asset_id_parameter() -> ::AssetIdParameter { - let asset_id: ::AssetId = ::DLCAssetId::get().into(); - asset_id.into().into() - } - - pub fn get_dlc_asset_id() -> as Inspect>::AssetId { - let asset_id: ::AssetId = ::DLCAssetId::get().into(); - asset_id.into() - } - - pub fn get_renters(machine_id: &MachineId) -> Vec { - let rent_order_info = Self::machine_rent_order(machine_id); - let mut renters: Vec = Vec::new(); - for rent_order_id in rent_order_info.rent_order { - if let Some(rent_info) = Self::rent_info(rent_order_id) { - renters.push(rent_info.renter); - } - } - renters - } - - fn mapping_dlc_rent_id_2_parent_dbc_rent_id( - rent_id: &RentOrderId, - machine_id: &MachineId, - ) -> Result<(), ()> { - if let Some(parent_dbc_rent_id) = - rent_machine::Pallet::::get_rent_id_of_renting_dbc_machine_by_owner(machine_id) - { - DlcRentId2ParentDbcRentId::::insert(rent_id, parent_dbc_rent_id); - return Ok(()) - } - Err(()) - } - - fn get_dbc_rent_machine_duration( - machine_id: &MachineId, - ) -> Result { - let rent_id = - rent_machine::Pallet::::get_rent_id_of_renting_dbc_machine_by_owner(machine_id) - .ok_or(Error::::DBCRentIdNotFound)?; - - let dbc_rent_info = - rent_machine::Pallet::::rent_info(rent_id).ok_or(Error::::DBCRentIdNotFound)?; - - let now = >::block_number(); - Ok(dbc_rent_info.rent_end.saturating_sub(now)) - } - - pub fn get_parent_dbc_rent_order_id( - rent_id: RentOrderId, - ) -> Result { - let _ = Self::rent_info(rent_id).ok_or(Error::::DLCRentIdNotFound)?; - let dbc_rent_id = - Self::dlc_rent_id_2_parent_dbc_rent_id(rent_id).ok_or(Error::::DLCRentIdNotFound)?; - - Ok(dbc_rent_id) - } -} - -impl DLCMachineInfoTrait for Pallet { - type BlockNumber = T::BlockNumber; - fn get_dlc_machine_rent_duration( - last_claim_at: T::BlockNumber, - slash_at: T::BlockNumber, - machine_id: MachineId, - ) -> Result { - let now = >::block_number(); - let mut rent_duration: T::BlockNumber = T::BlockNumber::default(); - let rented_orders = Self::dlc_machine_rented_orders(machine_id); - - rented_orders.iter().for_each(|rented_order| { - if rented_order.rent_end >= last_claim_at { - if slash_at == T::BlockNumber::default() { - rent_duration += - now.min(rented_order.rent_end) - last_claim_at.max(rented_order.rent_start) - } else { - rent_duration += now.min(rented_order.rent_end).min(slash_at) - - last_claim_at.max(rented_order.rent_start) - } - } - }); - - Ok(rent_duration) - } - - fn get_rented_gpu_count_in_dlc_nft_staking(phase_level: PhaseLevel) -> u64 { - let machine_ids_dlc_nft_staking = - dlc_machine::Pallet::::get_machine_ids_in_dlc_nft_staking(phase_level); - let mut count = 0u64; - machine_ids_dlc_nft_staking.iter().for_each(|machine_id| { - let result = Self::machine_rent_order(machine_id); - count = count.saturating_add(result.used_gpu.len() as u64); - }); - - count - } - - fn get_rented_gpu_count_of_machine_in_dlc_nft_staking(machine_id: MachineId) -> u64 { - let mut count = 0u64; - let result = Self::machine_rent_order(machine_id); - count = count.saturating_add(result.used_gpu.len() as u64); - - count - } - - fn get_total_dlc_nft_staking_burned_rent_fee(phase_level: PhaseLevel) -> u64 { - MachineId2BurnRecord::::iter_prefix(phase_level) - .map(|(_, burn_records)| { - let mut total_burned_amount = 0u64; - burn_records.iter().for_each(|burn_record| { - total_burned_amount = total_burned_amount - .saturating_add(burn_record.burned_amount.saturated_into()); - }); - total_burned_amount - }) - .sum() - } - - fn get_dlc_nft_staking_burned_rent_fee_by_machine_id( - phase_level: PhaseLevel, - machine_id: MachineId, - ) -> u64 { - Self::machine_id_2_burn_record(phase_level, machine_id) - .iter() - .map(|burn_record| burn_record.burned_amount.saturated_into::()) - .sum() - } -} diff --git a/pallets/rent-dlc-machine/src/mock.rs b/pallets/rent-dlc-machine/src/mock.rs deleted file mode 100644 index 53054602..00000000 --- a/pallets/rent-dlc-machine/src/mock.rs +++ /dev/null @@ -1,577 +0,0 @@ -use crate as rent_dlc_machine; -use dbc_price_ocw::MAX_LEN; -use dbc_support::machine_type::{ - CommitteeUploadInfo, Latitude, Longitude, StakerCustomizeInfo, StandardGpuPointPrice, -}; - -use frame_support::{ - assert_ok, parameter_types, - traits::{AsEnsureOriginWithArg, ConstU128, ConstU32, OnFinalize, OnInitialize}, - weights::Weight, - PalletId, -}; -use frame_system::{EnsureRoot, EnsureSigned, EnsureWithSuccess, RawOrigin}; -use parity_scale_codec::Compact; -pub use sp_core::{ - sr25519::{self, Signature}, - H256, -}; -pub use sp_keyring::sr25519::Keyring as Sr25519Keyring; -use sp_runtime::{ - testing::{Header, TestXt}, - traits::{BlakeTwo256, IdentityLookup, Verify}, - Perbill, Permill, -}; -use std::convert::TryInto; - -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; -type Block = frame_system::mocking::MockBlock; -type Balance = u128; - -// 1 DBC = 1 * 10^15 -pub const ONE_DBC: u128 = 1_000_000_000_000_000; -pub const ONE_DLC: u128 = 1_000_000_000_000_000; - -// 初始1000WDBC -pub const INIT_BALANCE: u128 = 10_000_000 * ONE_DBC; -pub type BlockNumber = u64; -pub const INIT_TIMESTAMP: u64 = 90_000; -pub const BLOCK_TIME: u64 = 30_000; - -parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const SS58Prefix: u8 = 42; -} - -impl frame_system::Config for TestRuntime { - type BaseCallFilter = (); - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = sr25519::Public; - type Lookup = IdentityLookup; - type Header = Header; - type RuntimeEvent = RuntimeEvent; - type BlockHashCount = BlockHashCount; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = SS58Prefix; - type OnSetCode = (); - type MaxConsumers = ConstU32<16>; -} - -parameter_types! { - pub const ExistentialDeposit: u64 = 1; - pub const MaxReservers: u32 = 50; -} - -impl pallet_balances::Config for TestRuntime { - type MaxLocks = (); - type MaxReserves = MaxReservers; - type ReserveIdentifier = [u8; 8]; - type Balance = u128; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type WeightInfo = (); - - type FreezeIdentifier = (); - type MaxFreezes = (); - type HoldIdentifier = (); - type MaxHolds = ConstU32<2>; -} - -impl pallet_insecure_randomness_collective_flip::Config for TestRuntime {} - -parameter_types! { - pub const BlockPerEra: u32 = 3600 * 24 / 30; -} - -parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); - pub const ProposalBondMinimum: u64 = 1; - pub const SpendPeriod: u64 = 2; - pub const Burn: Permill = Permill::from_percent(50); - pub const DataDepositPerByte: u64 = 1; - pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry"); - pub const MaxApprovals: u32 = 100; - - pub const MaxBalance: Balance = Balance::max_value(); -} - -impl pallet_treasury::Config for TestRuntime { - type PalletId = TreasuryModuleId; - type Currency = Balances; - type ApproveOrigin = EnsureRoot; - type RejectOrigin = EnsureRoot; - type RuntimeEvent = RuntimeEvent; - type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ProposalBondMinimum; - type SpendPeriod = SpendPeriod; - type Burn = Burn; - type BurnDestination = (); // Just gets burned. - type WeightInfo = (); - type SpendFunds = (); - - type ProposalBondMaximum = (); - type MaxApprovals = MaxApprovals; - type SpendOrigin = EnsureWithSuccess, Self::AccountId, MaxBalance>; -} - -parameter_types! { - pub const CouncilMotionDuration: u32 = 5 * 2880; - pub const CouncilMaxProposals: u32 = 100; - pub const CouncilMaxMembers: u32 = 100; - pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights::simple_max(Weight::MAX); - pub MaxProposalWeight: Weight = sp_runtime::Perbill::from_percent(50) * BlockWeights::get().max_block; -} - -type TechnicalCollective = pallet_collective::Instance2; -impl pallet_collective::Config for TestRuntime { - type RuntimeOrigin = RuntimeOrigin; - type Proposal = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type MotionDuration = CouncilMotionDuration; - type MaxProposals = CouncilMaxProposals; - type MaxMembers = CouncilMaxMembers; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type WeightInfo = pallet_collective::weights::SubstrateWeight; - type SetMembersOrigin = EnsureRoot; - - type MaxProposalWeight = MaxProposalWeight; -} - -parameter_types! { - pub const MinimumPeriod: u64 = 5; -} -impl pallet_timestamp::Config for TestRuntime { - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); -} - -parameter_types! { - pub const BondingDuration: u32 = 7; - pub const ProfitReleaseDuration: u64 = 150; -} - -impl committee::Config for TestRuntime { - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - // type WeightInfo = (); -} - -impl online_profile::Config for TestRuntime { - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - type BondingDuration = BondingDuration; - // type ProfitReleaseDuration = ProfitReleaseDuration; - type DbcPrice = DBCPriceOCW; - type ManageCommittee = Committee; - type Slash = Treasury; - type CancelSlashOrigin = - pallet_collective::EnsureProportionAtLeast; - type SlashAndReward = GenericFunc; -} - -impl dbc_price_ocw::Config for TestRuntime { - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - type RandomnessSource = RandomnessCollectiveFlip; -} - -impl online_committee::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; - type Currency = Balances; - type OCOps = OnlineProfile; - type ManageCommittee = Committee; - type CancelSlashOrigin = - pallet_collective::EnsureProportionAtLeast; - type SlashAndReward = GenericFunc; -} - -impl rent_machine::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; - type Currency = Balances; - type RTOps = OnlineProfile; - type DbcPrice = DBCPriceOCW; -} - -type TestExtrinsic = TestXt; -impl frame_system::offchain::CreateSignedTransaction for TestRuntime -where - RuntimeCall: From, -{ - fn create_transaction>( - call: RuntimeCall, - _public: ::Signer, - _account: ::AccountId, - index: ::Index, - ) -> Option<(RuntimeCall, ::SignaturePayload)> - { - Some((call, (index, ()))) - } -} - -impl frame_system::offchain::SigningTypes for TestRuntime { - type Public = ::Signer; - type Signature = Signature; -} - -impl frame_system::offchain::SendTransactionTypes for TestRuntime -where - RuntimeCall: From, -{ - type OverarchingCall = RuntimeCall; - type Extrinsic = TestExtrinsic; -} - -impl generic_func::Config for TestRuntime { - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - type RandomnessSource = RandomnessCollectiveFlip; - type FixedTxFee = Treasury; - type Slash = Treasury; -} - -impl rent_dlc_machine::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; - type RTOps = OnlineProfile; - type DbcPrice = DBCPriceOCW; - type AssetId = u32; - type DLCAssetId = ConstU32<88>; -} - -impl dlc_machine::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; -} -pub const DBCS: Balance = 1_000_000_000_000_000; -pub const DOLLARS: Balance = DBCS / 100; - -pub const ONE_DAY: BlockNumber = 10 * 60 * 24; -parameter_types! { - pub const AssetDeposit: Balance = 100 * DOLLARS; - pub const ApprovalDeposit: Balance = 1 * DOLLARS; - pub const StringLimit: u32 = 50; - pub const MetadataDepositBase: Balance = 10 * DOLLARS; - pub const MetadataDepositPerByte: Balance = 1 * DOLLARS; - - pub const AssetLockLimit: u32 = 1000; - pub const MinLockAmount: Balance = 1 * ONE_DLC; - pub const MaxLockDuration: BlockNumber = 1800 * ONE_DAY; -} -impl pallet_assets::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; - type Balance = u128; - type AssetId = u32; - type AssetIdParameter = Compact; - type Currency = Balances; - type CreateOrigin = - AsEnsureOriginWithArg::AccountId>>; - type ForceOrigin = EnsureRoot<::AccountId>; - type AssetDeposit = AssetDeposit; - type AssetAccountDeposit = ConstU128; - type MetadataDepositBase = MetadataDepositBase; - type MetadataDepositPerByte = MetadataDepositPerByte; - type ApprovalDeposit = ApprovalDeposit; - type StringLimit = StringLimit; - type Freezer = (); - type Extra = (); - type CallbackHandle = (); - type WeightInfo = pallet_assets::weights::SubstrateWeight; - type RemoveItemsLimit = ConstU32<1000>; - - type MinLockAmount = MinLockAmount; - - type MaxLockDuration = MaxLockDuration; - // #[cfg(feature = "runtime-benchmarks")] - // type BenchmarkHelper = (); -} - -// Configure a mock runtime to test the pallet. -frame_support::construct_runtime!( - pub enum TestRuntime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system, - Timestamp: pallet_timestamp, - OnlineCommittee: online_committee, - OnlineProfile: online_profile, - RandomnessCollectiveFlip: pallet_insecure_randomness_collective_flip, - Balances: pallet_balances, - Committee: committee, - DBCPriceOCW: dbc_price_ocw, - Treasury: pallet_treasury, - GenericFunc: generic_func, - Assets: pallet_assets, - RentMachine: rent_machine, - TechnicalCommittee: pallet_collective::, - RentDlcMachine: rent_dlc_machine, - DLCMachine: dlc_machine, - } -); - -pub fn new_test_ext_after_machine_online() -> sp_io::TestExternalities { - let mut storage = - frame_system::GenesisConfig::default().build_storage::().unwrap(); - - #[rustfmt::skip] - pallet_balances::GenesisConfig:: { - balances: vec![ - (sr25519::Public::from(Sr25519Keyring::Alice).into(), INIT_BALANCE), - (sr25519::Public::from(Sr25519Keyring::Bob).into(), INIT_BALANCE), - (sr25519::Public::from(Sr25519Keyring::Charlie).into(), INIT_BALANCE), - (sr25519::Public::from(Sr25519Keyring::Dave).into(), 2 * INIT_BALANCE), - (sr25519::Public::from(Sr25519Keyring::Eve).into(), INIT_BALANCE), - (sr25519::Public::from(Sr25519Keyring::Ferdie).into(), INIT_BALANCE), - (sr25519::Public::from(Sr25519Keyring::One).into(), INIT_BALANCE), - (sr25519::Public::from(Sr25519Keyring::Two).into(), INIT_BALANCE), - ], - } - .assimilate_storage(&mut storage) - .unwrap(); - - let mut ext = sp_io::TestExternalities::from(storage); - - let controller = sr25519::Public::from(Sr25519Keyring::Eve); - let stash = sr25519::Public::from(Sr25519Keyring::Ferdie); - let pot_two = sr25519::Public::from(Sr25519Keyring::Two); - let committee1 = sr25519::Public::from(Sr25519Keyring::One); - let committee2 = sr25519::Public::from(Sr25519Keyring::Two); - let committee3 = sr25519::Public::from(Sr25519Keyring::Dave); - - // Bob pubkey - let machine_id = "8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48" - .as_bytes() - .to_vec(); - let msg = "8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48\ - 5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL"; - let sig = "b4084f70730b183127e9db78c6d8dcf79039f23466cd1ee8b536c40c3027a83d\ - ab040be4ed2db57b67eaac406817a69ce72a13f8ac11ba460e15d318b1504481"; - - ext.execute_with(|| { - run_to_block(1); - // 初始化price_ocw (0.012$) - assert_eq!(DBCPriceOCW::avg_price(), None); - for _ in 0..MAX_LEN { - DBCPriceOCW::add_price(12_000u64); - } - DBCPriceOCW::add_avg_price(); - assert_eq!(DBCPriceOCW::avg_price(), Some(12_000u64)); - - // 初始化设置参数 - // 委员会每次抢单质押数量 (15$) - // 委员会每次抢单质押数量 (15$) - let _ = Committee::set_committee_stake_params( - RawOrigin::Root.into(), - committee::CommitteeStakeParamsInfo { - stake_baseline: 20000 * ONE_DBC, - stake_per_order: 1000 * ONE_DBC, - min_free_stake_percent: Perbill::from_rational(40u32, 100u32), - }, - ); - // assert_ok!(Committee::set_staked_usd_per_order(RawOrigin::Root.into(), 15_000_000)); - // 操作时的固定费率: 10 DBC - assert_ok!(GenericFunc::set_fixed_tx_fee(RawOrigin::Root.into(), 10 * ONE_DBC)); - // 每张GPU质押数量: 100,000 DBC - // 设置单卡质押上限: 7700_000_000, 每张GPU质押数量: 100,000 DBC - let _ = OnlineProfile::set_online_stake_params( - RawOrigin::Root.into(), - online_profile::OnlineStakeParamsInfo { - online_stake_per_gpu: 100000 * ONE_DBC, - online_stake_usd_limit: 7700_000_000, - reonline_stake: 46_000_000, - slash_review_stake: 1000 * ONE_DBC, - }, - ); - // 设置奖励发放开始时间 - // 设置每个Era奖励数量: 1,100,000 - let _ = OnlineProfile::set_reward_info( - RawOrigin::Root.into(), - online_profile::PhaseRewardInfoDetail { - online_reward_start_era: 0, - first_phase_duration: 1095, - galaxy_on_era: 0, - phase_0_reward_per_era: 1_100_000 * ONE_DBC, - phase_1_reward_per_era: 550_000 * ONE_DBC, - phase_2_reward_per_era: 275_000 * ONE_DBC, - }, - ); - - // 设置标准GPU租金价格: (3080得分1000;租金每月1000RMB) {1000; 150_000_000}; - assert_ok!(OnlineProfile::set_standard_gpu_point_price( - RawOrigin::Root.into(), - StandardGpuPointPrice { gpu_point: 1000, gpu_price: 5_000_000 } - )); - // 设置机器租金支付地址 - assert_ok!(RentMachine::set_rent_fee_pot(RawOrigin::Root.into(), pot_two)); - - run_to_block(2); - - // stash 账户设置控制账户 - assert_ok!(OnlineProfile::set_controller(RuntimeOrigin::signed(stash), controller)); - - // controller 生成server_name - assert_ok!(OnlineProfile::gen_server_room(RuntimeOrigin::signed(controller))); - assert_ok!(OnlineProfile::gen_server_room(RuntimeOrigin::signed(controller))); - - let server_room = OnlineProfile::stash_server_rooms(&stash); - - // controller bond_machine - assert_ok!(OnlineProfile::bond_machine( - RuntimeOrigin::signed(controller), - machine_id.clone(), - msg.as_bytes().to_vec(), - hex::decode(sig).unwrap() - )); - - // 控制账户添加机器信息 - assert_ok!(OnlineProfile::add_machine_info( - RuntimeOrigin::signed(controller), - machine_id.clone(), - StakerCustomizeInfo { - // server_room: H256::from_low_u64_be(1), - server_room: server_room[0], - upload_net: 10000, - download_net: 10000, - longitude: Longitude::East(1157894), - latitude: Latitude::North(235678), - telecom_operators: vec!["China Unicom".into()], - is_bare_machine: false - } - )); - - run_to_block(3); - - // 增加一个委员会 - assert_ok!(Committee::add_committee(RawOrigin::Root.into(), committee1)); - assert_ok!(Committee::add_committee(RawOrigin::Root.into(), committee2)); - assert_ok!(Committee::add_committee(RawOrigin::Root.into(), committee3)); - - let one_box_pubkey: [u8; 32] = - hex::decode("9dccbab2d61405084eac440f877a6479bc827373b2e414e81a6170ebe5aadd12") - .unwrap() - .try_into() - .unwrap(); - assert_ok!(Committee::committee_set_box_pubkey( - RuntimeOrigin::signed(committee1), - one_box_pubkey.clone() - )); - assert_ok!(Committee::committee_set_box_pubkey( - RuntimeOrigin::signed(committee2), - one_box_pubkey.clone() - )); - assert_ok!(Committee::committee_set_box_pubkey( - RuntimeOrigin::signed(committee3), - one_box_pubkey.clone() - )); - - run_to_block(5); - - // 委员会提交机器Hash - let machine_info_hash1: [u8; 16] = - hex::decode("fd8885a22a9d9784adaa36effcd77522").unwrap().try_into().unwrap(); - assert_ok!(OnlineCommittee::submit_confirm_hash( - RuntimeOrigin::signed(committee1), - machine_id.clone(), - machine_info_hash1 - )); - let machine_info_hash2: [u8; 16] = - hex::decode("c016090e0943c17f5d4999dc6eb52683").unwrap().try_into().unwrap(); - assert_ok!(OnlineCommittee::submit_confirm_hash( - RuntimeOrigin::signed(committee2), - machine_id.clone(), - machine_info_hash2 - )); - let machine_info_hash3: [u8; 16] = - hex::decode("4a6b2df1e1a77b9bcdab5e31dc7950d2").unwrap().try_into().unwrap(); - assert_ok!(OnlineCommittee::submit_confirm_hash( - RuntimeOrigin::signed(committee3), - machine_id.clone(), - machine_info_hash3 - )); - - let mut committee_upload_info = CommitteeUploadInfo { - machine_id: machine_id.clone(), - gpu_type: "GeForceRTX3080".as_bytes().to_vec(), - gpu_num: 4, - cuda_core: 8704, - gpu_mem: 10, - calc_point: 59890, - sys_disk: 500, - data_disk: 3905, - cpu_type: "Intel(R) Xeon(R) Silver 4214R".as_bytes().to_vec(), - cpu_core_num: 46, - cpu_rate: 2400, - mem_num: 440, - - rand_str: "abcdefg1".as_bytes().to_vec(), - is_support: true, - }; - - // 委员会提交原始信息 - assert_ok!(OnlineCommittee::submit_confirm_raw( - RuntimeOrigin::signed(committee1), - committee_upload_info.clone() - )); - committee_upload_info.rand_str = "abcdefg2".as_bytes().to_vec(); - assert_ok!(OnlineCommittee::submit_confirm_raw( - RuntimeOrigin::signed(committee2), - committee_upload_info.clone() - )); - committee_upload_info.rand_str = "abcdefg3".as_bytes().to_vec(); - assert_ok!(OnlineCommittee::submit_confirm_raw( - RuntimeOrigin::signed(committee3), - committee_upload_info.clone() - )); - - run_to_block(10); - - let asset_id = RentDlcMachine::get_dlc_asset_id_parameter(); - assert_ok!(Assets::create(RuntimeOrigin::signed(committee3), asset_id, committee3, 1)); - assert_ok!(Assets::mint( - RuntimeOrigin::signed(committee3), - asset_id, - committee3, - 10_000_000 * ONE_DLC - )); - }); - - ext -} - -pub fn run_to_block(n: BlockNumber) { - for b in System::block_number()..=n { - OnlineProfile::on_finalize(b); - OnlineCommittee::on_finalize(b); - Committee::on_finalize(b); - RentMachine::on_finalize(b); - System::on_finalize(b); - RandomnessCollectiveFlip::on_finalize(b); - Timestamp::set_timestamp(System::block_number() * BLOCK_TIME + INIT_TIMESTAMP); - RentDlcMachine::on_finalize(b); - - System::set_block_number(b + 1); - - System::on_initialize(b + 1); - OnlineCommittee::on_initialize(b + 1); - Committee::on_initialize(b + 1); - OnlineProfile::on_initialize(b + 1); - RandomnessCollectiveFlip::on_initialize(b + 1); - } -} diff --git a/pallets/rent-dlc-machine/src/rpc.rs b/pallets/rent-dlc-machine/src/rpc.rs deleted file mode 100644 index ffbc00c9..00000000 --- a/pallets/rent-dlc-machine/src/rpc.rs +++ /dev/null @@ -1,35 +0,0 @@ -use sp_std::vec::Vec; - -use crate::{BalanceOf, Config, MachineGPUOrder, Pallet, RentOrderId}; -use dbc_support::{rental_type::RentOrderDetail, MachineId}; - -// RPC -impl Pallet { - pub fn get_dlc_rent_order( - rent_id: RentOrderId, - ) -> Option>> { - Self::rent_info(&rent_id) - } - - pub fn get_dlc_rent_list(renter: T::AccountId) -> Vec { - Self::user_order(&renter) - } - - pub fn is_dlc_machine_renter(machine_id: MachineId, renter: T::AccountId) -> bool { - let machine_order = Self::machine_rent_order(machine_id); - - for order_id in machine_order.rent_order { - if let Some(rent_info) = Self::rent_info(order_id) { - if rent_info.renter == renter { - return true - } - } - } - - false - } - - pub fn get_dlc_machine_rent_id(machine_id: MachineId) -> MachineGPUOrder { - Self::machine_rent_order(machine_id) - } -} diff --git a/pallets/rent-dlc-machine/src/tests/mod.rs b/pallets/rent-dlc-machine/src/tests/mod.rs deleted file mode 100644 index 15ab5605..00000000 --- a/pallets/rent-dlc-machine/src/tests/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod tests; diff --git a/pallets/rent-dlc-machine/src/tests/tests.rs b/pallets/rent-dlc-machine/src/tests/tests.rs deleted file mode 100644 index f3d8110d..00000000 --- a/pallets/rent-dlc-machine/src/tests/tests.rs +++ /dev/null @@ -1,195 +0,0 @@ -use crate::{mock::*, Error}; - -use dbc_support::{rental_type::RentStatus, traits::DLCMachineReportStakingTrait, ONE_DAY}; -use frame_support::{assert_err, assert_ok}; -use once_cell::sync::Lazy; - -use rent_machine::Error as RentMachineError; -use sp_core::Pair; -use sp_keyring::AccountKeyring::{Dave, Eve}; -const renter_dave: Lazy = Lazy::new(|| sr25519::Public::from(Dave)); - -const renter_owner: Lazy = Lazy::new(|| sr25519::Public::from(Eve)); -const machine_id: Lazy> = Lazy::new(|| { - "8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48" - .as_bytes() - .to_vec() -}); - -#[test] -fn report_dlc_staking_should_works() { - new_test_ext_after_machine_online().execute_with(|| { - let msg: Vec = b"abc".to_vec(); - let eve_sig = Eve.sign(&msg[..]); - assert_eq!(Eve.public(), sr25519::Public::from(Sr25519Keyring::Eve)); - - // 过10个块之后执行租用成功 - run_to_block(10 + 20); - - assert_err!( - as DLCMachineReportStakingTrait>::report_dlc_staking( - msg.clone(), - eve_sig.clone(), - Eve.public(), - machine_id.clone() - ), - RentMachineError::::MachineNotRented - ); - - assert_ok!(RentMachine::rent_machine( - RuntimeOrigin::signed(*renter_owner), - machine_id.clone(), - 4, - (10 * ONE_DAY) as u64 - )); - - assert_ok!(RentMachine::confirm_rent(RuntimeOrigin::signed(*renter_owner), 0)); - - assert_eq!( - dlc_machine::DLCMachinesInStaking::::contains_key(machine_id.clone()), - false - ); - - assert_ok!( - as DLCMachineReportStakingTrait>::report_dlc_staking( - msg, - eve_sig, - Eve.public(), - machine_id.clone() - ) - ); - assert_eq!( - dlc_machine::DLCMachinesInStaking::::contains_key(machine_id.clone()), - true - ) - }) -} - -#[test] -fn rent_dlc_machine_should_works() { - new_test_ext_after_machine_online().execute_with(|| { - let eve = sp_core::sr25519::Pair::from(Eve); - let msg: Vec = b"abc".to_vec(); - let eve_sig = eve.sign(&msg[..]); - assert_eq!(eve.public(), sr25519::Public::from(Eve)); - - // 过10个块之后执行租用成功 - run_to_block(10 + 20); - - assert_err!( - as DLCMachineReportStakingTrait>::report_dlc_staking( - msg.clone(), - eve_sig.clone(), - eve.public(), - machine_id.clone() - ), - RentMachineError::::MachineNotRented - ); - - assert_ok!(RentMachine::rent_machine( - RuntimeOrigin::signed(*renter_owner), - machine_id.clone(), - 4, - (10 * ONE_DAY) as u64 - )); - - assert_ok!(RentMachine::confirm_rent(RuntimeOrigin::signed(*renter_owner), 0)); - assert_eq!( - dlc_machine::DLCMachinesInStaking::::contains_key(machine_id.clone()), - false - ); - assert_err!( - RentDlcMachine::rent_dlc_machine( - RuntimeOrigin::signed(*renter_dave), - machine_id.clone(), - 4, - (10 * ONE_DAY * 2) as u64 - ), - Error::::MachineNotDLCStaking - ); - - assert_ok!( - as DLCMachineReportStakingTrait>::report_dlc_staking( - msg, - eve_sig, - eve.public(), - machine_id.clone() - ) - ); - assert_eq!( - dlc_machine::DLCMachinesInStaking::::contains_key(machine_id.clone()), - true - ); - - // renter's dlc balance should be 10000000*ONE_DLC before rent dlc machine - let asset_id = RentDlcMachine::get_dlc_asset_id_parameter(); - assert_eq!(Assets::balance(asset_id.into(), *renter_dave), 10000000 * ONE_DLC); - - // dlc total_supply should be 10000000*ONE_DLC before rent dlc machine - assert_eq!(Assets::total_supply(asset_id.into()), 10000000 * ONE_DLC); - - assert_ok!(RentDlcMachine::rent_dlc_machine( - RuntimeOrigin::signed(*renter_dave), - machine_id.clone(), - 4, - (10 * ONE_DAY * 2) as u64 - )); - - let burn_total = RentDlcMachine::burn_total_amount(); - assert_ne!(burn_total, 0); - // renter's dlc balance should less than 10000000*ONE_DLC after rent dlc machine - assert_eq!(Assets::balance(asset_id.into(), *renter_dave), 10000000 * ONE_DLC - burn_total); - - // dlc total_supply should less than 10000000*ONE_DLC after rent dlc machine - assert_eq!(Assets::total_supply(asset_id.into()), 10000000 * ONE_DLC - burn_total); - - let rent_order_infos = RentDlcMachine::machine_rent_order(machine_id.clone()); - assert_eq!(rent_order_infos.used_gpu.len(), 4); - assert_eq!(rent_order_infos.rent_order.len(), 1); - let rent_dlc_machine_id = rent_order_infos.rent_order[0]; - let rent_info = RentDlcMachine::rent_info(rent_dlc_machine_id.clone()).unwrap(); - assert_eq!(rent_info.rent_status, RentStatus::Renting); - let rent_duration = rent_info.rent_end.saturating_sub(rent_info.rent_start); - assert_eq!(rent_duration, 10 * ONE_DAY as u64); - - let records = RentDlcMachine::burn_details(); - assert_eq!(records.len(), 1); - let detail = records.first().unwrap(); - assert_eq!(detail.burned_amount, burn_total); - assert_ne!(detail.at, 0); - assert_eq!(detail.rent_id, rent_dlc_machine_id); - assert_eq!(detail.renter, Dave.public()); - - let dbc_rent_order_infos = RentMachine::machine_rent_order(machine_id.clone()); - let rent_dbc_machine_id = dbc_rent_order_infos.rent_order[0]; - assert_eq!( - RentDlcMachine::dlc_rent_id_2_parent_dbc_rent_id(rent_dlc_machine_id.clone()).unwrap(), - rent_dbc_machine_id - ); - - let rent_ids = RentDlcMachine::user_order(Dave.public()); - assert_eq!(rent_ids.len(), 1); - - let rented_gpu_num = RentDlcMachine::dlc_machine_rented_gpu(machine_id.clone()); - assert_eq!(rented_gpu_num, 4); - - run_to_block((30 + ONE_DAY * 10 + 1) as BlockNumber); - - let rent_ids = RentDlcMachine::user_order(Dave.public()); - assert_eq!(rent_ids.len(), 0); - - assert_eq!(RentDlcMachine::rent_info(rent_dlc_machine_id.clone()).is_none(), true); - - let dlc_rent_order_infos = RentDlcMachine::machine_rent_order(machine_id.clone()); - assert_eq!(dlc_rent_order_infos.rent_order.len(), 0); - assert_eq!(dlc_rent_order_infos.used_gpu.len(), 0); - - assert_eq!( - RentDlcMachine::dlc_rent_id_2_parent_dbc_rent_id(rent_dlc_machine_id.clone()).unwrap(), - rent_dbc_machine_id - ); - - let rented_gpu_num = RentDlcMachine::dlc_machine_rented_gpu(machine_id.clone()); - assert_eq!(rented_gpu_num, 0); - }) -} diff --git a/pallets/rent-machine/src/lib.rs b/pallets/rent-machine/src/lib.rs index 86821ca6..e5d9884d 100644 --- a/pallets/rent-machine/src/lib.rs +++ b/pallets/rent-machine/src/lib.rs @@ -15,7 +15,6 @@ pub use dbc_support::machine_type::MachineStatus; use dbc_support::{ rental_type::{MachineGPUOrder, MachineRenterRentedOrderDetail, RentOrderDetail, RentStatus}, traits::{DbcPrice, MachineInfoTrait, RTOps}, - utils::{account_id, verify_signature}, EraIndex, ItemList, MachineId, RentOrderId, HALF_HOUR, ONE_DAY, ONE_MINUTE, }; use frame_support::{ @@ -25,7 +24,11 @@ use frame_support::{ traits::{Currency, ExistenceRequirement::KeepAlive, ReservableCurrency}, }; use frame_system::{ensure_root, ensure_signed, pallet_prelude::*}; -use sp_runtime::traits::{CheckedAdd, CheckedSub, SaturatedConversion, Saturating, Zero}; +use sp_core::H160; +use sp_runtime::{ + traits::{CheckedAdd, CheckedSub, SaturatedConversion, Saturating, Zero}, + Perbill, +}; use sp_std::{prelude::*, str, vec::Vec}; type BalanceOf = @@ -151,6 +154,11 @@ pub mod pallet { pub(super) type MaximumRentalDuration = StorageValue<_, EraIndex, ValueQuery, MaximumRentalDurationDefault>; + #[pallet::storage] + #[pallet::getter(fn evm_address_to_account)] + pub(super) type EvmAddress2Account = + StorageMap<_, Blake2_128Concat, H160, T::AccountId>; + // The current storage version. #[pallet::storage] #[pallet::getter(fn storage_version)] @@ -277,6 +285,26 @@ pub mod pallet { let renter = ensure_signed(origin)?; Self::relet_machine_by_block(renter, rent_id, relet_duration) } + + #[pallet::call_index(4)] + #[pallet::weight(Weight::from_parts(10000, 0))] + pub fn bond_evm_address( + origin: OriginFor, + machine_id: MachineId, + evm_address: H160, + ) -> DispatchResultWithPostInfo { + let who = ensure_signed(origin)?; + + let machine_info = online_profile::Pallet::::machines_info(machine_id) + .ok_or(Error::::MachineNotFound.as_str())?; + ensure!( + machine_info.controller == who || machine_info.machine_stash == who, + Error::::NotMachineOwner + ); + EvmAddress2Account::::insert(evm_address, who.clone()); + Self::deposit_event(Event::SetEvmAddress(evm_address, who)); + Ok(().into()) + } } #[pallet::event] @@ -290,6 +318,8 @@ pub mod pallet { Rent(RentOrderId, T::AccountId, MachineId, u32, T::BlockNumber, BalanceOf), // rent_id, renter, MachineId, gpu_num, duration, balance Relet(RentOrderId, T::AccountId, MachineId, u32, T::BlockNumber, BalanceOf), + + SetEvmAddress(H160, T::AccountId), } #[pallet::error] @@ -311,6 +341,7 @@ pub mod pallet { Unknown, ReletTooShort, + NotMachineOwner, SignVerifiedFailed, MachineNotRented, MachineNotFound, @@ -741,6 +772,14 @@ impl MachineInfoTrait for Pallet { 0 } + fn get_machine_cpu_rate(machine_id: MachineId) -> u64 { + let machine_info_result = online_profile::Pallet::::machines_info(machine_id); + if let Some(machine_info) = machine_info_result { + return machine_info.cpu_rate() + } + 0 + } + fn get_machine_gpu_num(machine_id: MachineId) -> u64 { let machine_info_result = online_profile::Pallet::::machines_info(machine_id); if let Some(machine_info) = machine_info_result { @@ -749,11 +788,10 @@ impl MachineInfoTrait for Pallet { 0 } - fn get_machine_valid_stake_duration( - last_claim_at: T::BlockNumber, - slash_at: T::BlockNumber, - end_at: T::BlockNumber, + // get machine rent end block number by owner + fn get_rent_end_at( machine_id: MachineId, + rent_id: RentOrderId, ) -> Result { let machine_info = online_profile::Pallet::::machines_info(&machine_id) .ok_or(Error::::MachineNotFound.as_str())?; @@ -761,99 +799,104 @@ impl MachineInfoTrait for Pallet { let renter_controller = machine_info.controller; let renter_stash = machine_info.machine_stash; - let now = >::block_number(); - let mut rent_duration: T::BlockNumber = T::BlockNumber::default(); - let mut controller_rented_orders = - Self::machine_renter_rented_orders(&machine_id, &renter_controller); - let stash_rented_orders = Self::machine_renter_rented_orders(&machine_id, &renter_stash); - controller_rented_orders.extend(stash_rented_orders); - controller_rented_orders.iter().for_each(|rented_order| { - let mut end_time = rented_order.rent_end; - if end_at.saturated_into::() > 0 { - end_time = rented_order.rent_end.min(end_at); - } - if end_time >= last_claim_at { - if slash_at == T::BlockNumber::default() { - rent_duration += now.min(end_time) - last_claim_at.max(rented_order.rent_start) - } else { - rent_duration += - now.min(end_at).min(slash_at) - last_claim_at.max(rented_order.rent_start) - } - } - }); - Ok(rent_duration) - } - - fn get_renting_duration( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, - machine_id: MachineId, - rent_id: RentOrderId, - ) -> Result { - let ok = verify_signature(data, sig, from.clone()); - if !ok { - return Err(Error::::SignVerifiedFailed.as_str()) - }; - - let who = account_id::(from.clone())?; let rent_info = Self::rent_info(rent_id).ok_or(Error::::MachineNotRented.as_str())?; - if rent_info.renter != who { + + if rent_info.machine_id != machine_id { return Err(Error::::NotMachineRenter.as_str()) } - if rent_info.machine_id != machine_id { + + if rent_info.renter != renter_controller && rent_info.renter != renter_stash { return Err(Error::::NotMachineRenter.as_str()) } - Ok(rent_info.rent_end.saturating_sub(>::block_number())) + + Ok(rent_info.rent_end) } - fn is_both_machine_renter_and_owner( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, - machine_id: MachineId, - ) -> Result { - let ok = verify_signature(data, sig, from.clone()); - if !ok { - return Err(Error::::SignVerifiedFailed.as_str()) - }; + fn is_machine_owner(machine_id: MachineId, evm_address: H160) -> Result { + let account = Self::evm_address_to_account(evm_address) + .ok_or(Error::::NotMachineOwner.as_str())?; - let renter = account_id::(from.clone())?; let machine_info = online_profile::Pallet::::machines_info(machine_id) .ok_or(Error::::MachineNotFound.as_str())?; - if machine_info.machine_status != MachineStatus::Rented { - return Err(Error::::MachineNotRented.as_str()) - }; - if machine_info.controller != renter && machine_info.machine_stash != renter { - return Err(Error::::NotMachineRenter.as_str()) - } - if machine_info.renters.len() != 1 { - return Err(Error::::MoreThanOneRenter.as_str()) - } + return Ok(machine_info.controller == account || machine_info.machine_stash == account) + } - if machine_info.renters.iter().find(|&r| r == &renter).is_some() { - return Ok(true) - } + fn get_usdt_machine_rent_fee( + machine_id: MachineId, + duration: T::BlockNumber, + rent_gpu_num: u32, + ) -> Result { + let machine_info = >::machines_info(&machine_id) + .ok_or(Error::::Unknown.as_str())?; + + let machine_price = T::RTOps::get_machine_price( + machine_info.calc_point(), + rent_gpu_num, + machine_info.gpu_num(), + ) + .ok_or(Error::::GetMachinePriceFailed)?; + + // 根据租用时长计算rent_fee + let rent_fee_value = machine_price + .checked_mul(duration.saturated_into::()) + .ok_or(Error::::Overflow)? + .checked_div(ONE_DAY.into()) + .ok_or(Error::::Overflow)?; + Ok(rent_fee_value.saturated_into::()) + } + fn get_dlc_machine_rent_fee( + machine_id: MachineId, + duration: T::BlockNumber, + rent_gpu_num: u32, + ) -> Result { + let machine_info = >::machines_info(&machine_id) + .ok_or(Error::::Unknown.as_str())?; + + let machine_price = T::RTOps::get_machine_price( + machine_info.calc_point(), + rent_gpu_num, + machine_info.gpu_num(), + ) + .ok_or(Error::::GetMachinePriceFailed)?; + + // 根据租用时长计算rent_fee + let rent_fee_value = machine_price + .checked_mul(duration.saturated_into::()) + .ok_or(Error::::Overflow)? + .checked_div(ONE_DAY.into()) + .ok_or(Error::::Overflow)?; + let rent_fee_value = + Perbill::from_rational(25u32, 100u32) * rent_fee_value + rent_fee_value; - return Err(Error::::NotMachineRenter.as_str()) + let rent_fee = ::DbcPrice::get_dlc_amount_by_value(rent_fee_value) + .ok_or(Error::::Overflow)?; + Ok(rent_fee.saturated_into::()) } - fn is_machine_owner( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, + fn get_dbc_machine_rent_fee( machine_id: MachineId, - ) -> Result { - let ok = verify_signature(data, sig, from.clone()); - if !ok { - return Err(Error::::SignVerifiedFailed.as_str()) - }; + duration: T::BlockNumber, + rent_gpu_num: u32, + ) -> Result { + let machine_info = >::machines_info(&machine_id) + .ok_or(Error::::Unknown.as_str())?; - let renter = account_id::(from.clone())?; - let machine_info = online_profile::Pallet::::machines_info(machine_id) - .ok_or(Error::::MachineNotFound.as_str())?; + let machine_price = T::RTOps::get_machine_price( + machine_info.calc_point(), + rent_gpu_num, + machine_info.gpu_num(), + ) + .ok_or(Error::::GetMachinePriceFailed)?; - return Ok(machine_info.controller == renter || machine_info.machine_stash == renter) + // 根据租用时长计算rent_fee + let rent_fee_value = machine_price + .checked_mul(duration.saturated_into::()) + .ok_or(Error::::Overflow)? + .checked_div(ONE_DAY.into()) + .ok_or(Error::::Overflow)?; + let rent_fee = ::DbcPrice::get_dbc_amount_by_value(rent_fee_value) + .ok_or(Error::::Overflow)?; + Ok(rent_fee.saturated_into::()) } } diff --git a/pallets/rent-machine/src/tests/test_rent_individual_gpu.rs b/pallets/rent-machine/src/tests/test_rent_individual_gpu.rs index ef20763a..beb2b627 100644 --- a/pallets/rent-machine/src/tests/test_rent_individual_gpu.rs +++ b/pallets/rent-machine/src/tests/test_rent_individual_gpu.rs @@ -25,7 +25,7 @@ fn report_individual_gpu() { // 补充质押 让租金进入算工的余额而不是质押 let mut machine_info = OnlineProfile::machines_info(&machine_id).unwrap(); - Balances::reserve(&stash, 396000 * ONE_DBC); + let _ = Balances::reserve(&stash, 396000 * ONE_DBC); machine_info.stake_amount += 396000 * ONE_DBC; MachinesInfo::::insert(&machine_id, &machine_info); diff --git a/pallets/rent-machine/src/tests/tests.rs b/pallets/rent-machine/src/tests/tests.rs index 0ea8973a..261c53d6 100644 --- a/pallets/rent-machine/src/tests/tests.rs +++ b/pallets/rent-machine/src/tests/tests.rs @@ -213,7 +213,7 @@ fn controller_report_offline_when_rented_should_work() { new_test_ext_after_machine_online().execute_with(|| { // 补充质押 let mut machine_info = OnlineProfile::machines_info(machine_id.clone()).unwrap(); - Balances::reserve(&stash, 396000 * ONE_DBC); + let _ = Balances::reserve(&stash, 396000 * ONE_DBC); machine_info.stake_amount += 396000 * ONE_DBC; MachinesInfo::::insert(machine_id.clone(), &machine_info); @@ -273,7 +273,7 @@ fn rented_report_offline_rented_end_report_online() { // 补充质押 让租金进入算工的余额而不是质押 let mut machine_info = OnlineProfile::machines_info(machine_id.clone()).unwrap(); - Balances::reserve(&stash, 396000 * ONE_DBC); + let _ = Balances::reserve(&stash, 396000 * ONE_DBC); machine_info.stake_amount += 396000 * ONE_DBC; MachinesInfo::::insert(machine_id.clone(), &machine_info); diff --git a/pallets/support/src/machine_info.rs b/pallets/support/src/machine_info.rs index a283761d..ed866b01 100644 --- a/pallets/support/src/machine_info.rs +++ b/pallets/support/src/machine_info.rs @@ -260,4 +260,8 @@ where pub fn can_rent(&self) -> bool { matches!(self.machine_status, MachineStatus::Online | MachineStatus::Rented) } + + pub fn cpu_rate(&self) -> u64 { + self.machine_info_detail.committee_upload_info.cpu_rate + } } diff --git a/pallets/support/src/traits.rs b/pallets/support/src/traits.rs index fa328e35..b1b68e68 100644 --- a/pallets/support/src/traits.rs +++ b/pallets/support/src/traits.rs @@ -118,6 +118,8 @@ pub trait DbcPrice { fn get_dbc_price() -> Option; fn get_dbc_amount_by_value(value: u64) -> Option; + + fn get_dlc_amount_by_value(value: u64) -> Option; } pub trait ProjectRegister { @@ -152,56 +154,32 @@ pub trait ProjectRegister { pub trait MachineInfoTrait { type BlockNumber; fn get_machine_calc_point(machine_id: MachineId) -> u64; - + fn get_machine_cpu_rate(machine_id: MachineId) -> u64; fn get_machine_gpu_num(machine_id: MachineId) -> u64; - fn get_machine_valid_stake_duration( - last_claim_at: Self::BlockNumber, - slash_at: Self::BlockNumber, - end_at: Self::BlockNumber, - machine_id: MachineId, - ) -> Result; - - fn get_renting_duration( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, + fn get_rent_end_at( machine_id: MachineId, rent_id: RentOrderId, ) -> Result; - fn is_both_machine_renter_and_owner( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, - machine_id: MachineId, - ) -> Result; + fn is_machine_owner(machine_id: MachineId, evm_address: H160) -> Result; - fn is_machine_owner( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, + fn get_dlc_machine_rent_fee( machine_id: MachineId, - ) -> Result; -} + duration: Self::BlockNumber, + rent_gpu_num: u32, + ) -> Result; -pub trait DLCMachineInfoTrait { - type BlockNumber; - - fn get_dlc_machine_rent_duration( - last_claim_at: Self::BlockNumber, - slash_at: Self::BlockNumber, + fn get_dbc_machine_rent_fee( machine_id: MachineId, - ) -> Result; - - fn get_rented_gpu_count_in_dlc_nft_staking(phase_level: PhaseLevel) -> u64; + duration: Self::BlockNumber, + rent_gpu_num: u32, + ) -> Result; - fn get_rented_gpu_count_of_machine_in_dlc_nft_staking(machine_id: MachineId) -> u64; - fn get_total_dlc_nft_staking_burned_rent_fee(phase_level: PhaseLevel) -> u64; - - fn get_dlc_nft_staking_burned_rent_fee_by_machine_id( - phase_level: PhaseLevel, + fn get_usdt_machine_rent_fee( machine_id: MachineId, - ) -> u64; + duration: Self::BlockNumber, + rent_gpu_num: u32, + ) -> Result; } #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)] pub enum PhaseLevel { @@ -226,59 +204,6 @@ impl From for PhaseLevel { } } -pub trait DLCMachineReportStakingTrait { - type BlockNumber; - - fn report_dlc_nft_staking( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, - machine_id: MachineId, - phase_level: PhaseLevel, - ) -> Result<(), &'static str>; - - fn report_dlc_nft_end_staking( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, - machine_id: MachineId, - phase_level: PhaseLevel, - ) -> Result<(), &'static str>; - - fn report_dlc_staking( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, - machine_id: MachineId, - ) -> Result<(), &'static str>; - - fn report_dlc_end_staking( - data: Vec, - sig: sp_core::sr25519::Signature, - from: sp_core::sr25519::Public, - machine_id: MachineId, - ) -> Result<(), &'static str>; - - fn get_nft_staking_valid_reward_duration( - last_claim_at: Self::BlockNumber, - total_stake_duration: Self::BlockNumber, - phase_level: PhaseLevel, - ) -> Self::BlockNumber; - - fn get_nft_staking_reward_start_at(phase_level: &PhaseLevel) -> Self::BlockNumber; - - fn get_nft_staking_gpu_count(phase_level: &PhaseLevel) -> (u64, u64); -} - -pub trait DLCMachineSlashInfoTrait { - fn get_dlc_machine_slashed_at(machine_id: MachineId) -> u64; - fn get_dlc_machine_slashed_report_id(machine_id: MachineId) -> u64; - - fn is_slashed(machine_id: MachineId) -> bool; - - fn get_dlc_machine_slashed_reporter(machine_id: MachineId) -> H160; -} - pub trait MTOps { type AccountId; type MachineId; diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index dc89984e..388fec03 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -21,7 +21,6 @@ evm-macro = { path = "src/precompiles/macro" } ethabi = { workspace = true } array-bytes = { workspace = true } num_enum = { workspace = true } -hex = { workspace = true } # primitives sp-authority-discovery = { workspace = true } @@ -113,10 +112,6 @@ online-profile-runtime-api = { path = "../pallets/online-profile/rpc/runtime-api rent-machine-runtime-api = { path = "../pallets/rent-machine/rpc/runtime-api", default-features = false } simple-rpc-runtime-api = { path = "../pallets/simple-rpc/rpc/runtime-api", default-features = false } terminating-rental-runtime-api = { path = "../pallets/terminating-rental/rpc/runtime-api", default-features = false } -ai-project-register = { path = "../pallets/ai-project-register", default-features = false } -rent-dlc-machine = { path = "../pallets/rent-dlc-machine", default-features = false } -rent-dlc-machine-runtime-api = { path = "../pallets/rent-dlc-machine/rpc/runtime-api", default-features = false } -dlc-machine = { path = "../pallets/dlc-machine", default-features = false } dbc-primitives-rpc-debug = { workspace = true } dbc-primitives-rpc-txpool = { workspace = true } @@ -233,10 +228,6 @@ std = [ "rent-machine-runtime-api/std", "simple-rpc-runtime-api/std", "terminating-rental-runtime-api/std", - "rent-dlc-machine/std", - "rent-dlc-machine-runtime-api/std", - "dlc-machine/std", - # Evm "fp-evm/std", "fp-rpc/std", @@ -352,9 +343,6 @@ try-runtime = [ "pallet-evm/try-runtime", "pallet-evm-chain-id/try-runtime", "pallet-base-fee/try-runtime", - "ai-project-register/try-runtime", - "rent-dlc-machine/try-runtime", - "dlc-machine/try-runtime" ] evm-tracing = [ diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 8ae596b8..d2097ab8 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -1419,8 +1419,6 @@ impl maintain_committee::Config for Runtime { type CancelSlashOrigin = pallet_collective::EnsureProportionAtLeast; type SlashAndReward = GenericFunc; - type AssetId = u32; - type DLCAssetId = ConstU32<88>; } impl terminating_rental::Config for Runtime { @@ -1569,23 +1567,6 @@ impl pallet_base_fee::Config for Runtime { type DefaultBaseFeePerGas = DefaultBaseFeePerGas; type DefaultElasticity = DefaultElasticity; } - -impl ai_project_register::Config for Runtime { - type RuntimeEvent = RuntimeEvent; -} - -impl rent_dlc_machine::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type RTOps = OnlineProfile; - type DbcPrice = DBCPriceOCW; - type AssetId = u32; - type DLCAssetId = ConstU32<88>; -} - -impl dlc_machine::Config for Runtime { - type RuntimeEvent = RuntimeEvent; -} - const ALLIANCE_MOTION_DURATION_IN_BLOCKS: BlockNumber = 5 * DAYS; parameter_types! { @@ -1658,9 +1639,6 @@ construct_runtime!( RentMachine: rent_machine = 111, MaintainCommittee: maintain_committee = 112, TerminatingRental: terminating_rental = 113, - AiProjectRegister: ai_project_register = 114, - RentDLCMachine:rent_dlc_machine = 115, - DLCMachine: dlc_machine = 116, } ); @@ -2571,24 +2549,6 @@ impl_runtime_apis! { } } - impl rent_dlc_machine_runtime_api::DlcRmRpcApi for Runtime { - fn get_dlc_rent_order(rent_id: RentOrderId) -> Option> { - RentMachine::get_rent_order(rent_id) - } - - fn get_dlc_rent_list(renter: AccountId) -> Vec { - RentMachine::get_rent_list(renter) - } - - fn is_dlc_machine_renter(machine_id: MachineId, renter: AccountId) -> bool { - RentMachine::is_machine_renter(machine_id, renter) - } - - fn get_dlc_machine_rent_id(machine_id: MachineId) -> MachineGPUOrder { - RentMachine::get_machine_rent_id(machine_id) - } - } - impl committee_runtime_api::CmRpcApi for Runtime { fn get_committee_list() -> committee::CommitteeList { Committee::get_committee_list() diff --git a/runtime/src/precompiles/dlc_machine_report_staking.rs b/runtime/src/precompiles/dlc_machine_report_staking.rs deleted file mode 100644 index 893979cf..00000000 --- a/runtime/src/precompiles/dlc_machine_report_staking.rs +++ /dev/null @@ -1,539 +0,0 @@ -use fp_evm::{ - ExitRevert, ExitSucceed, Precompile, PrecompileFailure, PrecompileHandle, PrecompileOutput, - PrecompileResult, -}; -use sp_core::Get; -use sp_runtime::{RuntimeDebug, SaturatedConversion}; -extern crate alloc; -use crate::precompiles::LOG_TARGET; -use alloc::format; -use core::marker::PhantomData; -use dbc_support::traits::DLCMachineReportStakingTrait; -use frame_support::{ensure, pallet_prelude::Weight}; -use num_enum::{IntoPrimitive, TryFromPrimitive}; -use pallet_evm::GasWeightMapping; -use sp_std::vec; -pub struct DLCMachineReportStaking(PhantomData); - -#[evm_macro::generate_function_selector] -#[derive(RuntimeDebug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive)] -#[repr(u32)] -pub enum Selector { - ReportDlcStaking = "reportDlcStaking(string,string,string,string)", - ReportDlcEndStaking = "reportDlcEndStaking(string,string,string,string)", - - ReportDlcNftStaking = "reportDlcNftStaking(string,string,string,string,uint256)", - ReportDlcNftEndStaking = "reportDlcNftEndStaking(string,string,string,string,uint256)", - GetValidRewardDuration = "getValidRewardDuration(uint256,uint256,uint256)", - GetDlcNftStakingRewardStartAt = "getDlcNftStakingRewardStartAt(uint256)", - GetDlcStakingGPUCount = "getDlcStakingGPUCount(uint256)", -} - -impl Precompile for DLCMachineReportStaking -where - T: pallet_evm::Config + dlc_machine::Config, -{ - fn execute(handle: &mut impl PrecompileHandle) -> PrecompileResult { - let input = handle.input(); - ensure!( - input.len() >= 4, - PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "invalid input".into(), - } - ); - - let selector = u32::from_be_bytes(input[..4].try_into().expect("checked. qed!")); - let selector: Selector = selector.try_into().map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("invalid selector: {:?}", e).into(), - })?; - - match selector { - Selector::ReportDlcStaking => { - let param = ethabi::decode( - &[ - ethabi::ParamType::String, // msg - ethabi::ParamType::String, // sig - ethabi::ParamType::String, // public - ethabi::ParamType::String, // machine_id - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let msg = - param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - - let sig_str = - param[1].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[1] failed".into(), - })?; - - let sig = - hex::decode(sig_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode sig failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 64]; - b.copy_from_slice(&sig[..]); - let sig = sp_core::sr25519::Signature(b); - - let public_str = - param[2].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[2] failed".into(), - })?; - - let public = - hex::decode(public_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode pub key failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 32]; - b.copy_from_slice(&public[..]); - let public = sp_core::sr25519::Public(b); - - let machine_id_str = - param[3].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[3] failed".into(), - })?; - - let machine_id = machine_id_str.as_bytes().to_vec(); - - let _ = - as DLCMachineReportStakingTrait>::report_dlc_staking( - msg.clone().into_bytes(), - sig.clone(), - public.clone(), - machine_id_str.clone().as_bytes().to_vec(), - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!( - "err: {}, msg: {}, sig: {:?}, public: {:?}, machine_id: {}", - e, msg, sig, public, machine_id_str - ) - .into(), - })?; - - log::debug!(target: LOG_TARGET, "report_dlc_staking: machine_id: {:?}", machine_id,); - - let weight = Weight::default() - .saturating_add(::DbWeight::get().writes(1)); - - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; - - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Bool(true)]), - }) - }, - - Selector::ReportDlcEndStaking => { - let param = ethabi::decode( - &[ - ethabi::ParamType::String, // msg - ethabi::ParamType::String, // sig - ethabi::ParamType::String, // public - ethabi::ParamType::String, // machine_id - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let msg = - param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - - let sig_str = - param[1].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[1] failed".into(), - })?; - - let sig = - hex::decode(sig_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode sig failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 64]; - b.copy_from_slice(&sig[..]); - let sig = sp_core::sr25519::Signature(b); - - let public_str = - param[2].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[2] failed".into(), - })?; - - let public = - hex::decode(public_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode pub key failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 32]; - b.copy_from_slice(&public[..]); - let public = sp_core::sr25519::Public(b); - - let machine_id_str = - param[3].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[3] failed".into(), - })?; - - let _ = as DLCMachineReportStakingTrait>::report_dlc_end_staking(msg.clone().into_bytes(),sig.clone(),public.clone(), machine_id_str.clone().as_bytes().to_vec()).map_err( |e| { - PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("err: {}, msg: {}, sig: {:?}, public: {:?}, machine_id: {}",e,msg,sig,public, machine_id_str).into(), - } - })?; - log::debug!( - target: LOG_TARGET, - "msg : {:?}, sig : {:?}, public : {:?}, machine_id : {:?}", - msg, - sig, - public, - machine_id_str - ); - - let weight = Weight::default() - .saturating_add(::DbWeight::get().writes(1)); - - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; - - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Bool(true)]), - }) - }, - - Selector::ReportDlcNftStaking => { - let param = ethabi::decode( - &[ - ethabi::ParamType::String, // msg - ethabi::ParamType::String, // sig - ethabi::ParamType::String, // public - ethabi::ParamType::String, // machine_id - ethabi::ParamType::Uint(256), // phase_level - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let msg = - param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - - let sig_str = - param[1].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[1] failed".into(), - })?; - - let sig = - hex::decode(sig_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode sig failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 64]; - b.copy_from_slice(&sig[..]); - let sig = sp_core::sr25519::Signature(b); - - let public_str = - param[2].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[2] failed".into(), - })?; - - let public = - hex::decode(public_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode pub key failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 32]; - b.copy_from_slice(&public[..]); - let public = sp_core::sr25519::Public(b); - - let machine_id_str = - param[3].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[3] failed".into(), - })?; - - let machine_id = machine_id_str.as_bytes().to_vec(); - - let phase_level_uint = - param[4].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[4] failed".into(), - })?; - let phase_level: u64 = phase_level_uint.as_u64(); - - let _ = - as DLCMachineReportStakingTrait>::report_dlc_nft_staking( - msg.clone().into_bytes(), - sig.clone(), - public.clone(), - machine_id_str.clone().as_bytes().to_vec(), - phase_level.into() - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!( - "err: {}, msg: {}, sig: {:?}, public: {:?}, machine_id: {}", - e, msg, sig, public, machine_id_str - ) - .into(), - })?; - - log::debug!(target: LOG_TARGET, "report_dlc_nft_staking: machine_id: {:?}", machine_id,); - - let weight = Weight::default() - .saturating_add(::DbWeight::get().writes(1)); - - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; - - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Bool(true)]), - }) - }, - - Selector::ReportDlcNftEndStaking => { - let param = ethabi::decode( - &[ - ethabi::ParamType::String, // msg - ethabi::ParamType::String, // sig - ethabi::ParamType::String, // public - ethabi::ParamType::String, // machine_id - ethabi::ParamType::Uint(256), // phase_level - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let msg = - param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - - let sig_str = - param[1].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[1] failed".into(), - })?; - - let sig = - hex::decode(sig_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode sig failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 64]; - b.copy_from_slice(&sig[..]); - let sig = sp_core::sr25519::Signature(b); - - let public_str = - param[2].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[2] failed".into(), - })?; - - let public = - hex::decode(public_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode pub key failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 32]; - b.copy_from_slice(&public[..]); - let public = sp_core::sr25519::Public(b); - - let machine_id_str = - param[3].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[3] failed".into(), - })?; - - let phase_level_uint = - param[4].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[4] failed".into(), - })?; - let phase_level: u64 = phase_level_uint.as_u64(); - - let _ = as DLCMachineReportStakingTrait>::report_dlc_nft_end_staking(msg.clone().into_bytes(),sig.clone(),public.clone(), machine_id_str.clone().as_bytes().to_vec(),phase_level.into()).map_err( |e| { - PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("err: {}, msg: {}, sig: {:?}, public: {:?}, machine_id: {}",e,msg,sig,public, machine_id_str).into(), - } - })?; - log::debug!( - target: LOG_TARGET, - "msg : {:?}, sig : {:?}, public : {:?}, machine_id : {:?}", - msg, - sig, - public, - machine_id_str - ); - - let weight = Weight::default() - .saturating_add(::DbWeight::get().writes(1)); - - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; - - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Bool(true)]), - }) - }, - - Selector::GetValidRewardDuration => { - let param = ethabi::decode( - &[ - ethabi::ParamType::Uint(256), // last_claim_at - ethabi::ParamType::Uint(256), // total_stake_duration - ethabi::ParamType::Uint(256), // phase_level - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let last_claim_at_uint = - param[0].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - - let total_stake_duration_uint = - param[1].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[1] failed".into(), - })?; - - let phase_level_uint = - param[2].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[2] failed".into(), - })?; - let phase_level: u64 = phase_level_uint.as_u64(); - - let last_claim_at: u64 = last_claim_at_uint.as_u64(); - let total_stake_duration: u64 = total_stake_duration_uint.as_u64(); - - let valid_duration = as DLCMachineReportStakingTrait>::get_nft_staking_valid_reward_duration(T::BlockNumber::saturated_from(last_claim_at), T::BlockNumber::saturated_from(total_stake_duration), phase_level.into()); - let weight = Weight::default() - .saturating_add(::DbWeight::get().reads(1)); - - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; - - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Uint( - valid_duration.saturated_into::().into(), - )]), - }) - }, - - Selector::GetDlcNftStakingRewardStartAt => { - let param = ethabi::decode( - &[ - ethabi::ParamType::Uint(256), // phase_level - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let phase_level_uint = - param[0].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - let phase_level: u64 = phase_level_uint.as_u64(); - - let phase_one_reward_start_at = as DLCMachineReportStakingTrait>::get_nft_staking_reward_start_at(&phase_level.into()); - let weight = Weight::default() - .saturating_add(::DbWeight::get().reads(1)); - - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; - - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Uint( - phase_one_reward_start_at.saturated_into::().into(), - )]), - }) - }, - Selector::GetDlcStakingGPUCount => { - let param = ethabi::decode( - &[ - ethabi::ParamType::Uint(256), // phase_level - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let phase_level_uint = - param[0].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - let phase_level: u64 = phase_level_uint.as_u64(); - - let (gpu_count,gpu_count_before_reward_start) = as DLCMachineReportStakingTrait>::get_nft_staking_gpu_count(&phase_level.into()); - let weight = Weight::default() - .saturating_add(::DbWeight::get().reads(1)); - - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; - - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Tuple(vec![ - ethabi::Token::Uint(gpu_count.saturated_into::().into()), - ethabi::Token::Uint( - gpu_count_before_reward_start.saturated_into::().into(), - ), - ])]), - }) - }, - } - } -} diff --git a/runtime/src/precompiles/dlc_machine_slash_info.rs b/runtime/src/precompiles/dlc_machine_slash_info.rs deleted file mode 100644 index 473eb210..00000000 --- a/runtime/src/precompiles/dlc_machine_slash_info.rs +++ /dev/null @@ -1,196 +0,0 @@ -use fp_evm::{ - ExitRevert, ExitSucceed, Precompile, PrecompileFailure, PrecompileHandle, PrecompileOutput, - PrecompileResult, -}; -use sp_core::Get; -use sp_runtime::RuntimeDebug; -extern crate alloc; -use crate::precompiles::LOG_TARGET; -use alloc::format; -use core::marker::PhantomData; -use dbc_support::traits::DLCMachineSlashInfoTrait; -use frame_support::{ensure, pallet_prelude::Weight}; -use num_enum::{IntoPrimitive, TryFromPrimitive}; -use pallet_evm::GasWeightMapping; - -pub struct DLCMachineSlashInfo(PhantomData); - -#[evm_macro::generate_function_selector] -#[derive(RuntimeDebug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive)] -#[repr(u32)] -pub enum Selector { - GetDlcMachineSlashedAt = "getDlcMachineSlashedAt(string)", - GetDlcMachineSlashedReportId = "getDlcMachineSlashedReportId(string)", - GetDlcMachineSlashedReporter = "getDlcMachineSlashedReporter(string)", - IsSlashed = "isSlashed(string)", -} - -impl Precompile for DLCMachineSlashInfo -where - T: pallet_evm::Config + maintain_committee::Config, -{ - fn execute(handle: &mut impl PrecompileHandle) -> PrecompileResult { - let input = handle.input(); - ensure!( - input.len() >= 4, - PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "invalid input".into(), - } - ); - - let selector = u32::from_be_bytes(input[..4].try_into().expect("checked. qed!")); - let selector: Selector = selector.try_into().map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("invalid selector: {:?}", e).into(), - })?; - - match selector { - Selector::GetDlcMachineSlashedAt => { - let param = ethabi::decode( - &[ - ethabi::ParamType::String, // machine_id - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let machine_id_str = - param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - - let machine_id = machine_id_str.as_bytes().to_vec(); - - let slash_at = as DLCMachineSlashInfoTrait>::get_dlc_machine_slashed_at(machine_id_str.clone().as_bytes().to_vec()); - - log::debug!( - target: LOG_TARGET, - "get_dlc_machine_slashed_at: machine_id: {:?}", - machine_id, - ); - - let weight = Weight::default() - .saturating_add(::DbWeight::get().reads(1)); - - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; - - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Uint(slash_at.into())]), - }) - }, - - Selector::GetDlcMachineSlashedReportId => { - let param = ethabi::decode( - &[ - ethabi::ParamType::String, // machine_id - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let machine_id_str = - param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - - let report_id = as DLCMachineSlashInfoTrait>::get_dlc_machine_slashed_report_id(machine_id_str.clone().as_bytes().to_vec()); - - log::debug!(target: LOG_TARGET, " machine_id : {:?}", machine_id_str); - - let weight = Weight::default() - .saturating_add(::DbWeight::get().reads(1)); - - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; - - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Int(report_id.into())]), - }) - }, - Selector::GetDlcMachineSlashedReporter => { - let param = ethabi::decode( - &[ - ethabi::ParamType::String, // machine_id - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let machine_id_str = - param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - - let machine_id = machine_id_str.as_bytes().to_vec(); - - let reporter = as DLCMachineSlashInfoTrait>::get_dlc_machine_slashed_reporter(machine_id_str.clone().as_bytes().to_vec()); - - log::debug!( - target: LOG_TARGET, - "get_dlc_machine_slashed_reporter: machine_id: {:?}", - machine_id, - ); - - let weight = Weight::default() - .saturating_add(::DbWeight::get().reads(1)); - - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; - - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Address(reporter.into())]), - }) - }, - - Selector::IsSlashed => { - let param = ethabi::decode( - &[ - ethabi::ParamType::String, // machine_id - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let machine_id_str = - param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - - let slashed = - as DLCMachineSlashInfoTrait>::is_slashed( - machine_id_str.clone().as_bytes().to_vec(), - ); - - log::debug!(target: LOG_TARGET, " machine_id : {:?}", machine_id_str); - - let weight = Weight::default() - .saturating_add(::DbWeight::get().reads(1)); - - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; - - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Bool(slashed)]), - }) - }, - } - } -} diff --git a/runtime/src/precompiles/machine_info.rs b/runtime/src/precompiles/machine_info.rs index 57009fde..e6288419 100644 --- a/runtime/src/precompiles/machine_info.rs +++ b/runtime/src/precompiles/machine_info.rs @@ -8,7 +8,7 @@ extern crate alloc; use crate::precompiles::LOG_TARGET; use alloc::format; use core::marker::PhantomData; -use dbc_support::traits::{DLCMachineInfoTrait, MachineInfoTrait}; +use dbc_support::traits::MachineInfoTrait; use frame_support::{ensure, pallet_prelude::Weight}; use num_enum::{IntoPrimitive, TryFromPrimitive}; use pallet_evm::GasWeightMapping; @@ -21,24 +21,18 @@ pub struct MachineInfo(PhantomData); #[repr(u32)] pub enum Selector { GetMachineCalcPoint = "getMachineCalcPoint(string)", + GetMachineCPURate = "getMachineCPURate(string)", GetMachineGPUCount = "getMachineGPUCount(string)", - GetRentDuration = "getRentDuration(uint256,uint256,uint256,string)", - GetDlcMachineRentDuration = "getDlcMachineRentDuration(uint256,uint256,string)", - GetRentingDuration = "getRentingDuration(string,string,string,string,uint256)", - GetRentedGPUCountInDlcNftStaking = "getRentedGPUCountInDlcNftStaking(uint256)", - GetRentedGPUCountOfMachineInDlcNftStaking = - "getRentedGPUCountOfMachineInDlcNftStaking(uint256,string)", - GetTotalDlcNftStakingBurnedRentFee = "getTotalDlcNftStakingBurnedRentFee(uint256)", - GetDlcNftStakingBurnedRentFeeByMachine = - "getDlcNftStakingBurnedRentFeeByMachine(uint256,string)", + GetRentEndAt = "getRentEndAt(string,uint256)", + IsMachineOwner = "isMachineOwner(string,address)", + GetDLCMachineRentFee = "getDLCMachineRentFee(string,uint256,uint256)", + GetDBCMachineRentFee = "getDBCMachineRentFee(string,uint256,uint256)", + GetUSDTMachineRentFee = "getUSDTMachineRentFee(string,uint256,uint256)", } impl Precompile for MachineInfo where - T: pallet_evm::Config - + pallet_balances::Config - + rent_machine::Config - + rent_dlc_machine::Config, + T: pallet_evm::Config + pallet_balances::Config + rent_machine::Config, { fn execute(handle: &mut impl PrecompileHandle) -> PrecompileResult { let input = handle.input(); @@ -98,7 +92,7 @@ where }) }, - Selector::GetMachineGPUCount => { + Selector::GetMachineCPURate => { let param = ethabi::decode(&[ethabi::ParamType::String], &input[4..]).map_err(|e| { PrecompileFailure::Revert { @@ -115,12 +109,19 @@ where let machine_id = machine_id_str.as_bytes().to_vec(); - let gpu_num: U256 = - as MachineInfoTrait>::get_machine_gpu_num( + let cpu_rate: U256 = + as MachineInfoTrait>::get_machine_cpu_rate( machine_id.clone(), ) .into(); + log::debug!( + target: LOG_TARGET, + "get_machine_cpu_rate: machine_id: {:?}, cpu_rate: {:?}", + machine_id, + cpu_rate + ); + let weight = Weight::default() .saturating_add(::DbWeight::get().reads(1)); @@ -128,62 +129,32 @@ where Ok(PrecompileOutput { exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Uint(gpu_num)]), + output: ethabi::encode(&[ethabi::Token::Uint(cpu_rate)]), }) }, - Selector::GetRentDuration => { - let param = ethabi::decode( - &[ - ethabi::ParamType::Uint(256), // last_claim_at - ethabi::ParamType::Uint(256), // slash_at - ethabi::ParamType::Uint(256), // end_at - ethabi::ParamType::String, // machine_id - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let last_claim_at_block_number_uint = - param[0].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - - let last_claim_at_block_number: u64 = last_claim_at_block_number_uint.as_u64(); - - let slash_at_block_number_uint = - param[1].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[1] failed".into(), - })?; - - let slash_at_block_number: u64 = slash_at_block_number_uint.as_u64(); - - let end_at_block_number_uint = - param[2].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[2] failed".into(), + Selector::GetMachineGPUCount => { + let param = + ethabi::decode(&[ethabi::ParamType::String], &input[4..]).map_err(|e| { + PrecompileFailure::Revert { + exit_status: ExitRevert::Reverted, + output: format!("decode param failed: {:?}", e).into(), + } })?; - let end_at_block_number: u64 = end_at_block_number_uint.as_u64(); - let machine_id_str = - param[3].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { + param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, - output: "decode param[3] failed".into(), + output: "decode param[0] failed".into(), })?; - let duration = as MachineInfoTrait>::get_machine_valid_stake_duration(T::BlockNumber::saturated_from(last_claim_at_block_number.clone()),T::BlockNumber::saturated_from(slash_at_block_number.clone()),T::BlockNumber::saturated_from(end_at_block_number.clone()), machine_id_str.clone().as_bytes().to_vec()).map_err( |e| { - PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("err: {}, last_claim_at: {},slash_at: {}, machine_id: {}",e,last_claim_at_block_number,slash_at_block_number,machine_id_str).into(), - } - })?; - log::debug!(target: LOG_TARGET, " last_claim_at: {},slash_at: {}, machine_id : {:?}, get_machine_valid_stake_duration: duration: {:?}",last_claim_at_block_number,slash_at_block_number,machine_id_str,duration); + let machine_id = machine_id_str.as_bytes().to_vec(); + + let gpu_num: U256 = + as MachineInfoTrait>::get_machine_gpu_num( + machine_id.clone(), + ) + .into(); let weight = Weight::default() .saturating_add(::DbWeight::get().reads(1)); @@ -192,18 +163,15 @@ where Ok(PrecompileOutput { exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Uint( - duration.saturated_into::().into(), - )]), + output: ethabi::encode(&[ethabi::Token::Uint(gpu_num)]), }) }, - Selector::GetDlcMachineRentDuration => { + Selector::GetRentEndAt => { let param = ethabi::decode( &[ - ethabi::ParamType::Uint(256), // last_claim_at - ethabi::ParamType::Uint(256), // slash_at ethabi::ParamType::String, // machine_id + ethabi::ParamType::Uint(256), // rent_id ], &input[4..], ) @@ -212,35 +180,29 @@ where output: format!("decode param failed: {:?}", e).into(), })?; - let last_claim_at_block_number_uint = - param[0].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { + let machine_id_str = + param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, output: "decode param[0] failed".into(), })?; - - let last_claim_at_block_number: u64 = last_claim_at_block_number_uint.as_u64(); - - let slash_at_block_number_uint = + let rent_id_uint = param[1].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, output: "decode param[1] failed".into(), })?; - - let slash_at_block_number: u64 = slash_at_block_number_uint.as_u64(); - - let machine_id_str = - param[2].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[2] failed".into(), - })?; - - let duration = as DLCMachineInfoTrait>::get_dlc_machine_rent_duration( T::BlockNumber::saturated_from(last_claim_at_block_number.clone()),T::BlockNumber::saturated_from(slash_at_block_number.clone()), machine_id_str.clone().as_bytes().to_vec()).map_err( |e| { - PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("err: {}, last_claim_at: {},slash_at: {}, machine_id: {}",e,last_claim_at_block_number,slash_at_block_number,machine_id_str).into(), - } + let rent_id: u64 = rent_id_uint.as_u64(); + let end_at = as MachineInfoTrait>::get_rent_end_at( + machine_id_str.clone().as_bytes().to_vec(), + rent_id, + ) + .map_err(|e| PrecompileFailure::Revert { + exit_status: ExitRevert::Reverted, + output: format!( + "err: {}, machine_id: {}, rent_id: {}", + e, machine_id_str, rent_id + ) + .into(), })?; - log::debug!(target: LOG_TARGET, "last_claim_at: {},slash_at: {}, machine_id : {:?}, get_machine_valid_stake_duration: duration: {:?}",last_claim_at_block_number,slash_at_block_number,machine_id_str,duration); let weight = Weight::default() .saturating_add(::DbWeight::get().reads(1)); @@ -250,18 +212,16 @@ where Ok(PrecompileOutput { exit_status: ExitSucceed::Returned, output: ethabi::encode(&[ethabi::Token::Uint( - duration.saturated_into::().into(), + end_at.saturated_into::().into(), )]), }) }, - Selector::GetRentingDuration => { + + Selector::IsMachineOwner => { let param = ethabi::decode( &[ - ethabi::ParamType::String, // msg - ethabi::ParamType::String, // sig - ethabi::ParamType::String, // public - ethabi::ParamType::String, // machine_id - ethabi::ParamType::Uint(256), // rent_id + ethabi::ParamType::String, // machine_id + ethabi::ParamType::Address, // evm_address ], &input[4..], ) @@ -270,67 +230,27 @@ where output: format!("decode param failed: {:?}", e).into(), })?; - let msg = + let machine_id_str = param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, output: "decode param[0] failed".into(), })?; - - let sig_str = - param[1].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { + let machine_id = machine_id_str.clone().as_bytes().to_vec(); + let evm_address = + param[1].clone().into_address().ok_or_else(|| PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, output: "decode param[1] failed".into(), })?; - let sig = - hex::decode(sig_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode sig failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 64]; - b.copy_from_slice(&sig[..]); - let sig = sp_core::sr25519::Signature(b); - - let public_str = - param[2].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[2] failed".into(), - })?; - - let public = - hex::decode(public_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode pub key failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 32]; - b.copy_from_slice(&public[..]); - let public = sp_core::sr25519::Public(b); - - let machine_id_str = - param[3].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[3] failed".into(), - })?; - let rent_id_uint = - param[4].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[4] failed".into(), - })?; - let rent_id: u64 = rent_id_uint.as_u64(); - let duration = as MachineInfoTrait>::get_renting_duration( - msg.clone().into_bytes(), - sig.clone(), - public.clone(), - machine_id_str.clone().as_bytes().to_vec(), - rent_id, + let is_owner = as MachineInfoTrait>::is_machine_owner( + machine_id.clone(), + evm_address, ) .map_err(|e| PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, output: format!( - "err: {}, msg: {}, sig: {:?}, public: {:?}, machine_id: {}, rent_id: {}", - e, msg, sig, public, machine_id_str, rent_id + "err: {}, machine_id: {}, evm_address: {}", + e, machine_id_str, evm_address ) .into(), })?; @@ -342,15 +262,16 @@ where Ok(PrecompileOutput { exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Uint( - duration.saturated_into::().into(), - )]), + output: ethabi::encode(&[ethabi::Token::Bool(is_owner)]), }) }, - Selector::GetRentedGPUCountInDlcNftStaking => { + + Selector::GetDLCMachineRentFee => { let param = ethabi::decode( &[ - ethabi::ParamType::Uint(256), // phase_level + ethabi::ParamType::String, // machine_id + ethabi::ParamType::Uint(256), // rent_block_numbers + ethabi::ParamType::Uint(8), // rent_gpu_count ], &input[4..], ) @@ -359,48 +280,43 @@ where output: format!("decode param failed: {:?}", e).into(), })?; - let phase_level_uint = - param[0].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { + let machine_id_str = + param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, output: "decode param[0] failed".into(), })?; - let phase_level: u64 = phase_level_uint.as_u64(); - - let rented_gpu_count = as DLCMachineInfoTrait>::get_rented_gpu_count_in_dlc_nft_staking(phase_level.into()); + let machine_id = machine_id_str.clone().as_bytes().to_vec(); - let weight = Weight::default() - .saturating_add(::DbWeight::get().reads(1)); + let rent_duration_uint = + param[1].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { + exit_status: ExitRevert::Reverted, + output: "decode param[1] failed".into(), + })?; - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; + let rent_duration: u64 = rent_duration_uint.as_u64(); - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Uint( - rented_gpu_count.saturated_into::().into(), - )]), - }) - }, + let rent_gpu_count_uint = + param[2].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { + exit_status: ExitRevert::Reverted, + output: "decode param[2] failed".into(), + })?; - Selector::GetTotalDlcNftStakingBurnedRentFee => { - let param = ethabi::decode( - &[ - ethabi::ParamType::Uint(256), // phase_level - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; + let rent_gpu_count: u32 = rent_gpu_count_uint.as_u32(); - let phase_level_uint = - param[0].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { + let rent_fee = + as MachineInfoTrait>::get_dlc_machine_rent_fee( + machine_id.clone(), + rent_duration.saturated_into(), + rent_gpu_count, + ) + .map_err(|e| PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), + output: format!( + " err: {}, machine_id: {}, rent_duration: {}, rent_gpu_count: {}", + e, machine_id_str, rent_duration, rent_gpu_count + ) + .into(), })?; - let phase_level: u64 = phase_level_uint.as_u64(); - - let burned_rent_fee = as DLCMachineInfoTrait>::get_total_dlc_nft_staking_burned_rent_fee(phase_level.into()); let weight = Weight::default() .saturating_add(::DbWeight::get().reads(1)); @@ -409,17 +325,16 @@ where Ok(PrecompileOutput { exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Uint( - burned_rent_fee.saturated_into::().into(), - )]), + output: ethabi::encode(&[ethabi::Token::Uint(rent_fee.into())]), }) }, - Selector::GetDlcNftStakingBurnedRentFeeByMachine => { + Selector::GetDBCMachineRentFee => { let param = ethabi::decode( &[ - ethabi::ParamType::Uint(256), // phase_level ethabi::ParamType::String, // machine_id + ethabi::ParamType::Uint(256), // rent_block_numbers + ethabi::ParamType::Uint(8), // rent_gpu_count ], &input[4..], ) @@ -428,21 +343,43 @@ where output: format!("decode param failed: {:?}", e).into(), })?; - let phase_level_uint = - param[0].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { + let machine_id_str = + param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, output: "decode param[0] failed".into(), })?; - let phase_level: u64 = phase_level_uint.as_u64(); + let machine_id = machine_id_str.clone().as_bytes().to_vec(); - let machine_id_str = - param[1].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { + let rent_duration_uint = + param[1].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, output: "decode param[1] failed".into(), })?; - let machine_id = machine_id_str.clone().as_bytes().to_vec(); - let burned_rent_fee = as DLCMachineInfoTrait>::get_dlc_nft_staking_burned_rent_fee_by_machine_id(phase_level.into(), machine_id); + let rent_duration: u64 = rent_duration_uint.as_u64(); + + let rent_gpu_count_uint = + param[2].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { + exit_status: ExitRevert::Reverted, + output: "decode param[2] failed".into(), + })?; + + let rent_gpu_count: u32 = rent_gpu_count_uint.as_u32(); + + let rent_fee = + as MachineInfoTrait>::get_dbc_machine_rent_fee( + machine_id.clone(), + rent_duration.saturated_into(), + rent_gpu_count, + ) + .map_err(|e| PrecompileFailure::Revert { + exit_status: ExitRevert::Reverted, + output: format!( + " err: {}, machine_id: {}, rent_duration: {}, rent_gpu_count: {}", + e, machine_id_str, rent_duration, rent_gpu_count + ) + .into(), + })?; let weight = Weight::default() .saturating_add(::DbWeight::get().reads(1)); @@ -451,17 +388,16 @@ where Ok(PrecompileOutput { exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Uint( - burned_rent_fee.saturated_into::().into(), - )]), + output: ethabi::encode(&[ethabi::Token::Uint(rent_fee.into())]), }) }, - Selector::GetRentedGPUCountOfMachineInDlcNftStaking => { + Selector::GetUSDTMachineRentFee => { let param = ethabi::decode( &[ - ethabi::ParamType::Uint(256), // phase_level ethabi::ParamType::String, // machine_id + ethabi::ParamType::Uint(256), // rent_block_numbers + ethabi::ParamType::Uint(8), // rent_gpu_count ], &input[4..], ) @@ -471,14 +407,42 @@ where })?; let machine_id_str = - param[1].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { + param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { + exit_status: ExitRevert::Reverted, + output: "decode param[0] failed".into(), + })?; + let machine_id = machine_id_str.clone().as_bytes().to_vec(); + + let rent_duration_uint = + param[1].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, output: "decode param[1] failed".into(), })?; - let machine_id = machine_id_str.as_bytes().to_vec(); + let rent_duration: u64 = rent_duration_uint.as_u64(); - let rented_gpu_count = as DLCMachineInfoTrait>::get_rented_gpu_count_of_machine_in_dlc_nft_staking(machine_id); + let rent_gpu_count_uint = + param[2].clone().into_uint().ok_or_else(|| PrecompileFailure::Revert { + exit_status: ExitRevert::Reverted, + output: "decode param[2] failed".into(), + })?; + + let rent_gpu_count: u32 = rent_gpu_count_uint.as_u32(); + + let rent_fee = + as MachineInfoTrait>::get_usdt_machine_rent_fee( + machine_id.clone(), + rent_duration.saturated_into(), + rent_gpu_count, + ) + .map_err(|e| PrecompileFailure::Revert { + exit_status: ExitRevert::Reverted, + output: format!( + " err: {}, machine_id: {}, rent_duration: {}, rent_gpu_count: {}", + e, machine_id_str, rent_duration, rent_gpu_count + ) + .into(), + })?; let weight = Weight::default() .saturating_add(::DbWeight::get().reads(1)); @@ -487,9 +451,7 @@ where Ok(PrecompileOutput { exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Uint( - rented_gpu_count.saturated_into::().into(), - )]), + output: ethabi::encode(&[ethabi::Token::Uint(rent_fee.into())]), }) }, } diff --git a/runtime/src/precompiles/mod.rs b/runtime/src/precompiles/mod.rs index 62b95a6a..ecfde78e 100644 --- a/runtime/src/precompiles/mod.rs +++ b/runtime/src/precompiles/mod.rs @@ -16,18 +16,8 @@ use bridge::Bridge; mod dbc_price; use dbc_price::DBCPrice; -mod project_register; -use project_register::AIProjectRegister; - mod machine_info; use machine_info::MachineInfo; - -mod dlc_machine_slash_info; -use dlc_machine_slash_info::DLCMachineSlashInfo; - -mod dlc_machine_report_staking; -use dlc_machine_report_staking::DLCMachineReportStaking; - const LOG_TARGET: &str = "evm"; pub struct DBCPrecompiles(PhantomData); @@ -59,10 +49,7 @@ where Dispatch: Precompile, Bridge: Precompile, DBCPrice: Precompile, - AIProjectRegister: Precompile, MachineInfo: Precompile, - DLCMachineReportStaking: Precompile, - DLCMachineSlashInfo: Precompile, { fn execute(&self, handle: &mut impl PrecompileHandle) -> Option { match handle.code_address() { @@ -84,10 +71,7 @@ where // DBC specific precompiles a if a == hash(2048) => Some(Bridge::::execute(handle)), a if a == hash(2049) => Some(DBCPrice::::execute(handle)), - a if a == hash(2050) => Some(AIProjectRegister::::execute(handle)), a if a == hash(2051) => Some(MachineInfo::::execute(handle)), - a if a == hash(2052) => Some(DLCMachineReportStaking::::execute(handle)), - a if a == hash(2053) => Some(DLCMachineSlashInfo::::execute(handle)), _ => None, } diff --git a/runtime/src/precompiles/project_register.rs b/runtime/src/precompiles/project_register.rs deleted file mode 100644 index 2a230c04..00000000 --- a/runtime/src/precompiles/project_register.rs +++ /dev/null @@ -1,385 +0,0 @@ -use fp_evm::{ - ExitRevert, ExitSucceed, Precompile, PrecompileFailure, PrecompileHandle, PrecompileOutput, - PrecompileResult, -}; -use sp_core::Get; -use sp_runtime::RuntimeDebug; -extern crate alloc; -use crate::precompiles::LOG_TARGET; -use alloc::format; -use core::marker::PhantomData; -use dbc_support::traits::ProjectRegister; -use frame_support::{ensure, pallet_prelude::Weight}; -use num_enum::{IntoPrimitive, TryFromPrimitive}; -use pallet_evm::GasWeightMapping; - -pub struct AIProjectRegister(PhantomData); - -#[evm_macro::generate_function_selector] -#[derive(RuntimeDebug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive)] -#[repr(u32)] -pub enum Selector { - MachineIsRegistered = "machineIsRegistered(string,string)", - AddMachineRegisteredProject = "addMachineRegisteredProject(string,string,string,string,string)", - RemovalMachineRegisteredProject = - "removeMachineRegisteredProject(string,string,string,string,string)", - IsRegisteredMachineOwner = "isRegisteredMachineOwner(string,string,string,string,string)", -} - -impl Precompile for AIProjectRegister -where - T: pallet_evm::Config + pallet_balances::Config + ai_project_register::Config, -{ - fn execute(handle: &mut impl PrecompileHandle) -> PrecompileResult { - let input = handle.input(); - - ensure!( - input.len() >= 4, - PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "invalid input".into(), - } - ); - - let selector = u32::from_be_bytes(input[..4].try_into().expect("checked. qed!")); - let selector: Selector = selector.try_into().map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("invalid selector: {:?}", e).into(), - })?; - - match selector { - Selector::MachineIsRegistered => { - let param = ethabi::decode( - &[ethabi::ParamType::String, ethabi::ParamType::String], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let machine_id_str = - param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - - let machine_id = machine_id_str.as_bytes().to_vec(); - - let project_name_str = - param[1].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[1] failed".into(), - })?; - let project_name = project_name_str.as_bytes().to_vec(); - - let is_registered: bool = - as ProjectRegister>::is_registered( - machine_id.clone(), - project_name.clone(), - ); - - log::debug!( - target: LOG_TARGET, - "machine_id: {:?}, project_name: {:?}, is_registered: {:?}", - machine_id, - project_name, - is_registered - ); - - let weight = Weight::default() - .saturating_add(::DbWeight::get().reads(1)); - - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; - - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Bool(is_registered)]), - }) - }, - - Selector::AddMachineRegisteredProject => { - let param = ethabi::decode( - &[ - ethabi::ParamType::String, - ethabi::ParamType::String, - ethabi::ParamType::String, - ethabi::ParamType::String, - ethabi::ParamType::String, - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let msg = - param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - - let sig_str = - param[1].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[1] failed".into(), - })?; - - let sig = - hex::decode(sig_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode sig failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 64]; - b.copy_from_slice(&sig[..]); - let sig = sp_core::sr25519::Signature(b); - - let public_str = - param[2].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[2] failed".into(), - })?; - - let public = - hex::decode(public_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode pub key failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 32]; - b.copy_from_slice(&public[..]); - let public = sp_core::sr25519::Public(b); - - let machine_id_str = - param[3].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[3] failed".into(), - })?; - - let project_name_str = - param[4].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[4] failed".into(), - })?; - let project_name = project_name_str.as_bytes().to_vec(); - as ProjectRegister>::add_machine_registered_project( - msg.clone().into_bytes(),sig.clone(),public.clone(),machine_id_str.clone().as_bytes().to_vec(),project_name.clone(), - ).map_err(|e|{ - PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: e.into(), - } - })?; - - log::debug!( - target: LOG_TARGET, - ":machine_id: {:?}, project_name: {:?}, registered", - machine_id_str, - project_name, - ); - - let weight = Weight::default() - .saturating_add(::DbWeight::get().writes(1)); - - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; - - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Bool(true)]), - }) - }, - - Selector::RemovalMachineRegisteredProject => { - let param = ethabi::decode( - &[ - ethabi::ParamType::String, - ethabi::ParamType::String, - ethabi::ParamType::String, - ethabi::ParamType::String, - ethabi::ParamType::String, - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let msg = - param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - - let sig_str = - param[1].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[1] failed".into(), - })?; - - let sig = - hex::decode(sig_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode sig failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 64]; - b.copy_from_slice(&sig[..]); - let sig = sp_core::sr25519::Signature(b); - - let public_str = - param[2].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[2] failed".into(), - })?; - - let public = - hex::decode(public_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode pub key failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 32]; - b.copy_from_slice(&public[..]); - let public = sp_core::sr25519::Public(b); - - let machine_id_str = - param[3].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[3] failed".into(), - })?; - - let project_name_str = - param[4].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[4] failed".into(), - })?; - let project_name = project_name_str.as_bytes().to_vec(); - - as ProjectRegister>::remove_machine_registered_project( - msg.clone().into_bytes(),sig.clone(),public.clone(),machine_id_str.clone().as_bytes().to_vec(),project_name.clone(), - ).map_err(|e|{ - PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: e.into(), - } - })?; - - log::debug!( - target: LOG_TARGET, - ":machine_id: {:?}, project_name: {:?}, unregistered", - machine_id_str, - project_name, - ); - - let weight = Weight::default() - .saturating_add(::DbWeight::get().writes(1)); - - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; - - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Bool(true)]), - }) - }, - - Selector::IsRegisteredMachineOwner => { - let param = ethabi::decode( - &[ - ethabi::ParamType::String, - ethabi::ParamType::String, - ethabi::ParamType::String, - ethabi::ParamType::String, - ethabi::ParamType::String, - ], - &input[4..], - ) - .map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode param failed: {:?}", e).into(), - })?; - - let msg = - param[0].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[0] failed".into(), - })?; - - let sig_str = - param[1].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[1] failed".into(), - })?; - - let sig = - hex::decode(sig_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode sig failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 64]; - b.copy_from_slice(&sig[..]); - let sig = sp_core::sr25519::Signature(b); - - let public_str = - param[2].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[2] failed".into(), - })?; - - let public = - hex::decode(public_str.as_bytes()).map_err(|e| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: format!("decode pub key failed: {:?}", e).into(), - })?; - - let mut b = [0u8; 32]; - b.copy_from_slice(&public[..]); - let public = sp_core::sr25519::Public(b); - - let machine_id_str = - param[3].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[3] failed".into(), - })?; - - let project_name_str = - param[4].clone().into_string().ok_or_else(|| PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: "decode param[4] failed".into(), - })?; - let project_name = project_name_str.as_bytes().to_vec(); - let is_owner = as ProjectRegister>::is_registered_machine_owner( - msg.clone().into_bytes(),sig.clone(),public.clone(),machine_id_str.clone().as_bytes().to_vec(),project_name.clone(), - ).map_err(|e|{ - PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: e.into(), - } - })?; - - log::debug!( - target: LOG_TARGET, - "pub_key: {:?}, machine_id: {:?}, project_name: {:?}, is registered owner result :{}", - public_str, - machine_id_str, - project_name, - is_owner, - - ); - - let weight = Weight::default() - .saturating_add(::DbWeight::get().reads(2)); - - handle.record_cost(T::GasWeightMapping::weight_to_gas(weight))?; - - Ok(PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: ethabi::encode(&[ethabi::Token::Bool(true)]), - }) - }, - } - } -}