1use core::fmt;
42
43use hashes::Hash;
44use io::{Read, Write};
45
46use self::MerkleBlockError::*;
47use crate::blockdata::block::{self, Block, TxMerkleNode};
48use crate::blockdata::transaction::{Transaction, Txid};
49use crate::blockdata::weight::Weight;
50use crate::consensus::encode::{self, Decodable, Encodable, MAX_VEC_SIZE};
51use crate::prelude::*;
52
53#[derive(PartialEq, Eq, Clone, Debug)]
58pub struct MerkleBlock {
59 pub header: block::Header,
61 pub txn: PartialMerkleTree,
63}
64
65impl MerkleBlock {
66 pub fn from_block_with_predicate<F>(block: &Block, match_txids: F) -> Self
103 where
104 F: Fn(&Txid) -> bool,
105 {
106 let block_txids: Vec<_> = block.txdata.iter().map(Transaction::compute_txid).collect();
107 Self::from_header_txids_with_predicate(&block.header, &block_txids, match_txids)
108 }
109
110 pub fn from_header_txids_with_predicate<F>(
115 header: &block::Header,
116 block_txids: &[Txid],
117 match_txids: F,
118 ) -> Self
119 where
120 F: Fn(&Txid) -> bool,
121 {
122 let matches: Vec<bool> = block_txids.iter().map(match_txids).collect();
123
124 let pmt = PartialMerkleTree::from_txids(block_txids, &matches);
125 MerkleBlock { header: *header, txn: pmt }
126 }
127
128 pub fn extract_matches(
132 &self,
133 matches: &mut Vec<Txid>,
134 indexes: &mut Vec<u32>,
135 ) -> Result<(), MerkleBlockError> {
136 let merkle_root = self.txn.extract_matches(matches, indexes)?;
137
138 if merkle_root.eq(&self.header.merkle_root) {
139 Ok(())
140 } else {
141 Err(MerkleRootMismatch)
142 }
143 }
144}
145
146impl Encodable for MerkleBlock {
147 fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
148 let len = self.header.consensus_encode(w)? + self.txn.consensus_encode(w)?;
149 Ok(len)
150 }
151}
152
153impl Decodable for MerkleBlock {
154 fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
155 Ok(MerkleBlock {
156 header: Decodable::consensus_decode(r)?,
157 txn: Decodable::consensus_decode(r)?,
158 })
159 }
160}
161
162#[derive(PartialEq, Eq, Clone, Debug)]
197pub struct PartialMerkleTree {
198 num_transactions: u32,
200 bits: Vec<bool>,
202 hashes: Vec<TxMerkleNode>,
204}
205
206impl PartialMerkleTree {
207 pub fn num_transactions(&self) -> u32 { self.num_transactions }
209
210 pub fn bits(&self) -> &Vec<bool> { &self.bits }
212
213 pub fn hashes(&self) -> &Vec<TxMerkleNode> { &self.hashes }
215
216 pub fn from_txids(txids: &[Txid], matches: &[bool]) -> Self {
244 assert_ne!(txids.len(), 0);
246 assert_eq!(txids.len(), matches.len());
247
248 let mut pmt = PartialMerkleTree {
249 num_transactions: txids.len() as u32,
250 bits: Vec::with_capacity(txids.len()),
251 hashes: vec![],
252 };
253 let height = pmt.calc_tree_height();
254
255 pmt.traverse_and_build(height, 0, txids, matches);
257 pmt
258 }
259
260 pub fn extract_matches(
264 &self,
265 matches: &mut Vec<Txid>,
266 indexes: &mut Vec<u32>,
267 ) -> Result<TxMerkleNode, MerkleBlockError> {
268 matches.clear();
269 indexes.clear();
270 if self.num_transactions == 0 {
272 return Err(NoTransactions);
273 };
274 if self.num_transactions as u64 > Weight::MAX_BLOCK / Weight::MIN_TRANSACTION {
276 return Err(TooManyTransactions);
277 }
278 if self.hashes.len() as u32 > self.num_transactions {
280 return Err(TooManyHashes);
281 };
282 if self.bits.len() < self.hashes.len() {
284 return Err(NotEnoughBits);
285 };
286
287 let height = self.calc_tree_height();
288
289 let mut bits_used = 0u32;
291 let mut hash_used = 0u32;
292 let hash_merkle_root =
293 self.traverse_and_extract(height, 0, &mut bits_used, &mut hash_used, matches, indexes)?;
294 if (bits_used + 7) / 8 != (self.bits.len() as u32 + 7) / 8 {
297 return Err(NotAllBitsConsumed);
298 }
299 if hash_used != self.hashes.len() as u32 {
301 return Err(NotAllHashesConsumed);
302 }
303 Ok(TxMerkleNode::from_byte_array(hash_merkle_root.to_byte_array()))
304 }
305
306 fn calc_tree_height(&self) -> u32 {
308 let mut height = 0;
309 while self.calc_tree_width(height) > 1 {
310 height += 1;
311 }
312 height
313 }
314
315 #[inline]
318 fn calc_tree_width(&self, height: u32) -> u32 {
319 (self.num_transactions + (1 << height) - 1) >> height
320 }
321
322 fn calc_hash(&self, height: u32, pos: u32, txids: &[Txid]) -> TxMerkleNode {
324 if height == 0 {
325 TxMerkleNode::from_byte_array(txids[pos as usize].to_byte_array())
327 } else {
328 let left = self.calc_hash(height - 1, pos * 2, txids);
330 let right = if pos * 2 + 1 < self.calc_tree_width(height - 1) {
332 self.calc_hash(height - 1, pos * 2 + 1, txids)
333 } else {
334 left
335 };
336 PartialMerkleTree::parent_hash(left, right)
338 }
339 }
340
341 fn traverse_and_build(&mut self, height: u32, pos: u32, txids: &[Txid], matches: &[bool]) {
343 let mut parent_of_match = false;
345 let mut p = pos << height;
346 while p < (pos + 1) << height && p < self.num_transactions {
347 parent_of_match |= matches[p as usize];
348 p += 1;
349 }
350 self.bits.push(parent_of_match);
352
353 if height == 0 || !parent_of_match {
354 let hash = self.calc_hash(height, pos, txids);
356 self.hashes.push(hash);
357 } else {
358 self.traverse_and_build(height - 1, pos * 2, txids, matches);
360 if pos * 2 + 1 < self.calc_tree_width(height - 1) {
361 self.traverse_and_build(height - 1, pos * 2 + 1, txids, matches);
362 }
363 }
364 }
365
366 fn traverse_and_extract(
369 &self,
370 height: u32,
371 pos: u32,
372 bits_used: &mut u32,
373 hash_used: &mut u32,
374 matches: &mut Vec<Txid>,
375 indexes: &mut Vec<u32>,
376 ) -> Result<TxMerkleNode, MerkleBlockError> {
377 if *bits_used as usize >= self.bits.len() {
378 return Err(BitsArrayOverflow);
379 }
380 let parent_of_match = self.bits[*bits_used as usize];
381 *bits_used += 1;
382 if height == 0 || !parent_of_match {
383 if *hash_used as usize >= self.hashes.len() {
385 return Err(HashesArrayOverflow);
386 }
387 let hash = self.hashes[*hash_used as usize];
388 *hash_used += 1;
389 if height == 0 && parent_of_match {
390 matches.push(Txid::from_byte_array(hash.to_byte_array()));
392 indexes.push(pos);
393 }
394 Ok(hash)
395 } else {
396 let left = self.traverse_and_extract(
398 height - 1,
399 pos * 2,
400 bits_used,
401 hash_used,
402 matches,
403 indexes,
404 )?;
405 let right;
406 if pos * 2 + 1 < self.calc_tree_width(height - 1) {
407 right = self.traverse_and_extract(
408 height - 1,
409 pos * 2 + 1,
410 bits_used,
411 hash_used,
412 matches,
413 indexes,
414 )?;
415 if right == left {
416 return Err(IdenticalHashesFound);
419 }
420 } else {
421 right = left;
422 }
423 Ok(PartialMerkleTree::parent_hash(left, right))
425 }
426 }
427
428 fn parent_hash(left: TxMerkleNode, right: TxMerkleNode) -> TxMerkleNode {
430 let mut encoder = TxMerkleNode::engine();
431 left.consensus_encode(&mut encoder).expect("engines don't error");
432 right.consensus_encode(&mut encoder).expect("engines don't error");
433 TxMerkleNode::from_engine(encoder)
434 }
435}
436
437impl Encodable for PartialMerkleTree {
438 fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
439 let mut ret = self.num_transactions.consensus_encode(w)?;
440 ret += self.hashes.consensus_encode(w)?;
441
442 let nb_bytes_for_bits = (self.bits.len() + 7) / 8;
443 ret += encode::VarInt::from(nb_bytes_for_bits).consensus_encode(w)?;
444 for chunk in self.bits.chunks(8) {
445 let mut byte = 0u8;
446 for (i, bit) in chunk.iter().enumerate() {
447 byte |= (*bit as u8) << i;
448 }
449 ret += byte.consensus_encode(w)?;
450 }
451 Ok(ret)
452 }
453}
454
455impl Decodable for PartialMerkleTree {
456 fn consensus_decode_from_finite_reader<R: Read + ?Sized>(
457 r: &mut R,
458 ) -> Result<Self, encode::Error> {
459 let num_transactions: u32 = Decodable::consensus_decode(r)?;
460 let hashes: Vec<TxMerkleNode> = Decodable::consensus_decode(r)?;
461
462 let nb_bytes_for_bits = encode::VarInt::consensus_decode(r)?.0 as usize;
463 if nb_bytes_for_bits > MAX_VEC_SIZE {
464 return Err(encode::Error::OversizedVectorAllocation {
465 requested: nb_bytes_for_bits,
466 max: MAX_VEC_SIZE,
467 });
468 }
469 let mut bits = vec![false; nb_bytes_for_bits * 8];
470 for chunk in bits.chunks_mut(8) {
471 let byte = u8::consensus_decode(r)?;
472 for (i, bit) in chunk.iter_mut().enumerate() {
473 *bit = (byte & (1 << i)) != 0;
474 }
475 }
476
477 Ok(PartialMerkleTree { num_transactions, hashes, bits })
478 }
479}
480
481#[derive(Debug, Clone, PartialEq, Eq)]
483#[non_exhaustive]
484pub enum MerkleBlockError {
485 MerkleRootMismatch,
487 NoTransactions,
489 TooManyTransactions,
491 TooManyHashes,
493 NotEnoughBits,
496 NotAllBitsConsumed,
498 NotAllHashesConsumed,
500 BitsArrayOverflow,
502 HashesArrayOverflow,
504 IdenticalHashesFound,
506}
507
508internals::impl_from_infallible!(MerkleBlockError);
509
510impl fmt::Display for MerkleBlockError {
511 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
512 use MerkleBlockError::*;
513
514 match *self {
515 MerkleRootMismatch => write!(f, "merkle header root doesn't match to the root calculated from the partial merkle tree"),
516 NoTransactions => write!(f, "partial merkle tree contains no transactions"),
517 TooManyTransactions => write!(f, "too many transactions"),
518 TooManyHashes => write!(f, "proof contains more hashes than transactions"),
519 NotEnoughBits => write!(f, "proof contains less bits than hashes"),
520 NotAllBitsConsumed => write!(f, "not all bit were consumed"),
521 NotAllHashesConsumed => write!(f, "not all hashes were consumed"),
522 BitsArrayOverflow => write!(f, "overflowed the bits array"),
523 HashesArrayOverflow => write!(f, "overflowed the hashes array"),
524 IdenticalHashesFound => write!(f, "found identical transaction hashes"),
525 }
526 }
527}
528
529#[cfg(feature = "std")]
530impl std::error::Error for MerkleBlockError {
531 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
532 use MerkleBlockError::*;
533
534 match *self {
535 MerkleRootMismatch | NoTransactions | TooManyTransactions | TooManyHashes
536 | NotEnoughBits | NotAllBitsConsumed | NotAllHashesConsumed | BitsArrayOverflow
537 | HashesArrayOverflow | IdenticalHashesFound => None,
538 }
539 }
540}
541
542#[cfg(test)]
543mod tests {
544 use hex::test_hex_unwrap as hex;
545 #[cfg(feature = "rand-std")]
546 use secp256k1::rand::prelude::*;
547
548 use super::*;
549 use crate::consensus::encode::{deserialize, serialize};
550
551 #[cfg(feature = "rand-std")]
552 macro_rules! pmt_tests {
553 ($($name:ident),* $(,)?) => {
554 $(
555 #[test]
556 fn $name() {
557 pmt_test_from_name(stringify!($name));
558 }
559 )*
560 }
561 }
562
563 #[cfg(feature = "rand-std")]
564 pmt_tests!(
565 pmt_test_1,
566 pmt_test_4,
567 pmt_test_7,
568 pmt_test_17,
569 pmt_test_56,
570 pmt_test_100,
571 pmt_test_127,
572 pmt_test_256,
573 pmt_test_312,
574 pmt_test_513,
575 pmt_test_1000,
576 pmt_test_4095
577 );
578
579 #[cfg(feature = "rand-std")]
581 fn pmt_test_from_name(name: &str) { pmt_test(name[9..].parse().unwrap()) }
582
583 #[cfg(feature = "rand-std")]
584 fn pmt_test(tx_count: usize) {
585 use core::cmp::min;
586
587 use crate::merkle_tree;
588
589 let mut rng = thread_rng();
590 let tx_ids = (1..=tx_count)
592 .map(|i| format!("{:064x}", i).parse::<Txid>().unwrap())
593 .collect::<Vec<_>>();
594
595 let hashes = tx_ids.iter().map(|t| t.to_raw_hash());
597 let merkle_root_1: TxMerkleNode =
598 merkle_tree::calculate_root(hashes).expect("hashes is not empty").into();
599 let mut height = 1;
600 let mut ntx = tx_count;
601 while ntx > 1 {
602 ntx = (ntx + 1) / 2;
603 height += 1;
604 }
605
606 for att in 1..15 {
608 let mut matches = vec![false; tx_count];
609 let mut match_txid1 = vec![];
610 for j in 0..tx_count {
611 let rand_bits = match att / 2 {
613 0 => 0,
614 bits => rng.gen::<u64>() >> (64 - bits),
615 };
616 let include = rand_bits == 0;
617 matches[j] = include;
618
619 if include {
620 match_txid1.push(tx_ids[j]);
621 };
622 }
623
624 let pmt1 = PartialMerkleTree::from_txids(&tx_ids, &matches);
626 let serialized = serialize(&pmt1);
627
628 let n = min(tx_count, 1 + match_txid1.len() * height);
630 assert!(serialized.len() <= 10 + (258 * n + 7) / 8);
631
632 let pmt2: PartialMerkleTree =
634 deserialize(&serialized).expect("Could not deserialize own data");
635
636 let mut match_txid2: Vec<Txid> = vec![];
638 let mut indexes = vec![];
639 let merkle_root_2 = pmt2
640 .extract_matches(&mut match_txid2, &mut indexes)
641 .expect("Could not extract matches");
642
643 assert_eq!(merkle_root_1, merkle_root_2);
645 assert_ne!(merkle_root_2, TxMerkleNode::all_zeros());
646
647 assert_eq!(match_txid1, match_txid2);
649
650 for _ in 0..4 {
652 let mut pmt3: PartialMerkleTree = deserialize(&serialized).unwrap();
653 pmt3.damage(&mut rng);
654 let mut match_txid3 = vec![];
655 let merkle_root_3 = pmt3.extract_matches(&mut match_txid3, &mut indexes).unwrap();
656 assert_ne!(merkle_root_3, merkle_root_1);
657 }
658 }
659 }
660
661 #[test]
662 fn pmt_malleability() {
663 let txids: Vec<Txid> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 10]
665 .iter()
666 .map(|i| format!("{:064x}", i).parse::<Txid>().unwrap())
667 .collect();
668
669 let matches =
670 vec![false, false, false, false, false, false, false, false, false, true, true, false];
671
672 let tree = PartialMerkleTree::from_txids(&txids, &matches);
673 let result = tree.extract_matches(&mut vec![], &mut vec![]);
675 assert!(result.is_err());
676 }
677
678 #[test]
679 fn merkleblock_serialization() {
680 let mb_hex = include_str!("../../tests/data/merkle_block.hex");
683
684 let mb: MerkleBlock = deserialize(&hex!(mb_hex)).unwrap();
685 assert_eq!(get_block_13b8a().block_hash(), mb.header.block_hash());
686 assert_eq!(
687 mb.header.merkle_root,
688 mb.txn.extract_matches(&mut vec![], &mut vec![]).unwrap()
689 );
690 assert_eq!(mb_hex, serialize(&mb).to_lower_hex_string().as_str());
692 }
693
694 #[test]
697 fn merkleblock_construct_from_txids_found() {
698 let block = get_block_13b8a();
699
700 let txids: Vec<Txid> = [
701 "74d681e0e03bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20",
702 "f9fc751cb7dc372406a9f8d738d5e6f8f63bab71986a39cf36ee70ee17036d07",
703 ]
704 .iter()
705 .map(|hex| hex.parse::<Txid>().unwrap())
706 .collect();
707
708 let txid1 = txids[0];
709 let txid2 = txids[1];
710 let txids = [txid1, txid2];
711
712 let merkle_block = MerkleBlock::from_block_with_predicate(&block, |t| txids.contains(t));
713
714 assert_eq!(merkle_block.header.block_hash(), block.block_hash());
715
716 let mut matches: Vec<Txid> = vec![];
717 let mut index: Vec<u32> = vec![];
718
719 assert_eq!(
720 merkle_block.txn.extract_matches(&mut matches, &mut index).unwrap(),
721 block.header.merkle_root
722 );
723 assert_eq!(matches.len(), 2);
724
725 assert_eq!(matches[0], txid2);
727 assert_eq!(index[0], 1);
728
729 assert_eq!(matches[1], txid1);
730 assert_eq!(index[1], 8);
731 }
732
733 #[test]
735 fn merkleblock_construct_from_txids_not_found() {
736 let block = get_block_13b8a();
737 let txids: Vec<Txid> = ["c0ffee00003bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20"]
738 .iter()
739 .map(|hex| hex.parse::<Txid>().unwrap())
740 .collect();
741
742 let merkle_block = MerkleBlock::from_block_with_predicate(&block, |t| txids.contains(t));
743
744 assert_eq!(merkle_block.header.block_hash(), block.block_hash());
745
746 let mut matches: Vec<Txid> = vec![];
747 let mut index: Vec<u32> = vec![];
748
749 assert_eq!(
750 merkle_block.txn.extract_matches(&mut matches, &mut index).unwrap(),
751 block.header.merkle_root
752 );
753 assert_eq!(matches.len(), 0);
754 assert_eq!(index.len(), 0);
755 }
756
757 #[cfg(feature = "rand-std")]
758 impl PartialMerkleTree {
759 fn damage(&mut self, rng: &mut ThreadRng) {
761 let n = rng.gen_range(0..self.hashes.len());
762 let bit = rng.gen::<u8>();
763 let hashes = &mut self.hashes;
764 let mut hash = hashes[n].to_byte_array();
765 hash[(bit >> 3) as usize] ^= 1 << (bit & 7);
766 hashes[n] = TxMerkleNode::from_slice(&hash).unwrap();
767 }
768 }
769
770 fn get_block_13b8a() -> Block {
773 use hex::FromHex;
774 let block_hex = include_str!("../../tests/data/block_13b8a.hex");
775 deserialize(&Vec::from_hex(block_hex).unwrap()).unwrap()
776 }
777
778 macro_rules! check_calc_tree_width {
779 ($($test_name:ident, $num_transactions:literal, $height:literal, $expected_width:literal);* $(;)?) => {
780 $(
781 #[test]
782 fn $test_name() {
783 let pmt = PartialMerkleTree {
784 num_transactions: $num_transactions,
785 bits: vec![],
786 hashes: vec![],
787 };
788 let got = pmt.calc_tree_width($height);
789 assert_eq!(got, $expected_width)
790 }
791 )*
792 }
793 }
794
795 check_calc_tree_width! {
799 tree_width_01, 1, 0, 1;
800 tree_width_02, 2, 0, 2;
802 tree_width_03, 2, 1, 1;
803 tree_width_04, 3, 0, 3;
805 tree_width_05, 3, 1, 2;
806 tree_width_06, 3, 2, 1;
807 tree_width_07, 4, 0, 4;
809 tree_width_08, 4, 1, 2;
810 tree_width_09, 4, 2, 1;
811 tree_width_10, 5, 0, 5;
813 tree_width_11, 5, 1, 3;
814 tree_width_12, 5, 2, 2;
815 tree_width_13, 5, 3, 1;
816 tree_width_14, 6, 0, 6;
818 tree_width_15, 6, 1, 3;
819 tree_width_16, 6, 2, 2;
820 tree_width_17, 6, 3, 1;
821 tree_width_18, 7, 0, 7;
823 tree_width_19, 7, 1, 4;
824 tree_width_20, 7, 2, 2;
825 tree_width_21, 7, 3, 1;
826 }
827
828 #[test]
829 fn regression_2606() {
830 let bytes = hex!(
832 "000006000000000000000004ee00000004c7f1ccb1000000ffff000000010000\
833 0000ffffffffff1f000000000400000000000002000000000500000000000000\
834 000000000300000000000003000000000200000000ff00000000c7f1ccb10407\
835 00000000000000ccb100c76538b100000004bfa9c251681b1b00040000000025\
836 00000004bfaac251681b1b25\
837 "
838 );
839 let deser = crate::consensus::deserialize::<MerkleBlock>(&bytes);
840 assert!(deser.is_err());
841 }
842}