X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Foffers%2Fmerkle.rs;h=a86f0b4e6fbff57c4b7ac59403bb357d894c3b45;hb=caafcedf3fc40fc6253261218c25b254dd955a82;hp=3b05899a8f59214872a1075179fc9428b48412fa;hpb=022eadc4dbf0f60179674f936d604cade6c5dd9e;p=rust-lightning diff --git a/lightning/src/offers/merkle.rs b/lightning/src/offers/merkle.rs index 3b05899a..a86f0b4e 100644 --- a/lightning/src/offers/merkle.rs +++ b/lightning/src/offers/merkle.rs @@ -12,6 +12,7 @@ use bitcoin::hashes::{Hash, HashEngine, sha256}; use bitcoin::secp256k1::{Message, PublicKey, Secp256k1, self}; use bitcoin::secp256k1::schnorr::Signature; +use core::convert::AsRef; use crate::io; use crate::util::ser::{BigSize, Readable, Writeable, Writer}; @@ -24,6 +25,55 @@ tlv_stream!(SignatureTlvStream, SignatureTlvStreamRef, SIGNATURE_TYPES, { (240, signature: Signature), }); +/// A hash for use in a specific context by tweaking with a context-dependent tag as per [BIP 340] +/// and computed over the merkle root of a TLV stream to sign as defined in [BOLT 12]. +/// +/// [BIP 340]: https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +/// [BOLT 12]: https://github.com/rustyrussell/lightning-rfc/blob/guilt/offers/12-offer-encoding.md#signature-calculation +#[derive(Clone, Debug, PartialEq)] +pub struct TaggedHash { + tag: String, + merkle_root: sha256::Hash, + digest: Message, +} + +impl TaggedHash { + /// Creates a tagged hash with the given parameters. + /// + /// Panics if `tlv_stream` is not a well-formed TLV stream containing at least one TLV record. + pub(super) fn new(tag: &str, tlv_stream: &[u8]) -> Self { + let tag_hash = sha256::Hash::hash(tag.as_bytes()); + let merkle_root = root_hash(tlv_stream); + let digest = Message::from_slice(&tagged_hash(tag_hash, merkle_root)).unwrap(); + Self { + tag: tag.to_owned(), + merkle_root, + digest, + } + } + + /// Returns the digest to sign. + pub fn as_digest(&self) -> &Message { + &self.digest + } + + /// Returns the tag used in the tagged hash. + pub fn tag(&self) -> &str { + &self.tag + } + + /// Returns the merkle root used in the tagged hash. + pub fn merkle_root(&self) -> sha256::Hash { + self.merkle_root + } +} + +impl AsRef for TaggedHash { + fn as_ref(&self) -> &TaggedHash { + self + } +} + /// Error when signing messages. #[derive(Debug, PartialEq)] pub enum SignError { @@ -33,43 +83,41 @@ pub enum SignError { Verification(secp256k1::Error), } -/// Signs a message digest consisting of a tagged hash of the given bytes, checking if it can be -/// verified with the supplied pubkey. +/// Signs a [`TaggedHash`] computed over the merkle root of `message`'s TLV stream, checking if it +/// can be verified with the supplied `pubkey`. +/// +/// Since `message` is any type that implements [`AsRef`], `sign` may be a closure that +/// takes a message such as [`Bolt12Invoice`] or [`InvoiceRequest`]. This allows further message +/// verification before signing its [`TaggedHash`]. /// -/// Panics if `bytes` is not a well-formed TLV stream containing at least one TLV record. -pub(super) fn sign_message( - sign: F, tag: &str, bytes: &[u8], pubkey: PublicKey, +/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice +/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest +pub(super) fn sign_message( + sign: F, message: &T, pubkey: PublicKey, ) -> Result> where - F: FnOnce(&Message) -> Result + F: FnOnce(&T) -> Result, + T: AsRef, { - let digest = message_digest(tag, bytes); - let signature = sign(&digest).map_err(|e| SignError::Signing(e))?; + let signature = sign(message).map_err(|e| SignError::Signing(e))?; + let digest = message.as_ref().as_digest(); let pubkey = pubkey.into(); let secp_ctx = Secp256k1::verification_only(); - secp_ctx.verify_schnorr(&signature, &digest, &pubkey).map_err(|e| SignError::Verification(e))?; + secp_ctx.verify_schnorr(&signature, digest, &pubkey).map_err(|e| SignError::Verification(e))?; Ok(signature) } -/// Verifies the signature with a pubkey over the given bytes using a tagged hash as the message +/// Verifies the signature with a pubkey over the given message using a tagged hash as the message /// digest. -/// -/// Panics if `bytes` is not a well-formed TLV stream containing at least one TLV record. pub(super) fn verify_signature( - signature: &Signature, tag: &str, bytes: &[u8], pubkey: PublicKey, + signature: &Signature, message: &TaggedHash, pubkey: PublicKey, ) -> Result<(), secp256k1::Error> { - let digest = message_digest(tag, bytes); + let digest = message.as_digest(); let pubkey = pubkey.into(); let secp_ctx = Secp256k1::verification_only(); - secp_ctx.verify_schnorr(signature, &digest, &pubkey) -} - -pub(super) fn message_digest(tag: &str, bytes: &[u8]) -> Message { - let tag = sha256::Hash::hash(tag.as_bytes()); - let merkle_root = root_hash(bytes); - Message::from_slice(&tagged_hash(tag, merkle_root)).unwrap() + secp_ctx.verify_schnorr(signature, digest, &pubkey) } /// Computes a merkle root hash for the given data, which must be a well-formed TLV stream @@ -207,12 +255,12 @@ impl<'a> Iterator for TlvStream<'a> { /// Encoding for a pre-serialized TLV stream that excludes any signature TLV records. /// /// Panics if the wrapped bytes are not a well-formed TLV stream. -pub(super) struct WithoutSignatures<'a>(pub &'a Vec); +pub(super) struct WithoutSignatures<'a>(pub &'a [u8]); impl<'a> Writeable for WithoutSignatures<'a> { #[inline] fn write(&self, writer: &mut W) -> Result<(), io::Error> { - let tlv_stream = TlvStream::new(&self.0[..]); + let tlv_stream = TlvStream::new(self.0); for record in tlv_stream.skip_signatures() { writer.write_all(record.record_bytes)?; } @@ -225,11 +273,13 @@ mod tests { use super::{SIGNATURE_TYPES, TlvStream, WithoutSignatures}; use bitcoin::hashes::{Hash, sha256}; - use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey}; + use bitcoin::secp256k1::{KeyPair, Message, Secp256k1, SecretKey}; + use bitcoin::secp256k1::schnorr::Signature; use core::convert::Infallible; use crate::offers::offer::{Amount, OfferBuilder}; use crate::offers::invoice_request::InvoiceRequest; use crate::offers::parse::Bech32Encode; + use crate::offers::test_utils::{payer_pubkey, recipient_pubkey}; use crate::util::ser::Writeable; #[test] @@ -270,7 +320,9 @@ mod tests { .build_unchecked() .request_invoice(vec![0; 8], payer_keys.public_key()).unwrap() .build_unchecked() - .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &payer_keys))) + .sign::<_, Infallible>( + |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &payer_keys)) + ) .unwrap(); assert_eq!( invoice_request.to_string(), @@ -280,8 +332,31 @@ mod tests { super::root_hash(&invoice_request.bytes[..]), sha256::Hash::from_slice(&hex::decode("608407c18ad9a94d9ea2bcdbe170b6c20c462a7833a197621c916f78cf18e624").unwrap()).unwrap(), ); + assert_eq!( + invoice_request.signature(), + Signature::from_slice(&hex::decode("b8f83ea3288cfd6ea510cdb481472575141e8d8744157f98562d162cc1c472526fdb24befefbdebab4dbb726bbd1b7d8aec057f8fa805187e5950d2bbe0e5642").unwrap()).unwrap(), + ); } + #[test] + fn compute_tagged_hash() { + let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey()) + .amount_msats(1000) + .build().unwrap() + .request_invoice(vec![1; 32], payer_pubkey()).unwrap() + .payer_note("bar".into()) + .build().unwrap(); + + // Simply test that we can grab the tag and merkle root exposed by the accessor + // functions, then use them to succesfully compute a tagged hash. + let tagged_hash = unsigned_invoice_request.as_ref(); + let expected_digest = unsigned_invoice_request.as_ref().as_digest(); + let tag = sha256::Hash::hash(tagged_hash.tag().as_bytes()); + let actual_digest = Message::from_slice(&super::tagged_hash(tag, tagged_hash.merkle_root())) + .unwrap(); + assert_eq!(*expected_digest, actual_digest); + } + #[test] fn skips_encoding_signature_tlv_records() { let secp_ctx = Secp256k1::new(); @@ -299,7 +374,9 @@ mod tests { .build_unchecked() .request_invoice(vec![0; 8], payer_keys.public_key()).unwrap() .build_unchecked() - .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &payer_keys))) + .sign::<_, Infallible>( + |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &payer_keys)) + ) .unwrap(); let mut bytes_without_signature = Vec::new(); @@ -329,7 +406,9 @@ mod tests { .build_unchecked() .request_invoice(vec![0; 8], payer_keys.public_key()).unwrap() .build_unchecked() - .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &payer_keys))) + .sign::<_, Infallible>( + |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &payer_keys)) + ) .unwrap(); let tlv_stream = TlvStream::new(&invoice_request.bytes).range(0..1)