Skip to content

Commit 70ea110

Browse files
authored
Merge pull request #2740 from wpaulino/rust-bitcoin-30-update
Update to rust-bitcoin v0.30.2
2 parents 870a0f1 + ad56847 commit 70ea110

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

76 files changed

+1383
-1386
lines changed

fuzz/Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ stdin_fuzz = []
2020
[dependencies]
2121
lightning = { path = "../lightning", features = ["regex", "hashbrown", "_test_utils"] }
2222
lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync" }
23-
bitcoin = { version = "0.29.0", features = ["secp-lowmemory"] }
24-
hex = "0.3"
23+
bitcoin = { version = "0.30.2", features = ["secp-lowmemory"] }
24+
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
2525
hashbrown = "0.8"
2626

2727
afl = { version = "0.12", optional = true }

fuzz/src/chanmon_consistency.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@
2020
2121
use bitcoin::blockdata::constants::genesis_block;
2222
use bitcoin::blockdata::transaction::{Transaction, TxOut};
23-
use bitcoin::blockdata::script::{Builder, Script};
23+
use bitcoin::blockdata::script::{Builder, ScriptBuf};
2424
use bitcoin::blockdata::opcodes;
25-
use bitcoin::blockdata::locktime::PackedLockTime;
25+
use bitcoin::blockdata::locktime::absolute::LockTime;
2626
use bitcoin::network::constants::Network;
2727

2828
use bitcoin::hashes::Hash as TraitImport;
@@ -270,11 +270,11 @@ impl SignerProvider for KeyProvider {
270270
})
271271
}
272272

273-
fn get_destination_script(&self) -> Result<Script, ()> {
273+
fn get_destination_script(&self) -> Result<ScriptBuf, ()> {
274274
let secp_ctx = Secp256k1::signing_only();
275275
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();
276276
let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
277-
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script())
277+
Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(our_channel_monitor_claim_key_hash).into_script())
278278
}
279279

280280
fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
@@ -343,7 +343,7 @@ type ChanMan<'a> = ChannelManager<Arc<TestChainMonitor>, Arc<TestBroadcaster>, A
343343
fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(PaymentSecret, PaymentHash)> {
344344
let mut payment_hash;
345345
for _ in 0..256 {
346-
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).into_inner());
346+
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).to_byte_array());
347347
if let Ok(payment_secret) = dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None) {
348348
return Some((payment_secret, payment_hash));
349349
}
@@ -565,7 +565,7 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
565565
let events = $source.get_and_clear_pending_events();
566566
assert_eq!(events.len(), 1);
567567
if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
568-
let tx = Transaction { version: $chan_id, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
568+
let tx = Transaction { version: $chan_id, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
569569
value: *channel_value_satoshis, script_pubkey: output_script.clone(),
570570
}]};
571571
funding_output = OutPoint { txid: tx.txid(), index: 0 };

fuzz/src/full_stack.rs

+13-17
Large diffs are not rendered by default.

fuzz/src/onion_message.rs

