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

chore: Add endpoints to minibf #447

Draft
wants to merge 7 commits into
base: feat/light-bf
Choose a base branch
from
Draft
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
26 changes: 13 additions & 13 deletions Cargo.lock

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

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ authors = ["Santiago Carmuega <[email protected]>"]


[dependencies]
pallas = { git = "https://github.com/txpipe/pallas.git", features = ["hardano", "applying"] }
# pallas = { version = "^0.30.1", features = ["hardano", "applying"] }
pallas = { git = "https://github.com/gonzalezzfelipe/pallas.git", branch = "fix/error-on-tx-validation", features = ["hardano", "applying"] }
# pallas = { version = "0.32.0", features = ["hardano", "applying"] }
# pallas = { path = "../pallas/pallas", features = ["hardano", "applying"] }

# gasket = { git = "https://github.com/construkts/gasket-rs.git", features = ["derive"] }
Expand Down
8 changes: 4 additions & 4 deletions src/ledger/pparams/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use pallas::{
traverse::MultiEraUpdate,
},
};
use tracing::{debug, warn};
use tracing::debug;

mod hacks;
mod summary;
Expand Down Expand Up @@ -363,7 +363,7 @@ fn apply_param_update(
apply_field!(pparams, update, extra_entropy);

if let Some(value) = update.alonzo_first_proposed_cost_models_for_script_languages() {
warn!(
debug!(
?value,
"found new cost_models_for_script_languages update proposal"
);
Expand Down Expand Up @@ -399,7 +399,7 @@ fn apply_param_update(
apply_field!(pparams, update, extra_entropy);

if let Some(value) = update.babbage_first_proposed_cost_models_for_script_languages() {
warn!(
debug!(
?value,
"found new cost_models_for_script_languages update proposal"
);
Expand Down Expand Up @@ -442,7 +442,7 @@ fn apply_param_update(
apply_field!(pparams, update, minfee_refscript_cost_per_byte);

if let Some(value) = update.conway_first_proposed_cost_models_for_script_languages() {
warn!(
debug!(
?value,
"found new cost_models_for_script_languages update proposal"
);
Expand Down
68 changes: 68 additions & 0 deletions src/serve/minibf/common.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
use rocket::{http::Status, FromFormField};

#[derive(Default, Debug, Clone, FromFormField)]
pub enum Order {
#[default]
Asc,
Desc,
}

#[derive(Debug, Clone)]
pub struct Pagination {
pub count: u8,
pub page: u64,
pub order: Order,
}
impl Default for Pagination {
fn default() -> Self {
Pagination {
count: 100,
page: 1,
order: Order::Asc,
}
}
}
impl Pagination {
pub fn try_new(
count: Option<u8>,
page: Option<u64>,
order: Option<Order>,
) -> Result<Self, Status> {
let count = match count {
Some(count) => {
if !(1..=100).contains(&count) {
return Err(Status::BadRequest);
} else {
count
}
}
None => 100,
};
let page = match page {
Some(page) => {
if page < 1 {
return Err(Status::BadRequest);
} else {
page
}
}
None => 1,
};
Ok(Self {
count,
page,
order: order.unwrap_or_default(),
})
}

pub fn from(&self) -> usize {
((self.page - 1) * self.count as u64) as usize
}

pub fn to(&self) -> usize {
(self.count as u64 * self.page) as usize
}
pub fn includes(&self, i: usize) -> bool {
i > self.from() && i <= self.to()
}
}
140 changes: 38 additions & 102 deletions src/serve/minibf/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use pallas::ledger::{primitives::conway, traverse::MultiEraAsset};
use rocket::{get, http::Status, routes, State};
use pallas::ledger::traverse::wellknown::GenesisValues;
use rocket::routes;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::{net::SocketAddr, sync::Arc};
use tokio_util::sync::CancellationToken;

use crate::{
ledger::{EraCbor, TxoRef},
state::LedgerStore,
};
use crate::{ledger::pparams::Genesis, mempool::Mempool, state::LedgerStore, wal::redb::WalStore};

mod common;
mod routes;

#[derive(Deserialize, Serialize, Clone)]
pub struct Config {
Expand All @@ -16,7 +16,11 @@ pub struct Config {

pub async fn serve(
cfg: Config,
genesis: Arc<Genesis>,
genesis_values: GenesisValues,
wal: WalStore,
ledger: LedgerStore,
mempool: Mempool,
_exit: CancellationToken,
) -> Result<(), rocket::Error> {
// TODO: connect cancellation token to rocket shutdown
Expand All @@ -34,104 +38,36 @@ pub async fn serve(
.merge(("address", cfg.listen_address.ip().to_string()))
.merge(("port", cfg.listen_address.port())),
)
.manage(genesis)
.manage(genesis_values)
.manage(wal)
.manage(ledger)
.mount("/", routes![address_utxos])
.manage(mempool)
.mount(
"/",
routes![
// Accounts
routes::accounts::stake_address::utxos::route,
// Addresses
routes::addresses::address::utxos::route,
routes::addresses::address::utxos::asset::route,
// Blocks
routes::blocks::latest::route,
routes::blocks::latest::txs::route,
routes::blocks::hash_or_number::route,
routes::blocks::hash_or_number::addresses::route,
routes::blocks::hash_or_number::next::route,
routes::blocks::hash_or_number::previous::route,
routes::blocks::hash_or_number::txs::route,
routes::blocks::slot::slot_number::route,
//Epoch
routes::epochs::latest::parameters::route,
// Submit
routes::tx::submit::route,
],
)
.launch()
.await?;

Ok(())
}

#[derive(Debug, Serialize, Deserialize)]
struct Amount {
unit: String,
quantity: String,
}

impl Amount {
fn lovelace(quantity: u64) -> Self {
Self {
unit: "lovelace".to_string(),
quantity: quantity.to_string(),
}
}
}

#[derive(Debug, Serialize, Deserialize)]
struct Utxo {
address: String,
tx_hash: String,
output_index: u32,
amount: Vec<Amount>,
data_hash: Option<String>,
inline_datum: Option<String>,
reference_script_hash: Option<String>,
}

impl From<MultiEraAsset<'_>> for Amount {
fn from(value: MultiEraAsset<'_>) -> Self {
Self {
unit: value.policy().to_string(),
quantity: value.any_coin().to_string(),
}
}
}

impl TryFrom<(TxoRef, EraCbor)> for Utxo {
type Error = Status;

fn try_from((txo, era): (TxoRef, EraCbor)) -> Result<Self, Self::Error> {
let parsed = pallas::ledger::traverse::MultiEraOutput::decode(era.0, &era.1)
.map_err(|_| Status::InternalServerError)?;

let value = parsed.value();
let lovelace = Amount::lovelace(value.coin());
let assets: Vec<Amount> = value
.assets()
.iter()
.flat_map(|x| x.assets())
.map(|x| x.into())
.collect();

Ok(Self {
tx_hash: txo.0.to_string(),
output_index: txo.1,
address: parsed
.address()
.map_err(|_| Status::InternalServerError)?
.to_string(),
amount: std::iter::once(lovelace).chain(assets).collect(),
data_hash: parsed.datum().and_then(|x| match x {
conway::PseudoDatumOption::Hash(hash) => Some(hash.to_string()),
conway::PseudoDatumOption::Data(_) => None,
}),
inline_datum: parsed.datum().and_then(|x| match x {
conway::PseudoDatumOption::Hash(_) => None,
conway::PseudoDatumOption::Data(x) => Some(hex::encode(x.raw_cbor())),
}),
reference_script_hash: None,
})
}
}

#[get("/addresses/<address>/utxos")]
fn address_utxos(
address: String,
ledger: &State<LedgerStore>,
) -> Result<rocket::serde::json::Json<Vec<Utxo>>, Status> {
let address = pallas::ledger::addresses::Address::from_bech32(&address)
.map_err(|_| Status::BadRequest)?;

let refs = ledger
.get_utxo_by_address(&address.to_vec())
.map_err(|_| Status::InternalServerError)?;

let utxos: Vec<_> = ledger
.get_utxos(refs.into_iter().collect())
.map_err(|_| Status::InternalServerError)?
.into_iter()
.map(|x| Utxo::try_from(x))
.collect::<Result<_, _>>()?;

Ok(rocket::serde::json::Json(utxos))
}
1 change: 1 addition & 0 deletions src/serve/minibf/routes/accounts/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod stake_address;
Loading