Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Predict when the next reward will be farmed #161

Closed
wants to merge 32 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
830e7a7
Add draft version of the function to get total_space_pledged
abhi3700 Mar 13, 2024
23f1e13
Add a TODO for optimize fn
abhi3700 Mar 13, 2024
c44268b
Add code to fetch info from sp_api runtime api calls
abhi3700 Mar 14, 2024
783ea57
Add the fn to predict expected reward timestamp based on space_pledged
abhi3700 Mar 14, 2024
e0dab34
Remove warnings
abhi3700 Mar 14, 2024
991b148
Remove external crate: chrono
abhi3700 Mar 14, 2024
f4bdccd
Replace RPC approach with direct runtime API call to get the solution…
abhi3700 Mar 14, 2024
27fb06d
Add minor changes
abhi3700 Mar 14, 2024
bd91a7e
Made changed based on PR #161#pullrequestreview-1941023244
abhi3700 Mar 18, 2024
4f7b364
Rectify calculation of total space pledged
abhi3700 Mar 18, 2024
f89ab70
Constants fetched using runtime_api
abhi3700 Mar 18, 2024
36dc4d5
minor change
abhi3700 Mar 18, 2024
4752d0f
Refactor runtime API calls in node.rs for better error handling
abhi3700 Mar 18, 2024
bba9146
Resolve conflicts & rebase over v0.1.17
abhi3700 May 8, 2024
06bd101
Add progress bar widget with both themes as well as tooltip
abhi3700 May 16, 2024
9e0bcd6
Parametrize the progress bar function with custom diameter
abhi3700 May 16, 2024
10f76b8
Update circular progress bar
abhi3700 May 17, 2024
2d31e8d
Add the total_space_pledged fn part of the impl block for Consensus node
abhi3700 May 20, 2024
7505f7c
minor fix
abhi3700 May 20, 2024
d00d257
Merge branch 'main' of https://github.com/subspace/space-acres into i…
abhi3700 May 20, 2024
78a1e36
Resolved conflicts & added missing sp-api for this branch
abhi3700 May 20, 2024
1d2ce79
Merge branch 'main' of https://github.com/subspace/space-acres into i…
abhi3700 May 22, 2024
b5dfa7d
Remove solution_range_to_sectors func
abhi3700 May 22, 2024
5755124
Add required TSP metrics to calculate TSP, Allocated space for ETA
abhi3700 May 24, 2024
d0e26f7
Enhance Reward ETA Calculation and Progress Bar Visualization
abhi3700 May 26, 2024
ff6d965
Update reward ETA progress bar variable name
abhi3700 May 27, 2024
784b37f
Fetch chain constants from frontend
abhi3700 May 27, 2024
dc19143
Add last_reward_timestamp field for reward_eta calculation
abhi3700 May 28, 2024
44792bd
Reimplement progress bar with Relm4 Component trait
abhi3700 May 29, 2024
265e630
Merge branch 'main' of https://github.com/subspace/space-acres into i…
abhi3700 May 29, 2024
a1cc6f4
Cleanup
abhi3700 May 29, 2024
1d631e0
Fix clippy warnings
abhi3700 May 29, 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
40 changes: 20 additions & 20 deletions Cargo.lock

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

