Skip to content

Commit

Permalink
Merge branch 'main' into backup
Browse files Browse the repository at this point in the history
  • Loading branch information
tq-tuan15 committed Feb 11, 2024
2 parents 4aadf98 + a99261d commit a73d0aa
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 12 deletions.
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ CHECK_CURL := $(shell command -v curl 2> /dev/null)
CHECK_WGET := $(shell command -v wget 2> /dev/null)

ifdef CHECK_CURL
DOWNLOAD_CMD = curl -o
DOWNLOAD_CMD = curl -L -o
else ifdef CHECK_WGET
DOWNLOAD_CMD = wget -O
else
Expand All @@ -35,7 +35,7 @@ download-checksum:

install-deps:
# Use OS variable in the download URL and unzip command
$(DOWNLOAD_CMD) https://github.com/protocolbuffers/protobuf/releases/download/v3.16.3/protoc-3.16.3-$(OS)-x86_64.zip
$(DOWNLOAD_CMD) protoc-3.16.3-$(OS)-x86_64.zip https://github.com/protocolbuffers/protobuf/releases/download/v3.16.3/protoc-3.16.3-$(OS)-x86_64.zip
unzip protoc-3.16.3-$(OS)-x86_64.zip -d ./protoc


Expand Down
1 change: 1 addition & 0 deletions config/Settings.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ host = "localhost"
user = "postgres"
password = "wow"
dbname = "blockchain"
port=5432
# Optional field to configure a timeout if database connection
# fails.
connection_timeout = 20
Expand Down
5 changes: 5 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pub struct DatabaseConfig {
pub user: String,
pub password: String,
pub dbname: String,
pub port: u16,
// The limit in seconds to wait for a ready database connection
pub connection_timeout: Option<u64>,
// Give the option to skip the index creation
Expand Down Expand Up @@ -112,6 +113,7 @@ impl Default for DatabaseConfig {
user: "postgres".to_owned(),
password: "wow".to_owned(),
dbname: "blockchain".to_owned(),
port: 5432,
connection_timeout: None,
create_index: true,
}
Expand All @@ -136,6 +138,8 @@ pub struct CliSettings {
pub database_password: String,
#[clap(long, env, default_value = "blockchain")]
pub database_dbname: String,
#[clap(long, env, default_value_t = 5432)]
pub database_port: u16,
#[clap(long, env)]
pub database_connection_timeout: Option<u64>,
#[clap(long, env, default_value = "true")]
Expand Down Expand Up @@ -189,6 +193,7 @@ impl From<CliSettings> for Settings {
user: value.database_user,
password: value.database_password,
dbname: value.database_dbname,
port: value.database_port,
connection_timeout: value.database_connection_timeout,
create_index: value.database_create_index,
},
Expand Down
21 changes: 18 additions & 3 deletions src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ pub struct Database {
impl Database {
pub async fn new(db_config: &DatabaseConfig, network: &str) -> Result<Database, Error> {
// sqlx expects config of the form:
// postgres://user:password@host/db_name
// postgres://user:password@host:port/db_name
let config = format!(
"postgres://{}:{}@{}/{}",
db_config.user,
Expand Down Expand Up @@ -706,8 +706,7 @@ impl Database {
.push_bind(tx_bridge.transfer.sender.to_string())
.push_bind(tx_bridge.transfer.amount.to_string_native())
.push_bind(tx_bridge.gas_fee.amount.to_string_native())
.push_bind(tx_bridge.gas_fee.payer.to_string())
.push_bind(false);
.push_bind(tx_bridge.gas_fee.payer.to_string());
})
.build();
query.execute(&mut *sqlx_tx).await?;
Expand Down Expand Up @@ -1374,6 +1373,22 @@ impl Database {
Ok(count)
}

#[instrument(skip(self))]
/// Returns the latest block, otherwise returns an Error.
pub async fn get_lastest_blocks(
&self,
num: &i32,
offset: Option<&i32>,
) -> Result<Vec<Row>, Error> {
let str = format!("SELECT * FROM {0}.{BLOCKS_TABLE_NAME} ORDER BY header_height DESC LIMIT {1} OFFSET {2};", self.network, num, offset.unwrap_or(& 0));

// use query_one as the row matching max height is unique.
query(&str)
.fetch_all(&*self.pool)
.await
.map_err(Error::from)
}

pub fn pool(&self) -> &PgPool {
self.pool.as_ref()
}
Expand Down
50 changes: 43 additions & 7 deletions src/server/endpoints/block.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
use axum::{ extract::{ Path, State, Query }, Json };
use axum::{
extract::{Path, Query, State},
Json,
};
use serde::{Deserialize, Serialize};
use sqlx::Row as TRow;
use std::collections::HashMap;
use tracing::info;

use crate::{
Expand All @@ -8,6 +13,13 @@ use crate::{
Error,
};

#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum LatestBlock {
LastBlock(Box<BlockInfo>),
LatestBlocks(Vec<BlockInfo>),
}

async fn get_tx_hashes(
state: &ServerState,
block: &mut BlockInfo,
Expand Down Expand Up @@ -67,15 +79,39 @@ pub async fn get_block_by_height(
Ok(Json(Some(block)))
}

pub async fn get_last_block(State(state): State<ServerState>) -> Result<Json<BlockInfo>, Error> {
let row = state.db.get_last_block().await?;
pub async fn get_last_block(
State(state): State<ServerState>,
Query(params): Query<HashMap<String, i32>>,
) -> Result<Json<LatestBlock>, Error> {
info!("calling /block/last");

let mut block = BlockInfo::try_from(&row)?;
let num = params.get("num");
let offset = params.get("offset");

let block_id: Vec<u8> = row.try_get("block_id")?;
get_tx_hashes(&state, &mut block, &block_id).await?;
if let Some(n) = num {
let rows = state.db.get_lastest_blocks(n, offset).await?;
let mut blocks: Vec<BlockInfo> = vec![];

for row in rows {
let mut block = BlockInfo::try_from(&row)?;

let block_id: Vec<u8> = row.try_get("block_id")?;
get_tx_hashes(&state, &mut block, &block_id).await?;

Ok(Json(block))
blocks.push(block);
}

Ok(Json(LatestBlock::LatestBlocks(blocks)))
} else {
let row = state.db.get_last_block().await?;

let mut block = BlockInfo::try_from(&row)?;

let block_id: Vec<u8> = row.try_get("block_id")?;
get_tx_hashes(&state, &mut block, &block_id).await?;

Ok(Json(LatestBlock::LastBlock(Box::new(block))))
}
}

pub async fn get_blocks(
Expand Down

0 comments on commit a73d0aa

Please sign in to comment.