Skip to content

Commit

Permalink
[chore]: Move mock definitions into apps to re-restrict visibility. B…
Browse files Browse the repository at this point in the history
…etter implementation of mock stdin
  • Loading branch information
batconjurer committed Jul 18, 2023
1 parent bd7c2f7 commit 5275401
Show file tree
Hide file tree
Showing 22 changed files with 261 additions and 226 deletions.
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.

3 changes: 2 additions & 1 deletion apps/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ file-lock.workspace = true
flate2.workspace = true
futures.workspace = true
itertools.workspace = true
lazy_static.workspace= true
libc.workspace = true
libloading.workspace = true
masp_primitives = { workspace = true, features = ["transparent-inputs"] }
Expand Down Expand Up @@ -126,6 +127,7 @@ sha2.workspace = true
signal-hook.workspace = true
sysinfo.workspace = true
tar.workspace = true
tempfile.workspace = true
tendermint-config.workspace = true
thiserror.workspace = true
tokio = {workspace = true, features = ["full"]}
Expand All @@ -149,7 +151,6 @@ namada = {path = "../shared", default-features = false, features = ["testing", "
namada_test_utils = {path = "../test_utils"}
bit-set.workspace = true
proptest.workspace = true
tempfile.workspace = true
test-log.workspace = true
tokio-test.workspace = true

Expand Down
4 changes: 2 additions & 2 deletions apps/src/lib/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
//! respectively.

pub mod context;
pub mod utils;
pub(super) mod utils;

use clap::{ArgGroup, ArgMatches, ColorChoice};
use color_eyre::eyre::Result;
pub use utils::safe_exit;
use utils::*;
pub use utils::{dispatch_prompt, safe_exit, TESTIN};

pub use self::context::Context;

Expand Down
44 changes: 36 additions & 8 deletions apps/src/lib/cli/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::str::FromStr;

use clap::{ArgAction, ArgMatches};
use color_eyre::eyre::Result;
use lazy_static::lazy_static;

use super::args;
use super::context::{Context, FromContext};
Expand Down Expand Up @@ -343,25 +344,52 @@ pub fn safe_exit(_: i32) -> ! {
panic!("Test failed because the client exited unexpectedly.")
}

lazy_static! {
/// A replacement for stdin in testing.
pub static ref TESTIN: std::sync::Arc<std::sync::Mutex<Vec<u8>>> =
std::sync::Arc::new(std::sync::Mutex::new(vec![]));
}

/// A generic function for displaying a prompt to users and reading
/// in their response.
fn prompt_aux<R, W>(mut reader: R, mut writer: W, question: &str) -> String
where
R: std::io::Read,
W: Write,
{
write!(&mut writer, "{}", question).expect("Unable to write");
std::io::stdout().flush().unwrap();
writer.flush().unwrap();
let mut s = String::new();
reader.read_to_string(&mut s).expect("Unable to read");
s
}

#[cfg(feature = "testing")]
pub fn prompt(question: &str) -> String {
let file = std::fs::File::open("stdin.mock").unwrap();
prompt_aux(file, std::io::stdout(), question)
/// A function that chooses how to dispatch prompts
/// to users. There is a hierarchy of feature flags
/// that determines this. If no flags are set,
/// the question is printed to stdout and response
/// read from stdin.
pub fn dispatch_prompt(question: impl AsRef<str>) -> String {
if cfg!(feature = "testing") {
prompt_aux(
TESTIN.lock().unwrap().as_slice(),
std::io::stdout(),
question.as_ref(),
)
} else {
prompt_aux(
std::io::stdin().lock(),
std::io::stdout(),
question.as_ref(),
)
}
}

#[cfg(not(feature = "testing"))]
pub fn prompt(question: &str) -> String {
prompt_aux(std::io::stdin().lock(), std::io::stdout(), question)
#[macro_export]
/// A convenience macro for formatting the user prompt before
/// forwarding it to the `[dispatch_prompt]` method.
macro_rules! prompt {
($($arg:tt)*) => {{
$crate::cli::dispatch_prompt(format!("{}", format_args!($($arg)*)))
}}
}
5 changes: 2 additions & 3 deletions apps/src/lib/client/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ use namada::types::token::{Change, Denomination, MaspDenom, TokenAddress};
use namada::types::{storage, token};
use tokio::time::Instant;

use crate::cli::utils::prompt;
use crate::cli::{self, args};
use crate::facade::tendermint::merkle::proof::Proof;
use crate::facade::tendermint_rpc::error::Error as TError;
use crate::prompt;
use crate::wallet::CliWalletUtils;

/// Query the status of a given transaction.
Expand Down Expand Up @@ -440,8 +440,7 @@ pub async fn query_pinned_balance<
}
// If a suitable viewing key was not found, then demand it from the user
if balance == pinned_error {
let vk_str =
prompt(&format!("Enter the viewing key for {}: ", owner));
let vk_str = prompt!("Enter the viewing key for {}: ", owner);
let fvk = match ExtendedViewingKey::from_str(vk_str.trim()) {
Ok(fvk) => fvk,
_ => {
Expand Down
6 changes: 3 additions & 3 deletions apps/src/lib/client/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use borsh::{BorshDeserialize, BorshSerialize};
use data_encoding::HEXLOWER_PERMISSIVE;
use masp_proofs::prover::LocalTxProver;
use namada::ledger::governance::storage as gov_storage;
use namada::ledger::queries::Client;
use namada::ledger::rpc::{TxBroadcastData, TxResponse};
use namada::ledger::signing::TxSigningKey;
use namada::ledger::wallet::{Wallet, WalletUtils};
Expand All @@ -35,7 +36,6 @@ use crate::client::signing::find_pk;
use crate::client::tx::tx::ProcessTxResponse;
use crate::config::TendermintMode;
use crate::facade::tendermint_rpc::endpoint::broadcast::tx_sync::Response;
use crate::facade::tendermint_rpc::HttpClient;
use crate::node::ledger::tendermint_node;
use crate::wallet::{gen_validator_keys, read_and_confirm_encryption_password};

Expand Down Expand Up @@ -523,8 +523,8 @@ impl masp::ShieldedUtils for CLIShieldedUtils {
}
}

pub async fn submit_transfer(
client: &HttpClient,
pub async fn submit_transfer<C: Client + Sync>(
client: &C,
mut ctx: Context,
args: args::TxTransfer,
) -> Result<(), tx::Error> {
Expand Down
39 changes: 2 additions & 37 deletions apps/src/lib/client/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,41 +47,6 @@ const DEFAULT_NETWORK_CONFIGS_SERVER: &str =
/// We do pre-genesis validator set up in this directory
pub const PRE_GENESIS_DIR: &str = "pre-genesis";

/// Environment variable set to reduce the amount of printing the CLI
/// tools perform. Extra prints, while good for UI, clog up test tooling.
pub const REDUCED_CLI_PRINTING: &str = "REDUCED_CLI_PRINTING";

macro_rules! cli_print {
($($arg:tt)*) => {{
if std::env::var(REDUCED_CLI_PRINTING)
.map(|v| if v.to_lowercase().trim() == "true" {
false
} else {
true
}).unwrap_or(true) {
let mut stdout = std::io::stdout().lock();
_ = stdout.write_all(format!("{}", std::format_args!($($arg)*)).as_bytes());
_ = stdout.flush();
}
}};
}

#[allow(unused)]
macro_rules! cli_println {
($($arg:tt)*) => {{
if std::env::var(REDUCED_CLI_PRINTING)
.map(|v| if v.to_lowercase().trim() == "true" {
false
} else {
true
}).unwrap_or(true) {
let mut stdout = std::io::stdout().lock();
_ = stdout.write_all(format!("{}\n", std::format_args!($($arg)*)).as_bytes());
_ = stdout.flush();
}
}};
}

/// Configure Namada to join an existing network. The chain must be released in
/// the <https://github.com/heliaxdev/anoma-network-config> repository.
pub async fn join_network(
Expand Down Expand Up @@ -1204,9 +1169,9 @@ where
print!("{}", msg);
_ = std::io::stdout().flush();
for c in spinny_wheel.chars().cycle() {
cli_print!("{}", c);
print!("{}", c);
std::thread::sleep(std::time::Duration::from_secs(1));
cli_print!("{}", (8u8 as char));
print!("{}", (8u8 as char));
if task.is_finished() {
break;
}
Expand Down
17 changes: 10 additions & 7 deletions apps/src/lib/node/ledger/shell/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ mod prepare_proposal;
mod process_proposal;
pub(super) mod queries;
mod stats;
#[cfg(any(test, feature = "testing"))]
#[allow(dead_code)]
pub mod testing;
mod vote_extensions;

use std::collections::{BTreeSet, HashSet};
Expand Down Expand Up @@ -368,26 +371,26 @@ where
{
/// The id of the current chain
#[allow(dead_code)]
pub chain_id: ChainId,
chain_id: ChainId,
/// The persistent storage with write log
pub wl_storage: WlStorage<D, H>,
pub(super) wl_storage: WlStorage<D, H>,
/// Gas meter for the current block
gas_meter: BlockGasMeter,
/// Byzantine validators given from ABCI++ `prepare_proposal` are stored in
/// this field. They will be slashed when we finalize the block.
byzantine_validators: Vec<Evidence>,
/// Path to the base directory with DB data and configs
#[allow(dead_code)]
pub base_dir: PathBuf,
base_dir: PathBuf,
/// Path to the WASM directory for files used in the genesis block.
pub wasm_dir: PathBuf,
pub(super) wasm_dir: PathBuf,
/// Information about the running shell instance
#[allow(dead_code)]
mode: ShellMode,
/// VP WASM compilation cache
pub vp_wasm_cache: VpCache<WasmCacheRwAccess>,
pub(super) vp_wasm_cache: VpCache<WasmCacheRwAccess>,
/// Tx WASM compilation cache
pub tx_wasm_cache: TxCache<WasmCacheRwAccess>,
pub(super) tx_wasm_cache: TxCache<WasmCacheRwAccess>,
/// Taken from config `storage_read_past_height_limit`. When set, will
/// limit the how many block heights in the past can the storage be
/// queried for reading values.
Expand Down Expand Up @@ -1395,7 +1398,7 @@ where
/// Helper functions and types for writing unit tests
/// for the shell
#[cfg(test)]
pub mod test_utils {
mod test_utils {
use std::ops::{Deref, DerefMut};
use std::path::PathBuf;

Expand Down
2 changes: 1 addition & 1 deletion apps/src/lib/node/ledger/shell/prepare_proposal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ where
/// Otherwise, we return an allocator wrapped in an
/// [`EncryptedTxBatchAllocator::WithEncryptedTxs`] value.
#[inline]
pub fn get_encrypted_txs_allocator(&self) -> EncryptedTxBatchAllocator {
fn get_encrypted_txs_allocator(&self) -> EncryptedTxBatchAllocator {
let pos_queries = self.wl_storage.pos_queries();

let is_2nd_height_off = pos_queries.is_deciding_offset_within_epoch(1);
Expand Down
2 changes: 1 addition & 1 deletion apps/src/lib/node/ledger/shell/process_proposal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -934,7 +934,7 @@ where

/// Checks if it is not possible to include encrypted txs at the current
/// block height.
pub fn encrypted_txs_not_allowed(&self) -> bool {
pub(super) fn encrypted_txs_not_allowed(&self) -> bool {
let pos_queries = self.wl_storage.pos_queries();
let is_2nd_height_off = pos_queries.is_deciding_offset_within_epoch(1);
let is_3rd_height_off = pos_queries.is_deciding_offset_within_epoch(2);
Expand Down
Loading

0 comments on commit 5275401

Please sign in to comment.