Skip to content

Commit 271fb6d

Browse files
committed
Use Sha256s for tweaks in sign to enforce randomness
We assume that tweaks are the output of a SHA-256 hash function (and thus that failing to create a private key from the has negligible probability) in `add_public_key_tweak` and elsewhere. Thus, we really shouldn't be taking byte arrays in the public API but rather `Sha256` objects, and communicating in the docs for `add_public_key_tweak` that we can panic if its not the output of a hash function, both of which we do here.
1 parent 95da809 commit 271fb6d

File tree

2 files changed

+8
-6
lines changed

2 files changed

+8
-6
lines changed

lightning/src/ln/channel_keys.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,11 @@ macro_rules! basepoint_impl {
4545
///
4646
/// This calculates the hash part in the tweak derivation process, which is used to
4747
/// ensure that each key is unique and cannot be guessed by an external party.
48-
pub fn derive_add_tweak(&self, per_commitment_point: &PublicKey) -> [u8; 32] {
48+
pub fn derive_add_tweak(&self, per_commitment_point: &PublicKey) -> Sha256 {
4949
let mut sha = Sha256::engine();
5050
sha.input(&per_commitment_point.serialize());
5151
sha.input(&self.to_public_key().serialize());
52-
Sha256::from_engine(sha).to_byte_array()
52+
Sha256::from_engine(sha)
5353
}
5454
}
5555

@@ -166,18 +166,20 @@ fn derive_public_key<T: secp256k1::Signing>(
166166
let mut sha = Sha256::engine();
167167
sha.input(&per_commitment_point.serialize());
168168
sha.input(&base_point.serialize());
169-
let res = Sha256::from_engine(sha).to_byte_array();
169+
let res = Sha256::from_engine(sha);
170170

171171
add_public_key_tweak(secp_ctx, base_point, &res)
172172
}
173173

174174
/// Adds a tweak to a public key to derive a new public key.
175+
///
176+
/// May panic if `tweak` is not the output of a SHA-256 hash.
175177
pub fn add_public_key_tweak<T: secp256k1::Signing>(
176-
secp_ctx: &Secp256k1<T>, base_point: &PublicKey, tweak: &[u8; 32],
178+
secp_ctx: &Secp256k1<T>, base_point: &PublicKey, tweak: &Sha256,
177179
) -> PublicKey {
178180
let hashkey = PublicKey::from_secret_key(
179181
&secp_ctx,
180-
&SecretKey::from_slice(tweak)
182+
&SecretKey::from_slice(tweak.as_byte_array())
181183
.expect("Hashes should always be valid keys unless SHA-256 is broken"),
182184
);
183185
base_point.combine(&hashkey)

lightning/src/sign/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,7 @@ impl SpendableOutputDescriptor {
401401
subtype: 0,
402402
key: "add_tweak".as_bytes().to_vec(),
403403
},
404-
add_tweak.to_vec(),
404+
add_tweak.as_byte_array().to_vec(),
405405
)]
406406
.into_iter()
407407
.collect()

0 commit comments

Comments
 (0)