diff --git a/core/src/main/java/org/bitcoinj/core/AbstractBlockChain.java b/core/src/main/java/org/bitcoinj/core/AbstractBlockChain.java index 671378996..803f4c2ff 100644 --- a/core/src/main/java/org/bitcoinj/core/AbstractBlockChain.java +++ b/core/src/main/java/org/bitcoinj/core/AbstractBlockChain.java @@ -34,6 +34,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; +import java.math.BigInteger; import java.nio.ByteBuffer; import java.time.Instant; import java.time.temporal.ChronoUnit; @@ -478,6 +479,10 @@ public abstract class AbstractBlockChain { return false; } + BigInteger target = block.getDifficultyTargetAsInteger(); + if (target.signum() <= 0 || target.compareTo(params.maxTarget) > 0) + throw new VerificationException("Difficulty target is out of range: " + target.toString()); + // If we want to verify transactions (ie we are running with full blocks), verify that block has transactions if (shouldVerifyTransactions() && block.getTransactions() == null) throw new VerificationException("Got a block header while running in full-block mode"); diff --git a/core/src/main/java/org/bitcoinj/core/Block.java b/core/src/main/java/org/bitcoinj/core/Block.java index 3823b5602..404b34d36 100644 --- a/core/src/main/java/org/bitcoinj/core/Block.java +++ b/core/src/main/java/org/bitcoinj/core/Block.java @@ -452,14 +452,12 @@ public class Block extends Message { /** * Returns the difficulty target as a 256 bit value that can be compared to a SHA-256 hash. Inside a block the - * target is represented using a compact form. If this form decodes to a value that is out of bounds, an exception - * is thrown. + * target is represented using a compact form. + * + * @return difficulty target as 256-bit value */ - public BigInteger getDifficultyTargetAsInteger() throws VerificationException { - BigInteger target = ByteUtils.decodeCompactBits(difficultyTarget); - if (target.signum() <= 0 || target.compareTo(params.maxTarget) > 0) - throw new VerificationException("Difficulty target is bad: " + target.toString()); - return target; + public BigInteger getDifficultyTargetAsInteger() { + return ByteUtils.decodeCompactBits(difficultyTarget); } /** Returns true if the hash of the block is OK (lower than difficulty target). */ diff --git a/core/src/test/java/org/bitcoinj/core/BlockChainTest.java b/core/src/test/java/org/bitcoinj/core/BlockChainTest.java index 37be22829..e7f991093 100644 --- a/core/src/test/java/org/bitcoinj/core/BlockChainTest.java +++ b/core/src/test/java/org/bitcoinj/core/BlockChainTest.java @@ -234,7 +234,7 @@ public class BlockChainTest { // allowable difficulty. fail(); } catch (VerificationException e) { - assertTrue(e.getMessage(), e.getCause().getMessage().contains("Difficulty target is bad")); + assertTrue(e.getMessage(), e.getCause().getMessage().contains("Difficulty target is out of range")); } }