use anyhow::{Context, Result};
use bsv_wallet_toolbox::{
services::{ArcadeConfig, ARCADE_V2_MAINNET},
ArcConfig, Chain, ServicesOptions,
};
use std::io::Write;
use std::path::PathBuf;
#[derive(Debug, Clone)]
pub struct ArcadeRuntime {
pub url: String,
pub callback_token: String,
pub public_callback_url: Option<String>,
}
pub fn arcade_mode_enabled() -> bool {
if let Ok(mode) = std::env::var("ARC_MODE") {
if mode.eq_ignore_ascii_case("arcade") {
return true;
}
}
if let Ok(v) = std::env::var("ARCADE") {
let v = v.trim();
return v == "1" || v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("yes");
}
false
}
pub fn arcade_runtime(db_path: &str) -> Result<Option<ArcadeRuntime>> {
if !arcade_mode_enabled() {
return Ok(None);
}
let url = std::env::var("ARC_URL").unwrap_or_else(|_| ARCADE_V2_MAINNET.to_string());
let callback_token = resolve_callback_token(db_path)?;
let public_callback_url = std::env::var("PUBLIC_CALLBACK_URL")
.ok()
.filter(|s| !s.is_empty());
Ok(Some(ArcadeRuntime {
url,
callback_token,
public_callback_url,
}))
}
pub fn resolve_callback_token(db_path: &str) -> Result<String> {
if let Ok(tok) = std::env::var("CALLBACK_TOKEN") {
let tok = tok.trim().to_string();
if !tok.is_empty() {
return Ok(tok);
}
}
let token_path = callback_token_path(db_path);
if token_path.exists() {
let tok = std::fs::read_to_string(&token_path)
.with_context(|| format!("reading {}", token_path.display()))?
.trim()
.to_string();
if !tok.is_empty() {
return Ok(tok);
}
}
let tok: String = bsv_sdk::primitives::PrivateKey::random()
.to_hex()
.chars()
.take(32)
.collect();
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
let mut f = opts
.open(&token_path)
.with_context(|| format!("creating {}", token_path.display()))?;
f.write_all(tok.as_bytes())?;
tracing::info!(path = %token_path.display(), "generated per-wallet callback token");
Ok(tok)
}
pub fn callback_token_path(db_path: &str) -> PathBuf {
PathBuf::from(format!("{}.callback-token", db_path))
}
pub fn services_options_from_env(chain: Chain, db_path: &str) -> Result<ServicesOptions> {
let mut opts = match chain {
Chain::Main => ServicesOptions::mainnet(),
Chain::Test => ServicesOptions::testnet(),
};
if let Ok(url) = std::env::var("CHAINTRACKS_URL") {
if !url.is_empty() {
opts = opts.with_chaintracks_url(url);
}
}
let mut arc_config: Option<ArcConfig> = None;
if let Ok(key) = std::env::var("TAAL_API_KEY") {
if !key.is_empty() {
arc_config = Some(ArcConfig::with_api_key(key));
}
}
if let Ok(key) = std::env::var("MAIN_TAAL_API_KEY") {
if !key.is_empty() {
let mut headers = std::collections::HashMap::new();
headers.insert("Authorization".to_string(), key);
let mut cfg = arc_config.unwrap_or_default();
cfg.headers = Some(headers);
arc_config = Some(cfg);
}
}
if let Some(runtime) = arcade_runtime(db_path)? {
let arcade_config = ArcadeConfig {
callback_token: Some(runtime.callback_token.clone()),
callback_url: runtime.public_callback_url.clone(),
..Default::default()
};
opts.arc_config = arc_config;
opts = opts.with_arcade(runtime.url, Some(arcade_config));
} else {
let arc_url = std::env::var("ARC_URL")
.ok()
.filter(|s| !s.is_empty())
.unwrap_or_else(|| opts.arc_url.clone());
opts = opts.with_arc(arc_url, arc_config);
}
Ok(opts)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn callback_token_path_is_next_to_db() {
let p = callback_token_path("/tmp/wallet.db");
assert_eq!(p, PathBuf::from("/tmp/wallet.db.callback-token"));
}
#[test]
fn generated_token_is_32_hex_and_persisted() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("w.db");
let db = db.to_str().unwrap();
std::env::remove_var("CALLBACK_TOKEN");
let tok = resolve_callback_token(db).unwrap();
assert_eq!(tok.len(), 32);
assert!(tok.chars().all(|c| c.is_ascii_hexdigit()));
let tok2 = resolve_callback_token(db).unwrap();
assert_eq!(tok, tok2);
assert!(callback_token_path(db).exists());
}
}