47 changes: 0 additions & 47 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -130,58 +130,11 @@ numa = [
#
# This list is ordered alphabetically.
[profile.dev.package]
bitvec = { opt-level = 3 }
abhi3700 marked this conversation as resolved.
Show resolved Hide resolved
blake2 = { opt-level = 3 }
blake3 = { opt-level = 3 }
blake2b_simd = { opt-level = 3 }
blst = { opt-level = 3 }
rust-kzg-blst = { opt-level = 3 }
chacha20 = { opt-level = 3 }
chacha20poly1305 = { opt-level = 3 }
cranelift-codegen = { opt-level = 3 }
cranelift-wasm = { opt-level = 3 }
crc32fast = { opt-level = 3 }
crossbeam-deque = { opt-level = 3 }
crypto-mac = { opt-level = 3 }
curve25519-dalek = { opt-level = 3 }
ed25519-zebra = { opt-level = 3 }
flate2 = { opt-level = 3 }
futures-channel = { opt-level = 3 }
hashbrown = { opt-level = 3 }
hash-db = { opt-level = 3 }
hmac = { opt-level = 3 }
httparse = { opt-level = 3 }
integer-sqrt = { opt-level = 3 }
k256 = { opt-level = 3 }
keccak = { opt-level = 3 }
kzg = { opt-level = 3 }
libsecp256k1 = { opt-level = 3 }
libz-sys = { opt-level = 3 }
mio = { opt-level = 3 }
nalgebra = { opt-level = 3 }
num-bigint = { opt-level = 3 }
parking_lot = { opt-level = 3 }
parking_lot_core = { opt-level = 3 }
percent-encoding = { opt-level = 3 }
primitive-types = { opt-level = 3 }
ring = { opt-level = 3 }
rustls = { opt-level = 3 }
secp256k1 = { opt-level = 3 }
sha2 = { opt-level = 3 }
sha3 = { opt-level = 3 }
smallvec = { opt-level = 3 }
snow = { opt-level = 3 }
subspace-archiving = { opt-level = 3 }
subspace-core-primitives = { opt-level = 3 }
subspace-erasure-coding = { opt-level = 3 }
subspace-farmer-components = { opt-level = 3 }
subspace-proof-of-space = { opt-level = 3 }
subspace-proof-of-time = { opt-level = 3 }
twox-hash = { opt-level = 3 }
uint = { opt-level = 3 }
x25519-dalek = { opt-level = 3 }
yamux = { opt-level = 3 }
zeroize = { opt-level = 3 }

abhi3700 marked this conversation as resolved.
Show resolved Hide resolved
[profile.release]
# Substrate runtime requires unwinding.
Expand Down
22 changes: 18 additions & 4 deletions src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ use future::FutureExt;
use futures::channel::mpsc;
use futures::{future, select, SinkExt, StreamExt};
use sc_subspace_chain_specs::GEMINI_3H_CHAIN_SPEC;
use sp_api::ProvideRuntimeApi;
use sp_consensus_subspace::{ChainConstants, SubspaceApi};
use std::error::Error;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -187,7 +189,11 @@ enum LoadedConsensusChainNode {
#[derive(Debug, Clone)]
pub enum NodeNotification {
SyncStateUpdate(SyncState),
BlockImported(BlockImported),
BlockImported {
imported_block: BlockImported,
current_solution_range: u64,
max_pieces_in_sector: u16,
},
}

/// Notification messages send from backend about its operation
Expand Down Expand Up @@ -221,6 +227,7 @@ pub enum BackendNotification {
reward_address_balance: Balance,
initial_farm_states: Vec<InitialFarmState>,
chain_info: ChainInfo,
chain_constants: ChainConstants,
},
Node(NodeNotification),
Farmer(FarmerNotification<FarmIndex>),
Expand Down Expand Up @@ -490,13 +497,15 @@ async fn run(
"networking".to_string(),
)?;

let runtime_api = consensus_node.full_node.client.runtime_api();
notifications_sender
.send(BackendNotification::Running {
raw_config,
best_block_number: consensus_node.best_block_number(),
reward_address_balance: consensus_node.account_balance(&config.reward_address),
initial_farm_states: farmer.initial_farm_states().to_vec(),
chain_info: consensus_node.chain_info().clone(),
chain_constants: runtime_api.chain_constants(consensus_node.best_block_hash())?,
})
.await?;

Expand All @@ -523,9 +532,14 @@ async fn run(
let _on_imported_block_handler_id = consensus_node.on_block_imported({
let notifications_sender = notifications_sender.clone();
// let reward_address_storage_key = account_storage_key(&config.reward_address);

Arc::new(move |&block_imported| {
let notification = NodeNotification::BlockImported(block_imported);
let (current_solution_range, max_pieces_in_sector) = consensus_node.tsp_metrics()?;

Arc::new(move |&imported_block| {
let notification = NodeNotification::BlockImported {
imported_block,
current_solution_range,
max_pieces_in_sector,
};

let mut notifications_sender = notifications_sender.clone();

Expand Down
37 changes: 36 additions & 1 deletion src/backend/farmer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use std::hash::Hash;
use std::num::{NonZeroU8, NonZeroUsize};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::{fmt, fs};
use subspace_core_primitives::crypto::kzg::Kzg;
use subspace_core_primitives::{PublicKey, Record, SectorIndex};
Expand Down Expand Up @@ -693,3 +693,38 @@ where
action_sender,
})
}

/// Calculate the ETA for reward payment.
/// The farmer can expect reward in secs/mins/hrs/days/weeks time.
pub(crate) fn calculate_expected_reward_duration_from_now(
total_space_pledged: u128,
space_pledged: u128,
last_reward_timestamp: Option<u64>,
) -> anyhow::Result<u64> {
// Time elapsed since the last reward payment timestamp.
let time_previous = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
.checked_sub(last_reward_timestamp.unwrap_or(0))
.ok_or_else(|| anyhow!("Overflow occurred while subtracting the last reward timestamp"))?;

// Ensure space_pledged is not zero to prevent division by zero.
if space_pledged == 0 {
return Err(anyhow!("Division by zero error: space_pledged is zero"));
}

// Expected time duration for next reward payment since the last reward payment timestamp.
let expected_time_next = (total_space_pledged as u64)
.checked_div(space_pledged as u64)
.ok_or_else(|| anyhow!("Overflow occurred during division"))?
.checked_mul(time_previous)
.ok_or_else(|| anyhow!("Overflow occurred during multiplication"))?;

// Subtract the duration till now from the expected time duration to get the ETA duration.
let eta_duration = expected_time_next
.checked_sub(time_previous)
.ok_or_else(|| anyhow!("Overflow occurred during final subtraction"))?;

Ok(eta_duration)
}
40 changes: 36 additions & 4 deletions src/backend/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ use sc_network::config::{Ed25519Secret, NodeKeyConfig, NonReservedPeerMode, SetC
use sc_service::{BlocksPruning, Configuration, GenericChainSpec};
use sc_storage_monitor::{StorageMonitorParams, StorageMonitorService};
use serde_json::Value;
use sp_api::ProvideRuntimeApi;
use sp_consensus_subspace::SubspaceApi;
use sp_core::crypto::Ss58AddressFormat;
use sp_core::storage::StorageKey;
use sp_core::H256;
Expand All @@ -30,7 +32,7 @@ use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use subspace_core_primitives::{BlockNumber, PublicKey};
use subspace_core_primitives::{solution_range_to_sectors, BlockNumber, PublicKey};
use subspace_fake_runtime_api::RuntimeApi;
use subspace_networking::libp2p::identity::ed25519::Keypair;
use subspace_networking::libp2p::Multiaddr;
Expand Down Expand Up @@ -120,8 +122,8 @@ struct Handlers {
block_imported: Handler<BlockImported>,
}

pub(super) struct ConsensusNode {
full_node: NewFull<FullClient<RuntimeApi>>,
pub(crate) struct ConsensusNode {
pub full_node: NewFull<FullClient<RuntimeApi>>,
pause_sync: Arc<AtomicBool>,
chain_info: ChainInfo,
handlers: Handlers,
Expand All @@ -134,7 +136,7 @@ impl fmt::Debug for ConsensusNode {
}

impl ConsensusNode {
fn new(
pub(crate) fn new(
full_node: NewFull<FullClient<RuntimeApi>>,
pause_sync: Arc<AtomicBool>,
chain_info: ChainInfo,
Expand Down Expand Up @@ -235,6 +237,20 @@ impl ConsensusNode {
self.full_node.client.info().best_number
}

pub(super) fn best_block_hash(&self) -> H256 {
self.full_node.client.info().best_hash
}

/// Returns current solution range & max. pieces in a sector
pub(super) fn tsp_metrics(&self) -> anyhow::Result<(u64, u16)> {
let runtime_api = self.full_node.client.runtime_api();
let block_hash = self.full_node.client.info().best_hash;
let current_solution_range = runtime_api.solution_ranges(block_hash)?.current;
let max_pieces_in_sector = runtime_api.max_pieces_in_sector(block_hash)?;

Ok((current_solution_range, max_pieces_in_sector))
}

pub(super) fn account_balance(&self, account: &PublicKey) -> Balance {
let reward_address_storage_key = account_storage_key(account);

Expand Down Expand Up @@ -563,3 +579,19 @@ pub(super) async fn create_consensus_node(

Ok(ConsensusNode::new(consensus_node, pause_sync, chain_info))
}

pub(crate) fn total_space_pledged(
current_solution_range: u64,
slot_probability: (u64, u64),
max_pieces_in_sector: u16,
) -> u128 {
// calculate the sectors
let sectors = solution_range_to_sectors(
current_solution_range,
slot_probability,
max_pieces_in_sector,
);

// Calculate the total space pledged
sectors as u128 * max_pieces_in_sector as u128 * subspace_core_primitives::Piece::SIZE as u128
}
3 changes: 3 additions & 0 deletions src/frontend.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
pub mod configuration;
pub mod loading;
pub mod new_version;
#[path = "./frontend/widgets/progress_bar.rs"]
pub mod progress_bar;
pub mod running;
pub mod utils;
Loading
Loading