Skip to content
This repository has been archived by the owner on Feb 21, 2024. It is now read-only.

Commit

Permalink
Merge pull request paritytech#273 from subspace/block-rewards
Browse files Browse the repository at this point in the history
Add custom block rewards address
  • Loading branch information
i1i1 authored Mar 6, 2022
2 parents 0f544ec + 7c30e3c commit 2a4e635
Show file tree
Hide file tree
Showing 19 changed files with 117 additions and 19 deletions.
3 changes: 3 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions crates/pallet-rewards/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ codec = { package = "parity-scale-codec", version = "2.3.0", default-features =
frame-support = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/substrate", rev = "e6def65920d30029e42d498cb07cec5dd433b927" }
frame-system = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/substrate", rev = "e6def65920d30029e42d498cb07cec5dd433b927" }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
subspace-runtime-primitives = { version = "0.1.0", default-features = false, path = "../subspace-runtime-primitives" }

[features]
default = ["std"]
Expand Down
10 changes: 6 additions & 4 deletions crates/pallet-rewards/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@

mod default_weights;

use frame_support::traits::{Currency, FindAuthor, Get};
use frame_support::traits::{Currency, Get};
use frame_support::weights::Weight;
pub use pallet::*;
use subspace_runtime_primitives::FindBlockRewardAddress;

pub trait WeightInfo {
fn on_initialize() -> Weight;
Expand All @@ -33,8 +34,9 @@ pub trait WeightInfo {
mod pallet {
use super::WeightInfo;
use frame_support::pallet_prelude::*;
use frame_support::traits::{Currency, FindAuthor};
use frame_support::traits::Currency;
use frame_system::pallet_prelude::*;
use subspace_runtime_primitives::FindBlockRewardAddress;

type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
Expand All @@ -50,7 +52,7 @@ mod pallet {
#[pallet::constant]
type BlockReward: Get<BalanceOf<Self>>;

type FindAuthor: FindAuthor<Self::AccountId>;
type FindBlockRewardAddress: FindBlockRewardAddress<Self::AccountId>;

type WeightInfo: WeightInfo;
}
Expand Down Expand Up @@ -82,7 +84,7 @@ mod pallet {

impl<T: Config> Pallet<T> {
fn do_initialize(_n: T::BlockNumber) {
let block_author = T::FindAuthor::find_author(
let block_author = T::FindBlockRewardAddress::find_block_reward_address(
frame_system::Pallet::<T>::digest()
.logs
.iter()
Expand Down
1 change: 1 addition & 0 deletions crates/pallet-subspace/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ sp-io = { version = "5.0.0", default-features = false, git = "https://github.com
sp-runtime = { version = "5.0.0", default-features = false, git = "https://github.com/paritytech/substrate", rev = "e6def65920d30029e42d498cb07cec5dd433b927" }
sp-std = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/substrate", rev = "e6def65920d30029e42d498cb07cec5dd433b927" }
subspace-core-primitives = { version = "0.1.0", default-features = false, path = "../subspace-core-primitives" }
subspace-runtime-primitives = { version = "0.1.0", default-features = false, path = "../subspace-runtime-primitives" }

[dev-dependencies]
pallet-balances = { version = "4.0.0-dev", git = "https://github.com/paritytech/substrate", rev = "e6def65920d30029e42d498cb07cec5dd433b927" }
Expand Down
12 changes: 12 additions & 0 deletions crates/pallet-subspace/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,18 @@ impl<T: Config> frame_support::traits::FindAuthor<T::AccountId> for Pallet<T> {
}
}

impl<T: Config> subspace_runtime_primitives::FindBlockRewardAddress<T::AccountId> for Pallet<T> {
fn find_block_reward_address<'a, I>(digests: I) -> Option<T::AccountId>
where
I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
{
digests
.into_iter()
.find_map(|(id, data)| DigestItemRef::PreRuntime(&id, data).as_subspace_pre_digest())
.map(|pre_digest| pre_digest.solution.reward_address)
}
}

impl<T: Config> frame_support::traits::Randomness<T::Hash, T::BlockNumber> for Pallet<T> {
fn random(subject: &[u8]) -> (T::Hash, T::BlockNumber) {
let mut subject = subject.to_vec();
Expand Down
2 changes: 2 additions & 0 deletions crates/pallet-subspace/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ pub fn go_to_block(keypair: &Keypair, block: u64, slot: u64) {
slot.into(),
Solution {
public_key: FarmerPublicKey::unchecked_from(keypair.public.to_bytes()),
reward_address: FarmerPublicKey::unchecked_from(keypair.public.to_bytes()),
piece_index: 0,
encoding,
signature: keypair.sign(ctx.bytes(&tag)).to_bytes().into(),
Expand Down Expand Up @@ -250,6 +251,7 @@ pub fn generate_equivocation_proof(
slot,
Solution {
public_key: public_key.clone(),
reward_address: public_key.clone(),
piece_index,
encoding,
signature: signature.into(),
Expand Down
1 change: 1 addition & 0 deletions crates/pallet-transaction-fees/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ codec = { package = "parity-scale-codec", version = "2.3.0", default-features =
frame-support = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/substrate", rev = "e6def65920d30029e42d498cb07cec5dd433b927" }
frame-system = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/substrate", rev = "e6def65920d30029e42d498cb07cec5dd433b927" }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
subspace-runtime-primitives = { version = "0.1.0", default-features = false, path = "../subspace-runtime-primitives" }

[features]
default = ["std"]
Expand Down
10 changes: 6 additions & 4 deletions crates/pallet-transaction-fees/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@ mod default_weights;

use codec::{Codec, Decode, Encode};
use frame_support::sp_runtime::traits::Zero;
use frame_support::traits::{Currency, FindAuthor, Get};
use frame_support::traits::{Currency, Get};
use frame_support::weights::Weight;
pub use pallet::*;
use scale_info::TypeInfo;
use subspace_runtime_primitives::FindBlockRewardAddress;

type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
Expand All @@ -47,8 +48,9 @@ struct CollectedFees<Balance: Codec> {
mod pallet {
use super::{BalanceOf, CollectedFees, WeightInfo};
use frame_support::pallet_prelude::*;
use frame_support::traits::{Currency, FindAuthor};
use frame_support::traits::Currency;
use frame_system::pallet_prelude::*;
use subspace_runtime_primitives::FindBlockRewardAddress;

#[pallet::config]
pub trait Config: frame_system::Config {
Expand Down Expand Up @@ -85,7 +87,7 @@ mod pallet {

type Currency: Currency<Self::AccountId>;

type FindAuthor: FindAuthor<Self::AccountId>;
type FindBlockRewardAddress: FindBlockRewardAddress<Self::AccountId>;

type WeightInfo: WeightInfo;
}
Expand Down Expand Up @@ -172,7 +174,7 @@ where
BalanceOf<T>: From<u64>,
{
fn do_initialize(_n: T::BlockNumber) {
let block_author = T::FindAuthor::find_author(
let block_author = T::FindBlockRewardAddress::find_block_reward_address(
frame_system::Pallet::<T>::digest()
.logs
.iter()
Expand Down
15 changes: 14 additions & 1 deletion crates/sc-consensus-subspace-rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,16 +341,29 @@ where
let public_key =
match FarmerPublicKey::from_slice(&solution.public_key) {
Ok(public_key) => public_key,
Err(_) => {
Err(()) => {
warn!(
"Failed to convert public key: {:?}",
solution.public_key
);
return;
}
};
let reward_address =
match FarmerPublicKey::from_slice(&solution.reward_address) {
Ok(public_key) => public_key,
Err(()) => {
warn!(
"Failed to convert reward address: {:?}",
solution.reward_address,
);
return;
}
};

let solution = Solution {
public_key,
reward_address,
piece_index: solution.piece_index,
encoding: solution.encoding,
signature: solution.signature,
Expand Down
5 changes: 5 additions & 0 deletions crates/sc-consensus-subspace/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,9 @@ fn run_one_test(mutator: impl Fn(&mut TestHeader, Stage) + Send + Sync + 'static
let _ = solution_sender
.send(Solution {
public_key: FarmerPublicKey::unchecked_from(keypair.public.to_bytes()),
reward_address: FarmerPublicKey::unchecked_from(
keypair.public.to_bytes(),
),
piece_index,
encoding,
signature: keypair.sign(ctx.bytes(&tag)).to_bytes().into(),
Expand Down Expand Up @@ -666,6 +669,7 @@ pub fn dummy_claim_slot(slot: Slot) -> Option<(PreDigest<FarmerPublicKey>, Farme
PreDigest {
solution: Solution {
public_key: FarmerPublicKey::unchecked_from([0u8; 32]),
reward_address: FarmerPublicKey::unchecked_from([0u8; 32]),
piece_index: 0,
encoding: Piece::default(),
signature: Signature::default(),
Expand Down Expand Up @@ -725,6 +729,7 @@ fn propose_and_import_block<Transaction: Send + 'static>(
slot,
solution: Solution {
public_key: FarmerPublicKey::unchecked_from(keypair.public.to_bytes()),
reward_address: FarmerPublicKey::unchecked_from(keypair.public.to_bytes()),
piece_index: 0,
encoding,
signature: signature.into(),
Expand Down
6 changes: 5 additions & 1 deletion crates/subspace-core-primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,8 @@ impl RootBlock {
pub struct Solution<AccountId> {
/// Public key of the farmer that created the solution
pub public_key: AccountId,
/// Address for receiving block reward
pub reward_address: AccountId,
/// Index of encoded piece
pub piece_index: u64,
/// Encoding
Expand All @@ -476,11 +478,13 @@ pub struct Solution<AccountId> {
pub tag: Tag,
}

impl<AccountId> Solution<AccountId> {
impl<AccountId: Clone> Solution<AccountId> {
/// Dummy solution for the genesis block
pub fn genesis_solution(public_key: AccountId) -> Self {
let reward_address = public_key.clone();
Self {
public_key,
reward_address,
piece_index: 0u64,
encoding: Piece::default(),
signature: Signature::default(),
Expand Down
21 changes: 19 additions & 2 deletions crates/subspace-farmer/src/bin/subspace-farmer/commands/farm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::mem;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use subspace_core_primitives::PublicKey;
use subspace_farmer::ws_rpc_server::{RpcServer, RpcServerImpl};
use subspace_farmer::{
Commitments, Farming, Identity, ObjectMappings, Plot, Plotting, RpcClient, WsRpc,
Expand All @@ -23,6 +24,7 @@ pub(crate) async fn farm(
listen_on: Vec<Multiaddr>,
node_rpc_url: &str,
ws_server_listen_addr: SocketAddr,
reward_address: Option<PublicKey>,
) -> Result<(), anyhow::Error> {
// TODO: This doesn't account for the fact that node can
// have a completely different history to what farmer expects
Expand Down Expand Up @@ -60,6 +62,16 @@ pub(crate) async fn farm(

let identity = Identity::open_or_create(&base_directory)?;

let reward_address = reward_address.unwrap_or_else(|| {
identity
.public_key()
.as_ref()
.to_vec()
.try_into()
.map(From::<[u8; 32]>::from)
.expect("Length of public key is always correct")
});

let subspace_codec = SubspaceCodec::new(identity.public_key());

// Start RPC server
Expand Down Expand Up @@ -120,8 +132,13 @@ pub(crate) async fn farm(
});

// start the farming task
let farming_instance =
Farming::start(plot.clone(), commitments.clone(), client.clone(), identity);
let farming_instance = Farming::start(
plot.clone(),
commitments.clone(),
client.clone(),
identity,
reward_address,
);

// start the background plotting
let plotting_instance = Plotting::start(
Expand Down
14 changes: 13 additions & 1 deletion crates/subspace-farmer/src/bin/subspace-farmer/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ use anyhow::Result;
use clap::{Parser, ValueHint};
use env_logger::Env;
use log::info;
use sp_core::crypto::PublicError;
use std::net::SocketAddr;
use std::path::PathBuf;
use subspace_core_primitives::PublicKey;
use subspace_networking::libp2p::Multiaddr;

#[derive(Debug, Parser)]
Expand Down Expand Up @@ -72,13 +74,21 @@ enum Command {
/// Host and port where built-in WebSocket RPC server should listen for incoming connections
#[clap(long, short, default_value = "127.0.0.1:9955")]
ws_server_listen_addr: SocketAddr,
/// Address for farming rewards
#[clap(long, parse(try_from_str = parse_reward_address))]
reward_address: Option<PublicKey>,
},
}

fn parse_reward_address(s: &str) -> Result<PublicKey, PublicError> {
s.parse::<sp_core::sr25519::Public>()
.map(|key| PublicKey::from(key.0))
}

#[tokio::main]
async fn main() -> Result<()> {
env_logger::init_from_env(Env::new().default_filter_or("info"));
let command: Command = Command::parse();
let command = Command::parse();
match command {
Command::Identity(identity_command) => {
commands::identity(identity_command)?;
Expand All @@ -99,6 +109,7 @@ async fn main() -> Result<()> {
listen_on,
node_rpc_url,
ws_server_listen_addr,
reward_address,
} => {
let path = utils::get_path(custom_path);
commands::farm(
Expand All @@ -107,6 +118,7 @@ async fn main() -> Result<()> {
listen_on,
&node_rpc_url,
ws_server_listen_addr,
reward_address,
)
.await?;
}
Expand Down
9 changes: 7 additions & 2 deletions crates/subspace-farmer/src/farming.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use futures::{future, future::Either};
use log::{debug, error, info, trace, warn};
use std::sync::mpsc;
use std::time::Instant;
use subspace_core_primitives::PublicKey;
use subspace_core_primitives::{LocalChallenge, Salt, Solution};
use subspace_rpc_primitives::{BlockSignature, BlockSigningInfo, SlotInfo, SolutionResponse};
use thiserror::Error;
Expand Down Expand Up @@ -42,15 +43,17 @@ impl Farming {
commitments: Commitments,
client: T,
identity: Identity,
reward_adress: PublicKey,
) -> Self {
// Oneshot channels, that will be used for interrupt/stop the process
let (stop_sender, stop_receiver) = async_oneshot::oneshot();

// Get a handle for the background task, so that we can wait on it later if we want to
let farming_handle = tokio::spawn(async {
let farming_handle = tokio::spawn(async move {
match future::select(
Box::pin(async move {
subscribe_to_slot_info(&client, &plot, &commitments, &identity).await
subscribe_to_slot_info(&client, &plot, &commitments, &identity, reward_adress)
.await
}),
stop_receiver,
)
Expand Down Expand Up @@ -105,6 +108,7 @@ async fn subscribe_to_slot_info<T: RpcClient>(
plot: &Plot,
commitments: &Commitments,
identity: &Identity,
reward_address: PublicKey,
) -> Result<(), FarmingError> {
info!("Subscribing to slot info notifications");
let mut slot_info_notifications = client
Expand Down Expand Up @@ -135,6 +139,7 @@ async fn subscribe_to_slot_info<T: RpcClient>(
let encoding = plot.read(piece_index).map_err(FarmingError::PlotRead)?;
let solution = Solution {
public_key: identity.public_key().to_bytes().into(),
reward_address,
piece_index,
encoding,
signature: identity.sign_farmer_solution(&tag).to_bytes().into(),
Expand Down
Loading

0 comments on commit 2a4e635

Please sign in to comment.