Skip to content

Commit

Permalink
Implement internal and external APIs.
Browse files Browse the repository at this point in the history
Signed-off-by: Charlie Wilkin <[email protected]>
  • Loading branch information
busyboredom committed Nov 19, 2023
1 parent ff9dea7 commit 6ff9148
Show file tree
Hide file tree
Showing 136 changed files with 1,666 additions and 973 deletions.
745 changes: 425 additions & 320 deletions Cargo.lock

Large diffs are not rendered by default.

13 changes: 12 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,19 @@ resolver = "2"

members = [
"server",
"library"
"library",
"testing-utils"
]

[workspace.lints.rust]
unsafe_code = "forbid"
missing_docs = "warn"
unreachable_pub = "warn"

[workspace.lints.clippy]
pedantic = "warn"
cargo = "warn"
module_name_repetitions = "allow"

[profile.release]
lto = true
8 changes: 5 additions & 3 deletions library/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ readme = "README.md"
keywords = ["crypto", "gateway", "monero", "payment", "xmr"]
categories = ["cryptography::cryptocurrencies"]

[lints]
workspace = true

[lib]
name = "acceptxmr"
path = "src/lib.rs"
Expand All @@ -33,7 +36,7 @@ rand_chacha = "0.3"
serde = { version = "1.0", default-features = false, features = ["derive", "alloc"], optional = true }
serde_json = "1"
sled = { version = "0.34", optional = true }
sqlite = { version = "0.31", optional = true }
sqlite = { version = "0.32", optional = true }
strum = { version = "0.25", features = ["derive"] }
thiserror = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
Expand All @@ -54,11 +57,10 @@ actix-web-actors = "4"
bytestring = "1"
env_logger = "0.10"
handlebars = { version = "4", features = ["dir_source"] }
httpmock = "0.6"
qrcode = "0.12"
serde = "1"
tempfile = "3"
test-case = "3"
testing-utils = { path = "../testing-utils" }
# This is a workaround to enable features in tests.
acceptxmr = { path = ".", features = ["sled", "in-memory", "sqlite"] }

Expand Down
9 changes: 5 additions & 4 deletions library/examples/custom_storage/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#![warn(clippy::pedantic)]
//! Use a custom storage layer.
use std::collections::{
btree_map::{self, Entry},
Expand Down Expand Up @@ -53,9 +53,9 @@ async fn main() {
);
}

// This example uses a BTreeMap for simplicity, but you can implement this trait
// on virtually any storage layer you choose. Postgres or MySQL, CSV files,
// whatever works best for your application.
/// This example storage layer uses a `BTreeMap` for simplicity, but you can
/// implement this trait on virtually any storage layer you choose. `Postgres`
/// or `MySQL`, CSV files, whatever works best for your application.
pub struct MyCustomStorage {
invoices: BTreeMap<InvoiceId, Invoice>,
output_keys: BTreeMap<OutputPubKey, OutputId>,
Expand Down Expand Up @@ -121,6 +121,7 @@ impl InvoiceStorage for MyCustomStorage {
}
}

/// An iterator type for the custom storage layer.
pub struct MyCustomStorageIter<'a>(btree_map::Values<'a, InvoiceId, Invoice>);

