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

ci #1

Merged
merged 3 commits into from
Sep 18, 2023
Merged

ci #1

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: 2 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
target
scripts
59 changes: 59 additions & 0 deletions .github/workflows/docker.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
name: Build docker images

on:
workflow_dispatch:
inputs:
tag:
description: 'The docker image tag'
required: true
push:
branches:
- master
pull_request:
branches:
- master

env:
GIT_LFS_SKIP_SMUDGE: 1

jobs:
docker:
runs-on: ubuntu-latest

steps:
- name: Checkout repo
uses: actions/checkout@v3
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
with:
version: v0.9.1
- name: Login to private registry
uses: docker/login-action@v1
with:
registry: ${{ secrets.REGISTRY_URL }}
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_PASSWORD }}
- name: Docker meta
id: meta
uses: docker/metadata-action@v4
with:
images: ${{ secrets.REGISTRY_URL }}/namada-faucet
tags: |
type=schedule
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}}
type=raw,value=latest
- name: Build and Push
uses: docker/build-push-action@v4
with:
context: .
file: Dockerfile
push: ${{ github.ref == 'refs/heads/master' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}

12 changes: 12 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,15 @@ axum-macros = "0.3.8"

[patch.crates-io]
borsh = {git = "https://github.com/heliaxdev/borsh-rs.git", rev = "cd5223e5103c4f139e0c54cf8259b7ec5ec4073a"}

[profile.ephemeral-build]
inherits = "release"
incremental = false
lto = "thin"
opt-level = 2
codegen-units = 64
strip = "symbols"
debug = false

[profile.release]
incremental = false
24 changes: 24 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# use the default dart image as the build image
FROM rust:1.70 AS builder

# copy the current folder into the build folder
COPY . /app

# set the work directory
WORKDIR /app

# install protoc
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install --no-install-recommends --assume-yes protobuf-compiler libprotobuf-dev

# build app
RUN cargo build --release

# use a slim image
FROM debian:bullseye-slim

# copy the runtime files
COPY --from=builder /app/target/release/namada-faucet /app/server
WORKDIR /app

# start the dart server
CMD ["./server"]
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Namada Faucet

9 changes: 9 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
build:
cacrgo build

build-release:
cargo build --release

misc:
cargo clippy --fix --allow-dirty
cargo fmt
3 changes: 1 addition & 2 deletions rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
[toolchain]
channel = "1.70.0"
components = ["rustc", "cargo", "rust-std", "rust-docs", "rls", "rust-src", "rust-analysis"]
targets = ['x86_64-unknown-linux-musl']
components = ["rustc", "cargo", "rust-std", "rust-docs", "rls", "rust-src", "rust-analysis"]
17 changes: 13 additions & 4 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,14 @@ use tower_http::{
trace::TraceLayer,
};

use crate::{handler::faucet as faucet_handler, sdk::{utils::{sk_from_str, str_to_address}, namada::NamadaSdk}};
use crate::{app_state::AppState, config::AppConfig, state::faucet::FaucetState};
use crate::{
handler::faucet as faucet_handler,
sdk::{
namada::NamadaSdk,
utils::{sk_from_str, str_to_address},
},
};

lazy_static! {
static ref HTTP_TIMEOUT: u64 = 30;
Expand Down Expand Up @@ -54,10 +60,10 @@ impl ApplicationServer {
let nam_address = config.nam_address.clone();
let nam_address = str_to_address(&nam_address);

let sdk = NamadaSdk::new(rpc);
let sdk = NamadaSdk::new(rpc, sk.clone(), nam_address);

let routes = {
let faucet_state = FaucetState::new(&db, sdk, sk, nam_address, auth_key, difficulty, chain_id);
let faucet_state = FaucetState::new(&db, sdk, auth_key, difficulty, chain_id);

Router::new()
.route("/faucet", get(faucet_handler::request_challenge))
Expand All @@ -78,7 +84,10 @@ impl ApplicationServer {
.timeout(Duration::from_secs(*HTTP_TIMEOUT))
.layer(cors)
.layer(BufferLayer::new(4096))
.layer(RateLimitLayer::new(rps.unwrap_or(*REQ_PER_SEC), Duration::from_secs(1)))
.layer(RateLimitLayer::new(
rps.unwrap_or(*REQ_PER_SEC),
Duration::from_secs(1),
)),
);

let router = router.fallback(Self::handle_404);
Expand Down
4 changes: 2 additions & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ pub struct AppConfig {
pub chain_id: String,

#[clap(long, env)]
pub rpc: String,
pub rpc: String,

#[clap(long, env)]
pub nam_address: String,
pub nam_address: String,

#[clap(long, env)]
pub auth_key: Option<String>,
Expand Down
3 changes: 1 addition & 2 deletions src/dto/faucet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ pub struct FaucetRequestDto {
pub challenge: String,
#[validate(length(equal = 64, message = "Invalid proof"))]
pub tag: String,
pub transfer: Transfer

pub transfer: Transfer,
}

#[derive(Clone, Serialize, Deserialize, Validate)]
Expand Down
1 change: 0 additions & 1 deletion src/error/faucet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ impl IntoResponse for FaucetError {
FaucetError::InvalidProof => StatusCode::FORBIDDEN,
FaucetError::DuplicateChallenge => StatusCode::CONFLICT,
FaucetError::InvalidAddress => StatusCode::BAD_REQUEST,

};

ApiErrorResponse::send(status_code.as_u16(), Some(self.to_string()))
Expand Down
35 changes: 22 additions & 13 deletions src/handler/faucet.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
use std::sync::{Arc, RwLock};

use axum::{extract::State, Json};
use axum_macros::debug_handler;
use namada::{types::address::Address, tendermint::abci::Code};
use namada::{tendermint::abci::Code, types::address::Address};

use crate::{
dto::faucet::{FaucetRequestDto, FaucetResponseDto, FaucetResponseStatusDto},
error::{api::ApiError, faucet::FaucetError, validate::ValidatedRequest},
repository::faucet::FaucetRepositoryTrait,
state::faucet::FaucetState, sdk::namada::NamadaSdk,
state::faucet::FaucetState,
};

pub async fn request_challenge(
Expand All @@ -35,13 +33,13 @@ pub async fn request_transfer(
let token_address = if let Ok(address) = token_address {
address
} else {
return Err(FaucetError::InvalidAddress.into())
return Err(FaucetError::InvalidAddress.into());
};
let target_address = Address::decode(payload.transfer.target.clone());
let target_address = if let Ok(address) = target_address {
address
} else {
return Err(FaucetError::InvalidAddress.into())
return Err(FaucetError::InvalidAddress.into());
};

if state.faucet_repo.contains(&payload.challenge) {
Expand All @@ -66,22 +64,33 @@ pub async fn request_transfer(

let mut locked_sdk = state.sdk.lock().await;

let sk = state.sk.clone();
let nam_address = state.nam_address.clone();
let sk = locked_sdk.get_secret_key();
let nam_address = locked_sdk.get_address("nam".to_string());

let owner = Address::from(&sk.to_public());
let tx_args = locked_sdk.default_args(chain_id, vec![sk], None, nam_address.clone());
let signing_data = locked_sdk.compute_signing_data(Some(owner.clone()), None, &tx_args).await;
let tx_data = locked_sdk.build_transfer_args(owner, target_address, token_address, payload.transfer.amount, nam_address, tx_args.clone());
let mut tx = locked_sdk.build_transfer_tx(tx_data, signing_data.fee_payer.clone()).await;
let signing_data = locked_sdk
.compute_signing_data(Some(owner.clone()), None, &tx_args)
.await;
let tx_data = locked_sdk.build_transfer_args(
owner,
target_address,
token_address,
payload.transfer.amount,
nam_address,
tx_args.clone(),
);
let mut tx = locked_sdk
.build_transfer_tx(tx_data, signing_data.fee_payer.clone())
.await;
locked_sdk.sign_tx(&mut tx, signing_data, &tx_args);
let process_tx_response = locked_sdk.process_tx(tx, &tx_args).await;
drop(locked_sdk);

let transfer_result = match process_tx_response {
namada::ledger::tx::ProcessTxResponse::Applied(r) => r.code.eq(&"0"),
namada::ledger::tx::ProcessTxResponse::Broadcast(r) => r.code.eq(&Code::Ok),
_ => false
_ => false,
};

if transfer_result {
Expand All @@ -90,7 +99,7 @@ pub async fn request_transfer(

let response = FaucetResponseStatusDto {
token: payload.transfer.token.clone(),
amount: payload.transfer.amount.clone(),
amount: payload.transfer.amount,
target: payload.transfer.target.clone(),
sent: transfer_result,
};
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub mod error;
pub mod handler;
pub mod repository;
pub mod response;
pub mod sdk;
pub mod services;
pub mod state;
pub mod utils;
pub mod sdk;
6 changes: 4 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ async fn main() -> anyhow::Result<()> {
dotenv().ok();
let config = Arc::new(AppConfig::parse());
let db = Arc::new(RwLock::new(AppState::default()));

tracing_subscriber::fmt().with_max_level(tracing::Level::INFO).init();

tracing_subscriber::fmt()
.with_max_level(tracing::Level::INFO)
.init();

ApplicationServer::serve(config, db)
.await
Expand Down
2 changes: 1 addition & 1 deletion src/sdk/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ impl ClientTrait for SdkClient {
match response {
Ok(response) => {
let response_json = response.text().await.unwrap();
R::Response::from_string(&response_json)
R::Response::from_string(response_json)
}
Err(e) => {
let error_msg = e.to_string();
Expand Down
17 changes: 2 additions & 15 deletions src/sdk/masp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,14 @@ use borsh::{BorshDeserialize, BorshSerialize};
use masp_proofs::prover::LocalTxProver;
use namada::ledger::masp::{ShieldedContext, ShieldedUtils};

#[derive(Default)]
pub struct SdkShieldedCtx {
pub shielded_context: ShieldedContext<SdkShieldedUtils>,
}

impl Default for SdkShieldedCtx {
fn default() -> Self {
Self {
shielded_context: Default::default(),
}
}
}

#[derive(Clone, BorshDeserialize, BorshSerialize)]
#[derive(Clone, BorshDeserialize, BorshSerialize, Default)]
pub struct SdkShieldedUtils {}

impl Default for SdkShieldedUtils {
fn default() -> Self {
Self {}
}
}

#[async_trait::async_trait]
impl ShieldedUtils for SdkShieldedUtils {
fn local_tx_prover(&self) -> LocalTxProver {
Expand Down
6 changes: 3 additions & 3 deletions src/sdk/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
pub mod namada;
pub mod client;
pub mod wallet;
pub mod masp;
pub mod utils;
pub mod namada;
pub mod utils;
pub mod wallet;
Loading
Loading