Skip to content

Commit

Permalink
Add NIP 100 support
Browse files Browse the repository at this point in the history
  • Loading branch information
ssantos21 committed Dec 11, 2024
1 parent 07ff7b7 commit fd17ca7
Show file tree
Hide file tree
Showing 16 changed files with 970 additions and 127 deletions.
916 changes: 806 additions & 110 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion clients/apps/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ edition = "2021"
anyhow = "1.0"
bech32 = { version = "0.9.1", default-features = false }
bitcoin = { version = "0.30.1", features = ["serde", "base64", "rand-std", "std", "bitcoinconsensus"], default-features = false }
bip39 = "1.2.0"
bip39 = "2.0"
clap = { version = "4.2.5", features = ["derive"]}
chrono = "0.4.31"
config = "0.13.1"
Expand Down
2 changes: 1 addition & 1 deletion clients/apps/rust/rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[toolchain]
channel = "1.80.1"
channel = "1.83.0"
2 changes: 1 addition & 1 deletion clients/libs/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ edition = "2021"
anyhow = "1.0"
bech32 = { version = "0.9.1", default-features = false }
bitcoin = { version = "0.30.1", features = ["serde", "base64", "rand-std", "std", "bitcoinconsensus"], default-features = false }
bip39 = "1.2.0"
bip39 = "2.0"
clap = { version = "4.2.5", features = ["derive"]}
chrono = "0.4.31"
config = "0.13.1"
Expand Down
2 changes: 1 addition & 1 deletion clients/libs/rust/rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[toolchain]
channel = "1.80.1"
channel = "1.83.0"
2 changes: 1 addition & 1 deletion clients/tests/rust/rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[toolchain]
channel = "1.80.1"
channel = "1.83.0"
2 changes: 1 addition & 1 deletion lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ required-features = ["bindings"]

[dependencies]
bitcoin = { version = "0.30.1", features = ["serde", "base64", "rand-std", "std"], default-features = false }
bip39 = "1.2.0"
bip39 = "2.0"
bech32 = { version = "0.9.1", default-features = false }
ecies = {version = "0.2.7", default-features = false, features = ["pure"]}
hex = "0.4.3"
Expand Down
2 changes: 1 addition & 1 deletion lib/rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[toolchain]
channel = "1.80.1"
channel = "1.83.0"
1 change: 1 addition & 0 deletions server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,4 @@ chrono = "0.4.31"
sha2 = "0.10.8"
log = "0.4.22"
env_logger = "0.11.5"
nostr-sdk = "0.37.0"
13 changes: 13 additions & 0 deletions server/Settings.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@ db_host = "localhost"
db_port = 5432
db_name = "mercury"

[nostr_info]
relay_server = "wss://relay.damus.io/"
relay_interval = 15
nostr_privkey = "nsec17e0nvplcze4k7q9nazrw0k3aracwhg6vmuareewjp83ta89njw5spjcgzs"
server_url = "http://mercury_server.xyz"
location = "UK"
active = true
onchain_payments = false
ln_payments = true
fee = 0.0001
unit = "BTC"

[[enclaves]]
url = "http://0.0.0.0:18080"
allow_deposit = true
Expand All @@ -29,3 +41,4 @@ url = "http://0.0.0.0:18080"
allow_deposit = true

# env var: ENCLAVES='[{"url": "http://0.0.0.0:18080", "allow_deposit": true}, {"url": "http://0.0.0.0:18080", "allow_deposit": false}]'
# env var: NOSTR_INFO='{"relay_server": "wss://relay.damus.io/", "relay_interval": 10, "nostr_privkey": "nsec17e0nvplcze4k7q9nazrw0k3aracwhg6vmuareewjp83ta89njw5spjcgzs"}'
2 changes: 1 addition & 1 deletion server/rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[toolchain]
channel = "1.80.1"
channel = "1.83.0"
92 changes: 88 additions & 4 deletions server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ mod database;

