Skip to content

Commit

Permalink
feat: revealed pks
Browse files Browse the repository at this point in the history
  • Loading branch information
mateuszjasiuk committed Jun 3, 2024
1 parent 1d66c51 commit 622bb6b
Show file tree
Hide file tree
Showing 31 changed files with 381 additions and 12 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ chrono = { version = "0.4.30", features = ["serde"] }
async-trait = "0.1.73"
anyhow = "1.0.75"
namada_core = { git = "https://github.com/anoma/namada", tag = "v0.37.0" }
namada_sdk = { git = "https://github.com/anoma/namada", tag = "v0.37.0" }
namada_sdk = { git = "https://github.com/anoma/namada", tag = "v0.37.0", default-features = false, features = ["tendermint-rpc", "std", "async-send", "download-params", "rand"] }
namada_tx = { git = "https://github.com/anoma/namada", tag = "v0.37.0" }
namada_governance = { git = "https://github.com/anoma/namada", tag = "v0.37.0" }
namada_ibc = { git = "https://github.com/anoma/namada", tag = "v0.37.0" }
Expand Down
21 changes: 16 additions & 5 deletions chain/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,12 @@ async fn crawling_fn(
.into_rpc_error()?;
tracing::info!("Updating unbonds for {} addresses", unbonds.len());

let revealed_pks = block.revealed_pks();
tracing::info!(
"Updating revealed pks for {} addresses",
revealed_pks.len()
);

let metadata_change = block.validator_metadata();

let reward_claimers = block.pos_rewards();
Expand Down Expand Up @@ -204,11 +210,6 @@ async fn crawling_fn(
repository::pos::insert_bonds(transaction_conn, bonds)?;
repository::pos::insert_unbonds(transaction_conn, unbonds)?;

repository::crawler::insert_crawler_state(
transaction_conn,
crawler_state,
)?;

repository::pos::delete_claimed_rewards(
transaction_conn,
reward_claimers,
Expand All @@ -219,6 +220,16 @@ async fn crawling_fn(
metadata_change,
)?;

repository::revealed_pk::insert_revealed_pks(
transaction_conn,
revealed_pks,
)?;

repository::crawler::insert_crawler_state(
transaction_conn,
crawler_state,
)?;

anyhow::Ok(())
})
})
Expand Down
1 change: 1 addition & 0 deletions chain/src/repository/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ pub mod balance;
pub mod crawler;
pub mod gov;
pub mod pos;
pub mod revealed_pk;
22 changes: 22 additions & 0 deletions chain/src/repository/revealed_pk.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use anyhow::Context;
use diesel::{PgConnection, RunQueryDsl};
use orm::{revealed_pk::RevealedPkInsertDb, schema::revealed_pk};
use shared::{id::Id, public_key::PublicKey};

pub fn insert_revealed_pks(
transaction_conn: &mut PgConnection,
revealed_pks: Vec<(PublicKey, Id)>,
) -> anyhow::Result<()> {
diesel::insert_into(revealed_pk::table)
.values::<&Vec<RevealedPkInsertDb>>(
&revealed_pks
.into_iter()
.map(|(pk, address)| RevealedPkInsertDb::from(pk, address))
.collect::<Vec<_>>(),
)
.on_conflict_do_nothing()
.execute(transaction_conn)
.context("Failed to update balances in db")?;

anyhow::Ok(())
}
3 changes: 2 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,11 @@ services:
environment:
DATABASE_URL: postgres://postgres:password@postgres:5435/namada-indexer
CACHE_URL: redis://dragonfly:6379
TENDERMINT_URL: http://localhost:27657
healthcheck:
test: curl --fail http://localhost:5000/health || exit 1
interval: 15s
timeout: 10s
retries: 3
start_period: 10s


3 changes: 3 additions & 0 deletions orm/migrations/2024-06-03-084149_init_revealed_pk/down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-- This file should undo anything in `up.sql`

DROP TABLE IF EXISTS revealed_pk;
9 changes: 9 additions & 0 deletions orm/migrations/2024-06-03-084149_init_revealed_pk/up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
-- Your SQL goes here

CREATE TABLE revealed_pk (
id SERIAL PRIMARY KEY,
address VARCHAR NOT NULL,
pk VARCHAR NOT NULL
);

ALTER TABLE revealed_pk ADD UNIQUE (address, pk);
1 change: 1 addition & 0 deletions orm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub mod governance_proposal;
pub mod governance_votes;
pub mod migrations;
pub mod pos_rewards;
pub mod revealed_pk;
pub mod schema;
pub mod unbond;
pub mod validators;
23 changes: 23 additions & 0 deletions orm/src/revealed_pk.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use diesel::{Insertable, Queryable, Selectable};
use shared::{id::Id, public_key::PublicKey};

