Skip to content

Commit

Permalink
Merge branch 'main' into forward
Browse files Browse the repository at this point in the history
  • Loading branch information
0xbillw committed Nov 30, 2023
2 parents 0794d83 + 3db93d7 commit 902d020
Show file tree
Hide file tree
Showing 17 changed files with 144 additions and 42 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

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

10 changes: 9 additions & 1 deletion pallets/audit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ pub mod pallet {
pub(super) type VerifyReassignCount<T: Config> = StorageValue<_, u8, ValueQuery>;

#[pallet::storage]
#[pallet::getter(fn chllenge_snap_shot)]
#[pallet::getter(fn challenge_snap_shot)]
pub(super) type ChallengeSnapShot<T: Config> =
StorageMap<_, Blake2_128Concat, AccountOf<T>, ChallengeInfo<T>>;

Expand Down Expand Up @@ -932,6 +932,11 @@ pub mod pallet {
fn generate_challenge(now: BlockNumberFor<T>) -> Weight {
let mut weight: Weight = Weight::zero();

let one_day = T::OneDay::get();
if now < one_day.saturating_mul(3u32.saturated_into()) {
return weight;
}

weight = weight.saturating_add(T::DbWeight::get().reads(1));
let miner_list = match T::MinerControl::get_all_miner() {
Ok(miner_list) => miner_list,
Expand Down Expand Up @@ -1001,6 +1006,9 @@ pub mod pallet {
let one_hour = T::OneHours::get();
weight = weight.saturating_add(T::DbWeight::get().reads(1));
let tee_length = T::TeeWorkerHandler::get_controller_list().len();
if tee_length == 0 {
return weight;
}
let verify_life: u32 = (idle_space
.saturating_add(service_space)
.saturating_div(IDLE_VERIFY_RATE)
Expand Down
20 changes: 20 additions & 0 deletions pallets/cess-treasury/src/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Cess Treasury Module

Manage meta information of cess-treasury.

## Terminology

## Extrinsic


## Interface

### TeeWorkerHandler


#### Usage


## Implementation Details

###
2 changes: 1 addition & 1 deletion pallets/file-bank/src/constants.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// The average number of bytes that a storage node can transmit within each block
pub(super) const TRANSFER_RATE: u128 = 2_089_446;

pub(super) const CALCULATE_RATE: u128 = 651_088;
pub(super) const CALCULATE_RATE: u128 = 838_860;
7 changes: 5 additions & 2 deletions pallets/file-bank/src/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ impl<T: Config> Pallet<T> {
) -> DispatchResult {
let mut segment_info_list: BoundedVec<SegmentInfo<T>, T::SegmentCount> = Default::default();
ensure!(complete_list.len() == FRAGMENT_COUNT as usize, Error::<T>::Unexpected);
let mut complete_list = complete_list;
complete_list.sort_by_key(|info| info.index);
for segment in deal_info.iter() {
let mut segment_info = SegmentInfo::<T> {
hash: segment.hash,
Expand Down Expand Up @@ -164,11 +166,12 @@ impl<T: Config> Pallet<T> {

pub(super) fn remove_deal(deal_hash: &Hash) -> DispatchResult {
let deal_info = <DealMap<T>>::try_get(deal_hash).map_err(|_| Error::<T>::NonExistent)?;
let needed_space = Self::cal_file_size(deal_info.segment_list.len() as u128);
let segment_len = deal_info.segment_list.len() as u128;
let needed_space = Self::cal_file_size(segment_len);
T::StorageHandle::unlock_user_space(&deal_info.user.user, needed_space)?;
// unlock mienr space
for complete_info in deal_info.complete_list {
T::MinerControl::unlock_space(&complete_info.miner, FRAGMENT_SIZE * FRAGMENT_COUNT as u128)?;
T::MinerControl::unlock_space(&complete_info.miner, FRAGMENT_SIZE * segment_len)?;
}

<DealMap<T>>::remove(deal_hash);
Expand Down
2 changes: 2 additions & 0 deletions pallets/file-bank/src/impls/dealimpl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ impl<T: Config> DealInfo<T> {
ensure!(index != complete_info.index, Error::<T>::Existed);
ensure!(miner != complete_info.miner, Error::<T>::Existed);
}

T::MinerControl::lock_space(&miner, FRAGMENT_SIZE * self.segment_list.len() as u128)?;

let complete_info = CompleteInfo::<T> {
index,
Expand Down
2 changes: 1 addition & 1 deletion pallets/file-bank/src/impls/receptionist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ impl<T: Config> Receptionist<T> {
let max_needed_cal_space = (segment_count as u32).checked_mul(FRAGMENT_SIZE as u32).ok_or(Error::<T>::Overflow)?;
let mut life: u32 = (max_needed_cal_space / TRANSFER_RATE as u32).checked_add(11).ok_or(Error::<T>::Overflow)?;
life = (max_needed_cal_space / CALCULATE_RATE as u32)
.checked_add(30).ok_or(Error::<T>::Overflow)?
.checked_add(100).ok_or(Error::<T>::Overflow)?
.checked_add(life).ok_or(Error::<T>::Overflow)?;
Pallet::<T>::start_second_task(deal_hash.0.to_vec(), deal_hash, life)?;
if <Bucket<T>>::contains_key(&deal_info.user.user, &deal_info.user.bucket_name) {
Expand Down
9 changes: 5 additions & 4 deletions pallets/file-bank/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,6 @@ pub mod pallet {
InsufficientReplaceable,
}


#[pallet::storage]
#[pallet::getter(fn deal_map)]
pub(super) type DealMap<T: Config> = StorageMap<_, Blake2_128Concat, Hash, DealInfo<T>>;
Expand Down Expand Up @@ -585,6 +584,8 @@ pub mod pallet {
ensure!(<DealMap<T>>::contains_key(&deal_hash), Error::<T>::NonExistent);
ensure!(index as u32 <= FRAGMENT_COUNT, Error::<T>::SpecError);
ensure!(index > 0, Error::<T>::SpecError);
let is_positive = T::MinerControl::is_positive(&sender)?;
ensure!(is_positive, Error::<T>::MinerStateError);
<DealMap<T>>::try_mutate(&deal_hash, |deal_info_opt| -> DispatchResult {
// can use unwrap because there was a judgment above
let deal_info = deal_info_opt.as_mut().unwrap();
Expand Down Expand Up @@ -614,11 +615,11 @@ pub mod pallet {
let _ = ensure_root(origin)?;

let deal_info = <DealMap<T>>::try_get(&deal_hash).map_err(|_| Error::<T>::NonExistent)?;
for (index, complete_info) in deal_info.complete_list.iter().enumerate() {
let count = FRAGMENT_COUNT;
let count = deal_info.segment_list.len() as u128;
for complete_info in deal_info.complete_list.iter() {
let mut hash_list: Vec<Box<[u8; 256]>> = Default::default();
for segment in &deal_info.segment_list {
let fragment_hash = segment.fragment_list[index as usize];
let fragment_hash = segment.fragment_list[(complete_info.index - 1) as usize];
let hash_temp = fragment_hash.binary().map_err(|_| Error::<T>::BugInvalid)?;
hash_list.push(hash_temp);
}
Expand Down
2 changes: 1 addition & 1 deletion pallets/sminer/src/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ impl<T: Config> Pallet<T> {

<MinerItems<T>>::try_mutate(acc, |miner_opt| -> DispatchResult {
let miner = miner_opt.as_mut().ok_or(Error::<T>::Unexpected)?;
T::StorageHandle::sub_total_idle_space(miner.idle_space)?;
T::StorageHandle::sub_total_idle_space(miner.idle_space + miner.lock_space)?;
Self::create_restoral_target(acc, miner.service_space)?;
miner.state = Self::str_to_bound(STATE_OFFLINE)?;
let space_proof_info = miner.space_proof_info.clone().ok_or(Error::<T>::NotpositiveState)?;
Expand Down
10 changes: 9 additions & 1 deletion pallets/sminer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,9 @@ pub mod pallet {
acc: AccountOf<T>,
staking_val: BalanceOf<T>,
},
RegisterPoisKey {
miner: AccountOf<T>,
},
/// Users to withdraw faucet money
DrawFaucetMoney(),
/// User recharges faucet
Expand Down Expand Up @@ -400,6 +403,10 @@ pub mod pallet {
Ok(())
})?;

Self::deposit_event(Event::<T>::RegisterPoisKey {
miner: sender,
});

Ok(())
}

Expand Down Expand Up @@ -587,6 +594,7 @@ pub mod pallet {
<MinerItems<T>>::try_mutate(&sender, |miner_opt| -> DispatchResult {
let miner = miner_opt.as_mut().ok_or(Error::<T>::NotExisted)?;
ensure!(miner.state == STATE_POSITIVE.as_bytes().to_vec(), Error::<T>::StateError);
ensure!(miner.lock_space == 0, Error::<T>::StateError);
if miner.lock_space != 0 {
Err(Error::<T>::StateError)?;
}
Expand Down Expand Up @@ -640,7 +648,7 @@ pub mod pallet {
ensure!(miner_info.state.to_vec() == STATE_LOCK.as_bytes().to_vec(), Error::<T>::StateError);
// sub network total idle space.

T::StorageHandle::sub_total_idle_space(miner_info.idle_space)?;
T::StorageHandle::sub_total_idle_space(miner_info.idle_space + miner_info.lock_space)?;

Self::execute_exit(&miner)?;

Expand Down
36 changes: 29 additions & 7 deletions pallets/storage-handler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,11 @@ pub mod pallet {

#[pallet::constant]
type OneDay: Get<BlockNumberFor<Self>>;
/// pallet address.

#[pallet::constant]
type OneHours: Get<BlockNumberFor<Self>>;

/// pallet address.
#[pallet::constant]
type RewardPalletId: Get<PalletId>;

Expand Down Expand Up @@ -122,9 +126,13 @@ pub mod pallet {

LeaseExpired,

OrderExpired,

RandomErr,

NoOrder,

ParamError,
}

#[pallet::storage]
Expand Down Expand Up @@ -341,7 +349,7 @@ pub mod pallet {
#[pallet::weight(Weight::zero())]
pub fn update_price(origin: OriginFor<T>) -> DispatchResult {
let _ = ensure_root(origin)?;
let default_price: BalanceOf<T> = 30u32.saturated_into();
let default_price: BalanceOf<T> = 30_000_000_000_000u128.try_into().map_err(|_| Error::<T>::Overflow)?;
UnitPrice::<T>::put(default_price);

Ok(())
Expand All @@ -365,8 +373,20 @@ pub mod pallet {
#[pallet::call_index(6)]
#[transactional]
#[pallet::weight(Weight::zero())]
pub fn create_order(origin: OriginFor<T>, target_acc: AccountOf<T>, order_type: OrderType, gib_count: u32, days: u32) -> DispatchResult {
let sender = ensure_signed(origin)?;
pub fn create_order(
origin: OriginFor<T>,
target_acc: AccountOf<T>,
order_type: OrderType,
gib_count: u32,
days: u32,
// minute
expired: u32,
) -> DispatchResult {
let _ = ensure_signed(origin)?;

let expired: BlockNumberFor<T> = (expired
.checked_mul(6).ok_or(Error::<T>::Overflow)?).saturated_into();
ensure!(expired < T::OneHours::get(), Error::<T>::ParamError);

let price = match order_type {
OrderType::Buy => {
Expand All @@ -388,17 +408,17 @@ pub mod pallet {
},
};

let now = <frame_system::Pallet<T>>::block_number();
let expired = now.checked_add(&expired.saturated_into()).ok_or(Error::<T>::Overflow)?;
let pay_order = OrderInfo::<T> {
pay: price,
gib_count: gib_count,
days,
expired: 10u32.saturated_into(),
pay_acc: sender,
expired,
target_acc: target_acc,
order_type,
};

let now = <frame_system::Pallet<T>>::block_number();
let (seed, _) =
T::MyRandomness::random(&(T::RewardPalletId::get(), now).encode());
let seed = match seed {
Expand All @@ -422,6 +442,8 @@ pub mod pallet {
let sender = ensure_signed(origin)?;

let order = <PayOrder<T>>::try_get(&order_id).map_err(|_| Error::<T>::NoOrder)?;
let now = <frame_system::Pallet<T>>::block_number();
ensure!(order.expired > now, Error::<T>::OrderExpired);
match order.order_type {
OrderType::Buy => {
ensure!(!<UserOwnedSpace<T>>::contains_key(&order.target_acc), Error::<T>::PurchasedSpace);
Expand Down
3 changes: 1 addition & 2 deletions pallets/storage-handler/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ pub struct OrderInfo<T: Config> {
pub(super) pay: BalanceOf<T>,
pub(super) gib_count: u32,
pub(super) days: u32,
pub(super) expired: BlockNumberFor<T>,
pub(super) pay_acc: AccountOf<T>,
pub(super) expired: BlockNumberFor<T>,
pub(super) target_acc: AccountOf<T>,
pub(super) order_type: OrderType,
}
Expand Down
61 changes: 50 additions & 11 deletions pallets/tee-worker/README.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,61 @@
# File Map Module
# Tee Worker Module

Store scheduling related information
Manage meta information of tee-worker.

### Terminology
## Terminology

* **Ip:** Scheduled IP address.
* **EndPoint:** The ip+port of tee-worker, or the domain name of tee-worker. Selected independently by tee-workers.
* **StashAccount:** Staking account when bond a consensus node.
* **ControllerAccount:** The control account bound when registering the consensus node, used for work transaction signatures.
* **Podr2Pbk:** The only public key shared between tee-workers in the entire network.
* **SgxAttestationReport:** The SGX report certificate applied for tee-worker certification is provided by Inter.

## Extrinsic
* `register()` - The extrinsic used for tee-worker registration requires bond to become a consensus before registration. The report will be verified in Extrinsic to confirm that the registrant is a legitimate sgx.
* `update_whitelist()` - Used to support iterative updates of sgx. When the internal code of sgx is updated, the new identification code needs to be added to the whitelist.
* `exit()` - Tee worker exit function, when the last tee worker exits, the only public key in the entire network will be cleared. However, this function will not affect the unbundling of consensus stashes.
* `update_podr2_pk()` - Method to update root permissions of the only public key in the entire network.
* `force_register()` - Forced registration of tee workers through root privileges will ignore a series of qualification certifications such as verification reports. After mainnet login, this method will be removed

## Interface
### Trait
#### TeeWorkerHandler

### TeeWorkerHandler

A series of methods for finding consensus scheduling.
* `contains_scheduler` - Judge whether the controller account exists.
* `get_controller_acc` - Obtain controller account through stash account.
* `get_controller_list` - Get the list of controller accounts of currently registered tee workers.
* `get_first_controller` - Get the first consensus in the list.
### Dispatchable Functions
* `get_tee_publickey` - Get the network-wide unique public key of the tee worker to verify the signature of sgx.
* `punish_scheduler` - Punish tee workers and deduct credibility points.

#### Usage
in pallet::Config
```rust
pub trait Config:
frame_system::Config + sp_std::fmt::Debug
{
//...
type TeeWorkerHandler: TeeWorkerHandler<Self::AccountId>;
//...
}
```
in runtime.rs
```rust
impl pallet_audit::Config for Runtime {
//...
type TeeWorkerHandler = TeeWorker;
//...
}
```

## Implementation Details

### Verify SGX report
Use the `verify_miner_cert` method to verify sgx reports. The method uses the third-party library webpki internally to verify the sgx report. At the same time, it will also check whether the custom information of tee worker in the report is legal.

Custom information includes the following:
* `sign` - the certificate signature.
* `cert_der` - certificate.
* `report_json_raw` - the json format string of the report.
* `identity_hash` - some basic registration information of tee worker, which is composed of peer_id, podr2_pbk, end_point, and finally the hash value calculated by sha2_256 algorithm.

* `registration_scheduler` - The interface for scheduling registration has no special restrictions at present.
* `update_scheduler` - Consensus Method for Updating IP Endpoints.
* `init_public_key` - Initialize the public key related to the certificate.
2 changes: 1 addition & 1 deletion standalone/chain/node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ edition = '2021'
license = 'Unlicense'
name = 'cess-node'
repository = 'https://github.com/CESSProject/cess'
version = '0.7.4'
version = '0.7.5'

[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
Expand Down
Loading

0 comments on commit 902d020

Please sign in to comment.