mirror of
https://github.com/bitcoinj/bitcoinj.git
synced 2025-02-22 22:25:41 +01:00
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:
parent
36c82a3cfb
commit
9ec245c259
60 changed files with 311 additions and 341 deletions
|
@ -29,8 +29,6 @@ import java.util.Arrays;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.Objects;
|
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
|
* <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}
|
* 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
|
* 20-byte hash of pubkey or script
|
||||||
*/
|
*/
|
||||||
private LegacyAddress(Network network, boolean p2sh, byte[] hash160) throws AddressFormatException {
|
private LegacyAddress(Network network, boolean p2sh, byte[] hash160) throws AddressFormatException {
|
||||||
this.network = normalizeNetwork(checkNotNull(network));
|
this.network = normalizeNetwork(Objects.requireNonNull(network));
|
||||||
this.bytes = checkNotNull(hash160);
|
this.bytes = Objects.requireNonNull(hash160);
|
||||||
if (hash160.length != 20)
|
if (hash160.length != 20)
|
||||||
throw new AddressFormatException.InvalidDataLength(
|
throw new AddressFormatException.InvalidDataLength(
|
||||||
"Legacy addresses are 20 byte (160 bit) hashes, but got: " + hash160.length);
|
"Legacy addresses are 20 byte (160 bit) hashes, but got: " + hash160.length);
|
||||||
|
|
|
@ -31,7 +31,6 @@ import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
import static org.bitcoinj.base.BitcoinNetwork.*;
|
import static org.bitcoinj.base.BitcoinNetwork.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -184,9 +183,9 @@ public class SegwitAddress implements Address {
|
||||||
if (witnessVersion == 1 && witnessProgram.length != WITNESS_PROGRAM_LENGTH_TR)
|
if (witnessVersion == 1 && witnessProgram.length != WITNESS_PROGRAM_LENGTH_TR)
|
||||||
throw new AddressFormatException.InvalidDataLength(
|
throw new AddressFormatException.InvalidDataLength(
|
||||||
"Invalid length for address version 1: " + witnessProgram.length);
|
"Invalid length for address version 1: " + witnessProgram.length);
|
||||||
this.network = normalizeNetwork(checkNotNull(network));
|
this.network = normalizeNetwork(Objects.requireNonNull(network));
|
||||||
this.witnessVersion = (short) witnessVersion;
|
this.witnessVersion = (short) witnessVersion;
|
||||||
this.witnessProgram = checkNotNull(witnessProgram);
|
this.witnessProgram = Objects.requireNonNull(witnessProgram);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -47,13 +47,13 @@ import java.util.LinkedHashMap;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.concurrent.CopyOnWriteArrayList;
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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 com.google.common.base.Preconditions.checkState;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -727,7 +727,7 @@ public abstract class AbstractBlockChain {
|
||||||
sendTransactionsToListener(newStoredBlock, newBlockType, listener, 0, block.getTransactions(),
|
sendTransactionsToListener(newStoredBlock, newBlockType, listener, 0, block.getTransactions(),
|
||||||
!first, falsePositives);
|
!first, falsePositives);
|
||||||
} else if (filteredTxHashList != null) {
|
} 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
|
// 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
|
// set of hashes and call sendTransactionsToListener with individual txn when they have not already been
|
||||||
// seen in loose broadcasts - otherwise notifyTransactionIsInBlock on the hash.
|
// seen in loose broadcasts - otherwise notifyTransactionIsInBlock on the hash.
|
||||||
|
@ -856,7 +856,7 @@ public abstract class AbstractBlockChain {
|
||||||
StoredBlock cursor = higher;
|
StoredBlock cursor = higher;
|
||||||
do {
|
do {
|
||||||
results.add(cursor);
|
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));
|
} while (!cursor.equals(lower));
|
||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
@ -879,10 +879,10 @@ public abstract class AbstractBlockChain {
|
||||||
while (!currentChainCursor.equals(newChainCursor)) {
|
while (!currentChainCursor.equals(newChainCursor)) {
|
||||||
if (currentChainCursor.getHeight() > newChainCursor.getHeight()) {
|
if (currentChainCursor.getHeight() > newChainCursor.getHeight()) {
|
||||||
currentChainCursor = currentChainCursor.getPrev(store);
|
currentChainCursor = currentChainCursor.getPrev(store);
|
||||||
checkNotNull(currentChainCursor, "Attempt to follow an orphan chain");
|
Objects.requireNonNull(currentChainCursor, "Attempt to follow an orphan chain");
|
||||||
} else {
|
} else {
|
||||||
newChainCursor = newChainCursor.getPrev(store);
|
newChainCursor = newChainCursor.getPrev(store);
|
||||||
checkNotNull(newChainCursor, "Attempt to follow an orphan chain");
|
Objects.requireNonNull(newChainCursor, "Attempt to follow an orphan chain");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return currentChainCursor;
|
return currentChainCursor;
|
||||||
|
|
|
@ -18,7 +18,6 @@
|
||||||
package org.bitcoinj.core;
|
package org.bitcoinj.core;
|
||||||
|
|
||||||
import com.google.common.annotations.VisibleForTesting;
|
import com.google.common.annotations.VisibleForTesting;
|
||||||
import com.google.common.base.Preconditions;
|
|
||||||
import org.bitcoinj.base.Address;
|
import org.bitcoinj.base.Address;
|
||||||
import org.bitcoinj.base.Coin;
|
import org.bitcoinj.base.Coin;
|
||||||
import org.bitcoinj.base.Sha256Hash;
|
import org.bitcoinj.base.Sha256Hash;
|
||||||
|
@ -49,6 +48,7 @@ import java.util.EnumSet;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkState;
|
import static com.google.common.base.Preconditions.checkState;
|
||||||
import static org.bitcoinj.base.Coin.FIFTY_COINS;
|
import static org.bitcoinj.base.Coin.FIFTY_COINS;
|
||||||
|
@ -379,7 +379,7 @@ public class Block extends Message {
|
||||||
public byte[] bitcoinSerialize() {
|
public byte[] bitcoinSerialize() {
|
||||||
// we have completely cached byte array.
|
// we have completely cached byte array.
|
||||||
if (headerBytesValid && transactionBytesValid) {
|
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) {
|
if (length == payload.length) {
|
||||||
return payload;
|
return payload;
|
||||||
} else {
|
} else {
|
||||||
|
|
|
@ -46,10 +46,10 @@ import java.time.Instant;
|
||||||
import java.time.temporal.ChronoUnit;
|
import java.time.temporal.ChronoUnit;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.TreeMap;
|
import java.util.TreeMap;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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.checkPositionIndex;
|
||||||
import static com.google.common.base.Preconditions.checkState;
|
import static com.google.common.base.Preconditions.checkState;
|
||||||
|
|
||||||
|
@ -98,10 +98,10 @@ public class CheckpointManager {
|
||||||
|
|
||||||
/** Loads the checkpoints from the given stream */
|
/** Loads the checkpoints from the given stream */
|
||||||
public CheckpointManager(NetworkParameters params, @Nullable InputStream inputStream) throws IOException {
|
public CheckpointManager(NetworkParameters params, @Nullable InputStream inputStream) throws IOException {
|
||||||
this.params = checkNotNull(params);
|
this.params = Objects.requireNonNull(params);
|
||||||
if (inputStream == null)
|
if (inputStream == null)
|
||||||
inputStream = openStream(params);
|
inputStream = openStream(params);
|
||||||
checkNotNull(inputStream);
|
Objects.requireNonNull(inputStream);
|
||||||
inputStream = new BufferedInputStream(inputStream);
|
inputStream = new BufferedInputStream(inputStream);
|
||||||
inputStream.mark(1);
|
inputStream.mark(1);
|
||||||
int first = inputStream.read();
|
int first = inputStream.read();
|
||||||
|
@ -234,8 +234,8 @@ public class CheckpointManager {
|
||||||
*/
|
*/
|
||||||
public static void checkpoint(NetworkParameters params, InputStream checkpoints, BlockStore store, Instant time)
|
public static void checkpoint(NetworkParameters params, InputStream checkpoints, BlockStore store, Instant time)
|
||||||
throws IOException, BlockStoreException {
|
throws IOException, BlockStoreException {
|
||||||
checkNotNull(params);
|
Objects.requireNonNull(params);
|
||||||
checkNotNull(store);
|
Objects.requireNonNull(store);
|
||||||
checkArgument(!(store instanceof FullPrunedBlockStore), "You cannot use checkpointing with a full store.");
|
checkArgument(!(store instanceof FullPrunedBlockStore), "You cannot use checkpointing with a full store.");
|
||||||
|
|
||||||
time = time.minus(7, ChronoUnit.WEEKS);
|
time = time.minus(7, ChronoUnit.WEEKS);
|
||||||
|
|
|
@ -22,7 +22,7 @@ import org.bitcoinj.wallet.SendRequest;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
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: 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).
|
// 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}.
|
* a {@link ContextPropagatingThreadFactory}.
|
||||||
*/
|
*/
|
||||||
public static void propagate(Context context) {
|
public static void propagate(Context context) {
|
||||||
slot.set(checkNotNull(context));
|
slot.set(Objects.requireNonNull(context));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -19,8 +19,7 @@ package org.bitcoinj.core;
|
||||||
import org.bitcoinj.base.Coin;
|
import org.bitcoinj.base.Coin;
|
||||||
|
|
||||||
import javax.annotation.Nullable;
|
import javax.annotation.Nullable;
|
||||||
|
import java.util.Objects;
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Thrown to indicate that you don't have enough money available to perform the requested operation.
|
* 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) {
|
public InsufficientMoneyException(Coin missing, String message) {
|
||||||
super(message);
|
super(message);
|
||||||
this.missing = checkNotNull(missing);
|
this.missing = Objects.requireNonNull(missing);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -70,7 +70,6 @@ import java.util.concurrent.locks.ReentrantLock;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
import static com.google.common.base.Preconditions.checkState;
|
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> incomingVersionHandshakeFuture = new CompletableFuture<>();
|
||||||
private final CompletableFuture<Peer> versionHandshakeFuture = outgoingVersionHandshakeFuture
|
private final CompletableFuture<Peer> versionHandshakeFuture = outgoingVersionHandshakeFuture
|
||||||
.thenCombine(incomingVersionHandshakeFuture, (peer1, peer2) -> {
|
.thenCombine(incomingVersionHandshakeFuture, (peer1, peer2) -> {
|
||||||
checkNotNull(peer1);
|
Objects.requireNonNull(peer1);
|
||||||
checkState(peer1 == peer2);
|
checkState(peer1 == peer2);
|
||||||
return peer1;
|
return peer1;
|
||||||
});
|
});
|
||||||
|
@ -231,8 +230,8 @@ public class Peer extends PeerSocketHandler {
|
||||||
public Peer(NetworkParameters params, VersionMessage ver, PeerAddress remoteAddress,
|
public Peer(NetworkParameters params, VersionMessage ver, PeerAddress remoteAddress,
|
||||||
@Nullable AbstractBlockChain chain, long requiredServices, int downloadTxDependencyDepth) {
|
@Nullable AbstractBlockChain chain, long requiredServices, int downloadTxDependencyDepth) {
|
||||||
super(params, remoteAddress);
|
super(params, remoteAddress);
|
||||||
this.params = Preconditions.checkNotNull(params);
|
this.params = Objects.requireNonNull(params);
|
||||||
this.versionMessage = Preconditions.checkNotNull(ver);
|
this.versionMessage = Objects.requireNonNull(ver);
|
||||||
this.vDownloadTxDependencyDepth = chain != null ? downloadTxDependencyDepth : 0;
|
this.vDownloadTxDependencyDepth = chain != null ? downloadTxDependencyDepth : 0;
|
||||||
this.blockChain = chain; // Allowed to be null.
|
this.blockChain = chain; // Allowed to be null.
|
||||||
this.requiredServices = requiredServices;
|
this.requiredServices = requiredServices;
|
||||||
|
@ -971,7 +970,7 @@ public class Peer extends PeerSocketHandler {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
if (downloadBlockBodies) {
|
if (downloadBlockBodies) {
|
||||||
final Block orphanRoot = checkNotNull(blockChain.getOrphanRoot(m.getHash()));
|
final Block orphanRoot = Objects.requireNonNull(blockChain.getOrphanRoot(m.getHash()));
|
||||||
blockChainDownloadLocked(orphanRoot.getHash());
|
blockChainDownloadLocked(orphanRoot.getHash());
|
||||||
} else {
|
} else {
|
||||||
log.info("Did not start chain download on solved block due to in-flight header download.");
|
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.
|
// no matter how many blocks are solved, and therefore that the (2) duplicate filtering can work.
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
final Block orphanRoot = checkNotNull(blockChain.getOrphanRoot(m.getHash()));
|
final Block orphanRoot = Objects.requireNonNull(blockChain.getOrphanRoot(m.getHash()));
|
||||||
blockChainDownloadLocked(orphanRoot.getHash());
|
blockChainDownloadLocked(orphanRoot.getHash());
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock();
|
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
|
// 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
|
// 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.
|
// 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) {
|
for (final ListenerRegistration<BlocksDownloadedEventListener> registration : blocksDownloadedEventListeners) {
|
||||||
registration.executor.execute(() -> registration.listener.onBlocksDownloaded(Peer.this, block, fb, blocksLeft));
|
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 (blockChain.isOrphan(item.hash) && downloadBlockBodies) {
|
||||||
// If an orphan was re-advertised, ask for more blocks unless we are not currently downloading
|
// 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.
|
// 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());
|
blockChainDownloadLocked(orphanRoot.getHash());
|
||||||
} else {
|
} else {
|
||||||
// Don't re-request blocks we already requested. Normally this should not happen. However there is
|
// 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
|
// 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
|
// 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.
|
// 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();
|
StoredBlock chainHead = blockChain.getChainHead();
|
||||||
Sha256Hash chainHeadHash = chainHead.getHeader().getHash();
|
Sha256Hash chainHeadHash = chainHead.getHeader().getHash();
|
||||||
// Did we already make this request? If so, don't do it again.
|
// 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.
|
* behind the peer, or negative if the peer is ahead of us.
|
||||||
*/
|
*/
|
||||||
public int getPeerBlockHeightDifference() {
|
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.
|
// Chain will overflow signed int blocks in ~41,000 years.
|
||||||
int chainHeight = (int) getBestHeight();
|
int chainHeight = (int) getBestHeight();
|
||||||
// chainHeight should not be zero/negative because we shouldn't have given the user a Peer that is to another
|
// 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>
|
* unset a filter, though the underlying p2p protocol does support it.</p>
|
||||||
*/
|
*/
|
||||||
public void setBloomFilter(BloomFilter filter, boolean andQueryMemPool) {
|
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;
|
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()) {
|
if (version.isBloomFilteringSupported()) {
|
||||||
vBloomFilter = filter;
|
vBloomFilter = filter;
|
||||||
log.info("{}: Sending Bloom filter{}", this, andQueryMemPool ? " and querying mempool" : "");
|
log.info("{}: Sending Bloom filter{}", this, andQueryMemPool ? " and querying mempool" : "");
|
||||||
|
@ -1748,7 +1747,7 @@ public class Peer extends PeerSocketHandler {
|
||||||
// discarded.
|
// discarded.
|
||||||
sendPing().thenRunAsync(() -> {
|
sendPing().thenRunAsync(() -> {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
checkNotNull(awaitingFreshFilter);
|
Objects.requireNonNull(awaitingFreshFilter);
|
||||||
GetDataMessage getdata = new GetDataMessage(params);
|
GetDataMessage getdata = new GetDataMessage(params);
|
||||||
for (Sha256Hash hash : awaitingFreshFilter)
|
for (Sha256Hash hash : awaitingFreshFilter)
|
||||||
getdata.addFilteredBlock(hash);
|
getdata.addFilteredBlock(hash);
|
||||||
|
|
|
@ -39,8 +39,6 @@ import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.stream.Stream;
|
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
|
* <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>
|
* 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) {
|
public PeerAddress(NetworkParameters params, InetAddress addr, int port, BigInteger services, MessageSerializer serializer) {
|
||||||
super(params);
|
super(params);
|
||||||
this.addr = checkNotNull(addr);
|
this.addr = Objects.requireNonNull(addr);
|
||||||
this.port = port;
|
this.port = port;
|
||||||
setSerializer(serializer);
|
setSerializer(serializer);
|
||||||
this.services = services;
|
this.services = services;
|
||||||
|
|
|
@ -83,6 +83,7 @@ import java.util.LinkedList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.PriorityQueue;
|
import java.util.PriorityQueue;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
@ -100,7 +101,6 @@ import java.util.concurrent.TimeUnit;
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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 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.
|
* @param connectionManager used to create new connections and keep track of existing ones.
|
||||||
*/
|
*/
|
||||||
protected PeerGroup(Network network, @Nullable AbstractBlockChain chain, ClientConnectionManager connectionManager) {
|
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
|
@VisibleForTesting
|
||||||
protected PeerGroup(NetworkParameters params, @Nullable AbstractBlockChain chain, ClientConnectionManager connectionManager) {
|
protected PeerGroup(NetworkParameters params, @Nullable AbstractBlockChain chain, ClientConnectionManager connectionManager) {
|
||||||
checkNotNull(params);
|
Objects.requireNonNull(params);
|
||||||
Context.getOrCreate(); // create a context for convenience
|
Context.getOrCreate(); // create a context for convenience
|
||||||
this.params = params;
|
this.params = params;
|
||||||
this.chain = chain;
|
this.chain = chain;
|
||||||
|
@ -751,7 +751,7 @@ public class PeerGroup implements TransactionBroadcaster {
|
||||||
* @see Peer#addBlocksDownloadedEventListener(Executor, BlocksDownloadedEventListener)
|
* @see Peer#addBlocksDownloadedEventListener(Executor, BlocksDownloadedEventListener)
|
||||||
*/
|
*/
|
||||||
public void addBlocksDownloadedEventListener(Executor executor, BlocksDownloadedEventListener listener) {
|
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())
|
for (Peer peer : getConnectedPeers())
|
||||||
peer.addBlocksDownloadedEventListener(executor, listener);
|
peer.addBlocksDownloadedEventListener(executor, listener);
|
||||||
for (Peer peer : getPendingPeers())
|
for (Peer peer : getPendingPeers())
|
||||||
|
@ -768,7 +768,7 @@ public class PeerGroup implements TransactionBroadcaster {
|
||||||
* chain download starts.</p>
|
* chain download starts.</p>
|
||||||
*/
|
*/
|
||||||
public void addChainDownloadStartedEventListener(Executor executor, ChainDownloadStartedEventListener listener) {
|
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())
|
for (Peer peer : getConnectedPeers())
|
||||||
peer.addChainDownloadStartedEventListener(executor, listener);
|
peer.addChainDownloadStartedEventListener(executor, listener);
|
||||||
for (Peer peer : getPendingPeers())
|
for (Peer peer : getPendingPeers())
|
||||||
|
@ -785,7 +785,7 @@ public class PeerGroup implements TransactionBroadcaster {
|
||||||
* new peers are connected to.</p>
|
* new peers are connected to.</p>
|
||||||
*/
|
*/
|
||||||
public void addConnectedEventListener(Executor executor, PeerConnectedEventListener listener) {
|
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())
|
for (Peer peer : getConnectedPeers())
|
||||||
peer.addConnectedEventListener(executor, listener);
|
peer.addConnectedEventListener(executor, listener);
|
||||||
for (Peer peer : getPendingPeers())
|
for (Peer peer : getPendingPeers())
|
||||||
|
@ -802,7 +802,7 @@ public class PeerGroup implements TransactionBroadcaster {
|
||||||
* peers are disconnected from.</p>
|
* peers are disconnected from.</p>
|
||||||
*/
|
*/
|
||||||
public void addDisconnectedEventListener(Executor executor, PeerDisconnectedEventListener listener) {
|
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())
|
for (Peer peer : getConnectedPeers())
|
||||||
peer.addDisconnectedEventListener(executor, listener);
|
peer.addDisconnectedEventListener(executor, listener);
|
||||||
for (Peer peer : getPendingPeers())
|
for (Peer peer : getPendingPeers())
|
||||||
|
@ -819,7 +819,7 @@ public class PeerGroup implements TransactionBroadcaster {
|
||||||
* peers are discovered.</p>
|
* peers are discovered.</p>
|
||||||
*/
|
*/
|
||||||
public void addDiscoveredEventListener(Executor executor, PeerDiscoveredEventListener listener) {
|
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)} */
|
/** See {@link Peer#addGetDataEventListener(GetDataEventListener)} */
|
||||||
|
@ -829,7 +829,7 @@ public class PeerGroup implements TransactionBroadcaster {
|
||||||
|
|
||||||
/** See {@link Peer#addGetDataEventListener(Executor, GetDataEventListener)} */
|
/** See {@link Peer#addGetDataEventListener(Executor, GetDataEventListener)} */
|
||||||
public void addGetDataEventListener(final Executor executor, final GetDataEventListener listener) {
|
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())
|
for (Peer peer : getConnectedPeers())
|
||||||
peer.addGetDataEventListener(executor, listener);
|
peer.addGetDataEventListener(executor, listener);
|
||||||
for (Peer peer : getPendingPeers())
|
for (Peer peer : getPendingPeers())
|
||||||
|
@ -843,7 +843,7 @@ public class PeerGroup implements TransactionBroadcaster {
|
||||||
|
|
||||||
/** See {@link Peer#addOnTransactionBroadcastListener(OnTransactionBroadcastListener)} */
|
/** See {@link Peer#addOnTransactionBroadcastListener(OnTransactionBroadcastListener)} */
|
||||||
public void addOnTransactionBroadcastListener(Executor executor, OnTransactionBroadcastListener listener) {
|
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())
|
for (Peer peer : getConnectedPeers())
|
||||||
peer.addOnTransactionBroadcastListener(executor, listener);
|
peer.addOnTransactionBroadcastListener(executor, listener);
|
||||||
for (Peer peer : getPendingPeers())
|
for (Peer peer : getPendingPeers())
|
||||||
|
@ -857,7 +857,7 @@ public class PeerGroup implements TransactionBroadcaster {
|
||||||
|
|
||||||
/** See {@link Peer#addPreMessageReceivedEventListener(Executor, PreMessageReceivedEventListener)} */
|
/** See {@link Peer#addPreMessageReceivedEventListener(Executor, PreMessageReceivedEventListener)} */
|
||||||
public void addPreMessageReceivedEventListener(Executor executor, PreMessageReceivedEventListener listener) {
|
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())
|
for (Peer peer : getConnectedPeers())
|
||||||
peer.addPreMessageReceivedEventListener(executor, listener);
|
peer.addPreMessageReceivedEventListener(executor, listener);
|
||||||
for (Peer peer : getPendingPeers())
|
for (Peer peer : getPendingPeers())
|
||||||
|
@ -1244,7 +1244,7 @@ public class PeerGroup implements TransactionBroadcaster {
|
||||||
public void addWallet(Wallet wallet) {
|
public void addWallet(Wallet wallet) {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
checkNotNull(wallet);
|
Objects.requireNonNull(wallet);
|
||||||
checkState(!wallets.contains(wallet));
|
checkState(!wallets.contains(wallet));
|
||||||
wallets.add(wallet);
|
wallets.add(wallet);
|
||||||
wallet.setTransactionBroadcaster(this);
|
wallet.setTransactionBroadcaster(this);
|
||||||
|
@ -1277,7 +1277,7 @@ public class PeerGroup implements TransactionBroadcaster {
|
||||||
public ListenableCompletableFuture<BloomFilter> addPeerFilterProvider(PeerFilterProvider provider) {
|
public ListenableCompletableFuture<BloomFilter> addPeerFilterProvider(PeerFilterProvider provider) {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
checkNotNull(provider);
|
Objects.requireNonNull(provider);
|
||||||
checkState(!peerFilterProviders.contains(provider));
|
checkState(!peerFilterProviders.contains(provider));
|
||||||
// Insert provider at the start. This avoids various concurrency problems that could occur because we need
|
// 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
|
// 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) {
|
public void removePeerFilterProvider(PeerFilterProvider provider) {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
checkNotNull(provider);
|
Objects.requireNonNull(provider);
|
||||||
checkArgument(peerFilterProviders.remove(provider));
|
checkArgument(peerFilterProviders.remove(provider));
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock();
|
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.
|
* Unlinks the given wallet so it no longer receives broadcast transactions or has its transactions announced.
|
||||||
*/
|
*/
|
||||||
public void removeWallet(Wallet wallet) {
|
public void removeWallet(Wallet wallet) {
|
||||||
wallets.remove(checkNotNull(wallet));
|
wallets.remove(Objects.requireNonNull(wallet));
|
||||||
peerFilterProviders.remove(wallet);
|
peerFilterProviders.remove(wallet);
|
||||||
wallet.removeCoinsReceivedEventListener(walletCoinsReceivedEventListener);
|
wallet.removeCoinsReceivedEventListener(walletCoinsReceivedEventListener);
|
||||||
wallet.removeCoinsSentEventListener(walletCoinsSentEventListener);
|
wallet.removeCoinsSentEventListener(walletCoinsSentEventListener);
|
||||||
|
|
|
@ -37,10 +37,10 @@ import java.nio.BufferUnderflowException;
|
||||||
import java.nio.ByteBuffer;
|
import java.nio.ByteBuffer;
|
||||||
import java.nio.channels.NotYetConnectedException;
|
import java.nio.channels.NotYetConnectedException;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.concurrent.locks.Lock;
|
import java.util.concurrent.locks.Lock;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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 com.google.common.base.Preconditions.checkState;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -71,9 +71,9 @@ public abstract class PeerSocketHandler implements TimeoutHandler, StreamConnect
|
||||||
}
|
}
|
||||||
|
|
||||||
public PeerSocketHandler(NetworkParameters params, PeerAddress peerAddress) {
|
public PeerSocketHandler(NetworkParameters params, PeerAddress peerAddress) {
|
||||||
checkNotNull(params);
|
Objects.requireNonNull(params);
|
||||||
serializer = params.getDefaultSerializer();
|
serializer = params.getDefaultSerializer();
|
||||||
this.peerAddress = checkNotNull(peerAddress);
|
this.peerAddress = Objects.requireNonNull(peerAddress);
|
||||||
this.timeoutTask = new SocketTimeoutTask(this::timeoutOccurred);
|
this.timeoutTask = new SocketTimeoutTask(this::timeoutOccurred);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -60,11 +60,11 @@ import java.util.HashSet;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.TreeMap;
|
import java.util.TreeMap;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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 com.google.common.base.Preconditions.checkState;
|
||||||
import static org.bitcoinj.core.NetworkParameters.ProtocolVersion.WITNESS_VERSION;
|
import static org.bitcoinj.core.NetworkParameters.ProtocolVersion.WITNESS_VERSION;
|
||||||
import static org.bitcoinj.base.internal.ByteUtils.uint32ToByteStreamLE;
|
import static org.bitcoinj.base.internal.ByteUtils.uint32ToByteStreamLE;
|
||||||
|
@ -553,7 +553,7 @@ public class Transaction extends ChildMessage {
|
||||||
* @param updateTime update time
|
* @param updateTime update time
|
||||||
*/
|
*/
|
||||||
public void setUpdateTime(Instant updateTime) {
|
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
|
* @return The newly created input
|
||||||
*/
|
*/
|
||||||
public TransactionInput addSignedInput(TransactionOutput output, ECKey sigKey, SigHash sigHash, boolean anyoneCanPay) {
|
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");
|
checkState(output.getValue().value > 0, "TransactionOutput.getValue() must not be greater than zero");
|
||||||
return addSignedInput(output.getOutPointFor(), output.getScriptPubKey(), output.getValue(), sigKey, sigHash, anyoneCanPay);
|
return addSignedInput(output.getOutPointFor(), output.getScriptPubKey(), output.getValue(), sigKey, sigHash, anyoneCanPay);
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,12 +32,12 @@ import java.util.Collections;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.concurrent.CopyOnWriteArrayList;
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
import static com.google.common.base.Preconditions.checkState;
|
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.
|
// 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>
|
* a future from {@link #getDepthFuture(int)}.</p>
|
||||||
*/
|
*/
|
||||||
public void addEventListener(Executor executor, Listener listener) {
|
public void addEventListener(Executor executor, Listener listener) {
|
||||||
checkNotNull(listener);
|
Objects.requireNonNull(listener);
|
||||||
listeners.addIfAbsent(new ListenerRegistration<>(listener, executor));
|
listeners.addIfAbsent(new ListenerRegistration<>(listener, executor));
|
||||||
pinnedConfidenceObjects.add(this);
|
pinnedConfidenceObjects.add(this);
|
||||||
}
|
}
|
||||||
|
@ -244,7 +244,7 @@ public class TransactionConfidence {
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean removeEventListener(Listener listener) {
|
public boolean removeEventListener(Listener listener) {
|
||||||
checkNotNull(listener);
|
Objects.requireNonNull(listener);
|
||||||
boolean removed = ListenerRegistration.removeFromList(listener, listeners);
|
boolean removed = ListenerRegistration.removeFromList(listener, listeners);
|
||||||
if (listeners.isEmpty())
|
if (listeners.isEmpty())
|
||||||
pinnedConfidenceObjects.remove(this);
|
pinnedConfidenceObjects.remove(this);
|
||||||
|
@ -359,7 +359,7 @@ public class TransactionConfidence {
|
||||||
* @param lastBroadcastTime time the transaction was last announced to us
|
* @param lastBroadcastTime time the transaction was last announced to us
|
||||||
*/
|
*/
|
||||||
public void setLastBroadcastTime(Instant lastBroadcastTime) {
|
public void setLastBroadcastTime(Instant lastBroadcastTime) {
|
||||||
this.lastBroadcastTime = checkNotNull(lastBroadcastTime);
|
this.lastBroadcastTime = Objects.requireNonNull(lastBroadcastTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @deprecated use {@link #setLastBroadcastTime(Instant)} */
|
/** @deprecated use {@link #setLastBroadcastTime(Instant)} */
|
||||||
|
|
|
@ -37,7 +37,6 @@ import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkElementIndex;
|
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
|
* <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. */
|
/** Set the given program as the scriptSig that is supposed to satisfy the connected output script. */
|
||||||
public void setScriptSig(Script scriptSig) {
|
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.
|
// TODO: This should all be cleaned up so we have a consistent internal representation.
|
||||||
setScriptBytes(scriptSig.getProgram());
|
setScriptBytes(scriptSig.getProgram());
|
||||||
}
|
}
|
||||||
|
@ -456,7 +455,7 @@ public class TransactionInput extends ChildMessage {
|
||||||
public void verify() throws VerificationException {
|
public void verify() throws VerificationException {
|
||||||
final Transaction fromTx = getOutpoint().fromTx;
|
final Transaction fromTx = getOutpoint().fromTx;
|
||||||
long spendingIndex = getOutpoint().getIndex();
|
long spendingIndex = getOutpoint().getIndex();
|
||||||
checkNotNull(fromTx, "Not connected");
|
Objects.requireNonNull(fromTx, "Not connected");
|
||||||
final TransactionOutput output = fromTx.getOutput((int) spendingIndex);
|
final TransactionOutput output = fromTx.getOutput((int) spendingIndex);
|
||||||
verify(output);
|
verify(output);
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,7 +33,6 @@ import java.io.IOException;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
import static com.google.common.base.Preconditions.checkState;
|
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.
|
* @throws java.lang.NullPointerException if there is no connected output.
|
||||||
*/
|
*/
|
||||||
public byte[] getConnectedPubKeyScript() {
|
public byte[] getConnectedPubKeyScript() {
|
||||||
byte[] result = checkNotNull(getConnectedOutput()).getScriptBytes();
|
byte[] result = Objects.requireNonNull(getConnectedOutput()).getScriptBytes();
|
||||||
checkState(result.length > 0);
|
checkState(result.length > 0);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
@ -149,7 +148,7 @@ public class TransactionOutPoint extends ChildMessage {
|
||||||
@Nullable
|
@Nullable
|
||||||
public ECKey getConnectedKey(KeyBag keyBag) throws ScriptException {
|
public ECKey getConnectedKey(KeyBag keyBag) throws ScriptException {
|
||||||
TransactionOutput connectedOutput = getConnectedOutput();
|
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();
|
Script connectedScript = connectedOutput.getScriptPubKey();
|
||||||
if (ScriptPattern.isP2PKH(connectedScript)) {
|
if (ScriptPattern.isP2PKH(connectedScript)) {
|
||||||
byte[] addressBytes = ScriptPattern.extractHashFromP2PKH(connectedScript);
|
byte[] addressBytes = ScriptPattern.extractHashFromP2PKH(connectedScript);
|
||||||
|
@ -175,7 +174,7 @@ public class TransactionOutPoint extends ChildMessage {
|
||||||
@Nullable
|
@Nullable
|
||||||
public RedeemData getConnectedRedeemData(KeyBag keyBag) throws ScriptException {
|
public RedeemData getConnectedRedeemData(KeyBag keyBag) throws ScriptException {
|
||||||
TransactionOutput connectedOutput = getConnectedOutput();
|
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();
|
Script connectedScript = connectedOutput.getScriptPubKey();
|
||||||
if (ScriptPattern.isP2PKH(connectedScript)) {
|
if (ScriptPattern.isP2PKH(connectedScript)) {
|
||||||
byte[] addressBytes = ScriptPattern.extractHashFromP2PKH(connectedScript);
|
byte[] addressBytes = ScriptPattern.extractHashFromP2PKH(connectedScript);
|
||||||
|
|
|
@ -40,7 +40,6 @@ import java.util.List;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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 com.google.common.base.Preconditions.checkState;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -141,7 +140,7 @@ public class TransactionOutput extends ChildMessage {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
|
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
|
||||||
checkNotNull(scriptBytes);
|
Objects.requireNonNull(scriptBytes);
|
||||||
ByteUtils.int64ToByteStreamLE(value, stream);
|
ByteUtils.int64ToByteStreamLE(value, stream);
|
||||||
// TODO: Move script serialization into the Script class, where it belongs.
|
// TODO: Move script serialization into the Script class, where it belongs.
|
||||||
stream.write(new VarInt(scriptBytes.length).encode());
|
stream.write(new VarInt(scriptBytes.length).encode());
|
||||||
|
@ -160,7 +159,7 @@ public class TransactionOutput extends ChildMessage {
|
||||||
* Sets the value of this output.
|
* Sets the value of this output.
|
||||||
*/
|
*/
|
||||||
public void setValue(Coin value) {
|
public void setValue(Coin value) {
|
||||||
checkNotNull(value);
|
Objects.requireNonNull(value);
|
||||||
unCache();
|
unCache();
|
||||||
this.value = value.value;
|
this.value = value.value;
|
||||||
}
|
}
|
||||||
|
|
|
@ -25,10 +25,9 @@ import java.lang.ref.ReferenceQueue;
|
||||||
import java.lang.ref.WeakReference;
|
import java.lang.ref.WeakReference;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
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
|
* <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
|
* {@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.
|
* is unknown to the system at this time.
|
||||||
*/
|
*/
|
||||||
public TransactionConfidence getOrCreate(Sha256Hash hash) {
|
public TransactionConfidence getOrCreate(Sha256Hash hash) {
|
||||||
checkNotNull(hash);
|
Objects.requireNonNull(hash);
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
WeakConfidenceReference reference = table.get(hash);
|
WeakConfidenceReference reference = table.get(hash);
|
||||||
|
|
|
@ -30,8 +30,6 @@ import java.math.BigInteger;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Objects;
|
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
|
// 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,
|
boolean coinbase,
|
||||||
Script script,
|
Script script,
|
||||||
String address) {
|
String address) {
|
||||||
this.hash = checkNotNull(hash);
|
this.hash = Objects.requireNonNull(hash);
|
||||||
this.index = index;
|
this.index = index;
|
||||||
this.value = checkNotNull(value);
|
this.value = Objects.requireNonNull(value);
|
||||||
this.height = height;
|
this.height = height;
|
||||||
this.script = script;
|
this.script = script;
|
||||||
this.coinbase = coinbase;
|
this.coinbase = coinbase;
|
||||||
|
|
|
@ -39,7 +39,6 @@ import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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 com.google.common.base.Preconditions.checkState;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -74,7 +73,7 @@ public class DeterministicKey extends ECKey {
|
||||||
super(priv, publicAsPoint.compress());
|
super(priv, publicAsPoint.compress());
|
||||||
checkArgument(chainCode.length == 32);
|
checkArgument(chainCode.length == 32);
|
||||||
this.parent = parent;
|
this.parent = parent;
|
||||||
this.childNumberPath = HDPath.M(checkNotNull(childNumberPath));
|
this.childNumberPath = HDPath.M(Objects.requireNonNull(childNumberPath));
|
||||||
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
|
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
|
||||||
this.depth = parent == null ? 0 : parent.depth + 1;
|
this.depth = parent == null ? 0 : parent.depth + 1;
|
||||||
this.parentFingerprint = (parent != null) ? parent.getFingerprint() : 0;
|
this.parentFingerprint = (parent != null) ? parent.getFingerprint() : 0;
|
||||||
|
@ -97,7 +96,7 @@ public class DeterministicKey extends ECKey {
|
||||||
super(priv, ECKey.publicPointFromPrivate(priv), true);
|
super(priv, ECKey.publicPointFromPrivate(priv), true);
|
||||||
checkArgument(chainCode.length == 32);
|
checkArgument(chainCode.length == 32);
|
||||||
this.parent = parent;
|
this.parent = parent;
|
||||||
this.childNumberPath = checkNotNull(hdPath);
|
this.childNumberPath = Objects.requireNonNull(hdPath);
|
||||||
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
|
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
|
||||||
this.depth = parent == null ? 0 : parent.depth + 1;
|
this.depth = parent == null ? 0 : parent.depth + 1;
|
||||||
this.parentFingerprint = (parent != null) ? parent.getFingerprint() : 0;
|
this.parentFingerprint = (parent != null) ? parent.getFingerprint() : 0;
|
||||||
|
@ -111,8 +110,8 @@ public class DeterministicKey extends ECKey {
|
||||||
EncryptedData priv,
|
EncryptedData priv,
|
||||||
@Nullable DeterministicKey parent) {
|
@Nullable DeterministicKey parent) {
|
||||||
this(childNumberPath, chainCode, pub, null, parent);
|
this(childNumberPath, chainCode, pub, null, parent);
|
||||||
this.encryptedPrivateKey = checkNotNull(priv);
|
this.encryptedPrivateKey = Objects.requireNonNull(priv);
|
||||||
this.keyCrypter = checkNotNull(crypter);
|
this.keyCrypter = Objects.requireNonNull(crypter);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -145,7 +144,7 @@ public class DeterministicKey extends ECKey {
|
||||||
super(null, publicAsPoint.compress());
|
super(null, publicAsPoint.compress());
|
||||||
checkArgument(chainCode.length == 32);
|
checkArgument(chainCode.length == 32);
|
||||||
this.parent = parent;
|
this.parent = parent;
|
||||||
this.childNumberPath = HDPath.M(checkNotNull(childNumberPath));
|
this.childNumberPath = HDPath.M(Objects.requireNonNull(childNumberPath));
|
||||||
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
|
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
|
||||||
this.depth = depth;
|
this.depth = depth;
|
||||||
this.parentFingerprint = ascertainParentFingerprint(parentFingerprint);
|
this.parentFingerprint = ascertainParentFingerprint(parentFingerprint);
|
||||||
|
@ -165,7 +164,7 @@ public class DeterministicKey extends ECKey {
|
||||||
super(priv, ECKey.publicPointFromPrivate(priv), true);
|
super(priv, ECKey.publicPointFromPrivate(priv), true);
|
||||||
checkArgument(chainCode.length == 32);
|
checkArgument(chainCode.length == 32);
|
||||||
this.parent = parent;
|
this.parent = parent;
|
||||||
this.childNumberPath = HDPath.M(checkNotNull(childNumberPath));
|
this.childNumberPath = HDPath.M(Objects.requireNonNull(childNumberPath));
|
||||||
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
|
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
|
||||||
this.depth = depth;
|
this.depth = depth;
|
||||||
this.parentFingerprint = ascertainParentFingerprint(parentFingerprint);
|
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 {
|
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.
|
// Same as the parent code, except we construct a DeterministicKey instead of an ECKey.
|
||||||
checkNotNull(keyCrypter);
|
Objects.requireNonNull(keyCrypter);
|
||||||
if (newParent != null)
|
if (newParent != null)
|
||||||
checkArgument(newParent.isEncrypted());
|
checkArgument(newParent.isEncrypted());
|
||||||
final byte[] privKeyBytes = getPrivKeyBytes();
|
final byte[] privKeyBytes = getPrivKeyBytes();
|
||||||
|
@ -380,7 +379,7 @@ public class DeterministicKey extends ECKey {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DeterministicKey decrypt(KeyCrypter keyCrypter, AesKey aesKey) throws KeyCrypterException {
|
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.
|
// Check that the keyCrypter matches the one used to encrypt the keys, if set.
|
||||||
if (this.keyCrypter != null && !this.keyCrypter.equals(keyCrypter))
|
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");
|
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.
|
// catch it.
|
||||||
if (!downCursor.pub.equals(pub))
|
if (!downCursor.pub.equals(pub))
|
||||||
throw new KeyCrypterException.PublicPrivateMismatch("Could not decrypt bytes");
|
throw new KeyCrypterException.PublicPrivateMismatch("Could not decrypt bytes");
|
||||||
return checkNotNull(downCursor.priv);
|
return Objects.requireNonNull(downCursor.priv);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -86,7 +86,6 @@ import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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 com.google.common.base.Preconditions.checkState;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -189,7 +188,7 @@ public class ECKey implements EncryptableItem {
|
||||||
}
|
}
|
||||||
|
|
||||||
protected ECKey(@Nullable BigInteger priv, ECPoint pub, boolean compressed) {
|
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) {
|
protected ECKey(@Nullable BigInteger priv, LazyECPoint pub) {
|
||||||
|
@ -202,7 +201,7 @@ public class ECKey implements EncryptableItem {
|
||||||
checkArgument(!priv.equals(BigInteger.ONE));
|
checkArgument(!priv.equals(BigInteger.ONE));
|
||||||
}
|
}
|
||||||
this.priv = priv;
|
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.
|
* already. The compression state of the point will be preserved.
|
||||||
*/
|
*/
|
||||||
public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub) {
|
public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub) {
|
||||||
checkNotNull(priv);
|
Objects.requireNonNull(priv);
|
||||||
checkNotNull(pub);
|
Objects.requireNonNull(pub);
|
||||||
return new ECKey(ByteUtils.bytesToBigInteger(priv), new LazyECPoint(CURVE.getCurve(), 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) {
|
public static ECKey fromEncrypted(EncryptedData encryptedPrivateKey, KeyCrypter crypter, byte[] pubKey) {
|
||||||
ECKey key = fromPublicOnly(pubKey);
|
ECKey key = fromPublicOnly(pubKey);
|
||||||
key.encryptedPrivateKey = checkNotNull(encryptedPrivateKey);
|
key.encryptedPrivateKey = Objects.requireNonNull(encryptedPrivateKey);
|
||||||
key.keyCrypter = checkNotNull(crypter);
|
key.keyCrypter = Objects.requireNonNull(crypter);
|
||||||
return key;
|
return key;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -601,7 +600,7 @@ public class ECKey implements EncryptableItem {
|
||||||
throw new RuntimeException(e); // cannot happen
|
throw new RuntimeException(e); // cannot happen
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
checkNotNull(privateKeyForSigning);
|
Objects.requireNonNull(privateKeyForSigning);
|
||||||
ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
|
ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
|
||||||
ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeyForSigning, CURVE);
|
ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeyForSigning, CURVE);
|
||||||
signer.init(true, privKey);
|
signer.init(true, privKey);
|
||||||
|
@ -988,7 +987,7 @@ public class ECKey implements EncryptableItem {
|
||||||
Preconditions.checkArgument(recId >= 0, "recId must be positive");
|
Preconditions.checkArgument(recId >= 0, "recId must be positive");
|
||||||
Preconditions.checkArgument(sig.r.signum() >= 0, "r must be positive");
|
Preconditions.checkArgument(sig.r.signum() >= 0, "r must be positive");
|
||||||
Preconditions.checkArgument(sig.s.signum() >= 0, "s 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
|
// 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.0 For j from 0 to h (h == recId here and the loop is outside this function)
|
||||||
// 1.1 Let x = r + jn
|
// 1.1 Let x = r + jn
|
||||||
|
@ -1091,7 +1090,7 @@ public class ECKey implements EncryptableItem {
|
||||||
* @param creationTime creation time of this key
|
* @param creationTime creation time of this key
|
||||||
*/
|
*/
|
||||||
public void setCreationTime(Instant creationTime) {
|
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
|
* @return encryptedKey
|
||||||
*/
|
*/
|
||||||
public ECKey encrypt(KeyCrypter keyCrypter, AesKey aesKey) throws KeyCrypterException {
|
public ECKey encrypt(KeyCrypter keyCrypter, AesKey aesKey) throws KeyCrypterException {
|
||||||
checkNotNull(keyCrypter);
|
Objects.requireNonNull(keyCrypter);
|
||||||
final byte[] privKeyBytes = getPrivKeyBytes();
|
final byte[] privKeyBytes = getPrivKeyBytes();
|
||||||
EncryptedData encryptedPrivateKey = keyCrypter.encrypt(privKeyBytes, aesKey);
|
EncryptedData encryptedPrivateKey = keyCrypter.encrypt(privKeyBytes, aesKey);
|
||||||
ECKey result = ECKey.fromEncrypted(encryptedPrivateKey, keyCrypter, getPubKey());
|
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).
|
* @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 {
|
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.
|
// Check that the keyCrypter matches the one used to encrypt the keys, if set.
|
||||||
if (this.keyCrypter != null && !this.keyCrypter.equals(keyCrypter))
|
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");
|
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();
|
final MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(this).omitNullValues();
|
||||||
helper.add("pub HEX", getPublicKeyAsHex());
|
helper.add("pub HEX", getPublicKeyAsHex());
|
||||||
if (includePrivate) {
|
if (includePrivate) {
|
||||||
ECKey decryptedKey = isEncrypted() ? decrypt(checkNotNull(aesKey)) : this;
|
ECKey decryptedKey = isEncrypted() ? decrypt(Objects.requireNonNull(aesKey)) : this;
|
||||||
try {
|
try {
|
||||||
helper.add("priv HEX", decryptedKey.getPrivateKeyAsHex());
|
helper.add("priv HEX", decryptedKey.getPrivateKeyAsHex());
|
||||||
helper.add("priv WIF", decryptedKey.getPrivateKeyAsWiF(network));
|
helper.add("priv WIF", decryptedKey.getPrivateKeyAsWiF(network));
|
||||||
|
|
|
@ -23,8 +23,6 @@ import org.bitcoinj.core.NetworkParameters;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Objects;
|
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.
|
* 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 final byte[] bytes;
|
||||||
|
|
||||||
protected EncodedPrivateKey(Network network, byte[] bytes) {
|
protected EncodedPrivateKey(Network network, byte[] bytes) {
|
||||||
this.network = checkNotNull(network);
|
this.network = Objects.requireNonNull(network);
|
||||||
this.bytes = checkNotNull(bytes);
|
this.bytes = Objects.requireNonNull(bytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Deprecated
|
@Deprecated
|
||||||
protected EncodedPrivateKey(NetworkParameters params, byte[] bytes) {
|
protected EncodedPrivateKey(NetworkParameters params, byte[] bytes) {
|
||||||
this(checkNotNull(params).network(), checkNotNull(bytes));
|
this(Objects.requireNonNull(params).network(), Objects.requireNonNull(bytes));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -38,8 +38,6 @@ import java.time.Instant;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Objects;
|
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
|
* <p>This class encrypts and decrypts byte arrays and strings using scrypt as the
|
||||||
* key derivation function and AES for the encryption.</p>
|
* 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.
|
* @throws NullPointerException if the scryptParameters or any of its N, R or P is null.
|
||||||
*/
|
*/
|
||||||
public KeyCrypterScrypt(ScryptParameters scryptParameters) {
|
public KeyCrypterScrypt(ScryptParameters scryptParameters) {
|
||||||
this.scryptParameters = checkNotNull(scryptParameters);
|
this.scryptParameters = Objects.requireNonNull(scryptParameters);
|
||||||
// Check there is a non-empty salt.
|
// Check there is a non-empty salt.
|
||||||
// (Some early MultiBit wallets has a missing salt so it is not a hard fail).
|
// (Some early MultiBit wallets has a missing salt so it is not a hard fail).
|
||||||
if (scryptParameters.getSalt() == null
|
if (scryptParameters.getSalt() == null
|
||||||
|
@ -171,8 +169,8 @@ public class KeyCrypterScrypt implements KeyCrypter {
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public EncryptedData encrypt(byte[] plainBytes, AesKey aesKey) throws KeyCrypterException {
|
public EncryptedData encrypt(byte[] plainBytes, AesKey aesKey) throws KeyCrypterException {
|
||||||
checkNotNull(plainBytes);
|
Objects.requireNonNull(plainBytes);
|
||||||
checkNotNull(aesKey);
|
Objects.requireNonNull(aesKey);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Generate iv - each encryption call has a different iv.
|
// Generate iv - each encryption call has a different iv.
|
||||||
|
@ -204,8 +202,8 @@ public class KeyCrypterScrypt implements KeyCrypter {
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public byte[] decrypt(EncryptedData dataToDecrypt, AesKey aesKey) throws KeyCrypterException {
|
public byte[] decrypt(EncryptedData dataToDecrypt, AesKey aesKey) throws KeyCrypterException {
|
||||||
checkNotNull(dataToDecrypt);
|
Objects.requireNonNull(dataToDecrypt);
|
||||||
checkNotNull(aesKey);
|
Objects.requireNonNull(aesKey);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ParametersWithIV keyWithIv = new ParametersWithIV(new KeyParameter(aesKey.bytes()), dataToDecrypt.initialisationVector);
|
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.
|
* Note: a String.getBytes() is not used to avoid creating a String of the password in the JVM.
|
||||||
*/
|
*/
|
||||||
private static byte[] convertToByteArray(CharSequence charSequence) {
|
private static byte[] convertToByteArray(CharSequence charSequence) {
|
||||||
checkNotNull(charSequence);
|
Objects.requireNonNull(charSequence);
|
||||||
|
|
||||||
byte[] byteArray = new byte[charSequence.length() << 1];
|
byte[] byteArray = new byte[charSequence.length() << 1];
|
||||||
for(int i = 0; i < charSequence.length(); i++) {
|
for(int i = 0; i < charSequence.length(); i++) {
|
||||||
|
|
|
@ -23,8 +23,7 @@ import org.bouncycastle.math.ec.ECPoint;
|
||||||
import javax.annotation.Nullable;
|
import javax.annotation.Nullable;
|
||||||
import java.math.BigInteger;
|
import java.math.BigInteger;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
import java.util.Objects;
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A wrapper around ECPoint that delays decoding of the point for as long as possible. This is useful because point
|
* 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
|
* @param compressed true if the represented public key is compressed
|
||||||
*/
|
*/
|
||||||
public LazyECPoint(ECPoint point, boolean compressed) {
|
public LazyECPoint(ECPoint point, boolean compressed) {
|
||||||
this.point = checkNotNull(point).normalize();
|
this.point = Objects.requireNonNull(point).normalize();
|
||||||
this.compressed = compressed;
|
this.compressed = compressed;
|
||||||
this.curve = null;
|
this.curve = null;
|
||||||
this.bits = null;
|
this.bits = null;
|
||||||
|
|
|
@ -36,9 +36,9 @@ import java.time.Instant;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
import static com.google.common.base.Preconditions.checkArgument;
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
import org.bitcoinj.base.internal.ByteUtils;
|
import org.bitcoinj.base.internal.ByteUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -132,7 +132,7 @@ public class MnemonicCode {
|
||||||
* Convert mnemonic word list to seed.
|
* Convert mnemonic word list to seed.
|
||||||
*/
|
*/
|
||||||
public static byte[] toSeed(List<String> words, String passphrase) {
|
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
|
// To create binary seed from mnemonic, we use PBKDF2 function
|
||||||
// with mnemonic sentence (in UTF-8) used as a password and
|
// with mnemonic sentence (in UTF-8) used as a password and
|
||||||
|
|
|
@ -56,10 +56,10 @@ import java.nio.channels.FileLock;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
import static com.google.common.base.Preconditions.checkState;
|
import static com.google.common.base.Preconditions.checkState;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -142,12 +142,12 @@ public class WalletAppKit extends AbstractIdleService {
|
||||||
*/
|
*/
|
||||||
public WalletAppKit(BitcoinNetwork network, ScriptType preferredOutputScriptType,
|
public WalletAppKit(BitcoinNetwork network, ScriptType preferredOutputScriptType,
|
||||||
KeyChainGroupStructure structure, File directory, String filePrefix) {
|
KeyChainGroupStructure structure, File directory, String filePrefix) {
|
||||||
this.network = checkNotNull(network);
|
this.network = Objects.requireNonNull(network);
|
||||||
this.params = NetworkParameters.of(this.network);
|
this.params = NetworkParameters.of(this.network);
|
||||||
this.preferredOutputScriptType = checkNotNull(preferredOutputScriptType);
|
this.preferredOutputScriptType = Objects.requireNonNull(preferredOutputScriptType);
|
||||||
this.structure = checkNotNull(structure);
|
this.structure = Objects.requireNonNull(structure);
|
||||||
this.directory = checkNotNull(directory);
|
this.directory = Objects.requireNonNull(directory);
|
||||||
this.filePrefix = checkNotNull(filePrefix);
|
this.filePrefix = Objects.requireNonNull(filePrefix);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Will only connect to the given addresses. Cannot be called after startup. */
|
/** 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.
|
* too, due to some missing implementation code.
|
||||||
*/
|
*/
|
||||||
public WalletAppKit setDownloadListener(DownloadProgressTracker listener) {
|
public WalletAppKit setDownloadListener(DownloadProgressTracker listener) {
|
||||||
checkNotNull(listener);
|
Objects.requireNonNull(listener);
|
||||||
this.downloadListener = listener;
|
this.downloadListener = listener;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
@ -200,7 +200,7 @@ public class WalletAppKit extends AbstractIdleService {
|
||||||
public WalletAppKit setCheckpoints(InputStream checkpoints) {
|
public WalletAppKit setCheckpoints(InputStream checkpoints) {
|
||||||
if (this.checkpoints != null)
|
if (this.checkpoints != null)
|
||||||
Closeables.closeQuietly(checkpoints);
|
Closeables.closeQuietly(checkpoints);
|
||||||
this.checkpoints = checkNotNull(checkpoints);
|
this.checkpoints = Objects.requireNonNull(checkpoints);
|
||||||
return this;
|
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"
|
* @param version A short string that contains the version number, e.g. "1.0-BETA"
|
||||||
*/
|
*/
|
||||||
public WalletAppKit setUserAgent(String userAgent, String version) {
|
public WalletAppKit setUserAgent(String userAgent, String version) {
|
||||||
this.userAgent = checkNotNull(userAgent);
|
this.userAgent = Objects.requireNonNull(userAgent);
|
||||||
this.version = checkNotNull(version);
|
this.version = Objects.requireNonNull(version);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -232,7 +232,7 @@ public class WalletAppKit extends AbstractIdleService {
|
||||||
* @return WalletAppKit for method chaining purposes
|
* @return WalletAppKit for method chaining purposes
|
||||||
*/
|
*/
|
||||||
public WalletAppKit setWalletFactory(@Nonnull WalletProtobufSerializer.WalletFactory walletFactory) {
|
public WalletAppKit setWalletFactory(@Nonnull WalletProtobufSerializer.WalletFactory walletFactory) {
|
||||||
checkNotNull(walletFactory);
|
Objects.requireNonNull(walletFactory);
|
||||||
this.walletFactory = walletFactory;
|
this.walletFactory = walletFactory;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
|
@ -26,10 +26,9 @@ import java.time.Duration;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* <p>A thin wrapper around a set of {@link BlockingClient}s.</p>
|
* <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.
|
* bitcoinj connects to the P2P network.
|
||||||
*/
|
*/
|
||||||
public BlockingClientManager(SocketFactory socketFactory) {
|
public BlockingClientManager(SocketFactory socketFactory) {
|
||||||
this.socketFactory = checkNotNull(socketFactory);
|
this.socketFactory = Objects.requireNonNull(socketFactory);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|
|
@ -34,10 +34,10 @@ import java.nio.channels.SocketChannel;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
import static com.google.common.base.Preconditions.checkState;
|
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.
|
// 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) {
|
private ConnectionHandler(@Nullable StreamConnection connection, SelectionKey key) {
|
||||||
this.key = key;
|
this.key = key;
|
||||||
this.channel = checkNotNull(((SocketChannel)key.channel()));
|
this.channel = Objects.requireNonNull(((SocketChannel)key.channel()));
|
||||||
if (connection == null) {
|
if (connection == null) {
|
||||||
readBuff = null;
|
readBuff = null;
|
||||||
return;
|
return;
|
||||||
|
@ -98,7 +98,7 @@ class ConnectionHandler implements MessageWriteTarget {
|
||||||
}
|
}
|
||||||
|
|
||||||
public ConnectionHandler(StreamConnection connection, SelectionKey key, Set<ConnectionHandler> connectedHandlers) {
|
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
|
// 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
|
// 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
|
// "flip" the buffer - setting the limit to the current position and setting position to 0
|
||||||
((Buffer) handler.readBuff).flip();
|
((Buffer) handler.readBuff).flip();
|
||||||
// Use connection.receiveBytes's return value as a check that it stopped reading at the right location
|
// 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);
|
checkState(handler.readBuff.position() == bytesConsumed);
|
||||||
// Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative
|
// Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative
|
||||||
// position)
|
// position)
|
||||||
|
|
|
@ -63,11 +63,11 @@ import java.util.EnumSet;
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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 com.google.common.base.Preconditions.checkState;
|
||||||
import static org.bitcoinj.script.ScriptOpCodes.OP_0;
|
import static org.bitcoinj.script.ScriptOpCodes.OP_0;
|
||||||
import static org.bitcoinj.script.ScriptOpCodes.OP_0NOTEQUAL;
|
import static org.bitcoinj.script.ScriptOpCodes.OP_0NOTEQUAL;
|
||||||
|
@ -260,7 +260,7 @@ public class Script {
|
||||||
public Script(byte[] programBytes, Instant creationTime) throws ScriptException {
|
public Script(byte[] programBytes, Instant creationTime) throws ScriptException {
|
||||||
this.program = programBytes;
|
this.program = programBytes;
|
||||||
parse(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
|
* @param creationTime creation time of this script
|
||||||
*/
|
*/
|
||||||
public void setCreationTime(Instant creationTime) {
|
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.
|
// and any placeholder OP_0 sigs.
|
||||||
List<ScriptChunk> existingChunks = chunks.subList(1, chunks.size() - 1);
|
List<ScriptChunk> existingChunks = chunks.subList(1, chunks.size() - 1);
|
||||||
ScriptChunk redeemScriptChunk = chunks.get(chunks.size() - 1);
|
ScriptChunk redeemScriptChunk = chunks.get(chunks.size() - 1);
|
||||||
checkNotNull(redeemScriptChunk.data);
|
Objects.requireNonNull(redeemScriptChunk.data);
|
||||||
Script redeemScript = new Script(redeemScriptChunk.data);
|
Script redeemScript = new Script(redeemScriptChunk.data);
|
||||||
|
|
||||||
int sigCount = 0;
|
int sigCount = 0;
|
||||||
|
@ -579,7 +579,7 @@ public class Script {
|
||||||
if (chunk.opcode == OP_0) {
|
if (chunk.opcode == OP_0) {
|
||||||
// OP_0, skip
|
// OP_0, skip
|
||||||
} else {
|
} else {
|
||||||
checkNotNull(chunk.data);
|
Objects.requireNonNull(chunk.data);
|
||||||
try {
|
try {
|
||||||
if (myIndex < redeemScript.findSigInRedeem(chunk.data, hash))
|
if (myIndex < redeemScript.findSigInRedeem(chunk.data, hash))
|
||||||
return sigCount;
|
return sigCount;
|
||||||
|
|
|
@ -33,8 +33,7 @@ import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* <p>This signer may be used as a template for creating custom multisig transaction signers.</p>
|
* <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;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Script inputScript = checkNotNull(txIn.getScriptSig());
|
Script inputScript = Objects.requireNonNull(txIn.getScriptSig());
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// We assume if its already signed, its hopefully got a SIGHASH type that will not invalidate when
|
// We assume if its already signed, its hopefully got a SIGHASH type that will not invalidate when
|
||||||
|
|
|
@ -16,7 +16,6 @@
|
||||||
|
|
||||||
package org.bitcoinj.store;
|
package org.bitcoinj.store;
|
||||||
|
|
||||||
import com.google.common.base.Preconditions;
|
|
||||||
import org.bitcoinj.base.ScriptType;
|
import org.bitcoinj.base.ScriptType;
|
||||||
import org.bitcoinj.base.Address;
|
import org.bitcoinj.base.Address;
|
||||||
import org.bitcoinj.crypto.ECKey;
|
import org.bitcoinj.crypto.ECKey;
|
||||||
|
@ -290,14 +289,14 @@ public class MemoryFullPrunedBlockStore implements FullPrunedBlockStore {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public synchronized void put(StoredBlock block) throws BlockStoreException {
|
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();
|
Sha256Hash hash = block.getHeader().getHash();
|
||||||
blockMap.put(hash, new StoredBlockAndWasUndoableFlag(block, false));
|
blockMap.put(hash, new StoredBlockAndWasUndoableFlag(block, false));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public synchronized final void put(StoredBlock storedBlock, StoredUndoableBlock undoableBlock) throws BlockStoreException {
|
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();
|
Sha256Hash hash = storedBlock.getHeader().getHash();
|
||||||
fullBlockMap.put(hash, storedBlock.getHeight(), undoableBlock);
|
fullBlockMap.put(hash, storedBlock.getHeight(), undoableBlock);
|
||||||
blockMap.put(hash, new StoredBlockAndWasUndoableFlag(storedBlock, true));
|
blockMap.put(hash, new StoredBlockAndWasUndoableFlag(storedBlock, true));
|
||||||
|
@ -306,7 +305,7 @@ public class MemoryFullPrunedBlockStore implements FullPrunedBlockStore {
|
||||||
@Override
|
@Override
|
||||||
@Nullable
|
@Nullable
|
||||||
public synchronized StoredBlock get(Sha256Hash hash) throws BlockStoreException {
|
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);
|
StoredBlockAndWasUndoableFlag storedBlock = blockMap.get(hash);
|
||||||
return storedBlock == null ? null : storedBlock.block;
|
return storedBlock == null ? null : storedBlock.block;
|
||||||
}
|
}
|
||||||
|
@ -314,7 +313,7 @@ public class MemoryFullPrunedBlockStore implements FullPrunedBlockStore {
|
||||||
@Override
|
@Override
|
||||||
@Nullable
|
@Nullable
|
||||||
public synchronized StoredBlock getOnceUndoableStoredBlock(Sha256Hash hash) throws BlockStoreException {
|
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);
|
StoredBlockAndWasUndoableFlag storedBlock = blockMap.get(hash);
|
||||||
return (storedBlock != null && storedBlock.wasUndoable) ? storedBlock.block : null;
|
return (storedBlock != null && storedBlock.wasUndoable) ? storedBlock.block : null;
|
||||||
}
|
}
|
||||||
|
@ -322,31 +321,31 @@ public class MemoryFullPrunedBlockStore implements FullPrunedBlockStore {
|
||||||
@Override
|
@Override
|
||||||
@Nullable
|
@Nullable
|
||||||
public synchronized StoredUndoableBlock getUndoBlock(Sha256Hash hash) throws BlockStoreException {
|
public synchronized StoredUndoableBlock getUndoBlock(Sha256Hash hash) throws BlockStoreException {
|
||||||
Preconditions.checkNotNull(fullBlockMap, "MemoryFullPrunedBlockStore is closed");
|
Objects.requireNonNull(fullBlockMap, "MemoryFullPrunedBlockStore is closed");
|
||||||
return fullBlockMap.get(hash);
|
return fullBlockMap.get(hash);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public synchronized StoredBlock getChainHead() throws BlockStoreException {
|
public synchronized StoredBlock getChainHead() throws BlockStoreException {
|
||||||
Preconditions.checkNotNull(blockMap, "MemoryFullPrunedBlockStore is closed");
|
Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed");
|
||||||
return chainHead;
|
return chainHead;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public synchronized final void setChainHead(StoredBlock chainHead) throws BlockStoreException {
|
public synchronized final void setChainHead(StoredBlock chainHead) throws BlockStoreException {
|
||||||
Preconditions.checkNotNull(blockMap, "MemoryFullPrunedBlockStore is closed");
|
Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed");
|
||||||
this.chainHead = chainHead;
|
this.chainHead = chainHead;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public synchronized StoredBlock getVerifiedChainHead() throws BlockStoreException {
|
public synchronized StoredBlock getVerifiedChainHead() throws BlockStoreException {
|
||||||
Preconditions.checkNotNull(blockMap, "MemoryFullPrunedBlockStore is closed");
|
Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed");
|
||||||
return verifiedChainHead;
|
return verifiedChainHead;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public synchronized final void setVerifiedChainHead(StoredBlock chainHead) throws BlockStoreException {
|
public synchronized final void setVerifiedChainHead(StoredBlock chainHead) throws BlockStoreException {
|
||||||
Preconditions.checkNotNull(blockMap, "MemoryFullPrunedBlockStore is closed");
|
Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed");
|
||||||
this.verifiedChainHead = chainHead;
|
this.verifiedChainHead = chainHead;
|
||||||
if (this.chainHead.getHeight() < chainHead.getHeight())
|
if (this.chainHead.getHeight() < chainHead.getHeight())
|
||||||
setChainHead(chainHead);
|
setChainHead(chainHead);
|
||||||
|
@ -365,19 +364,19 @@ public class MemoryFullPrunedBlockStore implements FullPrunedBlockStore {
|
||||||
@Override
|
@Override
|
||||||
@Nullable
|
@Nullable
|
||||||
public synchronized UTXO getTransactionOutput(Sha256Hash hash, long index) throws BlockStoreException {
|
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));
|
return transactionOutputMap.get(new StoredTransactionOutPoint(hash, index));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public synchronized void addUnspentTransactionOutput(UTXO out) throws BlockStoreException {
|
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);
|
transactionOutputMap.put(new StoredTransactionOutPoint(out), out);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public synchronized void removeUnspentTransactionOutput(UTXO out) throws BlockStoreException {
|
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)
|
if (transactionOutputMap.remove(new StoredTransactionOutPoint(out)) == null)
|
||||||
throw new BlockStoreException("Tried to remove a UTXO from MemoryFullPrunedBlockStore that it didn't have!");
|
throw new BlockStoreException("Tried to remove a UTXO from MemoryFullPrunedBlockStore that it didn't have!");
|
||||||
}
|
}
|
||||||
|
|
|
@ -38,10 +38,10 @@ import java.nio.charset.StandardCharsets;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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 com.google.common.base.Preconditions.checkState;
|
||||||
|
|
||||||
// TODO: Lose the mmap in this class. There are too many platform bugs that require odd workarounds.
|
// 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
|
* @throws BlockStoreException if something goes wrong
|
||||||
*/
|
*/
|
||||||
public SPVBlockStore(NetworkParameters params, File file, int capacity, boolean grow) throws BlockStoreException {
|
public SPVBlockStore(NetworkParameters params, File file, int capacity, boolean grow) throws BlockStoreException {
|
||||||
checkNotNull(file);
|
Objects.requireNonNull(file);
|
||||||
this.params = checkNotNull(params);
|
this.params = Objects.requireNonNull(params);
|
||||||
checkArgument(capacity > 0);
|
checkArgument(capacity > 0);
|
||||||
try {
|
try {
|
||||||
boolean exists = file.exists();
|
boolean exists = file.exists();
|
||||||
|
|
|
@ -36,8 +36,7 @@ import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* <p>Provides a standard implementation of a Bitcoin URI with support for the following:</p>
|
* <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.
|
* @throws BitcoinURIParseException If the input fails Bitcoin URI syntax and semantic checks.
|
||||||
*/
|
*/
|
||||||
public BitcoinURI(@Nonnull Network network, String input) throws BitcoinURIParseException {
|
public BitcoinURI(@Nonnull Network network, String input) throws BitcoinURIParseException {
|
||||||
checkNotNull(network);
|
Objects.requireNonNull(network);
|
||||||
checkNotNull(input);
|
Objects.requireNonNull(input);
|
||||||
|
|
||||||
String scheme = network.uriScheme();
|
String scheme = network.uriScheme();
|
||||||
|
|
||||||
|
@ -398,8 +397,8 @@ public class BitcoinURI {
|
||||||
public static String convertToBitcoinURI(Network network,
|
public static String convertToBitcoinURI(Network network,
|
||||||
String address, @Nullable Coin amount,
|
String address, @Nullable Coin amount,
|
||||||
@Nullable String label, @Nullable String message) {
|
@Nullable String label, @Nullable String message) {
|
||||||
checkNotNull(network);
|
Objects.requireNonNull(network);
|
||||||
checkNotNull(address);
|
Objects.requireNonNull(address);
|
||||||
if (amount != null && amount.signum() < 0) {
|
if (amount != null && amount.signum() < 0) {
|
||||||
throw new IllegalArgumentException("Coin must be positive");
|
throw new IllegalArgumentException("Coin must be positive");
|
||||||
}
|
}
|
||||||
|
|
|
@ -21,8 +21,7 @@ import com.google.protobuf.ByteString;
|
||||||
import javax.annotation.Nullable;
|
import javax.annotation.Nullable;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A simple implementation of {@link TaggableObject} that uses a hashmap that is
|
* A simple implementation of {@link TaggableObject} that uses a hashmap that is
|
||||||
|
@ -53,8 +52,8 @@ public class BaseTaggableObject implements TaggableObject {
|
||||||
@Deprecated
|
@Deprecated
|
||||||
public synchronized void setTag(String tag, ByteString value) {
|
public synchronized void setTag(String tag, ByteString value) {
|
||||||
// HashMap allows null keys and values, but we don't
|
// HashMap allows null keys and values, but we don't
|
||||||
checkNotNull(tag);
|
Objects.requireNonNull(tag);
|
||||||
checkNotNull(value);
|
Objects.requireNonNull(value);
|
||||||
tags.put(tag, value);
|
tags.put(tag, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -17,10 +17,9 @@
|
||||||
package org.bitcoinj.utils;
|
package org.bitcoinj.utils;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.concurrent.Executor;
|
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.
|
* 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 final Executor executor;
|
||||||
|
|
||||||
public ListenerRegistration(T listener, Executor executor) {
|
public ListenerRegistration(T listener, Executor executor) {
|
||||||
this.listener = checkNotNull(listener);
|
this.listener = Objects.requireNonNull(listener);
|
||||||
this.executor = checkNotNull(executor);
|
this.executor = Objects.requireNonNull(executor);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Returns true if the listener was removed, else false. */
|
/** Returns true if the listener was removed, else false. */
|
||||||
public static <T> boolean removeFromList(T listener, List<? extends ListenerRegistration<T>> list) {
|
public static <T> boolean removeFromList(T listener, List<? extends ListenerRegistration<T>> list) {
|
||||||
checkNotNull(listener);
|
Objects.requireNonNull(listener);
|
||||||
|
|
||||||
ListenerRegistration<T> item = null;
|
ListenerRegistration<T> item = null;
|
||||||
for (ListenerRegistration<T> registration : list) {
|
for (ListenerRegistration<T> registration : list) {
|
||||||
|
|
|
@ -40,6 +40,7 @@ import java.util.LinkedHashMap;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.concurrent.CopyOnWriteArrayList;
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
|
@ -47,7 +48,6 @@ import java.util.concurrent.locks.ReentrantLock;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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 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
|
* @throws org.bitcoinj.wallet.UnreadableWalletException if the data structures are corrupted/inconsistent
|
||||||
*/
|
*/
|
||||||
public static BasicKeyChain fromProtobufEncrypted(List<Protos.Key> keys, KeyCrypter crypter) throws UnreadableWalletException {
|
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);
|
chain.deserializeFromProtobuf(keys);
|
||||||
return chain;
|
return chain;
|
||||||
}
|
}
|
||||||
|
@ -474,7 +474,7 @@ public class BasicKeyChain implements EncryptableKeyChain {
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public BasicKeyChain toEncrypted(CharSequence password) {
|
public BasicKeyChain toEncrypted(CharSequence password) {
|
||||||
checkNotNull(password);
|
Objects.requireNonNull(password);
|
||||||
checkArgument(password.length() > 0);
|
checkArgument(password.length() > 0);
|
||||||
KeyCrypter scrypt = new KeyCrypterScrypt();
|
KeyCrypter scrypt = new KeyCrypterScrypt();
|
||||||
AesKey derivedKey = scrypt.deriveKey(password);
|
AesKey derivedKey = scrypt.deriveKey(password);
|
||||||
|
@ -494,7 +494,7 @@ public class BasicKeyChain implements EncryptableKeyChain {
|
||||||
public BasicKeyChain toEncrypted(KeyCrypter keyCrypter, AesKey aesKey) {
|
public BasicKeyChain toEncrypted(KeyCrypter keyCrypter, AesKey aesKey) {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
checkNotNull(keyCrypter);
|
Objects.requireNonNull(keyCrypter);
|
||||||
checkState(this.keyCrypter == null, "Key chain is already encrypted");
|
checkState(this.keyCrypter == null, "Key chain is already encrypted");
|
||||||
BasicKeyChain encrypted = new BasicKeyChain(keyCrypter);
|
BasicKeyChain encrypted = new BasicKeyChain(keyCrypter);
|
||||||
for (ECKey key : hashToKeys.values()) {
|
for (ECKey key : hashToKeys.values()) {
|
||||||
|
@ -519,7 +519,7 @@ public class BasicKeyChain implements EncryptableKeyChain {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public BasicKeyChain toDecrypted(CharSequence password) {
|
public BasicKeyChain toDecrypted(CharSequence password) {
|
||||||
checkNotNull(keyCrypter, "Wallet is already decrypted");
|
Objects.requireNonNull(keyCrypter, "Wallet is already decrypted");
|
||||||
AesKey aesKey = keyCrypter.deriveKey(password);
|
AesKey aesKey = keyCrypter.deriveKey(password);
|
||||||
return toDecrypted(aesKey);
|
return toDecrypted(aesKey);
|
||||||
}
|
}
|
||||||
|
@ -551,7 +551,7 @@ public class BasicKeyChain implements EncryptableKeyChain {
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public boolean checkPassword(CharSequence password) {
|
public boolean checkPassword(CharSequence password) {
|
||||||
checkNotNull(password);
|
Objects.requireNonNull(password);
|
||||||
checkState(keyCrypter != null, "Key chain not encrypted");
|
checkState(keyCrypter != null, "Key chain not encrypted");
|
||||||
return checkAESKey(keyCrypter.deriveKey(password));
|
return checkAESKey(keyCrypter.deriveKey(password));
|
||||||
}
|
}
|
||||||
|
|
|
@ -23,8 +23,7 @@ import org.bitcoinj.crypto.ECKey;
|
||||||
import javax.annotation.Nullable;
|
import javax.annotation.Nullable;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A DecryptingKeyBag filters a pre-existing key bag, decrypting keys as they are requested using the provided
|
* 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;
|
protected final AesKey aesKey;
|
||||||
|
|
||||||
public DecryptingKeyBag(KeyBag target, @Nullable AesKey aesKey) {
|
public DecryptingKeyBag(KeyBag target, @Nullable AesKey aesKey) {
|
||||||
this.target = checkNotNull(target);
|
this.target = Objects.requireNonNull(target);
|
||||||
this.aesKey = aesKey;
|
this.aesKey = aesKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -56,6 +56,7 @@ import java.util.LinkedList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
@ -63,7 +64,6 @@ import java.util.function.Predicate;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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 com.google.common.base.Preconditions.checkState;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -214,7 +214,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
||||||
*/
|
*/
|
||||||
public T entropy(byte[] entropy, Instant creationTime) {
|
public T entropy(byte[] entropy, Instant creationTime) {
|
||||||
this.entropy = entropy;
|
this.entropy = entropy;
|
||||||
this.creationTime = checkNotNull(creationTime);
|
this.creationTime = Objects.requireNonNull(creationTime);
|
||||||
return self();
|
return self();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -306,7 +306,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
||||||
*/
|
*/
|
||||||
public T accountPath(List<ChildNumber> accountPath) {
|
public T accountPath(List<ChildNumber> accountPath) {
|
||||||
checkState(watchingKey == null, "either watch or accountPath");
|
checkState(watchingKey == null, "either watch or accountPath");
|
||||||
this.accountPath = HDPath.M(checkNotNull(accountPath));
|
this.accountPath = HDPath.M(Objects.requireNonNull(accountPath));
|
||||||
return self();
|
return self();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -396,7 +396,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
||||||
this.seed = seed;
|
this.seed = seed;
|
||||||
basicKeyChain = new BasicKeyChain(crypter);
|
basicKeyChain = new BasicKeyChain(crypter);
|
||||||
if (!seed.isEncrypted()) {
|
if (!seed.isEncrypted()) {
|
||||||
rootKey = HDKeyDerivation.createMasterPrivateKey(checkNotNull(seed.getSeedBytes()));
|
rootKey = HDKeyDerivation.createMasterPrivateKey(Objects.requireNonNull(seed.getSeedBytes()));
|
||||||
Optional<Instant> creationTime = seed.getCreationTime();
|
Optional<Instant> creationTime = seed.getCreationTime();
|
||||||
if (creationTime.isPresent())
|
if (creationTime.isPresent())
|
||||||
rootKey.setCreationTime(creationTime.get());
|
rootKey.setCreationTime(creationTime.get());
|
||||||
|
@ -422,8 +422,8 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
||||||
*/
|
*/
|
||||||
protected DeterministicKeyChain(KeyCrypter crypter, AesKey aesKey, DeterministicKeyChain chain) {
|
protected DeterministicKeyChain(KeyCrypter crypter, AesKey aesKey, DeterministicKeyChain chain) {
|
||||||
// Can't encrypt a watching chain.
|
// Can't encrypt a watching chain.
|
||||||
checkNotNull(chain.rootKey);
|
Objects.requireNonNull(chain.rootKey);
|
||||||
checkNotNull(chain.seed);
|
Objects.requireNonNull(chain.seed);
|
||||||
|
|
||||||
checkArgument(!chain.rootKey.isEncrypted(), "Chain already encrypted");
|
checkArgument(!chain.rootKey.isEncrypted(), "Chain already encrypted");
|
||||||
this.accountPath = chain.getAccountPath();
|
this.accountPath = chain.getAccountPath();
|
||||||
|
@ -470,7 +470,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
||||||
private DeterministicKey encryptNonLeaf(AesKey aesKey, DeterministicKeyChain chain,
|
private DeterministicKey encryptNonLeaf(AesKey aesKey, DeterministicKeyChain chain,
|
||||||
DeterministicKey parent, List<ChildNumber> path) {
|
DeterministicKey parent, List<ChildNumber> path) {
|
||||||
DeterministicKey key = chain.hierarchy.get(path, false, false);
|
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);
|
putKey(key);
|
||||||
return key;
|
return key;
|
||||||
}
|
}
|
||||||
|
@ -561,12 +561,12 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
||||||
|
|
||||||
// Clone key to new hierarchy.
|
// Clone key to new hierarchy.
|
||||||
private static DeterministicKey cloneKey(DeterministicHierarchy hierarchy, DeterministicKey key) {
|
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);
|
return new DeterministicKey(key.dropPrivateBytes(), parent);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void checkForBitFlip(DeterministicKey k) {
|
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[] rederived = HDKeyDerivation.deriveChildKeyBytesFromPublic(parent, k.getChildNumber(), HDKeyDerivation.PublicDeriveMode.WITH_INVERSION).keyBytes;
|
||||||
byte[] actual = k.getPubKey();
|
byte[] actual = k.getPubKey();
|
||||||
if (!Arrays.equals(rederived, actual))
|
if (!Arrays.equals(rederived, actual))
|
||||||
|
@ -955,7 +955,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
||||||
Protos.EncryptedData proto = key.getEncryptedData();
|
Protos.EncryptedData proto = key.getEncryptedData();
|
||||||
EncryptedData data = new EncryptedData(proto.getInitialisationVector().toByteArray(),
|
EncryptedData data = new EncryptedData(proto.getInitialisationVector().toByteArray(),
|
||||||
proto.getEncryptedPrivateKey().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);
|
detkey = new DeterministicKey(path, chainCode, crypter, pubkey, data, parent);
|
||||||
} else {
|
} else {
|
||||||
// No secret key bytes and key is not encrypted: either a watching key or private key bytes
|
// 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
|
@Override
|
||||||
public DeterministicKeyChain toEncrypted(CharSequence password) {
|
public DeterministicKeyChain toEncrypted(CharSequence password) {
|
||||||
checkNotNull(password);
|
Objects.requireNonNull(password);
|
||||||
checkArgument(password.length() > 0);
|
checkArgument(password.length() > 0);
|
||||||
checkState(seed != null, "Attempt to encrypt a watching chain.");
|
checkState(seed != null, "Attempt to encrypt a watching chain.");
|
||||||
checkState(!seed.isEncrypted());
|
checkState(!seed.isEncrypted());
|
||||||
|
@ -1042,7 +1042,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DeterministicKeyChain toDecrypted(CharSequence password) {
|
public DeterministicKeyChain toDecrypted(CharSequence password) {
|
||||||
checkNotNull(password);
|
Objects.requireNonNull(password);
|
||||||
checkArgument(password.length() > 0);
|
checkArgument(password.length() > 0);
|
||||||
KeyCrypter crypter = getKeyCrypter();
|
KeyCrypter crypter = getKeyCrypter();
|
||||||
checkState(crypter != null, "Chain not encrypted");
|
checkState(crypter != null, "Chain not encrypted");
|
||||||
|
@ -1088,7 +1088,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean checkPassword(CharSequence password) {
|
public boolean checkPassword(CharSequence password) {
|
||||||
checkNotNull(password);
|
Objects.requireNonNull(password);
|
||||||
checkState(getKeyCrypter() != null, "Key chain not encrypted");
|
checkState(getKeyCrypter() != null, "Key chain not encrypted");
|
||||||
return checkAESKey(getKeyCrypter().deriveKey(password));
|
return checkAESKey(getKeyCrypter().deriveKey(password));
|
||||||
}
|
}
|
||||||
|
@ -1096,7 +1096,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
|
||||||
@Override
|
@Override
|
||||||
public boolean checkAESKey(AesKey aesKey) {
|
public boolean checkAESKey(AesKey aesKey) {
|
||||||
checkState(rootKey != null, "Can't check password for a watching chain");
|
checkState(rootKey != null, "Can't check password for a watching chain");
|
||||||
checkNotNull(aesKey);
|
Objects.requireNonNull(aesKey);
|
||||||
checkState(getKeyCrypter() != null, "Key chain not encrypted");
|
checkState(getKeyCrypter() != null, "Key chain not encrypted");
|
||||||
try {
|
try {
|
||||||
return rootKey.decrypt(aesKey).getPubKeyPoint().equals(rootKey.getPubKeyPoint());
|
return rootKey.decrypt(aesKey).getPubKeyPoint().equals(rootKey.getPubKeyPoint());
|
||||||
|
|
|
@ -37,7 +37,6 @@ import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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 com.google.common.base.Preconditions.checkState;
|
||||||
import org.bitcoinj.base.internal.ByteUtils;
|
import org.bitcoinj.base.internal.ByteUtils;
|
||||||
|
|
||||||
|
@ -66,7 +65,7 @@ public class DeterministicSeed implements EncryptableItem {
|
||||||
* @param creationTime when the seed was originally created
|
* @param creationTime when the seed was originally created
|
||||||
*/
|
*/
|
||||||
public static DeterministicSeed ofMnemonic(String mnemonicCode, String passphrase, Instant creationTime) {
|
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
|
* @param creationTime when the seed was originally created
|
||||||
*/
|
*/
|
||||||
public static DeterministicSeed ofMnemonic(List<String> mnemonicCode, String passphrase, Instant creationTime) {
|
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
|
* @param creationTime when the seed was originally created
|
||||||
*/
|
*/
|
||||||
public static DeterministicSeed ofEntropy(byte[] entropy, String passphrase, Instant creationTime) {
|
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. */
|
/** Internal use only. */
|
||||||
private DeterministicSeed(byte[] seed, List<String> mnemonic, @Nullable Instant creationTime) {
|
private DeterministicSeed(byte[] seed, List<String> mnemonic, @Nullable Instant creationTime) {
|
||||||
this.seed = checkNotNull(seed);
|
this.seed = Objects.requireNonNull(seed);
|
||||||
this.mnemonicCode = checkNotNull(mnemonic);
|
this.mnemonicCode = Objects.requireNonNull(mnemonic);
|
||||||
this.encryptedMnemonicCode = null;
|
this.encryptedMnemonicCode = null;
|
||||||
this.encryptedSeed = null;
|
this.encryptedSeed = null;
|
||||||
this.creationTime = creationTime;
|
this.creationTime = creationTime;
|
||||||
|
@ -159,7 +158,7 @@ public class DeterministicSeed implements EncryptableItem {
|
||||||
DeterministicSeed(EncryptedData encryptedMnemonic, @Nullable EncryptedData encryptedSeed, @Nullable Instant creationTime) {
|
DeterministicSeed(EncryptedData encryptedMnemonic, @Nullable EncryptedData encryptedSeed, @Nullable Instant creationTime) {
|
||||||
this.seed = null;
|
this.seed = null;
|
||||||
this.mnemonicCode = null;
|
this.mnemonicCode = null;
|
||||||
this.encryptedMnemonicCode = checkNotNull(encryptedMnemonic);
|
this.encryptedMnemonicCode = Objects.requireNonNull(encryptedMnemonic);
|
||||||
this.encryptedSeed = encryptedSeed;
|
this.encryptedSeed = encryptedSeed;
|
||||||
this.creationTime = creationTime;
|
this.creationTime = creationTime;
|
||||||
}
|
}
|
||||||
|
@ -172,7 +171,7 @@ public class DeterministicSeed implements EncryptableItem {
|
||||||
|
|
||||||
/** Internal use only. */
|
/** Internal use only. */
|
||||||
private DeterministicSeed(List<String> mnemonicCode, @Nullable byte[] seed, String passphrase, @Nullable Instant creationTime) {
|
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)} */
|
/** @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 use {@link #ofRandom(SecureRandom, int, String)} */
|
||||||
@Deprecated
|
@Deprecated
|
||||||
public DeterministicSeed(SecureRandom random, int bits, String passphrase) {
|
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. */
|
/** Internal use only. */
|
||||||
private DeterministicSeed(byte[] entropy, String passphrase, @Nullable Instant creationTime) {
|
private DeterministicSeed(byte[] entropy, String passphrase, @Nullable Instant creationTime) {
|
||||||
checkArgument(entropy.length * 8 >= DEFAULT_SEED_ENTROPY_BITS, "entropy size too small");
|
checkArgument(entropy.length * 8 >= DEFAULT_SEED_ENTROPY_BITS, "entropy size too small");
|
||||||
checkNotNull(passphrase);
|
Objects.requireNonNull(passphrase);
|
||||||
|
|
||||||
this.mnemonicCode = MnemonicCode.INSTANCE.toMnemonic(entropy);
|
this.mnemonicCode = MnemonicCode.INSTANCE.toMnemonic(entropy);
|
||||||
this.seed = MnemonicCode.toSeed(mnemonicCode, passphrase);
|
this.seed = MnemonicCode.toSeed(mnemonicCode, passphrase);
|
||||||
|
@ -278,7 +277,7 @@ public class DeterministicSeed implements EncryptableItem {
|
||||||
* @param creationTime creation time of this seed
|
* @param creationTime creation time of this seed
|
||||||
*/
|
*/
|
||||||
public void setCreationTime(Instant creationTime) {
|
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) {
|
public DeterministicSeed decrypt(KeyCrypter crypter, String passphrase, AesKey aesKey) {
|
||||||
checkState(isEncrypted());
|
checkState(isEncrypted());
|
||||||
checkNotNull(encryptedMnemonicCode);
|
Objects.requireNonNull(encryptedMnemonicCode);
|
||||||
List<String> mnemonic = decodeMnemonicCode(crypter.decrypt(encryptedMnemonicCode, aesKey));
|
List<String> mnemonic = decodeMnemonicCode(crypter.decrypt(encryptedMnemonicCode, aesKey));
|
||||||
byte[] seed = encryptedSeed == null ? null : crypter.decrypt(encryptedSeed, aesKey);
|
byte[] seed = encryptedSeed == null ? null : crypter.decrypt(encryptedSeed, aesKey);
|
||||||
return new DeterministicSeed(mnemonic, seed, passphrase, creationTime);
|
return new DeterministicSeed(mnemonic, seed, passphrase, creationTime);
|
||||||
|
|
|
@ -52,13 +52,13 @@ import java.util.Iterator;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.concurrent.CopyOnWriteArrayList;
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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 com.google.common.base.Preconditions.checkState;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -735,7 +735,7 @@ public class KeyChainGroup implements KeyBag {
|
||||||
* @throws java.lang.IllegalArgumentException if the key is deterministic.
|
* @throws java.lang.IllegalArgumentException if the key is deterministic.
|
||||||
*/
|
*/
|
||||||
public boolean removeImportedKey(ECKey key) {
|
public boolean removeImportedKey(ECKey key) {
|
||||||
checkNotNull(key);
|
Objects.requireNonNull(key);
|
||||||
checkArgument(!(key instanceof DeterministicKey));
|
checkArgument(!(key instanceof DeterministicKey));
|
||||||
return basic.removeKey(key);
|
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.
|
* @throws DeterministicUpgradeRequiredException Thrown if there are random keys but no HD chain.
|
||||||
*/
|
*/
|
||||||
public void encrypt(KeyCrypter keyCrypter, AesKey aesKey) {
|
public void encrypt(KeyCrypter keyCrypter, AesKey aesKey) {
|
||||||
checkNotNull(keyCrypter);
|
Objects.requireNonNull(keyCrypter);
|
||||||
checkNotNull(aesKey);
|
Objects.requireNonNull(aesKey);
|
||||||
checkState((chains != null && !chains.isEmpty()) || basic.numKeys() != 0, "can't encrypt entirely empty wallet");
|
checkState((chains != null && !chains.isEmpty()) || basic.numKeys() != 0, "can't encrypt entirely empty wallet");
|
||||||
|
|
||||||
BasicKeyChain newBasic = basic.toEncrypted(keyCrypter, aesKey);
|
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.
|
* @throws org.bitcoinj.crypto.KeyCrypterException Thrown if the wallet decryption fails for some reason, leaving the group unchanged.
|
||||||
*/
|
*/
|
||||||
public void decrypt(AesKey aesKey) {
|
public void decrypt(AesKey aesKey) {
|
||||||
checkNotNull(aesKey);
|
Objects.requireNonNull(aesKey);
|
||||||
|
|
||||||
BasicKeyChain newBasic = basic.toDecrypted(aesKey);
|
BasicKeyChain newBasic = basic.toDecrypted(aesKey);
|
||||||
if (chains != null) {
|
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. */
|
/** Adds a listener for events that are run when keys are added, on the given executor. */
|
||||||
public void addEventListener(KeyChainEventListener listener, Executor executor) {
|
public void addEventListener(KeyChainEventListener listener, Executor executor) {
|
||||||
checkNotNull(listener);
|
Objects.requireNonNull(listener);
|
||||||
checkNotNull(executor);
|
Objects.requireNonNull(executor);
|
||||||
basic.addEventListener(listener, executor);
|
basic.addEventListener(listener, executor);
|
||||||
if (chains != null)
|
if (chains != null)
|
||||||
for (DeterministicKeyChain chain : chains)
|
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. */
|
/** Removes a listener for events that are run when keys are added. */
|
||||||
public boolean removeEventListener(KeyChainEventListener listener) {
|
public boolean removeEventListener(KeyChainEventListener listener) {
|
||||||
checkNotNull(listener);
|
Objects.requireNonNull(listener);
|
||||||
if (chains != null)
|
if (chains != null)
|
||||||
for (DeterministicKeyChain chain : chains)
|
for (DeterministicKeyChain chain : chains)
|
||||||
chain.removeEventListener(listener);
|
chain.removeEventListener(listener);
|
||||||
|
@ -926,13 +926,13 @@ public class KeyChainGroup implements KeyBag {
|
||||||
* executor.
|
* executor.
|
||||||
*/
|
*/
|
||||||
public void addCurrentKeyChangeEventListener(CurrentKeyChangeEventListener listener, Executor executor) {
|
public void addCurrentKeyChangeEventListener(CurrentKeyChangeEventListener listener, Executor executor) {
|
||||||
checkNotNull(listener);
|
Objects.requireNonNull(listener);
|
||||||
currentKeyChangeListeners.add(new ListenerRegistration<>(listener, executor));
|
currentKeyChangeListeners.add(new ListenerRegistration<>(listener, executor));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Removes a listener for events that are run when a current key and/or address changes. */
|
/** Removes a listener for events that are run when a current key and/or address changes. */
|
||||||
public boolean removeCurrentKeyChangeEventListener(CurrentKeyChangeEventListener listener) {
|
public boolean removeCurrentKeyChangeEventListener(CurrentKeyChangeEventListener listener) {
|
||||||
checkNotNull(listener);
|
Objects.requireNonNull(listener);
|
||||||
return ListenerRegistration.removeFromList(listener, currentKeyChangeListeners);
|
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 {
|
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);
|
BasicKeyChain basicKeyChain = BasicKeyChain.fromProtobufEncrypted(keys, crypter);
|
||||||
List<DeterministicKeyChain> chains = DeterministicKeyChain.fromProtobuf(keys, crypter, factory);
|
List<DeterministicKeyChain> chains = DeterministicKeyChain.fromProtobuf(keys, crypter, factory);
|
||||||
int lookaheadSize = -1, lookaheadThreshold = -1;
|
int lookaheadSize = -1, lookaheadThreshold = -1;
|
||||||
|
@ -1025,7 +1025,7 @@ public class KeyChainGroup implements KeyBag {
|
||||||
@Nullable Instant keyRotationTime, @Nullable AesKey aesKey)
|
@Nullable Instant keyRotationTime, @Nullable AesKey aesKey)
|
||||||
throws DeterministicUpgradeRequiresPassword {
|
throws DeterministicUpgradeRequiresPassword {
|
||||||
checkState(supportsDeterministicChains(), "doesn't support deterministic chains");
|
checkState(supportsDeterministicChains(), "doesn't support deterministic chains");
|
||||||
checkNotNull(structure);
|
Objects.requireNonNull(structure);
|
||||||
if (!isDeterministicUpgradeRequired(preferredScriptType, keyRotationTime))
|
if (!isDeterministicUpgradeRequired(preferredScriptType, keyRotationTime))
|
||||||
return; // Nothing to do.
|
return; // Nothing to do.
|
||||||
|
|
||||||
|
@ -1044,7 +1044,7 @@ public class KeyChainGroup implements KeyBag {
|
||||||
.outputScriptType(ScriptType.P2WPKH)
|
.outputScriptType(ScriptType.P2WPKH)
|
||||||
.accountPath(structure.accountPathFor(ScriptType.P2WPKH, BitcoinNetwork.MAINNET)).build();
|
.accountPath(structure.accountPathFor(ScriptType.P2WPKH, BitcoinNetwork.MAINNET)).build();
|
||||||
if (seedWasEncrypted)
|
if (seedWasEncrypted)
|
||||||
chain = chain.toEncrypted(checkNotNull(keyCrypter), aesKey);
|
chain = chain.toEncrypted(Objects.requireNonNull(keyCrypter), aesKey);
|
||||||
addAndActivateHDChain(chain);
|
addAndActivateHDChain(chain);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,8 +32,7 @@ import org.slf4j.LoggerFactory;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A coin selector that takes all coins assigned to keys created before the given timestamp.
|
* 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;
|
private final boolean ignorePending;
|
||||||
|
|
||||||
public KeyTimeCoinSelector(Wallet wallet, Instant time, boolean ignorePending) {
|
public KeyTimeCoinSelector(Wallet wallet, Instant time, boolean ignorePending) {
|
||||||
this.time = checkNotNull(time);
|
this.time = Objects.requireNonNull(time);
|
||||||
this.wallet = wallet;
|
this.wallet = wallet;
|
||||||
this.ignorePending = ignorePending;
|
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);
|
log.info("Skipping tx output {} because it's not of simple form.", output);
|
||||||
continue;
|
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;
|
if (controllingKey.getCreationTime().orElse(Instant.EPOCH).compareTo(time) >= 0) continue;
|
||||||
// It's older than the cutoff time so select.
|
// It's older than the cutoff time so select.
|
||||||
gathered.push(output);
|
gathered.push(output);
|
||||||
|
|
|
@ -36,11 +36,11 @@ import java.util.Collections;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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 com.google.common.base.Preconditions.checkState;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -94,7 +94,7 @@ public class MarriedKeyChain extends DeterministicKeyChain {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public MarriedKeyChain build() {
|
public MarriedKeyChain build() {
|
||||||
checkNotNull(followingKeys, "followingKeys must be provided");
|
Objects.requireNonNull(followingKeys, "followingKeys must be provided");
|
||||||
|
|
||||||
if (threshold == 0)
|
if (threshold == 0)
|
||||||
threshold = (followingKeys.size() + 1) / 2 + 1;
|
threshold = (followingKeys.size() + 1) / 2 + 1;
|
||||||
|
|
|
@ -31,7 +31,7 @@ import org.bitcoinj.utils.ExchangeRate;
|
||||||
import org.bitcoinj.wallet.KeyChain.KeyPurpose;
|
import org.bitcoinj.wallet.KeyChain.KeyPurpose;
|
||||||
import org.bitcoinj.wallet.Wallet.MissingSigsMode;
|
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.
|
* 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) {
|
public static SendRequest to(Address destination, Coin value) {
|
||||||
SendRequest req = new SendRequest();
|
SendRequest req = new SendRequest();
|
||||||
final NetworkParameters parameters = NetworkParameters.of(destination.network());
|
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 = new Transaction(parameters);
|
||||||
req.tx.addOutput(value, destination);
|
req.tx.addOutput(value, destination);
|
||||||
return req;
|
return req;
|
||||||
|
@ -202,7 +202,7 @@ public class SendRequest {
|
||||||
public static SendRequest emptyWallet(Address destination) {
|
public static SendRequest emptyWallet(Address destination) {
|
||||||
SendRequest req = new SendRequest();
|
SendRequest req = new SendRequest();
|
||||||
final NetworkParameters parameters = NetworkParameters.of(destination.network());
|
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 = new Transaction(parameters);
|
||||||
req.tx.addOutput(Coin.ZERO, destination);
|
req.tx.addOutput(Coin.ZERO, destination);
|
||||||
req.emptyWallet = true;
|
req.emptyWallet = true;
|
||||||
|
@ -224,7 +224,7 @@ public class SendRequest {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// TODO spend another confirmed output of own wallet if needed
|
// 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());
|
final Transaction tx = new Transaction(parentTransaction.getParams());
|
||||||
tx.addInput(outputToSpend);
|
tx.addInput(outputToSpend);
|
||||||
|
@ -257,4 +257,4 @@ public class SendRequest {
|
||||||
helper.add("recipientsPayFees", recipientsPayFees);
|
helper.add("recipientsPayFees", recipientsPayFees);
|
||||||
return helper.toString();
|
return helper.toString();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -128,6 +128,7 @@ import java.util.LinkedHashMap;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.TreeSet;
|
import java.util.TreeSet;
|
||||||
|
@ -139,7 +140,6 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
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 com.google.common.base.Preconditions.checkState;
|
||||||
|
|
||||||
// To do list:
|
// To do list:
|
||||||
|
@ -509,8 +509,8 @@ public class Wallet extends BaseTaggableObject
|
||||||
* @param keyChainGroup keychain group to manage keychains
|
* @param keyChainGroup keychain group to manage keychains
|
||||||
*/
|
*/
|
||||||
public Wallet(NetworkParameters params, KeyChainGroup keyChainGroup) {
|
public Wallet(NetworkParameters params, KeyChainGroup keyChainGroup) {
|
||||||
this.params = checkNotNull(params);
|
this.params = Objects.requireNonNull(params);
|
||||||
this.keyChainGroup = checkNotNull(keyChainGroup);
|
this.keyChainGroup = Objects.requireNonNull(keyChainGroup);
|
||||||
watchedScripts = new HashSet<>();
|
watchedScripts = new HashSet<>();
|
||||||
unspent = new HashMap<>();
|
unspent = new HashMap<>();
|
||||||
spent = new HashMap<>();
|
spent = new HashMap<>();
|
||||||
|
@ -941,7 +941,7 @@ public class Wallet extends BaseTaggableObject
|
||||||
public int importKeysAndEncrypt(final List<ECKey> keys, CharSequence password) {
|
public int importKeysAndEncrypt(final List<ECKey> keys, CharSequence password) {
|
||||||
keyChainGroupLock.lock();
|
keyChainGroupLock.lock();
|
||||||
try {
|
try {
|
||||||
checkNotNull(getKeyCrypter(), "Wallet is not encrypted");
|
Objects.requireNonNull(getKeyCrypter(), "Wallet is not encrypted");
|
||||||
return importKeysAndEncrypt(keys, getKeyCrypter().deriveKey(password));
|
return importKeysAndEncrypt(keys, getKeyCrypter().deriveKey(password));
|
||||||
} finally {
|
} finally {
|
||||||
keyChainGroupLock.unlock();
|
keyChainGroupLock.unlock();
|
||||||
|
@ -1664,7 +1664,7 @@ public class Wallet extends BaseTaggableObject
|
||||||
public void setRiskAnalyzer(RiskAnalysis.Analyzer analyzer) {
|
public void setRiskAnalyzer(RiskAnalysis.Analyzer analyzer) {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
this.riskAnalyzer = checkNotNull(analyzer);
|
this.riskAnalyzer = Objects.requireNonNull(analyzer);
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock();
|
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 (result == TransactionInput.ConnectionResult.ALREADY_SPENT) {
|
||||||
if (fromChain) {
|
if (fromChain) {
|
||||||
// Can be:
|
// 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.
|
// 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
|
// 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.
|
// 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());
|
log.info(" marked {} as spent by {}", input.getOutpoint(), tx.getTxId());
|
||||||
maybeMovePool(connected, "prevtx");
|
maybeMovePool(connected, "prevtx");
|
||||||
// Just because it's connected doesn't mean it's actually ours: sometimes we have total visibility.
|
// 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) {
|
public void setLastBlockSeenTime(Instant time) {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
lastBlockSeenTime = checkNotNull(time);
|
lastBlockSeenTime = Objects.requireNonNull(time);
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
}
|
}
|
||||||
|
@ -3853,7 +3853,7 @@ public class Wallet extends BaseTaggableObject
|
||||||
public Coin getBalance(CoinSelector selector) {
|
public Coin getBalance(CoinSelector selector) {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
checkNotNull(selector);
|
Objects.requireNonNull(selector);
|
||||||
List<TransactionOutput> candidates = calculateAllSpendCandidates(true, false);
|
List<TransactionOutput> candidates = calculateAllSpendCandidates(true, false);
|
||||||
CoinSelection selection = selector.select((Coin) params.network().maxMoney(), candidates);
|
CoinSelection selection = selector.select((Coin) params.network().maxMoney(), candidates);
|
||||||
return selection.totalValue();
|
return selection.totalValue();
|
||||||
|
@ -4474,7 +4474,8 @@ public class Wallet extends BaseTaggableObject
|
||||||
}
|
}
|
||||||
|
|
||||||
RedeemData redeemData = txIn.getConnectedRedeemData(maybeDecryptingKeyBag);
|
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.setScriptSig(scriptPubKey.createEmptyInputScript(redeemData.keys.get(0), redeemData.redeemScript));
|
||||||
txIn.setWitness(scriptPubKey.createEmptyWitness(redeemData.keys.get(0)));
|
txIn.setWitness(scriptPubKey.createEmptyWitness(redeemData.keys.get(0)));
|
||||||
}
|
}
|
||||||
|
@ -4532,7 +4533,7 @@ public class Wallet extends BaseTaggableObject
|
||||||
if (vUTXOProvider == null) {
|
if (vUTXOProvider == null) {
|
||||||
candidates = myUnspents.stream()
|
candidates = myUnspents.stream()
|
||||||
.filter(output -> (!excludeUnsignable || canSignFor(output.getScriptPubKey())) &&
|
.filter(output -> (!excludeUnsignable || canSignFor(output.getScriptPubKey())) &&
|
||||||
(!excludeImmatureCoinbases || checkNotNull(output.getParentTransaction()).isMature()))
|
(!excludeImmatureCoinbases || Objects.requireNonNull(output.getParentTransaction()).isMature()))
|
||||||
.collect(StreamUtils.toUnmodifiableList());
|
.collect(StreamUtils.toUnmodifiableList());
|
||||||
} else {
|
} else {
|
||||||
candidates = calculateAllSpendCandidatesFromUTXOProvider(excludeImmatureCoinbases);
|
candidates = calculateAllSpendCandidatesFromUTXOProvider(excludeImmatureCoinbases);
|
||||||
|
@ -4579,7 +4580,7 @@ public class Wallet extends BaseTaggableObject
|
||||||
*/
|
*/
|
||||||
protected LinkedList<TransactionOutput> calculateAllSpendCandidatesFromUTXOProvider(boolean excludeImmatureCoinbases) {
|
protected LinkedList<TransactionOutput> calculateAllSpendCandidatesFromUTXOProvider(boolean excludeImmatureCoinbases) {
|
||||||
checkState(lock.isHeldByCurrentThread());
|
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<>();
|
LinkedList<TransactionOutput> candidates = new LinkedList<>();
|
||||||
try {
|
try {
|
||||||
int chainHeight = utxoProvider.getChainHeadHeight();
|
int chainHeight = utxoProvider.getChainHeadHeight();
|
||||||
|
@ -4620,7 +4621,7 @@ public class Wallet extends BaseTaggableObject
|
||||||
* @return The list of stored outputs.
|
* @return The list of stored outputs.
|
||||||
*/
|
*/
|
||||||
protected List<UTXO> getStoredOutputsFromUTXOProvider() throws UTXOProviderException {
|
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<UTXO> candidates = new ArrayList<>();
|
||||||
List<ECKey> keys = getImportedKeys();
|
List<ECKey> keys = getImportedKeys();
|
||||||
keys.addAll(getActiveKeyChain().getLeafKeys());
|
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.
|
* add the same extension twice (or two different objects that use the same ID) will throw an IllegalStateException.
|
||||||
*/
|
*/
|
||||||
public void addExtension(WalletExtension extension) {
|
public void addExtension(WalletExtension extension) {
|
||||||
String id = checkNotNull(extension).getWalletExtensionID();
|
String id = Objects.requireNonNull(extension).getWalletExtensionID();
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
if (extensions.containsKey(id))
|
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.
|
* Atomically adds extension or returns an existing extension if there is one with the same id already present.
|
||||||
*/
|
*/
|
||||||
public WalletExtension addOrGetExistingExtension(WalletExtension extension) {
|
public WalletExtension addOrGetExistingExtension(WalletExtension extension) {
|
||||||
String id = checkNotNull(extension).getWalletExtensionID();
|
String id = Objects.requireNonNull(extension).getWalletExtensionID();
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
WalletExtension previousExtension = extensions.get(id);
|
WalletExtension previousExtension = extensions.get(id);
|
||||||
|
@ -5105,7 +5106,7 @@ public class Wallet extends BaseTaggableObject
|
||||||
* already present.
|
* already present.
|
||||||
*/
|
*/
|
||||||
public void addOrUpdateExtension(WalletExtension extension) {
|
public void addOrUpdateExtension(WalletExtension extension) {
|
||||||
String id = checkNotNull(extension).getWalletExtensionID();
|
String id = Objects.requireNonNull(extension).getWalletExtensionID();
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
extensions.put(id, extension);
|
extensions.put(id, extension);
|
||||||
|
@ -5290,16 +5291,16 @@ public class Wallet extends BaseTaggableObject
|
||||||
Script redeemScript = null;
|
Script redeemScript = null;
|
||||||
if (ScriptPattern.isP2PKH(script)) {
|
if (ScriptPattern.isP2PKH(script)) {
|
||||||
key = findKeyFromPubKeyHash(ScriptPattern.extractHashFromP2PKH(script), ScriptType.P2PKH);
|
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);
|
vsize += script.getNumberOfBytesRequiredToSpend(key, redeemScript);
|
||||||
} else if (ScriptPattern.isP2WPKH(script)) {
|
} else if (ScriptPattern.isP2WPKH(script)) {
|
||||||
key = findKeyFromPubKeyHash(ScriptPattern.extractHashFromP2WH(script), ScriptType.P2WPKH);
|
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,
|
vsize += IntMath.divide(script.getNumberOfBytesRequiredToSpend(key, redeemScript), 4,
|
||||||
RoundingMode.CEILING); // round up
|
RoundingMode.CEILING); // round up
|
||||||
} else if (ScriptPattern.isP2SH(script)) {
|
} else if (ScriptPattern.isP2SH(script)) {
|
||||||
redeemScript = findRedeemDataFromScriptHash(ScriptPattern.extractHashFromP2SH(script)).redeemScript;
|
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);
|
vsize += script.getNumberOfBytesRequiredToSpend(key, redeemScript);
|
||||||
} else {
|
} else {
|
||||||
vsize += script.getNumberOfBytesRequiredToSpend(key, redeemScript);
|
vsize += script.getNumberOfBytesRequiredToSpend(key, redeemScript);
|
||||||
|
|
|
@ -30,13 +30,12 @@ import java.sql.Time;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.concurrent.Callable;
|
import java.util.concurrent.Callable;
|
||||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
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.
|
* 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
|
* 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.setKeepAliveTime(5, TimeUnit.SECONDS);
|
||||||
this.executor.allowCoreThreadTimeOut(true);
|
this.executor.allowCoreThreadTimeOut(true);
|
||||||
this.executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
|
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.
|
// 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.savePending = new AtomicBoolean();
|
||||||
this.delay = checkNotNull(delay);
|
this.delay = Objects.requireNonNull(delay);
|
||||||
|
|
||||||
this.saver = () -> {
|
this.saver = () -> {
|
||||||
// Runs in an auto save thread.
|
// 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.
|
* 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) {
|
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. */
|
/** Actually write the wallet file to disk, using an atomic rename when possible. Runs on the current thread. */
|
||||||
|
|
|
@ -61,10 +61,9 @@ import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Serialize and de-serialize a wallet to a byte stream containing a
|
* 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
|
* <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)));
|
tx.getTxId(), byteStringToHash(spentByTransactionHash)));
|
||||||
}
|
}
|
||||||
final int spendingIndex = transactionOutput.getSpentByTransactionIndex();
|
final int spendingIndex = transactionOutput.getSpentByTransactionIndex();
|
||||||
TransactionInput input = checkNotNull(spendingTx.getInput(spendingIndex));
|
TransactionInput input = Objects.requireNonNull(spendingTx.getInput(spendingIndex));
|
||||||
input.connect(output);
|
input.connect(output);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,7 +18,7 @@ package org.bitcoinj.wallet;
|
||||||
|
|
||||||
import org.bitcoinj.core.Transaction;
|
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.
|
* 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;
|
private final Pool pool;
|
||||||
|
|
||||||
public WalletTransaction(Pool pool, Transaction transaction) {
|
public WalletTransaction(Pool pool, Transaction transaction) {
|
||||||
this.pool = checkNotNull(pool);
|
this.pool = Objects.requireNonNull(pool);
|
||||||
this.transaction = transaction;
|
this.transaction = transaction;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -42,10 +42,10 @@ import java.io.ByteArrayOutputStream;
|
||||||
import java.math.BigInteger;
|
import java.math.BigInteger;
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
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.CENT;
|
||||||
import static org.bitcoinj.base.Coin.COIN;
|
import static org.bitcoinj.base.Coin.COIN;
|
||||||
import static org.bitcoinj.base.Coin.FIFTY_COINS;
|
import static org.bitcoinj.base.Coin.FIFTY_COINS;
|
||||||
|
@ -346,9 +346,9 @@ public class ChainSplitTest {
|
||||||
Block b1 = TESTNET.getGenesisBlock().createNextBlock(coinsTo);
|
Block b1 = TESTNET.getGenesisBlock().createNextBlock(coinsTo);
|
||||||
chain.add(b1);
|
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);
|
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);
|
wallet.commitTx(t1);
|
||||||
// t1 is still pending ...
|
// t1 is still pending ...
|
||||||
Block b2 = b1.createNextBlock(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
|
Block b2 = b1.createNextBlock(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
|
||||||
|
@ -383,8 +383,8 @@ public class ChainSplitTest {
|
||||||
assertEquals(ZERO, wallet.getBalance());
|
assertEquals(ZERO, wallet.getBalance());
|
||||||
// t2 is pending - resurrected double spends take precedence over our dead transactions (which are in nobodies
|
// t2 is pending - resurrected double spends take precedence over our dead transactions (which are in nobodies
|
||||||
// mempool by this point).
|
// mempool by this point).
|
||||||
t1 = checkNotNull(wallet.getTransaction(t1.getTxId()));
|
t1 = Objects.requireNonNull(wallet.getTransaction(t1.getTxId()));
|
||||||
t2 = checkNotNull(wallet.getTransaction(t2.getTxId()));
|
t2 = Objects.requireNonNull(wallet.getTransaction(t2.getTxId()));
|
||||||
assertEquals(ConfidenceType.DEAD, t1.getConfidence().getConfidenceType());
|
assertEquals(ConfidenceType.DEAD, t1.getConfidence().getConfidenceType());
|
||||||
assertEquals(ConfidenceType.PENDING, t2.getConfidence().getConfidenceType());
|
assertEquals(ConfidenceType.PENDING, t2.getConfidence().getConfidenceType());
|
||||||
}
|
}
|
||||||
|
@ -517,9 +517,9 @@ public class ChainSplitTest {
|
||||||
chain.add(b1);
|
chain.add(b1);
|
||||||
|
|
||||||
// Send a couple of payments one after the other (so the second depends on the change output of the first).
|
// 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);
|
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);
|
wallet.commitTx(t3);
|
||||||
chain.add(FakeTxBuilder.makeSolvedTestBlock(b1, t2, t3));
|
chain.add(FakeTxBuilder.makeSolvedTestBlock(b1, t2, t3));
|
||||||
|
|
||||||
|
|
|
@ -46,11 +46,11 @@ import java.util.Iterator;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Queue;
|
import java.util.Queue;
|
||||||
import java.util.Random;
|
import java.util.Random;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
import static com.google.common.base.Preconditions.checkState;
|
import static com.google.common.base.Preconditions.checkState;
|
||||||
import static org.bitcoinj.base.Coin.FIFTY_COINS;
|
import static org.bitcoinj.base.Coin.FIFTY_COINS;
|
||||||
import static org.bitcoinj.base.Coin.SATOSHI;
|
import static org.bitcoinj.base.Coin.SATOSHI;
|
||||||
|
@ -254,7 +254,7 @@ public class FullBlockTestGenerator {
|
||||||
// genesis -> b1 (0) -> b2 (1)
|
// genesis -> b1 (0) -> b2 (1)
|
||||||
// \-> b3 (1) -> b4 (2)
|
// \-> b3 (1) -> b4 (2)
|
||||||
//
|
//
|
||||||
TransactionOutPointWithValue out2 = checkNotNull(spendableOutputs.poll());
|
TransactionOutPointWithValue out2 = Objects.requireNonNull(spendableOutputs.poll());
|
||||||
NewBlock b4 = createNextBlock(b3, chainHeadHeight + 3, out2, null);
|
NewBlock b4 = createNextBlock(b3, chainHeadHeight + 3, out2, null);
|
||||||
blocks.add(new BlockAndValidity(b4, true, false, b4.getHash(), chainHeadHeight + 3, "b4"));
|
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)
|
// \-> b80 (25) -> b81 (26) -> b82 (27)
|
||||||
// b78 creates a tx, which is spent in b79. after b82, both should be in mempool
|
// b78 creates a tx, which is spent in b79. after b82, both should be in mempool
|
||||||
//
|
//
|
||||||
TransactionOutPointWithValue out24 = checkNotNull(spendableOutputs.poll());
|
TransactionOutPointWithValue out24 = Objects.requireNonNull(spendableOutputs.poll());
|
||||||
TransactionOutPointWithValue out25 = checkNotNull(spendableOutputs.poll());
|
TransactionOutPointWithValue out25 = Objects.requireNonNull(spendableOutputs.poll());
|
||||||
TransactionOutPointWithValue out26 = checkNotNull(spendableOutputs.poll());
|
TransactionOutPointWithValue out26 = Objects.requireNonNull(spendableOutputs.poll());
|
||||||
TransactionOutPointWithValue out27 = checkNotNull(spendableOutputs.poll());
|
TransactionOutPointWithValue out27 = Objects.requireNonNull(spendableOutputs.poll());
|
||||||
|
|
||||||
NewBlock b77 = createNextBlock(b76, chainHeadHeight + 25, out24, null);
|
NewBlock b77 = createNextBlock(b76, chainHeadHeight + 25, out24, null);
|
||||||
blocks.add(new BlockAndValidity(b77, true, false, b77.getHash(), chainHeadHeight + 25, "b77"));
|
blocks.add(new BlockAndValidity(b77, true, false, b77.getHash(), chainHeadHeight + 25, "b77"));
|
||||||
|
|
|
@ -41,6 +41,7 @@ import java.security.SignatureException;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.Random;
|
import java.util.Random;
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
@ -48,7 +49,6 @@ import java.util.function.Function;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.IntStream;
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
import static org.bitcoinj.base.internal.ByteUtils.reverseBytes;
|
import static org.bitcoinj.base.internal.ByteUtils.reverseBytes;
|
||||||
import static org.junit.Assert.assertArrayEquals;
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
@ -327,7 +327,7 @@ public class ECKeyTest {
|
||||||
boolean found = false;
|
boolean found = false;
|
||||||
for (int i = 0; i < 4; i++) {
|
for (int i = 0; i < 4; i++) {
|
||||||
ECKey key2 = ECKey.recoverFromSignature(i, sig, hash, true);
|
ECKey key2 = ECKey.recoverFromSignature(i, sig, hash, true);
|
||||||
checkNotNull(key2);
|
Objects.requireNonNull(key2);
|
||||||
if (key.equals(key2)) {
|
if (key.equals(key2)) {
|
||||||
found = true;
|
found = true;
|
||||||
break;
|
break;
|
||||||
|
@ -356,7 +356,7 @@ public class ECKeyTest {
|
||||||
@Test
|
@Test
|
||||||
public void testEncryptedCreate() {
|
public void testEncryptedCreate() {
|
||||||
ECKey unencryptedKey = new ECKey();
|
ECKey unencryptedKey = new ECKey();
|
||||||
byte[] originalPrivateKeyBytes = checkNotNull(unencryptedKey.getPrivKeyBytes());
|
byte[] originalPrivateKeyBytes = Objects.requireNonNull(unencryptedKey.getPrivKeyBytes());
|
||||||
log.info("Original private key = " + ByteUtils.formatHex(originalPrivateKeyBytes));
|
log.info("Original private key = " + ByteUtils.formatHex(originalPrivateKeyBytes));
|
||||||
EncryptedData encryptedPrivateKey = keyCrypter.encrypt(unencryptedKey.getPrivKeyBytes(), keyCrypter.deriveKey(PASSWORD1));
|
EncryptedData encryptedPrivateKey = keyCrypter.encrypt(unencryptedKey.getPrivKeyBytes(), keyCrypter.deriveKey(PASSWORD1));
|
||||||
ECKey encryptedKey = ECKey.fromEncrypted(encryptedPrivateKey, keyCrypter, unencryptedKey.getPubKey());
|
ECKey encryptedKey = ECKey.fromEncrypted(encryptedPrivateKey, keyCrypter, unencryptedKey.getPubKey());
|
||||||
|
@ -425,7 +425,7 @@ public class ECKeyTest {
|
||||||
boolean found = false;
|
boolean found = false;
|
||||||
for (int i = 0; i < 4; i++) {
|
for (int i = 0; i < 4; i++) {
|
||||||
ECKey key2 = ECKey.recoverFromSignature(i, sig, hash, true);
|
ECKey key2 = ECKey.recoverFromSignature(i, sig, hash, true);
|
||||||
checkNotNull(key2);
|
Objects.requireNonNull(key2);
|
||||||
if (unencryptedKey.equals(key2)) {
|
if (unencryptedKey.equals(key2)) {
|
||||||
found = true;
|
found = true;
|
||||||
break;
|
break;
|
||||||
|
|
|
@ -71,9 +71,9 @@ import java.time.temporal.ChronoUnit;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Set;
|
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.COIN;
|
||||||
import static org.bitcoinj.base.Coin.FIFTY_COINS;
|
import static org.bitcoinj.base.Coin.FIFTY_COINS;
|
||||||
import static org.bitcoinj.testing.FakeTxBuilder.createFakeTx;
|
import static org.bitcoinj.testing.FakeTxBuilder.createFakeTx;
|
||||||
|
@ -253,9 +253,9 @@ public class WalletProtobufSerializerTest {
|
||||||
tx2.getInput(0).setSequenceNumber(TransactionInput.NO_SEQUENCE - 1);
|
tx2.getInput(0).setSequenceNumber(TransactionInput.NO_SEQUENCE - 1);
|
||||||
wallet.receivePending(tx2, null);
|
wallet.receivePending(tx2, null);
|
||||||
Wallet walletCopy = roundTrip(wallet);
|
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());
|
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());
|
assertEquals(TransactionInput.NO_SEQUENCE - 1, tx2copy.getInput(0).getSequenceNumber());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -392,7 +392,7 @@ public class WalletProtobufSerializerTest {
|
||||||
myWallet.addWalletTransaction(new WalletTransaction(Pool.UNSPENT, tx));
|
myWallet.addWalletTransaction(new WalletTransaction(Pool.UNSPENT, tx));
|
||||||
Wallet wallet1 = roundTrip(myWallet);
|
Wallet wallet1 = roundTrip(myWallet);
|
||||||
Transaction tx2 = wallet1.getTransaction(tx.getTxId());
|
Transaction tx2 = wallet1.getTransaction(tx.getTxId());
|
||||||
assertEquals(checkNotNull(tx2).getVersion(), 2);
|
assertEquals(Objects.requireNonNull(tx2).getVersion(), 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -36,10 +36,10 @@ import java.util.Arrays;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
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.assertArrayEquals;
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertFalse;
|
import static org.junit.Assert.assertFalse;
|
||||||
|
@ -231,7 +231,7 @@ public class BasicKeyChainTest {
|
||||||
assertArrayEquals(key1.getPubKey(), keys.get(0).getPublicKey().toByteArray());
|
assertArrayEquals(key1.getPubKey(), keys.get(0).getPublicKey().toByteArray());
|
||||||
assertFalse(keys.get(0).hasSecretBytes());
|
assertFalse(keys.get(0).hasSecretBytes());
|
||||||
assertTrue(keys.get(0).hasEncryptedData());
|
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());
|
assertEquals(key1.getEncryptedPrivateKey(), chain.getKeys().get(0).getEncryptedPrivateKey());
|
||||||
assertTrue(chain.checkPassword("foo bar"));
|
assertTrue(chain.checkPassword("foo bar"));
|
||||||
}
|
}
|
||||||
|
|
|
@ -36,8 +36,8 @@ import java.net.InetAddress;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
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.CENT;
|
||||||
import static org.bitcoinj.base.Coin.COIN;
|
import static org.bitcoinj.base.Coin.COIN;
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
@ -84,8 +84,8 @@ public class DefaultCoinSelectorTest extends TestWithWallet {
|
||||||
@Test
|
@Test
|
||||||
public void depthOrdering() {
|
public void depthOrdering() {
|
||||||
// Send two transactions in two blocks on top of each other.
|
// Send two transactions in two blocks on top of each other.
|
||||||
Transaction t1 = checkNotNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN));
|
Transaction t1 = Objects.requireNonNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN));
|
||||||
Transaction t2 = checkNotNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN));
|
Transaction t2 = Objects.requireNonNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN));
|
||||||
|
|
||||||
// Check we selected just the oldest one.
|
// Check we selected just the oldest one.
|
||||||
DefaultCoinSelector selector = DefaultCoinSelector.get();
|
DefaultCoinSelector selector = DefaultCoinSelector.get();
|
||||||
|
@ -106,12 +106,12 @@ public class DefaultCoinSelectorTest extends TestWithWallet {
|
||||||
public void coinAgeOrdering() {
|
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
|
// 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.
|
// 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.
|
// Padding block.
|
||||||
wallet.notifyNewBestBlock(FakeTxBuilder.createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).storedBlock);
|
wallet.notifyNewBestBlock(FakeTxBuilder.createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).storedBlock);
|
||||||
final Coin TWO_COINS = COIN.multiply(2);
|
final Coin TWO_COINS = COIN.multiply(2);
|
||||||
Transaction t2 = checkNotNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, TWO_COINS));
|
Transaction t2 = Objects.requireNonNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, TWO_COINS));
|
||||||
Transaction t3 = checkNotNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT));
|
Transaction t3 = Objects.requireNonNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT));
|
||||||
|
|
||||||
// Should be ordered t2, t1, t3.
|
// Should be ordered t2, t1, t3.
|
||||||
ArrayList<TransactionOutput> candidates = new ArrayList<>();
|
ArrayList<TransactionOutput> candidates = new ArrayList<>();
|
||||||
|
|
|
@ -50,11 +50,11 @@ import java.security.SecureRandom;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
import static org.bitcoinj.base.BitcoinNetwork.MAINNET;
|
import static org.bitcoinj.base.BitcoinNetwork.MAINNET;
|
||||||
import static org.bitcoinj.base.BitcoinNetwork.TESTNET;
|
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.assertEquals;
|
||||||
import static org.junit.Assert.assertFalse;
|
import static org.junit.Assert.assertFalse;
|
||||||
import static org.junit.Assert.assertNotEquals;
|
import static org.junit.Assert.assertNotEquals;
|
||||||
|
@ -357,7 +357,7 @@ public class DeterministicKeyChainTest {
|
||||||
assertFalse(key1.isEncrypted());
|
assertFalse(key1.isEncrypted());
|
||||||
assertTrue(encKey1.isEncrypted());
|
assertTrue(encKey1.isEncrypted());
|
||||||
assertEquals(encKey1.getPubKeyPoint(), key1.getPubKeyPoint());
|
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);
|
encKey1.sign(Sha256Hash.ZERO_HASH, aesKey);
|
||||||
encKey2.sign(Sha256Hash.ZERO_HASH, aesKey);
|
encKey2.sign(Sha256Hash.ZERO_HASH, aesKey);
|
||||||
assertTrue(encChain.checkAESKey(aesKey));
|
assertTrue(encChain.checkAESKey(aesKey));
|
||||||
|
|
|
@ -43,9 +43,9 @@ import java.time.Instant;
|
||||||
import java.time.temporal.ChronoUnit;
|
import java.time.temporal.ChronoUnit;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
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.assertEquals;
|
||||||
import static org.junit.Assert.assertFalse;
|
import static org.junit.Assert.assertFalse;
|
||||||
import static org.junit.Assert.assertNotEquals;
|
import static org.junit.Assert.assertNotEquals;
|
||||||
|
@ -283,9 +283,9 @@ public class KeyChainGroupTest {
|
||||||
assertTrue(group.checkPassword("password"));
|
assertTrue(group.checkPassword("password"));
|
||||||
assertFalse(group.checkPassword("wrong password"));
|
assertFalse(group.checkPassword("wrong password"));
|
||||||
final ECKey ea = group.findKeyFromPubKey(a.getPubKey());
|
final ECKey ea = group.findKeyFromPubKey(a.getPubKey());
|
||||||
assertTrue(checkNotNull(ea).isEncrypted());
|
assertTrue(Objects.requireNonNull(ea).isEncrypted());
|
||||||
if (withImported) {
|
if (withImported) {
|
||||||
assertTrue(checkNotNull(group.findKeyFromPubKey(b.getPubKey())).isEncrypted());
|
assertTrue(Objects.requireNonNull(group.findKeyFromPubKey(b.getPubKey())).isEncrypted());
|
||||||
assertEquals(yesterday, group.getEarliestKeyCreationTimeInstant());
|
assertEquals(yesterday, group.getEarliestKeyCreationTimeInstant());
|
||||||
} else {
|
} else {
|
||||||
assertEquals(now, group.getEarliestKeyCreationTimeInstant());
|
assertEquals(now, group.getEarliestKeyCreationTimeInstant());
|
||||||
|
@ -320,9 +320,9 @@ public class KeyChainGroupTest {
|
||||||
|
|
||||||
group.decrypt(AES_KEY);
|
group.decrypt(AES_KEY);
|
||||||
assertFalse(group.isEncrypted());
|
assertFalse(group.isEncrypted());
|
||||||
assertFalse(checkNotNull(group.findKeyFromPubKey(a.getPubKey())).isEncrypted());
|
assertFalse(Objects.requireNonNull(group.findKeyFromPubKey(a.getPubKey())).isEncrypted());
|
||||||
if (withImported) {
|
if (withImported) {
|
||||||
assertFalse(checkNotNull(group.findKeyFromPubKey(b.getPubKey())).isEncrypted());
|
assertFalse(Objects.requireNonNull(group.findKeyFromPubKey(b.getPubKey())).isEncrypted());
|
||||||
assertEquals(yesterday, group.getEarliestKeyCreationTimeInstant());
|
assertEquals(yesterday, group.getEarliestKeyCreationTimeInstant());
|
||||||
} else {
|
} else {
|
||||||
assertEquals(now, group.getEarliestKeyCreationTimeInstant());
|
assertEquals(now, group.getEarliestKeyCreationTimeInstant());
|
||||||
|
@ -336,7 +336,7 @@ public class KeyChainGroupTest {
|
||||||
assertTrue(group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).isEncrypted());
|
assertTrue(group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).isEncrypted());
|
||||||
final ECKey key = group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
|
final ECKey key = group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
|
||||||
group.decrypt(AES_KEY);
|
group.decrypt(AES_KEY);
|
||||||
assertFalse(checkNotNull(group.findKeyFromPubKey(key.getPubKey())).isEncrypted());
|
assertFalse(Objects.requireNonNull(group.findKeyFromPubKey(key.getPubKey())).isEncrypted());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -514,7 +514,7 @@ public class KeyChainGroupTest {
|
||||||
@Test
|
@Test
|
||||||
public void constructFromSeed() {
|
public void constructFromSeed() {
|
||||||
ECKey key1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
|
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)
|
KeyChainGroup group2 = KeyChainGroup.builder(MAINNET).lookaheadSize(5)
|
||||||
.addChain(DeterministicKeyChain.builder().seed(seed).outputScriptType(ScriptType.P2PKH).build())
|
.addChain(DeterministicKeyChain.builder().seed(seed).outputScriptType(ScriptType.P2PKH).build())
|
||||||
.build();
|
.build();
|
||||||
|
@ -587,7 +587,7 @@ public class KeyChainGroupTest {
|
||||||
final DeterministicSeed deterministicSeed = group.getActiveKeyChain().getSeed();
|
final DeterministicSeed deterministicSeed = group.getActiveKeyChain().getSeed();
|
||||||
assertNotNull(deterministicSeed);
|
assertNotNull(deterministicSeed);
|
||||||
assertTrue(deterministicSeed.isEncrypted());
|
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
|
@Test
|
||||||
|
|
|
@ -90,6 +90,7 @@ import java.util.Collections;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Random;
|
import java.util.Random;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.concurrent.CompletableFuture;
|
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.AtomicBoolean;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
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.CENT;
|
||||||
import static org.bitcoinj.base.Coin.COIN;
|
import static org.bitcoinj.base.Coin.COIN;
|
||||||
import static org.bitcoinj.base.Coin.MILLICOIN;
|
import static org.bitcoinj.base.Coin.MILLICOIN;
|
||||||
|
@ -858,15 +858,15 @@ public class WalletTest extends TestWithWallet {
|
||||||
final Coin value2 = valueOf(2, 0);
|
final Coin value2 = valueOf(2, 0);
|
||||||
// Give us three coins and make sure we have some change.
|
// Give us three coins and make sure we have some change.
|
||||||
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, value.add(value2));
|
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, value.add(value2));
|
||||||
Transaction send1 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value2));
|
Transaction send1 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, value2));
|
||||||
Transaction send2 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value2));
|
Transaction send2 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, value2));
|
||||||
byte[] buf = send1.bitcoinSerialize();
|
byte[] buf = send1.bitcoinSerialize();
|
||||||
buf[43] = 0; // Break the signature: bitcoinj won't check in SPV mode and this is easier than other mutations.
|
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);
|
send1 = TESTNET.getDefaultSerializer().makeTransaction(buf);
|
||||||
wallet.commitTx(send2);
|
wallet.commitTx(send2);
|
||||||
assertEquals(value, wallet.getBalance(BalanceType.ESTIMATED));
|
assertEquals(value, wallet.getBalance(BalanceType.ESTIMATED));
|
||||||
// Now spend the change. This transaction should die permanently when the mutant appears in the chain.
|
// 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);
|
wallet.commitTx(send3);
|
||||||
assertEquals(ZERO, wallet.getBalance(BalanceType.AVAILABLE));
|
assertEquals(ZERO, wallet.getBalance(BalanceType.AVAILABLE));
|
||||||
final LinkedList<TransactionConfidence> dead = new LinkedList<>();
|
final LinkedList<TransactionConfidence> dead = new LinkedList<>();
|
||||||
|
@ -1169,8 +1169,8 @@ public class WalletTest extends TestWithWallet {
|
||||||
@Test
|
@Test
|
||||||
public void doubleSpendForBuildingTx() throws Exception {
|
public void doubleSpendForBuildingTx() throws Exception {
|
||||||
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
|
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
|
||||||
Transaction send1 = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
|
Transaction send1 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
|
||||||
Transaction send2 = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 20), true));
|
Transaction send2 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 20), true));
|
||||||
|
|
||||||
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send1);
|
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send1);
|
||||||
assertUnspent(send1);
|
assertUnspent(send1);
|
||||||
|
@ -1183,11 +1183,11 @@ public class WalletTest extends TestWithWallet {
|
||||||
@Test
|
@Test
|
||||||
public void txSpendingDeadTx() throws Exception {
|
public void txSpendingDeadTx() throws Exception {
|
||||||
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
|
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
|
||||||
Transaction send1 = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
|
Transaction send1 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
|
||||||
Transaction send2 = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 20), true));
|
Transaction send2 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 20), true));
|
||||||
wallet.commitTx(send1);
|
wallet.commitTx(send1);
|
||||||
assertPending(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);
|
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send2);
|
||||||
assertDead(send1);
|
assertDead(send1);
|
||||||
|
@ -1227,12 +1227,12 @@ public class WalletTest extends TestWithWallet {
|
||||||
@Test
|
@Test
|
||||||
public void testAddTransactionsDependingOn() throws Exception {
|
public void testAddTransactionsDependingOn() throws Exception {
|
||||||
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
|
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
|
||||||
Transaction send1 = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
|
Transaction send1 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
|
||||||
Transaction send2 = checkNotNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 20), true));
|
Transaction send2 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 20), true));
|
||||||
wallet.commitTx(send1);
|
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);
|
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(send1c);
|
||||||
wallet.commitTx(send2);
|
wallet.commitTx(send2);
|
||||||
Set<Transaction> txns = new HashSet<>();
|
Set<Transaction> txns = new HashSet<>();
|
||||||
|
@ -1247,15 +1247,15 @@ public class WalletTest extends TestWithWallet {
|
||||||
@Test
|
@Test
|
||||||
public void sortTxnsByDependency() throws Exception {
|
public void sortTxnsByDependency() throws Exception {
|
||||||
Transaction send1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
|
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);
|
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);
|
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(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);
|
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);
|
wallet.commitTx(send1e);
|
||||||
|
|
||||||
Transaction send2 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(200, 0));
|
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));
|
sendMoneyToWallet(encryptedWallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN, key.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
|
||||||
assertEquals(Coin.COIN, encryptedWallet.getBalance());
|
assertEquals(Coin.COIN, encryptedWallet.getBalance());
|
||||||
SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
|
SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
|
||||||
req.aesKey = checkNotNull(encryptedWallet.getKeyCrypter()).deriveKey(PASSWORD1);
|
req.aesKey = Objects.requireNonNull(encryptedWallet.getKeyCrypter()).deriveKey(PASSWORD1);
|
||||||
encryptedWallet.sendCoinsOffline(req);
|
encryptedWallet.sendCoinsOffline(req);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2963,7 +2963,7 @@ public class WalletTest extends TestWithWallet {
|
||||||
wallet = roundTrip(wallet);
|
wallet = roundTrip(wallet);
|
||||||
|
|
||||||
tx = wallet.getTransaction(tx.getTxId());
|
tx = wallet.getTransaction(tx.getTxId());
|
||||||
checkNotNull(tx);
|
Objects.requireNonNull(tx);
|
||||||
assertEquals(Transaction.Purpose.KEY_ROTATION, tx.getPurpose());
|
assertEquals(Transaction.Purpose.KEY_ROTATION, tx.getPurpose());
|
||||||
// Have to divide here to avoid mismatch due to second-level precision in serialisation.
|
// Have to divide here to avoid mismatch due to second-level precision in serialisation.
|
||||||
assertEquals(compromiseTime, wallet.getKeyRotationTimeInstant().get());
|
assertEquals(compromiseTime, wallet.getKeyRotationTimeInstant().get());
|
||||||
|
|
|
@ -22,8 +22,7 @@ import java.math.BigInteger;
|
||||||
import java.security.NoSuchAlgorithmException;
|
import java.security.NoSuchAlgorithmException;
|
||||||
import java.security.SecureRandom;
|
import java.security.SecureRandom;
|
||||||
import java.util.EnumSet;
|
import java.util.EnumSet;
|
||||||
|
import java.util.Objects;
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
|
|
||||||
import org.bitcoinj.base.BitcoinNetwork;
|
import org.bitcoinj.base.BitcoinNetwork;
|
||||||
import org.bitcoinj.base.Network;
|
import org.bitcoinj.base.Network;
|
||||||
|
@ -148,7 +147,8 @@ public class GenerateLowSTests {
|
||||||
TransactionInput txIn = outputTransaction.getInput(i);
|
TransactionInput txIn = outputTransaction.getInput(i);
|
||||||
Script scriptPubKey = txIn.getConnectedOutput().getScriptPubKey();
|
Script scriptPubKey = txIn.getConnectedOutput().getScriptPubKey();
|
||||||
RedeemData redeemData = txIn.getConnectedRedeemData(bag);
|
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));
|
txIn.setScriptSig(scriptPubKey.createEmptyInputScript(redeemData.keys.get(0), redeemData.redeemScript));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -37,11 +37,11 @@ import org.junit.runners.Parameterized;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Random;
|
import java.util.Random;
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
import java.util.concurrent.ExecutionException;
|
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.CENT;
|
||||||
import static org.bitcoinj.base.Coin.COIN;
|
import static org.bitcoinj.base.Coin.COIN;
|
||||||
import static org.bitcoinj.base.Coin.FIFTY_COINS;
|
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.
|
// Do the same thing with an offline transaction.
|
||||||
peerGroup.removeWallet(wallet);
|
peerGroup.removeWallet(wallet);
|
||||||
SendRequest req = SendRequest.to(dest, valueOf(2, 0));
|
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.
|
assertNull(outbound(p1)); // Nothing sent.
|
||||||
// Add the wallet to the peer group (simulate initialization). Transactions should be announced.
|
// Add the wallet to the peer group (simulate initialization). Transactions should be announced.
|
||||||
peerGroup.addWallet(wallet);
|
peerGroup.addWallet(wallet);
|
||||||
|
|
|
@ -39,8 +39,8 @@ import org.slf4j.LoggerFactory;
|
||||||
import org.bitcoinj.walletfx.utils.KeyDerivationTasks;
|
import org.bitcoinj.walletfx.utils.KeyDerivationTasks;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
import static org.bitcoinj.walletfx.utils.GuiUtils.*;
|
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();
|
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()) {
|
KeyDerivationTasks tasks = new KeyDerivationTasks(keyCrypter, password, getTargetTime()) {
|
||||||
@Override
|
@Override
|
||||||
protected final void onFinish(AesKey aesKey, int timeTakenMsec) {
|
protected final void onFinish(AesKey aesKey, int timeTakenMsec) {
|
||||||
|
|
|
@ -41,8 +41,8 @@ import java.time.LocalDate;
|
||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.time.ZoneOffset;
|
import java.time.ZoneOffset;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
|
||||||
import static javafx.beans.binding.Bindings.*;
|
import static javafx.beans.binding.Bindings.*;
|
||||||
import static org.bitcoinj.walletfx.utils.GuiUtils.checkGuiThread;
|
import static org.bitcoinj.walletfx.utils.GuiUtils.checkGuiThread;
|
||||||
import static org.bitcoinj.walletfx.utils.GuiUtils.informationalAlert;
|
import static org.bitcoinj.walletfx.utils.GuiUtils.informationalAlert;
|
||||||
|
@ -82,7 +82,7 @@ public class WalletSettingsController implements OverlayController<WalletSetting
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
this.aesKey = aesKey;
|
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.
|
// Now we can display the wallet seed as appropriate.
|
||||||
passwordButton.setText("Remove password");
|
passwordButton.setText("Remove password");
|
||||||
}
|
}
|
||||||
|
@ -94,7 +94,7 @@ public class WalletSettingsController implements OverlayController<WalletSetting
|
||||||
|
|
||||||
// Set the mnemonic seed words.
|
// Set the mnemonic seed words.
|
||||||
final List<String> mnemonicCode = seed.getMnemonicCode();
|
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);
|
String origWords = InternalUtils.SPACE_JOINER.join(mnemonicCode);
|
||||||
wordsArea.setText(origWords);
|
wordsArea.setText(origWords);
|
||||||
|
|
||||||
|
|
|
@ -95,6 +95,7 @@ import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.concurrent.Callable;
|
import java.util.concurrent.Callable;
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
@ -107,7 +108,6 @@ import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static org.bitcoinj.base.Coin.parseCoin;
|
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.
|
* 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);
|
AesKey aesKey = passwordToKey(true);
|
||||||
if (aesKey == null)
|
if (aesKey == null)
|
||||||
return; // Error message already printed.
|
return; // Error message already printed.
|
||||||
key = key.encrypt(checkNotNull(wallet.getKeyCrypter()), aesKey);
|
key = key.encrypt(Objects.requireNonNull(wallet.getKeyCrypter()), aesKey);
|
||||||
}
|
}
|
||||||
} catch (KeyCrypterException kce) {
|
} catch (KeyCrypterException kce) {
|
||||||
System.err.println("There was an encryption related error when adding the key. The error was '"
|
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.");
|
System.err.println("The password is incorrect.");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return checkNotNull(wallet.getKeyCrypter()).deriveKey(password);
|
return Objects.requireNonNull(wallet.getKeyCrypter()).deriveKey(password);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
Loading…
Add table
Reference in a new issue