Objects: migrate entire codebase to requireNonNull() from Guava Precondition.checkNotNull()

This has the added benefit of exception messages being evaluated on demand.
This commit is contained in:
Andreas Schildbach 2023-03-16 17:48:59 +01:00
parent 36c82a3cfb
commit 9ec245c259
60 changed files with 311 additions and 341 deletions

View file

@ -29,8 +29,6 @@ import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* <p>A Bitcoin address looks like 1MsScoe2fTJoq4ZPdQgqyhgWeoNamYPevy and is derived from an elliptic curve public key
* plus a set of network parameters. Not to be confused with a {@link org.bitcoinj.core.PeerAddress}
@ -66,8 +64,8 @@ public class LegacyAddress implements Address {
* 20-byte hash of pubkey or script
*/
private LegacyAddress(Network network, boolean p2sh, byte[] hash160) throws AddressFormatException {
this.network = normalizeNetwork(checkNotNull(network));
this.bytes = checkNotNull(hash160);
this.network = normalizeNetwork(Objects.requireNonNull(network));
this.bytes = Objects.requireNonNull(hash160);
if (hash160.length != 20)
throw new AddressFormatException.InvalidDataLength(
"Legacy addresses are 20 byte (160 bit) hashes, but got: " + hash160.length);

View file

@ -31,7 +31,6 @@ import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.bitcoinj.base.BitcoinNetwork.*;
/**
@ -184,9 +183,9 @@ public class SegwitAddress implements Address {
if (witnessVersion == 1 && witnessProgram.length != WITNESS_PROGRAM_LENGTH_TR)
throw new AddressFormatException.InvalidDataLength(
"Invalid length for address version 1: " + witnessProgram.length);
this.network = normalizeNetwork(checkNotNull(network));
this.network = normalizeNetwork(Objects.requireNonNull(network));
this.witnessVersion = (short) witnessVersion;
this.witnessProgram = checkNotNull(witnessProgram);
this.witnessProgram = Objects.requireNonNull(witnessProgram);
}
/**

View file

@ -47,13 +47,13 @@ import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
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.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
@ -727,7 +727,7 @@ public abstract class AbstractBlockChain {
sendTransactionsToListener(newStoredBlock, newBlockType, listener, 0, block.getTransactions(),
!first, falsePositives);
} else if (filteredTxHashList != null) {
checkNotNull(filteredTxn);
Objects.requireNonNull(filteredTxn);
// We must send transactions to listeners in the order they appeared in the block - thus we iterate over the
// set of hashes and call sendTransactionsToListener with individual txn when they have not already been
// seen in loose broadcasts - otherwise notifyTransactionIsInBlock on the hash.
@ -856,7 +856,7 @@ public abstract class AbstractBlockChain {
StoredBlock cursor = higher;
do {
results.add(cursor);
cursor = checkNotNull(cursor.getPrev(store), "Ran off the end of the chain");
cursor = Objects.requireNonNull(cursor.getPrev(store), "Ran off the end of the chain");
} while (!cursor.equals(lower));
return results;
}
@ -879,10 +879,10 @@ public abstract class AbstractBlockChain {
while (!currentChainCursor.equals(newChainCursor)) {
if (currentChainCursor.getHeight() > newChainCursor.getHeight()) {
currentChainCursor = currentChainCursor.getPrev(store);
checkNotNull(currentChainCursor, "Attempt to follow an orphan chain");
Objects.requireNonNull(currentChainCursor, "Attempt to follow an orphan chain");
} else {
newChainCursor = newChainCursor.getPrev(store);
checkNotNull(newChainCursor, "Attempt to follow an orphan chain");
Objects.requireNonNull(newChainCursor, "Attempt to follow an orphan chain");
}
}
return currentChainCursor;

View file

@ -18,7 +18,6 @@
package org.bitcoinj.core;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import org.bitcoinj.base.Address;
import org.bitcoinj.base.Coin;
import org.bitcoinj.base.Sha256Hash;
@ -49,6 +48,7 @@ import java.util.EnumSet;
import java.util.LinkedList;
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;
@ -379,7 +379,7 @@ public class Block extends Message {
public byte[] bitcoinSerialize() {
// we have completely cached byte array.
if (headerBytesValid && transactionBytesValid) {
Preconditions.checkNotNull(payload, "Bytes should never be null if headerBytesValid && transactionBytesValid");
Objects.requireNonNull(payload, "Bytes should never be null if headerBytesValid && transactionBytesValid");
if (length == payload.length) {
return payload;
} else {

View file

@ -46,10 +46,10 @@ import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
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.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.base.Preconditions.checkState;
@ -98,10 +98,10 @@ public class CheckpointManager {
/** Loads the checkpoints from the given stream */
public CheckpointManager(NetworkParameters params, @Nullable InputStream inputStream) throws IOException {
this.params = checkNotNull(params);
this.params = Objects.requireNonNull(params);
if (inputStream == null)
inputStream = openStream(params);
checkNotNull(inputStream);
Objects.requireNonNull(inputStream);
inputStream = new BufferedInputStream(inputStream);
inputStream.mark(1);
int first = inputStream.read();
@ -234,8 +234,8 @@ public class CheckpointManager {
*/
public static void checkpoint(NetworkParameters params, InputStream checkpoints, BlockStore store, Instant time)
throws IOException, BlockStoreException {
checkNotNull(params);
checkNotNull(store);
Objects.requireNonNull(params);
Objects.requireNonNull(store);
checkArgument(!(store instanceof FullPrunedBlockStore), "You cannot use checkpointing with a full store.");
time = time.minus(7, ChronoUnit.WEEKS);

View file

@ -22,7 +22,7 @@ import org.bitcoinj.wallet.SendRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
// TODO: Finish adding Context c'tors to all the different objects so we can start deprecating the versions that take NetworkParameters.
// TODO: Add a working directory notion to Context and make various subsystems that want to use files default to that directory (eg. Orchid, block stores, wallet, etc).
@ -173,7 +173,7 @@ public class Context {
* a {@link ContextPropagatingThreadFactory}.
*/
public static void propagate(Context context) {
slot.set(checkNotNull(context));
slot.set(Objects.requireNonNull(context));
}
/**

View file

@ -19,8 +19,7 @@ package org.bitcoinj.core;
import org.bitcoinj.base.Coin;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
/**
* Thrown to indicate that you don't have enough money available to perform the requested operation.
@ -40,6 +39,6 @@ public class InsufficientMoneyException extends Exception {
public InsufficientMoneyException(Coin missing, String message) {
super(message);
this.missing = checkNotNull(missing);
this.missing = Objects.requireNonNull(missing);
}
}

View file

@ -70,7 +70,6 @@ import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
@ -184,7 +183,7 @@ public class Peer extends PeerSocketHandler {
private final CompletableFuture<Peer> incomingVersionHandshakeFuture = new CompletableFuture<>();
private final CompletableFuture<Peer> versionHandshakeFuture = outgoingVersionHandshakeFuture
.thenCombine(incomingVersionHandshakeFuture, (peer1, peer2) -> {
checkNotNull(peer1);
Objects.requireNonNull(peer1);
checkState(peer1 == peer2);
return peer1;
});
@ -231,8 +230,8 @@ public class Peer extends PeerSocketHandler {
public Peer(NetworkParameters params, VersionMessage ver, PeerAddress remoteAddress,
@Nullable AbstractBlockChain chain, long requiredServices, int downloadTxDependencyDepth) {
super(params, remoteAddress);
this.params = Preconditions.checkNotNull(params);
this.versionMessage = Preconditions.checkNotNull(ver);
this.params = Objects.requireNonNull(params);
this.versionMessage = Objects.requireNonNull(ver);
this.vDownloadTxDependencyDepth = chain != null ? downloadTxDependencyDepth : 0;
this.blockChain = chain; // Allowed to be null.
this.requiredServices = requiredServices;
@ -971,7 +970,7 @@ public class Peer extends PeerSocketHandler {
lock.lock();
try {
if (downloadBlockBodies) {
final Block orphanRoot = checkNotNull(blockChain.getOrphanRoot(m.getHash()));
final Block orphanRoot = Objects.requireNonNull(blockChain.getOrphanRoot(m.getHash()));
blockChainDownloadLocked(orphanRoot.getHash());
} else {
log.info("Did not start chain download on solved block due to in-flight header download.");
@ -1073,7 +1072,7 @@ public class Peer extends PeerSocketHandler {
// no matter how many blocks are solved, and therefore that the (2) duplicate filtering can work.
lock.lock();
try {
final Block orphanRoot = checkNotNull(blockChain.getOrphanRoot(m.getHash()));
final Block orphanRoot = Objects.requireNonNull(blockChain.getOrphanRoot(m.getHash()));
blockChainDownloadLocked(orphanRoot.getHash());
} finally {
lock.unlock();
@ -1115,7 +1114,7 @@ public class Peer extends PeerSocketHandler {
// It is possible for the peer block height difference to be negative when blocks have been solved and broadcast
// since the time we first connected to the peer. However, it's weird and unexpected to receive a callback
// with negative "blocks left" in this case, so we clamp to zero so the API user doesn't have to think about it.
final int blocksLeft = Math.max(0, (int) vPeerVersionMessage.bestHeight - checkNotNull(blockChain).getBestChainHeight());
final int blocksLeft = Math.max(0, (int) vPeerVersionMessage.bestHeight - Objects.requireNonNull(blockChain).getBestChainHeight());
for (final ListenerRegistration<BlocksDownloadedEventListener> registration : blocksDownloadedEventListeners) {
registration.executor.execute(() -> registration.listener.onBlocksDownloaded(Peer.this, block, fb, blocksLeft));
}
@ -1205,7 +1204,7 @@ public class Peer extends PeerSocketHandler {
if (blockChain.isOrphan(item.hash) && downloadBlockBodies) {
// If an orphan was re-advertised, ask for more blocks unless we are not currently downloading
// full block data because we have a getheaders outstanding.
final Block orphanRoot = checkNotNull(blockChain.getOrphanRoot(item.hash));
final Block orphanRoot = Objects.requireNonNull(blockChain.getOrphanRoot(item.hash));
blockChainDownloadLocked(orphanRoot.getHash());
} else {
// Don't re-request blocks we already requested. Normally this should not happen. However there is
@ -1416,7 +1415,7 @@ public class Peer extends PeerSocketHandler {
// This is because it requires scanning all the block chain headers, which is very slow. Instead we add the top
// 100 block headers. If there is a re-org deeper than that, we'll end up downloading the entire chain. We
// must always put the genesis block as the first entry.
BlockStore store = checkNotNull(blockChain).getBlockStore();
BlockStore store = Objects.requireNonNull(blockChain).getBlockStore();
StoredBlock chainHead = blockChain.getChainHead();
Sha256Hash chainHeadHash = chainHead.getHeader().getHash();
// Did we already make this request? If so, don't do it again.
@ -1619,7 +1618,7 @@ public class Peer extends PeerSocketHandler {
* behind the peer, or negative if the peer is ahead of us.
*/
public int getPeerBlockHeightDifference() {
checkNotNull(blockChain, "No block chain configured");
Objects.requireNonNull(blockChain, "No block chain configured");
// Chain will overflow signed int blocks in ~41,000 years.
int chainHeight = (int) getBestHeight();
// chainHeight should not be zero/negative because we shouldn't have given the user a Peer that is to another
@ -1718,9 +1717,9 @@ public class Peer extends PeerSocketHandler {
* unset a filter, though the underlying p2p protocol does support it.</p>
*/
public void setBloomFilter(BloomFilter filter, boolean andQueryMemPool) {
checkNotNull(filter, "Clearing filters is not currently supported");
Objects.requireNonNull(filter, "Clearing filters is not currently supported");
final VersionMessage version = vPeerVersionMessage;
checkNotNull(version, "Cannot set filter before version handshake is complete");
Objects.requireNonNull(version, "Cannot set filter before version handshake is complete");
if (version.isBloomFilteringSupported()) {
vBloomFilter = filter;
log.info("{}: Sending Bloom filter{}", this, andQueryMemPool ? " and querying mempool" : "");
@ -1748,7 +1747,7 @@ public class Peer extends PeerSocketHandler {
// discarded.
sendPing().thenRunAsync(() -> {
lock.lock();
checkNotNull(awaitingFreshFilter);
Objects.requireNonNull(awaitingFreshFilter);
GetDataMessage getdata = new GetDataMessage(params);
for (Sha256Hash hash : awaitingFreshFilter)
getdata.addFilteredBlock(hash);

View file

@ -39,8 +39,6 @@ import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* <p>A PeerAddress holds an IP address and port number representing the network location of
* a peer in the Bitcoin P2P network. It exists primarily for serialization purposes.</p>
@ -99,7 +97,7 @@ public class PeerAddress extends ChildMessage {
*/
public PeerAddress(NetworkParameters params, InetAddress addr, int port, BigInteger services, MessageSerializer serializer) {
super(params);
this.addr = checkNotNull(addr);
this.addr = Objects.requireNonNull(addr);
this.port = port;
setSerializer(serializer);
this.services = services;

View file

@ -83,6 +83,7 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
@ -100,7 +101,6 @@ 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.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
@ -410,7 +410,7 @@ public class PeerGroup implements TransactionBroadcaster {
* @param connectionManager used to create new connections and keep track of existing ones.
*/
protected PeerGroup(Network network, @Nullable AbstractBlockChain chain, ClientConnectionManager connectionManager) {
this(NetworkParameters.of(checkNotNull(network)), chain, connectionManager);
this(NetworkParameters.of(Objects.requireNonNull(network)), chain, connectionManager);
}
/**
@ -421,7 +421,7 @@ public class PeerGroup implements TransactionBroadcaster {
*/
@VisibleForTesting
protected PeerGroup(NetworkParameters params, @Nullable AbstractBlockChain chain, ClientConnectionManager connectionManager) {
checkNotNull(params);
Objects.requireNonNull(params);
Context.getOrCreate(); // create a context for convenience
this.params = params;
this.chain = chain;
@ -751,7 +751,7 @@ public class PeerGroup implements TransactionBroadcaster {
* @see Peer#addBlocksDownloadedEventListener(Executor, BlocksDownloadedEventListener)
*/
public void addBlocksDownloadedEventListener(Executor executor, BlocksDownloadedEventListener listener) {
peersBlocksDownloadedEventListeners.add(new ListenerRegistration<>(checkNotNull(listener), executor));
peersBlocksDownloadedEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addBlocksDownloadedEventListener(executor, listener);
for (Peer peer : getPendingPeers())
@ -768,7 +768,7 @@ public class PeerGroup implements TransactionBroadcaster {
* chain download starts.</p>
*/
public void addChainDownloadStartedEventListener(Executor executor, ChainDownloadStartedEventListener listener) {
peersChainDownloadStartedEventListeners.add(new ListenerRegistration<>(checkNotNull(listener), executor));
peersChainDownloadStartedEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addChainDownloadStartedEventListener(executor, listener);
for (Peer peer : getPendingPeers())
@ -785,7 +785,7 @@ public class PeerGroup implements TransactionBroadcaster {
* new peers are connected to.</p>
*/
public void addConnectedEventListener(Executor executor, PeerConnectedEventListener listener) {
peerConnectedEventListeners.add(new ListenerRegistration<>(checkNotNull(listener), executor));
peerConnectedEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addConnectedEventListener(executor, listener);
for (Peer peer : getPendingPeers())
@ -802,7 +802,7 @@ public class PeerGroup implements TransactionBroadcaster {
* peers are disconnected from.</p>
*/
public void addDisconnectedEventListener(Executor executor, PeerDisconnectedEventListener listener) {
peerDisconnectedEventListeners.add(new ListenerRegistration<>(checkNotNull(listener), executor));
peerDisconnectedEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addDisconnectedEventListener(executor, listener);
for (Peer peer : getPendingPeers())
@ -819,7 +819,7 @@ public class PeerGroup implements TransactionBroadcaster {
* peers are discovered.</p>
*/
public void addDiscoveredEventListener(Executor executor, PeerDiscoveredEventListener listener) {
peerDiscoveredEventListeners.add(new ListenerRegistration<>(checkNotNull(listener), executor));
peerDiscoveredEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
}
/** See {@link Peer#addGetDataEventListener(GetDataEventListener)} */
@ -829,7 +829,7 @@ public class PeerGroup implements TransactionBroadcaster {
/** See {@link Peer#addGetDataEventListener(Executor, GetDataEventListener)} */
public void addGetDataEventListener(final Executor executor, final GetDataEventListener listener) {
peerGetDataEventListeners.add(new ListenerRegistration<>(checkNotNull(listener), executor));
peerGetDataEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addGetDataEventListener(executor, listener);
for (Peer peer : getPendingPeers())
@ -843,7 +843,7 @@ public class PeerGroup implements TransactionBroadcaster {
/** See {@link Peer#addOnTransactionBroadcastListener(OnTransactionBroadcastListener)} */
public void addOnTransactionBroadcastListener(Executor executor, OnTransactionBroadcastListener listener) {
peersTransactionBroadastEventListeners.add(new ListenerRegistration<>(checkNotNull(listener), executor));
peersTransactionBroadastEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addOnTransactionBroadcastListener(executor, listener);
for (Peer peer : getPendingPeers())
@ -857,7 +857,7 @@ public class PeerGroup implements TransactionBroadcaster {
/** See {@link Peer#addPreMessageReceivedEventListener(Executor, PreMessageReceivedEventListener)} */
public void addPreMessageReceivedEventListener(Executor executor, PreMessageReceivedEventListener listener) {
peersPreMessageReceivedEventListeners.add(new ListenerRegistration<>(checkNotNull(listener), executor));
peersPreMessageReceivedEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addPreMessageReceivedEventListener(executor, listener);
for (Peer peer : getPendingPeers())
@ -1244,7 +1244,7 @@ public class PeerGroup implements TransactionBroadcaster {
public void addWallet(Wallet wallet) {
lock.lock();
try {
checkNotNull(wallet);
Objects.requireNonNull(wallet);
checkState(!wallets.contains(wallet));
wallets.add(wallet);
wallet.setTransactionBroadcaster(this);
@ -1277,7 +1277,7 @@ public class PeerGroup implements TransactionBroadcaster {
public ListenableCompletableFuture<BloomFilter> addPeerFilterProvider(PeerFilterProvider provider) {
lock.lock();
try {
checkNotNull(provider);
Objects.requireNonNull(provider);
checkState(!peerFilterProviders.contains(provider));
// Insert provider at the start. This avoids various concurrency problems that could occur because we need
// all providers to be in a consistent, unchanging state whilst the filter is built. Providers can give
@ -1308,7 +1308,7 @@ public class PeerGroup implements TransactionBroadcaster {
public void removePeerFilterProvider(PeerFilterProvider provider) {
lock.lock();
try {
checkNotNull(provider);
Objects.requireNonNull(provider);
checkArgument(peerFilterProviders.remove(provider));
} finally {
lock.unlock();
@ -1319,7 +1319,7 @@ public class PeerGroup implements TransactionBroadcaster {
* Unlinks the given wallet so it no longer receives broadcast transactions or has its transactions announced.
*/
public void removeWallet(Wallet wallet) {
wallets.remove(checkNotNull(wallet));
wallets.remove(Objects.requireNonNull(wallet));
peerFilterProviders.remove(wallet);
wallet.removeCoinsReceivedEventListener(walletCoinsReceivedEventListener);
wallet.removeCoinsSentEventListener(walletCoinsSentEventListener);

View file

@ -37,10 +37,10 @@ import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.channels.NotYetConnectedException;
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.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
@ -71,9 +71,9 @@ public abstract class PeerSocketHandler implements TimeoutHandler, StreamConnect
}
public PeerSocketHandler(NetworkParameters params, PeerAddress peerAddress) {
checkNotNull(params);
Objects.requireNonNull(params);
serializer = params.getDefaultSerializer();
this.peerAddress = checkNotNull(peerAddress);
this.peerAddress = Objects.requireNonNull(peerAddress);
this.timeoutTask = new SocketTimeoutTask(this::timeoutOccurred);
}

View file

@ -60,11 +60,11 @@ import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
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.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static org.bitcoinj.core.NetworkParameters.ProtocolVersion.WITNESS_VERSION;
import static org.bitcoinj.base.internal.ByteUtils.uint32ToByteStreamLE;
@ -553,7 +553,7 @@ public class Transaction extends ChildMessage {
* @param updateTime update time
*/
public void setUpdateTime(Instant updateTime) {
this.updateTime = checkNotNull(updateTime);
this.updateTime = Objects.requireNonNull(updateTime);
}
/**
@ -1117,7 +1117,7 @@ public class Transaction extends ChildMessage {
* @return The newly created input
*/
public TransactionInput addSignedInput(TransactionOutput output, ECKey sigKey, SigHash sigHash, boolean anyoneCanPay) {
checkNotNull(output.getValue(), "TransactionOutput.getValue() must not be null");
Objects.requireNonNull(output.getValue(), "TransactionOutput.getValue() must not be null");
checkState(output.getValue().value > 0, "TransactionOutput.getValue() must not be greater than zero");
return addSignedInput(output.getOutPointFor(), output.getScriptPubKey(), output.getValue(), sigKey, sigHash, anyoneCanPay);
}

View file

@ -32,12 +32,12 @@ import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.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.
@ -224,7 +224,7 @@ public class TransactionConfidence {
* a future from {@link #getDepthFuture(int)}.</p>
*/
public void addEventListener(Executor executor, Listener listener) {
checkNotNull(listener);
Objects.requireNonNull(listener);
listeners.addIfAbsent(new ListenerRegistration<>(listener, executor));
pinnedConfidenceObjects.add(this);
}
@ -244,7 +244,7 @@ public class TransactionConfidence {
}
public boolean removeEventListener(Listener listener) {
checkNotNull(listener);
Objects.requireNonNull(listener);
boolean removed = ListenerRegistration.removeFromList(listener, listeners);
if (listeners.isEmpty())
pinnedConfidenceObjects.remove(this);
@ -359,7 +359,7 @@ public class TransactionConfidence {
* @param lastBroadcastTime time the transaction was last announced to us
*/
public void setLastBroadcastTime(Instant lastBroadcastTime) {
this.lastBroadcastTime = checkNotNull(lastBroadcastTime);
this.lastBroadcastTime = Objects.requireNonNull(lastBroadcastTime);
}
/** @deprecated use {@link #setLastBroadcastTime(Instant)} */

View file

@ -37,7 +37,6 @@ import java.util.Map;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* <p>A transfer of coins from one address to another creates a transaction in which the outputs
@ -204,7 +203,7 @@ public class TransactionInput extends ChildMessage {
/** Set the given program as the scriptSig that is supposed to satisfy the connected output script. */
public void setScriptSig(Script scriptSig) {
this.scriptSig = new WeakReference<>(checkNotNull(scriptSig));
this.scriptSig = new WeakReference<>(Objects.requireNonNull(scriptSig));
// TODO: This should all be cleaned up so we have a consistent internal representation.
setScriptBytes(scriptSig.getProgram());
}
@ -456,7 +455,7 @@ public class TransactionInput extends ChildMessage {
public void verify() throws VerificationException {
final Transaction fromTx = getOutpoint().fromTx;
long spendingIndex = getOutpoint().getIndex();
checkNotNull(fromTx, "Not connected");
Objects.requireNonNull(fromTx, "Not connected");
final TransactionOutput output = fromTx.getOutput((int) spendingIndex);
verify(output);
}

View file

@ -33,7 +33,6 @@ import java.io.IOException;
import java.io.OutputStream;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
@ -133,7 +132,7 @@ public class TransactionOutPoint extends ChildMessage {
* @throws java.lang.NullPointerException if there is no connected output.
*/
public byte[] getConnectedPubKeyScript() {
byte[] result = checkNotNull(getConnectedOutput()).getScriptBytes();
byte[] result = Objects.requireNonNull(getConnectedOutput()).getScriptBytes();
checkState(result.length > 0);
return result;
}
@ -149,7 +148,7 @@ public class TransactionOutPoint extends ChildMessage {
@Nullable
public ECKey getConnectedKey(KeyBag keyBag) throws ScriptException {
TransactionOutput connectedOutput = getConnectedOutput();
checkNotNull(connectedOutput, "Input is not connected so cannot retrieve key");
Objects.requireNonNull(connectedOutput, "Input is not connected so cannot retrieve key");
Script connectedScript = connectedOutput.getScriptPubKey();
if (ScriptPattern.isP2PKH(connectedScript)) {
byte[] addressBytes = ScriptPattern.extractHashFromP2PKH(connectedScript);
@ -175,7 +174,7 @@ public class TransactionOutPoint extends ChildMessage {
@Nullable
public RedeemData getConnectedRedeemData(KeyBag keyBag) throws ScriptException {
TransactionOutput connectedOutput = getConnectedOutput();
checkNotNull(connectedOutput, "Input is not connected so cannot retrieve key");
Objects.requireNonNull(connectedOutput, "Input is not connected so cannot retrieve key");
Script connectedScript = connectedOutput.getScriptPubKey();
if (ScriptPattern.isP2PKH(connectedScript)) {
byte[] addressBytes = ScriptPattern.extractHashFromP2PKH(connectedScript);

View file

@ -40,7 +40,6 @@ import java.util.List;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
@ -141,7 +140,7 @@ public class TransactionOutput extends ChildMessage {
@Override
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
checkNotNull(scriptBytes);
Objects.requireNonNull(scriptBytes);
ByteUtils.int64ToByteStreamLE(value, stream);
// TODO: Move script serialization into the Script class, where it belongs.
stream.write(new VarInt(scriptBytes.length).encode());
@ -160,7 +159,7 @@ public class TransactionOutput extends ChildMessage {
* Sets the value of this output.
*/
public void setValue(Coin value) {
checkNotNull(value);
Objects.requireNonNull(value);
unCache();
this.value = value.value;
}

View file

@ -25,10 +25,9 @@ import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* <p>Tracks transactions that are being announced across the network. Typically one is created for you by a
* {@link PeerGroup} and then given to each Peer to update. The current purpose is to let Peers update the confidence
@ -166,7 +165,7 @@ public class TxConfidenceTable {
* is unknown to the system at this time.
*/
public TransactionConfidence getOrCreate(Sha256Hash hash) {
checkNotNull(hash);
Objects.requireNonNull(hash);
lock.lock();
try {
WeakConfidenceReference reference = table.get(hash);

View file

@ -30,8 +30,6 @@ import java.math.BigInteger;
import java.util.Locale;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkNotNull;
// TODO: Fix this class: should not talk about addresses, height should be optional/support mempool height etc
/**
@ -83,9 +81,9 @@ public class UTXO {
boolean coinbase,
Script script,
String address) {
this.hash = checkNotNull(hash);
this.hash = Objects.requireNonNull(hash);
this.index = index;
this.value = checkNotNull(value);
this.value = Objects.requireNonNull(value);
this.height = height;
this.script = script;
this.coinbase = coinbase;

View file

@ -39,7 +39,6 @@ import java.util.Objects;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
@ -74,7 +73,7 @@ public class DeterministicKey extends ECKey {
super(priv, publicAsPoint.compress());
checkArgument(chainCode.length == 32);
this.parent = parent;
this.childNumberPath = HDPath.M(checkNotNull(childNumberPath));
this.childNumberPath = HDPath.M(Objects.requireNonNull(childNumberPath));
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
this.depth = parent == null ? 0 : parent.depth + 1;
this.parentFingerprint = (parent != null) ? parent.getFingerprint() : 0;
@ -97,7 +96,7 @@ public class DeterministicKey extends ECKey {
super(priv, ECKey.publicPointFromPrivate(priv), true);
checkArgument(chainCode.length == 32);
this.parent = parent;
this.childNumberPath = checkNotNull(hdPath);
this.childNumberPath = Objects.requireNonNull(hdPath);
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
this.depth = parent == null ? 0 : parent.depth + 1;
this.parentFingerprint = (parent != null) ? parent.getFingerprint() : 0;
@ -111,8 +110,8 @@ public class DeterministicKey extends ECKey {
EncryptedData priv,
@Nullable DeterministicKey parent) {
this(childNumberPath, chainCode, pub, null, parent);
this.encryptedPrivateKey = checkNotNull(priv);
this.keyCrypter = checkNotNull(crypter);
this.encryptedPrivateKey = Objects.requireNonNull(priv);
this.keyCrypter = Objects.requireNonNull(crypter);
}
/**
@ -145,7 +144,7 @@ public class DeterministicKey extends ECKey {
super(null, publicAsPoint.compress());
checkArgument(chainCode.length == 32);
this.parent = parent;
this.childNumberPath = HDPath.M(checkNotNull(childNumberPath));
this.childNumberPath = HDPath.M(Objects.requireNonNull(childNumberPath));
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
this.depth = depth;
this.parentFingerprint = ascertainParentFingerprint(parentFingerprint);
@ -165,7 +164,7 @@ public class DeterministicKey extends ECKey {
super(priv, ECKey.publicPointFromPrivate(priv), true);
checkArgument(chainCode.length == 32);
this.parent = parent;
this.childNumberPath = HDPath.M(checkNotNull(childNumberPath));
this.childNumberPath = HDPath.M(Objects.requireNonNull(childNumberPath));
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
this.depth = depth;
this.parentFingerprint = ascertainParentFingerprint(parentFingerprint);
@ -301,7 +300,7 @@ public class DeterministicKey extends ECKey {
public DeterministicKey encrypt(KeyCrypter keyCrypter, AesKey aesKey, @Nullable DeterministicKey newParent) throws KeyCrypterException {
// Same as the parent code, except we construct a DeterministicKey instead of an ECKey.
checkNotNull(keyCrypter);
Objects.requireNonNull(keyCrypter);
if (newParent != null)
checkArgument(newParent.isEncrypted());
final byte[] privKeyBytes = getPrivKeyBytes();
@ -380,7 +379,7 @@ public class DeterministicKey extends ECKey {
@Override
public DeterministicKey decrypt(KeyCrypter keyCrypter, AesKey aesKey) throws KeyCrypterException {
checkNotNull(keyCrypter);
Objects.requireNonNull(keyCrypter);
// 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");
@ -460,7 +459,7 @@ public class DeterministicKey extends ECKey {
// catch it.
if (!downCursor.pub.equals(pub))
throw new KeyCrypterException.PublicPrivateMismatch("Could not decrypt bytes");
return checkNotNull(downCursor.priv);
return Objects.requireNonNull(downCursor.priv);
}
/**

View file

@ -86,7 +86,6 @@ import java.util.Objects;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
@ -189,7 +188,7 @@ public class ECKey implements EncryptableItem {
}
protected ECKey(@Nullable BigInteger priv, ECPoint pub, boolean compressed) {
this(priv, new LazyECPoint(checkNotNull(pub), compressed));
this(priv, new LazyECPoint(Objects.requireNonNull(pub), compressed));
}
protected ECKey(@Nullable BigInteger priv, LazyECPoint pub) {
@ -202,7 +201,7 @@ public class ECKey implements EncryptableItem {
checkArgument(!priv.equals(BigInteger.ONE));
}
this.priv = priv;
this.pub = checkNotNull(pub);
this.pub = Objects.requireNonNull(pub);
}
/**
@ -262,8 +261,8 @@ public class ECKey implements EncryptableItem {
* already. The compression state of the point will be preserved.
*/
public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub) {
checkNotNull(priv);
checkNotNull(pub);
Objects.requireNonNull(priv);
Objects.requireNonNull(pub);
return new ECKey(ByteUtils.bytesToBigInteger(priv), new LazyECPoint(CURVE.getCurve(), pub));
}
@ -305,8 +304,8 @@ public class ECKey implements EncryptableItem {
*/
public static ECKey fromEncrypted(EncryptedData encryptedPrivateKey, KeyCrypter crypter, byte[] pubKey) {
ECKey key = fromPublicOnly(pubKey);
key.encryptedPrivateKey = checkNotNull(encryptedPrivateKey);
key.keyCrypter = checkNotNull(crypter);
key.encryptedPrivateKey = Objects.requireNonNull(encryptedPrivateKey);
key.keyCrypter = Objects.requireNonNull(crypter);
return key;
}
@ -601,7 +600,7 @@ public class ECKey implements EncryptableItem {
throw new RuntimeException(e); // cannot happen
}
}
checkNotNull(privateKeyForSigning);
Objects.requireNonNull(privateKeyForSigning);
ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeyForSigning, CURVE);
signer.init(true, privKey);
@ -988,7 +987,7 @@ public class ECKey implements EncryptableItem {
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");
Preconditions.checkNotNull(message);
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)
// 1.1 Let x = r + jn
@ -1091,7 +1090,7 @@ public class ECKey implements EncryptableItem {
* @param creationTime creation time of this key
*/
public void setCreationTime(Instant creationTime) {
this.creationTime = checkNotNull(creationTime);
this.creationTime = Objects.requireNonNull(creationTime);
}
/**
@ -1122,7 +1121,7 @@ public class ECKey implements EncryptableItem {
* @return encryptedKey
*/
public ECKey encrypt(KeyCrypter keyCrypter, AesKey aesKey) throws KeyCrypterException {
checkNotNull(keyCrypter);
Objects.requireNonNull(keyCrypter);
final byte[] privKeyBytes = getPrivKeyBytes();
EncryptedData encryptedPrivateKey = keyCrypter.encrypt(privKeyBytes, aesKey);
ECKey result = ECKey.fromEncrypted(encryptedPrivateKey, keyCrypter, getPubKey());
@ -1142,7 +1141,7 @@ public class ECKey implements EncryptableItem {
* @param aesKey The KeyParameter with the AES encryption key (usually constructed with keyCrypter#deriveKey and cached).
*/
public ECKey decrypt(KeyCrypter keyCrypter, AesKey aesKey) throws KeyCrypterException {
checkNotNull(keyCrypter);
Objects.requireNonNull(keyCrypter);
// 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");
@ -1332,7 +1331,7 @@ public class ECKey implements EncryptableItem {
final MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(this).omitNullValues();
helper.add("pub HEX", getPublicKeyAsHex());
if (includePrivate) {
ECKey decryptedKey = isEncrypted() ? decrypt(checkNotNull(aesKey)) : this;
ECKey decryptedKey = isEncrypted() ? decrypt(Objects.requireNonNull(aesKey)) : this;
try {
helper.add("priv HEX", decryptedKey.getPrivateKeyAsHex());
helper.add("priv WIF", decryptedKey.getPrivateKeyAsWiF(network));

View file

@ -23,8 +23,6 @@ import org.bitcoinj.core.NetworkParameters;
import java.util.Arrays;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Some form of string-encoded private key. This form is useful for noting them down, e.g. on paper wallets.
*/
@ -33,13 +31,13 @@ public abstract class EncodedPrivateKey {
protected final byte[] bytes;
protected EncodedPrivateKey(Network network, byte[] bytes) {
this.network = checkNotNull(network);
this.bytes = checkNotNull(bytes);
this.network = Objects.requireNonNull(network);
this.bytes = Objects.requireNonNull(bytes);
}
@Deprecated
protected EncodedPrivateKey(NetworkParameters params, byte[] bytes) {
this(checkNotNull(params).network(), checkNotNull(bytes));
this(Objects.requireNonNull(params).network(), Objects.requireNonNull(bytes));
}
/**

View file

@ -38,8 +38,6 @@ import java.time.Instant;
import java.util.Arrays;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* <p>This class encrypts and decrypts byte arrays and strings using scrypt as the
* key derivation function and AES for the encryption.</p>
@ -119,7 +117,7 @@ public class KeyCrypterScrypt implements KeyCrypter {
* @throws NullPointerException if the scryptParameters or any of its N, R or P is null.
*/
public KeyCrypterScrypt(ScryptParameters scryptParameters) {
this.scryptParameters = checkNotNull(scryptParameters);
this.scryptParameters = Objects.requireNonNull(scryptParameters);
// Check there is a non-empty salt.
// (Some early MultiBit wallets has a missing salt so it is not a hard fail).
if (scryptParameters.getSalt() == null
@ -171,8 +169,8 @@ public class KeyCrypterScrypt implements KeyCrypter {
*/
@Override
public EncryptedData encrypt(byte[] plainBytes, AesKey aesKey) throws KeyCrypterException {
checkNotNull(plainBytes);
checkNotNull(aesKey);
Objects.requireNonNull(plainBytes);
Objects.requireNonNull(aesKey);
try {
// Generate iv - each encryption call has a different iv.
@ -204,8 +202,8 @@ public class KeyCrypterScrypt implements KeyCrypter {
*/
@Override
public byte[] decrypt(EncryptedData dataToDecrypt, AesKey aesKey) throws KeyCrypterException {
checkNotNull(dataToDecrypt);
checkNotNull(aesKey);
Objects.requireNonNull(dataToDecrypt);
Objects.requireNonNull(aesKey);
try {
ParametersWithIV keyWithIv = new ParametersWithIV(new KeyParameter(aesKey.bytes()), dataToDecrypt.initialisationVector);
@ -233,7 +231,7 @@ public class KeyCrypterScrypt implements KeyCrypter {
* Note: a String.getBytes() is not used to avoid creating a String of the password in the JVM.
*/
private static byte[] convertToByteArray(CharSequence charSequence) {
checkNotNull(charSequence);
Objects.requireNonNull(charSequence);
byte[] byteArray = new byte[charSequence.length() << 1];
for(int i = 0; i < charSequence.length(); i++) {

View file

@ -23,8 +23,7 @@ import org.bouncycastle.math.ec.ECPoint;
import javax.annotation.Nullable;
import java.math.BigInteger;
import java.util.Arrays;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
/**
* A wrapper around ECPoint that delays decoding of the point for as long as possible. This is useful because point
@ -63,7 +62,7 @@ public class LazyECPoint {
* @param compressed true if the represented public key is compressed
*/
public LazyECPoint(ECPoint point, boolean compressed) {
this.point = checkNotNull(point).normalize();
this.point = Objects.requireNonNull(point).normalize();
this.compressed = compressed;
this.curve = null;
this.bits = null;

View file

@ -36,9 +36,9 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import org.bitcoinj.base.internal.ByteUtils;
/**
@ -132,7 +132,7 @@ public class MnemonicCode {
* Convert mnemonic word list to seed.
*/
public static byte[] toSeed(List<String> words, String passphrase) {
checkNotNull(passphrase, "A null passphrase is not allowed.");
Objects.requireNonNull(passphrase, "A null passphrase is not allowed.");
// To create binary seed from mnemonic, we use PBKDF2 function
// with mnemonic sentence (in UTF-8) used as a password and

View file

@ -56,10 +56,10 @@ import java.nio.channels.FileLock;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
@ -142,12 +142,12 @@ public class WalletAppKit extends AbstractIdleService {
*/
public WalletAppKit(BitcoinNetwork network, ScriptType preferredOutputScriptType,
KeyChainGroupStructure structure, File directory, String filePrefix) {
this.network = checkNotNull(network);
this.network = Objects.requireNonNull(network);
this.params = NetworkParameters.of(this.network);
this.preferredOutputScriptType = checkNotNull(preferredOutputScriptType);
this.structure = checkNotNull(structure);
this.directory = checkNotNull(directory);
this.filePrefix = checkNotNull(filePrefix);
this.preferredOutputScriptType = Objects.requireNonNull(preferredOutputScriptType);
this.structure = Objects.requireNonNull(structure);
this.directory = Objects.requireNonNull(directory);
this.filePrefix = Objects.requireNonNull(filePrefix);
}
/** Will only connect to the given addresses. Cannot be called after startup. */
@ -181,7 +181,7 @@ public class WalletAppKit extends AbstractIdleService {
* too, due to some missing implementation code.
*/
public WalletAppKit setDownloadListener(DownloadProgressTracker listener) {
checkNotNull(listener);
Objects.requireNonNull(listener);
this.downloadListener = listener;
return this;
}
@ -200,7 +200,7 @@ public class WalletAppKit extends AbstractIdleService {
public WalletAppKit setCheckpoints(InputStream checkpoints) {
if (this.checkpoints != null)
Closeables.closeQuietly(checkpoints);
this.checkpoints = checkNotNull(checkpoints);
this.checkpoints = Objects.requireNonNull(checkpoints);
return this;
}
@ -221,8 +221,8 @@ public class WalletAppKit extends AbstractIdleService {
* @param version A short string that contains the version number, e.g. "1.0-BETA"
*/
public WalletAppKit setUserAgent(String userAgent, String version) {
this.userAgent = checkNotNull(userAgent);
this.version = checkNotNull(version);
this.userAgent = Objects.requireNonNull(userAgent);
this.version = Objects.requireNonNull(version);
return this;
}
@ -232,7 +232,7 @@ public class WalletAppKit extends AbstractIdleService {
* @return WalletAppKit for method chaining purposes
*/
public WalletAppKit setWalletFactory(@Nonnull WalletProtobufSerializer.WalletFactory walletFactory) {
checkNotNull(walletFactory);
Objects.requireNonNull(walletFactory);
this.walletFactory = walletFactory;
return this;
}

View file

@ -26,10 +26,9 @@ import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* <p>A thin wrapper around a set of {@link BlockingClient}s.</p>
*
@ -52,7 +51,7 @@ public class BlockingClientManager extends AbstractIdleService implements Client
* bitcoinj connects to the P2P network.
*/
public BlockingClientManager(SocketFactory socketFactory) {
this.socketFactory = checkNotNull(socketFactory);
this.socketFactory = Objects.requireNonNull(socketFactory);
}
@Override

View file

@ -34,10 +34,10 @@ import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.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.
@ -86,7 +86,7 @@ class ConnectionHandler implements MessageWriteTarget {
private ConnectionHandler(@Nullable StreamConnection connection, SelectionKey key) {
this.key = key;
this.channel = checkNotNull(((SocketChannel)key.channel()));
this.channel = Objects.requireNonNull(((SocketChannel)key.channel()));
if (connection == null) {
readBuff = null;
return;
@ -98,7 +98,7 @@ class ConnectionHandler implements MessageWriteTarget {
}
public ConnectionHandler(StreamConnection connection, SelectionKey key, Set<ConnectionHandler> connectedHandlers) {
this(checkNotNull(connection), key);
this(Objects.requireNonNull(connection), key);
// closeConnection() may have already happened because we invoked the other c'tor above, which called
// connection.setWriteTarget which might have re-entered already. In this case we shouldn't add ourselves
@ -236,7 +236,7 @@ class ConnectionHandler implements MessageWriteTarget {
// "flip" the buffer - setting the limit to the current position and setting position to 0
((Buffer) handler.readBuff).flip();
// Use connection.receiveBytes's return value as a check that it stopped reading at the right location
int bytesConsumed = checkNotNull(handler.connection).receiveBytes(handler.readBuff);
int bytesConsumed = Objects.requireNonNull(handler.connection).receiveBytes(handler.readBuff);
checkState(handler.readBuff.position() == bytesConsumed);
// Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative
// position)

View file

@ -63,11 +63,11 @@ import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
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.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static org.bitcoinj.script.ScriptOpCodes.OP_0;
import static org.bitcoinj.script.ScriptOpCodes.OP_0NOTEQUAL;
@ -260,7 +260,7 @@ public class Script {
public Script(byte[] programBytes, Instant creationTime) throws ScriptException {
this.program = programBytes;
parse(programBytes);
this.creationTime = checkNotNull(creationTime);
this.creationTime = Objects.requireNonNull(creationTime);
}
/**
@ -282,7 +282,7 @@ public class Script {
* @param creationTime creation time of this script
*/
public void setCreationTime(Instant creationTime) {
this.creationTime = checkNotNull(creationTime);
this.creationTime = Objects.requireNonNull(creationTime);
}
/**
@ -570,7 +570,7 @@ public class Script {
// and any placeholder OP_0 sigs.
List<ScriptChunk> existingChunks = chunks.subList(1, chunks.size() - 1);
ScriptChunk redeemScriptChunk = chunks.get(chunks.size() - 1);
checkNotNull(redeemScriptChunk.data);
Objects.requireNonNull(redeemScriptChunk.data);
Script redeemScript = new Script(redeemScriptChunk.data);
int sigCount = 0;
@ -579,7 +579,7 @@ public class Script {
if (chunk.opcode == OP_0) {
// OP_0, skip
} else {
checkNotNull(chunk.data);
Objects.requireNonNull(chunk.data);
try {
if (myIndex < redeemScript.findSigInRedeem(chunk.data, hash))
return sigCount;

View file

@ -33,8 +33,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
/**
* <p>This signer may be used as a template for creating custom multisig transaction signers.</p>
@ -69,7 +68,7 @@ public abstract class CustomTransactionSigner implements TransactionSigner {
return false;
}
Script inputScript = checkNotNull(txIn.getScriptSig());
Script inputScript = Objects.requireNonNull(txIn.getScriptSig());
try {
// We assume if its already signed, its hopefully got a SIGHASH type that will not invalidate when

View file

@ -16,7 +16,6 @@
package org.bitcoinj.store;
import com.google.common.base.Preconditions;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.base.Address;
import org.bitcoinj.crypto.ECKey;
@ -290,14 +289,14 @@ public class MemoryFullPrunedBlockStore implements FullPrunedBlockStore {
@Override
public synchronized void put(StoredBlock block) throws BlockStoreException {
Preconditions.checkNotNull(blockMap, "MemoryFullPrunedBlockStore is closed");
Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed");
Sha256Hash hash = block.getHeader().getHash();
blockMap.put(hash, new StoredBlockAndWasUndoableFlag(block, false));
}
@Override
public synchronized final void put(StoredBlock storedBlock, StoredUndoableBlock undoableBlock) throws BlockStoreException {
Preconditions.checkNotNull(blockMap, "MemoryFullPrunedBlockStore is closed");
Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed");
Sha256Hash hash = storedBlock.getHeader().getHash();
fullBlockMap.put(hash, storedBlock.getHeight(), undoableBlock);
blockMap.put(hash, new StoredBlockAndWasUndoableFlag(storedBlock, true));
@ -306,7 +305,7 @@ public class MemoryFullPrunedBlockStore implements FullPrunedBlockStore {
@Override
@Nullable
public synchronized StoredBlock get(Sha256Hash hash) throws BlockStoreException {
Preconditions.checkNotNull(blockMap, "MemoryFullPrunedBlockStore is closed");
Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed");
StoredBlockAndWasUndoableFlag storedBlock = blockMap.get(hash);
return storedBlock == null ? null : storedBlock.block;
}
@ -314,7 +313,7 @@ public class MemoryFullPrunedBlockStore implements FullPrunedBlockStore {
@Override
@Nullable
public synchronized StoredBlock getOnceUndoableStoredBlock(Sha256Hash hash) throws BlockStoreException {
Preconditions.checkNotNull(blockMap, "MemoryFullPrunedBlockStore is closed");
Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed");
StoredBlockAndWasUndoableFlag storedBlock = blockMap.get(hash);
return (storedBlock != null && storedBlock.wasUndoable) ? storedBlock.block : null;
}
@ -322,31 +321,31 @@ public class MemoryFullPrunedBlockStore implements FullPrunedBlockStore {
@Override
@Nullable
public synchronized StoredUndoableBlock getUndoBlock(Sha256Hash hash) throws BlockStoreException {
Preconditions.checkNotNull(fullBlockMap, "MemoryFullPrunedBlockStore is closed");
Objects.requireNonNull(fullBlockMap, "MemoryFullPrunedBlockStore is closed");
return fullBlockMap.get(hash);
}
@Override
public synchronized StoredBlock getChainHead() throws BlockStoreException {
Preconditions.checkNotNull(blockMap, "MemoryFullPrunedBlockStore is closed");
Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed");
return chainHead;
}
@Override
public synchronized final void setChainHead(StoredBlock chainHead) throws BlockStoreException {
Preconditions.checkNotNull(blockMap, "MemoryFullPrunedBlockStore is closed");
Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed");
this.chainHead = chainHead;
}
@Override
public synchronized StoredBlock getVerifiedChainHead() throws BlockStoreException {
Preconditions.checkNotNull(blockMap, "MemoryFullPrunedBlockStore is closed");
Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed");
return verifiedChainHead;
}
@Override
public synchronized final void setVerifiedChainHead(StoredBlock chainHead) throws BlockStoreException {
Preconditions.checkNotNull(blockMap, "MemoryFullPrunedBlockStore is closed");
Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed");
this.verifiedChainHead = chainHead;
if (this.chainHead.getHeight() < chainHead.getHeight())
setChainHead(chainHead);
@ -365,19 +364,19 @@ public class MemoryFullPrunedBlockStore implements FullPrunedBlockStore {
@Override
@Nullable
public synchronized UTXO getTransactionOutput(Sha256Hash hash, long index) throws BlockStoreException {
Preconditions.checkNotNull(transactionOutputMap, "MemoryFullPrunedBlockStore is closed");
Objects.requireNonNull(transactionOutputMap, "MemoryFullPrunedBlockStore is closed");
return transactionOutputMap.get(new StoredTransactionOutPoint(hash, index));
}
@Override
public synchronized void addUnspentTransactionOutput(UTXO out) throws BlockStoreException {
Preconditions.checkNotNull(transactionOutputMap, "MemoryFullPrunedBlockStore is closed");
Objects.requireNonNull(transactionOutputMap, "MemoryFullPrunedBlockStore is closed");
transactionOutputMap.put(new StoredTransactionOutPoint(out), out);
}
@Override
public synchronized void removeUnspentTransactionOutput(UTXO out) throws BlockStoreException {
Preconditions.checkNotNull(transactionOutputMap, "MemoryFullPrunedBlockStore is closed");
Objects.requireNonNull(transactionOutputMap, "MemoryFullPrunedBlockStore is closed");
if (transactionOutputMap.remove(new StoredTransactionOutPoint(out)) == null)
throw new BlockStoreException("Tried to remove a UTXO from MemoryFullPrunedBlockStore that it didn't have!");
}

View file

@ -38,10 +38,10 @@ import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.LinkedHashMap;
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.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
// TODO: Lose the mmap in this class. There are too many platform bugs that require odd workarounds.
@ -112,8 +112,8 @@ public class SPVBlockStore implements BlockStore {
* @throws BlockStoreException if something goes wrong
*/
public SPVBlockStore(NetworkParameters params, File file, int capacity, boolean grow) throws BlockStoreException {
checkNotNull(file);
this.params = checkNotNull(params);
Objects.requireNonNull(file);
this.params = Objects.requireNonNull(params);
checkArgument(capacity > 0);
try {
boolean exists = file.exists();

View file

@ -36,8 +36,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
/**
* <p>Provides a standard implementation of a Bitcoin URI with support for the following:</p>
@ -136,8 +135,8 @@ public class BitcoinURI {
* @throws BitcoinURIParseException If the input fails Bitcoin URI syntax and semantic checks.
*/
public BitcoinURI(@Nonnull Network network, String input) throws BitcoinURIParseException {
checkNotNull(network);
checkNotNull(input);
Objects.requireNonNull(network);
Objects.requireNonNull(input);
String scheme = network.uriScheme();
@ -398,8 +397,8 @@ public class BitcoinURI {
public static String convertToBitcoinURI(Network network,
String address, @Nullable Coin amount,
@Nullable String label, @Nullable String message) {
checkNotNull(network);
checkNotNull(address);
Objects.requireNonNull(network);
Objects.requireNonNull(address);
if (amount != null && amount.signum() < 0) {
throw new IllegalArgumentException("Coin must be positive");
}

View file

@ -21,8 +21,7 @@ import com.google.protobuf.ByteString;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
/**
* A simple implementation of {@link TaggableObject} that uses a hashmap that is
@ -53,8 +52,8 @@ public class BaseTaggableObject implements TaggableObject {
@Deprecated
public synchronized void setTag(String tag, ByteString value) {
// HashMap allows null keys and values, but we don't
checkNotNull(tag);
checkNotNull(value);
Objects.requireNonNull(tag);
Objects.requireNonNull(value);
tags.put(tag, value);
}

View file

@ -17,10 +17,9 @@
package org.bitcoinj.utils;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executor;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A simple wrapper around a listener and an executor, with some utility methods.
*/
@ -29,13 +28,13 @@ public class ListenerRegistration<T> {
public final Executor executor;
public ListenerRegistration(T listener, Executor executor) {
this.listener = checkNotNull(listener);
this.executor = checkNotNull(executor);
this.listener = Objects.requireNonNull(listener);
this.executor = Objects.requireNonNull(executor);
}
/** Returns true if the listener was removed, else false. */
public static <T> boolean removeFromList(T listener, List<? extends ListenerRegistration<T>> list) {
checkNotNull(listener);
Objects.requireNonNull(listener);
ListenerRegistration<T> item = null;
for (ListenerRegistration<T> registration : list) {

View file

@ -40,6 +40,7 @@ import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
@ -47,7 +48,6 @@ 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.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
@ -388,7 +388,7 @@ public class BasicKeyChain implements EncryptableKeyChain {
* @throws org.bitcoinj.wallet.UnreadableWalletException if the data structures are corrupted/inconsistent
*/
public static BasicKeyChain fromProtobufEncrypted(List<Protos.Key> keys, KeyCrypter crypter) throws UnreadableWalletException {
BasicKeyChain chain = new BasicKeyChain(checkNotNull(crypter));
BasicKeyChain chain = new BasicKeyChain(Objects.requireNonNull(crypter));
chain.deserializeFromProtobuf(keys);
return chain;
}
@ -474,7 +474,7 @@ public class BasicKeyChain implements EncryptableKeyChain {
*/
@Override
public BasicKeyChain toEncrypted(CharSequence password) {
checkNotNull(password);
Objects.requireNonNull(password);
checkArgument(password.length() > 0);
KeyCrypter scrypt = new KeyCrypterScrypt();
AesKey derivedKey = scrypt.deriveKey(password);
@ -494,7 +494,7 @@ public class BasicKeyChain implements EncryptableKeyChain {
public BasicKeyChain toEncrypted(KeyCrypter keyCrypter, AesKey aesKey) {
lock.lock();
try {
checkNotNull(keyCrypter);
Objects.requireNonNull(keyCrypter);
checkState(this.keyCrypter == null, "Key chain is already encrypted");
BasicKeyChain encrypted = new BasicKeyChain(keyCrypter);
for (ECKey key : hashToKeys.values()) {
@ -519,7 +519,7 @@ public class BasicKeyChain implements EncryptableKeyChain {
@Override
public BasicKeyChain toDecrypted(CharSequence password) {
checkNotNull(keyCrypter, "Wallet is already decrypted");
Objects.requireNonNull(keyCrypter, "Wallet is already decrypted");
AesKey aesKey = keyCrypter.deriveKey(password);
return toDecrypted(aesKey);
}
@ -551,7 +551,7 @@ public class BasicKeyChain implements EncryptableKeyChain {
*/
@Override
public boolean checkPassword(CharSequence password) {
checkNotNull(password);
Objects.requireNonNull(password);
checkState(keyCrypter != null, "Key chain not encrypted");
return checkAESKey(keyCrypter.deriveKey(password));
}

View file

@ -23,8 +23,7 @@ import org.bitcoinj.crypto.ECKey;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
/**
* A DecryptingKeyBag filters a pre-existing key bag, decrypting keys as they are requested using the provided
@ -36,7 +35,7 @@ public class DecryptingKeyBag implements KeyBag {
protected final AesKey aesKey;
public DecryptingKeyBag(KeyBag target, @Nullable AesKey aesKey) {
this.target = checkNotNull(target);
this.target = Objects.requireNonNull(target);
this.aesKey = aesKey;
}

View file

@ -56,6 +56,7 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.Executor;
import java.util.concurrent.locks.ReentrantLock;
@ -63,7 +64,6 @@ 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.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
@ -214,7 +214,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
*/
public T entropy(byte[] entropy, Instant creationTime) {
this.entropy = entropy;
this.creationTime = checkNotNull(creationTime);
this.creationTime = Objects.requireNonNull(creationTime);
return self();
}
@ -306,7 +306,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
*/
public T accountPath(List<ChildNumber> accountPath) {
checkState(watchingKey == null, "either watch or accountPath");
this.accountPath = HDPath.M(checkNotNull(accountPath));
this.accountPath = HDPath.M(Objects.requireNonNull(accountPath));
return self();
}
@ -396,7 +396,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
this.seed = seed;
basicKeyChain = new BasicKeyChain(crypter);
if (!seed.isEncrypted()) {
rootKey = HDKeyDerivation.createMasterPrivateKey(checkNotNull(seed.getSeedBytes()));
rootKey = HDKeyDerivation.createMasterPrivateKey(Objects.requireNonNull(seed.getSeedBytes()));
Optional<Instant> creationTime = seed.getCreationTime();
if (creationTime.isPresent())
rootKey.setCreationTime(creationTime.get());
@ -422,8 +422,8 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
*/
protected DeterministicKeyChain(KeyCrypter crypter, AesKey aesKey, DeterministicKeyChain chain) {
// Can't encrypt a watching chain.
checkNotNull(chain.rootKey);
checkNotNull(chain.seed);
Objects.requireNonNull(chain.rootKey);
Objects.requireNonNull(chain.seed);
checkArgument(!chain.rootKey.isEncrypted(), "Chain already encrypted");
this.accountPath = chain.getAccountPath();
@ -470,7 +470,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
private DeterministicKey encryptNonLeaf(AesKey aesKey, DeterministicKeyChain chain,
DeterministicKey parent, List<ChildNumber> path) {
DeterministicKey key = chain.hierarchy.get(path, false, false);
key = key.encrypt(checkNotNull(basicKeyChain.getKeyCrypter()), aesKey, parent);
key = key.encrypt(Objects.requireNonNull(basicKeyChain.getKeyCrypter()), aesKey, parent);
putKey(key);
return key;
}
@ -561,12 +561,12 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
// Clone key to new hierarchy.
private static DeterministicKey cloneKey(DeterministicHierarchy hierarchy, DeterministicKey key) {
DeterministicKey parent = hierarchy.get(checkNotNull(key.getParent()).getPath(), false, false);
DeterministicKey parent = hierarchy.get(Objects.requireNonNull(key.getParent()).getPath(), false, false);
return new DeterministicKey(key.dropPrivateBytes(), parent);
}
private void checkForBitFlip(DeterministicKey k) {
DeterministicKey parent = checkNotNull(k.getParent());
DeterministicKey parent = Objects.requireNonNull(k.getParent());
byte[] rederived = HDKeyDerivation.deriveChildKeyBytesFromPublic(parent, k.getChildNumber(), HDKeyDerivation.PublicDeriveMode.WITH_INVERSION).keyBytes;
byte[] actual = k.getPubKey();
if (!Arrays.equals(rederived, actual))
@ -955,7 +955,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
Protos.EncryptedData proto = key.getEncryptedData();
EncryptedData data = new EncryptedData(proto.getInitialisationVector().toByteArray(),
proto.getEncryptedPrivateKey().toByteArray());
checkNotNull(crypter, "Encountered an encrypted key but no key crypter provided");
Objects.requireNonNull(crypter, "Encountered an encrypted key but no key crypter provided");
detkey = new DeterministicKey(path, chainCode, crypter, pubkey, data, parent);
} else {
// No secret key bytes and key is not encrypted: either a watching key or private key bytes
@ -1026,7 +1026,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
@Override
public DeterministicKeyChain toEncrypted(CharSequence password) {
checkNotNull(password);
Objects.requireNonNull(password);
checkArgument(password.length() > 0);
checkState(seed != null, "Attempt to encrypt a watching chain.");
checkState(!seed.isEncrypted());
@ -1042,7 +1042,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
@Override
public DeterministicKeyChain toDecrypted(CharSequence password) {
checkNotNull(password);
Objects.requireNonNull(password);
checkArgument(password.length() > 0);
KeyCrypter crypter = getKeyCrypter();
checkState(crypter != null, "Chain not encrypted");
@ -1088,7 +1088,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
@Override
public boolean checkPassword(CharSequence password) {
checkNotNull(password);
Objects.requireNonNull(password);
checkState(getKeyCrypter() != null, "Key chain not encrypted");
return checkAESKey(getKeyCrypter().deriveKey(password));
}
@ -1096,7 +1096,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
@Override
public boolean checkAESKey(AesKey aesKey) {
checkState(rootKey != null, "Can't check password for a watching chain");
checkNotNull(aesKey);
Objects.requireNonNull(aesKey);
checkState(getKeyCrypter() != null, "Key chain not encrypted");
try {
return rootKey.decrypt(aesKey).getPubKeyPoint().equals(rootKey.getPubKeyPoint());

View file

@ -37,7 +37,6 @@ import java.util.Objects;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import org.bitcoinj.base.internal.ByteUtils;
@ -66,7 +65,7 @@ public class DeterministicSeed implements EncryptableItem {
* @param creationTime when the seed was originally created
*/
public static DeterministicSeed ofMnemonic(String mnemonicCode, String passphrase, Instant creationTime) {
return new DeterministicSeed(mnemonicCode, null, passphrase, checkNotNull(creationTime));
return new DeterministicSeed(mnemonicCode, null, passphrase, Objects.requireNonNull(creationTime));
}
/**
@ -87,7 +86,7 @@ public class DeterministicSeed implements EncryptableItem {
* @param creationTime when the seed was originally created
*/
public static DeterministicSeed ofMnemonic(List<String> mnemonicCode, String passphrase, Instant creationTime) {
return new DeterministicSeed(mnemonicCode, null, passphrase, checkNotNull(creationTime));
return new DeterministicSeed(mnemonicCode, null, passphrase, Objects.requireNonNull(creationTime));
}
/**
@ -108,7 +107,7 @@ public class DeterministicSeed implements EncryptableItem {
* @param creationTime when the seed was originally created
*/
public static DeterministicSeed ofEntropy(byte[] entropy, String passphrase, Instant creationTime) {
return new DeterministicSeed(entropy, passphrase, checkNotNull(creationTime));
return new DeterministicSeed(entropy, passphrase, Objects.requireNonNull(creationTime));
}
/**
@ -148,8 +147,8 @@ public class DeterministicSeed implements EncryptableItem {
/** Internal use only. */
private DeterministicSeed(byte[] seed, List<String> mnemonic, @Nullable Instant creationTime) {
this.seed = checkNotNull(seed);
this.mnemonicCode = checkNotNull(mnemonic);
this.seed = Objects.requireNonNull(seed);
this.mnemonicCode = Objects.requireNonNull(mnemonic);
this.encryptedMnemonicCode = null;
this.encryptedSeed = null;
this.creationTime = creationTime;
@ -159,7 +158,7 @@ public class DeterministicSeed implements EncryptableItem {
DeterministicSeed(EncryptedData encryptedMnemonic, @Nullable EncryptedData encryptedSeed, @Nullable Instant creationTime) {
this.seed = null;
this.mnemonicCode = null;
this.encryptedMnemonicCode = checkNotNull(encryptedMnemonic);
this.encryptedMnemonicCode = Objects.requireNonNull(encryptedMnemonic);
this.encryptedSeed = encryptedSeed;
this.creationTime = creationTime;
}
@ -172,7 +171,7 @@ public class DeterministicSeed implements EncryptableItem {
/** Internal use only. */
private DeterministicSeed(List<String> mnemonicCode, @Nullable byte[] seed, String passphrase, @Nullable Instant creationTime) {
this((seed != null ? seed : MnemonicCode.toSeed(mnemonicCode, checkNotNull(passphrase))), mnemonicCode, creationTime);
this((seed != null ? seed : MnemonicCode.toSeed(mnemonicCode, Objects.requireNonNull(passphrase))), mnemonicCode, creationTime);
}
/** @deprecated use {@link #ofMnemonic(List, String, Instant)} or {@link #ofMnemonic(List, String)} */
@ -184,13 +183,13 @@ public class DeterministicSeed implements EncryptableItem {
/** @deprecated use {@link #ofRandom(SecureRandom, int, String)} */
@Deprecated
public DeterministicSeed(SecureRandom random, int bits, String passphrase) {
this(getEntropy(random, bits), checkNotNull(passphrase), TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS));
this(getEntropy(random, bits), Objects.requireNonNull(passphrase), TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS));
}
/** Internal use only. */
private DeterministicSeed(byte[] entropy, String passphrase, @Nullable Instant creationTime) {
checkArgument(entropy.length * 8 >= DEFAULT_SEED_ENTROPY_BITS, "entropy size too small");
checkNotNull(passphrase);
Objects.requireNonNull(passphrase);
this.mnemonicCode = MnemonicCode.INSTANCE.toMnemonic(entropy);
this.seed = MnemonicCode.toSeed(mnemonicCode, passphrase);
@ -278,7 +277,7 @@ public class DeterministicSeed implements EncryptableItem {
* @param creationTime creation time of this seed
*/
public void setCreationTime(Instant creationTime) {
this.creationTime = checkNotNull(creationTime);
this.creationTime = Objects.requireNonNull(creationTime);
}
/**
@ -314,7 +313,7 @@ public class DeterministicSeed implements EncryptableItem {
public DeterministicSeed decrypt(KeyCrypter crypter, String passphrase, AesKey aesKey) {
checkState(isEncrypted());
checkNotNull(encryptedMnemonicCode);
Objects.requireNonNull(encryptedMnemonicCode);
List<String> mnemonic = decodeMnemonicCode(crypter.decrypt(encryptedMnemonicCode, aesKey));
byte[] seed = encryptedSeed == null ? null : crypter.decrypt(encryptedSeed, aesKey);
return new DeterministicSeed(mnemonic, seed, passphrase, creationTime);

View file

@ -52,13 +52,13 @@ import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
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.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
@ -735,7 +735,7 @@ public class KeyChainGroup implements KeyBag {
* @throws java.lang.IllegalArgumentException if the key is deterministic.
*/
public boolean removeImportedKey(ECKey key) {
checkNotNull(key);
Objects.requireNonNull(key);
checkArgument(!(key instanceof DeterministicKey));
return basic.removeKey(key);
}
@ -758,8 +758,8 @@ public class KeyChainGroup implements KeyBag {
* @throws DeterministicUpgradeRequiredException Thrown if there are random keys but no HD chain.
*/
public void encrypt(KeyCrypter keyCrypter, AesKey aesKey) {
checkNotNull(keyCrypter);
checkNotNull(aesKey);
Objects.requireNonNull(keyCrypter);
Objects.requireNonNull(aesKey);
checkState((chains != null && !chains.isEmpty()) || basic.numKeys() != 0, "can't encrypt entirely empty wallet");
BasicKeyChain newBasic = basic.toEncrypted(keyCrypter, aesKey);
@ -785,7 +785,7 @@ public class KeyChainGroup implements KeyBag {
* @throws org.bitcoinj.crypto.KeyCrypterException Thrown if the wallet decryption fails for some reason, leaving the group unchanged.
*/
public void decrypt(AesKey aesKey) {
checkNotNull(aesKey);
Objects.requireNonNull(aesKey);
BasicKeyChain newBasic = basic.toDecrypted(aesKey);
if (chains != null) {
@ -899,8 +899,8 @@ public class KeyChainGroup implements KeyBag {
/** Adds a listener for events that are run when keys are added, on the given executor. */
public void addEventListener(KeyChainEventListener listener, Executor executor) {
checkNotNull(listener);
checkNotNull(executor);
Objects.requireNonNull(listener);
Objects.requireNonNull(executor);
basic.addEventListener(listener, executor);
if (chains != null)
for (DeterministicKeyChain chain : chains)
@ -909,7 +909,7 @@ public class KeyChainGroup implements KeyBag {
/** Removes a listener for events that are run when keys are added. */
public boolean removeEventListener(KeyChainEventListener listener) {
checkNotNull(listener);
Objects.requireNonNull(listener);
if (chains != null)
for (DeterministicKeyChain chain : chains)
chain.removeEventListener(listener);
@ -926,13 +926,13 @@ public class KeyChainGroup implements KeyBag {
* executor.
*/
public void addCurrentKeyChangeEventListener(CurrentKeyChangeEventListener listener, Executor executor) {
checkNotNull(listener);
Objects.requireNonNull(listener);
currentKeyChangeListeners.add(new ListenerRegistration<>(listener, executor));
}
/** Removes a listener for events that are run when a current key and/or address changes. */
public boolean removeCurrentKeyChangeEventListener(CurrentKeyChangeEventListener listener) {
checkNotNull(listener);
Objects.requireNonNull(listener);
return ListenerRegistration.removeFromList(listener, currentKeyChangeListeners);
}
@ -981,7 +981,7 @@ public class KeyChainGroup implements KeyBag {
}
public static KeyChainGroup fromProtobufEncrypted(NetworkParameters params, List<Protos.Key> keys, KeyCrypter crypter, KeyChainFactory factory) throws UnreadableWalletException {
checkNotNull(crypter);
Objects.requireNonNull(crypter);
BasicKeyChain basicKeyChain = BasicKeyChain.fromProtobufEncrypted(keys, crypter);
List<DeterministicKeyChain> chains = DeterministicKeyChain.fromProtobuf(keys, crypter, factory);
int lookaheadSize = -1, lookaheadThreshold = -1;
@ -1025,7 +1025,7 @@ public class KeyChainGroup implements KeyBag {
@Nullable Instant keyRotationTime, @Nullable AesKey aesKey)
throws DeterministicUpgradeRequiresPassword {
checkState(supportsDeterministicChains(), "doesn't support deterministic chains");
checkNotNull(structure);
Objects.requireNonNull(structure);
if (!isDeterministicUpgradeRequired(preferredScriptType, keyRotationTime))
return; // Nothing to do.
@ -1044,7 +1044,7 @@ public class KeyChainGroup implements KeyBag {
.outputScriptType(ScriptType.P2WPKH)
.accountPath(structure.accountPathFor(ScriptType.P2WPKH, BitcoinNetwork.MAINNET)).build();
if (seedWasEncrypted)
chain = chain.toEncrypted(checkNotNull(keyCrypter), aesKey);
chain = chain.toEncrypted(Objects.requireNonNull(keyCrypter), aesKey);
addAndActivateHDChain(chain);
}
}

View file

@ -32,8 +32,7 @@ import org.slf4j.LoggerFactory;
import java.time.Instant;
import java.util.LinkedList;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
/**
* A coin selector that takes all coins assigned to keys created before the given timestamp.
@ -50,7 +49,7 @@ public class KeyTimeCoinSelector implements CoinSelector {
private final boolean ignorePending;
public KeyTimeCoinSelector(Wallet wallet, Instant time, boolean ignorePending) {
this.time = checkNotNull(time);
this.time = Objects.requireNonNull(time);
this.wallet = wallet;
this.ignorePending = ignorePending;
}
@ -82,7 +81,7 @@ public class KeyTimeCoinSelector implements CoinSelector {
log.info("Skipping tx output {} because it's not of simple form.", output);
continue;
}
checkNotNull(controllingKey, "Coin selector given output as candidate for which we lack the key");
Objects.requireNonNull(controllingKey, "Coin selector given output as candidate for which we lack the key");
if (controllingKey.getCreationTime().orElse(Instant.EPOCH).compareTo(time) >= 0) continue;
// It's older than the cutoff time so select.
gathered.push(output);

View file

@ -36,11 +36,11 @@ import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
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.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
@ -94,7 +94,7 @@ public class MarriedKeyChain extends DeterministicKeyChain {
@Override
public MarriedKeyChain build() {
checkNotNull(followingKeys, "followingKeys must be provided");
Objects.requireNonNull(followingKeys, "followingKeys must be provided");
if (threshold == 0)
threshold = (followingKeys.size() + 1) / 2 + 1;

View file

@ -31,7 +31,7 @@ import org.bitcoinj.utils.ExchangeRate;
import org.bitcoinj.wallet.KeyChain.KeyPurpose;
import org.bitcoinj.wallet.Wallet.MissingSigsMode;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
/**
* A SendRequest gives the wallet information about precisely how to send money to a recipient or set of recipients.
@ -171,7 +171,7 @@ public class SendRequest {
public static SendRequest to(Address destination, Coin value) {
SendRequest req = new SendRequest();
final NetworkParameters parameters = NetworkParameters.of(destination.network());
checkNotNull(parameters, "Address is for an unknown network");
Objects.requireNonNull(parameters, "Address is for an unknown network");
req.tx = new Transaction(parameters);
req.tx.addOutput(value, destination);
return req;
@ -202,7 +202,7 @@ public class SendRequest {
public static SendRequest emptyWallet(Address destination) {
SendRequest req = new SendRequest();
final NetworkParameters parameters = NetworkParameters.of(destination.network());
checkNotNull(parameters, "Address is for an unknown network");
Objects.requireNonNull(parameters, "Address is for an unknown network");
req.tx = new Transaction(parameters);
req.tx.addOutput(Coin.ZERO, destination);
req.emptyWallet = true;
@ -224,7 +224,7 @@ public class SendRequest {
}
}
// TODO spend another confirmed output of own wallet if needed
checkNotNull(outputToSpend, "Can't find adequately sized output that spends to us");
Objects.requireNonNull(outputToSpend, "Can't find adequately sized output that spends to us");
final Transaction tx = new Transaction(parentTransaction.getParams());
tx.addInput(outputToSpend);
@ -257,4 +257,4 @@ public class SendRequest {
helper.add("recipientsPayFees", recipientsPayFees);
return helper.toString();
}
}
}

View file

@ -128,6 +128,7 @@ import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
@ -139,7 +140,6 @@ 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.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
// To do list:
@ -509,8 +509,8 @@ public class Wallet extends BaseTaggableObject
* @param keyChainGroup keychain group to manage keychains
*/
public Wallet(NetworkParameters params, KeyChainGroup keyChainGroup) {
this.params = checkNotNull(params);
this.keyChainGroup = checkNotNull(keyChainGroup);
this.params = Objects.requireNonNull(params);
this.keyChainGroup = Objects.requireNonNull(keyChainGroup);
watchedScripts = new HashSet<>();
unspent = new HashMap<>();
spent = new HashMap<>();
@ -941,7 +941,7 @@ public class Wallet extends BaseTaggableObject
public int importKeysAndEncrypt(final List<ECKey> keys, CharSequence password) {
keyChainGroupLock.lock();
try {
checkNotNull(getKeyCrypter(), "Wallet is not encrypted");
Objects.requireNonNull(getKeyCrypter(), "Wallet is not encrypted");
return importKeysAndEncrypt(keys, getKeyCrypter().deriveKey(password));
} finally {
keyChainGroupLock.unlock();
@ -1664,7 +1664,7 @@ public class Wallet extends BaseTaggableObject
public void setRiskAnalyzer(RiskAnalysis.Analyzer analyzer) {
lock.lock();
try {
this.riskAnalyzer = checkNotNull(analyzer);
this.riskAnalyzer = Objects.requireNonNull(analyzer);
} finally {
lock.unlock();
}
@ -2607,7 +2607,7 @@ public class Wallet extends BaseTaggableObject
}
}
TransactionOutput output = checkNotNull(input.getConnectedOutput());
TransactionOutput output = Objects.requireNonNull(input.getConnectedOutput());
if (result == TransactionInput.ConnectionResult.ALREADY_SPENT) {
if (fromChain) {
// Can be:
@ -2630,7 +2630,7 @@ public class Wallet extends BaseTaggableObject
// Otherwise we saw a transaction spend our coins, but we didn't try and spend them ourselves yet.
// The outputs are already marked as spent by the connect call above, so check if there are any more for
// us to use. Move if not.
Transaction connected = checkNotNull(input.getConnectedTransaction());
Transaction connected = Objects.requireNonNull(input.getConnectedTransaction());
log.info(" marked {} as spent by {}", input.getOutpoint(), tx.getTxId());
maybeMovePool(connected, "prevtx");
// Just because it's connected doesn't mean it's actually ours: sometimes we have total visibility.
@ -3679,7 +3679,7 @@ public class Wallet extends BaseTaggableObject
public void setLastBlockSeenTime(Instant time) {
lock.lock();
try {
lastBlockSeenTime = checkNotNull(time);
lastBlockSeenTime = Objects.requireNonNull(time);
} finally {
lock.unlock();
}
@ -3853,7 +3853,7 @@ public class Wallet extends BaseTaggableObject
public Coin getBalance(CoinSelector selector) {
lock.lock();
try {
checkNotNull(selector);
Objects.requireNonNull(selector);
List<TransactionOutput> candidates = calculateAllSpendCandidates(true, false);
CoinSelection selection = selector.select((Coin) params.network().maxMoney(), candidates);
return selection.totalValue();
@ -4474,7 +4474,8 @@ public class Wallet extends BaseTaggableObject
}
RedeemData redeemData = txIn.getConnectedRedeemData(maybeDecryptingKeyBag);
checkNotNull(redeemData, "Transaction exists in wallet that we cannot redeem: %s", txIn.getOutpoint().getHash());
Objects.requireNonNull(redeemData, () ->
"Transaction exists in wallet that we cannot redeem: " + txIn.getOutpoint().getHash());
txIn.setScriptSig(scriptPubKey.createEmptyInputScript(redeemData.keys.get(0), redeemData.redeemScript));
txIn.setWitness(scriptPubKey.createEmptyWitness(redeemData.keys.get(0)));
}
@ -4532,7 +4533,7 @@ public class Wallet extends BaseTaggableObject
if (vUTXOProvider == null) {
candidates = myUnspents.stream()
.filter(output -> (!excludeUnsignable || canSignFor(output.getScriptPubKey())) &&
(!excludeImmatureCoinbases || checkNotNull(output.getParentTransaction()).isMature()))
(!excludeImmatureCoinbases || Objects.requireNonNull(output.getParentTransaction()).isMature()))
.collect(StreamUtils.toUnmodifiableList());
} else {
candidates = calculateAllSpendCandidatesFromUTXOProvider(excludeImmatureCoinbases);
@ -4579,7 +4580,7 @@ public class Wallet extends BaseTaggableObject
*/
protected LinkedList<TransactionOutput> calculateAllSpendCandidatesFromUTXOProvider(boolean excludeImmatureCoinbases) {
checkState(lock.isHeldByCurrentThread());
UTXOProvider utxoProvider = checkNotNull(vUTXOProvider, "No UTXO provider has been set");
UTXOProvider utxoProvider = Objects.requireNonNull(vUTXOProvider, "No UTXO provider has been set");
LinkedList<TransactionOutput> candidates = new LinkedList<>();
try {
int chainHeight = utxoProvider.getChainHeadHeight();
@ -4620,7 +4621,7 @@ public class Wallet extends BaseTaggableObject
* @return The list of stored outputs.
*/
protected List<UTXO> getStoredOutputsFromUTXOProvider() throws UTXOProviderException {
UTXOProvider utxoProvider = checkNotNull(vUTXOProvider, "No UTXO provider has been set");
UTXOProvider utxoProvider = Objects.requireNonNull(vUTXOProvider, "No UTXO provider has been set");
List<UTXO> candidates = new ArrayList<>();
List<ECKey> keys = getImportedKeys();
keys.addAll(getActiveKeyChain().getLeafKeys());
@ -5069,7 +5070,7 @@ public class Wallet extends BaseTaggableObject
* add the same extension twice (or two different objects that use the same ID) will throw an IllegalStateException.
*/
public void addExtension(WalletExtension extension) {
String id = checkNotNull(extension).getWalletExtensionID();
String id = Objects.requireNonNull(extension).getWalletExtensionID();
lock.lock();
try {
if (extensions.containsKey(id))
@ -5085,7 +5086,7 @@ public class Wallet extends BaseTaggableObject
* Atomically adds extension or returns an existing extension if there is one with the same id already present.
*/
public WalletExtension addOrGetExistingExtension(WalletExtension extension) {
String id = checkNotNull(extension).getWalletExtensionID();
String id = Objects.requireNonNull(extension).getWalletExtensionID();
lock.lock();
try {
WalletExtension previousExtension = extensions.get(id);
@ -5105,7 +5106,7 @@ public class Wallet extends BaseTaggableObject
* already present.
*/
public void addOrUpdateExtension(WalletExtension extension) {
String id = checkNotNull(extension).getWalletExtensionID();
String id = Objects.requireNonNull(extension).getWalletExtensionID();
lock.lock();
try {
extensions.put(id, extension);
@ -5290,16 +5291,16 @@ public class Wallet extends BaseTaggableObject
Script redeemScript = null;
if (ScriptPattern.isP2PKH(script)) {
key = findKeyFromPubKeyHash(ScriptPattern.extractHashFromP2PKH(script), ScriptType.P2PKH);
checkNotNull(key, "Coin selection includes unspendable outputs");
Objects.requireNonNull(key, "Coin selection includes unspendable outputs");
vsize += script.getNumberOfBytesRequiredToSpend(key, redeemScript);
} else if (ScriptPattern.isP2WPKH(script)) {
key = findKeyFromPubKeyHash(ScriptPattern.extractHashFromP2WH(script), ScriptType.P2WPKH);
checkNotNull(key, "Coin selection includes unspendable outputs");
Objects.requireNonNull(key, "Coin selection includes unspendable outputs");
vsize += IntMath.divide(script.getNumberOfBytesRequiredToSpend(key, redeemScript), 4,
RoundingMode.CEILING); // round up
} else if (ScriptPattern.isP2SH(script)) {
redeemScript = findRedeemDataFromScriptHash(ScriptPattern.extractHashFromP2SH(script)).redeemScript;
checkNotNull(redeemScript, "Coin selection includes unspendable outputs");
Objects.requireNonNull(redeemScript, "Coin selection includes unspendable outputs");
vsize += script.getNumberOfBytesRequiredToSpend(key, redeemScript);
} else {
vsize += script.getNumberOfBytesRequiredToSpend(key, redeemScript);

View file

@ -30,13 +30,12 @@ import java.sql.Time;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A class that handles atomic and optionally delayed writing of the wallet file to disk. In future: backups too.
* It can be useful to delay writing of a wallet file to disk on slow devices where disk and serialization overhead
@ -82,11 +81,11 @@ public class WalletFiles {
this.executor.setKeepAliveTime(5, TimeUnit.SECONDS);
this.executor.allowCoreThreadTimeOut(true);
this.executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
this.wallet = checkNotNull(wallet);
this.wallet = Objects.requireNonNull(wallet);
// File must only be accessed from the auto-save executor from now on, to avoid simultaneous access.
this.file = checkNotNull(file);
this.file = Objects.requireNonNull(file);
this.savePending = new AtomicBoolean();
this.delay = checkNotNull(delay);
this.delay = Objects.requireNonNull(delay);
this.saver = () -> {
// Runs in an auto save thread.
@ -120,7 +119,7 @@ public class WalletFiles {
* The given listener will be called on the autosave thread before and after the wallet is saved to disk.
*/
public void setListener(@Nonnull Listener listener) {
this.vListener = checkNotNull(listener);
this.vListener = Objects.requireNonNull(listener);
}
/** Actually write the wallet file to disk, using an atomic rename when possible. Runs on the current thread. */

View file

@ -61,10 +61,9 @@ import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Serialize and de-serialize a wallet to a byte stream containing a
* <a href="https://developers.google.com/protocol-buffers/docs/overview">protocol buffer</a>. Protocol buffers are
@ -742,7 +741,7 @@ public class WalletProtobufSerializer {
tx.getTxId(), byteStringToHash(spentByTransactionHash)));
}
final int spendingIndex = transactionOutput.getSpentByTransactionIndex();
TransactionInput input = checkNotNull(spendingTx.getInput(spendingIndex));
TransactionInput input = Objects.requireNonNull(spendingTx.getInput(spendingIndex));
input.connect(output);
}
}

View file

@ -18,7 +18,7 @@ package org.bitcoinj.wallet;
import org.bitcoinj.core.Transaction;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
/**
* Stores data about a transaction that is only relevant to the {@link Wallet} class.
@ -34,7 +34,7 @@ public class WalletTransaction {
private final Pool pool;
public WalletTransaction(Pool pool, Transaction transaction) {
this.pool = checkNotNull(pool);
this.pool = Objects.requireNonNull(pool);
this.transaction = transaction;
}

View file

@ -42,10 +42,10 @@ import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.bitcoinj.base.Coin.CENT;
import static org.bitcoinj.base.Coin.COIN;
import static org.bitcoinj.base.Coin.FIFTY_COINS;
@ -346,9 +346,9 @@ public class ChainSplitTest {
Block b1 = TESTNET.getGenesisBlock().createNextBlock(coinsTo);
chain.add(b1);
Transaction t1 = checkNotNull(wallet.createSend(someOtherGuy, valueOf(10, 0)));
Transaction t1 = Objects.requireNonNull(wallet.createSend(someOtherGuy, valueOf(10, 0)));
Address yetAnotherGuy = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
Transaction t2 = checkNotNull(wallet.createSend(yetAnotherGuy, valueOf(20, 0)));
Transaction t2 = Objects.requireNonNull(wallet.createSend(yetAnotherGuy, valueOf(20, 0)));
wallet.commitTx(t1);
// t1 is still pending ...
Block b2 = b1.createNextBlock(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
@ -383,8 +383,8 @@ public class ChainSplitTest {
assertEquals(ZERO, wallet.getBalance());
// t2 is pending - resurrected double spends take precedence over our dead transactions (which are in nobodies
// mempool by this point).
t1 = checkNotNull(wallet.getTransaction(t1.getTxId()));
t2 = checkNotNull(wallet.getTransaction(t2.getTxId()));
t1 = Objects.requireNonNull(wallet.getTransaction(t1.getTxId()));
t2 = Objects.requireNonNull(wallet.getTransaction(t2.getTxId()));
assertEquals(ConfidenceType.DEAD, t1.getConfidence().getConfidenceType());
assertEquals(ConfidenceType.PENDING, t2.getConfidence().getConfidenceType());
}
@ -517,9 +517,9 @@ public class ChainSplitTest {
chain.add(b1);
// Send a couple of payments one after the other (so the second depends on the change output of the first).
Transaction t2 = checkNotNull(wallet.createSend(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET), CENT, true));
Transaction t2 = Objects.requireNonNull(wallet.createSend(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET), CENT, true));
wallet.commitTx(t2);
Transaction t3 = checkNotNull(wallet.createSend(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET), CENT, true));
Transaction t3 = Objects.requireNonNull(wallet.createSend(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET), CENT, true));
wallet.commitTx(t3);
chain.add(FakeTxBuilder.makeSolvedTestBlock(b1, t2, t3));

View file

@ -46,11 +46,11 @@ import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static org.bitcoinj.base.Coin.FIFTY_COINS;
import static org.bitcoinj.base.Coin.SATOSHI;
@ -254,7 +254,7 @@ public class FullBlockTestGenerator {
// genesis -> b1 (0) -> b2 (1)
// \-> b3 (1) -> b4 (2)
//
TransactionOutPointWithValue out2 = checkNotNull(spendableOutputs.poll());
TransactionOutPointWithValue out2 = Objects.requireNonNull(spendableOutputs.poll());
NewBlock b4 = createNextBlock(b3, chainHeadHeight + 3, out2, null);
blocks.add(new BlockAndValidity(b4, true, false, b4.getHash(), chainHeadHeight + 3, "b4"));
@ -1460,10 +1460,10 @@ public class FullBlockTestGenerator {
// \-> b80 (25) -> b81 (26) -> b82 (27)
// b78 creates a tx, which is spent in b79. after b82, both should be in mempool
//
TransactionOutPointWithValue out24 = checkNotNull(spendableOutputs.poll());
TransactionOutPointWithValue out25 = checkNotNull(spendableOutputs.poll());
TransactionOutPointWithValue out26 = checkNotNull(spendableOutputs.poll());
TransactionOutPointWithValue out27 = checkNotNull(spendableOutputs.poll());
TransactionOutPointWithValue out24 = Objects.requireNonNull(spendableOutputs.poll());
TransactionOutPointWithValue out25 = Objects.requireNonNull(spendableOutputs.poll());
TransactionOutPointWithValue out26 = Objects.requireNonNull(spendableOutputs.poll());
TransactionOutPointWithValue out27 = Objects.requireNonNull(spendableOutputs.poll());
NewBlock b77 = createNextBlock(b76, chainHeadHeight + 25, out24, null);
blocks.add(new BlockAndValidity(b77, true, false, b77.getHash(), chainHeadHeight + 25, "b77"));

View file

@ -41,6 +41,7 @@ import java.security.SignatureException;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
@ -48,7 +49,6 @@ import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.bitcoinj.base.internal.ByteUtils.reverseBytes;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
@ -327,7 +327,7 @@ public class ECKeyTest {
boolean found = false;
for (int i = 0; i < 4; i++) {
ECKey key2 = ECKey.recoverFromSignature(i, sig, hash, true);
checkNotNull(key2);
Objects.requireNonNull(key2);
if (key.equals(key2)) {
found = true;
break;
@ -356,7 +356,7 @@ public class ECKeyTest {
@Test
public void testEncryptedCreate() {
ECKey unencryptedKey = new ECKey();
byte[] originalPrivateKeyBytes = checkNotNull(unencryptedKey.getPrivKeyBytes());
byte[] originalPrivateKeyBytes = Objects.requireNonNull(unencryptedKey.getPrivKeyBytes());
log.info("Original private key = " + ByteUtils.formatHex(originalPrivateKeyBytes));
EncryptedData encryptedPrivateKey = keyCrypter.encrypt(unencryptedKey.getPrivKeyBytes(), keyCrypter.deriveKey(PASSWORD1));
ECKey encryptedKey = ECKey.fromEncrypted(encryptedPrivateKey, keyCrypter, unencryptedKey.getPubKey());
@ -425,7 +425,7 @@ public class ECKeyTest {
boolean found = false;
for (int i = 0; i < 4; i++) {
ECKey key2 = ECKey.recoverFromSignature(i, sig, hash, true);
checkNotNull(key2);
Objects.requireNonNull(key2);
if (unencryptedKey.equals(key2)) {
found = true;
break;

View file

@ -71,9 +71,9 @@ import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.bitcoinj.base.Coin.COIN;
import static org.bitcoinj.base.Coin.FIFTY_COINS;
import static org.bitcoinj.testing.FakeTxBuilder.createFakeTx;
@ -253,9 +253,9 @@ public class WalletProtobufSerializerTest {
tx2.getInput(0).setSequenceNumber(TransactionInput.NO_SEQUENCE - 1);
wallet.receivePending(tx2, null);
Wallet walletCopy = roundTrip(wallet);
Transaction tx1copy = checkNotNull(walletCopy.getTransaction(tx1.getTxId()));
Transaction tx1copy = Objects.requireNonNull(walletCopy.getTransaction(tx1.getTxId()));
assertEquals(TransactionInput.NO_SEQUENCE, tx1copy.getInput(0).getSequenceNumber());
Transaction tx2copy = checkNotNull(walletCopy.getTransaction(tx2.getTxId()));
Transaction tx2copy = Objects.requireNonNull(walletCopy.getTransaction(tx2.getTxId()));
assertEquals(TransactionInput.NO_SEQUENCE - 1, tx2copy.getInput(0).getSequenceNumber());
}
@ -392,7 +392,7 @@ public class WalletProtobufSerializerTest {
myWallet.addWalletTransaction(new WalletTransaction(Pool.UNSPENT, tx));
Wallet wallet1 = roundTrip(myWallet);
Transaction tx2 = wallet1.getTransaction(tx.getTxId());
assertEquals(checkNotNull(tx2).getVersion(), 2);
assertEquals(Objects.requireNonNull(tx2).getVersion(), 2);
}
@Test

View file

@ -36,10 +36,10 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@ -231,7 +231,7 @@ public class BasicKeyChainTest {
assertArrayEquals(key1.getPubKey(), keys.get(0).getPublicKey().toByteArray());
assertFalse(keys.get(0).hasSecretBytes());
assertTrue(keys.get(0).hasEncryptedData());
chain = BasicKeyChain.fromProtobufEncrypted(keys, checkNotNull(chain.getKeyCrypter()));
chain = BasicKeyChain.fromProtobufEncrypted(keys, Objects.requireNonNull(chain.getKeyCrypter()));
assertEquals(key1.getEncryptedPrivateKey(), chain.getKeys().get(0).getEncryptedPrivateKey());
assertTrue(chain.checkPassword("foo bar"));
}

View file

@ -36,8 +36,8 @@ import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.bitcoinj.base.Coin.CENT;
import static org.bitcoinj.base.Coin.COIN;
import static org.junit.Assert.assertEquals;
@ -84,8 +84,8 @@ public class DefaultCoinSelectorTest extends TestWithWallet {
@Test
public void depthOrdering() {
// Send two transactions in two blocks on top of each other.
Transaction t1 = checkNotNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN));
Transaction t2 = checkNotNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN));
Transaction t1 = Objects.requireNonNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN));
Transaction t2 = Objects.requireNonNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN));
// Check we selected just the oldest one.
DefaultCoinSelector selector = DefaultCoinSelector.get();
@ -106,12 +106,12 @@ public class DefaultCoinSelectorTest extends TestWithWallet {
public void coinAgeOrdering() {
// Send three transactions in four blocks on top of each other. Coin age of t1 is 1*4=4, coin age of t2 = 2*2=4
// and t3=0.01.
Transaction t1 = checkNotNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN));
Transaction t1 = Objects.requireNonNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN));
// Padding block.
wallet.notifyNewBestBlock(FakeTxBuilder.createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).storedBlock);
final Coin TWO_COINS = COIN.multiply(2);
Transaction t2 = checkNotNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, TWO_COINS));
Transaction t3 = checkNotNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT));
Transaction t2 = Objects.requireNonNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, TWO_COINS));
Transaction t3 = Objects.requireNonNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT));
// Should be ordered t2, t1, t3.
ArrayList<TransactionOutput> candidates = new ArrayList<>();

View file

@ -50,11 +50,11 @@ import java.security.SecureRandom;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static org.bitcoinj.base.BitcoinNetwork.MAINNET;
import static org.bitcoinj.base.BitcoinNetwork.TESTNET;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
@ -357,7 +357,7 @@ public class DeterministicKeyChainTest {
assertFalse(key1.isEncrypted());
assertTrue(encKey1.isEncrypted());
assertEquals(encKey1.getPubKeyPoint(), key1.getPubKeyPoint());
final AesKey aesKey = checkNotNull(encChain.getKeyCrypter()).deriveKey("open secret");
final AesKey aesKey = Objects.requireNonNull(encChain.getKeyCrypter()).deriveKey("open secret");
encKey1.sign(Sha256Hash.ZERO_HASH, aesKey);
encKey2.sign(Sha256Hash.ZERO_HASH, aesKey);
assertTrue(encChain.checkAESKey(aesKey));

View file

@ -43,9 +43,9 @@ import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
@ -283,9 +283,9 @@ public class KeyChainGroupTest {
assertTrue(group.checkPassword("password"));
assertFalse(group.checkPassword("wrong password"));
final ECKey ea = group.findKeyFromPubKey(a.getPubKey());
assertTrue(checkNotNull(ea).isEncrypted());
assertTrue(Objects.requireNonNull(ea).isEncrypted());
if (withImported) {
assertTrue(checkNotNull(group.findKeyFromPubKey(b.getPubKey())).isEncrypted());
assertTrue(Objects.requireNonNull(group.findKeyFromPubKey(b.getPubKey())).isEncrypted());
assertEquals(yesterday, group.getEarliestKeyCreationTimeInstant());
} else {
assertEquals(now, group.getEarliestKeyCreationTimeInstant());
@ -320,9 +320,9 @@ public class KeyChainGroupTest {
group.decrypt(AES_KEY);
assertFalse(group.isEncrypted());
assertFalse(checkNotNull(group.findKeyFromPubKey(a.getPubKey())).isEncrypted());
assertFalse(Objects.requireNonNull(group.findKeyFromPubKey(a.getPubKey())).isEncrypted());
if (withImported) {
assertFalse(checkNotNull(group.findKeyFromPubKey(b.getPubKey())).isEncrypted());
assertFalse(Objects.requireNonNull(group.findKeyFromPubKey(b.getPubKey())).isEncrypted());
assertEquals(yesterday, group.getEarliestKeyCreationTimeInstant());
} else {
assertEquals(now, group.getEarliestKeyCreationTimeInstant());
@ -336,7 +336,7 @@ public class KeyChainGroupTest {
assertTrue(group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).isEncrypted());
final ECKey key = group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
group.decrypt(AES_KEY);
assertFalse(checkNotNull(group.findKeyFromPubKey(key.getPubKey())).isEncrypted());
assertFalse(Objects.requireNonNull(group.findKeyFromPubKey(key.getPubKey())).isEncrypted());
}
@Test
@ -514,7 +514,7 @@ public class KeyChainGroupTest {
@Test
public void constructFromSeed() {
ECKey key1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
final DeterministicSeed seed = checkNotNull(group.getActiveKeyChain().getSeed());
final DeterministicSeed seed = Objects.requireNonNull(group.getActiveKeyChain().getSeed());
KeyChainGroup group2 = KeyChainGroup.builder(MAINNET).lookaheadSize(5)
.addChain(DeterministicKeyChain.builder().seed(seed).outputScriptType(ScriptType.P2PKH).build())
.build();
@ -587,7 +587,7 @@ public class KeyChainGroupTest {
final DeterministicSeed deterministicSeed = group.getActiveKeyChain().getSeed();
assertNotNull(deterministicSeed);
assertTrue(deterministicSeed.isEncrypted());
byte[] entropy = checkNotNull(group.getActiveKeyChain().toDecrypted(AES_KEY).getSeed()).getEntropyBytes();
byte[] entropy = Objects.requireNonNull(group.getActiveKeyChain().toDecrypted(AES_KEY).getSeed()).getEntropyBytes();
}
@Test

View file

@ -90,6 +90,7 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
@ -98,7 +99,6 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.bitcoinj.base.Coin.CENT;
import static org.bitcoinj.base.Coin.COIN;
import static org.bitcoinj.base.Coin.MILLICOIN;
@ -858,15 +858,15 @@ public class WalletTest extends TestWithWallet {
final Coin value2 = valueOf(2, 0);
// Give us three coins and make sure we have some change.
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, value.add(value2));
Transaction send1 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value2));
Transaction send2 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value2));
Transaction send1 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, value2));
Transaction send2 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, value2));
byte[] buf = send1.bitcoinSerialize();
buf[43] = 0; // Break the signature: bitcoinj won't check in SPV mode and this is easier than other mutations.
send1 = TESTNET.getDefaultSerializer().makeTransaction(buf);
wallet.commitTx(send2);
assertEquals(value, wallet.getBalance(BalanceType.ESTIMATED));
// Now spend the change. This transaction should die permanently when the mutant appears in the chain.
Transaction send3 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value, true));
Transaction send3 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, value, true));
wallet.commitTx(send3);
assertEquals(ZERO, wallet.getBalance(BalanceType.AVAILABLE));
final LinkedList<TransactionConfidence> dead = new LinkedList<>();
@ -1169,8 +1169,8 @@ public class WalletTest extends TestWithWallet {
@Test
public void doubleSpendForBuildingTx() throws Exception {
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
Transaction send1 = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
Transaction send2 = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 20), true));
Transaction send1 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
Transaction send2 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 20), true));
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send1);
assertUnspent(send1);
@ -1183,11 +1183,11 @@ public class WalletTest extends TestWithWallet {
@Test
public void txSpendingDeadTx() throws Exception {
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
Transaction send1 = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
Transaction send2 = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 20), true));
Transaction send1 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
Transaction send2 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 20), true));
wallet.commitTx(send1);
assertPending(send1);
Transaction send1b = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 50), true));
Transaction send1b = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 50), true));
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send2);
assertDead(send1);
@ -1227,12 +1227,12 @@ public class WalletTest extends TestWithWallet {
@Test
public void testAddTransactionsDependingOn() throws Exception {
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
Transaction send1 = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
Transaction send2 = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 20), true));
Transaction send1 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
Transaction send2 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 20), true));
wallet.commitTx(send1);
Transaction send1b = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 50), true));
Transaction send1b = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 50), true));
wallet.commitTx(send1b);
Transaction send1c = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 25), true));
Transaction send1c = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 25), true));
wallet.commitTx(send1c);
wallet.commitTx(send2);
Set<Transaction> txns = new HashSet<>();
@ -1247,15 +1247,15 @@ public class WalletTest extends TestWithWallet {
@Test
public void sortTxnsByDependency() throws Exception {
Transaction send1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
Transaction send1a = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
Transaction send1a = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
wallet.commitTx(send1a);
Transaction send1b = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 50), true));
Transaction send1b = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 50), true));
wallet.commitTx(send1b);
Transaction send1c = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 25), true));
Transaction send1c = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 25), true));
wallet.commitTx(send1c);
Transaction send1d = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 12), true));
Transaction send1d = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 12), true));
wallet.commitTx(send1d);
Transaction send1e = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 06), true));
Transaction send1e = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 06), true));
wallet.commitTx(send1e);
Transaction send2 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(200, 0));
@ -2092,7 +2092,7 @@ public class WalletTest extends TestWithWallet {
sendMoneyToWallet(encryptedWallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN, key.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
assertEquals(Coin.COIN, encryptedWallet.getBalance());
SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
req.aesKey = checkNotNull(encryptedWallet.getKeyCrypter()).deriveKey(PASSWORD1);
req.aesKey = Objects.requireNonNull(encryptedWallet.getKeyCrypter()).deriveKey(PASSWORD1);
encryptedWallet.sendCoinsOffline(req);
}
@ -2963,7 +2963,7 @@ public class WalletTest extends TestWithWallet {
wallet = roundTrip(wallet);
tx = wallet.getTransaction(tx.getTxId());
checkNotNull(tx);
Objects.requireNonNull(tx);
assertEquals(Transaction.Purpose.KEY_ROTATION, tx.getPurpose());
// Have to divide here to avoid mismatch due to second-level precision in serialisation.
assertEquals(compromiseTime, wallet.getKeyRotationTimeInstant().get());

View file

@ -22,8 +22,7 @@ import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.EnumSet;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.Network;
@ -148,7 +147,8 @@ public class GenerateLowSTests {
TransactionInput txIn = outputTransaction.getInput(i);
Script scriptPubKey = txIn.getConnectedOutput().getScriptPubKey();
RedeemData redeemData = txIn.getConnectedRedeemData(bag);
checkNotNull(redeemData, "Transaction exists in wallet that we cannot redeem: %s", txIn.getOutpoint().getHash());
Objects.requireNonNull(redeemData, () ->
"Transaction exists in wallet that we cannot redeem: " + txIn.getOutpoint().getHash());
txIn.setScriptSig(scriptPubKey.createEmptyInputScript(redeemData.keys.get(0), redeemData.redeemScript));
}
}

View file

@ -37,11 +37,11 @@ import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.bitcoinj.base.Coin.CENT;
import static org.bitcoinj.base.Coin.COIN;
import static org.bitcoinj.base.Coin.FIFTY_COINS;
@ -251,7 +251,7 @@ public class TransactionBroadcastTest extends TestWithPeerGroup {
// Do the same thing with an offline transaction.
peerGroup.removeWallet(wallet);
SendRequest req = SendRequest.to(dest, valueOf(2, 0));
Transaction t3 = checkNotNull(wallet.sendCoinsOffline(req));
Transaction t3 = Objects.requireNonNull(wallet.sendCoinsOffline(req));
assertNull(outbound(p1)); // Nothing sent.
// Add the wallet to the peer group (simulate initialization). Transactions should be announced.
peerGroup.addWallet(wallet);

View file

@ -39,8 +39,8 @@ import org.slf4j.LoggerFactory;
import org.bitcoinj.walletfx.utils.KeyDerivationTasks;
import java.time.Duration;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.bitcoinj.walletfx.utils.GuiUtils.*;
/**
@ -83,7 +83,7 @@ public class WalletPasswordController implements OverlayController<WalletPasswor
}
final KeyCrypterScrypt keyCrypter = (KeyCrypterScrypt) app.walletAppKit().wallet().getKeyCrypter();
checkNotNull(keyCrypter); // We should never arrive at this GUI if the wallet isn't actually encrypted.
Objects.requireNonNull(keyCrypter); // We should never arrive at this GUI if the wallet isn't actually encrypted.
KeyDerivationTasks tasks = new KeyDerivationTasks(keyCrypter, password, getTargetTime()) {
@Override
protected final void onFinish(AesKey aesKey, int timeTakenMsec) {

View file

@ -41,8 +41,8 @@ import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkNotNull;
import static javafx.beans.binding.Bindings.*;
import static org.bitcoinj.walletfx.utils.GuiUtils.checkGuiThread;
import static org.bitcoinj.walletfx.utils.GuiUtils.informationalAlert;
@ -82,7 +82,7 @@ public class WalletSettingsController implements OverlayController<WalletSetting
}
} else {
this.aesKey = aesKey;
seed = seed.decrypt(checkNotNull(app.walletAppKit().wallet().getKeyCrypter()), "", aesKey);
seed = seed.decrypt(Objects.requireNonNull(app.walletAppKit().wallet().getKeyCrypter()), "", aesKey);
// Now we can display the wallet seed as appropriate.
passwordButton.setText("Remove password");
}
@ -94,7 +94,7 @@ public class WalletSettingsController implements OverlayController<WalletSetting
// Set the mnemonic seed words.
final List<String> mnemonicCode = seed.getMnemonicCode();
checkNotNull(mnemonicCode); // Already checked for encryption.
Objects.requireNonNull(mnemonicCode); // Already checked for encryption.
String origWords = InternalUtils.SPACE_JOINER.join(mnemonicCode);
wordsArea.setText(origWords);

View file

@ -95,6 +95,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
@ -107,7 +108,6 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.bitcoinj.base.Coin.parseCoin;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A command line tool for manipulating wallets and working with Bitcoin.
@ -1158,7 +1158,7 @@ public class WalletTool implements Callable<Integer> {
AesKey aesKey = passwordToKey(true);
if (aesKey == null)
return; // Error message already printed.
key = key.encrypt(checkNotNull(wallet.getKeyCrypter()), aesKey);
key = key.encrypt(Objects.requireNonNull(wallet.getKeyCrypter()), aesKey);
}
} catch (KeyCrypterException kce) {
System.err.println("There was an encryption related error when adding the key. The error was '"
@ -1186,7 +1186,7 @@ public class WalletTool implements Callable<Integer> {
System.err.println("The password is incorrect.");
return null;
}
return checkNotNull(wallet.getKeyCrypter()).deriveKey(password);
return Objects.requireNonNull(wallet.getKeyCrypter()).deriveKey(password);
}
/**