Skip to content

Commit faa43a0

Browse files
committed
Add initial no_std support
Add initial no_std support for embedded platforms
1 parent 7297e13 commit faa43a0

37 files changed

+186
-106
lines changed

ci/check-compiles.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ cargo check
66
cargo doc
77
cargo doc --document-private-items
88
cd fuzz && cargo check --features=stdin_fuzz
9+
cd ../lightning && cargo check --default-features=false --features=core

lightning/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,18 @@ max_level_error = []
2121
max_level_warn = []
2222
max_level_info = []
2323
max_level_debug = []
24+
std = []
25+
core = ["hashbrown"]
2426
# Allow signing of local transactions that may have been revoked or will be revoked, for functional testing (e.g. justice tx handling).
2527
# This is unsafe to use in production because it may result in the counterparty publishing taking our funds.
2628
unsafe_revoked_tx_signing = []
2729
unstable = []
30+
default = ["std"]
2831

2932
[dependencies]
3033
bitcoin = "0.26"
3134

35+
hashbrown = { version = "0.9", optional = true }
3236
hex = { version = "0.3", optional = true }
3337
regex = { version = "0.1.80", optional = true }
3438

lightning/src/chain/chainmonitor.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,11 @@ use util::logger::Logger;
3737
use util::events;
3838
use util::events::Event;
3939

40-
use std::collections::{HashMap, hash_map};
40+
use alloc::vec::Vec;
41+
use core::ops::Deref;
42+
use crate::{HashMap, hash_map};
4143
use std::sync::RwLock;
42-
use std::ops::Deref;
44+
4345

4446
/// An implementation of [`chain::Watch`] for monitoring channels.
4547
///
@@ -324,6 +326,9 @@ mod tests {
324326
use util::events::MessageSendEventsProvider;
325327
use util::test_utils::{OnRegisterOutput, TxOutReference};
326328

329+
#[macro_use]
330+
use alloc::vec;
331+
327332
/// Tests that in-block dependent transactions are processed by `block_connected` when not
328333
/// included in `txdata` but returned by [`chain::Filter::register_output`]. For instance,
329334
/// a (non-anchor) commitment transaction's HTLC output may be spent in the same block as the

lightning/src/chain/channelmonitor.rs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,11 @@ use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48};
5151
use util::byte_utils;
5252
use util::events::Event;
5353

54-
use std::collections::{HashMap, HashSet};
55-
use std::{cmp, mem};
54+
#[macro_use]
55+
use alloc::{boxed::Box, vec, vec::Vec};
56+
use crate::{HashMap, HashSet};
57+
use core::{cmp, mem, ops::Deref};
5658
use std::io::Error;
57-
use std::ops::Deref;
5859
use std::sync::Mutex;
5960

6061
/// An update generated by the underlying Channel itself which contains some new information the
@@ -85,7 +86,7 @@ pub struct ChannelMonitorUpdate {
8586
/// then we allow the `ChannelManager` to send a `ChannelMonitorUpdate` with this update ID,
8687
/// with the update providing said payment preimage. No other update types are allowed after
8788
/// force-close.
88-
pub const CLOSED_CHANNEL_UPDATE_ID: u64 = std::u64::MAX;
89+
pub const CLOSED_CHANNEL_UPDATE_ID: u64 = ::core::u64::MAX;
8990

9091
impl Writeable for ChannelMonitorUpdate {
9192
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
@@ -101,7 +102,7 @@ impl Readable for ChannelMonitorUpdate {
101102
fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
102103
let update_id: u64 = Readable::read(r)?;
103104
let len: u64 = Readable::read(r)?;
104-
let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::std::mem::size_of::<ChannelMonitorUpdateStep>()));
105+
let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<ChannelMonitorUpdateStep>()));
105106
for _ in 0..len {
106107
updates.push(Readable::read(r)?);
107108
}
@@ -1932,7 +1933,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
19321933

