From edec5916d04e794252fe3c1f0d2f81341b741f83 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 7 Aug 2024 14:12:04 +0000 Subject: [PATCH 01/61] refactoring score-staking event, adding new event --- pallets/score-staking/src/lib.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/pallets/score-staking/src/lib.rs b/pallets/score-staking/src/lib.rs index 24d9238cc1..b681bfa3e3 100644 --- a/pallets/score-staking/src/lib.rs +++ b/pallets/score-staking/src/lib.rs @@ -150,7 +150,8 @@ pub mod pallet { ScoreUpdated { who: Identity, new_score: Score }, ScoreRemoved { who: Identity }, ScoreCleared {}, - RewardCalculated { total: BalanceOf, distributed: BalanceOf }, + RewardDistributionStarted {}, + RewardDistributionCompleted { total: BalanceOf, distributed: BalanceOf }, RewardClaimed { who: T::AccountId, amount: BalanceOf }, } @@ -268,10 +269,7 @@ pub mod pallet { weight = weight.saturating_add(T::DbWeight::get().reads_writes(2, 1)); } - Self::deposit_event(Event::::RewardCalculated { - total: round_reward, - distributed: all_user_reward, - }); + Self::deposit_event(Event::::RewardDistributionStarted {}); weight } From addc61f6c662dcbaf0c8c1431639e05f6f6293e8 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 7 Aug 2024 14:18:57 +0000 Subject: [PATCH 02/61] exporting primitives types --- tee-worker/core-primitives/types/src/lib.rs | 4 ++-- tee-worker/litentry/primitives/Cargo.toml | 2 ++ tee-worker/litentry/primitives/src/lib.rs | 2 ++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/tee-worker/core-primitives/types/src/lib.rs b/tee-worker/core-primitives/types/src/lib.rs index a4d58a2969..2179588cf3 100644 --- a/tee-worker/core-primitives/types/src/lib.rs +++ b/tee-worker/core-primitives/types/src/lib.rs @@ -29,8 +29,8 @@ pub mod storage; pub use itp_sgx_runtime_primitives::types::*; pub use litentry_primitives::{ - Assertion, AttestationType, DcapProvider, DecryptableRequest, Enclave, EnclaveFingerprint, - MrEnclave, SidechainBlockNumber, WorkerType, + Assertion, AttestationType, DcapProvider, DecryptableRequest, Delegator, Enclave, + EnclaveFingerprint, MrEnclave, ScorePayment, SidechainBlockNumber, WorkerType, }; pub use sp_core::{crypto::AccountId32 as AccountId, H256}; diff --git a/tee-worker/litentry/primitives/Cargo.toml b/tee-worker/litentry/primitives/Cargo.toml index 855048f9bf..402ff41a28 100644 --- a/tee-worker/litentry/primitives/Cargo.toml +++ b/tee-worker/litentry/primitives/Cargo.toml @@ -30,6 +30,8 @@ sgx_tstd = { git = "https://github.com/apache/teaclave-sgx-sdk.git", branch = "m # internal dependencies itp-sgx-crypto = { path = "../../core-primitives/sgx/crypto", default-features = false } itp-utils = { path = "../../core-primitives/utils", default-features = false } +pallet-parachain-staking = { path = "../../../pallets/parachain-staking", default-features = false } +pallet-score-staking = { path = "../../../pallets/score-staking", default-features = false } pallet-teebag = { path = "../../../pallets/teebag", default-features = false } parentchain-primitives = { package = "core-primitives", path = "../../../primitives/core", default-features = false } diff --git a/tee-worker/litentry/primitives/src/lib.rs b/tee-worker/litentry/primitives/src/lib.rs index da8d5e8e94..442f241e0d 100644 --- a/tee-worker/litentry/primitives/src/lib.rs +++ b/tee-worker/litentry/primitives/src/lib.rs @@ -42,6 +42,8 @@ use bitcoin::sign_message::{signed_msg_hash, MessageSignature}; use codec::{Decode, Encode, MaxEncodedLen}; use itp_sgx_crypto::ShieldingCryptoDecrypt; use log::error; +pub use pallet_parachain_staking::Delegator; +pub use pallet_score_staking::ScorePayment; pub use pallet_teebag::{ decl_rsa_request, extract_tcb_info_from_raw_dcap_quote, AttestationType, DcapProvider, Enclave, EnclaveFingerprint, MrEnclave, ShardIdentifier, SidechainBlockNumber, WorkerMode, WorkerType, From 5a12d7bef393bfb42fc941f6935ac5e3e6af9e35 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 7 Aug 2024 14:23:00 +0000 Subject: [PATCH 03/61] adding new parentchain event and filters --- .../src/integritee/event_filter.rs | 8 +++++++- .../src/target_a/event_filter.rs | 6 ++++++ .../src/target_b/event_filter.rs | 6 ++++++ .../types/src/parentchain/events.rs | 14 ++++++++++++++ .../core-primitives/types/src/parentchain/mod.rs | 6 +++++- .../indirect-calls-executor/src/mock.rs | 6 ++++++ 6 files changed, 44 insertions(+), 2 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_filter.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_filter.rs index 456cebe639..0c15bbdfcc 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_filter.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_filter.rs @@ -25,7 +25,7 @@ use itp_types::{ events::{ ActivateIdentityRequested, AssertionCreated, DeactivateIdentityRequested, EnclaveUnauthorized, LinkIdentityRequested, OpaqueTaskPosted, - ParentchainBlockProcessed, VCRequested, + ParentchainBlockProcessed, RewardDistributionStarted, VCRequested, }, FilterEvents, }, @@ -104,4 +104,10 @@ impl FilterEvents for FilterableEvents { ) -> Result, Self::Error> { self.filter() } + + fn get_reward_distribution_started_events( + &self, + ) -> Result, Self::Error> { + self.filter() + } } diff --git a/tee-worker/app-libs/parentchain-interface/src/target_a/event_filter.rs b/tee-worker/app-libs/parentchain-interface/src/target_a/event_filter.rs index 2490b2e1d9..8209b16a18 100644 --- a/tee-worker/app-libs/parentchain-interface/src/target_a/event_filter.rs +++ b/tee-worker/app-libs/parentchain-interface/src/target_a/event_filter.rs @@ -105,4 +105,10 @@ impl FilterEvents for FilterableEvents { ) -> Result, Self::Error> { Ok(Vec::new()) } + + fn get_reward_distribution_started_events( + &self, + ) -> Result, Self::Error> { + Ok(Vec::new()) + } } diff --git a/tee-worker/app-libs/parentchain-interface/src/target_b/event_filter.rs b/tee-worker/app-libs/parentchain-interface/src/target_b/event_filter.rs index 2490b2e1d9..8209b16a18 100644 --- a/tee-worker/app-libs/parentchain-interface/src/target_b/event_filter.rs +++ b/tee-worker/app-libs/parentchain-interface/src/target_b/event_filter.rs @@ -105,4 +105,10 @@ impl FilterEvents for FilterableEvents { ) -> Result, Self::Error> { Ok(Vec::new()) } + + fn get_reward_distribution_started_events( + &self, + ) -> Result, Self::Error> { + Ok(Vec::new()) + } } diff --git a/tee-worker/core-primitives/types/src/parentchain/events.rs b/tee-worker/core-primitives/types/src/parentchain/events.rs index f6b40d1339..453682c39a 100644 --- a/tee-worker/core-primitives/types/src/parentchain/events.rs +++ b/tee-worker/core-primitives/types/src/parentchain/events.rs @@ -244,3 +244,17 @@ impl StaticEvent for AssertionCreated { const PALLET: &'static str = "EvmAssertions"; const EVENT: &'static str = "AssertionCreated"; } + +#[derive(Encode, Decode, Debug)] +pub struct RewardDistributionStarted {} + +impl core::fmt::Display for RewardDistributionStarted { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + write!(f, "{}", RewardDistributionStarted::EVENT) + } +} + +impl StaticEvent for RewardDistributionStarted { + const PALLET: &'static str = "ScoreStaking"; + const EVENT: &'static str = "RewardDistributionStarted"; +} diff --git a/tee-worker/core-primitives/types/src/parentchain/mod.rs b/tee-worker/core-primitives/types/src/parentchain/mod.rs index 723127eafa..1c0eeef42d 100644 --- a/tee-worker/core-primitives/types/src/parentchain/mod.rs +++ b/tee-worker/core-primitives/types/src/parentchain/mod.rs @@ -23,7 +23,7 @@ use codec::{Decode, Encode}; use core::fmt::Debug; use events::{ ActivateIdentityRequested, DeactivateIdentityRequested, EnclaveUnauthorized, - LinkIdentityRequested, OpaqueTaskPosted, VCRequested, + LinkIdentityRequested, OpaqueTaskPosted, RewardDistributionStarted, VCRequested, }; use itp_stf_primitives::traits::{IndirectExecutor, TrustedCallVerification}; #[cfg(feature = "std")] @@ -116,6 +116,10 @@ pub trait FilterEvents { fn get_parentchain_block_proccessed_events( &self, ) -> Result, Self::Error>; + + fn get_reward_distribution_started_events( + &self, + ) -> Result, Self::Error>; } #[derive(Debug)] diff --git a/tee-worker/core/parentchain/indirect-calls-executor/src/mock.rs b/tee-worker/core/parentchain/indirect-calls-executor/src/mock.rs index bc63f95317..e8ce7379f5 100644 --- a/tee-worker/core/parentchain/indirect-calls-executor/src/mock.rs +++ b/tee-worker/core/parentchain/indirect-calls-executor/src/mock.rs @@ -70,6 +70,12 @@ impl FilterEvents for MockEvents { ) -> Result, Self::Error> { Ok(Vec::new()) } + + fn get_reward_distribution_started_events( + &self, + ) -> Result, Self::Error> { + Ok(Vec::new()) + } } pub struct MockParentchainEventHandler {} From f81d31b2263db68eee07a7308a973d86f484ba3d Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 7 Aug 2024 14:53:30 +0000 Subject: [PATCH 04/61] injecting ocall_api and state_handler to the parentchain event handler --- .../src/integritee/event_handler.rs | 16 ++++++++++++++-- .../src/initialization/global_components.rs | 2 +- .../src/initialization/parentchain/common.rs | 8 ++++++-- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index 5a11d596c5..06c0a6e266 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -21,6 +21,9 @@ use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; use itc_parentchain_indirect_calls_executor::error::Error; use itp_api_client_types::StaticEvent; use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation}; +use itp_ocall_api::{EnclaveAttestationOCallApi, EnclaveOnChainOCallApi}; +use itp_sgx_externalities::{SgxExternalities, SgxExternalitiesTrait}; +use itp_stf_state_handler::handle_state::HandleState; use itp_types::{ parentchain::{ events::ParentchainBlockProcessed, AccountId, FilterEvents, HandleParentchainEvents, @@ -36,11 +39,20 @@ use sp_core::{blake2_256, H160}; use sp_std::vec::Vec; use std::{format, string::String, sync::Arc}; -pub struct ParentchainEventHandler { +pub struct ParentchainEventHandler< + OCallApi: EnclaveOnChainOCallApi + EnclaveAttestationOCallApi, + HS: HandleState, +> { pub assertion_repository: Arc, + pub ocall_api: Arc, + pub state_handler: Arc, } -impl ParentchainEventHandler { +impl< + OCallApi: EnclaveOnChainOCallApi + EnclaveAttestationOCallApi, + HS: HandleState, + > ParentchainEventHandler +{ fn link_identity>( executor: &Executor, account: &AccountId, diff --git a/tee-worker/enclave-runtime/src/initialization/global_components.rs b/tee-worker/enclave-runtime/src/initialization/global_components.rs index 84c335789d..16edb29166 100644 --- a/tee-worker/enclave-runtime/src/initialization/global_components.rs +++ b/tee-worker/enclave-runtime/src/initialization/global_components.rs @@ -177,7 +177,7 @@ pub type IntegriteeParentchainIndirectCallsExecutor = IndirectCallsExecutor< EnclaveTopPoolAuthor, EnclaveNodeMetadataRepository, EventCreator, - integritee::ParentchainEventHandler, + integritee::ParentchainEventHandler, EnclaveTrustedCallSigned, EnclaveGetter, >; diff --git a/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs b/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs index 5dabe3e328..2d34581a2b 100644 --- a/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs +++ b/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs @@ -69,9 +69,13 @@ pub(crate) fn create_integritee_parentchain_block_importer( let shielding_key_repository = GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT.get()?; let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; let repository = GLOBAL_ASSERTION_REPOSITORY.get()?; + let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - let parentchain_event_handler = - LitentryParentchainEventHandler { assertion_repository: repository }; + let parentchain_event_handler = LitentryParentchainEventHandler { + assertion_repository: repository, + ocall_api: ocall_api.clone(), + state_handler, + }; let stf_enclave_signer = Arc::new(EnclaveStfEnclaveSigner::new( state_observer, From 3ff077803456c8c12d4f6a83e32df9eb28d33429 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 7 Aug 2024 14:54:38 +0000 Subject: [PATCH 05/61] adding missing dependencies --- tee-worker/Cargo.lock | 164 ++++++++++-------- .../app-libs/parentchain-interface/Cargo.toml | 10 ++ tee-worker/enclave-runtime/Cargo.lock | 45 ++++- 3 files changed, 145 insertions(+), 74 deletions(-) diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index a1df660878..0609458e86 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -384,7 +384,7 @@ dependencies = [ [[package]] name = "binary-merkle-tree" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "hash-db 0.16.0", "log 0.4.20", @@ -887,7 +887,7 @@ dependencies = [ "scale-info", "serde 1.0.193", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "strum 0.26.1", @@ -1838,7 +1838,7 @@ dependencies = [ "scale-info", "serde 1.0.193", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -1856,7 +1856,7 @@ dependencies = [ "scale-info", "serde 1.0.193", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-runtime-interface", "sp-std 5.0.0", @@ -1901,7 +1901,7 @@ checksum = "6c2141d6d6c8512188a7891b4b01590a45f6dac67afb4f255c4124dbb86d4eaa" [[package]] name = "frame-benchmarking" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-support-procedural", @@ -1915,7 +1915,7 @@ dependencies = [ "sp-api", "sp-application-crypto", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-runtime-interface", "sp-std 5.0.0", @@ -1926,14 +1926,14 @@ dependencies = [ [[package]] name = "frame-executive" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "sp-tracing", @@ -1954,7 +1954,7 @@ dependencies = [ [[package]] name = "frame-support" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "bitflags 1.3.2", "environmental 1.1.4", @@ -1974,7 +1974,7 @@ dependencies = [ "sp-core", "sp-core-hashing-proc-macro", "sp-inherents", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-staking", "sp-state-machine", @@ -1987,7 +1987,7 @@ dependencies = [ [[package]] name = "frame-support-procedural" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "Inflector", "cfg-expr", @@ -2003,7 +2003,7 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support-procedural-tools-derive", "proc-macro-crate", @@ -2015,7 +2015,7 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools-derive" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "proc-macro2", "quote", @@ -2025,7 +2025,7 @@ dependencies = [ [[package]] name = "frame-system" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "log 0.4.20", @@ -2033,7 +2033,7 @@ dependencies = [ "scale-info", "serde 1.0.193", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "sp-version", @@ -2946,6 +2946,7 @@ version = "0.9.0" dependencies = [ "bs58", "env_logger 0.9.3", + "frame-support", "ita-sgx-runtime", "ita-stf", "itc-parentchain", @@ -2953,9 +2954,13 @@ dependencies = [ "itc-parentchain-test", "itp-api-client-types", "itp-node-api", + "itp-ocall-api", "itp-sgx-crypto", + "itp-sgx-externalities", "itp-stf-executor", "itp-stf-primitives", + "itp-stf-state-handler", + "itp-storage", "itp-test", "itp-top-pool-author", "itp-types", @@ -2966,6 +2971,7 @@ dependencies = [ "litentry-hex-utils", "litentry-primitives", "log 0.4.20", + "pallet-identity-management-tee", "parity-scale-codec", "regex 1.9.5", "sgx_tstd", @@ -5075,6 +5081,8 @@ dependencies = [ "itp-utils", "log 0.4.20", "pallet-evm 6.0.0-dev (git+https://github.com/integritee-network/frontier.git?branch=bar/polkadot-v0.9.42)", + "pallet-parachain-staking", + "pallet-score-staking", "pallet-teebag", "parity-scale-codec", "rand 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -5085,7 +5093,7 @@ dependencies = [ "serde 1.0.193", "sgx_tstd", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "strum 0.26.1", @@ -5973,7 +5981,7 @@ checksum = "4d5d9eb14b174ee9aa2ef96dc2b94637a2d4b6e7cb873c7e171f0c20c6cf3eac" [[package]] name = "pallet-assets" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-benchmarking", "frame-support", @@ -5988,7 +5996,7 @@ dependencies = [ [[package]] name = "pallet-authorship" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", @@ -6002,7 +6010,7 @@ dependencies = [ [[package]] name = "pallet-balances" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-benchmarking", "frame-support", @@ -6033,7 +6041,7 @@ dependencies = [ "rlp", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -6058,7 +6066,7 @@ dependencies = [ "rlp", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -6076,7 +6084,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -6109,14 +6117,32 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-runtime", +] + +[[package]] +name = "pallet-score-staking" +version = "0.1.0" +dependencies = [ + "core-primitives", + "frame-support", + "frame-system", + "num-integer 0.1.45", + "pallet-parachain-staking", + "parity-scale-codec", + "scale-info", + "serde 1.0.193", + "serde_json 1.0.103", + "sp-core", "sp-runtime", + "sp-std 5.0.0", ] [[package]] name = "pallet-session" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", @@ -6126,7 +6152,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-session", "sp-staking", @@ -6136,13 +6162,13 @@ dependencies = [ [[package]] name = "pallet-sudo" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", "parity-scale-codec", "scale-info", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -6168,7 +6194,7 @@ dependencies = [ "serde 1.0.193", "serde_json 1.0.103", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "x509-cert", @@ -6177,7 +6203,7 @@ dependencies = [ [[package]] name = "pallet-timestamp" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-benchmarking", "frame-support", @@ -6186,7 +6212,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-inherents", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "sp-timestamp", @@ -6195,7 +6221,7 @@ dependencies = [ [[package]] name = "pallet-transaction-payment" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", @@ -6203,7 +6229,7 @@ dependencies = [ "scale-info", "serde 1.0.193", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -7377,7 +7403,7 @@ dependencies = [ [[package]] name = "sc-keystore" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "array-bytes 4.2.0", "async-trait", @@ -8140,7 +8166,7 @@ dependencies = [ [[package]] name = "sp-api" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "hash-db 0.16.0", "log 0.4.20", @@ -8160,7 +8186,7 @@ dependencies = [ [[package]] name = "sp-api-proc-macro" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "Inflector", "blake2", @@ -8174,20 +8200,20 @@ dependencies = [ [[package]] name = "sp-application-crypto" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", "serde 1.0.193", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-std 5.0.0", ] [[package]] name = "sp-arithmetic" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "integer-sqrt", "num-traits 0.2.16", @@ -8201,7 +8227,7 @@ dependencies = [ [[package]] name = "sp-consensus" version = "0.10.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "async-trait", "futures 0.3.28", @@ -8216,7 +8242,7 @@ dependencies = [ [[package]] name = "sp-consensus-aura" version = "0.10.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "async-trait", "parity-scale-codec", @@ -8234,7 +8260,7 @@ dependencies = [ [[package]] name = "sp-consensus-grandpa" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "finality-grandpa", "log 0.4.20", @@ -8252,7 +8278,7 @@ dependencies = [ [[package]] name = "sp-consensus-slots" version = "0.10.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", @@ -8264,7 +8290,7 @@ dependencies = [ [[package]] name = "sp-core" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "array-bytes 4.2.0", "bitflags 1.3.2", @@ -8308,7 +8334,7 @@ dependencies = [ [[package]] name = "sp-core-hashing" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "blake2b_simd", "byteorder 1.4.3", @@ -8337,7 +8363,7 @@ dependencies = [ [[package]] name = "sp-core-hashing-proc-macro" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "proc-macro2", "quote", @@ -8348,7 +8374,7 @@ dependencies = [ [[package]] name = "sp-debug-derive" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "proc-macro2", "quote", @@ -8358,7 +8384,7 @@ dependencies = [ [[package]] name = "sp-externalities" version = "0.13.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "environmental 1.1.4", "parity-scale-codec", @@ -8369,7 +8395,7 @@ dependencies = [ [[package]] name = "sp-inherents" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "async-trait", "impl-trait-for-tuples", @@ -8396,7 +8422,7 @@ dependencies = [ [[package]] name = "sp-io" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "bytes 1.4.0", "ed25519", @@ -8422,7 +8448,7 @@ dependencies = [ [[package]] name = "sp-keyring" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "lazy_static", "sp-core", @@ -8433,7 +8459,7 @@ dependencies = [ [[package]] name = "sp-keystore" version = "0.13.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "futures 0.3.28", "parity-scale-codec", @@ -8447,7 +8473,7 @@ dependencies = [ [[package]] name = "sp-metadata-ir" version = "0.1.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-metadata", "parity-scale-codec", @@ -8458,7 +8484,7 @@ dependencies = [ [[package]] name = "sp-panic-handler" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "backtrace", "lazy_static", @@ -8468,7 +8494,7 @@ dependencies = [ [[package]] name = "sp-runtime" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "either", "hash256-std-hasher", @@ -8482,7 +8508,7 @@ dependencies = [ "sp-application-crypto", "sp-arithmetic", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-std 5.0.0", "sp-weights", ] @@ -8490,7 +8516,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "bytes 1.4.0", "impl-trait-for-tuples", @@ -8508,7 +8534,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface-proc-macro" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "Inflector", "proc-macro-crate", @@ -8520,7 +8546,7 @@ dependencies = [ [[package]] name = "sp-session" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", @@ -8533,7 +8559,7 @@ dependencies = [ [[package]] name = "sp-staking" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", @@ -8546,7 +8572,7 @@ dependencies = [ [[package]] name = "sp-state-machine" version = "0.13.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "hash-db 0.16.0", "log 0.4.20", @@ -8566,7 +8592,7 @@ dependencies = [ [[package]] name = "sp-std" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" [[package]] name = "sp-std" @@ -8577,7 +8603,7 @@ checksum = "af0ee286f98455272f64ac5bb1384ff21ac029fbb669afbaf48477faff12760e" [[package]] name = "sp-storage" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "impl-serde", "parity-scale-codec", @@ -8590,7 +8616,7 @@ dependencies = [ [[package]] name = "sp-timestamp" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "async-trait", "futures-timer", @@ -8605,7 +8631,7 @@ dependencies = [ [[package]] name = "sp-tracing" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "sp-std 5.0.0", @@ -8617,7 +8643,7 @@ dependencies = [ [[package]] name = "sp-trie" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "ahash 0.8.3", "hash-db 0.16.0", @@ -8640,7 +8666,7 @@ dependencies = [ [[package]] name = "sp-version" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "impl-serde", "parity-scale-codec", @@ -8657,7 +8683,7 @@ dependencies = [ [[package]] name = "sp-version-proc-macro" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "proc-macro2", @@ -8668,7 +8694,7 @@ dependencies = [ [[package]] name = "sp-wasm-interface" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "anyhow", "impl-trait-for-tuples", @@ -8682,7 +8708,7 @@ dependencies = [ [[package]] name = "sp-weights" version = "4.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", diff --git a/tee-worker/app-libs/parentchain-interface/Cargo.toml b/tee-worker/app-libs/parentchain-interface/Cargo.toml index a3bf24e150..a46ca23429 100644 --- a/tee-worker/app-libs/parentchain-interface/Cargo.toml +++ b/tee-worker/app-libs/parentchain-interface/Cargo.toml @@ -15,9 +15,15 @@ itc-parentchain = { path = "../../core/parentchain/parentchain-crate", default-f itc-parentchain-indirect-calls-executor = { path = "../../core/parentchain/indirect-calls-executor", default-features = false } itp-api-client-types = { path = "../../core-primitives/node-api/api-client-types", default-features = false } itp-node-api = { path = "../../core-primitives/node-api", default-features = false } +itp-ocall-api = { path = "../../core-primitives/ocall-api", default-features = false } +itp-sgx-externalities = { path = "../../core-primitives/substrate-sgx/externalities", default-features = false } itp-stf-primitives = { path = "../../core-primitives/stf-primitives", default-features = false } +itp-stf-state-handler = { path = "../../core-primitives/stf-state-handler", default-features = false } +itp-storage = { path = "../../core-primitives/storage", default-features = false } itp-types = { path = "../../core-primitives/types", default-features = false } itp-utils = { path = "../../core-primitives/utils", default-features = false } +pallet-identity-management-tee = { path = "../../litentry/pallets/identity-management", default-features = false } + # no-std compatible libraries bs58 = { version = "0.4.0", default-features = false, features = ["alloc"] } @@ -28,9 +34,11 @@ regex = { optional = true, version = "1.9.5" } substrate-api-client = { optional = true, default-features = false, features = ["std", "sync-api"], git = "https://github.com/scs/substrate-api-client.git", branch = "polkadot-v0.9.42-tag-v0.14.0" } # substrate dep +frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false } sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } + # litentry lc-dynamic-assertion = { path = "../../litentry/core/dynamic-assertion", default-features = false } lc-evm-dynamic-assertions = { path = "../../litentry/core/evm-dynamic-assertions", default-features = false } @@ -65,6 +73,7 @@ std = [ "itp-stf-executor/std", "itp-stf-primitives/std", "itp-top-pool-author/std", + "itp-sgx-externalities/std", "itp-types/std", "itp-utils/std", "log/std", @@ -85,6 +94,7 @@ sgx = [ "itp-node-api/sgx", "itp-sgx-crypto/sgx", "itp-stf-executor/sgx", + "itp-sgx-externalities/sgx", "itp-top-pool-author/sgx", "litentry-primitives/sgx", "lc-dynamic-assertion/sgx", diff --git a/tee-worker/enclave-runtime/Cargo.lock b/tee-worker/enclave-runtime/Cargo.lock index dcd0907e25..3101253bb3 100644 --- a/tee-worker/enclave-runtime/Cargo.lock +++ b/tee-worker/enclave-runtime/Cargo.lock @@ -545,7 +545,7 @@ name = "chrono" version = "0.4.11" source = "git+https://github.com/mesalock-linux/chrono-sgx#f964ae7f5f65bd2c9cd6f44a067e7980afc08ca0" dependencies = [ - "num-integer", + "num-integer 0.1.41", "num-traits 0.2.10", "sgx_tstd", ] @@ -1975,13 +1975,18 @@ name = "ita-parentchain-interface" version = "0.9.0" dependencies = [ "bs58", + "frame-support", "ita-sgx-runtime", "ita-stf", "itc-parentchain", "itc-parentchain-indirect-calls-executor", "itp-api-client-types", "itp-node-api", + "itp-ocall-api", + "itp-sgx-externalities", "itp-stf-primitives", + "itp-stf-state-handler", + "itp-storage", "itp-types", "itp-utils", "lc-dynamic-assertion", @@ -1990,6 +1995,7 @@ dependencies = [ "litentry-hex-utils", "litentry-primitives", "log", + "pallet-identity-management-tee", "parity-scale-codec", "sgx_tstd", "sp-core", @@ -3435,6 +3441,8 @@ dependencies = [ "itp-utils", "log", "pallet-evm 6.0.0-dev (git+https://github.com/integritee-network/frontier.git?branch=bar/polkadot-v0.9.42)", + "pallet-parachain-staking", + "pallet-score-staking", "pallet-teebag", "parity-scale-codec", "rand 0.7.3", @@ -3621,7 +3629,7 @@ source = "git+https://github.com/mesalock-linux/num-sgx#22645415542cc67551890dfd dependencies = [ "num-bigint", "num-complex", - "num-integer", + "num-integer 0.1.41", "num-iter", "num-rational", "num-traits 0.2.10", @@ -3633,7 +3641,7 @@ version = "0.2.5" source = "git+https://github.com/mesalock-linux/num-bigint-sgx#76a5bed94dc31c32bd1670dbf72877abcf9bbc09" dependencies = [ "autocfg 1.1.0", - "num-integer", + "num-integer 0.1.41", "num-traits 0.2.10", "sgx_tstd", ] @@ -3669,12 +3677,21 @@ dependencies = [ "sgx_tstd", ] +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits 0.2.16", +] + [[package]] name = "num-iter" version = "0.1.39" source = "git+https://github.com/mesalock-linux/num-iter-sgx#f19fc44fcad0b82a040e5a24c511e5049cc04b60" dependencies = [ - "num-integer", + "num-integer 0.1.41", "num-traits 0.2.10", "sgx_tstd", ] @@ -3686,7 +3703,7 @@ source = "git+https://github.com/mesalock-linux/num-rational-sgx#be65f9ce439f3c9 dependencies = [ "autocfg 0.1.8", "num-bigint", - "num-integer", + "num-integer 0.1.41", "num-traits 0.2.10", "sgx_tstd", ] @@ -3875,6 +3892,24 @@ dependencies = [ "sp-runtime", ] +[[package]] +name = "pallet-score-staking" +version = "0.1.0" +dependencies = [ + "core-primitives", + "frame-support", + "frame-system", + "num-integer 0.1.46", + "pallet-parachain-staking", + "parity-scale-codec", + "scale-info", + "serde 1.0.193", + "serde_json 1.0.107", + "sp-core", + "sp-runtime", + "sp-std", +] + [[package]] name = "pallet-session" version = "4.0.0-dev" From 15a0d0cd06c5c4d19d864a510f4f92e9f36144ef Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 7 Aug 2024 15:04:48 +0000 Subject: [PATCH 06/61] adding key helper --- tee-worker/core-primitives/storage/src/keys.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tee-worker/core-primitives/storage/src/keys.rs b/tee-worker/core-primitives/storage/src/keys.rs index 43de4f667e..c4767097d7 100644 --- a/tee-worker/core-primitives/storage/src/keys.rs +++ b/tee-worker/core-primitives/storage/src/keys.rs @@ -17,6 +17,7 @@ use codec::Encode; use frame_metadata::v14::StorageHasher; +use sp_core::crypto::AccountId32 as AccountId; use sp_std::vec::Vec; pub fn storage_value_key(module_prefix: &str, storage_prefix: &str) -> Vec { @@ -69,3 +70,16 @@ fn key_hash(key: &K, hasher: &StorageHasher) -> Vec { StorageHasher::Twox64Concat => sp_core::twox_64(&encoded_key).to_vec(), } } + +/// Extracts the AccountId from a storage key +pub fn key_to_account_id(key: &Vec) -> Option { + if key.len() >= 32 { + let account_id_bytes = &key[key.len() - 32..]; + let mut account_id_32_bytes = [0; 32]; + account_id_32_bytes.copy_from_slice(account_id_bytes); + + Some(AccountId::new(account_id_32_bytes)) + } else { + None + } +} From 7da34b35c5570f235f51bdcc04800e8132587c11 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 7 Aug 2024 15:06:56 +0000 Subject: [PATCH 07/61] passing block_header to handle_events --- .../parentchain-interface/src/integritee/event_handler.rs | 2 ++ .../parentchain-interface/src/target_a/event_handler.rs | 2 ++ .../parentchain-interface/src/target_b/event_handler.rs | 2 ++ tee-worker/core-primitives/types/src/parentchain/mod.rs | 7 ++++++- .../parentchain/indirect-calls-executor/src/executor.rs | 5 +++-- .../core/parentchain/indirect-calls-executor/src/mock.rs | 2 ++ 6 files changed, 17 insertions(+), 3 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index 06c0a6e266..41aa65f0cd 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -36,6 +36,7 @@ use lc_evm_dynamic_assertions::repository::EvmAssertionRepository; use litentry_primitives::{Assertion, Identity, ValidationData, Web3Network}; use log::*; use sp_core::{blake2_256, H160}; +use sp_runtime::traits::Header; use sp_std::vec::Vec; use std::{format, string::String, sync::Arc}; @@ -224,6 +225,7 @@ where &self, executor: &Executor, events: impl FilterEvents, + block_header: impl Header, ) -> Result { let mut handled_events: Vec = Vec::new(); let mut successful_assertion_ids: Vec = Vec::new(); diff --git a/tee-worker/app-libs/parentchain-interface/src/target_a/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/target_a/event_handler.rs index af091e98f8..a73312c63e 100644 --- a/tee-worker/app-libs/parentchain-interface/src/target_a/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/target_a/event_handler.rs @@ -22,6 +22,7 @@ use itc_parentchain_indirect_calls_executor::error::Error; use itp_stf_primitives::traits::IndirectExecutor; use itp_types::parentchain::{FilterEvents, HandleParentchainEvents, ProcessedEventsArtifacts}; use log::*; +use sp_runtime::traits::Header; use sp_std::vec::Vec; pub struct ParentchainEventHandler {} @@ -35,6 +36,7 @@ where &self, _executor: &Executor, _events: impl FilterEvents, + _block_header: impl Header, ) -> Result { debug!("not handling any events for target a"); Ok((Vec::new(), Vec::new(), Vec::new())) diff --git a/tee-worker/app-libs/parentchain-interface/src/target_b/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/target_b/event_handler.rs index 56151a9ccc..ce279228bf 100644 --- a/tee-worker/app-libs/parentchain-interface/src/target_b/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/target_b/event_handler.rs @@ -22,6 +22,7 @@ use itc_parentchain_indirect_calls_executor::error::Error; use itp_stf_primitives::traits::IndirectExecutor; use itp_types::parentchain::{FilterEvents, HandleParentchainEvents, ProcessedEventsArtifacts}; use log::*; +use sp_runtime::traits::Header; use sp_std::vec::Vec; pub struct ParentchainEventHandler {} @@ -35,6 +36,7 @@ where &self, _executor: &Executor, _events: impl FilterEvents, + _block_header: impl Header, ) -> Result { debug!("not handling any events for target B"); Ok((Vec::new(), Vec::new(), Vec::new())) diff --git a/tee-worker/core-primitives/types/src/parentchain/mod.rs b/tee-worker/core-primitives/types/src/parentchain/mod.rs index 1c0eeef42d..dcd0d529d9 100644 --- a/tee-worker/core-primitives/types/src/parentchain/mod.rs +++ b/tee-worker/core-primitives/types/src/parentchain/mod.rs @@ -29,7 +29,11 @@ use itp_stf_primitives::traits::{IndirectExecutor, TrustedCallVerification}; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; use sp_core::{bounded::alloc, H160, H256}; -use sp_runtime::{generic::Header as HeaderG, traits::BlakeTwo256, MultiAddress, MultiSignature}; +use sp_runtime::{ + generic::Header as HeaderG, + traits::{BlakeTwo256, Header as HeaderT}, + MultiAddress, MultiSignature, +}; use self::events::ParentchainBlockProcessed; @@ -139,6 +143,7 @@ where &self, executor: &Executor, events: impl FilterEvents, + block_header: impl HeaderT, ) -> Result; } diff --git a/tee-worker/core/parentchain/indirect-calls-executor/src/executor.rs b/tee-worker/core/parentchain/indirect-calls-executor/src/executor.rs index 61ced37b8a..14815c880a 100644 --- a/tee-worker/core/parentchain/indirect-calls-executor/src/executor.rs +++ b/tee-worker/core/parentchain/indirect-calls-executor/src/executor.rs @@ -167,8 +167,9 @@ impl< })? .ok_or_else(|| Error::Other("Could not create events from metadata".into()))?; - let (processed_events, successful_assertion_ids, failed_assertion_ids) = - self.parentchain_event_handler.handle_events(self, events)?; + let (processed_events, successful_assertion_ids, failed_assertion_ids) = self + .parentchain_event_handler + .handle_events(self, events, block.header().clone())?; let mut calls: Vec = Vec::new(); if !successful_assertion_ids.is_empty() { calls.extend(self.create_assertion_stored_call(successful_assertion_ids)?); diff --git a/tee-worker/core/parentchain/indirect-calls-executor/src/mock.rs b/tee-worker/core/parentchain/indirect-calls-executor/src/mock.rs index e8ce7379f5..ad621adef6 100644 --- a/tee-worker/core/parentchain/indirect-calls-executor/src/mock.rs +++ b/tee-worker/core/parentchain/indirect-calls-executor/src/mock.rs @@ -12,6 +12,7 @@ use itp_types::{ RsaRequest, H256, }; use sp_core::H160; +use sp_runtime::traits::Header; use std::vec::Vec; pub struct TestEventCreator; @@ -89,6 +90,7 @@ where &self, _: &Executor, _: impl FilterEvents, + _: impl Header, ) -> Result { Ok(( Vec::from([H256::default()]), From a3ed38dc7844a6d583ec3feb91dd1172f0ef4a83 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 7 Aug 2024 15:14:58 +0000 Subject: [PATCH 08/61] updating generics for the event handler --- .../src/integritee/event_handler.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index 41aa65f0cd..28b5b6f0ba 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -21,7 +21,7 @@ use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; use itc_parentchain_indirect_calls_executor::error::Error; use itp_api_client_types::StaticEvent; use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation}; -use itp_ocall_api::{EnclaveAttestationOCallApi, EnclaveOnChainOCallApi}; +use itp_ocall_api::EnclaveOnChainOCallApi; use itp_sgx_externalities::{SgxExternalities, SgxExternalitiesTrait}; use itp_stf_state_handler::handle_state::HandleState; use itp_types::{ @@ -41,7 +41,7 @@ use sp_std::vec::Vec; use std::{format, string::String, sync::Arc}; pub struct ParentchainEventHandler< - OCallApi: EnclaveOnChainOCallApi + EnclaveAttestationOCallApi, + OCallApi: EnclaveOnChainOCallApi, HS: HandleState, > { pub assertion_repository: Arc, @@ -49,10 +49,8 @@ pub struct ParentchainEventHandler< pub state_handler: Arc, } -impl< - OCallApi: EnclaveOnChainOCallApi + EnclaveAttestationOCallApi, - HS: HandleState, - > ParentchainEventHandler +impl> + ParentchainEventHandler { fn link_identity>( executor: &Executor, @@ -216,10 +214,12 @@ impl< } } -impl HandleParentchainEvents - for ParentchainEventHandler +impl HandleParentchainEvents + for ParentchainEventHandler where Executor: IndirectExecutor, + OCallApi: EnclaveOnChainOCallApi + EnclaveAttestationOCallApi, + HS: HandleState, { fn handle_events( &self, From a7a954181ed31edff09a9ace80a897aacd0bb173 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 7 Aug 2024 15:42:34 +0000 Subject: [PATCH 09/61] adding ParentchainEventProcessingError variant --- tee-worker/core-primitives/types/src/parentchain/mod.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tee-worker/core-primitives/types/src/parentchain/mod.rs b/tee-worker/core-primitives/types/src/parentchain/mod.rs index dcd0d529d9..34bd9f24fa 100644 --- a/tee-worker/core-primitives/types/src/parentchain/mod.rs +++ b/tee-worker/core-primitives/types/src/parentchain/mod.rs @@ -158,6 +158,7 @@ pub enum ParentchainEventProcessingError { OpaqueTaskPostedFailure, AssertionCreatedFailure, ParentchainBlockProcessedFailure, + RewardDistributionStartedFailure, } impl core::fmt::Display for ParentchainEventProcessingError { @@ -181,6 +182,8 @@ impl core::fmt::Display for ParentchainEventProcessingError { "Parentchain Event Processing Error: AssertionCreatedFailure", ParentchainEventProcessingError::ParentchainBlockProcessedFailure => "Parentchain Event Processing Error: ParentchainBlockProcessedFailure", + ParentchainEventProcessingError::RewardDistributionStartedFailure => + "Parentchain Event Processing Error: RewardDistributionStartedFailure", }; write!(f, "{}", message) } From 2c92a8b1043738f1a50e6a9bcc6f360ed9cec4c5 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 7 Aug 2024 15:43:44 +0000 Subject: [PATCH 10/61] fixing generics --- .../parentchain-interface/src/integritee/event_handler.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index 28b5b6f0ba..e873c496be 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -218,7 +218,7 @@ impl HandleParentchainEvents where Executor: IndirectExecutor, - OCallApi: EnclaveOnChainOCallApi + EnclaveAttestationOCallApi, + OCallApi: EnclaveOnChainOCallApi, HS: HandleState, { fn handle_events( From 7d6ec853604ac923bb01bc1dac498a0d09c3f06f Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 7 Aug 2024 15:44:46 +0000 Subject: [PATCH 11/61] draft logic of the staking updates logic, getting necessary data from the parentchain storage and idgraphs --- .../src/integritee/event_handler.rs | 126 +++++++++++++++++- 1 file changed, 121 insertions(+), 5 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index e873c496be..6c3bf10dc3 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -16,29 +16,33 @@ */ use codec::{Decode, Encode}; -pub use ita_sgx_runtime::{Balance, Index}; +use frame_support::storage::storage_prefix; +pub use ita_sgx_runtime::{Balance, Index, Runtime}; use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; use itc_parentchain_indirect_calls_executor::error::Error; use itp_api_client_types::StaticEvent; -use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation}; use itp_ocall_api::EnclaveOnChainOCallApi; use itp_sgx_externalities::{SgxExternalities, SgxExternalitiesTrait}; +use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation}; use itp_stf_state_handler::handle_state::HandleState; +use itp_storage::{key_to_account_id, storage_map_key, StorageHasher}; use itp_types::{ parentchain::{ events::ParentchainBlockProcessed, AccountId, FilterEvents, HandleParentchainEvents, - ParentchainEventProcessingError, ProcessedEventsArtifacts, + ParentchainEventProcessingError, ParentchainId, ProcessedEventsArtifacts, }, - RsaRequest, H256, + Delegator, RsaRequest, ScorePayment, H256, }; use lc_dynamic_assertion::AssertionLogicRepository; use lc_evm_dynamic_assertions::repository::EvmAssertionRepository; +use litentry_hex_utils::decode_hex; use litentry_primitives::{Assertion, Identity, ValidationData, Web3Network}; use log::*; +use pallet_identity_management_tee::IdentityContext; use sp_core::{blake2_256, H160}; use sp_runtime::traits::Header; use sp_std::vec::Vec; -use std::{format, string::String, sync::Arc}; +use std::{collections::BTreeMap, format, println, string::String, sync::Arc}; pub struct ParentchainEventHandler< OCallApi: EnclaveOnChainOCallApi, @@ -212,6 +216,104 @@ impl>( + &self, + executor: &Executor, + block_header: impl Header, + ) -> Result<(), Error> { + let scores_key_prefix = storage_prefix(b"ScoreStaking", b"Scores"); + let scores_storage_keys_response = self + .ocall_api + .get_storage_keys(scores_key_prefix.into()) + .map_err(|_| Error::Other("Failed to get storage keys".into()))?; + let scores_storage_keys: Vec> = scores_storage_keys_response + .into_iter() + .filter_map(|r| { + let hex_key = String::decode(&mut r.as_slice()).unwrap_or_default(); + decode_hex(hex_key).ok() + }) + .collect(); + let account_ids: Vec = + scores_storage_keys.iter().filter_map(key_to_account_id).collect(); + let scores: Vec> = self + .ocall_api + .get_multiple_storages_verified( + scores_storage_keys, + &block_header, + &ParentchainId::Litentry, + ) + .map_err(|_| Error::Other("Failed to get multiple storages".into()))? + .into_iter() + .filter_map(|entry| entry.into_tuple().1) + .collect(); + let delegator_state_storage_keys: Vec> = account_ids + .iter() + .map(|account_id| { + storage_map_key( + "ParachainStaking", + "DelegatorState", + account_id, + &StorageHasher::Blake2_128Concat, + ) + }) + .collect(); + let delegator_states: Vec> = self + .ocall_api + .get_multiple_storages_verified( + delegator_state_storage_keys, + &block_header, + &ParentchainId::Litentry, + ) + .map_err(|_| Error::Other("Failed to get multiple storages".into()))? + .into_iter() + .filter_map(|entry| entry.into_tuple().1) + .collect(); + + let id_graphs_storage_keys: Vec> = account_ids + .iter() + .map(|account_id| { + storage_map_key( + "IdentityManagement", + "IDGraphs", + &Identity::from(account_id.clone()), + &StorageHasher::Blake2_128Concat, + ) + }) + .collect(); + + let shard = executor.get_default_shard(); + + let graph_accounts = self + .state_handler + .execute_on_current(&shard, |state, _| { + let mut accounts_id_graph_accounts: BTreeMap> = + BTreeMap::new(); + for id_graph_storage_key in id_graphs_storage_keys.iter() { + let id_graph: Vec<(Identity, IdentityContext)> = state + .iter_prefix::>(id_graph_storage_key) + .unwrap_or_default(); + let graph_accounts: Vec = id_graph + .iter() + .filter_map(|(identity, _)| { + if identity.is_web2() { + return None + } + identity.to_account_id() + }) + .collect(); + let account_id = key_to_account_id(id_graph_storage_key).unwrap(); + accounts_id_graph_accounts.insert(account_id, graph_accounts); + } + + accounts_id_graph_accounts + }) + .map_err(|_| Error::Other("Failed to get id graphs".into()))?; + + // TODO: calculate new scores and send extrinsic to update them + + Ok(()) + } } impl HandleParentchainEvents @@ -344,6 +446,20 @@ where }); } + if let Ok(events) = events.get_reward_distribution_started_events() { + println!("Handling RewardDistributionStarted events"); + events + .iter() + .try_for_each(|event| { + let event_hash = hash_of(&event); + let result = self.update_staking_scores(executor, block_header.clone()); + handled_events.push(event_hash); + + result + }) + .map_err(|_| ParentchainEventProcessingError::RewardDistributionStartedFailure)?; + } + Ok((handled_events, successful_assertion_ids, failed_assertion_ids)) } } From 9ebaa378c23035b7b14ddf3f831a8d478a449243 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 8 Aug 2024 10:44:37 +0000 Subject: [PATCH 12/61] adding dependency to send extrinsics from the event handler --- tee-worker/Cargo.lock | 1 + tee-worker/app-libs/parentchain-interface/Cargo.toml | 3 +++ tee-worker/enclave-runtime/Cargo.lock | 1 + 3 files changed, 5 insertions(+) diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index 0609458e86..6c3a67ff96 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -2967,6 +2967,7 @@ dependencies = [ "itp-utils", "lc-dynamic-assertion", "lc-evm-dynamic-assertions", + "lc-parachain-extrinsic-task-sender", "lc-vc-task-sender", "litentry-hex-utils", "litentry-primitives", diff --git a/tee-worker/app-libs/parentchain-interface/Cargo.toml b/tee-worker/app-libs/parentchain-interface/Cargo.toml index a46ca23429..aa36425416 100644 --- a/tee-worker/app-libs/parentchain-interface/Cargo.toml +++ b/tee-worker/app-libs/parentchain-interface/Cargo.toml @@ -22,6 +22,7 @@ itp-stf-state-handler = { path = "../../core-primitives/stf-state-handler", defa itp-storage = { path = "../../core-primitives/storage", default-features = false } itp-types = { path = "../../core-primitives/types", default-features = false } itp-utils = { path = "../../core-primitives/utils", default-features = false } +lc-parachain-extrinsic-task-sender = { path = "../../litentry/core/parachain-extrinsic-task/sender", default-features = false } pallet-identity-management-tee = { path = "../../litentry/pallets/identity-management", default-features = false } @@ -85,6 +86,7 @@ std = [ "lc-dynamic-assertion/std", "lc-evm-dynamic-assertions/std", "lc-vc-task-sender/std", + "lc-parachain-extrinsic-task-sender/std", "sp-std/std", ] sgx = [ @@ -100,4 +102,5 @@ sgx = [ "lc-dynamic-assertion/sgx", "lc-evm-dynamic-assertions/sgx", "lc-vc-task-sender/sgx", + "lc-parachain-extrinsic-task-sender/sgx", ] diff --git a/tee-worker/enclave-runtime/Cargo.lock b/tee-worker/enclave-runtime/Cargo.lock index 3101253bb3..755cd0940a 100644 --- a/tee-worker/enclave-runtime/Cargo.lock +++ b/tee-worker/enclave-runtime/Cargo.lock @@ -1991,6 +1991,7 @@ dependencies = [ "itp-utils", "lc-dynamic-assertion", "lc-evm-dynamic-assertions", + "lc-parachain-extrinsic-task-sender", "lc-vc-task-sender", "litentry-hex-utils", "litentry-primitives", From 551c14426a8160ad622e78d29565416048395018 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 8 Aug 2024 10:50:33 +0000 Subject: [PATCH 13/61] refactoring collected data to make it easier to operate --- .../src/integritee/event_handler.rs | 31 ++++++++++++++----- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index 6c3bf10dc3..d8e330a08a 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -229,14 +229,11 @@ impl> = scores_storage_keys_response .into_iter() - .filter_map(|r| { - let hex_key = String::decode(&mut r.as_slice()).unwrap_or_default(); - decode_hex(hex_key).ok() - }) + .filter_map(decode_storage_key) .collect(); let account_ids: Vec = scores_storage_keys.iter().filter_map(key_to_account_id).collect(); - let scores: Vec> = self + let scores: BTreeMap> = self .ocall_api .get_multiple_storages_verified( scores_storage_keys, @@ -245,8 +242,15 @@ impl> = account_ids .iter() .map(|account_id| { @@ -258,7 +262,7 @@ impl> = self + let delegator_states: BTreeMap> = self .ocall_api .get_multiple_storages_verified( delegator_state_storage_keys, @@ -267,7 +271,13 @@ impl> = account_ids @@ -316,6 +326,11 @@ impl) -> Option> { + let hex_key = String::decode(&mut raw_key.as_slice()).unwrap_or_default(); + decode_hex(hex_key).ok() +} + impl HandleParentchainEvents for ParentchainEventHandler where From 07a4d9de28e28120c86eefb5aa34ca4c056943af Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 8 Aug 2024 10:52:18 +0000 Subject: [PATCH 14/61] refactoring how idgraphs are collected --- .../src/integritee/event_handler.rs | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index d8e330a08a..a1980d0b76 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -294,29 +294,24 @@ impl> = - BTreeMap::new(); + let mut id_graphs_accounts: BTreeMap> = BTreeMap::new(); for id_graph_storage_key in id_graphs_storage_keys.iter() { let id_graph: Vec<(Identity, IdentityContext)> = state .iter_prefix::>(id_graph_storage_key) .unwrap_or_default(); let graph_accounts: Vec = id_graph .iter() - .filter_map(|(identity, _)| { - if identity.is_web2() { - return None - } - identity.to_account_id() - }) + .filter_map(|(identity, _)| identity.to_account_id()) .collect(); - let account_id = key_to_account_id(id_graph_storage_key).unwrap(); - accounts_id_graph_accounts.insert(account_id, graph_accounts); + if let Some(account_id) = key_to_account_id(id_graph_storage_key) { + id_graphs_accounts.insert(account_id, graph_accounts); + } } - accounts_id_graph_accounts + id_graphs_accounts }) .map_err(|_| Error::Other("Failed to get id graphs".into()))?; From 1ae43f904d2b1b2023d8bb20cda2cf85693b9cd0 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 8 Aug 2024 10:53:05 +0000 Subject: [PATCH 15/61] tentative logic to update scores --- .../src/integritee/event_handler.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index a1980d0b76..185a4f8ea1 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -316,6 +316,23 @@ impl = BTreeMap::new(); + + for account_id in account_ids.iter() { + let default_id_graph = Vec::new(); + let id_graph = accounts_graphs.get(account_id).unwrap_or(&default_id_graph); + for identity in id_graph.iter() { + if let Some(delegator) = delegator_states.get(identity) { + if let Some(score_payment) = scores.get(account_id) { + new_scores_rewards.insert( + account_id.clone(), + score_payment.total_reward + delegator.total, + ); + } + } + } + } + Ok(()) } From 554574d178d2ab730ad5413a012fb3ca5544e69e Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 8 Aug 2024 10:53:48 +0000 Subject: [PATCH 16/61] updating TODO --- .../parentchain-interface/src/integritee/event_handler.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index 185a4f8ea1..4e372afc5b 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -35,6 +35,7 @@ use itp_types::{ }; use lc_dynamic_assertion::AssertionLogicRepository; use lc_evm_dynamic_assertions::repository::EvmAssertionRepository; +// use lc_parachain_extrinsic_task_sender::{ParachainExtrinsicSender, SendParachainExtrinsic}; use litentry_hex_utils::decode_hex; use litentry_primitives::{Assertion, Identity, ValidationData, Web3Network}; use log::*; @@ -315,7 +316,6 @@ impl = BTreeMap::new(); for account_id in account_ids.iter() { @@ -333,6 +333,12 @@ impl Date: Thu, 8 Aug 2024 13:13:10 +0000 Subject: [PATCH 17/61] fixing staking amount calculation --- .../src/integritee/event_handler.rs | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index 4e372afc5b..878cdf6935 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -316,21 +316,19 @@ impl = BTreeMap::new(); + let mut staking_amounts: BTreeMap = BTreeMap::new(); for account_id in account_ids.iter() { let default_id_graph = Vec::new(); let id_graph = accounts_graphs.get(account_id).unwrap_or(&default_id_graph); - for identity in id_graph.iter() { - if let Some(delegator) = delegator_states.get(identity) { - if let Some(score_payment) = scores.get(account_id) { - new_scores_rewards.insert( - account_id.clone(), - score_payment.total_reward + delegator.total, - ); - } - } - } + let staking_amount: Balance = id_graph + .iter() + .filter_map(|identity| { + let delegator = delegator_states.get(identity)?; + Some(delegator.total) + }) + .sum(); + staking_amounts.insert(account_id.clone(), staking_amount); } // let extrinsic_sender = ParachainExtrinsicSender::new(); From 54cdfd1ea72c32f0c315df0eea8a6fcb5873fd44 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 8 Aug 2024 13:13:34 +0000 Subject: [PATCH 18/61] cleaning up unused code --- tee-worker/Cargo.lock | 19 ---------- .../src/integritee/event_handler.rs | 19 +--------- tee-worker/core-primitives/types/src/lib.rs | 2 +- tee-worker/enclave-runtime/Cargo.lock | 38 +++---------------- tee-worker/litentry/primitives/Cargo.toml | 1 - tee-worker/litentry/primitives/src/lib.rs | 1 - 6 files changed, 7 insertions(+), 73 deletions(-) diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index 6c3a67ff96..79126ed1f0 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -5083,7 +5083,6 @@ dependencies = [ "log 0.4.20", "pallet-evm 6.0.0-dev (git+https://github.com/integritee-network/frontier.git?branch=bar/polkadot-v0.9.42)", "pallet-parachain-staking", - "pallet-score-staking", "pallet-teebag", "parity-scale-codec", "rand 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -6122,24 +6121,6 @@ dependencies = [ "sp-runtime", ] -[[package]] -name = "pallet-score-staking" -version = "0.1.0" -dependencies = [ - "core-primitives", - "frame-support", - "frame-system", - "num-integer 0.1.45", - "pallet-parachain-staking", - "parity-scale-codec", - "scale-info", - "serde 1.0.193", - "serde_json 1.0.103", - "sp-core", - "sp-runtime", - "sp-std 5.0.0", -] - [[package]] name = "pallet-session" version = "4.0.0-dev" diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index 878cdf6935..a0d925ea12 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -31,7 +31,7 @@ use itp_types::{ events::ParentchainBlockProcessed, AccountId, FilterEvents, HandleParentchainEvents, ParentchainEventProcessingError, ParentchainId, ProcessedEventsArtifacts, }, - Delegator, RsaRequest, ScorePayment, H256, + Delegator, RsaRequest, H256, }; use lc_dynamic_assertion::AssertionLogicRepository; use lc_evm_dynamic_assertions::repository::EvmAssertionRepository; @@ -234,23 +234,6 @@ impl = scores_storage_keys.iter().filter_map(key_to_account_id).collect(); - let scores: BTreeMap> = self - .ocall_api - .get_multiple_storages_verified( - scores_storage_keys, - &block_header, - &ParentchainId::Litentry, - ) - .map_err(|_| Error::Other("Failed to get multiple storages".into()))? - .into_iter() - .filter_map(|entry| { - // TODO: check of the key needs to be decoded here - let storage_key = decode_storage_key(entry.key)?; - let account_id = key_to_account_id(&storage_key)?; - let score_payment = entry.value?; - Some((account_id, score_payment)) - }) - .collect(); let delegator_state_storage_keys: Vec> = account_ids .iter() diff --git a/tee-worker/core-primitives/types/src/lib.rs b/tee-worker/core-primitives/types/src/lib.rs index 2179588cf3..35c31f1f18 100644 --- a/tee-worker/core-primitives/types/src/lib.rs +++ b/tee-worker/core-primitives/types/src/lib.rs @@ -30,7 +30,7 @@ pub mod storage; pub use itp_sgx_runtime_primitives::types::*; pub use litentry_primitives::{ Assertion, AttestationType, DcapProvider, DecryptableRequest, Delegator, Enclave, - EnclaveFingerprint, MrEnclave, ScorePayment, SidechainBlockNumber, WorkerType, + EnclaveFingerprint, MrEnclave, SidechainBlockNumber, WorkerType, }; pub use sp_core::{crypto::AccountId32 as AccountId, H256}; diff --git a/tee-worker/enclave-runtime/Cargo.lock b/tee-worker/enclave-runtime/Cargo.lock index 755cd0940a..a585b7e926 100644 --- a/tee-worker/enclave-runtime/Cargo.lock +++ b/tee-worker/enclave-runtime/Cargo.lock @@ -545,7 +545,7 @@ name = "chrono" version = "0.4.11" source = "git+https://github.com/mesalock-linux/chrono-sgx#f964ae7f5f65bd2c9cd6f44a067e7980afc08ca0" dependencies = [ - "num-integer 0.1.41", + "num-integer", "num-traits 0.2.10", "sgx_tstd", ] @@ -3443,7 +3443,6 @@ dependencies = [ "log", "pallet-evm 6.0.0-dev (git+https://github.com/integritee-network/frontier.git?branch=bar/polkadot-v0.9.42)", "pallet-parachain-staking", - "pallet-score-staking", "pallet-teebag", "parity-scale-codec", "rand 0.7.3", @@ -3630,7 +3629,7 @@ source = "git+https://github.com/mesalock-linux/num-sgx#22645415542cc67551890dfd dependencies = [ "num-bigint", "num-complex", - "num-integer 0.1.41", + "num-integer", "num-iter", "num-rational", "num-traits 0.2.10", @@ -3642,7 +3641,7 @@ version = "0.2.5" source = "git+https://github.com/mesalock-linux/num-bigint-sgx#76a5bed94dc31c32bd1670dbf72877abcf9bbc09" dependencies = [ "autocfg 1.1.0", - "num-integer 0.1.41", + "num-integer", "num-traits 0.2.10", "sgx_tstd", ] @@ -3678,21 +3677,12 @@ dependencies = [ "sgx_tstd", ] -[[package]] -name = "num-integer" -version = "0.1.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" -dependencies = [ - "num-traits 0.2.16", -] - [[package]] name = "num-iter" version = "0.1.39" source = "git+https://github.com/mesalock-linux/num-iter-sgx#f19fc44fcad0b82a040e5a24c511e5049cc04b60" dependencies = [ - "num-integer 0.1.41", + "num-integer", "num-traits 0.2.10", "sgx_tstd", ] @@ -3704,7 +3694,7 @@ source = "git+https://github.com/mesalock-linux/num-rational-sgx#be65f9ce439f3c9 dependencies = [ "autocfg 0.1.8", "num-bigint", - "num-integer 0.1.41", + "num-integer", "num-traits 0.2.10", "sgx_tstd", ] @@ -3893,24 +3883,6 @@ dependencies = [ "sp-runtime", ] -[[package]] -name = "pallet-score-staking" -version = "0.1.0" -dependencies = [ - "core-primitives", - "frame-support", - "frame-system", - "num-integer 0.1.46", - "pallet-parachain-staking", - "parity-scale-codec", - "scale-info", - "serde 1.0.193", - "serde_json 1.0.107", - "sp-core", - "sp-runtime", - "sp-std", -] - [[package]] name = "pallet-session" version = "4.0.0-dev" diff --git a/tee-worker/litentry/primitives/Cargo.toml b/tee-worker/litentry/primitives/Cargo.toml index 402ff41a28..143394bd3c 100644 --- a/tee-worker/litentry/primitives/Cargo.toml +++ b/tee-worker/litentry/primitives/Cargo.toml @@ -31,7 +31,6 @@ sgx_tstd = { git = "https://github.com/apache/teaclave-sgx-sdk.git", branch = "m itp-sgx-crypto = { path = "../../core-primitives/sgx/crypto", default-features = false } itp-utils = { path = "../../core-primitives/utils", default-features = false } pallet-parachain-staking = { path = "../../../pallets/parachain-staking", default-features = false } -pallet-score-staking = { path = "../../../pallets/score-staking", default-features = false } pallet-teebag = { path = "../../../pallets/teebag", default-features = false } parentchain-primitives = { package = "core-primitives", path = "../../../primitives/core", default-features = false } diff --git a/tee-worker/litentry/primitives/src/lib.rs b/tee-worker/litentry/primitives/src/lib.rs index 442f241e0d..1f05bb0afc 100644 --- a/tee-worker/litentry/primitives/src/lib.rs +++ b/tee-worker/litentry/primitives/src/lib.rs @@ -43,7 +43,6 @@ use codec::{Decode, Encode, MaxEncodedLen}; use itp_sgx_crypto::ShieldingCryptoDecrypt; use log::error; pub use pallet_parachain_staking::Delegator; -pub use pallet_score_staking::ScorePayment; pub use pallet_teebag::{ decl_rsa_request, extract_tcb_info_from_raw_dcap_quote, AttestationType, DcapProvider, Enclave, EnclaveFingerprint, MrEnclave, ShardIdentifier, SidechainBlockNumber, WorkerMode, WorkerType, From 44213e6f3eb128b04fcac3365e03d17d44090caa Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 8 Aug 2024 13:30:32 +0000 Subject: [PATCH 19/61] updating pallet events and fixing pallet tests --- pallets/score-staking/src/lib.rs | 9 ++++-- pallets/score-staking/src/tests.rs | 49 +++++++++++++++++------------- 2 files changed, 34 insertions(+), 24 deletions(-) diff --git a/pallets/score-staking/src/lib.rs b/pallets/score-staking/src/lib.rs index b681bfa3e3..fe6bf48f8a 100644 --- a/pallets/score-staking/src/lib.rs +++ b/pallets/score-staking/src/lib.rs @@ -150,8 +150,8 @@ pub mod pallet { ScoreUpdated { who: Identity, new_score: Score }, ScoreRemoved { who: Identity }, ScoreCleared {}, - RewardDistributionStarted {}, - RewardDistributionCompleted { total: BalanceOf, distributed: BalanceOf }, + RewardDistributionStarted { total: BalanceOf, distributed: BalanceOf }, + RewardDistributionCompleted {}, RewardClaimed { who: T::AccountId, amount: BalanceOf }, } @@ -269,7 +269,10 @@ pub mod pallet { weight = weight.saturating_add(T::DbWeight::get().reads_writes(2, 1)); } - Self::deposit_event(Event::::RewardDistributionStarted {}); + Self::deposit_event(Event::::RewardDistributionStarted { + total: round_reward, + distributed: all_user_reward, + }); weight } diff --git a/pallets/score-staking/src/tests.rs b/pallets/score-staking/src/tests.rs index 32bebe1e7c..d7362293fd 100644 --- a/pallets/score-staking/src/tests.rs +++ b/pallets/score-staking/src/tests.rs @@ -114,10 +114,9 @@ fn default_mint_works() { // run to next reward distribution round run_to_block(7); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardCalculated { - total: round_reward(), - distributed: 0, - })); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { total: round_reward(), distributed: 0 }, + )); }); } @@ -168,10 +167,12 @@ fn score_staking_works() { // run to next reward distribution round, alice should win all rewards run_to_block(7); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardCalculated { - total: round_reward(), - distributed: round_reward(), - })); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + total: round_reward(), + distributed: round_reward(), + }, + )); assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { @@ -184,10 +185,12 @@ fn score_staking_works() { // alice's winning should accumulate run_to_block(12); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardCalculated { - total: round_reward(), - distributed: round_reward(), - })); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + total: round_reward(), + distributed: round_reward(), + }, + )); assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { @@ -203,10 +206,12 @@ fn score_staking_works() { pallet_parachain_staking::Total::::put(1600); run_to_block(17); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardCalculated { - total: round_reward(), - distributed: round_reward() * 3 / 4, - })); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + total: round_reward(), + distributed: round_reward() * 3 / 4, + }, + )); assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { @@ -229,7 +234,7 @@ fn score_staking_works() { assert_eq!(ScoreStaking::score_user_count(), 2); run_to_block(22); - // System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardCalculated { + // System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardDistributionStarted { // total: round_reward(), // distributed: round_reward() * 2 * 3 / (3 * 5) + round_reward() * 1 * 4 / (3 * 5), // })); @@ -291,10 +296,12 @@ fn claim_works() { // run to next reward distribution round, alice should win all rewards run_to_block(7); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardCalculated { - total: round_reward(), - distributed: round_reward(), - })); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + total: round_reward(), + distributed: round_reward(), + }, + )); assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { From a9d65180375141dbfa904ff0c9a6eaadfeaf05ec Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 8 Aug 2024 13:34:35 +0000 Subject: [PATCH 20/61] updating parentchain events --- .../core-primitives/types/src/parentchain/events.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/tee-worker/core-primitives/types/src/parentchain/events.rs b/tee-worker/core-primitives/types/src/parentchain/events.rs index 453682c39a..d830622c52 100644 --- a/tee-worker/core-primitives/types/src/parentchain/events.rs +++ b/tee-worker/core-primitives/types/src/parentchain/events.rs @@ -246,11 +246,20 @@ impl StaticEvent for AssertionCreated { } #[derive(Encode, Decode, Debug)] -pub struct RewardDistributionStarted {} +pub struct RewardDistributionStarted { + pub total: Balance, + pub distributed: Balance, +} impl core::fmt::Display for RewardDistributionStarted { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - write!(f, "{}", RewardDistributionStarted::EVENT) + let message = format!( + "{:?} :: total: {}, distributed: {}", + RewardDistributionStarted::EVENT, + self.total, + self.distributed + ); + write!(f, "{}", message) } } From 4e1761915c975b93fdf46e34ae5a4451477284f7 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 8 Aug 2024 13:35:25 +0000 Subject: [PATCH 21/61] adding new field for id_graph rewards --- pallets/score-staking/src/tests.rs | 16 +++++++++++++++- pallets/score-staking/src/types.rs | 1 + 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/pallets/score-staking/src/tests.rs b/pallets/score-staking/src/tests.rs index d7362293fd..3783194b98 100644 --- a/pallets/score-staking/src/tests.rs +++ b/pallets/score-staking/src/tests.rs @@ -151,7 +151,13 @@ fn score_staking_works() { assert_ok!(ScoreStaking::update_score(RuntimeOrigin::signed(alice()), alice().into(), 500)); assert_eq!( ScoreStaking::scores(alice()).unwrap(), - ScorePayment { score: 500, total_reward: 0, last_round_reward: 0, unpaid_reward: 0 } + ScorePayment { + score: 500, + total_reward: 0, + last_round_reward: 0, + unpaid_reward: 0, + token_staking_amount: 0, + } ); assert_eq!(ScoreStaking::total_score(), 500); assert_eq!(ScoreStaking::score_user_count(), 1); @@ -180,6 +186,7 @@ fn score_staking_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward(), + token_staking_amount: 0, } ); @@ -198,6 +205,7 @@ fn score_staking_works() { total_reward: 2 * round_reward(), last_round_reward: round_reward(), unpaid_reward: 2 * round_reward(), + token_staking_amount: 0, } ); @@ -219,6 +227,7 @@ fn score_staking_works() { total_reward: 2 * round_reward() + round_reward() * 3 / 4, last_round_reward: round_reward() * 3 / 4, unpaid_reward: 2 * round_reward() + round_reward() * 3 / 4, + token_staking_amount: 0, } ); @@ -250,6 +259,7 @@ fn score_staking_works() { unpaid_reward: 2 * round_reward() + round_reward() * 3 / 4 + round_reward() * 2 * 3 / (3 * 5), + token_staking_amount: 0, } ); @@ -260,6 +270,7 @@ fn score_staking_works() { total_reward: round_reward() * 1 * 4 / (3 * 5), last_round_reward: round_reward() * 1 * 4 / (3 * 5), unpaid_reward: round_reward() * 1 * 4 / (3 * 5), + token_staking_amount: 0, } ); @@ -309,6 +320,7 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward(), + token_staking_amount: 0, } ); @@ -324,6 +336,7 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward() - 200, + token_staking_amount: 0, } ); @@ -339,6 +352,7 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: 0, + token_staking_amount: 0, } ); diff --git a/pallets/score-staking/src/types.rs b/pallets/score-staking/src/types.rs index 1456f4e67d..6f39d672b3 100644 --- a/pallets/score-staking/src/types.rs +++ b/pallets/score-staking/src/types.rs @@ -83,4 +83,5 @@ pub struct ScorePayment { pub total_reward: Balance, pub last_round_reward: Balance, pub unpaid_reward: Balance, + pub token_staking_amount: Balance, } From f63032c11fbf75d18df8010877e15bf9db21dd4b Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 8 Aug 2024 15:34:49 +0000 Subject: [PATCH 22/61] adding update_token_staking_amount call to pallet score-staking --- pallets/score-staking/src/lib.rs | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/pallets/score-staking/src/lib.rs b/pallets/score-staking/src/lib.rs index fe6bf48f8a..5e4ac4f718 100644 --- a/pallets/score-staking/src/lib.rs +++ b/pallets/score-staking/src/lib.rs @@ -46,6 +46,7 @@ use frame_support::{ traits::{Currency, Imbalance, LockableCurrency, ReservableCurrency, StorageVersion}, }; use pallet_parachain_staking as ParaStaking; +use pallet_teebag as Teebag; use sp_core::crypto::AccountId32; use sp_runtime::{traits::CheckedSub, Perbill, SaturatedConversion}; @@ -85,7 +86,7 @@ pub mod pallet { pub struct Pallet(_); #[pallet::config] - pub trait Config: frame_system::Config + ParaStaking::Config { + pub trait Config: frame_system::Config + ParaStaking::Config + Teebag::Config { type Currency: Currency + ReservableCurrency + LockableCurrency; @@ -150,6 +151,7 @@ pub mod pallet { ScoreUpdated { who: Identity, new_score: Score }, ScoreRemoved { who: Identity }, ScoreCleared {}, + TokenStakingAmountUpdated { account: T::AccountId, amount: BalanceOf }, RewardDistributionStarted { total: BalanceOf, distributed: BalanceOf }, RewardDistributionCompleted {}, RewardClaimed { who: T::AccountId, amount: BalanceOf }, @@ -432,6 +434,33 @@ pub mod pallet { let payment = Scores::::get(&account).ok_or(Error::::UserNotExist)?; Self::claim(origin, payment.unpaid_reward) } + + #[pallet::call_index(9)] + #[pallet::weight((195_000_000, DispatchClass::Normal))] + pub fn update_token_staking_amount( + origin: OriginFor, + account: T::AccountId, + amount: BalanceOf, + ) -> DispatchResultWithPostInfo { + let sender = ensure_signed(origin.clone())?; + + let _ = Teebag::Pallet::::enclave_registry(&sender) + .ok_or(Error::::UnauthorizedOrigin)?; + + Scores::::try_mutate(&account, |payment| { + let mut p = payment.take().ok_or(Error::::UserNotExist)?; + p.token_staking_amount = amount; + *payment = Some(p); + + Self::deposit_event(Event::TokenStakingAmountUpdated { + account: account.clone(), + amount, + }); + Ok::<(), Error>(()) + })?; + + Ok(Pays::No.into()) + } } } From 72160ab6e740958e632f7db6c89a97b2be4fdfe7 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 8 Aug 2024 15:35:42 +0000 Subject: [PATCH 23/61] adding missing dependencies --- Cargo.lock | 2 ++ pallets/score-staking/Cargo.toml | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 1a9fc541df..6d99ca9ceb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8018,6 +8018,8 @@ dependencies = [ "num-integer", "pallet-balances", "pallet-parachain-staking", + "pallet-teebag", + "pallet-timestamp", "parity-scale-codec", "scale-info", "serde", diff --git a/pallets/score-staking/Cargo.toml b/pallets/score-staking/Cargo.toml index fb0497ccbb..c8fc2f2b34 100644 --- a/pallets/score-staking/Cargo.toml +++ b/pallets/score-staking/Cargo.toml @@ -14,12 +14,14 @@ serde_json = { workspace = true, features = ["alloc"] } frame-benchmarking = { workspace = true, optional = true } frame-support = { workspace = true } frame-system = { workspace = true } +pallet-timestamp = { workspace = true } sp-core = { workspace = true } sp-runtime = { workspace = true } sp-std = { workspace = true } core-primitives = { workspace = true } pallet-parachain-staking = { workspace = true } +pallet-teebag = { workspace = true } [dev-dependencies] sp-io = { workspace = true } @@ -44,12 +46,15 @@ std = [ "pallet-balances/std", "core-primitives/std", "pallet-parachain-staking/std", + "pallet-teebag/std", + "pallet-timestamp/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", "sp-runtime/runtime-benchmarks", + "pallet-timestamp/runtime-benchmarks", ] try-runtime = [ "frame-support/try-runtime", From 58c7936a27f946bfb5517310672b879adce752e2 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 8 Aug 2024 15:35:56 +0000 Subject: [PATCH 24/61] updating score-staking mock --- pallets/score-staking/src/mock.rs | 34 +++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/pallets/score-staking/src/mock.rs b/pallets/score-staking/src/mock.rs index a013ca9edc..443c0426b8 100644 --- a/pallets/score-staking/src/mock.rs +++ b/pallets/score-staking/src/mock.rs @@ -62,6 +62,7 @@ construct_runtime!( Balances: pallet_balances, ParachainStaking: pallet_parachain_staking, ScoreStaking: pallet_score_staking, + Teebag: pallet_teebag, } ); @@ -179,6 +180,32 @@ impl pallet_score_staking::Config for Test { type MaxScoreUserCount = ConstU32<2>; } +parameter_types! { + pub const MinimumPeriod: u64 = 6000 / 2; +} + +pub type Moment = u64; + +impl pallet_timestamp::Config for Test { + type Moment = Moment; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); +} + +parameter_types! { + pub const MomentsPerDay: u64 = 86_400_000; // [ms/d] +} + +impl pallet_teebag::Config for Test { + type RuntimeEvent = RuntimeEvent; + type MomentsPerDay = MomentsPerDay; + type SetAdminOrigin = EnsureRoot; + type MaxEnclaveIdentifier = ConstU32<1>; + type MaxAuthorizedEnclave = ConstU32<2>; + type WeightInfo = (); +} + pub fn alice() -> AccountId { AccountKeyring::Alice.to_account_id() } @@ -197,6 +224,13 @@ pub fn new_test_ext(fast_round: bool) -> sp_io::TestExternalities { .assimilate_storage(&mut t) .unwrap(); + let teebag = pallet_teebag::GenesisConfig:: { + allow_sgx_debug_mode: true, + admin: Some(AccountKeyring::Alice.to_account_id()), + mode: pallet_teebag::OperationalMode::Production, + }; + teebag.assimilate_storage(&mut t).unwrap(); + let genesis_config: pallet_score_staking::GenesisConfig = crate::GenesisConfig { state: PoolState::Stopped, marker: Default::default() }; From fe012ec09fd276db032bd7ca8ec2b55fb07de25a Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 8 Aug 2024 15:36:14 +0000 Subject: [PATCH 25/61] adding tests --- pallets/score-staking/src/tests.rs | 83 +++++++++++++++++++++++++++++- 1 file changed, 82 insertions(+), 1 deletion(-) diff --git a/pallets/score-staking/src/tests.rs b/pallets/score-staking/src/tests.rs index 3783194b98..4a08670e90 100644 --- a/pallets/score-staking/src/tests.rs +++ b/pallets/score-staking/src/tests.rs @@ -18,8 +18,9 @@ use crate::{mock::*, Error, Event, PoolState, RoundInfo, RoundSetting, ScorePayment}; use core_primitives::{DAYS, YEARS}; -use frame_support::{assert_err, assert_ok}; +use frame_support::{assert_err, assert_noop, assert_ok}; use pallet_parachain_staking::Delegator; +use pallet_teebag::{Enclave, WorkerType}; use sp_runtime::Perbill; fn round_reward() -> Balance { @@ -363,3 +364,83 @@ fn claim_works() { ); }); } + +#[test] +fn update_token_staking_amount_works() { + new_test_ext(false).execute_with(|| { + let enclave = Enclave::new(WorkerType::Identity); + pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); + + run_to_block(2); + assert_ok!(ScoreStaking::start_pool(RuntimeOrigin::root())); + + run_to_block(3); + pallet_parachain_staking::DelegatorState::::insert( + alice(), + Delegator::new(bob(), bob(), 900), + ); + + assert_ok!(ScoreStaking::update_score(RuntimeOrigin::signed(alice()), alice().into(), 500)); + assert_eq!( + ScoreStaking::scores(alice()).unwrap(), + ScorePayment { + score: 500, + total_reward: 0, + last_round_reward: 0, + unpaid_reward: 0, + token_staking_amount: 0, + } + ); + + assert_ok!(ScoreStaking::update_token_staking_amount( + RuntimeOrigin::signed(alice()), + alice().into(), + 1000 + )); + + assert_eq!( + ScoreStaking::scores(alice()).unwrap(), + ScorePayment { + score: 500, + total_reward: 0, + last_round_reward: 0, + unpaid_reward: 0, + token_staking_amount: 1000, + } + ); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::TokenStakingAmountUpdated { account: alice(), amount: 1000 }, + )); + }) +} + +#[test] +fn update_token_staking_amount_origin_check_works() { + new_test_ext(false).execute_with(|| { + assert_noop!( + ScoreStaking::update_token_staking_amount( + RuntimeOrigin::signed(alice()), + alice().into(), + 1000 + ), + Error::::UnauthorizedOrigin + ); + }) +} + +#[test] +fn update_token_staking_amount_existing_user_check_works() { + new_test_ext(false).execute_with(|| { + let enclave = Enclave::new(WorkerType::Identity); + pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); + + assert_noop!( + ScoreStaking::update_token_staking_amount( + RuntimeOrigin::signed(alice()), + alice().into(), + 1000 + ), + Error::::UserNotExist + ); + }) +} From 1bcaf5e3b21a2e77c90daabf9b79af535e51f231 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 14 Aug 2024 13:40:58 +0000 Subject: [PATCH 26/61] fixing Cargo.toml format issue --- tee-worker/app-libs/parentchain-interface/Cargo.toml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/Cargo.toml b/tee-worker/app-libs/parentchain-interface/Cargo.toml index 98cdf15155..3943dbb1ee 100644 --- a/tee-worker/app-libs/parentchain-interface/Cargo.toml +++ b/tee-worker/app-libs/parentchain-interface/Cargo.toml @@ -36,8 +36,8 @@ sp-runtime = { default-features = false, git = "https://github.com/paritytech/su # litentry lc-dynamic-assertion = { path = "../../litentry/core/dynamic-assertion", default-features = false } lc-evm-dynamic-assertions = { path = "../../litentry/core/evm-dynamic-assertions", default-features = false } -litentry-primitives = { path = "../../litentry/primitives", default-features = false } litentry-hex-utils = { path = "../../../primitives/hex", default-features = false } +litentry-primitives = { path = "../../litentry/primitives", default-features = false } sp-std = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } @@ -50,7 +50,6 @@ itp-test = { path = "../../core-primitives/test" } itp-top-pool-author = { path = "../../core-primitives/top-pool-author", features = ["mocks"] } itc-parentchain-test = { path = "../../core/parentchain/test" } - [features] default = ["std"] std = [ From 169582dd373d9e544d69e66e4188639e87f1eb4b Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 14 Aug 2024 13:48:52 +0000 Subject: [PATCH 27/61] adding extrinsic to complete reward distribution --- pallets/score-staking/src/lib.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/pallets/score-staking/src/lib.rs b/pallets/score-staking/src/lib.rs index 5e4ac4f718..acab199e4a 100644 --- a/pallets/score-staking/src/lib.rs +++ b/pallets/score-staking/src/lib.rs @@ -443,7 +443,6 @@ pub mod pallet { amount: BalanceOf, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin.clone())?; - let _ = Teebag::Pallet::::enclave_registry(&sender) .ok_or(Error::::UnauthorizedOrigin)?; @@ -461,6 +460,17 @@ pub mod pallet { Ok(Pays::No.into()) } + + #[pallet::call_index(10)] + #[pallet::weight((195_000_000, DispatchClass::Normal))] + pub fn complete_reward_distribution(origin: OriginFor) -> DispatchResultWithPostInfo { + let sender = ensure_signed(origin.clone())?; + let _ = Teebag::Pallet::::enclave_registry(&sender) + .ok_or(Error::::UnauthorizedOrigin)?; + Self::deposit_event(Event::RewardDistributionCompleted {}); + + Ok(Pays::No.into()) + } } } From da4165987659fdfefb9059e9919de4fdbcf5fbf7 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 14 Aug 2024 13:49:15 +0000 Subject: [PATCH 28/61] adding tests --- pallets/score-staking/src/tests.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/pallets/score-staking/src/tests.rs b/pallets/score-staking/src/tests.rs index 4a08670e90..de918d2062 100644 --- a/pallets/score-staking/src/tests.rs +++ b/pallets/score-staking/src/tests.rs @@ -444,3 +444,27 @@ fn update_token_staking_amount_existing_user_check_works() { ); }) } + +#[test] +fn complete_reward_distribution_works() { + new_test_ext(false).execute_with(|| { + let enclave = Enclave::new(WorkerType::Identity); + pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); + + assert_ok!(ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()),)); + + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionCompleted {}, + )); + }); +} + +#[test] +fn complete_reward_distribution_origin_check_works() { + new_test_ext(false).execute_with(|| { + assert_noop!( + ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()),), + Error::::UnauthorizedOrigin + ); + }); +} From 7366a47320e9a9f5d8ed57652f63dd7a68bec977 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 14 Aug 2024 14:09:46 +0000 Subject: [PATCH 29/61] updating node-api metadata, including staking-score calls --- .../node-api/metadata/src/lib.rs | 12 ++++--- .../metadata/src/pallet_score_staking.rs | 36 +++++++++++++++++++ 2 files changed, 44 insertions(+), 4 deletions(-) create mode 100644 tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs diff --git a/tee-worker/core-primitives/node-api/metadata/src/lib.rs b/tee-worker/core-primitives/node-api/metadata/src/lib.rs index 1705582b90..ab80b24a6d 100644 --- a/tee-worker/core-primitives/node-api/metadata/src/lib.rs +++ b/tee-worker/core-primitives/node-api/metadata/src/lib.rs @@ -22,9 +22,10 @@ use crate::{ error::Result, pallet_balances::BalancesCallIndexes, pallet_evm_assertion::EvmAssertionsCallIndexes, pallet_imp::IMPCallIndexes, - pallet_proxy::ProxyCallIndexes, pallet_system::SystemConstants, - pallet_teebag::TeebagCallIndexes, pallet_timestamp::TimestampCallIndexes, - pallet_utility::UtilityCallIndexes, pallet_vcmp::VCMPCallIndexes, + pallet_proxy::ProxyCallIndexes, pallet_score_staking::ScoreStakingCallIndexes, + pallet_system::SystemConstants, pallet_teebag::TeebagCallIndexes, + pallet_timestamp::TimestampCallIndexes, pallet_utility::UtilityCallIndexes, + pallet_vcmp::VCMPCallIndexes, }; use codec::{Decode, Encode}; use sp_core::storage::StorageKey; @@ -37,6 +38,7 @@ pub mod pallet_balances; pub mod pallet_evm_assertion; pub mod pallet_imp; pub mod pallet_proxy; +pub mod pallet_score_staking; pub mod pallet_system; pub mod pallet_teebag; pub mod pallet_utility; @@ -58,6 +60,7 @@ pub trait NodeMetadataTrait: + BalancesCallIndexes + TimestampCallIndexes + EvmAssertionsCallIndexes + + ScoreStakingCallIndexes { } @@ -70,7 +73,8 @@ impl< + ProxyCallIndexes + BalancesCallIndexes + TimestampCallIndexes - + EvmAssertionsCallIndexes, + + EvmAssertionsCallIndexes + + ScoreStakingCallIndexes, > NodeMetadataTrait for T { } diff --git a/tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs b/tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs new file mode 100644 index 0000000000..9450e36c01 --- /dev/null +++ b/tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs @@ -0,0 +1,36 @@ +/* + Copyright 2021 Integritee AG and Supercomputing Systems AG + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +*/ +use crate::{error::Result, NodeMetadata}; + +/// Pallet' name: +pub const SCORE_STAKING: &str = "ScoreStaking"; + +// we only list the extrinsics that we care +pub trait ScoreStakingCallIndexes { + fn update_token_staking_amount_call_indexes(&self) -> Result<[u8; 2]>; + + fn complete_reward_distribution_call_indexes(&self) -> Result<[u8; 2]>; +} + +impl ScoreStakingCallIndexes for NodeMetadata { + fn update_token_staking_amount_call_indexes(&self) -> Result<[u8; 2]> { + self.call_indexes(SCORE_STAKING, "update_token_staking_amount") + } + fn complete_reward_distribution_call_indexes(&self) -> Result<[u8; 2]> { + self.call_indexes(SCORE_STAKING, "complete_reward_distribution") + } +} From 02d90f5d8ee9534c43bc35e15795e2eed2d74bfd Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 14 Aug 2024 14:42:28 +0000 Subject: [PATCH 30/61] updating metadata mocks --- .../node-api/metadata/src/metadata_mocks.rs | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs b/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs index adf13c8cf8..5918d141e3 100644 --- a/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs +++ b/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs @@ -18,9 +18,10 @@ use crate::{ error::Result, pallet_balances::BalancesCallIndexes, pallet_evm_assertion::EvmAssertionsCallIndexes, pallet_imp::IMPCallIndexes, - pallet_proxy::ProxyCallIndexes, pallet_system::SystemConstants, - pallet_teebag::TeebagCallIndexes, pallet_timestamp::TimestampCallIndexes, - pallet_utility::UtilityCallIndexes, pallet_vcmp::VCMPCallIndexes, runtime_call::RuntimeCall, + pallet_proxy::ProxyCallIndexes, pallet_score_staking::ScoreStakingCallIndexes, + pallet_system::SystemConstants, pallet_teebag::TeebagCallIndexes, + pallet_timestamp::TimestampCallIndexes, pallet_utility::UtilityCallIndexes, + pallet_vcmp::VCMPCallIndexes, runtime_call::RuntimeCall, }; use codec::{Decode, Encode}; @@ -88,6 +89,11 @@ pub struct NodeMetadataMock { timestamp_set: u8, runtime_spec_version: u32, runtime_transaction_version: u32, + + //ScoreStaking + score_staking_module: u8, + update_token_staking_amount: u8, + complete_reward_distribution: u8, } impl NodeMetadataMock { @@ -143,6 +149,10 @@ impl NodeMetadataMock { timestamp_set: 0, runtime_spec_version: 25, runtime_transaction_version: 4, + + score_staking_module: 100u8, + update_token_staking_amount: 0u8, + complete_reward_distribution: 1u8, } } } @@ -177,6 +187,16 @@ impl TeebagCallIndexes for NodeMetadataMock { } } +impl ScoreStakingCallIndexes for NodeMetadataMock { + fn update_token_staking_amount_call_indexes(&self) -> Result<[u8; 2]> { + Ok([self.score_staking_module, self.update_token_staking_amount]) + } + + fn complete_reward_distribution_call_indexes(&self) -> Result<[u8; 2]> { + Ok([self.score_staking_module, self.complete_reward_distribution]) + } +} + impl IMPCallIndexes for NodeMetadataMock { fn link_identity_call_indexes(&self) -> Result<[u8; 2]> { Ok([self.imp_module, self.imp_link_identity]) From fe1504708e2a1c70102e690a2b8c09ace876187d Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 14 Aug 2024 14:43:56 +0000 Subject: [PATCH 31/61] injecting node metadata repository to ParentchainEventHandler --- .../src/integritee/event_handler.rs | 15 +++++++++++---- .../src/initialization/global_components.rs | 6 +++++- .../src/initialization/parentchain/common.rs | 1 + 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index a0d925ea12..f7edc9e361 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -21,6 +21,7 @@ pub use ita_sgx_runtime::{Balance, Index, Runtime}; use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; use itc_parentchain_indirect_calls_executor::error::Error; use itp_api_client_types::StaticEvent; +use itp_node_api::metadata::provider::AccessNodeMetadata; use itp_ocall_api::EnclaveOnChainOCallApi; use itp_sgx_externalities::{SgxExternalities, SgxExternalitiesTrait}; use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation}; @@ -48,14 +49,19 @@ use std::{collections::BTreeMap, format, println, string::String, sync::Arc}; pub struct ParentchainEventHandler< OCallApi: EnclaveOnChainOCallApi, HS: HandleState, + NMR: AccessNodeMetadata, > { pub assertion_repository: Arc, pub ocall_api: Arc, pub state_handler: Arc, + pub node_metadata_repository: Arc, } -impl> - ParentchainEventHandler +impl ParentchainEventHandler +where + OCallApi: EnclaveOnChainOCallApi, + HS: HandleState, + NMR: AccessNodeMetadata, { fn link_identity>( executor: &Executor, @@ -330,12 +336,13 @@ fn decode_storage_key(raw_key: Vec) -> Option> { decode_hex(hex_key).ok() } -impl HandleParentchainEvents - for ParentchainEventHandler +impl HandleParentchainEvents + for ParentchainEventHandler where Executor: IndirectExecutor, OCallApi: EnclaveOnChainOCallApi, HS: HandleState, + NMR: AccessNodeMetadata, { fn handle_events( &self, diff --git a/tee-worker/enclave-runtime/src/initialization/global_components.rs b/tee-worker/enclave-runtime/src/initialization/global_components.rs index 16edb29166..939d69fe18 100644 --- a/tee-worker/enclave-runtime/src/initialization/global_components.rs +++ b/tee-worker/enclave-runtime/src/initialization/global_components.rs @@ -177,7 +177,11 @@ pub type IntegriteeParentchainIndirectCallsExecutor = IndirectCallsExecutor< EnclaveTopPoolAuthor, EnclaveNodeMetadataRepository, EventCreator, - integritee::ParentchainEventHandler, + integritee::ParentchainEventHandler< + EnclaveOCallApi, + EnclaveStateHandler, + EnclaveNodeMetadataRepository, + >, EnclaveTrustedCallSigned, EnclaveGetter, >; diff --git a/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs b/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs index 2d34581a2b..40fa90d6c7 100644 --- a/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs +++ b/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs @@ -75,6 +75,7 @@ pub(crate) fn create_integritee_parentchain_block_importer( assertion_repository: repository, ocall_api: ocall_api.clone(), state_handler, + node_metadata_repository: node_metadata_repository.clone(), }; let stf_enclave_signer = Arc::new(EnclaveStfEnclaveSigner::new( From a4465dc8f93cecba860fc81ec901a7c4769845f3 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 15 Aug 2024 07:45:58 +0000 Subject: [PATCH 32/61] sending extrinsics to the parentchain to update staking scores and complete rewards distribution --- .../src/integritee/event_handler.rs | 57 +++++++++++++------ 1 file changed, 40 insertions(+), 17 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index f7edc9e361..79c72adfca 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -21,7 +21,10 @@ pub use ita_sgx_runtime::{Balance, Index, Runtime}; use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; use itc_parentchain_indirect_calls_executor::error::Error; use itp_api_client_types::StaticEvent; -use itp_node_api::metadata::provider::AccessNodeMetadata; +use itp_node_api::metadata::{ + pallet_imp::IMPCallIndexes, pallet_score_staking::ScoreStakingCallIndexes, + provider::AccessNodeMetadata, NodeMetadataTrait, +}; use itp_ocall_api::EnclaveOnChainOCallApi; use itp_sgx_externalities::{SgxExternalities, SgxExternalitiesTrait}; use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation}; @@ -32,11 +35,11 @@ use itp_types::{ events::ParentchainBlockProcessed, AccountId, FilterEvents, HandleParentchainEvents, ParentchainEventProcessingError, ParentchainId, ProcessedEventsArtifacts, }, - Delegator, RsaRequest, H256, + Delegator, OpaqueCall, RsaRequest, H256, }; use lc_dynamic_assertion::AssertionLogicRepository; use lc_evm_dynamic_assertions::repository::EvmAssertionRepository; -// use lc_parachain_extrinsic_task_sender::{ParachainExtrinsicSender, SendParachainExtrinsic}; +use lc_parachain_extrinsic_task_sender::{ParachainExtrinsicSender, SendParachainExtrinsic}; use litentry_hex_utils::decode_hex; use litentry_primitives::{Assertion, Identity, ValidationData, Web3Network}; use log::*; @@ -46,15 +49,11 @@ use sp_runtime::traits::Header; use sp_std::vec::Vec; use std::{collections::BTreeMap, format, println, string::String, sync::Arc}; -pub struct ParentchainEventHandler< - OCallApi: EnclaveOnChainOCallApi, - HS: HandleState, - NMR: AccessNodeMetadata, -> { +pub struct ParentchainEventHandler { pub assertion_repository: Arc, pub ocall_api: Arc, - pub state_handler: Arc, - pub node_metadata_repository: Arc, + pub state_handler: Arc, + pub node_metadata_repository: Arc, } impl ParentchainEventHandler @@ -62,6 +61,7 @@ where OCallApi: EnclaveOnChainOCallApi, HS: HandleState, NMR: AccessNodeMetadata, + NMR::MetadataType: NodeMetadataTrait, { fn link_identity>( executor: &Executor, @@ -305,7 +305,16 @@ where }) .map_err(|_| Error::Other("Failed to get id graphs".into()))?; - let mut staking_amounts: BTreeMap = BTreeMap::new(); + let extrinsic_sender = ParachainExtrinsicSender::new(); + let update_token_staking_amount_call_index = self + .node_metadata_repository + .get_from_metadata(|m| m.update_token_staking_amount_call_indexes()) + .map_err(|_| { + Error::Other( + "Metadata retrieval for update_token_staking_amount_call_indexes failed".into(), + ) + })? + .map_err(|_| Error::Other("Invalid metadata".into()))?; for account_id in account_ids.iter() { let default_id_graph = Vec::new(); @@ -317,15 +326,28 @@ where Some(delegator.total) }) .sum(); - staking_amounts.insert(account_id.clone(), staking_amount); + let call = OpaqueCall::from_tuple(&( + update_token_staking_amount_call_index.clone(), + account_id, + staking_amount, + )); + extrinsic_sender.send(call); } - // let extrinsic_sender = ParachainExtrinsicSender::new(); + let complete_reward_distribution_call_index = self + .node_metadata_repository + .get_from_metadata(|m| m.complete_reward_distribution_call_indexes()) + .map_err(|_| { + Error::Other( + "Metadata retrieval for complete_reward_distribution_call_indexes failed" + .into(), + ) + })? + .map_err(|_| Error::Other("Invalid metadata".into()))?; - // TODO: after the new calls are created in ScoreStaking pallet - // - create a call to update the scores for each account with the new rewards - // - submit the call to the extrinsic sender - // - send another extrinsic to indicate that the reward distribution has finished + let complete_reward_distribution_call = + OpaqueCall::from_tuple(&(complete_reward_distribution_call_index.clone())); + extrinsic_sender.send(complete_reward_distribution_call); Ok(()) } @@ -343,6 +365,7 @@ where OCallApi: EnclaveOnChainOCallApi, HS: HandleState, NMR: AccessNodeMetadata, + NMR::MetadataType: NodeMetadataTrait, { fn handle_events( &self, From cd1ea06a6f5a4254f1b0f51ee4c026673221ee4a Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 15 Aug 2024 09:55:05 +0000 Subject: [PATCH 33/61] making score-staking pallet loosely coupled to teebag --- pallets/score-staking/src/lib.rs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/pallets/score-staking/src/lib.rs b/pallets/score-staking/src/lib.rs index acab199e4a..2042f682ad 100644 --- a/pallets/score-staking/src/lib.rs +++ b/pallets/score-staking/src/lib.rs @@ -46,7 +46,6 @@ use frame_support::{ traits::{Currency, Imbalance, LockableCurrency, ReservableCurrency, StorageVersion}, }; use pallet_parachain_staking as ParaStaking; -use pallet_teebag as Teebag; use sp_core::crypto::AccountId32; use sp_runtime::{traits::CheckedSub, Perbill, SaturatedConversion}; @@ -69,6 +68,10 @@ pub trait AccountIdConvert { fn convert(account: AccountId32) -> T::AccountId; } +pub trait TokenStakingAuthorizer { + fn can_update_staking(sender: &T::AccountId) -> bool; +} + #[frame_support::pallet] pub mod pallet { use super::*; @@ -86,7 +89,7 @@ pub mod pallet { pub struct Pallet(_); #[pallet::config] - pub trait Config: frame_system::Config + ParaStaking::Config + Teebag::Config { + pub trait Config: frame_system::Config + ParaStaking::Config { type Currency: Currency + ReservableCurrency + LockableCurrency; @@ -103,6 +106,8 @@ pub mod pallet { type AdminOrigin: EnsureOrigin; /// AccountId converter type AccountIdConvert: AccountIdConvert; + /// Token staking authorization + type TokenStakingAuthorizer: TokenStakingAuthorizer; } #[pallet::error] @@ -443,8 +448,10 @@ pub mod pallet { amount: BalanceOf, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin.clone())?; - let _ = Teebag::Pallet::::enclave_registry(&sender) - .ok_or(Error::::UnauthorizedOrigin)?; + ensure!( + T::TokenStakingAuthorizer::can_update_staking(&sender), + Error::::UnauthorizedOrigin + ); Scores::::try_mutate(&account, |payment| { let mut p = payment.take().ok_or(Error::::UserNotExist)?; @@ -465,8 +472,11 @@ pub mod pallet { #[pallet::weight((195_000_000, DispatchClass::Normal))] pub fn complete_reward_distribution(origin: OriginFor) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin.clone())?; - let _ = Teebag::Pallet::::enclave_registry(&sender) - .ok_or(Error::::UnauthorizedOrigin)?; + ensure!( + T::TokenStakingAuthorizer::can_update_staking(&sender), + Error::::UnauthorizedOrigin + ); + Self::deposit_event(Event::RewardDistributionCompleted {}); Ok(Pays::No.into()) From 375f7e93f81c168dd9b0557ab8e7346d5e355cb0 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 15 Aug 2024 09:59:50 +0000 Subject: [PATCH 34/61] updating mock --- pallets/score-staking/src/mock.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/pallets/score-staking/src/mock.rs b/pallets/score-staking/src/mock.rs index 443c0426b8..d69b68905d 100644 --- a/pallets/score-staking/src/mock.rs +++ b/pallets/score-staking/src/mock.rs @@ -178,6 +178,7 @@ impl pallet_score_staking::Config for Test { type YearlyIssuance = ConstU128<{ 100_000_000 * UNIT }>; type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<2>; + type TokenStakingAuthorizer = pallet_teebag::Pallet; } parameter_types! { @@ -206,6 +207,12 @@ impl pallet_teebag::Config for Test { type WeightInfo = (); } +impl pallet_score_staking::TokenStakingAuthorizer for pallet_teebag::Pallet { + fn can_update_staking(sender: &::AccountId) -> bool { + pallet_teebag::Pallet::::enclave_registry(sender).is_some() + } +} + pub fn alice() -> AccountId { AccountKeyring::Alice.to_account_id() } From 448768e6887ddf70692795037dc50b1f3d14ee54 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 15 Aug 2024 10:00:02 +0000 Subject: [PATCH 35/61] updating runtimes --- runtime/litentry/src/lib.rs | 7 +++++++ runtime/rococo/src/lib.rs | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/runtime/litentry/src/lib.rs b/runtime/litentry/src/lib.rs index c6c0c5610d..3cdc21387a 100644 --- a/runtime/litentry/src/lib.rs +++ b/runtime/litentry/src/lib.rs @@ -1140,6 +1140,12 @@ impl pallet_score_staking::AccountIdConvert for IdentityAccountIdConver } } +impl pallet_score_staking::TokenStakingAuthorizer for pallet_teebag::Pallet { + fn can_update_staking(sender: &::AccountId) -> bool { + pallet_teebag::Pallet::::enclave_registry(sender).is_some() + } +} + impl pallet_score_staking::Config for Runtime { type Currency = Balances; type RuntimeEvent = RuntimeEvent; @@ -1149,6 +1155,7 @@ impl pallet_score_staking::Config for Runtime { type YearlyIssuance = ConstU128<{ 100_000_000 * UNIT }>; type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<1_000_000>; + type TokenStakingAuthorizer = pallet_teebag::Pallet; } impl runtime_common::BaseRuntimeRequirements for Runtime {} diff --git a/runtime/rococo/src/lib.rs b/runtime/rococo/src/lib.rs index c5237fabdb..3e8f0d76d0 100644 --- a/runtime/rococo/src/lib.rs +++ b/runtime/rococo/src/lib.rs @@ -1177,6 +1177,12 @@ impl pallet_score_staking::AccountIdConvert for IdentityAccountIdConver } } +impl pallet_score_staking::TokenStakingAuthorizer for pallet_teebag::Pallet { + fn can_update_staking(sender: &::AccountId) -> bool { + pallet_teebag::Pallet::::enclave_registry(sender).is_some() + } +} + impl pallet_score_staking::Config for Runtime { type Currency = Balances; type RuntimeEvent = RuntimeEvent; @@ -1185,6 +1191,7 @@ impl pallet_score_staking::Config for Runtime { type YearlyIssuance = ConstU128<{ 100_000_000 * UNIT }>; type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<1_000_000>; + type TokenStakingAuthorizer = pallet_teebag::Pallet; } impl runtime_common::BaseRuntimeRequirements for Runtime {} From 5c2dc8ff61ce53970060a6cdbbd6c9ae2a71cc9f Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 15 Aug 2024 10:18:31 +0000 Subject: [PATCH 36/61] removing TODO --- .../parentchain-interface/src/integritee/event_handler.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index 79c72adfca..e7cd0dda9e 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -262,7 +262,6 @@ where .map_err(|_| Error::Other("Failed to get multiple storages".into()))? .into_iter() .filter_map(|entry| { - // TODO: check of the key needs to be decoded here let storage_key = decode_storage_key(entry.key)?; let account_id = key_to_account_id(&storage_key)?; let delegator = entry.value?; From f440a5b05f0e733b6f03caa408c33847d6559fa7 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 15 Aug 2024 12:32:19 +0000 Subject: [PATCH 37/61] updating commend --- pallets/score-staking/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/score-staking/src/lib.rs b/pallets/score-staking/src/lib.rs index 2042f682ad..e30bdb8340 100644 --- a/pallets/score-staking/src/lib.rs +++ b/pallets/score-staking/src/lib.rs @@ -106,7 +106,7 @@ pub mod pallet { type AdminOrigin: EnsureOrigin; /// AccountId converter type AccountIdConvert: AccountIdConvert; - /// Token staking authorization + /// Token staking authorizer type TokenStakingAuthorizer: TokenStakingAuthorizer; } From d36294edb14d1b22f93df8a422cc5d3a5a78756f Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 15 Aug 2024 13:43:07 +0000 Subject: [PATCH 38/61] updating precompiles mock --- Cargo.lock | 1 + precompiles/score-staking/Cargo.toml | 2 ++ precompiles/score-staking/src/mock.rs | 28 +++++++++++++++++++++++++++ 3 files changed, 31 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index acdd1cc11d..87dafeb4aa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7479,6 +7479,7 @@ dependencies = [ "pallet-evm", "pallet-parachain-staking", "pallet-score-staking", + "pallet-teebag", "pallet-timestamp", "parity-scale-codec", "precompile-utils", diff --git a/precompiles/score-staking/Cargo.toml b/precompiles/score-staking/Cargo.toml index 4e79f4d180..4c98e9809c 100644 --- a/precompiles/score-staking/Cargo.toml +++ b/precompiles/score-staking/Cargo.toml @@ -6,6 +6,7 @@ version = '0.1.0' [dependencies] pallet-score-staking = { workspace = true } +pallet-teebag = { workspace = true } precompile-utils = { workspace = true } fp-evm = { workspace = true } @@ -37,6 +38,7 @@ std = [ "frame-system/std", "pallet-evm/std", "pallet-score-staking/std", + "pallet-teebag/std", "precompile-utils/std", "sp-core/std", "sp-io/std", diff --git a/precompiles/score-staking/src/mock.rs b/precompiles/score-staking/src/mock.rs index e36d492a74..b12076bd1a 100644 --- a/precompiles/score-staking/src/mock.rs +++ b/precompiles/score-staking/src/mock.rs @@ -66,6 +66,7 @@ construct_runtime!( Evm: pallet_evm, ParachainStaking: pallet_parachain_staking, ScoreStaking: pallet_score_staking, + Teebag: pallet_teebag, } ); @@ -179,6 +180,7 @@ impl pallet_score_staking::Config for Test { type YearlyIssuance = ConstU128<{ 100_000_000 * UNIT }>; type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<2>; + type TokenStakingAuthorizer = pallet_teebag::Pallet; } pub fn precompile_address() -> H160 { @@ -260,6 +262,25 @@ impl pallet_timestamp::Config for Test { type WeightInfo = (); } +parameter_types! { + pub const MomentsPerDay: u64 = 86_400_000; // [ms/d] +} + +impl pallet_teebag::Config for Test { + type RuntimeEvent = RuntimeEvent; + type MomentsPerDay = MomentsPerDay; + type SetAdminOrigin = EnsureRoot; + type MaxEnclaveIdentifier = ConstU32<1>; + type MaxAuthorizedEnclave = ConstU32<2>; + type WeightInfo = (); +} + +impl pallet_score_staking::TokenStakingAuthorizer for pallet_teebag::Pallet { + fn can_update_staking(sender: &::AccountId) -> bool { + pallet_teebag::Pallet::::enclave_registry(sender).is_some() + } +} + pub fn alice() -> AccountId { U8Wrapper(1u8).into() } @@ -274,6 +295,13 @@ pub fn new_test_ext(fast_round: bool) -> sp_io::TestExternalities { .assimilate_storage(&mut t) .unwrap(); + let teebag = pallet_teebag::GenesisConfig:: { + allow_sgx_debug_mode: true, + admin: Some(alice()), + mode: pallet_teebag::OperationalMode::Production, + }; + teebag.assimilate_storage(&mut t).unwrap(); + let genesis_config = pallet_score_staking::GenesisConfig { state: PoolState::Stopped, marker: Default::default(), From ad3c7c79ed1c4fc9d9254cd5191b11824e0d4ebc Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 15 Aug 2024 13:43:14 +0000 Subject: [PATCH 39/61] fixing precompiles tests --- precompiles/score-staking/src/tests.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/precompiles/score-staking/src/tests.rs b/precompiles/score-staking/src/tests.rs index b3e61b6e0e..405c45b22d 100644 --- a/precompiles/score-staking/src/tests.rs +++ b/precompiles/score-staking/src/tests.rs @@ -52,10 +52,12 @@ fn claim_is_ok() { // run to next reward distribution round, alice should win all rewards run_to_block(7); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardCalculated { - total: round_reward(), - distributed: round_reward(), - })); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + total: round_reward(), + distributed: round_reward(), + }, + )); assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { @@ -63,6 +65,7 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward(), + token_staking_amount: 0, } ); @@ -86,6 +89,7 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward() - 200, + token_staking_amount: 0, } ); @@ -109,6 +113,7 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: 0, + token_staking_amount: 0, } ); From 8e3e0e18f11db2ba9aa513e5440d8e94543e6c87 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 15 Aug 2024 14:11:05 +0000 Subject: [PATCH 40/61] fixing clippy issues --- pallets/score-staking/src/tests.rs | 6 +++--- .../src/integritee/event_handler.rs | 13 ++++++++----- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/pallets/score-staking/src/tests.rs b/pallets/score-staking/src/tests.rs index b9ddc71994..edad9b021f 100644 --- a/pallets/score-staking/src/tests.rs +++ b/pallets/score-staking/src/tests.rs @@ -441,7 +441,7 @@ fn update_token_staking_amount_works() { assert_ok!(ScoreStaking::update_token_staking_amount( RuntimeOrigin::signed(alice()), - alice().into(), + alice(), 1000 )); @@ -467,7 +467,7 @@ fn update_token_staking_amount_origin_check_works() { assert_noop!( ScoreStaking::update_token_staking_amount( RuntimeOrigin::signed(alice()), - alice().into(), + alice(), 1000 ), Error::::UnauthorizedOrigin @@ -484,7 +484,7 @@ fn update_token_staking_amount_existing_user_check_works() { assert_noop!( ScoreStaking::update_token_staking_amount( RuntimeOrigin::signed(alice()), - alice().into(), + alice(), 1000 ), Error::::UserNotExist diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index e7cd0dda9e..b891564e4e 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -22,8 +22,7 @@ use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; use itc_parentchain_indirect_calls_executor::error::Error; use itp_api_client_types::StaticEvent; use itp_node_api::metadata::{ - pallet_imp::IMPCallIndexes, pallet_score_staking::ScoreStakingCallIndexes, - provider::AccessNodeMetadata, NodeMetadataTrait, + pallet_score_staking::ScoreStakingCallIndexes, provider::AccessNodeMetadata, NodeMetadataTrait, }; use itp_ocall_api::EnclaveOnChainOCallApi; use itp_sgx_externalities::{SgxExternalities, SgxExternalitiesTrait}; @@ -326,11 +325,13 @@ where }) .sum(); let call = OpaqueCall::from_tuple(&( - update_token_staking_amount_call_index.clone(), + update_token_staking_amount_call_index, account_id, staking_amount, )); - extrinsic_sender.send(call); + extrinsic_sender + .send(call) + .map_err(|_| Error::Other("Failed to send extrinsic".into()))?; } let complete_reward_distribution_call_index = self @@ -346,7 +347,9 @@ where let complete_reward_distribution_call = OpaqueCall::from_tuple(&(complete_reward_distribution_call_index.clone())); - extrinsic_sender.send(complete_reward_distribution_call); + extrinsic_sender.send(complete_reward_distribution_call).map_err(|_| { + Error::Other("Failed to send complete_reward_distribution_call extrinsic".into()) + })?; Ok(()) } From 844dbd0ee9ff5c26fa2a76a2646f03ee0a295103 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 21 Aug 2024 15:32:37 +0000 Subject: [PATCH 41/61] adding trusted calls to avoid sending duplicated extrinsics on multiworker setup --- tee-worker/app-libs/stf/src/trusted_call.rs | 36 ++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/tee-worker/app-libs/stf/src/trusted_call.rs b/tee-worker/app-libs/stf/src/trusted_call.rs index 3f0277f54b..2d738fd0f4 100644 --- a/tee-worker/app-libs/stf/src/trusted_call.rs +++ b/tee-worker/app-libs/stf/src/trusted_call.rs @@ -40,7 +40,8 @@ pub use ita_sgx_runtime::{ ParentchainInstanceTargetB, ParentchainLitentry, Runtime, System, VERSION as SIDECHAIN_VERSION, }; use itp_node_api::metadata::{ - pallet_system::SystemConstants, provider::AccessNodeMetadata, NodeMetadataTrait, + pallet_score_staking::ScoreStakingCallIndexes, pallet_system::SystemConstants, + provider::AccessNodeMetadata, NodeMetadataTrait, }; use itp_node_api_metadata::{pallet_imp::IMPCallIndexes, pallet_vcmp::VCMPCallIndexes}; use itp_stf_interface::ExecuteCall; @@ -142,6 +143,10 @@ pub enum TrustedCall { send_erroneous_parentchain_call(Identity), #[codec(index = 25)] maybe_create_id_graph(Identity, Identity), + #[codec(index = 26)] + update_token_staking_amount(Identity, AccountId, Balance), + #[codec(index = 27)] + reward_distribution_completed(Identity), // original integritee trusted calls, starting from index 50 #[codec(index = 50)] @@ -228,6 +233,8 @@ impl TrustedCall { Self::handle_vcmp_error(sender_identity, ..) => sender_identity, Self::send_erroneous_parentchain_call(sender_identity) => sender_identity, Self::maybe_create_id_graph(sender_identity, ..) => sender_identity, + Self::update_token_staking_amount(sender_identity, ..) => sender_identity, + Self::reward_distribution_completed(sender_identity) => sender_identity, #[cfg(feature = "development")] Self::remove_identity(sender_identity, ..) => sender_identity, Self::request_batch_vc(sender_identity, ..) => sender_identity, @@ -973,6 +980,33 @@ where Err(e) => warn!("maybe_create_id_graph NOK: {:?}", e), }; + Ok(TrustedCallResult::Empty) + }, + TrustedCall::update_token_staking_amount(signer, account_id, staking_amount) => { + let signer_account: AccountId32 = + signer.to_account_id().ok_or(Self::Error::InvalidAccount)?; + ensure_enclave_signer_account(&signer_account)?; + + let call = OpaqueCall::from_tuple(&( + node_metadata_repo + .get_from_metadata(|m| m.update_token_staking_amount_call_indexes())??, + account_id, + staking_amount, + )); + calls.push(ParentchainCall::Litentry(call)); + + Ok(TrustedCallResult::Empty) + }, + TrustedCall::reward_distribution_completed(signer) => { + let signer_account: AccountId32 = + signer.to_account_id().ok_or(Self::Error::InvalidAccount)?; + ensure_enclave_signer_account(&signer_account)?; + let call = OpaqueCall::from_tuple( + &(node_metadata_repo + .get_from_metadata(|m| m.complete_reward_distribution_call_indexes())??), + ); + calls.push(ParentchainCall::Litentry(call)); + Ok(TrustedCallResult::Empty) }, } From 51392f61806267c847cacde18c3754ddbbfd7ef8 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 21 Aug 2024 15:33:58 +0000 Subject: [PATCH 42/61] updating event_handler to submit the new trusted calls --- .../src/integritee/event_handler.rs | 49 ++++++------------- 1 file changed, 16 insertions(+), 33 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index b891564e4e..b87152e5c1 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -303,16 +303,7 @@ where }) .map_err(|_| Error::Other("Failed to get id graphs".into()))?; - let extrinsic_sender = ParachainExtrinsicSender::new(); - let update_token_staking_amount_call_index = self - .node_metadata_repository - .get_from_metadata(|m| m.update_token_staking_amount_call_indexes()) - .map_err(|_| { - Error::Other( - "Metadata retrieval for update_token_staking_amount_call_indexes failed".into(), - ) - })? - .map_err(|_| Error::Other("Invalid metadata".into()))?; + let enclave_account_id = executor.get_enclave_account().expect("no enclave account"); for account_id in account_ids.iter() { let default_id_graph = Vec::new(); @@ -324,32 +315,24 @@ where Some(delegator.total) }) .sum(); - let call = OpaqueCall::from_tuple(&( - update_token_staking_amount_call_index, - account_id, + let trusted_call = TrustedCall::update_token_staking_amount( + enclave_account_id.clone().into(), + account_id.clone(), staking_amount, - )); - extrinsic_sender - .send(call) - .map_err(|_| Error::Other("Failed to send extrinsic".into()))?; + ); + let signed_trusted_call = executor.sign_call_with_self(&trusted_call, &shard)?; + let trusted_operation = + TrustedOperation::::indirect_call(signed_trusted_call); + let encrypted_trusted_call = executor.encrypt(&trusted_operation.encode())?; + executor.submit_trusted_call(shard.clone(), encrypted_trusted_call); } - let complete_reward_distribution_call_index = self - .node_metadata_repository - .get_from_metadata(|m| m.complete_reward_distribution_call_indexes()) - .map_err(|_| { - Error::Other( - "Metadata retrieval for complete_reward_distribution_call_indexes failed" - .into(), - ) - })? - .map_err(|_| Error::Other("Invalid metadata".into()))?; - - let complete_reward_distribution_call = - OpaqueCall::from_tuple(&(complete_reward_distribution_call_index.clone())); - extrinsic_sender.send(complete_reward_distribution_call).map_err(|_| { - Error::Other("Failed to send complete_reward_distribution_call extrinsic".into()) - })?; + let trusted_call = TrustedCall::reward_distribution_completed(enclave_account_id.into()); + let signed_trusted_call = executor.sign_call_with_self(&trusted_call, &shard)?; + let trusted_operation = + TrustedOperation::::indirect_call(signed_trusted_call); + let encrypted_trusted_call = executor.encrypt(&trusted_operation.encode())?; + executor.submit_trusted_call(shard.clone(), encrypted_trusted_call); Ok(()) } From 0dbb5d675af0701e68efd4c8b2fdfd3373b7dcd6 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 21 Aug 2024 15:34:22 +0000 Subject: [PATCH 43/61] cleaning up dependencies that are not needed anymore --- .../src/integritee/event_handler.rs | 19 +++++-------------- .../src/initialization/global_components.rs | 6 +----- .../src/initialization/parentchain/common.rs | 1 - 3 files changed, 6 insertions(+), 20 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index b87152e5c1..53b330bb1b 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -21,9 +21,6 @@ pub use ita_sgx_runtime::{Balance, Index, Runtime}; use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; use itc_parentchain_indirect_calls_executor::error::Error; use itp_api_client_types::StaticEvent; -use itp_node_api::metadata::{ - pallet_score_staking::ScoreStakingCallIndexes, provider::AccessNodeMetadata, NodeMetadataTrait, -}; use itp_ocall_api::EnclaveOnChainOCallApi; use itp_sgx_externalities::{SgxExternalities, SgxExternalitiesTrait}; use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation}; @@ -34,11 +31,10 @@ use itp_types::{ events::ParentchainBlockProcessed, AccountId, FilterEvents, HandleParentchainEvents, ParentchainEventProcessingError, ParentchainId, ProcessedEventsArtifacts, }, - Delegator, OpaqueCall, RsaRequest, H256, + Delegator, RsaRequest, H256, }; use lc_dynamic_assertion::AssertionLogicRepository; use lc_evm_dynamic_assertions::repository::EvmAssertionRepository; -use lc_parachain_extrinsic_task_sender::{ParachainExtrinsicSender, SendParachainExtrinsic}; use litentry_hex_utils::decode_hex; use litentry_primitives::{Assertion, Identity, ValidationData, Web3Network}; use log::*; @@ -48,19 +44,16 @@ use sp_runtime::traits::Header; use sp_std::vec::Vec; use std::{collections::BTreeMap, format, println, string::String, sync::Arc}; -pub struct ParentchainEventHandler { +pub struct ParentchainEventHandler { pub assertion_repository: Arc, pub ocall_api: Arc, pub state_handler: Arc, - pub node_metadata_repository: Arc, } -impl ParentchainEventHandler +impl ParentchainEventHandler where OCallApi: EnclaveOnChainOCallApi, HS: HandleState, - NMR: AccessNodeMetadata, - NMR::MetadataType: NodeMetadataTrait, { fn link_identity>( executor: &Executor, @@ -343,14 +336,12 @@ fn decode_storage_key(raw_key: Vec) -> Option> { decode_hex(hex_key).ok() } -impl HandleParentchainEvents - for ParentchainEventHandler +impl HandleParentchainEvents + for ParentchainEventHandler where Executor: IndirectExecutor, OCallApi: EnclaveOnChainOCallApi, HS: HandleState, - NMR: AccessNodeMetadata, - NMR::MetadataType: NodeMetadataTrait, { fn handle_events( &self, diff --git a/tee-worker/enclave-runtime/src/initialization/global_components.rs b/tee-worker/enclave-runtime/src/initialization/global_components.rs index 939d69fe18..16edb29166 100644 --- a/tee-worker/enclave-runtime/src/initialization/global_components.rs +++ b/tee-worker/enclave-runtime/src/initialization/global_components.rs @@ -177,11 +177,7 @@ pub type IntegriteeParentchainIndirectCallsExecutor = IndirectCallsExecutor< EnclaveTopPoolAuthor, EnclaveNodeMetadataRepository, EventCreator, - integritee::ParentchainEventHandler< - EnclaveOCallApi, - EnclaveStateHandler, - EnclaveNodeMetadataRepository, - >, + integritee::ParentchainEventHandler, EnclaveTrustedCallSigned, EnclaveGetter, >; diff --git a/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs b/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs index 40fa90d6c7..2d34581a2b 100644 --- a/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs +++ b/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs @@ -75,7 +75,6 @@ pub(crate) fn create_integritee_parentchain_block_importer( assertion_repository: repository, ocall_api: ocall_api.clone(), state_handler, - node_metadata_repository: node_metadata_repository.clone(), }; let stf_enclave_signer = Arc::new(EnclaveStfEnclaveSigner::new( From a6ff29eae9677b9fd2bb581698b9ebffea851c43 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 21 Aug 2024 15:36:06 +0000 Subject: [PATCH 44/61] more clean up --- .../parentchain-interface/src/integritee/event_handler.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index 53b330bb1b..23c6d50919 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -317,7 +317,7 @@ where let trusted_operation = TrustedOperation::::indirect_call(signed_trusted_call); let encrypted_trusted_call = executor.encrypt(&trusted_operation.encode())?; - executor.submit_trusted_call(shard.clone(), encrypted_trusted_call); + executor.submit_trusted_call(shard, encrypted_trusted_call); } let trusted_call = TrustedCall::reward_distribution_completed(enclave_account_id.into()); @@ -325,7 +325,7 @@ where let trusted_operation = TrustedOperation::::indirect_call(signed_trusted_call); let encrypted_trusted_call = executor.encrypt(&trusted_operation.encode())?; - executor.submit_trusted_call(shard.clone(), encrypted_trusted_call); + executor.submit_trusted_call(shard, encrypted_trusted_call); Ok(()) } From a3a6ca3730f8cee127d688c4d43cbbea5e47b475 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Fri, 23 Aug 2024 13:52:37 +0000 Subject: [PATCH 45/61] adding NodeMetadataProvider trait to extend trait bounds --- .../extrinsics-factory/src/lib.rs | 2 +- .../node-api/metadata/src/lib.rs | 18 +++++++++++++----- .../node-api/metadata/src/metadata_mocks.rs | 8 +++++++- 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/tee-worker/core-primitives/extrinsics-factory/src/lib.rs b/tee-worker/core-primitives/extrinsics-factory/src/lib.rs index ab58d65853..f869917b27 100644 --- a/tee-worker/core-primitives/extrinsics-factory/src/lib.rs +++ b/tee-worker/core-primitives/extrinsics-factory/src/lib.rs @@ -35,7 +35,7 @@ use itp_node_api::{ api_client::{ ExtrinsicParams, ParentchainAdditionalParams, ParentchainExtrinsicParams, SignExtrinsic, }, - metadata::{provider::AccessNodeMetadata, NodeMetadata}, + metadata::{provider::AccessNodeMetadata, NodeMetadata, NodeMetadataProvider}, }; use itp_nonce_cache::{MutateNonce, Nonce}; use itp_types::{parentchain::AccountId, OpaqueCall}; diff --git a/tee-worker/core-primitives/node-api/metadata/src/lib.rs b/tee-worker/core-primitives/node-api/metadata/src/lib.rs index ab80b24a6d..5625e77ed1 100644 --- a/tee-worker/core-primitives/node-api/metadata/src/lib.rs +++ b/tee-worker/core-primitives/node-api/metadata/src/lib.rs @@ -50,6 +50,10 @@ pub mod pallet_timestamp; #[cfg(feature = "mocks")] pub mod metadata_mocks; +pub trait NodeMetadataProvider { + fn get_metadata(&self) -> Option<&Metadata>; +} + pub trait NodeMetadataTrait: TeebagCallIndexes + IMPCallIndexes @@ -61,6 +65,7 @@ pub trait NodeMetadataTrait: + TimestampCallIndexes + EvmAssertionsCallIndexes + ScoreStakingCallIndexes + + NodeMetadataProvider { } @@ -74,7 +79,8 @@ impl< + BalancesCallIndexes + TimestampCallIndexes + EvmAssertionsCallIndexes - + ScoreStakingCallIndexes, + + ScoreStakingCallIndexes + + NodeMetadataProvider, > NodeMetadataTrait for T { } @@ -107,10 +113,6 @@ impl NodeMetadata { } } - pub fn get_metadata(&self) -> Option<&Metadata> { - self.node_metadata.as_ref() - } - /// Return the substrate chain runtime version. pub fn get_runtime_version(&self) -> u32 { self.runtime_spec_version @@ -185,3 +187,9 @@ impl NodeMetadata { } } } + +impl NodeMetadataProvider for NodeMetadata { + fn get_metadata(&self) -> Option<&Metadata> { + self.node_metadata.as_ref() + } +} diff --git a/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs b/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs index 5918d141e3..a4461eb72a 100644 --- a/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs +++ b/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs @@ -21,7 +21,7 @@ use crate::{ pallet_proxy::ProxyCallIndexes, pallet_score_staking::ScoreStakingCallIndexes, pallet_system::SystemConstants, pallet_teebag::TeebagCallIndexes, pallet_timestamp::TimestampCallIndexes, pallet_utility::UtilityCallIndexes, - pallet_vcmp::VCMPCallIndexes, runtime_call::RuntimeCall, + pallet_vcmp::VCMPCallIndexes, runtime_call::RuntimeCall, NodeMetadataProvider, }; use codec::{Decode, Encode}; @@ -330,3 +330,9 @@ impl EvmAssertionsCallIndexes for NodeMetadataMock { Ok([self.evm_assertions_module, self.evm_assertions_void_assertion]) } } + +impl NodeMetadataProvider for NodeMetadataMock { + fn get_metadata(&self) -> Option<&Metadata> { + None + } +} From 717394fe2cdc28004d59a4ab19fd805224ed8087 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Fri, 23 Aug 2024 13:53:15 +0000 Subject: [PATCH 46/61] exposing compose_call from api-client-types --- tee-worker/core-primitives/node-api/api-client-types/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/tee-worker/core-primitives/node-api/api-client-types/src/lib.rs b/tee-worker/core-primitives/node-api/api-client-types/src/lib.rs index b82b0c376b..e5ecf29664 100644 --- a/tee-worker/core-primitives/node-api/api-client-types/src/lib.rs +++ b/tee-worker/core-primitives/node-api/api-client-types/src/lib.rs @@ -26,6 +26,7 @@ pub use itp_types::parentchain::{ AccountData, AccountId, AccountInfo, Address, Balance, Hash, Index, Signature as PairSignature, }; pub use substrate_api_client::{ + ac_compose_macros::compose_call, ac_node_api::{ metadata::{InvalidMetadataError, Metadata, MetadataError}, EventDetails, Events, StaticEvent, From aa3a50ea406fec62c1721f52b1027c89c51fd4e7 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Fri, 23 Aug 2024 13:56:39 +0000 Subject: [PATCH 47/61] refactoring to send calls in batches --- .../src/integritee/event_handler.rs | 22 ++++---- tee-worker/app-libs/stf/src/trusted_call.rs | 53 ++++++++++++++----- 2 files changed, 51 insertions(+), 24 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index 23c6d50919..5a457d17b9 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -298,6 +298,8 @@ where let enclave_account_id = executor.get_enclave_account().expect("no enclave account"); + let mut updates: Vec<(AccountId, Balance)> = Vec::new(); + for account_id in account_ids.iter() { let default_id_graph = Vec::new(); let id_graph = accounts_graphs.get(account_id).unwrap_or(&default_id_graph); @@ -308,18 +310,18 @@ where Some(delegator.total) }) .sum(); - let trusted_call = TrustedCall::update_token_staking_amount( - enclave_account_id.clone().into(), - account_id.clone(), - staking_amount, - ); - let signed_trusted_call = executor.sign_call_with_self(&trusted_call, &shard)?; - let trusted_operation = - TrustedOperation::::indirect_call(signed_trusted_call); - let encrypted_trusted_call = executor.encrypt(&trusted_operation.encode())?; - executor.submit_trusted_call(shard, encrypted_trusted_call); + updates.push((account_id.clone(), staking_amount)); } + // Update the staking amounts + let trusted_call = + TrustedCall::update_token_staking_amounts(enclave_account_id.clone().into(), updates); + let signed_trusted_call = executor.sign_call_with_self(&trusted_call, &shard)?; + let trusted_operation = + TrustedOperation::::indirect_call(signed_trusted_call); + let encrypted_trusted_call = executor.encrypt(&trusted_operation.encode())?; + executor.submit_trusted_call(shard, encrypted_trusted_call); + // Notify the parachain that the reward distribution is completed let trusted_call = TrustedCall::reward_distribution_completed(enclave_account_id.into()); let signed_trusted_call = executor.sign_call_with_self(&trusted_call, &shard)?; let trusted_operation = diff --git a/tee-worker/app-libs/stf/src/trusted_call.rs b/tee-worker/app-libs/stf/src/trusted_call.rs index 2d738fd0f4..9be13fa0d4 100644 --- a/tee-worker/app-libs/stf/src/trusted_call.rs +++ b/tee-worker/app-libs/stf/src/trusted_call.rs @@ -39,9 +39,12 @@ pub use ita_sgx_runtime::{ Balance, IDGraph, Index, ParentchainInstanceLitentry, ParentchainInstanceTargetA, ParentchainInstanceTargetB, ParentchainLitentry, Runtime, System, VERSION as SIDECHAIN_VERSION, }; -use itp_node_api::metadata::{ - pallet_score_staking::ScoreStakingCallIndexes, pallet_system::SystemConstants, - provider::AccessNodeMetadata, NodeMetadataTrait, +use itp_node_api::{ + api_client::compose_call, + metadata::{ + pallet_score_staking::ScoreStakingCallIndexes, pallet_system::SystemConstants, + provider::AccessNodeMetadata, NodeMetadataProvider, NodeMetadataTrait, + }, }; use itp_node_api_metadata::{pallet_imp::IMPCallIndexes, pallet_vcmp::VCMPCallIndexes}; use itp_stf_interface::ExecuteCall; @@ -68,6 +71,7 @@ use sp_core::{ }; use sp_io::hashing::blake2_256; use sp_runtime::{traits::ConstU32, BoundedVec, MultiAddress}; +use std::borrow::ToOwned; pub type IMTCall = ita_sgx_runtime::IdentityManagementCall; pub type IMT = ita_sgx_runtime::pallet_imt::Pallet; @@ -143,8 +147,8 @@ pub enum TrustedCall { send_erroneous_parentchain_call(Identity), #[codec(index = 25)] maybe_create_id_graph(Identity, Identity), - #[codec(index = 26)] - update_token_staking_amount(Identity, AccountId, Balance), + #[codec(index = 25)] + update_token_staking_amounts(Identity, Vec<(AccountId, Balance)>), #[codec(index = 27)] reward_distribution_completed(Identity), @@ -233,7 +237,7 @@ impl TrustedCall { Self::handle_vcmp_error(sender_identity, ..) => sender_identity, Self::send_erroneous_parentchain_call(sender_identity) => sender_identity, Self::maybe_create_id_graph(sender_identity, ..) => sender_identity, - Self::update_token_staking_amount(sender_identity, ..) => sender_identity, + Self::update_token_staking_amounts(sender_identity, ..) => sender_identity, Self::reward_distribution_completed(sender_identity) => sender_identity, #[cfg(feature = "development")] Self::remove_identity(sender_identity, ..) => sender_identity, @@ -982,18 +986,39 @@ where Ok(TrustedCallResult::Empty) }, - TrustedCall::update_token_staking_amount(signer, account_id, staking_amount) => { + TrustedCall::update_token_staking_amounts(signer, updates) => { let signer_account: AccountId32 = signer.to_account_id().ok_or(Self::Error::InvalidAccount)?; ensure_enclave_signer_account(&signer_account)?; - let call = OpaqueCall::from_tuple(&( - node_metadata_repo - .get_from_metadata(|m| m.update_token_staking_amount_call_indexes())??, - account_id, - staking_amount, - )); - calls.push(ParentchainCall::Litentry(call)); + let mut update_token_staking_amount_calls: Vec = Vec::new(); + + for (account_id, staking_amount) in updates { + let call = OpaqueCall::from_tuple(&( + node_metadata_repo.get_from_metadata(|m| { + m.update_token_staking_amount_call_indexes() + })??, + account_id, + staking_amount, + )); + update_token_staking_amount_calls.push(call); + } + + let node_metadata = node_metadata_repo.get_from_metadata(|m| { + let metadata = m.get_metadata().expect("Metadata not set"); + metadata.clone() + })?; + + for batch in update_token_staking_amount_calls.chunks(500) { + let batch_call = OpaqueCall::from_tuple(&compose_call!( + node_metadata, + "Utility", + "batch", + batch + )); + + calls.push(ParentchainCall::Litentry(batch_call)); + } Ok(TrustedCallResult::Empty) }, From d6e1dc7d8a76adb14c597c72a05389451d2728e0 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Mon, 26 Aug 2024 14:33:27 +0000 Subject: [PATCH 48/61] updating pallet to only update non distributed staking amounts --- pallets/score-staking/src/lib.rs | 74 ++++++++++++++------ pallets/score-staking/src/tests.rs | 105 ++++++++++++++++++++++------- pallets/score-staking/src/types.rs | 1 + 3 files changed, 135 insertions(+), 45 deletions(-) diff --git a/pallets/score-staking/src/lib.rs b/pallets/score-staking/src/lib.rs index d881cfbac2..c3120b73d3 100644 --- a/pallets/score-staking/src/lib.rs +++ b/pallets/score-staking/src/lib.rs @@ -156,22 +156,45 @@ pub mod pallet { ScoreUserCountUnderflow, // when the score user count would exceed `MaxScoreUserCount` MaxScoreUserCountReached, + // the token staking amount has been updated already for the round + TokenStakingAmountAlreadyUpdated, } #[pallet::event] #[pallet::generate_deposit(pub (crate) fn deposit_event)] pub enum Event { - PoolStarted { start_block: BlockNumberFor }, + PoolStarted { + start_block: BlockNumberFor, + }, PoolStopped {}, - ScoreFeederSet { new_score_feeder: Option }, - RoundConfigSet { new_config: RoundSetting }, - ScoreUpdated { who: Identity, new_score: Score }, - ScoreRemoved { who: Identity }, + ScoreFeederSet { + new_score_feeder: Option, + }, + RoundConfigSet { + new_config: RoundSetting, + }, + ScoreUpdated { + who: Identity, + new_score: Score, + }, + ScoreRemoved { + who: Identity, + }, ScoreCleared {}, - TokenStakingAmountUpdated { account: T::AccountId, amount: BalanceOf }, - RewardDistributionStarted { total: BalanceOf, distributed: BalanceOf }, + TokenStakingAmountUpdated { + account: T::AccountId, + amount: BalanceOf, + }, + RewardDistributionStarted { + total: BalanceOf, + distributed: BalanceOf, + round_index: RoundIndex, + }, RewardDistributionCompleted {}, - RewardClaimed { who: T::AccountId, amount: BalanceOf }, + RewardClaimed { + who: T::AccountId, + amount: BalanceOf, + }, } #[pallet::storage] @@ -250,7 +273,8 @@ pub mod pallet { // We are about to start a new round // 1. update round info - r.index = r.index.saturating_add(1); + let round_index = r.index.saturating_add(1); + r.index = round_index; r.start_block = now; Round::::put(r); weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 1)); @@ -290,6 +314,7 @@ pub mod pallet { Self::deposit_event(Event::::RewardDistributionStarted { total: round_reward, distributed: all_user_reward, + round_index, }); weight @@ -460,6 +485,7 @@ pub mod pallet { origin: OriginFor, account: T::AccountId, amount: BalanceOf, + round_index: RoundIndex, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin.clone())?; ensure!( @@ -467,19 +493,23 @@ pub mod pallet { Error::::UnauthorizedOrigin ); - Scores::::try_mutate(&account, |payment| { - let mut p = payment.take().ok_or(Error::::UserNotExist)?; - p.token_staking_amount = amount; - *payment = Some(p); - - Self::deposit_event(Event::TokenStakingAmountUpdated { - account: account.clone(), - amount, - }); - Ok::<(), Error>(()) - })?; - - Ok(Pays::No.into()) + match Scores::::get(&account) { + Some(mut s) => { + if round_index <= s.last_token_distributed_round { + return Err(Error::::TokenStakingAmountAlreadyUpdated.into()); + } + let last_round = Round::::get(); + s.token_staking_amount = amount; + s.last_token_distributed_round = last_round.index; + Scores::::insert(account.clone(), s); + Self::deposit_event(Event::TokenStakingAmountUpdated { + account: account.clone(), + amount, + }); + Ok(Pays::No.into()) + }, + None => Err(Error::::UserNotExist.into()), + } } #[pallet::call_index(10)] diff --git a/pallets/score-staking/src/tests.rs b/pallets/score-staking/src/tests.rs index 1efb2240a7..f9ce4640ac 100644 --- a/pallets/score-staking/src/tests.rs +++ b/pallets/score-staking/src/tests.rs @@ -129,7 +129,11 @@ fn default_mint_works() { // run to next reward distribution round run_to_block(7); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { total: round_reward(), distributed: 0 }, + Event::::RewardDistributionStarted { + total: round_reward(), + distributed: 0, + round_index: 2, + }, )); }); } @@ -171,6 +175,7 @@ fn score_staking_works() { last_round_reward: 0, unpaid_reward: 0, token_staking_amount: 0, + last_token_distributed_round: 0 } ); assert_eq!(ScoreStaking::total_score(), 500); @@ -191,9 +196,10 @@ fn score_staking_works() { Event::::RewardDistributionStarted { total: round_reward(), distributed: round_reward(), + round_index: 2, }, )); - // total reward round 1 + // total reward first distribution let mut alice_total_reward = round_reward(); assert_eq!( ScoreStaking::scores(alice()).unwrap(), @@ -203,6 +209,7 @@ fn score_staking_works() { last_round_reward: alice_total_reward, unpaid_reward: alice_total_reward, token_staking_amount: 0, + last_token_distributed_round: 0, } ); @@ -212,9 +219,10 @@ fn score_staking_works() { Event::::RewardDistributionStarted { total: round_reward(), distributed: round_reward(), + round_index: 3, }, )); - // total reward round 2 + // total reward second distribution alice_total_reward += round_reward(); assert_eq!( @@ -225,6 +233,7 @@ fn score_staking_works() { last_round_reward: round_reward(), unpaid_reward: alice_total_reward, token_staking_amount: 0, + last_token_distributed_round: 0, } ); @@ -237,9 +246,10 @@ fn score_staking_works() { Event::::RewardDistributionStarted { total: round_reward(), distributed: calculate_round_reward(2000, 2000, 900, 1600), + round_index: 4, }, )); - // total reward round 3 + // total reward third distribution alice_total_reward += calculate_round_reward(2000, 2000, 900, 1600); assert_eq!( @@ -250,6 +260,7 @@ fn score_staking_works() { last_round_reward: calculate_round_reward(2000, 2000, 900, 1600), unpaid_reward: alice_total_reward, token_staking_amount: 0, + last_token_distributed_round: 0, } ); @@ -262,7 +273,7 @@ fn score_staking_works() { assert_eq!(ScoreStaking::score_user_count(), 2); run_to_block(22); - // total rewards round 4 + // total rewards fourth distribution alice_total_reward += calculate_round_reward(2000, 3000, 900, 3200); let mut bob_total_reward = calculate_round_reward(1000, 3000, 1600, 3200); @@ -274,6 +285,7 @@ fn score_staking_works() { last_round_reward: calculate_round_reward(2000, 3000, 900, 3200), unpaid_reward: alice_total_reward, token_staking_amount: 0, + last_token_distributed_round: 0, } ); assert_eq!( @@ -284,6 +296,7 @@ fn score_staking_works() { last_round_reward: bob_total_reward, unpaid_reward: bob_total_reward, token_staking_amount: 0, + last_token_distributed_round: 0, } ); @@ -305,7 +318,7 @@ fn score_staking_works() { )); run_to_block(25); - // total rewards round 5 + // total rewards fifth distribution alice_total_reward += calculate_round_reward(2000, 3000, 900, 3200); bob_total_reward += calculate_round_reward(1000, 3000, 1600, 3200); @@ -317,7 +330,7 @@ fn score_staking_works() { )); run_to_block(31); - // total reward round 6 + // total reward sixth distribution alice_total_reward += calculate_round_reward(2000, 2000, 900, 900); // remove increased stake (keep only alice's stake) @@ -334,6 +347,7 @@ fn score_staking_works() { last_round_reward: round_reward(), unpaid_reward: alice_total_reward, token_staking_amount: 0, + last_token_distributed_round: 0, } ); @@ -346,6 +360,7 @@ fn score_staking_works() { last_round_reward: 0, unpaid_reward: bob_total_reward, token_staking_amount: 0, + last_token_distributed_round: 0, } ); assert_eq!(ScoreStaking::total_score(), 2000); @@ -383,6 +398,7 @@ fn claim_works() { Event::::RewardDistributionStarted { total: round_reward(), distributed: round_reward(), + round_index: 2, }, )); assert_eq!( @@ -393,6 +409,7 @@ fn claim_works() { last_round_reward: round_reward(), unpaid_reward: round_reward(), token_staking_amount: 0, + last_token_distributed_round: 0, } ); @@ -409,6 +426,7 @@ fn claim_works() { last_round_reward: round_reward(), unpaid_reward: round_reward() - 200, token_staking_amount: 0, + last_token_distributed_round: 0, } ); @@ -425,6 +443,7 @@ fn claim_works() { last_round_reward: round_reward(), unpaid_reward: 0, token_staking_amount: 0, + last_token_distributed_round: 0, } ); @@ -438,7 +457,7 @@ fn claim_works() { #[test] fn update_token_staking_amount_works() { - new_test_ext(false).execute_with(|| { + new_test_ext_with_parachain_staking().execute_with(|| { let enclave = Enclave::new(WorkerType::Identity); pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); @@ -450,38 +469,76 @@ fn update_token_staking_amount_works() { alice(), Delegator::new(bob(), bob(), 900), ); - + pallet_parachain_staking::Total::::put(900); assert_ok!(ScoreStaking::update_score(RuntimeOrigin::signed(alice()), alice().into(), 500)); + + // run to next reward distribution round, alice should win all rewards + run_to_block(7); + let mut total_reward = round_reward(); + + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + total: total_reward, + distributed: total_reward, + round_index: 2, + }, + )); + + assert_ok!(ScoreStaking::update_token_staking_amount( + RuntimeOrigin::signed(alice()), + alice(), + 1000, + 2, + )); + assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { score: 500, - total_reward: 0, - last_round_reward: 0, - unpaid_reward: 0, - token_staking_amount: 0, + total_reward, + last_round_reward: total_reward, + unpaid_reward: total_reward, + token_staking_amount: 1000, + last_token_distributed_round: 2, } ); + run_to_block(12); + + total_reward += round_reward(); + + assert_noop!( + ScoreStaking::update_token_staking_amount( + RuntimeOrigin::signed(alice()), + alice(), + 1000, + 2, + ), + Error::::TokenStakingAmountAlreadyUpdated + ); + assert_ok!(ScoreStaking::update_token_staking_amount( RuntimeOrigin::signed(alice()), alice(), - 1000 + 1200, + 3, + )); + + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::TokenStakingAmountUpdated { account: alice(), amount: 1200 }, )); assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { score: 500, - total_reward: 0, - last_round_reward: 0, - unpaid_reward: 0, - token_staking_amount: 1000, + total_reward, + last_round_reward: round_reward(), + unpaid_reward: total_reward, + token_staking_amount: 1200, + last_token_distributed_round: 3, } ); - System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::TokenStakingAmountUpdated { account: alice(), amount: 1000 }, - )); }) } @@ -492,7 +549,8 @@ fn update_token_staking_amount_origin_check_works() { ScoreStaking::update_token_staking_amount( RuntimeOrigin::signed(alice()), alice(), - 1000 + 1000, + 1 ), Error::::UnauthorizedOrigin ); @@ -509,7 +567,8 @@ fn update_token_staking_amount_existing_user_check_works() { ScoreStaking::update_token_staking_amount( RuntimeOrigin::signed(alice()), alice(), - 1000 + 1000, + 1 ), Error::::UserNotExist ); diff --git a/pallets/score-staking/src/types.rs b/pallets/score-staking/src/types.rs index 6f39d672b3..b7c1e3d346 100644 --- a/pallets/score-staking/src/types.rs +++ b/pallets/score-staking/src/types.rs @@ -84,4 +84,5 @@ pub struct ScorePayment { pub last_round_reward: Balance, pub unpaid_reward: Balance, pub token_staking_amount: Balance, + pub last_token_distributed_round: RoundIndex, } From cd372d5550a44155f8b10f83044be904e518faa0 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Mon, 26 Aug 2024 15:07:31 +0000 Subject: [PATCH 49/61] removing added trusted calls --- tee-worker/app-libs/stf/src/trusted_call.rs | 63 +------------------ .../node-api/api-client-types/src/lib.rs | 1 - 2 files changed, 2 insertions(+), 62 deletions(-) diff --git a/tee-worker/app-libs/stf/src/trusted_call.rs b/tee-worker/app-libs/stf/src/trusted_call.rs index 9be13fa0d4..3f0277f54b 100644 --- a/tee-worker/app-libs/stf/src/trusted_call.rs +++ b/tee-worker/app-libs/stf/src/trusted_call.rs @@ -39,12 +39,8 @@ pub use ita_sgx_runtime::{ Balance, IDGraph, Index, ParentchainInstanceLitentry, ParentchainInstanceTargetA, ParentchainInstanceTargetB, ParentchainLitentry, Runtime, System, VERSION as SIDECHAIN_VERSION, }; -use itp_node_api::{ - api_client::compose_call, - metadata::{ - pallet_score_staking::ScoreStakingCallIndexes, pallet_system::SystemConstants, - provider::AccessNodeMetadata, NodeMetadataProvider, NodeMetadataTrait, - }, +use itp_node_api::metadata::{ + pallet_system::SystemConstants, provider::AccessNodeMetadata, NodeMetadataTrait, }; use itp_node_api_metadata::{pallet_imp::IMPCallIndexes, pallet_vcmp::VCMPCallIndexes}; use itp_stf_interface::ExecuteCall; @@ -71,7 +67,6 @@ use sp_core::{ }; use sp_io::hashing::blake2_256; use sp_runtime::{traits::ConstU32, BoundedVec, MultiAddress}; -use std::borrow::ToOwned; pub type IMTCall = ita_sgx_runtime::IdentityManagementCall; pub type IMT = ita_sgx_runtime::pallet_imt::Pallet; @@ -147,10 +142,6 @@ pub enum TrustedCall { send_erroneous_parentchain_call(Identity), #[codec(index = 25)] maybe_create_id_graph(Identity, Identity), - #[codec(index = 25)] - update_token_staking_amounts(Identity, Vec<(AccountId, Balance)>), - #[codec(index = 27)] - reward_distribution_completed(Identity), // original integritee trusted calls, starting from index 50 #[codec(index = 50)] @@ -237,8 +228,6 @@ impl TrustedCall { Self::handle_vcmp_error(sender_identity, ..) => sender_identity, Self::send_erroneous_parentchain_call(sender_identity) => sender_identity, Self::maybe_create_id_graph(sender_identity, ..) => sender_identity, - Self::update_token_staking_amounts(sender_identity, ..) => sender_identity, - Self::reward_distribution_completed(sender_identity) => sender_identity, #[cfg(feature = "development")] Self::remove_identity(sender_identity, ..) => sender_identity, Self::request_batch_vc(sender_identity, ..) => sender_identity, @@ -984,54 +973,6 @@ where Err(e) => warn!("maybe_create_id_graph NOK: {:?}", e), }; - Ok(TrustedCallResult::Empty) - }, - TrustedCall::update_token_staking_amounts(signer, updates) => { - let signer_account: AccountId32 = - signer.to_account_id().ok_or(Self::Error::InvalidAccount)?; - ensure_enclave_signer_account(&signer_account)?; - - let mut update_token_staking_amount_calls: Vec = Vec::new(); - - for (account_id, staking_amount) in updates { - let call = OpaqueCall::from_tuple(&( - node_metadata_repo.get_from_metadata(|m| { - m.update_token_staking_amount_call_indexes() - })??, - account_id, - staking_amount, - )); - update_token_staking_amount_calls.push(call); - } - - let node_metadata = node_metadata_repo.get_from_metadata(|m| { - let metadata = m.get_metadata().expect("Metadata not set"); - metadata.clone() - })?; - - for batch in update_token_staking_amount_calls.chunks(500) { - let batch_call = OpaqueCall::from_tuple(&compose_call!( - node_metadata, - "Utility", - "batch", - batch - )); - - calls.push(ParentchainCall::Litentry(batch_call)); - } - - Ok(TrustedCallResult::Empty) - }, - TrustedCall::reward_distribution_completed(signer) => { - let signer_account: AccountId32 = - signer.to_account_id().ok_or(Self::Error::InvalidAccount)?; - ensure_enclave_signer_account(&signer_account)?; - let call = OpaqueCall::from_tuple( - &(node_metadata_repo - .get_from_metadata(|m| m.complete_reward_distribution_call_indexes())??), - ); - calls.push(ParentchainCall::Litentry(call)); - Ok(TrustedCallResult::Empty) }, } diff --git a/tee-worker/core-primitives/node-api/api-client-types/src/lib.rs b/tee-worker/core-primitives/node-api/api-client-types/src/lib.rs index e5ecf29664..b82b0c376b 100644 --- a/tee-worker/core-primitives/node-api/api-client-types/src/lib.rs +++ b/tee-worker/core-primitives/node-api/api-client-types/src/lib.rs @@ -26,7 +26,6 @@ pub use itp_types::parentchain::{ AccountData, AccountId, AccountInfo, Address, Balance, Hash, Index, Signature as PairSignature, }; pub use substrate_api_client::{ - ac_compose_macros::compose_call, ac_node_api::{ metadata::{InvalidMetadataError, Metadata, MetadataError}, EventDetails, Events, StaticEvent, From c02459002001eb98905f56b7dae7049a6576b5a8 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Mon, 26 Aug 2024 15:07:51 +0000 Subject: [PATCH 50/61] updating event --- tee-worker/core-primitives/types/src/parentchain/events.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tee-worker/core-primitives/types/src/parentchain/events.rs b/tee-worker/core-primitives/types/src/parentchain/events.rs index d830622c52..3cce6e2e10 100644 --- a/tee-worker/core-primitives/types/src/parentchain/events.rs +++ b/tee-worker/core-primitives/types/src/parentchain/events.rs @@ -249,15 +249,17 @@ impl StaticEvent for AssertionCreated { pub struct RewardDistributionStarted { pub total: Balance, pub distributed: Balance, + pub round_index: u32, } impl core::fmt::Display for RewardDistributionStarted { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { let message = format!( - "{:?} :: total: {}, distributed: {}", + "{:?} :: total: {}, distributed: {}, round_index: {}", RewardDistributionStarted::EVENT, self.total, - self.distributed + self.distributed, + self.round_index ); write!(f, "{}", message) } From 53e90641a0ea2032052a02d904d4f23c304628cb Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Mon, 26 Aug 2024 15:08:54 +0000 Subject: [PATCH 51/61] injecting node_metadata_repository to the event handler --- .../src/integritee/event_handler.rs | 13 +++++++++---- .../src/initialization/global_components.rs | 6 +++++- .../src/initialization/parentchain/common.rs | 1 + 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index 5a457d17b9..ed61de676f 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -44,16 +44,19 @@ use sp_runtime::traits::Header; use sp_std::vec::Vec; use std::{collections::BTreeMap, format, println, string::String, sync::Arc}; -pub struct ParentchainEventHandler { +pub struct ParentchainEventHandler { pub assertion_repository: Arc, pub ocall_api: Arc, pub state_handler: Arc, + pub node_metadata_repository: Arc, } -impl ParentchainEventHandler +impl ParentchainEventHandler where OCallApi: EnclaveOnChainOCallApi, HS: HandleState, + NMR: AccessNodeMetadata, + NMR::MetadataType: NodeMetadataTrait, { fn link_identity>( executor: &Executor, @@ -338,12 +341,14 @@ fn decode_storage_key(raw_key: Vec) -> Option> { decode_hex(hex_key).ok() } -impl HandleParentchainEvents - for ParentchainEventHandler +impl HandleParentchainEvents + for ParentchainEventHandler where Executor: IndirectExecutor, OCallApi: EnclaveOnChainOCallApi, HS: HandleState, + NMR: AccessNodeMetadata, + NMR::MetadataType: NodeMetadataTrait, { fn handle_events( &self, diff --git a/tee-worker/enclave-runtime/src/initialization/global_components.rs b/tee-worker/enclave-runtime/src/initialization/global_components.rs index 16edb29166..939d69fe18 100644 --- a/tee-worker/enclave-runtime/src/initialization/global_components.rs +++ b/tee-worker/enclave-runtime/src/initialization/global_components.rs @@ -177,7 +177,11 @@ pub type IntegriteeParentchainIndirectCallsExecutor = IndirectCallsExecutor< EnclaveTopPoolAuthor, EnclaveNodeMetadataRepository, EventCreator, - integritee::ParentchainEventHandler, + integritee::ParentchainEventHandler< + EnclaveOCallApi, + EnclaveStateHandler, + EnclaveNodeMetadataRepository, + >, EnclaveTrustedCallSigned, EnclaveGetter, >; diff --git a/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs b/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs index 2d34581a2b..40fa90d6c7 100644 --- a/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs +++ b/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs @@ -75,6 +75,7 @@ pub(crate) fn create_integritee_parentchain_block_importer( assertion_repository: repository, ocall_api: ocall_api.clone(), state_handler, + node_metadata_repository: node_metadata_repository.clone(), }; let stf_enclave_signer = Arc::new(EnclaveStfEnclaveSigner::new( From a4b07e3c6e8e3c247a64ce917c927e7f51094741 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Mon, 26 Aug 2024 16:05:27 +0000 Subject: [PATCH 52/61] refactoring event handler --- .../src/integritee/event_handler.rs | 66 +++++++++++++------ 1 file changed, 46 insertions(+), 20 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index ed61de676f..ef7f616d94 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -21,6 +21,9 @@ pub use ita_sgx_runtime::{Balance, Index, Runtime}; use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; use itc_parentchain_indirect_calls_executor::error::Error; use itp_api_client_types::StaticEvent; +use itp_node_api::metadata::{ + pallet_score_staking::ScoreStakingCallIndexes, provider::AccessNodeMetadata, NodeMetadataTrait, +}; use itp_ocall_api::EnclaveOnChainOCallApi; use itp_sgx_externalities::{SgxExternalities, SgxExternalitiesTrait}; use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation}; @@ -31,10 +34,11 @@ use itp_types::{ events::ParentchainBlockProcessed, AccountId, FilterEvents, HandleParentchainEvents, ParentchainEventProcessingError, ParentchainId, ProcessedEventsArtifacts, }, - Delegator, RsaRequest, H256, + Delegator, OpaqueCall, RsaRequest, H256, }; use lc_dynamic_assertion::AssertionLogicRepository; use lc_evm_dynamic_assertions::repository::EvmAssertionRepository; +use lc_parachain_extrinsic_task_sender::{ParachainExtrinsicSender, SendParachainExtrinsic}; use litentry_hex_utils::decode_hex; use litentry_primitives::{Assertion, Identity, ValidationData, Web3Network}; use log::*; @@ -223,6 +227,7 @@ where &self, executor: &Executor, block_header: impl Header, + round_index: u32, ) -> Result<(), Error> { let scores_key_prefix = storage_prefix(b"ScoreStaking", b"Scores"); let scores_storage_keys_response = self @@ -299,9 +304,17 @@ where }) .map_err(|_| Error::Other("Failed to get id graphs".into()))?; - let enclave_account_id = executor.get_enclave_account().expect("no enclave account"); + let extrinsic_sender = ParachainExtrinsicSender::new(); - let mut updates: Vec<(AccountId, Balance)> = Vec::new(); + let update_token_staking_amount_call_index = self + .node_metadata_repository + .get_from_metadata(|m| m.update_token_staking_amount_call_indexes()) + .map_err(|_| { + Error::Other( + "Metadata retrieval for update_token_staking_amount_call_indexes failed".into(), + ) + })? + .map_err(|_| Error::Other("Invalid metadata".into()))?; for account_id in account_ids.iter() { let default_id_graph = Vec::new(); @@ -313,24 +326,33 @@ where Some(delegator.total) }) .sum(); - updates.push((account_id.clone(), staking_amount)); + let call = OpaqueCall::from_tuple(&( + update_token_staking_amount_call_index, + account_id, + staking_amount, + round_index, + )); + extrinsic_sender + .send(call) + .map_err(|_| Error::Other("Failed to send extrinsic".into()))?; } - // Update the staking amounts - let trusted_call = - TrustedCall::update_token_staking_amounts(enclave_account_id.clone().into(), updates); - let signed_trusted_call = executor.sign_call_with_self(&trusted_call, &shard)?; - let trusted_operation = - TrustedOperation::::indirect_call(signed_trusted_call); - let encrypted_trusted_call = executor.encrypt(&trusted_operation.encode())?; - executor.submit_trusted_call(shard, encrypted_trusted_call); - // Notify the parachain that the reward distribution is completed - let trusted_call = TrustedCall::reward_distribution_completed(enclave_account_id.into()); - let signed_trusted_call = executor.sign_call_with_self(&trusted_call, &shard)?; - let trusted_operation = - TrustedOperation::::indirect_call(signed_trusted_call); - let encrypted_trusted_call = executor.encrypt(&trusted_operation.encode())?; - executor.submit_trusted_call(shard, encrypted_trusted_call); + let complete_reward_distribution_call_index = self + .node_metadata_repository + .get_from_metadata(|m| m.complete_reward_distribution_call_indexes()) + .map_err(|_| { + Error::Other( + "Metadata retrieval for complete_reward_distribution_call_indexes failed" + .into(), + ) + })? + .map_err(|_| Error::Other("Invalid metadata".into()))?; + + let complete_reward_distribution_call = + OpaqueCall::from_tuple(&(complete_reward_distribution_call_index.clone())); + extrinsic_sender.send(complete_reward_distribution_call).map_err(|_| { + Error::Other("Failed to send complete_reward_distribution_call extrinsic".into()) + })?; Ok(()) } @@ -479,7 +501,11 @@ where .iter() .try_for_each(|event| { let event_hash = hash_of(&event); - let result = self.update_staking_scores(executor, block_header.clone()); + let result = self.update_staking_scores( + executor, + block_header.clone(), + event.round_index, + ); handled_events.push(event_hash); result From f629e0c1d2020faea5663d005b84d7b577fd3220 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Tue, 27 Aug 2024 07:40:11 +0000 Subject: [PATCH 53/61] fixing precompiles tests --- precompiles/score-staking/src/tests.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/precompiles/score-staking/src/tests.rs b/precompiles/score-staking/src/tests.rs index 405c45b22d..7d21dea24c 100644 --- a/precompiles/score-staking/src/tests.rs +++ b/precompiles/score-staking/src/tests.rs @@ -56,6 +56,7 @@ fn claim_is_ok() { Event::::RewardDistributionStarted { total: round_reward(), distributed: round_reward(), + round_index: 2, }, )); assert_eq!( @@ -66,6 +67,7 @@ fn claim_is_ok() { last_round_reward: round_reward(), unpaid_reward: round_reward(), token_staking_amount: 0, + last_token_distributed_round: 0, } ); @@ -90,6 +92,7 @@ fn claim_is_ok() { last_round_reward: round_reward(), unpaid_reward: round_reward() - 200, token_staking_amount: 0, + last_token_distributed_round: 0, } ); @@ -114,6 +117,7 @@ fn claim_is_ok() { last_round_reward: round_reward(), unpaid_reward: 0, token_staking_amount: 0, + last_token_distributed_round: 0, } ); From 682ce176d2756ddbb4f84f66354a1dba2090ec31 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 12 Sep 2024 13:52:08 +0000 Subject: [PATCH 54/61] making use of the existing EnsureEnclaveSigner struct --- pallets/score-staking/src/lib.rs | 20 +++----------- pallets/score-staking/src/mock.rs | 40 +++++++++++++++++++++++---- pallets/score-staking/src/tests.rs | 8 +++--- precompiles/score-staking/src/mock.rs | 40 +++++++++++++++++++++++---- runtime/litentry/src/lib.rs | 8 +----- runtime/rococo/src/lib.rs | 8 +----- 6 files changed, 80 insertions(+), 44 deletions(-) diff --git a/pallets/score-staking/src/lib.rs b/pallets/score-staking/src/lib.rs index c3120b73d3..d50b747ee4 100644 --- a/pallets/score-staking/src/lib.rs +++ b/pallets/score-staking/src/lib.rs @@ -68,10 +68,6 @@ pub trait AccountIdConvert { fn convert(account: AccountId32) -> T::AccountId; } -pub trait TokenStakingAuthorizer { - fn can_update_staking(sender: &T::AccountId) -> bool; -} - #[frame_support::pallet] pub mod pallet { use super::*; @@ -118,8 +114,8 @@ pub mod pallet { type AdminOrigin: EnsureOrigin; /// AccountId converter type AccountIdConvert: AccountIdConvert; - /// Token staking authorizer - type TokenStakingAuthorizer: TokenStakingAuthorizer; + // For extrinsics that should only be called by origins from TEE + type TEECallOrigin: EnsureOrigin; } #[pallet::error] @@ -487,11 +483,7 @@ pub mod pallet { amount: BalanceOf, round_index: RoundIndex, ) -> DispatchResultWithPostInfo { - let sender = ensure_signed(origin.clone())?; - ensure!( - T::TokenStakingAuthorizer::can_update_staking(&sender), - Error::::UnauthorizedOrigin - ); + let _ = T::TEECallOrigin::ensure_origin(origin)?; match Scores::::get(&account) { Some(mut s) => { @@ -515,11 +507,7 @@ pub mod pallet { #[pallet::call_index(10)] #[pallet::weight((195_000_000, DispatchClass::Normal))] pub fn complete_reward_distribution(origin: OriginFor) -> DispatchResultWithPostInfo { - let sender = ensure_signed(origin.clone())?; - ensure!( - T::TokenStakingAuthorizer::can_update_staking(&sender), - Error::::UnauthorizedOrigin - ); + let _ = T::TEECallOrigin::ensure_origin(origin)?; Self::deposit_event(Event::RewardDistributionCompleted {}); diff --git a/pallets/score-staking/src/mock.rs b/pallets/score-staking/src/mock.rs index 00a2228a25..d50d8acff3 100644 --- a/pallets/score-staking/src/mock.rs +++ b/pallets/score-staking/src/mock.rs @@ -18,8 +18,11 @@ use crate::{ self as pallet_score_staking, AccountIdConvert, Config, Perbill, PoolState, RoundSetting, }; +use core::marker::PhantomData; use frame_support::{ - assert_ok, construct_runtime, ord_parameter_types, parameter_types, + assert_ok, construct_runtime, ord_parameter_types, + pallet_prelude::EnsureOrigin, + parameter_types, traits::{OnFinalize, OnInitialize}, }; use frame_system::{EnsureRoot, EnsureSignedBy}; @@ -167,7 +170,7 @@ impl pallet_score_staking::Config for Test { type YearlyIssuance = ConstU128<{ 100_000_000 * UNIT }>; type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<2>; - type TokenStakingAuthorizer = pallet_teebag::Pallet; + type TEECallOrigin = EnsureEnclaveSigner; } parameter_types! { @@ -196,9 +199,36 @@ impl pallet_teebag::Config for Test { type WeightInfo = (); } -impl pallet_score_staking::TokenStakingAuthorizer for pallet_teebag::Pallet { - fn can_update_staking(sender: &::AccountId) -> bool { - pallet_teebag::Pallet::::enclave_registry(sender).is_some() +pub struct EnsureEnclaveSigner(PhantomData); +impl EnsureOrigin for EnsureEnclaveSigner +where + T: frame_system::Config + pallet_teebag::Config + pallet_timestamp::Config, + ::AccountId: From<[u8; 32]>, + ::Hash: From<[u8; 32]>, +{ + type Success = T::AccountId; + fn try_origin(o: T::RuntimeOrigin) -> Result { + o.into().and_then(|o| match o { + frame_system::RawOrigin::Signed(who) + if pallet_teebag::EnclaveRegistry::::contains_key(&who) => + { + Ok(who) + }, + r => Err(T::RuntimeOrigin::from(r)), + }) + } + + #[cfg(feature = "runtime-benchmarks")] + fn try_successful_origin() -> Result { + use pallet_teebag::test_util::{get_signer, TEST8_MRENCLAVE, TEST8_SIGNER_PUB}; + let signer: ::AccountId = get_signer(TEST8_SIGNER_PUB); + if !pallet_teebag::EnclaveRegistry::::contains_key(signer.clone()) { + assert_ok!(pallet_teebag::Pallet::::add_enclave( + &signer, + &pallet_teebag::Enclave::default().with_mrenclave(TEST8_MRENCLAVE), + )); + } + Ok(frame_system::RawOrigin::Signed(signer).into()) } } diff --git a/pallets/score-staking/src/tests.rs b/pallets/score-staking/src/tests.rs index f9ce4640ac..049bba57b6 100644 --- a/pallets/score-staking/src/tests.rs +++ b/pallets/score-staking/src/tests.rs @@ -552,7 +552,7 @@ fn update_token_staking_amount_origin_check_works() { 1000, 1 ), - Error::::UnauthorizedOrigin + sp_runtime::DispatchError::BadOrigin ); }) } @@ -581,7 +581,7 @@ fn complete_reward_distribution_works() { let enclave = Enclave::new(WorkerType::Identity); pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); - assert_ok!(ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()),)); + assert_ok!(ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()))); System::assert_last_event(RuntimeEvent::ScoreStaking( Event::::RewardDistributionCompleted {}, @@ -593,8 +593,8 @@ fn complete_reward_distribution_works() { fn complete_reward_distribution_origin_check_works() { new_test_ext(false).execute_with(|| { assert_noop!( - ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()),), - Error::::UnauthorizedOrigin + ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice())), + sp_runtime::DispatchError::BadOrigin ); }); } diff --git a/precompiles/score-staking/src/mock.rs b/precompiles/score-staking/src/mock.rs index 6013dfc523..c127b263d8 100644 --- a/precompiles/score-staking/src/mock.rs +++ b/precompiles/score-staking/src/mock.rs @@ -15,8 +15,11 @@ // along with Litentry. If not, see . use super::*; +use core::marker::PhantomData; use frame_support::{ - assert_ok, construct_runtime, parameter_types, + assert_ok, construct_runtime, + pallet_prelude::EnsureOrigin, + parameter_types, traits::{OnFinalize, OnInitialize}, weights::Weight, }; @@ -165,7 +168,7 @@ impl pallet_score_staking::Config for Test { type YearlyIssuance = ConstU128<{ 100_000_000 * UNIT }>; type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<2>; - type TokenStakingAuthorizer = pallet_teebag::Pallet; + type TEECallOrigin = EnsureEnclaveSigner; } pub fn precompile_address() -> H160 { @@ -260,9 +263,36 @@ impl pallet_teebag::Config for Test { type WeightInfo = (); } -impl pallet_score_staking::TokenStakingAuthorizer for pallet_teebag::Pallet { - fn can_update_staking(sender: &::AccountId) -> bool { - pallet_teebag::Pallet::::enclave_registry(sender).is_some() +pub struct EnsureEnclaveSigner(PhantomData); +impl EnsureOrigin for EnsureEnclaveSigner +where + T: frame_system::Config + pallet_teebag::Config + pallet_timestamp::Config, + ::AccountId: From<[u8; 32]>, + ::Hash: From<[u8; 32]>, +{ + type Success = T::AccountId; + fn try_origin(o: T::RuntimeOrigin) -> Result { + o.into().and_then(|o| match o { + frame_system::RawOrigin::Signed(who) + if pallet_teebag::EnclaveRegistry::::contains_key(&who) => + { + Ok(who) + }, + r => Err(T::RuntimeOrigin::from(r)), + }) + } + + #[cfg(feature = "runtime-benchmarks")] + fn try_successful_origin() -> Result { + use pallet_teebag::test_util::{get_signer, TEST8_MRENCLAVE, TEST8_SIGNER_PUB}; + let signer: ::AccountId = get_signer(TEST8_SIGNER_PUB); + if !pallet_teebag::EnclaveRegistry::::contains_key(signer.clone()) { + assert_ok!(pallet_teebag::Pallet::::add_enclave( + &signer, + &pallet_teebag::Enclave::default().with_mrenclave(TEST8_MRENCLAVE), + )); + } + Ok(frame_system::RawOrigin::Signed(signer).into()) } } diff --git a/runtime/litentry/src/lib.rs b/runtime/litentry/src/lib.rs index 39ec8060be..29171d88d9 100644 --- a/runtime/litentry/src/lib.rs +++ b/runtime/litentry/src/lib.rs @@ -1118,12 +1118,6 @@ impl pallet_score_staking::AccountIdConvert for IdentityAccountIdConver } } -impl pallet_score_staking::TokenStakingAuthorizer for pallet_teebag::Pallet { - fn can_update_staking(sender: &::AccountId) -> bool { - pallet_teebag::Pallet::::enclave_registry(sender).is_some() - } -} - impl pallet_score_staking::Config for Runtime { type Currency = Balances; type RuntimeEvent = RuntimeEvent; @@ -1133,7 +1127,7 @@ impl pallet_score_staking::Config for Runtime { type YearlyIssuance = ConstU128<{ 100_000_000 * UNIT }>; type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<1_000_000>; - type TokenStakingAuthorizer = pallet_teebag::Pallet; + type TEECallOrigin = EnsureEnclaveSigner; } impl runtime_common::BaseRuntimeRequirements for Runtime {} diff --git a/runtime/rococo/src/lib.rs b/runtime/rococo/src/lib.rs index fcb2fdc2a3..25ed6b2bf7 100644 --- a/runtime/rococo/src/lib.rs +++ b/runtime/rococo/src/lib.rs @@ -1160,12 +1160,6 @@ impl pallet_score_staking::AccountIdConvert for IdentityAccountIdConver } } -impl pallet_score_staking::TokenStakingAuthorizer for pallet_teebag::Pallet { - fn can_update_staking(sender: &::AccountId) -> bool { - pallet_teebag::Pallet::::enclave_registry(sender).is_some() - } -} - impl pallet_score_staking::Config for Runtime { type Currency = Balances; type RuntimeEvent = RuntimeEvent; @@ -1174,7 +1168,7 @@ impl pallet_score_staking::Config for Runtime { type YearlyIssuance = ConstU128<{ 100_000_000 * UNIT }>; type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<1_000_000>; - type TokenStakingAuthorizer = pallet_teebag::Pallet; + type TEECallOrigin = EnsureEnclaveSigner; } impl runtime_common::BaseRuntimeRequirements for Runtime {} From 04fc8e0159550cd087503ec75338e4adb2d00481 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 12 Sep 2024 14:17:40 +0000 Subject: [PATCH 55/61] fixing mocks --- pallets/identity-management/src/mock.rs | 5 +++++ precompiles/score-staking/src/mock.rs | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/pallets/identity-management/src/mock.rs b/pallets/identity-management/src/mock.rs index 79777fdd20..1ea31a1c1d 100644 --- a/pallets/identity-management/src/mock.rs +++ b/pallets/identity-management/src/mock.rs @@ -69,6 +69,11 @@ where } Ok(frame_system::RawOrigin::Signed(signer).into()) } + + #[cfg(not(feature = "runtime-benchmarks"))] + fn try_successful_origin() -> Result { + Err(()) + } } // Configure a mock runtime to test the pallet. diff --git a/precompiles/score-staking/src/mock.rs b/precompiles/score-staking/src/mock.rs index c127b263d8..f770d6bf50 100644 --- a/precompiles/score-staking/src/mock.rs +++ b/precompiles/score-staking/src/mock.rs @@ -294,6 +294,11 @@ where } Ok(frame_system::RawOrigin::Signed(signer).into()) } + + #[cfg(not(feature = "runtime-benchmarks"))] + fn try_successful_origin() -> Result { + Err(()) + } } pub fn alice() -> AccountId { From a2568629b3213b4df7ae6fbbab60bcfb38bb35be Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 12 Sep 2024 15:13:55 +0000 Subject: [PATCH 56/61] making the distribution directly instead of storing the amount to token_staking_amount --- pallets/score-staking/src/lib.rs | 4 +++- pallets/score-staking/src/tests.rs | 19 +++++-------------- pallets/score-staking/src/types.rs | 1 - 3 files changed, 8 insertions(+), 16 deletions(-) diff --git a/pallets/score-staking/src/lib.rs b/pallets/score-staking/src/lib.rs index d50b747ee4..16d947f403 100644 --- a/pallets/score-staking/src/lib.rs +++ b/pallets/score-staking/src/lib.rs @@ -491,7 +491,9 @@ pub mod pallet { return Err(Error::::TokenStakingAmountAlreadyUpdated.into()); } let last_round = Round::::get(); - s.token_staking_amount = amount; + s.last_round_reward += amount; + s.total_reward += amount; + s.unpaid_reward += amount; s.last_token_distributed_round = last_round.index; Scores::::insert(account.clone(), s); Self::deposit_event(Event::TokenStakingAmountUpdated { diff --git a/pallets/score-staking/src/tests.rs b/pallets/score-staking/src/tests.rs index 049bba57b6..3075fd5400 100644 --- a/pallets/score-staking/src/tests.rs +++ b/pallets/score-staking/src/tests.rs @@ -174,7 +174,6 @@ fn score_staking_works() { total_reward: 0, last_round_reward: 0, unpaid_reward: 0, - token_staking_amount: 0, last_token_distributed_round: 0 } ); @@ -208,7 +207,6 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: alice_total_reward, unpaid_reward: alice_total_reward, - token_staking_amount: 0, last_token_distributed_round: 0, } ); @@ -232,7 +230,6 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: round_reward(), unpaid_reward: alice_total_reward, - token_staking_amount: 0, last_token_distributed_round: 0, } ); @@ -259,7 +256,6 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: calculate_round_reward(2000, 2000, 900, 1600), unpaid_reward: alice_total_reward, - token_staking_amount: 0, last_token_distributed_round: 0, } ); @@ -284,7 +280,6 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: calculate_round_reward(2000, 3000, 900, 3200), unpaid_reward: alice_total_reward, - token_staking_amount: 0, last_token_distributed_round: 0, } ); @@ -295,7 +290,6 @@ fn score_staking_works() { total_reward: bob_total_reward, last_round_reward: bob_total_reward, unpaid_reward: bob_total_reward, - token_staking_amount: 0, last_token_distributed_round: 0, } ); @@ -346,7 +340,6 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: round_reward(), unpaid_reward: alice_total_reward, - token_staking_amount: 0, last_token_distributed_round: 0, } ); @@ -359,7 +352,6 @@ fn score_staking_works() { total_reward: bob_total_reward, last_round_reward: 0, unpaid_reward: bob_total_reward, - token_staking_amount: 0, last_token_distributed_round: 0, } ); @@ -408,7 +400,6 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward(), - token_staking_amount: 0, last_token_distributed_round: 0, } ); @@ -425,7 +416,6 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward() - 200, - token_staking_amount: 0, last_token_distributed_round: 0, } ); @@ -442,7 +432,6 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: 0, - token_staking_amount: 0, last_token_distributed_round: 0, } ); @@ -491,6 +480,8 @@ fn update_token_staking_amount_works() { 2, )); + total_reward += 1000; + assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { @@ -498,7 +489,6 @@ fn update_token_staking_amount_works() { total_reward, last_round_reward: total_reward, unpaid_reward: total_reward, - token_staking_amount: 1000, last_token_distributed_round: 2, } ); @@ -524,6 +514,8 @@ fn update_token_staking_amount_works() { 3, )); + total_reward += 1200; + System::assert_last_event(RuntimeEvent::ScoreStaking( Event::::TokenStakingAmountUpdated { account: alice(), amount: 1200 }, )); @@ -533,9 +525,8 @@ fn update_token_staking_amount_works() { ScorePayment { score: 500, total_reward, - last_round_reward: round_reward(), + last_round_reward: round_reward() + 1200, unpaid_reward: total_reward, - token_staking_amount: 1200, last_token_distributed_round: 3, } ); diff --git a/pallets/score-staking/src/types.rs b/pallets/score-staking/src/types.rs index b7c1e3d346..5b6edda153 100644 --- a/pallets/score-staking/src/types.rs +++ b/pallets/score-staking/src/types.rs @@ -83,6 +83,5 @@ pub struct ScorePayment { pub total_reward: Balance, pub last_round_reward: Balance, pub unpaid_reward: Balance, - pub token_staking_amount: Balance, pub last_token_distributed_round: RoundIndex, } From 3de18226db83d33adc0aa57bad49831c6f6e2fa9 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 12 Sep 2024 15:23:15 +0000 Subject: [PATCH 57/61] fixing precompiles tests --- precompiles/score-staking/src/tests.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/precompiles/score-staking/src/tests.rs b/precompiles/score-staking/src/tests.rs index 7d21dea24c..c096c09a73 100644 --- a/precompiles/score-staking/src/tests.rs +++ b/precompiles/score-staking/src/tests.rs @@ -66,7 +66,6 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward(), - token_staking_amount: 0, last_token_distributed_round: 0, } ); @@ -91,7 +90,6 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward() - 200, - token_staking_amount: 0, last_token_distributed_round: 0, } ); @@ -116,7 +114,6 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: 0, - token_staking_amount: 0, last_token_distributed_round: 0, } ); From a52c90dd1c60b670abfca2182b5b01c04c5cbf40 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 12 Sep 2024 15:23:24 +0000 Subject: [PATCH 58/61] reverting try_successful_origin --- precompiles/score-staking/src/mock.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/precompiles/score-staking/src/mock.rs b/precompiles/score-staking/src/mock.rs index f770d6bf50..c127b263d8 100644 --- a/precompiles/score-staking/src/mock.rs +++ b/precompiles/score-staking/src/mock.rs @@ -294,11 +294,6 @@ where } Ok(frame_system::RawOrigin::Signed(signer).into()) } - - #[cfg(not(feature = "runtime-benchmarks"))] - fn try_successful_origin() -> Result { - Err(()) - } } pub fn alice() -> AccountId { From af81e389376865e59958c154b2a65de145758e73 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 12 Sep 2024 15:26:46 +0000 Subject: [PATCH 59/61] reverting it in identity-management as well --- pallets/identity-management/src/mock.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/pallets/identity-management/src/mock.rs b/pallets/identity-management/src/mock.rs index 1ea31a1c1d..79777fdd20 100644 --- a/pallets/identity-management/src/mock.rs +++ b/pallets/identity-management/src/mock.rs @@ -69,11 +69,6 @@ where } Ok(frame_system::RawOrigin::Signed(signer).into()) } - - #[cfg(not(feature = "runtime-benchmarks"))] - fn try_successful_origin() -> Result { - Err(()) - } } // Configure a mock runtime to test the pallet. From 8e375f0e5fdce241cb30766d5f997c2c53f22130 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 12 Sep 2024 15:42:42 +0000 Subject: [PATCH 60/61] fixing precompiles mock --- precompiles/score-staking/src/mock.rs | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/precompiles/score-staking/src/mock.rs b/precompiles/score-staking/src/mock.rs index c127b263d8..bc7c555a56 100644 --- a/precompiles/score-staking/src/mock.rs +++ b/precompiles/score-staking/src/mock.rs @@ -281,19 +281,6 @@ where r => Err(T::RuntimeOrigin::from(r)), }) } - - #[cfg(feature = "runtime-benchmarks")] - fn try_successful_origin() -> Result { - use pallet_teebag::test_util::{get_signer, TEST8_MRENCLAVE, TEST8_SIGNER_PUB}; - let signer: ::AccountId = get_signer(TEST8_SIGNER_PUB); - if !pallet_teebag::EnclaveRegistry::::contains_key(signer.clone()) { - assert_ok!(pallet_teebag::Pallet::::add_enclave( - &signer, - &pallet_teebag::Enclave::default().with_mrenclave(TEST8_MRENCLAVE), - )); - } - Ok(frame_system::RawOrigin::Signed(signer).into()) - } } pub fn alice() -> AccountId { From 2db3da4ef80e8c37c3e60deba784e0d04a442ccc Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Fri, 13 Sep 2024 08:24:01 +0000 Subject: [PATCH 61/61] fixing precompiles score-staking mock --- precompiles/score-staking/Cargo.toml | 1 + precompiles/score-staking/src/mock.rs | 13 +++++++++++++ 2 files changed, 14 insertions(+) diff --git a/precompiles/score-staking/Cargo.toml b/precompiles/score-staking/Cargo.toml index 9329466b00..0913f0877b 100644 --- a/precompiles/score-staking/Cargo.toml +++ b/precompiles/score-staking/Cargo.toml @@ -46,3 +46,4 @@ std = [ "sp-runtime/std", "sp-std/std", ] +runtime-benchmarks = [] diff --git a/precompiles/score-staking/src/mock.rs b/precompiles/score-staking/src/mock.rs index bc7c555a56..c127b263d8 100644 --- a/precompiles/score-staking/src/mock.rs +++ b/precompiles/score-staking/src/mock.rs @@ -281,6 +281,19 @@ where r => Err(T::RuntimeOrigin::from(r)), }) } + + #[cfg(feature = "runtime-benchmarks")] + fn try_successful_origin() -> Result { + use pallet_teebag::test_util::{get_signer, TEST8_MRENCLAVE, TEST8_SIGNER_PUB}; + let signer: ::AccountId = get_signer(TEST8_SIGNER_PUB); + if !pallet_teebag::EnclaveRegistry::::contains_key(signer.clone()) { + assert_ok!(pallet_teebag::Pallet::::add_enclave( + &signer, + &pallet_teebag::Enclave::default().with_mrenclave(TEST8_MRENCLAVE), + )); + } + Ok(frame_system::RawOrigin::Signed(signer).into()) + } } pub fn alice() -> AccountId {