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

Add per-account rate limit to eth-spout #186

Merged
merged 1 commit into from
Sep 7, 2023
Merged
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
6 changes: 1 addition & 5 deletions products/eth-spout/README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
# eth-spout - A super simple faucet for Ethereum testnets

Check failure on line 1 in products/eth-spout/README.md

View workflow job for this annotation

GitHub Actions / Trunk Check

prettier

Incorrect formatting, autoformat by running 'trunk fmt'

## Features

A static site which lets users request funds from a pre-configured account.

## Non-features

* Rate limiting of any kind
* A fancy UI

## Configuration

All configuration is passed via environment variables.
Expand All @@ -21,3 +16,4 @@
| `PRIVATE_KEY` | The private key of the account to send funds from. Required. |
| `ETH_AMOUNT` | The amount to send for each request in Eth. Defaults to `1`. |
| `EXPLORER_URL` | The URL to a block explorer for this chain, used to provide a link to the transaction after a request succeeds. Optional. |
| `MINIMUM_SECONDS_BETWEEN_REQUESTS` | The minimum time between each request to send funds to the same address. Set to `0` to disable rate limiting. Defaults to `300`. |
77 changes: 63 additions & 14 deletions products/eth-spout/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
use std::{env, net::IpAddr, sync::Arc};
use std::{
collections::HashMap,
env, mem,
net::IpAddr,
sync::Arc,
time::{Duration, Instant},
};

use anyhow::{anyhow, Result};
use askama::Template;
use axum::{extract::State, routing::get, Form, Router};
use ethers::{
middleware::{signer::SignerMiddlewareError, SignerMiddleware},
middleware::{nonce_manager::NonceManagerError, NonceManagerMiddleware, SignerMiddleware},
providers::{Http, Middleware, Provider},
signers::LocalWallet,
types::{TransactionRequest, H256},
types::{Address, TransactionRequest, H256},
utils::{parse_checksummed, parse_ether, to_checksum, ConversionError, WEI_IN_ETHER},
};
use serde::Deserialize;
use tokio::sync::Mutex;

#[derive(Template)]
#[template(path = "home.html")]
Expand All @@ -26,12 +33,13 @@ struct Home {
enum RequestStatus {
Sent(H256),
AddrErr(ConversionError),
SendErr(SignerMiddlewareError<Provider<Http>, LocalWallet>),
SendErr(NonceManagerError<SignerMiddleware<Provider<Http>, LocalWallet>>),
RateLimitErr(Duration),
}

async fn home_inner(State(state): State<Arc<AppState>>, status: Option<RequestStatus>) -> Home {
Home {
from_addr: to_checksum(&state.signer.address(), None),
from_addr: to_checksum(&state.provider.inner().address(), None),
native_token_symbol: state.config.native_token_symbol.clone(),
amount: state.config.eth_amount.clone(),
explorer_url: state.config.explorer_url.clone(),
Expand All @@ -42,6 +50,10 @@ async fn home_inner(State(state): State<Arc<AppState>>, status: Option<RequestSt
error: match status {
Some(RequestStatus::AddrErr(e)) => Some(format!("Invalid address: {e}")),
Some(RequestStatus::SendErr(e)) => Some(format!("Failed to send transaction: {e}")),
Some(RequestStatus::RateLimitErr(d)) => Some(format!(
"Request made too recently, please wait {} seconds before trying again",
d.as_secs()
)),
_ => None,
},
}
Expand All @@ -62,15 +74,32 @@ async fn request(State(state): State<Arc<AppState>>, Form(request): Form<Request
Err(e) => {
eprintln!("{e:?}");
return home_inner(State(state), Some(RequestStatus::AddrErr(e))).await;
},
}
};

let minimum_time_between_requests = state.config.minimum_time_between_requests;
// Avoid accessing mutex if minimum time is zero.
if !minimum_time_between_requests.is_zero() {
let guard = state.last_request.lock().await;
if let Some(last_request) = guard.get(&address) {
let elapsed = last_request.elapsed();
mem::drop(guard);
if elapsed <= minimum_time_between_requests {
eprintln!("Last request for {address:?} was too recent ({elapsed:?} ago)");
return home_inner(
State(state),
Some(RequestStatus::RateLimitErr(
minimum_time_between_requests - elapsed,
)),
)
.await;
}
}
}

let value = parse_ether(&state.config.eth_amount).unwrap_or(WEI_IN_ETHER);
let tx = TransactionRequest::pay(
address,
value,
);
let status = match state.signer.send_transaction(tx, None).await {
let tx = TransactionRequest::pay(address, value);
let status = match state.provider.send_transaction(tx, None).await {
Ok(t) => RequestStatus::Sent(t.tx_hash()),
Err(e) => {
eprintln!("{e:?}");
Expand All @@ -80,6 +109,15 @@ async fn request(State(state): State<Arc<AppState>>, Form(request): Form<Request

println!("Sent {value} to {address:?}");

// No need to keep this state if minimum time is zero
if !minimum_time_between_requests.is_zero() {
state
.last_request
.lock()
.await
.insert(address, Instant::now());
}

home_inner(State(state), Some(status)).await
}

Expand All @@ -90,6 +128,7 @@ struct Config {
private_key: String,
eth_amount: String,
explorer_url: Option<String>,
minimum_time_between_requests: Duration,
}

fn env_var(key: &'static str) -> Result<String> {
Expand All @@ -108,13 +147,17 @@ impl Config {
private_key: env_var("PRIVATE_KEY")?,
eth_amount: env_var("ETH_AMOUNT").unwrap_or_else(|_| "1".to_owned()),
explorer_url: env_var("EXPLORER_URL").ok(),
minimum_time_between_requests: env_var("MINIMUM_SECONDS_BETWEEN_REQUESTS")
.and_then(|t| Ok(Duration::from_secs(t.parse()?)))
.unwrap_or(Duration::from_secs(300)),
})
}
}

struct AppState {
signer: SignerMiddleware<Provider<Http>, LocalWallet>,
provider: NonceManagerMiddleware<SignerMiddleware<Provider<Http>, LocalWallet>>,
config: Config,
last_request: Mutex<HashMap<Address, Instant>>,
}

#[tokio::main]
Expand All @@ -123,10 +166,16 @@ async fn main() -> Result<()> {

let provider = Provider::try_from(&config.rpc_url)?;
let wallet: LocalWallet = config.private_key.parse()?;
let signer = SignerMiddleware::new_with_provider_chain(provider, wallet).await?;
let provider = SignerMiddleware::new_with_provider_chain(provider, wallet).await?;
let address = provider.address();
let provider = NonceManagerMiddleware::new(provider, address);

let addr = ("0.0.0.0".parse::<IpAddr>()?, config.http_port).into();
let state = Arc::new(AppState { signer, config });
let state = Arc::new(AppState {
provider,
config,
last_request: Default::default(),
});

let app = Router::new()
.route("/", get(home).post(request))
Expand Down
Loading