@@ -31,19 +31,38 @@ tlv_stream!(SignatureTlvStream, SignatureTlvStreamRef, SIGNATURE_TYPES, {
3131/// [BIP 340]: https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
3232/// [BOLT 12]: https://github.com/rustyrussell/lightning-rfc/blob/guilt/offers/12-offer-encoding.md#signature-calculation
3333#[ derive( Debug , PartialEq ) ]
34- pub struct TaggedHash ( Message ) ;
34+ pub struct TaggedHash {
35+ tag : String ,
36+ merkle_root : sha256:: Hash ,
37+ digest : Message ,
38+ }
3539
3640impl TaggedHash {
3741 /// Creates a tagged hash with the given parameters.
3842 ///
3943 /// Panics if `tlv_stream` is not a well-formed TLV stream containing at least one TLV record.
4044 pub ( super ) fn new ( tag : & str , tlv_stream : & [ u8 ] ) -> Self {
41- Self ( message_digest ( tag, tlv_stream) )
45+ let merkle_root = root_hash ( tlv_stream) ;
46+ Self {
47+ tag : tag. to_owned ( ) ,
48+ merkle_root,
49+ digest : message_digest ( tag, merkle_root) ,
50+ }
4251 }
4352
4453 /// Returns the digest to sign.
4554 pub fn as_digest ( & self ) -> & Message {
46- & self . 0
55+ & self . digest
56+ }
57+
58+ /// Returns the tag used in the tagged hash.
59+ pub fn tag ( & self ) -> & str {
60+ & self . tag
61+ }
62+
63+ /// Returns the merkle root used in the tagged hash.
64+ pub fn merkle_root ( & self ) -> sha256:: Hash {
65+ self . merkle_root
4766 }
4867}
4968
@@ -99,15 +118,14 @@ pub(super) fn verify_signature(
99118 secp_ctx. verify_schnorr ( signature, digest, & pubkey)
100119}
101120
102- pub ( super ) fn message_digest ( tag : & str , bytes : & [ u8 ] ) -> Message {
121+ pub ( super ) fn message_digest ( tag : & str , merkle_root : sha256 :: Hash ) -> Message {
103122 let tag = sha256:: Hash :: hash ( tag. as_bytes ( ) ) ;
104- let merkle_root = root_hash ( bytes) ;
105123 Message :: from_slice ( & tagged_hash ( tag, merkle_root) ) . unwrap ( )
106124}
107125
108126/// Computes a merkle root hash for the given data, which must be a well-formed TLV stream
109127/// containing at least one TLV record.
110- fn root_hash ( data : & [ u8 ] ) -> sha256:: Hash {
128+ pub ( crate ) fn root_hash ( data : & [ u8 ] ) -> sha256:: Hash {
111129 let nonce_tag = tagged_hash_engine ( sha256:: Hash :: from_engine ( {
112130 let first_tlv_record = TlvStream :: new ( & data[ ..] ) . next ( ) . unwrap ( ) ;
113131 let mut engine = sha256:: Hash :: engine ( ) ;
@@ -144,7 +162,7 @@ fn root_hash(data: &[u8]) -> sha256::Hash {
144162 * leaves. first ( ) . unwrap ( )
145163}
146164
147- fn tagged_hash < T : AsRef < [ u8 ] > > ( tag : sha256:: Hash , msg : T ) -> sha256:: Hash {
165+ pub ( crate ) fn tagged_hash < T : AsRef < [ u8 ] > > ( tag : sha256:: Hash , msg : T ) -> sha256:: Hash {
148166 let engine = tagged_hash_engine ( tag) ;
149167 tagged_hash_from_engine ( engine, msg)
150168}
0 commit comments