use crate::schema::revealed_pk;

#[derive(Insertable, Clone, Queryable, Selectable)]
#[diesel(table_name = revealed_pk)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct RevealedPkInsertDb {
pub pk: String,
pub address: String,
}

pub type RevealedPkDb = RevealedPkInsertDb;

impl RevealedPkInsertDb {
pub fn from(pk: PublicKey, address: Id) -> Self {
Self {
pk: pk.0,
address: address.to_string(),
}
}
}
9 changes: 9 additions & 0 deletions orm/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,14 @@ diesel::table! {
}
}

diesel::table! {
revealed_pk (id) {
id -> Int4,
address -> Varchar,
pk -> Varchar,
}
}

diesel::table! {
unbonds (id) {
id -> Int4,
Expand Down Expand Up @@ -134,6 +142,7 @@ diesel::allow_tables_to_appear_in_same_query!(
governance_proposals,
governance_votes,
pos_rewards,
revealed_pk,
unbonds,
validators,
);
20 changes: 20 additions & 0 deletions shared/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::collections::{BTreeMap, HashSet};
use std::str::FromStr;

use namada_sdk::borsh::BorshDeserialize;
use namada_sdk::key::common::PublicKey as NamadaPublicKey;
use namada_tx::data::pos;
use subtle_encoding::hex;
use tendermint_rpc::endpoint::block::Response as TendermintBlockResponse;
Expand All @@ -12,6 +13,7 @@ use crate::checksums::Checksums;
use crate::header::BlockHeader;
use crate::id::Id;
use crate::proposal::{GovernanceProposal, GovernanceProposalKind};
use crate::public_key::PublicKey;
use crate::transaction::{Transaction, TransactionKind};
use crate::unbond::UnbondAddresses;
use crate::utils::BalanceChange;
Expand Down Expand Up @@ -486,4 +488,22 @@ impl Block {
})
.collect()
}

pub fn revealed_pks(&self) -> Vec<(PublicKey, Id)> {
self.transactions
.iter()
.filter_map(|tx| match &tx.kind {
TransactionKind::RevealPk(data) => {
let namada_public_key =
NamadaPublicKey::try_from_slice(data).unwrap();

Some((
PublicKey::from(namada_public_key.clone()),
Id::from(namada_public_key),
))
}
_ => None,
})
.collect()
}
}
1 change: 1 addition & 0 deletions shared/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub mod error;
pub mod header;
pub mod id;
pub mod proposal;
pub mod public_key;
pub mod rewards;
pub mod transaction;
pub mod unbond;
Expand Down
9 changes: 9 additions & 0 deletions shared/src/public_key.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use namada_sdk::key::common::PublicKey as NamadaPublicKey;

pub struct PublicKey(pub String);

impl From<NamadaPublicKey> for PublicKey {
fn from(pk: NamadaPublicKey) -> Self {
PublicKey(pk.to_string())
}
}
2 changes: 2 additions & 0 deletions shared/src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub enum TransactionKind {
InitProposal(Vec<u8>),
MetadataChange(Vec<u8>),
CommissionChange(Vec<u8>),
RevealPk(Vec<u8>),
Unknown,
}

Expand Down Expand Up @@ -60,6 +61,7 @@ impl TransactionKind {
"tx_commission_change" => {
TransactionKind::CommissionChange(data.to_vec())
}
"tx_reveal_pk" => TransactionKind::RevealPk(data.to_vec()),
_ => TransactionKind::Unknown,
}
}
Expand Down
24 changes: 23 additions & 1 deletion swagger.yml
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,24 @@ paths:
items:
$ref: '#/components/schemas/Balance'

/api/v1/revealed_public_key/{address}:
get:
summary: Get revealed public key for an address if exists
parameters:
- in: path
name: address
schema:
type: string
required: true
description: The address account
responses:
'200':
description: Revealed public key.
content:
application/json:
schema:
$ref: '#/components/schemas/RevealedPk'

components:
schemas:
Validator:
Expand Down Expand Up @@ -384,7 +402,6 @@ components:
type: object
properties:
validator:
type: object
$ref: '#/components/schemas/Validator'
amount:
type: number
Expand Down Expand Up @@ -453,4 +470,9 @@ components:
total_items:
type: integer
minimum: 0
RevealedPk:
type: object
properties:
publicKey:
type: string

