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

mock-client: 👀 implement ViewClient (work in progress) #3958

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
13 changes: 12 additions & 1 deletion 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/core/app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ tracing = {workspace = true}
ed25519-consensus = {workspace = true}
penumbra-mock-consensus = {workspace = true}
penumbra-mock-client = {workspace = true}
rand = {workspace = true}
rand_core = {workspace = true}
rand_chacha = {workspace = true}
tap = {workspace = true}
Expand Down
1 change: 1 addition & 0 deletions crates/core/app/src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ pub struct App {
}

impl App {
/// Constructs a new application, using the provided [`Snapshot`].
pub async fn new(snapshot: Snapshot) -> Result<Self> {
tracing::debug!("initializing App instance");

Expand Down
44 changes: 17 additions & 27 deletions crates/core/app/tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,24 @@
// NB: Allow dead code, these are in fact shared by files in `tests/`.
#![allow(dead_code)]

use async_trait::async_trait;
use cnidarium::TempStorage;
use penumbra_app::{
app::App,
server::consensus::{Consensus, ConsensusService},
pub use self::test_node_builder_ext::BuilderExt;

use {
async_trait::async_trait,
cnidarium::TempStorage,
penumbra_app::{
app::App,
server::consensus::{Consensus, ConsensusService},
},
penumbra_genesis::AppState,
penumbra_mock_consensus::TestNode,
std::ops::Deref,
};
use penumbra_genesis::AppState;
use penumbra_mock_consensus::TestNode;
use std::ops::Deref;

/// Penumbra-specific extensions to the mock consensus builder.
///
/// See [`BuilderExt`].
mod test_node_builder_ext;

// Installs a tracing subscriber to log events until the returned guard is dropped.
pub fn set_tracing_subscriber() -> tracing::subscriber::DefaultGuard {
Expand Down Expand Up @@ -80,22 +89,3 @@ impl TempStorageExt for TempStorage {
self.apply_genesis(Default::default()).await
}
}

/// Penumbra-specific extensions to the mock consensus builder.
pub trait BuilderExt: Sized {
type Error;
fn with_penumbra_auto_app_state(self, app_state: AppState) -> Result<Self, Self::Error>;
}

impl BuilderExt for penumbra_mock_consensus::builder::Builder {
type Error = anyhow::Error;
fn with_penumbra_auto_app_state(self, app_state: AppState) -> Result<Self, Self::Error> {
// what to do here?
// - read out list of abci/comet validators from the builder,
// - define a penumbra validator for each one
// - inject that into the penumbra app state
// - serialize to json and then call `with_app_state_bytes`
let app_state = serde_json::to_vec(&app_state)?;
Ok(self.app_state(app_state))
}
}
120 changes: 120 additions & 0 deletions crates/core/app/tests/common/test_node_builder_ext.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
use {
penumbra_genesis::AppState,
penumbra_mock_consensus::{builder::Builder, keyring::Keys},
penumbra_proto::{
core::keys::v1::{GovernanceKey, IdentityKey},
penumbra::core::component::stake::v1::Validator as PenumbraValidator,
},
tap::Tap,
};

/// Penumbra-specific extensions to the mock consensus builder.
pub trait BuilderExt: Sized {
/// The error thrown by [`with_penumbra_auto_app_state`]
type Error;
/// Add the provided Penumbra [`AppState`] to the builder.
///
/// This will inject any configured validators into the state before serializing it into bytes.
fn with_penumbra_auto_app_state(self, app_state: AppState) -> Result<Self, Self::Error>;
}

impl BuilderExt for Builder {
type Error = anyhow::Error;
fn with_penumbra_auto_app_state(self, app_state: AppState) -> Result<Self, Self::Error> {
// Generate a penumbra validator using the test node's consensus keys (if they exist).
// Eventually, we may wish to generate and inject additional definitions, but only a single
// validator is supported for now.
let app_state = match self
.keys
.as_ref()
.map(generate_penumbra_validator)
.inspect(log_validator)
.map(std::iter::once)
{
Some(validator) => app_state_with_validators(app_state, validator)?,
None => app_state,
};

// Serialize the app state into bytes, and add it to the builder.
serde_json::to_vec(&app_state)
.map_err(Self::Error::from)
.map(|s| self.app_state(s))
}
}

/// Injects the given collection of [`Validator`s][PenumbraValidator] into the app state.
fn app_state_with_validators<V>(
app_state: AppState,
validators: V,
) -> Result<AppState, anyhow::Error>
where
V: IntoIterator<Item = PenumbraValidator>,
{
use AppState::{Checkpoint, Content};
match app_state {
Checkpoint(_) => anyhow::bail!("checkpoint app state isn't supported"),
Content(mut content) => {
// Inject the builder's validators into the staking component's genesis state.
std::mem::replace(
&mut content.stake_content.validators,
validators.into_iter().collect(),
)
.tap(|overwritten| {
// Log a warning if this overwrote any validators already in the app state.
if !overwritten.is_empty() {
tracing::warn!(
?overwritten,
"`with_penumbra_auto_app_state` overwrote validators in the given AppState"
)
}
});
Ok(Content(content))
}
}
}

/// Generates a [`Validator`][PenumbraValidator] given a set of consensus [`Keys`].
fn generate_penumbra_validator(
Keys {
consensus_verification_key,
..
}: &Keys,
) -> PenumbraValidator {
/// A temporary stub for validator keys.
///
/// NB: for now, we will use the same key for governance. See the documentation of
/// `GovernanceKey` for more information about cold storage of validator keys.
const BYTES: [u8; 32] = [0; 32];

PenumbraValidator {
identity_key: Some(IdentityKey {
ik: BYTES.to_vec().clone(),
}),
governance_key: Some(GovernanceKey {
gk: BYTES.to_vec().clone(),
}),
consensus_key: consensus_verification_key.as_bytes().to_vec(),
enabled: true,
sequence_number: 0,
name: String::default(),
website: String::default(),
description: String::default(),
funding_streams: Vec::default(),
}
}

fn log_validator(
PenumbraValidator {
name,
enabled,
sequence_number,
..
}: &PenumbraValidator,
) {
tracing::trace!(
%name,
%enabled,
%sequence_number,
"injecting validator into app state"
)
}
37 changes: 37 additions & 0 deletions crates/core/app/tests/mock_consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use {
penumbra_proto::DomainType,
penumbra_sct::component::{clock::EpochRead, tree::SctRead as _},
penumbra_shielded_pool::{OutputPlan, SpendPlan},
penumbra_stake::component::validator_handler::ValidatorDataRead as _,
penumbra_transaction::{
memo::MemoPlaintext, plan::MemoPlan, TransactionParameters, TransactionPlan,
},
Expand All @@ -37,6 +38,42 @@ async fn mock_consensus_can_send_an_init_chain_request() -> anyhow::Result<()> {
Ok(())
}

/// Exercises that the mock consensus engine can provide a single genesis validator.
#[tokio::test]
async fn mock_consensus_can_define_a_genesis_validator() -> anyhow::Result<()> {
// Install a test logger, acquire some temporary storage, and start the test node.
let guard = common::set_tracing_subscriber();
let storage = TempStorage::new().await?;
let _test_node = common::start_test_node(&storage).await?;

let snapshot = storage.latest_snapshot();
let validators = snapshot
.validator_definitions()
.tap(|_| info!("getting validator definitions"))
.await?;
match validators.as_slice() {
[v] => {
let identity_key = v.identity_key;
let status = snapshot
.get_validator_state(&identity_key)
.await?
.ok_or_else(|| anyhow!("could not find validator status"))?;
assert_eq!(
status,
penumbra_stake::validator::State::Active,
"validator should be active"
);
}
unexpected => panic!("there should be one validator, got: {unexpected:?}"),
}

// Free our temporary storage.
drop(storage);
drop(guard);

Ok(())
}

/// Exercises that a series of empty blocks, with no validator set present, can be successfully
/// executed by the consensus service.
#[tokio::test]
Expand Down
32 changes: 19 additions & 13 deletions crates/test/mock-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,22 @@ homepage.workspace = true
license.workspace = true

[dependencies]
anyhow = {workspace = true}
cnidarium = {workspace = true, default-features = true}
penumbra-compact-block = {workspace = true, default-features = true}
penumbra-dex = {workspace = true, default-features = true}
penumbra-keys = {workspace = true, default-features = true}
penumbra-sct = {workspace = true, default-features = true}
penumbra-shielded-pool = {workspace = true, features = [
"component",
], default-features = true}
penumbra-tct = {workspace = true, default-features = true}
penumbra-transaction = {workspace = true, default-features = true}
rand_core = {workspace = true}

anyhow = { workspace = true }
cnidarium = { workspace = true, default-features = true }
futures = { workspace = true }
penumbra-app = { workspace = true }
penumbra-asset = { workspace = true, default-features = true }
penumbra-compact-block = { workspace = true, default-features = true }
penumbra-dex = { workspace = true, default-features = true }
penumbra-fee = { workspace = true, default-features = false }
penumbra-keys = { workspace = true, default-features = true }
penumbra-num = {workspace = true, default-features = true}
penumbra-proto = { workspace = true, features = ["rpc"], default-features = true }
penumbra-sct = { workspace = true, default-features = true }
penumbra-shielded-pool = { workspace = true, features = ["component"], default-features = true }
penumbra-stake = { workspace = true, default-features = false }
penumbra-tct = { workspace = true, default-features = true }
penumbra-transaction = { workspace = true, default-features = true }
penumbra-view = { workspace = true }
rand_core = { workspace = true }
tracing = { workspace = true }
2 changes: 2 additions & 0 deletions crates/test/mock-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use penumbra_transaction::{AuthorizationData, Transaction, TransactionPlan, Witn
use rand_core::OsRng;
use std::collections::BTreeMap;

mod view;

/// A bare-bones mock client for use exercising the state machine.
pub struct MockClient {
latest_height: u64,
Expand Down
Loading
Loading