]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/util/message_signing.rs
Merge pull request #2845 from wpaulino/decode-htlc-onion-when-committed
[rust-lightning] / lightning / src / util / message_signing.rs
1 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
2 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
4 // You may not use this file except in accordance with one or both of these
5 // licenses.
6
7 //! Lightning message signing and verification lives here. These tools can be used to sign messages using the node's
8 //! secret so receivers are sure that they come from you. You can also use this to verify that a given message comes
9 //! from a specific node.
10 //! Furthermore, these tools can be used to sign / verify messages using ephemeral keys not tied to node's identities.
11 //!
12 //! Note this is not part of the specs, but follows lnd's signing and verifying protocol, which can is defined as follows:
13 //!
14 //! signature = zbase32(SigRec(sha256d(("Lightning Signed Message:" + msg)))
15 //! zbase32 from <https://philzimmermann.com/docs/human-oriented-base-32-encoding.txt>
16 //! SigRec has first byte 31 + recovery id, followed by 64 byte sig.
17 //!
18 //! This implementation is compatible with both lnd's and c-lightning's
19 //!
20 //! <https://lightning.readthedocs.io/lightning-signmessage.7.html>
21 //! <https://api.lightning.community/#signmessage>
22
23 use crate::prelude::*;
24 use crate::util::base32;
25 use bitcoin::hashes::{sha256d, Hash};
26 use bitcoin::secp256k1::ecdsa::{RecoverableSignature, RecoveryId};
27 use bitcoin::secp256k1::{Error, Message, PublicKey, Secp256k1, SecretKey};
28
29 static LN_MESSAGE_PREFIX: &[u8] = b"Lightning Signed Message:";
30
31 fn sigrec_encode(sig_rec: RecoverableSignature) -> Vec<u8> {
32         let (rid, rsig) = sig_rec.serialize_compact();
33         let prefix = rid.to_i32() as u8 + 31;
34
35         [&[prefix], &rsig[..]].concat()
36 }
37
38 fn sigrec_decode(sig_rec: Vec<u8>) -> Result<RecoverableSignature, Error> {
39         // Signature must be 64 + 1 bytes long (compact signature + recovery id)
40         if sig_rec.len() != 65 {
41                 return Err(Error::InvalidSignature);
42         }
43
44         let rsig = &sig_rec[1..];
45         let rid = sig_rec[0] as i32 - 31;
46
47         match RecoveryId::from_i32(rid) {
48                 Ok(x) => RecoverableSignature::from_compact(rsig, x),
49                 Err(e) => Err(e)
50         }
51 }
52
53 /// Creates a digital signature of a message given a SecretKey, like the node's secret.
54 /// A receiver knowing the PublicKey (e.g. the node's id) and the message can be sure that the signature was generated by the caller.
55 /// Signatures are EC recoverable, meaning that given the message and the signature the PublicKey of the signer can be extracted.
56 pub fn sign(msg: &[u8], sk: &SecretKey) -> Result<String, Error> {
57         let secp_ctx = Secp256k1::signing_only();
58         let msg_hash = sha256d::Hash::hash(&[LN_MESSAGE_PREFIX, msg].concat());
59
60         let sig = secp_ctx.sign_ecdsa_recoverable(&Message::from_slice(msg_hash.as_byte_array())?, sk);
61         Ok(base32::Alphabet::ZBase32.encode(&sigrec_encode(sig)))
62 }
63
64 /// Recovers the PublicKey of the signer of the message given the message and the signature.
65 pub fn recover_pk(msg: &[u8], sig: &str) ->  Result<PublicKey, Error> {
66         let secp_ctx = Secp256k1::verification_only();
67         let msg_hash = sha256d::Hash::hash(&[LN_MESSAGE_PREFIX, msg].concat());
68
69         match base32::Alphabet::ZBase32.decode(&sig) {
70                 Ok(sig_rec) => {
71                         match sigrec_decode(sig_rec) {
72                                 Ok(sig) => secp_ctx.recover_ecdsa(&Message::from_slice(msg_hash.as_byte_array())?, &sig),
73                                 Err(e) => Err(e)
74                         }
75                 },
76                 Err(_) => Err(Error::InvalidSignature)
77         }
78 }
79
80 /// Verifies a message was signed by a PrivateKey that derives to a given PublicKey, given a message, a signature,
81 /// and the PublicKey.
82 pub fn verify(msg: &[u8], sig: &str, pk: &PublicKey) -> bool {
83         match recover_pk(msg, sig) {
84                 Ok(x) => x == *pk,
85                 Err(_) => false
86         }
87 }
88
89 #[cfg(test)]
90 mod test {
91         use core::str::FromStr;
92         use crate::util::message_signing::{sign, recover_pk, verify};
93         use bitcoin::secp256k1::constants::ONE;
94         use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
95
96         #[test]
97         fn test_sign() {
98                 let message = "test message";
99                 let one_key = SecretKey::from_slice(&ONE).unwrap();
100                 let zbase32_sig = sign(message.as_bytes(), &one_key);
101
102                 assert_eq!(zbase32_sig.unwrap(), "d9tibmnic9t5y41hg7hkakdcra94akas9ku3rmmj4ag9mritc8ok4p5qzefs78c9pqfhpuftqqzhydbdwfg7u6w6wdxcqpqn4sj4e73e")
103         }
104
105         #[test]
106         fn test_recover_pk() {
107                 let message = "test message";
108                 let one_key = SecretKey::from_slice(&ONE).unwrap();
109                 let sig = "d9tibmnic9t5y41hg7hkakdcra94akas9ku3rmmj4ag9mritc8ok4p5qzefs78c9pqfhpuftqqzhydbdwfg7u6w6wdxcqpqn4sj4e73e";
110                 let pk = recover_pk(message.as_bytes(), sig);
111
112                 assert_eq!(pk.unwrap(), PublicKey::from_secret_key(&Secp256k1::signing_only(), &one_key))
113         }
114
115         #[test]
116         fn test_verify() {
117                 let message = "another message";
118                 let one_key = SecretKey::from_slice(&ONE).unwrap();
119                 let sig = sign(message.as_bytes(), &one_key).unwrap();
120                 let pk = PublicKey::from_secret_key(&Secp256k1::signing_only(), &one_key);
121
122                 assert!(verify(message.as_bytes(), &sig, &pk))
123         }
124
125         #[test]
126         fn test_verify_ground_truth_ish() {
127                 // There are no standard tests vectors for Sign/Verify, using the same tests vectors as c-lightning to see if they are compatible.
128                 // Taken from https://github.com/ElementsProject/lightning/blob/1275af6fbb02460c8eb2f00990bb0ef9179ce8f3/tests/test_misc.py#L1925-L1938
129
130                 let corpus = [
131                         ["@bitconner",
132                         "is this compatible?",
133                         "rbgfioj114mh48d8egqx8o9qxqw4fmhe8jbeeabdioxnjk8z3t1ma1hu1fiswpakgucwwzwo6ofycffbsqusqdimugbh41n1g698hr9t",
134                         "02b80cabdf82638aac86948e4c06e82064f547768dcef977677b9ea931ea75bab5"],
135                         ["@duck1123",
136                         "hi",
137                         "rnrphcjswusbacjnmmmrynh9pqip7sy5cx695h6mfu64iac6qmcmsd8xnsyczwmpqp9shqkth3h4jmkgyqu5z47jfn1q7gpxtaqpx4xg",
138                         "02de60d194e1ca5947b59fe8e2efd6aadeabfb67f2e89e13ae1a799c1e08e4a43b"],
139                         ["@jochemin",
140                         "hi",
141                         "ry8bbsopmduhxy3dr5d9ekfeabdpimfx95kagdem7914wtca79jwamtbw4rxh69hg7n6x9ty8cqk33knbxaqftgxsfsaeprxkn1k48p3",
142                         "022b8ece90ee891cbcdac0c1cc6af46b73c47212d8defbce80265ac81a6b794931"],
143                 ];
144
145                 for c in &corpus {
146                         assert!(verify(c[1].as_bytes(), c[2], &PublicKey::from_str(c[3]).unwrap()))
147                 }
148         }
149 }
150