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 json rpc for sat ranges #11

Merged
merged 3 commits into from
Jul 27, 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
17 changes: 17 additions & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ tokio = { version = "1.17.0", features = ["rt-multi-thread"] }
tokio-stream = "0.1.9"
tokio-util = {version = "0.7.3", features = ["compat"] }
tower-http = { version = "0.4.0", features = ["compression-br", "compression-gzip", "cors", "set-header"] }

rdkafka = { version = "0.33.2" }
axum-jrpc = { version = "0.5.1", features = ["serde_json", "anyhow_error"] }


[dev-dependencies]
Expand Down
6 changes: 2 additions & 4 deletions src/index/updater/inscription_updater.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,7 @@ impl<'a, 'db, 'tx> InscriptionUpdater<'a, 'db, 'tx> {

let next_number = number_to_id
.iter()?
.rev()
.next()
.next_back()
.and_then(|result| result.ok())
.map(|(number, _id)| number.value() + 1)
.unwrap_or(0);
Expand Down Expand Up @@ -181,8 +180,7 @@ impl<'a, 'db, 'tx> InscriptionUpdater<'a, 'db, 'tx> {
let seq_num = self
.reinscription_id_to_seq_num
.iter()?
.rev()
.next()
.next_back()
.and_then(|result| result.ok())
.map(|(_id, number)| number.value() + 1)
.unwrap_or(0);
Expand Down
5 changes: 5 additions & 0 deletions src/subcommand/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ use {
};

mod error;
mod rpc;

enum BlockQuery {
Height(u64),
Expand Down Expand Up @@ -176,6 +177,10 @@ impl Server {
.route("/static/*path", get(Self::static_asset))
.route("/status", get(Self::status))
.route("/tx/:txid", get(Self::transaction))

// API routes
.route("/rpc/v1", get(rpc::handler))

.layer(Extension(index))
.layer(Extension(page_config))
.layer(Extension(Arc::new(config)))
Expand Down
148 changes: 148 additions & 0 deletions src/subcommand/server/rpc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
use crate::subcommand::{traits::Output as SatDetails, wallet::sats::rare_sats};
use super::*;
use axum_jrpc::{
error::{JsonRpcError, JsonRpcErrorReason},
JrpcResult, JsonRpcExtractor, JsonRpcResponse,
};
use serde_json::Value;

pub(super) async fn handler(
Extension(_page_config): Extension<Arc<PageConfig>>,
Extension(index): Extension<Arc<Index>>,
value: JsonRpcExtractor,
) -> JrpcResult {
match value.method.as_str() {
"getHealth" => get_health(value).await,
"getSatRanges" => get_sat_ranges(value, index).await,
method => Ok(value.method_not_found(method)),
}
}

fn invalid_params(answer_id: i64, message: String) -> JrpcResult {
Err(JsonRpcResponse::error(
answer_id,
JsonRpcError::new(JsonRpcErrorReason::InvalidParams, message, Value::default()),
))
}

async fn get_health(value: JsonRpcExtractor) -> JrpcResult {
let answer_id = value.get_answer_id();
Ok(JsonRpcResponse::success(answer_id, "OK"))
}

async fn get_sat_ranges(value: JsonRpcExtractor, index: Arc<Index>) -> JrpcResult {
#[derive(Deserialize)]
struct Req {
utxos: Vec<String>,
}

#[derive(Serialize)]
struct SatRange {
utxo: String,
start: u64,
end: u64,
}

#[derive(Serialize)]
struct RareSat {
utxo: String,
offset: u64,
rarity: Rarity,
sat: Sat,
sat_details: SatDetails,
}

#[derive(Serialize)]
struct Res {
sat_ranges: Vec<SatRange>,
rare_sats: Vec<RareSat>,
}

let answer_id = value.get_answer_id();
if index.has_sat_index().is_err() {
return invalid_params(answer_id, "Sat index is not available".to_string());
}

let req: Req = value.parse_params()?;
let mut res = Res { sat_ranges: vec![], rare_sats: vec![] };
let mut utxos: Vec<(OutPoint, Vec<(u64, u64)>)> = vec![];

for output in req.utxos {
let outpoint = match OutPoint::from_str(output.as_str()) {
Ok(outpoint) => outpoint,
Err(err) => return invalid_params(answer_id, err.to_string()),
};
let list = match index.list(outpoint) {
Ok(list) => list,
Err(err) => return invalid_params(answer_id, err.to_string()),
};
let mut sat_ranges = vec![];
if let Some(list) = list {
match list {
List::Spent => {}
List::Unspent(ranges) => {
for range in ranges {
res.sat_ranges.push(SatRange {
utxo: output.clone(),
start: range.0,
end: range.1,
});
sat_ranges.push(range);
}
}
}
}
utxos.push((outpoint, sat_ranges));
}

let rare_sats = rare_sats(utxos);
for (outpoint, sat, offset, rarity) in rare_sats {
let sat_details = SatDetails {
number: sat.n(),
decimal: sat.decimal().to_string(),
degree: sat.degree().to_string(),
name: sat.name(),
height: sat.height().0,
cycle: sat.cycle(),
epoch: sat.epoch().0,
period: sat.period(),
offset: sat.third(),
rarity: sat.rarity(),
};
res.rare_sats.push(RareSat {
utxo: outpoint.to_string(),
offset,
rarity,
sat,
sat_details,
});
}

Ok(JsonRpcResponse::success(answer_id, res))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_invalid_params() {
let result = invalid_params(123, "Invalid input".to_string());
assert!(result.is_err());
let error = result.err().unwrap();
assert_eq!(error.id, 123);
}

#[tokio::test]
async fn test_get_health() {
let value = JsonRpcExtractor {
method: "getHealth".to_string(),
parsed: Value::default(),
id: 0,
};
let result = get_health(value).await;
assert!(result.is_ok());
let response = result.unwrap();
assert_eq!(response.id, 0);
}
}
2 changes: 1 addition & 1 deletion src/subcommand/wallet/sats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl Sats {
}
}

fn rare_sats(utxos: Vec<(OutPoint, Vec<(u64, u64)>)>) -> Vec<(OutPoint, Sat, u64, Rarity)> {
pub(crate) fn rare_sats(utxos: Vec<(OutPoint, Vec<(u64, u64)>)>) -> Vec<(OutPoint, Sat, u64, Rarity)> {
utxos
.into_iter()
.flat_map(|(outpoint, sat_ranges)| {
Expand Down