#[macro_use] extern crate rocket;

use std::time::{Duration, SystemTime, UNIX_EPOCH};

use endpoints::utils;
use rocket::{serde::json::{Value, json}, Request, Response};
use rocket::fairing::{Fairing, Info, Kind};
use rocket::{serde::json::{json, Value}, tokio::{self, time::interval}, Request, Response};
use rocket::fairing::{Fairing, Info};
use rocket::http::Header;
use server::StateChainEntity;

Expand All @@ -34,12 +36,70 @@ fn not_found(req: &Request) -> Value {
json!(message)
}

async fn broadcast_nip_100(nostr_info: &server_config::NostrInfo, published_at: u64, timelock: u32) -> Result<(), Box<dyn std::error::Error>> {

let relay_server = &nostr_info.relay_server;
let nostr_privkey = &nostr_info.nostr_privkey;
let server_url = &nostr_info.server_url;
let location = &nostr_info.location;
let status = &nostr_info.active;
let onchain_payments = &nostr_info.onchain_payments.to_string();
let ln_payments = &nostr_info.ln_payments.to_string();
let fee = &nostr_info.fee.to_string();
let unit = &nostr_info.unit;

let sec_key = nostr_sdk::Keys::parse(nostr_privkey)?;

let content = "Mercury server descritpion";
let mut tags = vec![
nostr_sdk::Tag::custom(nostr_sdk::TagKind::Custom("url".into()), [server_url]),
nostr_sdk::Tag::custom(nostr_sdk::TagKind::Custom("published_at".into()), [published_at.to_string()]),
nostr_sdk::Tag::custom(nostr_sdk::TagKind::Custom("timelock".into()), [timelock.to_string()]),
];

if location.is_some() {
tags.push(nostr_sdk::Tag::custom(nostr_sdk::TagKind::Custom("location".into()), [location.as_ref().unwrap()]));
}

tags.push(nostr_sdk::Tag::custom(nostr_sdk::TagKind::Custom("fee".into()), [fee, unit, ln_payments, onchain_payments]));

if status.is_some() {
let status_desc = if status.unwrap() { "active" } else { "offline" };
tags.push(nostr_sdk::Tag::custom(nostr_sdk::TagKind::Custom("status".into()), [status_desc]));
}

let client = nostr_sdk::Client::new(sec_key.clone());

client.add_relay(relay_server).await?;

client.connect().await;

let created_at = nostr_sdk::Timestamp::now();

let event = nostr_sdk::EventBuilder::new(
nostr_sdk::Kind::Custom(39101),
content.to_string(),
)
.tags(tags)
.custom_created_at(created_at)
.sign_with_keys(&sec_key)?;

/* println!("Event as JSON:");
println!("{}", serde_json::to_string_pretty(&event)?); */


client.send_event(event).await?;

Ok(())

}