+7-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Imports that need to be added manually
22
use bitcoin::bech32::u5;
3-
use bitcoin::blockdata::script::Script;
3+
use bitcoin::blockdata::script::ScriptBuf;
44
use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
55
use bitcoin::secp256k1::ecdh::SharedSecret;
66
use bitcoin::secp256k1::ecdsa::RecoverableSignature;
@@ -199,13 +199,14 @@ impl SignerProvider for KeyProvider {
199199

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

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

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

207207
#[cfg(test)]
208208
mod tests {
209+
use bitcoin::hashes::hex::FromHex;
209210
use lightning::util::logger::{Logger, Record};
210211
use std::collections::HashMap;
211212
use std::sync::Mutex;
@@ -258,7 +259,7 @@ mod tests {
258259
000000000000000000000000000000000000000005600000000000000000000000000000000000000000000\
259260
000000000000000000";
260261
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
261-
super::do_test(&::hex::decode(one_hop_om).unwrap(), &logger);
262+
super::do_test(&<Vec<u8>>::from_hex(one_hop_om).unwrap(), &logger);
262263
{
263264
let log_entries = logger.lines.lock().unwrap();
264265
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(),
@@ -302,7 +303,7 @@ mod tests {
302303
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
303304
000000000000000000";
304305
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
305-
super::do_test(&::hex::decode(two_unblinded_hops_om).unwrap(), &logger);
306+
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_hops_om).unwrap(), &logger);
306307
{
307308
let log_entries = logger.lines.lock().unwrap();
308309
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
@@ -343,7 +344,7 @@ mod tests {
343344
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
344345
000000000000000000";
345346
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
346-
super::do_test(&::hex::decode(two_unblinded_two_blinded_om).unwrap(), &logger);
347+
super::do_test(&<Vec<u8>>::from_hex(two_unblinded_two_blinded_om).unwrap(), &logger);
347348
{
348349
let log_entries = logger.lines.lock().unwrap();
349350
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
@@ -384,7 +385,7 @@ mod tests {
384385
000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
385386
000000000000000000";
386387
let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
387-
super::do_test(&::hex::decode(three_blinded_om).unwrap(), &logger);
388+
super::do_test(&<Vec<u8>>::from_hex(three_blinded_om).unwrap(), &logger);
388389
{
389390
let log_entries = logger.lines.lock().unwrap();
390391
assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));

lightning-background-processor/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ no-std = ["bitcoin/no-std", "lightning/no-std", "lightning-rapid-gossip-sync/no-
2121
default = ["std"]
2222

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

lightning-background-processor/src/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -845,7 +845,7 @@ impl Drop for BackgroundProcessor {
845845
#[cfg(all(feature = "std", test))]
846846
mod tests {
847847
use bitcoin::blockdata::constants::{genesis_block, ChainHash};
848-
use bitcoin::blockdata::locktime::PackedLockTime;
848+
use bitcoin::blockdata::locktime::absolute::LockTime;
849849
use bitcoin::blockdata::transaction::{Transaction, TxOut};
850850
use bitcoin::network::constants::Network;
851851
use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1};
@@ -1254,7 +1254,7 @@ mod tests {
12541254
assert_eq!(channel_value_satoshis, $channel_value);
12551255
assert_eq!(user_channel_id, 42);
12561256

1257-
let tx = Transaction { version: 1 as i32, lock_time: PackedLockTime(0), input: Vec::new(), output: vec![TxOut {
1257+
let tx = Transaction { version: 1 as i32, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
12581258
value: channel_value_satoshis, script_pubkey: output_script.clone(),
12591259
}]};
12601260
(temporary_channel_id, tx)

lightning-block-sync/Cargo.toml

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ rest-client = [ "serde_json", "chunked_transfer" ]
1818
rpc-client = [ "serde_json", "chunked_transfer" ]
1919

2020
[dependencies]
21-
bitcoin = "0.29.0"
21+
bitcoin = "0.30.2"
22+
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }
2223
lightning = { version = "0.0.118", path = "../lightning" }
2324
tokio = { version = "1.0", features = [ "io-util", "net", "time" ], optional = true }
2425
serde_json = { version = "1.0", optional = true }

lightning-block-sync/src/convert.rs

+24-20
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use crate::http::{BinaryResponse, JsonResponse};
2-
use crate::utils::hex_to_uint256;
2+
use crate::utils::hex_to_work;
33
use crate::{BlockHeaderData, BlockSourceError};
44

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

9090
Ok(BlockHeaderData {
91-
header: BlockHeader {
92-
version: get_field!("version", as_i64).try_into().map_err(|_| ())?,
91+
header: Header {
92+
version: bitcoin::blockdata::block::Version::from_consensus(
93+
get_field!("version", as_i64).try_into().map_err(|_| ())?
94+
),
9395
prev_blockhash: if let Some(hash_str) = response.get("previousblockhash") {
94-
BlockHash::from_hex(hash_str.as_str().ok_or(())?).map_err(|_| ())?
96+
BlockHash::from_str(hash_str.as_str().ok_or(())?).map_err(|_| ())?
9597
} else { BlockHash::all_zeros() },
96-
merkle_root: TxMerkleNode::from_hex(get_field!("merkleroot", as_str)).map_err(|_| ())?,
98+
merkle_root: TxMerkleNode::from_str(get_field!("merkleroot", as_str)).map_err(|_| ())?,
9799
time: get_field!("time", as_u64).try_into().map_err(|_| ())?,
98-
bits: u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?),
100+
bits: bitcoin::CompactTarget::from_consensus(
101+
u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?)
102+
),
99103
nonce: get_field!("nonce", as_u64).try_into().map_err(|_| ())?,
100104
},
101-
chainwork: hex_to_uint256(get_field!("chainwork", as_str)).map_err(|_| ())?,
105+
chainwork: hex_to_work(get_field!("chainwork", as_str)).map_err(|_| ())?,
102106
height: get_field!("height", as_u64).try_into().map_err(|_| ())?,
103107
})
104108
}
@@ -132,7 +136,7 @@ impl TryInto<(BlockHash, Option<u32>)> for JsonResponse {
132136
}
133137

134138
let hash = match &self.0["bestblockhash"] {
135-
serde_json::Value::String(hex_data) => match BlockHash::from_hex(&hex_data) {
139+
serde_json::Value::String(hex_data) => match BlockHash::from_str(&hex_data) {
136140
Err(_) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid hex data")),
137141
Ok(block_hash) => block_hash,
138142
},
@@ -288,8 +292,8 @@ pub(crate) mod tests {
288292
use super::*;
289293
use bitcoin::blockdata::constants::genesis_block;
290294
use bitcoin::hashes::Hash;
291-
use bitcoin::hashes::hex::ToHex;
292295
use bitcoin::network::constants::Network;
296+
use hex::DisplayHex;
293297
use serde_json::value::Number;
294298
use serde_json::Value;
295299

@@ -298,14 +302,14 @@ pub(crate) mod tests {
298302
fn from(data: BlockHeaderData) -> Self {
299303
let BlockHeaderData { chainwork, height, header } = data;
300304
serde_json::json!({
301-
"chainwork": chainwork.to_string()["0x".len()..],
305+
"chainwork": chainwork.to_be_bytes().as_hex().to_string(),
302306
"height": height,
303-
"version": header.version,
304-
"merkleroot": header.merkle_root.to_hex(),
307+
"version": header.version.to_consensus(),
308+
"merkleroot": header.merkle_root.to_string(),
305309
"time": header.time,
306310
"nonce": header.nonce,
307-
"bits": header.bits.to_hex(),
308-
"previousblockhash": header.prev_blockhash.to_hex(),
311+
"bits": header.bits.to_consensus().to_be_bytes().as_hex().to_string(),
312+
"previousblockhash": header.prev_blockhash.to_string(),
309313
})
310314
}
311315
}
@@ -394,7 +398,7 @@ pub(crate) mod tests {
394398
#[test]
395399
fn into_block_header_from_json_response_with_valid_header_array() {
396400
let genesis_block = genesis_block(Network::Bitcoin);
397-
let best_block_header = BlockHeader {
401+
let best_block_header = Header {
398402
prev_blockhash: genesis_block.block_hash(),
399403
..genesis_block.header
400404
};
@@ -541,7 +545,7 @@ pub(crate) mod tests {
541545
fn into_block_hash_from_json_response_without_height() {
542546
let block = genesis_block(Network::Bitcoin);
543547
let response = JsonResponse(serde_json::json!({
544-
"bestblockhash": block.block_hash().to_hex(),
548+
"bestblockhash": block.block_hash().to_string(),
545549
}));
546550
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
547551
Err(e) => panic!("Unexpected error: {:?}", e),
@@ -556,7 +560,7 @@ pub(crate) mod tests {
556560
fn into_block_hash_from_json_response_with_unexpected_blocks_type() {
557561
let block = genesis_block(Network::Bitcoin);
558562
let response = JsonResponse(serde_json::json!({
559-
"bestblockhash": block.block_hash().to_hex(),
563+
"bestblockhash": block.block_hash().to_string(),
560564
"blocks": "foo",
561565
}));
562566
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
@@ -572,7 +576,7 @@ pub(crate) mod tests {
572576
fn into_block_hash_from_json_response_with_invalid_height() {
573577
let block = genesis_block(Network::Bitcoin);
574578
let response = JsonResponse(serde_json::json!({
575-
"bestblockhash": block.block_hash().to_hex(),
579+
"bestblockhash": block.block_hash().to_string(),
576580
"blocks": std::u64::MAX,
577581
}));
578582
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
@@ -588,7 +592,7 @@ pub(crate) mod tests {
588592
fn into_block_hash_from_json_response_with_height() {
589593
let block = genesis_block(Network::Bitcoin);
590594
let response = JsonResponse(serde_json::json!({
591-
"bestblockhash": block.block_hash().to_hex(),
595+
"bestblockhash": block.block_hash().to_string(),
592596
"blocks": 1,
593597
}));
594598
match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {

lightning-block-sync/src/init.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
use crate::{BlockSource, BlockSourceResult, Cache, ChainNotifier};
55
use crate::poll::{ChainPoller, Validate, ValidatedBlockHeader};
66

7-
use bitcoin::blockdata::block::BlockHeader;
7+
use bitcoin::blockdata::block::Header;
88
use bitcoin::hash_types::BlockHash;
99
use bitcoin::network::constants::Network;
1010

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

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

218-
fn block_disconnected(&self, header: &BlockHeader, height: u32) {
218+
fn block_disconnected(&self, header: &Header, height: u32) {
219219
self.0.block_disconnected(header, height)
220220
}
221221
}
@@ -234,15 +234,15 @@ impl<'a, L: chain::Listen + ?Sized> chain::Listen for ChainListenerSet<'a, L> {
234234
}
235235
}
236236

237-
fn filtered_block_connected(&self, header: &BlockHeader, txdata: &chain::transaction::TransactionData, height: u32) {
237+
fn filtered_block_connected(&self, header: &Header, txdata: &chain::transaction::TransactionData, height: u32) {
238238
for (starting_height, chain_listener) in self.0.iter() {
239239
if height > *starting_height {
240240
chain_listener.filtered_block_connected(header, txdata, height);
241241
}
242242
}
243243
}
244244

245-
fn block_disconnected(&self, _header: &BlockHeader, _height: u32) {
245+
fn block_disconnected(&self, _header: &Header, _height: u32) {
246246
unreachable!()
247247
}
248248
}

lightning-block-sync/src/lib.rs

+6-7
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,9 @@ mod utils;
4747

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

50-
use bitcoin::blockdata::block::{Block, BlockHeader};
50+
use bitcoin::blockdata::block::{Block, Header};
5151
use bitcoin::hash_types::BlockHash;
52-
use bitcoin::util::uint::Uint256;
52+
use bitcoin::pow::Work;
5353

5454
use lightning::chain;
5555
use lightning::chain::Listen;
@@ -147,14 +147,13 @@ impl BlockSourceError {
147147
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
148148
pub struct BlockHeaderData {
149149
/// The block header itself.
150-
pub header: BlockHeader,
150+
pub header: Header,
151151

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

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

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

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

0 commit comments

Comments
 (0)