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

Traced client #1571

Closed
wants to merge 27 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
2 changes: 1 addition & 1 deletion apps/fortuna/Cargo.lock

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

2 changes: 1 addition & 1 deletion apps/fortuna/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "fortuna"
version = "5.2.4"
version = "5.3.0"
edition = "2021"

[dependencies]
Expand Down
91 changes: 46 additions & 45 deletions apps/fortuna/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,20 +52,45 @@ mod revelation;

pub type ChainId = String;

#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct RequestLabel {
pub value: String,
}

pub struct ApiMetrics {
pub http_requests: Family<RequestLabel, Counter>,
}

#[derive(Clone)]
pub struct ApiState {
pub chains: Arc<HashMap<ChainId, BlockchainState>>,

pub metrics_registry: Arc<RwLock<Registry>>,

/// Prometheus metrics
pub metrics: Arc<Metrics>,
pub metrics: Arc<ApiMetrics>,
}

impl ApiState {
pub fn new(chains: &[(ChainId, BlockchainState)]) -> ApiState {
let map: HashMap<ChainId, BlockchainState> = chains.into_iter().cloned().collect();
pub async fn new(
chains: HashMap<ChainId, BlockchainState>,
metrics_registry: Arc<RwLock<Registry>>,
) -> ApiState {
let metrics = ApiMetrics {
http_requests: Family::default(),
};

let http_requests = metrics.http_requests.clone();
metrics_registry.write().await.register(
"http_requests",
"Number of HTTP requests received",
http_requests,
);

ApiState {
chains: Arc::new(map),
metrics: Arc::new(Metrics::new()),
chains: Arc::new(chains),
metrics: Arc::new(metrics),
metrics_registry,
}
}
}
Expand All @@ -89,38 +114,6 @@ pub struct BlockchainState {
pub confirmed_block_status: BlockStatus,
}

pub struct Metrics {
pub registry: RwLock<Registry>,
// TODO: track useful metrics. this counter is just a placeholder to get things set up.
pub request_counter: Family<Label, Counter>,
}

#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct Label {
value: String,
}

impl Metrics {
pub fn new() -> Self {
let mut metrics_registry = Registry::default();
let http_requests = Family::<Label, Counter>::default();

// Register the metric family with the registry.
metrics_registry.register(
// With the metric name.
"http_requests",
// And the metric help text.
"Number of HTTP requests received",
http_requests.clone(),
);

Metrics {
registry: RwLock::new(metrics_registry),
request_counter: http_requests,
}
}
}

pub enum RestError {
/// The caller passed a sequence number that isn't within the supported range
InvalidSequenceNumber,
Expand Down Expand Up @@ -225,7 +218,12 @@ mod test {
},
ethers::prelude::Address,
lazy_static::lazy_static,
std::sync::Arc,
prometheus_client::registry::Registry,
std::{
collections::HashMap,
sync::Arc,
},
tokio::sync::RwLock,
};

const PROVIDER: Address = Address::zero();
Expand All @@ -243,7 +241,7 @@ mod test {
));
}

