1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Keys used to generate commitment transactions.
11 //! See: <https://github.com/lightning/bolts/blob/master/03-transactions.md#keys>
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::HashEngine;
15 use bitcoin::secp256k1::Scalar;
16 use bitcoin::secp256k1::SecretKey;
17 use bitcoin::secp256k1::Secp256k1;
18 use bitcoin::secp256k1;
19 use crate::ln::msgs::DecodeError;
20 use crate::util::ser::Readable;
22 use crate::util::ser::Writer;
23 use crate::util::ser::Writeable;
24 use bitcoin::secp256k1::PublicKey;
25 use bitcoin::hashes::sha256::Hash as Sha256;
27 macro_rules! doc_comment {
28 ($x:expr, $($tt:tt)*) => {
33 macro_rules! basepoint_impl {
36 /// Get inner Public Key
37 pub fn to_public_key(&self) -> PublicKey {
42 impl From<PublicKey> for $BasepointT {
43 fn from(value: PublicKey) -> Self {
50 macro_rules! key_impl {
51 ($BasepointT:ty, $KeyName:expr) => {
53 concat!("Derive a public ", $KeyName, " using one node's `per_commitment_point` and its countersignatory's `basepoint`"),
54 pub fn from_basepoint<T: secp256k1::Signing>(
55 secp_ctx: &Secp256k1<T>,
56 countersignatory_basepoint: &$BasepointT,
57 per_commitment_point: &PublicKey,
59 Self(derive_public_key(secp_ctx, per_commitment_point, &countersignatory_basepoint.0))
64 concat!("Build a ", $KeyName, " directly from an already-derived private key"),
65 pub fn from_secret_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, sk: &SecretKey) -> Self {
66 Self(PublicKey::from_secret_key(&secp_ctx, &sk))
70 /// Get inner Public Key
71 pub fn to_public_key(&self) -> PublicKey {
76 macro_rules! key_read_write {
78 impl Writeable for $SelfT {
79 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
80 self.0.serialize().write(w)
84 impl Readable for $SelfT {
85 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
86 let key: PublicKey = Readable::read(r)?;
95 /// Master key used in conjunction with per_commitment_point to generate [`local_delayedpubkey`](https://github.com/lightning/bolts/blob/master/03-transactions.md#key-derivation) for the latest state of a channel.
96 /// A watcher can be given a [DelayedPaymentBasepoint] to generate per commitment [DelayedPaymentKey] to create justice transactions.
97 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
98 pub struct DelayedPaymentBasepoint(pub PublicKey);
99 basepoint_impl!(DelayedPaymentBasepoint);
100 key_read_write!(DelayedPaymentBasepoint);
102 /// [delayedpubkey](https://github.com/lightning/bolts/blob/master/03-transactions.md#localpubkey-local_htlcpubkey-remote_htlcpubkey-local_delayedpubkey-and-remote_delayedpubkey-derivation)
103 /// To allow a counterparty to contest a channel state published by a node, Lightning protocol sets delays for some of the outputs, before can be spend.
104 /// For example a commitment transaction has to_local output encumbered by a delay, negotiated at the channel establishment flow.
105 /// To spend from such output a node has to generate a script using, among others, a local delayed payment key.
106 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
107 pub struct DelayedPaymentKey(pub PublicKey);
109 impl DelayedPaymentKey {
110 key_impl!(DelayedPaymentBasepoint, "delayedpubkey");
112 key_read_write!(DelayedPaymentKey);
114 /// Master key used in conjunction with per_commitment_point to generate [htlcpubkey](https://github.com/lightning/bolts/blob/master/03-transactions.md#key-derivation) for the latest state of a channel.
115 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
116 pub struct HtlcBasepoint(pub PublicKey);
117 basepoint_impl!(HtlcBasepoint);
118 key_read_write!(HtlcBasepoint);
121 /// [htlcpubkey](https://github.com/lightning/bolts/blob/master/03-transactions.md#localpubkey-local_htlcpubkey-remote_htlcpubkey-local_delayedpubkey-and-remote_delayedpubkey-derivation) is a child key of an htlc basepoint,
122 /// that enables secure routing of payments in onion scheme without a risk of them getting stuck or diverted. It is used to claim the funds in successful or timed out htlc outputs.
123 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
124 pub struct HtlcKey(pub PublicKey);
127 key_impl!(HtlcBasepoint, "htlcpubkey");
129 key_read_write!(HtlcKey);
131 /// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
132 /// from the base point and the per_commitment_key. This is the public equivalent of
133 /// derive_private_key - using only public keys to derive a public key instead of private keys.
134 fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> PublicKey {
135 let mut sha = Sha256::engine();
136 sha.input(&per_commitment_point.serialize());
137 sha.input(&base_point.serialize());
138 let res = Sha256::from_engine(sha).to_byte_array();
140 let hashkey = PublicKey::from_secret_key(&secp_ctx,
141 &SecretKey::from_slice(&res).expect("Hashes should always be valid keys unless SHA-256 is broken"));
142 base_point.combine(&hashkey)
143 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak contains the hash of the key.")
146 /// Master key used in conjunction with per_commitment_point to generate [htlcpubkey](https://github.com/lightning/bolts/blob/master/03-transactions.md#key-derivation) for the latest state of a channel.
147 /// A watcher can be given a [RevocationBasepoint] to generate per commitment [RevocationKey] to create justice transactions.
148 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
149 pub struct RevocationBasepoint(pub PublicKey);
150 basepoint_impl!(RevocationBasepoint);
151 key_read_write!(RevocationBasepoint);
154 /// The revocation key is used to allow a channel party to revoke their state - giving their
155 /// counterparty the required material to claim all of their funds if they broadcast that state.
157 /// Each commitment transaction has a revocation key based on the basepoint and
158 /// per_commitment_point which is used in both commitment and HTLC transactions.
160 /// See [the BOLT spec for derivation details]
161 /// (https://github.com/lightning/bolts/blob/master/03-transactions.md#revocationpubkey-derivation)
162 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
163 pub struct RevocationKey(pub PublicKey);
166 /// Derives a per-commitment-transaction revocation public key from one party's per-commitment
167 /// point and the other party's [`RevocationBasepoint`]. This is the public equivalent of
168 /// [`chan_utils::derive_private_revocation_key`] - using only public keys to derive a public
169 /// key instead of private keys.
171 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
172 /// generated (ie our own).
174 /// [`chan_utils::derive_private_revocation_key`]: crate::ln::chan_utils::derive_private_revocation_key
175 pub fn from_basepoint<T: secp256k1::Verification>(
176 secp_ctx: &Secp256k1<T>,
177 countersignatory_basepoint: &RevocationBasepoint,
178 per_commitment_point: &PublicKey,
180 let rev_append_commit_hash_key = {
181 let mut sha = Sha256::engine();
182 sha.input(&countersignatory_basepoint.to_public_key().serialize());
183 sha.input(&per_commitment_point.serialize());
185 Sha256::from_engine(sha).to_byte_array()
187 let commit_append_rev_hash_key = {
188 let mut sha = Sha256::engine();
189 sha.input(&per_commitment_point.serialize());
190 sha.input(&countersignatory_basepoint.to_public_key().serialize());
192 Sha256::from_engine(sha).to_byte_array()
195 let countersignatory_contrib = countersignatory_basepoint.to_public_key().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
196 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
197 let broadcaster_contrib = (&per_commitment_point).mul_tweak(&secp_ctx, &Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
198 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
199 let pk = countersignatory_contrib.combine(&broadcaster_contrib)
200 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.");
204 /// Get inner Public Key
205 pub fn to_public_key(&self) -> PublicKey {
209 key_read_write!(RevocationKey);
214 use bitcoin::secp256k1::{Secp256k1, SecretKey, PublicKey};
215 use bitcoin::hashes::hex::FromHex;
216 use super::derive_public_key;
219 fn test_key_derivation() {
220 // Test vectors from BOLT 3 Appendix E:
221 let secp_ctx = Secp256k1::new();
223 let base_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap()[..]).unwrap();
224 let per_commitment_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
226 let base_point = PublicKey::from_secret_key(&secp_ctx, &base_secret);
227 assert_eq!(base_point.serialize()[..], <Vec<u8>>::from_hex("036d6caac248af96f6afa7f904f550253a0f3ef3f5aa2fe6838a95b216691468e2").unwrap()[..]);
229 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
230 assert_eq!(per_commitment_point.serialize()[..], <Vec<u8>>::from_hex("025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486").unwrap()[..]);
232 assert_eq!(derive_public_key(&secp_ctx, &per_commitment_point, &base_point).serialize()[..],
233 <Vec<u8>>::from_hex("0235f2dbfaa89b57ec7b055afe29849ef7ddfeb1cefdb9ebdc43f5494984db29e5").unwrap()[..]);