From 8d02f465b4780ddf5ed15073a53453e503f48f9d Mon Sep 17 00:00:00 2001 From: ytqaljn <2716693942@qq.com> Date: Fri, 5 Jul 2024 11:14:28 +0800 Subject: [PATCH 1/2] fix: fix some territory bug --- pallets/file-bank/src/lib.rs | 16 ++--- pallets/storage-handler/src/benchmarking.rs | 2 +- pallets/storage-handler/src/lib.rs | 73 ++++++++++++++++----- pallets/storage-handler/src/types.rs | 2 +- pallets/storage-handler/src/weights.rs | 6 +- 5 files changed, 67 insertions(+), 32 deletions(-) diff --git a/pallets/file-bank/src/lib.rs b/pallets/file-bank/src/lib.rs index 8c5e6c32..195b6f43 100755 --- a/pallets/file-bank/src/lib.rs +++ b/pallets/file-bank/src/lib.rs @@ -323,18 +323,16 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(now: BlockNumberFor) -> Weight { + fn on_initialize(_now: BlockNumberFor) -> Weight { let days = T::OneDay::get(); let mut weight: Weight = Weight::zero(); // FOR TESTING - if now % days == 0u32.saturated_into() { - let (temp_weight, clear_list) = T::StorageHandle::frozen_task(); - weight = weight.saturating_add(temp_weight); - let temp_acc_list: BoundedVec<(AccountOf, TerrName), ConstU32<2000>> = - clear_list.try_into().unwrap_or_default(); - ClearUserList::::put(temp_acc_list); - weight = weight.saturating_add(T::DbWeight::get().writes(1)); - } + let (temp_weight, clear_list) = T::StorageHandle::frozen_task(); + weight = weight.saturating_add(temp_weight); + let temp_acc_list: BoundedVec<(AccountOf, TerrName), ConstU32<2000>> = + clear_list.try_into().unwrap_or_default(); + ClearUserList::::put(temp_acc_list); + weight = weight.saturating_add(T::DbWeight::get().writes(1)); let mut count: u32 = 0; let clear_list = ClearUserList::::get(); diff --git a/pallets/storage-handler/src/benchmarking.rs b/pallets/storage-handler/src/benchmarking.rs index 6827b5c9..55601b7c 100644 --- a/pallets/storage-handler/src/benchmarking.rs +++ b/pallets/storage-handler/src/benchmarking.rs @@ -54,7 +54,7 @@ benchmarks! { assert_eq!(territory_info.deadline, (40u32 * 14400u32).saturated_into()); } - treeitory_consignment { + territory_consignment { let caller: AccountOf = account("user1", 100, SEED); let terr_name: TerrName = "t1".as_bytes().to_vec().try_into().map_err(|_| "boundedvec error")?; let free: BalanceOf = 365_000_000_000_000_000_000_000u128.try_into().map_err(|_| "tryinto error!").expect("tryinto error!"); diff --git a/pallets/storage-handler/src/lib.rs b/pallets/storage-handler/src/lib.rs index f366233e..a25da181 100644 --- a/pallets/storage-handler/src/lib.rs +++ b/pallets/storage-handler/src/lib.rs @@ -51,6 +51,7 @@ pub const SPACE_DEAD: &str = "dead"; type AccountOf = ::AccountId; type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +type TokenId = H256; const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); @@ -134,7 +135,7 @@ pub mod pallet { PaidOrder { order_hash: BoundedVec> }, MintTerritory { - token: H256, + token: TokenId, name: TerrName, storage_capacity: u128, spend: BalanceOf, @@ -160,28 +161,28 @@ pub mod pallet { Consignment { name: TerrName, - token: H256, + token: TokenId, price: BalanceOf, }, BuyConsignment { name: TerrName, - token: H256, + token: TokenId, price: BalanceOf, }, CancleConsignment { - token: H256, + token: TokenId, }, CancelPurchaseAction { - token: H256, + token: TokenId, }, ExecConsignment { buyer: AccountOf, seller: AccountOf, - token: H256, + token: TokenId, }, } @@ -249,12 +250,14 @@ pub mod pallet { NotBuyer, /// This is an invalid order, Because the price can't match InvalidOrder, + /// Unable to purchase own consignment + OwnConsignment, } #[pallet::storage] #[pallet::getter(fn territory_key)] pub(super) type TerritoryKey = - StorageMap<_, Blake2_128Concat, H256, (AccountOf, TerrName)>; + StorageMap<_, Blake2_128Concat, TokenId, (AccountOf, TerrName)>; #[pallet::storage] #[pallet::getter(fn territory)] @@ -271,7 +274,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn consignment)] pub(super) type Consignment = - StorageMap<_, Blake2_128Concat, H256, ConsignmentInfo>; + StorageMap<_, Blake2_128Concat, TokenId, ConsignmentInfo>; #[pallet::storage] #[pallet::getter(fn territory_frozen)] @@ -281,7 +284,7 @@ pub mod pallet { Blake2_128Concat, BlockNumberFor, Blake2_128Concat, - H256, + TokenId, bool, >; @@ -298,7 +301,7 @@ pub mod pallet { Blake2_128Concat, BlockNumberFor, Blake2_128Concat, - H256, + TokenId, bool, >; @@ -556,15 +559,15 @@ pub mod pallet { #[pallet::call_index(102)] #[transactional] - #[pallet::weight(::WeightInfo::treeitory_consignment())] - pub fn treeitory_consignment( + #[pallet::weight(::WeightInfo::territory_consignment())] + pub fn territory_consignment( origin: OriginFor, territory_name: TerrName, price: BalanceOf ) -> DispatchResult { let sender = ensure_signed(origin)?; - let token = >::try_mutate(&sender, &territory_name, |t_opt| -> Result { + let token = >::try_mutate(&sender, &territory_name, |t_opt| -> Result { let t = t_opt.as_mut().ok_or(Error::::NotHaveTerritory)?; ensure!(t.state == TerritoryState::Active, Error::::NotActive); @@ -604,13 +607,14 @@ pub mod pallet { #[pallet::weight(::WeightInfo::buy_consignment())] pub fn buy_consignment( origin: OriginFor, - token: H256, + token: TokenId, rename: TerrName, ) -> DispatchResult { let sender = ensure_signed(origin)?; let consignment = >::try_get(&token).map_err(|_| Error::::NonExistentConsignment)?; ensure!(!consignment.locked, Error::::ConsignmentLocked); + ensure!(consignment.user != sender, Error::::OwnConsignment); >::try_mutate(&token, |c_opt| -> DispatchResult { let c = c_opt.as_mut().ok_or(Error::::NonExistentConsignment)?; @@ -647,7 +651,7 @@ pub mod pallet { #[pallet::call_index(104)] #[transactional] #[pallet::weight(::WeightInfo::exec_consignment())] - pub fn exec_consignment(origin: OriginFor, token: H256, territory_name: TerrName) -> DispatchResult { + pub fn exec_consignment(origin: OriginFor, token: TokenId, territory_name: TerrName) -> DispatchResult { ensure_root(origin)?; let consignment = >::try_get(&token).map_err(|_| Error::::NonExistentConsignment)?; @@ -703,7 +707,7 @@ pub mod pallet { #[pallet::call_index(106)] #[transactional] #[pallet::weight(::WeightInfo::cancel_purchase_action())] - pub fn cancel_purchase_action(origin: OriginFor, token: H256) -> DispatchResult { + pub fn cancel_purchase_action(origin: OriginFor, token: TokenId) -> DispatchResult { let sender = ensure_signed(origin)?; >::try_mutate(&token, |c_opt| -> DispatchResult { @@ -797,18 +801,51 @@ pub mod pallet { #[pallet::call_index(5)] #[transactional] #[pallet::weight(Weight::zero())] - pub fn update_user_territory_life(origin: OriginFor, user: AccountOf, terr_name: TerrName, deadline: BlockNumberFor) -> DispatchResult { + pub fn update_user_territory_life( + origin: OriginFor, + user: AccountOf, + terr_name: TerrName, + deadline: BlockNumberFor + ) -> DispatchResult { let _ = ensure_root(origin)?; >::try_mutate(&user, &terr_name, |space_opt| -> DispatchResult { let space_info = space_opt.as_mut().ok_or(Error::::NotPurchasedSpace)?; + // TerritoryFrozenCounter::::mutate(&space_info.deadline, |counter| -> DispatchResult { + // *counter = counter.checked_sub(1).ok_or(Error::::Overflow)?; + // Ok(()) + // })?; + + TerritoryFrozen::::remove(&space_info.deadline, &space_info.token); + space_info.deadline = deadline; + TerritoryFrozen::::insert(&space_info.deadline, &space_info.token, true); + Ok(()) }) } + #[pallet::call_index(201)] + #[transactional] + #[pallet::weight(Weight::zero())] + pub fn update_expired_exec( + origin: OriginFor, + old_block: BlockNumberFor, + new_block: BlockNumberFor, + token: TokenId + ) -> DispatchResult { + let _ = ensure_root(origin)?; + + TerritoryExpired::::remove(&old_block, &token); + + TerritoryExpired::::insert(&new_block, &token, true); + + Ok(()) + } + + #[pallet::call_index(6)] #[transactional] #[pallet::weight(::WeightInfo::create_order())] @@ -978,7 +1015,7 @@ impl Pallet { } fn storage_territory( - token: H256, + token: TokenId, user: AccountOf, space: u128, days: u32, diff --git a/pallets/storage-handler/src/types.rs b/pallets/storage-handler/src/types.rs index 3836b092..6c7afd16 100644 --- a/pallets/storage-handler/src/types.rs +++ b/pallets/storage-handler/src/types.rs @@ -24,7 +24,7 @@ pub enum OrderType { #[scale_info(skip_type_params(T))] #[codec(mel_bound())] pub struct TerritoryInfo { - pub(super) token: H256, + pub(super) token: TokenId, pub(super) total_space: u128, pub(super) used_space: u128, pub(super) locked_space: u128, diff --git a/pallets/storage-handler/src/weights.rs b/pallets/storage-handler/src/weights.rs index 4e8837c9..3aadc452 100644 --- a/pallets/storage-handler/src/weights.rs +++ b/pallets/storage-handler/src/weights.rs @@ -39,7 +39,7 @@ pub trait WeightInfo { fn mint_territory() -> Weight; fn expanding_territory() -> Weight; fn renewal_territory() -> Weight; - fn treeitory_consignment() -> Weight; + fn territory_consignment() -> Weight; fn buy_consignment() -> Weight; fn exec_consignment() -> Weight; fn cancel_consignment() -> Weight; @@ -129,7 +129,7 @@ impl WeightInfo for SubstrateWeight { /// Proof: `StorageHandler::Territory` (`max_values`: None, `max_size`: Some(233), added: 2708, mode: `MaxEncodedLen`) /// Storage: `StorageHandler::Consignment` (r:1 w:1) /// Proof: `StorageHandler::Consignment` (`max_values`: None, `max_size`: Some(135), added: 2610, mode: `MaxEncodedLen`) - fn treeitory_consignment() -> Weight { + fn territory_consignment() -> Weight { // Proof Size summary in bytes: // Measured: `590` // Estimated: `3698` @@ -374,7 +374,7 @@ impl WeightInfo for () { /// Proof: `StorageHandler::Territory` (`max_values`: None, `max_size`: Some(233), added: 2708, mode: `MaxEncodedLen`) /// Storage: `StorageHandler::Consignment` (r:1 w:1) /// Proof: `StorageHandler::Consignment` (`max_values`: None, `max_size`: Some(135), added: 2610, mode: `MaxEncodedLen`) - fn treeitory_consignment() -> Weight { + fn territory_consignment() -> Weight { // Proof Size summary in bytes: // Measured: `590` // Estimated: `3698` From d55e1ad6370b2e5b222d16c7c12b20f565ee4c5c Mon Sep 17 00:00:00 2001 From: ytqaljn <2716693942@qq.com> Date: Fri, 5 Jul 2024 17:18:20 +0800 Subject: [PATCH 2/2] style: update readme --- pallets/storage-handler/README.md | 87 ++++++++++++++++++++++-------- pallets/storage-handler/src/lib.rs | 8 ++- 2 files changed, 71 insertions(+), 24 deletions(-) diff --git a/pallets/storage-handler/README.md b/pallets/storage-handler/README.md index 46053520..97e50a23 100644 --- a/pallets/storage-handler/README.md +++ b/pallets/storage-handler/README.md @@ -8,13 +8,24 @@ This module records the usage of each space in the CESS network, such as the sto ## Terminology +* **Territory:** Users can mint an unlimited number of territories, and each territory will be bound to a unique token. Territories can be used for trading, transfer, or file storage. Users can also customize the names of their territories, but they cannot be repeated. * **PayOrder:** Users can purchase storage space for others. In the process, a payment order will be created waiting for payment. * **IdleSpace:** The idle space provided by the storage user is filled with generated random data, waiting for the data uploaded by the storage user. * **ServiceSpace:** The space used for data uploaded by users is called service space. ## Storage -* `UserOwnedSpace` - Used to store the details of users after purchasing space, recording expiration time, used space, total space and other related data. +* `Territory` - It is used to store detailed information about the territories owned by the user, and to specify the query territory through the user address and the user-defined territory name. + +* `TerritoryKey` - Ensure unique record of territory token. + +* `Consignment` - Stores the details of the current consignment order, using the territory token as the primary key. + +* `TerritoryFrozen` - It is used to store some data related to executing territory freezing. The primary key block height represents the block height of the execution task, and the stored territory id represents the territory that needs to be frozen. + +* `TerritoryFrozenCounter` - This storage is a counter set up to prevent too many freezing tasks from being executed within a block height. + +* `TerritoryExpired` - This storage is similar to `TerritoryFrozen` and is used to store records related to executing territory expiration tasks. * `UnitPrice` - Current unit price of storage space (Gib/days). @@ -28,17 +39,49 @@ This module records the usage of each space in the CESS network, such as the sto ## Extrinsic -**buy_space(origin: OriginFor, gib_count: u32):** +**mint_territory(origin: OriginFor, gib_count: u32, territory_name: TerrName):** + +Used for transactions where users mint territories. `gib_count` indicates the size of the territory the user wants to mint, in gib. The default expiration time for a territory is 30 days. Through the `territory_name` field, users can customize the name of the territory they mint, but the name of a territory owned by a user cannot be repeated. + +**expanding_territory(origin: OriginFor, territory_name: TerrName, gib_count: u32):** + +Transactions for expanding the user's territory can be called when the user expands the territory. The payment amount is determined by the remaining expiration time and the size of the territory the user needs to expand. Use the territory name to specify which territory you want to expand. (Less than one day will be counted as one day) + +**renewal_territory(origin: OriginFor, days: u32, territory_name: TerrName):** + +Used for user renewal of territory transactions. After the user has minted a territory, this transaction can be called to extend the expiration date of a certain territory. `days` indicates the number of days for renewal. The fee paid depends on the renewal time and the space size of the current territory. Use the territory name to specify which territory. + +**reactivate_territory(origin: OriginFor, territory_name: TerrName, days: u32)** + +When a user's territory expires, this transaction can be called to reactivate the territory. The territory status must be Expired to be reactivated. If it is in Frozen status, the territory renewal transaction should be called. + +**territory_consignment(origin: OriginFor, territory_name: TerrName, price: BalanceOf)** -Used for users to purchase space transactions, `gib_count` represents the size of the space the user wants to purchase, in gib. Users who have purchased space and the space has not expired cannot invoke this transaction. The default expiration time of space is 30 days. +Through this transaction, users can consign their own territories, customize the price and then display it to other users. The consigned territory needs to be empty, and the status of the territory needs to be Active, and the remaining expiration time is greater than one day. -**expansion_space(origin: OriginFor, gib_count: u32):** +**buy_consignment(origin: OriginFor, token: TokenId, rename: TerrName)** -Transactions used to expand space for users can be called when the user has purchased space, and the amount paid is determined by the remaining expiration time and the amount of space the user needs to expand.(Any less than one day will be counted as one day.) +Users can purchase the territories on consignment through transactions. After calling this transaction, the corresponding consignment order will be locked. During the lock-in period, users can cancel the purchase. When the lock-in period ends, the subsequent transaction content will be automatically executed. -**renewal_space(origin: OriginFor, days: u32):** +**exec_consignment(origin: OriginFor, token: TokenId, territory_name: TerrName)** -Used for user renewal space transactions. After the user purchases space, this transaction can be called to extend the expiration time of the space. `days` represents the number of days to extend. The fee paid is based on the lease renewal time and the space currently held. +The method for executing a consignment transaction. This transaction cannot be actively called by the user. It is a transaction automatically called by the system after the consignment transaction lock-up period ends. + +**cancel_consignment(origin: OriginFor, territory_name: TerrName)** + +This transaction is used to remove the consignments that the current user is currently consigning, but the consignment needs to be unlocked. + +**cancel_purchase_action(origin: OriginFor, token: TokenId)** + +After a buyer locks a commission, if he wants to cancel the purchase during the lock-in period, he can call this transaction. The locked cess will then be returned to the buyer's wallet free balance. + +**territory_grants(origin: OriginFor, territory_name: TerrName, receiver: AccountOf)** + +The purpose of this transaction is that a user can transfer his territory to another user, but the premise is that there are no files stored in this territory and the status is Active. + +**territory_rename(origin: OriginFor, old_name: TerrName, new_name: TerrName)** + +It is used by users to rename a piece of their territory, and it is required that no files are stored in the territory. **update_price(origin: OriginFor):** @@ -48,9 +91,9 @@ The interface during testing can only be called by the root user. Used to change The interface during testing can only be called by the root user. Used to change the expiration time of the space purchased by the user. -**create_order(origin: OriginFor,target_acc: AccountOf,order_type: OrderType,gib_count: u32, days: u32):** +**create_order(origin: OriginFor, target_acc: AccountOf, territory_name: TerrName, order_type: OrderType, gib_count: u32, days: u32):** -Transaction that creates a payment order. Create a payment order to purchase space for `target_acc`. Specify the size and time of the payment space through `gib_count` and `days`. `order_type` specifies whether the order type is purchase, expansion, or lease renewal. +Create a transaction for a payment order. Create a payment order to purchase territory for `target_acc`. Specify the space size and time of the territory to be paid for by `gib_count` and `days`. `order_type` specifies whether the order type is purchase, expansion or renewal. **exec_order(origin: OriginFor, order_id: BoundedVec>):** @@ -64,7 +107,11 @@ Provide methods for updating the status of various types of spaces for other pal #### Function -* `update_user_space` - Update the space used by the user. +* `check_territry_owner` - Check if the user is the owner of the corresponding territory. + +* `add_territory_used_space` - Increase the use of territory. + +* `sub_territory_used_space` - Reduce the use of territory. * `add_total_idle_space` - Increase total idle space. @@ -74,22 +121,18 @@ Provide methods for updating the status of various types of spaces for other pal * `sub_total_service_space` - Reduce total service space. -* `get_total_idle_space` - Get total idle space. - -* `get_total_service_space` - Get total service space. - -* `add_purchased_space` - Increase purchased space. +* `get_total_idle_space` - Get the current total idle space. -* `sub_purchased_space` - Reduce purchased space. +* `get_total_service_space` - Get the current total service space. -* `get_total_space` - Get the total space on the current chain, that is, idle space + service space. +* `get_avail_space` - Get the space that can be purchased on the current chain. -* `lock_user_space` - Lock user space. +* `lock_user_space` - Locking a user's space in a certain territory. -* `unlock_and_used_user_space` - Update the user's locked space to used space. +* `unlock_user_space` - Unlock space for a certain territory for users. -* `get_user_avail_space` - Get the user's available space. +* `unlock_and_used_user_space` - Unlock space in a territory for the user and then increase the used space. -* `frozen_task` - Perform freeze detection and freeze the user's expired space. +* `get_user_avail_space` - Get the available space of a user's territory. -* `delete_user_space_storage` - Clear space held by user. \ No newline at end of file +* `frozen_task` - Method used to perform the task of polling for territory expiration. \ No newline at end of file diff --git a/pallets/storage-handler/src/lib.rs b/pallets/storage-handler/src/lib.rs index a25da181..714171f1 100644 --- a/pallets/storage-handler/src/lib.rs +++ b/pallets/storage-handler/src/lib.rs @@ -623,9 +623,12 @@ pub mod pallet { let lock_block = T::LockingBlock::get(); let exec_block = now.checked_add(&lock_block).ok_or(Error::::Overflow)?; - c.buyers = Some(sender); + c.buyers = Some(sender.clone()); c.exec = Some(exec_block); c.locked = true; + + ::Currency::reserve(&sender, c.price); + let call: ::SProposal = Call::exec_consignment{token: token.clone(), territory_name: rename.clone()}.into(); T::FScheduler::schedule_named( *(token.as_fixed_bytes()), @@ -672,7 +675,7 @@ pub mod pallet { >::insert(&token, (buyer.clone(), territory_name)); >::remove(&token); - + ::Currency::unreserve(&buyer, consignment.price); ::Currency::transfer(&buyer, &holder, consignment.price, KeepAlive)?; Self::deposit_event(Event::::ExecConsignment { @@ -715,6 +718,7 @@ pub mod pallet { let buyer = c.buyers.as_ref().ok_or(Error::::NotBuyer)?; ensure!(&sender == buyer, Error::::NotBuyer); + ::Currency::unreserve(&buyer, c.price); c.buyers = None; c.exec = None; c.locked = false;