Skip to content
This repository was archived by the owner on Jan 6, 2025. It is now read-only.

Make crate no_std compatible #53

Merged
merged 1 commit into from
Dec 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ jobs:
if: matrix.check-fmt
run: rustup component add rustfmt && cargo fmt --all -- --check
- name: Test on Rust ${{ matrix.toolchain }}
run: cargo test
- name: Test on Rust ${{ matrix.toolchain }} with LSPS1 support
run: RUSTFLAGS="--cfg lsps1" cargo test
run: |
cargo test
RUSTFLAGS="--cfg lsps1" cargo test
- name: Test on Rust ${{ matrix.toolchain }} with no-std support
run: |
cargo test --no-default-features --features no-std
RUSTFLAGS="--cfg lsps1" cargo test --no-default-features --features no-std
14 changes: 10 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,18 @@ description = "Types and primitives to integrate a spec-compliant LSP with an LD

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[features]
default = ["std"]
std = ["lightning/std", "bitcoin/std"]
no-std = ["hashbrown", "lightning/no-std", "bitcoin/no-std", "core2/alloc"]

[dependencies]
lightning = { version = "0.0.118", default-features = false, features = ["max_level_trace", "std"] }
lightning = { version = "0.0.118", default-features = false, features = ["max_level_trace"] }
lightning-invoice = "0.26.0"
bitcoin = { version = "0.29.0", default-features = false }
hashbrown = { version = "0.8", optional = true }
core2 = { version = "0.3.0", optional = true, default-features = false }

bitcoin = "0.29.0"

chrono = { version = "0.4", default-features = false, features = ["std", "serde"] }
chrono = { version = "0.4", default-features = false, features = ["serde", "alloc"] }
serde = { version = "1.0", default-features = false, features = ["derive", "alloc"] }
serde_json = "1.0"
25 changes: 21 additions & 4 deletions src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,42 @@
#[cfg(lsps1)]
use crate::lsps1;
use crate::lsps2;
use std::collections::VecDeque;
use std::sync::{Condvar, Mutex};
use crate::prelude::{Vec, VecDeque};
use crate::sync::Mutex;

#[derive(Default)]
pub(crate) struct EventQueue {
queue: Mutex<VecDeque<Event>>,
condvar: Condvar,
#[cfg(feature = "std")]
condvar: std::sync::Condvar,
}

