Skip to content

Commit

Permalink
Update struts in typescript (#436)
Browse files Browse the repository at this point in the history
* Update struts in typescript

* Camel Case

* Update structs

* Live metrics (#435)

* Switch to in-memory metrics.

* Metrics fixes.

* Also write metrics to disk as a backup.

* Disable LN swaps tests since these often fail. (#437)

* Update struct rgbofferresponse

* Update lib/web/rgb.ts

Co-authored-by: Armando CD <[email protected]>

---------

Co-authored-by: Hunter Beast <[email protected]>
Co-authored-by: Armando CD <[email protected]>
  • Loading branch information
3 people authored Dec 14, 2023
1 parent b2a88db commit a42700d
Show file tree
Hide file tree
Showing 8 changed files with 327 additions and 148 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "bitmask-core"
version = "0.7.0-beta.9"
version = "0.7.0-beta.10"
authors = [
"Jose Diego Robles <[email protected]>",
"Hunter Trujillo <[email protected]>",
Expand Down
80 changes: 70 additions & 10 deletions lib/web/rgb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -432,15 +432,15 @@ export interface InvoiceResponse {

export interface PsbtRequest {
/// Asset UTXOs
asset_inputs: PsbtInputRequest[];
assetInputs: PsbtInputRequest[];
/// Asset Descriptor Change
asset_descriptor_change: string;
assetDescriptorChange: string;
/// Asset Terminal Change (default: /10/0)
asset_terminal_change: string;
assetTerminalChange: string;
/// Bitcoin UTXOs
bitcoin_inputs: PsbtInputRequest[];
bitcoinInputs: PsbtInputRequest[];
/// Bitcoin Change Addresses (format: {address}:{amount})
bitcoin_changes: string[];
bitcoinChanges: string[];
/// Bitcoin Fee
fee: PsbtFeeRequest;
/// Allow RBF
Expand All @@ -453,11 +453,11 @@ interface PsbtInputRequest {
/// Asset or Bitcoin UTXO
utxo: string;
/// Asset or Bitcoin UTXO Terminal (ex. /0/0)
utxo_terminal: string;
utxoTerminal: string;
/// Asset or Bitcoin Tweak
tapret?: string;
/// Asset or Bitcoin Tweak
sigh_hash?: PsbtSigHashRequest;
sighHash?: PsbtSigHashRequest;
}

interface PsbtSigHashRequest {
Expand Down Expand Up @@ -748,7 +748,7 @@ export interface RgbTransferDetail {
}

export interface TxStatus {
not_found?: any;
notFound?: any;
error?: string;
mempool?: any;
block?: number;
Expand Down Expand Up @@ -793,8 +793,66 @@ export interface RgbOfferRequest {
changeTerminal: string;
/// Bitcoin Change Addresses (format: {address}:{amount})
bitcoinChanges: string[];
presig: boolean;
expire_at?: number;
strategy: RgbSwapStrategy;
expireAt?: number;
}

export interface RgbSwapStrategy {
auction?: string,
p2p?: string,
hotswap?: string,
}
export interface RgbAuctionOfferRequest {
signKeys: string[],

/// List of Offers
offers: RgbOfferRequest[],
}

export interface RgbAuctionBidRequest {
/// The Offer ID
offerId: string,
/// Asset Amount
assetAmount: string,
/// Universal Descriptor
descriptor: string,
/// Bitcoin Terminal Change
changeTerminal: string,
/// Descriptors to Sign
signKeys: string[],
/// Bitcoin Fee
fee: PsbtFeeRequest,
}

export interface RgbAuctionBidResponse {
/// The Bid ID
bidId: string,
/// The Offer ID
offerId: string,
/// Fee Value
feeValue: number,
}

export interface RgbMatchResponse {
/// Transfer ID
consigId: string,
/// Offer ID
offerId: string,
/// Bid ID
bidId: string,
}

export interface RgbAuctionOfferResponse {
/// Offer ID
offerId: string,
/// Contract ID
contractId: string,
/// Asset/Contract Amount
assetAmount: number,
/// Bitcoin Price
bitcoinPrice: number,
/// Bundle ID
bundleId: string,
}

export interface RgbOfferResponse {
Expand All @@ -810,6 +868,8 @@ export interface RgbOfferResponse {
sellerAddress: string;
/// Seller PSBT (encoded in base64)
sellerPsbt: string;
/// Bundle ID (collection)
bundleId?: string,
}

export interface RgbBidRequest {
Expand Down
55 changes: 20 additions & 35 deletions src/bin/bitmaskd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::{
fs::OpenOptions,
io::ErrorKind,
net::SocketAddr,
path,
str::FromStr,
time::{Duration, Instant},
};
Expand All @@ -24,11 +25,7 @@ use axum::{
use bitcoin_30::secp256k1::{ecdh::SharedSecret, PublicKey, SecretKey};
use bitmask_core::{
bitcoin::{save_mnemonic, sign_and_publish_psbt_file},
carbonado::{
handle_file, marketplace_retrieve, marketplace_store,
metrics::{metrics, metrics_csv},
store,
},
carbonado::{handle_file, marketplace_retrieve, marketplace_store, metrics, store},
constants::{
get_marketplace_nostr_key, get_marketplace_seed, get_network, get_udas_utxo, switch_network,
},
Expand Down Expand Up @@ -432,7 +429,13 @@ async fn co_store(
Path((pk, name)): Path<(String, String)>,
body: Bytes,
) -> Result<impl IntoResponse, AppError> {
let cc = CacheControl::new().with_no_cache();

let incoming_header = carbonado::file::Header::try_from(&body)?;
if incoming_header.pubkey.to_string() != pk {
return Ok((StatusCode::UNAUTHORIZED, TypedHeader(cc), "Unauthorized"));
}

let body_len = incoming_header.encoded_len - incoming_header.padding_len;
info!("POST /carbonado/{pk}/{name}, {body_len} bytes");

Expand Down Expand Up @@ -471,9 +474,9 @@ async fn co_store(
},
}

let cc = CacheControl::new().with_no_cache();
metrics::update(&filepath).await?;

Ok((StatusCode::OK, TypedHeader(cc)))
Ok((StatusCode::OK, TypedHeader(cc), "Success"))
}

async fn co_force_store(
Expand Down Expand Up @@ -771,40 +774,29 @@ async fn send_coins(
}

async fn json_metrics() -> Result<impl IntoResponse, AppError> {
use bitmask_core::carbonado::metrics::metrics;
let path = std::env::var("CARBONADO_DIR").unwrap_or("/tmp/bitmaskd/carbonado".to_owned());
let contents = fs::read_to_string(&format!("{path}/metrics.json")).await?;
let metrics_json = metrics::json().await?;

Ok((
StatusCode::OK,
[("content-type", "application/json")],
contents,
metrics_json,
))
}

async fn csv_metrics() -> Result<impl IntoResponse, AppError> {
let path = std::env::var("CARBONADO_DIR").unwrap_or("/tmp/bitmaskd/carbonado".to_owned());
let contents = fs::read_to_string(&format!("{path}/metrics.csv")).await?;
let metrics_csv = metrics::csv().await;

Ok((
StatusCode::OK,
[("content-type", "application/json")],
contents,
))
Ok((StatusCode::OK, [("content-type", "text/csv")], metrics_csv))
}

async fn periodic_metrics() -> Result<()> {
let path = std::env::var("CARBONADO_DIR").unwrap_or("/tmp/bitmaskd/carbonado".to_owned());
let dir = std::path::Path::new(&path);
fs::create_dir_all(dir).await?;
async fn init_metrics() -> Result<()> {
let path = env::var("CARBONADO_DIR").unwrap_or("/tmp/bitmaskd/carbonado".to_owned());
let dir = path::Path::new(&path);

info!("Starting metrics collection...");

let duration = Instant::now();

let metrics = metrics(dir).await?;
let metrics_json = serde_json::to_string_pretty(&metrics)?;
let metrics_csv = metrics_csv(metrics);
metrics::init(dir).await?;

let duration = Instant::now() - duration;

Expand All @@ -813,11 +805,6 @@ async fn periodic_metrics() -> Result<()> {
duration.as_secs_f32()
);

fs::write(&format!("{path}/metrics.json"), &metrics_json).await?;
fs::write(&format!("{path}/metrics.csv"), &metrics_csv).await?;

sleep(Duration::from_secs(4 * 60 * 60)).await;

Ok(())
}

Expand Down Expand Up @@ -896,10 +883,8 @@ async fn main() -> Result<()> {
.route("/regtest/send/:address/:amount", get(send_coins));
} else {
tokio::spawn(async {
loop {
if let Err(e) = periodic_metrics().await {
error!("Error in periodic metrics: {e}");
}
if let Err(e) = init_metrics().await {
error!("Error in periodic metrics: {e}");
}
});
}
Expand Down
6 changes: 4 additions & 2 deletions src/carbonado.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ mod server {

let (body, _encode_info) = carbonado::file::encode(&sk, Some(&pk), input, level, meta)?;
let filepath = handle_file(&pk_hex, name, body.len()).await?;
fs::write(filepath, body).await?;
fs::write(&filepath, body).await?;
metrics::update(&filepath).await?;
Ok(())
}

Expand All @@ -79,7 +80,8 @@ mod server {

let (body, _encode_info) = carbonado::file::encode(&sk, Some(&pk), input, level, meta)?;
let filepath = handle_file(&pk_hex, name, body.len()).await?;
fs::write(filepath.clone(), body.clone()).await?;
fs::write(&filepath, body.clone()).await?;
metrics::update(&filepath).await?;
Ok((filepath, body))
}

Expand Down
2 changes: 2 additions & 0 deletions src/carbonado/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,6 @@ pub enum CarbonadoError {
WrongNostrPublicKey,
/// Debug: {0}
Debug(String),
/// Error: {0}
AnyhowError(#[from] anyhow::Error),
}
Loading

0 comments on commit a42700d

Please sign in to comment.