impl<'a> Iterator for MyCustomStorageIter<'a> {
Expand Down
2 changes: 1 addition & 1 deletion library/examples/nojs/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#![warn(clippy::pedantic)]
//! Serve a no-js frontend.
use acceptxmr::{storage::stores::InMemory, InvoiceId, PaymentGateway, PaymentGatewayBuilder};
use actix_files::Files;
Expand Down
2 changes: 1 addition & 1 deletion library/examples/persistence/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#![warn(clippy::pedantic)]
//! Use a persistent invoice store to enable recovery from power loss.
use acceptxmr::{storage::stores::Sqlite, PaymentGateway, PaymentGatewayBuilder};
use log::{error, info, LevelFilter};
Expand Down
2 changes: 1 addition & 1 deletion library/examples/websockets/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#![warn(clippy::pedantic)]
//! Use websockets to notify of invoice updates.
use std::{
future::Future,
Expand Down
11 changes: 1 addition & 10 deletions library/src/invoice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -502,20 +502,11 @@ impl Transfer {
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use log::LevelFilter;
use test_case::test_case;
use testing_utils::init_logger;

use crate::{Invoice, SubIndex};

fn init_logger() {
env_logger::builder()
.filter_level(LevelFilter::Warn)
.filter_module("acceptxmr", log::LevelFilter::Debug)
.is_test(true)
.try_init()
.ok();
}

#[test_case(1, 0 => "0.000000000001".to_string(); "small")]
#[test_case(u64::MAX, 0 => "18446744.073709551615".to_string(); "big")]
#[test_case(1, 1 => "0.0"; "zero")]
Expand Down
6 changes: 0 additions & 6 deletions library/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,16 +119,10 @@
//! The `sqlite` feature enables the [`Sqlite`](storage::stores::Sqlite) storage
//! implementation. The `bincode` feature will also be enabled by this feature.
#![deny(unsafe_code)]
#![warn(missing_docs)]
#![warn(unreachable_pub)]
#![warn(clippy::pedantic)]
#![warn(clippy::cargo)]
#![warn(clippy::panic)]
#![warn(clippy::unwrap_used)]
#![warn(clippy::expect_used)]
#![allow(clippy::multiple_crate_versions)]
#![allow(clippy::module_name_repetitions)]
// Show feature flag tags on `docs.rs`
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

Expand Down
20 changes: 3 additions & 17 deletions library/src/payment_gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,8 @@ impl<S: Storage + 'static> PaymentGateway<S> {
// Create persistent sub key checker for efficient tx output checking.
let mut sub_key_checker = SubKeyChecker::new(
&viewpair,
1..2,
0..highest_minor_index.load(atomic::Ordering::Relaxed) + 1,
major_index..major_index.saturating_add(1),
0..highest_minor_index.load(atomic::Ordering::Relaxed).saturating_add(1),
);
// Scan for transactions once every scan_interval.
let mut blockscan_interval = time::interval(scan_interval);
Expand Down Expand Up @@ -680,24 +680,10 @@ pub(crate) enum MessageToScanner {
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use log::LevelFilter;
use testing_utils::{init_logger, PRIMARY_ADDRESS, PRIVATE_VIEW_KEY};

use crate::{storage::stores::InMemory, PaymentGateway, PaymentGatewayBuilder};

fn init_logger() {
env_logger::builder()
.filter_level(LevelFilter::Warn)
.filter_module("acceptxmr", log::LevelFilter::Debug)
.is_test(true)
.try_init()
.ok();
}

const PRIVATE_VIEW_KEY: &str =
"ad2093a5705b9f33e6f0f0c1bc1f5f639c756cdfc168c8f2ac6127ccbdab3a03";
const PRIMARY_ADDRESS: &str =
"4613YiHLM6JMH4zejMB2zJY5TwQCxL8p65ufw8kBP5yxX9itmuGLqp1dS4tkVoTxjyH3aYhYNrtGHbQzJQP5bFus3KHVdmf";

#[test]
fn daemon_url() {
// Setup.
Expand Down
10 changes: 7 additions & 3 deletions library/src/scanner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,13 @@ impl<S: Storage> Scanner<S> {
e
);
} else {
// If the update was successful, send an update that down the subscriber
// channel.
// If the update was successful, send an update down the
// subscriber channel.
self.publisher.send_updates(&invoice).await;
debug!(
"Published invoice update for subaddress index {}",
invoice.index()
);
}
}

Expand Down Expand Up @@ -276,7 +280,7 @@ impl<S: Storage> Scanner<S> {
"Scanned {} transactions from block {}, and found {} transactions to tracked invoices",
transactions.len(),
block_cache.blocks()[i].height,
amounts_received.len()
amounts_received.len(),
);

let block_cache_height: u64 = block_cache.height() - i as u64;
Expand Down
14 changes: 1 addition & 13 deletions library/src/storage/height_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,26 +26,14 @@ pub trait HeightStorage: Send + Sync {
mod test {
use std::fmt::{Debug, Display};

use tempfile::Builder;
use test_case::test_case;
use testing_utils::new_temp_dir;

use crate::storage::{
stores::{InMemory, Sled, Sqlite},
HeightStorage,
};

fn new_temp_dir() -> String {
Builder::new()
.prefix("temp_db_")
.rand_bytes(16)
.tempdir()
.unwrap()
.path()
.to_str()
.expect("failed to get temporary directory path")
.to_string()
}

#[test_case(Sled::new(&new_temp_dir(), "invoices", "output keys", "height").unwrap(); "sled")]
#[test_case(InMemory::new(); "in-memory")]
#[test_case(Sqlite::new(":memory:", "invoices", "output keys", "height").unwrap(); "sqlite")]
Expand Down
14 changes: 1 addition & 13 deletions library/src/storage/invoice_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ pub trait InvoiceStorage: Send + Sync {
mod test {
use std::fmt::{Debug, Display};

use tempfile::Builder;
use test_case::test_case;
use testing_utils::new_temp_dir;

use crate::{
storage::{
Expand All @@ -106,18 +106,6 @@ mod test {
Invoice, SubIndex,
};

fn new_temp_dir() -> String {
Builder::new()
.prefix("temp_db_")
.rand_bytes(16)
.tempdir()
.unwrap()
.path()
.to_str()
.expect("failed to get temporary directory path")
.to_string()
}

fn dummy_invoice() -> Invoice {
Invoice::new(
"4A1WSBQdCbUCqt3DaGfmqVFchXScF43M6c5r4B6JXT3dUwuALncU9XTEnRPmUMcB3c16kVP9Y7thFLCJ5BaMW3UmSy93w3w".to_string(),
Expand Down
14 changes: 1 addition & 13 deletions library/src/storage/output_key_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,26 +55,14 @@ pub struct OutputId {
mod test {
use std::fmt::{Debug, Display};

use tempfile::Builder;
use test_case::test_case;
use testing_utils::new_temp_dir;

use crate::storage::{
stores::{InMemory, Sled, Sqlite},
OutputId, OutputKeyStorage, OutputPubKey,
};

fn new_temp_dir() -> String {
Builder::new()
.prefix("temp_db_")
.rand_bytes(16)
.tempdir()
.unwrap()
.path()
.to_str()
.expect("failed to get temporary directory path")
.to_string()
}

fn dummy_key() -> OutputPubKey {
OutputPubKey([0; 32])
}
Expand Down
6 changes: 3 additions & 3 deletions library/src/storage/stores/sqlite.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::fmt::Display;

use log::{debug, trace, warn};
use sqlite::{version, Connection, ConnectionWithFullMutex, CursorWithOwnership, State, Value};
use sqlite::{version, Connection, ConnectionThreadSafe, CursorWithOwnership, State, Value};
use thiserror::Error;

use crate::{
Expand All @@ -11,7 +11,7 @@ use crate::{

/// `SQLite` database.
pub struct Sqlite {
db: ConnectionWithFullMutex,
db: ConnectionThreadSafe,
invoices: TableName,
output_keys: TableName,
height: TableName,
Expand All @@ -31,7 +31,7 @@ impl Sqlite {
output_key_table: &str,
height_table: &str,
) -> Result<Sqlite, SqliteStorageError> {
let db = Connection::open_with_full_mutex(path)?;
let db = Connection::open_thread_safe(path)?;
debug!("Connection to SQLite v{} database established", version());

let invoices = TableName::new(invoice_table);
Expand Down
Loading

0 comments on commit 6ff9148

Please sign in to comment.