Skip to content

Commit 9fba7c9

Browse files
authored
Merge pull request #802 from TheBlueMatt/2021-01-update-rust-bitcoin
Update rust-bitcoin and add secp256k1 context randomization
2 parents beb88e6 + ea48a5a commit 9fba7c9

File tree

19 files changed

+127
-93
lines changed

19 files changed

+127
-93
lines changed

.github/workflows/build.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ jobs:
202202
sudo apt-get update
203203
sudo apt-get -y install build-essential binutils-dev libunwind-dev
204204
- name: Sanity check fuzz targets on Rust ${{ env.TOOLCHAIN }}
205-
run: cd fuzz && cargo test --verbose --color always
205+
run: cd fuzz && RUSTFLAGS="--cfg=fuzzing" cargo test --verbose --color always
206206
- name: Run fuzzers
207207
run: cd fuzz && ./ci-fuzz.sh
208208

background-processor/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ edition = "2018"
77
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
88

99
[dependencies]
10-
bitcoin = "0.24"
10+
bitcoin = "0.26"
1111
lightning = { version = "0.0.12", path = "../lightning", features = ["allow_wallclock_use"] }
1212
lightning-persister = { version = "0.0.1", path = "../lightning-persister" }
1313

fuzz/Cargo.toml

+7-1
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,17 @@ stdin_fuzz = []
1919
[dependencies]
2020
afl = { version = "0.4", optional = true }
2121
lightning = { path = "../lightning", features = ["fuzztarget"] }
22-
bitcoin = { version = "0.24", features = ["fuzztarget"] }
22+
bitcoin = { version = "0.26", features = ["fuzztarget", "secp-lowmemory"] }
2323
hex = "0.3"
2424
honggfuzz = { version = "0.5", optional = true }
2525
libfuzzer-sys = { git = "https://github.com/rust-fuzz/libfuzzer-sys.git", optional = true }
2626

27+
[patch.crates-io]
28+
# Rust-Secp256k1 PR 282. This patch should be dropped once that is merged.
29+
secp256k1 = { git = 'https://github.com/TheBlueMatt/rust-secp256k1', rev = '32767e0e21e8861701ff7d5957613169d67ff1f8' }
30+
# bitcoin_hashes PR 111 (without the top commit). This patch should be dropped once that is merged.
31+
bitcoin_hashes = { git = 'https://github.com/TheBlueMatt/bitcoin_hashes', rev = 'c90d26339a3e34fd2f942aa80298f410cc41b743' }
32+
2733
[build-dependencies]
2834
cc = "1.0"
2935

fuzz/src/full_stack.rs

+43-43
Large diffs are not rendered by default.

lightning-block-sync/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ rest-client = [ "serde", "serde_json", "chunked_transfer" ]
1313
rpc-client = [ "serde", "serde_json", "chunked_transfer" ]
1414

1515
[dependencies]
16-
bitcoin = "0.24"
16+
bitcoin = "0.26"
1717
lightning = { version = "0.0.12", path = "../lightning" }
1818
tokio = { version = "1.0", features = [ "io-util", "net" ], optional = true }
1919
serde = { version = "1.0", features = ["derive"], optional = true }

lightning-c-bindings/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ crate-type = ["staticlib"
1515
,"cdylib"]
1616

1717
[dependencies]
18-
bitcoin = "0.24"
18+
bitcoin = "0.26"
1919
lightning = { version = "0.0.12", path = "../lightning" }
2020

2121
# We eventually want to join the root workspace, but for now, the bindings generation is

