Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
133 commits
Select commit Hold shift + click to select a range
4689acf
Shielding parentchain transfers (#1378)
coax1d Nov 15, 2023
4e4de90
Ab/shield from shard vault (#1497)
brenzi Nov 20, 2023
9672c7e
expose shard and shard vault rpc call (#1498)
brenzi Nov 20, 2023
922e873
[CI] test shielding/unshielding using shard vault (#1499)
brenzi Nov 20, 2023
d2db3e0
fix unresolved imports
m-yahya Nov 22, 2023
636ed10
import String
m-yahya Nov 22, 2023
1eeef4d
reorder imports
m-yahya Nov 22, 2023
a07aad4
fix path
m-yahya Nov 22, 2023
06d312d
fix path
m-yahya Nov 22, 2023
690fe70
comment orders dir path
m-yahya Nov 22, 2023
25ef717
remove comment
m-yahya Nov 23, 2023
882e394
Clean up cargo dependencies (#1503)
Kailai-Wang Nov 28, 2023
b8c6dc6
TargetA shielding unshielding sidechain by event (#1502)
brenzi Nov 29, 2023
60ad5cf
run tests on ubuntu-latest
m-yahya Nov 29, 2023
60ef825
Specify return type in `perform_trusted_operation` (#1500)
kziemianek Nov 30, 2023
4625871
run tests on self-hosted runner
m-yahya Nov 30, 2023
597c787
Fix OOM error in large parentchain syncs with sidechain feature. (#1493)
clangenb Nov 30, 2023
5cb95fe
bump version 0.12.1
brenzi Nov 30, 2023
a36ae4b
support json-rpc request string id (#1512)
kziemianek Dec 1, 2023
642aece
fix matrix host
m-yahya Dec 1, 2023
e40355f
Return encoded extrinsics without padding (#1505)
Kailai-Wang Dec 4, 2023
66223ce
ensure extrinsic success for enclave RA registration and fix #1515 (#…
brenzi Dec 6, 2023
88bf275
rename scripts
m-yahya Dec 7, 2023
b70c116
fix file name
m-yahya Dec 7, 2023
8a3ea6e
skip indirect invocations for initial sync of integritee parentchain …
brenzi Dec 8, 2023
3d31fa7
use envsubst
m-yahya Dec 9, 2023
3c13d36
remove test for BEST-Energy
m-yahya Dec 12, 2023
5f82ff5
automatically init shard if primary worker and no shard exists onchai…
brenzi Dec 13, 2023
c76c688
Hopefully fix of the service test
mosonyi Dec 15, 2023
af4080e
rename test
m-yahya Dec 15, 2023
c5d61cc
peer discovery by shard status with flexible url prefix (#1532)
brenzi Dec 17, 2023
9aa5d60
fix comment
m-yahya Dec 18, 2023
ea55416
comment enclave test
m-yahya Dec 18, 2023
b7c72bb
custom dependencies on parentchain runtimes to decode L1 Events (#1528)
brenzi Dec 21, 2023
78b1356
tiny mods to ease testing and log readability (#1549)
brenzi Dec 21, 2023
7e91475
Ab/fix light client provisioning and unshielding (#1541)
brenzi Dec 21, 2023
7ff60be
got rid of runtime dependencies (#1550)
brenzi Dec 21, 2023
455c3b7
cosmetics (#1551)
brenzi Dec 26, 2023
b85cabb
more robust sidechain block import logic (#1558)
brenzi Dec 29, 2023
c640ddc
make rococo relaychain work as shielding target (#1546)
brenzi Jan 10, 2024
061aff2
propagate parentchain(s) timestamps (#1572)
brenzi Jan 15, 2024
5df0a13
fast-sync targetA/B (#1573)
brenzi Jan 17, 2024
17aae85
add comment
m-yahya Jan 23, 2024
6aa384d
dummy commit to start CI tests
m-yahya Jan 23, 2024
95681ea
Merge tag 'v0.12.11' into my/fix-merged-conflicts
m-yahya Feb 12, 2024
9b840f0
update cargo lock
m-yahya Feb 12, 2024
10f98b4
fix clippy error
m-yahya Feb 12, 2024
f8995bf
update with upstream
m-yahya Feb 12, 2024
05cf25d
update toml_datetime
m-yahya Feb 12, 2024
d1ce9a1
manually set toml_datetime to 0.6.3
m-yahya Feb 12, 2024
0d4734b
update lock files with upstream
m-yahya Feb 12, 2024
f7d5069
update toml_datetime with correct command
m-yahya Feb 12, 2024
6c7c29c
specify the taplo version
m-yahya Feb 14, 2024
297674b
add missing dependencies
m-yahya Feb 14, 2024
11f0aaa
fix args, type mismatches, and inference error
m-yahya Feb 14, 2024
0249a18
fix unreachable pattern
m-yahya Feb 15, 2024
9f10430
fix mismatched types
m-yahya Feb 15, 2024
ebe771f
fix decode response error
m-yahya Feb 21, 2024
487c01a
comment EVM test
m-yahya Feb 21, 2024
fb3c623
test gh runner
m-yahya Apr 3, 2024
2654bac
comment teeracle test
m-yahya Apr 4, 2024
4fdb5e5
comment teeracle tests
m-yahya Apr 4, 2024
e83f47d
comment teeracle test
m-yahya Apr 4, 2024
a7c12af
test commit
m-yahya Apr 4, 2024
8f8c35f
test commit
m-yahya Apr 24, 2024
1a30c25
comment Teeracle test
m-yahya Apr 24, 2024
a5af265
comment teeracle test
m-yahya Apr 24, 2024
5e98531
comment teeracle release
m-yahya Apr 25, 2024
8ae1066
comment tests
m-yahya Apr 25, 2024
1d1f453
Update build_and_test.yml
muhammadumairsabir Apr 26, 2024
355ad4f
Update build_and_test.yml
muhammadumairsabir Apr 26, 2024
c82f277
Update build_and_test.yml
muhammadumairsabir May 28, 2024
9455db5
remove retry option
m-yahya Jul 31, 2024
ac07d62
use actions v3
m-yahya Jul 31, 2024
d98153f
update CI with upstream and comment EVM and Teeracle tests
m-yahya Jul 31, 2024
3734a61
add debug info and use actions v4
m-yahya Jul 31, 2024
3a413d3
use artifact actions v4
m-yahya Jul 31, 2024
a18f4bd
use actions v3 and comment benchmark test
m-yahya Aug 1, 2024
6c5c68f
comment M6, M8, M6 tests
m-yahya Aug 1, 2024
b9c6957
run benchmark with self-hosted runner
m-yahya Aug 1, 2024
733f461
use test-runner-sgx
m-yahya Aug 1, 2024
46bc615
add steps to upload worker artifacts
m-yahya Aug 1, 2024
04b0736
update download worker artifacts
m-yahya Aug 1, 2024
398c718
update with the upstream
m-yahya Aug 1, 2024
8e574ff
fix artifact not found error
m-yahya Aug 1, 2024
f6539d5
run build test on self-hosted runner
m-yahya Aug 1, 2024
27187f1
fix artifact not found
m-yahya Aug 1, 2024
15d0865
update to fix artifact not found
m-yahya Aug 1, 2024
28d3ab0
fix artifacts not found
m-yahya Aug 1, 2024
e5c3f73
fix artifact not found error
m-yahya Aug 1, 2024
fba497f
fix artifact not found
m-yahya Aug 1, 2024
6391a2b
comment download sidechain image
m-yahya Aug 2, 2024
ac8aac3
comment download worker image
m-yahya Aug 2, 2024
46ff609
update with the upstream
m-yahya Aug 2, 2024
e772ec6
update to fix artifact not found error
m-yahya Aug 2, 2024
26eac61
uncomment M6 test
m-yahya Aug 2, 2024
20e3527
uncomment M6 offchain-worker
m-yahya Aug 2, 2024
0b61872
uncomment Release Build of teeracle
m-yahya Aug 2, 2024
a8fc453
add tests
m-yahya Aug 2, 2024
c68f6b6
runs on ubuntu-latest
m-yahya Aug 2, 2024
8437042
use self-hosted to trigger expected checks
m-yahya Aug 2, 2024
9bc265d
update to use ubuntu-latest
m-yahya Aug 2, 2024
9f75a13
update to use ubuntu-latest
m-yahya Aug 2, 2024
fb479c2
run integration-tests on ubuntu-latest
m-yahya Aug 2, 2024
d295fcd
use matrix.host
m-yahya Aug 2, 2024
b0fdc0b
run release-build on integritee-builder-sgx
m-yahya Aug 2, 2024
992f4f7
run M6 on ubuntu-latest
m-yahya Aug 2, 2024
40a2f4d
add host for BestEnergy test
m-yahya Aug 2, 2024
d73e296
run BestEnergy on ubuntu-latest
m-yahya Aug 2, 2024
1c1bacc
update actions version
m-yahya Aug 2, 2024
6cc3d06
fix artifacts not found error
m-yahya Aug 2, 2024
4ace537
correct name for download sidechain image
m-yahya Aug 2, 2024
ec771ec
add M6 test
m-yahya Aug 2, 2024
76a9a9b
use test-runner-sgx
m-yahya Aug 2, 2024
527f98e
remove test yml
m-yahya Aug 2, 2024
558a38f
remove diff file
m-yahya Aug 2, 2024
44b1c6d
use selft hosted
m-yahya Aug 3, 2024
f2b7b2c
use ubuntu latest
m-yahya Aug 3, 2024
4b6ad71
update with upstream
m-yahya Aug 3, 2024
8e1fefd
Merge branch 'my/fix-merged-conflicts' of https://github.com/olisyste…
m-yahya Aug 3, 2024
642946a
use ubuntu latest
m-yahya Aug 3, 2024
d816ba0
use artifact v4 for cli client
m-yahya Aug 3, 2024
2dd4d08
uncomment tests
m-yahya Aug 3, 2024
b95d613
comment script
m-yahya Aug 3, 2024
bc7dfa0
use SW
m-yahya Aug 3, 2024
8c77b9c
add energy market demo
m-yahya Aug 3, 2024
3e316c5
comment tests
m-yahya Aug 3, 2024
dfc8ef4
manually add worker node 1
m-yahya Aug 3, 2024
cc247bd
comment demo
m-yahya Aug 3, 2024
d9d70c4
add tests without demo
m-yahya Aug 3, 2024
c92f8b9
run on ubuntu-latest
m-yahya Aug 3, 2024
5ccde13
run with HW
m-yahya Aug 3, 2024
6f23768
remove bin output files
m-yahya Aug 5, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fast-sync targetA/B (integritee-network#1573)
* let targetA/B fast-sync as well

* disable BadJustification panic

* disable bogus event proof validation

* warning if event proof validation fails

* pause startup if lockfile present. +small fixes

* implement failover to backup db

* refactor account_funding for convenience in production

* only start sidechain block production once everything is ready. provide ETA for syncing parentchains

* fix teeracle build

* filter noisy logs
  • Loading branch information
brenzi authored Jan 17, 2024
commit 5df0a13983745a81251d8f5fc15e07ef0ac47acb
2 changes: 2 additions & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2643,6 +2643,7 @@ dependencies = [
"frame-support",
"futures 0.3.28",
"hex",
"humantime",
"ipfs-api",
"ita-parentchain-interface",
"itc-parentchain",
Expand All @@ -2657,6 +2658,7 @@ dependencies = [
"itp-settings",
"itp-stf-interface",
"itp-storage",
"itp-time-utils",
"itp-types",
"itp-utils",
"its-consensus-slots",
Expand Down
2 changes: 2 additions & 0 deletions app-libs/parentchain-interface/src/event_subscriber.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ pub fn subscribe_to_parentchain_events(api: &ParentchainApi, parentchain_id: Par
let event = event.unwrap();
match event.pallet_name() {
"System" => continue,
"ParaInclusion" => continue,
"MessageQueue" => continue,
"TransactionPayment" => continue,
"Treasury" => continue,
"Balances" => match event.variant_name() {
Expand Down
7 changes: 1 addition & 6 deletions app-libs/parentchain-interface/src/target_a/event_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,7 @@ impl FilterEvents for FilterableEvents {
.iter()
.flatten() // flatten filters out the nones
.filter_map(|ev| match ev.as_event::<BalanceTransfer>() {
Ok(maybe_event) => {
if maybe_event.is_none() {
log::warn!("Transfer event does not exist in parentchain metadata");
};
maybe_event
},
Ok(maybe_event) => maybe_event,
Err(e) => {
log::error!("Could not decode event: {:?}", e);
None
Expand Down
7 changes: 1 addition & 6 deletions app-libs/parentchain-interface/src/target_b/event_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,7 @@ impl FilterEvents for FilterableEvents {
.iter()
.flatten() // flatten filters out the nones
.filter_map(|ev| match ev.as_event::<BalanceTransfer>() {
Ok(maybe_event) => {
if maybe_event.is_none() {
log::warn!("Transfer event does not exist in parentchain metadata");
};
maybe_event
},
Ok(maybe_event) => maybe_event,
Err(e) => {
log::error!("Could not decode event: {:?}", e);
None
Expand Down
2 changes: 1 addition & 1 deletion core-primitives/settings/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ pub mod worker {
// the maximum size of any extrinsic that the enclave will ever generate in B
pub const EXTRINSIC_MAX_SIZE: usize = 13_000;
// the maximum size of the header
pub const HEADER_MAX_SIZE: usize = 200;
pub const HEADER_MAX_SIZE: usize = 512;
// maximum size of shielding key
pub const SHIELDING_KEY_SIZE: usize = 8192;
// maximum size of signing key
Expand Down
52 changes: 48 additions & 4 deletions core/parentchain/light-client/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,12 +123,50 @@ impl<B: Block, LightClientState: Decode + Encode + Debug> LightClientSealing
Ok(unsealed.using_encoded(|bytes| seal(bytes, self.db_path()))?)
}

// unseals db with automatic failover to db backup
fn unseal(&self) -> Result<LightClientState> {
Ok(unseal(self.db_path()).map(|b| Decode::decode(&mut b.as_slice()))??)
Ok(unseal(self.db_path())
.or_else(|e| {
warn!(
"can't unseal db at {:?}. error {:?}. trying backup at {:?}",
self.db_path(),
e,
self.backup_path()
);
// create a copy because we will overwrite the db in the next step
fs::copy(self.db_path(), self.db_path().with_extension("cantunseal")).and_then(
|_| {
fs::copy(self.backup_path(), self.db_path()).and_then(|_| {
unseal(self.db_path()).map_err(|e| {
warn!("{:?}", e);
e
})
})
},
)
})
.map(|b| Decode::decode(&mut b.as_slice()))??)
}

// checks if either the db or its backup can be opened in opaque mode (no unseal)
fn exists(&self) -> bool {
SgxFile::open(self.db_path()).is_ok()
debug!("check if db exists at {:?}", self.db_path());
fs::File::open(self.db_path())
.or_else(|e| {
warn!(
"can't open db at {:?}. error: {:?}. trying restore backup at {:?}",
self.db_path(),
e,
self.backup_path()
);
fs::copy(self.backup_path(), self.db_path())
.and_then(|_| fs::File::open(self.db_path()))
.map_err(|e| {
warn!("{:?}", e);
e
})
})
.is_ok()
}

fn path(&self) -> &Path {
Expand Down Expand Up @@ -206,7 +244,7 @@ where

if !seal.exists() {
info!(
"[{:?}] ChainRelay DB not found, creating new! {}",
"[{:?}] ChainRelay DB for grandpa validator not found, creating new! {}",
seal.parentchain_id(),
seal.path().display()
);
Expand Down Expand Up @@ -257,8 +295,13 @@ where
OCallApi: EnclaveOnChainOCallApi,
LightClientSeal: LightClientSealing<LightClientState = LightValidationState<B>>,
{
trace!("[{:?}] init light client db", parentchain_id);
if !seal.exists() {
info!("[Enclave] ChainRelay DB not found, creating new! {}", seal.path().display());
info!(
"[{:?}] ChainRelay DB for parachain validator not found, creating new! {}",
parentchain_id,
seal.path().display()
);
let validator = init_parachain_validator::<B, OCallApi>(
ocall_api,
RelayState::new(params.genesis_header, Default::default()).into(),
Expand All @@ -269,6 +312,7 @@ where
}

let validation_state = seal.unseal()?;
info!("unseal success");
let genesis_hash = validation_state.genesis_hash()?;

let init_state = if genesis_hash == params.genesis_header.hash() {
Expand Down
8 changes: 4 additions & 4 deletions core/parentchain/light-client/src/justification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,10 +151,10 @@ impl<Block: BlockT> GrandpaJustification<Block> {
set_id,
&mut buf,
) {
debug!("Bad signature on message from {:?}", &signed.id);
return Err(ClientError::BadJustification(
"invalid signature for precommit in grandpa justification".to_string(),
))
warn!("Bad signature on message from {:?}", &signed.id);
// return Err(ClientError::BadJustification(
// "invalid signature for precommit in grandpa justification".to_string(),
// ))
}

if self.commit.target_hash == signed.precommit.target_hash {
Expand Down
10 changes: 9 additions & 1 deletion enclave-runtime/src/initialization/parentchain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ use itc_parentchain::{
};
use itp_component_container::ComponentInitializer;
use itp_settings::worker_mode::ProvideWorkerMode;

use log::*;
use std::{path::PathBuf, vec::Vec};

mod common;
Expand All @@ -61,6 +61,10 @@ pub(crate) fn init_parentchain_components<WorkerModeProvider: ProvideWorkerMode>
) -> Result<Vec<u8>> {
match ParentchainInitParams::decode(&mut encoded_params.as_slice())? {
ParentchainInitParams::Parachain { id, shard, params } => {
info!(
"[{:?}] initializing parachain parentchain components for shard: {:?}",
id, shard
);
let shard_creation_info = get_shard_creation_info_internal(shard)?;

// todo: query timestamp of creation header to give a creation reference to target_a/b as well in order to fast-sync
Expand Down Expand Up @@ -104,6 +108,10 @@ pub(crate) fn init_parentchain_components<WorkerModeProvider: ProvideWorkerMode>
}
},
ParentchainInitParams::Solochain { id, shard, params } => {
info!(
"[{:?}] initializing solochain parentchain components for shard: {:?}",
id, shard
);
let shard_creation_info = get_shard_creation_info_internal(shard)?;
// todo: query timestamp of creation header to give a creation reference to target_a/b as well in order to fast-sync
match id {
Expand Down
6 changes: 3 additions & 3 deletions enclave-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,8 +394,6 @@ pub unsafe extern "C" fn init_parentchain_components(
latest_header: *mut u8,
latest_header_size: usize,
) -> sgx_status_t {
info!("Initializing light client!");

let encoded_params = slice::from_raw_parts(params, params_size);
let latest_header_slice = slice::from_raw_parts_mut(latest_header, latest_header_size);

Expand Down Expand Up @@ -482,8 +480,10 @@ unsafe fn sync_parentchain_internal(
let blocks_to_sync_merkle_roots: Vec<sp_core::H256> =
blocks_to_sync.iter().map(|block| block.block.header.state_root).collect();
// fixme: vulnerability! https://github.com/integritee-network/worker/issues/1518
// until fixed properly, we deactivate the panic upon error altogether in the scope of #1547
if let Err(e) = validate_events(&events_proofs_to_sync, &blocks_to_sync_merkle_roots) {
return e.into()
warn!("ignoring event validation error {:?}", e);
// return e.into()
}
}

Expand Down
4 changes: 2 additions & 2 deletions enclave-runtime/src/shard_creation_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,10 @@ fn init_shard_creation_parentchain_header_internal(
parentchain_id: ParentchainId,
header: Header,
) -> EnclaveResult<()> {
if let Some(_creation_block) =
if let Some(creation_block) =
get_shard_creation_info_internal(shard)?.for_parentchain(parentchain_id)
{
error!("first relevant parentchain header has been previously initialized. cannot change: {:?}", parentchain_id);
error!("first relevant parentchain header has been previously initialized to {:?}. cannot change: {:?}", creation_block.number, parentchain_id);
return Err(Error::Other(
"first relevant parentchain header has been previously initialized. cannot change"
.into(),
Expand Down
2 changes: 2 additions & 0 deletions service/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ dirs = "3.0.2"
env_logger = "0.9"
futures = "0.3"
hex = "0.4.3"
humantime = "2.1"
jsonrpsee = { version = "0.2.0", features = ["client", "ws-server", "macros"] }
lazy_static = "1.4.0"
log = "0.4"
Expand Down Expand Up @@ -51,6 +52,7 @@ itp-node-api = { path = "../core-primitives/node-api" }
itp-settings = { path = "../core-primitives/settings" }
itp-stf-interface = { path = "../core-primitives/stf-interface" }
itp-storage = { path = "../core-primitives/storage" }
itp-time-utils = { path = "../core-primitives/time-utils" }
itp-types = { path = "../core-primitives/types" }
itp-utils = { path = "../core-primitives/utils" }
its-consensus-slots = { path = "../sidechain/consensus/slots" }
Expand Down
92 changes: 40 additions & 52 deletions service/src/account_funding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use codec::Encode;
use itp_node_api::api_client::{AccountApi, ParentchainApi, TEEREX};
use itp_settings::worker::REGISTERING_FEE_FACTOR_FOR_INIT_FUNDS;
use itp_types::{
parentchain::{AccountId, Balance},
parentchain::{AccountId, Balance, ParentchainId},
Moment,
};
use log::*;
Expand All @@ -29,7 +29,8 @@ use sp_core::{
Pair,
};
use sp_keyring::AccountKeyring;
use sp_runtime::MultiAddress;
use sp_runtime::{MultiAddress, Saturating};
use std::{thread, time::Duration};
use substrate_api_client::{
ac_compose_macros::compose_extrinsic, ac_primitives::Bytes, extrinsic::BalancesExtrinsics,
GetBalance, GetStorage, GetTransactionPayment, SubmitAndWatch, XtStatus,
Expand Down Expand Up @@ -60,61 +61,55 @@ impl EnclaveAccountInfoProvider {
}
}

pub fn setup_account_funding(
/// evaluate if the enclave should have more funds and how much more
/// in --dev mode: let Alice pay for missing funds
/// in production mode: wait for manual transfer before continuing
pub fn setup_reasonable_account_funding(
api: &ParentchainApi,
accountid: &AccountId32,
encoded_extrinsic: Vec<u8>,
parentchain_id: ParentchainId,
is_development_mode: bool,
) -> ServiceResult<()> {
// Account funds
if is_development_mode {
// Development mode, the faucet will ensure that the enclave has enough funds
ensure_account_has_funds(api, accountid)?;
} else {
// Production mode, there is no faucet.
let registration_fees = precise_enclave_registration_fees(api, encoded_extrinsic)?;
info!("Registration fees = {:?}", registration_fees);
let free_balance = api.get_free_balance(accountid)?;
info!("TEE's free balance = {:?}", free_balance);

let min_required_funds =
registration_fees.saturating_mul(REGISTERING_FEE_FACTOR_FOR_INIT_FUNDS);
let missing_funds = min_required_funds.saturating_sub(free_balance);

if missing_funds > 0 {
// If there are not enough funds, then the user can send the missing TEER to the enclave address and start again.
println!(
"Enclave account: {:}, missing funds {}",
accountid.to_ss58check(),
missing_funds
loop {
let needed = estimate_funds_needed_to_run_for_a_while(api, accountid, parentchain_id)?;
let free = api.get_free_balance(accountid)?;
let missing_funds = needed.saturating_sub(free);

if missing_funds < needed * 2 / 3 {
return Ok(())
}

if is_development_mode {
info!("[{:?}] Alice will grant {:?} to {:?}", parentchain_id, missing_funds, accountid);
bootstrap_funds_from_alice(api, accountid, missing_funds)?;
} else {
error!(
"[{:?}] Enclave account needs funding. please send at least {:?} to {:?}",
parentchain_id, missing_funds, accountid
);
return Err(Error::Custom(
"Enclave does not have enough funds on the parentchain to register.".into(),
))
thread::sleep(Duration::from_secs(10));
}
}
Ok(())
}

// Alice plays the faucet and sends some funds to the account if balance is low
fn ensure_account_has_funds(api: &ParentchainApi, accountid: &AccountId32) -> Result<(), Error> {
// check account balance
let free_balance = api.get_free_balance(accountid)?;
info!("TEE's free balance = {:?} (Account: {})", free_balance, accountid);

fn estimate_funds_needed_to_run_for_a_while(
api: &ParentchainApi,
accountid: &AccountId32,
parentchain_id: ParentchainId,
) -> ServiceResult<Balance> {
let existential_deposit = api.get_existential_deposit()?;
info!("Existential deposit is = {:?}", existential_deposit);
info!("[{:?}] Existential deposit is = {:?}", parentchain_id, existential_deposit);

let mut min_required_funds: Balance = existential_deposit;
min_required_funds += shard_vault_initial_funds(api)?;

let transfer_fee = estimate_transfer_fee(api)?;
info!("a single transfer costs {:?}", transfer_fee);
info!("[{:?}] a single transfer costs {:?}", parentchain_id, transfer_fee);
min_required_funds += 1000 * transfer_fee;

// Check if this is an integritee chain and Compose a register_sgx_enclave extrinsic
if let Ok(ra_renewal) = api.get_constant::<Moment>("Teerex", "MaxAttestationRenewalPeriod") {
info!("this chain has the teerex pallet. estimating RA fees");
info!("[{:?}] this chain has the teerex pallet. estimating RA fees", parentchain_id);
let encoded_xt: Bytes = compose_extrinsic!(
api,
TEEREX,
Expand All @@ -129,32 +124,25 @@ fn ensure_account_has_funds(api: &ParentchainApi, accountid: &AccountId32) -> Re
api.get_fee_details(&encoded_xt, None).unwrap().unwrap().inclusion_fee.unwrap();
let ra_fee = tx_fee.base_fee + tx_fee.len_fee + tx_fee.adjusted_weight_fee;
info!(
"one enclave registration costs {:?} and needs to be renewed every {:?}h",
"[{:?}] one enclave registration costs {:?} and needs to be renewed every {:?}h",
parentchain_id,
ra_fee,
ra_renewal / 1_000 / 3_600
);
min_required_funds += 5 * ra_fee;
} else {
info!("this chain has no teerex pallet, no need to add RA fees");
info!("[{:?}] this chain has no teerex pallet, no need to add RA fees", parentchain_id);
}

info!(
"we estimate the funding requirement for the primary validateer (worst case) to be {:?}",
"[{:?}] we estimate the funding requirement for the primary validateer (worst case) to be {:?}",
parentchain_id,
min_required_funds
);
let missing_funds = min_required_funds.saturating_sub(free_balance);

if missing_funds > 0 {
info!("Transfer {:?} from Alice to {}", missing_funds, accountid);
bootstrap_funds_from_alice(api, accountid, missing_funds)?;
}
Ok(())
Ok(min_required_funds)
}

fn precise_enclave_registration_fees(
api: &ParentchainApi,
encoded_extrinsic: Vec<u8>,
) -> Result<u128, Error> {
pub fn estimate_fee(api: &ParentchainApi, encoded_extrinsic: Vec<u8>) -> Result<u128, Error> {
let reg_fee_details = api.get_fee_details(&encoded_extrinsic.into(), None)?;
match reg_fee_details {
Some(details) => match details.inclusion_fee {
Expand Down
Loading