Coverage Summary for Class: PartialMerkleTreeFormatUtils (co.rsk.peg.utils)

Class Class, % Method, % Line, %
PartialMerkleTreeFormatUtils 0% (0/1) 0% (0/7) 0% (0/25)


1 package co.rsk.peg.utils; 2  3 import co.rsk.bitcoinj.core.Sha256Hash; 4 import co.rsk.bitcoinj.core.VarInt; 5  6 import java.util.Arrays; 7 import java.util.stream.IntStream; 8 import java.util.stream.Stream; 9  10 public class PartialMerkleTreeFormatUtils { 11  12  private static final int BLOCK_TRANSACTION_COUNT_LENGTH = 4; 13  14  public static VarInt getHashesCount(byte[] pmtSerialized) { 15  return new VarInt(pmtSerialized, BLOCK_TRANSACTION_COUNT_LENGTH); 16  } 17  18  public static VarInt getFlagBitsCount(byte[] pmtSerialized) { 19  VarInt hashesCount = getHashesCount(pmtSerialized); 20  return new VarInt( 21  pmtSerialized, 22  Math.addExact( 23  BLOCK_TRANSACTION_COUNT_LENGTH + hashesCount.getOriginalSizeInBytes(), 24  Math.multiplyExact(Math.toIntExact(hashesCount.value), Sha256Hash.LENGTH) 25  ) 26  ); 27  } 28  29  public static boolean hasExpectedSize(byte[] pmtSerialized) { 30  try { 31  VarInt hashesCount = getHashesCount(pmtSerialized); 32  VarInt flagBitsCount = getFlagBitsCount(pmtSerialized); 33  int declaredSize = Math.addExact(Math.addExact(BLOCK_TRANSACTION_COUNT_LENGTH 34  + hashesCount.getOriginalSizeInBytes() 35  + flagBitsCount.getOriginalSizeInBytes(), 36  Math.toIntExact(flagBitsCount.value)), 37  Math.multiplyExact(Math.toIntExact(hashesCount.value), Sha256Hash.LENGTH) 38  ); 39  return pmtSerialized.length == declaredSize; 40  } catch (RuntimeException e) { 41  return false; 42  } 43  } 44  45  public static Stream<Sha256Hash> streamIntermediateHashes(byte[] pmtSerialized) { 46  VarInt hashesCount = PartialMerkleTreeFormatUtils.getHashesCount(pmtSerialized); 47  int offset = BLOCK_TRANSACTION_COUNT_LENGTH + hashesCount.getOriginalSizeInBytes(); 48  return IntStream.range(0, (int) hashesCount.value) 49  .mapToObj(index -> getHash(pmtSerialized, offset, index)); 50  } 51  52  private static Sha256Hash getHash(byte[] pmtSerialized, int offset, int index) { 53  int start = index * Sha256Hash.LENGTH; 54  int end = (index + 1) * Sha256Hash.LENGTH; 55  byte[] hash = Arrays.copyOfRange(pmtSerialized, offset + start, offset + end); 56  return Sha256Hash.wrapReversed(hash); 57  } 58 }