Skip to content

Commit 74d5bb9

Browse files
committed
fixup! lightning: move no_std conditional into main lib
1 parent dd9f430 commit 74d5bb9

30 files changed

+137
-84
lines changed

lightning/src/chain/chainmonitor.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ use util::logger::Logger;
4242
use util::events;
4343
use util::events::Event;
4444

45-
use crate::{HashMap, hash_map, ops::Deref};
45+
use crate::{HashMap, hash_map};
46+
use core::ops::Deref;
4647
use std::sync::RwLock;
4748

4849
/// An implementation of [`chain::Watch`] for monitoring channels.

lightning/src/chain/channelmonitor.rs

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

54-
use crate::{HashMap, HashSet, cmp, hash_map, mem, ops::Deref};
54+
#[cfg(feature = "no_std")]
55+
#[macro_use]
56+
use alloc::{boxed::Box, vec, vec::Vec};
57+
use crate::{HashMap, HashSet, hash_map};
58+
use core::{cmp, mem, ops::Deref};
5559
use std::io::Error;
5660
use std::sync::Mutex;
5761

@@ -85,7 +89,7 @@ pub struct ChannelMonitorUpdate {
8589
/// then we allow the `ChannelManager` to send a `ChannelMonitorUpdate` with this update ID,
8690
/// with the update providing said payment preimage. No other update types are allowed after
8791
/// force-close.
88-
pub const CLOSED_CHANNEL_UPDATE_ID: u64 = crate::u64::MAX;
92+
pub const CLOSED_CHANNEL_UPDATE_ID: u64 = ::core::u64::MAX;
8993

9094
impl Writeable for ChannelMonitorUpdate {
9195
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
@@ -101,7 +105,7 @@ impl Readable for ChannelMonitorUpdate {
101105
fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
102106
let update_id: u64 = Readable::read(r)?;
103107
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>()));
108+
let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<ChannelMonitorUpdateStep>()));
105109
for _ in 0..len {
106110
updates.push(Readable::read(r)?);
107111
}
@@ -1819,7 +1823,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
18191823

