wip
This commit is contained in:
parent
f06ca98460
commit
be52a49c02
@ -35,7 +35,7 @@ sha2 = "0.10.8"
|
|||||||
sqlx = { version = "0.8.1", features = ["mysql", "runtime-tokio", "chrono", "uuid"] }
|
sqlx = { version = "0.8.1", features = ["mysql", "runtime-tokio", "chrono", "uuid"] }
|
||||||
config = { version = "0.15.7", features = ["yaml"] }
|
config = { version = "0.15.7", features = ["yaml"] }
|
||||||
chrono = { version = "0.4.38", features = ["serde"] }
|
chrono = { version = "0.4.38", features = ["serde"] }
|
||||||
reqwest = { version = "0.12.8", features = ["stream"] }
|
reqwest = { version = "0.12.8", features = ["stream", "http2"] }
|
||||||
clap = { version = "4.5.18", features = ["derive"] }
|
clap = { version = "4.5.18", features = ["derive"] }
|
||||||
mime2ext = "0.1.53"
|
mime2ext = "0.1.53"
|
||||||
infer = "0.19.0"
|
infer = "0.19.0"
|
||||||
@ -48,4 +48,4 @@ ffmpeg-rs-raw = { git = "https://git.v0l.io/Kieran/ffmpeg-rs-raw.git", rev = "a6
|
|||||||
candle-core = { git = "https://git.v0l.io/huggingface/candle.git", tag = "0.8.1", optional = true }
|
candle-core = { git = "https://git.v0l.io/huggingface/candle.git", tag = "0.8.1", optional = true }
|
||||||
candle-nn = { git = "https://git.v0l.io/huggingface/candle.git", tag = "0.8.1", optional = true }
|
candle-nn = { git = "https://git.v0l.io/huggingface/candle.git", tag = "0.8.1", optional = true }
|
||||||
candle-transformers = { git = "https://git.v0l.io/huggingface/candle.git", tag = "0.8.1", optional = true }
|
candle-transformers = { git = "https://git.v0l.io/huggingface/candle.git", tag = "0.8.1", optional = true }
|
||||||
fedimint-tonic-lnd = { version = "0.2.0", optional = true, features = ["invoicesrpc"] }
|
fedimint-tonic-lnd = { version = "0.2.0", optional = true, default-features = false, features = ["invoicesrpc", "lightningrpc"] }
|
@ -35,9 +35,9 @@ payments:
|
|||||||
fiat: "USD"
|
fiat: "USD"
|
||||||
# LND node config
|
# LND node config
|
||||||
lnd:
|
lnd:
|
||||||
endpoint: "https://mylnd:10002"
|
endpoint: "https://127.0.0.1:10001"
|
||||||
tls: "tls.crt"
|
tls: "/home/kieran/.polar/networks/3/volumes/lnd/alice/tls.cert"
|
||||||
macaroon: "admin.macaroon"
|
macaroon: "/home/kieran/.polar/networks/3/volumes/lnd/alice/data/chain/bitcoin/regtest/admin.macaroon"
|
||||||
# Cost per unit (BTC/USD/EUR/AUD/CAD/JPY/GBP)
|
# Cost per unit (BTC/USD/EUR/AUD/CAD/JPY/GBP)
|
||||||
cost:
|
cost:
|
||||||
currency: "BTC"
|
currency: "BTC"
|
||||||
|
@ -9,13 +9,13 @@ create table payments
|
|||||||
user_id integer unsigned not null,
|
user_id integer unsigned not null,
|
||||||
created timestamp default current_timestamp,
|
created timestamp default current_timestamp,
|
||||||
amount integer unsigned not null,
|
amount integer unsigned not null,
|
||||||
is_paid bit(1) not null,
|
is_paid bit(1) not null default 0,
|
||||||
days_value integer unsigned not null,
|
days_value integer unsigned not null,
|
||||||
size_value integer unsigned not null,
|
size_value integer unsigned not null,
|
||||||
index integer unsigned not null,
|
settle_index integer unsigned,
|
||||||
rate double not null,
|
rate float,
|
||||||
|
|
||||||
constraint fk_payments_user
|
constraint fk_payments_user_id
|
||||||
foreign key (user_id) references users (id)
|
foreign key (user_id) references users (id)
|
||||||
on delete cascade
|
on delete cascade
|
||||||
on update restrict
|
on update restrict
|
||||||
|
@ -1,24 +1,47 @@
|
|||||||
use crate::db::Database;
|
use crate::db::Database;
|
||||||
use crate::filesystem::FileStore;
|
use crate::filesystem::FileStore;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use log::info;
|
use log::{info, warn};
|
||||||
use tokio::task::JoinHandle;
|
use tokio::task::JoinHandle;
|
||||||
|
|
||||||
#[cfg(feature = "media-compression")]
|
#[cfg(feature = "media-compression")]
|
||||||
mod media_metadata;
|
mod media_metadata;
|
||||||
|
|
||||||
pub fn start_background_tasks(db: Database, file_store: FileStore) -> Vec<JoinHandle<Result<()>>> {
|
#[cfg(feature = "payments")]
|
||||||
|
mod payments;
|
||||||
|
|
||||||
|
pub fn start_background_tasks(
|
||||||
|
db: Database,
|
||||||
|
file_store: FileStore,
|
||||||
|
#[cfg(feature = "payments")] client: Option<fedimint_tonic_lnd::Client>,
|
||||||
|
) -> Vec<JoinHandle<Result<()>>> {
|
||||||
let mut ret = vec![];
|
let mut ret = vec![];
|
||||||
|
|
||||||
#[cfg(feature = "media-compression")]
|
#[cfg(feature = "media-compression")]
|
||||||
{
|
{
|
||||||
|
let db = db.clone();
|
||||||
ret.push(tokio::spawn(async move {
|
ret.push(tokio::spawn(async move {
|
||||||
info!("Starting MediaMetadata background task");
|
info!("Starting MediaMetadata background task");
|
||||||
let mut m = media_metadata::MediaMetadata::new(db.clone(), file_store.clone());
|
let mut m = media_metadata::MediaMetadata::new(db, file_store.clone());
|
||||||
m.process().await?;
|
m.process().await?;
|
||||||
info!("MediaMetadata background task completed");
|
info!("MediaMetadata background task completed");
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
#[cfg(feature = "payments")]
|
||||||
|
{
|
||||||
|
if let Some(client) = client {
|
||||||
|
let db = db.clone();
|
||||||
|
ret.push(tokio::spawn(async move {
|
||||||
|
info!("Starting PaymentsHandler background task");
|
||||||
|
let mut m = payments::PaymentsHandler::new(client, db);
|
||||||
|
m.process().await?;
|
||||||
|
info!("PaymentsHandler background task completed");
|
||||||
|
Ok(())
|
||||||
|
}));
|
||||||
|
} else {
|
||||||
|
warn!("Not starting PaymentsHandler, configuration missing")
|
||||||
|
}
|
||||||
|
}
|
||||||
ret
|
ret
|
||||||
}
|
}
|
||||||
|
18
src/background/payments.rs
Normal file
18
src/background/payments.rs
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
use crate::db::Database;
|
||||||
|
use anyhow::Result;
|
||||||
|
use fedimint_tonic_lnd::Client;
|
||||||
|
|
||||||
|
pub struct PaymentsHandler {
|
||||||
|
client: Client,
|
||||||
|
database: Database,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PaymentsHandler {
|
||||||
|
pub fn new(client: Client, database: Database) -> Self {
|
||||||
|
PaymentsHandler { client, database }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn process(&mut self) -> Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
@ -3,6 +3,8 @@ use std::net::{IpAddr, SocketAddr};
|
|||||||
use anyhow::Error;
|
use anyhow::Error;
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use config::Config;
|
use config::Config;
|
||||||
|
#[cfg(feature = "payments")]
|
||||||
|
use fedimint_tonic_lnd::lnrpc::GetInfoRequest;
|
||||||
use log::{error, info};
|
use log::{error, info};
|
||||||
use rocket::config::Ident;
|
use rocket::config::Ident;
|
||||||
use rocket::data::{ByteUnit, Limits};
|
use rocket::data::{ByteUnit, Limits};
|
||||||
@ -102,11 +104,35 @@ async fn main() -> Result<(), Error> {
|
|||||||
rocket = rocket.mount("/", routes![routes::get_blob_thumb]);
|
rocket = rocket.mount("/", routes![routes::get_blob_thumb]);
|
||||||
}
|
}
|
||||||
#[cfg(feature = "payments")]
|
#[cfg(feature = "payments")]
|
||||||
{
|
let lnd = {
|
||||||
rocket = rocket.mount("/", routes::payment::routes());
|
if let Some(lnd) = settings.payments.as_ref().map(|p| &p.lnd) {
|
||||||
}
|
let lnd = fedimint_tonic_lnd::connect(
|
||||||
|
lnd.endpoint.clone(),
|
||||||
|
lnd.tls.clone(),
|
||||||
|
lnd.macaroon.clone(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
let jh = start_background_tasks(db, fs);
|
let info = {
|
||||||
|
let mut lnd = lnd.clone();
|
||||||
|
lnd.lightning().get_info(GetInfoRequest::default()).await?
|
||||||
|
};
|
||||||
|
|
||||||
|
info!(
|
||||||
|
"LND connected: {} v{}",
|
||||||
|
info.get_ref().alias,
|
||||||
|
info.get_ref().version
|
||||||
|
);
|
||||||
|
rocket = rocket
|
||||||
|
.manage(lnd.clone())
|
||||||
|
.mount("/", routes::payment::routes());
|
||||||
|
Some(lnd)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let jh = start_background_tasks(db, fs, lnd);
|
||||||
|
|
||||||
if let Err(e) = rocket.launch().await {
|
if let Err(e) = rocket.launch().await {
|
||||||
error!("Rocker error {}", e);
|
error!("Rocker error {}", e);
|
||||||
|
30
src/db.rs
30
src/db.rs
@ -94,6 +94,20 @@ pub struct UserStats {
|
|||||||
pub total_size: u64,
|
pub total_size: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "payments")]
|
||||||
|
#[derive(Clone, FromRow, Serialize)]
|
||||||
|
pub struct Payment {
|
||||||
|
pub payment_hash: Vec<u8>,
|
||||||
|
pub user_id: u64,
|
||||||
|
pub created: DateTime<Utc>,
|
||||||
|
pub amount: u64,
|
||||||
|
pub is_paid: bool,
|
||||||
|
pub days_value: u64,
|
||||||
|
pub size_value: u64,
|
||||||
|
pub settle_index: u64,
|
||||||
|
pub rate: f32,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Database {
|
pub struct Database {
|
||||||
pub(crate) pool: sqlx::pool::Pool<sqlx::mysql::MySql>,
|
pub(crate) pool: sqlx::pool::Pool<sqlx::mysql::MySql>,
|
||||||
@ -274,3 +288,19 @@ impl Database {
|
|||||||
Ok((results, count))
|
Ok((results, count))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "payments")]
|
||||||
|
impl Database {
|
||||||
|
pub async fn insert_payment(&self, payment: &Payment) -> Result<(), Error> {
|
||||||
|
sqlx::query("insert into payments(payment_hash,user_id,amount,days_value,size_value,rate) values(?,?,?,?,?,?)")
|
||||||
|
.bind(&payment.payment_hash)
|
||||||
|
.bind(&payment.user_id)
|
||||||
|
.bind(&payment.amount)
|
||||||
|
.bind(&payment.days_value)
|
||||||
|
.bind(&payment.size_value)
|
||||||
|
.bind(&payment.rate)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -5,13 +5,14 @@ pub mod background;
|
|||||||
pub mod cors;
|
pub mod cors;
|
||||||
pub mod db;
|
pub mod db;
|
||||||
pub mod filesystem;
|
pub mod filesystem;
|
||||||
|
#[cfg(feature = "payments")]
|
||||||
|
pub mod payments;
|
||||||
#[cfg(feature = "media-compression")]
|
#[cfg(feature = "media-compression")]
|
||||||
pub mod processing;
|
pub mod processing;
|
||||||
pub mod routes;
|
pub mod routes;
|
||||||
pub mod settings;
|
pub mod settings;
|
||||||
pub mod void_file;
|
pub mod void_file;
|
||||||
|
|
||||||
|
|
||||||
pub fn can_compress(mime_type: &str) -> bool {
|
pub fn can_compress(mime_type: &str) -> bool {
|
||||||
mime_type.starts_with("image/")
|
mime_type.starts_with("image/")
|
||||||
}
|
}
|
||||||
|
53
src/payments.rs
Normal file
53
src/payments.rs
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::fmt::{Display, Formatter};
|
||||||
|
|
||||||
|
#[cfg(feature = "payments")]
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct PaymentAmount {
|
||||||
|
pub currency: Currency,
|
||||||
|
pub amount: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "payments")]
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub enum Currency {
|
||||||
|
BTC,
|
||||||
|
USD,
|
||||||
|
EUR,
|
||||||
|
GBP,
|
||||||
|
JPY,
|
||||||
|
CAD,
|
||||||
|
AUD,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "payments")]
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub enum PaymentUnit {
|
||||||
|
GBSpace,
|
||||||
|
GBEgress,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PaymentUnit {
|
||||||
|
/// Get the total size from a number of units
|
||||||
|
pub fn to_size(&self, units: f32) -> u64 {
|
||||||
|
(1000f32 * 1000f32 * 1000f32 * units) as u64
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for PaymentUnit {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
PaymentUnit::GBSpace => write!(f, "GB Space"),
|
||||||
|
PaymentUnit::GBEgress => write!(f, "GB Egress"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "payments")]
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum PaymentInterval {
|
||||||
|
Day(u16),
|
||||||
|
Month(u16),
|
||||||
|
Year(u16),
|
||||||
|
}
|
@ -1,12 +1,18 @@
|
|||||||
use crate::auth::nip98::Nip98Auth;
|
use crate::auth::nip98::Nip98Auth;
|
||||||
use crate::db::Database;
|
use crate::db::{Database, Payment};
|
||||||
use crate::settings::{PaymentAmount, PaymentInterval, PaymentUnit, Settings};
|
use crate::payments::{Currency, PaymentAmount, PaymentInterval, PaymentUnit};
|
||||||
|
use crate::settings::Settings;
|
||||||
|
use chrono::{Months, Utc};
|
||||||
|
use fedimint_tonic_lnd::lnrpc::Invoice;
|
||||||
|
use fedimint_tonic_lnd::Client;
|
||||||
|
use log::{error, info};
|
||||||
use rocket::serde::json::Json;
|
use rocket::serde::json::Json;
|
||||||
use rocket::{routes, Route, State};
|
use rocket::{routes, Route, State};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::ops::{Add, Deref};
|
||||||
|
|
||||||
pub fn routes() -> Vec<Route> {
|
pub fn routes() -> Vec<Route> {
|
||||||
routes![get_payment]
|
routes![get_payment, req_payment]
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Serialize)]
|
#[derive(Deserialize, Serialize)]
|
||||||
@ -31,7 +37,9 @@ struct PaymentRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Serialize)]
|
#[derive(Deserialize, Serialize)]
|
||||||
struct PaymentResponse {}
|
struct PaymentResponse {
|
||||||
|
pub pr: String,
|
||||||
|
}
|
||||||
|
|
||||||
#[rocket::get("/payment")]
|
#[rocket::get("/payment")]
|
||||||
async fn get_payment(settings: &State<Settings>) -> Option<Json<PaymentInfo>> {
|
async fn get_payment(settings: &State<Settings>) -> Option<Json<PaymentInfo>> {
|
||||||
@ -49,7 +57,75 @@ async fn req_payment(
|
|||||||
auth: Nip98Auth,
|
auth: Nip98Auth,
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
settings: &State<Settings>,
|
settings: &State<Settings>,
|
||||||
|
lnd: &State<Client>,
|
||||||
req: Json<PaymentRequest>,
|
req: Json<PaymentRequest>,
|
||||||
) -> Json<PaymentResponse> {
|
) -> Result<Json<PaymentResponse>, String> {
|
||||||
Json::from(PaymentResponse {})
|
let cfg = if let Some(p) = &settings.payments {
|
||||||
|
p
|
||||||
|
} else {
|
||||||
|
return Err("Payment not enabled, missing configuration option(s)".to_string());
|
||||||
|
};
|
||||||
|
|
||||||
|
let btc_amount = match cfg.cost.currency {
|
||||||
|
Currency::BTC => cfg.cost.amount,
|
||||||
|
_ => return Err("Currency not supported".to_string()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let amount = btc_amount * req.units * req.quantity as f32;
|
||||||
|
|
||||||
|
let pubkey_vec = auth.event.pubkey.to_bytes().to_vec();
|
||||||
|
let uid = db
|
||||||
|
.upsert_user(&pubkey_vec)
|
||||||
|
.await
|
||||||
|
.map_err(|_| "Failed to get user account".to_string())?;
|
||||||
|
|
||||||
|
let mut lnd = lnd.deref().clone();
|
||||||
|
let c = lnd.lightning();
|
||||||
|
let msat = (amount * 1e11f32) as u64;
|
||||||
|
let memo = format!(
|
||||||
|
"{}x {} {} for {}",
|
||||||
|
req.quantity, req.units, cfg.unit, auth.event.pubkey
|
||||||
|
);
|
||||||
|
info!("Requesting {} msats: {}", msat, memo);
|
||||||
|
let invoice = c
|
||||||
|
.add_invoice(Invoice {
|
||||||
|
value_msat: msat as i64,
|
||||||
|
memo,
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.message().to_string())?;
|
||||||
|
|
||||||
|
let days_value = match cfg.interval {
|
||||||
|
PaymentInterval::Day(d) => d as u64,
|
||||||
|
PaymentInterval::Month(m) => {
|
||||||
|
let now = Utc::now();
|
||||||
|
(now.add(Months::new(m as u32)) - now).num_days() as u64
|
||||||
|
}
|
||||||
|
PaymentInterval::Year(y) => {
|
||||||
|
let now = Utc::now();
|
||||||
|
(now.add(Months::new(12 * y as u32)) - now).num_days() as u64
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let record = Payment {
|
||||||
|
payment_hash: invoice.get_ref().payment_addr.clone(),
|
||||||
|
user_id: uid,
|
||||||
|
created: Default::default(),
|
||||||
|
amount: msat,
|
||||||
|
is_paid: false,
|
||||||
|
days_value,
|
||||||
|
size_value: cfg.unit.to_size(req.units),
|
||||||
|
settle_index: 0,
|
||||||
|
rate: 0.0,
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Err(e) = db.insert_payment(&record).await {
|
||||||
|
error!("Failed to insert payment: {}", e);
|
||||||
|
return Err("Failed to insert payment".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Json(PaymentResponse {
|
||||||
|
pr: invoice.get_ref().payment_request.clone(),
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
|
#[cfg(feature = "payments")]
|
||||||
|
use crate::payments::{Currency, PaymentAmount, PaymentInterval, PaymentUnit};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
@ -63,41 +65,6 @@ pub struct PaymentConfig {
|
|||||||
pub fiat: Option<Currency>,
|
pub fiat: Option<Currency>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "payments")]
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct PaymentAmount {
|
|
||||||
pub currency: Currency,
|
|
||||||
pub amount: f32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "payments")]
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub enum Currency {
|
|
||||||
BTC,
|
|
||||||
USD,
|
|
||||||
EUR,
|
|
||||||
GBP,
|
|
||||||
JPY,
|
|
||||||
CAD,
|
|
||||||
AUD,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "payments")]
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub enum PaymentUnit {
|
|
||||||
GBSpace,
|
|
||||||
GBEgress,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "payments")]
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
#[serde(rename_all = "lowercase")]
|
|
||||||
pub enum PaymentInterval {
|
|
||||||
Day(u16),
|
|
||||||
Month(u16),
|
|
||||||
Year(u16),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "payments")]
|
#[cfg(feature = "payments")]
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct LndConfig {
|
pub struct LndConfig {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user