Block: move difficulty target range check to AbstractBlockChain.add()

It doesn't make much sense in a getter. It should be checked when
adding a block to the chain, like all the other checks.
This commit is contained in:
Andreas Schildbach 2023-04-02 11:01:25 +02:00
parent bfb840bbfd
commit 991d9ec0d9
3 changed files with 11 additions and 8 deletions

View File

@ -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");

View File

@ -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). */

View File

@ -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"));
}
}