Mostly motivated by the need of async/await.
version = "0.0.1"
authors = ["Automatically generated"]
publish = false
+edition = "2018"
# Because the function is unused it gets dropped before we link lightning, so
# we have to duplicate build.rs here. Note that this is only required for
# fuzzing mode.
use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
use lightning::routing::router::{Route, RouteHop};
-use utils::test_logger::{self, Output};
-use utils::test_persister::TestPersister;
+use crate::utils::test_logger::{self, Output};
+use crate::utils::test_persister::TestPersister;
use bitcoin::secp256k1::{PublicKey, SecretKey, Scalar};
use bitcoin::secp256k1::ecdh::SharedSecret;
use lightning::util::ser::{ReadableArgs, Writer, Writeable};
use lightning::util::test_utils::OnlyReadsKeysInterface;
-use utils::test_logger;
+use crate::utils::test_logger;
use std::io::Cursor;
use lightning::util::logger::Logger;
use lightning::util::ser::ReadableArgs;
-use utils::test_logger;
-use utils::test_persister::TestPersister;
+use crate::utils::test_logger;
+use crate::utils::test_persister::TestPersister;
use bitcoin::secp256k1::{PublicKey, SecretKey, Scalar};
use bitcoin::secp256k1::ecdh::SharedSecret;
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_accept_channel_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_announcement_signatures_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_channel_announcement_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_channel_details_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_channel_ready_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_channel_reestablish_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_channel_update_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_closing_signed_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_commitment_signed_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_decoded_onion_error_packet_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_error_message_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_funding_created_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_funding_signed_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_gossip_timestamp_filter_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_init_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_node_announcement_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_onion_hop_data_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_open_channel_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_ping_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_pong_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_query_channel_range_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_query_short_channel_ids_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_reply_channel_range_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_reply_short_channel_ids_end_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_revoke_and_ack_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_shutdown_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn TARGET_NAME_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_update_add_htlc_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_update_fail_htlc_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_update_fail_malformed_htlc_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_update_fee_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_update_fulfill_htlc_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.
-use msg_targets::utils::VecWriter;
-use utils::test_logger;
+use crate::msg_targets::utils::VecWriter;
+use crate::utils::test_logger;
#[inline]
pub fn msg_warning_message_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
use lightning::util::ser::{MaybeReadableArgs, Readable, Writeable, Writer};
use lightning::onion_message::{CustomOnionMessageContents, CustomOnionMessageHandler, OnionMessenger};
-use utils::test_logger;
+use crate::utils::test_logger;
use std::io::{self, Cursor};
use std::sync::atomic::{AtomicU64, Ordering};
use bitcoin::secp256k1::{Secp256k1, PublicKey, SecretKey};
-use utils::test_logger;
+use crate::utils::test_logger;
#[inline]
fn slice_to_be16(v: &[u8]) -> u16 {
use lightning_rapid_gossip_sync::RapidGossipSync;
use bitcoin::hashes::Hash as TraitImport;
-use utils::test_logger;
+use crate::utils::test_logger;
/// Actual fuzz test, method signature and name are fixed
fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
use bitcoin::network::constants::Network;
use bitcoin::blockdata::constants::genesis_block;
-use utils::test_logger;
+use crate::utils::test_logger;
use std::convert::TryInto;
use std::collections::HashSet;
use lightning::util::zbase32;
-use utils::test_logger;
+use crate::utils::test_logger;
#[inline]
pub fn do_test(data: &[u8]) {
keywords = [ "lightning", "bitcoin", "invoice", "BOLT11" ]
readme = "README.md"
repository = "https://github.com/lightningdevkit/rust-lightning/"
+edition = "2018"
[package.metadata.docs.rs]
all-features = true
version = "0.0.1"
authors = ["Automatically generated"]
publish = false
+edition = "2018"
[package.metadata]
cargo-fuzz = true
type Err = ParseError;
fn from_str(currency_prefix: &str) -> Result<Self, ParseError> {
- use SiPrefix::*;
+ use crate::SiPrefix::*;
match currency_prefix {
"m" => Ok(Milli),
"u" => Ok(Micro),
}
}
-impl From<::SemanticError> for ParseOrSemanticError {
+impl From<crate::SemanticError> for ParseOrSemanticError {
fn from(e: SemanticError) -> Self {
ParseOrSemanticError::SemanticError(e)
}
#[cfg(test)]
mod test {
- use de::ParseError;
+ use crate::de::ParseError;
use secp256k1::PublicKey;
use bech32::u5;
use bitcoin_hashes::hex::FromHex;
#[test]
fn test_parse_currency_prefix() {
- use Currency;
+ use crate::Currency;
assert_eq!("bc".parse::<Currency>(), Ok(Currency::Bitcoin));
assert_eq!("tb".parse::<Currency>(), Ok(Currency::BitcoinTestnet));
#[test]
fn test_parse_int_from_bytes_be() {
- use de::parse_int_be;
+ use crate::de::parse_int_be;
assert_eq!(parse_int_be::<u32, u8>(&[1, 2, 3, 4], 256), Some(16909060));
assert_eq!(parse_int_be::<u32, u8>(&[1, 3], 32), Some(35));
#[test]
fn test_parse_sha256_hash() {
- use Sha256;
+ use crate::Sha256;
use bech32::FromBase32;
let input = from_bech32(
#[test]
fn test_parse_description() {
- use ::Description;
+ use crate::Description;
use bech32::FromBase32;
let input = from_bech32("xysxxatsyp3k7enxv4js".as_bytes());
#[test]
fn test_parse_payee_pub_key() {
- use ::PayeePubKey;
+ use crate::PayeePubKey;
use bech32::FromBase32;
let input = from_bech32("q0n326hr8v9zprg8gsvezcch06gfaqqhde2aj730yg0durunfhv66".as_bytes());
#[test]
fn test_parse_expiry_time() {
- use ::ExpiryTime;
+ use crate::ExpiryTime;
use bech32::FromBase32;
let input = from_bech32("pu".as_bytes());
#[test]
fn test_parse_min_final_cltv_expiry() {
- use ::MinFinalCltvExpiry;
+ use crate::MinFinalCltvExpiry;
use bech32::FromBase32;
let input = from_bech32("pr".as_bytes());
#[test]
fn test_parse_fallback() {
- use Fallback;
+ use crate::Fallback;
use bech32::FromBase32;
let cases = vec![
fn test_parse_route() {
use lightning::routing::gossip::RoutingFees;
use lightning::routing::router::{RouteHint, RouteHintHop};
- use ::PrivateRoute;
+ use crate::PrivateRoute;
use bech32::FromBase32;
- use de::parse_int_be;
+ use crate::de::parse_int_be;
let input = from_bech32(
"q20q82gphp2nflc7jtzrcazrra7wwgzxqc8u7754cdlpfrmccae92qgzqvzq2ps8pqqqqqqpqqqqq9qqqvpeuqa\
fn test_payment_secret_and_features_de_and_ser() {
use lightning::ln::features::InvoiceFeatures;
use secp256k1::ecdsa::{RecoveryId, RecoverableSignature};
- use TaggedField::*;
- use {SiPrefix, SignedRawInvoice, InvoiceSignature, RawInvoice, RawHrp, RawDataPart,
+ use crate::TaggedField::*;
+ use crate::{SiPrefix, SignedRawInvoice, InvoiceSignature, RawInvoice, RawHrp, RawDataPart,
Currency, Sha256, PositiveTimestamp};
// Feature bits 9, 15, and 99 are set.
PaymentHash(Sha256(sha256::Hash::from_hex(
"0001020304050607080900010203040506070809000102030405060708090102"
).unwrap())).into(),
- Description(::Description::new("coffee beans".to_owned()).unwrap()).into(),
- PaymentSecret(::PaymentSecret([17; 32])).into(),
+ Description(crate::Description::new("coffee beans".to_owned()).unwrap()).into(),
+ PaymentSecret(crate::PaymentSecret([17; 32])).into(),
Features(expected_features).into()]}
},
hash: [0xb1, 0x96, 0x46, 0xc3, 0xbc, 0x56, 0x76, 0x1d, 0x20, 0x65, 0x6e, 0x0e, 0x32,
#[test]
fn test_raw_signed_invoice_deserialization() {
- use TaggedField::*;
+ use crate::TaggedField::*;
use secp256k1::ecdsa::{RecoveryId, RecoverableSignature};
- use {SignedRawInvoice, InvoiceSignature, RawInvoice, RawHrp, RawDataPart, Currency, Sha256,
+ use crate::{SignedRawInvoice, InvoiceSignature, RawInvoice, RawHrp, RawDataPart, Currency, Sha256,
PositiveTimestamp};
assert_eq!(
"0001020304050607080900010203040506070809000102030405060708090102"
).unwrap())).into(),
Description(
- ::Description::new(
+ crate::Description::new(
"Please consider supporting this project".to_owned()
).unwrap()
).into(),
pub use alloc::string::ToString;
}
-use prelude::*;
+use crate::prelude::*;
/// Sync compat for std/no_std
#[cfg(feature = "std")]
ParseError(ParseError),
/// The invoice could be decoded but violates the BOLT11 standard
- SemanticError(::SemanticError),
+ SemanticError(crate::SemanticError),
}
/// The number of bits used to represent timestamps as defined in BOLT 11.
/// (C-not exported) As we don't yet support a slice of enums, and also because this function
/// isn't the most critical to expose.
pub fn values_desc() -> &'static [SiPrefix] {
- use SiPrefix::*;
+ use crate::SiPrefix::*;
static VALUES: [SiPrefix; 4] = [Milli, Micro, Nano, Pico];
&VALUES
}
#[test]
fn test_system_time_bounds_assumptions() {
assert_eq!(
- ::PositiveTimestamp::from_unix_timestamp(::MAX_TIMESTAMP + 1),
- Err(::CreationError::TimestampOutOfBounds)
+ crate::PositiveTimestamp::from_unix_timestamp(crate::MAX_TIMESTAMP + 1),
+ Err(crate::CreationError::TimestampOutOfBounds)
);
}
#[test]
fn test_calc_invoice_hash() {
- use ::{RawInvoice, RawHrp, RawDataPart, Currency, PositiveTimestamp};
- use ::TaggedField::*;
+ use crate::{RawInvoice, RawHrp, RawDataPart, Currency, PositiveTimestamp};
+ use crate::TaggedField::*;
let invoice = RawInvoice {
hrp: RawHrp {
data: RawDataPart {
timestamp: PositiveTimestamp::from_unix_timestamp(1496314658).unwrap(),
tagged_fields: vec![
- PaymentHash(::Sha256(sha256::Hash::from_hex(
+ PaymentHash(crate::Sha256(sha256::Hash::from_hex(
"0001020304050607080900010203040506070809000102030405060708090102"
).unwrap())).into(),
- Description(::Description::new(
+ Description(crate::Description::new(
"Please consider supporting this project".to_owned()
).unwrap()).into(),
],
#[test]
fn test_check_signature() {
- use TaggedField::*;
+ use crate::TaggedField::*;
use secp256k1::Secp256k1;
use secp256k1::ecdsa::{RecoveryId, RecoverableSignature};
use secp256k1::{SecretKey, PublicKey};
- use {SignedRawInvoice, InvoiceSignature, RawInvoice, RawHrp, RawDataPart, Currency, Sha256,
+ use crate::{SignedRawInvoice, InvoiceSignature, RawInvoice, RawHrp, RawDataPart, Currency, Sha256,
PositiveTimestamp};
let invoice = SignedRawInvoice {
"0001020304050607080900010203040506070809000102030405060708090102"
).unwrap())).into(),
Description(
- ::Description::new(
+ crate::Description::new(
"Please consider supporting this project".to_owned()
).unwrap()
).into(),
).unwrap();
let public_key = PublicKey::from_secret_key(&Secp256k1::new(), &private_key);
- assert_eq!(invoice.recover_payee_pub_key(), Ok(::PayeePubKey(public_key)));
+ assert_eq!(invoice.recover_payee_pub_key(), Ok(crate::PayeePubKey(public_key)));
let (raw_invoice, _, _) = invoice.into_parts();
let new_signed = raw_invoice.sign::<_, ()>(|hash| {
#[test]
fn test_check_feature_bits() {
- use TaggedField::*;
+ use crate::TaggedField::*;
use lightning::ln::features::InvoiceFeatures;
use secp256k1::Secp256k1;
use secp256k1::SecretKey;
- use {RawInvoice, RawHrp, RawDataPart, Currency, Sha256, PositiveTimestamp, Invoice,
+ use crate::{RawInvoice, RawHrp, RawDataPart, Currency, Sha256, PositiveTimestamp, Invoice,
SemanticError};
let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
"0001020304050607080900010203040506070809000102030405060708090102"
).unwrap())).into(),
Description(
- ::Description::new(
+ crate::Description::new(
"Please consider supporting this project".to_owned()
).unwrap()
).into(),
#[test]
fn test_builder_amount() {
- use ::*;
+ use crate::*;
let builder = InvoiceBuilder::new(Currency::Bitcoin)
.description("Test".into())
#[test]
fn test_builder_fail() {
- use ::*;
+ use crate::*;
use lightning::routing::router::RouteHintHop;
use std::iter::FromIterator;
use secp256k1::PublicKey;
#[test]
fn test_builder_ok() {
- use ::*;
+ use crate::*;
use lightning::routing::router::RouteHintHop;
use secp256k1::Secp256k1;
use secp256k1::{SecretKey, PublicKey};
#[test]
fn test_default_values() {
- use ::*;
+ use crate::*;
use secp256k1::Secp256k1;
use secp256k1::SecretKey;
#[test]
fn test_expiration() {
- use ::*;
+ use crate::*;
use secp256k1::Secp256k1;
use secp256k1::SecretKey;
use lightning::util::events::{Event, EventHandler};
use lightning::util::logger::Logger;
use lightning::util::ser::Writeable;
-use time_utils::Time;
+use crate::time_utils::Time;
use crate::sync::Mutex;
use secp256k1::PublicKey;
#[cfg(not(feature = "no-std"))]
type ConfiguredTime = std::time::Instant;
#[cfg(feature = "no-std")]
-use time_utils;
+use crate::time_utils;
#[cfg(feature = "no-std")]
type ConfiguredTime = time_utils::Eternity;
mod tests {
use super::*;
use crate::{InvoiceBuilder, Currency};
- use utils::{ScorerAccountingForInFlightHtlcs, create_invoice_from_channelmanager_and_duration_since_epoch};
+ use crate::utils::{ScorerAccountingForInFlightHtlcs, create_invoice_from_channelmanager_and_duration_since_epoch};
use bitcoin_hashes::sha256::Hash as Sha256;
use lightning::ln::PaymentPreimage;
use lightning::ln::channelmanager;
use std::collections::VecDeque;
use std::ops::DerefMut;
use std::time::{SystemTime, Duration};
- use time_utils::tests::SinceEpoch;
- use DEFAULT_EXPIRY_TIME;
+ use crate::time_utils::tests::SinceEpoch;
+ use crate::DEFAULT_EXPIRY_TIME;
use lightning::util::errors::APIError::{ChannelUnavailable, MonitorUpdateInProgress};
fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
#[test]
fn test_currency_code() {
- use Currency;
+ use crate::Currency;
assert_eq!("bc", Currency::Bitcoin.to_string());
assert_eq!("tb", Currency::BitcoinTestnet.to_string());
#[test]
fn test_raw_hrp() {
- use ::{Currency, RawHrp, SiPrefix};
+ use crate::{Currency, RawHrp, SiPrefix};
let hrp = RawHrp {
currency: Currency::Bitcoin,
#[test]
fn test_encode_int_be_base32() {
- use ser::encode_int_be_base32;
+ use crate::ser::encode_int_be_base32;
let input: u64 = 33764;
let expected_out = CheckBase32::check_base32(&[1, 0, 31, 4]).unwrap();
#[test]
fn test_encode_int_be_base256() {
- use ser::encode_int_be_base256;
+ use crate::ser::encode_int_be_base256;
let input: u64 = 16842530;
let expected_out = vec![1, 0, 255, 34];
//! Convenient utilities to create an invoice.
-use {CreationError, Currency, Invoice, InvoiceBuilder, SignOrCreationError};
-use payment::{InFlightHtlcs, Payer, Router};
+use crate::{CreationError, Currency, Invoice, InvoiceBuilder, SignOrCreationError};
+use crate::payment::{InFlightHtlcs, Payer, Router};
use crate::{prelude::*, Description, InvoiceDescription, Sha256};
use bech32::ToBase32;
use secp256k1::PublicKey;
use core::ops::Deref;
use core::time::Duration;
-use sync::Mutex;
+use crate::sync::Mutex;
#[cfg(feature = "std")]
/// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
#[cfg(test)]
mod test {
use core::time::Duration;
- use {Currency, Description, InvoiceDescription};
+ use crate::{Currency, Description, InvoiceDescription};
use bitcoin_hashes::Hash;
use bitcoin_hashes::sha256::Hash as Sha256;
use lightning::chain::keysinterface::PhantomKeysManager;
use lightning::util::test_utils;
use lightning::util::config::UserConfig;
use lightning::chain::keysinterface::KeysInterface;
- use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
+ use crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch;
use std::collections::HashSet;
#[test]
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
let description_hash = crate::Sha256(Hash::hash("Testing description_hash".as_bytes()));
- let invoice = ::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
+ let invoice = crate::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
&nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
Some(10_000), description_hash, Duration::from_secs(1234567), 3600
).unwrap();
let non_default_invoice_expiry_secs = 4200;
let invoice =
- ::utils::create_phantom_invoice::<EnforcingSigner, &test_utils::TestKeysInterface, &test_utils::TestLogger>(
+ crate::utils::create_phantom_invoice::<EnforcingSigner, &test_utils::TestKeysInterface, &test_utils::TestLogger>(
Some(payment_amt), payment_hash, "test".to_string(), non_default_invoice_expiry_secs,
route_hints, &nodes[1].keys_manager, &nodes[1].logger, Currency::BitcoinTestnet
).unwrap();
nodes[2].node.get_phantom_route_hints(),
];
- let invoice = ::utils::create_phantom_invoice::<EnforcingSigner, &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), Some(payment_hash), "test".to_string(), 3600, route_hints, &nodes[1].keys_manager, &nodes[1].logger, Currency::BitcoinTestnet).unwrap();
+ let invoice = crate::utils::create_phantom_invoice::<EnforcingSigner, &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), Some(payment_hash), "test".to_string(), 3600, route_hints, &nodes[1].keys_manager, &nodes[1].logger, Currency::BitcoinTestnet).unwrap();
let chan_0_1 = &nodes[1].node.list_usable_channels()[0];
assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan_0_1.inbound_htlc_minimum_msat);
let description_hash = crate::Sha256(Hash::hash("Description hash phantom invoice".as_bytes()));
let non_default_invoice_expiry_secs = 4200;
- let invoice = ::utils::create_phantom_invoice_with_description_hash::<
+ let invoice = crate::utils::create_phantom_invoice_with_description_hash::<
EnforcingSigner, &test_utils::TestKeysInterface, &test_utils::TestLogger,
>(
Some(payment_amt), None, non_default_invoice_expiry_secs, description_hash,
.map(|route_hint| route_hint.phantom_scid)
.collect::<HashSet<u64>>();
- let invoice = ::utils::create_phantom_invoice::<EnforcingSigner, &test_utils::TestKeysInterface, &test_utils::TestLogger>(invoice_amt, None, "test".to_string(), 3600, phantom_route_hints, &invoice_node.keys_manager, &invoice_node.logger, Currency::BitcoinTestnet).unwrap();
+ let invoice = crate::utils::create_phantom_invoice::<EnforcingSigner, &test_utils::TestKeysInterface, &test_utils::TestLogger>(invoice_amt, None, "test".to_string(), 3600, phantom_route_hints, &invoice_node.keys_manager, &invoice_node.logger, Currency::BitcoinTestnet).unwrap();
let invoice_hints = invoice.private_routes();
description = """
Utilities to manage Rust-Lightning channel data persistence and retrieval.
"""
+edition = "2018"
[package.metadata.docs.rs]
all-features = true
Does most of the hard work, without implying a specific runtime, requiring clients implement basic network logic, chain interactions and disk storage.
Still missing tons of error-handling. See GitHub issues for suggested projects if you want to contribute. Don't have to bother telling you not to use this for anything serious, because you'd have to build a client around it to even try.
"""
+edition = "2018"
[package.metadata.docs.rs]
features = ["std"]
use bitcoin::blockdata::block::BlockHeader;
use bitcoin::hash_types::Txid;
-use chain;
-use chain::{ChannelMonitorUpdateStatus, Filter, WatchedOutput};
-use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
-use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, Balance, MonitorEvent, TransactionOutputs, LATENCY_GRACE_PERIOD_BLOCKS};
-use chain::transaction::{OutPoint, TransactionData};
-use chain::keysinterface::Sign;
-use util::atomic_counter::AtomicCounter;
-use util::logger::Logger;
-use util::errors::APIError;
-use util::events;
-use util::events::EventHandler;
-use ln::channelmanager::ChannelDetails;
-
-use prelude::*;
-use sync::{RwLock, RwLockReadGuard, Mutex, MutexGuard};
+use crate::chain;
+use crate::chain::{ChannelMonitorUpdateStatus, Filter, WatchedOutput};
+use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
+use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, Balance, MonitorEvent, TransactionOutputs, LATENCY_GRACE_PERIOD_BLOCKS};
+use crate::chain::transaction::{OutPoint, TransactionData};
+use crate::chain::keysinterface::Sign;
+use crate::util::atomic_counter::AtomicCounter;
+use crate::util::logger::Logger;
+use crate::util::errors::APIError;
+use crate::util::events;
+use crate::util::events::EventHandler;
+use crate::ln::channelmanager::ChannelDetails;
+
+use crate::prelude::*;
+use crate::sync::{RwLock, RwLockReadGuard, Mutex, MutexGuard};
use core::ops::Deref;
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use bitcoin::secp256k1::PublicKey;
#[cfg(any(test, fuzzing, feature = "_test_utils"))]
pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
- use util::events::EventsProvider;
+ use crate::util::events::EventsProvider;
let events = core::cell::RefCell::new(Vec::new());
let event_handler = |event: &events::Event| events.borrow_mut().push(event.clone());
self.process_pending_events(&event_handler);
mod tests {
use bitcoin::{BlockHeader, TxMerkleNode};
use bitcoin::hashes::Hash;
- use ::{check_added_monitors, check_closed_broadcast, check_closed_event};
- use ::{expect_payment_sent, expect_payment_claimed, expect_payment_sent_without_paths, expect_payment_path_successful, get_event_msg};
- use ::{get_htlc_update_msgs, get_local_commitment_txn, get_revoke_commit_msgs, get_route_and_payment_hash, unwrap_send_err};
- use chain::{ChannelMonitorUpdateStatus, Confirm, Watch};
- use chain::channelmonitor::LATENCY_GRACE_PERIOD_BLOCKS;
- use ln::channelmanager::{self, PaymentSendFailure};
- use ln::functional_test_utils::*;
- use ln::msgs::ChannelMessageHandler;
- use util::errors::APIError;
- use util::events::{ClosureReason, MessageSendEvent, MessageSendEventsProvider};
+ use crate::{check_added_monitors, check_closed_broadcast, check_closed_event};
+ use crate::{expect_payment_sent, expect_payment_claimed, expect_payment_sent_without_paths, expect_payment_path_successful, get_event_msg};
+ use crate::{get_htlc_update_msgs, get_local_commitment_txn, get_revoke_commit_msgs, get_route_and_payment_hash, unwrap_send_err};
+ use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Watch};
+ use crate::chain::channelmonitor::LATENCY_GRACE_PERIOD_BLOCKS;
+ use crate::ln::channelmanager::{self, PaymentSendFailure};
+ use crate::ln::functional_test_utils::*;
+ use crate::ln::msgs::ChannelMessageHandler;
+ use crate::util::errors::APIError;
+ use crate::util::events::{ClosureReason, MessageSendEvent, MessageSendEventsProvider};
#[test]
fn test_async_ooo_offchain_updates() {
use bitcoin::secp256k1::{SecretKey, PublicKey};
use bitcoin::secp256k1;
-use ln::{PaymentHash, PaymentPreimage};
-use ln::msgs::DecodeError;
-use ln::chan_utils;
-use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCClaim, ChannelTransactionParameters, HolderCommitmentTransaction};
-use ln::channelmanager::HTLCSource;
-use chain;
-use chain::{BestBlock, WatchedOutput};
-use chain::chaininterface::{BroadcasterInterface, FeeEstimator, LowerBoundedFeeEstimator};
-use chain::transaction::{OutPoint, TransactionData};
-use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, Sign, KeysInterface};
+use crate::ln::{PaymentHash, PaymentPreimage};
+use crate::ln::msgs::DecodeError;
+use crate::ln::chan_utils;
+use crate::ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCClaim, ChannelTransactionParameters, HolderCommitmentTransaction};
+use crate::ln::channelmanager::HTLCSource;
+use crate::chain;
+use crate::chain::{BestBlock, WatchedOutput};
+use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator, LowerBoundedFeeEstimator};
+use crate::chain::transaction::{OutPoint, TransactionData};
+use crate::chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, Sign, KeysInterface};
#[cfg(anchors)]
-use chain::onchaintx::ClaimEvent;
-use chain::onchaintx::OnchainTxHandler;
-use chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedOutput, RevokedHTLCOutput};
-use chain::Filter;
-use util::logger::Logger;
-use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48, OptionDeserWrapper};
-use util::byte_utils;
-use util::events::Event;
+use crate::chain::onchaintx::ClaimEvent;
+use crate::chain::onchaintx::OnchainTxHandler;
+use crate::chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedOutput, RevokedHTLCOutput};
+use crate::chain::Filter;
+use crate::util::logger::Logger;
+use crate::util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48, OptionDeserWrapper};
+use crate::util::byte_utils;
+use crate::util::events::Event;
#[cfg(anchors)]
-use util::events::{AnchorDescriptor, BumpTransactionEvent};
+use crate::util::events::{AnchorDescriptor, BumpTransactionEvent};
-use prelude::*;
+use crate::prelude::*;
use core::{cmp, mem};
-use io::{self, Error};
+use crate::io::{self, Error};
use core::convert::TryInto;
use core::ops::Deref;
-use sync::Mutex;
+use crate::sync::Mutex;
/// An update generated by the underlying channel itself which contains some new information the
/// [`ChannelMonitor`] should be made aware of.
use crate::chain::chaininterface::LowerBoundedFeeEstimator;
use super::ChannelMonitorUpdateStep;
- use ::{check_added_monitors, check_closed_broadcast, check_closed_event, check_spends, get_local_commitment_txn, get_monitor, get_route_and_payment_hash, unwrap_send_err};
- use chain::{BestBlock, Confirm};
- use chain::channelmonitor::ChannelMonitor;
- use chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
- use chain::transaction::OutPoint;
- use chain::keysinterface::InMemorySigner;
- use ln::{PaymentPreimage, PaymentHash};
- use ln::chan_utils;
- use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
- use ln::channelmanager::{self, PaymentSendFailure};
- use ln::functional_test_utils::*;
- use ln::script::ShutdownScript;
- use util::errors::APIError;
- use util::events::{ClosureReason, MessageSendEventsProvider};
- use util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
- use util::ser::{ReadableArgs, Writeable};
- use sync::{Arc, Mutex};
- use io;
+ use crate::{check_added_monitors, check_closed_broadcast, check_closed_event, check_spends, get_local_commitment_txn, get_monitor, get_route_and_payment_hash, unwrap_send_err};
+ use crate::chain::{BestBlock, Confirm};
+ use crate::chain::channelmonitor::ChannelMonitor;
+ use crate::chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
+ use crate::chain::transaction::OutPoint;
+ use crate::chain::keysinterface::InMemorySigner;
+ use crate::ln::{PaymentPreimage, PaymentHash};
+ use crate::ln::chan_utils;
+ use crate::ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
+ use crate::ln::channelmanager::{self, PaymentSendFailure};
+ use crate::ln::functional_test_utils::*;
+ use crate::ln::script::ShutdownScript;
+ use crate::util::errors::APIError;
+ use crate::util::events::{ClosureReason, MessageSendEventsProvider};
+ use crate::util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
+ use crate::util::ser::{ReadableArgs, Writeable};
+ use crate::sync::{Arc, Mutex};
+ use crate::io;
use bitcoin::{PackedLockTime, Sequence, TxMerkleNode, Witness};
- use prelude::*;
+ use crate::prelude::*;
fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
// Previously, monitor updates were allowed freely even after a funding-spend transaction
use bitcoin::secp256k1::ecdsa::RecoverableSignature;
use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness};
-use util::{byte_utils, transaction_utils};
-use util::crypto::{hkdf_extract_expand_twice, sign};
-use util::ser::{Writeable, Writer, Readable, ReadableArgs};
-
-use chain::transaction::OutPoint;
-use ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
-use ln::{chan_utils, PaymentPreimage};
-use ln::chan_utils::{HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, HolderCommitmentTransaction, ChannelTransactionParameters, CommitmentTransaction, ClosingTransaction};
-use ln::msgs::UnsignedChannelAnnouncement;
-use ln::script::ShutdownScript;
-
-use prelude::*;
+use crate::util::{byte_utils, transaction_utils};
+use crate::util::crypto::{hkdf_extract_expand_twice, sign};
+use crate::util::ser::{Writeable, Writer, Readable, ReadableArgs};
+
+use crate::chain::transaction::OutPoint;
+use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
+use crate::ln::{chan_utils, PaymentPreimage};
+use crate::ln::chan_utils::{HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, HolderCommitmentTransaction, ChannelTransactionParameters, CommitmentTransaction, ClosingTransaction};
+use crate::ln::msgs::UnsignedChannelAnnouncement;
+use crate::ln::script::ShutdownScript;
+
+use crate::prelude::*;
use core::sync::atomic::{AtomicUsize, Ordering};
-use io::{self, Error};
-use ln::msgs::{DecodeError, MAX_VALUE_MSAT};
-use util::invoice::construct_invoice_preimage;
+use crate::io::{self, Error};
+use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
+use crate::util::invoice::construct_invoice_preimage;
/// Used as initial key material, to be expanded into multiple secret keys (but not to be used
/// directly). This is used within LDK to encrypt/decrypt inbound payment data.
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::PublicKey;
-use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, MonitorEvent};
-use chain::keysinterface::Sign;
-use chain::transaction::{OutPoint, TransactionData};
+use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, MonitorEvent};
+use crate::chain::keysinterface::Sign;
+use crate::chain::transaction::{OutPoint, TransactionData};
-use prelude::*;
+use crate::prelude::*;
pub mod chaininterface;
pub mod chainmonitor;
use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
use bitcoin::secp256k1;
-use ln::msgs::DecodeError;
-use ln::PaymentPreimage;
+use crate::ln::msgs::DecodeError;
+use crate::ln::PaymentPreimage;
#[cfg(anchors)]
-use ln::chan_utils;
-use ln::chan_utils::{ChannelTransactionParameters, HolderCommitmentTransaction};
+use crate::ln::chan_utils;
+use crate::ln::chan_utils::{ChannelTransactionParameters, HolderCommitmentTransaction};
#[cfg(anchors)]
-use chain::chaininterface::ConfirmationTarget;
-use chain::chaininterface::{FeeEstimator, BroadcasterInterface, LowerBoundedFeeEstimator};
-use chain::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER};
-use chain::keysinterface::{Sign, KeysInterface};
+use crate::chain::chaininterface::ConfirmationTarget;
+use crate::chain::chaininterface::{FeeEstimator, BroadcasterInterface, LowerBoundedFeeEstimator};
+use crate::chain::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER};
+use crate::chain::keysinterface::{Sign, KeysInterface};
#[cfg(anchors)]
-use chain::package::PackageSolvingData;
-use chain::package::PackageTemplate;
-use util::logger::Logger;
-use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, VecWriter};
-use util::byte_utils;
-
-use io;
-use prelude::*;
+use crate::chain::package::PackageSolvingData;
+use crate::chain::package::PackageTemplate;
+use crate::util::logger::Logger;
+use crate::util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, VecWriter};
+use crate::util::byte_utils;
+
+use crate::io;
+use crate::prelude::*;
use alloc::collections::BTreeMap;
use core::cmp;
use core::ops::Deref;
use bitcoin::secp256k1::{SecretKey,PublicKey};
-use ln::PaymentPreimage;
-use ln::chan_utils::{TxCreationKeys, HTLCOutputInCommitment};
-use ln::chan_utils;
-use ln::msgs::DecodeError;
-use chain::chaininterface::{FeeEstimator, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
-use chain::keysinterface::Sign;
-use chain::onchaintx::OnchainTxHandler;
-use util::byte_utils;
-use util::logger::Logger;
-use util::ser::{Readable, Writer, Writeable};
-
-use io;
-use prelude::*;
+use crate::ln::PaymentPreimage;
+use crate::ln::chan_utils::{TxCreationKeys, HTLCOutputInCommitment};
+use crate::ln::chan_utils;
+use crate::ln::msgs::DecodeError;
+use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
+use crate::chain::keysinterface::Sign;
+use crate::chain::onchaintx::OnchainTxHandler;
+use crate::util::byte_utils;
+use crate::util::logger::Logger;
+use crate::util::ser::{Readable, Writer, Writeable};
+
+use crate::io;
+use crate::prelude::*;
use core::cmp;
#[cfg(anchors)]
use core::convert::TryInto;
#[cfg(test)]
mod tests {
- use chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderHTLCOutput, PackageTemplate, PackageSolvingData, RevokedOutput, WEIGHT_REVOKED_OUTPUT, weight_offered_htlc, weight_received_htlc};
- use chain::Txid;
- use ln::chan_utils::HTLCOutputInCommitment;
- use ln::{PaymentPreimage, PaymentHash};
+ use crate::chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderHTLCOutput, PackageTemplate, PackageSolvingData, RevokedOutput, WEIGHT_REVOKED_OUTPUT, weight_offered_htlc, weight_received_htlc};
+ use crate::chain::Txid;
+ use crate::ln::chan_utils::HTLCOutputInCommitment;
+ use crate::ln::{PaymentPreimage, PaymentHash};
use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
use bitcoin::blockdata::script::Script;
#[cfg(test)]
mod tests {
- use chain::transaction::OutPoint;
+ use crate::chain::transaction::OutPoint;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::consensus::encode;
use std::sync::RwLockWriteGuard as StdRwLockWriteGuard;
use std::sync::Condvar as StdCondvar;
-use prelude::HashMap;
+use crate::prelude::HashMap;
#[cfg(feature = "backtrace")]
-use {prelude::hash_map, backtrace::Backtrace, std::sync::Once};
+use {crate::prelude::hash_map, backtrace::Backtrace, std::sync::Once};
#[cfg(not(feature = "backtrace"))]
struct Backtrace{}
#[cfg(feature = "std")]
mod sync {
#[cfg(all(not(feature = "_bench_unstable"), test))]
- pub use debug_sync::*;
+ pub use crate::debug_sync::*;
#[cfg(any(feature = "_bench_unstable", not(test)))]
pub use ::std::sync::{Arc, Mutex, Condvar, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
#[cfg(any(feature = "_bench_unstable", not(test)))]
use bitcoin::hashes::ripemd160::Hash as Ripemd160;
use bitcoin::hash_types::{Txid, PubkeyHash};
-use ln::{PaymentHash, PaymentPreimage};
-use ln::msgs::DecodeError;
-use util::ser::{Readable, Writeable, Writer};
-use util::{byte_utils, transaction_utils};
+use crate::ln::{PaymentHash, PaymentPreimage};
+use crate::ln::msgs::DecodeError;
+use crate::util::ser::{Readable, Writeable, Writer};
+use crate::util::{byte_utils, transaction_utils};
use bitcoin::hash_types::WPubkeyHash;
use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar};
use bitcoin::secp256k1::Error as SecpError;
use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness};
-use io;
-use prelude::*;
+use crate::io;
+use crate::prelude::*;
use core::cmp;
-use ln::chan_utils;
-use util::transaction_utils::sort_outputs;
-use ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
+use crate::ln::chan_utils;
+use crate::util::transaction_utils::sort_outputs;
+use crate::ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
use core::ops::Deref;
-use chain;
-use util::crypto::sign;
+use crate::chain;
+use crate::util::crypto::sign;
pub(crate) const MAX_HTLCS: u16 = 483;
pub(crate) const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
#[cfg(test)]
mod tests {
use super::CounterpartyCommitmentSecrets;
- use ::{hex, chain};
- use prelude::*;
- use ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, get_p2wpkh_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
+ use crate::{hex, chain};
+ use crate::prelude::*;
+ use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, get_p2wpkh_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
- use util::test_utils;
- use chain::keysinterface::{KeysInterface, BaseSign};
+ use crate::util::test_utils;
+ use crate::chain::keysinterface::{KeysInterface, BaseSign};
use bitcoin::{Network, Txid};
use bitcoin::hashes::Hash;
- use ln::PaymentHash;
+ use crate::ln::PaymentHash;
use bitcoin::hashes::hex::ToHex;
#[test]
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::hash_types::BlockHash;
use bitcoin::network::constants::Network;
-use chain::channelmonitor::{ANTI_REORG_DELAY, ChannelMonitor};
-use chain::transaction::OutPoint;
-use chain::{ChannelMonitorUpdateStatus, Listen, Watch};
-use ln::channelmanager::{self, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure};
-use ln::channel::AnnouncementSigsState;
-use ln::msgs;
-use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler};
-use util::config::UserConfig;
-use util::enforcing_trait_impls::EnforcingSigner;
-use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason, HTLCDestination};
-use util::errors::APIError;
-use util::ser::{ReadableArgs, Writeable};
-use util::test_utils::TestBroadcaster;
-
-use ln::functional_test_utils::*;
-
-use util::test_utils;
-
-use io;
+use crate::chain::channelmonitor::{ANTI_REORG_DELAY, ChannelMonitor};
+use crate::chain::transaction::OutPoint;
+use crate::chain::{ChannelMonitorUpdateStatus, Listen, Watch};
+use crate::ln::channelmanager::{self, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure};
+use crate::ln::channel::AnnouncementSigsState;
+use crate::ln::msgs;
+use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler};
+use crate::util::config::UserConfig;
+use crate::util::enforcing_trait_impls::EnforcingSigner;
+use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason, HTLCDestination};
+use crate::util::errors::APIError;
+use crate::util::ser::{ReadableArgs, Writeable};
+use crate::util::test_utils::TestBroadcaster;
+
+use crate::ln::functional_test_utils::*;
+
+use crate::util::test_utils;
+
+use crate::io;
use bitcoin::hashes::Hash;
use bitcoin::TxMerkleNode;
-use prelude::*;
-use sync::{Arc, Mutex};
+use crate::prelude::*;
+use crate::sync::{Arc, Mutex};
#[test]
fn test_simple_monitor_permanent_update_fail() {
use bitcoin::secp256k1::{Secp256k1,ecdsa::Signature};
use bitcoin::secp256k1;
-use ln::{PaymentPreimage, PaymentHash};
-use ln::features::{ChannelTypeFeatures, InitFeatures};
-use ln::msgs;
-use ln::msgs::{DecodeError, OptionalField, DataLossProtect};
-use ln::script::{self, ShutdownScript};
-use ln::channelmanager::{self, CounterpartyForwardingInfo, PendingHTLCStatus, HTLCSource, HTLCFailReason, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, MAX_LOCAL_BREAKDOWN_TIMEOUT};
-use ln::chan_utils::{CounterpartyCommitmentSecrets, TxCreationKeys, HTLCOutputInCommitment, htlc_success_tx_weight, htlc_timeout_tx_weight, make_funding_redeemscript, ChannelPublicKeys, CommitmentTransaction, HolderCommitmentTransaction, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, MAX_HTLCS, get_commitment_transaction_number_obscure_factor, ClosingTransaction};
-use ln::chan_utils;
-use chain::BestBlock;
-use chain::chaininterface::{FeeEstimator, ConfirmationTarget, LowerBoundedFeeEstimator};
-use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, LATENCY_GRACE_PERIOD_BLOCKS};
-use chain::transaction::{OutPoint, TransactionData};
-use chain::keysinterface::{Sign, KeysInterface};
-use util::events::ClosureReason;
-use util::ser::{Readable, ReadableArgs, Writeable, Writer, VecWriter};
-use util::logger::Logger;
-use util::errors::APIError;
-use util::config::{UserConfig, ChannelConfig, LegacyChannelConfig, ChannelHandshakeConfig, ChannelHandshakeLimits};
-use util::scid_utils::scid_from_parts;
-
-use io;
-use prelude::*;
+use crate::ln::{PaymentPreimage, PaymentHash};
+use crate::ln::features::{ChannelTypeFeatures, InitFeatures};
+use crate::ln::msgs;
+use crate::ln::msgs::{DecodeError, OptionalField, DataLossProtect};
+use crate::ln::script::{self, ShutdownScript};
+use crate::ln::channelmanager::{self, CounterpartyForwardingInfo, PendingHTLCStatus, HTLCSource, HTLCFailReason, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, MAX_LOCAL_BREAKDOWN_TIMEOUT};
+use crate::ln::chan_utils::{CounterpartyCommitmentSecrets, TxCreationKeys, HTLCOutputInCommitment, htlc_success_tx_weight, htlc_timeout_tx_weight, make_funding_redeemscript, ChannelPublicKeys, CommitmentTransaction, HolderCommitmentTransaction, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, MAX_HTLCS, get_commitment_transaction_number_obscure_factor, ClosingTransaction};
+use crate::ln::chan_utils;
+use crate::chain::BestBlock;
+use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, LowerBoundedFeeEstimator};
+use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, LATENCY_GRACE_PERIOD_BLOCKS};
+use crate::chain::transaction::{OutPoint, TransactionData};
+use crate::chain::keysinterface::{Sign, KeysInterface};
+use crate::util::events::ClosureReason;
+use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer, VecWriter};
+use crate::util::logger::Logger;
+use crate::util::errors::APIError;
+use crate::util::config::{UserConfig, ChannelConfig, LegacyChannelConfig, ChannelHandshakeConfig, ChannelHandshakeLimits};
+use crate::util::scid_utils::scid_from_parts;
+
+use crate::io;
+use crate::prelude::*;
use core::{cmp,mem,fmt};
use core::ops::Deref;
#[cfg(any(test, fuzzing, debug_assertions))]
-use sync::Mutex;
+use crate::sync::Mutex;
use bitcoin::hashes::hex::ToHex;
#[cfg(test)]
use bitcoin::blockdata::opcodes;
use bitcoin::network::constants::Network;
use hex;
- use ln::PaymentHash;
- use ln::channelmanager::{self, HTLCSource, PaymentId};
- use ln::channel::{Channel, InboundHTLCOutput, OutboundHTLCOutput, InboundHTLCState, OutboundHTLCState, HTLCCandidate, HTLCInitiator};
- use ln::channel::{MAX_FUNDING_SATOSHIS_NO_WUMBO, TOTAL_BITCOIN_SUPPLY_SATOSHIS, MIN_THEIR_CHAN_RESERVE_SATOSHIS};
- use ln::features::ChannelTypeFeatures;
- use ln::msgs::{ChannelUpdate, DataLossProtect, DecodeError, OptionalField, UnsignedChannelUpdate, MAX_VALUE_MSAT};
- use ln::script::ShutdownScript;
- use ln::chan_utils;
- use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight};
- use chain::BestBlock;
- use chain::chaininterface::{FeeEstimator, LowerBoundedFeeEstimator, ConfirmationTarget};
- use chain::keysinterface::{InMemorySigner, Recipient, KeyMaterial, KeysInterface};
- use chain::transaction::OutPoint;
- use util::config::UserConfig;
- use util::enforcing_trait_impls::EnforcingSigner;
- use util::errors::APIError;
- use util::test_utils;
- use util::test_utils::OnGetShutdownScriptpubkey;
+ use crate::ln::PaymentHash;
+ use crate::ln::channelmanager::{self, HTLCSource, PaymentId};
+ use crate::ln::channel::{Channel, InboundHTLCOutput, OutboundHTLCOutput, InboundHTLCState, OutboundHTLCState, HTLCCandidate, HTLCInitiator};
+ use crate::ln::channel::{MAX_FUNDING_SATOSHIS_NO_WUMBO, TOTAL_BITCOIN_SUPPLY_SATOSHIS, MIN_THEIR_CHAN_RESERVE_SATOSHIS};
+ use crate::ln::features::ChannelTypeFeatures;
+ use crate::ln::msgs::{ChannelUpdate, DataLossProtect, DecodeError, OptionalField, UnsignedChannelUpdate, MAX_VALUE_MSAT};
+ use crate::ln::script::ShutdownScript;
+ use crate::ln::chan_utils;
+ use crate::ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight};
+ use crate::chain::BestBlock;
+ use crate::chain::chaininterface::{FeeEstimator, LowerBoundedFeeEstimator, ConfirmationTarget};
+ use crate::chain::keysinterface::{InMemorySigner, Recipient, KeyMaterial, KeysInterface};
+ use crate::chain::transaction::OutPoint;
+ use crate::util::config::UserConfig;
+ use crate::util::enforcing_trait_impls::EnforcingSigner;
+ use crate::util::errors::APIError;
+ use crate::util::test_utils;
+ use crate::util::test_utils::OnGetShutdownScriptpubkey;
use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Scalar};
use bitcoin::secp256k1::ffi::Signature as FFISignature;
use bitcoin::secp256k1::{SecretKey,PublicKey};
use bitcoin::bech32::u5;
use bitcoin::PackedLockTime;
use bitcoin::util::address::WitnessVersion;
- use prelude::*;
+ use crate::prelude::*;
struct TestFeeEstimator {
fee_est: u32
use bitcoin::hashes::hex::FromHex;
use bitcoin::hash_types::Txid;
use bitcoin::secp256k1::Message;
- use chain::keysinterface::BaseSign;
- use ln::PaymentPreimage;
- use ln::channel::{HTLCOutputInCommitment ,TxCreationKeys};
- use ln::chan_utils::{ChannelPublicKeys, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
- use util::logger::Logger;
- use sync::Arc;
+ use crate::chain::keysinterface::BaseSign;
+ use crate::ln::PaymentPreimage;
+ use crate::ln::channel::{HTLCOutputInCommitment ,TxCreationKeys};
+ use crate::ln::chan_utils::{ChannelPublicKeys, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
+ use crate::util::logger::Logger;
+ use crate::sync::Arc;
// Test vectors from BOLT 3 Appendices C and F (anchors):
let feeest = TestFeeEstimator{fee_est: 15000};
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::{LockTime, secp256k1, Sequence};
-use chain;
-use chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
-use chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
-use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent, CLOSED_CHANNEL_UPDATE_ID};
-use chain::transaction::{OutPoint, TransactionData};
+use crate::chain;
+use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
+use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
+use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent, CLOSED_CHANNEL_UPDATE_ID};
+use crate::chain::transaction::{OutPoint, TransactionData};
// Since this struct is returned in `list_channels` methods, expose it here in case users want to
// construct one themselves.
-use ln::{inbound_payment, PaymentHash, PaymentPreimage, PaymentSecret};
-use ln::channel::{Channel, ChannelError, ChannelUpdateStatus, UpdateFulfillCommitFetch};
-use ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
+use crate::ln::{inbound_payment, PaymentHash, PaymentPreimage, PaymentSecret};
+use crate::ln::channel::{Channel, ChannelError, ChannelUpdateStatus, UpdateFulfillCommitFetch};
+use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
#[cfg(any(feature = "_test_utils", test))]
-use ln::features::InvoiceFeatures;
-use routing::router::{PaymentParameters, Route, RouteHop, RoutePath, RouteParameters};
-use ln::msgs;
-use ln::onion_utils;
-use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, MAX_VALUE_MSAT};
-use ln::wire::Encode;
-use chain::keysinterface::{Sign, KeysInterface, KeysManager, InMemorySigner, Recipient};
-use util::config::{UserConfig, ChannelConfig};
-use util::events::{EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
-use util::{byte_utils, events};
-use util::wakers::{Future, Notifier};
-use util::scid_utils::fake_scid;
-use util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
-use util::logger::{Level, Logger};
-use util::errors::APIError;
-
-use io;
-use prelude::*;
+use crate::ln::features::InvoiceFeatures;
+use crate::routing::router::{PaymentParameters, Route, RouteHop, RoutePath, RouteParameters};
+use crate::ln::msgs;
+use crate::ln::onion_utils;
+use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, MAX_VALUE_MSAT};
+use crate::ln::wire::Encode;
+use crate::chain::keysinterface::{Sign, KeysInterface, KeysManager, InMemorySigner, Recipient};
+use crate::util::config::{UserConfig, ChannelConfig};
+use crate::util::events::{EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
+use crate::util::{byte_utils, events};
+use crate::util::wakers::{Future, Notifier};
+use crate::util::scid_utils::fake_scid;
+use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
+use crate::util::logger::{Level, Logger};
+use crate::util::errors::APIError;
+
+use crate::io;
+use crate::prelude::*;
use core::{cmp, mem};
use core::cell::RefCell;
-use io::Read;
-use sync::{Arc, Mutex, MutexGuard, RwLock, RwLockReadGuard};
+use crate::io::Read;
+use crate::sync::{Arc, Mutex, MutexGuard, RwLock, RwLockReadGuard};
use core::sync::atomic::{AtomicUsize, Ordering};
use core::time::Duration;
use core::ops::Deref;
impl Readable for ClaimableHTLC {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
- let mut prev_hop = ::util::ser::OptionDeserWrapper(None);
+ let mut prev_hop = crate::util::ser::OptionDeserWrapper(None);
let mut value = 0;
let mut payment_data: Option<msgs::FinalOnionHopData> = None;
let mut cltv_expiry = 0;
let id: u8 = Readable::read(reader)?;
match id {
0 => {
- let mut session_priv: ::util::ser::OptionDeserWrapper<SecretKey> = ::util::ser::OptionDeserWrapper(None);
+ let mut session_priv: crate::util::ser::OptionDeserWrapper<SecretKey> = crate::util::ser::OptionDeserWrapper(None);
let mut first_hop_htlc_msat: u64 = 0;
let mut path = Some(Vec::new());
let mut payment_id = None;
}
impl Writeable for HTLCSource {
- fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::io::Error> {
+ fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
match self {
HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id, payment_secret, payment_params } => {
0u8.write(writer)?;
use bitcoin::hashes::sha256::Hash as Sha256;
use core::time::Duration;
use core::sync::atomic::Ordering;
- use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
- use ln::channelmanager::{self, inbound_payment, PaymentId, PaymentSendFailure};
- use ln::functional_test_utils::*;
- use ln::msgs;
- use ln::msgs::ChannelMessageHandler;
- use routing::router::{PaymentParameters, RouteParameters, find_route};
- use util::errors::APIError;
- use util::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
- use util::test_utils;
- use chain::keysinterface::KeysInterface;
+ use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
+ use crate::ln::channelmanager::{self, inbound_payment, PaymentId, PaymentSendFailure};
+ use crate::ln::functional_test_utils::*;
+ use crate::ln::msgs;
+ use crate::ln::msgs::ChannelMessageHandler;
+ use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
+ use crate::util::errors::APIError;
+ use crate::util::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
+ use crate::util::test_utils;
+ use crate::chain::keysinterface::KeysInterface;
#[test]
fn test_notify_limits() {
#[cfg(all(any(test, feature = "_test_utils"), feature = "_bench_unstable"))]
pub mod bench {
- use chain::Listen;
- use chain::chainmonitor::{ChainMonitor, Persist};
- use chain::keysinterface::{KeysManager, KeysInterface, InMemorySigner};
- use ln::channelmanager::{self, BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage};
- use ln::features::{InitFeatures, InvoiceFeatures};
- use ln::functional_test_utils::*;
- use ln::msgs::{ChannelMessageHandler, Init};
- use routing::gossip::NetworkGraph;
- use routing::router::{PaymentParameters, get_route};
- use util::test_utils;
- use util::config::UserConfig;
- use util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
+ use crate::chain::Listen;
+ use crate::chain::chainmonitor::{ChainMonitor, Persist};
+ use crate::chain::keysinterface::{KeysManager, KeysInterface, InMemorySigner};
+ use crate::ln::channelmanager::{self, BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage};
+ use crate::ln::functional_test_utils::*;
+ use crate::ln::msgs::{ChannelMessageHandler, Init};
+ use crate::routing::gossip::NetworkGraph;
+ use crate::routing::router::{PaymentParameters, get_route};
+ use crate::util::test_utils;
+ use crate::util::config::UserConfig;
+ use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
use bitcoin::hashes::Hash;
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::{Block, BlockHeader, PackedLockTime, Transaction, TxMerkleNode, TxOut};
- use sync::{Arc, Mutex};
+ use crate::sync::{Arc, Mutex};
use test::Bencher;
//! [BOLT #9]: https://github.com/lightning/bolts/blob/master/09-features.md
//! [messages]: crate::ln::msgs
-use {io, io_extras};
-use prelude::*;
+use crate::{io, io_extras};
+use crate::prelude::*;
use core::{cmp, fmt};
use core::hash::{Hash, Hasher};
use core::marker::PhantomData;
use bitcoin::bech32;
use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, u5, WriteBase32};
-use ln::msgs::DecodeError;
-use util::ser::{Readable, Writeable, Writer};
+use crate::ln::msgs::DecodeError;
+use crate::util::ser::{Readable, Writeable, Writer};
mod sealed {
- use prelude::*;
- use ln::features::Features;
+ use crate::prelude::*;
+ use crate::ln::features::Features;
/// The context in which [`Features`] are applicable. Defines which features are known to the
/// implementation, though specification of them as required or optional is up to the code
//! A bunch of useful utilities for building networks of nodes and exchanging messages between
//! nodes for functional tests.
-use chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen, Watch, keysinterface::KeysInterface};
-use chain::channelmonitor::ChannelMonitor;
-use chain::transaction::OutPoint;
-use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
-use ln::channelmanager::{self, ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, PaymentId, MIN_CLTV_EXPIRY_DELTA};
-use routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate};
-use routing::router::{PaymentParameters, Route, get_route};
-use ln::features::InitFeatures;
-use ln::msgs;
-use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
-use util::enforcing_trait_impls::EnforcingSigner;
-use util::scid_utils;
-use util::test_utils;
-use util::test_utils::{panicking, TestChainMonitor};
-use util::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose};
-use util::errors::APIError;
-use util::config::UserConfig;
-use util::ser::{ReadableArgs, Writeable};
+use crate::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen, Watch, keysinterface::KeysInterface};
+use crate::chain::channelmonitor::ChannelMonitor;
+use crate::chain::transaction::OutPoint;
+use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
+use crate::ln::channelmanager::{self, ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, PaymentId, MIN_CLTV_EXPIRY_DELTA};
+use crate::routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate};
+use crate::routing::router::{PaymentParameters, Route, get_route};
+use crate::ln::features::InitFeatures;
+use crate::ln::msgs;
+use crate::ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
+use crate::util::enforcing_trait_impls::EnforcingSigner;
+use crate::util::scid_utils;
+use crate::util::test_utils;
+use crate::util::test_utils::{panicking, TestChainMonitor};
+use crate::util::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose};
+use crate::util::errors::APIError;
+use crate::util::config::UserConfig;
+use crate::util::ser::{ReadableArgs, Writeable};
use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::secp256k1::PublicKey;
-use io;
-use prelude::*;
+use crate::io;
+use crate::prelude::*;
use core::cell::RefCell;
use alloc::rc::Rc;
-use sync::{Arc, Mutex};
+use crate::sync::{Arc, Mutex};
use core::mem;
use core::iter::repeat;
use bitcoin::{PackedLockTime, TxMerkleNode};
//! payments/messages between them, and often checking the resulting ChannelMonitors are able to
//! claim outputs on-chain.
-use chain;
-use chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
-use chain::chaininterface::LowerBoundedFeeEstimator;
-use chain::channelmonitor;
-use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
-use chain::transaction::OutPoint;
-use chain::keysinterface::{BaseSign, KeysInterface};
-use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
-use ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
-use ln::channelmanager::{self, ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS};
-use ln::channel::{Channel, ChannelError};
-use ln::{chan_utils, onion_utils};
-use ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
-use routing::gossip::{NetworkGraph, NetworkUpdate};
-use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
-use ln::features::{ChannelFeatures, NodeFeatures};
-use ln::msgs;
-use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
-use util::enforcing_trait_impls::EnforcingSigner;
-use util::{byte_utils, test_utils};
-use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason, HTLCDestination};
-use util::errors::APIError;
-use util::ser::{Writeable, ReadableArgs};
-use util::config::UserConfig;
+use crate::chain;
+use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
+use crate::chain::chaininterface::LowerBoundedFeeEstimator;
+use crate::chain::channelmonitor;
+use crate::chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
+use crate::chain::transaction::OutPoint;
+use crate::chain::keysinterface::{BaseSign, KeysInterface};
+use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
+use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
+use crate::ln::channelmanager::{self, ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS};
+use crate::ln::channel::{Channel, ChannelError};
+use crate::ln::{chan_utils, onion_utils};
+use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
+use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
+use crate::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
+use crate::ln::features::{ChannelFeatures, NodeFeatures};
+use crate::ln::msgs;
+use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
+use crate::util::enforcing_trait_impls::EnforcingSigner;
+use crate::util::{byte_utils, test_utils};
+use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason, HTLCDestination};
+use crate::util::errors::APIError;
+use crate::util::ser::{Writeable, ReadableArgs};
+use crate::util::config::UserConfig;
use bitcoin::hash_types::BlockHash;
use bitcoin::blockdata::block::{Block, BlockHeader};
use regex;
-use io;
-use prelude::*;
+use crate::io;
+use crate::prelude::*;
use alloc::collections::BTreeSet;
use core::default::Default;
use core::iter::repeat;
use bitcoin::hashes::Hash;
-use sync::{Arc, Mutex};
+use crate::sync::{Arc, Mutex};
-use ln::functional_test_utils::*;
-use ln::chan_utils::CommitmentTransaction;
+use crate::ln::functional_test_utils::*;
+use crate::ln::chan_utils::CommitmentTransaction;
#[test]
fn test_insane_channel_opens() {
// Stand up a network of 2 nodes
- use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
+ use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
let mut cfg = UserConfig::default();
cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
let chanmon_cfgs = create_chanmon_cfgs(2);
} else { assert!(false); }
};
- use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
+ use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
// Test all mutations that would make the channel open message insane
insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
fn test_funding_exceeds_no_wumbo_limit() {
// Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
// them.
- use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
+ use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
let chanmon_cfgs = create_chanmon_cfgs(2);
let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
node_cfgs[1].features = channelmanager::provided_init_features().clear_wumbo();
let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
let mut payments = Vec::new();
- for _ in 0..::ln::channel::OUR_MAX_HTLCS {
+ for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
payments.push((payment_preimage, payment_hash));
check_added_monitors!(nodes[0], 0);
let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
- let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
+ let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
}
let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
- let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
+ let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
let channel_id = funding_outpoint.to_channel_id();
// Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
use bitcoin::hashes::cmp::fixed_time_eq;
use bitcoin::hashes::hmac::{Hmac, HmacEngine};
use bitcoin::hashes::sha256::Hash as Sha256;
-use chain::keysinterface::{KeyMaterial, KeysInterface, Sign};
-use ln::{PaymentHash, PaymentPreimage, PaymentSecret};
-use ln::msgs;
-use ln::msgs::MAX_VALUE_MSAT;
-use util::chacha20::ChaCha20;
-use util::crypto::hkdf_extract_expand_thrice;
-use util::errors::APIError;
-use util::logger::Logger;
+use crate::chain::keysinterface::{KeyMaterial, KeysInterface, Sign};
+use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
+use crate::ln::msgs;
+use crate::ln::msgs::MAX_VALUE_MSAT;
+use crate::util::chacha20::ChaCha20;
+use crate::util::crypto::hkdf_extract_expand_thrice;
+use crate::util::errors::APIError;
+use crate::util::logger::Logger;
use core::convert::TryInto;
use core::ops::Deref;
#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
pub struct PaymentSecret(pub [u8; 32]);
-use prelude::*;
+use crate::prelude::*;
use bitcoin::bech32;
use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, WriteBase32, u5};
//! Further functional tests which test blockchain reorganizations.
-use chain::channelmonitor::{ANTI_REORG_DELAY, Balance};
-use chain::transaction::OutPoint;
-use chain::chaininterface::LowerBoundedFeeEstimator;
-use ln::channel;
-use ln::channelmanager::{self, BREAKDOWN_TIMEOUT};
-use ln::msgs::ChannelMessageHandler;
-use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
+use crate::chain::channelmonitor::{ANTI_REORG_DELAY, Balance};
+use crate::chain::transaction::OutPoint;
+use crate::chain::chaininterface::LowerBoundedFeeEstimator;
+use crate::ln::channel;
+use crate::ln::channelmanager::{self, BREAKDOWN_TIMEOUT};
+use crate::ln::msgs::ChannelMessageHandler;
+use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
use bitcoin::blockdata::script::Builder;
use bitcoin::blockdata::opcodes;
use bitcoin::secp256k1::Secp256k1;
use bitcoin::Transaction;
-use prelude::*;
+use crate::prelude::*;
-use ln::functional_test_utils::*;
+use crate::ln::functional_test_utils::*;
#[test]
fn chanmon_fail_from_stale_commitment() {
use bitcoin::blockdata::script::Script;
use bitcoin::hash_types::{Txid, BlockHash};
-use ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
-use ln::onion_utils;
-use onion_message;
+use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
+use crate::ln::onion_utils;
+use crate::onion_message;
-use prelude::*;
+use crate::prelude::*;
use core::fmt;
use core::fmt::Debug;
-use io::{self, Read};
-use io_extras::read_to_end;
+use crate::io::{self, Read};
+use crate::io_extras::read_to_end;
-use util::events::{MessageSendEventsProvider, OnionMessageProvider};
-use util::logger;
-use util::ser::{BigSize, LengthReadable, Readable, ReadableArgs, Writeable, Writer, FixedLengthReader, HighZeroBytesDroppedBigSize, Hostname};
+use crate::util::events::{MessageSendEventsProvider, OnionMessageProvider};
+use crate::util::logger;
+use crate::util::ser::{BigSize, LengthReadable, Readable, ReadableArgs, Writeable, Writer, FixedLengthReader, HighZeroBytesDroppedBigSize, Hostname};
-use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
+use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
/// 21 million * 10^8 * 1000
pub(crate) const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000;
}
mod fuzzy_internal_msgs {
- use prelude::*;
- use ln::{PaymentPreimage, PaymentSecret};
+ use crate::prelude::*;
+ use crate::ln::{PaymentPreimage, PaymentSecret};
// These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
// them from untrusted input):
#[cfg(test)]
mod tests {
use hex;
- use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
- use ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
- use ln::msgs;
- use ln::msgs::{FinalOnionHopData, OptionalField, OnionErrorPacket, OnionHopDataFormat};
- use util::ser::{Writeable, Readable, Hostname};
+ use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
+ use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
+ use crate::ln::msgs;
+ use crate::ln::msgs::{FinalOnionHopData, OptionalField, OnionErrorPacket, OnionHopDataFormat};
+ use crate::util::ser::{Writeable, Readable, Hostname};
use bitcoin::hashes::hex::FromHex;
use bitcoin::util::address::Address;
use bitcoin::secp256k1::{PublicKey,SecretKey};
use bitcoin::secp256k1::{Secp256k1, Message};
- use io::{self, Cursor};
- use prelude::*;
+ use crate::io::{self, Cursor};
+ use crate::prelude::*;
use core::convert::TryFrom;
#[test]
}
// see above test, needs to be a separate method for use of the serialization macros.
fn encode_big_payload() -> Result<Vec<u8>, io::Error> {
- use util::ser::HighZeroBytesDroppedBigSize;
+ use crate::util::ser::HighZeroBytesDroppedBigSize;
let payload = msgs::OnionHopData {
format: OnionHopDataFormat::NonFinalNode {
short_channel_id: 0xdeadbeef1bad1dea,
//! These tests work by standing up full nodes and route payments across the network, checking the
//! returned errors decode to the correct thing.
-use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
-use chain::keysinterface::{KeysInterface, Recipient};
-use ln::{PaymentHash, PaymentSecret};
-use ln::channel::EXPIRE_PREV_CONFIG_TICKS;
-use ln::channelmanager::{self, ChannelManager, ChannelManagerReadArgs, HTLCForwardInfo, CLTV_FAR_FAR_AWAY, MIN_CLTV_EXPIRY_DELTA, PendingHTLCInfo, PendingHTLCRouting};
-use ln::onion_utils;
-use routing::gossip::{NetworkUpdate, RoutingFees, NodeId};
-use routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop};
-use ln::features::{InitFeatures, InvoiceFeatures, NodeFeatures};
-use ln::msgs;
-use ln::msgs::{ChannelMessageHandler, ChannelUpdate};
-use ln::wire::Encode;
-use util::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
-use util::ser::{ReadableArgs, Writeable, Writer};
-use util::{byte_utils, test_utils};
-use util::config::{UserConfig, ChannelConfig};
-use util::errors::APIError;
+use crate::chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
+use crate::chain::keysinterface::{KeysInterface, Recipient};
+use crate::ln::{PaymentHash, PaymentSecret};
+use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
+use crate::ln::channelmanager::{self, ChannelManager, ChannelManagerReadArgs, HTLCForwardInfo, CLTV_FAR_FAR_AWAY, MIN_CLTV_EXPIRY_DELTA, PendingHTLCInfo, PendingHTLCRouting};
+use crate::ln::onion_utils;
+use crate::routing::gossip::{NetworkUpdate, RoutingFees, NodeId};
+use crate::routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop};
+use crate::ln::features::{InitFeatures, InvoiceFeatures, NodeFeatures};
+use crate::ln::msgs;
+use crate::ln::msgs::{ChannelMessageHandler, ChannelUpdate};
+use crate::ln::wire::Encode;
+use crate::util::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
+use crate::util::ser::{ReadableArgs, Writeable, Writer};
+use crate::util::{byte_utils, test_utils};
+use crate::util::config::{UserConfig, ChannelConfig};
+use crate::util::errors::APIError;
use bitcoin::hash_types::BlockHash;
use bitcoin::secp256k1::Secp256k1;
use bitcoin::secp256k1::{PublicKey, SecretKey};
-use io;
-use prelude::*;
+use crate::io;
+use crate::prelude::*;
use core::default::Default;
-use ln::functional_test_utils::*;
+use crate::ln::functional_test_utils::*;
fn run_onion_failure_test<F1,F2>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, payment_secret: &PaymentSecret, callback_msg: F1, callback_node: F2, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<NetworkUpdate>, expected_short_channel_id: Option<u64>)
where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
// You may not use this file except in accordance with one or both of these
// licenses.
-use ln::{PaymentHash, PaymentPreimage, PaymentSecret};
-use ln::channelmanager::HTLCSource;
-use ln::msgs;
-use ln::wire::Encode;
-use routing::gossip::NetworkUpdate;
-use routing::router::RouteHop;
-use util::chacha20::{ChaCha20, ChaChaReader};
-use util::errors::{self, APIError};
-use util::ser::{Readable, ReadableArgs, Writeable, LengthCalculatingWriter};
-use util::logger::Logger;
+use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
+use crate::ln::channelmanager::HTLCSource;
+use crate::ln::msgs;
+use crate::ln::wire::Encode;
+use crate::routing::gossip::NetworkUpdate;
+use crate::routing::router::RouteHop;
+use crate::util::chacha20::{ChaCha20, ChaChaReader};
+use crate::util::errors::{self, APIError};
+use crate::util::ser::{Readable, ReadableArgs, Writeable, LengthCalculatingWriter};
+use crate::util::logger::Logger;
use bitcoin::hashes::{Hash, HashEngine};
use bitcoin::hashes::cmp::fixed_time_eq;
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1;
-use prelude::*;
-use io::{Cursor, Read};
+use crate::prelude::*;
+use crate::io::{Cursor, Read};
use core::convert::{AsMut, TryInto};
use core::ops::Deref;
#[cfg(test)]
mod tests {
- use io;
- use prelude::*;
- use ln::PaymentHash;
- use ln::features::{ChannelFeatures, NodeFeatures};
- use routing::router::{Route, RouteHop};
- use ln::msgs;
- use util::ser::{Writeable, Writer};
+ use crate::io;
+ use crate::prelude::*;
+ use crate::ln::PaymentHash;
+ use crate::ln::features::{ChannelFeatures, NodeFeatures};
+ use crate::routing::router::{Route, RouteHop};
+ use crate::ln::msgs;
+ use crate::util::ser::{Writeable, Writer};
use hex;
//! serialization ordering between ChannelManager/ChannelMonitors and ensuring we can still retry
//! payments thereafter.
-use chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
-use chain::channelmonitor::{ANTI_REORG_DELAY, ChannelMonitor, LATENCY_GRACE_PERIOD_BLOCKS};
-use chain::transaction::OutPoint;
-use chain::keysinterface::KeysInterface;
-use ln::channel::EXPIRE_PREV_CONFIG_TICKS;
-use ln::channelmanager::{self, BREAKDOWN_TIMEOUT, ChannelManager, ChannelManagerReadArgs, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure};
-use ln::msgs;
-use ln::msgs::ChannelMessageHandler;
-use routing::router::{PaymentParameters, get_route};
-use util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
-use util::test_utils;
-use util::errors::APIError;
-use util::enforcing_trait_impls::EnforcingSigner;
-use util::ser::{ReadableArgs, Writeable};
-use io;
+use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
+use crate::chain::channelmonitor::{ANTI_REORG_DELAY, ChannelMonitor, LATENCY_GRACE_PERIOD_BLOCKS};
+use crate::chain::transaction::OutPoint;
+use crate::chain::keysinterface::KeysInterface;
+use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
+use crate::ln::channelmanager::{self, BREAKDOWN_TIMEOUT, ChannelManager, ChannelManagerReadArgs, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure};
+use crate::ln::msgs;
+use crate::ln::msgs::ChannelMessageHandler;
+use crate::routing::router::{PaymentParameters, get_route};
+use crate::util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
+use crate::util::test_utils;
+use crate::util::errors::APIError;
+use crate::util::enforcing_trait_impls::EnforcingSigner;
+use crate::util::ser::{ReadableArgs, Writeable};
+use crate::io;
use bitcoin::{Block, BlockHeader, BlockHash, TxMerkleNode};
use bitcoin::hashes::Hash;
use bitcoin::network::constants::Network;
-use prelude::*;
+use crate::prelude::*;
-use ln::functional_test_utils::*;
+use crate::ln::functional_test_utils::*;
#[test]
fn retry_single_path_payment() {
// You may not use this file except in accordance with one or both of these
// licenses.
-use prelude::*;
+use crate::prelude::*;
-use ln::msgs::LightningError;
-use ln::msgs;
-use ln::wire;
+use crate::ln::msgs::LightningError;
+use crate::ln::msgs;
+use crate::ln::wire;
use bitcoin::hashes::{Hash, HashEngine};
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1;
-use util::chacha20poly1305rfc::ChaCha20Poly1305RFC;
-use util::crypto::hkdf_extract_expand_twice;
-use util::ser::VecWriter;
+use crate::util::chacha20poly1305rfc::ChaCha20Poly1305RFC;
+use crate::util::crypto::hkdf_extract_expand_twice;
+use crate::util::ser::VecWriter;
use bitcoin::hashes::hex::ToHex;
/// Maximum Lightning message data length according to
use hex;
- use ln::peer_channel_encryptor::{PeerChannelEncryptor,NoiseState};
+ use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor,NoiseState};
fn get_outbound_peer_for_initiator_test_vectors() -> PeerChannelEncryptor {
let their_node_id = PublicKey::from_slice(&hex::decode("028d7500dd4c12685d1f568b4c2b5048e8534b873319f3a8daa612b469132ec7f7").unwrap()[..]).unwrap();
use bitcoin::secp256k1::{self, Secp256k1, SecretKey, PublicKey};
-use ln::features::{InitFeatures, NodeFeatures};
-use ln::msgs;
-use ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, OnionMessageHandler, RoutingMessageHandler};
-use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
-use util::ser::{MaybeReadableArgs, VecWriter, Writeable, Writer};
-use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
-use ln::wire;
-use ln::wire::Encode;
-use onion_message::{CustomOnionMessageContents, CustomOnionMessageHandler, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
-use routing::gossip::{NetworkGraph, P2PGossipSync};
-use util::atomic_counter::AtomicCounter;
-use util::crypto::sign;
-use util::events::{MessageSendEvent, MessageSendEventsProvider, OnionMessageProvider};
-use util::logger::Logger;
-
-use prelude::*;
-use io;
+use crate::ln::features::{InitFeatures, NodeFeatures};
+use crate::ln::msgs;
+use crate::ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, OnionMessageHandler, RoutingMessageHandler};
+use crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
+use crate::util::ser::{MaybeReadableArgs, VecWriter, Writeable, Writer};
+use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
+use crate::ln::wire;
+use crate::ln::wire::Encode;
+use crate::onion_message::{CustomOnionMessageContents, CustomOnionMessageHandler, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
+use crate::routing::gossip::{NetworkGraph, P2PGossipSync};
+use crate::util::atomic_counter::AtomicCounter;
+use crate::util::crypto::sign;
+use crate::util::events::{MessageSendEvent, MessageSendEventsProvider, OnionMessageProvider};
+use crate::util::logger::Logger;
+
+use crate::prelude::*;
+use crate::io;
use alloc::collections::LinkedList;
-use sync::{Arc, Mutex, MutexGuard, FairRwLock};
+use crate::sync::{Arc, Mutex, MutexGuard, FairRwLock};
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use core::{cmp, hash, fmt, mem};
use core::ops::Deref;
#[cfg(test)]
mod tests {
- use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
- use ln::{msgs, wire};
- use ln::msgs::NetAddress;
- use util::events;
- use util::test_utils;
+ use crate::ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
+ use crate::ln::{msgs, wire};
+ use crate::ln::msgs::NetAddress;
+ use crate::util::events;
+ use crate::util::test_utils;
use bitcoin::secp256k1::Secp256k1;
use bitcoin::secp256k1::{SecretKey, PublicKey};
- use prelude::*;
- use sync::{Arc, Mutex};
+ use crate::prelude::*;
+ use crate::sync::{Arc, Mutex};
use core::sync::atomic::Ordering;
#[derive(Clone)]
//! other behavior that exists only on private channels or with a semi-trusted counterparty (eg
//! LSP).
-use chain::{ChannelMonitorUpdateStatus, Watch};
-use chain::channelmonitor::ChannelMonitor;
-use chain::keysinterface::{Recipient, KeysInterface};
-use ln::channelmanager::{self, ChannelManager, ChannelManagerReadArgs, MIN_CLTV_EXPIRY_DELTA};
-use routing::gossip::RoutingFees;
-use routing::router::{PaymentParameters, RouteHint, RouteHintHop};
-use ln::features::ChannelTypeFeatures;
-use ln::msgs;
-use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ChannelUpdate, ErrorAction};
-use ln::wire::Encode;
-use util::enforcing_trait_impls::EnforcingSigner;
-use util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
-use util::config::UserConfig;
-use util::ser::{Writeable, ReadableArgs};
-use util::test_utils;
-
-use prelude::*;
+use crate::chain::{ChannelMonitorUpdateStatus, Watch};
+use crate::chain::channelmonitor::ChannelMonitor;
+use crate::chain::keysinterface::{Recipient, KeysInterface};
+use crate::ln::channelmanager::{self, ChannelManager, ChannelManagerReadArgs, MIN_CLTV_EXPIRY_DELTA};
+use crate::routing::gossip::RoutingFees;
+use crate::routing::router::{PaymentParameters, RouteHint, RouteHintHop};
+use crate::ln::features::ChannelTypeFeatures;
+use crate::ln::msgs;
+use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ChannelUpdate, ErrorAction};
+use crate::ln::wire::Encode;
+use crate::util::enforcing_trait_impls::EnforcingSigner;
+use crate::util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
+use crate::util::config::UserConfig;
+use crate::util::ser::{Writeable, ReadableArgs};
+use crate::util::test_utils;
+
+use crate::prelude::*;
use core::default::Default;
-use ln::functional_test_utils::*;
+use crate::ln::functional_test_utils::*;
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::hash_types::BlockHash;
//! Further functional tests which test blockchain reorganizations.
-use chain::channelmonitor::{ANTI_REORG_DELAY, ChannelMonitor};
-use chain::transaction::OutPoint;
-use chain::{ChannelMonitorUpdateStatus, Confirm, Watch};
-use ln::channelmanager::{self, ChannelManager, ChannelManagerReadArgs};
-use ln::msgs::ChannelMessageHandler;
-use util::enforcing_trait_impls::EnforcingSigner;
-use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
-use util::test_utils;
-use util::ser::{ReadableArgs, Writeable};
+use crate::chain::channelmonitor::{ANTI_REORG_DELAY, ChannelMonitor};
+use crate::chain::transaction::OutPoint;
+use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Watch};
+use crate::ln::channelmanager::{self, ChannelManager, ChannelManagerReadArgs};
+use crate::ln::msgs::ChannelMessageHandler;
+use crate::util::enforcing_trait_impls::EnforcingSigner;
+use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
+use crate::util::test_utils;
+use crate::util::ser::{ReadableArgs, Writeable};
use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::script::Builder;
use bitcoin::hash_types::BlockHash;
use bitcoin::secp256k1::Secp256k1;
-use prelude::*;
+use crate::prelude::*;
use core::mem;
use bitcoin::hashes::Hash;
use bitcoin::TxMerkleNode;
-use ln::functional_test_utils::*;
+use crate::ln::functional_test_utils::*;
fn do_test_onchain_htlc_reorg(local_commitment: bool, claim: bool) {
// Our on-chain HTLC-claim learning has a few properties worth testing:
use bitcoin::secp256k1::PublicKey;
use bitcoin::util::address::WitnessVersion;
-use ln::channelmanager;
-use ln::features::InitFeatures;
-use ln::msgs::DecodeError;
-use util::ser::{Readable, Writeable, Writer};
+use crate::ln::channelmanager;
+use crate::ln::features::InitFeatures;
+use crate::ln::msgs::DecodeError;
+use crate::util::ser::{Readable, Writeable, Writer};
use core::convert::TryFrom;
-use io;
+use crate::io;
/// A script pubkey for shutting down a channel as defined by [BOLT #2].
///
use bitcoin::blockdata::script::{Builder, Script};
use bitcoin::secp256k1::Secp256k1;
use bitcoin::secp256k1::{PublicKey, SecretKey};
- use ln::features::InitFeatures;
+ use crate::ln::features::InitFeatures;
use core::convert::TryFrom;
use bitcoin::util::address::WitnessVersion;
//! Tests of our shutdown and closing_signed negotiation logic.
-use chain::keysinterface::KeysInterface;
-use chain::transaction::OutPoint;
-use ln::channelmanager::{self, PaymentSendFailure};
-use routing::router::{PaymentParameters, get_route};
-use ln::msgs;
-use ln::msgs::{ChannelMessageHandler, ErrorAction};
-use ln::script::ShutdownScript;
-use util::test_utils;
-use util::test_utils::OnGetShutdownScriptpubkey;
-use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
-use util::errors::APIError;
-use util::config::UserConfig;
+use crate::chain::keysinterface::KeysInterface;
+use crate::chain::transaction::OutPoint;
+use crate::ln::channelmanager::{self, PaymentSendFailure};
+use crate::routing::router::{PaymentParameters, get_route};
+use crate::ln::msgs;
+use crate::ln::msgs::{ChannelMessageHandler, ErrorAction};
+use crate::ln::script::ShutdownScript;
+use crate::util::test_utils;
+use crate::util::test_utils::OnGetShutdownScriptpubkey;
+use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
+use crate::util::errors::APIError;
+use crate::util::config::UserConfig;
use bitcoin::blockdata::script::Builder;
use bitcoin::blockdata::opcodes;
use core::default::Default;
-use ln::functional_test_utils::*;
-use ln::msgs::OptionalField::Present;
+use crate::ln::functional_test_utils::*;
+use crate::ln::msgs::OptionalField::Present;
#[test]
fn pre_funding_lock_shutdown_test() {
//!
//! [BOLT #1]: https://github.com/lightning/bolts/blob/master/01-messaging.md
-use io;
-use ln::msgs;
-use util::ser::{Readable, Writeable, Writer};
+use crate::io;
+use crate::ln::msgs;
+use crate::util::ser::{Readable, Writeable, Writer};
/// Trait to be implemented by custom message (unrelated to the channel/gossip LN layers)
/// decoders.
/// A message that could not be decoded because its type is unknown.
Unknown(u16),
/// A message that was produced by a [`CustomMessageReader`] and is to be handled by a
- /// [`::ln::peer_handler::CustomMessageHandler`].
+ /// [`crate::ln::peer_handler::CustomMessageHandler`].
Custom(T),
}
#[cfg(test)]
mod tests {
use super::*;
- use prelude::*;
+ use crate::prelude::*;
use core::convert::TryInto;
- use ::ln::peer_handler::IgnoringMessageHandler;
+ use crate::ln::peer_handler::IgnoringMessageHandler;
// Big-endian wire encoding of Pong message (type = 19, byteslen = 2).
const ENCODED_PONG: [u8; 6] = [0u8, 19u8, 0u8, 2u8, 0u8, 0u8];
use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
-use chain::keysinterface::KeysInterface;
+use crate::chain::keysinterface::KeysInterface;
use super::utils;
-use ln::msgs::DecodeError;
-use util::chacha20poly1305rfc::ChaChaPolyWriteAdapter;
-use util::ser::{Readable, VecWriter, Writeable, Writer};
+use crate::ln::msgs::DecodeError;
+use crate::util::chacha20poly1305rfc::ChaChaPolyWriteAdapter;
+use crate::util::ser::{Readable, VecWriter, Writeable, Writer};
-use io;
-use prelude::*;
+use crate::io;
+use crate::prelude::*;
/// Onion messages can be sent and received to blinded routes, which serve to hide the identity of
/// the recipient.
//! Onion message testing and test utilities live here.
-use chain::keysinterface::{KeysInterface, Recipient};
-use ln::features::InitFeatures;
-use ln::msgs::{self, DecodeError, OnionMessageHandler};
+use crate::chain::keysinterface::{KeysInterface, Recipient};
+use crate::ln::features::InitFeatures;
+use crate::ln::msgs::{self, DecodeError, OnionMessageHandler};
use super::{BlindedRoute, CustomOnionMessageContents, CustomOnionMessageHandler, Destination, OnionMessageContents, OnionMessenger, SendError};
-use util::enforcing_trait_impls::EnforcingSigner;
-use util::ser::{MaybeReadableArgs, Writeable, Writer};
-use util::test_utils;
+use crate::util::enforcing_trait_impls::EnforcingSigner;
+use crate::util::ser::{MaybeReadableArgs, Writeable, Writer};
+use crate::util::test_utils;
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::{PublicKey, Secp256k1};
-use io;
-use sync::Arc;
+use crate::io;
+use crate::sync::Arc;
struct MessengerNode {
keys_manager: Arc<test_utils::TestKeysInterface>,
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::secp256k1::{self, PublicKey, Scalar, Secp256k1, SecretKey};
-use chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager, Recipient, Sign};
-use ln::features::{InitFeatures, NodeFeatures};
-use ln::msgs::{self, OnionMessageHandler};
-use ln::onion_utils;
-use ln::peer_handler::IgnoringMessageHandler;
+use crate::chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager, Recipient, Sign};
+use crate::ln::features::{InitFeatures, NodeFeatures};
+use crate::ln::msgs::{self, OnionMessageHandler};
+use crate::ln::onion_utils;
+use crate::ln::peer_handler::IgnoringMessageHandler;
use super::blinded_route::{BlindedRoute, ForwardTlvs, ReceiveTlvs};
pub use super::packet::{CustomOnionMessageContents, OnionMessageContents};
use super::packet::{BIG_PACKET_HOP_DATA_LEN, ForwardControlTlvs, Packet, Payload, ReceiveControlTlvs, SMALL_PACKET_HOP_DATA_LEN};
use super::utils;
-use util::events::OnionMessageProvider;
-use util::logger::Logger;
-use util::ser::Writeable;
+use crate::util::events::OnionMessageProvider;
+use crate::util::logger::Logger;
+use crate::util::ser::Writeable;
use core::ops::Deref;
-use sync::{Arc, Mutex};
-use prelude::*;
+use crate::sync::{Arc, Mutex};
+use crate::prelude::*;
/// A sender, receiver and forwarder of onion messages. In upcoming releases, this object will be
/// used to retrieve invoices and fulfill invoice requests from [offers]. Currently, only sending
use bitcoin::secp256k1::PublicKey;
use bitcoin::secp256k1::ecdh::SharedSecret;
-use ln::msgs::DecodeError;
-use ln::onion_utils;
+use crate::ln::msgs::DecodeError;
+use crate::ln::onion_utils;
use super::blinded_route::{BlindedRoute, ForwardTlvs, ReceiveTlvs};
-use util::chacha20poly1305rfc::{ChaChaPolyReadAdapter, ChaChaPolyWriteAdapter};
-use util::ser::{BigSize, FixedLengthReader, LengthRead, LengthReadable, LengthReadableArgs, MaybeReadableArgs, Readable, ReadableArgs, Writeable, Writer};
+use crate::util::chacha20poly1305rfc::{ChaChaPolyReadAdapter, ChaChaPolyWriteAdapter};
+use crate::util::ser::{BigSize, FixedLengthReader, LengthRead, LengthReadable, LengthReadableArgs, MaybeReadableArgs, Readable, ReadableArgs, Writeable, Writer};
use core::cmp;
-use io::{self, Read};
-use prelude::*;
+use crate::io::{self, Read};
+use crate::prelude::*;
// Per the spec, an onion message packet's `hop_data` field length should be
// SMALL_PACKET_HOP_DATA_LEN if it fits, else BIG_PACKET_HOP_DATA_LEN if it fits.
use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey, Scalar};
use bitcoin::secp256k1::ecdh::SharedSecret;
-use ln::onion_utils;
+use crate::ln::onion_utils;
use super::blinded_route::BlindedRoute;
use super::messenger::Destination;
-use prelude::*;
+use crate::prelude::*;
// TODO: DRY with onion_utils::construct_onion_keys_callback
#[inline]
use bitcoin::blockdata::transaction::TxOut;
use bitcoin::hash_types::BlockHash;
-use chain;
-use chain::Access;
-use ln::chan_utils::make_funding_redeemscript;
-use ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
-use ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
-use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, GossipTimestampFilter};
-use ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
-use ln::msgs;
-use util::ser::{Readable, ReadableArgs, Writeable, Writer, MaybeReadable};
-use util::logger::{Logger, Level};
-use util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
-use util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
-
-use io;
-use io_extras::{copy, sink};
-use prelude::*;
+use crate::chain;
+use crate::chain::Access;
+use crate::ln::chan_utils::make_funding_redeemscript;
+use crate::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
+use crate::ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
+use crate::ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, GossipTimestampFilter};
+use crate::ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
+use crate::ln::msgs;
+use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer, MaybeReadable};
+use crate::util::logger::{Logger, Level};
+use crate::util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
+use crate::util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
+
+use crate::io;
+use crate::io_extras::{copy, sink};
+use crate::prelude::*;
use alloc::collections::{BTreeMap, btree_map::Entry as BtreeEntry};
use core::{cmp, fmt};
-use sync::{RwLock, RwLockReadGuard};
+use crate::sync::{RwLock, RwLockReadGuard};
+#[cfg(feature = "std")]
use core::sync::atomic::{AtomicUsize, Ordering};
-use sync::Mutex;
+use crate::sync::Mutex;
use core::ops::{Bound, Deref};
use bitcoin::hashes::hex::ToHex;
}
impl Writeable for ChannelUpdateInfo {
- fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
+ fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
write_tlv_fields!(writer, {
(0, self.last_update, required),
(2, self.enabled, required),
}
impl Writeable for ChannelInfo {
- fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
+ fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
write_tlv_fields!(writer, {
(0, self.features, required),
(1, self.announcement_received_time, (default_value, 0)),
impl MaybeReadable for ChannelUpdateInfoDeserWrapper {
fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
- match ::util::ser::Readable::read(reader) {
+ match crate::util::ser::Readable::read(reader) {
Ok(channel_update_option) => Ok(Some(Self(channel_update_option))),
Err(DecodeError::ShortRead) => Ok(None),
Err(DecodeError::InvalidValue) => Ok(None),
}
impl Writeable for NodeInfo {
- fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
+ fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
write_tlv_fields!(writer, {
(0, self.lowest_inbound_channel_fees, option),
(2, self.announcement_info, option),
impl MaybeReadable for NodeAnnouncementInfoDeserWrapper {
fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
- match ::util::ser::Readable::read(reader) {
+ match crate::util::ser::Readable::read(reader) {
Ok(node_announcement_info) => return Ok(Some(Self(node_announcement_info))),
Err(_) => {
copy(reader, &mut sink()).unwrap();
#[cfg(test)]
mod tests {
- use chain;
- use ln::channelmanager;
- use ln::chan_utils::make_funding_redeemscript;
- use ln::PaymentHash;
- use ln::features::InitFeatures;
- use routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate, NodeAlias, MAX_EXCESS_BYTES_FOR_RELAY, NodeId, RoutingFees, ChannelUpdateInfo, ChannelInfo, NodeAnnouncementInfo, NodeInfo};
- use ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
+ use crate::chain;
+ use crate::ln::channelmanager;
+ use crate::ln::chan_utils::make_funding_redeemscript;
+ use crate::ln::PaymentHash;
+ use crate::ln::features::InitFeatures;
+ use crate::routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate, NodeAlias, MAX_EXCESS_BYTES_FOR_RELAY, NodeId, RoutingFees, ChannelUpdateInfo, ChannelInfo, NodeAnnouncementInfo, NodeInfo};
+ use crate::ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate,
ReplyChannelRange, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
- use util::test_utils;
- use util::ser::{ReadableArgs, Writeable};
- use util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
- use util::scid_utils::scid_from_parts;
+ use crate::util::test_utils;
+ use crate::util::ser::{ReadableArgs, Writeable};
+ use crate::util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
+ use crate::util::scid_utils::scid_from_parts;
use crate::routing::gossip::REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS;
use super::STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS;
use bitcoin::secp256k1::{PublicKey, SecretKey};
use bitcoin::secp256k1::{All, Secp256k1};
- use io;
+ use crate::io;
use bitcoin::secp256k1;
- use prelude::*;
- use sync::Arc;
+ use crate::prelude::*;
+ use crate::sync::Arc;
fn create_network_graph() -> NetworkGraph<Arc<test_utils::TestLogger>> {
let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
#[cfg(feature = "std")]
fn calling_sync_routing_table() {
use std::time::{SystemTime, UNIX_EPOCH};
- use ln::msgs::Init;
+ use crate::ln::msgs::Init;
let network_graph = create_network_graph();
let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
#[test]
fn channel_info_is_readable() {
- let chanmon_cfgs = ::ln::functional_test_utils::create_chanmon_cfgs(2);
- let node_cfgs = ::ln::functional_test_utils::create_node_cfgs(2, &chanmon_cfgs);
- let node_chanmgrs = ::ln::functional_test_utils::create_node_chanmgrs(2, &node_cfgs, &[None, None, None, None]);
- let nodes = ::ln::functional_test_utils::create_network(2, &node_cfgs, &node_chanmgrs);
+ let chanmon_cfgs = crate::ln::functional_test_utils::create_chanmon_cfgs(2);
+ let node_cfgs = crate::ln::functional_test_utils::create_node_cfgs(2, &chanmon_cfgs);
+ let node_chanmgrs = crate::ln::functional_test_utils::create_node_chanmgrs(2, &node_cfgs, &[None, None, None, None]);
+ let nodes = crate::ln::functional_test_utils::create_network(2, &node_cfgs, &node_chanmgrs);
// 1. Test encoding/decoding of ChannelUpdateInfo
let chan_update_info = ChannelUpdateInfo {
assert!(chan_update_info.write(&mut encoded_chan_update_info).is_ok());
// First make sure we can read ChannelUpdateInfos we just wrote
- let read_chan_update_info: ChannelUpdateInfo = ::util::ser::Readable::read(&mut encoded_chan_update_info.as_slice()).unwrap();
+ let read_chan_update_info: ChannelUpdateInfo = crate::util::ser::Readable::read(&mut encoded_chan_update_info.as_slice()).unwrap();
assert_eq!(chan_update_info, read_chan_update_info);
// Check the serialization hasn't changed.
// Check we fail if htlc_maximum_msat is not present in either the ChannelUpdateInfo itself
// or the ChannelUpdate enclosed with `last_update_message`.
let legacy_chan_update_info_with_some_and_fail_update: Vec<u8> = hex::decode("b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f42400000271000000014").unwrap();
- let read_chan_update_info_res: Result<ChannelUpdateInfo, ::ln::msgs::DecodeError> = ::util::ser::Readable::read(&mut legacy_chan_update_info_with_some_and_fail_update.as_slice());
+ let read_chan_update_info_res: Result<ChannelUpdateInfo, crate::ln::msgs::DecodeError> = crate::util::ser::Readable::read(&mut legacy_chan_update_info_with_some_and_fail_update.as_slice());
assert!(read_chan_update_info_res.is_err());
let legacy_chan_update_info_with_none: Vec<u8> = hex::decode("2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c0100").unwrap();
- let read_chan_update_info_res: Result<ChannelUpdateInfo, ::ln::msgs::DecodeError> = ::util::ser::Readable::read(&mut legacy_chan_update_info_with_none.as_slice());
+ let read_chan_update_info_res: Result<ChannelUpdateInfo, crate::ln::msgs::DecodeError> = crate::util::ser::Readable::read(&mut legacy_chan_update_info_with_none.as_slice());
assert!(read_chan_update_info_res.is_err());
// 2. Test encoding/decoding of ChannelInfo
let mut encoded_chan_info: Vec<u8> = Vec::new();
assert!(chan_info_none_updates.write(&mut encoded_chan_info).is_ok());
- let read_chan_info: ChannelInfo = ::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
+ let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
assert_eq!(chan_info_none_updates, read_chan_info);
// Check we can encode/decode ChannelInfo with ChannelUpdateInfo fields present.
let mut encoded_chan_info: Vec<u8> = Vec::new();
assert!(chan_info_some_updates.write(&mut encoded_chan_info).is_ok());
- let read_chan_info: ChannelInfo = ::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
+ let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
assert_eq!(chan_info_some_updates, read_chan_info);
// Check the serialization hasn't changed.
// Check we can decode legacy ChannelInfo, even if the `two_to_one` / `one_to_two` /
// `last_update_message` fields fail to decode due to missing htlc_maximum_msat.
let legacy_chan_info_with_some_and_fail_update = hex::decode("fd01ca00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce8804b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f4240000027100000001406210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c2308b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f424000002710000000140a01000c0100").unwrap();
- let read_chan_info: ChannelInfo = ::util::ser::Readable::read(&mut legacy_chan_info_with_some_and_fail_update.as_slice()).unwrap();
+ let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_some_and_fail_update.as_slice()).unwrap();
assert_eq!(read_chan_info.announcement_received_time, 87654);
assert_eq!(read_chan_info.one_to_two, None);
assert_eq!(read_chan_info.two_to_one, None);
let legacy_chan_info_with_none: Vec<u8> = hex::decode("ba00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce88042e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c010006210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23082e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c01000a01000c0100").unwrap();
- let read_chan_info: ChannelInfo = ::util::ser::Readable::read(&mut legacy_chan_info_with_none.as_slice()).unwrap();
+ let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_none.as_slice()).unwrap();
assert_eq!(read_chan_info.announcement_received_time, 87654);
assert_eq!(read_chan_info.one_to_two, None);
assert_eq!(read_chan_info.two_to_one, None);
use std::convert::TryFrom;
// 1. Check we can read a valid NodeAnnouncementInfo and fail on an invalid one
- let valid_netaddr = ::ln::msgs::NetAddress::Hostname { hostname: ::util::ser::Hostname::try_from("A".to_string()).unwrap(), port: 1234 };
+ let valid_netaddr = crate::ln::msgs::NetAddress::Hostname { hostname: crate::util::ser::Hostname::try_from("A".to_string()).unwrap(), port: 1234 };
let valid_node_ann_info = NodeAnnouncementInfo {
features: channelmanager::provided_node_features(),
last_update: 0,
let mut encoded_valid_node_ann_info = Vec::new();
assert!(valid_node_ann_info.write(&mut encoded_valid_node_ann_info).is_ok());
- let read_valid_node_ann_info: NodeAnnouncementInfo = ::util::ser::Readable::read(&mut encoded_valid_node_ann_info.as_slice()).unwrap();
+ let read_valid_node_ann_info: NodeAnnouncementInfo = crate::util::ser::Readable::read(&mut encoded_valid_node_ann_info.as_slice()).unwrap();
assert_eq!(read_valid_node_ann_info, valid_node_ann_info);
let encoded_invalid_node_ann_info = hex::decode("3f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d2").unwrap();
- let read_invalid_node_ann_info_res: Result<NodeAnnouncementInfo, ::ln::msgs::DecodeError> = ::util::ser::Readable::read(&mut encoded_invalid_node_ann_info.as_slice());
+ let read_invalid_node_ann_info_res: Result<NodeAnnouncementInfo, crate::ln::msgs::DecodeError> = crate::util::ser::Readable::read(&mut encoded_invalid_node_ann_info.as_slice());
assert!(read_invalid_node_ann_info_res.is_err());
// 2. Check we can read a NodeInfo anyways, but set the NodeAnnouncementInfo to None if invalid
let mut encoded_valid_node_info = Vec::new();
assert!(valid_node_info.write(&mut encoded_valid_node_info).is_ok());
- let read_valid_node_info: NodeInfo = ::util::ser::Readable::read(&mut encoded_valid_node_info.as_slice()).unwrap();
+ let read_valid_node_info: NodeInfo = crate::util::ser::Readable::read(&mut encoded_valid_node_info.as_slice()).unwrap();
assert_eq!(read_valid_node_info, valid_node_info);
let encoded_invalid_node_info_hex = hex::decode("4402403f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d20400").unwrap();
- let read_invalid_node_info: NodeInfo = ::util::ser::Readable::read(&mut encoded_invalid_node_info_hex.as_slice()).unwrap();
+ let read_invalid_node_info: NodeInfo = crate::util::ser::Readable::read(&mut encoded_invalid_node_info_hex.as_slice()).unwrap();
assert_eq!(read_invalid_node_info.announcement_info, None);
}
}
#[bench]
fn read_network_graph(bench: &mut Bencher) {
- let logger = ::util::test_utils::TestLogger::new();
- let mut d = ::routing::router::bench_utils::get_route_file().unwrap();
+ let logger = crate::util::test_utils::TestLogger::new();
+ let mut d = crate::routing::router::bench_utils::get_route_file().unwrap();
let mut v = Vec::new();
d.read_to_end(&mut v).unwrap();
bench.iter(|| {
#[bench]
fn write_network_graph(bench: &mut Bencher) {
- let logger = ::util::test_utils::TestLogger::new();
- let mut d = ::routing::router::bench_utils::get_route_file().unwrap();
+ let logger = crate::util::test_utils::TestLogger::new();
+ let mut d = crate::routing::router::bench_utils::get_route_file().unwrap();
let net_graph = NetworkGraph::read(&mut d, &logger).unwrap();
bench.iter(|| {
let _ = net_graph.encode();
use bitcoin::secp256k1::PublicKey;
-use ln::channelmanager::ChannelDetails;
-use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
-use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
-use routing::gossip::{DirectedChannelInfoWithUpdate, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
-use routing::scoring::{ChannelUsage, Score};
-use util::ser::{Writeable, Readable, Writer};
-use util::logger::{Level, Logger};
-use util::chacha20::ChaCha20;
-
-use io;
-use prelude::*;
+use crate::ln::channelmanager::ChannelDetails;
+use crate::ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
+use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
+use crate::routing::gossip::{DirectedChannelInfoWithUpdate, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
+use crate::routing::scoring::{ChannelUsage, Score};
+use crate::util::ser::{Writeable, Readable, Writer};
+use crate::util::logger::{Level, Logger};
+use crate::util::chacha20::ChaCha20;
+
+use crate::io;
+use crate::prelude::*;
use alloc::collections::BinaryHeap;
use core::cmp;
use core::ops::Deref;
const MIN_SERIALIZATION_VERSION: u8 = 1;
impl Writeable for Route {
- fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
+ fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
(self.paths.len() as u64).write(writer)?;
for hops in self.paths.iter() {
pub struct RouteHint(pub Vec<RouteHintHop>);
impl Writeable for RouteHint {
- fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
+ fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
(self.0.len() as u64).write(writer)?;
for hop in self.0.iter() {
hop.write(writer)?;
#[cfg(test)]
mod tests {
- use routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
- use routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
+ use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
+ use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
- use routing::scoring::{ChannelUsage, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
- use routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
- use chain::transaction::OutPoint;
- use chain::keysinterface::KeysInterface;
- use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
- use ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
- use ln::channelmanager;
- use util::test_utils as ln_test_utils;
- use util::chacha20::ChaCha20;
+ use crate::routing::scoring::{ChannelUsage, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
+ use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
+ use crate::chain::transaction::OutPoint;
+ use crate::chain::keysinterface::KeysInterface;
+ use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
+ use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
+ use crate::ln::channelmanager;
+ use crate::util::test_utils as ln_test_utils;
+ use crate::util::chacha20::ChaCha20;
#[cfg(c_bindings)]
- use util::ser::{Writeable, Writer};
+ use crate::util::ser::{Writeable, Writer};
use bitcoin::hashes::Hash;
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::{PublicKey,SecretKey};
use bitcoin::secp256k1::Secp256k1;
- use prelude::*;
- use sync::Arc;
+ use crate::prelude::*;
+ use crate::sync::Arc;
use core::convert::TryInto;
#[cfg(c_bindings)]
impl Writeable for BadChannelScorer {
- fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
+ fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
}
impl Score for BadChannelScorer {
fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
#[cfg(c_bindings)]
impl Writeable for BadNodeScorer {
- fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
+ fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
}
impl Score for BadNodeScorer {
seed
}
#[cfg(not(feature = "no-std"))]
- use util::ser::ReadableArgs;
+ use crate::util::ser::ReadableArgs;
#[test]
#[cfg(not(feature = "no-std"))]
fn generate_routes() {
- use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
+ use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
let mut d = match super::bench_utils::get_route_file() {
Ok(f) => f,
#[test]
#[cfg(not(feature = "no-std"))]
fn generate_routes_mpp() {
- use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
+ use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
let mut d = match super::bench_utils::get_route_file() {
Ok(f) => f,
use super::*;
use bitcoin::hashes::Hash;
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
- use chain::transaction::OutPoint;
- use chain::keysinterface::{KeysManager,KeysInterface};
- use ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
- use ln::features::{InitFeatures, InvoiceFeatures};
- use routing::gossip::NetworkGraph;
- use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
- use util::logger::{Logger, Record};
- use util::ser::ReadableArgs;
+ use crate::chain::transaction::OutPoint;
+ use crate::chain::keysinterface::{KeysManager,KeysInterface};
+ use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
+ use crate::ln::features::InvoiceFeatures;
+ use crate::routing::gossip::NetworkGraph;
+ use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
+ use crate::util::logger::{Logger, Record};
+ use crate::util::ser::ReadableArgs;
use test::Bencher;
//!
//! [`find_route`]: crate::routing::router::find_route
-use ln::msgs::DecodeError;
-use routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId};
-use routing::router::RouteHop;
-use util::ser::{Readable, ReadableArgs, Writeable, Writer};
-use util::logger::Logger;
-use util::time::Time;
-
-use prelude::*;
+use crate::ln::msgs::DecodeError;
+use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId};
+use crate::routing::router::RouteHop;
+use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer};
+use crate::util::logger::Logger;
+use crate::util::time::Time;
+
+use crate::prelude::*;
use core::{cmp, fmt};
use core::cell::{RefCell, RefMut};
use core::convert::TryInto;
use core::ops::{Deref, DerefMut};
use core::time::Duration;
-use io::{self, Read};
-use sync::{Mutex, MutexGuard};
+use crate::io::{self, Read};
+use crate::sync::{Mutex, MutexGuard};
/// We define Score ever-so-slightly differently based on whether we are being built for C bindings
/// or not. For users, `LockableScore` must somehow be writeable to disk. For Rust users, this is
#[cfg(not(feature = "no-std"))]
type ConfiguredTime = std::time::Instant;
#[cfg(feature = "no-std")]
-use util::time::Eternity;
+use crate::util::time::Eternity;
#[cfg(feature = "no-std")]
type ConfiguredTime = Eternity;
#[cfg(test)]
mod tests {
use super::{ChannelLiquidity, HistoricalBucketRangeTracker, ProbabilisticScoringParameters, ProbabilisticScorerUsingTime};
- use util::time::Time;
- use util::time::tests::SinceEpoch;
+ use crate::util::time::Time;
+ use crate::util::time::tests::SinceEpoch;
- use ln::channelmanager;
- use ln::msgs::{ChannelAnnouncement, ChannelUpdate, UnsignedChannelAnnouncement, UnsignedChannelUpdate};
- use routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId};
- use routing::router::RouteHop;
- use routing::scoring::{ChannelUsage, Score};
- use util::ser::{ReadableArgs, Writeable};
- use util::test_utils::TestLogger;
+ use crate::ln::channelmanager;
+ use crate::ln::msgs::{ChannelAnnouncement, ChannelUpdate, UnsignedChannelAnnouncement, UnsignedChannelUpdate};
+ use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId};
+ use crate::routing::router::RouteHop;
+ use crate::routing::scoring::{ChannelUsage, Score};
+ use crate::util::ser::{ReadableArgs, Writeable};
+ use crate::util::test_utils::TestLogger;
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::hashes::Hash;
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
use core::time::Duration;
- use io;
+ use crate::io;
fn source_privkey() -> SecretKey {
SecretKey::from_slice(&[42; 32]).unwrap()
bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, &node_2_secret),
contents: unsigned_announcement,
};
- let chain_source: Option<&::util::test_utils::TestChainSource> = None;
+ let chain_source: Option<&crate::util::test_utils::TestChainSource> = None;
network_graph.update_channel_from_announcement(
&signed_announcement, &chain_source).unwrap();
update_channel(network_graph, short_channel_id, node_1_key, 0);
// You may not use this file except in accordance with one or both of these
// licenses.
-use routing::gossip::{NetworkGraph, P2PGossipSync};
-use ln::features::{ChannelFeatures, NodeFeatures};
-use ln::msgs::{UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
+use crate::routing::gossip::{NetworkGraph, P2PGossipSync};
+use crate::ln::features::{ChannelFeatures, NodeFeatures};
+use crate::ln::msgs::{UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate, MAX_VALUE_MSAT};
-use util::test_utils;
-use util::ser::Writeable;
+use crate::util::test_utils;
+use crate::util::ser::Writeable;
use bitcoin::hashes::sha256d::Hash as Sha256dHash;
use bitcoin::hashes::Hash;
use bitcoin::secp256k1::{PublicKey,SecretKey};
use bitcoin::secp256k1::{Secp256k1, All};
-use prelude::*;
-use sync::{self, Arc};
+use crate::prelude::*;
+use crate::sync::{self, Arc};
// Using the same keys for LN and BTC ids
pub(super) fn add_channel(
// You may not use this file except in accordance with one or both of these
// licenses.
-use io;
+use crate::io;
#[cfg(not(fuzzing))]
mod real_chacha {
#[cfg(test)]
mod test {
- use prelude::*;
+ use crate::prelude::*;
use core::iter::repeat;
use super::ChaCha20;
// This is a port of Andrew Moons poly1305-donna
// https://github.com/floodyberry/poly1305-donna
-use ln::msgs::DecodeError;
-use util::ser::{FixedLengthReader, LengthRead, LengthReadableArgs, Readable, Writeable, Writer};
-use io::{self, Read, Write};
+use crate::ln::msgs::DecodeError;
+use crate::util::ser::{FixedLengthReader, LengthRead, LengthReadableArgs, Readable, Writeable, Writer};
+use crate::io::{self, Read, Write};
#[cfg(not(fuzzing))]
mod real_chachapoly {
- use util::chacha20::ChaCha20;
- use util::poly1305::Poly1305;
+ use crate::util::chacha20::ChaCha20;
+ use crate::util::poly1305::Poly1305;
use bitcoin::hashes::cmp::fixed_time_eq;
#[derive(Clone, Copy)]
#[cfg(test)]
mod tests {
- use ln::msgs::DecodeError;
+ use crate::ln::msgs::DecodeError;
use super::{ChaChaPolyReadAdapter, ChaChaPolyWriteAdapter};
- use util::ser::{self, FixedLengthReader, LengthReadableArgs, Writeable};
+ use crate::util::ser::{self, FixedLengthReader, LengthReadableArgs, Writeable};
// Used for for testing various lengths of serialization.
#[derive(Debug, PartialEq, Eq)]
//! Various user-configurable channel limits and settings which ChannelManager
//! applies for you.
-use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
-use ln::channelmanager::{BREAKDOWN_TIMEOUT, MAX_LOCAL_BREAKDOWN_TIMEOUT};
+use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
+use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, MAX_LOCAL_BREAKDOWN_TIMEOUT};
/// Configuration we set when applicable.
///
}
}
-impl ::util::ser::Writeable for LegacyChannelConfig {
- fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::io::Error> {
+impl crate::util::ser::Writeable for LegacyChannelConfig {
+ fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
write_tlv_fields!(writer, {
(0, self.options.forwarding_fee_proportional_millionths, required),
(1, self.options.max_dust_htlc_exposure_msat, (default_value, 5_000_000)),
}
}
-impl ::util::ser::Readable for LegacyChannelConfig {
- fn read<R: ::io::Read>(reader: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
+impl crate::util::ser::Readable for LegacyChannelConfig {
+ fn read<R: crate::io::Read>(reader: &mut R) -> Result<Self, crate::ln::msgs::DecodeError> {
let mut forwarding_fee_proportional_millionths = 0;
let mut max_dust_htlc_exposure_msat = 5_000_000;
let mut cltv_expiry_delta = 0;
// You may not use this file except in accordance with one or both of these
// licenses.
-use ln::channel::{ANCHOR_OUTPUT_VALUE_SATOSHI, MIN_CHAN_DUST_LIMIT_SATOSHIS};
-use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, HolderCommitmentTransaction, CommitmentTransaction, ChannelTransactionParameters, TrustedCommitmentTransaction, ClosingTransaction};
-use ln::{chan_utils, msgs, PaymentPreimage};
-use chain::keysinterface::{Sign, InMemorySigner, BaseSign};
+use crate::ln::channel::{ANCHOR_OUTPUT_VALUE_SATOSHI, MIN_CHAN_DUST_LIMIT_SATOSHIS};
+use crate::ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, HolderCommitmentTransaction, CommitmentTransaction, ChannelTransactionParameters, TrustedCommitmentTransaction, ClosingTransaction};
+use crate::ln::{chan_utils, msgs, PaymentPreimage};
+use crate::chain::keysinterface::{Sign, InMemorySigner, BaseSign};
-use prelude::*;
+use crate::prelude::*;
use core::cmp;
-use sync::{Mutex, Arc};
-#[cfg(test)] use sync::MutexGuard;
+use crate::sync::{Mutex, Arc};
+#[cfg(test)] use crate::sync::MutexGuard;
use bitcoin::blockdata::transaction::{Transaction, EcdsaSighashType};
use bitcoin::util::sighash;
use bitcoin::secp256k1;
use bitcoin::secp256k1::{SecretKey, PublicKey};
use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
-use util::ser::{Writeable, Writer};
-use io::Error;
+use crate::util::ser::{Writeable, Writer};
+use crate::io::Error;
/// Initial value for revoked commitment downward counter
pub const INITIAL_REVOKED_COMMITMENT_NUMBER: u64 = 1 << 48;
//! Error types live here.
-use ln::script::ShutdownScript;
+use crate::ln::script::ShutdownScript;
use alloc::string::String;
use core::fmt;
//! future, as well as generate and broadcast funding transactions handle payment preimages and a
//! few other things.
-use chain::keysinterface::SpendableOutputDescriptor;
-use ln::chan_utils::HTLCOutputInCommitment;
-use ln::channelmanager::PaymentId;
-use ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
-use ln::features::ChannelTypeFeatures;
-use ln::msgs;
-use ln::msgs::DecodeError;
-use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
-use routing::gossip::NetworkUpdate;
-use util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, VecReadWrapper, VecWriteWrapper};
-use routing::router::{RouteHop, RouteParameters};
+use crate::chain::keysinterface::SpendableOutputDescriptor;
+use crate::ln::chan_utils::HTLCOutputInCommitment;
+use crate::ln::channelmanager::PaymentId;
+use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
+use crate::ln::features::ChannelTypeFeatures;
+use crate::ln::msgs;
+use crate::ln::msgs::DecodeError;
+use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
+use crate::routing::gossip::NetworkUpdate;
+use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, VecReadWrapper, VecWriteWrapper};
+use crate::routing::router::{RouteHop, RouteParameters};
use bitcoin::{PackedLockTime, Transaction, OutPoint};
use bitcoin::blockdata::script::Script;
use bitcoin::hashes::Hash;
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::secp256k1::PublicKey;
-use io;
-use prelude::*;
+use crate::io;
+use crate::prelude::*;
use core::time::Duration;
use core::ops::Deref;
-use sync::Arc;
+use crate::sync::Arc;
/// Some information provided on receipt of payment depends on whether the payment received is a
/// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
//! Low level invoice utilities.
use bitcoin::bech32::{u5, FromBase32};
-use prelude::*;
+use crate::prelude::*;
/// Construct the invoice's HRP and signatureless data into a preimage to be hashed.
pub fn construct_invoice_preimage(hrp_bytes: &[u8], data_without_signature: &[u5]) -> Vec<u8> {
use core::fmt;
#[cfg(c_bindings)]
-use prelude::*; // Needed for String
+use crate::prelude::*; // Needed for String
static LOG_LEVEL_NAMES: [&'static str; 6] = ["GOSSIP", "TRACE", "DEBUG", "INFO", "WARN", "ERROR"];
#[cfg(test)]
mod tests {
- use util::logger::{Logger, Level};
- use util::test_utils::TestLogger;
- use sync::Arc;
+ use crate::util::logger::{Logger, Level};
+ use crate::util::test_utils::TestLogger;
+ use crate::sync::Arc;
#[test]
fn test_level_show() {
// You may not use this file except in accordance with one or both of these
// licenses.
-use chain::transaction::OutPoint;
-use chain::keysinterface::SpendableOutputDescriptor;
+use crate::chain::transaction::OutPoint;
+use crate::chain::keysinterface::SpendableOutputDescriptor;
use bitcoin::hash_types::Txid;
use bitcoin::blockdata::transaction::Transaction;
-use routing::router::Route;
-use ln::chan_utils::HTLCClaim;
-use util::logger::DebugBytes;
+use crate::routing::router::Route;
+use crate::ln::chan_utils::HTLCClaim;
+use crate::util::logger::DebugBytes;
/// Logs a pubkey in hex format.
#[macro_export]
}
macro_rules! log_funding_channel_id {
($funding_txid: expr, $funding_txo: expr) => {
- ::util::macro_logger::DebugFundingChannelId(&$funding_txid, $funding_txo)
+ $crate::util::macro_logger::DebugFundingChannelId(&$funding_txid, $funding_txo)
}
}
}
macro_rules! log_funding_info {
($key_storage: expr) => {
- ::util::macro_logger::DebugFundingInfo(&$key_storage.get_funding_txo())
+ $crate::util::macro_logger::DebugFundingInfo(&$key_storage.get_funding_txo())
}
}
}
macro_rules! log_route {
($obj: expr) => {
- ::util::macro_logger::DebugRoute(&$obj)
+ $crate::util::macro_logger::DebugRoute(&$obj)
}
}
macro_rules! log_tx {
($obj: expr) => {
- ::util::macro_logger::DebugTx(&$obj)
+ $crate::util::macro_logger::DebugTx(&$obj)
}
}
macro_rules! log_spendable {
($obj: expr) => {
- ::util::macro_logger::DebugSpendable(&$obj)
+ $crate::util::macro_logger::DebugSpendable(&$obj)
}
}
//! <https://lightning.readthedocs.io/lightning-signmessage.7.html>
//! <https://api.lightning.community/#signmessage>
-use prelude::*;
+use crate::prelude::*;
use crate::util::zbase32;
use bitcoin::hashes::{sha256d, Hash};
use bitcoin::secp256k1::ecdsa::{RecoverableSignature, RecoveryId};
#[cfg(test)]
mod test {
use core::str::FromStr;
- use util::message_signing::{sign, recover_pk, verify};
+ use crate::util::message_signing::{sign, recover_pk, verify};
use bitcoin::secp256k1::ONE_KEY;
use bitcoin::secp256k1::{PublicKey, Secp256k1};
use core::ops::Deref;
use bitcoin::hashes::hex::ToHex;
-use io::{self};
-use routing::scoring::WriteableScore;
+use crate::io::{self};
+use crate::routing::scoring::WriteableScore;
use crate::{chain::{keysinterface::{Sign, KeysInterface}, self, transaction::{OutPoint}, chaininterface::{BroadcasterInterface, FeeEstimator}, chainmonitor::{Persist, MonitorUpdateId}, channelmonitor::{ChannelMonitor, ChannelMonitorUpdate}}, ln::channelmanager::ChannelManager, routing::gossip::NetworkGraph};
use super::{logger::Logger, ser::Writeable};
#[cfg(test)]
mod test {
- use prelude::*;
+ use crate::prelude::*;
use core::iter::repeat;
- use util::poly1305::Poly1305;
+ use crate::util::poly1305::Poly1305;
fn poly1305(key: &[u8], msg: &[u8], mac: &mut [u8]) {
let mut poly = Poly1305::new(key);
pub(crate) mod fake_scid {
use bitcoin::hash_types::BlockHash;
use bitcoin::hashes::hex::FromHex;
- use chain::keysinterface::{Sign, KeysInterface};
- use util::chacha20::ChaCha20;
- use util::scid_utils;
+ use crate::chain::keysinterface::{Sign, KeysInterface};
+ use crate::util::chacha20::ChaCha20;
+ use crate::util::scid_utils;
use core::convert::TryInto;
use core::ops::Deref;
mod tests {
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::network::constants::Network;
- use util::scid_utils::fake_scid::{is_valid_phantom, MAINNET_SEGWIT_ACTIVATION_HEIGHT, MAX_TX_INDEX, MAX_NAMESPACES, Namespace, NAMESPACE_ID_BITMASK, segwit_activation_height, TEST_SEGWIT_ACTIVATION_HEIGHT};
- use util::scid_utils;
- use util::test_utils;
- use sync::Arc;
+ use crate::util::scid_utils::fake_scid::{is_valid_phantom, MAINNET_SEGWIT_ACTIVATION_HEIGHT, MAX_TX_INDEX, MAX_NAMESPACES, Namespace, NAMESPACE_ID_BITMASK, segwit_activation_height, TEST_SEGWIT_ACTIVATION_HEIGHT};
+ use crate::util::scid_utils;
+ use crate::util::test_utils;
+ use crate::sync::Arc;
#[test]
fn namespace_identifier_is_within_range() {
//! A very simple serialization framework which is used to serialize/deserialize messages as well
//! as ChannelsManagers and ChannelMonitors.
-use prelude::*;
-use io::{self, Read, Write};
-use io_extras::{copy, sink};
+use crate::prelude::*;
+use crate::io::{self, Read, Write};
+use crate::io_extras::{copy, sink};
use core::hash::Hash;
-use sync::Mutex;
+use crate::sync::Mutex;
use core::cmp;
use core::convert::TryFrom;
use core::ops::Deref;
use bitcoin::hash_types::{Txid, BlockHash};
use core::marker::Sized;
use core::time::Duration;
-use ln::msgs::DecodeError;
-use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
+use crate::ln::msgs::DecodeError;
+use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
-use util::byte_utils::{be48_to_array, slice_to_be48};
+use crate::util::byte_utils::{be48_to_array, slice_to_be48};
/// serialization buffer size
pub const MAX_BUF_SIZE: usize = 64 * 1024;
#[cfg(test)]
mod tests {
use core::convert::TryFrom;
- use util::ser::{Readable, Hostname, Writeable};
+ use crate::util::ser::{Readable, Hostname, Writeable};
#[test]
fn hostname_conversion() {
$field.write($stream)?;
};
($stream: expr, $type: expr, $field: expr, vec_type) => {
- encode_tlv!($stream, $type, ::util::ser::VecWriteWrapper(&$field), required);
+ encode_tlv!($stream, $type, $crate::util::ser::VecWriteWrapper(&$field), required);
};
($stream: expr, $optional_type: expr, $optional_field: expr, option) => {
if let Some(ref field) = $optional_field {
macro_rules! encode_tlv_stream {
($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => { {
#[allow(unused_imports)]
- use {
+ use $crate::{
ln::msgs::DecodeError,
util::ser,
util::ser::BigSize,
$len.0 += field_len;
};
($len: expr, $type: expr, $field: expr, vec_type) => {
- get_varint_length_prefixed_tlv_length!($len, $type, ::util::ser::VecWriteWrapper(&$field), required);
+ get_varint_length_prefixed_tlv_length!($len, $type, $crate::util::ser::VecWriteWrapper(&$field), required);
};
($len: expr, $optional_type: expr, $optional_field: expr, option) => {
if let Some(ref field) = $optional_field {
macro_rules! encode_varint_length_prefixed_tlv {
($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}) => { {
- use util::ser::BigSize;
+ use $crate::util::ser::BigSize;
let len = {
#[allow(unused_mut)]
- let mut len = ::util::ser::LengthCalculatingWriter(0);
+ let mut len = $crate::util::ser::LengthCalculatingWriter(0);
$(
get_varint_length_prefixed_tlv_length!(len, $type, $field, $fieldty);
)*
decode_tlv!($reader, $field, required)
}};
($reader: expr, $field: ident, required) => {{
- $field = ::util::ser::Readable::read(&mut $reader)?;
+ $field = $crate::util::ser::Readable::read(&mut $reader)?;
}};
($reader: expr, $field: ident, vec_type) => {{
- let f: ::util::ser::VecReadWrapper<_> = ::util::ser::Readable::read(&mut $reader)?;
+ let f: $crate::util::ser::VecReadWrapper<_> = $crate::util::ser::Readable::read(&mut $reader)?;
$field = Some(f.0);
}};
($reader: expr, $field: ident, option) => {{
- $field = Some(::util::ser::Readable::read(&mut $reader)?);
+ $field = Some($crate::util::ser::Readable::read(&mut $reader)?);
}};
($reader: expr, $field: ident, ignorable) => {{
- $field = ::util::ser::MaybeReadable::read(&mut $reader)?;
+ $field = $crate::util::ser::MaybeReadable::read(&mut $reader)?;
}};
($reader: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
$field = Some($trait::read(&mut $reader $(, $read_arg)*)?);
macro_rules! decode_tlv_stream {
($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
$(, $decode_custom_tlv: expr)?) => { {
- use ln::msgs::DecodeError;
+ use $crate::ln::msgs::DecodeError;
let mut last_seen_type: Option<u64> = None;
let mut stream_ref = $stream;
'tlv_read: loop {
- use util::ser;
+ use $crate::util::ser;
// First decode the type of this TLV:
let typ: ser::BigSize = {
// UnexpectedEof. This should in every case be largely cosmetic, but its nice to
// pass the TLV test vectors exactly, which requre this distinction.
let mut tracking_reader = ser::ReadTrackingReader::new(&mut stream_ref);
- match ser::Readable::read(&mut tracking_reader) {
+ match $crate::util::ser::Readable::read(&mut tracking_reader) {
Err(DecodeError::ShortRead) => {
if !tracking_reader.have_read {
break 'tlv_read;
last_seen_type = Some(typ.0);
// Finally, read the length and value itself:
- let length: ser::BigSize = ser::Readable::read(&mut stream_ref)?;
+ let length: ser::BigSize = $crate::util::ser::Readable::read(&mut stream_ref)?;
let mut s = ser::FixedLengthReader::new(&mut stream_ref, length.0);
match typ.0 {
$($type => {
macro_rules! impl_writeable_msg {
($st:ident, {$($field:ident),* $(,)*}, {$(($type: expr, $tlvfield: ident, $fieldty: tt)),* $(,)*}) => {
- impl ::util::ser::Writeable for $st {
- fn write<W: ::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
+ impl $crate::util::ser::Writeable for $st {
+ fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
$( self.$field.write(w)?; )*
encode_tlv_stream!(w, {$(($type, self.$tlvfield, $fieldty)),*});
Ok(())
}
}
- impl ::util::ser::Readable for $st {
- fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
- $(let $field = ::util::ser::Readable::read(r)?;)*
+ impl $crate::util::ser::Readable for $st {
+ fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
+ $(let $field = $crate::util::ser::Readable::read(r)?;)*
$(init_tlv_field_var!($tlvfield, $fieldty);)*
decode_tlv_stream!(r, {$(($type, $tlvfield, $fieldty)),*});
Ok(Self {
macro_rules! impl_writeable {
($st:ident, {$($field:ident),*}) => {
- impl ::util::ser::Writeable for $st {
- fn write<W: ::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
+ impl $crate::util::ser::Writeable for $st {
+ fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
$( self.$field.write(w)?; )*
Ok(())
}
}
}
- impl ::util::ser::Readable for $st {
- fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
+ impl $crate::util::ser::Readable for $st {
+ fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
Ok(Self {
- $($field: ::util::ser::Readable::read(r)?),*
+ $($field: $crate::util::ser::Readable::read(r)?),*
})
}
}
/// Reads a suffix added by write_tlv_fields.
macro_rules! read_tlv_fields {
($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { {
- let tlv_len: ::util::ser::BigSize = ::util::ser::Readable::read($stream)?;
- let mut rd = ::util::ser::FixedLengthReader::new($stream, tlv_len.0);
+ let tlv_len: $crate::util::ser::BigSize = $crate::util::ser::Readable::read($stream)?;
+ let mut rd = $crate::util::ser::FixedLengthReader::new($stream, tlv_len.0);
decode_tlv_stream!(&mut rd, {$(($type, $field, $fieldty)),*});
- rd.eat_remaining().map_err(|_| ::ln::msgs::DecodeError::ShortRead)?;
+ rd.eat_remaining().map_err(|_| $crate::ln::msgs::DecodeError::ShortRead)?;
} }
}
macro_rules! init_tlv_field_var {
($field: ident, (default_value, $default: expr)) => {
- let mut $field = ::util::ser::OptionDeserWrapper(None);
+ let mut $field = $crate::util::ser::OptionDeserWrapper(None);
};
($field: ident, required) => {
- let mut $field = ::util::ser::OptionDeserWrapper(None);
+ let mut $field = $crate::util::ser::OptionDeserWrapper(None);
};
($field: ident, vec_type) => {
let mut $field = Some(Vec::new());
/// serialized.
macro_rules! impl_writeable_tlv_based {
($st: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
- impl ::util::ser::Writeable for $st {
- fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
+ impl $crate::util::ser::Writeable for $st {
+ fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
write_tlv_fields!(writer, {
$(($type, self.$field, $fieldty)),*
});
#[inline]
fn serialized_length(&self) -> usize {
- use util::ser::BigSize;
+ use $crate::util::ser::BigSize;
let len = {
#[allow(unused_mut)]
- let mut len = ::util::ser::LengthCalculatingWriter(0);
+ let mut len = $crate::util::ser::LengthCalculatingWriter(0);
$(
get_varint_length_prefixed_tlv_length!(len, $type, self.$field, $fieldty);
)*
len.0
};
- let mut len_calc = ::util::ser::LengthCalculatingWriter(0);
+ let mut len_calc = $crate::util::ser::LengthCalculatingWriter(0);
BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
len + len_calc.0
}
}
- impl ::util::ser::Readable for $st {
- fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
+ impl $crate::util::ser::Readable for $st {
+ fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
$(
init_tlv_field_var!($field, $fieldty);
)*
{$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
),* $(,)*;
$(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => {
- impl ::util::ser::Writeable for $st {
- fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
+ impl $crate::util::ser::Writeable for $st {
+ fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
match self {
$($st::$variant_name { $(ref $field),* } => {
let id: u8 = $variant_id;
$(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
$($(($tuple_variant_id, $tuple_variant_name)),*)*);
- impl ::util::ser::MaybeReadable for $st {
- fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Option<Self>, ::ln::msgs::DecodeError> {
- let id: u8 = ::util::ser::Readable::read(reader)?;
+ impl $crate::util::ser::MaybeReadable for $st {
+ fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Option<Self>, $crate::ln::msgs::DecodeError> {
+ let id: u8 = $crate::util::ser::Readable::read(reader)?;
match id {
$($variant_id => {
// Because read_tlv_fields creates a labeled loop, we cannot call it twice
$(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
$(($tuple_variant_id, $tuple_variant_name)),*);
- impl ::util::ser::Readable for $st {
- fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
- let id: u8 = ::util::ser::Readable::read(reader)?;
+ impl $crate::util::ser::Readable for $st {
+ fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
+ let id: u8 = $crate::util::ser::Readable::read(reader)?;
match id {
$($variant_id => {
// Because read_tlv_fields creates a labeled loop, we cannot call it twice
#[cfg(test)]
mod tests {
- use io::{self, Cursor};
- use prelude::*;
- use ln::msgs::DecodeError;
- use util::ser::{Writeable, HighZeroBytesDroppedBigSize, VecWriter};
+ use crate::io::{self, Cursor};
+ use crate::prelude::*;
+ use crate::ln::msgs::DecodeError;
+ use crate::util::ser::{Writeable, HighZeroBytesDroppedBigSize, VecWriter};
use bitcoin::secp256k1::PublicKey;
// The BOLT TLV test cases don't include any tests which use our "required-value" logic since
// You may not use this file except in accordance with one or both of these
// licenses.
-use chain;
-use chain::WatchedOutput;
-use chain::chaininterface;
-use chain::chaininterface::ConfirmationTarget;
-use chain::chainmonitor;
-use chain::chainmonitor::MonitorUpdateId;
-use chain::channelmonitor;
-use chain::channelmonitor::MonitorEvent;
-use chain::transaction::OutPoint;
-use chain::keysinterface;
-use ln::channelmanager;
-use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
-use ln::{msgs, wire};
-use ln::script::ShutdownScript;
-use routing::scoring::FixedPenaltyScorer;
-use util::enforcing_trait_impls::{EnforcingSigner, EnforcementState};
-use util::events;
-use util::logger::{Logger, Level, Record};
-use util::ser::{Readable, ReadableArgs, Writer, Writeable};
+use crate::chain;
+use crate::chain::WatchedOutput;
+use crate::chain::chaininterface;
+use crate::chain::chaininterface::ConfirmationTarget;
+use crate::chain::chainmonitor;
+use crate::chain::chainmonitor::MonitorUpdateId;
+use crate::chain::channelmonitor;
+use crate::chain::channelmonitor::MonitorEvent;
+use crate::chain::transaction::OutPoint;
+use crate::chain::keysinterface;
+use crate::ln::channelmanager;
+use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
+use crate::ln::{msgs, wire};
+use crate::ln::script::ShutdownScript;
+use crate::routing::scoring::FixedPenaltyScorer;
+use crate::util::enforcing_trait_impls::{EnforcingSigner, EnforcementState};
+use crate::util::events;
+use crate::util::logger::{Logger, Level, Record};
+use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use regex;
-use io;
-use prelude::*;
+use crate::io;
+use crate::prelude::*;
use core::time::Duration;
-use sync::{Mutex, Arc};
+use crate::sync::{Mutex, Arc};
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use core::mem;
use bitcoin::bech32::u5;
-use chain::keysinterface::{InMemorySigner, Recipient, KeyMaterial};
+use crate::chain::keysinterface::{InMemorySigner, Recipient, KeyMaterial};
#[cfg(feature = "std")]
use std::time::{SystemTime, UNIX_EPOCH};
use bitcoin::consensus::Encodable;
use bitcoin::consensus::encode::VarInt;
-use ln::msgs::MAX_VALUE_MSAT;
+use crate::ln::msgs::MAX_VALUE_MSAT;
-use prelude::*;
-use io_extras::sink;
+use crate::prelude::*;
+use crate::io_extras::sink;
use core::cmp::Ordering;
pub fn sort_outputs<T, C : Fn(&T, &T) -> Ordering>(outputs: &mut Vec<(TxOut, T)>, tie_breaker: C) {
use alloc::sync::Arc;
use core::mem;
-use sync::{Condvar, Mutex};
+use crate::sync::{Condvar, Mutex};
-use prelude::*;
+use crate::prelude::*;
#[cfg(any(test, feature = "std"))]
use std::time::{Duration, Instant};
#[cfg(feature = "std")]
#[test]
fn test_wait_timeout() {
- use sync::Arc;
+ use crate::sync::Arc;
use std::thread;
let persistence_notifier = Arc::new(Notifier::new());
* at your option.
*/
-use prelude::*;
+use crate::prelude::*;
const ALPHABET: &'static [u8] = b"ybndrfg8ejkmcpqxot1uwisza345h769";