impl EventQueue {
pub fn new() -> Self {
let queue = Mutex::new(VecDeque::new());
#[cfg(feature = "std")]
{
let condvar = std::sync::Condvar::new();
Self { queue, condvar }
}
#[cfg(not(feature = "std"))]
Self { queue }
}

pub fn enqueue(&self, event: Event) {
{
let mut queue = self.queue.lock().unwrap();
queue.push_back(event);
}

#[cfg(feature = "std")]
self.condvar.notify_one();
}

pub fn next_event(&self) -> Option<Event> {
self.queue.lock().unwrap().pop_front()
}

#[cfg(feature = "std")]
pub fn wait_next_event(&self) -> Event {
let mut queue =
self.condvar.wait_while(self.queue.lock().unwrap(), |queue| queue.is_empty()).unwrap();
Expand Down
21 changes: 21 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,33 @@
#![allow(ellipsis_inclusive_range_patterns)]
#![allow(clippy::drop_non_drop)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(not(any(feature = "std", feature = "no-std")))]
compile_error!("at least one of the `std` or `no-std` features must be enabled");

#[macro_use]
extern crate alloc;

mod prelude {
#[cfg(feature = "hashbrown")]
extern crate hashbrown;

#[cfg(feature = "hashbrown")]
pub use self::hashbrown::{hash_map, HashMap, HashSet};
pub use alloc::{boxed::Box, collections::VecDeque, string::String, vec, vec::Vec};
#[cfg(not(feature = "hashbrown"))]
pub use std::collections::{hash_map, HashMap, HashSet};

pub use alloc::borrow::ToOwned;
pub use alloc::string::ToString;
}

pub mod events;
mod lsps0;
#[cfg(lsps1)]
mod lsps1;
pub mod lsps2;
mod sync;
mod utils;

pub use lsps0::message_handler::{JITChannelsConfig, LiquidityManager, LiquidityProviderConfig};
20 changes: 14 additions & 6 deletions src/lsps0/message_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ use crate::lsps0::msgs::{LSPSMessage, RawLSPSMessage, LSPS_MESSAGE_TYPE_ID};
use crate::lsps0::protocol::LSPS0MessageHandler;
use crate::lsps2::channel_manager::JITChannelManager;
use crate::lsps2::msgs::{OpeningFeeParams, RawOpeningFeeParams};
use crate::prelude::{HashMap, String, ToString, Vec};
use crate::sync::{Arc, Mutex, RwLock};

use lightning::chain::{self, BestBlock, Confirm, Filter, Listen};
use lightning::ln::channelmanager::{AChannelManager, ChainParameters, InterceptId};
Expand All @@ -32,10 +34,8 @@ use bitcoin::BlockHash;
#[cfg(lsps1)]
use chrono::Utc;

use std::collections::HashMap;
use std::convert::TryFrom;
use std::ops::Deref;
use std::sync::{Arc, Mutex, RwLock};
use core::convert::TryFrom;
use core::ops::Deref;

const LSPS_FEATURE_BIT: usize = 729;

Expand Down Expand Up @@ -146,7 +146,7 @@ where
) -> Self
where {
let pending_messages = Arc::new(Mutex::new(vec![]));
let pending_events = Arc::new(EventQueue::default());
let pending_events = Arc::new(EventQueue::new());

let lsps0_message_handler = LSPS0MessageHandler::new(
entropy_source.clone().clone(),
Expand Down Expand Up @@ -197,13 +197,21 @@ where {
}
}

/// Blocks until next event is ready and returns it.
/// Blocks the current thread until next event is ready and returns it.
///
/// Typically you would spawn a thread or task that calls this in a loop.
#[cfg(feature = "std")]
pub fn wait_next_event(&self) -> Event {
self.pending_events.wait_next_event()
}

/// Returns `Some` if an event is ready.
///
/// Typically you would spawn a thread or task that calls this in a loop.
pub fn next_event(&self) -> Option<Event> {
self.pending_events.next_event()
}

/// Returns and clears all events without blocking.
///
/// Typically you would spawn a thread or task that calls this in a loop.
Expand Down
9 changes: 6 additions & 3 deletions src/lsps0/msgs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,19 @@ use crate::lsps2::msgs::{
LSPS2Message, LSPS2Request, LSPS2Response, LSPS2_BUY_METHOD_NAME, LSPS2_GET_INFO_METHOD_NAME,
LSPS2_GET_VERSIONS_METHOD_NAME,
};
use crate::prelude::{HashMap, String, ToString, Vec};

use lightning::impl_writeable_msg;
use lightning::ln::wire;

use serde::de;
use serde::de::{MapAccess, Visitor};
use serde::ser::SerializeStruct;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::json;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt;

use core::convert::TryFrom;
use core::fmt;

const LSPS_MESSAGE_SERIALIZED_STRUCT_NAME: &str = "LSPSMessage";
const JSONRPC_FIELD_KEY: &str = "jsonrpc";
Expand Down
20 changes: 12 additions & 8 deletions src/lsps0/protocol.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
use bitcoin::secp256k1::PublicKey;
use lightning::ln::msgs::{ErrorAction, LightningError};
use lightning::sign::EntropySource;
use lightning::util::logger::Level;
use std::ops::Deref;
use std::sync::{Arc, Mutex};

use crate::lsps0::message_handler::ProtocolMessageHandler;
use crate::lsps0::msgs::{
LSPS0Message, LSPS0Request, LSPS0Response, LSPSMessage, ListProtocolsRequest,
ListProtocolsResponse, RequestId, ResponseError,
};
use crate::prelude::Vec;
use crate::sync::{Arc, Mutex};
use crate::utils;

use lightning::ln::msgs::{ErrorAction, LightningError};
use lightning::sign::EntropySource;
use lightning::util::logger::Level;

use bitcoin::secp256k1::PublicKey;

use core::ops::Deref;

pub struct LSPS0MessageHandler<ES: Deref>
where
ES::Target: EntropySource,
Expand Down Expand Up @@ -104,7 +107,8 @@ where
#[cfg(test)]
mod tests {

use std::sync::Arc;
use alloc::string::ToString;
use alloc::sync::Arc;

use super::*;

Expand Down
Loading