mirror of
https://github.com/bitcoinj/bitcoinj.git
synced 2025-02-22 22:25:41 +01:00
Preconditions: replace Guava checkArgument()
and checkState()
for the entire codebase
This also fixes many precondition messages, and rewrites two cases of `checkPositionIndex()` and `checkElementIndex()`.
This commit is contained in:
parent
12b78a6d9b
commit
e37b2ad78c
65 changed files with 386 additions and 274 deletions
|
@ -17,8 +17,6 @@
|
|||
|
||||
package org.bitcoin;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.nio.Buffer;
|
||||
import java.nio.ByteBuffer;
|
||||
|
@ -28,6 +26,7 @@ import java.util.concurrent.locks.ReentrantReadWriteLock;
|
|||
|
||||
import static org.bitcoin.NativeSecp256k1Util.AssertFailException;
|
||||
import static org.bitcoin.NativeSecp256k1Util.assertEquals;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
/**
|
||||
* <p>This class holds native methods to handle ECDSA verification.</p>
|
||||
|
@ -60,7 +59,7 @@ public class NativeSecp256k1 {
|
|||
* @throws AssertFailException never thrown?
|
||||
*/
|
||||
public static boolean verify(byte[] data, byte[] signature, byte[] pub) throws AssertFailException {
|
||||
Preconditions.checkArgument(data.length == 32 && signature.length <= 520 && pub.length <= 520);
|
||||
checkArgument(data.length == 32 && signature.length <= 520 && pub.length <= 520);
|
||||
|
||||
ByteBuffer byteBuff = nativeECDSABuffer.get();
|
||||
if (byteBuff == null || byteBuff.capacity() < 520) {
|
||||
|
@ -90,7 +89,7 @@ public class NativeSecp256k1 {
|
|||
* @throws AssertFailException on bad signature length
|
||||
*/
|
||||
public static byte[] sign(byte[] data, byte[] sec) throws AssertFailException {
|
||||
Preconditions.checkArgument(data.length == 32 && sec.length <= 32);
|
||||
checkArgument(data.length == 32 && sec.length <= 32);
|
||||
|
||||
ByteBuffer byteBuff = nativeECDSABuffer.get();
|
||||
if (byteBuff == null || byteBuff.capacity() < 32 + 32) {
|
||||
|
@ -127,7 +126,7 @@ public class NativeSecp256k1 {
|
|||
* @return true if valid, false if invalid
|
||||
*/
|
||||
public static boolean secKeyVerify(byte[] seckey) {
|
||||
Preconditions.checkArgument(seckey.length == 32);
|
||||
checkArgument(seckey.length == 32);
|
||||
|
||||
ByteBuffer byteBuff = nativeECDSABuffer.get();
|
||||
if (byteBuff == null || byteBuff.capacity() < seckey.length) {
|
||||
|
@ -155,7 +154,7 @@ public class NativeSecp256k1 {
|
|||
*/
|
||||
// TODO add a 'compressed' arg
|
||||
public static byte[] computePubkey(byte[] seckey) throws AssertFailException {
|
||||
Preconditions.checkArgument(seckey.length == 32);
|
||||
checkArgument(seckey.length == 32);
|
||||
|
||||
ByteBuffer byteBuff = nativeECDSABuffer.get();
|
||||
if (byteBuff == null || byteBuff.capacity() < seckey.length) {
|
||||
|
@ -220,7 +219,7 @@ public class NativeSecp256k1 {
|
|||
* @throws AssertFailException assertion failure
|
||||
*/
|
||||
public static byte[] privKeyTweakMul(byte[] privkey, byte[] tweak) throws AssertFailException {
|
||||
Preconditions.checkArgument(privkey.length == 32);
|
||||
checkArgument(privkey.length == 32);
|
||||
|
||||
ByteBuffer byteBuff = nativeECDSABuffer.get();
|
||||
if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) {
|
||||
|
@ -261,7 +260,7 @@ public class NativeSecp256k1 {
|
|||
* @throws AssertFailException assertion failure
|
||||
*/
|
||||
public static byte[] privKeyTweakAdd(byte[] privkey, byte[] tweak) throws AssertFailException {
|
||||
Preconditions.checkArgument(privkey.length == 32);
|
||||
checkArgument(privkey.length == 32);
|
||||
|
||||
ByteBuffer byteBuff = nativeECDSABuffer.get();
|
||||
if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) {
|
||||
|
@ -302,7 +301,7 @@ public class NativeSecp256k1 {
|
|||
* @throws AssertFailException assertion failure
|
||||
*/
|
||||
public static byte[] pubKeyTweakAdd(byte[] pubkey, byte[] tweak) throws AssertFailException {
|
||||
Preconditions.checkArgument(pubkey.length == 33 || pubkey.length == 65);
|
||||
checkArgument(pubkey.length == 33 || pubkey.length == 65);
|
||||
|
||||
ByteBuffer byteBuff = nativeECDSABuffer.get();
|
||||
if (byteBuff == null || byteBuff.capacity() < pubkey.length + tweak.length) {
|
||||
|
@ -343,7 +342,7 @@ public class NativeSecp256k1 {
|
|||
* @throws AssertFailException assertion failure
|
||||
*/
|
||||
public static byte[] pubKeyTweakMul(byte[] pubkey, byte[] tweak) throws AssertFailException {
|
||||
Preconditions.checkArgument(pubkey.length == 33 || pubkey.length == 65);
|
||||
checkArgument(pubkey.length == 33 || pubkey.length == 65);
|
||||
|
||||
ByteBuffer byteBuff = nativeECDSABuffer.get();
|
||||
if (byteBuff == null || byteBuff.capacity() < pubkey.length + tweak.length) {
|
||||
|
@ -384,7 +383,7 @@ public class NativeSecp256k1 {
|
|||
* @throws AssertFailException assertion failure
|
||||
*/
|
||||
public static byte[] createECDHSecret(byte[] seckey, byte[] pubkey) throws AssertFailException {
|
||||
Preconditions.checkArgument(seckey.length <= 32 && pubkey.length <= 65);
|
||||
checkArgument(seckey.length <= 32 && pubkey.length <= 65);
|
||||
|
||||
ByteBuffer byteBuff = nativeECDSABuffer.get();
|
||||
if (byteBuff == null || byteBuff.capacity() < 32 + pubkey.length) {
|
||||
|
@ -421,7 +420,7 @@ public class NativeSecp256k1 {
|
|||
* @throws AssertFailException never thrown?
|
||||
*/
|
||||
public static synchronized boolean randomize(byte[] seed) throws AssertFailException {
|
||||
Preconditions.checkArgument(seed.length == 32 || seed == null);
|
||||
checkArgument(seed.length == 32 || seed == null);
|
||||
|
||||
ByteBuffer byteBuff = nativeECDSABuffer.get();
|
||||
if (byteBuff == null || byteBuff.capacity() < seed.length) {
|
||||
|
@ -447,7 +446,7 @@ public class NativeSecp256k1 {
|
|||
* @throws AssertFailException assertion failure
|
||||
*/
|
||||
public static byte[] schnorrSign(byte[] data, byte[] sec) throws AssertFailException {
|
||||
Preconditions.checkArgument(data.length == 32 && sec.length <= 32);
|
||||
checkArgument(data.length == 32 && sec.length <= 32);
|
||||
|
||||
ByteBuffer byteBuff = nativeECDSABuffer.get();
|
||||
if (byteBuff == null) {
|
||||
|
|
|
@ -17,7 +17,6 @@
|
|||
|
||||
package org.bitcoinj.core;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import org.bitcoinj.base.Sha256Hash;
|
||||
import org.bitcoinj.core.listeners.NewBestBlockListener;
|
||||
import org.bitcoinj.core.listeners.ReorganizeListener;
|
||||
|
@ -53,8 +52,8 @@ import java.util.concurrent.CopyOnWriteArrayList;
|
|||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>An AbstractBlockChain holds a series of {@link Block} objects, links them together, and knows how to verify that
|
||||
|
@ -137,7 +136,7 @@ public abstract class AbstractBlockChain {
|
|||
final Map<Sha256Hash, Transaction> filteredTxn;
|
||||
OrphanBlock(Block block, @Nullable List<Sha256Hash> filteredTxHashes, @Nullable Map<Sha256Hash, Transaction> filteredTxn) {
|
||||
final boolean filtered = filteredTxHashes != null && filteredTxn != null;
|
||||
Preconditions.checkArgument((block.getTransactions() == null && filtered)
|
||||
checkArgument((block.getTransactions() == null && filtered)
|
||||
|| (block.getTransactions() != null && !filtered));
|
||||
this.block = block;
|
||||
this.filteredTxHashes = filteredTxHashes;
|
||||
|
@ -519,7 +518,8 @@ public abstract class AbstractBlockChain {
|
|||
// We can't find the previous block. Probably we are still in the process of downloading the chain and a
|
||||
// block was solved whilst we were doing it. We put it to one side and try to connect it later when we
|
||||
// have more blocks.
|
||||
checkState(tryConnecting, "bug in tryConnectingOrphans");
|
||||
checkState(tryConnecting, () ->
|
||||
"bug in tryConnectingOrphans");
|
||||
log.warn("Block does not connect: {} prev {}", block.getHashAsString(), block.getPrevBlockHash());
|
||||
orphanBlocks.put(block.getHash(), new OrphanBlock(block, filteredTxHashList, filteredTxn));
|
||||
if (tryConnecting)
|
||||
|
@ -851,7 +851,8 @@ public abstract class AbstractBlockChain {
|
|||
* Returns the set of contiguous blocks between 'higher' and 'lower'. Higher is included, lower is not.
|
||||
*/
|
||||
private static LinkedList<StoredBlock> getPartialChain(StoredBlock higher, StoredBlock lower, BlockStore store) throws BlockStoreException {
|
||||
checkArgument(higher.getHeight() > lower.getHeight(), "higher and lower are reversed");
|
||||
checkArgument(higher.getHeight() > lower.getHeight(), () ->
|
||||
"higher and lower are reversed");
|
||||
LinkedList<StoredBlock> results = new LinkedList<>();
|
||||
StoredBlock cursor = higher;
|
||||
do {
|
||||
|
|
|
@ -50,9 +50,9 @@ import java.util.List;
|
|||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.Coin.FIFTY_COINS;
|
||||
import static org.bitcoinj.base.Sha256Hash.hashTwice;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>A block is a group of transactions, and is one of the fundamental data structures of the Bitcoin system.
|
||||
|
|
|
@ -29,7 +29,7 @@ import java.io.File;
|
|||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
// TODO: Rename this class to SPVBlockChain at some point.
|
||||
|
||||
|
@ -93,7 +93,8 @@ public class BlockChain extends AbstractBlockChain {
|
|||
lock.lock();
|
||||
try {
|
||||
int currentHeight = getBestChainHeight();
|
||||
checkArgument(height >= 0 && height <= currentHeight, "Bad height: %s", height);
|
||||
checkArgument(height >= 0 && height <= currentHeight, () ->
|
||||
"bad height: " + height);
|
||||
if (height == currentHeight)
|
||||
return; // nothing to do
|
||||
|
||||
|
|
|
@ -33,12 +33,12 @@ import java.util.Arrays;
|
|||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static java.lang.Math.E;
|
||||
import static java.lang.Math.log;
|
||||
import static java.lang.Math.max;
|
||||
import static java.lang.Math.min;
|
||||
import static java.lang.Math.pow;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
/**
|
||||
* <p>A Bloom filter is a probabilistic data structure which can be sent to another client so that it can avoid
|
||||
|
|
|
@ -49,9 +49,8 @@ import java.util.Map;
|
|||
import java.util.Objects;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkPositionIndex;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>Vends hard-coded {@link StoredBlock}s for blocks throughout the chain. Checkpoints serve two purposes:</p>
|
||||
|
@ -130,7 +129,9 @@ public class CheckpointManager {
|
|||
dis.readFully(header);
|
||||
if (!Arrays.equals(header, BINARY_MAGIC.getBytes(StandardCharsets.US_ASCII)))
|
||||
throw new IOException("Header bytes did not match expected version");
|
||||
int numSignatures = checkPositionIndex(dis.readInt(), MAX_SIGNATURES, "Num signatures out of range");
|
||||
int numSignatures = dis.readInt();
|
||||
checkState(numSignatures >= 0 && numSignatures < MAX_SIGNATURES, () ->
|
||||
"numSignatures out of range: " + numSignatures);
|
||||
for (int i = 0; i < numSignatures; i++) {
|
||||
byte[] sig = new byte[65];
|
||||
dis.readFully(sig);
|
||||
|
@ -236,7 +237,8 @@ public class CheckpointManager {
|
|||
throws IOException, BlockStoreException {
|
||||
Objects.requireNonNull(params);
|
||||
Objects.requireNonNull(store);
|
||||
checkArgument(!(store instanceof FullPrunedBlockStore), "You cannot use checkpointing with a full store.");
|
||||
checkArgument(!(store instanceof FullPrunedBlockStore), () ->
|
||||
"you cannot use checkpointing with a full store");
|
||||
|
||||
time = time.minus(7, ChronoUnit.WEEKS);
|
||||
|
||||
|
|
|
@ -45,7 +45,7 @@ import java.util.concurrent.Executors;
|
|||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.FutureTask;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>A FullPrunedBlockChain works in conjunction with a {@link FullPrunedBlockStore} to verify all the rules of the
|
||||
|
|
|
@ -16,7 +16,7 @@
|
|||
|
||||
package org.bitcoinj.core;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
/**
|
||||
* <p>Represents the "inv" P2P network message. An inv contains a list of hashes of either blocks or transactions. It's
|
||||
|
|
|
@ -30,7 +30,7 @@ import java.math.BigInteger;
|
|||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>A Message is a data structure that can be serialized/deserialized using the Bitcoin serialization format.
|
||||
|
@ -92,9 +92,8 @@ public abstract class Message {
|
|||
|
||||
parse();
|
||||
|
||||
if (this.length == UNKNOWN_LENGTH && !(this instanceof UnknownMessage))
|
||||
checkState(false, "Length field has not been set in constructor for %s after parse.",
|
||||
getClass().getSimpleName());
|
||||
checkState(this.length != UNKNOWN_LENGTH || this instanceof UnknownMessage, () ->
|
||||
"length field has not been set in constructor for " + getClass().getSimpleName() + " after parse");
|
||||
|
||||
if (serializer.isParseRetainMode())
|
||||
Objects.requireNonNull(this.payload, "payload must be retained");
|
||||
|
@ -271,8 +270,8 @@ public abstract class Message {
|
|||
* This returns a correct value by parsing the message.
|
||||
*/
|
||||
public final int getMessageSize() {
|
||||
if (length == UNKNOWN_LENGTH)
|
||||
checkState(false, "Length field has not been set in %s.", getClass().getSimpleName());
|
||||
checkState(length != UNKNOWN_LENGTH, () ->
|
||||
"length field has not been set in " + getClass().getSimpleName());
|
||||
return length;
|
||||
}
|
||||
|
||||
|
|
|
@ -17,7 +17,6 @@
|
|||
package org.bitcoinj.core;
|
||||
|
||||
import com.google.common.base.MoreObjects;
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.common.base.Throwables;
|
||||
import net.jcip.annotations.GuardedBy;
|
||||
|
@ -70,7 +69,8 @@ import java.util.concurrent.locks.ReentrantLock;
|
|||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>A Peer handles the high level communication with a Bitcoin node, extending a {@link PeerSocketHandler} which
|
||||
|
@ -631,7 +631,7 @@ public class Peer extends PeerSocketHandler {
|
|||
}
|
||||
|
||||
try {
|
||||
checkState(!downloadBlockBodies, toString());
|
||||
checkState(!downloadBlockBodies, () -> toString());
|
||||
for (int i = 0; i < m.getBlockHeaders().size(); i++) {
|
||||
Block header = m.getBlockHeaders().get(i);
|
||||
// Process headers until we pass the fast catchup time, or are about to catch up with the head
|
||||
|
@ -813,7 +813,7 @@ public class Peer extends PeerSocketHandler {
|
|||
*/
|
||||
public ListenableCompletableFuture<List<Transaction>> downloadDependencies(Transaction tx) {
|
||||
TransactionConfidence.ConfidenceType txConfidence = tx.getConfidence().getConfidenceType();
|
||||
Preconditions.checkArgument(txConfidence != TransactionConfidence.ConfidenceType.BUILDING);
|
||||
checkArgument(txConfidence != TransactionConfidence.ConfidenceType.BUILDING);
|
||||
log.info("{}: Downloading dependencies of {}", getAddress(), tx.getTxId());
|
||||
// future will be invoked when the entire dependency tree has been walked and the results compiled.
|
||||
return ListenableCompletableFuture.of(downloadDependenciesInternal(tx, vDownloadTxDependencyDepth, 0));
|
||||
|
@ -1287,7 +1287,7 @@ public class Peer extends PeerSocketHandler {
|
|||
/** Sends a getdata with a single item in it. */
|
||||
private CompletableFuture sendSingleGetData(GetDataMessage getdata) {
|
||||
// This does not need to be locked.
|
||||
Preconditions.checkArgument(getdata.getItems().size() == 1);
|
||||
checkArgument(getdata.getItems().size() == 1);
|
||||
GetDataRequest req = new GetDataRequest(getdata.getItems().get(0).hash);
|
||||
getDataFutures.add(req);
|
||||
sendMessage(getdata);
|
||||
|
@ -1624,7 +1624,8 @@ public class Peer extends PeerSocketHandler {
|
|||
// chainHeight should not be zero/negative because we shouldn't have given the user a Peer that is to another
|
||||
// client-mode node, nor should it be unconnected. If that happens it means the user overrode us somewhere or
|
||||
// there is a bug in the peer management code.
|
||||
checkState(params.allowEmptyPeerChain() || chainHeight > 0, "Connected to peer with zero/negative chain height", chainHeight);
|
||||
checkState(params.allowEmptyPeerChain() || chainHeight > 0, () ->
|
||||
"connected to peer with zero/negative chain height: " + chainHeight);
|
||||
return chainHeight - blockChain.getBestChainHeight();
|
||||
}
|
||||
|
||||
|
|
|
@ -100,8 +100,8 @@ import java.util.concurrent.ScheduledThreadPoolExecutor;
|
|||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>Runs a set of connections to the P2P network, brings up connections to replace disconnected nodes and manages
|
||||
|
@ -1150,7 +1150,8 @@ public class PeerGroup implements TransactionBroadcaster {
|
|||
// Just try to help catch what might be a programming error.
|
||||
log.warn("Starting up with no attached block chain. Did you forget to pass one to the constructor?");
|
||||
}
|
||||
checkState(!vUsedUp, "Cannot start a peer group twice");
|
||||
checkState(!vUsedUp, () ->
|
||||
"cannot start a peer group twice");
|
||||
vRunning = true;
|
||||
vUsedUp = true;
|
||||
executorStartupLatch.countDown();
|
||||
|
@ -1741,7 +1742,8 @@ public class PeerGroup implements TransactionBroadcaster {
|
|||
public void setFastCatchupTime(Instant fastCatchupTime) {
|
||||
lock.lock();
|
||||
try {
|
||||
checkState(chain == null || !chain.shouldVerifyTransactions(), "Fast catchup is incompatible with fully verifying");
|
||||
checkState(chain == null || !chain.shouldVerifyTransactions(), () ->
|
||||
"fast catchup is incompatible with fully verifying");
|
||||
this.fastCatchupTime = fastCatchupTime;
|
||||
if (downloadPeer != null) {
|
||||
downloadPeer.setFastDownloadParameters(bloomFilterMerger.getLastFilter() != null, fastCatchupTime);
|
||||
|
|
|
@ -40,8 +40,8 @@ import java.time.Duration;
|
|||
import java.util.Objects;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* Handles high-level message (de)serialization for peers, acting as the bridge between the
|
||||
|
|
|
@ -25,7 +25,7 @@ import java.nio.ByteBuffer;
|
|||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* Wraps a {@link Block} object with extra data that can be derived from the block chain but is slow or inconvenient to
|
||||
|
@ -126,7 +126,8 @@ public class StoredBlock {
|
|||
/** Serializes the stored block to a custom packed format. Used by {@link CheckpointManager}. */
|
||||
public void serializeCompact(ByteBuffer buffer) {
|
||||
byte[] chainWorkBytes = getChainWork().toByteArray();
|
||||
checkState(chainWorkBytes.length <= CHAIN_WORK_BYTES, "Ran out of space to store chain work!");
|
||||
checkState(chainWorkBytes.length <= CHAIN_WORK_BYTES, () ->
|
||||
"ran out of space to store chain work!");
|
||||
if (chainWorkBytes.length < CHAIN_WORK_BYTES) {
|
||||
// Pad to the right size.
|
||||
buffer.put(EMPTY_BYTES, 0, CHAIN_WORK_BYTES - chainWorkBytes.length);
|
||||
|
|
|
@ -66,8 +66,8 @@ import java.util.Objects;
|
|||
import java.util.Optional;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
import static org.bitcoinj.core.NetworkParameters.ProtocolVersion.WITNESS_VERSION;
|
||||
import static org.bitcoinj.base.internal.ByteUtils.uint32ToByteStreamLE;
|
||||
import static org.bitcoinj.base.internal.ByteUtils.uint64ToByteStreamLE;
|
||||
|
@ -1024,7 +1024,8 @@ public class Transaction extends ChildMessage {
|
|||
public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, Coin amount, ECKey sigKey,
|
||||
SigHash sigHash, boolean anyoneCanPay) throws ScriptException {
|
||||
// Verify the API user didn't try to do operations out of order.
|
||||
checkState(!outputs.isEmpty(), "Attempting to sign tx without outputs.");
|
||||
checkState(!outputs.isEmpty(), () ->
|
||||
"attempting to sign tx without outputs");
|
||||
if (amount == null || amount.value <= 0) {
|
||||
log.warn("Illegal amount value. Amount is required for SegWit transactions.");
|
||||
}
|
||||
|
@ -1120,7 +1121,8 @@ public class Transaction extends ChildMessage {
|
|||
*/
|
||||
public TransactionInput addSignedInput(TransactionOutput output, ECKey sigKey, SigHash sigHash, boolean anyoneCanPay) {
|
||||
Objects.requireNonNull(output.getValue(), "TransactionOutput.getValue() must not be null");
|
||||
checkState(output.getValue().value > 0, "TransactionOutput.getValue() must not be greater than zero");
|
||||
checkState(output.getValue().value > 0, () ->
|
||||
"transactionOutput.getValue() must not be greater than zero");
|
||||
return addSignedInput(output.getOutPointFor(), output.getScriptPubKey(), output.getValue(), sigKey, sigHash, anyoneCanPay);
|
||||
}
|
||||
|
||||
|
|
|
@ -39,7 +39,7 @@ import java.util.concurrent.CompletableFuture;
|
|||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* Represents a single transaction broadcast that we are performing. A broadcast occurs after a new transaction is created
|
||||
|
@ -324,7 +324,8 @@ public class TransactionBroadcast {
|
|||
}
|
||||
if (callback != null) {
|
||||
final double progress = Math.min(1.0, mined ? 1.0 : numSeenPeers / (double) numWaitingFor);
|
||||
checkState(progress >= 0.0 && progress <= 1.0, progress);
|
||||
checkState(progress >= 0.0 && progress <= 1.0, () ->
|
||||
"" + progress);
|
||||
try {
|
||||
if (executor == null)
|
||||
callback.onBroadcastProgress(progress);
|
||||
|
|
|
@ -38,7 +38,7 @@ import java.util.Set;
|
|||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
// TODO: Modify the getDepthInBlocks method to require the chain height to be specified, in preparation for ceasing to touch every tx on every block.
|
||||
|
||||
|
|
|
@ -36,7 +36,7 @@ import java.util.Arrays;
|
|||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkElementIndex;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
/**
|
||||
* <p>A transfer of coins from one address to another creates a transaction in which the outputs
|
||||
|
@ -370,8 +370,10 @@ public class TransactionInput extends ChildMessage {
|
|||
public ConnectionResult connect(Transaction transaction, ConnectMode mode) {
|
||||
if (!transaction.getTxId().equals(outpoint.getHash()))
|
||||
return ConnectionResult.NO_SUCH_TX;
|
||||
checkElementIndex((int) outpoint.getIndex(), transaction.getOutputs().size(), "Corrupt transaction");
|
||||
TransactionOutput out = transaction.getOutput((int) outpoint.getIndex());
|
||||
int outpointIndex = (int) outpoint.getIndex();
|
||||
checkArgument(outpointIndex >= 0 && outpointIndex < transaction.getOutputs().size(), () ->
|
||||
"corrupt transaction: " + outpointIndex);
|
||||
TransactionOutput out = transaction.getOutput(outpointIndex);
|
||||
if (!out.isAvailableForSpending()) {
|
||||
if (getParentTransaction().equals(outpoint.fromTx)) {
|
||||
// Already connected.
|
||||
|
|
|
@ -33,7 +33,7 @@ import java.io.IOException;
|
|||
import java.io.OutputStream;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>This message is a reference or pointer to an output of a different transaction.</p>
|
||||
|
|
|
@ -39,8 +39,8 @@ import java.util.Arrays;
|
|||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>A TransactionOutput message contains a scriptPubKey that controls who is able to spend its value. It is a sub-part
|
||||
|
@ -114,8 +114,10 @@ public class TransactionOutput extends ChildMessage {
|
|||
super(params);
|
||||
// Negative values obviously make no sense, except for -1 which is used as a sentinel value when calculating
|
||||
// SIGHASH_SINGLE signatures, so unfortunately we have to allow that here.
|
||||
checkArgument(value.signum() >= 0 || value.equals(Coin.NEGATIVE_SATOSHI), "Negative values not allowed");
|
||||
checkArgument(!params.network().exceedsMaxMoney(value), "Values larger than MAX_MONEY not allowed");
|
||||
checkArgument(value.signum() >= 0 || value.equals(Coin.NEGATIVE_SATOSHI), () ->
|
||||
"negative values not allowed");
|
||||
checkArgument(!params.network().exceedsMaxMoney(value), () ->
|
||||
"values larger than MAX_MONEY not allowed");
|
||||
this.value = value.value;
|
||||
this.scriptBytes = scriptBytes;
|
||||
setParent(parent);
|
||||
|
|
|
@ -28,7 +28,7 @@ import java.util.ArrayList;
|
|||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
public class TransactionWitness {
|
||||
public static final TransactionWitness EMPTY = new TransactionWitness(0);
|
||||
|
@ -38,7 +38,8 @@ public class TransactionWitness {
|
|||
* used as a placeholder.
|
||||
*/
|
||||
public static TransactionWitness redeemP2WPKH(@Nullable TransactionSignature signature, ECKey pubKey) {
|
||||
checkArgument(pubKey.isCompressed(), "only compressed keys allowed");
|
||||
checkArgument(pubKey.isCompressed(), () ->
|
||||
"only compressed keys allowed");
|
||||
TransactionWitness witness = new TransactionWitness(2);
|
||||
witness.setPush(0, signature != null ? signature.encodeToBitcoin() : new byte[0]); // signature
|
||||
witness.setPush(1, pubKey.getPubKey()); // pubkey
|
||||
|
|
|
@ -34,7 +34,7 @@ import java.security.GeneralSecurityException;
|
|||
import java.text.Normalizer;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* Implementation of <a href="https://github.com/bitcoin/bips/blob/master/bip-0038.mediawiki">BIP 38</a>
|
||||
|
|
|
@ -22,7 +22,7 @@ import java.util.List;
|
|||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
// TODO: This whole API feels a bit object heavy. Do we really need ChildNumber and so many maps, etc?
|
||||
// TODO: Should we be representing this using an actual tree arrangement in memory instead of a bunch of hashmaps?
|
||||
|
@ -102,7 +102,7 @@ public class DeterministicHierarchy {
|
|||
if (!create)
|
||||
throw new IllegalArgumentException(String.format(Locale.US, "No key found for %s path %s.",
|
||||
relativePath ? "relative" : "absolute", inputPath.toString()));
|
||||
checkArgument(absolutePath.size() > 0, "Can't derive the master key: nothing to derive from.");
|
||||
checkArgument(absolutePath.size() > 0, () -> "can't derive the master key: nothing to derive from");
|
||||
DeterministicKey parent = get(absolutePath.subList(0, absolutePath.size() - 1), false, true);
|
||||
putKey(HDKeyDerivation.deriveChildKey(parent, absolutePath.get(absolutePath.size() - 1)));
|
||||
}
|
||||
|
|
|
@ -38,8 +38,8 @@ import java.util.List;
|
|||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* A deterministic key is a node in a {@link DeterministicHierarchy}. As per
|
||||
|
@ -123,9 +123,8 @@ public class DeterministicKey extends ECKey {
|
|||
throws IllegalArgumentException {
|
||||
if (parentFingerprint != 0) {
|
||||
if (parent != null)
|
||||
checkArgument(parent.getFingerprint() == parentFingerprint,
|
||||
"parent fingerprint mismatch",
|
||||
Integer.toHexString(parent.getFingerprint()), Integer.toHexString(parentFingerprint));
|
||||
checkArgument(parent.getFingerprint() == parentFingerprint, () ->
|
||||
"parent fingerprint mismatch: " + Integer.toHexString(parent.getFingerprint()) + " vs " + Integer.toHexString(parentFingerprint));
|
||||
return parentFingerprint;
|
||||
} else return 0;
|
||||
}
|
||||
|
@ -304,7 +303,7 @@ public class DeterministicKey extends ECKey {
|
|||
if (newParent != null)
|
||||
checkArgument(newParent.isEncrypted());
|
||||
final byte[] privKeyBytes = getPrivKeyBytes();
|
||||
checkState(privKeyBytes != null, "Private key is not available");
|
||||
checkState(privKeyBytes != null, () -> "Private key is not available");
|
||||
EncryptedData encryptedPrivateKey = keyCrypter.encrypt(privKeyBytes, aesKey);
|
||||
DeterministicKey key = new DeterministicKey(childNumberPath, chainCode, keyCrypter, pub, encryptedPrivateKey, newParent);
|
||||
if (newParent == null) {
|
||||
|
@ -479,7 +478,8 @@ public class DeterministicKey extends ECKey {
|
|||
@Override
|
||||
public BigInteger getPrivKey() {
|
||||
final BigInteger key = findOrDerivePrivateKey();
|
||||
checkState(key != null, "Private key bytes not available");
|
||||
checkState(key != null, () ->
|
||||
"private key bytes not available");
|
||||
return key;
|
||||
}
|
||||
|
||||
|
@ -684,7 +684,8 @@ public class DeterministicKey extends ECKey {
|
|||
buffer.get(chainCode);
|
||||
byte[] data = new byte[33];
|
||||
buffer.get(data);
|
||||
checkArgument(!buffer.hasRemaining(), "Found unexpected data in key");
|
||||
checkArgument(!buffer.hasRemaining(), () ->
|
||||
"found unexpected data in key");
|
||||
if (pub) {
|
||||
return new DeterministicKey(path, chainCode, new LazyECPoint(ECKey.CURVE.getCurve(), data), parent, depth, parentFingerprint);
|
||||
} else {
|
||||
|
|
|
@ -17,7 +17,6 @@
|
|||
|
||||
package org.bitcoinj.crypto;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import org.bitcoinj.base.Base58;
|
||||
import org.bitcoinj.base.Network;
|
||||
import org.bitcoinj.base.exceptions.AddressFormatException;
|
||||
|
@ -27,6 +26,8 @@ import org.bitcoinj.params.Networks;
|
|||
import javax.annotation.Nullable;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
/**
|
||||
* Parses and generates private keys in the form used by the Bitcoin "dumpprivkey" command. This is the private key
|
||||
* bytes with a header byte and 4 checksum bytes at the end. If there are 33 private key bytes instead of 32, then
|
||||
|
@ -104,7 +105,7 @@ public class DumpedPrivateKey extends EncodedPrivateKey {
|
|||
}
|
||||
|
||||
private static byte[] encode(byte[] keyBytes, boolean compressed) {
|
||||
Preconditions.checkArgument(keyBytes.length == 32, "Private keys must be 32 bytes");
|
||||
checkArgument(keyBytes.length == 32, () -> "private keys must be 32 bytes");
|
||||
if (!compressed) {
|
||||
return keyBytes;
|
||||
} else {
|
||||
|
|
|
@ -19,7 +19,6 @@
|
|||
package org.bitcoinj.crypto;
|
||||
|
||||
import com.google.common.base.MoreObjects;
|
||||
import com.google.common.base.Preconditions;
|
||||
import org.bitcoin.NativeSecp256k1;
|
||||
import org.bitcoin.NativeSecp256k1Util;
|
||||
import org.bitcoin.Secp256k1Context;
|
||||
|
@ -85,8 +84,8 @@ import java.util.Comparator;
|
|||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>Represents an elliptic curve public and (optionally) private key, usable for digital signatures but not encryption.
|
||||
|
@ -193,7 +192,8 @@ public class ECKey implements EncryptableItem {
|
|||
|
||||
protected ECKey(@Nullable BigInteger priv, LazyECPoint pub) {
|
||||
if (priv != null) {
|
||||
checkArgument(priv.bitLength() <= 32 * 8, "private key exceeds 32 bytes: %s bits", priv.bitLength());
|
||||
checkArgument(priv.bitLength() <= 32 * 8, () ->
|
||||
"private key exceeds 32 bytes: " + priv.bitLength() + " bits");
|
||||
// Try and catch buggy callers or bad key imports, etc. Zero and one are special because these are often
|
||||
// used as sentinel values and because scripting languages have a habit of auto-casting true and false to
|
||||
// 1 and 0 or vice-versa. Type confusion bugs could therefore result in private keys with these values.
|
||||
|
@ -426,7 +426,8 @@ public class ECKey implements EncryptableItem {
|
|||
if (scriptType == ScriptType.P2PKH) {
|
||||
return LegacyAddress.fromPubKeyHash(network, this.getPubKeyHash());
|
||||
} else if (scriptType == ScriptType.P2WPKH) {
|
||||
checkArgument(this.isCompressed(), "only compressed keys allowed");
|
||||
checkArgument(this.isCompressed(), () ->
|
||||
"only compressed keys allowed");
|
||||
return SegwitAddress.fromHash(network, this.getPubKeyHash());
|
||||
} else {
|
||||
throw new IllegalArgumentException(scriptType.toString());
|
||||
|
@ -745,30 +746,36 @@ public class ECKey implements EncryptableItem {
|
|||
try {
|
||||
ASN1InputStream decoder = new ASN1InputStream(asn1privkey);
|
||||
DLSequence seq = (DLSequence) decoder.readObject();
|
||||
checkArgument(decoder.readObject() == null, "Input contains extra bytes");
|
||||
checkArgument(decoder.readObject() == null, () ->
|
||||
"input contains extra bytes");
|
||||
decoder.close();
|
||||
|
||||
checkArgument(seq.size() == 4, "Input does not appear to be an ASN.1 OpenSSL EC private key");
|
||||
checkArgument(seq.size() == 4, () ->
|
||||
"input does not appear to be an ASN.1 OpenSSL EC private key");
|
||||
|
||||
checkArgument(((ASN1Integer) seq.getObjectAt(0)).getValue().equals(BigInteger.ONE),
|
||||
"Input is of wrong version");
|
||||
checkArgument(((ASN1Integer) seq.getObjectAt(0)).getValue().equals(BigInteger.ONE), () ->
|
||||
"input is of wrong version");
|
||||
|
||||
byte[] privbits = ((ASN1OctetString) seq.getObjectAt(1)).getOctets();
|
||||
BigInteger privkey = ByteUtils.bytesToBigInteger(privbits);
|
||||
|
||||
ASN1TaggedObject pubkey = (ASN1TaggedObject) seq.getObjectAt(3);
|
||||
checkArgument(pubkey.getTagNo() == 1, "Input has 'publicKey' with bad tag number");
|
||||
checkArgument(pubkey.getTagClass() == BERTags.CONTEXT_SPECIFIC, "Input has 'publicKey' with bad tag class");
|
||||
checkArgument(pubkey.getTagNo() == 1, () ->
|
||||
"input has 'publicKey' with bad tag number");
|
||||
checkArgument(pubkey.getTagClass() == BERTags.CONTEXT_SPECIFIC, () ->
|
||||
"input has 'publicKey' with bad tag class");
|
||||
byte[] pubbits = ((DERBitString) pubkey.getBaseObject()).getBytes();
|
||||
checkArgument(pubbits.length == 33 || pubbits.length == 65, "Input has 'publicKey' with invalid length");
|
||||
checkArgument(pubbits.length == 33 || pubbits.length == 65, () ->
|
||||
"input has 'publicKey' with invalid length");
|
||||
int encoding = pubbits[0] & 0xFF;
|
||||
// Only allow compressed(2,3) and uncompressed(4), not infinity(0) or hybrid(6,7)
|
||||
checkArgument(encoding >= 2 && encoding <= 4, "Input has 'publicKey' with invalid encoding");
|
||||
checkArgument(encoding >= 2 && encoding <= 4, () ->
|
||||
"input has 'publicKey' with invalid encoding");
|
||||
|
||||
// Now sanity check to ensure the pubkey bytes match the privkey.
|
||||
ECKey key = ECKey.fromPrivate(privkey, isPubKeyCompressed(pubbits));
|
||||
if (!Arrays.equals(key.getPubKey(), pubbits))
|
||||
throw new IllegalArgumentException("Public key in ASN.1 structure does not match private key.");
|
||||
checkArgument (Arrays.equals(key.getPubKey(), pubbits), () ->
|
||||
"public key in ASN.1 structure does not match private key.");
|
||||
return key;
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e); // Cannot happen, reading from memory stream.
|
||||
|
@ -984,9 +991,9 @@ public class ECKey implements EncryptableItem {
|
|||
*/
|
||||
@Nullable
|
||||
public static ECKey recoverFromSignature(int recId, ECDSASignature sig, Sha256Hash message, boolean compressed) {
|
||||
Preconditions.checkArgument(recId >= 0, "recId must be positive");
|
||||
Preconditions.checkArgument(sig.r.signum() >= 0, "r must be positive");
|
||||
Preconditions.checkArgument(sig.s.signum() >= 0, "s must be positive");
|
||||
checkArgument(recId >= 0, () -> "recId must be positive");
|
||||
checkArgument(sig.r.signum() >= 0, () -> "r must be positive");
|
||||
checkArgument(sig.s.signum() >= 0, () -> "s must be positive");
|
||||
Objects.requireNonNull(message);
|
||||
// see https://www.secg.org/sec1-v2.pdf, section 4.1.6
|
||||
// 1.0 For j from 0 to h (h == recId here and the loop is outside this function)
|
||||
|
@ -1145,7 +1152,8 @@ public class ECKey implements EncryptableItem {
|
|||
// Check that the keyCrypter matches the one used to encrypt the keys, if set.
|
||||
if (this.keyCrypter != null && !this.keyCrypter.equals(keyCrypter))
|
||||
throw new KeyCrypterException("The keyCrypter being used to decrypt the key is different to the one that was used to encrypt it");
|
||||
checkState(encryptedPrivateKey != null, "This key is not encrypted");
|
||||
checkState(encryptedPrivateKey != null, () ->
|
||||
"this key is not encrypted");
|
||||
byte[] unencryptedPrivateKey = keyCrypter.decrypt(encryptedPrivateKey, aesKey);
|
||||
if (unencryptedPrivateKey.length != 32)
|
||||
throw new KeyCrypterException.InvalidCipherText(
|
||||
|
|
|
@ -27,8 +27,8 @@ import java.util.Arrays;
|
|||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* Implementation of the <a href="https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki">BIP 32</a>
|
||||
|
@ -60,12 +60,14 @@ public final class HDKeyDerivation {
|
|||
* @throws IllegalArgumentException if the seed is less than 8 bytes and could be brute forced
|
||||
*/
|
||||
public static DeterministicKey createMasterPrivateKey(byte[] seed) throws HDDerivationException {
|
||||
checkArgument(seed.length > 8, "Seed is too short and could be brute forced");
|
||||
checkArgument(seed.length > 8, () ->
|
||||
"seed is too short and could be brute forced");
|
||||
// Calculate I = HMAC-SHA512(key="Bitcoin seed", msg=S)
|
||||
byte[] i = HDUtils.hmacSha512(HDUtils.createHmacSha512Digest("Bitcoin seed".getBytes()), seed);
|
||||
// Split I into two 32-byte sequences, Il and Ir.
|
||||
// Use Il as master secret key, and Ir as master chain code.
|
||||
checkState(i.length == 64, i.length);
|
||||
checkState(i.length == 64, () ->
|
||||
"" + i.length);
|
||||
byte[] il = Arrays.copyOfRange(i, 0, 32);
|
||||
byte[] ir = Arrays.copyOfRange(i, 32, 64);
|
||||
Arrays.fill(i, (byte)0);
|
||||
|
@ -154,9 +156,11 @@ public final class HDKeyDerivation {
|
|||
|
||||
public static RawKeyBytes deriveChildKeyBytesFromPrivate(DeterministicKey parent,
|
||||
ChildNumber childNumber) throws HDDerivationException {
|
||||
checkArgument(parent.hasPrivKey(), "Parent key must have private key bytes for this method.");
|
||||
checkArgument(parent.hasPrivKey(), () ->
|
||||
"parent key must have private key bytes for this method");
|
||||
byte[] parentPublicKey = parent.getPubKeyPoint().getEncoded(true);
|
||||
checkState(parentPublicKey.length == 33, "Parent pubkey must be 33 bytes, but is " + parentPublicKey.length);
|
||||
checkState(parentPublicKey.length == 33, () ->
|
||||
"parent pubkey must be 33 bytes, but is: " + parentPublicKey.length);
|
||||
ByteBuffer data = ByteBuffer.allocate(37);
|
||||
if (childNumber.isHardened()) {
|
||||
data.put(parent.getPrivKeyBytes33());
|
||||
|
@ -165,7 +169,8 @@ public final class HDKeyDerivation {
|
|||
}
|
||||
data.putInt(childNumber.i());
|
||||
byte[] i = HDUtils.hmacSha512(parent.getChainCode(), data.array());
|
||||
checkState(i.length == 64, i.length);
|
||||
checkState(i.length == 64, () ->
|
||||
"" + i.length);
|
||||
byte[] il = Arrays.copyOfRange(i, 0, 32);
|
||||
byte[] chainCode = Arrays.copyOfRange(i, 32, 64);
|
||||
BigInteger ilInt = ByteUtils.bytesToBigInteger(il);
|
||||
|
@ -189,14 +194,17 @@ public final class HDKeyDerivation {
|
|||
}
|
||||
|
||||
public static RawKeyBytes deriveChildKeyBytesFromPublic(DeterministicKey parent, ChildNumber childNumber, PublicDeriveMode mode) throws HDDerivationException {
|
||||
checkArgument(!childNumber.isHardened(), "Hardened derivation is unsupported (%s).", childNumber);
|
||||
checkArgument(!childNumber.isHardened(), () ->
|
||||
"hardened derivation is unsupported: " + childNumber);
|
||||
byte[] parentPublicKey = parent.getPubKeyPoint().getEncoded(true);
|
||||
checkState(parentPublicKey.length == 33, "Parent pubkey must be 33 bytes, but is " + parentPublicKey.length);
|
||||
checkState(parentPublicKey.length == 33, () ->
|
||||
"parent pubkey must be 33 bytes, but is: " + parentPublicKey.length);
|
||||
ByteBuffer data = ByteBuffer.allocate(37);
|
||||
data.put(parentPublicKey);
|
||||
data.putInt(childNumber.i());
|
||||
byte[] i = HDUtils.hmacSha512(parent.getChainCode(), data.array());
|
||||
checkState(i.length == 64, i.length);
|
||||
checkState(i.length == 64, () ->
|
||||
"" + i.length);
|
||||
byte[] il = Arrays.copyOfRange(i, 0, 32);
|
||||
byte[] chainCode = Arrays.copyOfRange(i, 32, 64);
|
||||
BigInteger ilInt = ByteUtils.bytesToBigInteger(il);
|
||||
|
|
|
@ -38,9 +38,10 @@ import java.util.Collections;
|
|||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import org.bitcoinj.base.internal.ByteUtils;
|
||||
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
/**
|
||||
* A MnemonicCode object may be used to convert between binary seed values and
|
||||
* lists of words per <a href="https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki">the BIP 39
|
||||
|
@ -205,8 +206,10 @@ public class MnemonicCode {
|
|||
* @param entropy entropy bits, length must be a multiple of 32 bits
|
||||
*/
|
||||
public List<String> toMnemonic(byte[] entropy) {
|
||||
checkArgument(entropy.length % 4 == 0, "entropy length not multiple of 32 bits");
|
||||
checkArgument(entropy.length > 0, "entropy is empty");
|
||||
checkArgument(entropy.length % 4 == 0, () ->
|
||||
"entropy length not multiple of 32 bits");
|
||||
checkArgument(entropy.length > 0, () ->
|
||||
"entropy is empty");
|
||||
|
||||
// We take initial entropy of ENT bits and compute its
|
||||
// checksum by taking first ENT / 32 bits of its SHA256 hash.
|
||||
|
|
|
@ -16,7 +16,6 @@
|
|||
|
||||
package org.bitcoinj.crypto;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import org.bitcoinj.core.Transaction;
|
||||
import org.bitcoinj.core.Transaction.SigHash;
|
||||
import org.bitcoinj.core.VerificationException;
|
||||
|
@ -25,6 +24,8 @@ import java.io.ByteArrayOutputStream;
|
|||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
/**
|
||||
* A TransactionSignature wraps an {@link ECKey.ECDSASignature} and adds methods for handling
|
||||
* the additional SIGHASH mode byte that is used.
|
||||
|
@ -68,7 +69,7 @@ public class TransactionSignature extends ECKey.ECDSASignature {
|
|||
|
||||
/** Calculates the byte used in the protocol to represent the combination of mode and anyoneCanPay. */
|
||||
public static int calcSigHashValue(Transaction.SigHash mode, boolean anyoneCanPay) {
|
||||
Preconditions.checkArgument(SigHash.ALL == mode || SigHash.NONE == mode || SigHash.SINGLE == mode); // enforce compatibility since this code was made before the SigHash enum was updated
|
||||
checkArgument(SigHash.ALL == mode || SigHash.NONE == mode || SigHash.SINGLE == mode); // enforce compatibility since this code was made before the SigHash enum was updated
|
||||
int sighashFlags = mode.value;
|
||||
if (anyoneCanPay)
|
||||
sighashFlags |= Transaction.SigHash.ANYONECANPAY.value;
|
||||
|
|
|
@ -60,7 +60,7 @@ import java.util.Objects;
|
|||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>Utility class that wraps the boilerplate needed to set up a new SPV bitcoinj app. Instantiate it with a directory
|
||||
|
@ -152,7 +152,8 @@ public class WalletAppKit extends AbstractIdleService {
|
|||
|
||||
/** Will only connect to the given addresses. Cannot be called after startup. */
|
||||
public WalletAppKit setPeerNodes(PeerAddress... addresses) {
|
||||
checkState(state() == State.NEW, "Cannot call after startup");
|
||||
checkState(state() == State.NEW, () ->
|
||||
"cannot call after startup");
|
||||
this.peerAddresses = addresses;
|
||||
return this;
|
||||
}
|
||||
|
@ -170,7 +171,8 @@ public class WalletAppKit extends AbstractIdleService {
|
|||
|
||||
/** If true, the wallet will save itself to disk automatically whenever it changes. */
|
||||
public WalletAppKit setAutoSave(boolean value) {
|
||||
checkState(state() == State.NEW, "Cannot call after startup");
|
||||
checkState(state() == State.NEW, () ->
|
||||
"cannot call after startup");
|
||||
useAutoSave = value;
|
||||
return this;
|
||||
}
|
||||
|
@ -511,22 +513,26 @@ public class WalletAppKit extends AbstractIdleService {
|
|||
}
|
||||
|
||||
public BlockChain chain() {
|
||||
checkState(state() == State.STARTING || state() == State.RUNNING, "Cannot call until startup is complete");
|
||||
checkState(state() == State.STARTING || state() == State.RUNNING, () ->
|
||||
"cannot call until startup is complete");
|
||||
return vChain;
|
||||
}
|
||||
|
||||
public BlockStore store() {
|
||||
checkState(state() == State.STARTING || state() == State.RUNNING, "Cannot call until startup is complete");
|
||||
checkState(state() == State.STARTING || state() == State.RUNNING, () ->
|
||||
"cannot call until startup is complete");
|
||||
return vStore;
|
||||
}
|
||||
|
||||
public Wallet wallet() {
|
||||
checkState(state() == State.STARTING || state() == State.RUNNING, "Cannot call until startup is complete");
|
||||
checkState(state() == State.STARTING || state() == State.RUNNING, () ->
|
||||
"cannot call until startup is complete");
|
||||
return vWallet;
|
||||
}
|
||||
|
||||
public PeerGroup peerGroup() {
|
||||
checkState(state() == State.STARTING || state() == State.RUNNING, "Cannot call until startup is complete");
|
||||
checkState(state() == State.STARTING || state() == State.RUNNING, () ->
|
||||
"cannot call until startup is complete");
|
||||
return vPeerGroup;
|
||||
}
|
||||
|
||||
|
|
|
@ -35,7 +35,7 @@ import java.time.Duration;
|
|||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>Creates a simple connection to a server using a {@link StreamConnection} to process data.</p>
|
||||
|
|
|
@ -38,7 +38,7 @@ import java.util.Objects;
|
|||
import java.util.Set;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
// TODO: The locking in all this class is horrible and not really necessary. We should just run all network stuff on one thread.
|
||||
|
||||
|
|
|
@ -37,7 +37,7 @@ import java.util.concurrent.Executors;
|
|||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
/**
|
||||
* MultiplexingDiscovery queries multiple PeerDiscovery objects, optionally shuffles their responses and then returns the results,
|
||||
|
|
|
@ -42,7 +42,7 @@ import java.time.temporal.Temporal;
|
|||
import java.time.temporal.TemporalUnit;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* Parameters for Bitcoin-like networks.
|
||||
|
@ -191,8 +191,8 @@ public abstract class BitcoinNetworkParams extends NetworkParameters {
|
|||
}
|
||||
hash = cursor.getHeader().getPrevBlockHash();
|
||||
}
|
||||
checkState(cursor != null && isDifficultyTransitionPoint(cursor.getHeight() - 1),
|
||||
"Didn't arrive at a transition point.");
|
||||
checkState(cursor != null && isDifficultyTransitionPoint(cursor.getHeight() - 1), () ->
|
||||
"didn't arrive at a transition point");
|
||||
Duration elapsed = TimeUtils.elapsedTime(start);
|
||||
if (elapsed.toMillis() > 50)
|
||||
log.info("Difficulty transition traversal took {} ms", elapsed.toMillis());
|
||||
|
|
|
@ -24,7 +24,7 @@ import org.bitcoinj.base.Sha256Hash;
|
|||
|
||||
import java.time.Instant;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* Parameters for the main production network on which people trade goods and services.
|
||||
|
@ -138,7 +138,7 @@ public class MainNetParams extends BitcoinNetworkParams {
|
|||
genesisBlock.setDifficultyTarget(Block.STANDARD_MAX_DIFFICULTY_TARGET);
|
||||
genesisBlock.setTime(Instant.ofEpochSecond(GENESIS_TIME));
|
||||
genesisBlock.setNonce(GENESIS_NONCE);
|
||||
checkState(genesisBlock.getHash().equals(GENESIS_HASH), "Invalid genesis hash");
|
||||
checkState(genesisBlock.getHash().equals(GENESIS_HASH), () -> "invalid genesis hash");
|
||||
}
|
||||
}
|
||||
return genesisBlock;
|
||||
|
|
|
@ -24,7 +24,7 @@ import org.bitcoinj.base.Sha256Hash;
|
|||
|
||||
import java.time.Instant;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* Network parameters for the regression test mode of bitcoind in which all blocks are trivially solvable.
|
||||
|
@ -86,7 +86,8 @@ public class RegTestParams extends BitcoinNetworkParams {
|
|||
genesisBlock.setDifficultyTarget(Block.EASIEST_DIFFICULTY_TARGET);
|
||||
genesisBlock.setTime(Instant.ofEpochSecond(GENESIS_TIME));
|
||||
genesisBlock.setNonce(GENESIS_NONCE);
|
||||
checkState(genesisBlock.getHash().equals(GENESIS_HASH), "Invalid genesis hash");
|
||||
checkState(genesisBlock.getHash().equals(GENESIS_HASH), () ->
|
||||
"invalid genesis hash");
|
||||
}
|
||||
}
|
||||
return genesisBlock;
|
||||
|
|
|
@ -23,7 +23,7 @@ import org.bitcoinj.base.Sha256Hash;
|
|||
|
||||
import java.time.Instant;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>Parameters for the signet, a separate public instance of Bitcoin that has relaxed rules suitable for development
|
||||
|
@ -83,7 +83,8 @@ public class SigNetParams extends BitcoinNetworkParams {
|
|||
genesisBlock.setDifficultyTarget(GENESIS_DIFFICULTY);
|
||||
genesisBlock.setTime(Instant.ofEpochSecond(GENESIS_TIME));
|
||||
genesisBlock.setNonce(GENESIS_NONCE);
|
||||
checkState(genesisBlock.getHash().equals(GENESIS_HASH), "Invalid genesis hash");
|
||||
checkState(genesisBlock.getHash().equals(GENESIS_HASH), () ->
|
||||
"invalid genesis hash");
|
||||
}
|
||||
}
|
||||
return genesisBlock;
|
||||
|
|
|
@ -30,7 +30,7 @@ import org.bitcoinj.store.BlockStoreException;
|
|||
import java.math.BigInteger;
|
||||
import java.time.Instant;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* Parameters for the testnet, a separate public instance of Bitcoin that has relaxed rules suitable for development
|
||||
|
@ -92,7 +92,8 @@ public class TestNet3Params extends BitcoinNetworkParams {
|
|||
genesisBlock.setDifficultyTarget(Block.STANDARD_MAX_DIFFICULTY_TARGET);
|
||||
genesisBlock.setTime(Instant.ofEpochSecond(GENESIS_TIME));
|
||||
genesisBlock.setNonce(GENESIS_NONCE);
|
||||
checkState(genesisBlock.getHash().equals(GENESIS_HASH), "Invalid genesis hash");
|
||||
checkState(genesisBlock.getHash().equals(GENESIS_HASH), () ->
|
||||
"invalid genesis hash");
|
||||
}
|
||||
}
|
||||
return genesisBlock;
|
||||
|
|
|
@ -67,8 +67,8 @@ import java.util.Objects;
|
|||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
import static org.bitcoinj.script.ScriptOpCodes.OP_0;
|
||||
import static org.bitcoinj.script.ScriptOpCodes.OP_0NOTEQUAL;
|
||||
import static org.bitcoinj.script.ScriptOpCodes.OP_1;
|
||||
|
@ -384,7 +384,7 @@ public class Script {
|
|||
if (dataToRead > bis.available())
|
||||
throw new ScriptException(ScriptError.SCRIPT_ERR_BAD_OPCODE, "Push of data element that is larger than remaining data: " + dataToRead + " vs " + bis.available());
|
||||
byte[] data = new byte[(int)dataToRead];
|
||||
checkState(dataToRead == 0 || bis.read(data, 0, (int)dataToRead) == dataToRead);
|
||||
checkState(dataToRead == 0 || bis.read(data, 0, (int) dataToRead) == dataToRead);
|
||||
chunk = new ScriptChunk(opcode, data);
|
||||
}
|
||||
// Save some memory by eliminating redundant copies of the same chunk objects.
|
||||
|
@ -517,14 +517,16 @@ public class Script {
|
|||
*/
|
||||
public Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript) {
|
||||
if (ScriptPattern.isP2PKH(this)) {
|
||||
checkArgument(key != null, "Key required to create P2PKH input script");
|
||||
checkArgument(key != null, () ->
|
||||
"key required to create P2PKH input script");
|
||||
return ScriptBuilder.createInputScript(null, key);
|
||||
} else if (ScriptPattern.isP2WPKH(this)) {
|
||||
return ScriptBuilder.createEmpty();
|
||||
} else if (ScriptPattern.isP2PK(this)) {
|
||||
return ScriptBuilder.createInputScript(null);
|
||||
} else if (ScriptPattern.isP2SH(this)) {
|
||||
checkArgument(redeemScript != null, "Redeem script required to create P2SH input script");
|
||||
checkArgument(redeemScript != null, () ->
|
||||
"redeem script required to create P2SH input script");
|
||||
return ScriptBuilder.createP2SHMultiSigInputScript(null, redeemScript);
|
||||
} else {
|
||||
throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Do not understand script type: " + this);
|
||||
|
@ -533,7 +535,8 @@ public class Script {
|
|||
|
||||
public TransactionWitness createEmptyWitness(ECKey key) {
|
||||
if (ScriptPattern.isP2WPKH(this)) {
|
||||
checkArgument(key != null, "Key required to create P2WPKH witness");
|
||||
checkArgument(key != null, () ->
|
||||
"key required to create P2WPKH witness");
|
||||
return TransactionWitness.EMPTY;
|
||||
} else if (ScriptPattern.isP2PK(this) || ScriptPattern.isP2PKH(this)
|
||||
|| ScriptPattern.isP2SH(this)) {
|
||||
|
@ -664,8 +667,8 @@ public class Script {
|
|||
}
|
||||
|
||||
public static int decodeFromOpN(int opcode) {
|
||||
checkArgument((opcode == OP_0 || opcode == OP_1NEGATE) || (opcode >= OP_1 && opcode <= OP_16),
|
||||
"decodeFromOpN called on non OP_N opcode: %s", ScriptOpCodes.getOpCodeName(opcode));
|
||||
checkArgument((opcode == OP_0 || opcode == OP_1NEGATE) || (opcode >= OP_1 && opcode <= OP_16), () ->
|
||||
"decodeFromOpN called on non OP_N opcode: " + ScriptOpCodes.getOpCodeName(opcode));
|
||||
if (opcode == OP_0)
|
||||
return 0;
|
||||
else if (opcode == OP_1NEGATE)
|
||||
|
@ -675,7 +678,8 @@ public class Script {
|
|||
}
|
||||
|
||||
public static int encodeToOpN(int value) {
|
||||
checkArgument(value >= -1 && value <= 16, "encodeToOpN called for " + value + " which we cannot encode in an opcode.");
|
||||
checkArgument(value >= -1 && value <= 16, () ->
|
||||
"encodeToOpN called for " + value + " which we cannot encode in an opcode");
|
||||
if (value == 0)
|
||||
return OP_0;
|
||||
else if (value == -1)
|
||||
|
@ -741,7 +745,8 @@ public class Script {
|
|||
public int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript) {
|
||||
if (ScriptPattern.isP2SH(this)) {
|
||||
// scriptSig: <sig> [sig] [sig...] <redeemscript>
|
||||
checkArgument(redeemScript != null, "P2SH script requires redeemScript to be spent");
|
||||
checkArgument(redeemScript != null, () ->
|
||||
"P2SH script requires redeemScript to be spent");
|
||||
return redeemScript.getNumberOfSignaturesRequiredToSpend() * SIG_SIZE + redeemScript.getProgram().length;
|
||||
} else if (ScriptPattern.isSentToMultisig(this)) {
|
||||
// scriptSig: OP_0 <sig> [sig] [sig...]
|
||||
|
|
|
@ -36,8 +36,8 @@ import java.util.LinkedList;
|
|||
import java.util.List;
|
||||
import java.util.Stack;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
import static org.bitcoinj.script.ScriptOpCodes.OP_0;
|
||||
import static org.bitcoinj.script.ScriptOpCodes.OP_1NEGATE;
|
||||
import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKMULTISIG;
|
||||
|
@ -174,8 +174,10 @@ public class ScriptBuilder {
|
|||
* @see #number(long)
|
||||
*/
|
||||
public ScriptBuilder smallNum(int index, int num) {
|
||||
checkArgument(num >= 0, "Cannot encode negative numbers with smallNum");
|
||||
checkArgument(num <= 16, "Cannot encode numbers larger than 16 with smallNum");
|
||||
checkArgument(num >= 0, () ->
|
||||
"cannot encode negative numbers with smallNum");
|
||||
checkArgument(num <= 16, () ->
|
||||
"cannot encode numbers larger than 16 with smallNum");
|
||||
return addChunk(index, new ScriptChunk(Script.encodeToOpN(num), null));
|
||||
}
|
||||
|
||||
|
@ -399,7 +401,8 @@ public class ScriptBuilder {
|
|||
// We assume here that OP_0 placeholders always go after the sigs, so
|
||||
// to find if we have sigs missing, we can just check the chunk in latest sig position
|
||||
boolean hasMissingSigs = inputChunks.get(totalChunks - sigsSuffixCount - 1).equalsOpCode(OP_0);
|
||||
checkArgument(hasMissingSigs, "ScriptSig is already filled with signatures");
|
||||
checkArgument(hasMissingSigs, () ->
|
||||
"scriptSig is already filled with signatures");
|
||||
|
||||
// copy the prefix
|
||||
for (ScriptChunk chunk: inputChunks.subList(0, sigsPrefixCount))
|
||||
|
|
|
@ -26,7 +26,7 @@ import java.io.OutputStream;
|
|||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
import static org.bitcoinj.script.ScriptOpCodes.OP_0;
|
||||
import static org.bitcoinj.script.ScriptOpCodes.OP_1;
|
||||
import static org.bitcoinj.script.ScriptOpCodes.OP_16;
|
||||
|
|
|
@ -41,8 +41,8 @@ import java.util.Map;
|
|||
import java.util.Objects;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
// TODO: Lose the mmap in this class. There are too many platform bugs that require odd workarounds.
|
||||
|
||||
|
@ -331,7 +331,8 @@ public class SPVBlockStore implements BlockStore {
|
|||
/** Returns the offset from the file start where the latest block should be written (end of prev block). */
|
||||
private int getRingCursor(ByteBuffer buffer) {
|
||||
int c = buffer.getInt(4);
|
||||
checkState(c >= FILE_PROLOGUE_BYTES, "Integer overflow");
|
||||
checkState(c >= FILE_PROLOGUE_BYTES, () ->
|
||||
"integer overflow");
|
||||
return c;
|
||||
}
|
||||
|
||||
|
|
|
@ -46,9 +46,9 @@ import java.nio.ByteBuffer;
|
|||
import java.time.Instant;
|
||||
import java.util.Random;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.Coin.COIN;
|
||||
import static org.bitcoinj.base.Coin.valueOf;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* Methods for building fake transactions for unit tests. Since these methods are currently used both in the `bitcoinj-core`
|
||||
|
|
|
@ -31,7 +31,7 @@ import java.util.List;
|
|||
import java.util.Locale;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
/**
|
||||
* <p>This class reads block files stored in the Bitcoin Core format. This is simply a way to concatenate
|
||||
|
@ -55,7 +55,8 @@ public class BlockFileLoader implements Iterable<Block>, Iterator<Block> {
|
|||
* Gets the list of files which contain blocks from Bitcoin Core.
|
||||
*/
|
||||
public static List<File> getReferenceClientBlockFileList(File blocksDir) {
|
||||
checkArgument(blocksDir.isDirectory(), "%s is not a directory", blocksDir);
|
||||
checkArgument(blocksDir.isDirectory(), () ->
|
||||
"not a directory: " + blocksDir);
|
||||
List<File> list = new LinkedList<>();
|
||||
for (int i = 0; true; i++) {
|
||||
File file = new File(blocksDir, String.format(Locale.US, "blk%05d.dat", i));
|
||||
|
|
|
@ -26,8 +26,8 @@ import java.util.List;
|
|||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.Coin.SMALLEST_UNIT_EXPONENT;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
/**
|
||||
* <p>This class, a concrete extension of {@link BtcFormat}, is distinguished in that each
|
||||
|
@ -79,10 +79,8 @@ public final class BtcFixedFormat extends BtcFormat {
|
|||
Locale locale, int scale, int minDecimals, List<Integer> groups
|
||||
) {
|
||||
super((DecimalFormat)NumberFormat.getInstance(locale), minDecimals, groups);
|
||||
checkArgument(
|
||||
scale <= SMALLEST_UNIT_EXPONENT,
|
||||
"decimal cannot be shifted " + String.valueOf(scale) + " places"
|
||||
);
|
||||
checkArgument(scale <= SMALLEST_UNIT_EXPONENT, () ->
|
||||
"decimal cannot be shifted " + String.valueOf(scale) + " places");
|
||||
this.scale = scale;
|
||||
}
|
||||
|
||||
|
|
|
@ -39,9 +39,9 @@ import java.util.Objects;
|
|||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static java.math.RoundingMode.HALF_UP;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
import static org.bitcoinj.utils.BtcAutoFormat.Style.CODE;
|
||||
import static org.bitcoinj.utils.BtcAutoFormat.Style.SYMBOL;
|
||||
|
||||
|
@ -747,7 +747,8 @@ public abstract class BtcFormat extends Format {
|
|||
|
||||
/** This single constructor is invoked by the overriding subclass constructors. */
|
||||
protected BtcFormat(DecimalFormat numberFormat, int minDecimals, List<Integer> groups) {
|
||||
checkArgument(minDecimals >= 0, "There can be no fewer than zero fractional decimal places");
|
||||
checkArgument(minDecimals >= 0, () ->
|
||||
"there can be no fewer than zero fractional decimal places");
|
||||
this.numberFormat = numberFormat;
|
||||
this.numberFormat.setParseBigDecimal(true);
|
||||
this.numberFormat.setRoundingMode(HALF_UP);
|
||||
|
@ -930,7 +931,8 @@ public abstract class BtcFormat extends Format {
|
|||
private static List<Integer> boxAsList(int[] elements) throws IllegalArgumentException {
|
||||
List<Integer> list = new ArrayList<>(elements.length);
|
||||
for (int e : elements) {
|
||||
checkArgument(e > 0, "Size of decimal group must be at least one.");
|
||||
checkArgument(e > 0, () ->
|
||||
"size of decimal group must be at least one.");
|
||||
list.add(e);
|
||||
}
|
||||
return list;
|
||||
|
@ -1186,7 +1188,8 @@ public abstract class BtcFormat extends Format {
|
|||
|
||||
private StringBuffer format(Object qty, StringBuffer toAppendTo, FieldPosition pos,
|
||||
int minDecimals, List<Integer> fractionGroups) {
|
||||
checkArgument(minDecimals >= 0, "There can be no fewer than zero fractional decimal places");
|
||||
checkArgument(minDecimals >= 0, () ->
|
||||
"there can be no fewer than zero fractional decimal places");
|
||||
synchronized (numberFormat) {
|
||||
DecimalFormatSymbols anteSigns = numberFormat.getDecimalFormatSymbols();
|
||||
BigDecimal denominatedUnitCount = denominateAndRound(inSatoshis(qty), minDecimals, fractionGroups);
|
||||
|
|
|
@ -22,7 +22,7 @@ import org.bitcoinj.base.Coin;
|
|||
import java.math.BigInteger;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
/**
|
||||
* An exchange rate is expressed as a ratio of a {@link Coin} and a {@link Fiat} amount.
|
||||
|
@ -36,7 +36,8 @@ public class ExchangeRate {
|
|||
public ExchangeRate(Coin coin, Fiat fiat) {
|
||||
checkArgument(coin.isPositive());
|
||||
checkArgument(fiat.isPositive());
|
||||
checkArgument(fiat.currencyCode != null, "currency code required");
|
||||
checkArgument(fiat.currencyCode != null, () ->
|
||||
"currency code required");
|
||||
this.coin = coin;
|
||||
this.fiat = fiat;
|
||||
}
|
||||
|
@ -65,8 +66,8 @@ public class ExchangeRate {
|
|||
* @throws ArithmeticException if the converted coin amount is too high or too low.
|
||||
*/
|
||||
public Coin fiatToCoin(Fiat convertFiat) {
|
||||
checkArgument(convertFiat.currencyCode.equals(fiat.currencyCode), "Currency mismatch: %s vs %s",
|
||||
convertFiat.currencyCode, fiat.currencyCode);
|
||||
checkArgument(convertFiat.currencyCode.equals(fiat.currencyCode), () ->
|
||||
"currency mismatch: " + convertFiat.currencyCode + " vs " + fiat.currencyCode);
|
||||
// Use BigInteger because it's much easier to maintain full precision without overflowing.
|
||||
final BigInteger converted = BigInteger.valueOf(convertFiat.value).multiply(BigInteger.valueOf(coin.value))
|
||||
.divide(BigInteger.valueOf(fiat.value));
|
||||
|
|
|
@ -21,7 +21,7 @@ import org.bitcoinj.base.internal.TimeUtils;
|
|||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
/**
|
||||
* <p>Tracks successes and failures and calculates a time to retry the operation.</p>
|
||||
|
@ -51,8 +51,10 @@ public class ExponentialBackoff implements Comparable<ExponentialBackoff> {
|
|||
* @param maximumInterval the maximum interval to wait
|
||||
*/
|
||||
public Params(Duration initialInterval, float multiplier, Duration maximumInterval) {
|
||||
checkArgument(multiplier > 1.0f, "multiplier must be greater than 1.0");
|
||||
checkArgument(maximumInterval.compareTo(initialInterval) >= 0, "maximum must not be less than initial");
|
||||
checkArgument(multiplier > 1.0f, () ->
|
||||
"multiplier must be greater than 1.0: " + multiplier);
|
||||
checkArgument(maximumInterval.compareTo(initialInterval) >= 0, () ->
|
||||
"maximum must not be less than initial: " + maximumInterval);
|
||||
|
||||
this.initialInterval = initialInterval;
|
||||
this.multiplier = multiplier;
|
||||
|
|
|
@ -47,8 +47,8 @@ import java.util.concurrent.Executor;
|
|||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* A {@link KeyChain} that implements the simplest model possible: it can have keys imported into it, and just acts as
|
||||
|
@ -396,7 +396,8 @@ public class BasicKeyChain implements EncryptableKeyChain {
|
|||
private void deserializeFromProtobuf(List<Protos.Key> keys) throws UnreadableWalletException {
|
||||
lock.lock();
|
||||
try {
|
||||
checkState(hashToKeys.isEmpty(), "Tried to deserialize into a non-empty chain");
|
||||
checkState(hashToKeys.isEmpty(), () ->
|
||||
"tried to deserialize into a non-empty chain");
|
||||
for (Protos.Key key : keys) {
|
||||
if (key.getType() != Protos.Key.Type.ORIGINAL && key.getType() != Protos.Key.Type.ENCRYPTED_SCRYPT_AES)
|
||||
continue;
|
||||
|
@ -407,7 +408,8 @@ public class BasicKeyChain implements EncryptableKeyChain {
|
|||
byte[] pub = key.getPublicKey().toByteArray();
|
||||
ECKey ecKey;
|
||||
if (encrypted) {
|
||||
checkState(keyCrypter != null, "This wallet is encrypted but encrypt() was not called prior to deserialization");
|
||||
checkState(keyCrypter != null, () ->
|
||||
"this wallet is encrypted but encrypt() was not called prior to deserialization");
|
||||
if (!key.hasEncryptedData())
|
||||
throw new UnreadableWalletException("Encrypted private key data missing");
|
||||
Protos.EncryptedData proto = key.getEncryptedData();
|
||||
|
@ -495,7 +497,8 @@ public class BasicKeyChain implements EncryptableKeyChain {
|
|||
lock.lock();
|
||||
try {
|
||||
Objects.requireNonNull(keyCrypter);
|
||||
checkState(this.keyCrypter == null, "Key chain is already encrypted");
|
||||
checkState(this.keyCrypter == null, () ->
|
||||
"key chain is already encrypted");
|
||||
BasicKeyChain encrypted = new BasicKeyChain(keyCrypter);
|
||||
for (ECKey key : hashToKeys.values()) {
|
||||
ECKey encryptedKey = key.encrypt(keyCrypter, aesKey);
|
||||
|
@ -528,7 +531,8 @@ public class BasicKeyChain implements EncryptableKeyChain {
|
|||
public BasicKeyChain toDecrypted(AesKey aesKey) {
|
||||
lock.lock();
|
||||
try {
|
||||
checkState(keyCrypter != null, "Wallet is already decrypted");
|
||||
checkState(keyCrypter != null, () ->
|
||||
"wallet is already decrypted");
|
||||
// Do an up-front check.
|
||||
if (numKeys() > 0 && !checkAESKey(aesKey))
|
||||
throw new KeyCrypterException("Password/key was incorrect.");
|
||||
|
@ -552,7 +556,8 @@ public class BasicKeyChain implements EncryptableKeyChain {
|
|||
@Override
|
||||
public boolean checkPassword(CharSequence password) {
|
||||
Objects.requireNonNull(password);
|
||||
checkState(keyCrypter != null, "Key chain not encrypted");
|
||||
checkState(keyCrypter != null, () ->
|
||||
"key chain not encrypted");
|
||||
return checkAESKey(keyCrypter.deriveKey(password));
|
||||
}
|
||||
|
||||
|
@ -567,7 +572,8 @@ public class BasicKeyChain implements EncryptableKeyChain {
|
|||
try {
|
||||
// If no keys then cannot decrypt.
|
||||
if (hashToKeys.isEmpty()) return false;
|
||||
checkState(keyCrypter != null, "Key chain is not encrypted");
|
||||
checkState(keyCrypter != null, () ->
|
||||
"key chain is not encrypted");
|
||||
|
||||
// Find the first encrypted key in the wallet.
|
||||
ECKey first = null;
|
||||
|
@ -577,7 +583,8 @@ public class BasicKeyChain implements EncryptableKeyChain {
|
|||
break;
|
||||
}
|
||||
}
|
||||
checkState(first != null, "No encrypted keys in the wallet");
|
||||
checkState(first != null, () ->
|
||||
"no encrypted keys in the wallet");
|
||||
|
||||
try {
|
||||
ECKey rebornKey = first.decrypt(aesKey);
|
||||
|
|
|
@ -35,7 +35,7 @@ import java.time.Instant;
|
|||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>The default risk analysis. Currently, it only is concerned with whether a tx/dependency is non-final or not, and
|
||||
|
|
|
@ -63,8 +63,8 @@ import java.util.concurrent.locks.ReentrantLock;
|
|||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>A deterministic key chain is a {@link KeyChain} that uses the
|
||||
|
@ -262,7 +262,8 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
|||
* Creates a key chain that watches the given account key.
|
||||
*/
|
||||
public T watch(DeterministicKey accountKey) {
|
||||
checkState(accountPath == null, "either watch or accountPath");
|
||||
checkState(accountPath == null, () ->
|
||||
"either watch or accountPath");
|
||||
this.watchingKey = accountKey;
|
||||
this.isFollowing = false;
|
||||
return self();
|
||||
|
@ -273,7 +274,8 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
|||
* wallet following keychain represents "spouse". Watch key has to be an account key.
|
||||
*/
|
||||
public T watchAndFollow(DeterministicKey accountKey) {
|
||||
checkState(accountPath == null, "either watchAndFollow or accountPath");
|
||||
checkState(accountPath == null, () ->
|
||||
"either watchAndFollow or accountPath");
|
||||
this.watchingKey = accountKey;
|
||||
this.isFollowing = true;
|
||||
return self();
|
||||
|
@ -283,7 +285,8 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
|||
* Creates a key chain that can spend from the given account key.
|
||||
*/
|
||||
public T spend(DeterministicKey accountKey) {
|
||||
checkState(accountPath == null, "either spend or accountPath");
|
||||
checkState(accountPath == null, () ->
|
||||
"either spend or accountPath");
|
||||
this.spendingKey = accountKey;
|
||||
this.isFollowing = false;
|
||||
return self();
|
||||
|
@ -305,13 +308,15 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
|||
* Use an account path other than the default {@link DeterministicKeyChain#ACCOUNT_ZERO_PATH}.
|
||||
*/
|
||||
public T accountPath(List<ChildNumber> accountPath) {
|
||||
checkState(watchingKey == null, "either watch or accountPath");
|
||||
checkState(watchingKey == null, () ->
|
||||
"either watch or accountPath");
|
||||
this.accountPath = HDPath.M(Objects.requireNonNull(accountPath));
|
||||
return self();
|
||||
}
|
||||
|
||||
public DeterministicKeyChain build() {
|
||||
checkState(passphrase == null || seed == null, "Passphrase must not be specified with seed");
|
||||
checkState(passphrase == null || seed == null, () ->
|
||||
"passphrase must not be specified with seed");
|
||||
|
||||
if (accountPath == null)
|
||||
accountPath = ACCOUNT_ZERO_PATH;
|
||||
|
@ -360,10 +365,13 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
|||
public DeterministicKeyChain(DeterministicKey key, boolean isFollowing, boolean isWatching,
|
||||
ScriptType outputScriptType) {
|
||||
if (isWatching)
|
||||
checkArgument(key.isPubKeyOnly(), "Private subtrees not currently supported for watching keys: if you got this key from DKC.getWatchingKey() then use .dropPrivate().dropParent() on it first.");
|
||||
checkArgument(key.isPubKeyOnly(), () ->
|
||||
"private subtrees not currently supported for watching keys: if you got this key from DKC.getWatchingKey() then use .dropPrivate().dropParent() on it first");
|
||||
else
|
||||
checkArgument(key.hasPrivKey(), "Private subtrees are required.");
|
||||
checkArgument(isWatching || !isFollowing, "Can only follow a key that is watched");
|
||||
checkArgument(key.hasPrivKey(), () ->
|
||||
"private subtrees are required");
|
||||
checkArgument(isWatching || !isFollowing, () ->
|
||||
"can only follow a key that is watched");
|
||||
|
||||
basicKeyChain = new BasicKeyChain();
|
||||
this.seed = null;
|
||||
|
@ -389,8 +397,8 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
|||
*/
|
||||
protected DeterministicKeyChain(DeterministicSeed seed, @Nullable KeyCrypter crypter,
|
||||
ScriptType outputScriptType, List<ChildNumber> accountPath) {
|
||||
checkArgument(outputScriptType == null || outputScriptType == ScriptType.P2PKH
|
||||
|| outputScriptType == ScriptType.P2WPKH, "Only P2PKH or P2WPKH allowed.");
|
||||
checkArgument(outputScriptType == null || outputScriptType == ScriptType.P2PKH || outputScriptType == ScriptType.P2WPKH, () ->
|
||||
"only P2PKH or P2WPKH allowed");
|
||||
this.outputScriptType = outputScriptType != null ? outputScriptType : ScriptType.P2PKH;
|
||||
this.accountPath = HDPath.M(accountPath);
|
||||
this.seed = seed;
|
||||
|
@ -425,7 +433,8 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
|||
Objects.requireNonNull(chain.rootKey);
|
||||
Objects.requireNonNull(chain.seed);
|
||||
|
||||
checkArgument(!chain.rootKey.isEncrypted(), "Chain already encrypted");
|
||||
checkArgument(!chain.rootKey.isEncrypted(), () ->
|
||||
"chain already encrypted");
|
||||
this.accountPath = chain.getAccountPath();
|
||||
this.outputScriptType = chain.outputScriptType;
|
||||
|
||||
|
@ -1028,7 +1037,8 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
|||
public DeterministicKeyChain toEncrypted(CharSequence password) {
|
||||
Objects.requireNonNull(password);
|
||||
checkArgument(password.length() > 0);
|
||||
checkState(seed != null, "Attempt to encrypt a watching chain.");
|
||||
checkState(seed != null, () ->
|
||||
"attempt to encrypt a watching chain");
|
||||
checkState(!seed.isEncrypted());
|
||||
KeyCrypter scrypt = new KeyCrypterScrypt();
|
||||
AesKey derivedKey = scrypt.deriveKey(password);
|
||||
|
@ -1045,15 +1055,18 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
|||
Objects.requireNonNull(password);
|
||||
checkArgument(password.length() > 0);
|
||||
KeyCrypter crypter = getKeyCrypter();
|
||||
checkState(crypter != null, "Chain not encrypted");
|
||||
checkState(crypter != null, () ->
|
||||
"chain not encrypted");
|
||||
AesKey derivedKey = crypter.deriveKey(password);
|
||||
return toDecrypted(derivedKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeterministicKeyChain toDecrypted(AesKey aesKey) {
|
||||
checkState(getKeyCrypter() != null, "Key chain not encrypted");
|
||||
checkState(seed != null, "Can't decrypt a watching chain");
|
||||
checkState(getKeyCrypter() != null, () ->
|
||||
"key chain not encrypted");
|
||||
checkState(seed != null, () ->
|
||||
"can't decrypt a watching chain");
|
||||
checkState(seed.isEncrypted());
|
||||
String passphrase = DEFAULT_PASSPHRASE_FOR_MNEMONIC; // FIXME allow non-empty passphrase
|
||||
DeterministicSeed decSeed = seed.decrypt(getKeyCrypter(), passphrase, aesKey);
|
||||
|
@ -1089,15 +1102,18 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
|||
@Override
|
||||
public boolean checkPassword(CharSequence password) {
|
||||
Objects.requireNonNull(password);
|
||||
checkState(getKeyCrypter() != null, "Key chain not encrypted");
|
||||
checkState(getKeyCrypter() != null, () ->
|
||||
"key chain not encrypted");
|
||||
return checkAESKey(getKeyCrypter().deriveKey(password));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean checkAESKey(AesKey aesKey) {
|
||||
checkState(rootKey != null, "Can't check password for a watching chain");
|
||||
checkState(rootKey != null, () ->
|
||||
"can't check password for a watching chain");
|
||||
Objects.requireNonNull(aesKey);
|
||||
checkState(getKeyCrypter() != null, "Key chain not encrypted");
|
||||
checkState(getKeyCrypter() != null, () ->
|
||||
"key chain not encrypted");
|
||||
try {
|
||||
return rootKey.decrypt(aesKey).getPubKeyPoint().equals(rootKey.getPubKeyPoint());
|
||||
} catch (KeyCrypterException e) {
|
||||
|
|
|
@ -36,10 +36,11 @@ import java.util.List;
|
|||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import org.bitcoinj.base.internal.ByteUtils;
|
||||
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* Holds the seed bytes for the BIP32 deterministic wallet algorithm, inside a
|
||||
* {@link DeterministicKeyChain}. The purpose of this wrapper is to simplify the encryption
|
||||
|
@ -188,7 +189,7 @@ public class DeterministicSeed implements EncryptableItem {
|
|||
|
||||
/** Internal use only. */
|
||||
private DeterministicSeed(byte[] entropy, String passphrase, @Nullable Instant creationTime) {
|
||||
checkArgument(entropy.length * 8 >= DEFAULT_SEED_ENTROPY_BITS, "entropy size too small");
|
||||
checkArgument(entropy.length * 8 >= DEFAULT_SEED_ENTROPY_BITS, () -> "entropy size too small");
|
||||
Objects.requireNonNull(passphrase);
|
||||
|
||||
this.mnemonicCode = MnemonicCode.INSTANCE.toMnemonic(entropy);
|
||||
|
@ -205,7 +206,8 @@ public class DeterministicSeed implements EncryptableItem {
|
|||
}
|
||||
|
||||
private static byte[] getEntropy(SecureRandom random, int bits) {
|
||||
checkArgument(bits <= MAX_SEED_ENTROPY_BITS, "requested entropy size too large");
|
||||
checkArgument(bits <= MAX_SEED_ENTROPY_BITS, () ->
|
||||
"requested entropy size too large");
|
||||
|
||||
byte[] seed = new byte[bits / 8];
|
||||
random.nextBytes(seed);
|
||||
|
@ -300,8 +302,10 @@ public class DeterministicSeed implements EncryptableItem {
|
|||
}
|
||||
|
||||
public DeterministicSeed encrypt(KeyCrypter keyCrypter, AesKey aesKey) {
|
||||
checkState(encryptedMnemonicCode == null, "Trying to encrypt seed twice");
|
||||
checkState(mnemonicCode != null, "Mnemonic missing so cannot encrypt");
|
||||
checkState(encryptedMnemonicCode == null, () ->
|
||||
"trying to encrypt seed twice");
|
||||
checkState(mnemonicCode != null, () ->
|
||||
"mnemonic missing so cannot encrypt");
|
||||
EncryptedData encryptedMnemonic = keyCrypter.encrypt(getMnemonicAsBytes(), aesKey);
|
||||
EncryptedData encryptedSeed = keyCrypter.encrypt(seed, aesKey);
|
||||
return new DeterministicSeed(encryptedMnemonic, encryptedSeed, creationTime);
|
||||
|
|
|
@ -58,8 +58,8 @@ import java.util.concurrent.Executor;
|
|||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>A KeyChainGroup is used by the {@link Wallet} and manages: a {@link BasicKeyChain} object
|
||||
|
@ -322,7 +322,8 @@ public class KeyChainGroup implements KeyBag {
|
|||
* Useful for adding a complex pre-configured keychain, such as a married wallet.
|
||||
*/
|
||||
public void addAndActivateHDChain(DeterministicKeyChain chain) {
|
||||
checkState(supportsDeterministicChains(), "doesn't support deterministic chains");
|
||||
checkState(supportsDeterministicChains(), () ->
|
||||
"doesn't support deterministic chains");
|
||||
log.info("Activating a new HD chain: {}", chain);
|
||||
for (ListenerRegistration<KeyChainEventListener> registration : basic.getListeners())
|
||||
chain.addEventListener(registration.listener, registration.executor);
|
||||
|
@ -464,7 +465,8 @@ public class KeyChainGroup implements KeyBag {
|
|||
* @param keyRotationTime key rotation to take into account
|
||||
*/
|
||||
public List<DeterministicKeyChain> getActiveKeyChains(@Nullable Instant keyRotationTime) {
|
||||
checkState(supportsDeterministicChains(), "doesn't support deterministic chains");
|
||||
checkState(supportsDeterministicChains(), () ->
|
||||
"doesn't support deterministic chains");
|
||||
List<DeterministicKeyChain> activeChains = new LinkedList<>();
|
||||
for (DeterministicKeyChain chain : chains)
|
||||
if (keyRotationTime == null || chain.earliestKeyCreationTime().compareTo(keyRotationTime) >= 0)
|
||||
|
@ -484,7 +486,8 @@ public class KeyChainGroup implements KeyBag {
|
|||
* type and no active chain for this type exists, {@code null} is returned. No upgrade or downgrade is tried.
|
||||
*/
|
||||
public final DeterministicKeyChain getActiveKeyChain(ScriptType outputScriptType, Instant keyRotationTime) {
|
||||
checkState(supportsDeterministicChains(), "doesn't support deterministic chains");
|
||||
checkState(supportsDeterministicChains(), () ->
|
||||
"doesn't support deterministic chains");
|
||||
List<DeterministicKeyChain> chainsReversed = new ArrayList<>(chains);
|
||||
Collections.reverse(chainsReversed);
|
||||
for (DeterministicKeyChain chain : chainsReversed)
|
||||
|
@ -507,7 +510,8 @@ public class KeyChainGroup implements KeyBag {
|
|||
* tried.
|
||||
*/
|
||||
public final DeterministicKeyChain getActiveKeyChain() {
|
||||
checkState(supportsDeterministicChains(), "doesn't support deterministic chains");
|
||||
checkState(supportsDeterministicChains(), () ->
|
||||
"doesn't support deterministic chains");
|
||||
if (chains.isEmpty())
|
||||
throw new DeterministicUpgradeRequiredException();
|
||||
return chains.get(chains.size() - 1);
|
||||
|
@ -517,7 +521,8 @@ public class KeyChainGroup implements KeyBag {
|
|||
* Merge all active chains from the given keychain group into this keychain group.
|
||||
*/
|
||||
public final void mergeActiveKeyChains(KeyChainGroup from, Instant keyRotationTime) {
|
||||
checkArgument(isEncrypted() == from.isEncrypted(), "encrypted and non-encrypted keychains cannot be mixed");
|
||||
checkArgument(isEncrypted() == from.isEncrypted(), () ->
|
||||
"encrypted and non-encrypted keychains cannot be mixed");
|
||||
for (DeterministicKeyChain chain : from.getActiveKeyChains(keyRotationTime))
|
||||
addAndActivateHDChain(chain);
|
||||
}
|
||||
|
@ -535,7 +540,8 @@ public class KeyChainGroup implements KeyBag {
|
|||
* for more information.
|
||||
*/
|
||||
public int getLookaheadSize() {
|
||||
checkState(supportsDeterministicChains(), "doesn't support deterministic chains");
|
||||
checkState(supportsDeterministicChains(), () ->
|
||||
"doesn't support deterministic chains");
|
||||
if (lookaheadSize == -1)
|
||||
return getActiveKeyChain().getLookaheadSize();
|
||||
else
|
||||
|
@ -548,7 +554,8 @@ public class KeyChainGroup implements KeyBag {
|
|||
* for more information.
|
||||
*/
|
||||
public int getLookaheadThreshold() {
|
||||
checkState(supportsDeterministicChains(), "doesn't support deterministic chains");
|
||||
checkState(supportsDeterministicChains(), () ->
|
||||
"doesn't support deterministic chains");
|
||||
if (lookaheadThreshold == -1)
|
||||
return getActiveKeyChain().getLookaheadThreshold();
|
||||
else
|
||||
|
@ -566,12 +573,14 @@ public class KeyChainGroup implements KeyBag {
|
|||
}
|
||||
|
||||
public boolean checkPassword(CharSequence password) {
|
||||
checkState(keyCrypter != null, "Not encrypted");
|
||||
checkState(keyCrypter != null, () ->
|
||||
"not encrypted");
|
||||
return checkAESKey(keyCrypter.deriveKey(password));
|
||||
}
|
||||
|
||||
public boolean checkAESKey(AesKey aesKey) {
|
||||
checkState(keyCrypter != null, "Not encrypted");
|
||||
checkState(keyCrypter != null, () ->
|
||||
"not encrypted");
|
||||
if (basic.numKeys() > 0)
|
||||
return basic.checkAESKey(aesKey);
|
||||
return getActiveKeyChain().checkAESKey(aesKey);
|
||||
|
@ -580,7 +589,8 @@ public class KeyChainGroup implements KeyBag {
|
|||
/** Imports the given unencrypted keys into the basic chain, encrypting them along the way with the given key. */
|
||||
public int importKeysAndEncrypt(final List<ECKey> keys, AesKey aesKey) {
|
||||
// TODO: Firstly check if the aes key can decrypt any of the existing keys successfully.
|
||||
checkState(keyCrypter != null, "Not encrypted");
|
||||
checkState(keyCrypter != null, () ->
|
||||
"not encrypted");
|
||||
LinkedList<ECKey> encryptedKeys = new LinkedList<>();
|
||||
for (ECKey key : keys) {
|
||||
if (key.isEncrypted())
|
||||
|
@ -760,7 +770,8 @@ public class KeyChainGroup implements KeyBag {
|
|||
public void encrypt(KeyCrypter keyCrypter, AesKey aesKey) {
|
||||
Objects.requireNonNull(keyCrypter);
|
||||
Objects.requireNonNull(aesKey);
|
||||
checkState((chains != null && !chains.isEmpty()) || basic.numKeys() != 0, "can't encrypt entirely empty wallet");
|
||||
checkState((chains != null && !chains.isEmpty()) || basic.numKeys() != 0, () ->
|
||||
"can't encrypt entirely empty wallet");
|
||||
|
||||
BasicKeyChain newBasic = basic.toEncrypted(keyCrypter, aesKey);
|
||||
List<DeterministicKeyChain> newChains = new ArrayList<>();
|
||||
|
@ -1024,7 +1035,8 @@ public class KeyChainGroup implements KeyBag {
|
|||
public void upgradeToDeterministic(ScriptType preferredScriptType, KeyChainGroupStructure structure,
|
||||
@Nullable Instant keyRotationTime, @Nullable AesKey aesKey)
|
||||
throws DeterministicUpgradeRequiresPassword {
|
||||
checkState(supportsDeterministicChains(), "doesn't support deterministic chains");
|
||||
checkState(supportsDeterministicChains(), () ->
|
||||
"doesn't support deterministic chains");
|
||||
Objects.requireNonNull(structure);
|
||||
if (!isDeterministicUpgradeRequired(preferredScriptType, keyRotationTime))
|
||||
return; // Nothing to do.
|
||||
|
@ -1131,7 +1143,8 @@ public class KeyChainGroup implements KeyBag {
|
|||
|
||||
/** Returns a copy of the current list of chains. */
|
||||
public List<DeterministicKeyChain> getDeterministicKeyChains() {
|
||||
checkState(supportsDeterministicChains(), "doesn't support deterministic chains");
|
||||
checkState(supportsDeterministicChains(), () ->
|
||||
"doesn't support deterministic chains");
|
||||
return new ArrayList<>(chains);
|
||||
}
|
||||
/**
|
||||
|
@ -1139,7 +1152,8 @@ public class KeyChainGroup implements KeyBag {
|
|||
* lookahead and thus the Bloom filter that was previously calculated has become stale.
|
||||
*/
|
||||
public int getCombinedKeyLookaheadEpochs() {
|
||||
checkState(supportsDeterministicChains(), "doesn't support deterministic chains");
|
||||
checkState(supportsDeterministicChains(), () ->
|
||||
"doesn't support deterministic chains");
|
||||
int epoch = 0;
|
||||
for (DeterministicKeyChain chain : chains)
|
||||
epoch += chain.getKeyLookaheadEpoch();
|
||||
|
|
|
@ -40,8 +40,8 @@ import java.util.Objects;
|
|||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* <p>A multi-signature keychain using synchronized HD keys (a.k.a HDM)</p>
|
||||
|
@ -156,7 +156,8 @@ public class MarriedKeyChain extends DeterministicKeyChain {
|
|||
keys.add(followedKey);
|
||||
for (DeterministicKeyChain keyChain : followingKeyChains) {
|
||||
DeterministicKey followingKey = keyChain.getKey(purpose);
|
||||
checkState(followedKey.getChildNumber().equals(followingKey.getChildNumber()), "Following keychains should be in sync");
|
||||
checkState(followedKey.getChildNumber().equals(followingKey.getChildNumber()), () ->
|
||||
"following keychains should be in sync");
|
||||
keys.add(followingKey);
|
||||
}
|
||||
List<ECKey> marriedKeys = Collections.unmodifiableList(keys);
|
||||
|
@ -183,14 +184,17 @@ public class MarriedKeyChain extends DeterministicKeyChain {
|
|||
}
|
||||
|
||||
private void addFollowingAccountKeys(List<DeterministicKey> followingAccountKeys, int sigsRequiredToSpend) {
|
||||
checkArgument(sigsRequiredToSpend <= followingAccountKeys.size() + 1, "Multisig threshold can't exceed total number of keys");
|
||||
checkState(numLeafKeysIssued() == 0, "Active keychain already has keys in use");
|
||||
checkArgument(sigsRequiredToSpend <= followingAccountKeys.size() + 1, () ->
|
||||
"multisig threshold can't exceed total number of keys");
|
||||
checkState(numLeafKeysIssued() == 0, () ->
|
||||
"active keychain already has keys in use");
|
||||
checkState(followingKeyChains == null);
|
||||
|
||||
List<DeterministicKeyChain> followingKeyChains = new ArrayList<>();
|
||||
|
||||
for (DeterministicKey key : followingAccountKeys) {
|
||||
checkArgument(key.getPath().size() == getAccountPath().size(), "Following keys have to be account keys");
|
||||
checkArgument(key.getPath().size() == getAccountPath().size(), () ->
|
||||
"following keys have to be account keys");
|
||||
DeterministicKeyChain chain = DeterministicKeyChain.builder().watchAndFollow(key)
|
||||
.outputScriptType(getOutputScriptType()).build();
|
||||
if (lookaheadSize >= 0)
|
||||
|
@ -261,7 +265,8 @@ public class MarriedKeyChain extends DeterministicKeyChain {
|
|||
super.maybeLookAheadScripts();
|
||||
int numLeafKeys = getLeafKeys().size();
|
||||
|
||||
checkState(marriedKeysRedeemData.size() <= numLeafKeys, "Number of scripts is greater than number of leaf keys");
|
||||
checkState(marriedKeysRedeemData.size() <= numLeafKeys, () ->
|
||||
"number of scripts is greater than number of leaf keys");
|
||||
if (marriedKeysRedeemData.size() == numLeafKeys)
|
||||
return;
|
||||
|
||||
|
|
|
@ -26,7 +26,7 @@ import java.util.ArrayList;
|
|||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
/**
|
||||
* This class aggregates data required to spend transaction output.
|
||||
|
|
|
@ -139,8 +139,8 @@ import java.util.concurrent.TimeUnit;
|
|||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
// To do list:
|
||||
//
|
||||
|
@ -1417,7 +1417,8 @@ public class Wallet extends BaseTaggableObject
|
|||
keyChainGroupLock.lock();
|
||||
try {
|
||||
final KeyCrypter crypter = keyChainGroup.getKeyCrypter();
|
||||
checkState(crypter != null, "Not encrypted");
|
||||
checkState(crypter != null, () ->
|
||||
"not encrypted");
|
||||
keyChainGroup.decrypt(crypter.deriveKey(password));
|
||||
} catch (KeyCrypterException.InvalidCipherText | KeyCrypterException.PublicPrivateMismatch e) {
|
||||
throw new BadWalletEncryptionKeyException(e);
|
||||
|
@ -1705,7 +1706,8 @@ public class Wallet extends BaseTaggableObject
|
|||
public WalletFiles autosaveToFile(File f, Duration delay, @Nullable WalletFiles.Listener eventListener) {
|
||||
lock.lock();
|
||||
try {
|
||||
checkState(vFileManager == null, "Already auto saving this wallet.");
|
||||
checkState(vFileManager == null, () ->
|
||||
"already auto saving this wallet");
|
||||
WalletFiles manager = new WalletFiles(this, f, delay);
|
||||
if (eventListener != null)
|
||||
manager.setListener(eventListener);
|
||||
|
@ -1734,7 +1736,8 @@ public class Wallet extends BaseTaggableObject
|
|||
try {
|
||||
WalletFiles files = vFileManager;
|
||||
vFileManager = null;
|
||||
checkState(files != null, "Auto saving not enabled.");
|
||||
checkState(files != null, () ->
|
||||
"auto saving not enabled");
|
||||
files.shutdownAndWait();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
|
@ -2865,7 +2868,8 @@ public class Wallet extends BaseTaggableObject
|
|||
* @throws VerificationException if transaction was already in the pending pool
|
||||
*/
|
||||
public void commitTx(Transaction tx) throws VerificationException {
|
||||
checkArgument(maybeCommitTx(tx), "commitTx called on the same transaction twice");
|
||||
checkArgument(maybeCommitTx(tx), () ->
|
||||
"commitTx called on the same transaction twice");
|
||||
}
|
||||
|
||||
//endregion
|
||||
|
@ -4245,7 +4249,8 @@ public class Wallet extends BaseTaggableObject
|
|||
public SendResult sendCoins(SendRequest request)
|
||||
throws InsufficientMoneyException, BadWalletEncryptionKeyException {
|
||||
TransactionBroadcaster broadcaster = vTransactionBroadcaster;
|
||||
checkState(broadcaster != null, "No transaction broadcaster is configured");
|
||||
checkState(broadcaster != null, () ->
|
||||
"no transaction broadcaster is configured");
|
||||
return sendCoins(broadcaster, request);
|
||||
}
|
||||
|
||||
|
@ -4327,7 +4332,8 @@ public class Wallet extends BaseTaggableObject
|
|||
public void completeTx(SendRequest req) throws InsufficientMoneyException, BadWalletEncryptionKeyException {
|
||||
lock.lock();
|
||||
try {
|
||||
checkArgument(!req.completed, "Given SendRequest has already been completed.");
|
||||
checkArgument(!req.completed, () ->
|
||||
"given SendRequest has already been completed");
|
||||
// Calculate the amount of value we need to import.
|
||||
Coin value = req.tx.getOutputSum();
|
||||
|
||||
|
@ -4374,7 +4380,8 @@ public class Wallet extends BaseTaggableObject
|
|||
} else {
|
||||
// We're being asked to empty the wallet. What this means is ensuring "tx" has only a single output
|
||||
// of the total value we can currently spend as determined by the selector, and then subtracting the fee.
|
||||
checkState(req.tx.getOutputs().size() == 1, "Empty wallet TX must have a single output only.");
|
||||
checkState(req.tx.getOutputs().size() == 1, () ->
|
||||
"empty wallet TX must have a single output only");
|
||||
CoinSelector selector = req.coinSelector == null ? coinSelector : req.coinSelector;
|
||||
bestCoinSelection = selector.select((Coin) params.network().maxMoney(), candidates);
|
||||
candidates = null; // Selector took ownership and might have changed candidates. Don't access again.
|
||||
|
@ -5358,8 +5365,8 @@ public class Wallet extends BaseTaggableObject
|
|||
// is no inversion.
|
||||
for (Transaction tx : toBroadcast) {
|
||||
ConfidenceType confidenceType = tx.getConfidence().getConfidenceType();
|
||||
checkState(confidenceType == ConfidenceType.PENDING || confidenceType == ConfidenceType.IN_CONFLICT,
|
||||
"Tx %s: expected PENDING or IN_CONFLICT, was %s", tx.getTxId(), confidenceType);
|
||||
checkState(confidenceType == ConfidenceType.PENDING || confidenceType == ConfidenceType.IN_CONFLICT, () ->
|
||||
"Tx " + tx.getTxId() + ": expected PENDING or IN_CONFLICT, was " + confidenceType);
|
||||
// Re-broadcast even if it's marked as already seen for two reasons
|
||||
// 1) Old wallets may have transactions marked as broadcast by 1 peer when in reality the network
|
||||
// never saw it, due to bugs.
|
||||
|
@ -5389,9 +5396,8 @@ public class Wallet extends BaseTaggableObject
|
|||
* @param keyRotationTime rotate any keys created before this time, or null for no rotation
|
||||
*/
|
||||
public void setKeyRotationTime(@Nullable Instant keyRotationTime) {
|
||||
checkArgument(keyRotationTime == null || keyRotationTime.compareTo(TimeUtils.currentTime()) <= 0,
|
||||
"Given time (%s) cannot be in the future.",
|
||||
TimeUtils.dateTimeFormat(keyRotationTime));
|
||||
checkArgument(keyRotationTime == null || keyRotationTime.compareTo(TimeUtils.currentTime()) <= 0, () ->
|
||||
"given time cannot be in the future: " + TimeUtils.dateTimeFormat(keyRotationTime));
|
||||
vKeyRotationTime = keyRotationTime;
|
||||
saveNow();
|
||||
}
|
||||
|
|
|
@ -17,7 +17,6 @@
|
|||
|
||||
package org.bitcoinj.core;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.common.collect.Iterables;
|
||||
import org.bitcoinj.base.Sha256Hash;
|
||||
import org.bitcoinj.net.NioClient;
|
||||
|
@ -49,6 +48,8 @@ import java.util.Set;
|
|||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* A tool for comparing the blocks which are accepted/rejected by bitcoind/bitcoinj
|
||||
* It is designed to run as a testnet-in-a-box network between a single bitcoind node and bitcoinj
|
||||
|
@ -93,7 +94,7 @@ public class BitcoindComparisonTool {
|
|||
ver.localServices = VersionMessage.NODE_NETWORK;
|
||||
final Peer bitcoind = new Peer(PARAMS, ver, new PeerAddress(PARAMS, InetAddress.getLocalHost()),
|
||||
new BlockChain(PARAMS, new MemoryBlockStore(PARAMS)));
|
||||
Preconditions.checkState(bitcoind.getVersionMessage().hasBlockChain());
|
||||
checkState(bitcoind.getVersionMessage().hasBlockChain());
|
||||
|
||||
final BlockWrapper currentBlock = new BlockWrapper();
|
||||
|
||||
|
|
|
@ -16,7 +16,6 @@
|
|||
|
||||
package org.bitcoinj.core;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import org.bitcoinj.base.Coin;
|
||||
import org.bitcoinj.base.Sha256Hash;
|
||||
import org.bitcoinj.base.VarInt;
|
||||
|
@ -51,10 +50,11 @@ import java.util.Queue;
|
|||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.Coin.FIFTY_COINS;
|
||||
import static org.bitcoinj.base.Coin.SATOSHI;
|
||||
import static org.bitcoinj.base.Coin.ZERO;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
import static org.bitcoinj.script.ScriptOpCodes.OP_1;
|
||||
import static org.bitcoinj.script.ScriptOpCodes.OP_2DUP;
|
||||
import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKMULTISIG;
|
||||
|
@ -1514,7 +1514,7 @@ public class FullBlockTestGenerator {
|
|||
// b83 creates a tx which contains a transaction script with an invalid opcode in a dead execution path:
|
||||
// OP_FALSE OP_IF OP_INVALIDOPCODE OP_ELSE OP_TRUE OP_ENDIF
|
||||
//
|
||||
TransactionOutPointWithValue out28 = spendableOutputs.poll(); Preconditions.checkState(out28 != null);
|
||||
TransactionOutPointWithValue out28 = spendableOutputs.poll(); checkState(out28 != null);
|
||||
|
||||
NewBlock b83 = createNextBlock(b82, chainHeadHeight + 29, null, null);
|
||||
{
|
||||
|
@ -1537,10 +1537,10 @@ public class FullBlockTestGenerator {
|
|||
// -> b81 (26) -> b82 (27) -> b83 (28) -> b84 (29) -> b87 (30) -> b88 (31)
|
||||
// \-> b85 (29) -> b86 (30) \-> b89 (32)
|
||||
//
|
||||
TransactionOutPointWithValue out29 = spendableOutputs.poll(); Preconditions.checkState(out29 != null);
|
||||
TransactionOutPointWithValue out30 = spendableOutputs.poll(); Preconditions.checkState(out30 != null);
|
||||
TransactionOutPointWithValue out31 = spendableOutputs.poll(); Preconditions.checkState(out31 != null);
|
||||
TransactionOutPointWithValue out32 = spendableOutputs.poll(); Preconditions.checkState(out32 != null);
|
||||
TransactionOutPointWithValue out29 = spendableOutputs.poll(); checkState(out29 != null);
|
||||
TransactionOutPointWithValue out30 = spendableOutputs.poll(); checkState(out30 != null);
|
||||
TransactionOutPointWithValue out31 = spendableOutputs.poll(); checkState(out31 != null);
|
||||
TransactionOutPointWithValue out32 = spendableOutputs.poll(); checkState(out32 != null);
|
||||
|
||||
NewBlock b84 = createNextBlock(b83, chainHeadHeight + 30, out29, null);
|
||||
Transaction b84tx1 = new Transaction(params);
|
||||
|
@ -1671,7 +1671,7 @@ public class FullBlockTestGenerator {
|
|||
|
||||
if (runExpensiveTests) {
|
||||
// No way you can fit this test in memory
|
||||
Preconditions.checkArgument(blockStorageFile != null);
|
||||
checkArgument(blockStorageFile != null);
|
||||
|
||||
NewBlock lastBlock = b1001;
|
||||
TransactionOutPoint lastOutput = new TransactionOutPoint(params, 1, b1001.block.getTransactions().get(1).getTxId());
|
||||
|
|
|
@ -21,7 +21,7 @@ import org.bitcoinj.wallet.WalletExtension;
|
|||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
public class FooWalletExtension implements WalletExtension {
|
||||
private final byte[] data = {1, 2, 3};
|
||||
|
|
|
@ -42,8 +42,8 @@ import java.util.Arrays;
|
|||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.Coin.COIN;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA1;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
|
|
@ -60,8 +60,8 @@ import java.util.concurrent.CompletableFuture;
|
|||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* Utility class that makes it easy to work with mock NetworkConnections.
|
||||
|
|
|
@ -16,7 +16,6 @@
|
|||
|
||||
package org.bitcoinj.testing;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
|
||||
import com.google.common.util.concurrent.MoreExecutors;
|
||||
import org.bitcoinj.base.internal.TimeUtils;
|
||||
|
@ -45,8 +44,8 @@ import java.util.concurrent.ScheduledThreadPoolExecutor;
|
|||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* You can derive from this class and call peerGroup.start() in your tests to get a functional PeerGroup that can be
|
||||
|
@ -133,7 +132,7 @@ public class TestWithPeerGroup extends TestWithNetworkConnections {
|
|||
}
|
||||
|
||||
protected InboundMessageQueuer connectPeerWithoutVersionExchange(int id) throws Exception {
|
||||
Preconditions.checkArgument(id < PEER_SERVERS);
|
||||
checkArgument(id < PEER_SERVERS);
|
||||
InetSocketAddress remoteAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), TCP_PORT_BASE + id);
|
||||
Peer peer = peerGroup.connectTo(remoteAddress).getConnectionOpenFuture().get();
|
||||
InboundMessageQueuer writeTarget = newPeerWriteTargetQueue.take();
|
||||
|
|
|
@ -21,17 +21,18 @@ import org.bitcoinj.params.MainNetParams;
|
|||
import org.bitcoinj.params.TestNet3Params;
|
||||
import org.bitcoinj.store.*;
|
||||
import org.bitcoinj.utils.BlockFileLoader;
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
|
||||
|
||||
/** Very thin wrapper around {@link BlockFileLoader} */
|
||||
public class BlockImporter {
|
||||
public static void main(String[] args) throws BlockStoreException, VerificationException, PrunedException {
|
||||
System.out.println("USAGE: BlockImporter (prod|test) (Disk|MemFull|Mem|SPV) [blockStore]");
|
||||
System.out.println(" blockStore is required unless type is Mem or MemFull");
|
||||
System.out.println(" Does full verification if the store supports it");
|
||||
Preconditions.checkArgument(args.length == 2 || args.length == 3);
|
||||
checkArgument(args.length == 2 || args.length == 3);
|
||||
|
||||
NetworkParameters params;
|
||||
if (args[0].equals("test"))
|
||||
|
@ -42,15 +43,15 @@ public class BlockImporter {
|
|||
BlockStore store;
|
||||
switch (args[1]) {
|
||||
case "MemFull":
|
||||
Preconditions.checkArgument(args.length == 2);
|
||||
checkArgument(args.length == 2);
|
||||
store = new MemoryFullPrunedBlockStore(params, 100);
|
||||
break;
|
||||
case "Mem":
|
||||
Preconditions.checkArgument(args.length == 2);
|
||||
checkArgument(args.length == 2);
|
||||
store = new MemoryBlockStore(params);
|
||||
break;
|
||||
case "SPV":
|
||||
Preconditions.checkArgument(args.length == 3);
|
||||
checkArgument(args.length == 3);
|
||||
store = new SPVBlockStore(params, new File(args[2]));
|
||||
break;
|
||||
default:
|
||||
|
|
|
@ -49,8 +49,8 @@ import java.util.TreeMap;
|
|||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static java.util.concurrent.TimeUnit.SECONDS;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
|
||||
/**
|
||||
* Downloads and verifies a full chain from your local peer, emitting checkpoints at each difficulty transition period
|
||||
|
|
|
@ -32,7 +32,7 @@ import java.io.IOException;
|
|||
import java.net.URL;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
import static org.bitcoinj.walletfx.utils.WTUtils.unchecked;
|
||||
|
||||
public class GuiUtils {
|
||||
|
|
|
@ -40,7 +40,7 @@ import org.bitcoinj.walletfx.controls.BitcoinAddressValidator;
|
|||
import org.bitcoinj.walletfx.utils.TextFieldValidator;
|
||||
import org.bitcoinj.walletfx.utils.WTUtils;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.bitcoinj.base.internal.Preconditions.checkState;
|
||||
import static org.bitcoinj.walletfx.utils.GuiUtils.*;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
|
Loading…
Add table
Reference in a new issue