Skip to content

Commit

Permalink
feat: feature gates (#5287)
Browse files Browse the repository at this point in the history
Description
---
This PR is for reflective purposes regarding feature gating at compile
time. See #5135 for more
info. This PR as it stands is to be used as an example of a network
_type_ based feature gate at compile time.
It allows setting an ENVVAR for the network with conditional compilation
for features. The feature sets can be imported across any crate in the
project easily and then used with the `#[cfg(tari_feature_...)]`
attribute macro.

I've also introduced a secondary commit for binaries to perform a quick
network check against itself to ensure the intended network is supported
by the binary. This check is made non-invasive (not conditionally
compiling possible network) as that method of check ends up being much
more tedious.

Motivation and Context
---
We want some features on some networks, but maybe not all.

How Has This Been Tested?
---
Manually

What process can a PR reviewer use to test or verify this change?
---
Compile a binary with a set network
`TARI_NETWORK=nextnet cargo build --release --bin tari_base_node`

then run the binary with a test network as a parameter:

`./tari_base_node --network esme` 

and receive an error:

```
The application exited because of an internal network error. The network esmeralda is invalid for this binary built for NextNet
```

*Please note*

That running the binary will cause the build to default to the test
network _always_. Meaning this will not work:

```
$ TARI_NETWORK=nextnet cargo build --release --bin tari_base_node
$ cargo run --release --bin tari_base_node --network nextnet
```

The second command `cargo run` will re-build the binary, and without the
`TARI_NETWORK` env set the binary will default to a test binary.

In development if you want to call run and connect to a non test network
you need to also pass the TARI_NETWORK envvar instead of the `--network`
flag.
`TARI_NETWORK=nextnet cargo run --bin tari_base_node --release --
--network nextnet`


Breaking Changes
---

- [x] None

---------

Co-authored-by: Cayle Sharrock <CjS77@users.noreply.github.com>
Co-authored-by: SW van Heerden <swvheerden@gmail.com>
  • Loading branch information
3 people committed Apr 12, 2023
1 parent 344040a commit 72c19dc
Show file tree
Hide file tree
Showing 19 changed files with 418 additions and 17 deletions.
11 changes: 11 additions & 0 deletions Cargo.lock

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

4 changes: 3 additions & 1 deletion applications/tari_app_utilities/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ edition = "2018"
license = "BSD-3-Clause"

[dependencies]
tari_comms = { path = "../../comms/core" }
tari_common = { path = "../../common" }
tari_common_types = { path = "../../base_layer/common_types" }
tari_comms = { path = "../../comms/core" }
tari_features = { version = "0.49.0-pre.6", path = "../../common/tari_features"}
tari_utilities = { version = "0.4.10"}

clap = { version = "3.2.0", features = ["derive", "env"] }
Expand All @@ -22,3 +23,4 @@ thiserror = "^1.0.26"

[build-dependencies]
tari_common = { path = "../../common", features = ["build", "static-application-info"] }
tari_features = { version = "0.49.0-pre.6", path = "../../common/tari_features"}
2 changes: 2 additions & 0 deletions applications/tari_app_utilities/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use tari_common::build::StaticApplicationInfo;
use tari_features::resolver::build_features;

fn main() -> Result<(), Box<dyn std::error::Error>> {
build_features();
let gen = StaticApplicationInfo::initialize()?;
gen.write_consts_to_outdir("consts.rs")?;
Ok(())
Expand Down
1 change: 1 addition & 0 deletions applications/tari_app_utilities/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

pub mod common_cli_args;
pub mod identity_management;
pub mod network_check;
pub mod utilities;

pub mod consts {
Expand Down
66 changes: 66 additions & 0 deletions applications/tari_app_utilities/src/network_check.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright 2023. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use tari_common::{
configuration::Network,
exit_codes::{ExitCode, ExitError},
};
use tari_features::resolver::Target;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum NetworkCheckError {
#[error("The network {0} is invalid for this binary built for MainNet")]
MainNetBinary(Network),
#[error("The network {0} is invalid for this binary built for NextNet")]
NextNetBinary(Network),
#[error("The network {0} is invalid for this binary built for TestNet")]
TestNetBinary(Network),
}

impl From<NetworkCheckError> for ExitError {
fn from(err: NetworkCheckError) -> Self {
Self::new(ExitCode::NetworkError, err)
}
}

#[cfg(tari_network_mainnet)]
pub const TARGET_NETWORK: Target = Target::MainNet;

#[cfg(tari_network_nextnet)]
pub const TARGET_NETWORK: Target = Target::NextNet;

#[cfg(all(not(tari_network_mainnet), not(tari_network_nextnet)))]
pub const TARGET_NETWORK: Target = Target::TestNet;

pub fn is_network_choice_valid(network: Network) -> Result<(), NetworkCheckError> {
match (TARGET_NETWORK, network) {
(Target::MainNet, Network::MainNet | Network::StageNet) => Ok(()),
(Target::MainNet, _) => Err(NetworkCheckError::MainNetBinary(network)),

(Target::NextNet, Network::NextNet) => Ok(()),
(Target::NextNet, _) => Err(NetworkCheckError::NextNetBinary(network)),

(Target::TestNet, Network::LocalNet | Network::Igor | Network::Esmeralda) => Ok(()),
(Target::TestNet, _) => Err(NetworkCheckError::TestNetBinary(network)),
}
}
3 changes: 2 additions & 1 deletion applications/tari_base_node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,5 @@ metrics = ["tari_metrics", "tari_comms/metrics"]
safe = []
libtor = ["tari_libtor"]


[build-dependencies]
tari_features = { version = "0.49.0-pre.6", path = "../../common/tari_features"}
8 changes: 7 additions & 1 deletion applications/tari_base_node/build.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
// Copyright 2022 The Tari Project
// SPDX-License-Identifier: BSD-3-Clause

use tari_features::resolver::build_features;

#[cfg(windows)]
fn main() {
build_features();
use std::env;
println!("cargo:rerun-if-changed=icon.res");
let mut path = env::current_dir().unwrap();
Expand All @@ -11,4 +14,7 @@ fn main() {
}

#[cfg(not(windows))]
fn main() {}
pub fn main() {
build_features();
// Build as usual
}
4 changes: 3 additions & 1 deletion applications/tari_base_node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ use std::{process, sync::Arc};
use commands::{cli_loop::CliLoop, command::CommandContext};
use futures::FutureExt;
use log::*;
use tari_app_utilities::common_cli_args::CommonCliArgs;
use tari_app_utilities::{common_cli_args::CommonCliArgs, network_check::is_network_choice_valid};
use tari_common::{
configuration::bootstrap::{grpc_default_port, ApplicationType},
exit_codes::{ExitCode, ExitError},
Expand Down Expand Up @@ -97,6 +97,8 @@ pub async fn run_base_node_with_cli(
cli: Cli,
shutdown: Shutdown,
) -> Result<(), ExitError> {
is_network_choice_valid(config.network())?;

#[cfg(feature = "metrics")]
{
metrics::install(
Expand Down
22 changes: 13 additions & 9 deletions applications/tari_console_wallet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,22 @@ edition = "2018"
license = "BSD-3-Clause"

[dependencies]
tari_wallet = { path = "../../base_layer/wallet", features = ["bundled_sqlite"] }
tari_crypto = { version = "0.16.11"}
tari_common = { path = "../../common" }
tari_app_grpc = { path = "../tari_app_grpc" }
tari_app_utilities = { path = "../tari_app_utilities" }
tari_common = { path = "../../common" }
tari_common_types = { path = "../../base_layer/common_types" }
tari_comms = { path = "../../comms/core" }
tari_comms_dht = { path = "../../comms/dht" }
tari_common_types = { path = "../../base_layer/common_types" }
tari_contacts = { path = "../../base_layer/contacts" }
tari_crypto = { version = "0.16.11"}
tari_features = { version = "0.49.0-pre.6", path = "../../common/tari_features"}
tari_key_manager = { path = "../../base_layer/key_manager" }
tari_libtor = { path = "../../infrastructure/libtor", optional = true }
tari_p2p = { path = "../../base_layer/p2p", features = ["auto-update"] }
tari_app_grpc = { path = "../tari_app_grpc" }
tari_script = { path = "../../infrastructure/tari_script" }
tari_shutdown = { path = "../../infrastructure/shutdown" }
tari_key_manager = { path = "../../base_layer/key_manager" }
tari_utilities = "0.4.10"
tari_script = { path = "../../infrastructure/tari_script" }
tari_contacts = { path = "../../base_layer/contacts" }
tari_wallet = { path = "../../base_layer/wallet", features = ["bundled_sqlite"] }

# Uncomment for tokio tracing via tokio-console (needs "tracing" featurs)
#console-subscriber = "0.1.3"
Expand Down Expand Up @@ -63,9 +64,12 @@ version = "^0.16"
default-features = false
features = ["crossterm"]

[build-dependencies]
tari_features = { version = "0.49.0-pre.6", path = "../../common/tari_features"}

[features]
avx2 = ["tari_core/avx2", "tari_crypto/simd_backend", "tari_wallet/avx2", "tari_comms/avx2", "tari_comms_dht/avx2", "tari_p2p/avx2", "tari_key_manager/avx2"]
libtor = ["tari_libtor"]

[package.metadata.cargo-machete]
ignored = ["strum"]
ignored = ["strum"]
8 changes: 7 additions & 1 deletion applications/tari_console_wallet/build.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
// Copyright 2022 The Tari Project
// SPDX-License-Identifier: BSD-3-Clause

use tari_features::resolver::build_features;

#[cfg(windows)]
fn main() {
build_features();
use std::env;
println!("cargo:rerun-if-changed=icon.res");
let mut path = env::current_dir().unwrap();
Expand All @@ -11,4 +14,7 @@ fn main() {
}

#[cfg(not(windows))]
fn main() {}
pub fn main() {
build_features();
// Build as usual
}
4 changes: 3 additions & 1 deletion applications/tari_console_wallet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ pub use cli::{
use init::{change_password, get_base_node_peer_config, init_wallet, start_wallet, tari_splash_screen, WalletBoot};
use log::*;
use recovery::{get_seed_from_seed_words, prompt_private_key_from_seed_words};
use tari_app_utilities::{common_cli_args::CommonCliArgs, consts};
use tari_app_utilities::{common_cli_args::CommonCliArgs, consts, network_check::is_network_choice_valid};
use tari_common::{
configuration::bootstrap::ApplicationType,
exit_codes::{ExitCode, ExitError},
Expand Down Expand Up @@ -114,6 +114,8 @@ pub fn run_wallet_with_cli(
consts::APP_VERSION
);

is_network_choice_valid(config.wallet.network)?;

let password = get_password(config, &cli);

if password.is_none() {
Expand Down
3 changes: 2 additions & 1 deletion applications/tari_merge_mining_proxy/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,5 @@ tonic = "0.6.2"
tracing = "0.1"
url = "2.1.1"

[dev-dependencies]
[build-dependencies]
tari_features = { version = "0.49.0-pre.6", path = "../../common/tari_features"}
8 changes: 7 additions & 1 deletion applications/tari_merge_mining_proxy/build.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
// Copyright 2022 The Tari Project
// SPDX-License-Identifier: BSD-3-Clause

use tari_features::resolver::build_features;

#[cfg(windows)]
fn main() {
build_features();
use std::env;
println!("cargo:rerun-if-changed=icon.res");
let mut path = env::current_dir().unwrap();
Expand All @@ -11,4 +14,7 @@ fn main() {
}

#[cfg(not(windows))]
fn main() {}
pub fn main() {
build_features();
// Build as usual
}
15 changes: 15 additions & 0 deletions common/tari_features/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "tari_features"
description = "Compilable features for Tari applications"
authors = ["The Tari Development Community"]
repository = "https://github.com/tari-project/tari"
homepage = "https://tari.com"
readme = "README.md"
license = "BSD-3-Clause"
version = "0.49.0-pre.6"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
tari_common = { path = "../../common" }
Loading

0 comments on commit 72c19dc

Please sign in to comment.