1 change: 1 addition & 0 deletions webserver/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ tokio.workspace = true
tower.workspace = true
tower-http.workspace = true
tracing.workspace = true
namada_sdk.workspace = true
tracing-subscriber.workspace = true
serde.workspace = true
serde_json.workspace = true
Expand Down
2 changes: 1 addition & 1 deletion webserver/run.sh
Original file line number Diff line number Diff line change
@@ -1 +1 @@
cargo run -- --database-url postgres://postgres:[email protected]:5435/namada-indexer --cache-url redis://[email protected]:6379
cargo run -- --database-url postgres://postgres:[email protected]:5435/namada-indexer --cache-url redis://[email protected]:6379 --tendermint-url http://127.0.0.1:27657
10 changes: 8 additions & 2 deletions webserver/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use axum::routing::get;
use axum::{BoxError, Json, Router};
use axum_trace_id::SetTraceIdLayer;
use lazy_static::lazy_static;
use namada_sdk::tendermint_rpc::HttpClient;
use serde_json::json;
use tower::buffer::BufferLayer;
use tower::limit::RateLimitLayer;
Expand All @@ -20,7 +21,7 @@ use crate::appstate::AppState;
use crate::config::AppConfig;
use crate::handler::{
balance as balance_handlers, chain as chain_handlers,
governance as gov_handlers, pos as pos_handlers,
governance as gov_handlers, pk as pk_handlers, pos as pos_handlers,
};
use crate::state::common::CommonState;

Expand All @@ -37,9 +38,10 @@ impl ApplicationServer {
let cache_url = config.cache_url.clone();

let app_state = AppState::new(db_url, cache_url);
let client = HttpClient::new(config.tendermint_url.as_str()).unwrap();

let routes = {
let common_state = CommonState::new(app_state.clone());
let common_state = CommonState::new(client, app_state.clone());

Router::new()
.route("/pos/validator", get(pos_handlers::get_validators))
Expand Down Expand Up @@ -82,6 +84,10 @@ impl ApplicationServer {
"/account/:address",
get(balance_handlers::get_address_balance),
)
.route(
"/revealed_public_key/:address",
get(pk_handlers::get_revealed_pk),
)
.route("/chain/sync", get(chain_handlers::sync_height))
.with_state(common_state)
};
Expand Down
3 changes: 3 additions & 0 deletions webserver/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,7 @@ pub struct AppConfig {

#[clap(long, env)]
pub rps: Option<u64>,

#[clap(long, env)]
pub tendermint_url: String,
}
4 changes: 4 additions & 0 deletions webserver/src/error/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use thiserror::Error;
use super::balance::BalanceError;
use super::governance::GovernanceError;
use super::pos::PoSError;
use super::revealed_pk::RevealedPkError;
use crate::response::api::ApiErrorResponse;

#[derive(Error, Debug)]
Expand All @@ -15,6 +16,8 @@ pub enum ApiError {
BalanceError(#[from] BalanceError),
#[error(transparent)]
GovernanceError(#[from] GovernanceError),
#[error(transparent)]
RevealedPkError(#[from] RevealedPkError),
#[error("No chain parameters stored")]
NoChainParameters,
#[error("Invalid request header")]
Expand All @@ -33,6 +36,7 @@ impl IntoResponse for ApiError {
ApiError::PoSError(error) => error.into_response(),
ApiError::BalanceError(error) => error.into_response(),
ApiError::GovernanceError(error) => error.into_response(),
ApiError::RevealedPkError(error) => error.into_response(),
ApiError::InvalidHeader => ApiErrorResponse::send(
StatusCode::BAD_REQUEST.as_u16(),
Some("Invalid Header".to_string()),
Expand Down
1 change: 1 addition & 0 deletions webserver/src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ pub mod api;
pub mod balance;
pub mod governance;
pub mod pos;
pub mod revealed_pk;
30 changes: 30 additions & 0 deletions webserver/src/error/revealed_pk.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use thiserror::Error;

use crate::response::api::ApiErrorResponse;

#[derive(Error, Debug)]
pub enum RevealedPkError {
#[error("Revealed public key {0} not found")]
NotFound(u64),
#[error("Database error: {0}")]
Database(String),
#[error("Rpc error: {0}")]
Rpc(String),
#[error("Unknown error: {0}")]
Unknown(String),
}

impl IntoResponse for RevealedPkError {
fn into_response(self) -> Response {
let status_code = match self {
RevealedPkError::NotFound(_) => StatusCode::NOT_FOUND,
RevealedPkError::Unknown(_)
| RevealedPkError::Database(_)
| RevealedPkError::Rpc(_) => StatusCode::INTERNAL_SERVER_ERROR,
};

ApiErrorResponse::send(status_code.as_u16(), Some(self.to_string()))
}
}
Loading

0 comments on commit 622bb6b

Please sign in to comment.