fn test_server() -> (TestServer, Arc<MockEntropyReader>, Arc<MockEntropyReader>) {
async fn test_server() -> (TestServer, Arc<MockEntropyReader>, Arc<MockEntropyReader>) {
let eth_read = Arc::new(MockEntropyReader::with_requests(10, &[]));

let eth_state = BlockchainState {
Expand All @@ -255,6 +253,8 @@ mod test {
confirmed_block_status: BlockStatus::Latest,
};

let metrics_registry = Arc::new(RwLock::new(Registry::default()));

let avax_read = Arc::new(MockEntropyReader::with_requests(10, &[]));

let avax_state = BlockchainState {
Expand All @@ -266,10 +266,11 @@ mod test {
confirmed_block_status: BlockStatus::Latest,
};

let api_state = ApiState::new(&[
("ethereum".into(), eth_state),
("avalanche".into(), avax_state),
]);
let mut chains = HashMap::new();
chains.insert("ethereum".into(), eth_state);
chains.insert("avalanche".into(), avax_state);

let api_state = ApiState::new(chains, metrics_registry).await;

let app = api::routes(api_state);
(TestServer::new(app).unwrap(), eth_read, avax_read)
Expand All @@ -287,7 +288,7 @@ mod test {

#[tokio::test]
async fn test_revelation() {
let (server, eth_contract, avax_contract) = test_server();
let (server, eth_contract, avax_contract) = test_server().await;

// Can't access a revelation if it hasn't been requested
get_and_assert_status(
Expand Down Expand Up @@ -416,7 +417,7 @@ mod test {

#[tokio::test]
async fn test_revelation_confirmation_delay() {
let (server, eth_contract, avax_contract) = test_server();
let (server, eth_contract, avax_contract) = test_server().await;

eth_contract.insert(PROVIDER, 0, 10, false);
eth_contract.insert(PROVIDER, 1, 11, false);
Expand Down
2 changes: 1 addition & 1 deletion apps/fortuna/src/api/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use {
};

pub async fn metrics(State(state): State<crate::api::ApiState>) -> impl IntoResponse {
let registry = state.metrics.registry.read().await;
let registry = state.metrics_registry.read().await;
let mut buffer = String::new();

// Should not fail if the metrics are valid and there is memory available
Expand Down
6 changes: 3 additions & 3 deletions apps/fortuna/src/api/revelation.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use {
crate::api::{
ChainId,
Label,
RequestLabel,
RestError,
},
anyhow::Result,
Expand Down Expand Up @@ -45,8 +45,8 @@ pub async fn revelation(
) -> Result<Json<GetRandomValueResponse>, RestError> {
state
.metrics
.request_counter
.get_or_create(&Label {
.http_requests
.get_or_create(&RequestLabel {
value: "/v1/chains/{chain_id}/revelations/{sequence}".to_string(),
})
.inc();
Expand Down
1 change: 1 addition & 0 deletions apps/fortuna/src/chain.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub(crate) mod ethereum;
pub(crate) mod reader;
pub(crate) mod traced_client;
27 changes: 20 additions & 7 deletions apps/fortuna/src/chain/ethereum.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use {
super::traced_client::TracedClient,
crate::{
api::ChainId,
chain::reader::{
self,
BlockNumber,
Expand Down Expand Up @@ -34,7 +36,6 @@ use {
},
prelude::TransactionRequest,
providers::{
Http,
Middleware,
Provider,
},
Expand All @@ -48,11 +49,13 @@ use {
U256,
},
},
prometheus_client::registry::Registry,
sha3::{
Digest,
Keccak256,
},
std::sync::Arc,
tokio::sync::RwLock,
};

// TODO: Programmatically generate this so we don't have to keep committed ABI in sync with the
Expand All @@ -64,11 +67,11 @@ abigen!(

pub type SignablePythContract = PythRandom<
TransformerMiddleware<
NonceManagerMiddleware<SignerMiddleware<Provider<Http>, LocalWallet>>,
NonceManagerMiddleware<SignerMiddleware<Provider<TracedClient>, LocalWallet>>,
LegacyTxTransformer,
>,
>;
pub type PythContract = PythRandom<Provider<Http>>;
pub type PythContract = PythRandom<Provider<TracedClient>>;

/// Transformer that converts a transaction into a legacy transaction if use_legacy_tx is true.
#[derive(Clone, Debug)]
Expand All @@ -90,10 +93,14 @@ impl Transformer for LegacyTxTransformer {

impl SignablePythContract {
pub async fn from_config(
chain_id: ChainId,
chain_config: &EthereumConfig,
private_key: &str,
metrics_registry: Arc<RwLock<Registry>>,
) -> Result<SignablePythContract> {
let provider = Provider::<Http>::try_from(&chain_config.geth_rpc_addr)?;
let provider =
TracedClient::new_provider(chain_id, &chain_config.geth_rpc_addr, metrics_registry)
.await?;
let chain_id = provider.get_chainid().await?;

let transformer = LegacyTxTransformer {
Expand Down Expand Up @@ -184,8 +191,14 @@ impl SignablePythContract {
}

impl PythContract {
pub fn from_config(chain_config: &EthereumConfig) -> Result<PythContract> {
let provider = Provider::<Http>::try_from(&chain_config.geth_rpc_addr)?;
pub async fn from_config(
chain_id: ChainId,
chain_config: &EthereumConfig,
metrics_registry: Arc<RwLock<Registry>>,
) -> Result<PythContract> {
let provider =
TracedClient::new_provider(chain_id, &chain_config.geth_rpc_addr, metrics_registry)
.await?;

Ok(PythRandom::new(
chain_config.contract_addr,
Expand Down Expand Up @@ -262,7 +275,7 @@ impl EntropyReader for PythContract {
user_random_number: [u8; 32],
provider_revelation: [u8; 32],
) -> Result<Option<U256>> {
let result: Result<U256, ContractError<Provider<Http>>> = self
let result: Result<U256, ContractError<Provider<TracedClient>>> = self
.reveal_with_callback(
provider,
sequence_number,
Expand Down
Loading
Loading