18201824
for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
18211825
if let Some(transaction_output_index) = htlc.transaction_output_index {
1822-
claim_requests.push(ClaimRequest { absolute_timelock: crate::u32::MAX, aggregable: false, outpoint: BitcoinOutPoint { txid: holder_tx.txid, vout: transaction_output_index as u32 },
1826+
claim_requests.push(ClaimRequest { absolute_timelock: ::core::u32::MAX, aggregable: false, outpoint: BitcoinOutPoint { txid: holder_tx.txid, vout: transaction_output_index as u32 },
18231827
witness_data: InputMaterial::HolderHTLC {
18241828
preimage: if !htlc.offered {
18251829
if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
@@ -2367,7 +2371,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
23672371
fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
23682372
let mut spendable_output = None;
23692373
for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
2370-
if i > crate::u16::MAX as usize {
2374+
if i > ::core::u16::MAX as usize {
23712375
// While it is possible that an output exists on chain which is greater than the
23722376
// 2^16th output in a given transaction, this is only possible if the output is not
23732377
// in a lightning transaction and was instead placed there by some third party who

lightning/src/chain/keysinterface.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,11 @@ use ln::chan_utils;
3636
use ln::chan_utils::{HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, HolderCommitmentTransaction, ChannelTransactionParameters, CommitmentTransaction};
3737
use ln::msgs::UnsignedChannelAnnouncement;
3838

39-
use crate::{HashSet, atomic::{AtomicUsize, Ordering}};
39+
#[cfg(feature = "no_std")]
40+
#[macro_use]
41+
use alloc::{vec, vec::Vec};
42+
use crate::HashSet;
43+
use core::sync::atomic::{AtomicUsize, Ordering};
4044
use std::io::Error;
4145
use ln::msgs::{DecodeError, MAX_VALUE_MSAT};
4246

@@ -832,7 +836,7 @@ impl KeysManager {
832836
/// onchain output detection for which a corresponding delayed_payment_key must be derived.
833837
pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
834838
let chan_id = byte_utils::slice_to_be64(&params[0..8]);
835-
assert!(chan_id <= crate::u32::MAX as u64); // Otherwise the params field wasn't created by us
839+
assert!(chan_id <= core::u32::MAX as u64); // Otherwise the params field wasn't created by us
836840
let mut unique_start = Sha256::engine();
837841
unique_start.input(params);
838842
unique_start.input(&self.seed);
@@ -1014,7 +1018,7 @@ impl KeysInterface for KeysManager {
10141018

10151019
fn get_channel_signer(&self, _inbound: bool, channel_value_satoshis: u64) -> Self::Signer {
10161020
let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
1017-
assert!(child_ix <= crate::u32::MAX as usize);
1021+
assert!(child_ix <= core::u32::MAX as usize);
10181022
let mut id = [0; 32];
10191023
id[0..8].copy_from_slice(&byte_utils::be64_to_array(child_ix as u64));
10201024
id[8..16].copy_from_slice(&byte_utils::be64_to_array(self.starting_time_nanos as u64));

lightning/src/chain/mod.rs

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

1010
//! Structs and traits which allow other parts of rust-lightning to interact with the blockchain.
1111
12+
#[cfg(feature = "no_std")]
13+
use alloc::vec::Vec;
14+
1215
use bitcoin::blockdata::block::{Block, BlockHeader};
1316
use bitcoin::blockdata::script::Script;
1417
use bitcoin::blockdata::transaction::TxOut;
@@ -137,7 +140,7 @@ pub trait Filter: Send + Sync {
137140
fn register_output(&self, outpoint: &OutPoint, script_pubkey: &Script);
138141
}
139142

140-
impl<T: Listen> Listen for crate::ops::Deref<Target = T> {
143+
impl<T: Listen> Listen for core::ops::Deref<Target = T> {
141144
fn block_connected(&self, block: &Block, height: u32) {
142145
(**self).block_connected(block, height);
143146
}
@@ -147,7 +150,7 @@ impl<T: Listen> Listen for crate::ops::Deref<Target = T> {
147150
}
148151
}
149152

150-
impl<T: crate::ops::Deref, U: crate::ops::Deref> Listen for (T, U)
153+
impl<T: core::ops::Deref, U: core::ops::Deref> Listen for (T, U)
151154
where
152155
T::Target: Listen,
153156
U::Target: Listen,

lightning/src/lib.rs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
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))]
23+
#![cfg_attr(feature = "no_std", no_std)]
2324

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

3738
#[cfg(feature = "no_std")] extern crate alloc;
38-
#[cfg(feature = "no_std")] extern crate core;
39+
#[cfg(not(feature = "no_std"))] extern crate core;
3940
#[cfg(feature = "no_std")] extern crate hashbrown;
4041

41-
#[cfg(feature = "no_std")]
42-
use core::{cell, cmp, default, fmt, hash, iter, marker, mem, ops, sync::atomic, time, u16, u32, u64, usize};
43-
#[cfg(not(feature = "no_std"))]
44-
use std::{cell, cmp, default, fmt, hash, iter, marker, mem, ops, sync::atomic, time, u16, u32, u64, usize};
45-
4642
#[cfg(feature = "no_std")]
4743
use hashbrown::{HashMap, HashSet, hash_map};
4844
#[cfg(feature = "no_std")]

lightning/src/ln/chan_utils.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,16 @@ use bitcoin::secp256k1::{Secp256k1, Signature, Message};
3131
use bitcoin::secp256k1::Error as SecpError;
3232
use bitcoin::secp256k1;
3333

34-
use crate::{cmp, ops::Deref};
34+
use core::{cmp, ops::Deref};
3535
use ln::chan_utils;
3636
use util::transaction_utils::sort_outputs;
3737
use ln::channel::INITIAL_COMMITMENT_NUMBER;
3838
use std::io::Read;
3939
use chain;
4040

41+
#[cfg(feature = "no_std")]
42+
use alloc::vec::Vec;
43+
4144
const HTLC_OUTPUT_IN_COMMITMENT_SIZE: usize = 1 + 8 + 4 + 32 + 5;
4245

4346
pub(crate) const MAX_HTLCS: u16 = 483;

lightning/src/ln/channel.rs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,16 @@ use util::logger::Logger;
3838
use util::errors::APIError;
3939
use util::config::{UserConfig,ChannelConfig};
4040

41-
use crate::{cmp, mem, fmt, ops::Deref};
41+
use core::{cmp, mem, fmt, ops::Deref};
4242
#[cfg(any(test, feature = "fuzztarget"))]
4343
use std::sync::Mutex;
4444
use bitcoin::hashes::hex::ToHex;
4545
use bitcoin::blockdata::opcodes::all::OP_PUSHBYTES_0;
4646

47+
#[cfg(feature = "no_std")]
48+
#[macro_use]
49+
use alloc::{format, boxed::Box, string::String, vec, vec::Vec};
50+
4751
#[cfg(test)]
4852
pub struct ChannelValueStat {
4953
pub value_to_self_msat: u64,
@@ -1189,7 +1193,7 @@ impl<Signer: Sign> Channel<Signer> {
11891193
// on-chain ChannelsMonitors during block rescan. Ideally we'd figure out a way to drop
11901194
// these, but for now we just have to treat them as normal.
11911195

1192-
let mut pending_idx = crate::usize::MAX;
1196+
let mut pending_idx = core::usize::MAX;
11931197
for (idx, htlc) in self.pending_inbound_htlcs.iter().enumerate() {
11941198
if htlc.htlc_id == htlc_id_arg {
11951199
assert_eq!(htlc.payment_hash, payment_hash_calc);
@@ -1212,7 +1216,7 @@ impl<Signer: Sign> Channel<Signer> {
12121216
break;
12131217
}
12141218
}
1215-
if pending_idx == crate::usize::MAX {
1219+
if pending_idx == core::usize::MAX {
12161220
return Err(ChannelError::Ignore("Unable to find a pending HTLC which matched the given HTLC ID".to_owned()));
12171221
}
12181222

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

1314-
let mut pending_idx = crate::usize::MAX;
1318+
let mut pending_idx = core::usize::MAX;
13151319
for (idx, htlc) in self.pending_inbound_htlcs.iter().enumerate() {
13161320
if htlc.htlc_id == htlc_id_arg {
13171321
match htlc.state {
@@ -1328,7 +1332,7 @@ impl<Signer: Sign> Channel<Signer> {
13281332
pending_idx = idx;
13291333
}
13301334
}
1331-
if pending_idx == crate::usize::MAX {
1335+
if pending_idx == core::usize::MAX {
13321336
return Err(ChannelError::Ignore("Unable to find a pending HTLC which matched the given HTLC ID".to_owned()));
13331337
}
13341338

@@ -4281,8 +4285,8 @@ impl<Signer: Sign> Writeable for Channel<Signer> {
42814285

42824286
let mut key_data = VecWriter(Vec::new());
42834287
self.holder_signer.write(&mut key_data)?;
4284-
assert!(key_data.0.len() < crate::usize::MAX);
4285-
assert!(key_data.0.len() < crate::u32::MAX as usize);
4288+
assert!(key_data.0.len() < core::usize::MAX);
4289+
assert!(key_data.0.len() < core::u32::MAX as usize);
42864290
(key_data.0.len() as u32).write(writer)?;
42874291
writer.write_all(&key_data.0[..])?;
42884292

lightning/src/ln/channelmanager.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -55,15 +55,16 @@ use util::chacha20::{ChaCha20, ChaChaReader};
5555
use util::logger::Logger;
5656
use util::errors::APIError;
5757

58-
use crate::{
59-
HashMap,
60-
HashSet,
58+
#[cfg(feature = "no_std")]
59+
#[macro_use]
60+
use alloc::{format, vec, vec::Vec};
61+
use crate::{HashMap, HashSet, hash_map};
62+
use core::{
6163
cmp,
62-
hash_map,
6364
mem,
6465
marker::{Sync, Send},
6566
ops::Deref,
66-
atomic::{AtomicUsize, Ordering},
67+
sync::atomic::{AtomicUsize, Ordering},
6768
time::Duration,
6869
};
6970
use std::io::{Cursor, Read};
@@ -1583,7 +1584,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
15831584
// be absurd. We ensure this by checking that at least 500 (our stated public contract on when
15841585
// broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
15851586
// message...
1586-
const HALF_MESSAGE_IS_ADDRS: u32 = crate::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
1587+
const HALF_MESSAGE_IS_ADDRS: u32 = core::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
15871588
#[deny(const_err)]
15881589
#[allow(dead_code)]
15891590
// ...by failing to compile if the number of addresses that would be half of a message is

lightning/src/ln/features.rs

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,14 @@
2525
//! [`Features`]: struct.Features.html
2626
//! [`Context`]: sealed/trait.Context.html
2727
28-
use crate::{cmp, fmt, marker::PhantomData};
28+
use core::{cmp, fmt, marker::PhantomData};
2929

3030
use ln::msgs::DecodeError;
3131
use util::ser::{Readable, Writeable, Writer};
3232

33+
#[cfg(feature = "no_std")]
34+
use alloc::vec::Vec;
35+
3336
mod sealed {
3437
use ln::features::Features;
3538

@@ -197,42 +200,34 @@ mod sealed {
197200

198201
/// Returns whether the feature is required by the given flags.
199202
#[inline]
200-
fn requires_feature(flags: &Vec<u8>) -> bool {
203+
fn requires_feature(flags: &[u8]) -> bool {
201204
flags.len() > Self::BYTE_OFFSET &&
202205
(flags[Self::BYTE_OFFSET] & Self::REQUIRED_MASK) != 0
203206
}
204207

205208
/// Returns whether the feature is supported by the given flags.
206209
#[inline]
207-
fn supports_feature(flags: &Vec<u8>) -> bool {
210+
fn supports_feature(flags: &[u8]) -> bool {
208211
flags.len() > Self::BYTE_OFFSET &&
209212
(flags[Self::BYTE_OFFSET] & (Self::REQUIRED_MASK | Self::OPTIONAL_MASK)) != 0
210213
}
211214

212215
/// Sets the feature's required (even) bit in the given flags.
213216
#[inline]
214-
fn set_required_bit(flags: &mut Vec<u8>) {
215-
if flags.len() <= Self::BYTE_OFFSET {
216-
flags.resize(Self::BYTE_OFFSET + 1, 0u8);
217-
}
218-
217+
fn set_required_bit(flags: &mut [u8]) {
219218
flags[Self::BYTE_OFFSET] |= Self::REQUIRED_MASK;
220219
}
221220

222221
/// Sets the feature's optional (odd) bit in the given flags.
223222
#[inline]
224-
fn set_optional_bit(flags: &mut Vec<u8>) {
225-
if flags.len() <= Self::BYTE_OFFSET {
226-
flags.resize(Self::BYTE_OFFSET + 1, 0u8);
227-
}
228-
223+
fn set_optional_bit(flags: &mut [u8]) {
229224
flags[Self::BYTE_OFFSET] |= Self::OPTIONAL_MASK;
230225
}
231226

232227
/// Clears the feature's required (even) and optional (odd) bits from the given
233228
/// flags.
234229
#[inline]
235-
fn clear_bits(flags: &mut Vec<u8>) {
230+
fn clear_bits(flags: &mut [u8]) {
236231
if flags.len() > Self::BYTE_OFFSET {
237232
flags[Self::BYTE_OFFSET] &= !Self::REQUIRED_MASK;
238233
flags[Self::BYTE_OFFSET] &= !Self::OPTIONAL_MASK;

lightning/src/ln/functional_test_utils.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@ use bitcoin::secp256k1::key::PublicKey;
4040

4141
use std::rc::Rc;
4242
use std::sync::Mutex;
43-
use crate::{HashMap, cell::RefCell, mem};
43+
use core::{cell::RefCell, mem};
44+
use crate::HashMap;
4445

4546
pub const CHAN_CONFIRM_DEPTH: u32 = 100;
4647

lightning/src/ln/functional_tests.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@ use bitcoin::secp256k1::key::{PublicKey,SecretKey};
4848
use regex;
4949

5050
use std::sync::Mutex;
51-
use crate::{BTreeSet, HashMap, HashSet, atomic::Ordering, default::Default};
51+
use core::{sync::atomic::Ordering, default::Default};
52+
use crate::{BTreeSet, HashMap, HashSet};
5253

5354
use ln::functional_test_utils::*;
5455
use ln::chan_utils::CommitmentTransaction;

lightning/src/ln/msgs.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,10 @@ use bitcoin::hash_types::{Txid, BlockHash};
3232

3333
use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
3434

35-
use crate::{cmp, fmt::{self, Debug}};
35+
#[cfg(feature = "no_std")]
36+
#[macro_use]
37+
use alloc::{vec, vec::Vec};
38+
use core::{cmp, fmt::{self, Debug}};
3639
use std::io::Read;
3740

3841
use util::events::MessageSendEventsProvider;

lightning/src/ln/onchaintx.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,12 @@ use util::logger::Logger;
3232
use util::ser::{Readable, ReadableArgs, Writer, Writeable, VecWriter};
3333
use util::byte_utils;
3434

35-
use crate::{HashMap, hash_map, cmp, mem::replace, ops::Deref};
35+
use crate::{HashMap, hash_map};
36+
use core::{cmp, mem::replace, ops::Deref};
37+
38+
#[cfg(feature = "no_std")]
39+
#[macro_use]
40+
use alloc::{vec, vec::Vec};
3641

3742
const MAX_ALLOC_SIZE: usize = 64*1024;
3843

@@ -296,8 +301,8 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
296301

297302
let mut key_data = VecWriter(Vec::new());
298303
self.signer.write(&mut key_data)?;
299-
assert!(key_data.0.len() < crate::usize::MAX);
300-
assert!(key_data.0.len() < crate::u32::MAX as usize);
304+
assert!(key_data.0.len() < core::usize::MAX);
305+
assert!(key_data.0.len() < core::u32::MAX as usize);
301306
(key_data.0.len() as u32).write(writer)?;
302307
writer.write_all(&key_data.0[..])?;
303308

@@ -689,7 +694,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
689694
log_trace!(logger, "Updating claims view at height {} with {} matched transactions and {} claim requests", height, txn_matched.len(), claimable_outpoints.len());
690695
let mut new_claims = Vec::new();
691696
let mut aggregated_claim = HashMap::new();
692-
let mut aggregated_soonest = crate::u32::MAX;
697+
let mut aggregated_soonest = core::u32::MAX;
693698

694699
// Try to aggregate outputs if their timelock expiration isn't imminent (absolute_timelock
695700
// <= CLTV_SHARED_CLAIM_BUFFER) and they don't require an immediate nLockTime (aggregable).

lightning/src/ln/onion_route_tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ use bitcoin::hashes::Hash;
3232
use bitcoin::secp256k1::Secp256k1;
3333
use bitcoin::secp256k1::key::SecretKey;
3434

35-
use crate::{atomic::Ordering, default::Default};
35+
use core::{sync::atomic::Ordering, default::Default};
3636
use std::io;
3737

3838
use ln::functional_test_utils::*;

0 commit comments

Comments
 (0)