From 6b3535451e6243611d3435f9eb195706b9ca1ba7 Mon Sep 17 00:00:00 2001 From: Jeffrey Czyz Date: Thu, 22 Dec 2022 09:10:21 -0600 Subject: [PATCH] Define TlvStream::skip_signatures Provide a helper for skipping signature TLV records from a TLV stream. This prevents needing to duplicate the check for signature TLV records when writing a TLV stream without signatures in an upcoming commit. --- lightning/src/offers/merkle.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/lightning/src/offers/merkle.rs b/lightning/src/offers/merkle.rs index 9031e0eb5..1a505aae8 100644 --- a/lightning/src/offers/merkle.rs +++ b/lightning/src/offers/merkle.rs @@ -75,22 +75,21 @@ fn message_digest(tag: &str, bytes: &[u8]) -> Message { /// Computes a merkle root hash for the given data, which must be a well-formed TLV stream /// containing at least one TLV record. fn root_hash(data: &[u8]) -> sha256::Hash { - let mut tlv_stream = TlvStream::new(&data[..]).peekable(); let nonce_tag = tagged_hash_engine(sha256::Hash::from_engine({ + let first_tlv_record = TlvStream::new(&data[..]).next().unwrap(); let mut engine = sha256::Hash::engine(); engine.input("LnNonce".as_bytes()); - engine.input(tlv_stream.peek().unwrap().record_bytes); + engine.input(first_tlv_record.record_bytes); engine })); let leaf_tag = tagged_hash_engine(sha256::Hash::hash("LnLeaf".as_bytes())); let branch_tag = tagged_hash_engine(sha256::Hash::hash("LnBranch".as_bytes())); let mut leaves = Vec::new(); - for record in tlv_stream { - if !SIGNATURE_TYPES.contains(&record.r#type) { - leaves.push(tagged_hash_from_engine(leaf_tag.clone(), &record.record_bytes)); - leaves.push(tagged_hash_from_engine(nonce_tag.clone(), &record.type_bytes)); - } + let tlv_stream = TlvStream::new(&data[..]); + for record in tlv_stream.skip_signatures() { + leaves.push(tagged_hash_from_engine(leaf_tag.clone(), &record.record_bytes)); + leaves.push(tagged_hash_from_engine(nonce_tag.clone(), &record.type_bytes)); } // Calculate the merkle root hash in place. @@ -154,6 +153,10 @@ impl<'a> TlvStream<'a> { data: io::Cursor::new(data), } } + + fn skip_signatures(self) -> core::iter::Filter, fn(&TlvRecord) -> bool> { + self.filter(|record| !SIGNATURE_TYPES.contains(&record.r#type)) + } } /// A slice into a [`TlvStream`] for a record. -- 2.39.5