lightning-c-bindings/src/c_types/mod.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,8 @@ pub enum Secp256k1Error {
7272
InvalidSecretKey,
7373
InvalidRecoveryId,
7474
InvalidTweak,
75+
TweakCheckFailed,
7576
NotEnoughMemory,
76-
CallbackPanicked,
7777
}
7878
impl Secp256k1Error {
7979
pub(crate) fn from_rust(err: SecpError) -> Self {
@@ -85,6 +85,7 @@ impl Secp256k1Error {
8585
SecpError::InvalidSecretKey => Secp256k1Error::InvalidSecretKey,
8686
SecpError::InvalidRecoveryId => Secp256k1Error::InvalidRecoveryId,
8787
SecpError::InvalidTweak => Secp256k1Error::InvalidTweak,
88+
SecpError::TweakCheckFailed => Secp256k1Error::TweakCheckFailed,
8889
SecpError::NotEnoughMemory => Secp256k1Error::NotEnoughMemory,
8990
}
9091
}

lightning-net-tokio/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ For Rust-Lightning clients which wish to make direct connections to Lightning P2
1010
"""
1111

1212
[dependencies]
13-
bitcoin = "0.24"
13+
bitcoin = "0.26"
1414
lightning = { version = "0.0.12", path = "../lightning" }
1515
tokio = { version = "1.0", features = [ "io-util", "macros", "rt", "sync", "net", "time" ] }
1616

lightning-persister/Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,15 @@ Utilities to manage channel data persistence and retrieval.
88
"""
99

1010
[dependencies]
11-
bitcoin = "0.24"
11+
bitcoin = "0.26"
1212
lightning = { version = "0.0.12", path = "../lightning" }
1313
libc = "0.2"
1414

1515
[target.'cfg(windows)'.dependencies]
1616
winapi = { version = "0.3", features = ["winbase"] }
1717

1818
[dev-dependencies.bitcoin]
19-
version = "0.24"
19+
version = "0.26"
2020
features = ["bitcoinconsensus"]
2121

2222
[dev-dependencies]

lightning/Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,13 @@ unsafe_revoked_tx_signing = []
2727
unstable = []
2828

2929
[dependencies]
30-
bitcoin = "0.24"
30+
bitcoin = "0.26"
3131

3232
hex = { version = "0.3", optional = true }
3333
regex = { version = "0.1.80", optional = true }
3434

3535
[dev-dependencies.bitcoin]
36-
version = "0.24"
36+
version = "0.26"
3737
features = ["bitcoinconsensus"]
3838

3939
[dev-dependencies]

lightning/src/chain/channelmonitor.rs

+8-6
Original file line numberDiff line numberDiff line change
@@ -951,7 +951,7 @@ impl<Signer: Sign> Writeable for ChannelMonitor<Signer> {
951951
}
952952

953953
impl<Signer: Sign> ChannelMonitor<Signer> {
954-
pub(crate) fn new(keys: Signer, shutdown_pubkey: &PublicKey,
954+
pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_pubkey: &PublicKey,
955955
on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
956956
channel_parameters: &ChannelTransactionParameters,
957957
funding_redeemscript: Script, channel_value_satoshis: u64,
@@ -972,8 +972,6 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
972972
let channel_keys_id = keys.channel_keys_id();
973973
let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
974974

975-
let secp_ctx = Secp256k1::new();
976-
977975
// block for Rust 1.34 compat
978976
let (holder_commitment_tx, current_holder_commitment_number) = {
979977
let trusted_tx = initial_holder_commitment_tx.trust();
@@ -994,7 +992,8 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
994992
};
995993

996994
let onchain_tx_handler =
997-
OnchainTxHandler::new(destination_script.clone(), keys, channel_parameters.clone(), initial_holder_commitment_tx);
995+
OnchainTxHandler::new(destination_script.clone(), keys,
996+
channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx.clone());
998997

999998
let mut outputs_to_watch = HashMap::new();
1000999
outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
@@ -2558,6 +2557,9 @@ impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
25582557
let lockdown_from_offchain = Readable::read(reader)?;
25592558
let holder_tx_signed = Readable::read(reader)?;
25602559

2560+
let mut secp_ctx = Secp256k1::new();
2561+
secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
2562+
25612563
Ok((last_block_hash.clone(), ChannelMonitor {
25622564
latest_update_id,
25632565
commitment_transaction_number_obscure_factor,
@@ -2603,7 +2605,7 @@ impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
26032605
holder_tx_signed,
26042606

26052607
last_block_hash,
2606-
secp_ctx: Secp256k1::new(),
2608+
secp_ctx,
26072609
}))
26082610
}
26092611
}
@@ -2718,7 +2720,7 @@ mod tests {
27182720
};
27192721
// Prune with one old state and a holder commitment tx holding a few overlaps with the
27202722
// old state.
2721-
let mut monitor = ChannelMonitor::new(keys,
2723+
let mut monitor = ChannelMonitor::new(Secp256k1::new(), keys,
27222724
&PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0, &Script::new(),
27232725
(OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
27242726
&channel_parameters,

lightning/src/chain/keysinterface.rs

+17-10
Original file line numberDiff line numberDiff line change
@@ -744,8 +744,10 @@ pub struct KeysManager {
744744
shutdown_pubkey: PublicKey,
745745
channel_master_key: ExtendedPrivKey,
746746
channel_child_index: AtomicUsize,
747+
747748
rand_bytes_master_key: ExtendedPrivKey,
748749
rand_bytes_child_index: AtomicUsize,
750+
rand_bytes_unique_start: Sha256State,
749751

750752
seed: [u8; 32],
751753
starting_time_secs: u64,
@@ -794,31 +796,36 @@ impl KeysManager {
794796
let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
795797
let rand_bytes_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()).expect("Your RNG is busted");
796798

797-
KeysManager {
799+
let mut rand_bytes_unique_start = Sha256::engine();
800+
rand_bytes_unique_start.input(&byte_utils::be64_to_array(starting_time_secs));
801+
rand_bytes_unique_start.input(&byte_utils::be32_to_array(starting_time_nanos));
802+
rand_bytes_unique_start.input(seed);
803+
804+
let mut res = KeysManager {
798805
secp_ctx,
799806
node_secret,
807+
800808
destination_script,
801809
shutdown_pubkey,
810+
802811
channel_master_key,
803812
channel_child_index: AtomicUsize::new(0),
813+
804814
rand_bytes_master_key,
805815
rand_bytes_child_index: AtomicUsize::new(0),
816+
rand_bytes_unique_start,
806817

807818
seed: *seed,
808819
starting_time_secs,
809820
starting_time_nanos,
810-
}
821+
};
822+
let secp_seed = res.get_secure_random_bytes();
823+
res.secp_ctx.seeded_randomize(&secp_seed);
824+
res
811825
},
812826
Err(_) => panic!("Your rng is busted"),
813827
}
814828
}
815-
fn derive_unique_start(&self) -> Sha256State {
816-
let mut unique_start = Sha256::engine();
817-
unique_start.input(&byte_utils::be64_to_array(self.starting_time_secs));
818-
unique_start.input(&byte_utils::be32_to_array(self.starting_time_nanos));
819-
unique_start.input(&self.seed);
820-
unique_start
821-
}
822829
/// Derive an old set of Sign for per-channel secrets based on a key derivation
823830
/// parameters.
824831
/// Key derivation parameters are accessible through a per-channel secrets
@@ -1017,7 +1024,7 @@ impl KeysInterface for KeysManager {
10171024
}
10181025

10191026
fn get_secure_random_bytes(&self) -> [u8; 32] {
1020-
let mut sha = self.derive_unique_start();
1027+
let mut sha = self.rand_bytes_unique_start.clone();
10211028

10221029
let child_ix = self.rand_bytes_child_index.fetch_add(1, Ordering::AcqRel);
10231030
let child_privkey = self.rand_bytes_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(child_ix as u32).expect("key space exhausted")).expect("Your RNG is busted");

lightning/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
//! instead of having a rather-separate lightning appendage to a wallet.
2020
2121
#![cfg_attr(not(any(feature = "fuzztarget", feature = "_test_utils")), deny(missing_docs))]
22-
#![forbid(unsafe_code)]
22+
#![cfg_attr(not(any(test, feature = "fuzztarget", feature = "_test_utils")), forbid(unsafe_code))]
2323

2424
// In general, rust is absolutely horrid at supporting users doing things like,
2525
// for example, compiling Rust code for real environments. Disable useless lints

lightning/src/ln/channel.rs

+16-6
Original file line numberDiff line numberDiff line change
@@ -521,13 +521,16 @@ impl<Signer: Sign> Channel<Signer> {
521521

522522
let feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
523523

524+
let mut secp_ctx = Secp256k1::new();
525+
secp_ctx.seeded_randomize(&keys_provider.get_secure_random_bytes());
526+
524527
Ok(Channel {
525528
user_id,
526529
config: config.channel_options.clone(),
527530

528531
channel_id: keys_provider.get_secure_random_bytes(),
529532
channel_state: ChannelState::OurInitSent as u32,
530-
secp_ctx: Secp256k1::new(),
533+
secp_ctx,
531534
channel_value_satoshis,
532535

533536
latest_monitor_update_id: 0,
@@ -755,13 +758,16 @@ impl<Signer: Sign> Channel<Signer> {
755758
}
756759
} else { None };
757760

761+
let mut secp_ctx = Secp256k1::new();
762+
secp_ctx.seeded_randomize(&keys_provider.get_secure_random_bytes());
763+
758764
let chan = Channel {
759765
user_id,
760766
config: local_config,
761767

762768
channel_id: msg.temporary_channel_id,
763769
channel_state: (ChannelState::OurInitSent as u32) | (ChannelState::TheirInitSent as u32),
764-
secp_ctx: Secp256k1::new(),
770+
secp_ctx,
765771

766772
latest_monitor_update_id: 0,
767773

@@ -1564,7 +1570,7 @@ impl<Signer: Sign> Channel<Signer> {
15641570
let funding_redeemscript = self.get_funding_redeemscript();
15651571
let funding_txo_script = funding_redeemscript.to_v0_p2wsh();
15661572
let obscure_factor = get_commitment_transaction_number_obscure_factor(&self.get_holder_pubkeys().payment_point, &self.get_counterparty_pubkeys().payment_point, self.is_outbound());
1567-
let mut channel_monitor = ChannelMonitor::new(self.holder_signer.clone(),
1573+
let mut channel_monitor = ChannelMonitor::new(self.secp_ctx.clone(), self.holder_signer.clone(),
15681574
&self.shutdown_pubkey, self.get_holder_selected_contest_delay(),
15691575
&self.destination_script, (funding_txo, funding_txo_script.clone()),
15701576
&self.channel_transaction_parameters,
@@ -1634,7 +1640,7 @@ impl<Signer: Sign> Channel<Signer> {
16341640
let funding_txo = self.get_funding_txo().unwrap();
16351641
let funding_txo_script = funding_redeemscript.to_v0_p2wsh();
16361642
let obscure_factor = get_commitment_transaction_number_obscure_factor(&self.get_holder_pubkeys().payment_point, &self.get_counterparty_pubkeys().payment_point, self.is_outbound());
1637-
let mut channel_monitor = ChannelMonitor::new(self.holder_signer.clone(),
1643+
let mut channel_monitor = ChannelMonitor::new(self.secp_ctx.clone(), self.holder_signer.clone(),
16381644
&self.shutdown_pubkey, self.get_holder_selected_contest_delay(),
16391645
&self.destination_script, (funding_txo, funding_txo_script),
16401646
&self.channel_transaction_parameters,
@@ -4081,7 +4087,8 @@ impl<Signer: Sign> Channel<Signer> {
40814087
signature = res.0;
40824088
htlc_signatures = res.1;
40834089

4084-
log_trace!(logger, "Signed remote commitment tx {} with redeemscript {} -> {}",
4090+
log_trace!(logger, "Signed remote commitment tx {} (txid {}) with redeemscript {} -> {}",
4091+
encode::serialize_hex(&counterparty_commitment_tx.0.trust().built_transaction().transaction),
40854092
&counterparty_commitment_txid,
40864093
encode::serialize_hex(&self.get_funding_redeemscript()),
40874094
log_bytes!(signature.serialize_compact()[..]));
@@ -4608,13 +4615,16 @@ impl<'a, Signer: Sign, K: Deref> ReadableArgs<&'a K> for Channel<Signer>
46084615
let counterparty_shutdown_scriptpubkey = Readable::read(reader)?;
46094616
let commitment_secrets = Readable::read(reader)?;
46104617

4618+
let mut secp_ctx = Secp256k1::new();
4619+
secp_ctx.seeded_randomize(&keys_source.get_secure_random_bytes());
4620+
46114621
Ok(Channel {
46124622
user_id,
46134623

46144624
config,
46154625
channel_id,
46164626
channel_state,
4617-
secp_ctx: Secp256k1::new(),
4627+
secp_ctx,
46184628
channel_value_satoshis,
46194629

46204630
latest_monitor_update_id,

lightning/src/ln/channelmanager.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -766,7 +766,8 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
766766
/// Users need to notify the new ChannelManager when a new block is connected or
767767
/// disconnected using its `block_connected` and `block_disconnected` methods.
768768
pub fn new(network: Network, fee_est: F, chain_monitor: M, tx_broadcaster: T, logger: L, keys_manager: K, config: UserConfig, current_blockchain_height: usize) -> Self {
769-
let secp_ctx = Secp256k1::new();
769+
let mut secp_ctx = Secp256k1::new();
770+
secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
770771

771772
ChannelManager {
772773
default_configuration: config.clone(),
@@ -4129,6 +4130,9 @@ impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
41294130

41304131
let last_node_announcement_serial: u32 = Readable::read(reader)?;
41314132

4133+
let mut secp_ctx = Secp256k1::new();
4134+
secp_ctx.seeded_randomize(&args.keys_manager.get_secure_random_bytes());
4135+
41324136
let channel_manager = ChannelManager {
41334137
genesis_hash,
41344138
fee_estimator: args.fee_estimator,
@@ -4137,7 +4141,7 @@ impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
41374141

41384142
latest_block_height: AtomicUsize::new(latest_block_height as usize),
41394143
last_block_hash: Mutex::new(last_block_hash),
4140-
secp_ctx: Secp256k1::new(),
4144+
secp_ctx,
41414145

41424146
channel_state: Mutex::new(ChannelHolder {
41434147
by_id,

lightning/src/ln/onchaintx.rs

+6-3
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,9 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
406406
}
407407
let latest_height = Readable::read(reader)?;
408408

409+
let mut secp_ctx = Secp256k1::new();
410+
secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
411+
409412
Ok(OnchainTxHandler {
410413
destination_script,
411414
holder_commitment,
@@ -418,13 +421,13 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
418421
pending_claim_requests,
419422
onchain_events_waiting_threshold_conf,
420423
latest_height,
421-
secp_ctx: Secp256k1::new(),
424+
secp_ctx,
422425
})
423426
}
424427
}
425428

426429
impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
427-
pub(crate) fn new(destination_script: Script, signer: ChannelSigner, channel_parameters: ChannelTransactionParameters, holder_commitment: HolderCommitmentTransaction) -> Self {
430+
pub(crate) fn new(destination_script: Script, signer: ChannelSigner, channel_parameters: ChannelTransactionParameters, holder_commitment: HolderCommitmentTransaction, secp_ctx: Secp256k1<secp256k1::All>) -> Self {
428431
OnchainTxHandler {
429432
destination_script,
430433
holder_commitment,
@@ -438,7 +441,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
438441
onchain_events_waiting_threshold_conf: HashMap::new(),
439442
latest_height: 0,
440443

441-
secp_ctx: Secp256k1::new(),
444+
secp_ctx,
442445
}
443446
}
444447

0 commit comments

Comments
 (0)