Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions fuzz/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,8 +20,8 @@ stdin_fuzz = []
[dependencies]
lightning = { path = "../lightning", features = ["regex", "hashbrown", "_test_utils"] }
lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync" }
bitcoin = { version = "0.29.0", features = ["secp-lowmemory"] }
hex = "0.3"
bitcoin = { version = "0.30.2", features = ["secp-lowmemory"] }
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
hashbrown = "0.8"

afl = { version = "0.12", optional = true }
Expand Down
12 changes: 6 additions & 6 deletions fuzz/src/chanmon_consistency.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,9 +20,9 @@

use bitcoin::blockdata::constants::genesis_block;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::blockdata::script::{Builder, Script};
use bitcoin::blockdata::script::{Builder, ScriptBuf};
use bitcoin::blockdata::opcodes;
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::network::constants::Network;

use bitcoin::hashes::Hash as TraitImport;
Expand DownExpand Up@@ -270,11 +270,11 @@ impl SignerProvider for KeyProvider {
})
}

fn get_destination_script(&self) -> Result<Script, ()> {
fn get_destination_script(&self) -> Result<ScriptBuf, ()> {
let secp_ctx = Secp256k1::signing_only();
let channel_monitor_claim_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, self.node_secret[31]]).unwrap();
let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script())
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(our_channel_monitor_claim_key_hash).into_script())
}

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
Expand DownExpand Up@@ -343,7 +343,7 @@ type ChanMan<'a> = ChannelManager<Arc<TestChainMonitor>, Arc<TestBroadcaster>, A
fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(PaymentSecret, PaymentHash)> {
let mut payment_hash;
for _ in 0..256 {
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).into_inner());
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).to_byte_array());
if let Ok(payment_secret) = dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None) {
return Some((payment_secret, payment_hash));
}
Expand DownExpand Up@@ -565,7 +565,7 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
let events = $source.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
let tx = Transaction { version: $chan_id, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: $chan_id, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: *channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
funding_output = OutPoint { txid: tx.txid(), index: 0 };
Expand Down
30 changes: 13 additions & 17 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

13 changes: 7 additions & 6 deletions fuzz/src/onion_message.rs
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
// Imports that need to be added manually
use bitcoin::bech32::u5;
use bitcoin::blockdata::script::Script;
use bitcoin::blockdata::script::ScriptBuf;
use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1::ecdsa::RecoverableSignature;
Expand DownExpand Up@@ -199,13 +199,14 @@ impl SignerProvider for KeyProvider {

fn read_chan_signer(&self, _data: &[u8]) -> Result<TestChannelSigner, DecodeError> { unreachable!() }

fn get_destination_script(&self) -> Result<Script, ()> { unreachable!() }
fn get_destination_script(&self) -> Result<ScriptBuf, ()> { unreachable!() }

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { unreachable!() }
}

#[cfg(test)]
mod tests {
use bitcoin::hashes::hex::FromHex;
use lightning::util::logger::{Logger, Record};
use std::collections::HashMap;
use std::sync::Mutex;
Expand DownExpand Up@@ -258,7 +259,7 @@ mod tests {
000000000000000000000000000000000000000005600000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(one_hop_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(one_hop_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(),
Expand DownExpand Up@@ -302,7 +303,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_hops_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_hops_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -343,7 +344,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_two_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_two_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -384,7 +385,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(three_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(three_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand Down
2 changes: 1 addition & 1 deletion lightning-background-processor/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ no-std = ["bitcoin/no-std", "lightning/no-std", "lightning-rapid-gossip-sync/no-
default = ["std"]

[dependencies]
bitcoin = { version = "0.29.0", default-features = false }
bitcoin = { version = "0.30.2", default-features = false }
lightning = { version = "0.0.118", path = "../lightning", default-features = false }
lightning-rapid-gossip-sync = { version = "0.0.118", path = "../lightning-rapid-gossip-sync", default-features = false }

Expand Down
4 changes: 2 additions & 2 deletions lightning-background-processor/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -845,7 +845,7 @@ impl Drop for BackgroundProcessor {
#[cfg(all(feature = "std", test))]
mod tests {
use bitcoin::blockdata::constants::{genesis_block, ChainHash};
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1};
Expand DownExpand Up@@ -1254,7 +1254,7 @@ mod tests {
assert_eq!(channel_value_satoshis, $channel_value);
assert_eq!(user_channel_id, 42);

let tx = Transaction { version: 1 as i32, lock_time: PackedLockTime(0), input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: 1 as i32, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
(temporary_channel_id, tx)
Expand Down
3 changes: 2 additions & 1 deletion lightning-block-sync/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,8 @@ rest-client = [ "serde_json", "chunked_transfer" ]
rpc-client = [ "serde_json", "chunked_transfer" ]

[dependencies]
bitcoin = "0.29.0"
bitcoin = "0.30.2"
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
lightning = { version = "0.0.118", path = "../lightning" }
tokio = { version = "1.0", features = [ "io-util", "net", "time" ], optional = true }
serde_json = { version = "1.0", optional = true }
Expand Down
44 changes: 24 additions & 20 deletions lightning-block-sync/src/convert.rs
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
use crate::http::{BinaryResponse, JsonResponse};
use crate::utils::hex_to_uint256;
use crate::utils::hex_to_work;
use crate::{BlockHeaderData, BlockSourceError};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::consensus::encode;
use bitcoin::hash_types::{BlockHash, TxMerkleNode, Txid};
use bitcoin::hashes::hex::FromHex;
Expand DownExpand Up@@ -88,17 +88,21 @@ impl TryFrom<serde_json::Value> for BlockHeaderData {
} }

Ok(BlockHeaderData {
header: BlockHeader {
version: get_field!("version", as_i64).try_into().map_err(|_| ())?,
header: Header {
version: bitcoin::blockdata::block::Version::from_consensus(
get_field!("version", as_i64).try_into().map_err(|_| ())?
),
prev_blockhash: if let Some(hash_str) = response.get("previousblockhash") {
BlockHash::from_hex(hash_str.as_str().ok_or(())?).map_err(|_| ())?
BlockHash::from_str(hash_str.as_str().ok_or(())?).map_err(|_| ())?
} else { BlockHash::all_zeros() },
merkle_root: TxMerkleNode::from_hex(get_field!("merkleroot", as_str)).map_err(|_| ())?,
merkle_root: TxMerkleNode::from_str(get_field!("merkleroot", as_str)).map_err(|_| ())?,
time: get_field!("time", as_u64).try_into().map_err(|_| ())?,
bits: u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?),
bits: bitcoin::CompactTarget::from_consensus(
u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?)
),
nonce: get_field!("nonce", as_u64).try_into().map_err(|_| ())?,
},
chainwork: hex_to_uint256(get_field!("chainwork", as_str)).map_err(|_| ())?,
chainwork: hex_to_work(get_field!("chainwork", as_str)).map_err(|_| ())?,
height: get_field!("height", as_u64).try_into().map_err(|_| ())?,
})
}
Expand DownExpand Up@@ -132,7 +136,7 @@ impl TryInto<(BlockHash, Option<u32>)> for JsonResponse {
}

let hash = match &self.0["bestblockhash"] {
serde_json::Value::String(hex_data) => match BlockHash::from_hex(&hex_data) {
serde_json::Value::String(hex_data) => match BlockHash::from_str(&hex_data) {
Err(_) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid hex data")),
Ok(block_hash) => block_hash,
},
Expand DownExpand Up@@ -288,8 +292,8 @@ pub(crate) mod tests {
use super::*;
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::hashes::Hash;
use bitcoin::hashes::hex::ToHex;
use bitcoin::network::constants::Network;
use hex::DisplayHex;
use serde_json::value::Number;
use serde_json::Value;

Expand All@@ -298,14 +302,14 @@ pub(crate) mod tests {
fn from(data: BlockHeaderData) -> Self {
let BlockHeaderData { chainwork, height, header } = data;
serde_json::json!({
"chainwork": chainwork.to_string()["0x".len()..],
"chainwork": chainwork.to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI this could be format!("{:064x}", chainwork) which conveys the intent better.

"height": height,
"version": header.version,
"merkleroot": header.merkle_root.to_hex(),
"version": header.version.to_consensus(),
"merkleroot": header.merkle_root.to_string(),
"time": header.time,
"nonce": header.nonce,
"bits": header.bits.to_hex(),
"previousblockhash": header.prev_blockhash.to_hex(),
"bits": header.bits.to_consensus().to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

format!("{08x}", header.bits.to_consensus()) would convey the meaning better but your code is actually faster because std formatting is over-complicated. I've opened an issue to support hex directly on CompactTarget but that will still be slower than your code.

"previousblockhash": header.prev_blockhash.to_string(),
})
}
}
Expand DownExpand Up@@ -394,7 +398,7 @@ pub(crate) mod tests {
#[test]
fn into_block_header_from_json_response_with_valid_header_array() {
let genesis_block = genesis_block(Network::Bitcoin);
let best_block_header = BlockHeader {
let best_block_header = Header {
prev_blockhash: genesis_block.block_hash(),
..genesis_block.header
};
Expand DownExpand Up@@ -541,7 +545,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_without_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Err(e) => panic!("Unexpected error: {:?}", e),
Expand All@@ -556,7 +560,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_unexpected_blocks_type() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": "foo",
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -572,7 +576,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_invalid_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": std::u64::MAX,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -588,7 +592,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": 1,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand Down
10 changes: 5 additions & 5 deletions lightning-block-sync/src/init.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,7 +4,7 @@
use crate::{BlockSource, BlockSourceResult, Cache, ChainNotifier};
use crate::poll::{ChainPoller, Validate, ValidatedBlockHeader};

use bitcoin::blockdata::block::BlockHeader;
use bitcoin::blockdata::block::Header;
use bitcoin::hash_types::BlockHash;
use bitcoin::network::constants::Network;

Expand DownExpand Up@@ -211,11 +211,11 @@ impl<'a, C: Cache> Cache for ReadOnlyCache<'a, C> {
struct DynamicChainListener<'a, L: chain::Listen + ?Sized>(&'a L);

impl<'a, L: chain::Listen + ?Sized> chain::Listen for DynamicChainListener<'a, L> {
fn filtered_block_connected(&self, _header: &BlockHeader, _txdata: &chain::transaction::TransactionData, _height: u32) {
fn filtered_block_connected(&self, _header: &Header, _txdata: &chain::transaction::TransactionData, _height: u32) {
unreachable!()
}

fn block_disconnected(&self, header: &BlockHeader, height: u32) {
fn block_disconnected(&self, header: &Header, height: u32) {
self.0.block_disconnected(header, height)
}
}
Expand All@@ -234,15 +234,15 @@ impl<'a, L: chain::Listen + ?Sized> chain::Listen for ChainListenerSet<'a, L> {
}
}

fn filtered_block_connected(&self, header: &BlockHeader, txdata: &chain::transaction::TransactionData, height: u32) {
fn filtered_block_connected(&self, header: &Header, txdata: &chain::transaction::TransactionData, height: u32) {
for (starting_height, chain_listener) in self.0.iter() {
if height > *starting_height {
chain_listener.filtered_block_connected(header, txdata, height);
}
}
}

fn block_disconnected(&self, _header: &BlockHeader, _height: u32) {
fn block_disconnected(&self, _header: &Header, _height: u32) {
unreachable!()
}
}
Expand Down
13 changes: 6 additions & 7 deletions lightning-block-sync/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,9 +47,9 @@ mod utils;

use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::hash_types::BlockHash;
use bitcoin::util::uint::Uint256;
use bitcoin::pow::Work;

use lightning::chain;
use lightning::chain::Listen;
Expand DownExpand Up@@ -147,14 +147,13 @@ impl BlockSourceError {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlockHeaderData {
/// The block header itself.
pub header: BlockHeader,
pub header: Header,

/// The block height where the genesis block has height 0.
pub height: u32,

/// The total chain work in expected number of double-SHA256 hashes required to build a chain
/// of equivalent weight.
pub chainwork: Uint256,
/// The total chain work required to build a chain of equivalent weight.
pub chainwork: Work,
}

/// A block including either all its transactions or only the block header.
Expand All@@ -166,7 +165,7 @@ pub enum BlockData {
/// A block containing all its transactions.
FullBlock(Block),
/// A block header for when the block does not contain any pertinent transactions.
HeaderOnly(BlockHeader),
HeaderOnly(Header),
}

/// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions fuzz/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,8 +20,8 @@ stdin_fuzz = []
[dependencies]
lightning = { path = "../lightning", features = ["regex", "hashbrown", "_test_utils"] }
lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync" }
bitcoin = { version = "0.29.0", features = ["secp-lowmemory"] }
hex = "0.3"
bitcoin = { version = "0.30.2", features = ["secp-lowmemory"] }
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
hashbrown = "0.8"

afl = { version = "0.12", optional = true }
Expand Down
12 changes: 6 additions & 6 deletions fuzz/src/chanmon_consistency.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,9 +20,9 @@

use bitcoin::blockdata::constants::genesis_block;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::blockdata::script::{Builder, Script};
use bitcoin::blockdata::script::{Builder, ScriptBuf};
use bitcoin::blockdata::opcodes;
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::network::constants::Network;

use bitcoin::hashes::Hash as TraitImport;
Expand DownExpand Up@@ -270,11 +270,11 @@ impl SignerProvider for KeyProvider {
})
}

fn get_destination_script(&self) -> Result<Script, ()> {
fn get_destination_script(&self) -> Result<ScriptBuf, ()> {
let secp_ctx = Secp256k1::signing_only();
let channel_monitor_claim_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, self.node_secret[31]]).unwrap();
let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script())
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(our_channel_monitor_claim_key_hash).into_script())
}

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
Expand DownExpand Up@@ -343,7 +343,7 @@ type ChanMan<'a> = ChannelManager<Arc<TestChainMonitor>, Arc<TestBroadcaster>, A
fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(PaymentSecret, PaymentHash)> {
let mut payment_hash;
for _ in 0..256 {
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).into_inner());
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).to_byte_array());
if let Ok(payment_secret) = dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None) {
return Some((payment_secret, payment_hash));
}
Expand DownExpand Up@@ -565,7 +565,7 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
let events = $source.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
let tx = Transaction { version: $chan_id, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: $chan_id, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: *channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
funding_output = OutPoint { txid: tx.txid(), index: 0 };
Expand Down
30 changes: 13 additions & 17 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

13 changes: 7 additions & 6 deletions fuzz/src/onion_message.rs
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
// Imports that need to be added manually
use bitcoin::bech32::u5;
use bitcoin::blockdata::script::Script;
use bitcoin::blockdata::script::ScriptBuf;
use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1::ecdsa::RecoverableSignature;
Expand DownExpand Up@@ -199,13 +199,14 @@ impl SignerProvider for KeyProvider {

fn read_chan_signer(&self, _data: &[u8]) -> Result<TestChannelSigner, DecodeError> { unreachable!() }

fn get_destination_script(&self) -> Result<Script, ()> { unreachable!() }
fn get_destination_script(&self) -> Result<ScriptBuf, ()> { unreachable!() }

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { unreachable!() }
}

#[cfg(test)]
mod tests {
use bitcoin::hashes::hex::FromHex;
use lightning::util::logger::{Logger, Record};
use std::collections::HashMap;
use std::sync::Mutex;
Expand DownExpand Up@@ -258,7 +259,7 @@ mod tests {
000000000000000000000000000000000000000005600000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(one_hop_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(one_hop_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(),
Expand DownExpand Up@@ -302,7 +303,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_hops_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_hops_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -343,7 +344,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_two_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_two_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -384,7 +385,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(three_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(three_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand Down
2 changes: 1 addition & 1 deletion lightning-background-processor/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ no-std = ["bitcoin/no-std", "lightning/no-std", "lightning-rapid-gossip-sync/no-
default = ["std"]

[dependencies]
bitcoin = { version = "0.29.0", default-features = false }
bitcoin = { version = "0.30.2", default-features = false }
lightning = { version = "0.0.118", path = "../lightning", default-features = false }
lightning-rapid-gossip-sync = { version = "0.0.118", path = "../lightning-rapid-gossip-sync", default-features = false }

Expand Down
4 changes: 2 additions & 2 deletions lightning-background-processor/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -845,7 +845,7 @@ impl Drop for BackgroundProcessor {
#[cfg(all(feature = "std", test))]
mod tests {
use bitcoin::blockdata::constants::{genesis_block, ChainHash};
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1};
Expand DownExpand Up@@ -1254,7 +1254,7 @@ mod tests {
assert_eq!(channel_value_satoshis, $channel_value);
assert_eq!(user_channel_id, 42);

let tx = Transaction { version: 1 as i32, lock_time: PackedLockTime(0), input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: 1 as i32, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
(temporary_channel_id, tx)
Expand Down
3 changes: 2 additions & 1 deletion lightning-block-sync/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,8 @@ rest-client = [ "serde_json", "chunked_transfer" ]
rpc-client = [ "serde_json", "chunked_transfer" ]

[dependencies]
bitcoin = "0.29.0"
bitcoin = "0.30.2"
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
lightning = { version = "0.0.118", path = "../lightning" }
tokio = { version = "1.0", features = [ "io-util", "net", "time" ], optional = true }
serde_json = { version = "1.0", optional = true }
Expand Down
44 changes: 24 additions & 20 deletions lightning-block-sync/src/convert.rs
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
use crate::http::{BinaryResponse, JsonResponse};
use crate::utils::hex_to_uint256;
use crate::utils::hex_to_work;
use crate::{BlockHeaderData, BlockSourceError};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::consensus::encode;
use bitcoin::hash_types::{BlockHash, TxMerkleNode, Txid};
use bitcoin::hashes::hex::FromHex;
Expand DownExpand Up@@ -88,17 +88,21 @@ impl TryFrom<serde_json::Value> for BlockHeaderData {
} }

Ok(BlockHeaderData {
header: BlockHeader {
version: get_field!("version", as_i64).try_into().map_err(|_| ())?,
header: Header {
version: bitcoin::blockdata::block::Version::from_consensus(
get_field!("version", as_i64).try_into().map_err(|_| ())?
),
prev_blockhash: if let Some(hash_str) = response.get("previousblockhash") {
BlockHash::from_hex(hash_str.as_str().ok_or(())?).map_err(|_| ())?
BlockHash::from_str(hash_str.as_str().ok_or(())?).map_err(|_| ())?
} else { BlockHash::all_zeros() },
merkle_root: TxMerkleNode::from_hex(get_field!("merkleroot", as_str)).map_err(|_| ())?,
merkle_root: TxMerkleNode::from_str(get_field!("merkleroot", as_str)).map_err(|_| ())?,
time: get_field!("time", as_u64).try_into().map_err(|_| ())?,
bits: u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?),
bits: bitcoin::CompactTarget::from_consensus(
u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?)
),
nonce: get_field!("nonce", as_u64).try_into().map_err(|_| ())?,
},
chainwork: hex_to_uint256(get_field!("chainwork", as_str)).map_err(|_| ())?,
chainwork: hex_to_work(get_field!("chainwork", as_str)).map_err(|_| ())?,
height: get_field!("height", as_u64).try_into().map_err(|_| ())?,
})
}
Expand DownExpand Up@@ -132,7 +136,7 @@ impl TryInto<(BlockHash, Option<u32>)> for JsonResponse {
}

let hash = match &self.0["bestblockhash"] {
serde_json::Value::String(hex_data) => match BlockHash::from_hex(&hex_data) {
serde_json::Value::String(hex_data) => match BlockHash::from_str(&hex_data) {
Err(_) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid hex data")),
Ok(block_hash) => block_hash,
},
Expand DownExpand Up@@ -288,8 +292,8 @@ pub(crate) mod tests {
use super::*;
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::hashes::Hash;
use bitcoin::hashes::hex::ToHex;
use bitcoin::network::constants::Network;
use hex::DisplayHex;
use serde_json::value::Number;
use serde_json::Value;

Expand All@@ -298,14 +302,14 @@ pub(crate) mod tests {
fn from(data: BlockHeaderData) -> Self {
let BlockHeaderData { chainwork, height, header } = data;
serde_json::json!({
"chainwork": chainwork.to_string()["0x".len()..],
"chainwork": chainwork.to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI this could be format!("{:064x}", chainwork) which conveys the intent better.

"height": height,
"version": header.version,
"merkleroot": header.merkle_root.to_hex(),
"version": header.version.to_consensus(),
"merkleroot": header.merkle_root.to_string(),
"time": header.time,
"nonce": header.nonce,
"bits": header.bits.to_hex(),
"previousblockhash": header.prev_blockhash.to_hex(),
"bits": header.bits.to_consensus().to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

format!("{08x}", header.bits.to_consensus()) would convey the meaning better but your code is actually faster because std formatting is over-complicated. I've opened an issue to support hex directly on CompactTarget but that will still be slower than your code.

"previousblockhash": header.prev_blockhash.to_string(),
})
}
}
Expand DownExpand Up@@ -394,7 +398,7 @@ pub(crate) mod tests {
#[test]
fn into_block_header_from_json_response_with_valid_header_array() {
let genesis_block = genesis_block(Network::Bitcoin);
let best_block_header = BlockHeader {
let best_block_header = Header {
prev_blockhash: genesis_block.block_hash(),
..genesis_block.header
};
Expand DownExpand Up@@ -541,7 +545,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_without_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Err(e) => panic!("Unexpected error: {:?}", e),
Expand All@@ -556,7 +560,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_unexpected_blocks_type() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": "foo",
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -572,7 +576,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_invalid_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": std::u64::MAX,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -588,7 +592,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": 1,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand Down
10 changes: 5 additions & 5 deletions lightning-block-sync/src/init.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,7 +4,7 @@
use crate::{BlockSource, BlockSourceResult, Cache, ChainNotifier};
use crate::poll::{ChainPoller, Validate, ValidatedBlockHeader};

use bitcoin::blockdata::block::BlockHeader;
use bitcoin::blockdata::block::Header;
use bitcoin::hash_types::BlockHash;
use bitcoin::network::constants::Network;

Expand DownExpand Up@@ -211,11 +211,11 @@ impl<'a, C: Cache> Cache for ReadOnlyCache<'a, C> {
struct DynamicChainListener<'a, L: chain::Listen + ?Sized>(&'a L);

impl<'a, L: chain::Listen + ?Sized> chain::Listen for DynamicChainListener<'a, L> {
fn filtered_block_connected(&self, _header: &BlockHeader, _txdata: &chain::transaction::TransactionData, _height: u32) {
fn filtered_block_connected(&self, _header: &Header, _txdata: &chain::transaction::TransactionData, _height: u32) {
unreachable!()
}

fn block_disconnected(&self, header: &BlockHeader, height: u32) {
fn block_disconnected(&self, header: &Header, height: u32) {
self.0.block_disconnected(header, height)
}
}
Expand All@@ -234,15 +234,15 @@ impl<'a, L: chain::Listen + ?Sized> chain::Listen for ChainListenerSet<'a, L> {
}
}

fn filtered_block_connected(&self, header: &BlockHeader, txdata: &chain::transaction::TransactionData, height: u32) {
fn filtered_block_connected(&self, header: &Header, txdata: &chain::transaction::TransactionData, height: u32) {
for (starting_height, chain_listener) in self.0.iter() {
if height > *starting_height {
chain_listener.filtered_block_connected(header, txdata, height);
}
}
}

fn block_disconnected(&self, _header: &BlockHeader, _height: u32) {
fn block_disconnected(&self, _header: &Header, _height: u32) {
unreachable!()
}
}
Expand Down
13 changes: 6 additions & 7 deletions lightning-block-sync/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,9 +47,9 @@ mod utils;

use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::hash_types::BlockHash;
use bitcoin::util::uint::Uint256;
use bitcoin::pow::Work;

use lightning::chain;
use lightning::chain::Listen;
Expand DownExpand Up@@ -147,14 +147,13 @@ impl BlockSourceError {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlockHeaderData {
/// The block header itself.
pub header: BlockHeader,
pub header: Header,

/// The block height where the genesis block has height 0.
pub height: u32,

/// The total chain work in expected number of double-SHA256 hashes required to build a chain
/// of equivalent weight.
pub chainwork: Uint256,
/// The total chain work required to build a chain of equivalent weight.
pub chainwork: Work,
}

/// A block including either all its transactions or only the block header.
Expand All@@ -166,7 +165,7 @@ pub enum BlockData {
/// A block containing all its transactions.
FullBlock(Block),
/// A block header for when the block does not contain any pertinent transactions.
HeaderOnly(BlockHeader),
HeaderOnly(Header),
}

/// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions fuzz/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,8 +20,8 @@ stdin_fuzz = []
[dependencies]
lightning = { path = "../lightning", features = ["regex", "hashbrown", "_test_utils"] }
lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync" }
bitcoin = { version = "0.29.0", features = ["secp-lowmemory"] }
hex = "0.3"
bitcoin = { version = "0.30.2", features = ["secp-lowmemory"] }
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
hashbrown = "0.8"

afl = { version = "0.12", optional = true }
Expand Down
12 changes: 6 additions & 6 deletions fuzz/src/chanmon_consistency.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,9 +20,9 @@

use bitcoin::blockdata::constants::genesis_block;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::blockdata::script::{Builder, Script};
use bitcoin::blockdata::script::{Builder, ScriptBuf};
use bitcoin::blockdata::opcodes;
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::network::constants::Network;

use bitcoin::hashes::Hash as TraitImport;
Expand DownExpand Up@@ -270,11 +270,11 @@ impl SignerProvider for KeyProvider {
})
}

fn get_destination_script(&self) -> Result<Script, ()> {
fn get_destination_script(&self) -> Result<ScriptBuf, ()> {
let secp_ctx = Secp256k1::signing_only();
let channel_monitor_claim_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, self.node_secret[31]]).unwrap();
let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script())
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(our_channel_monitor_claim_key_hash).into_script())
}

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
Expand DownExpand Up@@ -343,7 +343,7 @@ type ChanMan<'a> = ChannelManager<Arc<TestChainMonitor>, Arc<TestBroadcaster>, A
fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(PaymentSecret, PaymentHash)> {
let mut payment_hash;
for _ in 0..256 {
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).into_inner());
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).to_byte_array());
if let Ok(payment_secret) = dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None) {
return Some((payment_secret, payment_hash));
}
Expand DownExpand Up@@ -565,7 +565,7 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
let events = $source.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
let tx = Transaction { version: $chan_id, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: $chan_id, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: *channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
funding_output = OutPoint { txid: tx.txid(), index: 0 };
Expand Down
30 changes: 13 additions & 17 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

13 changes: 7 additions & 6 deletions fuzz/src/onion_message.rs
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
// Imports that need to be added manually
use bitcoin::bech32::u5;
use bitcoin::blockdata::script::Script;
use bitcoin::blockdata::script::ScriptBuf;
use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1::ecdsa::RecoverableSignature;
Expand DownExpand Up@@ -199,13 +199,14 @@ impl SignerProvider for KeyProvider {

fn read_chan_signer(&self, _data: &[u8]) -> Result<TestChannelSigner, DecodeError> { unreachable!() }

fn get_destination_script(&self) -> Result<Script, ()> { unreachable!() }
fn get_destination_script(&self) -> Result<ScriptBuf, ()> { unreachable!() }

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { unreachable!() }
}

#[cfg(test)]
mod tests {
use bitcoin::hashes::hex::FromHex;
use lightning::util::logger::{Logger, Record};
use std::collections::HashMap;
use std::sync::Mutex;
Expand DownExpand Up@@ -258,7 +259,7 @@ mod tests {
000000000000000000000000000000000000000005600000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(one_hop_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(one_hop_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(),
Expand DownExpand Up@@ -302,7 +303,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_hops_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_hops_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -343,7 +344,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_two_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_two_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -384,7 +385,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(three_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(three_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand Down
2 changes: 1 addition & 1 deletion lightning-background-processor/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ no-std = ["bitcoin/no-std", "lightning/no-std", "lightning-rapid-gossip-sync/no-
default = ["std"]

[dependencies]
bitcoin = { version = "0.29.0", default-features = false }
bitcoin = { version = "0.30.2", default-features = false }
lightning = { version = "0.0.118", path = "../lightning", default-features = false }
lightning-rapid-gossip-sync = { version = "0.0.118", path = "../lightning-rapid-gossip-sync", default-features = false }

Expand Down
4 changes: 2 additions & 2 deletions lightning-background-processor/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -845,7 +845,7 @@ impl Drop for BackgroundProcessor {
#[cfg(all(feature = "std", test))]
mod tests {
use bitcoin::blockdata::constants::{genesis_block, ChainHash};
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1};
Expand DownExpand Up@@ -1254,7 +1254,7 @@ mod tests {
assert_eq!(channel_value_satoshis, $channel_value);
assert_eq!(user_channel_id, 42);

let tx = Transaction { version: 1 as i32, lock_time: PackedLockTime(0), input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: 1 as i32, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
(temporary_channel_id, tx)
Expand Down
3 changes: 2 additions & 1 deletion lightning-block-sync/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,8 @@ rest-client = [ "serde_json", "chunked_transfer" ]
rpc-client = [ "serde_json", "chunked_transfer" ]

[dependencies]
bitcoin = "0.29.0"
bitcoin = "0.30.2"
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
lightning = { version = "0.0.118", path = "../lightning" }
tokio = { version = "1.0", features = [ "io-util", "net", "time" ], optional = true }
serde_json = { version = "1.0", optional = true }
Expand Down
44 changes: 24 additions & 20 deletions lightning-block-sync/src/convert.rs
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
use crate::http::{BinaryResponse, JsonResponse};
use crate::utils::hex_to_uint256;
use crate::utils::hex_to_work;
use crate::{BlockHeaderData, BlockSourceError};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::consensus::encode;
use bitcoin::hash_types::{BlockHash, TxMerkleNode, Txid};
use bitcoin::hashes::hex::FromHex;
Expand DownExpand Up@@ -88,17 +88,21 @@ impl TryFrom<serde_json::Value> for BlockHeaderData {
} }

Ok(BlockHeaderData {
header: BlockHeader {
version: get_field!("version", as_i64).try_into().map_err(|_| ())?,
header: Header {
version: bitcoin::blockdata::block::Version::from_consensus(
get_field!("version", as_i64).try_into().map_err(|_| ())?
),
prev_blockhash: if let Some(hash_str) = response.get("previousblockhash") {
BlockHash::from_hex(hash_str.as_str().ok_or(())?).map_err(|_| ())?
BlockHash::from_str(hash_str.as_str().ok_or(())?).map_err(|_| ())?
} else { BlockHash::all_zeros() },
merkle_root: TxMerkleNode::from_hex(get_field!("merkleroot", as_str)).map_err(|_| ())?,
merkle_root: TxMerkleNode::from_str(get_field!("merkleroot", as_str)).map_err(|_| ())?,
time: get_field!("time", as_u64).try_into().map_err(|_| ())?,
bits: u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?),
bits: bitcoin::CompactTarget::from_consensus(
u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?)
),
nonce: get_field!("nonce", as_u64).try_into().map_err(|_| ())?,
},
chainwork: hex_to_uint256(get_field!("chainwork", as_str)).map_err(|_| ())?,
chainwork: hex_to_work(get_field!("chainwork", as_str)).map_err(|_| ())?,
height: get_field!("height", as_u64).try_into().map_err(|_| ())?,
})
}
Expand DownExpand Up@@ -132,7 +136,7 @@ impl TryInto<(BlockHash, Option<u32>)> for JsonResponse {
}

let hash = match &self.0["bestblockhash"] {
serde_json::Value::String(hex_data) => match BlockHash::from_hex(&hex_data) {
serde_json::Value::String(hex_data) => match BlockHash::from_str(&hex_data) {
Err(_) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid hex data")),
Ok(block_hash) => block_hash,
},
Expand DownExpand Up@@ -288,8 +292,8 @@ pub(crate) mod tests {
use super::*;
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::hashes::Hash;
use bitcoin::hashes::hex::ToHex;
use bitcoin::network::constants::Network;
use hex::DisplayHex;
use serde_json::value::Number;
use serde_json::Value;

Expand All@@ -298,14 +302,14 @@ pub(crate) mod tests {
fn from(data: BlockHeaderData) -> Self {
let BlockHeaderData { chainwork, height, header } = data;
serde_json::json!({
"chainwork": chainwork.to_string()["0x".len()..],
"chainwork": chainwork.to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI this could be format!("{:064x}", chainwork) which conveys the intent better.

"height": height,
"version": header.version,
"merkleroot": header.merkle_root.to_hex(),
"version": header.version.to_consensus(),
"merkleroot": header.merkle_root.to_string(),
"time": header.time,
"nonce": header.nonce,
"bits": header.bits.to_hex(),
"previousblockhash": header.prev_blockhash.to_hex(),
"bits": header.bits.to_consensus().to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

format!("{08x}", header.bits.to_consensus()) would convey the meaning better but your code is actually faster because std formatting is over-complicated. I've opened an issue to support hex directly on CompactTarget but that will still be slower than your code.

"previousblockhash": header.prev_blockhash.to_string(),
})
}
}
Expand DownExpand Up@@ -394,7 +398,7 @@ pub(crate) mod tests {
#[test]
fn into_block_header_from_json_response_with_valid_header_array() {
let genesis_block = genesis_block(Network::Bitcoin);
let best_block_header = BlockHeader {
let best_block_header = Header {
prev_blockhash: genesis_block.block_hash(),
..genesis_block.header
};
Expand DownExpand Up@@ -541,7 +545,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_without_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Err(e) => panic!("Unexpected error: {:?}", e),
Expand All@@ -556,7 +560,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_unexpected_blocks_type() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": "foo",
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -572,7 +576,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_invalid_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": std::u64::MAX,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -588,7 +592,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": 1,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand Down
10 changes: 5 additions & 5 deletions lightning-block-sync/src/init.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,7 +4,7 @@
use crate::{BlockSource, BlockSourceResult, Cache, ChainNotifier};
use crate::poll::{ChainPoller, Validate, ValidatedBlockHeader};

use bitcoin::blockdata::block::BlockHeader;
use bitcoin::blockdata::block::Header;
use bitcoin::hash_types::BlockHash;
use bitcoin::network::constants::Network;

Expand DownExpand Up@@ -211,11 +211,11 @@ impl<'a, C: Cache> Cache for ReadOnlyCache<'a, C> {
struct DynamicChainListener<'a, L: chain::Listen + ?Sized>(&'a L);

impl<'a, L: chain::Listen + ?Sized> chain::Listen for DynamicChainListener<'a, L> {
fn filtered_block_connected(&self, _header: &BlockHeader, _txdata: &chain::transaction::TransactionData, _height: u32) {
fn filtered_block_connected(&self, _header: &Header, _txdata: &chain::transaction::TransactionData, _height: u32) {
unreachable!()
}

fn block_disconnected(&self, header: &BlockHeader, height: u32) {
fn block_disconnected(&self, header: &Header, height: u32) {
self.0.block_disconnected(header, height)
}
}
Expand All@@ -234,15 +234,15 @@ impl<'a, L: chain::Listen + ?Sized> chain::Listen for ChainListenerSet<'a, L> {
}
}

fn filtered_block_connected(&self, header: &BlockHeader, txdata: &chain::transaction::TransactionData, height: u32) {
fn filtered_block_connected(&self, header: &Header, txdata: &chain::transaction::TransactionData, height: u32) {
for (starting_height, chain_listener) in self.0.iter() {
if height > *starting_height {
chain_listener.filtered_block_connected(header, txdata, height);
}
}
}

fn block_disconnected(&self, _header: &BlockHeader, _height: u32) {
fn block_disconnected(&self, _header: &Header, _height: u32) {
unreachable!()
}
}
Expand Down
13 changes: 6 additions & 7 deletions lightning-block-sync/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,9 +47,9 @@ mod utils;

use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::hash_types::BlockHash;
use bitcoin::util::uint::Uint256;
use bitcoin::pow::Work;

use lightning::chain;
use lightning::chain::Listen;
Expand DownExpand Up@@ -147,14 +147,13 @@ impl BlockSourceError {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlockHeaderData {
/// The block header itself.
pub header: BlockHeader,
pub header: Header,

/// The block height where the genesis block has height 0.
pub height: u32,

/// The total chain work in expected number of double-SHA256 hashes required to build a chain
/// of equivalent weight.
pub chainwork: Uint256,
/// The total chain work required to build a chain of equivalent weight.
pub chainwork: Work,
}

/// A block including either all its transactions or only the block header.
Expand All@@ -166,7 +165,7 @@ pub enum BlockData {
/// A block containing all its transactions.
FullBlock(Block),
/// A block header for when the block does not contain any pertinent transactions.
HeaderOnly(BlockHeader),
HeaderOnly(Header),
}

/// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions fuzz/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,8 +20,8 @@ stdin_fuzz = []
[dependencies]
lightning = { path = "../lightning", features = ["regex", "hashbrown", "_test_utils"] }
lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync" }
bitcoin = { version = "0.29.0", features = ["secp-lowmemory"] }
hex = "0.3"
bitcoin = { version = "0.30.2", features = ["secp-lowmemory"] }
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
hashbrown = "0.8"

afl = { version = "0.12", optional = true }
Expand Down
12 changes: 6 additions & 6 deletions fuzz/src/chanmon_consistency.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,9 +20,9 @@

use bitcoin::blockdata::constants::genesis_block;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::blockdata::script::{Builder, Script};
use bitcoin::blockdata::script::{Builder, ScriptBuf};
use bitcoin::blockdata::opcodes;
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::network::constants::Network;

use bitcoin::hashes::Hash as TraitImport;
Expand DownExpand Up@@ -270,11 +270,11 @@ impl SignerProvider for KeyProvider {
})
}

fn get_destination_script(&self) -> Result<Script, ()> {
fn get_destination_script(&self) -> Result<ScriptBuf, ()> {
let secp_ctx = Secp256k1::signing_only();
let channel_monitor_claim_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, self.node_secret[31]]).unwrap();
let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script())
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(our_channel_monitor_claim_key_hash).into_script())
}

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
Expand DownExpand Up@@ -343,7 +343,7 @@ type ChanMan<'a> = ChannelManager<Arc<TestChainMonitor>, Arc<TestBroadcaster>, A
fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(PaymentSecret, PaymentHash)> {
let mut payment_hash;
for _ in 0..256 {
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).into_inner());
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).to_byte_array());
if let Ok(payment_secret) = dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None) {
return Some((payment_secret, payment_hash));
}
Expand DownExpand Up@@ -565,7 +565,7 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
let events = $source.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
let tx = Transaction { version: $chan_id, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: $chan_id, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: *channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
funding_output = OutPoint { txid: tx.txid(), index: 0 };
Expand Down
30 changes: 13 additions & 17 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

13 changes: 7 additions & 6 deletions fuzz/src/onion_message.rs
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
// Imports that need to be added manually
use bitcoin::bech32::u5;
use bitcoin::blockdata::script::Script;
use bitcoin::blockdata::script::ScriptBuf;
use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1::ecdsa::RecoverableSignature;
Expand DownExpand Up@@ -199,13 +199,14 @@ impl SignerProvider for KeyProvider {

fn read_chan_signer(&self, _data: &[u8]) -> Result<TestChannelSigner, DecodeError> { unreachable!() }

fn get_destination_script(&self) -> Result<Script, ()> { unreachable!() }
fn get_destination_script(&self) -> Result<ScriptBuf, ()> { unreachable!() }

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { unreachable!() }
}

#[cfg(test)]
mod tests {
use bitcoin::hashes::hex::FromHex;
use lightning::util::logger::{Logger, Record};
use std::collections::HashMap;
use std::sync::Mutex;
Expand DownExpand Up@@ -258,7 +259,7 @@ mod tests {
000000000000000000000000000000000000000005600000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(one_hop_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(one_hop_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(),
Expand DownExpand Up@@ -302,7 +303,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_hops_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_hops_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -343,7 +344,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_two_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_two_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -384,7 +385,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(three_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(three_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand Down
2 changes: 1 addition & 1 deletion lightning-background-processor/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ no-std = ["bitcoin/no-std", "lightning/no-std", "lightning-rapid-gossip-sync/no-
default = ["std"]

[dependencies]
bitcoin = { version = "0.29.0", default-features = false }
bitcoin = { version = "0.30.2", default-features = false }
lightning = { version = "0.0.118", path = "../lightning", default-features = false }
lightning-rapid-gossip-sync = { version = "0.0.118", path = "../lightning-rapid-gossip-sync", default-features = false }

Expand Down
4 changes: 2 additions & 2 deletions lightning-background-processor/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -845,7 +845,7 @@ impl Drop for BackgroundProcessor {
#[cfg(all(feature = "std", test))]
mod tests {
use bitcoin::blockdata::constants::{genesis_block, ChainHash};
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1};
Expand DownExpand Up@@ -1254,7 +1254,7 @@ mod tests {
assert_eq!(channel_value_satoshis, $channel_value);
assert_eq!(user_channel_id, 42);

let tx = Transaction { version: 1 as i32, lock_time: PackedLockTime(0), input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: 1 as i32, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
(temporary_channel_id, tx)
Expand Down
3 changes: 2 additions & 1 deletion lightning-block-sync/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,8 @@ rest-client = [ "serde_json", "chunked_transfer" ]
rpc-client = [ "serde_json", "chunked_transfer" ]

[dependencies]
bitcoin = "0.29.0"
bitcoin = "0.30.2"
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
lightning = { version = "0.0.118", path = "../lightning" }
tokio = { version = "1.0", features = [ "io-util", "net", "time" ], optional = true }
serde_json = { version = "1.0", optional = true }
Expand Down
44 changes: 24 additions & 20 deletions lightning-block-sync/src/convert.rs
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
use crate::http::{BinaryResponse, JsonResponse};
use crate::utils::hex_to_uint256;
use crate::utils::hex_to_work;
use crate::{BlockHeaderData, BlockSourceError};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::consensus::encode;
use bitcoin::hash_types::{BlockHash, TxMerkleNode, Txid};
use bitcoin::hashes::hex::FromHex;
Expand DownExpand Up@@ -88,17 +88,21 @@ impl TryFrom<serde_json::Value> for BlockHeaderData {
} }

Ok(BlockHeaderData {
header: BlockHeader {
version: get_field!("version", as_i64).try_into().map_err(|_| ())?,
header: Header {
version: bitcoin::blockdata::block::Version::from_consensus(
get_field!("version", as_i64).try_into().map_err(|_| ())?
),
prev_blockhash: if let Some(hash_str) = response.get("previousblockhash") {
BlockHash::from_hex(hash_str.as_str().ok_or(())?).map_err(|_| ())?
BlockHash::from_str(hash_str.as_str().ok_or(())?).map_err(|_| ())?
} else { BlockHash::all_zeros() },
merkle_root: TxMerkleNode::from_hex(get_field!("merkleroot", as_str)).map_err(|_| ())?,
merkle_root: TxMerkleNode::from_str(get_field!("merkleroot", as_str)).map_err(|_| ())?,
time: get_field!("time", as_u64).try_into().map_err(|_| ())?,
bits: u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?),
bits: bitcoin::CompactTarget::from_consensus(
u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?)
),
nonce: get_field!("nonce", as_u64).try_into().map_err(|_| ())?,
},
chainwork: hex_to_uint256(get_field!("chainwork", as_str)).map_err(|_| ())?,
chainwork: hex_to_work(get_field!("chainwork", as_str)).map_err(|_| ())?,
height: get_field!("height", as_u64).try_into().map_err(|_| ())?,
})
}
Expand DownExpand Up@@ -132,7 +136,7 @@ impl TryInto<(BlockHash, Option<u32>)> for JsonResponse {
}

let hash = match &self.0["bestblockhash"] {
serde_json::Value::String(hex_data) => match BlockHash::from_hex(&hex_data) {
serde_json::Value::String(hex_data) => match BlockHash::from_str(&hex_data) {
Err(_) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid hex data")),
Ok(block_hash) => block_hash,
},
Expand DownExpand Up@@ -288,8 +292,8 @@ pub(crate) mod tests {
use super::*;
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::hashes::Hash;
use bitcoin::hashes::hex::ToHex;
use bitcoin::network::constants::Network;
use hex::DisplayHex;
use serde_json::value::Number;
use serde_json::Value;

Expand All@@ -298,14 +302,14 @@ pub(crate) mod tests {
fn from(data: BlockHeaderData) -> Self {
let BlockHeaderData { chainwork, height, header } = data;
serde_json::json!({
"chainwork": chainwork.to_string()["0x".len()..],
"chainwork": chainwork.to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI this could be format!("{:064x}", chainwork) which conveys the intent better.

"height": height,
"version": header.version,
"merkleroot": header.merkle_root.to_hex(),
"version": header.version.to_consensus(),
"merkleroot": header.merkle_root.to_string(),
"time": header.time,
"nonce": header.nonce,
"bits": header.bits.to_hex(),
"previousblockhash": header.prev_blockhash.to_hex(),
"bits": header.bits.to_consensus().to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

format!("{08x}", header.bits.to_consensus()) would convey the meaning better but your code is actually faster because std formatting is over-complicated. I've opened an issue to support hex directly on CompactTarget but that will still be slower than your code.

"previousblockhash": header.prev_blockhash.to_string(),
})
}
}
Expand DownExpand Up@@ -394,7 +398,7 @@ pub(crate) mod tests {
#[test]
fn into_block_header_from_json_response_with_valid_header_array() {
let genesis_block = genesis_block(Network::Bitcoin);
let best_block_header = BlockHeader {
let best_block_header = Header {
prev_blockhash: genesis_block.block_hash(),
..genesis_block.header
};
Expand DownExpand Up@@ -541,7 +545,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_without_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Err(e) => panic!("Unexpected error: {:?}", e),
Expand All@@ -556,7 +560,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_unexpected_blocks_type() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": "foo",
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -572,7 +576,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_invalid_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": std::u64::MAX,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -588,7 +592,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": 1,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand Down
10 changes: 5 additions & 5 deletions lightning-block-sync/src/init.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,7 +4,7 @@
use crate::{BlockSource, BlockSourceResult, Cache, ChainNotifier};
use crate::poll::{ChainPoller, Validate, ValidatedBlockHeader};

use bitcoin::blockdata::block::BlockHeader;
use bitcoin::blockdata::block::Header;
use bitcoin::hash_types::BlockHash;
use bitcoin::network::constants::Network;

Expand DownExpand Up@@ -211,11 +211,11 @@ impl<'a, C: Cache> Cache for ReadOnlyCache<'a, C> {
struct DynamicChainListener<'a, L: chain::Listen + ?Sized>(&'a L);

impl<'a, L: chain::Listen + ?Sized> chain::Listen for DynamicChainListener<'a, L> {
fn filtered_block_connected(&self, _header: &BlockHeader, _txdata: &chain::transaction::TransactionData, _height: u32) {
fn filtered_block_connected(&self, _header: &Header, _txdata: &chain::transaction::TransactionData, _height: u32) {
unreachable!()
}

fn block_disconnected(&self, header: &BlockHeader, height: u32) {
fn block_disconnected(&self, header: &Header, height: u32) {
self.0.block_disconnected(header, height)
}
}
Expand All@@ -234,15 +234,15 @@ impl<'a, L: chain::Listen + ?Sized> chain::Listen for ChainListenerSet<'a, L> {
}
}

fn filtered_block_connected(&self, header: &BlockHeader, txdata: &chain::transaction::TransactionData, height: u32) {
fn filtered_block_connected(&self, header: &Header, txdata: &chain::transaction::TransactionData, height: u32) {
for (starting_height, chain_listener) in self.0.iter() {
if height > *starting_height {
chain_listener.filtered_block_connected(header, txdata, height);
}
}
}

fn block_disconnected(&self, _header: &BlockHeader, _height: u32) {
fn block_disconnected(&self, _header: &Header, _height: u32) {
unreachable!()
}
}
Expand Down
13 changes: 6 additions & 7 deletions lightning-block-sync/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,9 +47,9 @@ mod utils;

use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::hash_types::BlockHash;
use bitcoin::util::uint::Uint256;
use bitcoin::pow::Work;

use lightning::chain;
use lightning::chain::Listen;
Expand DownExpand Up@@ -147,14 +147,13 @@ impl BlockSourceError {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlockHeaderData {
/// The block header itself.
pub header: BlockHeader,
pub header: Header,

/// The block height where the genesis block has height 0.
pub height: u32,

/// The total chain work in expected number of double-SHA256 hashes required to build a chain
/// of equivalent weight.
pub chainwork: Uint256,
/// The total chain work required to build a chain of equivalent weight.
pub chainwork: Work,
}

/// A block including either all its transactions or only the block header.
Expand All@@ -166,7 +165,7 @@ pub enum BlockData {
/// A block containing all its transactions.
FullBlock(Block),
/// A block header for when the block does not contain any pertinent transactions.
HeaderOnly(BlockHeader),
HeaderOnly(Header),
}

/// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions fuzz/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,8 +20,8 @@ stdin_fuzz = []
[dependencies]
lightning = { path = "../lightning", features = ["regex", "hashbrown", "_test_utils"] }
lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync" }
bitcoin = { version = "0.29.0", features = ["secp-lowmemory"] }
hex = "0.3"
bitcoin = { version = "0.30.2", features = ["secp-lowmemory"] }
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
hashbrown = "0.8"

afl = { version = "0.12", optional = true }
Expand Down
12 changes: 6 additions & 6 deletions fuzz/src/chanmon_consistency.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,9 +20,9 @@

use bitcoin::blockdata::constants::genesis_block;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::blockdata::script::{Builder, Script};
use bitcoin::blockdata::script::{Builder, ScriptBuf};
use bitcoin::blockdata::opcodes;
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::network::constants::Network;

use bitcoin::hashes::Hash as TraitImport;
Expand DownExpand Up@@ -270,11 +270,11 @@ impl SignerProvider for KeyProvider {
})
}

fn get_destination_script(&self) -> Result<Script, ()> {
fn get_destination_script(&self) -> Result<ScriptBuf, ()> {
let secp_ctx = Secp256k1::signing_only();
let channel_monitor_claim_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, self.node_secret[31]]).unwrap();
let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script())
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(our_channel_monitor_claim_key_hash).into_script())
}

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
Expand DownExpand Up@@ -343,7 +343,7 @@ type ChanMan<'a> = ChannelManager<Arc<TestChainMonitor>, Arc<TestBroadcaster>, A
fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(PaymentSecret, PaymentHash)> {
let mut payment_hash;
for _ in 0..256 {
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).into_inner());
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).to_byte_array());
if let Ok(payment_secret) = dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None) {
return Some((payment_secret, payment_hash));
}
Expand DownExpand Up@@ -565,7 +565,7 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
let events = $source.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
let tx = Transaction { version: $chan_id, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: $chan_id, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: *channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
funding_output = OutPoint { txid: tx.txid(), index: 0 };
Expand Down
30 changes: 13 additions & 17 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

13 changes: 7 additions & 6 deletions fuzz/src/onion_message.rs
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
// Imports that need to be added manually
use bitcoin::bech32::u5;
use bitcoin::blockdata::script::Script;
use bitcoin::blockdata::script::ScriptBuf;
use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1::ecdsa::RecoverableSignature;
Expand DownExpand Up@@ -199,13 +199,14 @@ impl SignerProvider for KeyProvider {

fn read_chan_signer(&self, _data: &[u8]) -> Result<TestChannelSigner, DecodeError> { unreachable!() }

fn get_destination_script(&self) -> Result<Script, ()> { unreachable!() }
fn get_destination_script(&self) -> Result<ScriptBuf, ()> { unreachable!() }

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { unreachable!() }
}

#[cfg(test)]
mod tests {
use bitcoin::hashes::hex::FromHex;
use lightning::util::logger::{Logger, Record};
use std::collections::HashMap;
use std::sync::Mutex;
Expand DownExpand Up@@ -258,7 +259,7 @@ mod tests {
000000000000000000000000000000000000000005600000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(one_hop_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(one_hop_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(),
Expand DownExpand Up@@ -302,7 +303,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_hops_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_hops_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -343,7 +344,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_two_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_two_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -384,7 +385,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(three_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(three_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand Down
2 changes: 1 addition & 1 deletion lightning-background-processor/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ no-std = ["bitcoin/no-std", "lightning/no-std", "lightning-rapid-gossip-sync/no-
default = ["std"]

[dependencies]
bitcoin = { version = "0.29.0", default-features = false }
bitcoin = { version = "0.30.2", default-features = false }
lightning = { version = "0.0.118", path = "../lightning", default-features = false }
lightning-rapid-gossip-sync = { version = "0.0.118", path = "../lightning-rapid-gossip-sync", default-features = false }

Expand Down
4 changes: 2 additions & 2 deletions lightning-background-processor/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -845,7 +845,7 @@ impl Drop for BackgroundProcessor {
#[cfg(all(feature = "std", test))]
mod tests {
use bitcoin::blockdata::constants::{genesis_block, ChainHash};
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1};
Expand DownExpand Up@@ -1254,7 +1254,7 @@ mod tests {
assert_eq!(channel_value_satoshis, $channel_value);
assert_eq!(user_channel_id, 42);

let tx = Transaction { version: 1 as i32, lock_time: PackedLockTime(0), input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: 1 as i32, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
(temporary_channel_id, tx)
Expand Down
3 changes: 2 additions & 1 deletion lightning-block-sync/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,8 @@ rest-client = [ "serde_json", "chunked_transfer" ]
rpc-client = [ "serde_json", "chunked_transfer" ]

[dependencies]
bitcoin = "0.29.0"
bitcoin = "0.30.2"
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
lightning = { version = "0.0.118", path = "../lightning" }
tokio = { version = "1.0", features = [ "io-util", "net", "time" ], optional = true }
serde_json = { version = "1.0", optional = true }
Expand Down
44 changes: 24 additions & 20 deletions lightning-block-sync/src/convert.rs
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
use crate::http::{BinaryResponse, JsonResponse};
use crate::utils::hex_to_uint256;
use crate::utils::hex_to_work;
use crate::{BlockHeaderData, BlockSourceError};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::consensus::encode;
use bitcoin::hash_types::{BlockHash, TxMerkleNode, Txid};
use bitcoin::hashes::hex::FromHex;
Expand DownExpand Up@@ -88,17 +88,21 @@ impl TryFrom<serde_json::Value> for BlockHeaderData {
} }

Ok(BlockHeaderData {
header: BlockHeader {
version: get_field!("version", as_i64).try_into().map_err(|_| ())?,
header: Header {
version: bitcoin::blockdata::block::Version::from_consensus(
get_field!("version", as_i64).try_into().map_err(|_| ())?
),
prev_blockhash: if let Some(hash_str) = response.get("previousblockhash") {
BlockHash::from_hex(hash_str.as_str().ok_or(())?).map_err(|_| ())?
BlockHash::from_str(hash_str.as_str().ok_or(())?).map_err(|_| ())?
} else { BlockHash::all_zeros() },
merkle_root: TxMerkleNode::from_hex(get_field!("merkleroot", as_str)).map_err(|_| ())?,
merkle_root: TxMerkleNode::from_str(get_field!("merkleroot", as_str)).map_err(|_| ())?,
time: get_field!("time", as_u64).try_into().map_err(|_| ())?,
bits: u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?),
bits: bitcoin::CompactTarget::from_consensus(
u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?)
),
nonce: get_field!("nonce", as_u64).try_into().map_err(|_| ())?,
},
chainwork: hex_to_uint256(get_field!("chainwork", as_str)).map_err(|_| ())?,
chainwork: hex_to_work(get_field!("chainwork", as_str)).map_err(|_| ())?,
height: get_field!("height", as_u64).try_into().map_err(|_| ())?,
})
}
Expand DownExpand Up@@ -132,7 +136,7 @@ impl TryInto<(BlockHash, Option<u32>)> for JsonResponse {
}

let hash = match &self.0["bestblockhash"] {
serde_json::Value::String(hex_data) => match BlockHash::from_hex(&hex_data) {
serde_json::Value::String(hex_data) => match BlockHash::from_str(&hex_data) {
Err(_) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid hex data")),
Ok(block_hash) => block_hash,
},
Expand DownExpand Up@@ -288,8 +292,8 @@ pub(crate) mod tests {
use super::*;
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::hashes::Hash;
use bitcoin::hashes::hex::ToHex;
use bitcoin::network::constants::Network;
use hex::DisplayHex;
use serde_json::value::Number;
use serde_json::Value;

Expand All@@ -298,14 +302,14 @@ pub(crate) mod tests {
fn from(data: BlockHeaderData) -> Self {
let BlockHeaderData { chainwork, height, header } = data;
serde_json::json!({
"chainwork": chainwork.to_string()["0x".len()..],
"chainwork": chainwork.to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI this could be format!("{:064x}", chainwork) which conveys the intent better.

"height": height,
"version": header.version,
"merkleroot": header.merkle_root.to_hex(),
"version": header.version.to_consensus(),
"merkleroot": header.merkle_root.to_string(),
"time": header.time,
"nonce": header.nonce,
"bits": header.bits.to_hex(),
"previousblockhash": header.prev_blockhash.to_hex(),
"bits": header.bits.to_consensus().to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

format!("{08x}", header.bits.to_consensus()) would convey the meaning better but your code is actually faster because std formatting is over-complicated. I've opened an issue to support hex directly on CompactTarget but that will still be slower than your code.

"previousblockhash": header.prev_blockhash.to_string(),
})
}
}
Expand DownExpand Up@@ -394,7 +398,7 @@ pub(crate) mod tests {
#[test]
fn into_block_header_from_json_response_with_valid_header_array() {
let genesis_block = genesis_block(Network::Bitcoin);
let best_block_header = BlockHeader {
let best_block_header = Header {
prev_blockhash: genesis_block.block_hash(),
..genesis_block.header
};
Expand DownExpand Up@@ -541,7 +545,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_without_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Err(e) => panic!("Unexpected error: {:?}", e),
Expand All@@ -556,7 +560,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_unexpected_blocks_type() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": "foo",
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -572,7 +576,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_invalid_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": std::u64::MAX,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -588,7 +592,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": 1,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand Down
10 changes: 5 additions & 5 deletions lightning-block-sync/src/init.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,7 +4,7 @@
use crate::{BlockSource, BlockSourceResult, Cache, ChainNotifier};
use crate::poll::{ChainPoller, Validate, ValidatedBlockHeader};

use bitcoin::blockdata::block::BlockHeader;
use bitcoin::blockdata::block::Header;
use bitcoin::hash_types::BlockHash;
use bitcoin::network::constants::Network;

Expand DownExpand Up@@ -211,11 +211,11 @@ impl<'a, C: Cache> Cache for ReadOnlyCache<'a, C> {
struct DynamicChainListener<'a, L: chain::Listen + ?Sized>(&'a L);

impl<'a, L: chain::Listen + ?Sized> chain::Listen for DynamicChainListener<'a, L> {
fn filtered_block_connected(&self, _header: &BlockHeader, _txdata: &chain::transaction::TransactionData, _height: u32) {
fn filtered_block_connected(&self, _header: &Header, _txdata: &chain::transaction::TransactionData, _height: u32) {
unreachable!()
}

fn block_disconnected(&self, header: &BlockHeader, height: u32) {
fn block_disconnected(&self, header: &Header, height: u32) {
self.0.block_disconnected(header, height)
}
}
Expand All@@ -234,15 +234,15 @@ impl<'a, L: chain::Listen + ?Sized> chain::Listen for ChainListenerSet<'a, L> {
}
}

fn filtered_block_connected(&self, header: &BlockHeader, txdata: &chain::transaction::TransactionData, height: u32) {
fn filtered_block_connected(&self, header: &Header, txdata: &chain::transaction::TransactionData, height: u32) {
for (starting_height, chain_listener) in self.0.iter() {
if height > *starting_height {
chain_listener.filtered_block_connected(header, txdata, height);
}
}
}

fn block_disconnected(&self, _header: &BlockHeader, _height: u32) {
fn block_disconnected(&self, _header: &Header, _height: u32) {
unreachable!()
}
}
Expand Down
13 changes: 6 additions & 7 deletions lightning-block-sync/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,9 +47,9 @@ mod utils;

use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::hash_types::BlockHash;
use bitcoin::util::uint::Uint256;
use bitcoin::pow::Work;

use lightning::chain;
use lightning::chain::Listen;
Expand DownExpand Up@@ -147,14 +147,13 @@ impl BlockSourceError {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlockHeaderData {
/// The block header itself.
pub header: BlockHeader,
pub header: Header,

/// The block height where the genesis block has height 0.
pub height: u32,

/// The total chain work in expected number of double-SHA256 hashes required to build a chain
/// of equivalent weight.
pub chainwork: Uint256,
/// The total chain work required to build a chain of equivalent weight.
pub chainwork: Work,
}

/// A block including either all its transactions or only the block header.
Expand All@@ -166,7 +165,7 @@ pub enum BlockData {
/// A block containing all its transactions.
FullBlock(Block),
/// A block header for when the block does not contain any pertinent transactions.
HeaderOnly(BlockHeader),
HeaderOnly(Header),
}

/// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions fuzz/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,8 +20,8 @@ stdin_fuzz = []
[dependencies]
lightning = { path = "../lightning", features = ["regex", "hashbrown", "_test_utils"] }
lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync" }
bitcoin = { version = "0.29.0", features = ["secp-lowmemory"] }
hex = "0.3"
bitcoin = { version = "0.30.2", features = ["secp-lowmemory"] }
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
hashbrown = "0.8"

afl = { version = "0.12", optional = true }
Expand Down
12 changes: 6 additions & 6 deletions fuzz/src/chanmon_consistency.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,9 +20,9 @@

use bitcoin::blockdata::constants::genesis_block;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::blockdata::script::{Builder, Script};
use bitcoin::blockdata::script::{Builder, ScriptBuf};
use bitcoin::blockdata::opcodes;
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::network::constants::Network;

use bitcoin::hashes::Hash as TraitImport;
Expand DownExpand Up@@ -270,11 +270,11 @@ impl SignerProvider for KeyProvider {
})
}

fn get_destination_script(&self) -> Result<Script, ()> {
fn get_destination_script(&self) -> Result<ScriptBuf, ()> {
let secp_ctx = Secp256k1::signing_only();
let channel_monitor_claim_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, self.node_secret[31]]).unwrap();
let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script())
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(our_channel_monitor_claim_key_hash).into_script())
}

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
Expand DownExpand Up@@ -343,7 +343,7 @@ type ChanMan<'a> = ChannelManager<Arc<TestChainMonitor>, Arc<TestBroadcaster>, A
fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(PaymentSecret, PaymentHash)> {
let mut payment_hash;
for _ in 0..256 {
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).into_inner());
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).to_byte_array());
if let Ok(payment_secret) = dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None) {
return Some((payment_secret, payment_hash));
}
Expand DownExpand Up@@ -565,7 +565,7 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
let events = $source.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
let tx = Transaction { version: $chan_id, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: $chan_id, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: *channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
funding_output = OutPoint { txid: tx.txid(), index: 0 };
Expand Down
30 changes: 13 additions & 17 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

13 changes: 7 additions & 6 deletions fuzz/src/onion_message.rs
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
// Imports that need to be added manually
use bitcoin::bech32::u5;
use bitcoin::blockdata::script::Script;
use bitcoin::blockdata::script::ScriptBuf;
use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1::ecdsa::RecoverableSignature;
Expand DownExpand Up@@ -199,13 +199,14 @@ impl SignerProvider for KeyProvider {

fn read_chan_signer(&self, _data: &[u8]) -> Result<TestChannelSigner, DecodeError> { unreachable!() }

fn get_destination_script(&self) -> Result<Script, ()> { unreachable!() }
fn get_destination_script(&self) -> Result<ScriptBuf, ()> { unreachable!() }

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { unreachable!() }
}

#[cfg(test)]
mod tests {
use bitcoin::hashes::hex::FromHex;
use lightning::util::logger::{Logger, Record};
use std::collections::HashMap;
use std::sync::Mutex;
Expand DownExpand Up@@ -258,7 +259,7 @@ mod tests {
000000000000000000000000000000000000000005600000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(one_hop_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(one_hop_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(),
Expand DownExpand Up@@ -302,7 +303,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_hops_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_hops_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -343,7 +344,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_two_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_two_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -384,7 +385,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(three_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(three_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand Down
2 changes: 1 addition & 1 deletion lightning-background-processor/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ no-std = ["bitcoin/no-std", "lightning/no-std", "lightning-rapid-gossip-sync/no-
default = ["std"]

[dependencies]
bitcoin = { version = "0.29.0", default-features = false }
bitcoin = { version = "0.30.2", default-features = false }
lightning = { version = "0.0.118", path = "../lightning", default-features = false }
lightning-rapid-gossip-sync = { version = "0.0.118", path = "../lightning-rapid-gossip-sync", default-features = false }

Expand Down
4 changes: 2 additions & 2 deletions lightning-background-processor/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -845,7 +845,7 @@ impl Drop for BackgroundProcessor {
#[cfg(all(feature = "std", test))]
mod tests {
use bitcoin::blockdata::constants::{genesis_block, ChainHash};
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1};
Expand DownExpand Up@@ -1254,7 +1254,7 @@ mod tests {
assert_eq!(channel_value_satoshis, $channel_value);
assert_eq!(user_channel_id, 42);

let tx = Transaction { version: 1 as i32, lock_time: PackedLockTime(0), input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: 1 as i32, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
(temporary_channel_id, tx)
Expand Down
3 changes: 2 additions & 1 deletion lightning-block-sync/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,8 @@ rest-client = [ "serde_json", "chunked_transfer" ]
rpc-client = [ "serde_json", "chunked_transfer" ]

[dependencies]
bitcoin = "0.29.0"
bitcoin = "0.30.2"
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
lightning = { version = "0.0.118", path = "../lightning" }
tokio = { version = "1.0", features = [ "io-util", "net", "time" ], optional = true }
serde_json = { version = "1.0", optional = true }
Expand Down
44 changes: 24 additions & 20 deletions lightning-block-sync/src/convert.rs
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
use crate::http::{BinaryResponse, JsonResponse};
use crate::utils::hex_to_uint256;
use crate::utils::hex_to_work;
use crate::{BlockHeaderData, BlockSourceError};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::consensus::encode;
use bitcoin::hash_types::{BlockHash, TxMerkleNode, Txid};
use bitcoin::hashes::hex::FromHex;
Expand DownExpand Up@@ -88,17 +88,21 @@ impl TryFrom<serde_json::Value> for BlockHeaderData {
} }

Ok(BlockHeaderData {
header: BlockHeader {
version: get_field!("version", as_i64).try_into().map_err(|_| ())?,
header: Header {
version: bitcoin::blockdata::block::Version::from_consensus(
get_field!("version", as_i64).try_into().map_err(|_| ())?
),
prev_blockhash: if let Some(hash_str) = response.get("previousblockhash") {
BlockHash::from_hex(hash_str.as_str().ok_or(())?).map_err(|_| ())?
BlockHash::from_str(hash_str.as_str().ok_or(())?).map_err(|_| ())?
} else { BlockHash::all_zeros() },
merkle_root: TxMerkleNode::from_hex(get_field!("merkleroot", as_str)).map_err(|_| ())?,
merkle_root: TxMerkleNode::from_str(get_field!("merkleroot", as_str)).map_err(|_| ())?,
time: get_field!("time", as_u64).try_into().map_err(|_| ())?,
bits: u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?),
bits: bitcoin::CompactTarget::from_consensus(
u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?)
),
nonce: get_field!("nonce", as_u64).try_into().map_err(|_| ())?,
},
chainwork: hex_to_uint256(get_field!("chainwork", as_str)).map_err(|_| ())?,
chainwork: hex_to_work(get_field!("chainwork", as_str)).map_err(|_| ())?,
height: get_field!("height", as_u64).try_into().map_err(|_| ())?,
})
}
Expand DownExpand Up@@ -132,7 +136,7 @@ impl TryInto<(BlockHash, Option<u32>)> for JsonResponse {
}

let hash = match &self.0["bestblockhash"] {
serde_json::Value::String(hex_data) => match BlockHash::from_hex(&hex_data) {
serde_json::Value::String(hex_data) => match BlockHash::from_str(&hex_data) {
Err(_) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid hex data")),
Ok(block_hash) => block_hash,
},
Expand DownExpand Up@@ -288,8 +292,8 @@ pub(crate) mod tests {
use super::*;
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::hashes::Hash;
use bitcoin::hashes::hex::ToHex;
use bitcoin::network::constants::Network;
use hex::DisplayHex;
use serde_json::value::Number;
use serde_json::Value;

Expand All@@ -298,14 +302,14 @@ pub(crate) mod tests {
fn from(data: BlockHeaderData) -> Self {
let BlockHeaderData { chainwork, height, header } = data;
serde_json::json!({
"chainwork": chainwork.to_string()["0x".len()..],
"chainwork": chainwork.to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI this could be format!("{:064x}", chainwork) which conveys the intent better.

"height": height,
"version": header.version,
"merkleroot": header.merkle_root.to_hex(),
"version": header.version.to_consensus(),
"merkleroot": header.merkle_root.to_string(),
"time": header.time,
"nonce": header.nonce,
"bits": header.bits.to_hex(),
"previousblockhash": header.prev_blockhash.to_hex(),
"bits": header.bits.to_consensus().to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

format!("{08x}", header.bits.to_consensus()) would convey the meaning better but your code is actually faster because std formatting is over-complicated. I've opened an issue to support hex directly on CompactTarget but that will still be slower than your code.

"previousblockhash": header.prev_blockhash.to_string(),
})
}
}
Expand DownExpand Up@@ -394,7 +398,7 @@ pub(crate) mod tests {
#[test]
fn into_block_header_from_json_response_with_valid_header_array() {
let genesis_block = genesis_block(Network::Bitcoin);
let best_block_header = BlockHeader {
let best_block_header = Header {
prev_blockhash: genesis_block.block_hash(),
..genesis_block.header
};
Expand DownExpand Up@@ -541,7 +545,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_without_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Err(e) => panic!("Unexpected error: {:?}", e),
Expand All@@ -556,7 +560,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_unexpected_blocks_type() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": "foo",
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -572,7 +576,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_invalid_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": std::u64::MAX,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -588,7 +592,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": 1,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand Down
10 changes: 5 additions & 5 deletions lightning-block-sync/src/init.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,7 +4,7 @@
use crate::{BlockSource, BlockSourceResult, Cache, ChainNotifier};
use crate::poll::{ChainPoller, Validate, ValidatedBlockHeader};

use bitcoin::blockdata::block::BlockHeader;
use bitcoin::blockdata::block::Header;
use bitcoin::hash_types::BlockHash;
use bitcoin::network::constants::Network;

Expand DownExpand Up@@ -211,11 +211,11 @@ impl<'a, C: Cache> Cache for ReadOnlyCache<'a, C> {
struct DynamicChainListener<'a, L: chain::Listen + ?Sized>(&'a L);

impl<'a, L: chain::Listen + ?Sized> chain::Listen for DynamicChainListener<'a, L> {
fn filtered_block_connected(&self, _header: &BlockHeader, _txdata: &chain::transaction::TransactionData, _height: u32) {
fn filtered_block_connected(&self, _header: &Header, _txdata: &chain::transaction::TransactionData, _height: u32) {
unreachable!()
}

fn block_disconnected(&self, header: &BlockHeader, height: u32) {
fn block_disconnected(&self, header: &Header, height: u32) {
self.0.block_disconnected(header, height)
}
}
Expand All@@ -234,15 +234,15 @@ impl<'a, L: chain::Listen + ?Sized> chain::Listen for ChainListenerSet<'a, L> {
}
}

fn filtered_block_connected(&self, header: &BlockHeader, txdata: &chain::transaction::TransactionData, height: u32) {
fn filtered_block_connected(&self, header: &Header, txdata: &chain::transaction::TransactionData, height: u32) {
for (starting_height, chain_listener) in self.0.iter() {
if height > *starting_height {
chain_listener.filtered_block_connected(header, txdata, height);
}
}
}

fn block_disconnected(&self, _header: &BlockHeader, _height: u32) {
fn block_disconnected(&self, _header: &Header, _height: u32) {
unreachable!()
}
}
Expand Down
13 changes: 6 additions & 7 deletions lightning-block-sync/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,9 +47,9 @@ mod utils;

use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::hash_types::BlockHash;
use bitcoin::util::uint::Uint256;
use bitcoin::pow::Work;

use lightning::chain;
use lightning::chain::Listen;
Expand DownExpand Up@@ -147,14 +147,13 @@ impl BlockSourceError {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlockHeaderData {
/// The block header itself.
pub header: BlockHeader,
pub header: Header,

/// The block height where the genesis block has height 0.
pub height: u32,

/// The total chain work in expected number of double-SHA256 hashes required to build a chain
/// of equivalent weight.
pub chainwork: Uint256,
/// The total chain work required to build a chain of equivalent weight.
pub chainwork: Work,
}

/// A block including either all its transactions or only the block header.
Expand All@@ -166,7 +165,7 @@ pub enum BlockData {
/// A block containing all its transactions.
FullBlock(Block),
/// A block header for when the block does not contain any pertinent transactions.
HeaderOnly(BlockHeader),
HeaderOnly(Header),
}

/// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions fuzz/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,8 +20,8 @@ stdin_fuzz = []
[dependencies]
lightning = { path = "../lightning", features = ["regex", "hashbrown", "_test_utils"] }
lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync" }
bitcoin = { version = "0.29.0", features = ["secp-lowmemory"] }
hex = "0.3"
bitcoin = { version = "0.30.2", features = ["secp-lowmemory"] }
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
hashbrown = "0.8"

afl = { version = "0.12", optional = true }
Expand Down
12 changes: 6 additions & 6 deletions fuzz/src/chanmon_consistency.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,9 +20,9 @@

use bitcoin::blockdata::constants::genesis_block;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::blockdata::script::{Builder, Script};
use bitcoin::blockdata::script::{Builder, ScriptBuf};
use bitcoin::blockdata::opcodes;
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::network::constants::Network;

use bitcoin::hashes::Hash as TraitImport;
Expand DownExpand Up@@ -270,11 +270,11 @@ impl SignerProvider for KeyProvider {
})
}

fn get_destination_script(&self) -> Result<Script, ()> {
fn get_destination_script(&self) -> Result<ScriptBuf, ()> {
let secp_ctx = Secp256k1::signing_only();
let channel_monitor_claim_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, self.node_secret[31]]).unwrap();
let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script())
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(our_channel_monitor_claim_key_hash).into_script())
}

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
Expand DownExpand Up@@ -343,7 +343,7 @@ type ChanMan<'a> = ChannelManager<Arc<TestChainMonitor>, Arc<TestBroadcaster>, A
fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(PaymentSecret, PaymentHash)> {
let mut payment_hash;
for _ in 0..256 {
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).into_inner());
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).to_byte_array());
if let Ok(payment_secret) = dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None) {
return Some((payment_secret, payment_hash));
}
Expand DownExpand Up@@ -565,7 +565,7 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
let events = $source.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
let tx = Transaction { version: $chan_id, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: $chan_id, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: *channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
funding_output = OutPoint { txid: tx.txid(), index: 0 };
Expand Down
30 changes: 13 additions & 17 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

13 changes: 7 additions & 6 deletions fuzz/src/onion_message.rs
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
// Imports that need to be added manually
use bitcoin::bech32::u5;
use bitcoin::blockdata::script::Script;
use bitcoin::blockdata::script::ScriptBuf;
use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1::ecdsa::RecoverableSignature;
Expand DownExpand Up@@ -199,13 +199,14 @@ impl SignerProvider for KeyProvider {

fn read_chan_signer(&self, _data: &[u8]) -> Result<TestChannelSigner, DecodeError> { unreachable!() }

fn get_destination_script(&self) -> Result<Script, ()> { unreachable!() }
fn get_destination_script(&self) -> Result<ScriptBuf, ()> { unreachable!() }

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { unreachable!() }
}

#[cfg(test)]
mod tests {
use bitcoin::hashes::hex::FromHex;
use lightning::util::logger::{Logger, Record};
use std::collections::HashMap;
use std::sync::Mutex;
Expand DownExpand Up@@ -258,7 +259,7 @@ mod tests {
000000000000000000000000000000000000000005600000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(one_hop_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(one_hop_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(),
Expand DownExpand Up@@ -302,7 +303,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_hops_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_hops_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -343,7 +344,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_two_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_two_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -384,7 +385,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(three_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(three_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand Down
2 changes: 1 addition & 1 deletion lightning-background-processor/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ no-std = ["bitcoin/no-std", "lightning/no-std", "lightning-rapid-gossip-sync/no-
default = ["std"]

[dependencies]
bitcoin = { version = "0.29.0", default-features = false }
bitcoin = { version = "0.30.2", default-features = false }
lightning = { version = "0.0.118", path = "../lightning", default-features = false }
lightning-rapid-gossip-sync = { version = "0.0.118", path = "../lightning-rapid-gossip-sync", default-features = false }

Expand Down
4 changes: 2 additions & 2 deletions lightning-background-processor/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -845,7 +845,7 @@ impl Drop for BackgroundProcessor {
#[cfg(all(feature = "std", test))]
mod tests {
use bitcoin::blockdata::constants::{genesis_block, ChainHash};
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1};
Expand DownExpand Up@@ -1254,7 +1254,7 @@ mod tests {
assert_eq!(channel_value_satoshis, $channel_value);
assert_eq!(user_channel_id, 42);

let tx = Transaction { version: 1 as i32, lock_time: PackedLockTime(0), input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: 1 as i32, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
(temporary_channel_id, tx)
Expand Down
3 changes: 2 additions & 1 deletion lightning-block-sync/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,8 @@ rest-client = [ "serde_json", "chunked_transfer" ]
rpc-client = [ "serde_json", "chunked_transfer" ]

[dependencies]
bitcoin = "0.29.0"
bitcoin = "0.30.2"
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
lightning = { version = "0.0.118", path = "../lightning" }
tokio = { version = "1.0", features = [ "io-util", "net", "time" ], optional = true }
serde_json = { version = "1.0", optional = true }
Expand Down
44 changes: 24 additions & 20 deletions lightning-block-sync/src/convert.rs
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
use crate::http::{BinaryResponse, JsonResponse};
use crate::utils::hex_to_uint256;
use crate::utils::hex_to_work;
use crate::{BlockHeaderData, BlockSourceError};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::consensus::encode;
use bitcoin::hash_types::{BlockHash, TxMerkleNode, Txid};
use bitcoin::hashes::hex::FromHex;
Expand DownExpand Up@@ -88,17 +88,21 @@ impl TryFrom<serde_json::Value> for BlockHeaderData {
} }

Ok(BlockHeaderData {
header: BlockHeader {
version: get_field!("version", as_i64).try_into().map_err(|_| ())?,
header: Header {
version: bitcoin::blockdata::block::Version::from_consensus(
get_field!("version", as_i64).try_into().map_err(|_| ())?
),
prev_blockhash: if let Some(hash_str) = response.get("previousblockhash") {
BlockHash::from_hex(hash_str.as_str().ok_or(())?).map_err(|_| ())?
BlockHash::from_str(hash_str.as_str().ok_or(())?).map_err(|_| ())?
} else { BlockHash::all_zeros() },
merkle_root: TxMerkleNode::from_hex(get_field!("merkleroot", as_str)).map_err(|_| ())?,
merkle_root: TxMerkleNode::from_str(get_field!("merkleroot", as_str)).map_err(|_| ())?,
time: get_field!("time", as_u64).try_into().map_err(|_| ())?,
bits: u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?),
bits: bitcoin::CompactTarget::from_consensus(
u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?)
),
nonce: get_field!("nonce", as_u64).try_into().map_err(|_| ())?,
},
chainwork: hex_to_uint256(get_field!("chainwork", as_str)).map_err(|_| ())?,
chainwork: hex_to_work(get_field!("chainwork", as_str)).map_err(|_| ())?,
height: get_field!("height", as_u64).try_into().map_err(|_| ())?,
})
}
Expand DownExpand Up@@ -132,7 +136,7 @@ impl TryInto<(BlockHash, Option<u32>)> for JsonResponse {
}

let hash = match &self.0["bestblockhash"] {
serde_json::Value::String(hex_data) => match BlockHash::from_hex(&hex_data) {
serde_json::Value::String(hex_data) => match BlockHash::from_str(&hex_data) {
Err(_) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid hex data")),
Ok(block_hash) => block_hash,
},
Expand DownExpand Up@@ -288,8 +292,8 @@ pub(crate) mod tests {
use super::*;
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::hashes::Hash;
use bitcoin::hashes::hex::ToHex;
use bitcoin::network::constants::Network;
use hex::DisplayHex;
use serde_json::value::Number;
use serde_json::Value;

Expand All@@ -298,14 +302,14 @@ pub(crate) mod tests {
fn from(data: BlockHeaderData) -> Self {
let BlockHeaderData { chainwork, height, header } = data;
serde_json::json!({
"chainwork": chainwork.to_string()["0x".len()..],
"chainwork": chainwork.to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI this could be format!("{:064x}", chainwork) which conveys the intent better.

"height": height,
"version": header.version,
"merkleroot": header.merkle_root.to_hex(),
"version": header.version.to_consensus(),
"merkleroot": header.merkle_root.to_string(),
"time": header.time,
"nonce": header.nonce,
"bits": header.bits.to_hex(),
"previousblockhash": header.prev_blockhash.to_hex(),
"bits": header.bits.to_consensus().to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

format!("{08x}", header.bits.to_consensus()) would convey the meaning better but your code is actually faster because std formatting is over-complicated. I've opened an issue to support hex directly on CompactTarget but that will still be slower than your code.

"previousblockhash": header.prev_blockhash.to_string(),
})
}
}
Expand DownExpand Up@@ -394,7 +398,7 @@ pub(crate) mod tests {
#[test]
fn into_block_header_from_json_response_with_valid_header_array() {
let genesis_block = genesis_block(Network::Bitcoin);
let best_block_header = BlockHeader {
let best_block_header = Header {
prev_blockhash: genesis_block.block_hash(),
..genesis_block.header
};
Expand DownExpand Up@@ -541,7 +545,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_without_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Err(e) => panic!("Unexpected error: {:?}", e),
Expand All@@ -556,7 +560,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_unexpected_blocks_type() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": "foo",
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -572,7 +576,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_invalid_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": std::u64::MAX,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -588,7 +592,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": 1,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand Down
10 changes: 5 additions & 5 deletions lightning-block-sync/src/init.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,7 +4,7 @@
use crate::{BlockSource, BlockSourceResult, Cache, ChainNotifier};
use crate::poll::{ChainPoller, Validate, ValidatedBlockHeader};

use bitcoin::blockdata::block::BlockHeader;
use bitcoin::blockdata::block::Header;
use bitcoin::hash_types::BlockHash;
use bitcoin::network::constants::Network;

Expand DownExpand Up@@ -211,11 +211,11 @@ impl<'a, C: Cache> Cache for ReadOnlyCache<'a, C> {
struct DynamicChainListener<'a, L: chain::Listen + ?Sized>(&'a L);

impl<'a, L: chain::Listen + ?Sized> chain::Listen for DynamicChainListener<'a, L> {
fn filtered_block_connected(&self, _header: &BlockHeader, _txdata: &chain::transaction::TransactionData, _height: u32) {
fn filtered_block_connected(&self, _header: &Header, _txdata: &chain::transaction::TransactionData, _height: u32) {
unreachable!()
}

fn block_disconnected(&self, header: &BlockHeader, height: u32) {
fn block_disconnected(&self, header: &Header, height: u32) {
self.0.block_disconnected(header, height)
}
}
Expand All@@ -234,15 +234,15 @@ impl<'a, L: chain::Listen + ?Sized> chain::Listen for ChainListenerSet<'a, L> {
}
}

fn filtered_block_connected(&self, header: &BlockHeader, txdata: &chain::transaction::TransactionData, height: u32) {
fn filtered_block_connected(&self, header: &Header, txdata: &chain::transaction::TransactionData, height: u32) {
for (starting_height, chain_listener) in self.0.iter() {
if height > *starting_height {
chain_listener.filtered_block_connected(header, txdata, height);
}
}
}

fn block_disconnected(&self, _header: &BlockHeader, _height: u32) {
fn block_disconnected(&self, _header: &Header, _height: u32) {
unreachable!()
}
}
Expand Down
13 changes: 6 additions & 7 deletions lightning-block-sync/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,9 +47,9 @@ mod utils;

use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::hash_types::BlockHash;
use bitcoin::util::uint::Uint256;
use bitcoin::pow::Work;

use lightning::chain;
use lightning::chain::Listen;
Expand DownExpand Up@@ -147,14 +147,13 @@ impl BlockSourceError {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlockHeaderData {
/// The block header itself.
pub header: BlockHeader,
pub header: Header,

/// The block height where the genesis block has height 0.
pub height: u32,

/// The total chain work in expected number of double-SHA256 hashes required to build a chain
/// of equivalent weight.
pub chainwork: Uint256,
/// The total chain work required to build a chain of equivalent weight.
pub chainwork: Work,
}

/// A block including either all its transactions or only the block header.
Expand All@@ -166,7 +165,7 @@ pub enum BlockData {
/// A block containing all its transactions.
FullBlock(Block),
/// A block header for when the block does not contain any pertinent transactions.
HeaderOnly(BlockHeader),
HeaderOnly(Header),
}

/// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions fuzz/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,8 +20,8 @@ stdin_fuzz = []
[dependencies]
lightning = { path = "../lightning", features = ["regex", "hashbrown", "_test_utils"] }
lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync" }
bitcoin = { version = "0.29.0", features = ["secp-lowmemory"] }
hex = "0.3"
bitcoin = { version = "0.30.2", features = ["secp-lowmemory"] }
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
hashbrown = "0.8"

afl = { version = "0.12", optional = true }
Expand Down
12 changes: 6 additions & 6 deletions fuzz/src/chanmon_consistency.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,9 +20,9 @@

use bitcoin::blockdata::constants::genesis_block;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::blockdata::script::{Builder, Script};
use bitcoin::blockdata::script::{Builder, ScriptBuf};
use bitcoin::blockdata::opcodes;
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::network::constants::Network;

use bitcoin::hashes::Hash as TraitImport;
Expand DownExpand Up@@ -270,11 +270,11 @@ impl SignerProvider for KeyProvider {
})
}

fn get_destination_script(&self) -> Result<Script, ()> {
fn get_destination_script(&self) -> Result<ScriptBuf, ()> {
let secp_ctx = Secp256k1::signing_only();
let channel_monitor_claim_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, self.node_secret[31]]).unwrap();
let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script())
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(our_channel_monitor_claim_key_hash).into_script())
}

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
Expand DownExpand Up@@ -343,7 +343,7 @@ type ChanMan<'a> = ChannelManager<Arc<TestChainMonitor>, Arc<TestBroadcaster>, A
fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(PaymentSecret, PaymentHash)> {
let mut payment_hash;
for _ in 0..256 {
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).into_inner());
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).to_byte_array());
if let Ok(payment_secret) = dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None) {
return Some((payment_secret, payment_hash));
}
Expand DownExpand Up@@ -565,7 +565,7 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
let events = $source.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
let tx = Transaction { version: $chan_id, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: $chan_id, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: *channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
funding_output = OutPoint { txid: tx.txid(), index: 0 };
Expand Down
30 changes: 13 additions & 17 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

13 changes: 7 additions & 6 deletions fuzz/src/onion_message.rs
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
// Imports that need to be added manually
use bitcoin::bech32::u5;
use bitcoin::blockdata::script::Script;
use bitcoin::blockdata::script::ScriptBuf;
use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1::ecdsa::RecoverableSignature;
Expand DownExpand Up@@ -199,13 +199,14 @@ impl SignerProvider for KeyProvider {

fn read_chan_signer(&self, _data: &[u8]) -> Result<TestChannelSigner, DecodeError> { unreachable!() }

fn get_destination_script(&self) -> Result<Script, ()> { unreachable!() }
fn get_destination_script(&self) -> Result<ScriptBuf, ()> { unreachable!() }

fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { unreachable!() }
}

#[cfg(test)]
mod tests {
use bitcoin::hashes::hex::FromHex;
use lightning::util::logger::{Logger, Record};
use std::collections::HashMap;
use std::sync::Mutex;
Expand DownExpand Up@@ -258,7 +259,7 @@ mod tests {
000000000000000000000000000000000000000005600000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(one_hop_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(one_hop_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(),
Expand DownExpand Up@@ -302,7 +303,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_hops_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_hops_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -343,7 +344,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(two_unblinded_two_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_two_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand DownExpand Up@@ -384,7 +385,7 @@ mod tests {
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
000000000000000000";
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
super::do_test(&::hex::decode(three_blinded_om).unwrap(), &logger);
super::do_test(&<Vec<u8>>::from_hex(three_blinded_om).unwrap(), &logger);
{
let log_entries = logger.lines.lock().unwrap();
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
Expand Down
2 changes: 1 addition & 1 deletion lightning-background-processor/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ no-std = ["bitcoin/no-std", "lightning/no-std", "lightning-rapid-gossip-sync/no-
default = ["std"]

[dependencies]
bitcoin = { version = "0.29.0", default-features = false }
bitcoin = { version = "0.30.2", default-features = false }
lightning = { version = "0.0.118", path = "../lightning", default-features = false }
lightning-rapid-gossip-sync = { version = "0.0.118", path = "../lightning-rapid-gossip-sync", default-features = false }

Expand Down
4 changes: 2 additions & 2 deletions lightning-background-processor/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -845,7 +845,7 @@ impl Drop for BackgroundProcessor {
#[cfg(all(feature = "std", test))]
mod tests {
use bitcoin::blockdata::constants::{genesis_block, ChainHash};
use bitcoin::blockdata::locktime::PackedLockTime;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::blockdata::transaction::{Transaction, TxOut};
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1};
Expand DownExpand Up@@ -1254,7 +1254,7 @@ mod tests {
assert_eq!(channel_value_satoshis, $channel_value);
assert_eq!(user_channel_id, 42);

let tx = Transaction { version: 1 as i32, lock_time: PackedLockTime(0), input: Vec::new(), output: vec![TxOut {
let tx = Transaction { version: 1 as i32, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
value: channel_value_satoshis, script_pubkey: output_script.clone(),
}]};
(temporary_channel_id, tx)
Expand Down
3 changes: 2 additions & 1 deletion lightning-block-sync/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,8 @@ rest-client = [ "serde_json", "chunked_transfer" ]
rpc-client = [ "serde_json", "chunked_transfer" ]

[dependencies]
bitcoin = "0.29.0"
bitcoin = "0.30.2"
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
lightning = { version = "0.0.118", path = "../lightning" }
tokio = { version = "1.0", features = [ "io-util", "net", "time" ], optional = true }
serde_json = { version = "1.0", optional = true }
Expand Down
44 changes: 24 additions & 20 deletions lightning-block-sync/src/convert.rs
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
use crate::http::{BinaryResponse, JsonResponse};
use crate::utils::hex_to_uint256;
use crate::utils::hex_to_work;
use crate::{BlockHeaderData, BlockSourceError};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::consensus::encode;
use bitcoin::hash_types::{BlockHash, TxMerkleNode, Txid};
use bitcoin::hashes::hex::FromHex;
Expand DownExpand Up@@ -88,17 +88,21 @@ impl TryFrom<serde_json::Value> for BlockHeaderData {
} }

Ok(BlockHeaderData {
header: BlockHeader {
version: get_field!("version", as_i64).try_into().map_err(|_| ())?,
header: Header {
version: bitcoin::blockdata::block::Version::from_consensus(
get_field!("version", as_i64).try_into().map_err(|_| ())?
),
prev_blockhash: if let Some(hash_str) = response.get("previousblockhash") {
BlockHash::from_hex(hash_str.as_str().ok_or(())?).map_err(|_| ())?
BlockHash::from_str(hash_str.as_str().ok_or(())?).map_err(|_| ())?
} else { BlockHash::all_zeros() },
merkle_root: TxMerkleNode::from_hex(get_field!("merkleroot", as_str)).map_err(|_| ())?,
merkle_root: TxMerkleNode::from_str(get_field!("merkleroot", as_str)).map_err(|_| ())?,
time: get_field!("time", as_u64).try_into().map_err(|_| ())?,
bits: u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?),
bits: bitcoin::CompactTarget::from_consensus(
u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?)
),
nonce: get_field!("nonce", as_u64).try_into().map_err(|_| ())?,
},
chainwork: hex_to_uint256(get_field!("chainwork", as_str)).map_err(|_| ())?,
chainwork: hex_to_work(get_field!("chainwork", as_str)).map_err(|_| ())?,
height: get_field!("height", as_u64).try_into().map_err(|_| ())?,
})
}
Expand DownExpand Up@@ -132,7 +136,7 @@ impl TryInto<(BlockHash, Option<u32>)> for JsonResponse {
}

let hash = match &self.0["bestblockhash"] {
serde_json::Value::String(hex_data) => match BlockHash::from_hex(&hex_data) {
serde_json::Value::String(hex_data) => match BlockHash::from_str(&hex_data) {
Err(_) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid hex data")),
Ok(block_hash) => block_hash,
},
Expand DownExpand Up@@ -288,8 +292,8 @@ pub(crate) mod tests {
use super::*;
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::hashes::Hash;
use bitcoin::hashes::hex::ToHex;
use bitcoin::network::constants::Network;
use hex::DisplayHex;
use serde_json::value::Number;
use serde_json::Value;

Expand All@@ -298,14 +302,14 @@ pub(crate) mod tests {
fn from(data: BlockHeaderData) -> Self {
let BlockHeaderData { chainwork, height, header } = data;
serde_json::json!({
"chainwork": chainwork.to_string()["0x".len()..],
"chainwork": chainwork.to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI this could be format!("{:064x}", chainwork) which conveys the intent better.

"height": height,
"version": header.version,
"merkleroot": header.merkle_root.to_hex(),
"version": header.version.to_consensus(),
"merkleroot": header.merkle_root.to_string(),
"time": header.time,
"nonce": header.nonce,
"bits": header.bits.to_hex(),
"previousblockhash": header.prev_blockhash.to_hex(),
"bits": header.bits.to_consensus().to_be_bytes().as_hex().to_string(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

format!("{08x}", header.bits.to_consensus()) would convey the meaning better but your code is actually faster because std formatting is over-complicated. I've opened an issue to support hex directly on CompactTarget but that will still be slower than your code.

"previousblockhash": header.prev_blockhash.to_string(),
})
}
}
Expand DownExpand Up@@ -394,7 +398,7 @@ pub(crate) mod tests {
#[test]
fn into_block_header_from_json_response_with_valid_header_array() {
let genesis_block = genesis_block(Network::Bitcoin);
let best_block_header = BlockHeader {
let best_block_header = Header {
prev_blockhash: genesis_block.block_hash(),
..genesis_block.header
};
Expand DownExpand Up@@ -541,7 +545,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_without_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Err(e) => panic!("Unexpected error: {:?}", e),
Expand All@@ -556,7 +560,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_unexpected_blocks_type() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": "foo",
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -572,7 +576,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_invalid_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": std::u64::MAX,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand All@@ -588,7 +592,7 @@ pub(crate) mod tests {
fn into_block_hash_from_json_response_with_height() {
let block = genesis_block(Network::Bitcoin);
let response = JsonResponse(serde_json::json!({
"bestblockhash": block.block_hash().to_hex(),
"bestblockhash": block.block_hash().to_string(),
"blocks": 1,
}));
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
Expand Down
10 changes: 5 additions & 5 deletions lightning-block-sync/src/init.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,7 +4,7 @@
use crate::{BlockSource, BlockSourceResult, Cache, ChainNotifier};
use crate::poll::{ChainPoller, Validate, ValidatedBlockHeader};

use bitcoin::blockdata::block::BlockHeader;
use bitcoin::blockdata::block::Header;
use bitcoin::hash_types::BlockHash;
use bitcoin::network::constants::Network;

Expand DownExpand Up@@ -211,11 +211,11 @@ impl<'a, C: Cache> Cache for ReadOnlyCache<'a, C> {
struct DynamicChainListener<'a, L: chain::Listen + ?Sized>(&'a L);

impl<'a, L: chain::Listen + ?Sized> chain::Listen for DynamicChainListener<'a, L> {
fn filtered_block_connected(&self, _header: &BlockHeader, _txdata: &chain::transaction::TransactionData, _height: u32) {
fn filtered_block_connected(&self, _header: &Header, _txdata: &chain::transaction::TransactionData, _height: u32) {
unreachable!()
}

fn block_disconnected(&self, header: &BlockHeader, height: u32) {
fn block_disconnected(&self, header: &Header, height: u32) {
self.0.block_disconnected(header, height)
}
}
Expand All@@ -234,15 +234,15 @@ impl<'a, L: chain::Listen + ?Sized> chain::Listen for ChainListenerSet<'a, L> {
}
}

fn filtered_block_connected(&self, header: &BlockHeader, txdata: &chain::transaction::TransactionData, height: u32) {
fn filtered_block_connected(&self, header: &Header, txdata: &chain::transaction::TransactionData, height: u32) {
for (starting_height, chain_listener) in self.0.iter() {
if height > *starting_height {
chain_listener.filtered_block_connected(header, txdata, height);
}
}
}

fn block_disconnected(&self, _header: &BlockHeader, _height: u32) {
fn block_disconnected(&self, _header: &Header, _height: u32) {
unreachable!()
}
}
Expand Down
13 changes: 6 additions & 7 deletions lightning-block-sync/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,9 +47,9 @@ mod utils;

use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};

use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::block::{Block, Header};
use bitcoin::hash_types::BlockHash;
use bitcoin::util::uint::Uint256;
use bitcoin::pow::Work;

use lightning::chain;
use lightning::chain::Listen;
Expand DownExpand Up@@ -147,14 +147,13 @@ impl BlockSourceError {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlockHeaderData {
/// The block header itself.
pub header: BlockHeader,
pub header: Header,

/// The block height where the genesis block has height 0.
pub height: u32,

/// The total chain work in expected number of double-SHA256 hashes required to build a chain
/// of equivalent weight.
pub chainwork: Uint256,
/// The total chain work required to build a chain of equivalent weight.
pub chainwork: Work,
}

/// A block including either all its transactions or only the block header.
Expand All@@ -166,7 +165,7 @@ pub enum BlockData {
/// A block containing all its transactions.
FullBlock(Block),
/// A block header for when the block does not contain any pertinent transactions.
HeaderOnly(BlockHeader),
HeaderOnly(Header),
}

/// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
Expand Down
Loading