19331934
for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
19341935
if let Some(transaction_output_index) = htlc.transaction_output_index {
1935-
claim_requests.push(ClaimRequest { absolute_timelock: ::std::u32::MAX, aggregable: false, outpoint: BitcoinOutPoint { txid: holder_tx.txid, vout: transaction_output_index as u32 },
1936+
claim_requests.push(ClaimRequest { absolute_timelock: ::core::u32::MAX, aggregable: false, outpoint: BitcoinOutPoint { txid: holder_tx.txid, vout: transaction_output_index as u32 },
19361937
witness_data: InputMaterial::HolderHTLC {
19371938
preimage: if !htlc.offered {
19381939
if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
@@ -2594,7 +2595,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
25942595
fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
25952596
let mut spendable_output = None;
25962597
for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
2597-
if i > ::std::u16::MAX as usize {
2598+
if i > ::core::u16::MAX as usize {
25982599
// While it is possible that an output exists on chain which is greater than the
25992600
// 2^16th output in a given transaction, this is only possible if the output is not
26002601
// in a lightning transaction and was instead placed there by some third party who
@@ -3060,6 +3061,7 @@ mod tests {
30603061
use bitcoin::secp256k1::Secp256k1;
30613062
use std::sync::{Arc, Mutex};
30623063
use chain::keysinterface::InMemorySigner;
3064+
use alloc::vec::Vec;
30633065

30643066
#[test]
30653067
fn test_prune_preimages() {

lightning/src/chain/keysinterface.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,10 @@ use ln::chan_utils;
3737
use ln::chan_utils::{HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, HolderCommitmentTransaction, ChannelTransactionParameters, CommitmentTransaction};
3838
use ln::msgs::UnsignedChannelAnnouncement;
3939

40-
use std::collections::HashSet;
41-
use std::sync::atomic::{AtomicUsize, Ordering};
40+
#[macro_use]
41+
use alloc::{vec, vec::Vec};
42+
use core::sync::atomic::{AtomicUsize, Ordering};
43+
use crate::HashSet;
4244
use std::io::Error;
4345
use ln::msgs::{DecodeError, MAX_VALUE_MSAT};
4446

@@ -850,7 +852,7 @@ impl KeysManager {
850852
/// onchain output detection for which a corresponding delayed_payment_key must be derived.
851853
pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
852854
let chan_id = byte_utils::slice_to_be64(&params[0..8]);
853-
assert!(chan_id <= std::u32::MAX as u64); // Otherwise the params field wasn't created by us
855+
assert!(chan_id <= core::u32::MAX as u64); // Otherwise the params field wasn't created by us
854856
let mut unique_start = Sha256::engine();
855857
unique_start.input(params);
856858
unique_start.input(&self.seed);
@@ -1032,7 +1034,7 @@ impl KeysInterface for KeysManager {
10321034

10331035
fn get_channel_signer(&self, _inbound: bool, channel_value_satoshis: u64) -> Self::Signer {
10341036
let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
1035-
assert!(child_ix <= std::u32::MAX as usize);
1037+
assert!(child_ix <= core::u32::MAX as usize);
10361038
let mut id = [0; 32];
10371039
id[0..8].copy_from_slice(&byte_utils::be64_to_array(child_ix as u64));
10381040
id[8..16].copy_from_slice(&byte_utils::be64_to_array(self.starting_time_nanos as u64));

lightning/src/chain/mod.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99

1010
//! Structs and traits which allow other parts of rust-lightning to interact with the blockchain.
1111
12+
use alloc::vec::Vec;
13+
1214
use bitcoin::blockdata::block::{Block, BlockHeader};
1315
use bitcoin::blockdata::script::Script;
1416
use bitcoin::blockdata::transaction::{Transaction, TxOut};
@@ -246,7 +248,7 @@ pub struct WatchedOutput {
246248
pub script_pubkey: Script,
247249
}
248250

249-
impl<T: Listen> Listen for std::ops::Deref<Target = T> {
251+
impl<T: Listen> Listen for core::ops::Deref<Target = T> {
250252
fn block_connected(&self, block: &Block, height: u32) {
251253
(**self).block_connected(block, height);
252254
}
@@ -256,7 +258,7 @@ impl<T: Listen> Listen for std::ops::Deref<Target = T> {
256258
}
257259
}
258260

259-
impl<T: std::ops::Deref, U: std::ops::Deref> Listen for (T, U)
261+
impl<T: core::ops::Deref, U: core::ops::Deref> Listen for (T, U)
260262
where
261263
T::Target: Listen,
262264
U::Target: Listen,

lightning/src/lib.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
#![cfg_attr(not(any(feature = "fuzztarget", feature = "_test_utils")), deny(missing_docs))]
2222
#![cfg_attr(not(any(test, feature = "fuzztarget", feature = "_test_utils")), forbid(unsafe_code))]
2323
#![deny(broken_intra_doc_links)]
24+
#![cfg_attr(feature = "core", no_std)]
2425

2526
// In general, rust is absolutely horrid at supporting users doing things like,
2627
// for example, compiling Rust code for real environments. Disable useless lints
@@ -35,6 +36,15 @@ extern crate bitcoin;
3536
#[cfg(any(test, feature = "_test_utils"))] extern crate hex;
3637
#[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))] extern crate regex;
3738

39+
extern crate alloc;
40+
#[cfg(feature = "std")] extern crate core;
41+
#[cfg(feature = "core")] extern crate hashbrown;
42+
43+
#[cfg(feature = "core")]
44+
use hashbrown::{HashMap, HashSet, hash_map};
45+
#[cfg(feature = "std")]
46+
use std::collections::{HashMap, HashSet, hash_map};
47+
3848
#[macro_use]
3949
pub mod util;
4050
pub mod chain;

lightning/src/ln/chan_utils.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,12 @@ use bitcoin::secp256k1::{Secp256k1, Signature, Message};
3131
use bitcoin::secp256k1::Error as SecpError;
3232
use bitcoin::secp256k1;
3333

34-
use std::cmp;
34+
use alloc::vec::Vec;
35+
use core::{cmp, ops::Deref};
3536
use ln::chan_utils;
3637
use util::transaction_utils::sort_outputs;
3738
use ln::channel::INITIAL_COMMITMENT_NUMBER;
3839
use std::io::Read;
39-
use std::ops::Deref;
4040
use chain;
4141

4242
// Maximum size of a serialized HTLCOutputInCommitment
@@ -1235,6 +1235,7 @@ fn script_for_p2wpkh(key: &PublicKey) -> Script {
12351235
mod tests {
12361236
use super::CounterpartyCommitmentSecrets;
12371237
use hex;
1238+
use alloc::vec::Vec;
12381239

12391240
#[test]
12401241
fn test_per_commitment_storage() {

lightning/src/ln/chanmon_update_fail_tests.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,9 @@ use ln::functional_test_utils::*;
3737

3838
use util::test_utils;
3939

40+
#[macro_use]
41+
use alloc::{vec, vec::Vec};
42+
4043
// If persister_fail is true, we have the persister return a PermanentFailure
4144
// instead of the higher-level ChainMonitor.
4245
fn do_test_simple_monitor_permanent_update_fail(persister_fail: bool) {

lightning/src/ln/channel.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,9 @@ use util::errors::APIError;
3939
use util::config::{UserConfig,ChannelConfig};
4040
use util::scid_utils::scid_from_parts;
4141

42-
use std;
43-
use std::{cmp,mem,fmt};
44-
use std::ops::Deref;
42+
#[macro_use]
43+
use alloc::{format, boxed::Box, string::String, vec, vec::Vec};
44+
use core::{cmp, mem, fmt, ops::Deref};
4545
#[cfg(any(test, feature = "fuzztarget"))]
4646
use std::sync::Mutex;
4747
use bitcoin::hashes::hex::ToHex;
@@ -1217,7 +1217,7 @@ impl<Signer: Sign> Channel<Signer> {
12171217
// on-chain ChannelsMonitors during block rescan. Ideally we'd figure out a way to drop
12181218
// these, but for now we just have to treat them as normal.
12191219

1220-
let mut pending_idx = std::usize::MAX;
1220+
let mut pending_idx = core::usize::MAX;
12211221
for (idx, htlc) in self.pending_inbound_htlcs.iter().enumerate() {
12221222
if htlc.htlc_id == htlc_id_arg {
12231223
assert_eq!(htlc.payment_hash, payment_hash_calc);
@@ -1240,7 +1240,7 @@ impl<Signer: Sign> Channel<Signer> {
12401240
break;
12411241
}
12421242
}
1243-
if pending_idx == std::usize::MAX {
1243+
if pending_idx == core::usize::MAX {
12441244
return Err(ChannelError::Ignore("Unable to find a pending HTLC which matched the given HTLC ID".to_owned()));
12451245
}
12461246

@@ -1339,7 +1339,7 @@ impl<Signer: Sign> Channel<Signer> {
13391339
// on-chain ChannelsMonitors during block rescan. Ideally we'd figure out a way to drop
13401340
// these, but for now we just have to treat them as normal.
13411341

1342-
let mut pending_idx = std::usize::MAX;
1342+
let mut pending_idx = core::usize::MAX;
13431343
for (idx, htlc) in self.pending_inbound_htlcs.iter().enumerate() {
13441344
if htlc.htlc_id == htlc_id_arg {
13451345
match htlc.state {
@@ -1356,7 +1356,7 @@ impl<Signer: Sign> Channel<Signer> {
13561356
pending_idx = idx;
13571357
}
13581358
}
1359-
if pending_idx == std::usize::MAX {
1359+
if pending_idx == core::usize::MAX {
13601360
return Err(ChannelError::Ignore("Unable to find a pending HTLC which matched the given HTLC ID".to_owned()));
13611361
}
13621362

@@ -4394,8 +4394,8 @@ impl<Signer: Sign> Writeable for Channel<Signer> {
43944394

43954395
let mut key_data = VecWriter(Vec::new());
43964396
self.holder_signer.write(&mut key_data)?;
4397-
assert!(key_data.0.len() < std::usize::MAX);
4398-
assert!(key_data.0.len() < std::u32::MAX as usize);
4397+
assert!(key_data.0.len() < core::usize::MAX);
4398+
assert!(key_data.0.len() < core::u32::MAX as usize);
43994399
(key_data.0.len() as u32).write(writer)?;
44004400
writer.write_all(&key_data.0[..])?;
44014401

@@ -4859,6 +4859,9 @@ mod tests {
48594859
use bitcoin::hash_types::{Txid, WPubkeyHash};
48604860
use std::sync::Arc;
48614861

4862+
#[macro_use]
4863+
use alloc::{vec, vec::Vec};
4864+
48624865
struct TestFeeEstimator {
48634866
fee_est: u32
48644867
}

lightning/src/ln/channelmanager.rs

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -61,15 +61,20 @@ use util::chacha20::{ChaCha20, ChaChaReader};
6161
use util::logger::Logger;
6262
use util::errors::APIError;
6363

64-
use std::{cmp, mem};
65-
use std::collections::{HashMap, hash_map, HashSet};
64+
#[macro_use]
65+
use alloc::{format, vec, string::String, vec::Vec};
66+
use core::{
67+
cmp,
68+
mem,
69+
ops::Deref,
70+
sync::atomic::{AtomicUsize, Ordering},
71+
time::Duration,
72+
};
73+
use crate::{HashMap, HashSet, hash_map};
6674
use std::io::{Cursor, Read};
6775
use std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard};
68-
use std::sync::atomic::{AtomicUsize, Ordering};
69-
use std::time::Duration;
7076
#[cfg(any(test, feature = "allow_wallclock_use"))]
7177
use std::time::Instant;
72-
use std::ops::Deref;
7378
use bitcoin::hashes::hex::ToHex;
7479

7580
// We hold various information about HTLC relay in the HTLC objects in Channel itself:
@@ -1748,7 +1753,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
17481753
// be absurd. We ensure this by checking that at least 500 (our stated public contract on when
17491754
// broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
17501755
// message...
1751-
const HALF_MESSAGE_IS_ADDRS: u32 = ::std::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
1756+
const HALF_MESSAGE_IS_ADDRS: u32 = core::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
17521757
#[deny(const_err)]
17531758
#[allow(dead_code)]
17541759
// ...by failing to compile if the number of addresses that would be half of a message is
@@ -4716,9 +4721,8 @@ impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
47164721
mod tests {
47174722
use ln::channelmanager::PersistenceNotifier;
47184723
use std::sync::Arc;
4719-
use std::sync::atomic::{AtomicBool, Ordering};
4724+
use core::{sync::atomic::{AtomicBool, Ordering}, time::Duration};
47204725
use std::thread;
4721-
use std::time::Duration;
47224726

47234727
#[test]
47244728
fn test_wait_timeout() {
@@ -4783,6 +4787,8 @@ pub mod bench {
47834787
use bitcoin::hashes::sha256::Hash as Sha256;
47844788
use bitcoin::{Block, BlockHeader, Transaction, TxOut};
47854789

4790+
use alloc::vec::Vec;
4791+
use core::default::Default;
47864792
use std::sync::Mutex;
47874793

47884794
use test::Bencher;

0 commit comments

Comments
 (0)