#[rocket::main]
async fn main() {

env_logger::init();

server_config::ServerConfig::load();
let config = server_config::ServerConfig::load();

let statechain_entity = StateChainEntity::new().await;

Expand All @@ -48,6 +108,30 @@ async fn main() {
.await
.unwrap();

if config.nostr_info.is_some() {
let nostr_info = config.nostr_info.unwrap();

let interval_seconds = nostr_info.relay_interval as u64;

tokio::spawn(async move {
let mut ticker = interval(Duration::from_secs(interval_seconds));

let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH).unwrap();
let published_at = since_the_epoch.as_secs();

let timelock = config.lockheight_init;

loop {
ticker.tick().await;
broadcast_nip_100(&nostr_info, published_at, timelock).await.unwrap();
}
});
} else {
println!("No Nostr info found in config file");
}


let _ = rocket::build()
.mount("/", routes![
endpoints::deposit::post_deposit,
Expand Down Expand Up @@ -95,7 +179,7 @@ impl Fairing for Cors {
fn info(&self) -> Info {
Info {
name: "Cross-Origin-Resource-Sharing Fairing",
kind: Kind::Response,
kind: rocket::fairing::Kind::Response,
}
}

Expand Down
53 changes: 51 additions & 2 deletions server/src/server_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,30 @@ pub struct Enclave {
pub allow_deposit: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct NostrInfo {
/// Nostr Relay server
pub relay_server: String,
/// Relay interval
pub relay_interval: u32,
/// Nostr private key
pub nostr_privkey: String,
/// Sever url
pub server_url: String,
/// Optional server location
pub location: Option<String>,
/// Optional server status
pub active: Option<bool>,
/// Accepts onchain payments
pub onchain_payments: bool,
/// Accepts LN payments
pub ln_payments: bool,
/// Fee charged by the server
pub fee: f64,
/// Fee currency unit
pub unit: String,
}

/// Config struct storing all StataChain Entity config
#[derive(Debug, Serialize, Deserialize)]
pub struct ServerConfig {
Expand All @@ -32,6 +56,9 @@ pub struct ServerConfig {
pub db_port: u16,
/// Database name
pub db_name: String,
/// Nostr info
pub nostr_info: Option<NostrInfo>,

}

impl Default for ServerConfig {
Expand All @@ -56,11 +83,12 @@ impl Default for ServerConfig {
db_host: String::from("db_server"),
db_port: 5432,
db_name: String::from("mercury"),
nostr_info: None,
}
}
}

impl From<ConfigRs> for ServerConfig {
/* impl From<ConfigRs> for ServerConfig {
fn from(config: ConfigRs) -> Self {
ServerConfig {
network: config.get::<String>("network").unwrap_or_else(|_| String::new()),
Expand All @@ -75,7 +103,7 @@ impl From<ConfigRs> for ServerConfig {
db_name: config.get::<String>("db_name").unwrap_or_else(|_| String::new()),
}
}
}
} */

impl ServerConfig {
pub fn load() -> Self {
Expand Down Expand Up @@ -111,6 +139,26 @@ impl ServerConfig {
settings.get::<Vec<Enclave>>(key).unwrap()
};

let get_env_or_config_nostr_info = |key: &str, env_var: &str| -> Option<NostrInfo> {

let env_nostr_info = env::var(env_var);


if env_nostr_info.is_ok() {

let res = serde_json::from_str::<NostrInfo>(&env_nostr_info.unwrap()).unwrap();
return Some(res)
}

let res = settings.get::<NostrInfo>(key);

if res.is_ok() {
return Some(res.unwrap())
} else {
return None
}
};

ServerConfig {
network: get_env_or_config("network", "BITCOIN_NETWORK"),
lockheight_init: get_env_or_config("lockheight_init", "LOCKHEIGHT_INIT").parse::<u32>().unwrap(),
Expand All @@ -122,6 +170,7 @@ impl ServerConfig {
db_host: get_env_or_config("db_host", "DB_HOST"),
db_port: get_env_or_config("db_port", "DB_PORT").parse::<u16>().unwrap(),
db_name: get_env_or_config("db_name", "DB_NAME"),
nostr_info: get_env_or_config_nostr_info("nostr_info", "NOSTR_INFO"),
}
}

Expand Down
2 changes: 1 addition & 1 deletion token-server/rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[toolchain]
channel = "1.80.1"
channel = "1.83.0"
2 changes: 1 addition & 1 deletion wasm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ js-sys = "0.3.64"
wasm-bindgen-futures = "0.4.37"
serde = { version = "1.0", features = ["derive"] }
serde-wasm-bindgen = "0.4"
bip39 = "1.2.0"
bip39 = "2.0"
rand = "0.8"
mercurylib = { path = "../lib" }

Expand Down
2 changes: 1 addition & 1 deletion wasm/rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[toolchain]
channel = "1.80.1"
channel = "1.83.0"

0 comments on commit fd17ca7

Please sign in to comment.