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

tests(config): Add tests for old configs #4676

Merged
merged 13 commits into from
Jun 27, 2022
1 change: 1 addition & 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 zebra-network/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ bytes = "1.1.0"
chrono = "0.4.19"
hex = "0.4.3"
humantime-serde = "1.1.1"
indexmap = { version = "1.8.2", features = ["serde"] }
lazy_static = "1.4.0"
ordered-map = "0.4.2"
pin-project = "1.0.10"
Expand Down
13 changes: 7 additions & 6 deletions zebra-network/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::{
time::Duration,
};

use indexmap::IndexSet;
use serde::{de, Deserialize, Deserializer};

use zebra_chain::parameters::Network;
Expand Down Expand Up @@ -55,11 +56,11 @@ pub struct Config {

/// A list of initial peers for the peerset when operating on
/// mainnet.
pub initial_mainnet_peers: HashSet<String>,
pub initial_mainnet_peers: IndexSet<String>,

/// A list of initial peers for the peerset when operating on
/// testnet.
pub initial_testnet_peers: HashSet<String>,
pub initial_testnet_peers: IndexSet<String>,

/// The initial target size for the peer set.
///
Expand Down Expand Up @@ -127,7 +128,7 @@ impl Config {
}

/// Returns the initial seed peer hostnames for the configured network.
pub fn initial_peer_hostnames(&self) -> &HashSet<String> {
pub fn initial_peer_hostnames(&self) -> &IndexSet<String> {
match self.network {
Network::Mainnet => &self.initial_mainnet_peers,
Network::Testnet => &self.initial_testnet_peers,
Expand All @@ -136,7 +137,7 @@ impl Config {

/// Resolve initial seed peer IP addresses, based on the configured network.
pub async fn initial_peers(&self) -> HashSet<SocketAddr> {
Config::resolve_peers(self.initial_peer_hostnames()).await
Config::resolve_peers(&self.initial_peer_hostnames().iter().cloned().collect()).await
}

/// Concurrently resolves `peers` into zero or more IP addresses, with a
Expand Down Expand Up @@ -296,8 +297,8 @@ impl<'de> Deserialize<'de> for Config {
struct DConfig {
listen_addr: String,
network: Network,
initial_mainnet_peers: HashSet<String>,
initial_testnet_peers: HashSet<String>,
initial_mainnet_peers: IndexSet<String>,
initial_testnet_peers: IndexSet<String>,
peerset_initial_target_size: usize,
#[serde(alias = "new_peer_interval", with = "humantime_serde")]
crawl_new_peer_interval: Duration,
Expand Down
10 changes: 5 additions & 5 deletions zebra-network/src/peer_set/initialize/tests/vectors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@
//! skip all the network tests by setting the `ZEBRA_SKIP_NETWORK_TESTS` environmental variable.
use std::{
collections::HashSet,
net::{Ipv4Addr, SocketAddr},
sync::Arc,
time::{Duration, Instant},
};

use chrono::Utc;
use futures::{channel::mpsc, FutureExt, StreamExt};
use indexmap::IndexSet;
use tokio::{net::TcpStream, task::JoinHandle};
use tower::{service_fn, Service};
use tracing::Span;
Expand Down Expand Up @@ -1137,7 +1137,7 @@ async fn add_initial_peers_deadlock() {
// Create a list of dummy IPs, and initialize a config using them as the
// initial peers. The amount of these peers will overflow
// `PEERSET_INITIAL_TARGET_SIZE`.
let mut peers = HashSet::new();
let mut peers = IndexSet::new();
for address_number in 0..PEER_COUNT {
peers.insert(
SocketAddr::new(Ipv4Addr::new(127, 1, 1, address_number as _).into(), 1).to_string(),
Expand Down Expand Up @@ -1173,8 +1173,8 @@ async fn local_listener_port_with(listen_addr: SocketAddr, network: Network) {
network,

// Stop Zebra making outbound connections
initial_mainnet_peers: HashSet::new(),
initial_testnet_peers: HashSet::new(),
initial_mainnet_peers: IndexSet::new(),
initial_testnet_peers: IndexSet::new(),

..Config::default()
};
Expand Down Expand Up @@ -1468,7 +1468,7 @@ where
{
// Create a list of dummy IPs and initialize a config using them as the
// initial peers.
let mut peers = HashSet::new();
let mut peers = IndexSet::new();
for address_number in 0..peer_count {
peers.insert(
SocketAddr::new(Ipv4Addr::new(127, 1, 1, address_number as _).into(), 1).to_string(),
Expand Down
7 changes: 4 additions & 3 deletions zebrad/src/components/inbound/tests/real_peer_set.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
//! Inbound service tests with a real peer set.
use std::{collections::HashSet, iter, net::SocketAddr, sync::Arc};
use std::{iter, net::SocketAddr, sync::Arc};

use futures::FutureExt;
use indexmap::IndexSet;
use tokio::{sync::oneshot, task::JoinHandle};
use tower::{
buffer::Buffer,
Expand Down Expand Up @@ -655,8 +656,8 @@ async fn setup(
listen_addr: config_listen_addr,

// Stop Zebra making outbound connections
initial_mainnet_peers: HashSet::new(),
initial_testnet_peers: HashSet::new(),
initial_mainnet_peers: IndexSet::new(),
initial_testnet_peers: IndexSet::new(),

..NetworkConfig::default()
};
Expand Down
72 changes: 71 additions & 1 deletion zebrad/tests/acceptance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ mod common;

use common::{
check::{is_zebrad_version, EphemeralCheck, EphemeralConfig},
config::{default_test_config, persistent_test_config, testdir},
config::{default_test_config, persistent_test_config, stored_config_path, testdir},
launch::{
spawn_zebrad_for_rpc_without_initial_peers, ZebradTestDirExt, BETWEEN_NODES_DELAY,
LAUNCH_DELAY,
Expand Down Expand Up @@ -1706,6 +1706,76 @@ async fn delete_old_databases() -> Result<()> {
Ok(())
}

#[test]
fn stored_config_works() -> Result<()> {
zebra_test::init();

// only run the test if we found a stored config
if let Some(stored_config_path) = stored_config_path() {
teor2345 marked this conversation as resolved.
Show resolved Hide resolved
let run_dir = testdir()?;

// run zebra with stored config
let mut child =
run_dir.spawn_child(args!["-c", stored_config_path.to_str().unwrap(), "start"])?;

//zebra was able to start with the stored config
child.expect_stdout_line_matches("Starting zebrad".to_string())?;

// finish
child.kill()?;

let output = child.wait_with_output()?;
let output = output.assert_failure()?;

// [Note on port conflict](#Note on port conflict)
output
.assert_was_killed()
.wrap_err("Possible port conflict. Are there other acceptance tests running?")?;
}

Ok(())
}

#[test]
#[allow(clippy::print_stderr)]
fn stored_config_is_newest() -> Result<()> {
zebra_test::init();

// only run the test if we found a stored config
if let Some(stored_config_path) = stored_config_path() {
let run_dir = testdir()?;
let generated_config_path = run_dir.path().join("newest_config.toml");

// generate an up to date config
let child = run_dir
.spawn_child(args!["generate", "-o": generated_config_path.to_str().unwrap()])?;

let output = child.wait_with_output()?;
let _output = output.assert_success()?;

let contents_generated = std::fs::read_to_string(generated_config_path).unwrap();
let mut contents_stored = std::fs::read_to_string(stored_config_path).unwrap();

let cache_dir = dirs::cache_dir()
.unwrap_or_else(|| std::env::current_dir().unwrap().join("cache"))
.join("zebra");

contents_stored = contents_stored.replace("[CACHE_DIR]", cache_dir.to_str().unwrap());

if contents_generated != contents_stored {
eprintln!(
"Error: Stored config is not up to date. Please generate an up to date config and overwrite
the stored one using `zebrad generate -o zebrad/common/newest_config.toml`. Then run this test again."
);

// show the 2 strings also
assert_eq!(contents_generated, contents_stored);
}
}

Ok(())
}

/// Test sending transactions using a lightwalletd instance connected to a zebrad instance.
///
/// See [`common::lightwalletd::send_transaction_test`] for more information.
Expand Down
17 changes: 16 additions & 1 deletion zebrad/tests/common/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
//! Test functions in this file will not be run.
//! This file is only for test library code.

use std::{env, time::Duration};
use std::{
env,
path::{Path, PathBuf},
time::Duration,
};

use color_eyre::eyre::Result;
use tempfile::TempDir;
Expand Down Expand Up @@ -80,3 +84,14 @@ pub fn testdir() -> Result<TempDir> {
.tempdir()
.map_err(Into::into)
}

/// Get stored config path
pub fn stored_config_path() -> Option<PathBuf> {
let ancestors = Path::new(env!("CARGO_BIN_EXE_zebrad")).ancestors();
for potential_zebra in ancestors {
if potential_zebra.ends_with("zebra") {
return Some(potential_zebra.join("zebrad/tests/common/config.toml"));
}
}
None
}
64 changes: 64 additions & 0 deletions zebrad/tests/common/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Default configuration for zebrad.
#
# This file can be used as a skeleton for custom configs.
#
# Unspecified fields use default values. Optional fields are Some(field) if the
# field is present and None if it is absent.
#
# This file is generated as an example using zebrad's current defaults.
# You should set only the config options you want to keep, and delete the rest.
# Only a subset of fields are present in the skeleton, since optional values
# whose default is None are omitted.
#
# The config format (including a complete list of sections and fields) is
# documented here:
# https://doc.zebra.zfnd.org/zebrad/config/struct.ZebradConfig.html
#
# zebrad attempts to load configs in the following order:
#
# 1. The -c flag on the command line, e.g., `zebrad -c myconfig.toml start`;
# 2. The file `zebrad.toml` in the users's preference directory (platform-dependent);
# 3. The default config.

[consensus]
checkpoint_sync = true
debug_skip_parameter_preload = false

[mempool]
eviction_memory_time = '1h'
tx_cost_limit = 80000000

[metrics]

[network]
crawl_new_peer_interval = '1m 1s'
initial_mainnet_peers = [
'dnsseed.z.cash:8233',
'dnsseed.str4d.xyz:8233',
'mainnet.seeder.zfnd.org:8233',
'mainnet.is.yolo.money:8233',
]
initial_testnet_peers = [
'dnsseed.testnet.z.cash:18233',
'testnet.seeder.zfnd.org:18233',
'testnet.is.yolo.money:18233',
]
listen_addr = '0.0.0.0:8233'
network = 'Mainnet'
peerset_initial_target_size = 25

[rpc]

[state]
cache_dir = '[CACHE_DIR]'
delete_old_database = true
ephemeral = false

[sync]
lookahead_limit = 400
max_concurrent_block_requests = 25

[tracing]
force_use_color = false
use_color = true
use_journald = false
6 changes: 3 additions & 3 deletions zebrad/tests/common/launch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
//! This file is only for test library code.
use std::{
collections::HashSet,
env,
net::SocketAddr,
path::{Path, PathBuf},
time::Duration,
};

use color_eyre::eyre::Result;
use indexmap::IndexSet;

use zebra_chain::parameters::Network;
use zebra_test::{
Expand Down Expand Up @@ -201,8 +201,8 @@ pub fn spawn_zebrad_for_rpc_without_initial_peers<P: ZebradTestDirExt>(
.expect("Failed to create a config file with a known RPC listener port");

config.state.ephemeral = false;
config.network.initial_mainnet_peers = HashSet::new();
config.network.initial_testnet_peers = HashSet::new();
config.network.initial_mainnet_peers = IndexSet::new();
config.network.initial_testnet_peers = IndexSet::new();
config.network.network = network;
config.mempool.debug_enable_at_height = Some(0);

Expand Down