From 6c82660b746048feabdb0597c765528ab18a9931 Mon Sep 17 00:00:00 2001 From: Marcos Date: Thu, 5 Dec 2024 13:42:33 -0300 Subject: [PATCH] Refactor validateWitnessInformation --- .../main/java/co/rsk/peg/BridgeSupport.java | 28 ++++++++----------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/rskj-core/src/main/java/co/rsk/peg/BridgeSupport.java b/rskj-core/src/main/java/co/rsk/peg/BridgeSupport.java index 1d069ea365..92c93eb4de 100644 --- a/rskj-core/src/main/java/co/rsk/peg/BridgeSupport.java +++ b/rskj-core/src/main/java/co/rsk/peg/BridgeSupport.java @@ -2283,24 +2283,20 @@ private void validateWitnessInformation( Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue ) throws BridgeIllegalArgumentException { + Optional expectedWitnessCommitment = findWitnessCommitment(coinbaseTransaction); Sha256Hash calculatedWitnessCommitment = Sha256Hash.twiceOf(witnessMerkleRoot.getReversedBytes(), witnessReservedValue); - findWitnessCommitment(coinbaseTransaction) - .filter(commitment -> commitment.equals(calculatedWitnessCommitment)) - .orElseThrow(() -> { - String message = String.format( - "[btcTx: %s] Calculated witness commitment %s does not match the expected value", - coinbaseTransaction.getHash(), - calculatedWitnessCommitment - ); - logger.warn("[validateWitnessInformation] {}", message); - return new BridgeIllegalArgumentException(message); - }); - logger.debug( - "[validateWitnessInformation] Witness commitment {} validated for btc tx {}", - calculatedWitnessCommitment, - coinbaseTransaction.getHash() - ); + if (expectedWitnessCommitment.isEmpty() || !expectedWitnessCommitment.get().equals(calculatedWitnessCommitment)) { + String message = String.format( + "[btcTx: %s] Witness commitment does not match. Expected: %s, Calculated: %s", + coinbaseTransaction.getHash(), + expectedWitnessCommitment.orElse(null), + calculatedWitnessCommitment + ); + logger.warn("[validateWitnessInformation] {}", message); + throw new BridgeIllegalArgumentException(message); + } + logger.debug("[validateWitnessInformation] Witness commitment {} validated for btc tx {}", calculatedWitnessCommitment, coinbaseTransaction.getHash()); } public boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash) {